diff --git a/editor.py b/editor.py index 410c148..e6eebec 100755 --- a/editor.py +++ b/editor.py @@ -3,7 +3,7 @@ import sys if not '-p' in sys.argv: - sys.path.insert(0, 'build/lib.linux-x86_64-2.7/') + sys.path.insert(0, 'build/lib.linux-x86_64-2.6/') import sip sip.setapi('QString', 2) @@ -11,8 +11,8 @@ from PyQt4.QtGui import QApplication, QFont, QPlainTextEdit, QSyntaxHighlighter, \ QTextCharFormat, QTextBlockUserData -from qutepart.syntaxhighlighter import SyntaxHighlighter -from qutepart.syntax import SyntaxManager +from qutepart.syntax.highlighter import SyntaxHighlighter +from qutepart.syntax.syntax import SyntaxManager def main(): diff --git a/makeres.sh b/makeres.sh deleted file mode 100755 index 1140e48..0000000 --- a/makeres.sh +++ /dev/null @@ -1,5 +0,0 @@ -#/bin/sh - -#env LD_PRELOAD="/usr/local/lib/libprofiler.so" python -m yep ./editor.py verybigfile.cpp -ulimit -c unlimited -python ./editor.py verybigfile.cpp \ No newline at end of file diff --git a/notes b/notes deleted file mode 100644 index 871ac18..0000000 --- a/notes +++ /dev/null @@ -1 +0,0 @@ -KateHlManager::getDefaults - default syntax highlighting styles diff --git a/part/.gitignore b/part/.gitignore deleted file mode 100644 index 84d1487..0000000 --- a/part/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*~ -.kdev4 -*.kdev4 diff --git a/part/AUTHORS b/part/AUTHORS deleted file mode 100644 index 4969e35..0000000 --- a/part/AUTHORS +++ /dev/null @@ -1,55 +0,0 @@ - *** Kate Team *** -- Christoph Cullmann - (Maintainer) - -- Joseph Wenninger - (highlight guy + big bug hunter) - -- Anders Lund - (bookmarks, iconborder, ...) - -- Hamish Rodda - (dynamic wrap, view, optimise, etc) - -- Waldo Bastian - (buffer handling) - -- Charles Samuels - (regular expressions) - -- Michael Bartl - (first one who really helped out :) - -- Matt Newell - -- Michael McCallum - -- John Firebaugh - -- Nadeem Hasan - -- Erlend Hamberg - (vi input mode) - - *** KWrite Team *** -- Jochen Wilhelmy - (original author of kwrite in kde 1.x until kde 2.1) - -- Glen Parker - (undo history, kspell-integration) - -- Michael Koch - (port to KParts) - -- Dominik Haumann - (developer, highlight wizard) - -- Mirko Stocker - (various bugfixes) - -- Matthew Woehlke - (selection, KColorScheme integration) - -- Sebastian Pipping - (search bar back- and front-end) - diff --git a/part/CMakeLists.txt b/part/CMakeLists.txt deleted file mode 100644 index b951f78..0000000 --- a/part/CMakeLists.txt +++ /dev/null @@ -1,231 +0,0 @@ -# define project -project(katepart) - -# these subdirs have their own CMakeLists -add_subdirectory( data ) - -# syntax highlighting data files -add_subdirectory( syntax/data ) - -# jscripts for the part -add_subdirectory( script/data ) - -add_subdirectory( plugins ) - -# tests -add_subdirectory( tests ) - -# includes -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/buffer - ${CMAKE_CURRENT_SOURCE_DIR}/completion - ${CMAKE_CURRENT_SOURCE_DIR}/dialogs - ${CMAKE_CURRENT_SOURCE_DIR}/document - ${CMAKE_CURRENT_SOURCE_DIR}/script - ${CMAKE_CURRENT_SOURCE_DIR}/mode - ${CMAKE_CURRENT_SOURCE_DIR}/render - ${CMAKE_CURRENT_SOURCE_DIR}/search - ${CMAKE_CURRENT_SOURCE_DIR}/syntax - ${CMAKE_CURRENT_SOURCE_DIR}/undo - ${CMAKE_CURRENT_SOURCE_DIR}/utils - ${CMAKE_CURRENT_SOURCE_DIR}/vimode - ${CMAKE_CURRENT_SOURCE_DIR}/view - ${CMAKE_CURRENT_SOURCE_DIR}/swapfile - ${CMAKE_SOURCE_DIR}/kutils - ${KDE4_KIO_INCLUDES} -) - -# our sources -set(katepart_PART_SRCS - -# text buffer -buffer/katetextbuffer.cpp -buffer/katetextblock.cpp -buffer/katetextline.cpp -buffer/katetextcursor.cpp -buffer/katetextrange.cpp -buffer/katetexthistory.cpp - -# completion (widget, model, delegate, ...) -completion/katecompletionwidget.cpp -completion/katecompletionmodel.cpp -completion/katecompletiontree.cpp -completion/katecompletionconfig.cpp -completion/kateargumenthinttree.cpp -completion/kateargumenthintmodel.cpp -completion/katecompletiondelegate.cpp -completion/expandingtree/expandingwidgetmodel.cpp -completion/expandingtree/expandingdelegate.cpp -completion/expandingtree/expandingtree.cpp - -# simple internal word completion -completion/katewordcompletion.cpp - -# dialogs -dialogs/katedialogs.cpp - -# document (THE document, buffer, lines/cursors/..., CORE STUFF) -document/katedocument.cpp -document/katedocumenthelpers.cpp -document/katebuffer.cpp - -# undo -undo/kateundo.cpp -undo/kateundomanager.cpp - -# scripting -script/katescript.cpp -script/kateindentscript.cpp -script/katecommandlinescript.cpp -script/katetemplatescript.cpp -script/katescriptmanager.cpp -script/katescriptaction.cpp -script/katescriptconsole.cpp - -# scripting wrappers -script/katescriptdocument.cpp -script/katescriptview.cpp -script/katescripthelpers.cpp - -# mode (modemanager and co) -mode/katemodemanager.cpp -mode/katemodeconfigpage.cpp -mode/katemodemenu.cpp -mode/katewildcardmatcher.cpp - -# rendering stuff (katerenderer and helpers) -render/katerenderer.cpp -render/katerenderrange.cpp -render/katelayoutcache.cpp -render/katetextlayout.cpp -render/katelinelayout.cpp - -# search stuff -search/kateregexp.cpp -search/kateplaintextsearch.cpp -search/kateregexpsearch.cpp -search/katematch.cpp -search/katesearchbar.cpp - -# syntax related stuff (highlighting, xml file parsing, folding, ...) -syntax/katesyntaxmanager.cpp -syntax/katehighlight.cpp -syntax/katehighlighthelpers.cpp -syntax/katehighlightmenu.cpp -syntax/katesyntaxdocument.cpp -syntax/katecodefolding.cpp -syntax/kateextendedattribute.cpp - -# view stuff (THE view and its helpers) -view/kateview.cpp -view/kateviewinternal.cpp -view/kateviewhelpers.cpp - -# vi input mode -vimode/kateviinputmodemanager.cpp -vimode/katevimodebase.cpp -vimode/katevinormalmode.cpp -vimode/kateviinsertmode.cpp -vimode/katevicommand.cpp -vimode/katevimotion.cpp -vimode/katevirange.cpp -vimode/katevikeyparser.cpp -vimode/kateviglobal.cpp -vimode/katevivisualmode.cpp -vimode/katevireplacemode.cpp -vimode/katevimodebar.cpp - -# spell checking -spellcheck/prefixstore.h -spellcheck/prefixstore.cpp -spellcheck/ontheflycheck.h -spellcheck/ontheflycheck.cpp -spellcheck/spellcheck.h -spellcheck/spellcheck.cpp -spellcheck/spellcheckdialog.h -spellcheck/spellcheckdialog.cpp -spellcheck/spellingmenu.h -spellcheck/spellingmenu.cpp - -# generic stuff, unsorted... -utils/katecmds.cpp -utils/kateconfig.cpp -utils/katebookmarks.cpp -utils/kateautoindent.cpp -utils/kateschema.cpp -utils/katetemplatehandler.cpp -utils/kateprinter.cpp -utils/kateglobal.cpp -utils/katecmd.cpp -utils/katestyletreewidget.cpp -utils/katepartpluginmanager.cpp - -# swapfile -swapfile/katerecoverbar.cpp -swapfile/kateswapfile.cpp -swapfile/katebrokenswapfilebar.cpp - -) - -set( katepart_PART_UI -dialogs/textareaappearanceconfigwidget.ui -dialogs/bordersappearanceconfigwidget.ui -dialogs/commandmenuconfigwidget.ui -dialogs/commandmenueditwidget.ui -dialogs/completionconfigtab.ui -dialogs/cursorconfigwidget.ui -dialogs/editconfigwidget.ui -dialogs/filetypeconfigwidget.ui -dialogs/indentationconfigwidget.ui -dialogs/opensaveconfigwidget.ui -dialogs/opensaveconfigadvwidget.ui -dialogs/modonhdwidget.ui -dialogs/schemaconfigcolortab.ui -dialogs/completionconfigwidget.ui -search/searchbarincremental.ui -search/searchbarpower.ui -dialogs/viinputmodeconfigwidget.ui -dialogs/spellcheckconfigwidget.ui -swapfile/recoverwidget.ui -swapfile/brokenswapfilewidget.ui -) - -add_definitions ( -DKDE_DEFAULT_DEBUG_AREA=13000 ) - -kde4_add_ui_files(katepart_PART_SRCS ${katepart_PART_UI} ) - -kde4_add_library (katepartinterfaces ${LIBRARY_TYPE} ${katepart_PART_SRCS} ) - -target_link_libraries ( - katepartinterfaces ${KDE4_KDECORE_LIBS} ${KDE4_KPARTS_LIBS} - ${KDE4_KCMUTILS_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${QT_QTSCRIPT_LIBRARY} ${KDE_4_4_LIBS_NEEDED} -) -target_link_libraries(katepartinterfaces LINK_INTERFACE_LIBRARIES "${KDE4_KPARTS_LIBS}" ) - -set_target_properties( - katepartinterfaces PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -# kde 4 final support -if(KDE4_ENABLE_FINAL) - macro_add_file_dependencies(${CMAKE_CURRENT_BINARY_DIR}/katepartinterfaces_final_cpp.cpp ) -else(KDE4_ENABLE_FINAL) - macro_add_file_dependencies(${CMAKE_CURRENT_SOURCE_DIR}/script/katescript.cpp ) -endif(KDE4_ENABLE_FINAL) - -# install kate part interfaces -install (TARGETS katepartinterfaces EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) - -# kate part itself just is interfaces + the factory -kde4_add_plugin (katepart utils/katefactory.cpp) - -# link the part, use kate part interfaces + kde stuff -target_link_libraries (katepart - ${KDE4_KDECORE_LIBS} ${KDE4_KPARTS_LIBS} - ${KDE4_KCMUTILS_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${QT_QTSCRIPT_LIBRARY} katepartinterfaces) - -# install the part -install (TARGETS katepart DESTINATION ${PLUGIN_INSTALL_DIR}) diff --git a/part/COPYING.LIB b/part/COPYING.LIB deleted file mode 100644 index a96b573..0000000 --- a/part/COPYING.LIB +++ /dev/null @@ -1,482 +0,0 @@ - GNU LIBRARY GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor - Boston, MA 02110-1301, USA. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the library GPL. It is - numbered 2 because it goes with version 2 of the ordinary GPL.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Library General Public License, applies to some -specially designated Free Software Foundation software, and to any -other libraries whose authors decide to use it. You can use it for -your libraries, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if -you distribute copies of the library, or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link a program with the library, you must provide -complete object files to the recipients so that they can relink them -with the library, after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - Our method of protecting your rights has two steps: (1) copyright -the library, and (2) offer you this license which gives you legal -permission to copy, distribute and/or modify the library. - - Also, for each distributor's protection, we want to make certain -that everyone understands that there is no warranty for this free -library. If the library is modified by someone else and passed on, we -want its recipients to know that what they have is not the original -version, so that any problems introduced by others will not reflect on -the original authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that companies distributing free -software will individually obtain patent licenses, thus in effect -transforming the program into proprietary software. To prevent this, -we have made it clear that any patent must be licensed for everyone's -free use or not licensed at all. - - Most GNU software, including some libraries, is covered by the ordinary -GNU General Public License, which was designed for utility programs. This -license, the GNU Library General Public License, applies to certain -designated libraries. This license is quite different from the ordinary -one; be sure to read it in full, and don't assume that anything in it is -the same as in the ordinary license. - - The reason we have a separate public license for some libraries is that -they blur the distinction we usually make between modifying or adding to a -program and simply using it. Linking a program with a library, without -changing the library, is in some sense simply using the library, and is -analogous to running a utility program or application program. However, in -a textual and legal sense, the linked executable is a combined work, a -derivative of the original library, and the ordinary General Public License -treats it as such. - - Because of this blurred distinction, using the ordinary General -Public License for libraries did not effectively promote software -sharing, because most developers did not use the libraries. We -concluded that weaker conditions might promote sharing better. - - However, unrestricted linking of non-free programs would deprive the -users of those programs of all benefit from the free status of the -libraries themselves. This Library General Public License is intended to -permit developers of non-free programs to use free libraries, while -preserving your freedom as a user of such programs to change the free -libraries that are incorporated in them. (We have not seen how to achieve -this as regards changes in header files, but we have achieved it as regards -changes in the actual functions of the Library.) The hope is that this -will lead to faster development of free libraries. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, while the latter only -works together with the library. - - Note that it is possible for a library to be covered by the ordinary -General Public License rather than by this special one. - - GNU LIBRARY GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library which -contains a notice placed by the copyright holder or other authorized -party saying it may be distributed under the terms of this Library -General Public License (also called "this License"). Each licensee is -addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also compile or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - c) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - d) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the source code distributed need not include anything that is normally -distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Library General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/part/ChangeLog b/part/ChangeLog deleted file mode 100644 index 07aeaa2..0000000 --- a/part/ChangeLog +++ /dev/null @@ -1,347 +0,0 @@ -2007-05-28 Christoph Cullmann - * Modes introduced - * Big resorting of our sources... - -2003-12-24 Christoph Cullmann - * Overview about some fixes done in the last months: - - Hamish Rodda: - - lots of fixes in the area of the - rendering/selection/view department and massive - bughunting - - - Anders Lund: - - bookmarks/printing enhancements - - - Christoph Cullmann: - - bughunting, config classes/dialogs, consolidation of - part -><- app interaction - -2003-08-28 Christoph Cullmann - * color schemes support - * filetype support - * indenters for different languages by jesse - * folding by indentation kind of working, not perfect :/ - -2002-11-05 Christoph Cullmann - * fix the printing crash + loop together with Anders ;) - -2002-09-06 Christoph Cullmann - * commiting a fix from Nicolai Haehnle for the - cursorDown()/cursorUp() behavior - -2002-09-03 Christoph Cullmann - * some minor fixes in the last days (redraw stuff, memset, ...) - -2002-08-27 Christoph Cullmann - * extended the context signed char to a uint ;) - * some folding fixes (hopefully) - * memleak fix - * undo stuff changed a bit, 0 means unlimited like before, show - that now in the dialog and add a comment to ktexteditor - -2002-08-26 Christoph Cullmann - * Fixes for folding, cleanup, move folding tree into the buffer, - add some inliner's - * Fixes for the big memory usage for the attributes in the buffer - by using run length encoding for the attributes if they are - dumped into the bytearray - -2002-06-01 Christian Couder - * Move view stuff from katedocument to kateviewinternal. - -2002-05-20 Christoph Cullmann - * some more references in use ;) - * fixed some undo probs - (mem leak, KateUndo is now only for internal use in KateUndoGroup) - * start of convertion my*** to m_*** and add m_ to any other private stuff - -2002-05-17 Christian Couder - * Move font stuff from katedocument into new katefont.h and - katefont.cpp files, and clean up katedocument font stuff. - -2002-05-14 Christian Couder - * Big clean up in katedocument using new katecursor stuff. - -2002-05-12 Bernd Gehrmann - * Moved browser extension from view to doc, where it belongs - * If servicetype in the browser extension specifies an encoding, - use that instead of user's local encoding - -2002-05-11 Christian Couder - * implement the KTextEditor::Cursor in the KateCursor class - -2002-05-04 Christoph Cullmann - * first KTextEditor::ViewPlugin which works - drop the helloworld plugin, as it is really no good example (bad code, ..) - -2002-05-04 Christian Couder - * fix undo for comment and uncomment - -2002-05-01 Christian Couder - * cleanups related to the uncomment feature in katetextline and katedocument - -2002-01-04 Christoph Cullmann - * the search stuff in the katedocument is rewritten now, should work mostly, - only search for whole words is just a mess :( - -2002-01-03 Christoph Cullmann - * kate app and kwrite app now use the katepart via libloader and link only - to the kateinterfaces (which will soon be splitted into katepartinterfaces - and kateinterfaces - * new framework for the configpages of the katepart accessible through the - interfaces - * KSpell works again ;) my god, what a buggy thingy - -2001-12-01 Christoph Cullmann - * speedup for insert/removeText/Line - * new editStart/editEnd/editAddUndo functions to make the undo/redo + update - after edit function calls easier to understand an use in katedocument.* - -2001-11-30 Joseph Wenninger - * I hopefully fixed the CSS highlighting finally. It used - deprecated syntax and there was a bug in the highlighting code, - for handling weakDeliminiators. Who renamed them, once they where - called weakDelimiters, which I think is the correct pronounciation. - -2001-11-29 Joseph Wenninger - * KWrite/Kate use different font settings for printing and viewing now - * Fixed a small crash in my kdevelop->kate port of the codecompletion interface - -2001-11-26 Christoph Cullmann - * backspace bug fixed - * more cleanups in doc/view - -2001-11-24 Christoph Cullmann - * the docID is now called documentNumber and is in the KTextEditor lib ;) - * new print and mark interfaces ;) - * bugfixes for some stuff in kateview/document.* - * move more of the document stuff from the view to the document - (old kwritedoc/view was very mixed, no real separation, but that should be nearly done) - -2001-11-17 Christoph Cullmann - * new selection code (bit buggy at the moment, but better than the old way - of storing the selection in the attributes - -2001-10-29 Joseph Wenninger - * Highlighting definitions support now #stay and #pop as context values - * Some highlighting definitions ported - -2001-10-27 Christoph Cullmann - * undo/redo works now without errors - * fix many memleaks + some crashs in buffer + hl - * fix ctx management (almost) - -2001-10-27 Joseph Wenninger - * The stacked highlighting shoul almost work now. - Using old description files it will use quite a lot memory, but - they should work. - Problems: - * It's leaking like a sieve on destruction, because the - memarrays aren't deleted correctly yet (They need to be pointers and not - references, otherwise there are out of memory errors in qgarray) - * Highlighting isn't updated completely yet - * I have to do some nasty workaround because the overloaded == - operator in QMemArray crashes, if one or both of the arrays has - a size of 0 (I think this is a bug in QT, but it could be that - this is intended behavior. Who knows ?) - -2001-10-20 Christoph Cullmann - * new undo/redo stuff, should work now already fine (mostly ;) - -2001-10-14 Christoph Cullmann - * new interfaces - * fixed some bugs (or better mistakes) in EditInterface - * fix bugs and even more bugs - -2001-10-14 Christoph Cullmann - * implementing and enhancing the new KTextEditor interfaces - * rewrite the whole internal document/view stuff ;) (hope will be finished - soon with that old crap ! - * reconstruction of whole katelibs + dirs - -2001-10-06 Christoph Cullmann - * myself back again ;) - * now kate is clean (only qt3), no backports ;) - -2001-08-24 christian@kdevelop.org - * reimplement the commenting of selections on some languages - -2001-08-19 christian@kdevelop.org - * added back Sather highlighting support - * improved Eiffel language syntax highlighting support - * added Eiffel language comment directive in eiffel.xml - * added Ada language comment directive in ada.xml - -2001-08-15 christian@kdevelop.org - * committed Eiffel language syntax highlighting support - -2001-08-08 rokrau@yahoo.com - * committed changes to Kate's API necessary for integration of kate as - a kpart into kdevelop - -2001-05-13 Christoph Cullmann - * after some time of learning for my "Abitur" now again some fixes ;): - textlines stuff rewritten, selection fixed + +/- font zoom buttons in the part - -2001-04-27 Christoph Cullmann - * now the pluginconfig pages work ;) - -2001-04-24 Joseph Wenninger - * now and is replaced by - -2001-04-20 Christoph Cullmann - * new configdialog - * enhanced pluginIface to supports configdialogpages - -2001-04-14 Christoph Cullmann - * now kateview has in iconborder too (without real function at the moment) - -2001-04-10 Christoph Cullmann - * bugfixes for drawBuffer stuff, next/prev viewspace, restoreView - -2001-04-08 Christoph Cullmann - * now encoding for files can be selected at settings dialog (not only UTF8, all possible encodings) - * dropped old code -> use Waldo's code ;) - -2001-04-07 Joseph Wenninger - * Activated Waldo Bastian's NEW_CODE - * Ported Highlighting to it - -2001-04-05 Joseph Wenninger - * Highlighting Configuration is now in kate/kwrite settings too - * Made a cleanup of no longer used classes - -2001-04-04 Christoph Cullmann - * sidebar now again restores config - -2001-04-03 Joseph Wenninger - * Cristi Dumitrescu's PHP keyword / type list added - -2001-04-01 Joseph Wenninger - * Added a new widget KateStackTabWidget - Now you can chose between tabbed or an - KOffice Workspace like view for the file sidebar - --> You can change this behavior in the config dialog - * Not implemented: - restore sidebar page on startup - remove page not implemented yet - (will be fixed soon) - * Added a backport of QT3's QRegExp I got from Scott Manson - wit one addtion (see qt3back/README) - hopefully this will give us more flexibility for syntax - highlighting - -2001-03-27 Christoph Cullmann - * console disabled per default - * console only loaded if enabled - -2001-03-28 Joseph Wenninger - * -n in kate.desktop removed, now config settings are used - -2001-03-27 Christoph Cullmann - * interfaces extended (mainly for projectmanager) - * piper moved to plugins/projectmanager/piper - * a piper Makefile.am created - -2001-03-26 Joseph Wenninger - * 2 reimplemented highlighing configs - * 1 experimental highlighting config - * preparations for an highlighting editing dialog - -2001-03-25 Christoph Cullmann - * rewrite of plugin API and manager, now loading/unloading nice - -2001-03-22 Joseph Wenninger - * single / multi instance mode configurable - Cullmann's -n option forces a new instance - Otherwise it uses the configuration from - the settings dialog. At the moment -n is - default start option - -2001-03-21 Christoph Cullmann - * QPopupMenu for filelist - -2001-03-20 Christoph Cullmann - * kate is now a normal KApplication - -2001-03-18 Christoph Cullmann - * big location changes of source files - * KateFactory now in use by hole Kate app - * KatePartView/Doc merged with KateView/Doc (make life more easy) - -2001-03-18 Joseph Wenninger - * openheader plugin opens the corresponding - .h file for .cpp or .c, and vice versa - * Hopefully fixed highlighting dialog for now. - -2001-03-17 Joseph Wenninger - * Syntaxhighlighting is now defined in cpp.xml, c.xml html.xml ... - instead of a global syntax.xml. - (Not ported completely yet) - * Some simple reg expression work (see html.xml) - -2001-03-17 Christoph Cullmann - * moved textfilter stuff to a own plugin "textfilter" - * cleaned up katemainwindow.* - -2001-03-16 Christoph Cullmann - * search dialog comes up with selected text - * backport of some KDevelop KWrite patches ;) - -2001-03-15 Christoph Cullmann - * katepart finished - * new kwrite using katepart - * removed old kwrite and kwritepart ! - * fixed menu and toolbar problems of the new KWrite app - -2001-03-11 Christoph Cullmann - * kwrite stuff merged into kate !!!!! - -2001-03-04 Christoph Cullmann - * mutiple mainwindows - * fileist, sync for all mainwindows, all open docs listed - -2001-03-03 Christoph Cullmann - * session management (Anders Lund) - * removed some debug stuff - -2001-02-26 Joseph Wenninger - * First step for a plugin management dialog page - Soon to come - -2001-02-26 Christoph Cullmann - * Kate is a part of kdebase :) - sourceforge.net CVS won't be used in the future - -2001-02-24 Phlip - * HTML button - select text, hit , and enter the fields - for an SGML tag. Don't enter the < > or closing tag. We put these - around the selected text, and [try to] re-select that text so you can add - another nested tag right away. We are now the first HTML editor - that's actually better than Notepad! Hours of fun. - - * Filter - select text, hit , and enter an OS command. - we pipe the selected text thru that command, such as "sort", and then - replace the selection with the result. Impress your friends. - -2001-02-21 Joseph Wenninger - * Makefile.am's : correction for linking - * katemenuitem.h : Improved menu items added doc-list - * katelistboxitem.h : Improved listboxitem files-list - -2001-02-19 Christoph Cullmann - * kateconsole.* konsole/* : add kateconsole widget - -2001-02-16 Anders Lund - * katemainwindow.cpp :fixing read/write options to use maindockwindow functions. - -2001-02-15 Joseph Wenninger - * kateview.cpp : Tab doesn't jump to next widget anymore, but inserts a tab into the text - * katemainwindow.* : F8 / SHIFT-F8 jumps to next / previous widget diff --git a/part/INDENTATION b/part/INDENTATION deleted file mode 100644 index f2aa3ac..0000000 --- a/part/INDENTATION +++ /dev/null @@ -1,105 +0,0 @@ -# -# Indentation for Dummies -# - -This file should is aimed to describe how the KatePart in KDE 4 is designed to allow -flexible indentation based on JavaScripts. - -As references, a good read is the way VIM handles this all, Emacs is out of scope I think, -as it's just to mangled together there with the mighty lisp engine. - -VIM seems to have a fairly simple way to integrate indentation scripts, I guess a similar -approach is no bad idea... - -What tell the VIM docs about indentation? -http://www.vim.org/htmldoc/indent.html - -Some little HOWTO showing a simple Pascal indenter: -http://psy.swan.ac.uk/staff/carter/unix/vim_indent.htm - -In short, how does scripted indentation work in VIM? - - - you must write a functions which returns for a given line the wanted indentation level. - - you specify some keywords/char which trigger indentation, inserting a linebreak always triggers it - - if indentation is triggered, VIM evaluates the function for the line and reindents the line to the - returned level or keeps the current indentation level if -1 is returned - -This sounds fairly simple, but seems to be enough for normal world usage, given that VIM is -very popular.... - -KatePart's current indentation scripts work similar, but are triggered on each keystroke. -I guess only calling them for linebreaks + special chars would increase performance already -a lot. Next part is that the scripts atm indent theirself, I guess letting them just return the -needed level and let the C++ code really indent the line would be faster and easier for the script -writers, too. - -One bad thing with the VIM way is that mixed indentation won't work correct, you can't return in one -int that the first 4 chars can be replaced with tabs, if tab indentation is enabled but the remaining 4 -chars should stay single spaces, as it is useful in this example (given tabwidth is 4): - -int test () -{ - if (hello || - muhh) // this line should be indented with tab + 4 spaces - return 1; // this line should be indented with 2 tabs - - return 0; -} - -I think we should have a interface in which the script indicates which normal indentation is wanted -and which further amount of spaces should be inserted to align with other words/keywords whatever... - -As it shows up, if we want to support both mixed-indentation and alignment, indent/unindent functions can't -be generic, as there is no way to tell, if for example 8 spaces are actually one tab, as they are 2 indent levels -or just one indent level + 4 alignment spaces. Therefor will take the vim way of things, where alignment is not -possible... - -# -# Built-in indenters -# -Right now we removed all built-in indenters due to refactoring and new indentation system. If it turns -out that js indentation for complex stuff like c/c++ is too slow, we maybe have to reintroduce the -built-in indenters. Interesting reference might be in vim, see: vim/src/misc1.c, function get_c_indent. - -# -# Idea: Extending itemData (=attribute information) -# -Scripts would benefit if they could access highlighting information in a -reliable- way, i.e. -not- -what we have now in KateNormalIndent::updateConfig(). - -Possible solution: extend itemData to have another attribute 'type'. -Example: -What types do indentation scripts need? C/C++ like languages need: - * default = everything that is not of the following types - * comment = single and multiline comments, and #if 0ed code - * string = "..." and '...' strings - * pp = all preprocessor macros (#ifdef etc.) - * symbol = characters like: {}[](),; (and more) - -This is actually everything we need for C like languages. Though, some further thoughts: - * number = all kind of numbers: int, double, float - * keyword = keywords like: void, int, while, class -Those two maybe would be a nice addon, but they are not necessarily needed for indentation. - -Shortcomings: -We need a good set of 'types', as they will be hard coded in the Kate Part. --> Todo: Think of other languages, what types do we need? - -In what way are those types useful? -Indenters (and scripts) can for example query doc.findOfType("{", "symbol"); -This will skip all { in comments and strings. -Indenters can check 'where are we?': if (doc.typeAt(cursor) == "comment") ... --> Todo: Find good API. - -How to make it work with our .xml files? -To be backward compatible, the default type would be "default", if not defined otherwise. -To make it work with our .xml files, we would need to adapt C++/Java/Php/... files to set the types -correctly. -Implementation: Extend KateExtendedAttribute to contain the type (besides the defaultStyle). To make -it fast, use an integer (enum) just like the defaultStyles. - -Another approach: Instead of putting a type into a KateExtendedAttribute, we also can put the type -into the KTextEditor::Attribute. Then overlay highlighting like it probably will be done by KDevelop -can also provide the needed type information (otherwise indentation might not work). - -Thoughts welcome. diff --git a/part/Mainpage.dox b/part/Mainpage.dox deleted file mode 100644 index 301d578..0000000 --- a/part/Mainpage.dox +++ /dev/null @@ -1,36 +0,0 @@ -/** @mainpage Kate Editor Component - -The Kate Editor Component (also called Kate Part) implements the -KTextEditor interfaces. Thus, all Kate Part classes are internal -and never appear in public interfaces. - -If you wish to have a text editor component in your application, -use the KTextEditor interfaces. - -@authors -Christoph Cullmann \
-Joseph Wenninger \
-Anders Lund \
-Hamish Rodda \
-Waldo Bastian \
-Charles Samuels \
-Michael Bartl \
-Matt Newell \
-Michael McCallum \
-John Firebaugh \
-Nadeem Hasan \
-Jochen Wilhelmy \
-Glen Parker \
-Michael Koch \
-Dominik Haumann \ - -@maintainers -Christoph Cullmann \ - -@licenses -@lgpl - -*/ -// DOXYGEN_REFERENCES = kdecore kio kdeui kparts interfaces/kdocument interfaces/ktexteditor kjs -// DOXYGEN_SET_PROJECT_NAME = Kate -// vim:ts=4:sw=4:expandtab:filetype=doxygen diff --git a/part/Messages.sh b/part/Messages.sh deleted file mode 100644 index f273e85..0000000 --- a/part/Messages.sh +++ /dev/null @@ -1,4 +0,0 @@ -#! /usr/bin/env bash -$EXTRACTRC `find . -name \*.rc -o -name \*.ui` >> rc.cpp || exit 11 -$EXTRACTATTR --attr=language,name,Language --attr="language,section,Language Section" syntax/data/*.xml >> rc.cpp || exit 12 -$XGETTEXT `find . -name "*.cpp" -o -name "*.h" -o -name '*.js' | egrep -v "/tests" | egrep -v "/plugins" ` -o $podir/katepart4.pot diff --git a/part/NEWS b/part/NEWS deleted file mode 100644 index 0061b57..0000000 --- a/part/NEWS +++ /dev/null @@ -1,47 +0,0 @@ -2008-04-19 - Kate Developer Sprint is over, hacking started again - QtScript support, vi modes in pipeline :) - -2005-05-05 - SVN conversion over, thx to coolo and co ;) - -2003-12-24 - XMas ;) - -2003-08-28 - KDE 3.2 feature freeze is close, last big stuff included like - the folding for indentation based languages and the new indenters - by jesse and the color schemes + file type settings, folding for pythong - still needs work - -2002-11-11 - KDE 3.1 is close, printing + dynamic word wrap seems to work fine ;P - -2002-08-26 - Hacking at the KDE e.V. meeting ;) - -2002-03-28 - The code folding Branch is readded back into HEAD - -2002-01-10 - Kate Part is now in Kdelibs ;) - -Old news of kate part/app in kdebase: - -2002-01-03 - Kate App and Part separated - -2001-11-24 - KTextEditor interfaces are near completion ;) - -2001-06-11 - Little Cullmann got his little Abitur with 1.zero ;) - -2001-05-12 - juhu, my abi is over ;) (just must type a news item ;) - -2001-04-01 - Kant -> Kate - -2001-03-01 - Kant is now official part of KDEBASE ;-) diff --git a/part/README b/part/README deleted file mode 100644 index 7068ba0..0000000 --- a/part/README +++ /dev/null @@ -1,11 +0,0 @@ - *** Kate Part *** -The Kate Part implements the KTextEditor interfaces and it is -highly recommended to use them. Detailed information can be found -in the API documentation of the KTextEditor interfaces: -http://api.kde.org/4.x-api/kdelibs-apidocs/interfaces/ktexteditor/html/index.html - -Homepage: http://kate-editor.org - -Licensing: -The Kate Part and its interfaces are licensed under the LGPL version 2, -not any later version. diff --git a/part/README.testing b/part/README.testing deleted file mode 100644 index a5d05b1..0000000 --- a/part/README.testing +++ /dev/null @@ -1,267 +0,0 @@ - Testing Kate -============== - -Author: Leo Savernik - -Kate contains regression tests to ensure that fixed bugs do not reappear in -newer versions. To facilitate regression testing, a dedicated application -testkateregression will execute the regression tests and compare them to the -expecting results, indicating passed as well as failed testcases. - - -1. Using testkateregression - -------------------------- - -We tried to make regression testing for Kate as easy as possible such that you -can run it before each commit and find out regressions caused by your changes -before they are shipped as part of a release. - -Running all regression tests works by simply invoking - - > make check - -in your kate-part build directory. While executing, testkateregression prints a line -for each executed testcase, prefixed with "PASS" if it passed, and "FAIL" if it -failed. Furthermore, testkateregression stores a comprehensive output log under -/output/index.html. The output log is invaluable for -determining why a certain testcase failed. - -If you invoke testkateregression the first time, it will print instructions on -how to fetch the testsuite and pointing testkateregression to it. This setup -has only to be done once per branch. - - -2. Discriminating your regressions against existing regressions - -------------------------------------------------------------- - -In an ideal universe, all testcases always pass. In this universe, however, -some testcases fail, be it because of anticipating future features not -implemented yet, be it because of nasty bugs which cannot be repaired easily. - -This means if you've hacked on kate for quite some while and then fire up -"make check", you are likely to see many failed tests pass by, most of them -*not* caused by your very changes, as they failed already before. - -To discriminate the failed tests caused by your changes against the unaffected -failures, testkateregression provides the option --save-failures=, which -runs the regression tests and stores all failures under a failure snapshot -identified by . - -The next time you run "make check", testkateregression automatically picks up -the most recently stored failure snapshot and compares the failures and passes -with the one stored in the snapshot. Each failure not listed in the failure -snapshot will be prefixed with "FAIL (new)", indicating that this is a new -failure. Testcases which failed in the snapshot but do pass now are prefixed -with "PASS (new)", indicating that this testcase seems to be fixed now. - - -3. Using testkateregression efficiently - -------------------------------------- - -Therefore, to get the most out of regression testing, we suggest the following -development approach: - - 1. Before you change Kate, update and run testkateregression in the part- - subdirectory. - - > make testkateregression && ./testkateregression --save-failures=last - - This will produce a failure snapshot called "last". - - 2. Hack on Kate. - - 3. Before you commit, run - - > make check - - It will automatically pick up the failure snapshot "last" (provided you - didn't generate a newer one in the meantime) and compare all results with - the previously stored ones. - - If you inspect /output/index.html, the new failures - are marked red. Those are of interest to you, because they have been - caused by your changes. - - New passes are marked green. These were former failures which started - working due to your changes. - - Goto 2 while there are any new failures. - - 4. Commit. - - -4. Invoking testkateregression directly - -------------------------------------- - -While make check is handy and simple enough for the common case, you might -sometimes need more control over regression testing. - -testkateregression features a broad range of options, enabling you to run -dedicated testcases only, specifying an alternate output directory for the -logs, etc. - - > ./testregression --help - -will provide you with a complete list of options. - - -5. Structure of the regression test suite - ---------------------------------------- - -Kate's regression testsuite is located in the KDE repository under - - trunk/tests/katetests/regression - -and consists of two subdirectories - - baseline - tests - -The latter, tests, contains a directory hierarchy for all testcases to be run -by testkateregression. The former, baseline, contains results as they are -expected by correct operation. Mismatch between the output of a test and its -baseline is considered to be a failure. - -Each directory under tests may optionally contain one of the following files. - - .kateconfig - .kateconfig-commands - ignore - KNOWN_FAILURES - -.kateconfig: This file works exactly like .kateconfig as supported by the kate -and kwrite editors. It may contain any kate line variable necessary to set up -the testcases proper. Note that .kateconfig files from parent directories are -not merged with .kateconfig files from child directories. - -.kateconfig-commands: This file may contain all commands that can be entered by -kate's command line (F7). Each line will be interpreted as one command. To the -contrary of .kateconfig, .kateconfig-commands files are merged with -.kateconfig-commands files from parent directories. Nearer ancestors' commands -take precedence over farther ancestors'. - -ignore: This file specifies on each line a file to be ignored in the directory -the ignore-file is located. This enables you to mark any helper files which -otherwise would be interpreted as testcases. Note that hidden files (.*) are -ignored by default, and cannot be "unignored". - -KNOWN_FAILURES: This file specifies on each line a file name of a testcase -which is known to fail. Such known failures are counted towards the total count -of failures but they don't cause testkateregression to return a failure code. - - -6. Structure of a testcase - ------------------------- - -A testcase is comprised of a simple plain text file .txt which may -be located in any subdirectory under tests. This file contains the *initial* -content the testcase operates on. - -Each .txt must be accompanied with a .txt-script which -contains the actual tests to be performed on the testcase. It consists of -simple JavaScript-statements for direct interfacing with Kate. - -Optionally, a .txt can also be accompanied by a -.txt-commands containing a list of valid kate-commands to be executed -before the testcase is run. - -Last but not least, a .txt-result exists under the baseline -subdirectory, which contains a mirrored directory hierarchy of tests. This very -file contains the expected *result* of the performed tests. - - -7. Writing a simple testcase - --------------------------- - -Writing your own testcases is easy once you know how to get started. Let's -test how Kate's C-Style indenter fares with indenting after opening braces. - -First, we create the new initial content under tests/indent/csmart/openbrc.txt -and fill it with (the dashed lines are not part of the content) ---------------------------- - -int main() { - ---------------------------- - -Now, we need to write a script performing some actions. We therefore create -a file tests/indent/csmart/openbrc.txt-script and fill it with ---------------------------- -v.setCursorPosition(1,12); -v.enter(); -v.type("good"); ---------------------------- - -Here, we set the initial cursor position to line 2 (the coordinates are zero- -based) and column 13 which happens to be just after the opening brace. Then -v.enter() simulates pressing the return key in the editor, thus inserting a -new line. v.type simulates typing of the word "good" at the current position -of the cursor. - -The options under .kateconfig specify the C-Style indenter to be applied to the -testcases and an indent width of two. With this information, we know what we -expect as a result. - -What we are still missing is the expected result itself which we create under -baseline/indent/csmart/openbrc.txt-result and fill it with ---------------------------- - -int main() { - good - ---------------------------- - -You can see that "good" is indented by two spaces, even though we didn't -specify those with v.type. We expect from the indenter to provide them for us. - -Last but not least we test the testcase by invoking in kate's part directory - - > ./testkateregression indent/csmart/openbrc.txt - -and checking whether it works the way we intended it. - - -7. The JavaScript-interface to the testcases - ------------------------------------------- - -testkateregression provides you with the following global objects for each -testcase (parenthesis contain aliases): - - view (v) - object of view - document (doc, d) - object of document - output (out, o) - object of direct output to result file - -Each object provides the same methods and fields as the respective JavaScript- -interfaces built in to Kate, like v.setCursorPosition. - -Additionally, v provides the following methods unique to testkateregression. - -type() - Inserts into the current cursor position as if had - been typed by the keyboard. Contrary to insert(), it will - trigger indentation and other checks. -enter([n]), returnKey([n]) - Inserts new lines as if the return key had been pressed times. - This will trigger special indentation rules. Omitting defaults to 1. -up([n]) -down([n]) -prev([n]), left([n]) -next([n]), right([n]) - Moves up/down/prev/next the cursor by characters/lines. Omitting - defaults to 1. - -o provides the following methods: - -write(), print() - Writes out to the result file instead of copying the content of - the editor at end of the testcase. The first invocation of an output - method will generate a new empty result file containing , - whereas consecutive calls to output routines will append to the - result file. -writeln(), println() - Like write, but appends a newline to . -writeCursorPosition(), cursorPosition(), pos() - Writes out , followed by the current cursor position in the - format "(line,col)". The coordinates are zero-based. -writeCursorPositionln(), cursorPositionln(), posln() - Like the above, but append an additional newline. diff --git a/part/README.vimode b/part/README.vimode deleted file mode 100644 index 904c04f..0000000 --- a/part/README.vimode +++ /dev/null @@ -1,24 +0,0 @@ -To enable the VI input mode, go to Settings → Configure Kate... → Editing → -VI Input Mode. It can also be toggled with the “VI Input Mode†setting in the -“Edit†menu (default shortcut key is Meta+Ctrl+V – where Meta usually is the -Windows key). - -Vim incompatibilities: - -1) - Kate: 'O' and 'o' opens [count] new lines and puts you in insert mode - Vim: 'O' and 'o' opens a new line and inserts text [count] times when - exiting insert mode - -2) - Kate: U and is redo - Vim: is normal redo, U is used to "undo all latest changes on one line" - -3) - Kate: :print shows the 'print' dialogue - Vim: :print prints the lines of the given range like its grandfather ed - -4) - Kate: 'Y' yanks to end of line. This is described as 'more - logical' in the Vim documentation (:help Y). - Vim: 'Y' yanks whole line, just like 'yy'. diff --git a/part/TODO b/part/TODO deleted file mode 100644 index ec0dfea..0000000 --- a/part/TODO +++ /dev/null @@ -1,172 +0,0 @@ -TODO: - -**** Bugs **** -* access of deleted cursors by the dynamic hl stuff - -* arbitrary highlighting - * failure to redraw when the cursor is off the screen and the highlighting changes - -* highlighting issues - * external context references don't pick up default attribute (bug 145052) - -* color issues - * use color roles when they become available to initialize attributes - DONE - -> check if this does indeed fix bug 143606 - * port to KStatefulBrush (how do we use this? need to repaint on losing focus or will Qt do it?) - -* HL configuration issues - * current highlighter not selected (regression) - * controls seem to need to be clicked twice? - -* memory usage - * we currently use x16 the size of a file when in memory, if the file does not contain newline characters. - -* RTL issues - * dynamic wrapping of indented lines - x offset is incorrect (calculated as for LTR lines) - -**** Refactoring/Cleanups **** -* code cleanups wherever needed ;) - -* Memory usage and leak auditing - * KateHlContext::items needs to be implicitly shared + autodelete - -**** new features **** - -* Fix EOL whitespace cleaning finally by removing whitespace at load-time and - keeping the document consistent all the time - - -> DONE ;) whitespaces are no cleaned at load time, the magic clean on save stuff is gone - -> is bug 115175 fixed? - Ah, but there are bugs: - -* BiDi finally, using Scribe - * just needs porting of deprecated calls, and testing - -* Finally implement arbitrary highlighting and arbitrary input filtering - * Smart Cursors and Ranges todo list: - * change edit notification to come as KTextEditor::EditInfo or similar - * types: Insert, Remove, Change, Batch -> more EditInfos - * Implement batching - * multiple edits for one logical edit - * multiple logical edits for one undo step - * fix passive changes to cursors/ranges - * extra regression testing needed to check that notifications work across SmartGroup boundaries - * implement feedback requirement tree - * consider a custom pointer type for Smart* objects - * consider removing it now that the multiple watchers plan is probably better - * dynamic highlighting - * catch highlighting being created where the mouse or caret already occupies - * probably already implemented, guess it just needs testing - * add a QVariant as data store for 3rd party apps ? - * D-pointer consideration - * shouldn't get dptr imho - * move back any excessively exposed parts of the smart ranges and cursors - * testcases - * performances testing suite - * need to implement edit merging to reduce changes to cursors with large single edits - * cachegrinding - * make a translation snapshot feature where you can translate any cursor from a certain point in time - would be very cool :) - * code cleanup - * add advance{Pos|Line|Column} functions and replace the set*(*+x) calls - -* Switch internal highlighting to use arbitrary highlighting api and thus be - exposed (read-only) - * only if the above cursors and ranges can be made to perform well enough - -* Buffer reentrancy for multithreaded access - * needed for potential: - * separate threads for processing of bracket marks, - * third party processing - -* More featureful code completion including syntax highlighted entries - * done: - * model based completion - * non-focused completion box (view passes on any interactions required) - * native highlighting of completion entries - * column resizing on scroll - * highlighting - * add a column to CodeCompletionModel to enable displaying an icon just before a completion's name - * column merging - * filtering of items based on metadata - * multiple model merging - * extend metadata to include inheritance depth of an item - * implement configurability - * show/hide/reorder/merge columns - * sorting list - * filtering list - * automatic invocation of code completion - * multiple code completion providers - * api improvement: generic way to detect when a completion could be offered, and possibly replaceable with a plugin, so that multiple model completion can be offered - * in progress: - * implement sorting of items based on metadata, and sorted group headers - * needs to react to model changes - * connect signals from source model to katecompletionmodel and vice-versa - * todo - * provide a way to have a small/tiny box? e.g. the word-completion plugin does not need much... - * implement click-execution of completion entries based on KDE click policy - * implement configurability - * positioning retaining horizontal sync with text when it would mean the completion box going outside the screen or not (alternative: reorganise columns, hide column(s)) - * highlighting mode (native / custom / user / combination) - * consider embedding 3rd party cc config with the above - * make sure enough info is exported that the current completion's documentation can be retreived in a documentation browser; - * place basic documentation in an extended popup... positioning / design still to be worked out - * configurability of keyboard commands for cc - * refine keyboard control - * performance testing and optimisation - * test user-defined highlighting - * test for thread safety - -* Custom widgets in between lines interface (eg. so kcachegrind could use - katepart to display its cpu usage information etc) - * Add an extraHeight() field to KateLineLayout - * Change linesDisplayed() over to use these extra heights - * Remove assumptions about the fixed height of lines (the difficult part? maybe not so hard seeing it supports dynamic wrapping) - * Expose via an interface - -* KateFoldingTree* to use smart* - -* Fix folding for HL's where region end is defined by a new region starting (bug 112888) - -* Splitting a view over multiple columns - -* Modular input subsystem, to support emulation of other editors in a clean way - -> see also scripting and idea with extending the command line - -> in progress to some degree (vi mode) - -* Improved input modes especially in block selection - -* Multiple selection support - -* Better support for information overlay (eg. documentation of a function - - switch between short / detailed descriptions) - -* Whatever else is needed for multiuser editing (and perhaps put most of it - inside the part, so eg. kate, kdevelop, quanta etc. could all use it) - -* Scripting using QtScript (in progress) - * design stable API for KDE >= 4.1 - * add API so that scripts can save&load data (remember: we don't have persistent loaded scripts right now) - -* Good interface for JavaScript indentation scripts - * add unindent() function. Call if available, otherwise use current fallback - It is a good idea to look how other editors deal with indentation, I think vim & emacs are good - references... - The INDENTATION file in this directory describes the general concepts. - -* Cursor position restriction extension - * export enough api to allow 3rd party apps to provide a cursor that - * handles advancing/retreating - * allows to query if a position is a valid cursor position, and to find the closest valid position - * create a test version which does some basic restriction - -* Input restriction extension - * needed? probably not - -* improved block selection with tabs - * block selection on tabs selects too much of the line that contains the tab, because the tab - counts as one character but is rendered as multiple visible spaces. There are several possible - solutions: - * expand the whole blockselection to include the whole width of the tab - * cut the tab into multiple spaces - * implement both and make it configurable :) - diff --git a/part/TODO.vimode b/part/TODO.vimode deleted file mode 100644 index 9b98659..0000000 --- a/part/TODO.vimode +++ /dev/null @@ -1,13 +0,0 @@ -* Make it possible to save marks, command history etc. between sessions. -* integrate the vi input mode marks with kate's bookmarks system -* make mouse dragging start visual mode -* in insert mode should first delete back to the point where insert mode - was started even if that was in the middle of a word -* make it possible to use registers in ranges and add support for the the < and - > registers (start and end of selection) -* synchronize modes for views of the same document. this is necessary because - when in insert mode all undo items are merged. if one of the views of a - document is in insert mode, all undo items will be merged. -* commands like 'y', 'gU', etc, in visual mode should result in the cursor - being at the start of the visual mode selection after having been returned to - normal mode diff --git a/part/buffer/katetextblock.cpp b/part/buffer/katetextblock.cpp deleted file mode 100644 index f52f8f3..0000000 --- a/part/buffer/katetextblock.cpp +++ /dev/null @@ -1,616 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextblock.h" -#include "katetextbuffer.h" - -namespace Kate { - -TextBlock::TextBlock (TextBuffer *buffer, int startLine) - : m_buffer (buffer) - , m_startLine (startLine) -{ -} - -TextBlock::~TextBlock () -{ - // blocks should be empty before they are deleted! - Q_ASSERT (m_lines.empty()); - Q_ASSERT (m_cursors.empty()); - - // it only is a hint for ranges for this block, not the storage of them -} - -void TextBlock::setStartLine (int startLine) -{ - // allow only valid lines - Q_ASSERT (startLine >= 0); - Q_ASSERT (startLine < m_buffer->lines ()); - - m_startLine = startLine; -} - -TextLine TextBlock::line (int line) const -{ - // right input - Q_ASSERT (line >= startLine ()); - - // calc internal line - line = line - startLine (); - - // in range - Q_ASSERT (line < m_lines.size ()); - - // get text line - return m_lines.at(line); -} - -void TextBlock::text (QString &text) const -{ - // combine all lines - for (int i = 0; i < m_lines.size(); ++i) { - // not first line, insert \n - if (i > 0 || startLine() > 0) - text.append ('\n'); - - text.append (m_lines.at(i)->text ()); - } -} - -void TextBlock::wrapLine (const KTextEditor::Cursor &position) -{ - // calc internal line - int line = position.line () - startLine (); - - // get text - QString &text = m_lines.at(line)->textReadWrite (); - - // check if valid column - Q_ASSERT (position.column() >= 0); - Q_ASSERT (position.column() <= text.size()); - - // create new line and insert it - m_lines.insert (m_lines.begin() + line + 1, TextLine (new TextLineData())); - - // perhaps remove some text from previous line and append it - if (position.column() < text.size ()) { - // text from old line moved first to new one - m_lines.at(line+1)->textReadWrite() = text.right (text.size() - position.column()); - - // now remove wrapped text from old line - text.chop (text.size() - position.column()); - } - - /** - * notify the text history - */ - m_buffer->history().wrapLine (position); - - /** - * cursor and range handling below - */ - - // no cursors will leave or join this block - - // no cursors in this block, no work to do.. - if (m_cursors.empty()) - return; - - // move all cursors on the line which has the text inserted - // remember all ranges modified - QSet changedRanges; - foreach (TextCursor *cursor, m_cursors) { - // skip cursors on lines in front of the wrapped one! - if (cursor->lineInBlock() < line) - continue; - - // either this is simple, line behind the wrapped one - if (cursor->lineInBlock() > line) { - // patch line of cursor - cursor->m_line++; - } - - // this is the wrapped line - else { - // skip cursors with too small column - if (cursor->column() <= position.column()) { - if (cursor->column() < position.column() || !cursor->m_moveOnInsert) - continue; - } - - // move cursor - - // patch line of cursor - cursor->m_line++; - - // patch column - cursor->m_column -= position.column(); - } - - // remember range, if any - if (cursor->kateRange()) - changedRanges.insert (cursor->kateRange()); - } - - // check validity of all ranges, might invalidate them... - foreach (TextRange *range, changedRanges) - range->checkValidity (); -} - -void TextBlock::unwrapLine (int line, TextBlock *previousBlock) -{ - // calc internal line - line = line - startLine (); - - // two possiblities: either first line of this block or later line - if (line == 0) { - // we need previous block with at least one line - Q_ASSERT (previousBlock); - Q_ASSERT (previousBlock->lines () > 0); - - // move last line of previous block to this one, might result in empty block - TextLine oldFirst = m_lines.at(0); - int lastLineOfPreviousBlock = previousBlock->lines ()-1; - TextLine newFirst = previousBlock->m_lines.last(); - m_lines[0] = newFirst; - previousBlock->m_lines.erase (previousBlock->m_lines.begin() + (previousBlock->lines () - 1)); - - // append text - int oldSizeOfPreviousLine = newFirst->text().size(); - newFirst->textReadWrite().append (oldFirst->text()); - - // patch startLine of this block - --m_startLine; - - /** - * notify the text history in advance - */ - m_buffer->history().unwrapLine (startLine () + line, oldSizeOfPreviousLine); - - /** - * cursor and range handling below - */ - - // no cursors in this and previous block, no work to do.. - // no need to touch ranges-cache, without cursors, no range could end between this blocks! - if (previousBlock->m_cursors.empty() && m_cursors.empty()) - return; - - // move all cursors because of the unwrapped line - // remember all ranges modified - QSet changedRanges; - foreach (TextCursor *cursor, m_cursors) { - // this is the unwrapped line - if (cursor->lineInBlock() == 0) { - // patch column - cursor->m_column += oldSizeOfPreviousLine; - } - - // remember range, if any - if (cursor->kateRange()) - changedRanges.insert (cursor->kateRange()); - } - - // move cursors of the moved line from previous block to this block now - QSet newPreviousCursors; - QSet rangesMoved; - foreach (TextCursor *cursor, previousBlock->m_cursors) { - if (cursor->lineInBlock() == lastLineOfPreviousBlock) { - cursor->m_line = 0; - cursor->m_block = this; - m_cursors.insert (cursor); - - // remember ranges moved over block boundary - if (cursor->kateRange()) - rangesMoved.insert (cursor->kateRange()); - } - else - newPreviousCursors.insert (cursor); - } - previousBlock->m_cursors = newPreviousCursors; - - foreach (TextRange *range, rangesMoved) { - // either now only in new block - if (range->start().line () >= startLine()) - previousBlock->removeRange (range); - - // or now in both - updateRange (range); - } - - // check validity of all ranges, might invalidate them... - foreach (TextRange *range, changedRanges) - range->checkValidity (); - - // be done - return; - } - - // easy: just move text to previous line and remove current one - int oldSizeOfPreviousLine = m_lines.at(line-1)->text().size(); - m_lines.at(line-1)->textReadWrite().append (m_lines.at(line)->text()); - m_lines.erase (m_lines.begin () + line); - - /** - * notify the text history in advance - */ - m_buffer->history().unwrapLine (startLine () + line, oldSizeOfPreviousLine); - - /** - * cursor and range handling below - */ - - // no cursors in this block, no work to do.. - if (m_cursors.empty()) - return; - - // move all cursors because of the unwrapped line - // remember all ranges modified - QSet changedRanges; - foreach (TextCursor *cursor, m_cursors) { - // skip cursors in lines in front of removed one - if (cursor->lineInBlock() < line) - continue; - - // this is the unwrapped line - if (cursor->lineInBlock() == line) { - // patch column - cursor->m_column += oldSizeOfPreviousLine; - } - - // patch line of cursor - cursor->m_line--; - - // remember range, if any - if (cursor->kateRange()) - changedRanges.insert (cursor->kateRange()); - } - - // check validity of all ranges, might invalidate them... - foreach (TextRange *range, changedRanges) - range->checkValidity (); -} - -void TextBlock::insertText (const KTextEditor::Cursor &position, const QString &text) -{ - // calc internal line - int line = position.line () - startLine (); - - // get text - QString &textOfLine = m_lines.at(line)->textReadWrite (); - int oldLength = textOfLine.size (); - - // check if valid column - Q_ASSERT (position.column() >= 0); - Q_ASSERT (position.column() <= textOfLine.size()); - - // insert text - textOfLine.insert (position.column(), text); - - /** - * notify the text history - */ - m_buffer->history().insertText (position, text.size(), oldLength); - - /** - * cursor and range handling below - */ - - // no cursors in this block, no work to do.. - if (m_cursors.empty()) - return; - - // move all cursors on the line which has the text inserted - // remember all ranges modified - QSet changedRanges; - foreach (TextCursor *cursor, m_cursors) { - // skip cursors not on this line! - if (cursor->lineInBlock() != line) - continue; - - // skip cursors with too small column - if (cursor->column() <= position.column()) { - if (cursor->column() < position.column() || !cursor->m_moveOnInsert) - continue; - } - - // patch column of cursor - if (cursor->m_column <= oldLength) - cursor->m_column += text.size (); - - // special handling if cursor behind the real line, e.g. non-wrapping cursor in block selection mode - else if (cursor->m_column < textOfLine.size()) - cursor->m_column = textOfLine.size(); - - // remember range, if any - if (cursor->kateRange()) - changedRanges.insert (cursor->kateRange()); - } - - // check validity of all ranges, might invalidate them... - foreach (TextRange *range, changedRanges) - range->checkValidity (); -} - -void TextBlock::removeText (const KTextEditor::Range &range, QString &removedText) -{ - // calc internal line - int line = range.start().line () - startLine (); - - // get text - QString &textOfLine = m_lines.at(line)->textReadWrite (); - int oldLength = textOfLine.size (); - - // check if valid column - Q_ASSERT (range.start().column() >= 0); - Q_ASSERT (range.start().column() <= textOfLine.size()); - Q_ASSERT (range.end().column() >= 0); - Q_ASSERT (range.end().column() <= textOfLine.size()); - - // get text which will be removed - removedText = textOfLine.mid (range.start().column(), range.end().column() - range.start().column()); - - // remove text - textOfLine.remove (range.start().column(), range.end().column() - range.start().column()); - - /** - * notify the text history - */ - m_buffer->history().removeText (range, oldLength); - - /** - * cursor and range handling below - */ - - // no cursors in this block, no work to do.. - if (m_cursors.empty()) - return; - - // move all cursors on the line which has the text removed - // remember all ranges modified - QSet changedRanges; - foreach (TextCursor *cursor, m_cursors) { - // skip cursors not on this line! - if (cursor->lineInBlock() != line) - continue; - - // skip cursors with too small column - if (cursor->column() <= range.start().column()) - continue; - - // patch column of cursor - if (cursor->column() <= range.end().column()) - cursor->m_column = range.start().column (); - else - cursor->m_column -= (range.end().column() - range.start().column()); - - // remember range, if any - if (cursor->kateRange()) - changedRanges.insert (cursor->kateRange()); - } - - // check validity of all ranges, might invalidate them... - foreach (TextRange *range, changedRanges) - range->checkValidity (); -} - -void TextBlock::debugPrint (int blockIndex) const -{ - // print all blocks - for (int i = 0; i < m_lines.size(); ++i) - printf ("%4d - %4d : %4d : '%s'\n", blockIndex, startLine() + i - , m_lines.at(i)->text().size(), qPrintable (m_lines.at(i)->text())); -} - -TextBlock *TextBlock::splitBlock (int fromLine) -{ - // half the block - int linesOfNewBlock = lines () - fromLine; - - // create and insert new block - TextBlock *newBlock = new TextBlock (m_buffer, startLine() + fromLine); - - // move lines - newBlock->m_lines.reserve (linesOfNewBlock); - for (int i = fromLine; i < m_lines.size(); ++i) - newBlock->m_lines.append (m_lines.at(i)); - m_lines.resize (fromLine); - - // move cursors - QSet oldBlockSet; - QSet rangesInteresting; - foreach (TextCursor *cursor, m_cursors) { - if (cursor->kateRange()) - rangesInteresting.insert (cursor->kateRange()); - - if (cursor->lineInBlock() >= fromLine) { - cursor->m_line = cursor->lineInBlock() - fromLine; - cursor->m_block = newBlock; - newBlock->m_cursors.insert (cursor); - } - else - oldBlockSet.insert (cursor); - } - m_cursors = oldBlockSet; - - foreach (TextRange *range, rangesInteresting) { - // only in new block - if (range->start().line () >= newBlock->startLine()) { - removeRange (range); - newBlock->updateRange (range); - } - } - - // return the new generated block - return newBlock; -} - -void TextBlock::mergeBlock (TextBlock *targetBlock) -{ - // move cursors, do this first, now still lines() count is correct for target - foreach (TextCursor *cursor, m_cursors) { - cursor->m_line = cursor->lineInBlock() + targetBlock->lines (); - cursor->m_block = targetBlock; - targetBlock->m_cursors.insert (cursor); - } - m_cursors.clear (); - - // move lines - targetBlock->m_lines.reserve (targetBlock->lines() + lines ()); - for (int i = 0; i < m_lines.size(); ++i) - targetBlock->m_lines.append (m_lines.at(i)); - m_lines.clear (); - - QList allRanges = m_uncachedRanges.toList() + m_cachedLineForRanges.keys(); - foreach(TextRange* range, allRanges) { - removeRange(range); - targetBlock->updateRange(range); - } -} - -void TextBlock::deleteBlockContent () -{ - // kill cursors, if not belonging to a range - QSet copy = m_cursors; - foreach (TextCursor *cursor, copy) - if (!cursor->kateRange()) - delete cursor; - - // kill lines - m_lines.clear (); -} - -void TextBlock::clearBlockContent (TextBlock *targetBlock) -{ - // move cursors, if not belonging to a range - QSet copy = m_cursors; - foreach (TextCursor *cursor, copy) { - if (!cursor->kateRange()) { - cursor->m_column = 0; - cursor->m_line = 0; - cursor->m_block = targetBlock; - targetBlock->m_cursors.insert (cursor); - m_cursors.remove (cursor); - } - } - - // kill lines - m_lines.clear (); -} - -void TextBlock::updateRange (TextRange* range) -{ - /** - * get some simple facts about our nice range - */ - const int startLine = range->startInternal().lineInternal(); - const int endLine = range->endInternal().lineInternal(); - const bool isSingleLine = startLine == endLine; - - /** - * The range is still a single-line range, and is still cached to the correct line. - */ - if(isSingleLine && m_cachedLineForRanges.contains (range) && (m_cachedLineForRanges.value(range) == startLine - m_startLine)) - return; - - /** - * The range is still a multi-line range, and is already in the correct set. - */ - if(!isSingleLine && m_uncachedRanges.contains (range)) - return; - - /** - * remove, if already there! - */ - if(containsRange(range)) - removeRange(range); - - /** - * simple case: multi-line range - */ - if (!isSingleLine) { - /** - * The range cannot be cached per line, as it spans multiple lines - */ - m_uncachedRanges.insert(range); - return; - } - - /** - * The range is contained by a single line, put it into the line-cache - */ - const int lineOffset = startLine - m_startLine; - - /** - * enlarge cache if needed - */ - if (m_cachedRangesForLine.size() <= lineOffset) - m_cachedRangesForLine.resize(lineOffset+1); - - /** - * insert into mapping - */ - m_cachedRangesForLine[lineOffset].insert(range); - m_cachedLineForRanges[range] = lineOffset; -} - -void TextBlock::removeRange (TextRange* range) -{ - /** - * uncached range? remove it and be done - */ - if(m_uncachedRanges.remove (range)) { - /** - * must be only uncached! - */ - Q_ASSERT (!m_cachedLineForRanges.contains(range)); - - return; - } - - /** - * cached range? - */ - QHash::iterator it = m_cachedLineForRanges.find(range); - if (it != m_cachedLineForRanges.end()) { - /** - * must be only cached! - */ - Q_ASSERT (!m_uncachedRanges.contains(range)); - - /** - * query the range from cache, must be there - */ - Q_ASSERT (m_cachedRangesForLine.at(*it).contains(range)); - - /** - * remove it and be done - */ - m_cachedRangesForLine[*it].remove(range); - m_cachedLineForRanges.erase(it); - return; - } - - /** - * else: perhaps later see if we can assert, that this is not allowed? - */ -} - -} diff --git a/part/buffer/katetextblock.h b/part/buffer/katetextblock.h deleted file mode 100644 index 2b9d050..0000000 --- a/part/buffer/katetextblock.h +++ /dev/null @@ -1,244 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTBLOCK_H -#define KATE_TEXTBLOCK_H - -#include -#include - -#include "katepartprivate_export.h" -#include -#include "katetextline.h" - -namespace Kate { - -class TextBuffer; -class TextCursor; -class TextRange; - -/** - * Class representing a text block. - * This is used to build up a Kate::TextBuffer. - */ -class KATEPART_TESTS_EXPORT TextBlock { - friend class TextCursor; - friend class TextRange; - friend class TextBuffer; - - public: - /** - * Construct an empty text block. - * @param buffer parent text buffer - * @param startLine start line of this block - */ - TextBlock (TextBuffer *buffer, int startLine); - - /** - * Destruct the text block - */ - ~TextBlock (); - - /** - * Start line of this block. - * @return start line of this block - */ - int startLine () const { return m_startLine; } - - /** - * Set start line of this block. - * @param startLine new start line of this block - */ - void setStartLine (int startLine); - - /** - * Retrieve a text line. - * @param line wanted line number - * @return text line - */ - TextLine line (int line) const; - - /** - * Append a new line. - * @param line line to append - */ - void appendLine (TextLine line) { m_lines.append (line); } - - /** - * Number of lines in this block. - * @return number of lines - */ - int lines () const { return m_lines.size(); } - - /** - * Retrieve text of block. - * @param text for this block, lines separated by '\n' - */ - void text (QString &text) const; - - /** - * Wrap line at given cursor position. - * @param position line/column as cursor where to wrap - * @param nextBlock next block, if any - */ - void wrapLine (const KTextEditor::Cursor &position); - - /** - * Unwrap given line. - * @param line line to unwrap - * @param previousBlock previous block, if any, if we unwrap first line in block, we need to have this - */ - void unwrapLine (int line, TextBlock *previousBlock); - - /** - * Insert text at given cursor position. - * @param position position where to insert text - * @param text text to insert - */ - void insertText (const KTextEditor::Cursor &position, const QString &text); - - /** - * Remove text at given range. - * @param range range of text to remove, must be on one line only. - * @param removedText will be filled with removed text - */ - void removeText (const KTextEditor::Range &range, QString &removedText); - - /** - * Debug output, print whole block content with line numbers and line length - * @param blockIndex index of this block in buffer - */ - void debugPrint (int blockIndex) const; - - /** - * Split given block. A new block will be created and all lines starting from the given index will - * be moved to it, together with the cursors belonging to it. - * @param fromLine line from which to split - * @return new block containing the lines + cursors removed from this one - */ - TextBlock *splitBlock (int fromLine); - - /** - * Merge this block with given one, the given one must be a direct predecessor. - * @param targetBlock block to merge with - */ - void mergeBlock (TextBlock *targetBlock); - - /** - * Delete the block content, delete all lines and delete all cursors not bound to ranges. - * This is used in destructor of TextBuffer, for fast cleanup. Only stuff remaining afterwards are cursors which are - * part of a range, TextBuffer will delete them itself... - */ - void deleteBlockContent (); - - /** - * Clear the block content, delete all lines, move all cursors not bound to range to given block at 0,0. - * This is used by clear() of TextBuffer. - * @param targetBlock empty target block for cursors - */ - void clearBlockContent (TextBlock *targetBlock); - - /** - * Return all ranges in this block which might intersect the given line. - * @param line line to check intersection - * @return list of sets of possible candidate ranges - */ - QList > rangesForLine (int line) const { - return QList >() << m_uncachedRanges << cachedRangesForLine(line); - } - - /** - * Is the given range contained in this block? - * @param range range to check for - * @return contained in this blocks mapping? - */ - bool containsRange (TextRange* range) const { - return m_cachedLineForRanges.contains(range) || m_uncachedRanges.contains(range); - } - - private: - /** - * Update a range from this block. - * Will move the range to right set, either cached for one-line ranges or not. - * @param range range to update - */ - void updateRange(TextRange* range); - - /** - * Remove a range from this block. - * @param range range to remove - */ - void removeRange (TextRange* range); - - /** - * Return all ranges in this block which might intersect the given line and only span one line. - * For them an internal fast lookup cache is hold. - * @param line line to check intersection - * @return set of ranges - */ - QSet cachedRangesForLine (int line) const { - line -= m_startLine; - if(line >= 0 && line < m_cachedRangesForLine.size()) - return m_cachedRangesForLine[line]; - else - return QSet(); - } - - private: - /** - * parent text buffer - */ - TextBuffer *m_buffer; - - /** - * Lines contained in this buffer. These are shared pointers. - */ - QVector m_lines; - - /** - * Startline of this block - */ - int m_startLine; - - /** - * Set of cursors for this block. - */ - QSet m_cursors; - - /** - * Contains for each line-offset the ranges that were cached into it. - * These ranges are fully contained by the line. - */ - QVector > m_cachedRangesForLine; - - /** - * Maps for each cached range the line into which the range was cached. - */ - QHash m_cachedLineForRanges; - - /** - * This contains all the ranges that are not cached. - */ - QSet m_uncachedRanges; -}; - -} - -#endif diff --git a/part/buffer/katetextbuffer.cpp b/part/buffer/katetextbuffer.cpp deleted file mode 100644 index 10d8b44..0000000 --- a/part/buffer/katetextbuffer.cpp +++ /dev/null @@ -1,767 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" - -#include "katetextbuffer.h" -#include "katetextloader.h" - -// this is unfortunate, but needed for performance -#include "katedocument.h" -#include "kateview.h" - -#include - -namespace Kate { - -TextBuffer::TextBuffer (KTextEditor::Document *parent, int blockSize) - : QObject (parent) - , m_document (parent) - , m_history (*this) - , m_blockSize (blockSize) - , m_lines (0) - , m_lastUsedBlock (0) - , m_revision (0) - , m_editingTransactions (0) - , m_editingLastRevision (0) - , m_editingLastLines (0) - , m_editingMinimalLineChanged (-1) - , m_editingMaximalLineChanged (-1) - , m_encodingProberType (KEncodingProber::Universal) - , m_fallbackTextCodec (0) - , m_textCodec (0) - , m_generateByteOrderMark (false) - , m_endOfLineMode (eolUnix) - , m_removeTrailingSpaces (false) -{ - // minimal block size must be > 0 - Q_ASSERT (m_blockSize > 0); - - // create initial state - clear (); -} - -TextBuffer::~TextBuffer () -{ - // remove document pointer, this will avoid any notifyAboutRangeChange to have a effect - m_document = 0; - - // not allowed during editing - Q_ASSERT (m_editingTransactions == 0); - - // kill all ranges, work on copy, they will remove themself from the hash - QSet copyRanges = m_ranges; - qDeleteAll (copyRanges); - Q_ASSERT (m_ranges.empty()); - - // clean out all cursors and lines, only cursors belonging to range will survive - foreach(TextBlock* block, m_blocks) - block->deleteBlockContent (); - - // delete all blocks, now that all cursors are really deleted - // else asserts in destructor of blocks will fail! - qDeleteAll (m_blocks); - m_blocks.clear (); - - // kill all invalid cursors, do this after block deletion, to uncover if they might be still linked in blocks - QSet copyCursors = m_invalidCursors; - qDeleteAll (copyCursors); - Q_ASSERT (m_invalidCursors.empty()); -} - -void TextBuffer::invalidateRanges() -{ - // invalidate all ranges, work on copy, they might delete themself... - QSet copyRanges = m_ranges; - foreach (TextRange *range, copyRanges) - range->setRange (KTextEditor::Cursor::invalid(), KTextEditor::Cursor::invalid()); -} - -void TextBuffer::clear () -{ - // not allowed during editing - Q_ASSERT (m_editingTransactions == 0); - - invalidateRanges(); - - // new block for empty buffer - TextBlock *newBlock = new TextBlock (this, 0); - newBlock->appendLine (TextLine (new TextLineData())); - - // clean out all cursors and lines, either move them to newBlock or invalidate them, if belonging to a range - foreach(TextBlock* block, m_blocks) - block->clearBlockContent (newBlock); - - // kill all buffer blocks - qDeleteAll (m_blocks); - m_blocks.clear (); - - // insert one block with one empty line - m_blocks.append (newBlock); - - // reset lines and last used block - m_lines = 1; - m_lastUsedBlock = 0; - - // reset revision - m_revision = 0; - - // reset bom detection - m_generateByteOrderMark = false; - - // reset the filter device - m_mimeTypeForFilterDev = "text/plain"; - - // clear edit history - m_history.clear (); - - // we got cleared - emit cleared (); -} - -TextLine TextBuffer::line (int line) const -{ - // get block, this will assert on invalid line - int blockIndex = blockForLine (line); - - // get line - return m_blocks.at(blockIndex)->line (line); -} - -QString TextBuffer::text () const -{ - QString text; - - // combine all blocks - foreach(TextBlock* block, m_blocks) - block->text (text); - - // return generated string - return text; -} - -bool TextBuffer::startEditing () -{ - // increment transaction counter - ++m_editingTransactions; - - // if not first running transaction, do nothing - if (m_editingTransactions > 1) - return false; - - // reset informations about edit... - m_editingLastRevision = m_revision; - m_editingLastLines = m_lines; - m_editingMinimalLineChanged = -1; - m_editingMaximalLineChanged = -1; - - // transaction has started - emit editingStarted (); - - // first transaction started - return true; -} - -bool TextBuffer::finishEditing () -{ - // only allowed if still transactions running - Q_ASSERT (m_editingTransactions > 0); - - // decrement counter - --m_editingTransactions; - - // if not last running transaction, do nothing - if (m_editingTransactions > 0) - return false; - - // assert that if buffer changed, the line ranges are set and valid! - Q_ASSERT (!editingChangedBuffer() || (m_editingMinimalLineChanged != -1 && m_editingMaximalLineChanged != -1)); - Q_ASSERT (!editingChangedBuffer() || (m_editingMinimalLineChanged <= m_editingMaximalLineChanged)); - Q_ASSERT (!editingChangedBuffer() || (m_editingMinimalLineChanged >= 0 && m_editingMinimalLineChanged < m_lines)); - Q_ASSERT (!editingChangedBuffer() || (m_editingMaximalLineChanged >= 0 && m_editingMaximalLineChanged < m_lines)); - - // transaction has finished - emit editingFinished (); - - // last transaction finished - return true; -} - -void TextBuffer::wrapLine (const KTextEditor::Cursor &position) -{ - // only allowed if editing transaction running - Q_ASSERT (m_editingTransactions > 0); - - // get block, this will assert on invalid line - int blockIndex = blockForLine (position.line()); - - // let the block handle the wrapLine - // this can only lead to one more line in this block - // no other blocks will change - ++m_lines; // first alter the line counter, as functions called will need the valid one - m_blocks.at(blockIndex)->wrapLine (position); - - // remember changes - ++m_revision; - - // update changed line interval - if (position.line() < m_editingMinimalLineChanged || m_editingMinimalLineChanged == -1) - m_editingMinimalLineChanged = position.line(); - - if (position.line() <= m_editingMaximalLineChanged) - ++m_editingMaximalLineChanged; - else - m_editingMaximalLineChanged = position.line() + 1; - - // fixup all following blocks - fixStartLines (blockIndex); - - // balance the changed block if needed - balanceBlock (blockIndex); - - // emit signal about done change - emit lineWrapped (position); -} - -void TextBuffer::unwrapLine (int line) -{ - // only allowed if editing transaction running - Q_ASSERT (m_editingTransactions > 0); - - // line 0 can't be unwrapped - Q_ASSERT (line > 0); - - // get block, this will assert on invalid line - int blockIndex = blockForLine (line); - - // is this the first line in the block? - bool firstLineInBlock = (line == m_blocks.at(blockIndex)->startLine()); - - // let the block handle the unwrapLine - // this can either lead to one line less in this block or the previous one - // the previous one could even end up with zero lines - m_blocks.at(blockIndex)->unwrapLine (line, (blockIndex > 0) ? m_blocks.at(blockIndex-1) : 0); - --m_lines; - - // decrement index for later fixup, if we modified the block in front of the found one - if (firstLineInBlock) - --blockIndex; - - // remember changes - ++m_revision; - - // update changed line interval - if ((line - 1) < m_editingMinimalLineChanged || m_editingMinimalLineChanged == -1) - m_editingMinimalLineChanged = line - 1; - - if (line <= m_editingMaximalLineChanged) - --m_editingMaximalLineChanged; - else - m_editingMaximalLineChanged = line -1; - - // fixup all following blocks - fixStartLines (blockIndex); - - // balance the changed block if needed - balanceBlock (blockIndex); - - // emit signal about done change - emit lineUnwrapped (line); -} - -void TextBuffer::insertText (const KTextEditor::Cursor &position, const QString &text) -{ - // only allowed if editing transaction running - Q_ASSERT (m_editingTransactions > 0); - - // skip work, if no text to insert - if (text.isEmpty()) - return; - - // get block, this will assert on invalid line - int blockIndex = blockForLine (position.line()); - - // let the block handle the insertText - m_blocks.at(blockIndex)->insertText (position, text); - - // remember changes - ++m_revision; - - // update changed line interval - if (position.line () < m_editingMinimalLineChanged || m_editingMinimalLineChanged == -1) - m_editingMinimalLineChanged = position.line (); - - if (position.line () > m_editingMaximalLineChanged) - m_editingMaximalLineChanged = position.line (); - - // emit signal about done change - emit textInserted (position, text); -} - -void TextBuffer::removeText (const KTextEditor::Range &range) -{ - // only allowed if editing transaction running - Q_ASSERT (m_editingTransactions > 0); - - // only ranges on one line are supported - Q_ASSERT (range.start().line() == range.end().line()); - - // start colum <= end column and >= 0 - Q_ASSERT (range.start().column() <= range.end().column()); - Q_ASSERT (range.start().column() >= 0); - - // skip work, if no text to remove - if (range.isEmpty()) - return; - - // get block, this will assert on invalid line - int blockIndex = blockForLine (range.start().line()); - - // let the block handle the removeText, retrieve removed text - QString text; - m_blocks.at(blockIndex)->removeText (range, text); - - // remember changes - ++m_revision; - - // update changed line interval - if (range.start().line() < m_editingMinimalLineChanged || m_editingMinimalLineChanged == -1) - m_editingMinimalLineChanged = range.start().line(); - - if (range.start().line() > m_editingMaximalLineChanged) - m_editingMaximalLineChanged = range.start().line(); - - // emit signal about done change - emit textRemoved (range, text); -} - -int TextBuffer::blockForLine (int line) const -{ - // only allow valid lines - Q_ASSERT (line >= 0); - Q_ASSERT (line < lines()); - - // block to start search with - int index = m_lastUsedBlock; - int blockStart = 0; - int blockEnd = m_blocks.size(); - - // check if start is ok - if (index < 0 || index >= m_blocks.size()) - index = 0; - - // search for right block - forever { - // facts bout this block - TextBlock* block = m_blocks.at(index); - const int start = block->startLine(); - const int lines = block->lines (); - - // right block found, remember it and return it - if (start <= line && line < (start + lines)) { - m_lastUsedBlock = index; - return index; - } - - if (line < start) - { - // Search left of index - blockEnd = index; - }else{ - // Search right of index - blockStart = index+1; - } - index = (blockStart + (blockEnd-1)) / 2; - } - - // we should always find a block - Q_ASSERT (false); - return -1; -} - -void TextBuffer::fixStartLines (int startBlock) -{ - // only allow valid start block - Q_ASSERT (startBlock >= 0); - Q_ASSERT (startBlock < m_blocks.size()); - - // new start line for next block - TextBlock* block = m_blocks.at(startBlock); - int newStartLine = block->startLine () + block->lines (); - - // fixup block - for (int index = startBlock + 1; index < m_blocks.size(); ++index) { - // set new start line - block = m_blocks.at(index); - block->setStartLine (newStartLine); - - // calculate next start line - newStartLine += block->lines (); - } -} - -void TextBuffer::balanceBlock (int index) -{ - /** - * two cases, too big or too small block - */ - TextBlock *blockToBalance = m_blocks.at(index); - - // first case, too big one, split it - if (blockToBalance->lines () >= 2 * m_blockSize) { - // half the block - int halfSize = blockToBalance->lines () / 2; - - // create and insert new block behind current one, already set right start line - TextBlock *newBlock = blockToBalance->splitBlock (halfSize); - Q_ASSERT (newBlock); - m_blocks.insert (m_blocks.begin() + index + 1, newBlock); - - // split is done - return; - } - - // second case: possibly too small block - - // if only one block, no chance to unite - // same if this is first block, we always append to previous one - if (index == 0) - return; - - // block still large enough, do nothing - if (2 * blockToBalance->lines () > m_blockSize) - return; - - // unite small block with predecessor - TextBlock *targetBlock = m_blocks.at(index-1); - - // merge block - blockToBalance->mergeBlock (targetBlock); - - // delete old block - delete blockToBalance; - m_blocks.erase (m_blocks.begin() + index); -} - -void TextBuffer::debugPrint (const QString &title) const -{ - // print header with title - printf ("%s (lines: %d bs: %d)\n", qPrintable (title), m_lines, m_blockSize); - - // print all blocks - for (int i = 0; i < m_blocks.size(); ++i) - m_blocks.at(i)->debugPrint (i); -} - -bool TextBuffer::load (const QString &filename, bool &encodingErrors) -{ - // fallback codec must exist - Q_ASSERT (m_fallbackTextCodec); - - // codec must be set! - Q_ASSERT (m_textCodec); - - /** - * first: clear buffer in any case! - */ - clear (); - - /** - * check if this is a normal file or not, else exit - */ - KDE_struct_stat sbuf; - if (KDE::stat(filename, &sbuf) != 0 || !S_ISREG(sbuf.st_mode)) - return false; - - /** - * construct the file loader for the given file, with correct prober type - */ - Kate::TextLoader file (filename, m_encodingProberType); - - /** - * triple play, maximal three loading rounds - * 0) use the given encoding, be done, if no encoding errors happen - * 1) use BOM to decided if unicode or if that fails, use encoding prober, if no encoding errors happen, be done - * 2) use fallback encoding, be done, if no encoding errors happen - * 3) use again given encoding, be done in any case - */ - for (int i = 0; i < 4; ++i) { - /** - * kill all blocks beside first one - */ - for (int b = 1; b < m_blocks.size(); ++b) { - TextBlock* block = m_blocks.at(b); - block->m_lines.clear (); - delete block; - } - m_blocks.resize (1); - - /** - * remove lines in first block - */ - m_blocks.last()->m_lines.clear (); - m_lines = 0; - - /** - * try to open file, with given encoding - * in round 0 + 3 use the given encoding from user - * in round 1 use 0, to trigger detection - * in round 2 use fallback - */ - QTextCodec *codec = m_textCodec; - if (i == 1) - codec = 0; - else if (i == 2) - codec = m_fallbackTextCodec; - - if (!file.open (codec)) { - // create one dummy textline, in any case - m_blocks.last()->appendLine (TextLine (new TextLineData())); - m_lines++; - return false; - } - - // read in all lines... - encodingErrors = false; - while ( !file.eof() ) - { - // read line - int offset = 0, length = 0; - bool currentError = !file.readLine (offset, length); - encodingErrors = encodingErrors || currentError; - - // bail out on encoding error, if not last round! - if (encodingErrors && i < 3) { - kDebug (13020) << "Failed try to load file" << filename << "with codec" << - (file.textCodec() ? file.textCodec()->name() : "(null)"); - break; - } - - // get unicode data for this line - const QChar *unicodeData = file.unicode () + offset; - - // construct new text line with content from file - TextLine textLine = TextLine (new TextLineData(QString (unicodeData, length))); - - // ensure blocks aren't too large - if (m_blocks.last()->lines() >= m_blockSize) - m_blocks.append (new TextBlock (this, m_blocks.last()->startLine() + m_blocks.last()->lines())); - - m_blocks.last()->appendLine (textLine); - m_lines++; - } - - // if no encoding error, break out of reading loop - if (!encodingErrors) { - // remember used codec - m_textCodec = file.textCodec (); - break; - } - } - - // remember if BOM was found - if (file.byteOrderMarkFound ()) - setGenerateByteOrderMark (true); - - // remember eol mode, if any found in file - if (file.eol() != eolUnknown) - setEndOfLineMode (file.eol()); - - // remember mime type for filter device - m_mimeTypeForFilterDev = file.mimeTypeForFilterDev (); - - // assert that one line is there! - Q_ASSERT (m_lines > 0); - - // report CODEC + ERRORS - kDebug (13020) << "Loaded file " << filename << "with codec" << m_textCodec->name() - << (encodingErrors ? "with" : "without") << "encoding errors"; - - // report BOM - kDebug (13020) << (file.byteOrderMarkFound () ? "Found" : "Didn't find") << "byte order mark"; - - // report filter device mime-type - kDebug (13020) << "used filter device for mime-type" << m_mimeTypeForFilterDev; - - // emit success - emit loaded (filename, encodingErrors); - - // file loading worked, modulo encoding problems - return true; -} - -bool TextBuffer::save (const QString &filename) -{ - // codec must be set! - Q_ASSERT (m_textCodec); - - /** - * construct correct filter device and try to open - */ - QIODevice *file = KFilterDev::deviceForFile (filename, m_mimeTypeForFilterDev, false); - if (!file->open (QIODevice::WriteOnly)) { - delete file; - return false; - } - - /** - * construct stream + disable Unicode headers - */ - QTextStream stream (file); - stream.setCodec (QTextCodec::codecForName("UTF-16")); - - // set the correct codec - stream.setCodec (m_textCodec); - - // generate byte order mark? - stream.setGenerateByteOrderMark (generateByteOrderMark()); - - // our loved eol string ;) - QString eol = "\n"; //m_doc->config()->eolString (); - if (endOfLineMode() == eolDos) - eol = QString ("\r\n"); - else if (endOfLineMode() == eolMac) - eol = QString ("\r"); - - // just dump the lines out ;) - for (int i = 0; i < m_lines; ++i) - { - // get line to save - Kate::TextLine textline = line (i); - - // strip trailing spaces - if (m_removeTrailingSpaces) - { - int lastChar = textline->lastChar(); - if (lastChar > -1) - { - stream << textline->text().left (lastChar+1); - } - } - else // simple, dump the line - stream << textline->text(); - - // append correct end of line string - if ((i+1) < m_lines) - stream << eol; - } - - // flush stream - stream.flush (); - - // close and delete file - file->close (); - delete file; - -#ifndef Q_OS_WIN - // ensure that the file is written to disk - // we crete new qfile, as the above might be wrapper around compression - QFile syncFile (filename); - syncFile.open (QIODevice::ReadOnly); - -#ifdef HAVE_FDATASYNC - fdatasync (syncFile.handle()); -#else - fsync (syncFile.handle()); -#endif -#endif - - // did save work? - bool ok = stream.status() == QTextStream::Ok; - - // remember this revision as last saved if we had success! - if (ok) - m_history.setLastSavedRevision (); - - // report CODEC + ERRORS - kDebug (13020) << "Saved file " << filename << "with codec" << m_textCodec->name() - << (ok ? "without" : "with") << "errors"; - - // emit signal on success - if (ok) - emit saved (filename); - - // return success or not - return ok; -} - -void TextBuffer::notifyAboutRangeChange (KTextEditor::View *view, int startLine, int endLine, bool rangeWithAttribute) -{ - /** - * ignore calls if no document is around - */ - if (!m_document) - return; - - /** - * update all views, this IS ugly and could be a signal, but I profiled and a signal is TOO slow, really - * just create 20k ranges in a go and you wait seconds on a decent machine - */ - const QList &views = m_document->views (); - foreach(KTextEditor::View* curView, views) { - // filter wrong views - if (view && view != curView) - continue; - - // notify view, it is really a kate view - static_cast (curView)->notifyAboutRangeChange (startLine, endLine, rangeWithAttribute); - } -} - -QList TextBuffer::rangesForLine (int line, KTextEditor::View *view, bool rangesWithAttributeOnly) const -{ - // get block, this will assert on invalid line - const int blockIndex = blockForLine (line); - - // get the ranges of the right block - QList rightRanges; - foreach (const QSet &ranges, m_blocks.at(blockIndex)->rangesForLine (line)) { - foreach (TextRange * const range, ranges) { - /** - * we want only ranges with attributes, but this one has none - */ - if (rangesWithAttributeOnly && !range->hasAttribute()) - continue; - - /** - * we want ranges for no view, but this one's attribute is only valid for views - */ - if (!view && range->attributeOnlyForViews()) - continue; - - /** - * the range's attribute is not valid for this view - */ - if (range->view() && range->view() != view) - continue; - - /** - * if line is in the range, ok - */ - if (range->startInternal().lineInternal() <= line && line <= range->endInternal().lineInternal()) - rightRanges.append (range); - } - } - - // return right ranges - return rightRanges; -} - -} diff --git a/part/buffer/katetextbuffer.h b/part/buffer/katetextbuffer.h deleted file mode 100644 index 4254973..0000000 --- a/part/buffer/katetextbuffer.h +++ /dev/null @@ -1,538 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTBUFFER_H -#define KATE_TEXTBUFFER_H - -#include -#include -#include -#include -#include - -#include - -#include "katepartprivate_export.h" -#include "katetextblock.h" -#include "katetextcursor.h" -#include "katetextrange.h" -#include "katetexthistory.h" - -// encoding prober -#include - -namespace Kate { - -/** - * Class representing a text buffer. - * The interface is line based, internally the text will be stored in blocks of text lines. - */ -class KATEPART_TESTS_EXPORT TextBuffer : public QObject { - friend class TextCursor; - friend class TextRange; - - Q_OBJECT - - public: - /** - * End of line mode - */ - enum EndOfLineMode { - eolUnknown = -1 - , eolUnix = 0 - , eolDos = 1 - , eolMac = 2 - }; - - /** - * Construct an empty text buffer. - * Empty means one empty line in one block. - * @param parent parent qobject - * @param blockSize block size in lines the buffer should try to hold, default 64 lines - */ - TextBuffer (KTextEditor::Document *parent = 0, int blockSize = 64); - - /** - * Destruct the text buffer - * Virtual, we allow inheritance - */ - virtual ~TextBuffer (); - - /** - * Clears the buffer, reverts to initial empty state. - * Empty means one empty line in one block. - * Virtual, can be overwritten. - */ - virtual void clear (); - - /** - * Set encoding prober type for this buffer to use for load. - * @param proberType prober type to use for encoding - */ - void setEncodingProberType (KEncodingProber::ProberType proberType) { m_encodingProberType = proberType; } - - /** - * Get encoding prober type for this buffer - * @return currently in use prober type of this buffer - */ - KEncodingProber::ProberType encodingProberType () const { return m_encodingProberType; } - - /** - * Set fallback codec for this buffer to use for load. - * @param codec fallback QTextCodec to use for encoding - */ - void setFallbackTextCodec (QTextCodec *codec) { m_fallbackTextCodec = codec; } - - /** - * Get fallback codec for this buffer - * @return currently in use fallback codec of this buffer - */ - QTextCodec *fallbackTextCodec () const { return m_fallbackTextCodec; } - - /** - * Set codec for this buffer to use for load/save. - * Loading might overwrite this, if it encounters problems and finds a better codec. - * @param codec QTextCodec to use for encoding - */ - void setTextCodec (QTextCodec *codec) { m_textCodec = codec; } - - /** - * Get codec for this buffer - * @return currently in use codec of this buffer - */ - QTextCodec *textCodec () const { return m_textCodec; } - - /** - * Generate byte order mark on save. - * Loading might overwrite this setting, if there is a BOM found inside the file. - * @param generateByteOrderMark should BOM be generated? - */ - void setGenerateByteOrderMark (bool generateByteOrderMark) { m_generateByteOrderMark = generateByteOrderMark; } - - /** - * Generate byte order mark on save? - * @return should BOM be generated? - */ - bool generateByteOrderMark () const { return m_generateByteOrderMark; } - - /** - * Set end of line mode for this buffer, not allowed to be set to unknown. - * Loading might overwrite this setting, if there is a eol found inside the file. - * @param endOfLineMode new eol mode - */ - void setEndOfLineMode (EndOfLineMode endOfLineMode) { Q_ASSERT (endOfLineMode != eolUnknown); m_endOfLineMode = endOfLineMode; } - - /** - * Get end of line mode - * @return end of line mode - */ - EndOfLineMode endOfLineMode () const { return m_endOfLineMode; } - - /** - * Specify if the buffer should remove trailing spaces while loading/saving files. - * @param removeTrailingSpaces should trailing spaces be removed on load/save? - */ - void setRemoveTrailingSpaces (bool removeTrailingSpaces) { m_removeTrailingSpaces = removeTrailingSpaces; } - - /** - * Should trailing spaces be removed on load/save. - * @return should trailing spaces be removed on load/save? - */ - bool removeTrailingSpaces () const { return m_removeTrailingSpaces; } - - /** - * Load the given file. This will first clear the buffer and then load the file. - * Even on error during loading the buffer will still be cleared. - * Before calling this, setTextCodec must have been used to set codec! - * @param filename file to open - * @param encodingErrors were there problems occured while decoding the file? - * @return success, the file got loaded, perhaps with encoding errors - * Virtual, can be overwritten. - */ - virtual bool load (const QString &filename, bool &encodingErrors); - - /** - * Save the current buffer content to the given file. - * Before calling this, setTextCodec and setFallbackTextCodec must have been used to set codec! - * @param filename file to save - * @return success - * Virtual, can be overwritten. - */ - virtual bool save (const QString &filename); - - /** - * Lines currently stored in this buffer. - * This is never 0, even clear will let one empty line remain. - */ - int lines () const { Q_ASSERT (m_lines > 0); return m_lines; } - - /** - * Revision of this buffer. Is set to 0 on construction, clear() (load will trigger clear()). - * Is incremented on each change to the buffer. - * @return current revision - */ - qint64 revision () const { return m_revision; } - - /** - * Retrieve a text line. - * @param line wanted line number - * @return text line - */ - TextLine line (int line) const; - - /** - * Retrieve text of complete buffer. - * @return text for this buffer, lines separated by '\n' - */ - QString text () const; - - /** - * Start an editing transaction, the wrapLine/unwrapLine/insertText and removeText functions - * are only to be allowed to be called inside a editing transaction. - * Editing transactions can stack. The number startEdit and endEdit calls must match. - * @return returns true, if no transaction was already running - * Virtual, can be overwritten. - */ - virtual bool startEditing (); - - /** - * Finish an editing transaction. Only allowed to be called if editing transaction is started. - * @return returns true, if this finished last running transaction - * Virtual, can be overwritten. - */ - virtual bool finishEditing (); - - /** - * Query the number of editing transactions running atm. - * @return number of running transactions - */ - int editingTransactions () const { return m_editingTransactions; } - - /** - * Query the revsion of this buffer before the ongoing editing transactions. - * @return revision of buffer before current editing transaction altered it - */ - qint64 editingLastRevision () const { return m_editingLastRevision; } - - /** - * Query the number of lines of this buffer before the ongoing editing transactions. - * @return number of lines of buffer before current editing transaction altered it - */ - int editingLastLines () const { return m_editingLastLines; } - - /** - * Query information from the last editing transaction: was the content of the buffer changed? - * This is checked by comparing the editingLastRevision() with the current revision(). - * @return content of buffer was changed in last transaction? - */ - bool editingChangedBuffer () const { return editingLastRevision() != revision(); } - - /** - * Query information from the last editing transaction: was the number of lines of the buffer changed? - * This is checked by comparing the editingLastLines() with the current lines(). - * @return content of buffer was changed in last transaction? - */ - bool editingChangedNumberOfLines () const { return editingLastLines() != lines(); } - - /** - * Get minimal line number changed by last editing transaction - * @return maximal line number changed by last editing transaction, or -1, if none changed - */ - int editingMinimalLineChanged () const { return m_editingMinimalLineChanged; } - - /** - * Get maximal line number changed by last editing transaction - * @return maximal line number changed by last editing transaction, or -1, if none changed - */ - int editingMaximalLineChanged () const { return m_editingMaximalLineChanged; } - - /** - * Wrap line at given cursor position. - * @param position line/column as cursor where to wrap - * Virtual, can be overwritten. - */ - virtual void wrapLine (const KTextEditor::Cursor &position); - - /** - * Unwrap given line. - * @param line line to unwrap - * Virtual, can be overwritten. - */ - virtual void unwrapLine (int line); - - /** - * Insert text at given cursor position. Does nothing if text is empty, beside some consistency checks. - * @param position position where to insert text - * @param text text to insert - * Virtual, can be overwritten. - */ - virtual void insertText (const KTextEditor::Cursor &position, const QString &text); - - /** - * Remove text at given range. Does nothing if range is empty, beside some consistency checks. - * @param range range of text to remove, must be on one line only. - * Virtual, can be overwritten. - */ - virtual void removeText (const KTextEditor::Range &range); - - /** - * TextHistory of this buffer - * @return text history for this buffer - */ - TextHistory &history () { return m_history; } - - Q_SIGNALS: - /** - * Buffer got cleared. This is emited when constructor or load have called clear() internally, - * or when the user of the buffer has called clear() itself. - */ - void cleared (); - - /** - * Buffer loaded successfully a file - * @param filename file which was loaded - * @param encodingErrors were there problems occured while decoding the file? - */ - void loaded (const QString &filename, bool encodingErrors); - - /** - * Buffer saved successfully a file - * @param filename file which was saved - */ - void saved (const QString &filename); - - /** - * Editing transaction has started. - */ - void editingStarted (); - - /** - * Editing transaction has finished. - */ - void editingFinished (); - - /** - * A line got wrapped. - * @param position position where the wrap occured - */ - void lineWrapped (const KTextEditor::Cursor &position); - - /** - * A line got unwrapped. - * @param line line where the unwrap occured - */ - void lineUnwrapped (int line); - - /** - * Text got inserted. - * @param position position where the insertion occured - * @param text inserted text - */ - void textInserted (const KTextEditor::Cursor &position, const QString &text); - - /** - * Text got removed. - * @param range range where the removal occured - * @param text removed text - */ - void textRemoved (const KTextEditor::Range &range, const QString &text); - - private: - /** - * Find block containing given line. - * @param line we want to find block for this line - * @return index of found block - */ - int blockForLine (int line) const; - - /** - * Fix start lines of all blocks after the given one - * @param startBlock index of block from which we start to fix - */ - void fixStartLines (int startBlock); - - /** - * Balance the given block. Look if it is too small or too large. - * @param index block to balance - */ - void balanceBlock (int index); - - /** - * Block for given index in block list. - * @param index block index - * @return block matching this index - */ - TextBlock *blockForIndex (int index) { return m_blocks[index]; } - - /** - * A range changed, notify the views, in case of attributes or feedback. - * @param view which view is affected? 0 for all views - * @param startLine start line of change - * @param endLine end line of change - * @param rangeWithAttribute attribute changed or is active, this will perhaps lead to repaints - */ - void notifyAboutRangeChange (KTextEditor::View *view, int startLine, int endLine, bool rangeWithAttribute); - - public: - /** - * Gets the document to which this buffer is bound. - * \return a pointer to the document - */ - KTextEditor::Document *document () const { return m_document; } - - /** - * Debug output, print whole buffer content with line numbers and line length - * @param title title for this output - */ - void debugPrint (const QString &title) const; - - /** - * Return the ranges which affect the given line. - * @param line line to look at - * @param view only return ranges associated with given view - * @param rangesWithAttributeOnly only return ranges which have a attribute set - * @return list of ranges affecting this line - */ - QList rangesForLine (int line, KTextEditor::View *view, bool rangesWithAttributeOnly) const; - - /** - * Check if the given range pointer is still valid. - * @return range pointer still belongs to range for this buffer - */ - bool rangePointerValid (TextRange *range) const { return m_ranges.contains (range); } - - /** - * Invalidate all ranges in this buffer. - */ - void invalidateRanges(); - - private: - /** - * parent document - */ - KTextEditor::Document *m_document; - - /** - * text history - */ - TextHistory m_history; - - /** - * block size in lines the buffer will try to hold - */ - const int m_blockSize; - - /** - * List of blocks which contain the lines of this buffer - */ - QVector m_blocks; - - /** - * Number of lines in buffer - */ - int m_lines; - - /** - * Last used block in the buffer. Is used for speeding up blockForLine. - * May contain invalid index, must be checked before using. - */ - mutable int m_lastUsedBlock; - - /** - * Revision of the buffer. - */ - qint64 m_revision; - - /** - * Current number of running edit transactions - */ - int m_editingTransactions; - - /** - * Revision remembered at start of current editing transaction - */ - qint64 m_editingLastRevision; - - /** - * Number of lines remembered at start of current editing transaction - */ - int m_editingLastLines; - - /** - * minimal line number changed by last editing transaction - */ - int m_editingMinimalLineChanged; - - /** - * maximal line number changed by last editing transaction - */ - int m_editingMaximalLineChanged; - - /** - * Set of invalid cursors for this whole buffer. - * Valid cursors are inside the block the belong to. - */ - QSet m_invalidCursors; - - /** - * Set of ranges of this whole buffer. - */ - QSet m_ranges; - - /** - * Encoding prober type to use - */ - KEncodingProber::ProberType m_encodingProberType; - - /** - * Fallback text codec to use - */ - QTextCodec *m_fallbackTextCodec; - - /** - * Text codec to use - */ - QTextCodec *m_textCodec; - - /** - * Mime-Type used for transparent compression/decompression support - * Set by load(), reset by clear() - */ - QString m_mimeTypeForFilterDev; - - /** - * Should byte order mark be created? - */ - bool m_generateByteOrderMark; - - /** - * End of line mode, default is Unix - */ - EndOfLineMode m_endOfLineMode; - - /** - * Should trailing spaces be removed on load/save. - */ - bool m_removeTrailingSpaces; -}; - -} - -#endif diff --git a/part/buffer/katetextcursor.cpp b/part/buffer/katetextcursor.cpp deleted file mode 100644 index a69a379..0000000 --- a/part/buffer/katetextcursor.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * Based on code of the SmartCursor/Range by: - * Copyright (C) 2003-2005 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextcursor.h" -#include "katetextbuffer.h" - -namespace Kate { - -TextCursor::TextCursor (TextBuffer &buffer, const KTextEditor::Cursor &position, InsertBehavior insertBehavior) - : m_buffer (buffer) - , m_range (0) - , m_block (0) - , m_line (-1) - , m_column (-1) - , m_moveOnInsert (insertBehavior == MoveOnInsert) -{ - // init position - setPosition (position, true); -} - -TextCursor::TextCursor (TextBuffer &buffer, TextRange *range, const KTextEditor::Cursor &position, InsertBehavior insertBehavior) - : m_buffer (buffer) - , m_range (range) - , m_block (0) - , m_line (-1) - , m_column (-1) - , m_moveOnInsert (insertBehavior == MoveOnInsert) -{ - // init position - setPosition (position, true); -} - -TextCursor::~TextCursor () -{ - // remove cursor from block or buffer - if (m_block) - m_block->m_cursors.remove (this); - - // only cursors without range are here! - else if (!m_range) - m_buffer.m_invalidCursors.remove (this); -} - -void TextCursor::setPosition( const TextCursor& position ) -{ - if (m_block && m_block != position.m_block) - m_block->m_cursors.remove(this); - - m_line = position.m_line; - m_column = position.m_column; - - m_block = position.m_block; - if (m_block) - m_block->m_cursors.insert(this); -} - -void TextCursor::setPosition(const KTextEditor::Cursor& position, bool init) -{ - // any change or init? else do nothing - if (!init && position.line() == line() && position.column() == m_column) - return; - - // remove cursor from old block in any case - if (m_block) - m_block->m_cursors.remove (this); - - // first: validate the line and column, else invalid - if (position.column() < 0 || position.line () < 0 || position.line () >= m_buffer.lines ()) { - if (!m_range) - m_buffer.m_invalidCursors.insert (this); - m_block = 0; - m_line = m_column = -1; - return; - } - - // else, find block - TextBlock *block = m_buffer.blockForIndex (m_buffer.blockForLine (position.line())); - - // get line - TextLine textLine = block->line (position.line()); - -#if 0 // this is no good idea, smart cursors don't do that, too, for non-wrapping cursors - // now, validate column, else stay invalid - if (position.column() > textLine->text().size()) { - if (!m_range) - m_buffer.m_invalidCursors.insert (this); - m_block = 0; - m_line = m_column = -1; - return; - } -#endif - - // else: valid cursor - m_block = block; - m_line = position.line () - m_block->startLine (); - m_column = position.column (); - m_block->m_cursors.insert (this); -} - -void TextCursor::setPosition(const KTextEditor::Cursor& position) -{ - setPosition(position, false); -} - -int TextCursor::line() const -{ - // invalid cursor have no block - if (!m_block) - return -1; - - // else, calculate real line - return m_block->startLine () + m_line; -} - -KTextEditor::Document *Kate::TextCursor::document () const -{ - return m_buffer.document(); -} - -KTextEditor::MovingRange *Kate::TextCursor::range () const -{ - return m_range; -} - -} diff --git a/part/buffer/katetextcursor.h b/part/buffer/katetextcursor.h deleted file mode 100644 index 168eec1..0000000 --- a/part/buffer/katetextcursor.h +++ /dev/null @@ -1,221 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * Based on code of the SmartCursor/Range by: - * Copyright (C) 2003-2005 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTCURSOR_H -#define KATE_TEXTCURSOR_H - -#include - -#include "katepartprivate_export.h" -#include "katetextblock.h" - -namespace Kate { - -class TextBuffer; -class TextBlock; -class TextRange; - -/** - * Class representing a 'clever' text cursor. - * It will automagically move if the text inside the buffer it belongs to is modified. - * By intention no subclass of KTextEditor::Cursor, must be converted manually. - */ -class KATEPART_TESTS_EXPORT TextCursor : public KTextEditor::MovingCursor { - // range wants direct access to some internals - friend class TextRange; - - // this is a friend, because this is needed to efficiently transfer cursors from on to an other block - friend class TextBlock; - - private: - /** - * Construct a text cursor with given range as parent, private, used by TextRange constructor only. - * @param buffer text buffer this cursor belongs to - * @param range text range this cursor is part of - * @param position wanted cursor position, if not valid for given buffer, will lead to invalid cursor - * @param insertBehavior behavior of this cursor on insert of text at it's position - */ - TextCursor (TextBuffer &buffer, TextRange *range, const KTextEditor::Cursor &position, InsertBehavior insertBehavior); - - public: - /** - * Construct a text cursor. - * @param buffer text buffer this cursor belongs to - * @param position wanted cursor position, if not valid for given buffer, will lead to invalid cursor - * @param insertBehavior behavior of this cursor on insert of text at it's position - */ - TextCursor (TextBuffer &buffer, const KTextEditor::Cursor &position, InsertBehavior insertBehavior); - - /** - * Destruct the text cursor - */ - ~TextCursor (); - - /** - * Set insert behavior. - * @param insertBehavior new insert behavior - */ - void setInsertBehavior (InsertBehavior insertBehavior) { m_moveOnInsert = insertBehavior == MoveOnInsert; } - - /** - * Get current insert behavior. - * @return current insert behavior - */ - InsertBehavior insertBehavior () const { return m_moveOnInsert ? MoveOnInsert : StayOnInsert; } - - /** - * Gets the document to which this cursor is bound. - * \return a pointer to the document - */ - KTextEditor::Document *document () const; - - /** - * Fast way to set the current cursor position to \e position. - * - * \param position new cursor position - */ - void setPosition (const TextCursor& position); - - /** - * Set the current cursor position to \e position. - * - * \param position new cursor position - */ - void setPosition (const KTextEditor::Cursor& position); - - /** - * \overload - * - * Set the cursor position to \e line and \e column. - * - * \param line new cursor line - * \param column new cursor column - */ - void setPosition (int line, int column) { KTextEditor::MovingCursor::setPosition (line, column); } - - /** - * Retrieve the line on which this cursor is situated. - * \return line number, where 0 is the first line. - */ - int line() const; - - /** - * Non-virtual version of line(), which is faster. - * Inlined for fast access (especially in KateTextBuffer::rangesForLine - * \return line number, where 0 is the first line. - */ - int lineInternal() const - { - // invalid cursor have no block - if (!m_block) - return -1; - - // else, calculate real line - return m_block->startLine () + m_line; - } - - /** - * Retrieve the column on which this cursor is situated. - * \return column number, where 0 is the first column. - */ - int column() const { return m_column; } - - /** - * Non-virtual version of column(), which is faster. - * \return column number, where 0 is the first column. - * */ - int columnInternal() const { return m_column; } - - /** - * Get range this cursor belongs to, if any - * @return range this pointer is part of, else 0 - */ - KTextEditor::MovingRange *range () const; - - /** - * Get range this cursor belongs to, if any - * @return range this pointer is part of, else 0 - */ - Kate::TextRange *kateRange () const { return m_range; } - - /** - * Get block this cursor belongs to, if any - * @return block this pointer is part of, else 0 - */ - TextBlock *block () const { return m_block; } - - /** - * Get offset into block this cursor belongs to, if any - * @return offset into block this pointer is part of, else -1 - */ - int lineInBlock () const { if (m_block) return m_line; return -1; } - - private: - /** - * Set the current cursor position to \e position. - * Internal helper to allow the same code be used for constructor and - * setPosition. - * - * @param position new cursor position - * @param init is this the initial setup of the position in the constructor? - */ - void setPosition (const KTextEditor::Cursor& position, bool init); - - private: - /** - * parent text buffer - * is a reference, and no pointer, as this must always exist and can't change - */ - TextBuffer &m_buffer; - - /** - * range this cursor belongs to - * may be null, then no range owns this cursor - * can not change after initial assignment - */ - TextRange * const m_range; - - /** - * parent text block, valid cursors always belong to a block, else they are invalid. - */ - TextBlock *m_block; - - /** - * line, offset in block, or -1 - */ - int m_line; - - /** - * column - */ - int m_column; - - /** - * should this cursor move on insert - */ - bool m_moveOnInsert; -}; - -} - -#endif diff --git a/part/buffer/katetexthistory.cpp b/part/buffer/katetexthistory.cpp deleted file mode 100644 index 9665523..0000000 --- a/part/buffer/katetexthistory.cpp +++ /dev/null @@ -1,587 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetexthistory.h" -#include "katetextbuffer.h" - -namespace Kate { - -TextHistory::TextHistory (TextBuffer &buffer) - : m_buffer (buffer) - , m_lastSavedRevision (-1) - , m_firstHistoryEntryRevision (0) -{ - // just call clear to init - clear (); -} - -TextHistory::~TextHistory () -{ -} - -qint64 TextHistory::revision () const -{ - // just output last revisions of buffer - return m_buffer.revision (); -} - -void TextHistory::clear () -{ - // reset last saved revision - m_lastSavedRevision = -1; - - // remove all history entries and add no-change dummy for first revision - m_historyEntries.clear (); - m_historyEntries.push_back (Entry ()); - - // first entry will again belong to first revision - m_firstHistoryEntryRevision = 0; -} - -void TextHistory::setLastSavedRevision () -{ - // current revision was succesful saved - m_lastSavedRevision = revision (); -} - -void TextHistory::wrapLine (const KTextEditor::Cursor &position) -{ - // create and add new entry - Entry entry; - entry.type = Entry::WrapLine; - entry.line = position.line (); - entry.column = position.column (); - addEntry (entry); -} - -void TextHistory::unwrapLine (int line, int oldLineLength) -{ - // create and add new entry - Entry entry; - entry.type = Entry::UnwrapLine; - entry.line = line; - entry.column = 0; - entry.oldLineLength = oldLineLength; - addEntry (entry); -} - -void TextHistory::insertText (const KTextEditor::Cursor &position, int length, int oldLineLength) -{ - // create and add new entry - Entry entry; - entry.type = Entry::InsertText; - entry.line = position.line (); - entry.column = position.column (); - entry.length = length; - entry.oldLineLength = oldLineLength; - addEntry (entry); -} - -void TextHistory::removeText (const KTextEditor::Range &range, int oldLineLength) -{ - // create and add new entry - Entry entry; - entry.type = Entry::RemoveText; - entry.line = range.start().line (); - entry.column = range.start().column (); - entry.length = range.end().column() - range.start().column(); - entry.oldLineLength = oldLineLength; - addEntry (entry); -} - -void TextHistory::addEntry (const Entry &entry) -{ - /** - * history should never be empty - */ - Q_ASSERT (!m_historyEntries.empty ()); - - /** - * simple efficient check: if we only have one entry, and the entry is not referenced - * just replace it with the new one and adjust the revision - */ - if ((m_historyEntries.size () == 1) && !m_historyEntries.first().referenceCounter) { - /** - * remember new revision for first element, it is the revision we get after this change - */ - m_firstHistoryEntryRevision = revision () + 1; - - /** - * remember edit - */ - m_historyEntries.first() = entry; - - /** - * be done... - */ - return; - } - - /** - * ok, we have more than one entry or the entry is referenced, just add up new entries - */ - m_historyEntries.push_back (entry); -} - -void TextHistory::lockRevision (qint64 revision) -{ - /** - * some invariants must hold - */ - Q_ASSERT (!m_historyEntries.empty ()); - Q_ASSERT (revision >= m_firstHistoryEntryRevision); - Q_ASSERT (revision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - - /** - * increment revision reference counter - */ - Entry &entry = m_historyEntries[revision - m_firstHistoryEntryRevision]; - ++entry.referenceCounter; -} - -void TextHistory::unlockRevision (qint64 revision) -{ - /** - * some invariants must hold - */ - Q_ASSERT (!m_historyEntries.empty ()); - Q_ASSERT (revision >= m_firstHistoryEntryRevision); - Q_ASSERT (revision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - - /** - * decrement revision reference counter - */ - Entry &entry = m_historyEntries[revision - m_firstHistoryEntryRevision]; - Q_ASSERT (entry.referenceCounter); - --entry.referenceCounter; - - /** - * clean up no longer used revisions... - */ - if (!entry.referenceCounter) { - /** - * search for now unused stuff - */ - int unreferencedEdits = 0; - for (int i = 0; i + 1 < m_historyEntries.size(); ++i) { - if (m_historyEntries.at(i).referenceCounter) - break; - - // remember deleted count - ++unreferencedEdits; - } - - /** - * remove unrefed from the list now - */ - if (unreferencedEdits > 0) { - // remove stuff from history - m_historyEntries.erase (m_historyEntries.begin(), m_historyEntries.begin() + unreferencedEdits); - - // patch first entry revision - m_firstHistoryEntryRevision += unreferencedEdits; - } - } -} - -void TextHistory::Entry::transformCursor (int &cursorLine, int &cursorColumn, bool moveOnInsert) const -{ - /** - * simple stuff, sort out generic things - */ - - /** - * no change, if this change is in line behind cursor - */ - if (line > cursorLine) - return; - - /** - * handle all history types - */ - switch (type) { - /** - * Wrap a line - */ - case WrapLine: - /** - * we wrap this line - */ - if (cursorLine == line) { - /** - * skip cursors with too small column - */ - if (cursorColumn <= column) { - if (cursorColumn < column || !moveOnInsert) - return; - } - - /** - * adjust column - */ - cursorColumn = cursorColumn - column; - } - - /** - * always increment cursor line - */ - cursorLine += 1; - return; - - /** - * Unwrap a line - */ - case UnwrapLine: - /** - * we unwrap this line, adjust column - */ - if (cursorLine == line) - cursorColumn += oldLineLength; - - /** - * decrease cursor line - */ - cursorLine -= 1; - return; - - /** - * Insert text - */ - case InsertText: - /** - * only interesting, if same line - */ - if (cursorLine != line) - return; - - // skip cursors with too small column - if (cursorColumn <= column) - if (cursorColumn < column || !moveOnInsert) - return; - - // patch column of cursor - if (cursorColumn <= oldLineLength) - cursorColumn += length; - - // special handling if cursor behind the real line, e.g. non-wrapping cursor in block selection mode - else if (cursorColumn < oldLineLength + length) - cursorColumn = oldLineLength + length; - - return; - - /** - * Remove text - */ - case RemoveText: - /** - * only interesting, if same line - */ - if (cursorLine != line) - return; - - // skip cursors with too small column - if (cursorColumn <= column) - return; - - // patch column of cursor - if (cursorColumn <= column + length) - cursorColumn = column; - else - cursorColumn -= length; - - return; - - /** - * nothing - */ - default: - return; - } -} - -void TextHistory::Entry::reverseTransformCursor (int &cursorLine, int &cursorColumn, bool moveOnInsert) const -{ - /** - * handle all history types - */ - switch (type) { - /** - * Wrap a line - */ - case WrapLine: - /** - * ignore this line - */ - if (cursorLine <= line) - return; - - /** - * next line is unwrapped - */ - if (cursorLine == line + 1) { - /** - * adjust column - */ - cursorColumn = cursorColumn + column; - } - - /** - * always decrement cursor line - */ - cursorLine -= 1; - return; - - /** - * Unwrap a line - */ - case UnwrapLine: - /** - * ignore lines before unwrapped one - */ - if (cursorLine < line - 1) - return; - - /** - * we unwrap this line, try to adjust cursor column if needed - */ - if (cursorLine == line - 1) { - /** - * skip cursors with to small columns - */ - if (cursorColumn <= oldLineLength) { - if (cursorColumn < oldLineLength || !moveOnInsert) - return; - } - - cursorColumn -= oldLineLength; - } - - /** - * increase cursor line - */ - cursorLine += 1; - return; - - /** - * Insert text - */ - case InsertText: - /** - * only interesting, if same line - */ - if (cursorLine != line) - return; - - // skip cursors with too small column - if (cursorColumn <= column) - return; - - // patch column of cursor - if (cursorColumn - length < column) - cursorColumn = column; - else - cursorColumn -= length; - - return; - - /** - * Remove text - */ - case RemoveText: - /** - * only interesting, if same line - */ - if (cursorLine != line) - return; - - // skip cursors with too small column - if (cursorColumn <= column) - if (cursorColumn < column || !moveOnInsert) - return; - - // patch column of cursor - if (cursorColumn <= oldLineLength) - cursorColumn += length; - - // special handling if cursor behind the real line, e.g. non-wrapping cursor in block selection mode - else if (cursorColumn < oldLineLength + length) - cursorColumn = oldLineLength + length; - return; - - /** - * nothing - */ - default: - return; - } -} - -void TextHistory::transformCursor (int& line, int& column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision) -{ - /** - * -1 special meaning for from/toRevision - */ - if (fromRevision == -1) - fromRevision = revision (); - - if (toRevision == -1) - toRevision = revision (); - - /** - * shortcut, same revision - */ - if (fromRevision == toRevision) - return; - - /** - * some invariants must hold - */ - Q_ASSERT (!m_historyEntries.empty ()); - Q_ASSERT (fromRevision != toRevision); - Q_ASSERT (fromRevision >= m_firstHistoryEntryRevision); - Q_ASSERT (fromRevision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - Q_ASSERT (toRevision >= m_firstHistoryEntryRevision); - Q_ASSERT (toRevision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - - /** - * transform cursor - */ - bool moveOnInsert = insertBehavior == KTextEditor::MovingCursor::MoveOnInsert; - - /** - * forward or reverse transform? - */ - if (toRevision > fromRevision) { - for (int rev = fromRevision - m_firstHistoryEntryRevision + 1; rev <= (toRevision - m_firstHistoryEntryRevision); ++rev) { - const Entry &entry = m_historyEntries.at(rev); - entry.transformCursor (line, column, moveOnInsert); - } - } else { - for (int rev = fromRevision - m_firstHistoryEntryRevision; rev >= (toRevision - m_firstHistoryEntryRevision + 1); --rev) { - const Entry &entry = m_historyEntries.at(rev); - entry.reverseTransformCursor (line, column, moveOnInsert); - } - } -} - -void TextHistory::transformRange (KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision) -{ - /** - * invalidate on empty? - */ - bool invalidateIfEmpty = emptyBehavior == KTextEditor::MovingRange::InvalidateIfEmpty; - if (invalidateIfEmpty && range.end() <= range.start()) { - range = KTextEditor::Range::invalid(); - return; - } - - /** - * -1 special meaning for from/toRevision - */ - if (fromRevision == -1) - fromRevision = revision (); - - if (toRevision == -1) - toRevision = revision (); - - /** - * shortcut, same revision - */ - if (fromRevision == toRevision) - return; - - /** - * some invariants must hold - */ - Q_ASSERT (!m_historyEntries.empty ()); - Q_ASSERT (fromRevision != toRevision); - Q_ASSERT (fromRevision >= m_firstHistoryEntryRevision); - Q_ASSERT (fromRevision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - Q_ASSERT (toRevision >= m_firstHistoryEntryRevision); - Q_ASSERT (toRevision < (m_firstHistoryEntryRevision + m_historyEntries.size())); - - /** - * transform cursors - */ - - // first: copy cursors, without range association - int startLine = range.start().line(), startColumn = range.start().column(), endLine = range.end().line(), endColumn = range.end().column(); - - bool moveOnInsertStart = !(insertBehaviors & KTextEditor::MovingRange::ExpandLeft); - bool moveOnInsertEnd = (insertBehaviors & KTextEditor::MovingRange::ExpandRight); - - /** - * forward or reverse transform? - */ - if (toRevision > fromRevision) { - for (int rev = fromRevision - m_firstHistoryEntryRevision + 1; rev <= (toRevision - m_firstHistoryEntryRevision); ++rev) { - const Entry &entry = m_historyEntries.at(rev); - - entry.transformCursor (startLine, startColumn, moveOnInsertStart); - - entry.transformCursor (endLine, endColumn, moveOnInsertEnd); - - // got empty? - if(endLine < startLine || (endLine == startLine && endColumn <= startColumn)) - { - if (invalidateIfEmpty) { - range = KTextEditor::Range::invalid(); - return; - } - else{ - // else normalize them - endLine = startLine; - endColumn = startColumn; - } - } - } - } else { - for (int rev = fromRevision - m_firstHistoryEntryRevision ; rev >= (toRevision - m_firstHistoryEntryRevision + 1); --rev) { - const Entry &entry = m_historyEntries.at(rev); - - entry.reverseTransformCursor (startLine, startColumn, moveOnInsertStart); - - entry.reverseTransformCursor (endLine, endColumn, moveOnInsertEnd); - - // got empty? - if(endLine < startLine || (endLine == startLine && endColumn <= startColumn)) - { - if (invalidateIfEmpty) { - range = KTextEditor::Range::invalid(); - return; - } - else{ - // else normalize them - endLine = startLine; - endColumn = startColumn; - } - } - } - } - - // now, copy cursors back - range.start().setLine(startLine); - range.start().setColumn(startColumn); - range.end().setLine(endLine); - range.end().setColumn(endColumn); - -} - -} diff --git a/part/buffer/katetexthistory.h b/part/buffer/katetexthistory.h deleted file mode 100644 index 846c575..0000000 --- a/part/buffer/katetexthistory.h +++ /dev/null @@ -1,240 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTHISTORY_H -#define KATE_TEXTHISTORY_H - -#include - -#include - -#include "katepartprivate_export.h" -#include "katetextcursor.h" -#include "katetextrange.h" - -namespace Kate { - -class TextBuffer; - -/** - * Class representing the editing history of a TextBuffer - */ -class KATEPART_TESTS_EXPORT TextHistory { - friend class TextBuffer; - friend class TextBlock; - - public: - /** - * Current revision, just relay the revision of the buffer - * @return current revision - */ - qint64 revision () const; - - /** - * Last revision the buffer got successful saved - * @return last revision buffer got saved, -1 if none - */ - qint64 lastSavedRevision () const { return m_lastSavedRevision; } - - /** - * Lock a revision, this will keep it around until released again. - * But all revisions will always be cleared on buffer clear() (and therefor load()) - * @param revision revision to lock - */ - void lockRevision (qint64 revision); - - /** - * Release a revision. - * @param revision revision to release - */ - void unlockRevision (qint64 revision); - - /** - * Transform a cursor from one revision to an other. - * @param line line number of the cursor to transform - * @param column column number of the cursor to transform - * @param insertBehavior behavior of this cursor on insert of text at it's position - * @param fromRevision from this revision we want to transform - * @param toRevision to this revision we want to transform, default of -1 is current revision - */ - void transformCursor (int& line, int& column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1); - - /** - * Transform a range from one revision to an other. - * @param range range to transform - * @param insertBehaviors behavior of this range on insert of text at it's position - * @param emptyBehavior behavior on becoming empty - * @param fromRevision from this revision we want to transform - * @param toRevision to this revision we want to transform, default of -1 is current revision - */ - void transformRange (KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision = -1); - - private: - /** - * Class representing one entry in the editing history. - */ - class Entry { - public: - /** - * transform cursor for this history entry - * @param line line number of the cursor to transform - * @param column column number of the cursor to transform - * @param moveOnInsert behavior of this cursor on insert of text at it's position - */ - void transformCursor (int &line, int &column, bool moveOnInsert) const; - - /** - * reverse transform cursor for this history entry - * @param line line number of the cursor to transform - * @param column column number of the cursor to transform - * @param moveOnInsert behavior of this cursor on insert of text at it's position - */ - void reverseTransformCursor (int &line, int &column, bool moveOnInsert) const; - - /** - * Types of entries, matching editing primitives of buffer and placeholder - */ - enum Type { - NoChange - , WrapLine - , UnwrapLine - , InsertText - , RemoveText - }; - - /** - * Defaul Constructor, invalidates all fields - */ - Entry () - : referenceCounter (0), type (NoChange), line (-1), column (-1), length (-1), oldLineLength (-1) - { - } - - /** - * Reference counter, how often ist this entry referenced from the outside? - */ - unsigned int referenceCounter; - - /** - * Type of change - */ - Type type; - - /** - * line the change occured - */ - int line; - - /** - * column the change occured - */ - int column; - - /** - * length of change (length of insert or removed text) - */ - int length; - - /** - * old line length (needed for unwrap and insert) - */ - int oldLineLength; - }; - - /** - * Construct an empty text history. - * @param buffer buffer this text history belongs to - */ - TextHistory (TextBuffer &buffer); - - /** - * Destruct the text history - */ - ~TextHistory (); - - /** - * Clear the edit history, this is done on clear() in buffer. - */ - void clear (); - - /** - * Set current revision as last saved revision - */ - void setLastSavedRevision (); - - /** - * Notify about wrap line at given cursor position. - * @param position line/column as cursor where to wrap - */ - void wrapLine (const KTextEditor::Cursor &position); - - /** - * Notify about unwrap given line. - * @param line line to unwrap - * @param oldLineLength text length of the line in front of this one before this unwrap - */ - void unwrapLine (int line, int oldLineLength); - - /** - * Notify about insert text at given cursor position. - * @param position position where to insert text - * @param length text length to be inserted - * @param oldLineLength text length of the line before this insert - */ - void insertText (const KTextEditor::Cursor &position, int length, int oldLineLength); - - /** - * Notify about remove text at given range. - * @param range range of text to remove, must be on one line only. - * @param oldLineLength text length of the line before this remove - */ - void removeText (const KTextEditor::Range &range, int oldLineLength); - - /** - * Generic function to add a entry to the history. Is used by the above functions for the different editing primitives. - * @param entry new entry to add - */ - void addEntry (const Entry &entry); - - private: - /** - * TextBuffer this history belongs to - */ - TextBuffer &m_buffer; - - /** - * Last revision the buffer got saved - */ - qint64 m_lastSavedRevision; - - /** - * history of edits - */ - QList m_historyEntries; - - /** - * offset for the first entry in m_history, to which revision it really belongs? - */ - qint64 m_firstHistoryEntryRevision; -}; - -} - -#endif diff --git a/part/buffer/katetextline.cpp b/part/buffer/katetextline.cpp deleted file mode 100644 index 9d557c8..0000000 --- a/part/buffer/katetextline.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextline.h" - -namespace Kate { - -TextLineData::TextLineData () - : m_flags (0) -{ -} - -TextLineData::TextLineData (const QString &text) - : m_text (text) - , m_flags (0) -{ -} - -TextLineData::~TextLineData () -{ -} - -int TextLineData::firstChar() const -{ - return nextNonSpaceChar(0); -} - -int TextLineData::lastChar() const -{ - return previousNonSpaceChar(m_text.length() - 1); -} - -int TextLineData::nextNonSpaceChar (int pos) const -{ - Q_ASSERT (pos >= 0); - - for(int i = pos; i < m_text.length(); i++) - if (!m_text[i].isSpace()) - return i; - - return -1; -} - -int TextLineData::previousNonSpaceChar (int pos) const -{ - if (pos >= m_text.length()) - pos = m_text.length() - 1; - - for(int i = pos; i >= 0; i--) - if (!m_text[i].isSpace()) - return i; - - return -1; -} - -QString TextLineData::leadingWhitespace() const -{ - if (firstChar() < 0) - return string(0, length()); - - return string(0, firstChar()); -} - -int TextLineData::indentDepth (int tabWidth) const -{ - int d = 0; - const int len = m_text.length(); - const QChar *unicode = m_text.unicode(); - - for(int i = 0; i < len; ++i) - { - if(unicode[i].isSpace()) - { - if (unicode[i] == QLatin1Char('\t')) - d += tabWidth - (d % tabWidth); - else - d++; - } - else - return d; - } - - return d; -} - -bool TextLineData::matchesAt(int column, const QString& match) const -{ - if (column < 0) - return false; - - const int len = m_text.length(); - const int matchlen = match.length(); - - if ((column + matchlen) > len) - return false; - - const QChar *unicode = m_text.unicode(); - const QChar *matchUnicode = match.unicode(); - - for (int i=0; i < matchlen; ++i) - if (unicode[i+column] != matchUnicode[i]) - return false; - - return true; -} - -int TextLineData::toVirtualColumn (int column, int tabWidth) const -{ - if (column < 0) - return 0; - - int x = 0; - const int zmax = qMin(column, m_text.length()); - const QChar *unicode = m_text.unicode(); - - for ( int z = 0; z < zmax; ++z) - { - if (unicode[z] == QLatin1Char('\t')) - x += tabWidth - (x % tabWidth); - else - x++; - } - - return x + column - zmax; -} - -int TextLineData::fromVirtualColumn (int column, int tabWidth) const -{ - if (column < 0) - return 0; - - const int zmax = qMin(m_text.length(), column); - const QChar *unicode = m_text.unicode(); - - int x = 0; - int z = 0; - for (; z < zmax; ++z) - { - int diff = 1; - if (unicode[z] == QLatin1Char('\t')) - diff = tabWidth - (x % tabWidth); - - if (x + diff > column) - break; - x += diff; - } - - return z; -} - -int TextLineData::virtualLength (int tabWidth) const -{ - int x = 0; - const int len = m_text.length(); - const QChar *unicode = m_text.unicode(); - - for ( int z = 0; z < len; ++z) - { - if (unicode[z] == QLatin1Char('\t')) - x += tabWidth - (x % tabWidth); - else - x++; - } - - return x; -} - -void TextLineData::addAttribute (int start, int length, int attribute) -{ - // try to append to previous range - if ((m_attributesList.size() > 2) && (m_attributesList[m_attributesList.size()-1] == attribute) - && (m_attributesList[m_attributesList.size()-3]+m_attributesList[m_attributesList.size()-2] - == start)) - { - m_attributesList[m_attributesList.size()-2] += length; - return; - } - - m_attributesList.resize (m_attributesList.size()+3); - m_attributesList[m_attributesList.size()-3] = start; - m_attributesList[m_attributesList.size()-2] = length; - m_attributesList[m_attributesList.size()-1] = attribute; -} - -} diff --git a/part/buffer/katetextline.h b/part/buffer/katetextline.h deleted file mode 100644 index 30aa2e6..0000000 --- a/part/buffer/katetextline.h +++ /dev/null @@ -1,401 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTLINE_H -#define KATE_TEXTLINE_H - -#include -#include -#include - -#include "katepartprivate_export.h" - -namespace Kate { - -/** - * Class representing a single text line. - * For efficience reasons, not only pure text is stored here, but also additional data. - * Will be only accessed over shared pointers. - */ -class KATEPART_TESTS_EXPORT TextLineData { - /** - * TextBuffer/Block are friend classes, only ones allowed to touch the text content. - */ - friend class TextBuffer; - friend class TextBlock; - - public: - /** - * Flags of TextLineData - */ - enum Flags - { - flagHlContinue = 1, - flagAutoWrapped = 2, - flagFoldingColumnsOutdated = 4, - flagNoIndentationBasedFolding = 8, - flagNoIndentationBasedFoldingAtStart = 16 - }; - - /** - * Construct an empty text line. - */ - TextLineData (); - - /** - * Construct an text line with given text. - * @param text text to use for this line - */ - TextLineData (const QString &text); - - /** - * Destruct the text line - */ - ~TextLineData (); - - /** - * Accessor to the text contained in this line. - * @return text of this line as constant reference - */ - const QString &text () const { return m_text; } - - /** - * Returns the position of the first non-whitespace character - * @return position of first non-whitespace char or -1 if there is none - */ - int firstChar() const; - - /** - * Returns the position of the last non-whitespace character - * @return position of last non-whitespace char or -1 if there is none - */ - int lastChar() const; - - /** - * Find the position of the next char that is not a space. - * @param pos Column of the character which is examined first. - * @return True if the specified or a following character is not a space - * Otherwise false. - */ - int nextNonSpaceChar(int pos) const; - - /** - * Find the position of the previous char that is not a space. - * @param pos Column of the character which is examined first. - * @return The position of the first non-whitespace character preceding pos, - * or -1 if none is found. - */ - int previousNonSpaceChar(int pos) const; - - /** - * Returns the character at the given \e column. If \e column is out of - * range, the return value is QChar(). - * @param column column you want char for - * @return char at given column or QChar() - */ - inline QChar at (int column) const - { - if (column >= 0 && column < m_text.length()) - return m_text[column]; - - return QChar(); - } - - /** - * Same as at(). - * @param column column you want char for - * @return char at given column or QChar() - */ - inline QChar operator[](int column) const - { - if (column >= 0 && column < m_text.length()) - return m_text[column]; - - return QChar(); - } - - /** - * Set the flag that only positions have changed, not folding region begins/ends themselve - * @param set folding columns our of date? - */ - void setFoldingColumnsOutdated(bool set) - { - if (set) m_flags |= flagFoldingColumnsOutdated; - else m_flags &= (~flagFoldingColumnsOutdated); - } - - /** - * Returns \e true, if the folding columns are outdated, otherwise returns \e false. - * @return folding columns our of date? - */ - bool foldingColumnsOutdated() const { return m_flags & flagFoldingColumnsOutdated; } - - /** - * Returns the line's length. - */ - int length() const { return m_text.length(); } - - /** - * Returns \e true, if the line's hl-continue flag is set, otherwise returns - * \e false. The hl-continue flag is set in the hl-definition files. - * @return hl-continue flag is set - */ - bool hlLineContinue () const { return m_flags & flagHlContinue; } - - /** - * Returns \e true, if the line was automagically wrapped, otherwise returns - * \e false. - * @return was this line auto-wrapped? - */ - bool isAutoWrapped () const { return m_flags & flagAutoWrapped; } - - /** - * Returns the complete text line (as a QString reference). - * @return text of this line, read-only - */ - const QString& string() const { return m_text; } - - /** - * Returns the substring with \e length beginning at the given \e column. - * @param column start column of text to return - * @param length length of text to return - * @return wanted part of text - */ - QString string (int column, int length) const - { return m_text.mid(column, length); } - - /** - * Leading whitespace of this line - * @return leading whitespace of this line - */ - QString leadingWhitespace() const; - - /** - * Returns the indentation depth with each tab expanded into \e tabWidth characters. - */ - int indentDepth (int tabWidth) const; - - /** - * Returns the \e column with each tab expanded into \e tabWidth characters. - */ - int toVirtualColumn (int column, int tabWidth) const; - - /** - * Returns the "real" column where each tab only counts one character. - * The conversion calculates with \e tabWidth characters for each tab. - */ - int fromVirtualColumn (int column, int tabWidth) const; - - /** - * Returns the text length with each tab expanded into \e tabWidth characters. - */ - int virtualLength (int tabWidth) const; - - /** - * Returns \e true, if \e match equals to the text at position \e column, - * otherwise returns \e false. - */ - bool matchesAt(int column, const QString& match) const; - - /** - * Returns \e true, if the line starts with \e match, otherwise returns \e false. - */ - bool startsWith(const QString& match) const { return m_text.startsWith (match); } - - /** - * Returns \e true, if the line ends with \e match, otherwise returns \e false. - */ - bool endsWith(const QString& match) const { return m_text.endsWith (match); } - - /** - * Gets the attribute at the given position - * use KRenderer::attributes to get the KTextAttribute for this. - * - * @param pos position of attribute requested - * @return value of attribute - */ - int attribute (int pos) const - { - for (int i=0; i < m_attributesList.size(); i+=3) - { - if (pos >= m_attributesList[i] && pos < m_attributesList[i]+m_attributesList[i+1]) - return m_attributesList[i+2]; - - if (pos < m_attributesList[i]) - break; - } - - return 0; - } - - /** - * context stack - * @return context stack - */ - const QVector &contextStack () const { return m_ctx; } - - /** - * @return true if any context at the line end has the noIndentBasedFolding flag set - */ - bool noIndentBasedFolding() const { return m_flags & flagNoIndentationBasedFolding; } - - /** - * @return true if any context at the line end has the noIndentationBasedFoldingAtStart flag set - */ - bool noIndentBasedFoldingAtStart() const { return m_flags & flagNoIndentationBasedFoldingAtStart; } - - /** - * folding list - * @return folding array - */ - const QVector &foldingListArray () const { return m_foldingList; } - - /** - * indentation stack - * @return indentation array - */ - const QVector &indentationDepthArray () const { return m_indentationDepth; } - - /** - * Add attribute for given start + length to this line - * @param start start column of this attribute - * @param length length in chars this attribute should span - * @param attribute attribute to use - */ - void addAttribute (int start, int length, int attribute); - - /** - * Clear attributes of this line - */ - void clearAttributes () { m_attributesList.clear (); } - - /** - * Accessor to attributes - * @return attributes of this line - */ - const QVector &attributesList () const { return m_attributesList; } - - /** - * set hl continue flag - * @param cont continue flag? - */ - void setHlLineContinue (bool cont) - { - if (cont) m_flags = m_flags | flagHlContinue; - else m_flags = m_flags & ~ flagHlContinue; - } - - /** - * set auto-wrapped property - * @param wrapped line was wrapped? - */ - void setAutoWrapped (bool wrapped) - { - if (wrapped) m_flags = m_flags | flagAutoWrapped; - else m_flags = m_flags & ~ flagAutoWrapped; - } - - /** - * Sets the syntax highlight context number - * @param val new context array - */ - void setContextStack (QVector &val) { m_ctx = val; } - - /** - * sets if for the next line indent based folding should be disabled - * @param val should indent folding be disabled - */ - void setNoIndentBasedFolding(bool val) - { - if (val) m_flags = m_flags | flagNoIndentationBasedFolding; - else m_flags = m_flags & ~ flagNoIndentationBasedFolding; - } - - /** - * sets if indent based folding should be disabled at start - * @param val should indent based folding be disabled at start - */ - void setNoIndentBasedFoldingAtStart(bool val) - { - if (val) m_flags = m_flags | flagNoIndentationBasedFoldingAtStart; - else m_flags = m_flags & ~ flagNoIndentationBasedFoldingAtStart; - } - - /** - * update folding list - * @param val new folding list - */ - void setFoldingList (QVector &val) { m_foldingList = val; } - - /** - * update indentation stack - * @param val new indentation stack - */ - void setIndentationDepth (QVector &val) { m_indentationDepth = val; } - - private: - /** - * Accessor to the text contained in this line. - * This accessor is private, only the friend class text buffer/block is allowed to access the text read/write. - * @return text of this line - */ - QString &textReadWrite () { return m_text; } - - private: - /** - * text of this line - */ - QString m_text; - - /** - * store the attribs, int array - * one int start, next one len, next one attrib - */ - QVector m_attributesList; - - /** - * context stack - */ - QVector m_ctx; - - /** - * list of folding starts/ends - */ - QVector m_foldingList; - - /** - * indentation stack - */ - QVector m_indentationDepth; - - /** - * flags - */ - uchar m_flags; -}; - -/** - * The normal world only accesses the text lines with shared pointers. - */ -typedef QSharedPointer TextLine; - -} - -#endif diff --git a/part/buffer/katetextloader.h b/part/buffer/katetextloader.h deleted file mode 100644 index 82d264b..0000000 --- a/part/buffer/katetextloader.h +++ /dev/null @@ -1,355 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTLOADER_H -#define KATE_TEXTLOADER_H - -#include -#include - -// on the fly compression -#include -#include - -namespace Kate { - -/** - * loader block size, load 256 kb at once per default - * if file size is smaller, fall back to file size - * must be a multiple of 2 - */ -static const qint64 KATE_FILE_LOADER_BS = 256 * 1024; - -/** - * File Loader, will handle reading of files + detecting encoding - */ -class TextLoader -{ - public: - /** - * Construct file loader for given file. - * @param filename file to open - * @param proberType prober type - */ - TextLoader (const QString &filename, KEncodingProber::ProberType proberType) - : m_codec (0) - , m_eof (false) // default to not eof - , m_lastWasEndOfLine (true) // at start of file, we had a virtual newline - , m_lastWasR (false) // we have not found a \r as last char - , m_position (0) - , m_lastLineStart (0) - , m_eol (TextBuffer::eolUnknown) // no eol type detected atm - , m_buffer (KATE_FILE_LOADER_BS, 0) - , m_converterState (0) - , m_bomFound (false) - , m_firstRead (true) - , m_proberType (proberType) - { - // try to get mimetype for on the fly decompression, don't rely on filename! - QFile testMime (filename); - if (testMime.open (QIODevice::ReadOnly)) - m_mimeType = KMimeType::findByContent (&testMime)->name (); - else - m_mimeType = KMimeType::findByPath (filename, 0, false)->name (); - - // construct filter device - m_file = KFilterDev::deviceForFile (filename, m_mimeType, false); - } - - /** - * Destructor - */ - ~TextLoader () - { - delete m_file; - delete m_converterState; - } - - /** - * open file with given codec - * @param codec codec to use, if 0, will do some auto-dectect or fallback - * @return success - */ - bool open (QTextCodec *codec) - { - m_codec = codec; - m_eof = false; - m_lastWasEndOfLine = true; - m_lastWasR = false; - m_position = 0; - m_lastLineStart = 0; - m_eol = TextBuffer::eolUnknown; - m_text.clear (); - delete m_converterState; - m_converterState = new QTextCodec::ConverterState (QTextCodec::ConvertInvalidToNull); - m_bomFound = false; - m_firstRead = true; - - // if already opened, close the file... - if (m_file->isOpen()) - m_file->close (); - - return m_file->open (QIODevice::ReadOnly); - } - - /** - * end of file reached? - * @return end of file reached - */ - bool eof () const { return m_eof && !m_lastWasEndOfLine && (m_lastLineStart == m_text.length()); } - - /** - * Detected end of line mode for this file. - * Detected during reading, is valid after complete file is read. - * @return eol mode of this file - */ - TextBuffer::EndOfLineMode eol () const { return m_eol; } - - /** - * BOM found? - * @return byte order mark found? - */ - bool byteOrderMarkFound () const { return m_bomFound; } - - /** - * mime type used to create filter dev - * @return mime-type of filter device - */ - const QString &mimeTypeForFilterDev () const { return m_mimeType; } - - /** - * internal unicode data array - * @return internal unicode data - */ - const QChar *unicode () const { return m_text.unicode(); } - - /** - * Get codec for this loader - * @return currently in use codec of this loader - */ - QTextCodec *textCodec () const { return m_codec; } - - /** - * read a line, return length + offset in unicode data - * @param offset offset into internal unicode data for read line - * @param length lenght of read line - * @return true if no encoding errors occured - */ - bool readLine (int &offset, int &length) - { - length = 0; - offset = 0; - bool encodingError = false; - - static const QLatin1Char cr(QLatin1Char('\r')); - static const QLatin1Char lf(QLatin1Char('\n')); - - while (m_position <= m_text.length()) - { - if (m_position == m_text.length()) - { - // try to load more text if something is around - if (!m_eof) - { - int c = m_file->read (m_buffer.data(), m_buffer.size()); - - // kill the old lines... - m_text.remove (0, m_lastLineStart); - - // if any text is there, append it.... - if (c > 0) - { - // detect byte order marks & codec for byte order markers on first read - int bomBytes = 0; - if (m_firstRead) { - // use first 16 bytes max to allow BOM detection of codec - QByteArray bom (m_buffer.data(), qMin (16, c)); - QTextCodec *codecForByteOrderMark = QTextCodec::codecForUtfText (bom, 0); - - // if codec != null, we found a BOM! - if (codecForByteOrderMark) { - m_bomFound = true; - - // eat away the different boms! - int mib = codecForByteOrderMark->mibEnum (); - if (mib == 106) // utf8 - bomBytes = 3; - if (mib == 1013 || mib == 1014) // utf16 - bomBytes = 2; - if (mib == 1018 || mib == 1019) // utf32 - bomBytes = 4; - } - - /** - * if no codec given, do autodetection - */ - if (!m_codec) { - /** - * byte order said something about encoding? - */ - if (codecForByteOrderMark) - m_codec = codecForByteOrderMark; - else { - /** - * no unicode BOM found, trigger prober - */ - KEncodingProber prober (m_proberType); - prober.feed (m_buffer.constData(), c); - - // we found codec with some confidence? - if (prober.confidence() > 0.5) - m_codec = QTextCodec::codecForName(prober.encoding()); - - // no codec, no chance, encoding error - if (!m_codec) - return false; - } - } - - m_firstRead = false; - } - - Q_ASSERT (m_codec); - QString unicode = m_codec->toUnicode (m_buffer.constData() + bomBytes, c - bomBytes, m_converterState); - - // detect broken encoding - for (int i = 0; i < unicode.size(); ++i) { - if (unicode[i] == 0) { - encodingError = true; - break; - } - } - - m_text.append (unicode); - } - - // is file completely read ? - m_eof = (c == -1) || (c == 0); - - // recalc current pos and last pos - m_position -= m_lastLineStart; - m_lastLineStart = 0; - } - - // oh oh, end of file, escape ! - if (m_eof && (m_position == m_text.length())) - { - m_lastWasEndOfLine = false; - - // line data - offset = m_lastLineStart; - length = m_position-m_lastLineStart; - - m_lastLineStart = m_position; - - return !encodingError; - } - } - - if (m_text.at(m_position) == lf) - { - m_lastWasEndOfLine = true; - - if (m_lastWasR) - { - m_lastLineStart++; - m_lastWasR = false; - m_eol = TextBuffer::eolDos; - } - else - { - // line data - offset = m_lastLineStart; - length = m_position-m_lastLineStart; - - m_lastLineStart = m_position+1; - m_position++; - - // only win, if not dos! - if (m_eol != TextBuffer::eolDos) - m_eol = TextBuffer::eolUnix; - - return !encodingError; - } - } - else if (m_text.at(m_position) == cr) - { - m_lastWasEndOfLine = true; - m_lastWasR = true; - - // line data - offset = m_lastLineStart; - length = m_position-m_lastLineStart; - - m_lastLineStart = m_position+1; - m_position++; - - // should only win of first time! - if (m_eol == TextBuffer::eolUnknown) - m_eol = TextBuffer::eolMac; - - return !encodingError; - } - else if (m_text.at(m_position) == QChar::LineSeparator) - { - m_lastWasEndOfLine = true; - - // line data - offset = m_lastLineStart; - length = m_position-m_lastLineStart; - - m_lastLineStart = m_position+1; - m_position++; - - return !encodingError; - } - else - { - m_lastWasEndOfLine = false; - m_lastWasR = false; - } - - m_position++; - } - - return !encodingError; - } - - private: - QTextCodec *m_codec; - bool m_eof; - bool m_lastWasEndOfLine; - bool m_lastWasR; - int m_position; - int m_lastLineStart; - TextBuffer::EndOfLineMode m_eol; - QString m_mimeType; - QIODevice *m_file; - QByteArray m_buffer; - QString m_text; - QTextCodec::ConverterState *m_converterState; - bool m_bomFound; - bool m_firstRead; - KEncodingProber::ProberType m_proberType; -}; - -} - -#endif diff --git a/part/buffer/katetextrange.cpp b/part/buffer/katetextrange.cpp deleted file mode 100644 index 60d99c9..0000000 --- a/part/buffer/katetextrange.cpp +++ /dev/null @@ -1,331 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * Based on code of the SmartCursor/Range by: - * Copyright (C) 2003-2005 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextrange.h" -#include "katetextbuffer.h" - -namespace Kate { - -TextRange::TextRange (TextBuffer &buffer, const KTextEditor::Range &range, InsertBehaviors insertBehavior, EmptyBehavior emptyBehavior) - : m_buffer (buffer) - , m_start (buffer, this, range.start(), (insertBehavior & ExpandLeft) ? Kate::TextCursor::StayOnInsert : Kate::TextCursor::MoveOnInsert) - , m_end (buffer, this, range.end(), (insertBehavior & ExpandRight) ? Kate::TextCursor::MoveOnInsert : Kate::TextCursor::StayOnInsert) - , m_view (0) - , m_feedback (0) - , m_zDepth (0.0) - , m_attributeOnlyForViews (false) - , m_invalidateIfEmpty (emptyBehavior == InvalidateIfEmpty) -{ - // remember this range in buffer - m_buffer.m_ranges.insert (this); - - // check if range now invalid, there can happen no feedback, as m_feedback == 0 - checkValidity (); -} - -TextRange::~TextRange () -{ - /** - * reset feedback, don't want feedback during destruction - */ - m_feedback = 0; - - // remove range from m_ranges - fixLookup (m_start.line(), m_end.line(), -1, -1); - - // remove this range from the buffer - m_buffer.m_ranges.remove (this); - - /** - * trigger update, if we have attribute - * notify right view - * here we can ignore feedback, even with feedback, we want none if the range is deleted! - */ - if (m_attribute) - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), true /* we have a attribute */); -} - -void TextRange::setInsertBehaviors (InsertBehaviors _insertBehaviors) -{ - /** - * nothing to do? - */ - if (_insertBehaviors == insertBehaviors ()) - return; - - /** - * modify cursors - */ - m_start.setInsertBehavior ((_insertBehaviors & ExpandLeft) ? KTextEditor::MovingCursor::StayOnInsert : KTextEditor::MovingCursor::MoveOnInsert); - m_end.setInsertBehavior ((_insertBehaviors & ExpandRight) ? KTextEditor::MovingCursor::MoveOnInsert : KTextEditor::MovingCursor::StayOnInsert); - - /** - * notify world - */ - if (m_attribute || m_feedback) - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), true /* we have a attribute */); -} - -KTextEditor::MovingRange::InsertBehaviors TextRange::insertBehaviors () const -{ - InsertBehaviors behaviors = DoNotExpand; - - if (m_start.insertBehavior() == KTextEditor::MovingCursor::StayOnInsert) - behaviors = behaviors & ExpandLeft; - - if (m_end.insertBehavior() == KTextEditor::MovingCursor::MoveOnInsert) - behaviors = behaviors & ExpandRight; - - return behaviors; -} - -void TextRange::setEmptyBehavior (EmptyBehavior emptyBehavior) -{ - /** - * nothing to do? - */ - if (m_invalidateIfEmpty == (emptyBehavior == InvalidateIfEmpty)) - return; - - /** - * remember value - */ - m_invalidateIfEmpty = (emptyBehavior == InvalidateIfEmpty); - - /** - * invalidate range? - */ - if (end() <= start()) - setRange (KTextEditor::Range::invalid()); -} - -void TextRange::setRange (const KTextEditor::Range &range) -{ - // avoid work if nothing changed! - if (range == toRange()) - return; - - // remember old line range - int oldStartLine = m_start.line(); - int oldEndLine = m_end.line(); - - // change start and end cursor - m_start.setPosition (range.start ()); - m_end.setPosition (range.end ()); - - // check if range now invalid, don't emit feedback here, will be handled below - // otherwise you can't delete ranges in feedback! - checkValidity (oldStartLine, oldEndLine, false); - - // no attribute or feedback set, be done - if (!m_attribute && !m_feedback) - return; - - // get full range - int startLineMin = oldStartLine; - if (oldStartLine == -1 || (m_start.line() != -1 && m_start.line() < oldStartLine)) - startLineMin = m_start.line(); - - int endLineMax = oldEndLine; - if (oldEndLine == -1 || m_end.line() > oldEndLine) - endLineMax = m_end.line(); - - /** - * notify buffer about attribute change, it will propagate the changes - * notify right view - */ - m_buffer.notifyAboutRangeChange (m_view, startLineMin, endLineMax, m_attribute); - - // perhaps need to notify stuff! - if (m_feedback) { - // do this last: may delete this range - if (!toRange().isValid()) - m_feedback->rangeInvalid (this); - else if (toRange().isEmpty()) - m_feedback->rangeEmpty (this); - } -} - -void TextRange::checkValidity (int oldStartLine, int oldEndLine, bool notifyAboutChange) -{ - /** - * check if any cursor is invalid or the range is zero size and it should be invalidated then - */ - if (!m_start.isValid() || !m_end.isValid() || (m_invalidateIfEmpty && m_end <= m_start)) { - m_start.setPosition (-1, -1); - m_end.setPosition (-1, -1); - } - - /** - * for ranges which are allowed to become empty, normalize them, if the end has moved to the front of the start - */ - if (!m_invalidateIfEmpty && m_end < m_start) - m_end.setPosition (m_start); - - // fix lookup - fixLookup (oldStartLine, oldEndLine, m_start.line(), m_end.line()); - - // perhaps need to notify stuff! - if (notifyAboutChange && m_feedback) { - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), false /* attribute not interesting here */); - - // do this last: may delete this range - if (!toRange().isValid()) - m_feedback->rangeInvalid (this); - else if (toRange().isEmpty()) - m_feedback->rangeEmpty (this); - } -} - -void TextRange::fixLookup (int oldStartLine, int oldEndLine, int startLine, int endLine) -{ - // nothing changed? - if (oldStartLine == startLine && oldEndLine == endLine) - return; - - // now, not both can be invalid - Q_ASSERT (oldStartLine >= 0 || startLine >= 0); - Q_ASSERT (oldEndLine >= 0 || endLine >= 0); - - // get full range - int startLineMin = oldStartLine; - if (oldStartLine == -1 || (startLine != -1 && startLine < oldStartLine)) - startLineMin = startLine; - - int endLineMax = oldEndLine; - if (oldEndLine == -1 || endLine > oldEndLine) - endLineMax = endLine; - - // get start block - int blockIndex = m_buffer.blockForLine (startLineMin); - Q_ASSERT (blockIndex >= 0); - - // remove this range from m_ranges - for (; blockIndex < m_buffer.m_blocks.size(); ++blockIndex) { - // get block - TextBlock *block = m_buffer.m_blocks[blockIndex]; - - // either insert or remove range - if ((endLine < block->startLine()) || (startLine >= (block->startLine() + block->lines()))) - block->removeRange (this); - else - block->updateRange (this); - - // ok, reached end block - if (endLineMax < (block->startLine() + block->lines())) - return; - } - - // we should not be here, really, then endLine is wrong - Q_ASSERT (false); -} - -void TextRange::setView (KTextEditor::View *view) -{ - /** - * nothing changes, nop - */ - if (view == m_view) - return; - - /** - * remember the new attribute - */ - m_view = view; - - /** - * notify buffer about attribute change, it will propagate the changes - * notify all views (can be optimized later) - */ - if (m_attribute || m_feedback) - m_buffer.notifyAboutRangeChange (0, m_start.line(), m_end.line(), m_attribute); -} - -void TextRange::setAttribute ( KTextEditor::Attribute::Ptr attribute ) -{ - /** - * remember the new attribute - */ - m_attribute = attribute; - - /** - * notify buffer about attribute change, it will propagate the changes - * notify right view - */ - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), m_attribute); -} - -void TextRange::setFeedback (KTextEditor::MovingRangeFeedback *feedback) -{ - /** - * nothing changes, nop - */ - if (feedback == m_feedback) - return; - - /** - * remember the new feedback object - */ - m_feedback = feedback; - - /** - * notify buffer about feedback change, it will propagate the changes - * notify right view - */ - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), m_attribute); -} - -void TextRange::setAttributeOnlyForViews (bool onlyForViews) -{ - /** - * just set the value, no need to trigger updates, printing is not interruptable - */ - m_attributeOnlyForViews = onlyForViews; -} - -void TextRange::setZDepth (qreal zDepth) -{ - /** - * nothing changes, nop - */ - if (zDepth == m_zDepth) - return; - - /** - * remember the new attribute - */ - m_zDepth = zDepth; - - /** - * notify buffer about attribute change, it will propagate the changes - */ - if (m_attribute) - m_buffer.notifyAboutRangeChange (m_view, m_start.line(), m_end.line(), m_attribute); -} - -KTextEditor::Document *Kate::TextRange::document () const -{ - return m_buffer.document(); -} - -} diff --git a/part/buffer/katetextrange.h b/part/buffer/katetextrange.h deleted file mode 100644 index bbc34ef..0000000 --- a/part/buffer/katetextrange.h +++ /dev/null @@ -1,309 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * - * Based on code of the SmartCursor/Range by: - * Copyright (C) 2003-2005 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_TEXTRANGE_H -#define KATE_TEXTRANGE_H - -#include -#include -#include - -#include "katepartprivate_export.h" -#include "katetextcursor.h" - -namespace Kate { - -class TextBuffer; - -/** - * Class representing a 'clever' text range. - * It will automagically move if the text inside the buffer it belongs to is modified. - * By intention no subclass of KTextEditor::Range, must be converted manually. - * A TextRange is allowed to be empty. If you call setInvalidateIfEmpty(true), - * a TextRange will become automatically invalid as soon as start() == end() - * position holds. - */ -class KATEPART_TESTS_EXPORT TextRange : public KTextEditor::MovingRange { - // this is a friend, block changes might invalidate ranges... - friend class TextBlock; - - public: - /** - * Construct a text range. - * A TextRange is not allowed to be empty, as soon as start == end position, it will become - * automatically invalid! - * @param buffer parent text buffer - * @param range The initial text range assumed by the new range. - * @param insertBehavior Define whether the range should expand when text is inserted adjacent to the range. - * @param emptyBehavior Define whether the range should invalidate itself on becoming empty. - */ - TextRange (TextBuffer &buffer, const KTextEditor::Range &range, InsertBehaviors insertBehavior, EmptyBehavior emptyBehavior = AllowEmpty); - - /** - * Destruct the text block - */ - ~TextRange (); - - /** - * Set insert behaviors. - * @param insertBehaviors new insert behaviors - */ - void setInsertBehaviors (InsertBehaviors insertBehaviors); - - /** - * Get current insert behaviors. - * @return current insert behaviors - */ - InsertBehaviors insertBehaviors () const; - - /** - * Set if this range will invalidate itself if it becomes empty. - * @param emptyBehavior behavior on becoming empty - */ - void setEmptyBehavior (EmptyBehavior emptyBehavior); - - /** - * Will this range invalidate itself if it becomes empty? - * @return behavior on becoming empty - */ - EmptyBehavior emptyBehavior () const { return m_invalidateIfEmpty ? InvalidateIfEmpty : AllowEmpty; } - - /** - * Gets the document to which this range is bound. - * \return a pointer to the document - */ - KTextEditor::Document *document () const; - - /** - * Set the range of this range. - * A TextRange is not allowed to be empty, as soon as start == end position, it will become - * automatically invalid! - * @param range new range for this clever range - */ - void setRange (const KTextEditor::Range &range); - - /** - * \overload - * Set the range of this range - * A TextRange is not allowed to be empty, as soon as start == end position, it will become - * automatically invalid! - * @param start new start for this clever range - * @param end new end for this clever range - */ - void setRange (const KTextEditor::Cursor &start, const KTextEditor::Cursor &end) { KTextEditor::MovingRange::setRange (start, end); } - - /** - * Retrieve start cursor of this range, read-only. - * @return start cursor - */ - const KTextEditor::MovingCursor &start () const { return m_start; } - - /** - * Non-virtual version of start(), which is faster. - * @return start cursor - */ - const TextCursor &startInternal() const { return m_start; } - - /** - * Retrieve end cursor of this range, read-only. - * @return end cursor - */ - const KTextEditor::MovingCursor &end () const { return m_end; } - - /** - * Nonvirtual version of end(), which is faster. - * @return end cursor - */ - const TextCursor &endInternal () const { return m_end; } - - /** - * Convert this clever range into a dumb one. - * @return normal range - */ - const KTextEditor::Range toRange () const { return KTextEditor::Range (start().toCursor(), end().toCursor()); } - - /** - * Convert this clever range into a dumb one. Equal to toRange, allowing to use implicit conversion. - * @return normal range - */ - operator const KTextEditor::Range () const { return KTextEditor::Range (start().toCursor(), end().toCursor()); } - - /** - * Gets the active view for this range. Might be already invalid, internally only used for pointer comparisons. - * - * \return a pointer to the active view - */ - KTextEditor::View *view () const { return m_view; } - - /** - * Sets the currently active view for this range. - * This will trigger update of the relevant view parts, if the view changed. - * Set view before the attribute, that will avoid not needed redraws. - * - * \param attribute View to assign to this range. If null, simply - * removes the previous view. - */ - void setView (KTextEditor::View *view); - - /** - * Gets the active Attribute for this range. - * - * \return a pointer to the active attribute - */ - KTextEditor::Attribute::Ptr attribute () const { return m_attribute; } - - /** - * \return whether a nonzero attribute is set. This is faster than checking attribute(), - * because the reference-counting is omitted. - */ - bool hasAttribute() const { return !m_attribute.isNull(); } - - /** - * Sets the currently active attribute for this range. - * This will trigger update of the relevant view parts. - * - * \param attribute Attribute to assign to this range. If null, simply - * removes the previous Attribute. - */ - void setAttribute (KTextEditor::Attribute::Ptr attribute); - - /** - * Gets the active MovingRangeFeedback for this range. - * - * \return a pointer to the active MovingRangeFeedback - */ - KTextEditor::MovingRangeFeedback *feedback () const { return m_feedback; } - - /** - * Sets the currently active MovingRangeFeedback for this range. - * This will trigger evaluation if feedback must be send again (for example if mouse is already inside range). - * - * \param attribute MovingRangeFeedback to assign to this range. If null, simply - * removes the previous MovingRangeFeedback. - */ - void setFeedback (KTextEditor::MovingRangeFeedback *feedback); - - /** - * Is this range's attribute only visible in views, not for example prints? - * Default is false. - * @return range visible only for views - */ - bool attributeOnlyForViews () const { return m_attributeOnlyForViews; } - - /** - * Set if this range's attribute is only visible in views, not for example prints. - * @param onlyForViews attribute only valid for views - */ - void setAttributeOnlyForViews (bool onlyForViews); - - /** - * Gets the current Z-depth of this range. - * Ranges with smaller Z-depth than others will win during rendering. - * Default is 0.0. - * - * \return current Z-depth of this range - */ - qreal zDepth () const { return m_zDepth; } - - /** - * Set the current Z-depth of this range. - * Ranges with smaller Z-depth than others will win during rendering. - * This will trigger update of the relevant view parts, if the depth changed. - * Set depth before the attribute, that will avoid not needed redraws. - * Default is 0.0. - * - * \param zDepth new Z-depth of this range - */ - void setZDepth (qreal zDepth); - - private: - /** - * Check if range is valid, used by constructor and setRange. - * If at least one cursor is invalid, both will set to invalid. - * Same if range itself is invalid (start >= end). - * @param oldStartLine old start line of this range before changing of cursors, needed to add/remove range from m_ranges in blocks - * @param oldEndLine old end line of this range - * @param notifyAboutChange should feedback be emited or not? - */ - void checkValidity (int oldStartLine = -1, int oldEndLine = -1, bool notifyAboutChange = true); - - /** - * Add/Remove range from the lookup m_ranges hash of each block - * @param oldStartLine old start line of this range before changing of cursors, needed to add/remove range from m_ranges in blocks - * @param oldEndLine old end line of this range - * @param startLine start line to start looking for the range to remove - * @param endLine end line of this range - */ - void fixLookup (int oldStartLine, int oldEndLine, int startLine, int endLine); - - private: - /** - * parent text buffer - * is a reference, and no pointer, as this must always exist and can't change - */ - TextBuffer &m_buffer; - - /** - * Start cursor for this range, is a clever cursor - */ - TextCursor m_start; - - /** - * End cursor for this range, is a clever cursor - */ - TextCursor m_end; - - /** - * The view for which the attribute is valid, 0 means any view - */ - KTextEditor::View *m_view; - - /** - * This range's current attribute. - */ - KTextEditor::Attribute::Ptr m_attribute; - - /** - * pointer to the active MovingRangeFeedback - */ - KTextEditor::MovingRangeFeedback *m_feedback; - - /** - * Z-depth of this range for rendering - */ - qreal m_zDepth; - - /** - * Is this range's attribute only visible in views, not for example prints? - */ - bool m_attributeOnlyForViews; - - /** - * Will this range invalidate itself if it becomes empty? - */ - bool m_invalidateIfEmpty; -}; - -} - -#endif diff --git a/part/completion/expandingtree/expandingdelegate.cpp b/part/completion/expandingtree/expandingdelegate.cpp deleted file mode 100644 index 46a3163..0000000 --- a/part/completion/expandingtree/expandingdelegate.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "expandingdelegate.h" - -#include -#include -#include -#include -#include -#include - -#include - -#include "expandingwidgetmodel.h" - -ExpandingDelegate::ExpandingDelegate(ExpandingWidgetModel* model, QObject* parent) - : QItemDelegate(parent) - , m_model(model) -{ -} - -//Gets the background-color in the way QItemDelegate does it -static QColor getUsedBackgroundColor(const QStyleOptionViewItem & option, const QModelIndex& index) { -if (option.showDecorationSelected && (option.state & QStyle::State_Selected)) { - QPalette::ColorGroup cg = option.state & QStyle::State_Enabled - ? QPalette::Normal : QPalette::Disabled; - if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) - cg = QPalette::Inactive; - - return option.palette.brush(cg, QPalette::Highlight).color(); - } else { - QVariant value = index.data(Qt::BackgroundRole); - if (qVariantCanConvert(value)) - return qvariant_cast(value).color(); - } - - return QApplication::palette().background().color(); -} - -static void dampColors(QColor& col) { - //Reduce the colors that are less visible to the eye, because they are closer to black when it comes to contrast - //The most significant color to the eye is green. Then comes red, and then blue, with blue _much_ less significant. - - col.setBlue(0); - col.setRed(col.red() / 2); -} - -//A hack to compute more eye-focused contrast values -static double readabilityContrast(QColor foreground, QColor background) { - dampColors(foreground); - dampColors(background); - return abs(foreground.green()-background.green()) + abs(foreground.red()-background.red()) + abs(foreground.blue() - background.blue()); -} - -void ExpandingDelegate::paint( QPainter * painter, const QStyleOptionViewItem & optionOld, const QModelIndex & index ) const -{ - QStyleOptionViewItem option(optionOld); - - m_currentIndex = index; - - adjustStyle(index, option); - - if( index.column() == 0 ) - model()->placeExpandingWidget(index); - - //Make sure the decorations are painted at the top, because the center of expanded items will be filled with the embedded widget. - if( model()->isPartiallyExpanded(index) == ExpandingWidgetModel::ExpandUpwards ) - m_cachedAlignment = Qt::AlignBottom; - else - m_cachedAlignment = Qt::AlignTop; - - option.decorationAlignment = m_cachedAlignment; - option.displayAlignment = m_cachedAlignment; - - //kDebug( 13035 ) << "Painting row " << index.row() << ", column " << index.column() << ", internal " << index.internalPointer() << ", drawselected " << option.showDecorationSelected << ", selected " << (option.state & QStyle::State_Selected); - - m_cachedHighlights.clear(); - m_backgroundColor = getUsedBackgroundColor(option, index); - - if (model()->indexIsItem(index) ) { - m_currentColumnStart = 0; - m_cachedHighlights = createHighlighting(index, option); - } - - /*kDebug( 13035 ) << "Highlights for line:"; - foreach (const QTextLayout::FormatRange& fr, m_cachedHighlights) - kDebug( 13035 ) << fr.start << " len " << fr.length << " format ";*/ - - QItemDelegate::paint(painter, option, index); - - ///This is a bug workaround for the Qt raster paint engine: It paints over widgets embedded into the viewport when updating due to mouse events - ///@todo report to Qt Software - if( model()->isExpanded(index) && model()->expandingWidget( index ) ) - model()->expandingWidget( index )->update(); -} - -QList ExpandingDelegate::createHighlighting(const QModelIndex& index, QStyleOptionViewItem& option) const { - Q_UNUSED( index ); - Q_UNUSED( option ); - return QList(); -} - -QSize ExpandingDelegate::basicSizeHint( const QModelIndex& index ) const { - return QItemDelegate::sizeHint( QStyleOptionViewItem(), index ); -} - -QSize ExpandingDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const -{ - QSize s = QItemDelegate::sizeHint( option, index ); - if( model()->isExpanded(index) && model()->expandingWidget( index ) ) - { - QWidget* widget = model()->expandingWidget( index ); - QSize widgetSize = widget->size(); - - s.setHeight( widgetSize.height() + s.height() + 10 ); //10 is the sum that must match exactly the offsets used in ExpandingWidgetModel::placeExpandingWidgets - } else if( model()->isPartiallyExpanded( index ) ) { - s.setHeight( s.height() + 30 + 10 ); - } - return s; -} - -void ExpandingDelegate::adjustStyle( const QModelIndex& index, QStyleOptionViewItem & option ) const -{ - Q_UNUSED(index) - Q_UNUSED(option) -} - -void ExpandingDelegate::adjustRect(QRect& rect) const { - if (!model()->indexIsItem(m_currentIndex) /*&& m_currentIndex.column() == 0*/) { - - rect.setLeft(model()->treeView()->columnViewportPosition(0)); - int columnCount = model()->columnCount(m_currentIndex.parent()); - - if(!columnCount) - return; - rect.setRight(model()->treeView()->columnViewportPosition(columnCount-1) + model()->treeView()->columnWidth(columnCount-1)); - } -} - -void ExpandingDelegate::drawDisplay( QPainter * painter, const QStyleOptionViewItem & option, const QRect & _rect, const QString & text ) const -{ - QRect rect(_rect); - - adjustRect(rect); - - QTextLayout layout(text, option.font, painter->device()); - - QRect textRect = rect.adjusted(1, 0, -1, 0); // remove width padding - - QList additionalFormats; - - int missingFormats = text.length(); - - for (int i = 0; i < m_cachedHighlights.count(); ++i) { - if (m_cachedHighlights[i].start + m_cachedHighlights[i].length <= m_currentColumnStart) - continue; - - if (!additionalFormats.count()) - if (i != 0 && m_cachedHighlights[i - 1].start + m_cachedHighlights[i - 1].length > m_currentColumnStart) { - QTextLayout::FormatRange before; - before.start = 0; - before.length = m_cachedHighlights[i - 1].start + m_cachedHighlights[i - 1].length - m_currentColumnStart; - before.format = m_cachedHighlights[i - 1].format; - additionalFormats.append(before); - } - - - QTextLayout::FormatRange format; - format.start = m_cachedHighlights[i].start - m_currentColumnStart; - format.length = m_cachedHighlights[i].length; - format.format = m_cachedHighlights[i].format; - - additionalFormats.append(format); - } - if(!additionalFormats.isEmpty()) - missingFormats = text.length() - (additionalFormats.back().length + additionalFormats.back().start); - - if (missingFormats > 0) { - QTextLayout::FormatRange format; - format.start = text.length() - missingFormats; - format.length = missingFormats; - QTextCharFormat fm; - fm.setForeground(option.palette.text()); - format.format = fm; - additionalFormats.append(format); - } - - if(m_backgroundColor.isValid()) { - QColor background = m_backgroundColor; -// kDebug() << text << "background:" << background.name(); - //Now go through the formats, and make sure the contrast background/foreground is readable - for(int a = 0; a < additionalFormats.size(); ++a) { - QColor currentBackground = background; - if(additionalFormats[a].format.hasProperty(QTextFormat::BackgroundBrush)) - currentBackground = additionalFormats[a].format.background().color(); - - QColor currentColor = additionalFormats[a].format.foreground().color(); - - double currentContrast = readabilityContrast(currentColor, currentBackground); - QColor invertedColor(0xffffffff-additionalFormats[a].format.foreground().color().rgb()); - double invertedContrast = readabilityContrast(invertedColor, currentBackground); - -// kDebug() << "values:" << invertedContrast << currentContrast << invertedColor.name() << currentColor.name(); - - if(invertedContrast > currentContrast) { -// kDebug() << text << additionalFormats[a].length << "switching from" << currentColor.name() << "to" << invertedColor.name(); - QBrush b(additionalFormats[a].format.foreground()); - b.setColor(invertedColor); - additionalFormats[a].format.setForeground(b); - } - } - } - - for(int a = additionalFormats.size()-1; a >= 0; --a) { - if(additionalFormats[a].length == 0){ - additionalFormats.removeAt(a); - }else{ - ///For some reason the text-formats seem to be invalid in some way, sometimes - ///@todo Fix this properly, it sucks not copying everything over - QTextCharFormat fm; - fm.setForeground(QBrush(additionalFormats[a].format.foreground().color())); - fm.setBackground(additionalFormats[a].format.background()); - fm.setUnderlineStyle( additionalFormats[a].format.underlineStyle() ); - fm.setUnderlineColor( additionalFormats[a].format.underlineColor() ); - fm.setFontWeight( additionalFormats[a].format.fontWeight() ); - additionalFormats[a].format = fm; - } - } - -// kDebug( 13035 ) << "Highlights for text [" << text << "] col start " << m_currentColumnStart << ":"; -// foreach (const QTextLayout::FormatRange& fr, additionalFormats) -// kDebug( 13035 ) << fr.start << " len " << fr.length << "foreground" << fr.format.foreground() << "background" << fr.format.background(); - - layout.setAdditionalFormats(additionalFormats); - - QTextOption to; - - to.setAlignment( m_cachedAlignment ); - - to.setWrapMode(QTextOption::WrapAnywhere); - layout.setTextOption(to); - - layout.beginLayout(); - QTextLine line = layout.createLine(); - line.setLineWidth(rect.width()); - layout.endLayout(); - - //We need to do some hand layouting here - if( to.alignment() & Qt::AlignBottom) - layout.draw(painter, QPoint(rect.left(), rect.bottom() - (int)line.height()) ); - else - layout.draw(painter, rect.topLeft() ); - - return; - - //if (painter->fontMetrics().width(text) > textRect.width() && !text.contains(QLatin1Char('\n'))) - //str = elidedText(option.fontMetrics, textRect.width(), option.textElideMode, text); - //qt_format_text(option.font, textRect, option.displayAlignment, str, 0, 0, 0, 0, painter); -} - -void ExpandingDelegate::drawDecoration(QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect, const QPixmap& pixmap) const { - if (model()->indexIsItem(m_currentIndex) ) - QItemDelegate::drawDecoration(painter, option, rect, pixmap); -} - -void ExpandingDelegate::drawBackground ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { - Q_UNUSED(index) - QStyleOptionViewItemV4 opt = option; - //initStyleOption(&opt, index); - //Problem: This isn't called at all, because drawBrackground is not virtual :-/ - QStyle *style = model()->treeView()->style() ? model()->treeView()->style() : QApplication::style(); - style->drawControl(QStyle::CE_ItemViewItem, &opt, painter); -} - -ExpandingWidgetModel* ExpandingDelegate::model() const { - return m_model; -} - -void ExpandingDelegate::heightChanged() const { -} - -bool ExpandingDelegate::editorEvent ( QEvent * event, QAbstractItemModel * /*model*/, const QStyleOptionViewItem & /*option*/, const QModelIndex & index ) -{ - QKeyEvent* keyEvent = 0; - if( event->type() == QEvent::KeyPress ) - keyEvent = reinterpret_cast(event); - - if( event->type() == QEvent::MouseButtonRelease ) - { - event->accept(); - model()->setExpanded(index, !model()->isExpanded( index )); - heightChanged(); - - return true; - } else { - event->ignore(); - } - - return false; -} - -QList ExpandingDelegate::highlightingFromVariantList(const QList& customHighlights) const -{ - QList ret; - - for (int i = 0; i + 2 < customHighlights.count(); i += 3) { - if (!customHighlights[i].canConvert(QVariant::Int) || !customHighlights[i+1].canConvert(QVariant::Int) || !customHighlights[i+2].canConvert()) { - kWarning() << "Unable to convert triple to custom formatting."; - continue; - } - - QTextLayout::FormatRange format; - format.start = customHighlights[i].toInt(); - format.length = customHighlights[i+1].toInt(); - format.format = customHighlights[i+2].value().toCharFormat(); - - if(!format.format.isValid()) - kWarning() << "Format is not valid"; - - ret << format; - } - return ret; -} - -#include "expandingdelegate.moc" diff --git a/part/completion/expandingtree/expandingdelegate.h b/part/completion/expandingtree/expandingdelegate.h deleted file mode 100644 index f6de630..0000000 --- a/part/completion/expandingtree/expandingdelegate.h +++ /dev/null @@ -1,93 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef ExpandingDelegate_H -#define ExpandingDelegate_H - -#include -#include -#include -#include -#include - -class KateRenderer; -class KateCompletionWidget; -class KateDocument; -class KateTextLine; -class ExpandingWidgetModel; -class QVariant; -class QStyleOptionViewItem; - -/** - * This is a delegate that cares, together with ExpandingWidgetModel, about embedded widgets in tree-view. - * */ - -class ExpandingDelegate : public QItemDelegate -{ - Q_OBJECT - - public: - explicit ExpandingDelegate(ExpandingWidgetModel* model, QObject* parent = 0L); - - - // Overridden to create highlighting for current index - virtual void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; - - // Returns the basic size-hint as reported by QItemDelegate - QSize basicSizeHint( const QModelIndex& index ) const; - - ExpandingWidgetModel* model() const; - protected: - //Called right before paint to allow last-minute changes to the style - virtual void adjustStyle( const QModelIndex& index, QStyleOptionViewItem & option ) const; - virtual void drawDisplay ( QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect, const QString & text ) const; - virtual QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; - virtual bool editorEvent ( QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index ); - virtual void drawBackground ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; - virtual void drawDecoration(QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect, const QPixmap& pixmap) const; - //option can be changed - virtual QList createHighlighting(const QModelIndex& index, QStyleOptionViewItem& option) const; - - void adjustRect(QRect& rect) const; - - /** - * Creates a list of FormatRanges as should be returned by createHighlighting from a list of QVariants as described in the kde header ktexteditor/codecompletionmodel.h - * */ - QList highlightingFromVariantList(const QList& customHighlights) const; - - //Called when an item was expanded/unexpanded and the height changed - virtual void heightChanged() const; - - //Initializes the style options from the index - void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const; - - mutable int m_currentColumnStart; //Text-offset for custom highlighting, will be applied to m_cachedHighlights(Only highlights starting after this will be used). Shoult be zero of the highlighting is not taken from kate. - mutable QList m_currentColumnStarts; - mutable QList m_cachedHighlights; - - mutable Qt::Alignment m_cachedAlignment; - mutable QColor m_backgroundColor; - mutable QModelIndex m_currentIndex; - private: - - ExpandingWidgetModel* m_model; -}; - -#endif diff --git a/part/completion/expandingtree/expandingtree.cpp b/part/completion/expandingtree/expandingtree.cpp deleted file mode 100644 index 83c1436..0000000 --- a/part/completion/expandingtree/expandingtree.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "expandingtree.h" - -#include -#include -#include -#include -#include -#include "expandingwidgetmodel.h" - -ExpandingTree::ExpandingTree(QWidget* parent) : QTreeView(parent) { - m_drawText.documentLayout()->setPaintDevice(this); - setUniformRowHeights(false); -} - -void ExpandingTree::drawRow ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { - QTreeView::drawRow( painter, option, index ); - - const ExpandingWidgetModel* eModel = qobject_cast(model()); - if( eModel && eModel->isPartiallyExpanded( index ) ) - { - QRect rect = eModel->partialExpandRect( index ); - if( rect.isValid() ) - { - painter->fillRect(rect,QBrush(0xffffffff)); - - QAbstractTextDocumentLayout::PaintContext ctx; - // since arbitrary HTML can be shown use a black on white color scheme here - ctx.palette = QPalette( Qt::black, Qt::white ); - ctx.clip = QRectF(0,0,rect.width(),rect.height());; - painter->setViewTransformEnabled(true); - painter->translate(rect.left(), rect.top()); - - m_drawText.setHtml( eModel->partialExpandText( index ) ); - m_drawText.setPageSize(QSizeF(rect.width(), rect.height())); - m_drawText.documentLayout()->draw( painter, ctx ); - - painter->translate(-rect.left(), -rect.top()); - } - } -} - -int ExpandingTree::sizeHintForColumn ( int column ) const { - return columnWidth( column ); -} diff --git a/part/completion/expandingtree/expandingtree.h b/part/completion/expandingtree/expandingtree.h deleted file mode 100644 index ad29e62..0000000 --- a/part/completion/expandingtree/expandingtree.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef ExpandingTree_H -#define ExpandingTree_H - -#include -#include - -//A tree that allows drawing additional information -class ExpandingTree : public QTreeView { - public: - ExpandingTree(QWidget* parent); - protected: - virtual void drawRow ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; - virtual int sizeHintForColumn ( int column ) const; - private: - mutable QTextDocument m_drawText; -}; - -#endif diff --git a/part/completion/expandingtree/expandingwidgetmodel.cpp b/part/completion/expandingtree/expandingwidgetmodel.cpp deleted file mode 100644 index 7f9cfa9..0000000 --- a/part/completion/expandingtree/expandingwidgetmodel.cpp +++ /dev/null @@ -1,528 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "expandingwidgetmodel.h" - -#include -#include -#include - -#include -#include -#include -#include "kcolorutils.h" - -#include "expandingdelegate.h" -#include - -QIcon ExpandingWidgetModel::m_expandedIcon; -QIcon ExpandingWidgetModel::m_collapsedIcon; - -using namespace KTextEditor; - -inline QModelIndex firstColumn( const QModelIndex& index ) { - return index.sibling(index.row(), 0); -} - -ExpandingWidgetModel::ExpandingWidgetModel( QWidget* parent ) : - QAbstractTableModel(parent) -{ -} - -ExpandingWidgetModel::~ExpandingWidgetModel() { - clearExpanding(); -} - -static QColor doAlternate(QColor color) { - QColor background = QApplication::palette().background().color(); - return KColorUtils::mix(color, background, 0.15); -} - -uint ExpandingWidgetModel::matchColor(const QModelIndex& index) const { - - int matchQuality = contextMatchQuality( index.sibling(index.row(), 0) ); - - if( matchQuality > 0 ) - { - bool alternate = index.row() & 1; - - QColor badMatchColor(0xff00aa44); //Blue-ish green - QColor goodMatchColor(0xff00ff00); //Green - - QColor background = treeView()->palette().light().color(); - - QColor totalColor = KColorUtils::mix(badMatchColor, goodMatchColor, ((float)matchQuality)/10.0); - - if(alternate) - totalColor = doAlternate(totalColor); - - const float dynamicTint = 0.2; - const float minimumTint = 0.2; - double tintStrength = (dynamicTint*matchQuality)/10; - if(tintStrength) - tintStrength += minimumTint; //Some minimum tinting strength, else it's not visible any more - - return KColorUtils::tint(background, totalColor, tintStrength ).rgb(); - }else{ - return 0; - } -} - -QVariant ExpandingWidgetModel::data( const QModelIndex & index, int role ) const -{ - switch( role ) { - case Qt::BackgroundRole: - { - if( index.column() == 0 ) { - //Highlight by match-quality - uint color = matchColor(index); - if( color ) - return QBrush( color ); - } - //Use a special background-color for expanded items - if( isExpanded(index) ) { - if( index.row() & 1 ) { - return doAlternate(treeView()->palette().toolTipBase().color()); - } else { - return treeView()->palette().toolTipBase(); - } - } - } - } - return QVariant(); -} - -void ExpandingWidgetModel::clearMatchQualities() { - m_contextMatchQualities.clear(); -} - -QModelIndex ExpandingWidgetModel::partiallyExpandedRow() const { - if( m_partiallyExpanded.isEmpty() ) - return QModelIndex(); - else - return m_partiallyExpanded.constBegin().key(); -} - -void ExpandingWidgetModel::clearExpanding() { - - clearMatchQualities(); - QMap oldExpandState = m_expandState; - foreach( const QPointer &widget, m_expandingWidgets ) - delete widget; - m_expandingWidgets.clear(); - m_expandState.clear(); - m_partiallyExpanded.clear(); - - for( QMap::const_iterator it = oldExpandState.constBegin(); it != oldExpandState.constEnd(); ++it ) - if(it.value() == Expanded) - emit dataChanged(it.key(), it.key()); -} - -ExpandingWidgetModel::ExpansionType ExpandingWidgetModel::isPartiallyExpanded(const QModelIndex& index) const { - if( m_partiallyExpanded.contains(firstColumn(index)) ) - return m_partiallyExpanded[firstColumn(index)]; - else - return NotExpanded; -} - -void ExpandingWidgetModel::partiallyUnExpand(const QModelIndex& idx_) -{ - QModelIndex index( firstColumn(idx_) ); - m_partiallyExpanded.remove(index); - m_partiallyExpanded.remove(idx_); -} - -int ExpandingWidgetModel::partiallyExpandWidgetHeight() const { - return 60; ///@todo use font-metrics text-height*2 for 2 lines -} - -void ExpandingWidgetModel::rowSelected(const QModelIndex& idx_) -{ - QModelIndex idx( firstColumn(idx_) ); - if( !m_partiallyExpanded.contains( idx ) ) - { - QModelIndex oldIndex = partiallyExpandedRow(); - //Unexpand the previous partially expanded row - if( !m_partiallyExpanded.isEmpty() ) - { ///@todo allow multiple partially expanded rows - while( !m_partiallyExpanded.isEmpty() ) - m_partiallyExpanded.erase(m_partiallyExpanded.begin()); - //partiallyUnExpand( m_partiallyExpanded.begin().key() ); - } - //Notify the underlying models that the item was selected, and eventually get back the text for the expanding widget. - if( !idx.isValid() ) { - //All items have been unselected - if( oldIndex.isValid() ) - emit dataChanged(oldIndex, oldIndex); - } else { - QVariant variant = data(idx, CodeCompletionModel::ItemSelected); - - if( !isExpanded(idx) && variant.type() == QVariant::String) { - - //Either expand upwards or downwards, choose in a way that - //the visible fields of the new selected entry are not moved. - if( oldIndex.isValid() && (oldIndex < idx || (!(oldIndex < idx) && oldIndex.parent() < idx.parent()) ) ) - m_partiallyExpanded.insert(idx, ExpandUpwards); - else - m_partiallyExpanded.insert(idx, ExpandDownwards); - - //Say that one row above until one row below has changed, so no items will need to be moved(the space that is taken from one item is given to the other) - if( oldIndex.isValid() && oldIndex < idx ) { - emit dataChanged(oldIndex, idx); - - if( treeView()->verticalScrollMode() == QAbstractItemView::ScrollPerItem ) - { - //Qt fails to correctly scroll in ScrollPerItem mode, so the selected index is completely visible, - //so we do the scrolling by hand. - QRect selectedRect = treeView()->visualRect(idx); - QRect frameRect = treeView()->frameRect(); - - if( selectedRect.bottom() > frameRect.bottom() ) { - int diff = selectedRect.bottom() - frameRect.bottom(); - //We need to scroll down - QModelIndex newTopIndex = idx; - - QModelIndex nextTopIndex = idx; - QRect nextRect = treeView()->visualRect(nextTopIndex); - while( nextTopIndex.isValid() && nextRect.isValid() && nextRect.top() >= diff ) { - newTopIndex = nextTopIndex; - nextTopIndex = treeView()->indexAbove(nextTopIndex); - if( nextTopIndex.isValid() ) - nextRect = treeView()->visualRect(nextTopIndex); - } - treeView()->scrollTo( newTopIndex, QAbstractItemView::PositionAtTop ); - } - } - - //This is needed to keep the item we are expanding completely visible. Qt does not scroll the view to keep the item visible. - //But we must make sure that it isn't too expensive. - //We need to make sure that scrolling is efficient, and the whole content is not repainted. - //Since we are scrolling anyway, we can keep the next line visible, which might be a cool feature. - - //Since this also doesn't work smoothly, leave it for now - //treeView()->scrollTo( nextLine, QAbstractItemView::EnsureVisible ); - } else if( oldIndex.isValid() && idx < oldIndex ) { - emit dataChanged(idx, oldIndex); - - //For consistency with the down-scrolling, we keep one additional line visible above the current visible. - - //Since this also doesn't work smoothly, leave it for now -/* QModelIndex prevLine = idx.sibling(idx.row()-1, idx.column()); - if( prevLine.isValid() ) - treeView()->scrollTo( prevLine );*/ - } else - emit dataChanged(idx, idx); - } else if( oldIndex.isValid() ) { - //We are not partially expanding a new row, but we previously had a partially expanded row. So signalize that it has been unexpanded. - - emit dataChanged(oldIndex, oldIndex); - } - } - }else{ - kDebug( 13035 ) << "ExpandingWidgetModel::rowSelected: Row is already partially expanded"; - } -} - -QString ExpandingWidgetModel::partialExpandText(const QModelIndex& idx) const { - if( !idx.isValid() ) - return QString(); - - return data(firstColumn(idx), CodeCompletionModel::ItemSelected).toString(); -} - -QRect ExpandingWidgetModel::partialExpandRect(const QModelIndex& idx_) const -{ - QModelIndex idx(firstColumn(idx_)); - - if( !idx.isValid() ) - return QRect(); - - ExpansionType expansion = ExpandDownwards; - - if( m_partiallyExpanded.find(idx) != m_partiallyExpanded.constEnd() ) - expansion = m_partiallyExpanded[idx]; - - //Get the whole rectangle of the row: - QModelIndex rightMostIndex = idx; - QModelIndex tempIndex = idx; - while( (tempIndex = rightMostIndex.sibling(rightMostIndex.row(), rightMostIndex.column()+1)).isValid() ) - rightMostIndex = tempIndex; - - QRect rect = treeView()->visualRect(idx); - QRect rightMostRect = treeView()->visualRect(rightMostIndex); - - rect.setLeft( rect.left() + 20 ); - rect.setRight( rightMostRect.right() - 5 ); - - //These offsets must match exactly those used in ExpandingDelegate::sizeHint() - int top = rect.top() + 5; - int bottom = rightMostRect.bottom() - 5 ; - - if( expansion == ExpandDownwards ) - top += basicRowHeight(idx); - else - bottom -= basicRowHeight(idx); - - rect.setTop( top ); - rect.setBottom( bottom ); - - return rect; -} - -bool ExpandingWidgetModel::isExpandable(const QModelIndex& idx_) const -{ - QModelIndex idx(firstColumn(idx_)); - - if( !m_expandState.contains(idx) ) - { - m_expandState.insert(idx, NotExpandable); - QVariant v = data(idx, CodeCompletionModel::IsExpandable); - if( v.canConvert() && v.value() ) - m_expandState[idx] = Expandable; - } - - return m_expandState[idx] != NotExpandable; -} - -bool ExpandingWidgetModel::isExpanded(const QModelIndex& idx_) const -{ - QModelIndex idx(firstColumn(idx_)); - return m_expandState.contains(idx) && m_expandState[idx] == Expanded; -} - -void ExpandingWidgetModel::setExpanded(QModelIndex idx_, bool expanded) -{ - QModelIndex idx(firstColumn(idx_)); - - //kDebug( 13035 ) << "Setting expand-state of row " << idx.row() << " to " << expanded; - if( !idx.isValid() ) - return; - - if( isExpandable(idx) ) { - if( !expanded && m_expandingWidgets.contains(idx) && m_expandingWidgets[idx] ) { - m_expandingWidgets[idx]->hide(); - } - - m_expandState[idx] = expanded ? Expanded : Expandable; - - if( expanded ) - partiallyUnExpand(idx); - - if( expanded && !m_expandingWidgets.contains(idx) ) - { - QVariant v = data(idx, CodeCompletionModel::ExpandingWidget); - - if( v.canConvert() ) { - m_expandingWidgets[idx] = v.value(); - } else if( v.canConvert() ) { - //Create a html widget that shows the given string - KTextEdit* edit = new KTextEdit( v.value() ); - edit->setReadOnly(true); - edit->resize(200, 50); //Make the widget small so it embeds nicely. - m_expandingWidgets[idx] = edit; - } else { - m_expandingWidgets[idx] = 0; - } - } - - //Eventually partially expand the row - if( !expanded && firstColumn(treeView()->currentIndex()) == idx && !isPartiallyExpanded(idx) ) - rowSelected(idx); //Partially expand the row. - - emit dataChanged(idx, idx); - - if(treeView()) - treeView()->scrollTo(idx); - } -} - -int ExpandingWidgetModel::basicRowHeight( const QModelIndex& idx_ ) const -{ - QModelIndex idx(firstColumn(idx_)); - - ExpandingDelegate* delegate = dynamic_cast( treeView()->itemDelegate(idx) ); - if( !delegate || !idx.isValid() ) { - kDebug( 13035 ) << "ExpandingWidgetModel::basicRowHeight: Could not get delegate"; - return 15; - } - return delegate->basicSizeHint( idx ).height(); -} - - -void ExpandingWidgetModel::placeExpandingWidget(const QModelIndex& idx_) -{ - QModelIndex idx(firstColumn(idx_)); - - QWidget* w = 0; - if( m_expandingWidgets.contains(idx) ) - w = m_expandingWidgets[idx]; - - if( w && isExpanded(idx) ) { - if( !idx.isValid() ) - return; - - QRect rect = treeView()->visualRect(idx); - - if( !rect.isValid() || rect.bottom() < 0 || rect.top() >= treeView()->height() ) { - //The item is currently not visible - w->hide(); - return; - } - - QModelIndex rightMostIndex = idx; - QModelIndex tempIndex = idx; - while( (tempIndex = rightMostIndex.sibling(rightMostIndex.row(), rightMostIndex.column()+1)).isValid() ) - rightMostIndex = tempIndex; - - QRect rightMostRect = treeView()->visualRect(rightMostIndex); - - //Find out the basic height of the row - rect.setLeft( rect.left() + 20 ); - rect.setRight( rightMostRect.right() - 5 ); - - //These offsets must match exactly those used in KateCompletionDeleage::sizeHint() - rect.setTop( rect.top() + basicRowHeight(idx) + 5 ); - rect.setHeight( w->height() ); - - if( w->parent() != treeView()->viewport() || w->geometry() != rect || !w->isVisible() ) { - w->setParent( treeView()->viewport() ); - - w->setGeometry(rect); - w->show(); - } - } -} - -void ExpandingWidgetModel::placeExpandingWidgets() { - for( QMap >::const_iterator it = m_expandingWidgets.constBegin(); it != m_expandingWidgets.constEnd(); ++it ) { - placeExpandingWidget(it.key()); - } -} - -int ExpandingWidgetModel::expandingWidgetsHeight() const -{ - int sum = 0; - for( QMap >::const_iterator it = m_expandingWidgets.constBegin(); it != m_expandingWidgets.constEnd(); ++it ) { - if( isExpanded(it.key() ) && (*it) ) - sum += (*it)->height(); - } - return sum; -} - - -QWidget* ExpandingWidgetModel::expandingWidget(const QModelIndex& idx_) const -{ - QModelIndex idx(firstColumn(idx_)); - - if( m_expandingWidgets.contains(idx) ) - return m_expandingWidgets[idx]; - else - return 0; -} - -void ExpandingWidgetModel::cacheIcons() const { - if( m_expandedIcon.isNull() ) - m_expandedIcon = KIconLoader::global()->loadIcon("arrow-down", KIconLoader::Small, 10); - - if( m_collapsedIcon.isNull() ) - m_collapsedIcon = KIconLoader::global()->loadIcon("arrow-right", KIconLoader::Small, 10); -} - -QList mergeCustomHighlighting( int leftSize, const QList& left, int rightSize, const QList& right ) -{ - QList ret = left; - if( left.isEmpty() ) { - ret << QVariant(0); - ret << QVariant(leftSize); - ret << QTextFormat(QTextFormat::CharFormat); - } - - if( right.isEmpty() ) { - ret << QVariant(leftSize); - ret << QVariant(rightSize); - ret << QTextFormat(QTextFormat::CharFormat); - } else { - QList::const_iterator it = right.constBegin(); - while( it != right.constEnd() ) { - { - QList::const_iterator testIt = it; - for(int a = 0; a < 2; a++) { - ++testIt; - if(testIt == right.constEnd()) { - kWarning() << "Length of input is not multiple of 3"; - break; - } - } - } - - ret << QVariant( (*it).toInt() + leftSize ); - ++it; - ret << QVariant( (*it).toInt() ); - ++it; - ret << *it; - if(!(*it).value().isValid()) - kDebug( 13035 ) << "Text-format is invalid"; - ++it; - } - } - return ret; -} - -//It is assumed that between each two strings, one space is inserted -QList mergeCustomHighlighting( QStringList strings, QList highlights, int grapBetweenStrings ) -{ - if(strings.isEmpty()) { - kWarning() << "List of strings is empty"; - return QList(); - } - - if(highlights.isEmpty()) { - kWarning() << "List of highlightings is empty"; - return QList(); - } - - if(strings.count() != highlights.count()) { - kWarning() << "Length of string-list is " << strings.count() << " while count of highlightings is " << highlights.count() << ", should be same"; - return QList(); - } - - //Merge them together - QString totalString = strings[0]; - QVariantList totalHighlighting = highlights[0]; - - strings.pop_front(); - highlights.pop_front(); - - while( !strings.isEmpty() ) { - totalHighlighting = mergeCustomHighlighting( totalString.length(), totalHighlighting, strings[0].length(), highlights[0] ); - totalString += strings[0]; - - for(int a = 0; a < grapBetweenStrings; a++) - totalString += ' '; - - strings.pop_front(); - highlights.pop_front(); - - } - //Combine the custom-highlightings - return totalHighlighting; -} -#include "expandingwidgetmodel.moc" - diff --git a/part/completion/expandingtree/expandingwidgetmodel.h b/part/completion/expandingtree/expandingwidgetmodel.h deleted file mode 100644 index ab575f2..0000000 --- a/part/completion/expandingtree/expandingwidgetmodel.h +++ /dev/null @@ -1,161 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef EXPANDING_WIDGET_MODEL_H -#define EXPANDING_WIDGET_MODEL_H - -#include -#include -#include -#include -#include - -class KWidget; -class QTreeView; -class QTextEdit; - -/** - * Cares about expanding/un-expanding items in a tree-view together with ExpandingDelegate - */ -class ExpandingWidgetModel : public QAbstractTableModel { - Q_OBJECT - public: - - ExpandingWidgetModel( QWidget* parent ); - virtual ~ExpandingWidgetModel(); - - enum ExpandingType { - NotExpandable=0, - Expandable, - Expanded - }; - - ///The following three are convenience-functions for the current item that could be replaced by the later ones - ///@return whether the current item can be expanded - bool canExpandCurrentItem() const; - ///@return whether the current item can be collapsed - bool canCollapseCurrentItem() const; - ///Expand/collapse the current item - void setCurrentItemExpanded( bool ); - - void clearMatchQualities(); - - ///Unexpand all rows and clear all cached information about them(this includes deleting the expanding-widgets) - void clearExpanding(); - - ///@return whether the row given through index is expandable - bool isExpandable(const QModelIndex& index) const; - - enum ExpansionType { - NotExpanded = 0, - ExpandDownwards, //The additional(expanded) information is shown UNDER the original information - ExpandUpwards //The additional(expanded) information is shown ABOVE the original information - }; - - ///Returns whether the given index is currently partially expanded. Does not do any other checks like calling models for data. - ExpansionType isPartiallyExpanded(const QModelIndex& index) const; - - ///@return whether row is currently expanded - bool isExpanded(const QModelIndex & row) const; - ///Change the expand-state of the row given through index. The display will be updated. - void setExpanded(QModelIndex index, bool expanded); - - ///Returns the total height added through all open expanding-widgets - int expandingWidgetsHeight() const; - - ///@return the expanding-widget for the given row, if available. Expanding-widgets are in best case available for all expanded rows. - ///This does not return the partially-expand widget. - QWidget* expandingWidget(const QModelIndex & row) const; - - ///Amount by which the height of a row increases when it is partially expanded - int partiallyExpandWidgetHeight() const; - /** - * Notifies underlying models that the item was selected, collapses any previous partially expanded line, - * checks whether this line should be partially expanded, and eventually does it. - * Does nothing when nothing needs to be done. - * Does NOT show the expanding-widget. That is done immediately when painting by ExpandingDelegate, - * to reduce flickering. @see showPartialExpandWidget() - * @param row The row - * */ - /// - virtual void rowSelected(const QModelIndex & row); - - ///Returns the rectangle for the partially expanded part of the given row - QRect partialExpandRect(const QModelIndex & row) const; - - QString partialExpandText(const QModelIndex & row) const; - - ///Places and shows the expanding-widget for the given row, if it should be visible and is valid. - ///Also shows the partial-expanding-widget when it should be visible. - void placeExpandingWidget(const QModelIndex & row); - - virtual QTreeView* treeView() const = 0; - - ///Should return true if the given row should be painted like a contained item(as opposed to label-rows etc.) - virtual bool indexIsItem(const QModelIndex& index) const = 0; - - ///Does not request data from index, this only returns local data like highlighting for expanded rows and similar - virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; - - ///Returns the first row that is currently partially expanded. - QModelIndex partiallyExpandedRow() const; - - ///Returns the match-color for the given index, or zero if match-quality could not be computed. - uint matchColor(const QModelIndex& index) const; - - public slots: - ///Place or hides all expanding-widgets to the correct positions. Should be called after the view was scrolled. - void placeExpandingWidgets(); - - protected: - /** - * @return the context-match quality from 0 to 10 if it could be determined, else -1 - * */ - virtual int contextMatchQuality(const QModelIndex & index) const = 0; - - //Makes sure m_expandedIcon and m_collapsedIcon are loaded - void cacheIcons() const; - - static QIcon m_expandedIcon; - static QIcon m_collapsedIcon; - - //Does not update the view - void partiallyUnExpand(const QModelIndex& index); - //Finds out the basic height of the row represented by the given index. Basic means without respecting any expansion. - int basicRowHeight( const QModelIndex& index ) const; - - private: - QMap m_partiallyExpanded; - // Store expanding-widgets and cache whether items can be expanded - mutable QMap m_expandState; - QMap< QModelIndex, QPointer > m_expandingWidgets; //Map rows to their expanding-widgets - QMap< QModelIndex, int > m_contextMatchQualities; //Map rows to their context-match qualities(undefined if unknown, else 0 to 10). Not used yet, eventually remove. -}; - - -/** - * Helper-function to merge custom-highlighting variant-lists. - * - * @param strings A list of strings that should be merged - * @param highlights One variant-list for highlighting, as described in the kde header ktextedtor/codecompletionmodel.h - * @param gapBetweenStrings How many signs are inserted between 2 strings? - * */ -QList mergeCustomHighlighting( QStringList strings, QList highlights, int gapBetweenStrings = 0 ); -#endif diff --git a/part/completion/kateargumenthintmodel.cpp b/part/completion/kateargumenthintmodel.cpp deleted file mode 100644 index 118cdf8..0000000 --- a/part/completion/kateargumenthintmodel.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateargumenthintmodel.h" - -#include -#include -#include - -#include -#include "katecompletionwidget.h" -#include "kateargumenthinttree.h" -#include "katecompletiontree.h" - -using namespace KTextEditor; - -void KateArgumentHintModel::clear() { - m_rows.clear(); - clearExpanding(); -} - -QModelIndex KateArgumentHintModel::mapToSource( const QModelIndex & index ) const { - if( index.row() < 0 || index.row() >= m_rows.count() ) - return QModelIndex(); - - if( m_rows[index.row()] < 0 || m_rows[index.row()] >= group()->filtered.count() ) - return QModelIndex(); - - KateCompletionModel::ModelRow source = group()->filtered[m_rows[index.row()]].sourceRow(); - if( !source.first ) { - kDebug( 13035 ) << "KateArgumentHintModel::data: Row does not exist in source"; - return QModelIndex(); - } - - QModelIndex sourceIndex = source.second.sibling(source.second.row(), index.column()); - - return sourceIndex; -} - -void KateArgumentHintModel::parentModelReset() { - clear(); - buildRows(); -} - -void KateArgumentHintModel::buildRows() { - m_rows.clear(); - QMap > m_depths; //Map each hint-depth to a list of functions of that depth - for( int a = 0; a < group()->filtered.count(); a++ ) { - KateCompletionModel::ModelRow source = group()->filtered[a].sourceRow(); - QModelIndex sourceIndex = source.second.sibling(source.second.row(), 0); - QVariant v = sourceIndex.data(CodeCompletionModel::ArgumentHintDepth); - if( v.type() == QVariant::Int ) { - QList& lst( m_depths[v.toInt()] ); - lst << a; - } - } - - for( QMap >::const_iterator it = m_depths.constBegin(); it != m_depths.constEnd(); ++it ) { - foreach( int row, *it ) - m_rows.push_front(row);//Insert filtered in reversed order - m_rows.push_front( -it.key() ); - } - - reset(); - emit contentStateChanged(!m_rows.isEmpty()); -} - -KateArgumentHintModel::KateArgumentHintModel( KateCompletionWidget* parent ) : ExpandingWidgetModel(parent), m_parent(parent) { - connect(parent->model(), SIGNAL(modelReset()), this, SLOT(parentModelReset())); - connect(parent->model(), SIGNAL(argumentHintsChanged()), this, SLOT(parentModelReset())); -} - -QVariant KateArgumentHintModel::data ( const QModelIndex & index, int role ) const { - if( index.row() < 0 || index.row() >= m_rows.count() ) { - //kDebug( 13035 ) << "KateArgumentHintModel::data: index out of bound: " << index.row() << " total filtered: " << m_rows.count(); - return QVariant(); - } - - if( m_rows[index.row()] < 0 ) { - //Show labels - if( role == Qt::DisplayRole && index.column() == 0 ) { - return QString(); //QString("Depth %1").arg(-m_rows[index.row()]); - } else if( role == Qt::BackgroundRole ) { - return KApplication::kApplication()->palette().toolTipBase().color(); - }else if( role == Qt::ForegroundRole ) { - return KApplication::kApplication()->palette().toolTipText().color(); - }else{ - return QVariant(); - } - } - - if( m_rows[index.row()] < 0 || m_rows[index.row()] >= group()->filtered.count() ) { - kDebug( 13035 ) << "KateArgumentHintModel::data: index out of bound: " << m_rows[index.row()] << " total filtered: " << group()->filtered.count(); - return QVariant(); - } - - KateCompletionModel::ModelRow source = group()->filtered[m_rows[index.row()]].sourceRow(); - if( !source.first ) { - kDebug( 13035 ) << "KateArgumentHintModel::data: Row does not exist in source"; - return QVariant(); - } - - if( index.column() == 0 ) { - switch( role ) { - case Qt::DecorationRole: - { - //Show the expand-handle - model()->cacheIcons(); - - if( !isExpanded(index ) ) - return QVariant( model()->m_collapsedIcon ); - else - return QVariant( model()->m_expandedIcon ); - } - case Qt::DisplayRole: - //Ignore text in the first column(we create our own compound text in the second) - return QVariant(); - } - } - - QModelIndex sourceIndex = source.second.sibling(source.second.row(), index.column()); - - if( !sourceIndex.isValid() ) { - kDebug( 13035 ) << "KateArgumentHintModel::data: Source-index is not valid"; - return QVariant(); - } - - switch( role ) { - case Qt::DisplayRole: - { - //Construct the text - QString totalText; - for( int a = CodeCompletionModel::Prefix; a <= CodeCompletionModel::Postfix; a++ ) - if( a != CodeCompletionModel::Scope ) //Skip the scope - totalText += source.second.sibling(source.second.row(), a).data(Qt::DisplayRole).toString() + ' '; - - - return QVariant(totalText); - } - case CodeCompletionModel::HighlightingMethod: - { - //Return that we are doing custom-highlighting of one of the sub-strings does it - for( int a = CodeCompletionModel::Prefix; a <= CodeCompletionModel::Postfix; a++ ) { - QVariant method = source.second.sibling(source.second.row(), a).data(CodeCompletionModel::HighlightingMethod); - if( method.type() == QVariant::Int && method.toInt() == CodeCompletionModel::CustomHighlighting) - return QVariant(CodeCompletionModel::CustomHighlighting); - } - - return QVariant(); - } - case CodeCompletionModel::CustomHighlight: - { - QStringList strings; - - //Collect strings - for( int a = CodeCompletionModel::Prefix; a <= CodeCompletionModel::Postfix; a++ ) - strings << source.second.sibling(source.second.row(), a).data(Qt::DisplayRole).toString(); - - QList highlights; - - //Collect custom-highlightings - for( int a = CodeCompletionModel::Prefix; a <= CodeCompletionModel::Postfix; a++ ) - highlights << source.second.sibling(source.second.row(), a).data(CodeCompletionModel::CustomHighlight).toList(); - - //Replace invalid QTextFormats with match-quality color or yellow. - for( QList::iterator it = highlights.begin(); it != highlights.end(); ++it ) - { - QVariantList& list( *it ); - - for( int a = 2; a < list.count(); a += 3 ) - { - if( list[a].canConvert() ) - { - QTextFormat f = list[a].value(); - - if(!f.isValid()) - { - f = QTextFormat( QTextFormat::CharFormat ); - uint color = matchColor( index ); - - if( color ) - f.setBackground( QBrush(color) ); - else - f.setBackground( Qt::yellow ); - - list[a] = QVariant( f ); - } - } - } - } - - - return mergeCustomHighlighting( strings, highlights, 1 ); - } - case Qt::DecorationRole: - { - //Redirect the decoration to the decoration of the item-column - return source.second.sibling(source.second.row(), CodeCompletionModel::Icon).data(role); - } - } - - QVariant v = ExpandingWidgetModel::data( index, role ); - if( v.isValid() ) - return v; - else - return sourceIndex.data( role ); -} - -int KateArgumentHintModel::rowCount ( const QModelIndex & parent ) const { - if( !parent.isValid() ) - return m_rows.count(); - else - return 0; -} - -int KateArgumentHintModel::columnCount ( const QModelIndex & /*parent*/ ) const { - return 2; //2 Columns, one for the expand-handle, one for the signature -} - -KateCompletionModel::Group* KateArgumentHintModel::group() const { - return model()->m_argumentHints; -} - -KateCompletionModel* KateArgumentHintModel::model() const { - return m_parent->model(); -} - -QTreeView* KateArgumentHintModel::treeView() const { - return m_parent->argumentHintTree(); -} - -void KateArgumentHintModel::emitDataChanged( const QModelIndex& start, const QModelIndex& end ) { - emit dataChanged(start, end); -} - -bool KateArgumentHintModel::indexIsItem(const QModelIndex& index) const { - return index.row() >= 0 && index.row() < m_rows.count() && m_rows[index.row()] >= 0; -} - -int KateArgumentHintModel::contextMatchQuality(const QModelIndex& index) const { - int row=index.row(); - if( row < 0 || row >= m_rows.count() ) - return -1; - - if( m_rows[row] < 0 || m_rows[row] >= group()->filtered.count() ) - return -1; //Probably a label - - KateCompletionModel::ModelRow source = group()->filtered[m_rows[row]].sourceRow(); - if( !source.first ) - return -1; - - QModelIndex sourceIndex = source.second.sibling(source.second.row(), 0); - - if( !sourceIndex.isValid() ) - return -1; - - int depth = sourceIndex.data(CodeCompletionModel::ArgumentHintDepth).toInt(); - - switch(depth) { - case 1: - { - //This argument-hint is on the lowest level, match it with the currently selected item in the completion-widget - QModelIndex row = m_parent->treeView()->currentIndex(); - if( !row.isValid() ) - return -1; - - QModelIndex selectedIndex = m_parent->model()->mapToSource( row ); - if( !selectedIndex.isValid() ) - return -1; - - if( selectedIndex.model() != sourceIndex.model() ) - return -1; //We can only match items from the same source-model - - sourceIndex.data( CodeCompletionModel::SetMatchContext ); - - QVariant v = selectedIndex.data( CodeCompletionModel::MatchQuality ); - if( v.type() == QVariant::Int ) - return v.toInt(); - } - break; - default: - //Do some other nice matching here in future - break; - } - - return -1; -} - -#include "kateargumenthintmodel.moc" diff --git a/part/completion/kateargumenthintmodel.h b/part/completion/kateargumenthintmodel.h deleted file mode 100644 index 90b4a47..0000000 --- a/part/completion/kateargumenthintmodel.h +++ /dev/null @@ -1,67 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATEARGUMENTHINTMODEL_H -#define KATEARGUMENTHINTMODEL_H - -#include -#include "katecompletionmodel.h" -#include "expandingtree/expandingwidgetmodel.h" - -class KateCompletionWidget; - -class KateArgumentHintModel : public ExpandingWidgetModel { - Q_OBJECT - public: - KateArgumentHintModel( KateCompletionWidget* parent ); - - virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; - - virtual int rowCount ( const QModelIndex & parent ) const; - - virtual int columnCount ( const QModelIndex & /*parent*/ ) const; - - virtual QTreeView* treeView() const; - - virtual bool indexIsItem(const QModelIndex& index) const; - - void emitDataChanged( const QModelIndex& start, const QModelIndex& end ); - - //Returns the index in the source-model for an index within this model - QModelIndex mapToSource( const QModelIndex & proxyIndex ) const; - - void buildRows(); - void clear(); - protected: - virtual int contextMatchQuality(const QModelIndex& row) const; - public slots: - void parentModelReset(); - signals: - void contentStateChanged(bool hasContent); - private: - KateCompletionModel::Group* group() const; - KateCompletionModel* model() const; - - QList m_rows; //Maps rows to either a positive row-number in the source group, or to a negative number which indicates a label - - KateCompletionWidget* m_parent; -}; - -#endif diff --git a/part/completion/kateargumenthinttree.cpp b/part/completion/kateargumenthinttree.cpp deleted file mode 100644 index ad5702d..0000000 --- a/part/completion/kateargumenthinttree.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateargumenthinttree.h" - -#include -#include -#include -#include - -#include "kateargumenthintmodel.h" -#include "katecompletionwidget.h" -#include "expandingtree/expandingwidgetmodel.h" -#include "katecompletiondelegate.h" -#include "kateview.h" -#include - - -KateArgumentHintTree::KateArgumentHintTree( KateCompletionWidget* parent ) : ExpandingTree(0), m_parent(parent) { //Do not use the completion-widget as widget-parent, because the argument-hint-tree will be rendered separately - - setFrameStyle( QFrame::Box | QFrame::Plain ); - setLineWidth( 1 ); - - connect( parent, SIGNAL(destroyed(QObject*)), this, SLOT(deleteLater()) ); - setFrameStyle(QFrame::NoFrame); - setFrameStyle( QFrame::Box | QFrame::Plain ); - setFocusPolicy(Qt::NoFocus); - setWindowFlags(Qt::Tool | Qt::FramelessWindowHint); - setUniformRowHeights(false); - setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - header()->hide(); - setRootIsDecorated(false); - setIndentation(0); - setAllColumnsShowFocus(true); - setAlternatingRowColors(true); - setItemDelegate(new KateCompletionDelegate(parent->argumentHintModel(), parent)); -} - -void KateArgumentHintTree::clearCompletion() { - setCurrentIndex(QModelIndex()); -} - -KateArgumentHintModel* KateArgumentHintTree::model() const { - return m_parent->argumentHintModel(); -} - -void KateArgumentHintTree::paintEvent ( QPaintEvent * event ) { - QTreeView::paintEvent(event); - updateGeometry(); ///@todo delay this. It is needed here, because visualRect(...) returns an invalid rect in updateGeometry before the content is painted -} - -void KateArgumentHintTree::dataChanged ( const QModelIndex & topLeft, const QModelIndex & bottomRight ) { - QTreeView::dataChanged(topLeft,bottomRight); - //updateGeometry(); -} - -void KateArgumentHintTree::currentChanged ( const QModelIndex & current, const QModelIndex & previous ) { -/* kDebug( 13035 ) << "currentChanged()";*/ - static_cast(model())->rowSelected(current); - QTreeView::currentChanged(current, previous); -} - -void KateArgumentHintTree::rowsInserted ( const QModelIndex & parent, int start, int end ) { - QTreeView::rowsInserted(parent, start, end); - updateGeometry(); -} - -int KateArgumentHintTree::sizeHintForColumn(int column) const { - return QTreeView::sizeHintForColumn(column); -} - -unsigned int KateArgumentHintTree::rowHeight(const QModelIndex& index) const { - uint max = sizeHintForIndex(index).height(); - - for(int a = 0; a < index.model()->columnCount(index.parent()); ++a) { - QModelIndex i = index.sibling(index.row(), a); - uint cSize = sizeHintForIndex(i).height(); - if(cSize > max) - max = cSize; - } - return max; -} - -void KateArgumentHintTree::updateGeometry(QRect geom) { - //Avoid recursive calls of updateGeometry - static bool updatingGeometry = false; - if( updatingGeometry ) return; - updatingGeometry = true; - - if( model()->rowCount(QModelIndex()) == 0 ) { -/* kDebug( 13035 ) << "KateArgumentHintTree:: empty model";*/ - hide(); - setGeometry(geom); - updatingGeometry = false; - return; - } - - int bottom = geom.bottom(); - int totalWidth = resizeColumns(); - int totalHeight = 0; - for(int a = 0; a < model()->rowCount( QModelIndex() ); ++a) { - QModelIndex index(model()->index(a, 0)); - totalHeight += rowHeight(index); - for(int b = 0; b < model()->rowCount(index); ++b) { - QModelIndex childIndex = index.child(b, 0); - totalHeight += rowHeight(childIndex); - } - } - - totalHeight += frameWidth()*2; - - QRect topRect = visualRect(model()->index(0, 0)); - QRect contentRect = visualRect(model()->index(model()->rowCount(QModelIndex())-1, 0)); - - geom.setHeight(totalHeight); - - geom.moveBottom(bottom); -// if( totalWidth > geom.width() ) - geom.setWidth(totalWidth); - - bool enableScrollBars = false; - - //Resize and move so it fits the screen horizontally - int maxWidth = (QApplication::desktop()->screenGeometry(m_parent->view()).width()*3)/4; - if( geom.width() > maxWidth ) { - geom.setWidth(maxWidth); - geom.setHeight(geom.height() + horizontalScrollBar()->height() +2); - geom.moveBottom(bottom); - enableScrollBars = true; - } - - if (geom.right() > QApplication::desktop()->screenGeometry(m_parent->view()).right()) - geom.moveRight( QApplication::desktop()->screenGeometry(m_parent->view()).right() ); - - if( geom.left() < QApplication::desktop()->screenGeometry(m_parent->view()).left() ) - geom.moveLeft(QApplication::desktop()->screenGeometry(m_parent->view()).left()); - - //Resize and move so it fits the screen vertically - bool resized = false; - if( geom.top() < QApplication::desktop()->screenGeometry(this).top() ) { - int offset = QApplication::desktop()->screenGeometry(this).top() - geom.top(); - geom.setBottom( geom.bottom() - offset ); - geom.moveTo(geom.left(), QApplication::desktop()->screenGeometry(this).top()); - resized = true; - } - - if(geom != geometry()) - { - setUpdatesEnabled(false); - setAnimated(false); - - setHorizontalScrollBarPolicy( enableScrollBars ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff ); - - /* kDebug( 13035 ) << "KateArgumentHintTree::updateGeometry: updating geometry to " << geom;*/ - setGeometry(geom); - - if( resized && currentIndex().isValid() ) - scrollTo(currentIndex()); - - setUpdatesEnabled(true); - } - - updatingGeometry = false; -} - -int KateArgumentHintTree::resizeColumns() { - int totalSize = 0; - for( int a = 0; a < header()->count(); a++ ) { - int columnSize = sizeHintForColumn(a); - setColumnWidth(a, columnSize); - totalSize += columnSize; - } - return totalSize; -} - -void KateArgumentHintTree::updateGeometry() { - updateGeometry( geometry() ); -} - -bool KateArgumentHintTree::nextCompletion() -{ - QModelIndex current; - QModelIndex firstCurrent = currentIndex(); - - do { - QModelIndex oldCurrent = currentIndex(); - - current = moveCursor(MoveDown, Qt::NoModifier); - - if (current != oldCurrent && current.isValid()) { - setCurrentIndex(current); - - } else { - if (firstCurrent.isValid()) - setCurrentIndex(firstCurrent); - return false; - } - - } while (!model()->indexIsItem(current)); - - return true; -} - -bool KateArgumentHintTree::previousCompletion() -{ - QModelIndex current; - QModelIndex firstCurrent = currentIndex(); - - do { - QModelIndex oldCurrent = currentIndex(); - - current = moveCursor(MoveUp, Qt::NoModifier); - - if (current != oldCurrent && current.isValid()) { - setCurrentIndex(current); - - } else { - if (firstCurrent.isValid()) - setCurrentIndex(firstCurrent); - return false; - } - - } while (!model()->indexIsItem(current)); - - return true; -} - -bool KateArgumentHintTree::pageDown( ) -{ - QModelIndex old = currentIndex(); - QModelIndex current = moveCursor(MovePageDown, Qt::NoModifier); - - if (current.isValid()) { - setCurrentIndex(current); - if (!model()->indexIsItem(current)) - if (!nextCompletion()) - previousCompletion(); - } - - return current != old; -} - -bool KateArgumentHintTree::pageUp( ) -{ - QModelIndex old = currentIndex(); - QModelIndex current = moveCursor(MovePageUp, Qt::NoModifier); - - if (current.isValid()) { - setCurrentIndex(current); - if (!model()->indexIsItem(current)) - if (!previousCompletion()) - nextCompletion(); - } - return current != old; -} - -void KateArgumentHintTree::top( ) -{ - QModelIndex current = moveCursor(MoveHome, Qt::NoModifier); - setCurrentIndex(current); - - if (current.isValid()) { - setCurrentIndex(current); - if (!model()->indexIsItem(current)) - nextCompletion(); - } -} - -void KateArgumentHintTree::bottom( ) -{ - QModelIndex current = moveCursor(MoveEnd, Qt::NoModifier); - setCurrentIndex(current); - - if (current.isValid()) { - setCurrentIndex(current); - if (!model()->indexIsItem(current)) - previousCompletion(); - } -} - -#include "kateargumenthinttree.moc" diff --git a/part/completion/kateargumenthinttree.h b/part/completion/kateargumenthinttree.h deleted file mode 100644 index 4073255..0000000 --- a/part/completion/kateargumenthinttree.h +++ /dev/null @@ -1,63 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATEARGUMENTHINTTREE_H -#define KATEARGUMENTHINTTREE_H - -#include "expandingtree/expandingtree.h" - -class KateCompletionWidget; -class KateArgumentHintModel; -class QRect; - -class KateArgumentHintTree : public ExpandingTree { - Q_OBJECT - public: - KateArgumentHintTree( KateCompletionWidget* parent ); - - // Navigation - bool nextCompletion(); - bool previousCompletion(); - bool pageDown(); - bool pageUp(); - void top(); - void bottom(); - - //Returns the total size of all columns - int resizeColumns(); - - void clearCompletion(); - public slots: - void updateGeometry(); - void updateGeometry(QRect rect); - protected: - virtual void paintEvent ( QPaintEvent * event ); - virtual void rowsInserted ( const QModelIndex & parent, int start, int end ); - virtual void dataChanged ( const QModelIndex & topLeft, const QModelIndex & bottomRight ); - virtual void currentChanged ( const QModelIndex & current, const QModelIndex & previous ); - private: - uint rowHeight(const QModelIndex& index) const; - KateArgumentHintModel* model() const; - virtual int sizeHintForColumn ( int column ) const; - - KateCompletionWidget* m_parent; -}; - -#endif diff --git a/part/completion/katecompletionconfig.cpp b/part/completion/katecompletionconfig.cpp deleted file mode 100644 index 9d7dd20..0000000 --- a/part/completion/katecompletionconfig.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecompletionconfig.h" - -#include - -#include -#include - -#include "katecompletionmodel.h" - -#include "ui_completionconfigwidget.h" - -using namespace KTextEditor; - -KateCompletionConfig::KateCompletionConfig(KateCompletionModel* model, QWidget* parent) - : KDialog(parent) - , ui(new Ui::CompletionConfigWidget()) - , m_model(model) -{ - //setAttribute(Qt::WA_DestructiveClose); - setCaption(i18n("Code Completion Configuration")); - setButtons(KDialog::Ok | KDialog::Cancel); - setDefaultButton(KDialog::Ok); - connect(this, SIGNAL(okClicked()), SLOT(apply())); - - QWidget* mw = new QWidget(this); - ui->setupUi(mw); - setMainWidget(mw); - - // Sorting - ui->sorting->setChecked(m_model->isSortingEnabled()); - ui->sortingAlphabetical->setChecked(m_model->isSortingAlphabetical()); - ui->sortingCaseSensitive->setChecked(m_model->sortingCaseSensitivity() == Qt::CaseSensitive); - ui->groupingOrderUp->setIcon(KIcon("go-up")); - ui->groupingOrderDown->setIcon(KIcon("go-down")); - connect(ui->groupingOrderUp, SIGNAL(pressed()), SLOT(moveGroupingOrderUp())); - connect(ui->groupingOrderDown, SIGNAL(pressed()), SLOT(moveGroupingOrderDown())); - - // Filtering - ui->filtering->setChecked(m_model->isFilteringEnabled()); - ui->filteringContextMatchOnly->setChecked(m_model->filterContextMatchesOnly()); - ui->filteringHideAttributes->setChecked(m_model->filterByAttribute()); - - for (CodeCompletionModel::CompletionProperty i = CodeCompletionModel::FirstProperty; i <= CodeCompletionModel::LastProperty; i = static_cast(i << 1)) { - QListWidgetItem* item = new QListWidgetItem(m_model->propertyName(i), ui->filteringAttributesList, i); - item->setCheckState((m_model->filterAttributes() & i) ? Qt::Checked : Qt::Unchecked); - } - - ui->filteringMaximumInheritanceDepth->setValue(m_model->maximumInheritanceDepth()); - - // Grouping - ui->grouping->setChecked(m_model->isGroupingEnabled()); - ui->groupingUp->setIcon(KIcon("go-up")); - ui->groupingDown->setIcon(KIcon("go-down")); - - m_groupingScopeType = ui->groupingMethods->topLevelItem(0); - m_groupingScopeType->setCheckState(0, (m_model->groupingMethod() & KateCompletionModel::ScopeType) ? Qt::Checked : Qt::Unchecked); - - m_groupingScope = ui->groupingMethods->topLevelItem(1); - m_groupingScope->setCheckState(0, (m_model->groupingMethod() & KateCompletionModel::Scope) ? Qt::Checked : Qt::Unchecked); - - m_groupingAccessType = ui->groupingMethods->topLevelItem(2); - m_groupingAccessType->setCheckState(0, (m_model->groupingMethod() & KateCompletionModel::AccessType) ? Qt::Checked : Qt::Unchecked); - - m_groupingItemType = ui->groupingMethods->topLevelItem(3); - m_groupingItemType->setCheckState(0, (m_model->groupingMethod() & KateCompletionModel::ItemType) ? Qt::Checked : Qt::Unchecked); - - ui->accessConst->setChecked(m_model->accessIncludeConst()); - ui->accessStatic->setChecked(m_model->accessIncludeStatic()); - ui->accessSignalSlot->setChecked(m_model->accessIncludeSignalSlot()); - - for (int i = 0; i < 4; ++i) - ui->groupingMethods->topLevelItem(i)->setCheckState(0, Qt::Unchecked); - connect(ui->groupingUp, SIGNAL(pressed()), SLOT(moveGroupingUp())); - connect(ui->groupingDown, SIGNAL(pressed()), SLOT(moveGroupingDown())); - - // Column merging - ui->columnMerging->setChecked(m_model->isColumnMergingEnabled()); - ui->columnUp->setIcon(KIcon("go-up")); - ui->columnDown->setIcon(KIcon("go-down")); - connect(ui->columnUp, SIGNAL(pressed()), SLOT(moveColumnUp())); - connect(ui->columnDown, SIGNAL(pressed()), SLOT(moveColumnDown())); - - - QList mergedColumns; - if (!m_model->columnMerges().isEmpty()) { - foreach (const QList& list, m_model->columnMerges()) { - bool first = true; - foreach (int column, list) { - QTreeWidgetItem* item = new QTreeWidgetItem(ui->columnMergeTree, column); - item->setText(0, KateCompletionModel::columnName(column) + QString(" %1").arg(column)); - item->setCheckState(1, first ? Qt::Unchecked : Qt::Checked); - - if (column == KTextEditor::CodeCompletionModel::Name) - item->setText(2, i18n("Always")); - else - item->setCheckState(2, Qt::Checked); - - first = false; - mergedColumns << column; - } - } - - for (int column = 0; column < KTextEditor::CodeCompletionModel::ColumnCount; ++column) { - if (!mergedColumns.contains(column)) { - QTreeWidgetItem* item = new QTreeWidgetItem(ui->columnMergeTree, column); - item->setText(0, KateCompletionModel::columnName(column) + QString(" %1").arg(column)); - item->setCheckState(1, Qt::Unchecked); - - Q_ASSERT(column != KTextEditor::CodeCompletionModel::Name); - - item->setCheckState(2, Qt::Unchecked); - } - } - - } else { - for (int column = 0; column < KTextEditor::CodeCompletionModel::ColumnCount; ++column) { - QTreeWidgetItem* item = new QTreeWidgetItem(ui->columnMergeTree, column); - item->setText(0, KateCompletionModel::columnName(column) + QString(" %1").arg(column)); - item->setCheckState(1, Qt::Unchecked); - - if (column == KTextEditor::CodeCompletionModel::Name) - item->setText(2, i18n("Always")); - else - item->setCheckState(2, Qt::Checked); - } - } - - // init with defaults from config or really hardcoded ones - KConfigGroup config( KGlobal::config(), "Kate Code Completion Defaults"); - readConfig (config); -} - -KateCompletionConfig::~ KateCompletionConfig( ) -{ - delete ui; -} - -void KateCompletionConfig::readConfig(const KConfigGroup &config) -{ - configStart (); - - // Sorting - ui->sorting->setChecked(config.readEntry("Sorting Enabled", true)); - ui->sortingAlphabetical->setChecked(config.readEntry("Sort Alphabetically", true)); - ui->sortingCaseSensitive->setChecked(config.readEntry("Case Sensitive Sort", false)); - ui->sortingInheritanceDepth->setChecked(config.readEntry("Sort by Inheritance Depth", true)); - - // Filtering - ui->filtering->setChecked(config.readEntry("Filtering Enabled", false)); - ui->filteringContextMatchOnly->setChecked(config.readEntry("Filter by Context Match Only", false)); - ui->filteringHideAttributes->setChecked(config.readEntry("Hide Completions by Attribute", false)); - - int attributes = config.readEntry("Filter Attribute Mask", 0); - for (int i = 0; i < ui->filteringAttributesList->count(); ++i) { - QListWidgetItem* item = ui->filteringAttributesList->item(i); - item->setCheckState(((1 << (i - 1)) & attributes) ? Qt::Checked : Qt::Unchecked); - } - - ui->filteringMaximumInheritanceDepth->setValue(config.readEntry("Filter by Maximum Inheritance Depth", 0)); - - // Grouping - ui->grouping->setChecked(config.readEntry("Grouping Enabled", true)); - - m_groupingScopeType->setCheckState(0, config.readEntry("Group by Scope Type", true) ? Qt::Checked : Qt::Unchecked); - m_groupingScope->setCheckState(0, config.readEntry("Group by Scope", false) ? Qt::Checked : Qt::Unchecked); - m_groupingAccessType->setCheckState(0, config.readEntry("Group by Access Type", true) ? Qt::Checked : Qt::Unchecked); - m_groupingItemType->setCheckState(0, config.readEntry("Group by Item Type", false) ? Qt::Checked : Qt::Unchecked); - - ui->accessConst->setChecked(config.readEntry("Group by Const", false)); - ui->accessStatic->setChecked(config.readEntry("Group by Static", false)); - ui->accessSignalSlot->setChecked(config.readEntry("Group by Signals and Slots", false)); - - // Column merging - ui->columnMerging->setChecked(config.readEntry("Column Merging Enabled", true)); - - for (int i = 0; i < ui->columnMergeTree->topLevelItemCount(); ++i) { - QTreeWidgetItem* item = ui->columnMergeTree->topLevelItem(i); - ///Initialize a standard column-merging: Merge Scope, Name, Arguments and Postfix - item->setCheckState(1, config.readEntry(QString("Column %1 Merge").arg(i), (i == CodeCompletionModel::Scope || i == CodeCompletionModel::Name || i == CodeCompletionModel::Arguments)) ? Qt::Checked : Qt::Unchecked); - item->setCheckState(2, config.readEntry(QString("Column %1 Show").arg(i), true) ? Qt::Checked : Qt::Unchecked); - } - - applyInternal(); - - configEnd(); -} - -void KateCompletionConfig::writeConfig(KConfigGroup &config) -{ - // Sorting - config.writeEntry("Sorting Enabled", ui->sorting->isChecked()); - config.writeEntry("Sort Alphabetically", ui->sortingAlphabetical->isChecked()); - config.writeEntry("Case Sensitive Sort", ui->sortingCaseSensitive->isChecked()); - config.writeEntry("Sort by Inheritance Depth", ui->sortingInheritanceDepth->isChecked()); - - // Filtering - config.writeEntry("Filtering Enabled", ui->filtering->isChecked()); - config.writeEntry("Filter by Context Match Only", ui->filteringContextMatchOnly->isChecked()); - config.writeEntry("Hide Completions by Attribute", ui->filteringHideAttributes->isChecked()); - - int attributes = 0; - for (int i = 0; i < ui->filteringAttributesList->count(); ++i) { - QListWidgetItem* item = ui->filteringAttributesList->item(i); - if (item->checkState() == Qt::Checked) - attributes |= 1 << (i - 1); - } - config.writeEntry("Filter Attribute Mask", attributes); - - config.writeEntry("Filter by Maximum Inheritance Depth", ui->filteringMaximumInheritanceDepth->value()); - - // Grouping - config.writeEntry("Grouping Enabled", ui->grouping->isChecked()); - - config.writeEntry("Group by Scope Type", m_groupingScopeType->checkState(0) == Qt::Checked ? true : false); - config.writeEntry("Group by Scope", m_groupingScope->checkState(0) == Qt::Checked ? true : false); - config.writeEntry("Group by Access Type", m_groupingAccessType->checkState(0) == Qt::Checked ? true : false); - config.writeEntry("Group by Item Type", m_groupingItemType->checkState(0) == Qt::Checked ? true : false); - - config.writeEntry("Group by Const", ui->accessConst->isChecked()); - config.writeEntry("Group by Static", ui->accessStatic->isChecked()); - config.writeEntry("Group by Signals and Slots", ui->accessSignalSlot->isChecked()); - - // Column merging - config.writeEntry("Column Merging Enabled", ui->columnMerging->isChecked()); - - for (int i = 0; i < ui->columnMergeTree->topLevelItemCount(); ++i) { - QTreeWidgetItem* item = ui->columnMergeTree->topLevelItem(i); - config.writeEntry(QString("Column %1 Merge").arg(i), item->checkState(1) == Qt::Checked ? true : false); - config.writeEntry(QString("Column %1 Show").arg(i), item->checkState(2) == Qt::Checked ? true : false); - } - - config.sync(); -} - -void KateCompletionConfig::updateConfig() -{ - // Ah, nothing to do, I think...? -} - -void KateCompletionConfig::moveColumnUp( ) -{ - QTreeWidgetItem* item = ui->columnMergeTree->currentItem(); - if (item) { - int index = ui->columnMergeTree->indexOfTopLevelItem(item); - if (index > 0) { - ui->columnMergeTree->takeTopLevelItem(index); - ui->columnMergeTree->insertTopLevelItem(index - 1, item); - ui->columnMergeTree->setCurrentItem(item); - } - } -} - -void KateCompletionConfig::moveColumnDown( ) -{ - QTreeWidgetItem* item = ui->columnMergeTree->currentItem(); - if (item) { - int index = ui->columnMergeTree->indexOfTopLevelItem(item); - if (index < ui->columnMergeTree->topLevelItemCount() - 1) { - ui->columnMergeTree->takeTopLevelItem(index); - ui->columnMergeTree->insertTopLevelItem(index + 1, item); - ui->columnMergeTree->setCurrentItem(item); - } - } -} - -void KateCompletionConfig::apply( ) -{ - applyInternal(); - - KConfigGroup config( KGlobal::config(), "Kate Code Completion Defaults"); - writeConfig (config); -} - -void KateCompletionConfig::applyInternal() -{ - // Sorting - m_model->setSortingEnabled(ui->sorting->isChecked()); - m_model->setSortingAlphabetical(ui->sortingAlphabetical->isChecked()); - m_model->setSortingCaseSensitivity(ui->sortingCaseSensitive->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive); - m_model->setSortingByInheritanceDepth(ui->sortingInheritanceDepth->isChecked()); - - // Filtering - m_model->setFilteringEnabled(ui->filtering->isChecked()); - - m_model->setFilterContextMatchesOnly(ui->filteringContextMatchOnly->isChecked()); - m_model->setFilterByAttribute(ui->filteringHideAttributes->isChecked()); - - CodeCompletionModel::CompletionProperties attributes = 0; - for (int i = 0; i < ui->filteringAttributesList->count(); ++i) { - QListWidgetItem* item = ui->filteringAttributesList->item(i); - if (item->checkState() == Qt::Checked) - attributes |= static_cast(item->type()); - } - m_model->setFilterAttributes(attributes); - - m_model->setMaximumInheritanceDepth(ui->filteringMaximumInheritanceDepth->value()); - - // Grouping - m_model->setGroupingEnabled(ui->grouping->isChecked()); - - KateCompletionModel::GroupingMethods groupingMethod = 0; - if (m_groupingScopeType->checkState(0) == Qt::Checked) - groupingMethod = KateCompletionModel::ScopeType; - if (m_groupingScope->checkState(0) == Qt::Checked) - groupingMethod |= KateCompletionModel::Scope; - if (m_groupingAccessType->checkState(0) == Qt::Checked) - groupingMethod |= KateCompletionModel::AccessType; - if (m_groupingItemType->checkState(0) == Qt::Checked) - groupingMethod |= KateCompletionModel::ItemType; - m_model->setGroupingMethod(groupingMethod); - - m_model->setAccessIncludeConst(ui->accessConst->isChecked()); - m_model->setAccessIncludeStatic(ui->accessStatic->isChecked()); - m_model->setAccessIncludeSignalSlot(ui->accessSignalSlot->isChecked()); - - // Column merging - m_model->setColumnMergingEnabled(ui->columnMerging->isChecked()); - - QList< QList > mergedColumns; - QList oneMerge; - for (int i = 0; i < ui->columnMergeTree->topLevelItemCount(); ++i) { - QTreeWidgetItem* item = ui->columnMergeTree->topLevelItem(i); - - if (item->type() != KTextEditor::CodeCompletionModel::Name && item->checkState(2) == Qt::Unchecked) - continue; - - if (item->checkState(1) == Qt::Unchecked) { - if (oneMerge.count()) - mergedColumns.append(oneMerge); - oneMerge.clear(); - } - - oneMerge.append(item->type()); - } - - if (oneMerge.count()) - mergedColumns.append(oneMerge); - - m_model->setColumnMerges(mergedColumns); -} - -void KateCompletionConfig::moveGroupingUp( ) -{ - QTreeWidgetItem* item = ui->groupingMethods->currentItem(); - if (item) { - int index = ui->groupingMethods->indexOfTopLevelItem(item); - if (index > 0) { - ui->groupingMethods->takeTopLevelItem(index); - ui->groupingMethods->insertTopLevelItem(index - 1, item); - ui->groupingMethods->setCurrentItem(item); - } - } -} - -void KateCompletionConfig::moveGroupingDown( ) -{ - QTreeWidgetItem* item = ui->groupingMethods->currentItem(); - if (item) { - int index = ui->groupingMethods->indexOfTopLevelItem(item); - if (index < ui->groupingMethods->topLevelItemCount() - 1) { - ui->groupingMethods->takeTopLevelItem(index); - ui->groupingMethods->insertTopLevelItem(index + 1, item); - ui->groupingMethods->setCurrentItem(item); - } - } -} - -void KateCompletionConfig::moveGroupingOrderUp( ) -{ - QListWidgetItem* item = ui->sortGroupingOrder->currentItem(); - int index = ui->sortGroupingOrder->currentRow(); - if (index > 0) { - ui->sortGroupingOrder->takeItem(index); - ui->sortGroupingOrder->insertItem(index - 1, item); - ui->sortGroupingOrder->setCurrentItem(item); - } -} - -void KateCompletionConfig::moveGroupingOrderDown( ) -{ - QListWidgetItem* item = ui->sortGroupingOrder->currentItem(); - int index = ui->sortGroupingOrder->currentRow(); - if (index < ui->sortGroupingOrder->count() - 1) { - ui->sortGroupingOrder->takeItem(index); - ui->sortGroupingOrder->insertItem(index + 1, item); - ui->sortGroupingOrder->setCurrentItem(item); - } -} - -#include "katecompletionconfig.moc" diff --git a/part/completion/katecompletionconfig.h b/part/completion/katecompletionconfig.h deleted file mode 100644 index 452d94a..0000000 --- a/part/completion/katecompletionconfig.h +++ /dev/null @@ -1,80 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATECOMPLETIONCONFIG_H -#define KATECOMPLETIONCONFIG_H - -#include - -#include "kateconfig.h" - -namespace Ui { class CompletionConfigWidget; } - -class QTreeWidgetItem; -class KateCompletionModel; - -/** - * @author Hamish Rodda - */ -class KateCompletionConfig : public KDialog, public KateConfig -{ - Q_OBJECT - - public: - explicit KateCompletionConfig(KateCompletionModel* model, QWidget* parent = 0L); - virtual ~KateCompletionConfig(); - - /** - * Read config from object - */ - void readConfig (const KConfigGroup &config); - - /** - * Write config to object - */ - void writeConfig (KConfigGroup &config); - - public Q_SLOTS: - void apply(); - - protected: - virtual void updateConfig(); - - private Q_SLOTS: - void moveColumnUp(); - void moveColumnDown(); - void moveGroupingUp(); - void moveGroupingDown(); - void moveGroupingOrderUp(); - void moveGroupingOrderDown(); - - private: - void applyInternal(); - - Ui::CompletionConfigWidget* ui; - KateCompletionModel* m_model; - - QTreeWidgetItem* m_groupingScopeType; - QTreeWidgetItem* m_groupingScope; - QTreeWidgetItem* m_groupingAccessType; - QTreeWidgetItem* m_groupingItemType; -}; - -#endif diff --git a/part/completion/katecompletiondelegate.cpp b/part/completion/katecompletiondelegate.cpp deleted file mode 100644 index cdd0e93..0000000 --- a/part/completion/katecompletiondelegate.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecompletiondelegate.h" - -#include - -#include "katerenderer.h" -#include "katetextline.h" -#include "katedocument.h" -#include "kateview.h" -#include "katehighlight.h" -#include "katerenderrange.h" - -#include "katecompletionwidget.h" -#include "katecompletionmodel.h" -#include "katecompletiontree.h" - -//Currently disable because it doesn't work -#define DISABLE_INTERNAL_HIGHLIGHTING - -KateCompletionDelegate::KateCompletionDelegate(ExpandingWidgetModel* model, KateCompletionWidget* parent) : - ExpandingDelegate(model, parent), m_cachedRow(-1) -{ -} - -void KateCompletionDelegate::adjustStyle( const QModelIndex& index, QStyleOptionViewItem & option ) const { - if(index.column() == 0) { - //We always want to use the match-color if available, also for highlighted items. - ///@todo Only do this for the "current" item, for others the model is asked for the match color. - uint color = model()->matchColor(index); - if(color != 0) { - QColor match(color); - - for(int a = 0; a <=2; a++ ) - option.palette.setColor( (QPalette::ColorGroup)a, QPalette::Highlight, match ); - } - } -} - - -KateRenderer * KateCompletionDelegate::renderer( ) const -{ - return widget()->view()->renderer(); -} - -KateCompletionWidget * KateCompletionDelegate::widget( ) const -{ - return static_cast(const_cast(parent())); -} - -KateDocument * KateCompletionDelegate::document( ) const -{ - return widget()->view()->doc(); -} - -void KateCompletionDelegate::heightChanged() const { - if(parent()) - widget()->updateHeight(); -} - -QList KateCompletionDelegate::createHighlighting(const QModelIndex& index, QStyleOptionViewItem& option) const { - - QVariant highlight = model()->data(index, KTextEditor::CodeCompletionModel::HighlightingMethod); - - // TODO: config enable specifying no highlight as default - int highlightMethod = KTextEditor::CodeCompletionModel::InternalHighlighting; - if (highlight.canConvert(QVariant::Int)) - highlightMethod = highlight.toInt(); - - if (highlightMethod & KTextEditor::CodeCompletionModel::CustomHighlighting) { - m_currentColumnStart = 0; - return highlightingFromVariantList(model()->data(index, KTextEditor::CodeCompletionModel::CustomHighlight).toList()); - } - -#ifdef DISABLE_INTERNAL_HIGHLIGHTING - return QList(); -#endif - - if( index.row() == m_cachedRow && highlightMethod & KTextEditor::CodeCompletionModel::InternalHighlighting ) { - - if( index.column() < m_cachedColumnStarts.size() ) { - m_currentColumnStart = m_cachedColumnStarts[index.column()]; - } else { - kWarning() << "Column-count does not match"; - } - - return m_cachedHighlights; - } - - ///@todo reset the cache when the model changed - m_cachedRow = index.row(); - - KTextEditor::Cursor completionStart = widget()->completionRange()->start(); - - QString startText = document()->text(KTextEditor::Range(completionStart.line(), 0, completionStart.line(), completionStart.column())); - - QString lineContent = startText; - - int len = completionStart.column(); - m_cachedColumnStarts.clear(); - - for (int i = 0; i < KTextEditor::CodeCompletionModel::ColumnCount; ++i) { - m_cachedColumnStarts.append(len); - QString text = model()->data(model()->index(index.row(), i, index.parent()), Qt::DisplayRole).toString(); - lineContent += text; - len += text.length(); - } - - Kate::TextLine thisLine = Kate::TextLine (new Kate::TextLineData(lineContent)); - - //kDebug( 13035 ) << "About to highlight with mode " << highlightMethod << " text [" << thisLine->string() << "]"; - - if (highlightMethod & KTextEditor::CodeCompletionModel::InternalHighlighting) { - Kate::TextLine previousLine; - if (completionStart.line()) - previousLine = document()->kateTextLine(completionStart.line() - 1); - else - previousLine = Kate::TextLine (new Kate::TextLineData()); - - QVector foldingList; - bool ctxChanged = false; - document()->highlight()->doHighlight(previousLine.data(), thisLine.data(), foldingList, ctxChanged); - } - - m_currentColumnStart = m_cachedColumnStarts[index.column()]; - - NormalRenderRange rr; - QList ret = renderer()->decorationsForLine(thisLine, 0, false, &rr, option.state & QStyle::State_Selected); - - //Remove background-colors - for( QList::iterator it = ret.begin(); it != ret.end(); ++it ) - (*it).format.clearBackground(); - - return ret; -} - - diff --git a/part/completion/katecompletiondelegate.h b/part/completion/katecompletiondelegate.h deleted file mode 100644 index c526432..0000000 --- a/part/completion/katecompletiondelegate.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATECOMPLETIONDELEGATE_H -#define KATECOMPLETIONDELEGATE_H - -#include "expandingtree/expandingdelegate.h" - -class KateCompletionDelegate : public ExpandingDelegate { - public: - explicit KateCompletionDelegate(ExpandingWidgetModel* model, KateCompletionWidget* parent); - - KateRenderer* renderer() const; - KateCompletionWidget* widget() const; - KateDocument* document() const; - protected: - virtual void adjustStyle( const QModelIndex& index, QStyleOptionViewItem & option ) const; - mutable int m_cachedRow; - mutable QList m_cachedColumnStarts; - virtual void heightChanged() const; - QList createHighlighting(const QModelIndex& index, QStyleOptionViewItem& option) const; - -}; - -#endif diff --git a/part/completion/katecompletionmodel.cpp b/part/completion/katecompletionmodel.cpp deleted file mode 100644 index 64725e9..0000000 --- a/part/completion/katecompletionmodel.cpp +++ /dev/null @@ -1,2082 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005-2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecompletionmodel.h" - -#include -#include -#include - -#include -#include -#include - -#include "katecompletionwidget.h" -#include "katecompletiontree.h" -#include "katecompletiondelegate.h" -#include "kateargumenthintmodel.h" -#include "kateview.h" -#include "katerenderer.h" -#include "kateconfig.h" -#include - -using namespace KTextEditor; - -///A helper-class for handling completion-models with hierarchical grouping/optimization -class HierarchicalModelHandler { -public: - HierarchicalModelHandler(CodeCompletionModel* model); - void addValue(CodeCompletionModel::ExtraItemDataRoles role, const QVariant& value); - //Walks the index upwards and collects all defined completion-roles on the way - void collectRoles(const QModelIndex& index); - void takeRole(const QModelIndex& index); - - CodeCompletionModel* model() const; - - //Assumes that index is a sub-index of the indices where role-values were taken - QVariant getData(CodeCompletionModel::ExtraItemDataRoles role, const QModelIndex& index) const; - - bool hasHierarchicalRoles() const; - - int inheritanceDepth(const QModelIndex& i) const; - - QString customGroup() const { - return m_customGroup; - } - - int customGroupingKey() const { - return m_groupSortingKey; - } -private: - typedef QMap RoleMap; - RoleMap m_roleValues; - QString m_customGroup; - int m_groupSortingKey; - CodeCompletionModel* m_model; -}; - -CodeCompletionModel* HierarchicalModelHandler::model() const { - return m_model; -} - -bool HierarchicalModelHandler::hasHierarchicalRoles() const { - return !m_roleValues.isEmpty(); -} - -void HierarchicalModelHandler::collectRoles(const QModelIndex& index) { - if( index.parent().isValid() ) - collectRoles(index.parent()); - if(m_model->rowCount(index) != 0) - takeRole(index); -} - -int HierarchicalModelHandler::inheritanceDepth(const QModelIndex& i) const { - return getData(CodeCompletionModel::InheritanceDepth, i).toInt(); -} - -void HierarchicalModelHandler::takeRole(const QModelIndex& index) { - QVariant v = index.data(CodeCompletionModel::GroupRole); - if( v.isValid() && v.canConvert(QVariant::Int) ) { - QVariant value = index.data(v.toInt()); - if(v.toInt() == Qt::DisplayRole) { - m_customGroup = index.data(Qt::DisplayRole).toString(); - QVariant sortingKey = index.data(CodeCompletionModel::InheritanceDepth); - if(sortingKey.canConvert(QVariant::Int)) - m_groupSortingKey = sortingKey.toInt(); - }else{ - m_roleValues[(CodeCompletionModel::ExtraItemDataRoles)v.toInt()] = value; - } - }else{ - kDebug( 13035 ) << "Did not return valid GroupRole in hierarchical completion-model"; - } -} - -QVariant HierarchicalModelHandler::getData(CodeCompletionModel::ExtraItemDataRoles role, const QModelIndex& index) const { - RoleMap::const_iterator it = m_roleValues.find(role); - if( it != m_roleValues.end() ) - return *it; - else - return index.data(role); -} - -HierarchicalModelHandler::HierarchicalModelHandler(CodeCompletionModel* model) : m_groupSortingKey(-1), m_model(model) { -} - -void HierarchicalModelHandler::addValue(CodeCompletionModel::ExtraItemDataRoles role, const QVariant& value) { - m_roleValues[role] = value; -} - -KateCompletionModel::KateCompletionModel(KateCompletionWidget* parent) - : ExpandingWidgetModel(parent) - , m_hasGroups(false) - , m_matchCaseSensitivity(Qt::CaseInsensitive) - , m_ungrouped(new Group(this)) - , m_argumentHints(new Group(this)) - , m_bestMatches(new Group(this)) - , m_sortingEnabled(false) - , m_sortingAlphabetical(false) - , m_isSortingByInheritance(false) - , m_sortingCaseSensitivity(Qt::CaseInsensitive) - , m_filteringEnabled(false) - , m_filterContextMatchesOnly(false) - , m_filterByAttribute(false) - , m_filterAttributes(KTextEditor::CodeCompletionModel::NoProperty) - , m_maximumInheritanceDepth(0) - , m_groupingEnabled(false) - , m_accessConst(false) - , m_accessStatic(false) - , m_accesSignalSlot(false) - , m_columnMergingEnabled(false) -// , m_haveExactMatch(false) -{ - - m_ungrouped->attribute = 0; - m_argumentHints->attribute = -1; - m_bestMatches->attribute = BestMatchesProperty; - - m_argumentHints->title = i18n("Argument-hints"); - m_bestMatches->title = i18n("Best matches"); - - m_emptyGroups.append(m_ungrouped); - m_emptyGroups.append(m_argumentHints); - m_emptyGroups.append(m_bestMatches); - - m_updateBestMatchesTimer = new QTimer(this); - m_updateBestMatchesTimer->setSingleShot(true); - connect(m_updateBestMatchesTimer, SIGNAL(timeout()), this, SLOT(updateBestMatches())); - - m_groupHash.insert(0, m_ungrouped); - m_groupHash.insert(-1, m_argumentHints); - m_groupHash.insert(BestMatchesProperty, m_argumentHints); -} - -KateCompletionModel::~KateCompletionModel() { - clearCompletionModels(); - delete m_argumentHints; - delete m_ungrouped; - delete m_bestMatches; -} - -QTreeView* KateCompletionModel::treeView() const { - return view()->completionWidget()->treeView(); -} - -QVariant KateCompletionModel::data( const QModelIndex & index, int role ) const -{ - if (!hasCompletionModel() || !index.isValid()) - return QVariant(); - - if( role == Qt::DecorationRole && index.column() == KTextEditor::CodeCompletionModel::Prefix && isExpandable(index) ) - { - cacheIcons(); - - if( !isExpanded(index ) ) - return QVariant( m_collapsedIcon ); - else - return QVariant( m_expandedIcon ); - } - - //groupOfParent returns a group when the index is a member of that group, but not the group head/label. - if (!hasGroups() || groupOfParent(index)) { - switch (role) { - case Qt::TextAlignmentRole: - if (isColumnMergingEnabled() && m_columnMerges.count()) { - int c = 0; - foreach (const QList& list, m_columnMerges) { - foreach (int column, list) { - if (c++ == index.column()) { - if (column == CodeCompletionModel::Scope) - if (list.count() == 1) - return Qt::AlignRight; - - goto dontalign; - } - } - } - - } else if ((!isColumnMergingEnabled() || m_columnMerges.isEmpty()) && index.column() == CodeCompletionModel::Scope) { - return Qt::AlignRight; - } - - dontalign: - break; - } - - // Merge text for column merging - if (role == Qt::DisplayRole && m_columnMerges.count() && isColumnMergingEnabled()) { - QString text; - foreach (int column, m_columnMerges[index.column()]) { - QModelIndex sourceIndex = mapToSource(createIndex(index.row(), column, index.internalPointer())); - text.append(sourceIndex.data(role).toString()); - } - - return text; - } - - if(role == CodeCompletionModel::HighlightingMethod) - { - //Return that we are doing custom-highlighting of one of the sub-strings does it. Unfortunately internal highlighting does not work for the other substrings. - foreach (int column, m_columnMerges[index.column()]) { - QModelIndex sourceIndex = mapToSource(createIndex(index.row(), column, index.internalPointer())); - QVariant method = sourceIndex.data(CodeCompletionModel::HighlightingMethod); - if( method.type() == QVariant::Int && method.toInt() == CodeCompletionModel::CustomHighlighting) - return QVariant(CodeCompletionModel::CustomHighlighting); - } - return QVariant(); - } - if(role == CodeCompletionModel::CustomHighlight) - { - //Merge custom highlighting if multiple columns were merged - QStringList strings; - - //Collect strings - foreach (int column, m_columnMerges[index.column()]) - strings << mapToSource(createIndex(index.row(), column, index.internalPointer())).data(Qt::DisplayRole).toString(); - - QList highlights; - - //Collect custom-highlightings - foreach (int column, m_columnMerges[index.column()]) - highlights << mapToSource(createIndex(index.row(), column, index.internalPointer())).data(CodeCompletionModel::CustomHighlight).toList(); - - return mergeCustomHighlighting( strings, highlights, 0 ); - } - - QVariant v = mapToSource(index).data(role); - if( v.isValid() ) - return v; - else - return ExpandingWidgetModel::data(index, role); - } - - //Returns a nonzero group if this index is the head of a group(A Label in the list) - Group* g = groupForIndex(index); - - if (g && (!g->isEmpty)) { - switch (role) { - case Qt::DisplayRole: - //We return the group-header for all columns, ExpandingDelegate will paint them properly over the whole space - return QString(' ' + g->title); - break; - - case Qt::FontRole: - if (!index.column()) { - QFont f = view()->renderer()->config()->font(); - f.setBold(true); - return f; - } - break; - - case Qt::ForegroundRole: - return KApplication::kApplication()->palette().toolTipText().color(); - case Qt::BackgroundRole: - return KApplication::kApplication()->palette().toolTipBase().color(); - } - } - - return QVariant(); -} - -int KateCompletionModel::contextMatchQuality(const QModelIndex& index) const { - if(!index.isValid()) - return 0; - Group* g = groupOfParent(index); - if(!g || g->filtered.size() < index.row()) - return 0; - - return contextMatchQuality(g->filtered[index.row()].sourceRow()); -} - -int KateCompletionModel::contextMatchQuality(const ModelRow& source) const { - QModelIndex realIndex = source.second; - - int bestMatch = -1; - //Iterate through all argument-hints and find the best match-quality - foreach( const Item& item, m_argumentHints->filtered ) - { - const ModelRow& row(item.sourceRow()); - if( realIndex.model() != row.first ) - continue; //We can only match within the same source-model - - QModelIndex hintIndex = row.second; - - QVariant depth = hintIndex.data(CodeCompletionModel::ArgumentHintDepth); - if( !depth.isValid() || depth.type() != QVariant::Int || depth.toInt() != 1 ) - continue; //Only match completion-items to argument-hints of depth 1(the ones the item will be given to as argument) - - hintIndex.data(CodeCompletionModel::SetMatchContext); - - QVariant matchQuality = realIndex.data(CodeCompletionModel::MatchQuality); - if( matchQuality.isValid() && matchQuality.type() == QVariant::Int ) { - int m = matchQuality.toInt(); - if( m > bestMatch ) - bestMatch = m; - } - } - - if(m_argumentHints->filtered.isEmpty()) { - QVariant matchQuality = realIndex.data(CodeCompletionModel::MatchQuality); - if( matchQuality.isValid() && matchQuality.type() == QVariant::Int ) { - int m = matchQuality.toInt(); - if( m > bestMatch ) - bestMatch = m; - } - } - - return bestMatch; -} - -Qt::ItemFlags KateCompletionModel::flags( const QModelIndex & index ) const -{ - if (!hasCompletionModel() || !index.isValid()) - return 0; - - if (!hasGroups() || groupOfParent(index)) - return Qt::ItemIsSelectable | Qt::ItemIsEnabled; - - return Qt::ItemIsEnabled; -} - -KateCompletionWidget* KateCompletionModel::widget() const { - return static_cast(QObject::parent()); -} - -KateView * KateCompletionModel::view( ) const -{ - return widget()->view(); -} - -void KateCompletionModel::setMatchCaseSensitivity( Qt::CaseSensitivity cs ) -{ - m_matchCaseSensitivity = cs; -} - -int KateCompletionModel::columnCount( const QModelIndex& ) const -{ - return isColumnMergingEnabled() && !m_columnMerges.isEmpty() ? m_columnMerges.count() : KTextEditor::CodeCompletionModel::ColumnCount; -} - -KateCompletionModel::ModelRow KateCompletionModel::modelRowPair(const QModelIndex& index) const -{ - return qMakePair(static_cast(const_cast(index.model())), index); -} - -bool KateCompletionModel::hasChildren( const QModelIndex & parent ) const -{ - if (!hasCompletionModel()) - return false; - - if (!parent.isValid()) { - if (hasGroups()) - return true; - - return !m_ungrouped->filtered.isEmpty(); - } - - if (parent.column() != 0) - return false; - - if (!hasGroups()) - return false; - - if (Group* g = groupForIndex(parent)) - return !g->filtered.isEmpty(); - - return false; -} - -QModelIndex KateCompletionModel::index( int row, int column, const QModelIndex & parent ) const -{ - if (row < 0 || column < 0 || column >= columnCount(QModelIndex())) - return QModelIndex(); - - if (parent.isValid() || !hasGroups()) { - if (parent.isValid() && parent.column() != 0) - return QModelIndex(); - - Group* g = groupForIndex(parent); - - if (!g) - return QModelIndex(); - - if (row >= g->filtered.count()) { - //kWarning() << "Invalid index requested: row " << row << " beyond indivdual range in group " << g; - return QModelIndex(); - } - - //kDebug( 13035 ) << "Returning index for child " << row << " of group " << g; - return createIndex(row, column, g); - } - - if (row >= m_rowTable.count()) { - //kWarning() << "Invalid index requested: row " << row << " beyond group range."; - return QModelIndex(); - } - - //kDebug( 13035 ) << "Returning index for group " << m_rowTable[row]; - return createIndex(row, column, 0); -} - -/*QModelIndex KateCompletionModel::sibling( int row, int column, const QModelIndex & index ) const -{ - if (row < 0 || column < 0 || column >= columnCount(QModelIndex())) - return QModelIndex(); - - if (!index.isValid()) { - } - - if (Group* g = groupOfParent(index)) { - if (row >= g->filtered.count()) - return QModelIndex(); - - return createIndex(row, column, g); - } - - if (hasGroups()) - return QModelIndex(); - - if (row >= m_ungrouped->filtered.count()) - return QModelIndex(); - - return createIndex(row, column, m_ungrouped); -}*/ - -bool KateCompletionModel::hasIndex( int row, int column, const QModelIndex & parent ) const -{ - if (row < 0 || column < 0 || column >= columnCount(QModelIndex())) - return false; - - if (parent.isValid() || !hasGroups()) { - if (parent.isValid() && parent.column() != 0) - return false; - - Group* g = groupForIndex(parent); - - if (row >= g->filtered.count()) - return false; - - return true; - } - - if (row >= m_rowTable.count()) - return false; - - return true; -} - -QModelIndex KateCompletionModel::indexForRow( Group * g, int row ) const -{ - if (row < 0 || row >= g->filtered.count()) - return QModelIndex(); - - return createIndex(row, 0, g); -} - -QModelIndex KateCompletionModel::indexForGroup( Group * g ) const -{ - if (!hasGroups()) - return QModelIndex(); - - int row = m_rowTable.indexOf(g); - - if (row == -1) - return QModelIndex(); - - return createIndex(row, 0, 0); -} - -void KateCompletionModel::clearGroups( bool shouldReset ) -{ - clearExpanding(); - m_ungrouped->clear(); - m_argumentHints->clear(); - m_bestMatches->clear(); - - // Don't bother trying to work out where it is - m_rowTable.removeAll(m_ungrouped); - m_emptyGroups.removeAll(m_ungrouped); - - m_rowTable.removeAll(m_argumentHints); - m_emptyGroups.removeAll(m_argumentHints); - - m_rowTable.removeAll(m_bestMatches); - m_emptyGroups.removeAll(m_bestMatches); - - qDeleteAll(m_rowTable); - qDeleteAll(m_emptyGroups); - m_rowTable.clear(); - m_emptyGroups.clear(); - m_groupHash.clear(); - m_customGroupHash.clear(); - - m_emptyGroups.append(m_ungrouped); - m_groupHash.insert(0, m_ungrouped); - - m_emptyGroups.append(m_argumentHints); - m_groupHash.insert(-1, m_argumentHints); - - m_emptyGroups.append(m_bestMatches); - m_groupHash.insert(BestMatchesProperty, m_bestMatches); - - if(shouldReset) - reset(); -} - -QSet KateCompletionModel::createItems(const HierarchicalModelHandler& _handler, const QModelIndex& i, bool notifyModel) { - HierarchicalModelHandler handler(_handler); - QSet ret; - - if( handler.model()->rowCount(i) == 0 ) { - //Leaf node, create an item - ret.insert( createItem(handler, i, notifyModel) ); - } else { - //Non-leaf node, take the role from the node, and recurse to the sub-nodes - handler.takeRole(i); - for(int a = 0; a < handler.model()->rowCount(i); a++) - ret += createItems(handler, i.child(a, 0), notifyModel); - } - - return ret; -} - -QSet KateCompletionModel::deleteItems(const QModelIndex& i) { - QSet ret; - - if( i.model()->rowCount(i) == 0 ) { - //Leaf node, delete the item - Group* g = groupForIndex(mapFromSource(i)); - ret.insert(g); - g->removeItem(ModelRow(const_cast(static_cast(i.model())), i)); - } else { - //Non-leaf node - for(int a = 0; a < i.model()->rowCount(i); a++) - ret += deleteItems(i.child(a, 0)); - } - - return ret; -} - -void KateCompletionModel::createGroups() -{ - //After clearing the model, it has to be reset, else we will be in an invalid state while inserting - //new groups. - clearGroups(true); - - bool has_groups=false; - foreach (CodeCompletionModel* sourceModel, m_completionModels) { - has_groups|=sourceModel->hasGroups(); - for (int i = 0; i < sourceModel->rowCount(); ++i) - createItems(HierarchicalModelHandler(sourceModel), sourceModel->index(i, 0)); - } - m_hasGroups=has_groups; - - //debugStats(); - - foreach (Group* g, m_rowTable) - hideOrShowGroup(g); - - foreach (Group* g, m_emptyGroups) - hideOrShowGroup(g); - - updateBestMatches(); - - reset(); - - emit contentGeometryChanged(); -} - -KateCompletionModel::Group* KateCompletionModel::createItem(const HierarchicalModelHandler& handler, const QModelIndex& sourceIndex, bool notifyModel) -{ - //QModelIndex sourceIndex = sourceModel->index(row, CodeCompletionModel::Name, QModelIndex()); - - int completionFlags = handler.getData(CodeCompletionModel::CompletionRole, sourceIndex).toInt(); - - //Scope is expensive, should not be used with big models - QString scopeIfNeeded = (groupingMethod() & Scope) ? sourceIndex.sibling(sourceIndex.row(), CodeCompletionModel::Scope).data(Qt::DisplayRole).toString() : QString(); - - int argumentHintDepth = handler.getData(CodeCompletionModel::ArgumentHintDepth, sourceIndex).toInt(); - - Group* g; - if( argumentHintDepth ) { - g = m_argumentHints; - } else{ - QString customGroup = handler.customGroup(); - if(!customGroup.isNull() && m_hasGroups) { - if(m_customGroupHash.contains(customGroup)) { - g = m_customGroupHash[customGroup]; - }else{ - g = new Group(this); - g->title = customGroup; - g->customSortingKey = handler.customGroupingKey(); - m_emptyGroups.append(g); - m_customGroupHash.insert(customGroup, g); - } - }else{ - g = fetchGroup(completionFlags, scopeIfNeeded, handler.hasHierarchicalRoles()); - } - } - - Item item = Item(g != m_argumentHints, this, handler, ModelRow(handler.model(), sourceIndex)); - - if(g != m_argumentHints) - item.match(); - - g->addItem(item, notifyModel); - - return g; -} - -void KateCompletionModel::slotRowsInserted( const QModelIndex & parent, int start, int end ) -{ - QSet affectedGroups; - - HierarchicalModelHandler handler(static_cast(sender())); - if(parent.isValid()) - handler.collectRoles(parent); - - - for (int i = start; i <= end; ++i) - affectedGroups += createItems(handler, parent.isValid() ? parent.child(i, 0) : handler.model()->index(i, 0), true); - - foreach (Group* g, affectedGroups) - hideOrShowGroup(g); - - emit contentGeometryChanged(); -} - -void KateCompletionModel::slotRowsRemoved( const QModelIndex & parent, int start, int end ) -{ - CodeCompletionModel* source = static_cast(sender()); - - QSet affectedGroups; - - for (int i = start; i <= end; ++i) { - QModelIndex index = parent.isValid() ? parent.child(i, 0) : source->index(i, 0); - - affectedGroups += deleteItems(index); - } - - foreach (Group* g, affectedGroups) - hideOrShowGroup(g); - - emit contentGeometryChanged(); -} - -KateCompletionModel::Group* KateCompletionModel::fetchGroup( int attribute, const QString& scope, bool forceGrouping ) -{ - Q_UNUSED(forceGrouping); - - ///@todo use forceGrouping - if (!hasGroups()) - return m_ungrouped; - - int groupingAttribute = groupingAttributes(attribute); - //kDebug( 13035 ) << attribute << " " << groupingAttribute; - - if (m_groupHash.contains(groupingAttribute)) { - if (groupingMethod() & Scope) { - for (QHash::ConstIterator it = m_groupHash.constFind(groupingAttribute); it != m_groupHash.constEnd() && it.key() == groupingAttribute; ++it) - if (it.value()->scope == scope) - return it.value(); - } else { - return m_groupHash.value(groupingAttribute); - } - } - Group* ret = new Group(this); - - ret->attribute = attribute; - ret->scope = scope; - - QString st, at, it; - - if (groupingMethod() & ScopeType) { - if (attribute & KTextEditor::CodeCompletionModel::GlobalScope) - st = "Global"; - else if (attribute & KTextEditor::CodeCompletionModel::NamespaceScope) - st = "Namespace"; - else if (attribute & KTextEditor::CodeCompletionModel::LocalScope) - st = "Local"; - - ret->title = st; - } - - if (groupingMethod() & Scope) { - if (!ret->title.isEmpty()) - ret->title.append(" "); - - ret->title.append(scope); - } - - if (groupingMethod() & AccessType) { - if (attribute & KTextEditor::CodeCompletionModel::Public) - at = "Public"; - else if (attribute & KTextEditor::CodeCompletionModel::Protected) - at = "Protected"; - else if (attribute & KTextEditor::CodeCompletionModel::Private) - at = "Private"; - - if (accessIncludeStatic() && attribute & KTextEditor::CodeCompletionModel::Static) - at.append(" Static"); - - if (accessIncludeConst() && attribute & KTextEditor::CodeCompletionModel::Const) - at.append(" Const"); - - if( !at.isEmpty() ) { - if (!ret->title.isEmpty()) - ret->title.append(", "); - - ret->title.append(at); - } - } - - if (groupingMethod() & ItemType) { - if (attribute & CodeCompletionModel::Namespace) - it = i18n("Namespaces"); - else if (attribute & CodeCompletionModel::Class) - it = i18n("Classes"); - else if (attribute & CodeCompletionModel::Struct) - it = i18n("Structs"); - else if (attribute & CodeCompletionModel::Union) - it = i18n("Unions"); - else if (attribute & CodeCompletionModel::Function) - it = i18n("Functions"); - else if (attribute & CodeCompletionModel::Variable) - it = i18n("Variables"); - else if (attribute & CodeCompletionModel::Enum) - it = i18n("Enumerations"); - - if( !it.isEmpty() ) { - if (!ret->title.isEmpty()) - ret->title.append(" "); - - ret->title.append(it); - } - } - - m_emptyGroups.append(ret); - m_groupHash.insert(groupingAttribute, ret); - - return ret; -} - -bool KateCompletionModel::hasGroups( ) const -{ - //kDebug( 13035 ) << "m_groupHash.size()"<= m_rowTable.count()) - return m_ungrouped; - - return m_rowTable[index.row()]; -} - -/*QMap< int, QVariant > KateCompletionModel::itemData( const QModelIndex & index ) const -{ - if (!hasGroups() || groupOfParent(index)) { - QModelIndex index = mapToSource(index); - if (index.isValid()) - return index.model()->itemData(index); - } - - return QAbstractItemModel::itemData(index); -}*/ - -QModelIndex KateCompletionModel::parent( const QModelIndex & index ) const -{ - if (!index.isValid()) - return QModelIndex(); - - if (Group* g = groupOfParent(index)) { - if (!hasGroups()) { - Q_ASSERT(g == m_ungrouped); - return QModelIndex(); - } - - int row = m_rowTable.indexOf(g); - - if (row == -1) { - kWarning() << "Couldn't find parent for index" << index; - return QModelIndex(); - } - - return createIndex(row, 0, 0); - } - - return QModelIndex(); -} - -int KateCompletionModel::rowCount( const QModelIndex & parent ) const -{ - if (!parent.isValid()) { - if (hasGroups()) { - //kDebug( 13035 ) << "Returning row count for toplevel " << m_rowTable.count(); - return m_rowTable.count(); - } else { - //kDebug( 13035 ) << "Returning ungrouped row count for toplevel " << m_ungrouped->filtered.count(); - return m_ungrouped->filtered.count(); - } - } - - Group* g = groupForIndex(parent); - - // This is not an error, seems you don't have to check hasChildren() - if (!g) - return 0; - - //kDebug( 13035 ) << "Returning row count for group " << g << " as " << g->filtered.count(); - return g->filtered.count(); -} - -void KateCompletionModel::sort( int column, Qt::SortOrder order ) -{ - Q_UNUSED(column) - Q_UNUSED(order) -} - -QModelIndex KateCompletionModel::mapToSource( const QModelIndex & proxyIndex ) const -{ - if (!proxyIndex.isValid()) - return QModelIndex(); - - if (Group* g = groupOfParent(proxyIndex)) { - if( proxyIndex.row() >= 0 && proxyIndex.row() < g->filtered.count() ) { - ModelRow source = g->filtered[proxyIndex.row()].sourceRow(); - return source.second.sibling(source.second.row(), proxyIndex.column()); - }else{ - kDebug( 13035 ) << "Invalid proxy-index"; - } - } - - return QModelIndex(); -} - -QModelIndex KateCompletionModel::mapFromSource( const QModelIndex & sourceIndex ) const -{ - if (!sourceIndex.isValid()) - return QModelIndex(); - - if (!hasGroups()) - return index(m_ungrouped->rowOf(modelRowPair(sourceIndex)), sourceIndex.column(), QModelIndex()); - - foreach (Group* g, m_rowTable) { - int row = g->rowOf(modelRowPair(sourceIndex)); - if (row != -1) - return index(row, sourceIndex.column(), indexForGroup(g)); - } - - // Copied from above - foreach (Group* g, m_emptyGroups) { - int row = g->rowOf(modelRowPair(sourceIndex)); - if (row != -1) - return index(row, sourceIndex.column(), indexForGroup(g)); - } - - return QModelIndex(); -} - -void KateCompletionModel::setCurrentCompletion( KTextEditor::CodeCompletionModel* model, const QString & completion ) -{ - if (m_currentMatch[model] == completion) - return; - - if (!hasCompletionModel()) { - m_currentMatch[model] = completion; - return; - } - - changeTypes changeType = Change; - - if (m_currentMatch[model].length() > completion.length() && m_currentMatch[model].startsWith(completion, m_matchCaseSensitivity)) { - // Filter has been broadened - changeType = Broaden; - - } else if (m_currentMatch[model].length() < completion.length() && completion.startsWith(m_currentMatch[model], m_matchCaseSensitivity)) { - // Filter has been narrowed - changeType = Narrow; - } - - //kDebug( 13035 ) << model << "Old match: " << m_currentMatch[model] << ", new: " << completion << ", type: " << changeType; - - m_currentMatch[model] = completion; - - bool needsReset = false; - - if (!hasGroups()) { - needsReset |= changeCompletions(m_ungrouped, changeType); - } else { - foreach (Group* g, m_rowTable) { - if(g != m_argumentHints) - needsReset |= changeCompletions(g, changeType); - } - foreach (Group* g, m_emptyGroups) { - if(g != m_argumentHints) - needsReset |= changeCompletions(g, changeType); - } - - updateBestMatches(); - } - - kDebug()<<"needsReset"< groups = m_rowTable; - groups += m_ungrouped; - - foreach (Group* g, groups) { - foreach(const Item& item, g->filtered) - { - uint startPos = m_currentMatch[item.sourceRow().first].length(); - const QString candidate = item.name().mid(startPos); - - if(!candidate.startsWith(forcePrefix)) - continue; - - if(commonPrefix.isNull()) { - commonPrefix = candidate; - - //Replace QString::null prefix with QString(""), so we won't initialize it again - if(commonPrefix.isNull()) - commonPrefix = QString(""); // isEmpty() = true, isNull() = false - }else{ - commonPrefix = commonPrefix.left(candidate.length()); - - for(int a = 0; a < commonPrefix.length(); ++a) { - if(commonPrefix[a] != candidate[a]) { - commonPrefix = commonPrefix.left(a); - break; - } - } - } - } - } - - return commonPrefix; -} - -QString KateCompletionModel::commonPrefix(QModelIndex selectedIndex) const -{ - QString commonPrefix = commonPrefixInternal(QString()); - - if(commonPrefix.isEmpty() && selectedIndex.isValid()) { - Group* g = m_ungrouped; - if(hasGroups()) - g = groupOfParent(selectedIndex); - - if(g && selectedIndex.row() < g->filtered.size()) - { - //Follow the path of the selected item, finding the next non-empty common prefix - Item item = g->filtered[selectedIndex.row()]; - int matchLength = m_currentMatch[item.sourceRow().first].length(); - commonPrefix = commonPrefixInternal(item.name().mid(matchLength).left(1)); - } - } - - return commonPrefix; -} - -bool KateCompletionModel::changeCompletions( Group * g, changeTypes changeType ) -{ - bool notifyModel = true; - if(changeType != Narrow) { - notifyModel = false; - g->filtered = g->prefilter; - //In the "Broaden" or "Change" case, just re-filter everything, - //and don't notify the model. The model is notified afterwards through a reset(). - } - //This code determines what of the filtered items still fit, and computes the ranges that were removed, giving - //them to beginRemoveRows(..) in batches - - QList newFiltered; - int deleteUntil = -1; //In each state, the range [currentRow+1, deleteUntil] needs to be deleted - for(int currentRow = g->filtered.count()-1; currentRow >= 0; --currentRow) { - if(g->filtered[currentRow].match()) { - //This row does not need to be deleted, which means that currentRow+1 to deleteUntil need to be deleted now - if(deleteUntil != -1 && notifyModel) { - beginRemoveRows(indexForGroup(g), currentRow+1, deleteUntil); - endRemoveRows(); - } - deleteUntil = -1; - - newFiltered.prepend(g->filtered[currentRow]); - }else{ - if(deleteUntil == -1) - deleteUntil = currentRow; //Mark that this row needs to be deleted - } - } - - if(deleteUntil != -1) { - beginRemoveRows(indexForGroup(g), 0, deleteUntil); - endRemoveRows(); - } - - g->filtered = newFiltered; - hideOrShowGroup(g, notifyModel); - return !notifyModel; -} - -int KateCompletionModel::Group::orderNumber() const { - if( this == model->m_ungrouped ) - return 700; - - if(customSortingKey != -1) - return customSortingKey; - - if( attribute & BestMatchesProperty ) - return 1; - - if (attribute & KTextEditor::CodeCompletionModel::LocalScope) - return 100; - else if (attribute & KTextEditor::CodeCompletionModel::Public) - return 200; - else if (attribute & KTextEditor::CodeCompletionModel::Protected) - return 300; - else if (attribute & KTextEditor::CodeCompletionModel::Private) - return 400; - else if (attribute & KTextEditor::CodeCompletionModel::NamespaceScope) - return 500; - else if (attribute & KTextEditor::CodeCompletionModel::GlobalScope) - return 600; - - - return 700; -} - -bool KateCompletionModel::Group::orderBefore(Group* other) const { - return orderNumber() < other->orderNumber(); -} - -void KateCompletionModel::hideOrShowGroup(Group* g, bool notifyModel) -{ - if( g == m_argumentHints ) { - emit argumentHintsChanged(); - m_updateBestMatchesTimer->start(200); //We have new argument-hints, so we have new best matches - return; //Never show argument-hints in the normal completion-list - } - - if (!g->isEmpty) { - if (g->filtered.isEmpty()) { - // Move to empty group list - g->isEmpty = true; - int row = m_rowTable.indexOf(g); - if (row != -1) { - if (hasGroups() && notifyModel) - beginRemoveRows(QModelIndex(), row, row); - m_rowTable.removeAt(row); - if (hasGroups() && notifyModel) - endRemoveRows(); - m_emptyGroups.append(g); - } else { - kWarning() << "Group " << g << " not found in row table!!"; - } - } - - } else { - - if (!g->filtered.isEmpty()) { - // Move off empty group list - g->isEmpty = false; - - int row = 0; //Find row where to insert - for( int a = 0; a < m_rowTable.count(); a++ ) { - if( g->orderBefore(m_rowTable[a]) ) { - row = a; - break; - } - row = a+1; - } - - if(notifyModel) { - if (hasGroups()) - beginInsertRows(QModelIndex(), row, row); - else - beginInsertRows(QModelIndex(), 0, g->filtered.count()); - } - m_rowTable.insert(row, g); - if(notifyModel) - endInsertRows(); - m_emptyGroups.removeAll(g); - } - } -} - -bool KateCompletionModel::indexIsItem( const QModelIndex & index ) const -{ - if (!hasGroups()) - return true; - - if (groupOfParent(index)) - return true; - - return false; -} - -void KateCompletionModel::slotModelReset() -{ - createGroups(); - - //debugStats(); -} - -void KateCompletionModel::debugStats() -{ - if (!hasGroups()) - kDebug( 13035 ) << "Model groupless, " << m_ungrouped->filtered.count() << " items."; - else { - kDebug( 13035 ) << "Model grouped (" << m_rowTable.count() << " groups):"; - foreach (Group* g, m_rowTable) - kDebug( 13035 ) << "Group" << g << "count" << g->filtered.count(); - } -} - -bool KateCompletionModel::hasCompletionModel( ) const -{ - return !m_completionModels.isEmpty(); -} - -void KateCompletionModel::setFilteringEnabled( bool enable ) -{ - if (m_filteringEnabled != enable) - m_filteringEnabled = enable; -} - -void KateCompletionModel::setSortingEnabled( bool enable ) -{ - if (m_sortingEnabled != enable) { - m_sortingEnabled = enable; - resort(); - } -} - -void KateCompletionModel::setGroupingEnabled(bool enable) -{ - if (m_groupingEnabled != enable) - m_groupingEnabled = enable; -} - -void KateCompletionModel::setColumnMergingEnabled(bool enable) -{ - if (m_columnMergingEnabled != enable) - m_columnMergingEnabled = enable; -} - -bool KateCompletionModel::isColumnMergingEnabled( ) const -{ - return m_columnMergingEnabled; -} - -bool KateCompletionModel::isGroupingEnabled( ) const -{ - return m_groupingEnabled; -} - -bool KateCompletionModel::isFilteringEnabled( ) const -{ - return m_filteringEnabled; -} - -bool KateCompletionModel::isSortingEnabled( ) const -{ - return m_sortingEnabled; -} - -QString KateCompletionModel::columnName( int column ) -{ - switch (column) { - case KTextEditor::CodeCompletionModel::Prefix: - return i18n("Prefix"); - case KTextEditor::CodeCompletionModel::Icon: - return i18n("Icon"); - case KTextEditor::CodeCompletionModel::Scope: - return i18n("Scope"); - case KTextEditor::CodeCompletionModel::Name: - return i18n("Name"); - case KTextEditor::CodeCompletionModel::Arguments: - return i18n("Arguments"); - case KTextEditor::CodeCompletionModel::Postfix: - return i18n("Postfix"); - } - - return QString(); -} - -const QList< QList < int > > & KateCompletionModel::columnMerges( ) const -{ - return m_columnMerges; -} - -void KateCompletionModel::setColumnMerges( const QList< QList < int > > & columnMerges ) -{ - m_columnMerges = columnMerges; - reset(); -} - -int KateCompletionModel::translateColumn( int sourceColumn ) const -{ - if (m_columnMerges.isEmpty()) - return sourceColumn; - - /* Debugging - dump column merge list - - QString columnMerge; - foreach (const QList& list, m_columnMerges) { - columnMerge += '['; - foreach (int column, list) { - columnMerge += QString::number(column) + " "; - } - columnMerge += "] "; - } - - kDebug( 13035 ) << k_funcinfo << columnMerge;*/ - - int c = 0; - foreach (const QList& list, m_columnMerges) { - foreach (int column, list) { - if (column == sourceColumn) - return c; - } - c++; - } - return -1; -} - -int KateCompletionModel::groupingAttributes( int attribute ) const -{ - int ret = 0; - - if (m_groupingMethod & ScopeType) { - if (countBits(attribute & ScopeTypeMask) > 1) - kWarning() << "Invalid completion model metadata: more than one scope type modifier provided."; - - if (attribute & KTextEditor::CodeCompletionModel::GlobalScope) - ret |= KTextEditor::CodeCompletionModel::GlobalScope; - else if (attribute & KTextEditor::CodeCompletionModel::NamespaceScope) - ret |= KTextEditor::CodeCompletionModel::NamespaceScope; - else if (attribute & KTextEditor::CodeCompletionModel::LocalScope) - ret |= KTextEditor::CodeCompletionModel::LocalScope; - } - - if (m_groupingMethod & AccessType) { - if (countBits(attribute & AccessTypeMask) > 1) - kWarning() << "Invalid completion model metadata: more than one access type modifier provided."; - - if (attribute & KTextEditor::CodeCompletionModel::Public) - ret |= KTextEditor::CodeCompletionModel::Public; - else if (attribute & KTextEditor::CodeCompletionModel::Protected) - ret |= KTextEditor::CodeCompletionModel::Protected; - else if (attribute & KTextEditor::CodeCompletionModel::Private) - ret |= KTextEditor::CodeCompletionModel::Private; - - if (accessIncludeStatic() && attribute & KTextEditor::CodeCompletionModel::Static) - ret |= KTextEditor::CodeCompletionModel::Static; - - if (accessIncludeConst() && attribute & KTextEditor::CodeCompletionModel::Const) - ret |= KTextEditor::CodeCompletionModel::Const; - } - - if (m_groupingMethod & ItemType) { - if (countBits(attribute & ItemTypeMask) > 1) - kWarning() << "Invalid completion model metadata: more than one item type modifier provided."; - - if (attribute & KTextEditor::CodeCompletionModel::Namespace) - ret |= KTextEditor::CodeCompletionModel::Namespace; - else if (attribute & KTextEditor::CodeCompletionModel::Class) - ret |= KTextEditor::CodeCompletionModel::Class; - else if (attribute & KTextEditor::CodeCompletionModel::Struct) - ret |= KTextEditor::CodeCompletionModel::Struct; - else if (attribute & KTextEditor::CodeCompletionModel::Union) - ret |= KTextEditor::CodeCompletionModel::Union; - else if (attribute & KTextEditor::CodeCompletionModel::Function) - ret |= KTextEditor::CodeCompletionModel::Function; - else if (attribute & KTextEditor::CodeCompletionModel::Variable) - ret |= KTextEditor::CodeCompletionModel::Variable; - else if (attribute & KTextEditor::CodeCompletionModel::Enum) - ret |= KTextEditor::CodeCompletionModel::Enum; - - /* - if (itemIncludeTemplate() && attribute & KTextEditor::CodeCompletionModel::Template) - ret |= KTextEditor::CodeCompletionModel::Template;*/ - } - - return ret; -} - -void KateCompletionModel::setGroupingMethod( GroupingMethods m ) -{ - m_groupingMethod = m; - - createGroups(); -} - -bool KateCompletionModel::accessIncludeConst( ) const -{ - return m_accessConst; -} - -void KateCompletionModel::setAccessIncludeConst( bool include ) -{ - if (m_accessConst != include) { - m_accessConst = include; - - if (groupingMethod() & AccessType) - createGroups(); - } -} - -bool KateCompletionModel::accessIncludeStatic( ) const -{ - return m_accessStatic; -} - -void KateCompletionModel::setAccessIncludeStatic( bool include ) -{ - if (m_accessStatic != include) { - m_accessStatic = include; - - if (groupingMethod() & AccessType) - createGroups(); - } -} - -bool KateCompletionModel::accessIncludeSignalSlot( ) const -{ - return m_accesSignalSlot; -} - -void KateCompletionModel::setAccessIncludeSignalSlot( bool include ) -{ - if (m_accesSignalSlot != include) { - m_accesSignalSlot = include; - - if (groupingMethod() & AccessType) - createGroups(); - } -} - -int KateCompletionModel::countBits( int value ) const -{ - int count = 0; - for (int i = 1; i; i <<= 1) - if (i & value) - count++; - - return count; -} - -KateCompletionModel::GroupingMethods KateCompletionModel::groupingMethod( ) const -{ - return m_groupingMethod; -} - -bool KateCompletionModel::isSortingByInheritanceDepth() const { - return m_isSortingByInheritance; -} -void KateCompletionModel::setSortingByInheritanceDepth(bool byInheritance) { - m_isSortingByInheritance = byInheritance; -} - -bool KateCompletionModel::isSortingAlphabetical( ) const -{ - return m_sortingAlphabetical; -} - -Qt::CaseSensitivity KateCompletionModel::sortingCaseSensitivity( ) const -{ - return m_sortingCaseSensitivity; -} - -KateCompletionModel::Item::Item( bool doInitialMatch, KateCompletionModel* m, const HierarchicalModelHandler& handler, ModelRow sr ) - : model(m) - , m_sourceRow(sr) - , matchCompletion(StartsWithMatch) - , matchFilters(true) - , m_haveExactMatch(false) -{ - - inheritanceDepth = handler.getData(CodeCompletionModel::InheritanceDepth, m_sourceRow.second).toInt(); - - QModelIndex nameSibling = sr.second.sibling(sr.second.row(), CodeCompletionModel::Name); - m_nameColumn = nameSibling.data(Qt::DisplayRole).toString(); - - if(doInitialMatch) { - filter(); - match(); - } -} - -bool KateCompletionModel::Item::operator <( const Item & rhs ) const -{ - int ret = 0; - - //kDebug( 13035 ) << c1 << " c/w " << c2 << " -> " << (model->isSortingReverse() ? ret > 0 : ret < 0) << " (" << ret << ")"; - - if( model->isSortingByInheritanceDepth() ) - ret = inheritanceDepth - rhs.inheritanceDepth; - - if (ret == 0 && model->isSortingAlphabetical()) { - if(!m_completionSortingName.isEmpty() && !rhs.m_completionSortingName.isEmpty()) - //Shortcut, plays a role in this tight loop - ret = QString::compare(m_completionSortingName, rhs.m_completionSortingName); - else - ret = QString::compare(completionSortingName(), rhs.completionSortingName()); //Do not use localeAwareCompare, because it is simply too slow for a list of about 1000 items - } - - if( ret == 0 ) { - // FIXME need to define a better default ordering for multiple model display - ret = m_sourceRow.second.row() - rhs.m_sourceRow.second.row(); - } - - return ret < 0; -} - -QString KateCompletionModel::Item::completionSortingName( ) const -{ - if(m_completionSortingName.isEmpty()) { - m_completionSortingName = m_nameColumn; - if (model->sortingCaseSensitivity() == Qt::CaseInsensitive) - m_completionSortingName = m_completionSortingName.toLower(); - } - - return m_completionSortingName; -} - -void KateCompletionModel::Group::addItem( Item i, bool notifyModel ) -{ - if (isEmpty) - notifyModel = false; - - QModelIndex groupIndex; - if (notifyModel) - groupIndex = model->indexForGroup(this); - - if (model->isSortingEnabled()) { - - prefilter.insert(qUpperBound(prefilter.begin(), prefilter.end(), i), i); - if(i.isVisible()) { - QList::iterator it = qUpperBound(filtered.begin(), filtered.end(), i); - uint rowNumber = it - filtered.begin(); - - if(notifyModel) - model->beginInsertRows(groupIndex, rowNumber, rowNumber); - - filtered.insert(it, i); - } - } else { - if(notifyModel) - model->beginInsertRows(groupIndex, prefilter.size(), prefilter.size()); - if (i.isVisible()) - prefilter.append(i); - } - - if(notifyModel) - model->endInsertRows(); -} - -bool KateCompletionModel::Group::removeItem(const ModelRow& row) -{ - for (int pi = 0; pi < prefilter.count(); ++pi) - if (prefilter[pi].sourceRow() == row) { - int index = rowOf(row); - if (index != -1) - model->beginRemoveRows(model->indexForGroup(this), index, index); - - filtered.removeAt(index); - prefilter.removeAt(pi); - - if (index != -1) - model->endRemoveRows(); - - return index != -1; - } - - Q_ASSERT(false); - return false; -} - -KateCompletionModel::Group::Group( KateCompletionModel * m ) - : model(m) - , isEmpty(true) - , customSortingKey(-1) -{ - Q_ASSERT(model); -} - -void KateCompletionModel::setSortingAlphabetical( bool alphabetical ) -{ - if (m_sortingAlphabetical != alphabetical) { - m_sortingAlphabetical = alphabetical; - resort(); - } -} - -void KateCompletionModel::Group::resort( ) -{ - qStableSort(prefilter.begin(), prefilter.end()); - //int oldRowCount = filtered.count(); - filtered.clear(); - foreach (const Item& i, prefilter) - if (i.isVisible()) - filtered.append(i); - - model->hideOrShowGroup(this); - //Q_ASSERT(filtered.count() == oldRowCount); -} - -void KateCompletionModel::setSortingCaseSensitivity( Qt::CaseSensitivity cs ) -{ - if (m_sortingCaseSensitivity != cs) { - m_sortingCaseSensitivity = cs; - resort(); - } -} - -void KateCompletionModel::resort( ) -{ - foreach (Group* g, m_rowTable) - g->resort(); - - foreach (Group* g, m_emptyGroups) - g->resort(); - - emit contentGeometryChanged(); -} - -bool KateCompletionModel::Item::isValid( ) const -{ - return model && m_sourceRow.first && m_sourceRow.second.row() >= 0; -} - -void KateCompletionModel::Group::clear( ) -{ - prefilter.clear(); - filtered.clear(); - isEmpty = true; -} - -bool KateCompletionModel::filterContextMatchesOnly( ) const -{ - return m_filterContextMatchesOnly; -} - -void KateCompletionModel::setFilterContextMatchesOnly( bool filter ) -{ - if (m_filterContextMatchesOnly != filter) { - m_filterContextMatchesOnly = filter; - refilter(); - } -} - -bool KateCompletionModel::filterByAttribute( ) const -{ - return m_filterByAttribute; -} - -void KateCompletionModel::setFilterByAttribute( bool filter ) -{ - if (m_filterByAttribute == filter) { - m_filterByAttribute = filter; - refilter(); - } -} - -KTextEditor::CodeCompletionModel::CompletionProperties KateCompletionModel::filterAttributes( ) const -{ - return m_filterAttributes; -} - -void KateCompletionModel::setFilterAttributes( KTextEditor::CodeCompletionModel::CompletionProperties attributes ) -{ - if (m_filterAttributes == attributes) { - m_filterAttributes = attributes; - refilter(); - } -} - -int KateCompletionModel::maximumInheritanceDepth( ) const -{ - return m_maximumInheritanceDepth; -} - -void KateCompletionModel::setMaximumInheritanceDepth( int maxDepth ) -{ - if (m_maximumInheritanceDepth != maxDepth) { - m_maximumInheritanceDepth = maxDepth; - refilter(); - } -} - -void KateCompletionModel::refilter( ) -{ - m_ungrouped->refilter(); - - foreach (Group* g, m_rowTable) - if(g != m_argumentHints) - g->refilter(); - - foreach (Group* g, m_emptyGroups) - if(g != m_argumentHints) - g->refilter(); - - updateBestMatches(); - - clearExpanding(); //We need to do this, or be aware of expanding-widgets while filtering. -} - -void KateCompletionModel::Group::refilter( ) -{ - filtered.clear(); - foreach (const Item& i, prefilter) - if (!i.isFiltered()) - filtered.append(i); -} - -bool KateCompletionModel::Item::filter( ) -{ - matchFilters = false; - - if (model->isFilteringEnabled()) { - QModelIndex sourceIndex = m_sourceRow.second.sibling(m_sourceRow.second.row(), CodeCompletionModel::Name); - - if (model->filterContextMatchesOnly()) { - QVariant contextMatch = sourceIndex.data(CodeCompletionModel::MatchQuality); - if (contextMatch.canConvert(QVariant::Int) && !contextMatch.toInt()) - goto filter; - } - - if (model->filterByAttribute()) { - int completionFlags = sourceIndex.data(CodeCompletionModel::CompletionRole).toInt(); - if (model->filterAttributes() & completionFlags) - goto filter; - } - - if (model->maximumInheritanceDepth() > 0) { - int inheritanceDepth = sourceIndex.data(CodeCompletionModel::InheritanceDepth).toInt(); - if (inheritanceDepth > model->maximumInheritanceDepth()) - goto filter; - } - } - - matchFilters = true; - - filter: - return matchFilters; -} - -uint KateCompletionModel::filteredItemCount() const -{ - uint ret = 0; - foreach(Group* group, m_rowTable) - ret += group->filtered.size(); - - return ret; -} - -bool KateCompletionModel::shouldMatchHideCompletionList() const { - - // @todo Make this faster - - bool doHide = false; - CodeCompletionModel* hideModel = 0; - - foreach(Group* group, m_rowTable) - foreach(const Item& item, group->filtered) - if(item.haveExactMatch()) { - KTextEditor::CodeCompletionModelControllerInterface2* iface2 = dynamic_cast(item.sourceRow().first); - KTextEditor::CodeCompletionModelControllerInterface3* iface3 = dynamic_cast(item.sourceRow().first); - bool hide = false; - if (! (iface2 || iface3) ) hide = true; - if(iface2 && iface2->matchingItem(item.sourceRow().second) == KTextEditor::CodeCompletionModelControllerInterface2::HideListIfAutomaticInvocation) - hide = true; - if(iface3 && iface3->matchingItem(item.sourceRow().second) == KTextEditor::CodeCompletionModelControllerInterface3::HideListIfAutomaticInvocation) - hide = true; - if(hide) - { - doHide = true; - hideModel = item.sourceRow().first; - } - } - - if(doHide) - { - // Check if all other visible items are from the same model - foreach(Group* group, m_rowTable) - foreach(const Item& item, group->filtered) - if(item.sourceRow().first != hideModel) - return false; - } - - return doHide; -} - -KateCompletionModel::Item::MatchType KateCompletionModel::Item::match() -{ - // Check to see if the item is matched by the current completion string - QModelIndex sourceIndex = m_sourceRow.second.sibling(m_sourceRow.second.row(), CodeCompletionModel::Name); - - QString match = model->currentCompletion(m_sourceRow.first); - - m_haveExactMatch = false; - - // Hehe, everything matches nothing! (ie. everything matches a blank string) - if (match.isEmpty()) - return PerfectMatch; - - matchCompletion = (m_nameColumn.startsWith(match, model->matchCaseSensitivity()) ? StartsWithMatch : NoMatch); - - if(matchCompletion && match.length() == m_nameColumn.length()) { - matchCompletion = PerfectMatch; - m_haveExactMatch = true; - } - - return matchCompletion; -} - -QString KateCompletionModel::propertyName( KTextEditor::CodeCompletionModel::CompletionProperty property ) -{ - switch (property) { - case CodeCompletionModel::Public: - return i18n("Public"); - - case CodeCompletionModel::Protected: - return i18n("Protected"); - - case CodeCompletionModel::Private: - return i18n("Private"); - - case CodeCompletionModel::Static: - return i18n("Static"); - - case CodeCompletionModel::Const: - return i18n("Constant"); - - case CodeCompletionModel::Namespace: - return i18n("Namespace"); - - case CodeCompletionModel::Class: - return i18n("Class"); - - case CodeCompletionModel::Struct: - return i18n("Struct"); - - case CodeCompletionModel::Union: - return i18n("Union"); - - case CodeCompletionModel::Function: - return i18n("Function"); - - case CodeCompletionModel::Variable: - return i18n("Variable"); - - case CodeCompletionModel::Enum: - return i18n("Enumeration"); - - case CodeCompletionModel::Template: - return i18n("Template"); - - case CodeCompletionModel::Virtual: - return i18n("Virtual"); - - case CodeCompletionModel::Override: - return i18n("Override"); - - case CodeCompletionModel::Inline: - return i18n("Inline"); - - case CodeCompletionModel::Friend: - return i18n("Friend"); - - case CodeCompletionModel::Signal: - return i18n("Signal"); - - case CodeCompletionModel::Slot: - return i18n("Slot"); - - case CodeCompletionModel::LocalScope: - return i18n("Local Scope"); - - case CodeCompletionModel::NamespaceScope: - return i18n("Namespace Scope"); - - case CodeCompletionModel::GlobalScope: - return i18n("Global Scope"); - - default: - return i18n("Unknown Property"); - } -} - -bool KateCompletionModel::Item::isVisible( ) const -{ - return matchCompletion && matchFilters; -} - -bool KateCompletionModel::Item::isFiltered( ) const -{ - return !matchFilters; -} - -bool KateCompletionModel::Item::isMatching( ) const -{ - return matchFilters; -} - -const KateCompletionModel::ModelRow& KateCompletionModel::Item::sourceRow( ) const -{ - return m_sourceRow; -} - -QString KateCompletionModel::currentCompletion( KTextEditor::CodeCompletionModel* model ) const -{ - return m_currentMatch.value(model); -} - -Qt::CaseSensitivity KateCompletionModel::matchCaseSensitivity( ) const -{ - return m_matchCaseSensitivity; -} - -void KateCompletionModel::addCompletionModel(KTextEditor::CodeCompletionModel * model) -{ - if (m_completionModels.contains(model)) - return; - - m_completionModels.append(model); - - connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SLOT(slotRowsInserted(const QModelIndex&, int, int))); - connect(model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SLOT(slotRowsRemoved(const QModelIndex&, int, int))); - connect(model, SIGNAL(modelReset()), SLOT(slotModelReset())); - - // This performs the reset - createGroups(); -} - -void KateCompletionModel::setCompletionModel(KTextEditor::CodeCompletionModel* model) -{ - clearCompletionModels(); - addCompletionModel(model); -} - -void KateCompletionModel::setCompletionModels(const QList& models) -{ - //if (m_completionModels == models) - //return; - - clearCompletionModels(); - - m_completionModels = models; - - foreach (KTextEditor::CodeCompletionModel* model, models) { - connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SLOT(slotRowsInserted(const QModelIndex&, int, int))); - connect(model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SLOT(slotRowsRemoved(const QModelIndex&, int, int))); - connect(model, SIGNAL(modelReset()), SLOT(slotModelReset())); - } - - // This performs the reset - createGroups(); -} - -QList< KTextEditor::CodeCompletionModel * > KateCompletionModel::completionModels() const -{ - return m_completionModels; -} - -void KateCompletionModel::removeCompletionModel(CodeCompletionModel * model) -{ - if (!model || !m_completionModels.contains(model)) - return; - - m_currentMatch.remove(model); - - clearGroups(false); - - model->disconnect(this); - - m_completionModels.removeAll(model); - - if (!m_completionModels.isEmpty()) { - // This performs the reset - createGroups(); - }else{ - emit contentGeometryChanged(); - reset(); - } -} - -//Updates the best-matches group -void KateCompletionModel::updateBestMatches() { - int maxMatches = 300; //We cannot do too many operations here, because they are all executed whenever a character is added. Would be nice if we could split the operations up somewhat using a timer. - - m_updateBestMatchesTimer->stop(); - //Maps match-qualities to ModelRows paired together with the BestMatchesCount returned by the items. - typedef QMultiMap > BestMatchMap; - BestMatchMap matches; - - if(!hasGroups()) { - //If there is no grouping, just change the order of the items, moving the best matching ones to the front - QMultiMap rowsForQuality; - - int row = 0; - foreach(const Item& item, m_ungrouped->filtered) { - ModelRow source = item.sourceRow(); - - QVariant v = source.second.data(CodeCompletionModel::BestMatchesCount); - - if( v.type() == QVariant::Int && v.toInt() > 0 ) { - int quality = contextMatchQuality(source); - if(quality > 0) - rowsForQuality.insert(quality, row); - } - - ++row; - --maxMatches; - if(maxMatches < 0) - break; - } - - if(!rowsForQuality.isEmpty()) { - //Rewrite m_ungrouped->filtered in a new order - QSet movedToFront; - QList newFiltered; - for(QMultiMap::const_iterator it = rowsForQuality.constBegin(); it != rowsForQuality.constEnd(); ++it) { - newFiltered.prepend(m_ungrouped->filtered[it.value()]); - movedToFront.insert(it.value()); - } - - { - uint size = m_ungrouped->filtered.size(); - for(uint a = 0; a < size; ++a) - if(!movedToFront.contains(a)) - newFiltered.append(m_ungrouped->filtered[a]); - } - m_ungrouped->filtered = newFiltered; - } - return; - } - - ///@todo Cache the CodeCompletionModel::BestMatchesCount - foreach (Group* g, m_rowTable) { - if( g == m_bestMatches ) - continue; - for( int a = 0; a < g->filtered.size(); a++ ) - { - ModelRow source = g->filtered[a].sourceRow(); - - QVariant v = source.second.data(CodeCompletionModel::BestMatchesCount); - - if( v.type() == QVariant::Int && v.toInt() > 0 ) { - //Return the best match with any of the argument-hints - - int quality = contextMatchQuality(source); - if( quality > 0 ) - matches.insert(quality, qMakePair(v.toInt(), g->filtered[a].sourceRow())); - --maxMatches; - } - - if( maxMatches < 0 ) - break; - } - if( maxMatches < 0 ) - break; - } - - //Now choose how many of the matches will be taken. This is done with the rule: - //The count of shown best-matches should equal the average count of their BestMatchesCounts - int cnt = 0; - int matchesSum = 0; - BestMatchMap::const_iterator it = matches.constEnd(); - while( it != matches.constBegin() ) - { - --it; - ++cnt; - matchesSum += (*it).first; - if( cnt > matchesSum / cnt ) - break; - } - - m_bestMatches->filtered.clear(); - - it = matches.constEnd(); - - while( it != matches.constBegin() && cnt > 0 ) - { - --it; - --cnt; - - m_bestMatches->filtered.append( Item( true, this, HierarchicalModelHandler((*it).second.first), (*it).second) ); - } - - hideOrShowGroup(m_bestMatches); -} - -void KateCompletionModel::rowSelected(const QModelIndex& row) { - ExpandingWidgetModel::rowSelected(row); - ///@todo delay this - int rc = widget()->argumentHintModel()->rowCount(QModelIndex()); - if( rc == 0 ) return; - - //For now, simply update the whole column 0 - QModelIndex start = widget()->argumentHintModel()->index(0,0); - QModelIndex end = widget()->argumentHintModel()->index(rc-1,0); - - widget()->argumentHintModel()->emitDataChanged(start, end); -} - -void KateCompletionModel::clearCompletionModels() -{ - foreach (CodeCompletionModel * model, m_completionModels) - model->disconnect(this); - - m_completionModels.clear(); - - m_currentMatch.clear(); - - clearGroups(); -} - -#include "katecompletionmodel.moc" -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/completion/katecompletionmodel.h b/part/completion/katecompletionmodel.h deleted file mode 100644 index fd242cc..0000000 --- a/part/completion/katecompletionmodel.h +++ /dev/null @@ -1,395 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005-2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATECOMPLETIONMODEL_H -#define KATECOMPLETIONMODEL_H - -#include -#include -#include -#include - -#include - -#include "katepartprivate_export.h" -#include "expandingtree/expandingwidgetmodel.h" - -class KateCompletionWidget; -class KateArgumentHintModel; -class KateView; -class QWidget; -class QTextEdit; -class QTimer; -class HierarchicalModelHandler; - -/** - * This class has the responsibility for filtering, sorting, and manipulating - * code completion data provided by a CodeCompletionModel. - * - * @author Hamish Rodda - */ -class KATEPART_TESTS_EXPORT KateCompletionModel : public ExpandingWidgetModel -{ - Q_OBJECT - - public: - KateCompletionModel(KateCompletionWidget* parent = 0L); - ~KateCompletionModel(); - - QList completionModels() const; - void clearCompletionModels(); - void addCompletionModel(KTextEditor::CodeCompletionModel* model); - void setCompletionModel(KTextEditor::CodeCompletionModel* model); - void setCompletionModels(const QList& models); - void removeCompletionModel(KTextEditor::CodeCompletionModel* model); - - KateView* view() const; - KateCompletionWidget* widget() const; - - QString currentCompletion(KTextEditor::CodeCompletionModel* model) const; - void setCurrentCompletion(KTextEditor::CodeCompletionModel* model, const QString& completion); - - Qt::CaseSensitivity matchCaseSensitivity() const; - void setMatchCaseSensitivity( Qt::CaseSensitivity cs ); - - static QString columnName(int column); - int translateColumn(int sourceColumn) const; - - static QString propertyName(KTextEditor::CodeCompletionModel::CompletionProperty property); - - ///Returns a common prefix for all current visible completion entries - ///If there is no common prefix, extracts the next useful prefix for the selected index - QString commonPrefix(QModelIndex selectedIndex) const; - - virtual void rowSelected(const QModelIndex& row); - - virtual bool indexIsItem(const QModelIndex& index) const; - - virtual int columnCount ( const QModelIndex & parent = QModelIndex() ) const; - virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; - virtual Qt::ItemFlags flags ( const QModelIndex & index ) const; - virtual bool hasChildren ( const QModelIndex & parent = QModelIndex() ) const; - virtual bool hasIndex ( int row, int column, const QModelIndex & parent = QModelIndex() ) const; - virtual QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex() ) const; - - // Disabled in case of bugs, reenable once fully debugged. - //virtual QMap itemData ( const QModelIndex & index ) const; - virtual QModelIndex parent ( const QModelIndex & index ) const; - virtual int rowCount ( const QModelIndex & parent = QModelIndex() ) const; - - // Disabled in case of bugs, reenable once fully debugged. - //virtual QModelIndex sibling ( int row, int column, const QModelIndex & index ) const; - virtual void sort ( int column, Qt::SortOrder order = Qt::AscendingOrder ); - - ///Maps from this display-model into the appropriate source code-completion model - virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const; - - ///Maps from an index in a source-model to the index of the item in this display-model - virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const; - - // Sorting - bool isSortingEnabled() const; - bool isSortingAlphabetical() const; - bool isSortingByInheritanceDepth() const; - void setSortingByInheritanceDepth(bool byIneritance); - void setSortingAlphabetical(bool alphabetical); - - Qt::CaseSensitivity sortingCaseSensitivity() const; - void setSortingCaseSensitivity(Qt::CaseSensitivity cs); - - bool isSortingReverse() const; - void setSortingReverse(bool reverse); - - // Filtering - bool isFilteringEnabled() const; - - bool filterContextMatchesOnly() const; - void setFilterContextMatchesOnly(bool filter); - - bool filterByAttribute() const; - void setFilterByAttribute(bool filter); - - KTextEditor::CodeCompletionModel::CompletionProperties filterAttributes() const; - void setFilterAttributes(KTextEditor::CodeCompletionModel::CompletionProperties attributes); - - // A maximum depth of <= 0 equals don't filter by inheritance depth (i.e. infinity) and is default - int maximumInheritanceDepth() const; - void setMaximumInheritanceDepth(int maxDepth); - - // Grouping - bool isGroupingEnabled() const; - - enum gm { - ScopeType = 0x1, - Scope = 0x2, - AccessType = 0x4, - ItemType = 0x8 - }; - - enum { //An own property that will be used to mark the best-matches group internally - BestMatchesProperty = 2*KTextEditor::CodeCompletionModel::LastProperty - }; - - Q_DECLARE_FLAGS(GroupingMethods, gm) - - static const int ScopeTypeMask = 0x380000; - static const int AccessTypeMask = 0x7; - static const int ItemTypeMask = 0xfe0; - - GroupingMethods groupingMethod() const; - void setGroupingMethod(GroupingMethods m); - - bool accessIncludeConst() const; - void setAccessIncludeConst(bool include); - bool accessIncludeStatic() const; - void setAccessIncludeStatic(bool include); - bool accessIncludeSignalSlot() const; - void setAccessIncludeSignalSlot(bool include); - - // Column merging - bool isColumnMergingEnabled() const; - - const QList< QList >& columnMerges() const; - void setColumnMerges(const QList< QList >& columnMerges); - - void debugStats(); - - ///Returns whether one of the filtered items exactly matches its completion string - bool shouldMatchHideCompletionList() const; - - uint filteredItemCount() const; - - protected: - virtual int contextMatchQuality(const QModelIndex & index) const; - - Q_SIGNALS: - void expandIndex(const QModelIndex& index); - //Emitted whenever something has changed about the group of argument-hints - void argumentHintsChanged(); - void contentGeometryChanged(); - - public Q_SLOTS: - void setSortingEnabled(bool enable); - void setFilteringEnabled(bool enable); - void setGroupingEnabled(bool enable); - void setColumnMergingEnabled(bool enable); - - private Q_SLOTS: - void slotRowsInserted( const QModelIndex & parent, int start, int end ); - void slotRowsRemoved( const QModelIndex & parent, int start, int end ); - void slotModelReset(); - - //Updates the best-matches group - void updateBestMatches(); - - private: - - typedef QPair ModelRow; - virtual int contextMatchQuality(const ModelRow& sourceRow) const; - - QTreeView* treeView() const; - - friend class KateArgumentHintModel; - ModelRow modelRowPair(const QModelIndex& index) const; - - // Represents a source row; provides sorting method - class Item { - public: - Item(bool doInitialMatch, KateCompletionModel* model, const HierarchicalModelHandler& handler, ModelRow sourceRow); - - bool isValid() const; - // Returns true if the item is not filtered and matches the current completion string - bool isVisible() const; - // Returns whether the item is filtered or not - bool isFiltered() const; - // Returns whether the item matches the current completion string - bool isMatching() const; - - bool filter(); - enum MatchType { - NoMatch = 0, - StartsWithMatch, - PerfectMatch - }; - MatchType match(); - - const ModelRow& sourceRow() const; - - // Sorting operator - bool operator<(const Item& rhs) const; - - bool haveExactMatch() const { - return m_haveExactMatch; - } - - void clearExactMatch() { - m_haveExactMatch = false; - } - - QString name() const { - return m_nameColumn; - } - - private: - KateCompletionModel* model; - ModelRow m_sourceRow; - - mutable QString m_nameColumn, m_completionSortingName; - - int inheritanceDepth; - - // True when currently matching completion string - MatchType matchCompletion; - // True when passes all active filters - bool matchFilters, m_haveExactMatch; - - QString completionSortingName() const; - }; - - public: - // Grouping and sorting of rows - class Group { - public: - explicit Group(KateCompletionModel* model); - - void addItem(Item i, bool notifyModel = false); - /// Removes the item specified by \a row. Returns true if a change was made to rows. - bool removeItem(const ModelRow& row); - void resort(); - void refilter(); - void clear(); - //Returns whether this group should be ordered before other - bool orderBefore(Group* other) const; - //Returns a number that can be used for ordering - int orderNumber() const; - - ///Returns the row in the this group's filtered list of the given model-row in a source-model - ///-1 if the item is not in the filtered list - ///@todo Implement an efficient way of doing this map, that does _not_ iterate over all items! - int rowOf(ModelRow item) { - for(int a = 0; a < filtered.size(); ++a) - if(filtered[a].sourceRow() == item) - return a; - return -1; - } - - KateCompletionModel* model; - int attribute; - QString title, scope; - QList filtered; - QList prefilter; - bool isEmpty; - //-1 if none was set - int customSortingKey; - }; - - bool hasGroups() const; - - private: - QString commonPrefixInternal(const QString &forcePrefix) const; - void createGroups(); - ///Creates all sub-items of index i, or the item corresponding to index i. Returns the affected groups. - ///i must be an index in the source model - QSet createItems(const HierarchicalModelHandler&, const QModelIndex& i, bool notifyModel = false); - ///Deletes all sub-items of index i, or the item corresponding to index i. Returns the affected groups. - ///i must be an index in the source model - QSet deleteItems(const QModelIndex& i); - Group* createItem(const HierarchicalModelHandler&, const QModelIndex& i, bool notifyModel = false); - void clearGroups(bool reset = true); - void hideOrShowGroup(Group* g, bool notifyModel = true); - /// When forceGrouping is enabled, all given attributes will be used for grouping, regardless of the completion settings. - Group* fetchGroup(int attribute, const QString& scope = QString(), bool forceGrouping = false); - //If this returns nonzero on an index, the index is the header of the returned group - Group* groupForIndex(const QModelIndex& index) const; - inline Group* groupOfParent(const QModelIndex& child) const { return static_cast(child.internalPointer()); } - QModelIndex indexForRow(Group* g, int row) const; - QModelIndex indexForGroup(Group* g) const; - - enum changeTypes { - Broaden, - Narrow, - Change - }; - - //Returns whether the model needs to be reset - bool changeCompletions(Group* g, changeTypes changeType); - - bool hasCompletionModel() const; - - /// Removes attributes not used in grouping from the input \a attribute - int groupingAttributes(int attribute) const; - int countBits(int value) const; - - void resort(); - void refilter(); - - bool m_hasGroups; - - // ### Runtime state - // General - QList m_completionModels; - QMap m_currentMatch; - Qt::CaseSensitivity m_matchCaseSensitivity; - - // Column merging - QList< QList > m_columnMerges; - - QTimer* m_updateBestMatchesTimer; - - Group* m_ungrouped; - Group* m_argumentHints; //The argument-hints will be passed on to another model, to be shown in another widget - Group* m_bestMatches; //A temporary group used for holding the best matches of all visible items - - // Storing the sorted order - QList m_rowTable; - QList m_emptyGroups; - // Quick access to each specific group (if it exists) - QMultiHash m_groupHash; - // Maps custom group-names to their specific groups - QHash m_customGroupHash; - - // ### Configurable state - // Sorting - bool m_sortingEnabled; - bool m_sortingAlphabetical; - bool m_isSortingByInheritance; - Qt::CaseSensitivity m_sortingCaseSensitivity; - QHash< int, QList > m_sortingGroupingOrder; - - // Filtering - bool m_filteringEnabled; - bool m_filterContextMatchesOnly; - bool m_filterByAttribute; - KTextEditor::CodeCompletionModel::CompletionProperties m_filterAttributes; - int m_maximumInheritanceDepth; - - // Grouping - bool m_groupingEnabled; - GroupingMethods m_groupingMethod; - bool m_accessConst, m_accessStatic, m_accesSignalSlot; - - // Column merging - bool m_columnMergingEnabled/*, m_haveExactMatch*/; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(KateCompletionModel::GroupingMethods) - -#endif diff --git a/part/completion/katecompletiontree.cpp b/part/completion/katecompletiontree.cpp deleted file mode 100644 index 52030d8..0000000 --- a/part/completion/katecompletiontree.cpp +++ /dev/null @@ -1,403 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecompletiontree.h" - -#include -#include -#include -#include -#include -#include - -#include "kateview.h" -#include "katerenderer.h" -#include "kateconfig.h" - -#include "katecompletionwidget.h" -#include "katecompletiondelegate.h" -#include "katecompletionmodel.h" - -KateCompletionTree::KateCompletionTree(KateCompletionWidget* parent) - : ExpandingTree(parent) -{ - m_scrollingEnabled = true; - header()->hide(); - setRootIsDecorated(false); - setIndentation(0); - setFrameStyle(QFrame::NoFrame); - setAllColumnsShowFocus(true); - setAlternatingRowColors(true); - //We need ScrollPerItem, because ScrollPerPixel is too slow with a very large competion-list(see KDevelop). - setVerticalScrollMode(QAbstractItemView::ScrollPerItem); - - m_resizeTimer = new QTimer(this); - m_resizeTimer->setSingleShot(true); - - connect(m_resizeTimer, SIGNAL(timeout()), this, SLOT(resizeColumnsSlot())); - - // Provide custom highlighting to completion entries - setItemDelegate(new KateCompletionDelegate(widget()->model(), widget())); - - ///@todo uncomment this once we're sure it isn't called too often, or maybe use a timer. - //connect(widget()->model(), SIGNAL(contentGeometryChanged()), this, SLOT(resizeColumnsSlot())); - - // Prevent user from expanding / collapsing with the mouse - setItemsExpandable(false); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); -} - -void KateCompletionTree::currentChanged ( const QModelIndex & current, const QModelIndex & previous ) { - widget()->model()->rowSelected(current); - ExpandingTree::currentChanged(current, previous); -} - -void KateCompletionTree::setScrollingEnabled(bool enabled) { - m_scrollingEnabled = enabled; -} - -void KateCompletionTree::scrollContentsBy( int dx, int dy ) -{ - if(m_scrollingEnabled) - QTreeView::scrollContentsBy(dx, dy); - - if (isVisible()) - m_resizeTimer->start(300); -} - -int KateCompletionTree::columnTextViewportPosition ( int column ) const { - int ret = columnViewportPosition(column); - QModelIndex i = model()->index(0, column, QModelIndex()); - QModelIndex base = model()->index(0, 0, QModelIndex()); - - //If it's just a group header, use the first child - if(base.isValid() && model()->rowCount(base)) - i = base.child(0, column); - - if(i.isValid()) { - QIcon icon = i.data(Qt::DecorationRole).value(); - if(!icon.isNull()) - ret += icon.actualSize(sizeHintForIndex(i)).width(); - } - return ret; -} - -KateCompletionWidget * KateCompletionTree::widget( ) const -{ - return static_cast(const_cast(parent())); -} - -void KateCompletionTree::resizeColumnsSlot() -{ - if(model()) - resizeColumns(); -} - -void KateCompletionTree::resizeColumns(bool firstShow, bool forceResize) -{ - static bool preventRecursion = false; - if (preventRecursion) - return; - - if(firstShow) - forceResize = true; - - preventRecursion = true; - - widget()->setUpdatesEnabled(false); - - int modelIndexOfName = kateModel()->translateColumn(KTextEditor::CodeCompletionModel::Name); - int oldIndentWidth = columnViewportPosition(modelIndexOfName); - - ///Step 1: Compute the needed column-sizes for the visible content - - int numColumns = model()->columnCount(); - - QVector columnSize(numColumns, 5); - - int currentYPos = 0; - - QModelIndex current = indexAt(QPoint(1,1)); - if( current.child(0,0).isValid() ) { //If the index has children, it is a group-label. Then we should start with it's first child. - currentYPos += sizeHintForIndex(current).height(); - current = current.child(0,0); - } - - int num = 0; - bool changed = false; - - while( current.isValid() && currentYPos < height() ) - { -// kDebug() << current.row() << "out of" << model()->rowCount(current.parent()) << "in" << current.parent().data(Qt::DisplayRole); - currentYPos += sizeHintForIndex(current).height(); -// itemDelegate()->sizeHint(QStyleOptionViewItem(), current).isValid() && itemDelegate()->sizeHint(QStyleOptionViewItem(), current).intersects(visibleViewportRect) - changed = true; - num++; - for( int a = 0; a < numColumns; a++ ) - { - QSize s = sizeHintForIndex (current.sibling(current.row(), a)); -// kDebug() << "size-hint for" << current.row() << a << ":" << s << current.sibling(current.row(), a).data(Qt::DisplayRole); - if( s.width() > columnSize[a] && s.width() < 2000 ) - columnSize[a] = s.width(); - else if( s.width() > 2000 ) - kDebug( 13035 ) << "got invalid size-hint of width " << s.width(); - } - - QModelIndex oldCurrent = current; - current = current.sibling(current.row()+1, 0); - - //Are we at the end of a group? If yes, move on into the next group - if( !current.isValid() && oldCurrent.parent().isValid() ) { - current = oldCurrent.parent().sibling( oldCurrent.parent().row()+1, 0 ); - if( current.isValid() && current.child(0,0).isValid() ) { - currentYPos += sizeHintForIndex(current).height(); - current = current.child(0,0); - } - } - } - - int totalColumnsWidth = 0, originalViewportWidth = viewport()->width(); - - int maxWidth = (QApplication::desktop()->screenGeometry(widget()->view()).width()*3) / 4; - - ///Step 2: Update column-sizes - //This contains several hacks to reduce the amount of resizing that happens. Generally, - //resizes only happen if a) More than a specific amount of space is saved by the resize, or - //b) the resizing is required so the list can show all of its contents. - int minimumResize = 0; - int maximumResize = 0; - - if( changed ) { - - for( int n = 0; n < numColumns; n++ ) { - totalColumnsWidth += columnSize[n]; - - int diff = columnSize[n] - columnWidth(n); - if( diff < minimumResize ) - minimumResize = diff; - if( diff > maximumResize ) - maximumResize = diff; - } - - int noReduceTotalWidth = 0; //The total width of the widget of no columns are reduced - for( int n = 0; n < numColumns; n++ ) { - if(columnSize[n] < columnWidth(n)) - noReduceTotalWidth += columnWidth(n); - else - noReduceTotalWidth += columnSize[n]; - } - - //Check whether we can afford to reduce none of the columns - //Only reduce size if we widget would else be too wide. - bool noReduce = noReduceTotalWidth < maxWidth && !forceResize; - - if(noReduce) { - totalColumnsWidth = 0; - for( int n = 0; n < numColumns; n++ ) { - if(columnSize[n] < columnWidth(n)) - columnSize[n] = columnWidth(n); - - totalColumnsWidth += columnSize[n]; - } - } - - if( minimumResize > -40 && maximumResize == 0 && !forceResize ) { - //No column needs to be exanded, and no column needs to be reduced by more than 40 pixels. - //To prevent flashing, do not resize at all. - totalColumnsWidth = 0; - for( int n = 0; n < numColumns; n++ ) { - columnSize[n] = columnWidth(n); - totalColumnsWidth += columnSize[n]; - } - } else { -// viewport()->resize( 5000, viewport()->height() ); - for( int n = 0; n < numColumns; n++ ) { - setColumnWidth(n, columnSize[n]); - } -// kDebug() << "resizing viewport to" << totalColumnsWidth; - viewport()->resize( totalColumnsWidth, viewport()->height() ); - } - } - - ///Step 3: Update widget-size and -position - - int scrollBarWidth = verticalScrollBar()->width(); - - int newIndentWidth = columnViewportPosition(modelIndexOfName); - - int newWidth = qMin(maxWidth, qMax(75, totalColumnsWidth)); - - if(newWidth == maxWidth) - setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - else - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - - if(maximumResize > 0 || forceResize || oldIndentWidth != newIndentWidth) { - - // kDebug() << geometry() << "newWidth" << newWidth << "current width" << width() << "target width" << newWidth + scrollBarWidth; - - if((newWidth + scrollBarWidth) != width() && originalViewportWidth != totalColumnsWidth) - { - widget()->resize(newWidth + scrollBarWidth + 2, widget()->height()); - resize(newWidth + scrollBarWidth, widget()->height()- (2*widget()->frameWidth())); - } - - // kDebug() << "created geometry:" << widget()->geometry() << geometry() << "newWidth" << newWidth << "viewport" << viewport()->width(); - - if( viewport()->width() > totalColumnsWidth ) //Set the size of the last column to fill the whole rest of the widget - setColumnWidth(numColumns-1, viewport()->width() - columnViewportPosition(numColumns-1)); - - /* for(int a = 0; a < numColumns; ++a) - kDebug() << "column" << a << columnWidth(a) << "target:" << columnSize[a];*/ - - if (oldIndentWidth != newIndentWidth) - if(widget()->updatePosition() && !forceResize) { - preventRecursion = false; - resizeColumns(true, true); - } - } - - widget()->setUpdatesEnabled(true); - - preventRecursion = false; -} - -QStyleOptionViewItem KateCompletionTree::viewOptions( ) const -{ - QStyleOptionViewItem opt = QTreeView::viewOptions(); - - opt.font = widget()->view()->renderer()->config()->font(); - - return opt; -} - -KateCompletionModel * KateCompletionTree::kateModel( ) const -{ - return static_cast(model()); -} - -bool KateCompletionTree::nextCompletion() -{ - QModelIndex current; - QModelIndex firstCurrent = currentIndex(); - - do { - QModelIndex oldCurrent = currentIndex(); - - current = moveCursor(MoveDown, Qt::NoModifier); - - if (current != oldCurrent && current.isValid()) { - setCurrentIndex(current); - } else { - if (firstCurrent.isValid()) - setCurrentIndex(firstCurrent); - return false; - } - - } while (!kateModel()->indexIsItem(current)); - - return true; -} - -bool KateCompletionTree::previousCompletion() -{ - QModelIndex current; - QModelIndex firstCurrent = currentIndex(); - - do { - QModelIndex oldCurrent = currentIndex(); - - current = moveCursor(MoveUp, Qt::NoModifier); - - if (current != oldCurrent && current.isValid()) { - setCurrentIndex(current); - - } else { - if (firstCurrent.isValid()) - setCurrentIndex(firstCurrent); - return false; - } - - } while (!kateModel()->indexIsItem(current)); - - return true; -} - -bool KateCompletionTree::pageDown( ) -{ - QModelIndex old = currentIndex(); - - QModelIndex current = moveCursor(MovePageDown, Qt::NoModifier); - - if (current.isValid()) { - setCurrentIndex(current); - if (!kateModel()->indexIsItem(current)) - if (!nextCompletion()) - previousCompletion(); - } - - return current != old; -} - -bool KateCompletionTree::pageUp( ) -{ - QModelIndex old = currentIndex(); - QModelIndex current = moveCursor(MovePageUp, Qt::NoModifier); - - if (current.isValid()) { - setCurrentIndex(current); - if (!kateModel()->indexIsItem(current)) - if (!previousCompletion()) - nextCompletion(); - } - return current != old; -} - -void KateCompletionTree::top( ) -{ - QModelIndex current = moveCursor(MoveHome, Qt::NoModifier); - setCurrentIndex(current); - - if (current.isValid()) { - setCurrentIndex(current); - if (!kateModel()->indexIsItem(current)) - nextCompletion(); - } -} - -void KateCompletionTree::scheduleUpdate() -{ - m_resizeTimer->start(300); -} - -void KateCompletionTree::bottom( ) -{ - QModelIndex current = moveCursor(MoveEnd, Qt::NoModifier); - setCurrentIndex(current); - - if (current.isValid()) { - setCurrentIndex(current); - if (!kateModel()->indexIsItem(current)) - previousCompletion(); - } -} - -#include "katecompletiontree.moc" diff --git a/part/completion/katecompletiontree.h b/part/completion/katecompletiontree.h deleted file mode 100644 index 205a781..0000000 --- a/part/completion/katecompletiontree.h +++ /dev/null @@ -1,71 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATECOMPLETIONTREE_H -#define KATECOMPLETIONTREE_H - -#include "expandingtree/expandingtree.h" - -class KateCompletionWidget; -class KateCompletionModel; - -class QTimer; - -class KateCompletionTree : public ExpandingTree -{ - Q_OBJECT - - public: - explicit KateCompletionTree(KateCompletionWidget* parent); - - KateCompletionWidget* widget() const; - KateCompletionModel* kateModel() const; - - void resizeColumns(bool firstShow = false, bool forceResize = false); - - // Navigation - bool nextCompletion(); - bool previousCompletion(); - bool pageDown(); - bool pageUp(); - void top(); - void bottom(); - - void scheduleUpdate(); - - void setScrollingEnabled(bool); - - /// Returns the approximated viewport position of the text in the given column, skipping an eventual icon - int columnTextViewportPosition ( int column ) const; - - private slots: - void resizeColumnsSlot(); - - protected: - virtual void currentChanged ( const QModelIndex & current, const QModelIndex & previous ); ///Not available as a signal in this way - virtual void scrollContentsBy(int dx, int dy); - virtual QStyleOptionViewItem viewOptions() const; - private: - bool m_scrollingEnabled; - QTimer* m_resizeTimer; -}; - -#endif diff --git a/part/completion/katecompletionwidget.cpp b/part/completion/katecompletionwidget.cpp deleted file mode 100644 index 5841be1..0000000 --- a/part/completion/katecompletionwidget.cpp +++ /dev/null @@ -1,1387 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005-2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecompletionwidget.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#include "kateview.h" -#include "katerenderer.h" -#include "kateconfig.h" -#include "katedocument.h" -#include "katebuffer.h" - -#include "katecompletionmodel.h" -#include "katecompletiontree.h" -#include "katecompletionconfig.h" -#include "kateargumenthinttree.h" -#include "kateargumenthintmodel.h" - -//#include "modeltest.h" - -const bool hideAutomaticCompletionOnExactMatch = true; - -//If this is true, the completion-list is navigated up/down when 'tab' is pressed, instead of doing partial completion -const bool shellLikeTabCompletion = false; - -#define CALLCI(WHAT,WHATELSE,WHAT2,model,FUNC) \ -{\ - static KTextEditor::CodeCompletionModelControllerInterface3 defaultIf;\ - KTextEditor::CodeCompletionModelControllerInterface3* ret =\ - qobject_cast(model);\ - if (!ret) {\ - WHAT2 defaultIf.FUNC;\ - }else \ - WHAT2 ret->FUNC;\ -} - - -static KTextEditor::Range _completionRange(KTextEditor::CodeCompletionModel *model, KTextEditor::View *view, const KTextEditor::Cursor& cursor){ - CALLCI(return,,return, model,completionRange(view, cursor)); -} - -static KTextEditor::Range _updateRange(KTextEditor::CodeCompletionModel *model,KTextEditor::View *view, KTextEditor::Range& range) { - CALLCI(, return range,return, model,updateCompletionRange(view, range)); -} - -static QString _filterString(KTextEditor::CodeCompletionModel *model,KTextEditor::View *view, const KTextEditor::Range& range, const KTextEditor::Cursor& cursor) { - CALLCI(return,,return, model,filterString(view, range, cursor)); -} - -static bool _shouldAbortCompletion(KTextEditor::CodeCompletionModel *model,KTextEditor::View *view, const KTextEditor::Range& range, const QString& currentCompletion) { - CALLCI(return,,return, model,shouldAbortCompletion(view, range, currentCompletion)); -} - -static void _aborted(KTextEditor::CodeCompletionModel *model,KTextEditor::View *view) { - CALLCI(return,,return, model,aborted(view)); -} - -static bool _shouldStartCompletion(KTextEditor::CodeCompletionModel *model,KTextEditor::View *view, QString m_automaticInvocationLine,bool m_lastInsertionByUser, const KTextEditor::Cursor& cursor) { - CALLCI(return,,return,model,shouldStartCompletion(view, m_automaticInvocationLine, m_lastInsertionByUser, cursor)); -} - -KateCompletionWidget::KateCompletionWidget(KateView* parent) - : QFrame(parent, Qt::ToolTip) - , m_presentationModel(new KateCompletionModel(this)) - , m_entryList(new KateCompletionTree(this)) - , m_argumentHintModel(new KateArgumentHintModel(this)) - , m_argumentHintTree(new KateArgumentHintTree(this)) - , m_automaticInvocationDelay(100) - , m_filterInstalled(false) - , m_configWidget(new KateCompletionConfig(m_presentationModel, view())) - , m_lastInsertionByUser(false) - , m_inCompletionList(false) - , m_isSuspended(false) - , m_dontShowArgumentHints(false) - , m_needShow(false) - , m_hadCompletionNavigation(false) - , m_noAutoHide(false) - , m_completionEditRunning (false) - , m_expandedAddedHeightBase(0) - , m_lastInvocationType(KTextEditor::CodeCompletionModel::AutomaticInvocation) -{ - connect(parent, SIGNAL(navigateAccept()), SLOT(navigateAccept())); - connect(parent, SIGNAL(navigateBack()), SLOT(navigateBack())); - connect(parent, SIGNAL(navigateDown()), SLOT(navigateDown())); - connect(parent, SIGNAL(navigateLeft()), SLOT(navigateLeft())); - connect(parent, SIGNAL(navigateRight()), SLOT(navigateRight())); - connect(parent, SIGNAL(navigateUp()), SLOT(navigateUp())); - - qRegisterMetaType("KTextEditor::Cursor"); - - setFrameStyle( QFrame::Box | QFrame::Plain ); - setLineWidth( 1 ); - //setWindowOpacity(0.8); - - m_entryList->setModel(m_presentationModel); - m_entryList->setColumnWidth(0, 0); //These will be determined automatically in KateCompletionTree::resizeColumns - m_entryList->setColumnWidth(1, 0); - m_entryList->setColumnWidth(2, 0); - - m_entryList->setVerticalScrollMode(QAbstractItemView::ScrollPerItem); - - m_argumentHintTree->setParent(0, Qt::ToolTip); - m_argumentHintTree->setModel(m_argumentHintModel); - - connect(m_entryList->verticalScrollBar(), SIGNAL(valueChanged(int)), m_presentationModel, SLOT(placeExpandingWidgets())); - connect(m_argumentHintTree->verticalScrollBar(), SIGNAL(valueChanged(int)), m_argumentHintModel, SLOT(placeExpandingWidgets())); - connect(view(), SIGNAL(focusOut(KTextEditor::View*)), this, SLOT(viewFocusOut())); - - m_automaticInvocationTimer = new QTimer(this); - m_automaticInvocationTimer->setSingleShot(true); - connect(m_automaticInvocationTimer, SIGNAL(timeout()), this, SLOT(automaticInvocation())); - - // Keep branches expanded - connect(m_presentationModel, SIGNAL(modelReset()), this, SLOT(modelReset())); - connect(m_presentationModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SLOT(rowsInserted(const QModelIndex&, int, int))); - connect(m_argumentHintModel, SIGNAL(contentStateChanged(bool)), this, SLOT(argumentHintsChanged(bool))); - - // No smart lock, no queued connects - connect(view(), SIGNAL(cursorPositionChanged(KTextEditor::View*, const KTextEditor::Cursor&)), this, SLOT(cursorPositionChanged())); - connect(view(), SIGNAL(verticalScrollPositionChanged (KTextEditor::View*, const KTextEditor::Cursor&)), this, SLOT(updatePositionSlot())); - - /** - * connect to all possible editing primitives - */ - connect(&view()->doc()->buffer(), SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&))); - connect(&view()->doc()->buffer(), SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int))); - connect(&view()->doc()->buffer(), SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &))); - connect(&view()->doc()->buffer(), SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &))); - - // This is a non-focus widget, it is passed keyboard input from the view - - //We need to do this, because else the focus goes to nirvana without any control when the completion-widget is clicked. - setFocusPolicy(Qt::ClickFocus); - m_argumentHintTree->setFocusPolicy(Qt::ClickFocus); - - foreach (QWidget* childWidget, findChildren()) - childWidget->setFocusPolicy(Qt::NoFocus); - - //Position the entry-list so a frame can be drawn around it - m_entryList->move(frameWidth(), frameWidth()); -} - -KateCompletionWidget::~KateCompletionWidget() { -} - -void KateCompletionWidget::viewFocusOut() { - abortCompletion(); -} - -void KateCompletionWidget::modelContentChanged() { - kDebug()<<">>>>>>>>>>>>>>>>"; - if(m_completionRanges.isEmpty()) { - kDebug( 13035 ) << "content changed, but no completion active"; - abortCompletion(); - return; - } - - if(!view()->hasFocus()) { - kDebug( 13035 ) << "view does not have focus"; - return; - } - - if(!m_waitingForReset.isEmpty()) { - kDebug( 13035 ) << "waiting for" << m_waitingForReset.size() << "completion-models to reset"; - return; - } - - int realItemCount = 0; - foreach (KTextEditor::CodeCompletionModel* model, m_presentationModel->completionModels()) - realItemCount += model->rowCount(); - if( !m_isSuspended && ((isHidden() && m_argumentHintTree->isHidden()) || m_needShow) && realItemCount != 0 ) { - m_needShow = false; - updateAndShow(); - } - - if(m_argumentHintModel->rowCount(QModelIndex()) == 0) - m_argumentHintTree->hide(); - - if(m_presentationModel->rowCount(QModelIndex()) == 0) - hide(); - - - //With each filtering items can be added or removed, so we have to reset the current index here so we always have a selected item - m_entryList->setCurrentIndex(model()->index(0,0)); - if(!model()->indexIsItem(m_entryList->currentIndex())) { - QModelIndex firstIndex = model()->index(0,0, m_entryList->currentIndex()); - m_entryList->setCurrentIndex(firstIndex); - //m_entryList->scrollTo(firstIndex, QAbstractItemView::PositionAtTop); - } - - updateHeight(); - - //New items for the argument-hint tree may have arrived, so check whether it needs to be shown - if( m_argumentHintTree->isHidden() && !m_dontShowArgumentHints && m_argumentHintModel->rowCount(QModelIndex()) != 0 ) - m_argumentHintTree->show(); - - if(!m_noAutoHide && hideAutomaticCompletionOnExactMatch && !isHidden() && - m_lastInvocationType == KTextEditor::CodeCompletionModel::AutomaticInvocation && - m_presentationModel->shouldMatchHideCompletionList()) - hide(); - else if(isHidden() && !m_presentationModel->shouldMatchHideCompletionList() && - m_presentationModel->rowCount(QModelIndex())) - show(); -} - -KateArgumentHintTree* KateCompletionWidget::argumentHintTree() const { - return m_argumentHintTree; -} - -KateArgumentHintModel* KateCompletionWidget::argumentHintModel() const { - return m_argumentHintModel; -} - -const KateCompletionModel* KateCompletionWidget::model() const { - return m_presentationModel; -} - -KateCompletionModel* KateCompletionWidget::model() { - return m_presentationModel; -} - -void KateCompletionWidget::rowsInserted(const QModelIndex& parent, int rowFrom, int rowEnd) -{ - m_entryList->setAnimated(false); - if(!model()->isGroupingEnabled()) - return; - - if (!parent.isValid()) - for (int i = rowFrom; i <= rowEnd; ++i) - m_entryList->expand(m_presentationModel->index(i, 0, parent)); -} - -KateView * KateCompletionWidget::view( ) const -{ - return static_cast(const_cast(parent())); -} - -void KateCompletionWidget::argumentHintsChanged(bool hasContent) -{ - m_dontShowArgumentHints = !hasContent; - - if( m_dontShowArgumentHints ) - m_argumentHintTree->hide(); - else - updateArgumentHintGeometry(); -} - -void KateCompletionWidget::startCompletion(KTextEditor::CodeCompletionModel::InvocationType invocationType, const QList& models) -{ - if(invocationType == KTextEditor::CodeCompletionModel::UserInvocation) - { - abortCompletion(); - } - startCompletion(KTextEditor::Range(KTextEditor::Cursor(-1, -1), KTextEditor::Cursor(-1, -1)), models, invocationType); -} - -void KateCompletionWidget::deleteCompletionRanges() -{ - //kDebug(); - foreach(const CompletionRange &r, m_completionRanges) - delete r.range; - m_completionRanges.clear(); -} - -void KateCompletionWidget::startCompletion(const KTextEditor::Range& word, KTextEditor::CodeCompletionModel* model, KTextEditor::CodeCompletionModel::InvocationType invocationType) -{ - QList models; - if (model) { - models << model; - } else { - models = m_sourceModels; - } - startCompletion(word, models, invocationType); -} - -void KateCompletionWidget::startCompletion(const KTextEditor::Range& word, const QList& modelsToStart, KTextEditor::CodeCompletionModel::InvocationType invocationType) -{ - - kDebug()<<"============"; - - m_isSuspended = false; - m_inCompletionList = true; //Always start at the top of the completion-list - m_needShow = true; - - if(m_completionRanges.isEmpty()) - m_noAutoHide = false; //Re-enable auto-hide on every clean restart of the completion - - m_lastInvocationType = invocationType; - - disconnect(this->model(), SIGNAL(contentGeometryChanged()), this, SLOT(modelContentChanged())); - - m_dontShowArgumentHints = true; - - QList models = (modelsToStart.isEmpty() ? m_sourceModels : modelsToStart); - - foreach(KTextEditor::CodeCompletionModel* model, m_completionRanges.keys()) - if(!models.contains(model)) - models << model; - - if (!m_filterInstalled) { - if (!QApplication::activeWindow()) { - kWarning(13035) << "No active window to install event filter on!!"; - return; - } - // Enable the cc box to move when the editor window is moved - QApplication::activeWindow()->installEventFilter(this); - m_filterInstalled = true; - } - - m_presentationModel->clearCompletionModels(); - - if(invocationType == KTextEditor::CodeCompletionModel::UserInvocation) { - deleteCompletionRanges(); - } - - foreach (KTextEditor::CodeCompletionModel* model, models) { - KTextEditor::Range range; - if (word.isValid()) { - range = word; - kDebug()<<"word is used"; - } else { - range=_completionRange(model,view(), view()->cursorPosition()); - kDebug()<<"completionRange has been called, cursor pos is"<cursorPosition(); - } - kDebug()<<"range is"<completionInvoked(view(), range, invocationType); - - disconnect(model, SIGNAL(waitForReset()), this, SLOT(waitForModelReset())); - - m_completionRanges[model] = view()->doc()->newMovingRange(range, KTextEditor::MovingRange::ExpandRight | KTextEditor::MovingRange::ExpandLeft); - - //In automatic invocation mode, hide the completion widget as soon as the position where the completion was started is passed to the left - m_completionRanges[model].leftBoundary = view()->cursorPosition(); - - //In manual invocation mode, bound the activity either the the point from where completion was invoked, or to the start of the range - if(invocationType != KTextEditor::CodeCompletionModel::AutomaticInvocation) - if(range.start() < m_completionRanges[model].leftBoundary) - m_completionRanges[model].leftBoundary = range.start(); - - if(!m_completionRanges[model].range->toRange().isValid()) { - kWarning(13035) << "Could not construct valid smart-range from" << range << "instead got" << *m_completionRanges[model].range; - abortCompletion(); - return; - } - } - - m_presentationModel->setCompletionModels(models); - - cursorPositionChanged(); - - if (!m_completionRanges.isEmpty()) { - connect(this->model(), SIGNAL(contentGeometryChanged()), this, SLOT(modelContentChanged())); - //Now that all models have been notified, check whether the widget should be displayed instantly - modelContentChanged(); - } - else { - abortCompletion(); - } -} - -void KateCompletionWidget::waitForModelReset() -{ - KTextEditor::CodeCompletionModel* senderModel = qobject_cast(sender()); - if(!senderModel) { - kWarning() << "waitForReset signal from bad model"; - return; - } - m_waitingForReset.insert(senderModel); -} - -void KateCompletionWidget::updateAndShow() -{ - kDebug()<<"*******************************************"; - if(!view()->hasFocus()) { - kDebug( 13035 ) << "view does not have focus"; - return; - } - - setUpdatesEnabled(false); - - modelReset(); - - m_argumentHintModel->buildRows(); - if( m_argumentHintModel->rowCount(QModelIndex()) != 0 ) - argumentHintsChanged(true); -// } - - //We do both actions twice here so they are stable, because they influence each other: - //updatePosition updates the height, resizeColumns needs the correct height to decide over - //how many rows it computs the column-width - updatePosition(true); - m_entryList->resizeColumns(true, true); - updatePosition(true); - m_entryList->resizeColumns(true, true); - - setUpdatesEnabled(true); - - if(m_argumentHintModel->rowCount(QModelIndex())) { - updateArgumentHintGeometry(); - m_argumentHintTree->show(); - } else - m_argumentHintTree->hide(); - - if (m_presentationModel->rowCount() && (!m_presentationModel->shouldMatchHideCompletionList() || - !hideAutomaticCompletionOnExactMatch || - m_lastInvocationType != KTextEditor::CodeCompletionModel::AutomaticInvocation) ) - show(); - else - hide(); -} - -void KateCompletionWidget::updatePositionSlot() -{ - updatePosition(); -} - -bool KateCompletionWidget::updatePosition(bool force) -{ - if (!force && !isCompletionActive()) - return false; - - if (!completionRange()) { - return false; - } - QPoint cursorPosition = view()->cursorToCoordinate(completionRange()->start()); - if (cursorPosition == QPoint(-1,-1)) { - // Start of completion range is now off-screen -> abort - abortCompletion(); - return false; - } - - QPoint p = view()->mapToGlobal( cursorPosition ); - int x = p.x() - m_entryList->columnTextViewportPosition(m_presentationModel->translateColumn(KTextEditor::CodeCompletionModel::Name)) - 4 - (m_entryList->viewport()->pos().x()); - int y = p.y(); - - y += view()->renderer()->config()->fontMetrics().height() + 4; - - bool borderHit = false; - - if (x + width() > QApplication::desktop()->screenGeometry(view()).right()) { - x = QApplication::desktop()->screenGeometry(view()).right() - width(); - borderHit = true; - } - - if( x < QApplication::desktop()->screenGeometry(view()).left() ) { - x = QApplication::desktop()->screenGeometry(view()).left(); - borderHit = true; - } - - move( QPoint(x,y) ); - - updateHeight(); - - updateArgumentHintGeometry(); - -// kDebug() << "updated to" << geometry() << m_entryList->geometry() << borderHit; - - return borderHit; -} - -void KateCompletionWidget::updateArgumentHintGeometry() -{ - if( !m_dontShowArgumentHints ) { - //Now place the argument-hint widget - QRect geom = m_argumentHintTree->geometry(); - geom.moveTo(pos()); - geom.setWidth(width()); - geom.moveBottom(pos().y() - view()->renderer()->config()->fontMetrics().height()*2); - m_argumentHintTree->updateGeometry(geom); - } -} - -//Checks whether the given model has at least "rows" rows, also searching the second level of the tree. -bool hasAtLeastNRows(int rows, QAbstractItemModel* model) { - int count = 0; - for(int row = 0; row < model->rowCount(); ++row) { - ++count; - - QModelIndex index(model->index(row, 0)); - if(index.isValid()) - count += model->rowCount(index); - - if(count > rows) - return true; - } - return false; -} - -void KateCompletionWidget::updateHeight() -{ - QRect geom = geometry(); - - int minBaseHeight = 10; - int maxBaseHeight = 300; - - int baseHeight = 0; - int calculatedCustomHeight = 0; - - if(hasAtLeastNRows(15, m_presentationModel)) { - //If we know there is enough rows, always use max-height, we don't need to calculate size-hints - baseHeight = maxBaseHeight; - }else{ - //Calculate size-hints to determine the best height - for(int row = 0; row < m_presentationModel->rowCount(); ++row) { - baseHeight += treeView()->sizeHintForRow(row); - - QModelIndex index(m_presentationModel->index(row, 0)); - if(index.isValid()) { - for(int row2 = 0; row2 < m_presentationModel->rowCount(index); ++row2) { - int h = 0; - for(int a = 0; a < m_presentationModel->columnCount(index); ++a) { - int localHeight = treeView()->sizeHintForIndex(index.child(row2, a)).height(); - if(localHeight > h) - h = localHeight; - } - baseHeight += h; - if(baseHeight > maxBaseHeight) - break; - } - - if(baseHeight > maxBaseHeight) - break; - } - } - - calculatedCustomHeight = baseHeight; - } - - baseHeight += 2*frameWidth(); - - if(m_entryList->horizontalScrollBar()->isVisible()) - baseHeight += m_entryList->horizontalScrollBar()->height(); - - - if(baseHeight < minBaseHeight) - baseHeight = minBaseHeight; - if(baseHeight > maxBaseHeight) { - baseHeight = maxBaseHeight; - m_entryList->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - }else{ - //Somewhere there seems to be a bug that makes QTreeView add a scroll-bar - //even if the content exactly fits in. So forcefully disable the scroll-bar in that case - m_entryList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); -} - - int newExpandingAddedHeight = 0; - - if(baseHeight == maxBaseHeight && model()->expandingWidgetsHeight()) { - //Eventually add some more height - if(calculatedCustomHeight && calculatedCustomHeight > baseHeight && calculatedCustomHeight < (maxBaseHeight + model()->expandingWidgetsHeight())) - newExpandingAddedHeight = calculatedCustomHeight - baseHeight; - else - newExpandingAddedHeight = model()->expandingWidgetsHeight(); - } - - if( m_expandedAddedHeightBase != baseHeight && m_expandedAddedHeightBase - baseHeight > -2 && m_expandedAddedHeightBase - baseHeight < 2 ) - { - //Re-use the stored base-height if it only slightly differs from the current one. - //Reason: Qt seems to apply slightly wrong sizes when the completion-widget is moved out of the screen at the bottom, - // which completely breaks this algorithm. Solution: re-use the old base-size if it only slightly differs from the computed one. - baseHeight = m_expandedAddedHeightBase; - } - - int screenBottom = QApplication::desktop()->screenGeometry(view()).bottom(); - - //Limit the height to the bottom of the screen - int bottomPosition = baseHeight + newExpandingAddedHeight + geometry().top(); - - if( bottomPosition > screenBottom ) { - newExpandingAddedHeight -= bottomPosition - (screenBottom); - } - - int finalHeight = baseHeight+newExpandingAddedHeight; - - if( finalHeight < 10 ) { - m_entryList->resize(m_entryList->width(), height() - 2*frameWidth()); - return; - } - - m_expandedAddedHeightBase = geometry().height(); - - geom.setHeight(finalHeight); - - //Work around a crash deep within the Qt 4.5 raster engine - m_entryList->setScrollingEnabled(false); - - if(geometry() != geom) - setGeometry(geom); - - QSize entryListSize = QSize(m_entryList->width(), finalHeight - 2*frameWidth()); - if(m_entryList->size() != entryListSize) - m_entryList->resize(entryListSize); - - - m_entryList->setScrollingEnabled(true); -} - -void KateCompletionWidget::cursorPositionChanged( ) -{ - //kDebug(); - if (m_completionRanges.isEmpty()) - return; - - QModelIndex oldCurrentSourceIndex; - if(m_inCompletionList && m_entryList->currentIndex().isValid()) - oldCurrentSourceIndex = m_presentationModel->mapToSource(m_entryList->currentIndex()); - - KTextEditor::Cursor cursor = view()->cursorPosition(); - - QList checkCompletionRanges = m_completionRanges.keys(); - - //Check the models and eventuall abort some - for(QList::iterator it = checkCompletionRanges.begin(); - it != checkCompletionRanges.end(); ++it) { - if(!m_completionRanges.contains(*it)) - continue; - - KTextEditor::CodeCompletionModel *model = *it; - KTextEditor::MovingRange *range = m_completionRanges[*it].range; - - kDebug()<<"range before _updateRange:"<< *range; - KTextEditor::Range rangeTE = range->toRange(); - range->setRange (_updateRange(model, view(),rangeTE)); - kDebug()<<"range after _updateRange:"<< *range; - QString currentCompletion = _filterString(model,view(), *range, view()->cursorPosition()); - kDebug()<<"after _filterString, currentCompletion="<< currentCompletion; - bool abort = _shouldAbortCompletion(model,view(), *range, currentCompletion); - kDebug()<<"after _shouldAbortCompletion:abort="<cursorPosition() < m_completionRanges[*it].leftBoundary) { - kDebug() << "aborting because of boundary: cursor:"<cursorPosition()<<"completion_Range_left_boundary:"<removeCompletionModel(model); - } - } else { - m_presentationModel->setCurrentCompletion(model, currentCompletion); - } - } - - if(oldCurrentSourceIndex.isValid()) { - QModelIndex idx = m_presentationModel->mapFromSource(oldCurrentSourceIndex); - if(idx.isValid()) { - kDebug() << "setting" << idx; - m_entryList->setCurrentIndex(idx.sibling(idx.row(), 0)); -// m_entryList->nextCompletion(); -// m_entryList->previousCompletion(); - }else{ - kDebug() << "failed to map from source"; - } - } - - m_entryList->scheduleUpdate(); -} - -bool KateCompletionWidget::isCompletionActive( ) const -{ - return !m_completionRanges.isEmpty() && ((!isHidden() && isVisible()) || (!m_argumentHintTree->isHidden() && m_argumentHintTree->isVisible())); -} - -void KateCompletionWidget::abortCompletion( ) -{ - //kDebug(13035) ; - - m_isSuspended = false; - - bool wasActive = isCompletionActive(); - - clear(); - - if(!isHidden()) - hide(); - if(!m_argumentHintTree->isHidden()) - m_argumentHintTree->hide(); - - if (wasActive) - view()->sendCompletionAborted(); -} - -void KateCompletionWidget::clear() { - m_presentationModel->clearCompletionModels(); - m_argumentHintTree->clearCompletion(); - m_argumentHintModel->clear(); - - foreach(KTextEditor::CodeCompletionModel* model, m_completionRanges.keys()) - _aborted(model,view()); - - deleteCompletionRanges(); -} - -bool KateCompletionWidget::navigateAccept() { - m_hadCompletionNavigation = true; - - if(currentEmbeddedWidget()) - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetAccept"); - - QModelIndex index = selectedIndex(); - if( index.isValid() ) { - index.data(KTextEditor::CodeCompletionModel::AccessibilityAccept); - return true; - } - return false; -} - -void KateCompletionWidget::execute() -{ - //kDebug(13035) ; - - if (!isCompletionActive()) - return; - - QModelIndex index = selectedIndex(); - - if (!index.isValid()) - return abortCompletion(); - - QModelIndex toExecute; - - if(index.model() == m_presentationModel) - toExecute = m_presentationModel->mapToSource(index); - else - toExecute = m_argumentHintModel->mapToSource(index); - - if (!toExecute.isValid()) { - kWarning() << k_funcinfo << "Could not map index" << m_entryList->selectionModel()->currentIndex() << "to source index."; - return abortCompletion(); - } - - // encapsulate all editing as being from the code completion, and undo-able in one step. - view()->doc()->editStart(); - m_completionEditRunning = true; - - // create scoped pointer, to ensure deletion of cursor - QScopedPointer oldPos (view()->doc()->newMovingCursor(view()->cursorPosition(), KTextEditor::MovingCursor::StayOnInsert)); - - KTextEditor::CodeCompletionModel* model = static_cast(const_cast(toExecute.model())); - Q_ASSERT(model); - - KTextEditor::CodeCompletionModel2* model2 = qobject_cast(model); - - Q_ASSERT(m_completionRanges.contains(model)); - KTextEditor::Cursor start = m_completionRanges[model].range->start(); - - if(model2) - model2->executeCompletionItem2(view()->document(), *m_completionRanges[model].range, toExecute); - else if(toExecute.parent().isValid()) - //The normale CodeCompletionInterface cannot handle feedback for hierarchical models, so just do the replacement - view()->document()->replaceText(*m_completionRanges[model].range, model->data(toExecute.sibling(toExecute.row(), KTextEditor::CodeCompletionModel::Name)).toString()); - else - model->executeCompletionItem(view()->document(), *m_completionRanges[model].range, toExecute.row()); - - view()->doc()->editEnd(); - m_completionEditRunning = false; - - abortCompletion(); - - view()->sendCompletionExecuted(start, model, toExecute); - - KTextEditor::Cursor newPos = view()->cursorPosition(); - - if(newPos > *oldPos) { - m_automaticInvocationAt = newPos; - m_automaticInvocationLine = view()->doc()->text(KTextEditor::Range(*oldPos, newPos)); - kDebug() << "executed, starting automatic invocation with line" << m_automaticInvocationLine; - m_lastInsertionByUser = false; - m_automaticInvocationTimer->start(); - } -} - -void KateCompletionWidget::resizeEvent( QResizeEvent * event ) -{ - QFrame::resizeEvent(event); -} - -void KateCompletionWidget::showEvent ( QShowEvent * event ) -{ - m_isSuspended = false; - - QFrame::showEvent(event); - - if( !m_dontShowArgumentHints && m_argumentHintModel->rowCount(QModelIndex()) != 0 ) - m_argumentHintTree->show(); -} - -KTextEditor::MovingRange * KateCompletionWidget::completionRange(KTextEditor::CodeCompletionModel* model) const -{ - if (!model) { - if (m_completionRanges.isEmpty()) return 0; - - KTextEditor::MovingRange* ret = m_completionRanges.begin()->range; - - foreach(const CompletionRange &range, m_completionRanges) - if(range.range->start() > ret->start()) - ret = range.range; - return ret; - } - if(m_completionRanges.contains(model)) - return m_completionRanges[model].range; - else - return 0; -} - -QMap KateCompletionWidget::completionRanges( ) const -{ - return m_completionRanges; -} - -void KateCompletionWidget::modelReset( ) -{ - setUpdatesEnabled(false); - m_entryList->setAnimated(false); - m_argumentHintTree->setAnimated(false); - ///We need to do this by hand, because QTreeView::expandAll is very inefficient. - ///It creates a QPersistentModelIndex for every single item in the whole tree.. - for(int row = 0; row < m_argumentHintModel->rowCount(QModelIndex()); ++row) { - QModelIndex index(m_argumentHintModel->index(row, 0, QModelIndex())); - if(!m_argumentHintTree->isExpanded(index)) { - m_argumentHintTree->expand(index); - } - } - - for(int row = 0; row < m_entryList->model()->rowCount(QModelIndex()); ++row) { - QModelIndex index(m_entryList->model()->index(row, 0, QModelIndex())); - if(!m_entryList->isExpanded(index)) { - m_entryList->expand(index); - } - } - setUpdatesEnabled(true); -} - -KateCompletionTree* KateCompletionWidget::treeView() const { - return m_entryList; -} - -QModelIndex KateCompletionWidget::selectedIndex() const { - if(!isCompletionActive()) - return QModelIndex(); - - if( m_inCompletionList ) - return m_entryList->currentIndex(); - else - return m_argumentHintTree->currentIndex(); -} - -bool KateCompletionWidget::navigateLeft() { - m_hadCompletionNavigation = true; - if(currentEmbeddedWidget()) - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetLeft"); - - QModelIndex index = selectedIndex(); - - if( index.isValid() ) { - index.data(KTextEditor::CodeCompletionModel::AccessibilityPrevious); - - return true; - } - return false; -} - -bool KateCompletionWidget::navigateRight() { - m_hadCompletionNavigation = true; - if(currentEmbeddedWidget()) ///@todo post 4.2: Make these slots public interface, or create an interface using virtual functions - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetRight"); - - QModelIndex index = selectedIndex(); - - if( index.isValid() ) { - index.data(KTextEditor::CodeCompletionModel::AccessibilityNext); - return true; - } - - return false; -} - -bool KateCompletionWidget::hadNavigation() const { - return m_hadCompletionNavigation; -} - -void KateCompletionWidget::resetHadNavigation() { - m_hadCompletionNavigation = false; -} - - -bool KateCompletionWidget::navigateBack() { - m_hadCompletionNavigation = true; - if(currentEmbeddedWidget()) - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetBack"); - return false; -} - -bool KateCompletionWidget::toggleExpanded(bool forceExpand, bool forceUnExpand) { - if ( (canExpandCurrentItem() || forceExpand ) && !forceUnExpand) { - bool ret = canExpandCurrentItem(); - setCurrentItemExpanded(true); - return ret; - } else if (canCollapseCurrentItem() || forceUnExpand) { - bool ret = canCollapseCurrentItem(); - setCurrentItemExpanded(false); - return ret; - } - return false; -} - -bool KateCompletionWidget::canExpandCurrentItem() const { - if( m_inCompletionList ) { - if( !m_entryList->currentIndex().isValid() ) return false; - return model()->isExpandable( m_entryList->currentIndex() ) && !model()->isExpanded( m_entryList->currentIndex() ); - } else { - if( !m_argumentHintTree->currentIndex().isValid() ) return false; - return argumentHintModel()->isExpandable( m_argumentHintTree->currentIndex() ) && !argumentHintModel()->isExpanded( m_argumentHintTree->currentIndex() ); - } -} - -bool KateCompletionWidget::canCollapseCurrentItem() const { - if( m_inCompletionList ) { - if( !m_entryList->currentIndex().isValid() ) return false; - return model()->isExpandable( m_entryList->currentIndex() ) && model()->isExpanded( m_entryList->currentIndex() ); - }else{ - if( !m_argumentHintTree->currentIndex().isValid() ) return false; - return m_argumentHintModel->isExpandable( m_argumentHintTree->currentIndex() ) && m_argumentHintModel->isExpanded( m_argumentHintTree->currentIndex() ); - } -} - -void KateCompletionWidget::setCurrentItemExpanded( bool expanded ) { - if( m_inCompletionList ) { - if( !m_entryList->currentIndex().isValid() ) return; - model()->setExpanded(m_entryList->currentIndex(), expanded); - updateHeight(); - }else{ - if( !m_argumentHintTree->currentIndex().isValid() ) return; - m_argumentHintModel->setExpanded(m_argumentHintTree->currentIndex(), expanded); - } -} - -bool KateCompletionWidget::eventFilter( QObject * watched, QEvent * event ) -{ - bool ret = QFrame::eventFilter(watched, event); - - if (watched != this) - if (event->type() == QEvent::Move) - updatePosition(); - - return ret; -} - -bool KateCompletionWidget::navigateDown() { - m_hadCompletionNavigation = true; - if(currentEmbeddedWidget()) { - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetDown"); - } - return false; -} - -bool KateCompletionWidget::navigateUp() { - m_hadCompletionNavigation = true; - if(currentEmbeddedWidget()) - QMetaObject::invokeMethod(currentEmbeddedWidget(), "embeddedWidgetUp"); - return false; -} - -QWidget* KateCompletionWidget::currentEmbeddedWidget() { - QModelIndex index = selectedIndex(); - if(!index.isValid()) - return 0; - if( qobject_cast(index.model()) ) { - const ExpandingWidgetModel* model = static_cast(index.model()); - if( model->isExpanded(index) ) - return model->expandingWidget(index); - } - return 0; -} - -void KateCompletionWidget::cursorDown() -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) - m_entryList->nextCompletion(); - else { - if( !m_argumentHintTree->nextCompletion() ) - switchList(); - } - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::cursorUp() -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) { - if( !m_entryList->previousCompletion() ) - switchList(); - }else{ - m_argumentHintTree->previousCompletion(); - } - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::pageDown( ) -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) - m_entryList->pageDown(); - else { - if( !m_argumentHintTree->pageDown() ) - switchList(); - } - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::pageUp( ) -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) { - if( !m_entryList->pageUp() ) - switchList(); - }else{ - m_argumentHintTree->pageUp(); - } - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::top( ) -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) - m_entryList->top(); - else - m_argumentHintTree->top(); - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::bottom( ) -{ - bool wasPartiallyExpanded = model()->partiallyExpandedRow().isValid(); - - if( m_inCompletionList ) - m_entryList->bottom(); - else - m_argumentHintTree->bottom(); - - if(wasPartiallyExpanded != model()->partiallyExpandedRow().isValid()) - updateHeight(); -} - -void KateCompletionWidget::switchList() { - if( m_inCompletionList ) { - if( m_argumentHintModel->rowCount(QModelIndex()) != 0 ) { - m_entryList->setCurrentIndex(QModelIndex()); - m_argumentHintTree->setCurrentIndex(m_argumentHintModel->index(m_argumentHintModel->rowCount(QModelIndex())-1, 0)); - } - } else { - if( m_presentationModel->rowCount(QModelIndex()) != 0 ) { - m_argumentHintTree->setCurrentIndex(QModelIndex()); - m_entryList->setCurrentIndex(m_presentationModel->index(0, 0)); - if(model()->hasGroups()) //If we have groups we have to move on, because the first item is a label - m_entryList->nextCompletion(); - } - } - m_inCompletionList = !m_inCompletionList; -} - -void KateCompletionWidget::showConfig( ) -{ - abortCompletion(); - - m_configWidget->exec(); -} - -void KateCompletionWidget::completionModelReset() -{ - KTextEditor::CodeCompletionModel* model = qobject_cast(sender()); - if(!model) { - kWarning() << "bad sender"; - return; - } - - if(!m_waitingForReset.contains(model)) - return; - - m_waitingForReset.remove(model); - - if(m_waitingForReset.isEmpty()) { - if(!isCompletionActive()) { - kDebug() << "all completion-models we waited for are ready. Last one: " << model->objectName(); - //Eventually show the completion-list if this was the last model we were waiting for - //Use a queued connection once again to make sure that KateCompletionModel is notified before we are - QMetaObject::invokeMethod(this, "modelContentChanged", Qt::QueuedConnection); - } - } -} - -void KateCompletionWidget::modelDestroyed(QObject* model) { - unregisterCompletionModel(static_cast(model)); -} - -void KateCompletionWidget::registerCompletionModel(KTextEditor::CodeCompletionModel* model) -{ - if (m_sourceModels.contains(model)) { - return; - } - - connect(model, SIGNAL(destroyed(QObject*)), SLOT(modelDestroyed(QObject*))); - //This connection must not be queued - connect(model, SIGNAL(modelReset()), SLOT(completionModelReset())); - - m_sourceModels.append(model); - - if (isCompletionActive()) { - m_presentationModel->addCompletionModel(model); - } -} - -void KateCompletionWidget::unregisterCompletionModel(KTextEditor::CodeCompletionModel* model) -{ - disconnect(model, SIGNAL(destroyed(QObject*)), this, SLOT(modelDestroyed(QObject*))); - disconnect(model, SIGNAL(modelReset()), this, SLOT(completionModelReset())); - - m_sourceModels.removeAll(model); - abortCompletion(); -} - -int KateCompletionWidget::automaticInvocationDelay() const { - return m_automaticInvocationDelay; -} - -void KateCompletionWidget::setAutomaticInvocationDelay(int delay) { - m_automaticInvocationDelay = delay; -} - -void KateCompletionWidget::wrapLine (const KTextEditor::Cursor &) -{ - m_lastInsertionByUser = !m_completionEditRunning; - - // wrap line, be done - m_automaticInvocationLine.clear(); - m_automaticInvocationTimer->stop(); -} - -void KateCompletionWidget::unwrapLine (int) -{ - m_lastInsertionByUser = !m_completionEditRunning; - - // just removal - m_automaticInvocationLine.clear(); - m_automaticInvocationTimer->stop(); -} - -void KateCompletionWidget::insertText (const KTextEditor::Cursor &position, const QString &text) -{ - m_lastInsertionByUser = !m_completionEditRunning; - - // no invoke? - if (!view()->config()->automaticCompletionInvocation()) { - m_automaticInvocationLine.clear(); - m_automaticInvocationTimer->stop(); - return; - } - - if(m_automaticInvocationAt != position) { - m_automaticInvocationLine.clear(); - m_lastInsertionByUser = !m_completionEditRunning; - } - - m_automaticInvocationLine += text; - m_automaticInvocationAt = position; - m_automaticInvocationAt.setColumn (position.column() + text.length()); - - if (m_automaticInvocationLine.isEmpty()) { - m_automaticInvocationTimer->stop(); - return; - } - - m_automaticInvocationTimer->start(m_automaticInvocationDelay); -} - -void KateCompletionWidget::removeText (const KTextEditor::Range &) -{ - m_lastInsertionByUser = !m_completionEditRunning; - - // just removal - m_automaticInvocationLine.clear(); - m_automaticInvocationTimer->stop(); -} - -#if 0 -void KateCompletionWidget::editDone(KateEditInfo * edit) -{ - return; - - if(!edit->newText().join("\n").trimmed().isEmpty()) - m_lastInsertionByUser = edit->editSource() == Kate::UserInputEdit; - - if (!view()->config()->automaticCompletionInvocation() - || (edit->editSource() != Kate::UserInputEdit) - || edit->isRemoval() - || (edit->editSource() != Kate::UserInputEdit && edit->editSource() != Kate::CodeCompletionEdit) - || edit->newText().isEmpty() ) - { - m_automaticInvocationLine.clear(); - m_automaticInvocationTimer->stop(); - return; - } - - if(m_automaticInvocationAt != edit->newRange().start()) { - m_automaticInvocationLine.clear(); - m_lastInsertionByUser = edit->editSource() == Kate::UserInputEdit; - } - - m_automaticInvocationLine += edit->newText().last(); - m_automaticInvocationAt = edit->newRange().end(); - - if (m_automaticInvocationLine.isEmpty()) { - m_automaticInvocationTimer->stop(); - return; - } - - m_automaticInvocationTimer->start(m_automaticInvocationDelay); -} -#endif - -void KateCompletionWidget::automaticInvocation() -{ - kDebug()<<"m_automaticInvocationAt:"<cursorPosition(); - if(m_automaticInvocationAt != view()->cursorPosition()) - return; - - bool start = false; - QList models; - - kDebug()<<"checking models"; - foreach (KTextEditor::CodeCompletionModel *model, m_sourceModels) { - kDebug()<<"m_completionRanges contains model?:"<cursorPosition()); - kDebug()<<"start="<commonPrefix((m_inCompletionList && !shellLikeTabCompletion) ? m_entryList->currentIndex() : QModelIndex()); - if(!prefix.isEmpty()) { - view()->insertText(prefix); - }else if(shellLikeTabCompletion) { - cursorDown(); - return; - } - }else{ - if(shellLikeTabCompletion) { - cursorUp(); - return; - } - - //Reset left boundaries, so completion isn't stopped - typedef QMap CompletionRangeMap; - for(CompletionRangeMap::iterator it = m_completionRanges.begin(); it != m_completionRanges.end(); ++it) - (*it).leftBoundary = (*it).range->start(); - - //Remove suffix until the completion-list filter is widened again - uint itemCount = m_presentationModel->filteredItemCount(); - - while(view()->cursorPosition().column() > 0 && m_presentationModel->filteredItemCount() == itemCount) { - KTextEditor::Range lastcharRange = KTextEditor::Range(view()->cursorPosition()-KTextEditor::Cursor(0,1), view()->cursorPosition()); - QString cursorText = view()->document()->text(lastcharRange); - if(!cursorText[0].isSpace()) - { - view()->document()->removeText(lastcharRange); - QApplication::sendPostedEvents(); - }else{ - break; - } - } - } -} - -#include "katecompletionwidget.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/completion/katecompletionwidget.h b/part/completion/katecompletionwidget.h deleted file mode 100644 index df456d6..0000000 --- a/part/completion/katecompletionwidget.h +++ /dev/null @@ -1,239 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005-2006 Hamish Rodda - * Copyright (C) 2007-2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATECOMPLETIONWIDGET_H -#define KATECOMPLETIONWIDGET_H - -#include -#include - -#include "katepartprivate_export.h" - -#include -#include -#include - -class QToolButton; -class QPushButton; -class QLabel; -class QTimer; - -class KateView; -class KateCompletionModel; -class KateCompletionTree; -class KateArgumentHintTree; -class KateArgumentHintModel; - -namespace KTextEditor { - class EmbeddedWidgetInterface; -} - -/** - * This is the code completion's main widget, and also contains the - * core interface logic. - * - * @author Hamish Rodda - */ -class KATEPART_TESTS_EXPORT KateCompletionWidget : public QFrame -{ - Q_OBJECT - - public: - explicit KateCompletionWidget(KateView* parent); - ~KateCompletionWidget(); - - KateView* view() const; - KateCompletionTree* treeView() const; - - bool isCompletionActive() const; - void startCompletion(KTextEditor::CodeCompletionModel::InvocationType invocationType, const QList& models = QList()); - void startCompletion(const KTextEditor::Range& word, KTextEditor::CodeCompletionModel* model, KTextEditor::CodeCompletionModel::InvocationType invocationType = KTextEditor::CodeCompletionModel::ManualInvocation); - void startCompletion(const KTextEditor::Range& word, const QList& models = QList(), KTextEditor::CodeCompletionModel::InvocationType invocationType = KTextEditor::CodeCompletionModel::ManualInvocation); - void userInvokedCompletion(); - - //Executed when return is pressed while completion is active. - void execute(); - void cursorDown(); - void cursorUp(); - - void tab(bool shift); - - ///Returns whether the current item was expanded/unexpanded - bool toggleExpanded(bool forceExpand = false, bool forceUnExpand = false); - - const KateCompletionModel* model() const; - KateCompletionModel* model(); - - void registerCompletionModel(KTextEditor::CodeCompletionModel* model); - void unregisterCompletionModel(KTextEditor::CodeCompletionModel* model); - - int automaticInvocationDelay() const; - void setAutomaticInvocationDelay(int delay); - - struct CompletionRange{ - CompletionRange() : range(0) { - } - CompletionRange(KTextEditor::MovingRange* r) : range(r) { - } - - bool operator==(const CompletionRange& rhs) const { - return range->toRange() == rhs.range->toRange(); - } - - KTextEditor::MovingRange* range; - //Whenever the cursor goes before this position, the completion is stopped, unless it is invalid. - KTextEditor::Cursor leftBoundary; - }; - - KTextEditor::MovingRange* completionRange(KTextEditor::CodeCompletionModel* model = 0) const; - QMap completionRanges( ) const; - - // Navigation - void pageDown(); - void pageUp(); - void top(); - void bottom(); - - QWidget* currentEmbeddedWidget(); - - bool canExpandCurrentItem() const; - - bool canCollapseCurrentItem() const; - - void setCurrentItemExpanded( bool ); - - //Returns true if a screen border has been hit - bool updatePosition(bool force = false); - - virtual bool eventFilter( QObject * watched, QEvent * event ); - - KateArgumentHintTree* argumentHintTree() const; - - KateArgumentHintModel* argumentHintModel() const; - - ///Called by KateViewInternal, because we need the specific information from the event. - - void updateHeight(); - - public Q_SLOTS: - void waitForModelReset(); - - void abortCompletion(); - void showConfig(); -/* void viewFocusIn(); - void viewFocusOut();*/ - void updatePositionSlot(); - void automaticInvocation(); - -/* void updateFocus();*/ - void argumentHintsChanged(bool hasContent); - - bool navigateUp(); - bool navigateDown(); - bool navigateLeft(); - bool navigateRight(); - bool navigateAccept(); - bool navigateBack(); - - bool hadNavigation() const; - void resetHadNavigation(); - - protected: - virtual void showEvent ( QShowEvent * event ); - virtual void resizeEvent ( QResizeEvent * event ); -// virtual void focusInEvent ( QFocusEvent * event ); - - private Q_SLOTS: - void completionModelReset(); - void modelDestroyed(QObject* model); - void modelContentChanged(); - void cursorPositionChanged(); - void modelReset(); - void rowsInserted(const QModelIndex& parent, int row, int rowEnd); - void viewFocusOut(); - - void wrapLine (const KTextEditor::Cursor &position); - void unwrapLine (int line); - void insertText (const KTextEditor::Cursor &position, const QString &text); - void removeText (const KTextEditor::Range &range); - - private: - void updateAndShow(); - void updateArgumentHintGeometry(); - QModelIndex selectedIndex() const; - - void clear(); - //Switch cursor between argument-hint list / completion-list - void switchList(); - KTextEditor::Range determineRange() const; - void completionRangeChanged(KTextEditor::CodeCompletionModel*, const KTextEditor::Range& word); - - void deleteCompletionRanges(); - - QList m_sourceModels; - KateCompletionModel* m_presentationModel; - - QMap m_completionRanges; - QSet m_waitingForReset; - - KTextEditor::Cursor m_lastCursorPosition; - - KateCompletionTree* m_entryList; - KateArgumentHintModel* m_argumentHintModel; - KateArgumentHintTree* m_argumentHintTree; - - QTimer* m_automaticInvocationTimer; - //QTimer* m_updateFocusTimer; - QWidget* m_statusBar; - QToolButton* m_sortButton; - QLabel* m_sortText; - QToolButton* m_filterButton; - QLabel* m_filterText; - QPushButton* m_configButton; - - KTextEditor::Cursor m_automaticInvocationAt; - QString m_automaticInvocationLine; - int m_automaticInvocationDelay; - bool m_filterInstalled; - - class KateCompletionConfig* m_configWidget; - bool m_lastInsertionByUser; - bool m_inCompletionList; //Are we in the completion-list? If not, we're in the argument-hint list - bool m_isSuspended; - bool m_dontShowArgumentHints; //Used temporarily to prevent flashing - bool m_needShow; - - bool m_hadCompletionNavigation; - - bool m_haveExactMatch; - - bool m_noAutoHide; - - /** - * is a completion edit ongoing? - */ - bool m_completionEditRunning; - - int m_expandedAddedHeightBase; - KTextEditor::CodeCompletionModel::InvocationType m_lastInvocationType; -}; - -#endif diff --git a/part/completion/katewordcompletion.cpp b/part/completion/katewordcompletion.cpp deleted file mode 100644 index fce53c4..0000000 --- a/part/completion/katewordcompletion.cpp +++ /dev/null @@ -1,565 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003 Anders Lund - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN includes -#include "katewordcompletion.h" -#include "kateview.h" -#include "kateconfig.h" -#include "katedocument.h" -#include "kateglobal.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -//END - -//BEGIN KateWordCompletionModel -KateWordCompletionModel::KateWordCompletionModel( QObject *parent ) - : CodeCompletionModel( parent ), m_automatic(false) -{ - setHasGroups(false); -} - -KateWordCompletionModel::~KateWordCompletionModel() -{ -} - -void KateWordCompletionModel::saveMatches( KTextEditor::View* view, - const KTextEditor::Range& range) -{ - m_matches = allMatches( view, range ); - m_matches.sort(); -} - -QVariant KateWordCompletionModel::data(const QModelIndex& index, int role) const -{ - if( role == InheritanceDepth ) - return 10000; //Very high value, so the word-completion group and items are shown behind any other groups/items if there is multiple - - if( !index.parent().isValid() ) { - //It is the group header - switch ( role ) - { - case Qt::DisplayRole: - return i18n("Auto Word Completion"); - case GroupRole: - return Qt::DisplayRole; - } - } - - if( index.column() == KTextEditor::CodeCompletionModel::Name && role == Qt::DisplayRole ) - return m_matches.at( index.row() ); - - if( index.column() == KTextEditor::CodeCompletionModel::Icon && role == Qt::DecorationRole ) { - static QIcon icon(KIcon("insert-text").pixmap(QSize(16, 16))); - return icon; - } - - return QVariant(); -} - -QModelIndex KateWordCompletionModel::parent(const QModelIndex& index) const -{ - if(index.internalId()) - return createIndex(0, 0, 0); - else - return QModelIndex(); -} - -QModelIndex KateWordCompletionModel::index(int row, int column, const QModelIndex& parent) const -{ - if( !parent.isValid()) { - if(row == 0) - return createIndex(row, column, 0); - else - return QModelIndex(); - - }else if(parent.parent().isValid()) - return QModelIndex(); - - - if (row < 0 || row >= m_matches.count() || column < 0 || column >= ColumnCount ) - return QModelIndex(); - - return createIndex(row, column, 1); -} - -int KateWordCompletionModel::rowCount ( const QModelIndex & parent ) const -{ - if( !parent.isValid() && !m_matches.isEmpty() ) - return 1; //One root node to define the custom group - else if(parent.parent().isValid()) - return 0; //Completion-items have no children - else - return m_matches.count(); -} - - -bool KateWordCompletionModel::shouldStartCompletion(KTextEditor::View* view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position) -{ - if (!userInsertion) return false; - if(insertedText.isEmpty()) - return false; - - - KateView *v = qobject_cast (view); - - QString text = view->document()->line(position.line()).left(position.column()); - uint check=v->config()->wordCompletionMinimalWordLength(); - if (check<=0) return true; - int start=text.length(); - int end=text.length()-check; - if (end<0) return false; - for (int i=start-1;i>=end;i--) { - QChar c=text.at(i); - if (! (c.isLetter() || (c.isNumber()) || c=='_') ) return false; - } - - return true; -} - -bool KateWordCompletionModel::shouldAbortCompletion(KTextEditor::View* view, const KTextEditor::Range &range, const QString ¤tCompletion) { - - if (m_automatic) { - KateView *v = qobject_cast (view); - if (currentCompletion.length()config()->wordCompletionMinimalWordLength()) return true; - } - - return CodeCompletionModelControllerInterface3::shouldAbortCompletion(view,range,currentCompletion); -} - - - -void KateWordCompletionModel::completionInvoked(KTextEditor::View* view, const KTextEditor::Range& range, InvocationType it) -{ - /** - * auto invoke... - */ - m_automatic=false; - if (it==AutomaticInvocation) { - m_automatic=true; - KateView *v = qobject_cast (view); - - if (range.columnWidth() >= v->config()->wordCompletionMinimalWordLength()) - saveMatches( view, range ); - else - m_matches.clear(); - - // done here... - return; - } - - // normal case ;) - saveMatches( view, range ); -} - - -// Scan throughout the entire document for possible completions, -// ignoring any dublets -const QStringList KateWordCompletionModel::allMatches( KTextEditor::View *view, const KTextEditor::Range &range ) const -{ - QStringList l; - - int i( 0 ); - int pos( 0 ); - KTextEditor::Document *doc = view->document(); - QRegExp re( "\\b(" + doc->text( range ) + "\\w{1,})" ); - QString s, m; - QSet seen; - - while( i < doc->lines() ) - { - s = doc->line( i ); - pos = 0; - while ( pos >= 0 ) - { - pos = re.indexIn( s, pos ); - if ( pos >= 0 ) - { - // typing in the middle of a word - if ( ! ( i == range.start().line() && pos == range.start().column() ) ) - { - m = re.cap( 1 ); - if ( ! seen.contains( m ) ) { - seen.insert( m ); - l << m; - } - } - pos += re.matchedLength(); - } - } - i++; - } - return l; -} - -KTextEditor::CodeCompletionModelControllerInterface3::MatchReaction KateWordCompletionModel::matchingItem(const QModelIndex& /*matched*/) -{ - return HideListIfAutomaticInvocation; -} - -//END KateWordCompletionModel - - -//BEGIN KateWordCompletionView -struct KateWordCompletionViewPrivate -{ - KTextEditor::MovingRange* liRange; // range containing last inserted text - KTextEditor::Range dcRange; // current range to be completed by directional completion - KTextEditor::Cursor dcCursor; // directional completion search cursor - QRegExp re; // hrm - int directionalPos; // be able to insert "" at the correct time - bool isCompleting; // true when the directional completion is doing a completion -}; - -KateWordCompletionView::KateWordCompletionView( KTextEditor::View *view, KActionCollection* ac ) - : QObject( view ), - m_view( view ), - m_dWCompletionModel( KateGlobal::self()->wordCompletionModel() ), - d( new KateWordCompletionViewPrivate ) -{ - d->isCompleting = false; - d->dcRange = KTextEditor::Range::invalid(); - - d->liRange = static_cast(m_view->document())->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand); - - KColorScheme colors(QPalette::Active); - KTextEditor::Attribute::Ptr a = KTextEditor::Attribute::Ptr( new KTextEditor::Attribute() ); - a->setBackground( colors.background(KColorScheme::ActiveBackground) ); - a->setForeground( colors.foreground(KColorScheme::ActiveText) ); // ### this does 0 - d->liRange->setAttribute( a ); - - KTextEditor::CodeCompletionInterface *cci = qobject_cast(view); - - KAction *action; - - if (cci) - { - cci->registerCompletionModel( m_dWCompletionModel ); - - action = new KAction( i18n("Shell Completion"), this ); - ac->addAction( "doccomplete_sh", action ); - connect( action, SIGNAL( triggered() ), this, SLOT(shellComplete()) ); - } - - - action = new KAction( i18n("Reuse Word Above"), this ); - ac->addAction( "doccomplete_bw", action ); - action->setShortcut( Qt::CTRL+Qt::Key_8 ); - connect( action, SIGNAL( triggered() ), this, SLOT(completeBackwards()) ); - - action = new KAction( i18n("Reuse Word Below"), this ); - ac->addAction( "doccomplete_fw", action ); - action->setShortcut( Qt::CTRL+Qt::Key_9 ); - connect( action, SIGNAL( triggered() ), this, SLOT(completeForwards()) ); -} - -KateWordCompletionView::~KateWordCompletionView() -{ - KTextEditor::CodeCompletionInterface *cci = qobject_cast(m_view); - - if (cci) cci->unregisterCompletionModel(m_dWCompletionModel); - - delete d; -} - -void KateWordCompletionView::completeBackwards() -{ - complete( false ); -} - -void KateWordCompletionView::completeForwards() -{ - complete(); -} - -// Pop up the editors completion list if applicable -void KateWordCompletionView::popupCompletionList() -{ - kDebug( 13040 ) << "entered ..."; - KTextEditor::Range r = range(); - - KTextEditor::CodeCompletionInterface *cci = qobject_cast( m_view ); - if(!cci || cci->isCompletionActive()) - return; - - m_dWCompletionModel->saveMatches( m_view, r ); - - kDebug( 13040 ) << "after save matches ..."; - - if ( ! m_dWCompletionModel->rowCount(QModelIndex()) ) return; - - cci->startCompletion( r, m_dWCompletionModel ); -} - -// Contributed by -void KateWordCompletionView::shellComplete() -{ - KTextEditor::Range r = range(); - - QStringList matches = m_dWCompletionModel->allMatches( m_view, r ); - - if (matches.size() == 0) - return; - - QString partial = findLongestUnique( matches, r.columnWidth() ); - - if ( ! partial.length() ) - popupCompletionList(); - - else - { - m_view->document()->insertText( r.end(), partial.mid( r.columnWidth() ) ); - d->liRange->setView(m_view); - d->liRange->setRange( KTextEditor::Range( r.end(), partial.length() - r.columnWidth() ) ); - connect( m_view, SIGNAL(cursorPositionChanged(KTextEditor::View*, const KTextEditor::Cursor&)), this, SLOT(slotCursorMoved()) ); - } -} - -// Do one completion, searching in the desired direction, -// if possible -void KateWordCompletionView::complete( bool fw ) -{ - KTextEditor::Range r = range(); - - int inc = fw ? 1 : -1; - KTextEditor::Document *doc = m_view->document(); - - if ( d->dcRange.isValid() ) - { - //kDebug( 13040 )<<"CONTINUE "<dcRange; - // this is a repeted activation - - // if we are back to where we started, reset. - if ( ( fw && d->directionalPos == -1 ) || - ( !fw && d->directionalPos == 1 ) ) - { - const int spansColumns = d->liRange->end().column() - d->liRange->start().column(); - if ( spansColumns > 0 ) - doc->removeText( *d->liRange ); - - d->liRange->setRange( KTextEditor::Range::invalid() ); - d->dcCursor = r.end(); - d->directionalPos = 0; - - return; - } - - if ( fw ) { - const int spansColumns = d->liRange->end().column() - d->liRange->start().column(); - d->dcCursor.setColumn( d->dcCursor.column() + spansColumns ); - } - - d->directionalPos += inc; - } - else // new completion, reset all - { - //kDebug( 13040 )<<"RESET FOR NEW"; - d->dcRange = r; - d->liRange->setRange( KTextEditor::Range::invalid() ); - d->dcCursor = r.start(); - d->directionalPos = inc; - - d->liRange->setView( m_view ); - - connect( m_view, SIGNAL(cursorPositionChanged(KTextEditor::View*, const KTextEditor::Cursor&)), this, SLOT(slotCursorMoved()) ); - - } - - d->re.setPattern( "\\b" + doc->text( d->dcRange ) + "(\\w+)" ); - int pos ( 0 ); - QString ln = doc->line( d->dcCursor.line() ); - - while ( true ) - { - //kDebug( 13040 )<<"SEARCHING FOR "<re.pattern()<<" "<dcCursor; - pos = fw ? - d->re.indexIn( ln, d->dcCursor.column() ) : - d->re.lastIndexIn( ln, d->dcCursor.column() ); - - if ( pos > -1 ) // we matched a word - { - //kDebug( 13040 )<<"USABLE MATCH"; - QString m = d->re.cap( 1 ); - if ( m != doc->text( *d->liRange ) && (d->dcCursor.line() != d->dcRange.start().line() || pos != d->dcRange.start().column() ) ) - { - // we got good a match! replace text and return. - d->isCompleting = true; - KTextEditor::Range replaceRange(d->liRange->toRange()); - if (!replaceRange.isValid()) { - replaceRange.setRange(r.end(), r.end()); - } - doc->replaceText( replaceRange, m ); - d->liRange->setRange( KTextEditor::Range( d->dcRange.end(), m.length() ) ); - - d->dcCursor.setColumn( pos ); // for next try - - d->isCompleting = false; - return; - } - - // equal to last one, continue - else - { - //kDebug( 13040 )<<"SKIPPING, EQUAL MATCH"; - d->dcCursor.setColumn( pos ); // for next try - - if ( fw ) - d->dcCursor.setColumn( pos + m.length() ); - - else - { - if ( pos == 0 ) - { - if ( d->dcCursor.line() > 0 ) - { - int l = d->dcCursor.line() + inc; - ln = doc->line( l ); - d->dcCursor.setPosition( l, ln.length() ); - } - else - { - KNotification::beep(); - return; - } - } - - else - d->dcCursor.setColumn( d->dcCursor.column()-1 ); - } - } - } - - else // no match - { - //kDebug( 13040 )<<"NO MATCH"; - if ( (! fw && d->dcCursor.line() == 0 ) || ( fw && d->dcCursor.line() >= doc->lines() ) ) - { - KNotification::beep(); - return; - } - - int l = d->dcCursor.line() + inc; - ln = doc->line( l ); - d->dcCursor.setPosition( l, fw ? 0 : ln.length() ); - } - } // while true -} - -void KateWordCompletionView::slotCursorMoved() -{ - if ( d->isCompleting) return; - - d->dcRange = KTextEditor::Range::invalid(); - - disconnect( m_view, SIGNAL(cursorPositionChanged(KTextEditor::View*, const KTextEditor::Cursor&)), this, SLOT(slotCursorMoved()) ); - - d->liRange->setView(0); - d->liRange->setRange(KTextEditor::Range::invalid()); -} - -// Contributed by FIXME -QString KateWordCompletionView::findLongestUnique( const QStringList &matches, int lead ) const -{ - QString partial = matches.first(); - - QStringListIterator it( matches ); - QString current; - while ( it.hasNext() ) - { - current = it.next(); - if ( !current.startsWith( partial ) ) - { - while( partial.length() > lead ) - { - partial.remove( partial.length() - 1, 1 ); - if ( current.startsWith( partial ) ) - break; - } - - if ( partial.length() == lead ) - return QString(); - } - } - - return partial; -} - -// Return the string to complete (the letters behind the cursor) -const QString KateWordCompletionView::word() const -{ - return m_view->document()->text( range() ); -} - -// Return the range containing the word behind the cursor -const KTextEditor::Range KateWordCompletionView::range() const -{ - KTextEditor::Cursor end = m_view->cursorPosition(); - - int line = end.line(); - int col = end.column(); - - KTextEditor::Document *doc = m_view->document(); - while ( col > 0 ) - { - QChar c = ( doc->character( KTextEditor::Cursor( line, col-1 ) ) ); - if ( c.isLetterOrNumber() || c.isMark() || c == '_' ) - { - col--; - continue; - } - - break; - } - - return KTextEditor::Range( KTextEditor::Cursor( line, col ), end ); -} -//END - -#include "katewordcompletion.moc" -// kate: space-indent on; indent-width 2; replace-tabs on; mixed-indent off; diff --git a/part/completion/katewordcompletion.h b/part/completion/katewordcompletion.h deleted file mode 100644 index 95f1534..0000000 --- a/part/completion/katewordcompletion.h +++ /dev/null @@ -1,115 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003 Anders Lund - * Copyright (C) 2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KateWordCompletion_h_ -#define _KateWordCompletion_h_ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - - -class KateWordCompletionModel : public KTextEditor::CodeCompletionModel, public KTextEditor::CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) - public: - KateWordCompletionModel( QObject *parent ); - ~KateWordCompletionModel(); - - /** - * This function is responsible to generating / updating the list of current - * completions. The default implementation does nothing. - * - * When implementing this function, remember to call setRowCount() (or implement - * rowCount()), and to generate the appropriate change notifications (for instance - * by calling QAbstractItemModel::reset()). - * @param view The view to generate completions for - * @param range The range of text to generate completions for - * */ - void completionInvoked(KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType); - - - bool shouldStartCompletion(KTextEditor::View* view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position); - bool shouldAbortCompletion(KTextEditor::View* view, const KTextEditor::Range &range, const QString ¤tCompletion); - - - - void saveMatches( KTextEditor::View* view, - const KTextEditor::Range& range); - - int rowCount ( const QModelIndex & parent ) const; - - QVariant data(const QModelIndex& index, int role) const; - virtual QModelIndex index(int row, int column, const QModelIndex& parent=QModelIndex()) const; - virtual QModelIndex parent(const QModelIndex& index) const; - virtual MatchReaction matchingItem(const QModelIndex& matched); - - const QStringList allMatches( KTextEditor::View *view, const KTextEditor::Range &range ) const; - - private: - QStringList m_matches; - bool m_automatic; -}; - -class KateWordCompletionView : public QObject -{ - Q_OBJECT - - public: - KateWordCompletionView(KTextEditor::View *view, KActionCollection* ac ); - ~KateWordCompletionView(); - - private Q_SLOTS: - void completeBackwards(); - void completeForwards(); - void slotCursorMoved(); - - void shellComplete(); - - void popupCompletionList(); - - private: - void complete( bool fw=true ); - - const QString word() const; - const KTextEditor::Range range() const; - - QString findLongestUnique( const QStringList &matches, int lead ) const; - - KTextEditor::View *m_view; - KateWordCompletionModel *m_dWCompletionModel; - struct KateWordCompletionViewPrivate *d; -}; - -#endif // _DocWordCompletionPlugin_h_ - -// kate: space-indent on; indent-width 2; replace-tabs on; mixed-indent off; diff --git a/part/data/CMakeLists.txt b/part/data/CMakeLists.txt deleted file mode 100644 index 69fd115..0000000 --- a/part/data/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -install( FILES katepartui.rc katepartsimpleui.rc DESTINATION ${DATA_INSTALL_DIR}/katepart ) -install( FILES katepart.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) -install( FILES katemoderc katepartpluginsrc DESTINATION ${CONFIG_INSTALL_DIR} ) diff --git a/part/data/katemoderc b/part/data/katemoderc deleted file mode 100644 index 4478e71..0000000 --- a/part/data/katemoderc +++ /dev/null @@ -1,12 +0,0 @@ -[Python] -Variables=kate: indent-mode python; -#Variables=kate: presave-postdialog python-encoding; indent-mode python; - -[Makefile] -Variables=kate: tab-width 8; indent-width 8; replace-tabs off; replace-tabs-save off; - -[YAML] -Variables=kate: space-indent true; - -[XML] -Indenter=xml; diff --git a/part/data/katepart.desktop b/part/data/katepart.desktop deleted file mode 100644 index 43f8a5d..0000000 --- a/part/data/katepart.desktop +++ /dev/null @@ -1,98 +0,0 @@ -[Desktop Entry] -Name=Embedded Advanced Text Editor -Name[af]=Ingebedde Gevorderde teksredigeerder -Name[ar]=محرر نص كيدي متقدم مدمج -Name[as]=পà§à§°à§‹à¦¥à¦¿à¦¤ উনà§à¦¨à¦¤ লিপি সমà§à¦ªà¦¾à¦¦à¦• -Name[ast]=Editor de testu avanzáu encrustáu -Name[be]=Унутраны адмыÑловы Ñ‚ÑкÑтавы Ñ€Ñдактар -Name[be@latin]=Unutrany admysÅ‚ovy tekstavy redaktar -Name[bg]=Разширен текÑтов редактор -Name[bn]=অভà§à¦¯à¦¨à§à¦¤à¦°à§€à¦¨ উনà§à¦¨à¦¤ টেকà§à¦¸à¦Ÿ সমà§à¦ªà¦¾à¦¦à¦• -Name[bn_IN]=à¦à¦®à¦¬à§‡à¦¡ করা উনà§à¦¨à¦¤ টেকà§à¦¸à¦Ÿ à¦à¦¡à¦¿à¦Ÿà¦° -Name[br]=Aozer skrid barek enframmet -Name[ca]=Editor avançat de text, encastat -Name[ca@valencia]=Editor avançat de text, encastat -Name[cs]=Zabudovaný rozšířený editor -Name[csb]=Ã’bsôdzony awansowóny editora tekstu -Name[cy]=Golygydd Testun Uwch Mewnol -Name[da]=Indlejret avanceret teksteditor -Name[de]=Erweiterte Editorkomponente -Name[el]=Ενσωματωμένος Ï€ÏοχωÏημένος επεξεÏγαστής κειμένου -Name[en_GB]=Embedded Advanced Text Editor -Name[eo]=Enkorpigita altnivela tekstredaktilo -Name[es]=Editor de texto avanzado empotrado -Name[et]=Põimitud võimas tekstiredaktor -Name[eu]=Kapsulatutako testu-editore aurreratua -Name[fa]=ویرایشگر متن پیشرÙتۀ نهÙته -Name[fi]=Upotettava monipuolisempi tekstieditori -Name[fr]=Éditeur de texte avancé intégré -Name[fy]=Ynsletten avansearre tekstbewurker -Name[ga]=Ard-eagarthóir téacs leabaithe -Name[gl]=Editor avanzado de textos integrado -Name[gu]=જડિત ઉચà«àªš લખાણ સંપાદક -Name[he]=עורך הטקסט ×”×ž×ª×§×“× ×”×ž×©×•×‘×¥ -Name[hi]=अंतरà¥à¤¨à¤¿à¤°à¥à¤®à¤¿à¤¤ उनà¥à¤¨à¤¤ पाठ संपादक -Name[hne]=भीतर मं बने उनà¥à¤¨à¤¤ पाठ संपादक -Name[hr]=UgraÄ‘ena napredna obrada teksta -Name[hsb]=Integrowany lÄ›pÅ¡i wobdźěłar teksta -Name[hu]=Beágyazott Kate szövegszerkesztÅ‘ -Name[ia]=Avantiate Editor Interne de Texto -Name[id]=Penyunting Teks Canggih Terbenam -Name[is]=Ãvefjanlegur þróaður textaritill -Name[it]=Editor di testi avanzato integrato -Name[ja]=埋ã‚è¾¼ã¿é«˜æ©Ÿèƒ½ãƒ†ã‚­ã‚¹ãƒˆã‚¨ãƒ‡ã‚£ã‚¿ -Name[kk]=Ендірілетін үздік мәтін редакторы -Name[km]=កម្មវិធី​និពន្ធ​អážáŸ’ážáž”ទ​កម្រិážâ€‹ážáŸ’ពស់​ដែល​បាន​បង្កប់ -Name[kn]=ಹà³à²¦à³à²—ಿಸಲಾದ (ಎಂಬೆಡೆಡà³) ಪà³à²°à³Œà²¢ ಪಠà³à²¯ ಸಂಪಾದಕ -Name[ko]=ë¼ì›Œë„£ì€ 고급 í…스트 편집기 -Name[ku]=Edîtora Nivîsê ya Pêşketî yê Jixwe Heyî -Name[lb]=Agebetteten erweiderten Texteditor -Name[lt]=Ä®dÄ—tas sudÄ—tingesnis tekstų redaktorius -Name[lv]=Iegultais papl. tekstu redaktors -Name[mai]=अंतरà¥à¤¨à¤¿à¤°à¥à¤®à¤¿à¤¤ उनà¥à¤¨à¤¤ पाठ संपादक -Name[mk]=Вгнезден напреден текÑÑ‚ уредувач -Name[ml]=എംബഡൠചെയàµà´¤ ആധàµà´¨à´¿à´• ടെകàµà´¸àµà´±àµà´±àµ à´Žà´´àµà´¤àµà´¤à´¿à´Ÿà´‚ -Name[mr]=अंतरà¥à¤­à¥‚तीत पà¥à¤°à¤—त पाठà¥à¤¯ संपादक -Name[ms]=Penyunting Teks Termaju Terimplan -Name[nb]=Innebygget, avansert skriveprogram -Name[nds]=Inbett verwiedert Texteditor -Name[ne]=समà¥à¤®à¤¿à¤²à¤¿à¤¤ उनà¥à¤¨à¤¤ पाठ समà¥à¤ªà¤¾à¤¦à¤• -Name[nl]=Ingebed geavanceerd tekstinvoercomponent -Name[nn]=Innebyggbart avansert skriveprogram -Name[or]=Embedded Advanced Text Editor -Name[pa]=ਇੰਬੈੱਡ ਮਾਹਰ ਟੈਕਸਟ à¨à¨¡à©€à¨Ÿà¨° -Name[pl]=Osadzony zaawansowany edytor tekstu -Name[ps]=راتاو بريونلی ليک سمونګر -Name[pt]=Editor de Texto Avançado Incorporado -Name[pt_BR]=Editor de textos avançado integrado -Name[ro]=Redactor de text avansat înglobat -Name[ru]=Ð’Ñтроенный раÑширенный текÑтовый редактор -Name[se]=Nana buorre vuojuhanláhkái Äállinprográmma -Name[sk]=Vložený pokroÄilý textový editor -Name[sl]=Vgrajeni napredni urejevalnik besedil -Name[sr]=Угнежђени напредни уређивач текÑта -Name[sr@ijekavian]=Угнијежђени напредни уређивач текÑта -Name[sr@ijekavianlatin]=Ugniježđeni napredni ureÄ‘ivaÄ teksta -Name[sr@latin]=Ugnežđeni napredni ureÄ‘ivaÄ teksta -Name[sv]=Inbäddningsbar avancerad texteditor -Name[ta]=உடà¯à®ªà¯Šà®¤à®¿à®¨à¯à®¤ மேமà¯à®ªà®Ÿà¯à®Ÿ உரை தொகà¯à®ªà¯à®ªà®¾à®³à®°à¯ -Name[te]=ఆధà±à°¨à°¿à°• పొదగిన వాచకం సరిచేయà±à°¨à°¦à°¿ -Name[tg]=Таҳриргари матни пешрафти дарунÑохт -Name[th]=ตัวà¹à¸à¹‰à¹„ขข้อความขั้นสูงà¹à¸šà¸šà¸à¸±à¸‡à¸•à¸±à¸§à¹„ด้ -Name[tr]=GeliÅŸmiÅŸ Metin Düzenleyici -Name[uk]=Вмонтований потужний текÑтовий редактор -Name[uz]=Matn tahrirchi -Name[uz@cyrillic]=Матн таҳрирчи -Name[vi]=Bá»™ Soạn thảo Văn bản Cấp cao Nhúng -Name[wa]=Ravalé aspougneu di tecse avancî -Name[xh]=Umhleli Wombhalo Obhekisa phambili Olungiselweyo -Name[x-test]=xxEmbedded Advanced Text Editorxx -Name[zh_CN]=嵌入å¼é«˜çº§æ–‡æœ¬ç¼–辑器 -Name[zh_HK]=嵌入å¼é€²éšŽæ–‡å­—編輯器 -Name[zh_TW]=嵌入å¼é€²éšŽæ–‡å­—編輯器 -X-KDE-Library=katepart -Icon=kate -X-KDE-ServiceTypes=KParts/ReadOnlyPart,Browser/View,KParts/ReadWritePart,KTextEditor/Document -Type=Service -InitialPreference=8 -MimeType=text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-patch;text/x-adasrc;text/x-chdr;text/x-csrc;text/css;application/x-desktop;text/x-patch;text/x-fortran;text/html;text/x-java;text/x-tex;text/x-makefile;text/x-objcsrc;text/x-pascal;application/x-perl;application/x-perl;application/x-php;text/vnd.wap.wml;text/x-python;application/x-ruby;text/sgml;application/xml;model/vrml; diff --git a/part/data/katepartpluginsrc b/part/data/katepartpluginsrc deleted file mode 100644 index ca695de..0000000 --- a/part/data/katepartpluginsrc +++ /dev/null @@ -1,2 +0,0 @@ -[Kate Part Plugins] -ktexteditorexporter=true diff --git a/part/data/katepartsimpleui.rc b/part/data/katepartsimpleui.rc deleted file mode 100644 index bdd7b68..0000000 --- a/part/data/katepartsimpleui.rc +++ /dev/null @@ -1,90 +0,0 @@ - - - - &File - - - - - - - - &Edit - - - - - - - - - - - - - - - - - - - - - - - &View - - - - - - - - &Tools - - - - - - - - - - - - - - - - - - - - - - - &Settings - - - - - - - - - - - - - - - - -Main Toolbar - - - - - - - diff --git a/part/data/katepartui.rc b/part/data/katepartui.rc deleted file mode 100644 index 364c626..0000000 --- a/part/data/katepartui.rc +++ /dev/null @@ -1,131 +0,0 @@ - - - - &File - - - - - - - - &Edit - - - - - - - - - - - - - - - - - - - - - - - - - &View - - - - - - - - - - - - - - - &Code Folding - - - - - - - - - - - - - &Tools - - - - - - - - - - - - - Word Completion - - - - - - - - - - - - - - - - - - - - - - - - - - - &Settings - - - - - - - - - - - - - - - - - - -Main Toolbar - - - - - - - diff --git a/part/dialogs/bordersappearanceconfigwidget.ui b/part/dialogs/bordersappearanceconfigwidget.ui deleted file mode 100644 index a083a99..0000000 --- a/part/dialogs/bordersappearanceconfigwidget.ui +++ /dev/null @@ -1,112 +0,0 @@ - - - BordersAppearanceConfigWidget - - - - 0 - 0 - 275 - 260 - - - - - - - Borders - - - - - - If this option is checked, every new view will display marks for code folding, if code folding is available. - - - Show &folding markers (if available) - - - - - - - <p>If this option is checked, every new view will display an icon border on the left hand side.</p><p>The icon border shows bookmark signs, for instance.</p> - - - Show &icon border - - - - - - - If this option is checked, every new view will display line numbers on the left hand side. - - - Show &line numbers - - - - - - - <p>If this option is checked, every new view will show marks on the vertical scrollbar.</p><p>These marks will show bookmarks, for instance.</p> - - - Show &scrollbar marks - - - - - - - - - - Choose how the bookmarks should be ordered in the <b>Bookmarks</b> menu. - - - Sort Bookmarks Menu - - - - - - Each new bookmark will be added to the bottom, independently from where it is placed in the document. - - - By c&reation - - - - - - - The bookmarks will be ordered by the line numbers they are placed at. - - - By &position - - - - - - - - - - Qt::Vertical - - - - 20 - 31 - - - - - - - - - diff --git a/part/dialogs/commandmenuconfigwidget.ui b/part/dialogs/commandmenuconfigwidget.ui deleted file mode 100644 index 6448edf..0000000 --- a/part/dialogs/commandmenuconfigwidget.ui +++ /dev/null @@ -1,175 +0,0 @@ - - - CmdBindingConfigWidget - - - - 0 - - - - - - 0 - 1 - - - - false - - - - Name - - - - - Command - - - - - Description - - - - - - - - 0 - - - - - false - - - Edit Entry... - - - - - - - false - - - Remove Entry - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - Add Entry... - - - - - - - - - - 0 - 0 - - - - Further Notes - - - true - - - - - - - 0 - 0 - - - - <p>The entries are accessible through the submenu <b>Commands</b> in the <b>Tools</b> menu. For faster access it is possible to assign <b>shortcuts</b> in the shortcut configuration page after applying the changes.</p> - - - Qt::RichText - - - true - - - - - - - 0 - - - - - - 0 - 0 - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - - - - - Qt::Vertical - - - - - - - - KSeparator - QFrame -
kseparator.h
-
-
- - treeWidget - btnAddEntry - btnRemoveEntry - btnEditEntry - - - -
diff --git a/part/dialogs/commandmenueditwidget.ui b/part/dialogs/commandmenueditwidget.ui deleted file mode 100644 index f89b3c6..0000000 --- a/part/dialogs/commandmenueditwidget.ui +++ /dev/null @@ -1,180 +0,0 @@ - - - CmdBindingEditWidget - - - - 0 - - - - - Edit Command - - - true - - - - - - 0 - - - - - &Associated command: - - - cmbCommand - - - - - - - true - - - Qt::CaseSensitive - - - false - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - 0 - - - - - &Name: - - - edtName - - - - - - - 0 - - - - - - - - Choose an icon. - - - <p>This icon will be displayed in the menu and toolbar.</p> - - - - - - - - - - - - &Description: - - - edtDescription - - - - - - - - - - &Category: - - - cmbCategory - - - - - - - true - - - Qt::CaseSensitive - - - false - - - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIconButton - QPushButton -
kicondialog.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
-
- - edtName - edtDescription - cmbCategory - cmbCommand - - - -
diff --git a/part/dialogs/completionconfigtab.ui b/part/dialogs/completionconfigtab.ui deleted file mode 100644 index 01418e7..0000000 --- a/part/dialogs/completionconfigtab.ui +++ /dev/null @@ -1,91 +0,0 @@ - - - CompletionConfigTab - - - - 0 - - - - - General - - - - - - &Auto completion enabled - - - - - - - - - - Auto Word Completion - - - true - - - false - - - - - - - - Minimal word length to complete: - - - - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
-
- - -
diff --git a/part/dialogs/completionconfigwidget.ui b/part/dialogs/completionconfigwidget.ui deleted file mode 100644 index b189451..0000000 --- a/part/dialogs/completionconfigwidget.ui +++ /dev/null @@ -1,462 +0,0 @@ - - CompletionConfigWidget - - - - 0 - 0 - 687 - 853 - - - - - - - Sorting - - - true - - - true - - - false - - - - - - 0 - - - - - Alphabetical - - - - - - - Reverse - - - - - - - Case sensitive - - - - - - - Inheritance depth - - - - - - - Qt::Vertical - - - - 0 - 0 - - - - - - - - - - 0 - - - - - Order of Groupings (select a grouping method to configure): - - - - - - - 0 - - - - - - - - 0 - - - - - ^ - - - - - - - \/ - - - - - - - - - - - - - - - - Filtering - - - true - - - true - - - false - - - - - - Suitable context matches only - - - - - - - Hide completions with the following attributes: - - - - - - - - - - Maximum inheritance depth: - - - 0 - - - 20 - - - 0 - - - Infinity - - - - - - - - - - Grouping - - - true - - - true - - - false - - - - - - false - - - - Grouping Method - - - - - Scope type (local, namespace, global) - - - - - Scope (eg. per class) - - - - - Access type (public etc.) - - - - - Item type (function etc.) - - - - - - - - 0 - - - - - ^ - - - - - - - \/ - - - - - - - - - 0 - - - - - 0 - - - - - 0 - - - - - - 75 - true - - - - Access Grouping Properties - - - - - - - Include const in grouping - - - - - - - Include static in grouping - - - - - - - Include signals and slots in grouping - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - 75 - true - - - - Item Grouping properties - - - - - - - Include templates in grouping - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - - Column Merging - - - true - - - true - - - false - - - - - - - 0 - 0 - - - - false - - - - Columns - - - - - Merged - - - - - Shown - - - - - - - - 0 - - - - - ^ - - - - - - - \/ - - - - - - - - - Qt::Horizontal - - - - 20 - 105 - - - - - - - - - - - - KIntNumInput - QWidget -
knuminput.h
-
-
- - - - filteringHideAttributes - toggled(bool) - filteringAttributesList - setEnabled(bool) - - - 290 - 298 - - - 307 - 375 - - - - -
diff --git a/part/dialogs/cursorconfigwidget.ui b/part/dialogs/cursorconfigwidget.ui deleted file mode 100644 index 8c927e3..0000000 --- a/part/dialogs/cursorconfigwidget.ui +++ /dev/null @@ -1,141 +0,0 @@ - - - CursorConfigWidget - - - - 0 - - - - - Text Cursor Movement - - - - - - When selected, pressing the home key will cause the cursor to skip whitespace and go to the start of a line's text. The same applies for the end key. - - - Smart ho&me and smart end - - - - - - - <p>When on, moving the insertion cursor using the <b>Left</b> and <b>Right</b> keys will go on to previous/next line at beginning/end of the line, similar to most editors.</p><p>When off, the insertion cursor cannot be moved left of the line start, but it can be moved off the line end, which can be very handy for programmers.</p> - - - Wrap c&ursor - - - - - - - Selects whether the PageUp and PageDown keys should alter the vertical position of the cursor relative to the top of the view. - - - &PageUp/PageDown moves cursor - - - - - - - 0 - - - - - &Autocenter cursor (lines): - - - sbAutoCenterCursor - - - - - - - Sets the number of lines to maintain visible above and below the cursor when possible. - - - Disabled - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - - - - Text Selection Mode - - - - - - Selections will be overwritten by typed text and will be lost on cursor movement. - - - &Normal - - - - - - - Selections will stay even after cursor movement and typing. - - - P&ersistent - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
-
- - -
diff --git a/part/dialogs/editconfigwidget.ui b/part/dialogs/editconfigwidget.ui deleted file mode 100644 index 6b796c9..0000000 --- a/part/dialogs/editconfigwidget.ui +++ /dev/null @@ -1,159 +0,0 @@ - - - EditConfigWidget - - - - 0 - 0 - 321 - 377 - - - - - 0 - - - - - Static Word Wrap - - - - - - <p>Automatically start a new line of text when the current line exceeds the length specified by the <b>Wrap words at:</b> option.</p><p>This option does not wrap existing lines of text - use the <b>Apply Static Word Wrap</b> option in the <b>Tools</b> menu for that purpose.</p><p>If you want lines to be <i>visually wrapped</i> instead, according to the width of the view, enable <b>Dynamic Word Wrap</b> in the <b>View Defaults</b> config page.</p> - - - Enable static &word wrap - - - - - - - <p>If this option is checked, a vertical line will be drawn at the word wrap column as defined in the <strong>Editing</strong> properties.</p><p>Note that the word wrap marker is only drawn if you use a fixed pitch font.</p> - - - Show static word wra&p marker (if applicable) - - - - - - - 0 - - - - - W&rap words at: - - - sbWordWrap - - - - - - - If the Word Wrap option is selected this entry determines the length (in characters) at which the editor will automatically start a new line. - - - 20 - - - 200 - - - 76 - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - - - - Misc - - - - - - If this is enabled, the editor will remove any trailing whitespace on lines that are changed through editing. - - - Remove &trailing spaces while editing - - - - - - - When the user types a left bracket ([,(, or {) KateView automatically enters the right bracket (}, ), or ]) to the right of the cursor. - - - Auto &brackets - - - - - - - Copy/Cut the current line if no selection - - - - - - - Allow scrolling past the end of the document - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
-
- - -
diff --git a/part/dialogs/filetypeconfigwidget.ui b/part/dialogs/filetypeconfigwidget.ui deleted file mode 100644 index 02ce75a..0000000 --- a/part/dialogs/filetypeconfigwidget.ui +++ /dev/null @@ -1,272 +0,0 @@ - - - FileTypeConfigWidget - - - - 0 - - - - - - - &Filetype: - - - cmbFiletypes - - - - - - - Select the filetype you want to change. - - - - - - - Create a new file type. - - - &New - - - - - - - Delete the current file type. - - - &Delete - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - Properties - - - - - - &Name: - - - edtName - - - - - - - The name of the filetype will be the text of the corresponding menu item. - - - - - - - &Section: - - - edtSection - - - - - - - The section name is used to organize the file types in menus. - - - - - - - &Variables: - - - edtVariables - - - - - - - <p>This string allows to configure Kate's settings for the files selected by this mimetype using Kate variables. Almost any configuration option can be set, such as highlight, indent-mode, encoding, etc.</p><p>For a full list of known variables, see the manual.</p> - - - - - - - &Highlighting: - - - cmbHl - - - - - - - - - - &Indentation Mode: - - - cmbIndenter - - - - - - - - - - File e&xtensions: - - - edtFileExtensions - - - - - - - The wildcards mask allows to select files by filename. A typical mask uses an asterisk and the file extension, for example <code>*.txt; *.text</code>. The string is a semicolon-separated list of masks. - - - - - - - MIME &types: - - - edtMimeTypes - - - - - - - 0 - - - - - The mime type mask allows to select files by mimetype. The string is a semicolon-separated list of mimetypes, for example <code>text/plain; text/english</code>. - - - - - - - Displays a wizard that helps you easily select mimetypes. - - - - - - - - - P&riority: - - - sbPriority - - - - - - - Sets priority for this file type. If more than one file type selects the same file, the one with the highest priority will be used. - - - - - - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - Download Highlighting Files... - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
-
- - -
diff --git a/part/dialogs/indentationconfigwidget.ui b/part/dialogs/indentationconfigwidget.ui deleted file mode 100644 index 6d1fc08..0000000 --- a/part/dialogs/indentationconfigwidget.ui +++ /dev/null @@ -1,296 +0,0 @@ - - - IndentationConfigWidget - - - - 0 - 0 - 417 - 390 - - - - - 0 - - - - - 0 - - - - - Default indentation mode: - - - cmbMode - - - - - - - This is a list of available indentation modes. The specified indentation mode will be used for all new documents. Be aware that it is also possible to set the indentation mode with document variables, modes or a .kateconfig file. - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - Indent using - - - - - - &Tabulators - - - - - - - &Spaces - - - - - - - &Indentation width: - - - sbIndentWidth - - - - - - - The indentation width is the number of spaces which is used to indent a line. If the option <b>Insert spaces instead of tabulators</b> in the section <b>Editing</b> is disabled, a <b>Tab</b> character is inserted if the indentation is divisible by the tab width. - - - 1 - - - 16 - - - 4 - - - - - - - Tabulators &and Spaces - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Tab wi&dth: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - sbTabWidth - - - - - - - 1 - - - 16 - - - 8 - - - - - - - - - - Indentation Properties - - - - - - If this option is disabled, changing the indentation level aligns a line to a multiple of the width specified in <b>Indentation width</b>. - - - &Keep extra spaces - - - - - - - If this option is selected, pasted code from the clipboard is indented. Triggering the <b>undo</b>-action removes the indentation. - - - Adjust indentation of code &pasted from the clipboard - - - - - - - - - - Indentation Actions - - - - - - If this option is selected, the <b>Backspace</b> key decreases the indentation level if the cursor is located in the leading blank space of a line. - - - &Backspace key in leading blank space unindents - - - - - - - <html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body> -<p>Tab key action (if no selection exists) <a href="If you want <b>Tab</b> to align the current line in the current code block like in emacs, make <b>Tab</b> a shortcut to the action <b>Align</b>."><span>More ...</span></a></p></body></html> - - - - - - - 0 - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 0 - - - - - - - - 0 - - - - - If this option is selected, the <b>Tab</b> key always inserts white space so that the next tab position is reached. If the option <b>Insert spaces instead of tabulators</b> in the section <b>Editing</b> is enabled, spaces are inserted; otherwise, a single tabulator is inserted. - - - Always advance to the &next tab position - - - - - - - If this option is selected, the <b>Tab</b> key always indents the current line by the number of character positions specified in <b>Indentation width</b>. - - - Always increase indentation &level - - - - - - - If this option is selected, the <b>Tab</b> key either indents the current line or advances to the next tab position.<p> If the insertion point is at or before the first non-space character in the line, or if there is a selection, the current line is indented by the number of character positions specified in <b>Indentation width</b>.<p> If the insertion point is located after the first non-space character in the line and there is no selection, white space is inserted so that the next tab position is reached: if the option <b>Insert spaces instead of tabulators</b> in the section <b>Editing</b> is enabled, spaces are inserted; otherwise, a single tabulator is inserted. - - - Increase indentation level if in l&eading blank space - - - - - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
-
- - -
diff --git a/part/dialogs/katedialogs.cpp b/part/dialogs/katedialogs.cpp deleted file mode 100644 index 32fcf6d..0000000 --- a/part/dialogs/katedialogs.cpp +++ /dev/null @@ -1,1591 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002, 2003 Anders Lund - Copyright (C) 2003 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 2006 Dominik Haumann - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2009 Michel Ludwig - Copyright (C) 2009 Erlend Hamberg - - Based on work of: - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN Includes -#include "katedialogs.h" -#include "katedialogs.moc" - -#include "kateautoindent.h" -#include "katebuffer.h" -#include "kateconfig.h" -#include "katedocument.h" -#include "kateglobal.h" -#include "kateviglobal.h" -#include "katevikeyparser.h" -#include "kateschema.h" -#include "katesyntaxdocument.h" -#include "katemodeconfigpage.h" -#include "kateview.h" -#include "katepartpluginmanager.h" -#include "kpluginselector.h" -#include "spellcheck/spellcheck.h" - -// auto generated ui files -#include "ui_modonhdwidget.h" -#include "ui_textareaappearanceconfigwidget.h" -#include "ui_bordersappearanceconfigwidget.h" -#include "ui_cursorconfigwidget.h" -#include "ui_editconfigwidget.h" -#include "ui_indentationconfigwidget.h" -#include "ui_completionconfigtab.h" -#include "ui_opensaveconfigwidget.h" -#include "ui_opensaveconfigadvwidget.h" -#include "ui_viinputmodeconfigwidget.h" -#include "ui_spellcheckconfigwidget.h" - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// trailing slash is important -#define HLDOWNLOADPATH "http://kate.kde.org/syntax/" - -//END - -//BEGIN KateConfigPage -KateConfigPage::KateConfigPage ( QWidget *parent, const char * ) - : KTextEditor::ConfigPage (parent) - , m_changed (false) -{ - connect (this, SIGNAL(changed()), this, SLOT(somethingHasChanged ())); -} - -KateConfigPage::~KateConfigPage () -{ -} - -void KateConfigPage::slotChanged() -{ - emit changed(); -} - -void KateConfigPage::somethingHasChanged () -{ - m_changed = true; - kDebug (13000) << "TEST: something changed on the config page: " << this; -} -//END KateConfigPage - -//BEGIN KateIndentConfigTab -KateIndentConfigTab::KateIndentConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - // This will let us have more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::IndentationConfigWidget(); - ui->setupUi( newWidget ); - - ui->cmbMode->addItems (KateAutoIndent::listModes()); - - ui->label->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); - connect(ui->label, SIGNAL(linkActivated(const QString&)), this, SLOT(showWhatsThis(const QString&))); - - // What's This? help can be found in the ui file - - reload (); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect(ui->cmbMode, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect(ui->rbIndentWithTabs, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbIndentWithSpaces, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbIndentMixed, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbIndentWithTabs, SIGNAL(toggled(bool)), ui->sbIndentWidth, SLOT(setDisabled(bool))); - - connect(ui->chkKeepExtraSpaces, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkIndentPaste, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkBackspaceUnindents, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - - connect(ui->sbTabWidth, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - connect(ui->sbIndentWidth, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - - connect(ui->rbTabAdvances, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbTabIndents, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbTabSmart, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateIndentConfigTab::~KateIndentConfigTab() -{ - delete ui; -} - -void KateIndentConfigTab::slotChanged() -{ - if (ui->rbIndentWithTabs->isChecked()) - ui->sbIndentWidth->setValue(ui->sbTabWidth->value()); - - KateConfigPage::slotChanged(); -} - -void KateIndentConfigTab::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -void KateIndentConfigTab::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateDocumentConfig::global()->configStart (); - - KateDocumentConfig::global()->setKeepExtraSpaces(ui->chkKeepExtraSpaces->isChecked()); - KateDocumentConfig::global()->setBackspaceIndents(ui->chkBackspaceUnindents->isChecked()); - KateDocumentConfig::global()->setIndentPastedText(ui->chkIndentPaste->isChecked()); - KateDocumentConfig::global()->setIndentationWidth(ui->sbIndentWidth->value()); - KateDocumentConfig::global()->setIndentationMode(KateAutoIndent::modeName(ui->cmbMode->currentIndex())); - KateDocumentConfig::global()->setTabWidth(ui->sbTabWidth->value()); - KateDocumentConfig::global()->setReplaceTabsDyn(ui->rbIndentWithSpaces->isChecked()); - - if (ui->rbTabAdvances->isChecked()) - KateDocumentConfig::global()->setTabHandling( KateDocumentConfig::tabInsertsTab ); - else if (ui->rbTabIndents->isChecked()) - KateDocumentConfig::global()->setTabHandling( KateDocumentConfig::tabIndents ); - else - KateDocumentConfig::global()->setTabHandling( KateDocumentConfig::tabSmart ); - - KateDocumentConfig::global()->configEnd (); -} - -void KateIndentConfigTab::reload () -{ - ui->sbTabWidth->setSuffix(ki18np(" character", " characters")); - ui->sbTabWidth->setValue(KateDocumentConfig::global()->tabWidth()); - ui->sbIndentWidth->setSuffix(ki18np(" character", " characters")); - ui->sbIndentWidth->setValue(KateDocumentConfig::global()->indentationWidth()); - ui->chkKeepExtraSpaces->setChecked(KateDocumentConfig::global()->keepExtraSpaces()); - ui->chkIndentPaste->setChecked(KateDocumentConfig::global()->indentPastedText()); - ui->chkBackspaceUnindents->setChecked(KateDocumentConfig::global()->backspaceIndents()); - - ui->rbTabAdvances->setChecked( KateDocumentConfig::global()->tabHandling() == KateDocumentConfig::tabInsertsTab ); - ui->rbTabIndents->setChecked( KateDocumentConfig::global()->tabHandling() == KateDocumentConfig::tabIndents ); - ui->rbTabSmart->setChecked( KateDocumentConfig::global()->tabHandling() == KateDocumentConfig::tabSmart ); - - ui->cmbMode->setCurrentIndex (KateAutoIndent::modeNumber (KateDocumentConfig::global()->indentationMode())); - - if (KateDocumentConfig::global()->replaceTabsDyn()) - ui->rbIndentWithSpaces->setChecked (true); - else - { - if (KateDocumentConfig::global()->indentationWidth() == KateDocumentConfig::global()->tabWidth()) - ui->rbIndentWithTabs->setChecked (true); - else - ui->rbIndentMixed->setChecked (true); - } - - ui->sbIndentWidth->setEnabled(!ui->rbIndentWithTabs->isChecked()); -} -//END KateIndentConfigTab - -//BEGIN KateCompletionConfigTab -KateCompletionConfigTab::KateCompletionConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - // This will let us have more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::CompletionConfigTab (); - ui->setupUi( newWidget ); - - // What's This? help can be found in the ui file - - reload (); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect(ui->chkAutoCompletionEnabled, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->gbWordCompletion, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->minimalWordLength, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateCompletionConfigTab::~KateCompletionConfigTab() -{ - delete ui; -} - -void KateCompletionConfigTab::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -void KateCompletionConfigTab::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateViewConfig::global()->configStart (); - KateViewConfig::global()->setAutomaticCompletionInvocation (ui->chkAutoCompletionEnabled->isChecked()); - KateViewConfig::global()->setWordCompletion (ui->gbWordCompletion->isChecked()); - KateViewConfig::global()->setWordCompletionMinimalWordLength (ui->minimalWordLength->value()); - KateViewConfig::global()->configEnd (); -} - -void KateCompletionConfigTab::reload () -{ - ui->chkAutoCompletionEnabled->setChecked( KateViewConfig::global()->automaticCompletionInvocation () ); - ui->gbWordCompletion->setChecked( KateViewConfig::global()->wordCompletion () ); - ui->minimalWordLength->setValue (KateViewConfig::global()->wordCompletionMinimalWordLength ()); -} -//END KateCompletionConfigTab - -//BEGIN KateViInputModeConfigTab -KateViInputModeConfigTab::KateViInputModeConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - // This will let us have more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::ViInputModeConfigWidget (); - ui->setupUi( newWidget ); - - // What's This? help can be found in the ui file - - reload (); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect(ui->chkViInputModeDefault, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkViCommandsOverride, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkViStatusBarHide, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->tblNormalModeMappings, SIGNAL(cellChanged(int, int)), this, SLOT(slotChanged())); - connect(ui->btnAddNewNormal, SIGNAL(clicked()), this, SLOT(addNewNormalModeMappingRow())); - connect(ui->btnRemoveSelectedNormal, SIGNAL(clicked()), this, SLOT(removeSelectedNormalMappingRow())); - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateViInputModeConfigTab::~KateViInputModeConfigTab() -{ - delete ui; -} - -void KateViInputModeConfigTab::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -void KateViInputModeConfigTab::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateViewConfig::global()->configStart (); - KateViewConfig::global()->setViInputMode (ui->chkViInputModeDefault->isChecked()); - KateViewConfig::global()->setViInputModeStealKeys (ui->chkViCommandsOverride->isChecked()); - KateViewConfig::global()->setViInputModeHideStatusBar (ui->chkViStatusBarHide->isChecked()); - KateGlobal::self()->viInputModeGlobal()->clearMappings( NormalMode ); - for ( int i = 0; i < ui->tblNormalModeMappings->rowCount(); i++ ) { - QTableWidgetItem* from = ui->tblNormalModeMappings->item( i, 0 ); - QTableWidgetItem* to = ui->tblNormalModeMappings->item( i, 1 ); - - if ( from && to ) { - KateGlobal::self()->viInputModeGlobal()->addMapping( NormalMode, from->text(), to->text() ); - } - } - KateViewConfig::global()->configEnd (); -} - -void KateViInputModeConfigTab::reload () -{ - ui->chkViInputModeDefault->setChecked( KateViewConfig::global()->viInputMode () ); - ui->chkViCommandsOverride->setChecked( KateViewConfig::global()->viInputModeStealKeys () ); - ui->chkViStatusBarHide->setChecked( KateViewConfig::global()->viInputModeHideStatusBar () ); - - ui->chkViCommandsOverride->setEnabled(ui->chkViInputModeDefault->isChecked()); - ui->chkViStatusBarHide->setEnabled(ui->chkViInputModeDefault->isChecked()); - - QStringList l = KateGlobal::self()->viInputModeGlobal()->getMappings( NormalMode ); - ui->tblNormalModeMappings->setRowCount( l.size() ); - - // make the two columns fill the entire table width - ui->tblNormalModeMappings->setColumnWidth( 0, ui->tblNormalModeMappings->width()/3 ); - ui->tblNormalModeMappings->horizontalHeader()->setStretchLastSection( true ); - - int i = 0; - foreach( const QString &f, l ) { - QTableWidgetItem *from - = new QTableWidgetItem( KateViKeyParser::getInstance()->decodeKeySequence( f ) ); - QString s = KateGlobal::self()->viInputModeGlobal()->getMapping( NormalMode, f ); - QTableWidgetItem *to = - new QTableWidgetItem( KateViKeyParser::getInstance()->decodeKeySequence( s ) ); - - ui->tblNormalModeMappings->setItem(i, 0, from); - ui->tblNormalModeMappings->setItem(i++, 1, to); - } -} - -void KateViInputModeConfigTab::addNewNormalModeMappingRow() -{ - int rows = ui->tblNormalModeMappings->rowCount(); - ui->tblNormalModeMappings->insertRow( rows ); - ui->tblNormalModeMappings->setCurrentCell( rows, 0 ); - ui->tblNormalModeMappings->editItem( ui->tblNormalModeMappings->currentItem() ); -} - -void KateViInputModeConfigTab::removeSelectedNormalMappingRow() -{ - QList l = ui->tblNormalModeMappings->selectedRanges(); - - foreach( const QTableWidgetSelectionRange &range, l ) { - for ( int i = 0; i < range.bottomRow()-range.topRow()+1; i++ ) { - ui->tblNormalModeMappings->removeRow( range.topRow() ); - } - } -} -//END KateViInputModeConfigTab - -//BEGIN KateSpellCheckConfigTab -KateSpellCheckConfigTab::KateSpellCheckConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - // This will let us have more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::SpellCheckConfigWidget(); - ui->setupUi(newWidget); - - // What's This? help can be found in the ui file - reload(); - - // - // after initial reload, connect the stuff for the changed () signal - - m_sonnetConfigWidget = new Sonnet::ConfigWidget(KGlobal::config().data(), this); - connect(m_sonnetConfigWidget, SIGNAL(configChanged()), this, SLOT(slotChanged())); - layout->addWidget(m_sonnetConfigWidget); - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateSpellCheckConfigTab::~KateSpellCheckConfigTab() -{ - delete ui; -} - -void KateSpellCheckConfigTab::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -void KateSpellCheckConfigTab::apply() -{ - if (!hasChanged()) { - // nothing changed, no need to apply stuff - return; - } - m_changed = false; - - KateDocumentConfig::global()->configStart(); - m_sonnetConfigWidget->save(); - KateDocumentConfig::global()->configEnd(); - foreach (KateDocument *doc, KateGlobal::self()->kateDocuments()) { - doc->refreshOnTheFlyCheck(); - } -} - -void KateSpellCheckConfigTab::reload() -{ - // does nothing -} -//END KateSpellCheckConfigTab - -//BEGIN KateSelectConfigTab -KateSelectConfigTab::KateSelectConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - // This will let us having more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::CursorConfigWidget(); - ui->setupUi( newWidget ); - - // What's This? Help is in the ui-files - - reload (); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect(ui->rbNormal, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->rbPersistent, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkSmartHome, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkWrapCursor, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkPagingMovesCursor, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->sbAutoCenterCursor, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateSelectConfigTab::~KateSelectConfigTab() -{ - delete ui; -} - -void KateSelectConfigTab::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateViewConfig::global()->configStart (); - KateDocumentConfig::global()->configStart (); - - KateDocumentConfig::global()->setSmartHome(ui->chkSmartHome->isChecked()); - KateDocumentConfig::global()->setWrapCursor(ui->chkWrapCursor->isChecked()); - - KateViewConfig::global()->setAutoCenterLines(qMax(0, ui->sbAutoCenterCursor->value())); - KateDocumentConfig::global()->setPageUpDownMovesCursor(ui->chkPagingMovesCursor->isChecked()); - - KateViewConfig::global()->setPersistentSelection (ui->rbPersistent->isChecked()); - - KateDocumentConfig::global()->configEnd (); - KateViewConfig::global()->configEnd (); -} - -void KateSelectConfigTab::reload () -{ - ui->rbNormal->setChecked( ! KateViewConfig::global()->persistentSelection() ); - ui->rbPersistent->setChecked( KateViewConfig::global()->persistentSelection() ); - - ui->chkSmartHome->setChecked(KateDocumentConfig::global()->smartHome()); - ui->chkWrapCursor->setChecked(KateDocumentConfig::global()->wrapCursor()); - ui->chkPagingMovesCursor->setChecked(KateDocumentConfig::global()->pageUpDownMovesCursor()); - ui->sbAutoCenterCursor->setValue(KateViewConfig::global()->autoCenterLines()); -} -//END KateSelectConfigTab - -//BEGIN KateEditGeneralConfigTab -KateEditGeneralConfigTab::KateEditGeneralConfigTab(QWidget *parent) - : KateConfigPage(parent) -{ - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - ui = new Ui::EditConfigWidget(); - ui->setupUi( newWidget ); - - reload(); - - connect(ui->chkStaticWordWrap, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkShowStaticWordWrapMarker, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->sbWordWrap, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - connect( ui->chkRemoveTrailingSpaces, SIGNAL(toggled(bool)), this, SLOT(slotChanged()) ); - connect(ui->chkAutoBrackets, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkSmartCopyCut, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(ui->chkScrollPastEnd, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - - // "What's this?" help is in the ui-file - - layout->addWidget(newWidget); - setLayout(layout); -} - -KateEditGeneralConfigTab::~KateEditGeneralConfigTab() -{ - delete ui; -} - -void KateEditGeneralConfigTab::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateViewConfig::global()->configStart (); - KateDocumentConfig::global()->configStart (); - - KateDocumentConfig::global()->setAutoBrackets(ui->chkAutoBrackets->isChecked()); - KateDocumentConfig::global()->setRemoveTrailingDyn(ui->chkRemoveTrailingSpaces->isChecked()); - - KateDocumentConfig::global()->setWordWrapAt(ui->sbWordWrap->value()); - KateDocumentConfig::global()->setWordWrap(ui->chkStaticWordWrap->isChecked()); - - KateRendererConfig::global()->setWordWrapMarker (ui->chkShowStaticWordWrapMarker->isChecked()); - - KateDocumentConfig::global()->configEnd (); - KateViewConfig::global()->setSmartCopyCut(ui->chkSmartCopyCut->isChecked()); - KateViewConfig::global()->setScrollPastEnd(ui->chkScrollPastEnd->isChecked()); - KateViewConfig::global()->configEnd (); -} - -void KateEditGeneralConfigTab::reload () -{ - ui->chkStaticWordWrap->setChecked(KateDocumentConfig::global()->wordWrap()); - ui->chkShowStaticWordWrapMarker->setChecked( KateRendererConfig::global()->wordWrapMarker() ); - ui->sbWordWrap->setSuffix(ki18ncp("Wrap words at", " character", " characters")); - ui->sbWordWrap->setValue( KateDocumentConfig::global()->wordWrapAt() ); - ui->chkRemoveTrailingSpaces->setChecked( KateDocumentConfig::global()->removeTrailingDyn() ); - ui->chkAutoBrackets->setChecked( KateDocumentConfig::global()->autoBrackets() ); - ui->chkSmartCopyCut->setChecked( KateViewConfig::global()->smartCopyCut() ); - ui->chkScrollPastEnd->setChecked( KateViewConfig::global()->scrollPastEnd() ); -} -//END KateEditGeneralConfigTab - - -//BEGIN KateEditConfigTab -KateEditConfigTab::KateEditConfigTab(QWidget *parent) - : KateConfigPage(parent) - , editConfigTab(new KateEditGeneralConfigTab(this)) - , selectConfigTab(new KateSelectConfigTab(this)) - , indentConfigTab(new KateIndentConfigTab(this)) - , completionConfigTab (new KateCompletionConfigTab(this)) - , viInputModeConfigTab(new KateViInputModeConfigTab(this)) - , spellCheckConfigTab(new KateSpellCheckConfigTab(this)) -{ - QVBoxLayout *layout = new QVBoxLayout; - layout->setMargin(0); - KTabWidget *tabWidget = new KTabWidget(this); - - // add all tabs - tabWidget->insertTab(0, editConfigTab, i18n("General")); - tabWidget->insertTab(1, selectConfigTab, i18n("Cursor && Selection")); - tabWidget->insertTab(2, indentConfigTab, i18n("Indentation")); - tabWidget->insertTab(3, completionConfigTab, i18n("Auto Completion")); - tabWidget->insertTab(4, viInputModeConfigTab, i18n("Vi Input Mode")); - tabWidget->insertTab(5, spellCheckConfigTab, i18n("Spellcheck")); - - connect(editConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - connect(selectConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - connect(indentConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - connect(completionConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - connect(viInputModeConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - connect(spellCheckConfigTab, SIGNAL(changed()), this, SLOT(slotChanged())); - - layout->addWidget(tabWidget); - setLayout(layout); -} - -KateEditConfigTab::~KateEditConfigTab() -{ -} - -void KateEditConfigTab::apply () -{ - // try to update the rest of tabs - editConfigTab->apply(); - selectConfigTab->apply(); - indentConfigTab->apply(); - completionConfigTab->apply(); - viInputModeConfigTab->apply(); - spellCheckConfigTab->apply(); -} - -void KateEditConfigTab::reload () -{ - editConfigTab->reload(); - selectConfigTab->reload(); - indentConfigTab->reload(); - completionConfigTab->reload(); - viInputModeConfigTab->reload(); - spellCheckConfigTab->reload(); -} - -void KateEditConfigTab::reset () -{ - editConfigTab->reset(); - selectConfigTab->reset(); - indentConfigTab->reset(); - completionConfigTab->reset(); - viInputModeConfigTab->reset(); - spellCheckConfigTab->reset(); -} - -void KateEditConfigTab::defaults () -{ - editConfigTab->defaults(); - selectConfigTab->defaults(); - indentConfigTab->defaults(); - completionConfigTab->defaults(); - viInputModeConfigTab->defaults(); - spellCheckConfigTab->defaults(); -} -//END KateEditConfigTab - -//BEGIN KateViewDefaultsConfig -KateViewDefaultsConfig::KateViewDefaultsConfig(QWidget *parent) - : KateConfigPage(parent) - , textareaUi(new Ui::TextareaAppearanceConfigWidget()) - , bordersUi(new Ui::BordersAppearanceConfigWidget()) -{ - QLayout *layout = new QVBoxLayout( this ); - QTabWidget *tabWidget = new QTabWidget( this ); - layout->addWidget( tabWidget ); - layout->setMargin( 0 ); - - QWidget *textareaTab = new QWidget( tabWidget ); - textareaUi->setupUi( textareaTab ); - tabWidget->addTab( textareaTab, i18n("General") ); - - QWidget *bordersTab = new QWidget( tabWidget ); - bordersUi->setupUi( bordersTab ); - tabWidget->addTab( bordersTab, i18n("Borders") ); - - if (KateDocument::simpleMode ()) - bordersUi->gbSortBookmarks->hide (); - - textareaUi->cmbDynamicWordWrapIndicator->addItem( i18n("Off") ); - textareaUi->cmbDynamicWordWrapIndicator->addItem( i18n("Follow Line Numbers") ); - textareaUi->cmbDynamicWordWrapIndicator->addItem( i18n("Always On") ); - - // hide power user mode if activated anyway - if (!KateGlobal::self()->simpleMode ()) - textareaUi->chkDeveloperMode->hide (); - - // What's This? help is in the ui-file - - reload(); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect(textareaUi->gbWordWrap, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(textareaUi->cmbDynamicWordWrapIndicator, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect(textareaUi->sbDynamicWordWrapDepth, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - connect(textareaUi->chkShowTabs, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(textareaUi->chkShowSpaces, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(textareaUi->chkShowIndentationLines, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(textareaUi->chkShowWholeBracketExpression, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(textareaUi->chkDeveloperMode, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - - connect(bordersUi->chkIconBorder, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(bordersUi->chkScrollbarMarks, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(bordersUi->chkLineNumbers, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(bordersUi->chkShowFoldingMarkers, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(bordersUi->rbSortBookmarksByPosition, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect(bordersUi->rbSortBookmarksByCreation, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); -} - -KateViewDefaultsConfig::~KateViewDefaultsConfig() -{ - delete bordersUi; - delete textareaUi; -} - -void KateViewDefaultsConfig::apply () -{ - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateViewConfig::global()->configStart (); - KateRendererConfig::global()->configStart (); - - KateViewConfig::global()->setDynWordWrap (textareaUi->gbWordWrap->isChecked()); - KateViewConfig::global()->setDynWordWrapIndicators (textareaUi->cmbDynamicWordWrapIndicator->currentIndex ()); - KateViewConfig::global()->setDynWordWrapAlignIndent(textareaUi->sbDynamicWordWrapDepth->value()); - KateDocumentConfig::global()->setShowTabs (textareaUi->chkShowTabs->isChecked()); - KateDocumentConfig::global()->setShowSpaces (textareaUi->chkShowSpaces->isChecked()); - KateViewConfig::global()->setLineNumbers (bordersUi->chkLineNumbers->isChecked()); - KateViewConfig::global()->setIconBar (bordersUi->chkIconBorder->isChecked()); - KateViewConfig::global()->setScrollBarMarks (bordersUi->chkScrollbarMarks->isChecked()); - KateViewConfig::global()->setFoldingBar (bordersUi->chkShowFoldingMarkers->isChecked()); - - KateViewConfig::global()->setBookmarkSort (bordersUi->rbSortBookmarksByPosition->isChecked()?0:1); - KateRendererConfig::global()->setShowIndentationLines(textareaUi->chkShowIndentationLines->isChecked()); - KateRendererConfig::global()->setShowWholeBracketExpression(textareaUi->chkShowWholeBracketExpression->isChecked()); - - // warn user that he needs restart the application - if (!textareaUi->chkDeveloperMode->isChecked() != KateDocumentConfig::global()->allowSimpleMode()) - { - // inform... - KMessageBox::information( - this, - i18n("Changing the power user mode affects only newly opened / created documents. In KWrite a restart is recommended."), - i18n("Power user mode changed")); - - KateDocumentConfig::global()->setAllowSimpleMode (!textareaUi->chkDeveloperMode->isChecked()); - } - - KateRendererConfig::global()->configEnd (); - KateViewConfig::global()->configEnd (); -} - -void KateViewDefaultsConfig::reload () -{ - textareaUi->gbWordWrap->setChecked(KateViewConfig::global()->dynWordWrap()); - textareaUi->cmbDynamicWordWrapIndicator->setCurrentIndex( KateViewConfig::global()->dynWordWrapIndicators() ); - textareaUi->sbDynamicWordWrapDepth->setValue(KateViewConfig::global()->dynWordWrapAlignIndent()); - textareaUi->chkShowTabs->setChecked(KateDocumentConfig::global()->showTabs()); - textareaUi->chkShowSpaces->setChecked(KateDocumentConfig::global()->showSpaces()); - bordersUi->chkLineNumbers->setChecked(KateViewConfig::global()->lineNumbers()); - bordersUi->chkIconBorder->setChecked(KateViewConfig::global()->iconBar()); - bordersUi->chkScrollbarMarks->setChecked(KateViewConfig::global()->scrollBarMarks()); - bordersUi->chkShowFoldingMarkers->setChecked(KateViewConfig::global()->foldingBar()); - bordersUi->rbSortBookmarksByPosition->setChecked(KateViewConfig::global()->bookmarkSort()==0); - bordersUi->rbSortBookmarksByCreation->setChecked(KateViewConfig::global()->bookmarkSort()==1); - textareaUi->chkShowIndentationLines->setChecked(KateRendererConfig::global()->showIndentationLines()); - textareaUi->chkShowWholeBracketExpression->setChecked(KateRendererConfig::global()->showWholeBracketExpression()); - textareaUi->chkDeveloperMode->setChecked(!KateDocumentConfig::global()->allowSimpleMode()); -} - -void KateViewDefaultsConfig::reset () {;} - -void KateViewDefaultsConfig::defaults (){;} -//END KateViewDefaultsConfig - -//BEGIN KateSaveConfigTab -KateSaveConfigTab::KateSaveConfigTab( QWidget *parent ) - : KateConfigPage( parent ) - , modeConfigPage( new ModeConfigPage( this ) ) -{ - // FIXME: Is really needed to move all this code below to another class, - // since it is another tab itself on the config dialog. This means we should - // initialize, add and work with as we do with modeConfigPage (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - layout->setMargin(0); - KTabWidget *tabWidget = new KTabWidget(this); - - QWidget *tmpWidget = new QWidget(tabWidget); - QVBoxLayout *internalLayout = new QVBoxLayout; - QWidget *newWidget = new QWidget(tabWidget); - ui = new Ui::OpenSaveConfigWidget(); - ui->setupUi( newWidget ); - - QWidget *tmpWidget2 = new QWidget(tabWidget); - QVBoxLayout *internalLayout2 = new QVBoxLayout; - QWidget *newWidget2 = new QWidget(tabWidget); - uiadv = new Ui::OpenSaveConfigAdvWidget(); - uiadv->setupUi( newWidget2 ); - - // What's this help is added in ui/opensaveconfigwidget.ui - reload(); - - // - // after initial reload, connect the stuff for the changed () signal - // - - connect( ui->cmbEncoding, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect( ui->cmbEncodingDetection, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect( ui->cmbEncodingFallback, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect( ui->cmbEOL, SIGNAL(activated(int)), this, SLOT(slotChanged())); - connect( ui->chkDetectEOL, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) ); - connect( ui->chkEnableBOM, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) ); - connect( ui->chkRemoveTrailingSpaces, SIGNAL(toggled(bool)), this, SLOT(slotChanged())); - connect( uiadv->chkBackupLocalFiles, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) ); - connect( uiadv->chkBackupRemoteFiles, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) ); - connect( uiadv->sbConfigFileSearchDepth, SIGNAL(valueChanged(int)), this, SLOT(slotChanged())); - connect( uiadv->edtBackupPrefix, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( uiadv->edtBackupSuffix, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( uiadv->chkNoSync, SIGNAL( toggled(bool) ), this, SLOT( slotChanged() ) ); - - internalLayout->addWidget(newWidget); - tmpWidget->setLayout(internalLayout); - internalLayout2->addWidget(newWidget2); - tmpWidget2->setLayout(internalLayout2); - - // add all tabs - tabWidget->insertTab(0, tmpWidget, i18n("General")); - tabWidget->insertTab(1, tmpWidget2, i18n("Advanced")); - tabWidget->insertTab(2, modeConfigPage, i18n("Modes && Filetypes")); - - connect(modeConfigPage, SIGNAL(changed()), this, SLOT(slotChanged())); - - layout->addWidget(tabWidget); - setLayout(layout); -} - -KateSaveConfigTab::~KateSaveConfigTab() -{ - delete ui; -} - -void KateSaveConfigTab::apply() -{ - modeConfigPage->apply(); - - // nothing changed, no need to apply stuff - if (!hasChanged()) - return; - m_changed = false; - - KateGlobalConfig::global()->configStart (); - KateDocumentConfig::global()->configStart (); - - if ( uiadv->edtBackupSuffix->text().isEmpty() && uiadv->edtBackupPrefix->text().isEmpty() ) { - KMessageBox::information( - this, - i18n("You did not provide a backup suffix or prefix. Using default suffix: '~'"), - i18n("No Backup Suffix or Prefix") - ); - uiadv->edtBackupSuffix->setText( "~" ); - } - - uint f( 0 ); - if ( uiadv->chkBackupLocalFiles->isChecked() ) - f |= KateDocumentConfig::LocalFiles; - if ( uiadv->chkBackupRemoteFiles->isChecked() ) - f |= KateDocumentConfig::RemoteFiles; - - KateDocumentConfig::global()->setBackupFlags(f); - KateDocumentConfig::global()->setBackupPrefix(uiadv->edtBackupPrefix->text()); - KateDocumentConfig::global()->setBackupSuffix(uiadv->edtBackupSuffix->text()); - - KateDocumentConfig::global()->setSwapFileNoSync(uiadv->chkNoSync->isChecked()); - - KateDocumentConfig::global()->setSearchDirConfigDepth(uiadv->sbConfigFileSearchDepth->value()); - - KateDocumentConfig::global()->setRemoveSpaces(ui->chkRemoveTrailingSpaces->isChecked()); - - // set both standard and fallback encoding - KateDocumentConfig::global()->setEncoding((ui->cmbEncoding->currentIndex() == 0) ? "" : KGlobal::charsets()->encodingForName(ui->cmbEncoding->currentText())); - - KateGlobalConfig::global()->setProberType((KEncodingProber::ProberType)ui->cmbEncodingDetection->currentIndex()); - KateGlobalConfig::global()->setFallbackEncoding(KGlobal::charsets()->encodingForName(ui->cmbEncodingFallback->currentText())); - - KateDocumentConfig::global()->setEol(ui->cmbEOL->currentIndex()); - KateDocumentConfig::global()->setAllowEolDetection(ui->chkDetectEOL->isChecked()); - KateDocumentConfig::global()->setBom(ui->chkEnableBOM->isChecked()); - - KateDocumentConfig::global()->configEnd (); - KateGlobalConfig::global()->configEnd (); -} - -void KateSaveConfigTab::reload() -{ - modeConfigPage->reload(); - - // encodings - ui->cmbEncoding->clear (); - ui->cmbEncoding->addItem (i18n("KDE Default")); - ui->cmbEncoding->setCurrentIndex(0); - ui->cmbEncodingFallback->clear (); - QStringList encodings (KGlobal::charsets()->descriptiveEncodingNames()); - int insert = 1; - for (int i=0; i < encodings.count(); i++) - { - bool found = false; - QTextCodec *codecForEnc = KGlobal::charsets()->codecForName(KGlobal::charsets()->encodingForName(encodings[i]), found); - - if (found) - { - ui->cmbEncoding->addItem (encodings[i]); - ui->cmbEncodingFallback->addItem (encodings[i]); - - if ( codecForEnc->name() == KateDocumentConfig::global()->encoding() ) - { - ui->cmbEncoding->setCurrentIndex(insert); - } - - if ( codecForEnc == KateGlobalConfig::global()->fallbackCodec() ) - { - // adjust index for fallback config, has no default! - ui->cmbEncodingFallback->setCurrentIndex(insert-1); - } - - insert++; - } - } - - // encoding detection - ui->cmbEncodingDetection->clear (); - bool found = false; - for (int i = 0; !KEncodingProber::nameForProberType ((KEncodingProber::ProberType) i).isEmpty(); ++i) { - ui->cmbEncodingDetection->addItem (KEncodingProber::nameForProberType ((KEncodingProber::ProberType) i)); - if (i == KateGlobalConfig::global()->proberType()) { - ui->cmbEncodingDetection->setCurrentIndex(ui->cmbEncodingDetection->count()-1); - found = true; - } - } - if (!found) - ui->cmbEncodingDetection->setCurrentIndex(KEncodingProber::Universal); - - - // eol - ui->cmbEOL->setCurrentIndex(KateDocumentConfig::global()->eol()); - ui->chkDetectEOL->setChecked(KateDocumentConfig::global()->allowEolDetection()); - ui->chkEnableBOM->setChecked(KateDocumentConfig::global()->bom()); - - ui->chkRemoveTrailingSpaces->setChecked(KateDocumentConfig::global()->removeSpaces()); - uiadv->sbConfigFileSearchDepth->setValue(KateDocumentConfig::global()->searchDirConfigDepth()); - - // other stuff - uint f ( KateDocumentConfig::global()->backupFlags() ); - uiadv->chkBackupLocalFiles->setChecked( f & KateDocumentConfig::LocalFiles ); - uiadv->chkBackupRemoteFiles->setChecked( f & KateDocumentConfig::RemoteFiles ); - uiadv->edtBackupPrefix->setText( KateDocumentConfig::global()->backupPrefix() ); - uiadv->edtBackupSuffix->setText( KateDocumentConfig::global()->backupSuffix() ); - uiadv->chkNoSync->setChecked( KateDocumentConfig::global()->swapFileNoSync() ); -} - -void KateSaveConfigTab::reset() -{ - modeConfigPage->reset(); -} - -void KateSaveConfigTab::defaults() -{ - modeConfigPage->defaults(); - - uiadv->chkBackupLocalFiles->setChecked( true ); - uiadv->chkBackupRemoteFiles->setChecked( false ); - uiadv->edtBackupPrefix->setText( "" ); - uiadv->edtBackupSuffix->setText( "~" ); - uiadv->chkNoSync->setChecked( false ); -} - -//END KateSaveConfigTab - -//BEGIN KatePartPluginConfigPage -KatePartPluginConfigPage::KatePartPluginConfigPage (QWidget *parent) - : KateConfigPage (parent, "") - , scriptConfigPage (new KateScriptConfigPage(this)) -{ - // FIXME: Is really needed to move all this code below to another class, - // since it is another tab itself on the config dialog. This means we should - // initialize, add and work with as we do with scriptConfigPage (ereslibre) - QVBoxLayout *generalLayout = new QVBoxLayout; - generalLayout->setMargin(0); - KTabWidget *tabWidget = new KTabWidget(this); - - QWidget *tmpWidget = new QWidget(tabWidget); - QVBoxLayout *internalLayout = new QVBoxLayout; - QWidget *newWidget = new QWidget(tabWidget); - QVBoxLayout *layout = new QVBoxLayout; - newWidget->setLayout(layout); - layout->setMargin(0); - - plugins.clear(); - - int i = 0; - foreach (const KatePartPluginInfo &info, KatePartPluginManager::self()->pluginList()) - { - KPluginInfo it(info.service()); - it.setPluginEnabled(info.load); - plugins.append(it); - i++; - } - - selector = new KPluginSelector(0); - - connect(selector, SIGNAL(changed(bool)), this, SLOT(slotChanged())); - connect(selector, SIGNAL(configCommitted(QByteArray)), this, SLOT(slotChanged())); - - selector->addPlugins(plugins, KPluginSelector::IgnoreConfigFile, i18n("Editor Plugins"), "Editor"); - layout->addWidget(selector); - - internalLayout->addWidget(newWidget); - tmpWidget->setLayout(internalLayout); - - // add all tabs - tabWidget->insertTab(0, tmpWidget, i18n("Plugins")); - tabWidget->insertTab(1, scriptConfigPage, i18n("Scripts")); - - generalLayout->addWidget(tabWidget); - setLayout(generalLayout); -} - -KatePartPluginConfigPage::~KatePartPluginConfigPage () -{ -} - -void KatePartPluginConfigPage::apply () -{ - scriptConfigPage->apply(); - - selector->updatePluginsState(); - - KatePartPluginList &katePluginList = KatePartPluginManager::self()->pluginList(); - for (int i=0; i < plugins.count(); i++) { - if (plugins[i].isPluginEnabled()) { - if (!katePluginList[i].load) { - KatePartPluginManager::self()->loadPlugin(katePluginList[i]); - KatePartPluginManager::self()->enablePlugin(katePluginList[i]); - } - } else { - if (katePluginList[i].load) { - KatePartPluginManager::self()->disablePlugin(katePluginList[i]); - KatePartPluginManager::self()->unloadPlugin(katePluginList[i]); - } - } - } -} - -void KatePartPluginConfigPage::reload () -{ - scriptConfigPage->reload(); - - selector->load(); -} - -void KatePartPluginConfigPage::reset () -{ - scriptConfigPage->reset(); - - selector->load(); -} - -void KatePartPluginConfigPage::defaults () -{ - scriptConfigPage->defaults(); - - selector->defaults(); -} -//END KatePartPluginConfigPage - -class KateScriptNewStuff {}; - -/* -class KateScriptNewStuff: public KNewStuff { - public: - KateScriptNewStuff(QWidget *parent):KNewStuff("kate/scripts",parent) {} - virtual ~KateScriptNewStuff() {} - virtual bool install( const QString &fileName ) {return false;} - virtual bool createUploadFile( const QString &fileName ) {return false;} -}; -*/ -//BEGIN KateScriptConfigPage -KateScriptConfigPage::KateScriptConfigPage(QWidget *parent): KateConfigPage(parent,""), m_newStuff(new KateScriptNewStuff()) -{ - // TODO: Please look at KateSelectConfigTab or ModeConfigPage to add - // a layout like we do there, to be consistent and have on all config - // pages the same distance to the KTabWidget edge (ereslibre) - - //m_newStuff->download(); -} - -KateScriptConfigPage::~KateScriptConfigPage() -{ - delete m_newStuff; - m_newStuff=0; -} - -void KateScriptConfigPage::apply () { -} -void KateScriptConfigPage::reload () { -} - -//END KateScriptConfigPage - -//BEGIN KateHlDownloadDialog -KateHlDownloadDialog::KateHlDownloadDialog(QWidget *parent, const char *name, bool modal) - : KDialog( parent ) -{ - setCaption( i18n("Highlight Download") ); - setButtons( User1 | Close ); - setButtonGuiItem( User1, KGuiItem(i18n("&Install")) ); - setDefaultButton( User1 ); - setObjectName( name ); - setModal( modal ); - - KVBox* vbox = new KVBox(this); - setMainWidget(vbox); - vbox->setSpacing(-1); - new QLabel(i18n("Select the syntax highlighting files you want to update:"), vbox); - list = new QTreeWidget(vbox); - list->setColumnCount(4); - list->setHeaderLabels(QStringList() << "" << i18n("Name") << i18n("Installed") << i18n("Latest")); - list->setSelectionMode(QAbstractItemView::MultiSelection); - list->setAllColumnsShowFocus(true); - list->setRootIsDecorated(false); - list->setColumnWidth(0, 22); - - new QLabel(i18n("Note: New versions are selected automatically."), vbox); - setButtonIcon(User1, KIcon("dialog-ok")); - - transferJob = KIO::get( - KUrl(QString(HLDOWNLOADPATH) - + QString("update-") - + KateGlobal::katePartVersion() - + QString(".xml")), KIO::Reload ); - connect(transferJob, SIGNAL(data(KIO::Job *, const QByteArray &)), - this, SLOT(listDataReceived(KIO::Job *, const QByteArray &))); -// void data( KIO::Job *, const QByteArray &data); - resize(450, 400); - connect(this,SIGNAL(user1Clicked()),this,SLOT(slotUser1())); -} - -KateHlDownloadDialog::~KateHlDownloadDialog(){} - -void KateHlDownloadDialog::listDataReceived(KIO::Job *, const QByteArray &data) -{ - if (!transferJob || transferJob->isErrorPage()) - { - enableButton( User1, false ); - if (data.size()==0) - KMessageBox::error(this,i18n("The list of highlightings could not be found on / retrieved from the server")); - return; - } - - listData+=QString(data); - kDebug(13000)<0) - { - QString installedVersion; - KateHlManager *hlm=KateHlManager::self(); - QDomDocument doc; - doc.setContent(listData); - QDomElement DocElem=doc.documentElement(); - QDomNode n=DocElem.firstChild(); - KateHighlighting *hl = 0; - - if (n.isNull()) kDebug(13000)<<"There is no usable childnode"; - while (!n.isNull()) - { - installedVersion=" --"; - - QDomElement e=n.toElement(); - if (!e.isNull()) - kDebug(13000)<highlights();i++) - { - hl=hlm->getHl(i); - if (hl && hl->name()==Name) - { - installedVersion=" "+hl->version(); - break; - } - else hl = 0; - } - - // autoselect entry if new or updated. - QTreeWidgetItem* entry = new QTreeWidgetItem(list); - entry->setText(0, ""); - entry->setText(1, e.attribute("name")); - entry->setText(2, installedVersion); - entry->setText(3, e.attribute("version")); - entry->setText(4, e.attribute("url")); - - if (!hl || hl->version() < e.attribute("version")) - { - entry->treeWidget()->setItemSelected(entry, true); - entry->setIcon(0, SmallIcon(("get-hot-new-stuff"))); - } - } - list->resizeColumnToContents(1); - } - } -} - -void KateHlDownloadDialog::slotUser1() -{ - QString destdir=KGlobal::dirs()->saveLocation("data","katepart/syntax/"); - foreach (QTreeWidgetItem *it, list->selectedItems()) - { - KUrl src(it->text(4)); - QString filename=src.fileName(KUrl::ObeyTrailingSlash); - QString dest = destdir+filename; - - KIO::NetAccess::download(src,dest, this); - } - - // update Config !! - // this rewrites the cache.... - KateSyntaxDocument doc (KateHlManager::self()->getKConfig(), true); -} -//END KateHlDownloadDialog - -//BEGIN KateGotoBar -KateGotoBar::KateGotoBar(KTextEditor::View *view, QWidget *parent) - : KateViewBarWidget( true, parent ) - , m_view( view ) -{ - Q_ASSERT( m_view != 0 ); // this bar widget is pointless w/o a view - - QHBoxLayout *topLayout = new QHBoxLayout( centralWidget() ); - topLayout->setMargin(0); - gotoRange = new KIntSpinBox(centralWidget()); - - QLabel *label = new QLabel(i18n("&Go to line:"), centralWidget() ); - label->setBuddy(gotoRange); - - QToolButton *btnOK = new QToolButton(centralWidget()); - btnOK->setAutoRaise(true); - btnOK->setIcon(QIcon(SmallIcon("go-jump"))); - btnOK->setText(i18n("Go")); - btnOK->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - connect(btnOK, SIGNAL(clicked()), this, SLOT(gotoLine())); - - topLayout->addWidget(label); - topLayout->addWidget(gotoRange, 1); - topLayout->setStretchFactor( gotoRange, 0 ); - topLayout->addWidget(btnOK); - topLayout->addStretch(); -} - -void KateGotoBar::updateData() -{ - gotoRange->setMaximum(m_view->document()->lines()); - if (!isVisible()) - { - gotoRange->setValue(m_view->cursorPosition().line() + 1); - gotoRange->adjustSize(); // ### does not respect the range :-( - } - gotoRange->setFocus(Qt::OtherFocusReason); - gotoRange->selectAll(); -} - -void KateGotoBar::keyPressEvent(QKeyEvent* event) -{ - int key = event->key(); - if (key == Qt::Key_Return || key == Qt::Key_Enter) { - gotoLine(); - return; - } - KateViewBarWidget::keyPressEvent(event); -} - -void KateGotoBar::gotoLine() -{ - m_view->setCursorPosition( KTextEditor::Cursor(gotoRange->value() - 1, 0) ); - m_view->setFocus(); - emit hideMe(); -} -//END KateGotoBar - -//BEGIN KateDictionaryBar -KateDictionaryBar::KateDictionaryBar(KateView* view, QWidget *parent) - : KateViewBarWidget( true, parent ) - , m_view( view ) -{ - Q_ASSERT(m_view != 0); // this bar widget is pointless w/o a view - - QHBoxLayout *topLayout = new QHBoxLayout(centralWidget()); - topLayout->setMargin(0); - //topLayout->setSpacing(spacingHint()); - m_dictionaryComboBox = new Sonnet::DictionaryComboBox(centralWidget()); - connect(m_dictionaryComboBox, SIGNAL(dictionaryChanged(const QString&)), - this, SLOT(dictionaryChanged(const QString&))); - connect(view->doc(), SIGNAL(defaultDictionaryChanged(KateDocument*)), - this, SLOT(updateData())); - QLabel *label = new QLabel(i18n("Dictionary:"), centralWidget()); - label->setBuddy(m_dictionaryComboBox); - - topLayout->addWidget(label); - topLayout->addWidget(m_dictionaryComboBox, 1); - topLayout->setStretchFactor(m_dictionaryComboBox, 0); - topLayout->addStretch(); -} - -KateDictionaryBar::~KateDictionaryBar() -{ -} - -void KateDictionaryBar::updateData() -{ - KateDocument *document = m_view->doc(); - QString dictionary = document->defaultDictionary(); - if(dictionary.isEmpty()) { - dictionary = Sonnet::Speller().defaultLanguage(); - } - m_dictionaryComboBox->setCurrentByDictionary(dictionary); -} - -void KateDictionaryBar::dictionaryChanged(const QString& dictionary) -{ - KTextEditor::Range selection = m_view->selectionRange(); - if(selection.isValid() && !selection.isEmpty()) { - m_view->doc()->setDictionary(dictionary, selection); - } - else { - m_view->doc()->setDefaultDictionary(dictionary); - } -} - -//END KateGotoBar - - -//BEGIN KateModOnHdPrompt -KateModOnHdPrompt::KateModOnHdPrompt( KateDocument *doc, - KTextEditor::ModificationInterface::ModifiedOnDiskReason modtype, - const QString &reason, - QWidget *parent ) - : KDialog( parent ), - m_doc( doc ), - m_modtype ( modtype ), - m_proc( 0 ), - m_diffFile( 0 ) -{ - setButtons( Ok | Apply | Cancel | User1 ); - - QString title, btnOK, whatisok; - if ( modtype == KTextEditor::ModificationInterface::OnDiskDeleted ) - { - title = i18n("File Was Deleted on Disk"); - btnOK = i18n("&Save File As..."); - whatisok = i18n("Lets you select a location and save the file again."); - } else { - title = i18n("File Changed on Disk"); - btnOK = i18n("&Reload File"); - whatisok = i18n("Reload the file from disk. If you have unsaved changes, " - "they will be lost."); - } - - setButtonText( Ok, btnOK ); - setButtonText( Apply, i18n("&Ignore") ); - - setButtonWhatsThis( Ok, whatisok ); - setButtonWhatsThis( Apply, i18n("Ignore the changes. You will not be prompted again.") ); - setButtonWhatsThis( Cancel, i18n("Do nothing. Next time you focus the file, " - "or try to save it or close it, you will be prompted again.") ); - - setCaption( title ); - - QWidget *w = new QWidget(this); - ui = new Ui::ModOnHdWidget(); - ui->setupUi( w ); - setMainWidget( w ); - - ui->lblIcon->setPixmap( DesktopIcon("dialog-warning" ) ); - ui->lblText->setText( reason + "\n\n" + i18n("What do you want to do?") ); - - // If the file isn't deleted, present a diff button, and a overwrite action. - if ( modtype != KTextEditor::ModificationInterface::OnDiskDeleted ) - { - setButtonText( User1, i18n("Overwrite") ); - setButtonWhatsThis( User1, i18n("Overwrite the disk file with the editor content.") ); - connect( ui->btnDiff, SIGNAL(clicked()), this, SLOT(slotDiff()) ); - } - else - { - ui->chkIgnoreWhiteSpaces->setVisible( false ); - ui->btnDiff->setVisible( false ); - showButton( User1, false ); - } -} - -KateModOnHdPrompt::~KateModOnHdPrompt() -{ - delete m_proc; - m_proc = 0; - if (m_diffFile) { - m_diffFile->setAutoRemove(true); - delete m_diffFile; - m_diffFile = 0; - } - delete ui; -} - -void KateModOnHdPrompt::slotDiff() -{ - if (m_diffFile) - return; - - m_diffFile = new KTemporaryFile(); - m_diffFile->open(); - - // Start a KProcess that creates a diff - m_proc = new KProcess( this ); - m_proc->setOutputChannelMode( KProcess::MergedChannels ); - *m_proc << "diff" << QString(ui->chkIgnoreWhiteSpaces->isChecked() ? "-ub" : "-u") - << "-" << m_doc->url().toLocalFile(); - connect( m_proc, SIGNAL(readyRead()), this, SLOT(slotDataAvailable()) ); - connect( m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotPDone()) ); - - setCursor( Qt::WaitCursor ); - // disable the button and checkbox, to hinder the user to run it twice. - ui->chkIgnoreWhiteSpaces->setEnabled( false ); - ui->btnDiff->setEnabled( false ); - - m_proc->start(); - - QTextStream ts(m_proc); - int lastln = m_doc->lines(); - for ( int l = 0; l < lastln; ++l ) - ts << m_doc->line( l ) << '\n'; - ts.flush(); - m_proc->closeWriteChannel(); -} - -void KateModOnHdPrompt::slotDataAvailable() -{ - m_diffFile->write(m_proc->readAll()); -} - -void KateModOnHdPrompt::slotPDone() -{ - setCursor( Qt::ArrowCursor ); - ui->chkIgnoreWhiteSpaces->setEnabled( true ); - ui->btnDiff->setEnabled( true ); - - const QProcess::ExitStatus es = m_proc->exitStatus(); - delete m_proc; - m_proc = 0; - - if ( es != QProcess::NormalExit ) - { - KMessageBox::sorry( this, - i18n("The diff command failed. Please make sure that " - "diff(1) is installed and in your PATH."), - i18n("Error Creating Diff") ); - delete m_diffFile; - m_diffFile = 0; - return; - } - - if ( m_diffFile->size() == 0 ) - { - KMessageBox::information( this, - i18n("Besides white space changes, the files are identical."), - i18n("Diff Output") ); - delete m_diffFile; - m_diffFile = 0; - return; - } - - m_diffFile->setAutoRemove(false); - KUrl url = KUrl::fromPath(m_diffFile->fileName()); - delete m_diffFile; - m_diffFile = 0; - - // KRun::runUrl should delete the file, once the client exits - KRun::runUrl( url, "text/x-patch", this, true ); -} - -void KateModOnHdPrompt::slotButtonClicked(int button) -{ - switch(button) - { - case Default: - case Ok: - done( (m_modtype == KTextEditor::ModificationInterface::OnDiskDeleted) ? - Save : Reload ); - break; - case Apply: - { - if ( KMessageBox::warningContinueCancel( - this, - i18n("Ignoring means that you will not be warned again (unless " - "the disk file changes once more): if you save the document, you " - "will overwrite the file on disk; if you do not save then the disk " - "file (if present) is what you have."), - i18n("You Are on Your Own"), - KStandardGuiItem::cont(), - KStandardGuiItem::cancel(), - "kate_ignore_modonhd" ) != KMessageBox::Continue ) - return; - done( Ignore ); - break; - } - case User1: - done( Overwrite ); - break; - default: - KDialog::slotButtonClicked(button); - } -} - -//END KateModOnHdPrompt - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/dialogs/katedialogs.h b/part/dialogs/katedialogs.h deleted file mode 100644 index 5f6b568..0000000 --- a/part/dialogs/katedialogs.h +++ /dev/null @@ -1,450 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002, 2003 Anders Lund - Copyright (C) 2003 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 2006 Dominik Haumann - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2009 Michel Ludwig - - Based on work of: - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_DIALOGS_H__ -#define __KATE_DIALOGS_H__ - -#include "katehighlight.h" -#include "kateviewhelpers.h" - -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include - -struct syntaxContextData; - -class KateScriptConfigPage; -class ModeConfigPage; -class KateDocument; -class KateView; -class KatePartPluginInfo; - -namespace KIO -{ - class Job; - class TransferJob; -} - -class KComboBox; -class KShortcutsEditor; -class KTemporaryFile; -class KIntNumInput; -class KIntSpinBox; -class KPluginSelector; -class KPluginInfo; -class KProcess; - -class QCheckBox; -class QLabel; -class QCheckBox; -class QKeyEvent; - -namespace Ui -{ - class ModOnHdWidget; - class TextareaAppearanceConfigWidget; - class BordersAppearanceConfigWidget; - class CursorConfigWidget; - class EditConfigWidget; - class IndentationConfigWidget; - class OpenSaveConfigWidget; - class OpenSaveConfigAdvWidget; - class CompletionConfigTab; - class ViInputModeConfigWidget; - class SpellCheckConfigWidget; -} - -class KateConfigPage : public KTextEditor::ConfigPage -{ - Q_OBJECT - - public: - explicit KateConfigPage ( QWidget *parent=0, const char *name=0 ); - virtual ~KateConfigPage (); - - public: - bool hasChanged () { return m_changed; } - - protected Q_SLOTS: - void slotChanged(); - - private Q_SLOTS: - void somethingHasChanged (); - - protected: - bool m_changed; -}; - -class KateGotoBar : public KateViewBarWidget -{ - Q_OBJECT - - public: - explicit KateGotoBar(KTextEditor::View *view, QWidget *parent = 0); - - void updateData(); - - protected Q_SLOTS: - void gotoLine(); - - protected: - virtual void keyPressEvent(QKeyEvent* event); - - private: - KTextEditor::View *const m_view; - KIntSpinBox *gotoRange; -}; - -class KateDictionaryBar : public KateViewBarWidget -{ - Q_OBJECT - - public: - explicit KateDictionaryBar(KateView *view, QWidget *parent = NULL); - virtual ~KateDictionaryBar(); - - public Q_SLOTS: - void updateData(); - - protected Q_SLOTS: - void dictionaryChanged(const QString& dictionary); - - private: - KateView* m_view; - Sonnet::DictionaryComboBox *m_dictionaryComboBox; -}; - -class KateIndentConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateIndentConfigTab(QWidget *parent); - ~KateIndentConfigTab(); - - protected: - Ui::IndentationConfigWidget *ui; - - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} - - private Q_SLOTS: - void slotChanged (); - void showWhatsThis(const QString& text); -}; - -class KateCompletionConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateCompletionConfigTab(QWidget *parent); - ~KateCompletionConfigTab(); - - protected: - Ui::CompletionConfigTab *ui; - - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} - - private Q_SLOTS: - void showWhatsThis(const QString& text); -}; - -class KateEditGeneralConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateEditGeneralConfigTab(QWidget *parent); - ~KateEditGeneralConfigTab(); - - private: - Ui::EditConfigWidget *ui; - - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} -}; - -class KateSelectConfigTab : public KateConfigPage -{ - Q_OBJECT - -public: - KateSelectConfigTab(QWidget *parent); - ~KateSelectConfigTab(); - -private: - Ui::CursorConfigWidget *ui; - -public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} -}; - -class KateViInputModeConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateViInputModeConfigTab(QWidget *parent); - ~KateViInputModeConfigTab(); - - protected: - Ui::ViInputModeConfigWidget *ui; - - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} - - private Q_SLOTS: - void showWhatsThis(const QString& text); - void addNewNormalModeMappingRow(); - void removeSelectedNormalMappingRow(); -}; - -class KateSpellCheckConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateSpellCheckConfigTab(QWidget *parent); - ~KateSpellCheckConfigTab(); - - protected: - Ui::SpellCheckConfigWidget *ui; - Sonnet::ConfigWidget *m_sonnetConfigWidget; - - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} - - private Q_SLOTS: - void showWhatsThis(const QString& text); -}; - -class KateEditConfigTab : public KateConfigPage -{ - Q_OBJECT - -public: - KateEditConfigTab(QWidget *parent); - ~KateEditConfigTab(); - -public Q_SLOTS: - void apply (); - void reload (); - void reset (); - void defaults (); - -private: - KateEditGeneralConfigTab *editConfigTab; - KateSelectConfigTab *selectConfigTab; - KateIndentConfigTab *indentConfigTab; - KateCompletionConfigTab *completionConfigTab; - KateViInputModeConfigTab *viInputModeConfigTab; - KateSpellCheckConfigTab *spellCheckConfigTab; -}; - -class KateViewDefaultsConfig : public KateConfigPage -{ - Q_OBJECT - -public: - KateViewDefaultsConfig( QWidget *parent ); - ~KateViewDefaultsConfig(); - -public Q_SLOTS: - void apply (); - void reload (); - void reset (); - void defaults (); - -private: - Ui::TextareaAppearanceConfigWidget *const textareaUi; - Ui::BordersAppearanceConfigWidget *const bordersUi; -}; - -class KateSaveConfigTab : public KateConfigPage -{ - Q_OBJECT - - public: - KateSaveConfigTab( QWidget *parent ); - ~KateSaveConfigTab(); - - public Q_SLOTS: - void apply(); - void reload(); - void reset(); - void defaults(); - - protected: - //why? - //KComboBox *m_encoding, *m_encodingDetection, *m_eol; - QCheckBox *cbLocalFiles, *cbRemoteFiles; - QCheckBox *replaceTabs, *removeSpaces, *allowEolDetection; - KIntNumInput *dirSearchDepth; - class KIntSpinBox *blockCount; - class QLabel *blockCountLabel; - - private: - Ui::OpenSaveConfigWidget* ui; - Ui::OpenSaveConfigAdvWidget* uiadv; - ModeConfigPage *modeConfigPage; -}; - -class KatePartPluginConfigPage : public KateConfigPage -{ - Q_OBJECT - - public: - KatePartPluginConfigPage (QWidget *parent); - ~KatePartPluginConfigPage (); - - public Q_SLOTS: - void apply (); - void reload (); - void reset (); - void defaults (); - - private: - KPluginSelector *selector; - QList plugins; - KateScriptConfigPage *scriptConfigPage; -}; - -class KateScriptNewStuff; - -class KateScriptConfigPage : public KateConfigPage -{ - Q_OBJECT - - public: - KateScriptConfigPage(QWidget *parent); - virtual ~KateScriptConfigPage(); - public Q_SLOTS: - void apply (); - void reload (); - void reset () {} - void defaults () {} - private: - KateScriptNewStuff *m_newStuff; -}; - -class KateHlDownloadDialog: public KDialog -{ - Q_OBJECT - - public: - KateHlDownloadDialog(QWidget *parent, const char *name, bool modal); - ~KateHlDownloadDialog(); - - private: - class QTreeWidget *list; - class QString listData; - KIO::TransferJob *transferJob; - - private Q_SLOTS: - void listDataReceived(KIO::Job *, const QByteArray &data); - - public Q_SLOTS: - void slotUser1(); -}; - -/** - * This dialog will prompt the user for what do with a file that is - * modified on disk. - * If the file wasn't deleted, it has a 'diff' button, which will create - * a diff file (uing diff(1)) and launch that using KRun. - */ -class KateModOnHdPrompt : public KDialog -{ - Q_OBJECT - public: - enum Status { - Reload = 1, // 0 is QDialog::Rejected - Save, - Overwrite, - Ignore - }; - KateModOnHdPrompt( KateDocument *doc, - KTextEditor::ModificationInterface::ModifiedOnDiskReason modtype, - const QString &reason, QWidget *parent ); - ~KateModOnHdPrompt(); - - public Q_SLOTS: - /** - * Show a diff between the document text and the disk file. - * This will not close the dialog, since we still need a - * decision from the user. - */ - void slotDiff(); - - protected Q_SLOTS: - virtual void slotButtonClicked(int button); - - private Q_SLOTS: - void slotDataAvailable(); ///< read data from the process - void slotPDone(); ///< Runs the diff file when done - - private: - Ui::ModOnHdWidget* ui; - KateDocument *m_doc; - KTextEditor::ModificationInterface::ModifiedOnDiskReason m_modtype; - KProcess *m_proc; - KTemporaryFile *m_diffFile; -}; - -#endif -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/dialogs/modonhdwidget.ui b/part/dialogs/modonhdwidget.ui deleted file mode 100644 index 04f2a96..0000000 --- a/part/dialogs/modonhdwidget.ui +++ /dev/null @@ -1,43 +0,0 @@ - - ModOnHdWidget - - - - 0 - - - - - - - - - 7 - 0 - 0 - 0 - - - - Ignore white space changes - - - - - - - Calculates the difference between the editor contents and the disk file using diff(1). - - - &View Difference - - - - - - - - - - - diff --git a/part/dialogs/opensaveconfigadvwidget.ui b/part/dialogs/opensaveconfigadvwidget.ui deleted file mode 100644 index 2894a3d..0000000 --- a/part/dialogs/opensaveconfigadvwidget.ui +++ /dev/null @@ -1,190 +0,0 @@ - - - OpenSaveConfigAdvWidget - - - - 0 - 0 - 500 - 315 - - - - - 0 - - - - - Folder Config File - - - - - - 0 - - - - - Search &depth for config file: - - - sbConfigFileSearchDepth - - - - - - - The editor will search the given number of folder levels upwards for a .kateconfig file and load the settings line from it. - - - Do not use config file - - - -1 - - - 64 - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - - - - <p>Backing up on save will cause Kate to copy the disk file to '&lt;prefix&gt;&lt;filename&gt;&lt;suffix&gt;' before saving changes.<p>The suffix defaults to <strong>~</strong> and prefix is empty by default. - - - Backup on Save - - - - QFormLayout::ExpandingFieldsGrow - - - - - If this option is enabled, backups for local files will be created when saving. - - - &Local files - - - - - - - If this option is enabled, backups for remote files will be created when saving. - - - &Remote files - - - - - - - &Prefix: - - - edtBackupPrefix - - - - - - - Enter the prefix to prepend to the backup file names. - - - - - - - &Suffix: - - - edtBackupSuffix - - - - - - - Enter the suffix to append to the backup file names. - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Disable swap files syncing. - - - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
- - KLineEdit - QLineEdit -
klineedit.h
-
-
- - -
diff --git a/part/dialogs/opensaveconfigwidget.ui b/part/dialogs/opensaveconfigwidget.ui deleted file mode 100644 index 50b0582..0000000 --- a/part/dialogs/opensaveconfigwidget.ui +++ /dev/null @@ -1,176 +0,0 @@ - - - OpenSaveConfigWidget - - - - 0 - 0 - 489 - 334 - - - - - 0 - - - - - File Format - - - - - - QFormLayout::ExpandingFieldsGrow - - - - - &Encoding: - - - cmbEncoding - - - - - - - This defines the standard encoding to use to open/save files, if not changed in the open/save dialog or by using a command line option. - - - - - - - &Encoding Detection: - - - cmbEncodingDetection - - - - - - - if neither the encoding chosen as standard above, nor the encoding specified in the open/save dialog, nor the encoding specified on command line match the content of the file, this detection will be run. - - - - - - - &Fallback Encoding - - - cmbEncodingFallback - - - - - - - This defines the fallback encoding to try for opening files if neither the encoding chosen as standard above, nor the encoding specified in the open/save dialog, nor the encoding specified on command line match the content of the file. Before this is used, an attempt will be made to determine the encoding to use by looking for a byte order marker at start of file: if one is found, the right unicode encoding will be chosen; otherwise encoding detection will run, if both fail fallback encoding will be tried. - - - - - - - E&nd of line: - - - cmbEOL - - - - - - - - UNIX - - - - - DOS/Windows - - - - - Macintosh - - - - - - - - - - If this option is enabled the editor will autodetect the end of line type. The first found end of line type will be used for the whole file. - - - A&utomatic end of line detection - - - - - - - The byte order mark is a special sequence at the beginning of unicode encoded documents. It helps editors to open text documents with the correct unicode encoding. The byte order mark is not visible in the displayed document. - - - Enable byte order marker - - - - - - - - - - Automatic Cleanups on Load/Save - - - - - - The editor will automatically eliminate extra spaces at the ends of lines of text while loading/saving the file. This change is only visible after a save if you reload the file. - - - Re&move trailing spaces - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KComboBox - QComboBox -
kcombobox.h
-
-
- - -
diff --git a/part/dialogs/schemaconfigcolortab.ui b/part/dialogs/schemaconfigcolortab.ui deleted file mode 100644 index bba8c02..0000000 --- a/part/dialogs/schemaconfigcolortab.ui +++ /dev/null @@ -1,203 +0,0 @@ - - - SchemaConfigColorTab - - - - 0 - 0 - 548 - 419 - - - - - - - Text Area Background - - - true - - - - - - Normal text: - - - - - - - <p>Sets the background color of the editing area.</p> - - - - - - - Selected text: - - - - - - - <p>Sets the background color of the selection.</p><p>To set the text color for selected text, use the "<b>Configure Highlighting</b>" dialog.</p> - - - - - - - Current line: - - - - - - - <p>Sets the background color of the currently active line, which means the line where your cursor is positioned.</p> - - - - - - - <p>Select the marker type you want to change.</p> - - - - - - - <p>Sets the background color of the selected marker type.</p><p><b>Note</b>: The marker color is displayed lightly because of transparency.</p> - - - - - - - - - - Additional Elements - - - true - - - - - - Left border background: - - - - - - - - - - Line numbers: - - - - - - - <p>This color will be used to draw the line numbers (if enabled) and the lines in the code-folding pane.</p> - - - - - - - Bracket highlight: - - - - - - - <p>Sets the bracket matching color. This means, if you place the cursor e.g. at a <b>(</b>, the matching <b>)</b> will be highlighted with this color.</p> - - - - - - - Word wrap markers: - - - - - - - <p>Sets the color of Word Wrap-related markers:</p><dl><dt>Static Word Wrap</dt><dd>A vertical line which shows the column where text is going to be wrapped</dd><dt>Dynamic Word Wrap</dt><dd>An arrow shown to the left of visually-wrapped lines</dd></dl> - - - - - - - Tab and space markers: - - - - - - - <p>Sets the color of the tabulator marks.</p> - - - - - - - Spelling mistake line: - - - - - - - <p>Sets the color of the line that is used to indicate spelling mistakes.</p> - - - - - - - - - - Qt::Vertical - - - - 540 - 1 - - - - - - - - - KColorButton - QPushButton -
kcolorbutton.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
-
- - -
diff --git a/part/dialogs/spellcheckconfigwidget.ui b/part/dialogs/spellcheckconfigwidget.ui deleted file mode 100644 index cd75e87..0000000 --- a/part/dialogs/spellcheckconfigwidget.ui +++ /dev/null @@ -1,37 +0,0 @@ - - - SpellCheckConfigWidget - - - - 0 - 0 - 462 - 189 - - - - - 0 - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 0 - 1 - - - - - - - - - diff --git a/part/dialogs/textareaappearanceconfigwidget.ui b/part/dialogs/textareaappearanceconfigwidget.ui deleted file mode 100644 index ad62e7c..0000000 --- a/part/dialogs/textareaappearanceconfigwidget.ui +++ /dev/null @@ -1,208 +0,0 @@ - - - TextareaAppearanceConfigWidget - - - - 0 - 0 - 497 - 328 - - - - - - - If this option is checked, the text lines will be wrapped at the view border on the screen. - - - &Dynamic Word Wrap - - - true - - - - - - Dynamic &word wrap indicators (if applicable): - - - cmbDynamicWordWrapIndicator - - - - - - - Choose when the Dynamic Word Wrap Indicators should be displayed. - - - - - - - Align dynamically wrapped lines to indentation depth: - - - sbDynamicWordWrapDepth - - - - - - - - 0 - 0 - - - - <p>Enables the start of dynamically wrapped lines to be aligned vertically to the indentation level of the first line. This can help to make code and markup more readable.</p><p>Additionally, this allows you to set a maximum width of the screen, as a percentage, after which dynamically wrapped lines will no longer be vertically aligned. For example, at 50%, lines whose indentation levels are deeper than 50% of the width of the screen will not have vertical alignment applied to subsequent wrapped lines.</p> - - - Disabled - - - % of View Width - - - 80 - - - 10 - - - - - - - - - - Whitespace Highlighting - - - - - - The editor will display a symbol to indicate the presence of a tab in the text. - - - &Highlight tabulators - - - - - - - Highlight trailing &spaces - - - - - - - - - - Advanced - - - - - - Changing this mode affects only newly opened / created documents. In KWrite a restart is recommended. - - - Enable power user mode (KDE 3 mode) - - - - - - - If this is enabled, the editor will display vertical lines to help identify indent lines. - - - Show i&ndentation lines - - - - - - - If this is enabled, the range between the selected matching brackets will be highlighted. - - - Highlight range between selected brackets - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - KIntSpinBox - QSpinBox -
knuminput.h
-
- - KComboBox - QComboBox -
kcombobox.h
-
-
- - - - gbWordWrap - toggled(bool) - cmbDynamicWordWrapIndicator - setEnabled(bool) - - - 115 - 7 - - - 340 - 44 - - - - - gbWordWrap - toggled(bool) - sbDynamicWordWrapDepth - setEnabled(bool) - - - 59 - 6 - - - 385 - 72 - - - - -
diff --git a/part/dialogs/viinputmodeconfigwidget.ui b/part/dialogs/viinputmodeconfigwidget.ui deleted file mode 100644 index 353c176..0000000 --- a/part/dialogs/viinputmodeconfigwidget.ui +++ /dev/null @@ -1,188 +0,0 @@ - - - ViInputModeConfigWidget - - - - 0 - - - - - General - - - - - - When selected, the vi input mode will be enabled when opening a new view. You can still toggle the vi input mode on/off for a particular view in the Edit menu. - - - Use Vi input mode - - - - - - - When selected, vi commands will override Kate's built-in commands. For example: Ctrl+R will redo, and override the standard action (showing the search and replace dialog). - - - Let Vi commands override Kate shortcuts - - - - - - - By default, an extra status bar will be used when the Vi input mode is enabled. This status bar shows commands while they are being typed and messages/errors produced by Vi commands. - -Checking this options will hide this extra status line. - - - Hide the Vi mode status bar - - - - - - - - - - Key mapping is used to change the meaning of typed keys. This allows you to move commands to other keys or make special keypresses for doing a series of commands. - -Example: -"<F2>" → "I-- <esc>" - -This will prepend "-- " to a line when pressing F2. - - - Key Mapping - - - - - - 0 - - - - Normal mode - - - - - - true - - - QAbstractItemView::ContiguousSelection - - - QAbstractItemView::SelectRows - - - 2 - - - - Command - - - - - Replacement - - - - - - - - - - Remove selected - - - - - - - Add new mapping - - - - - - - Qt::Horizontal - - - - 1 - 0 - - - - - - - - - - - - - - - - - Qt::Vertical - - - - 0 - 1 - - - - - - - - - - chkViInputModeDefault - toggled(bool) - chkViCommandsOverride - setEnabled(bool) - - - 192 - 48 - - - 192 - 77 - - - - - chkViInputModeDefault - toggled(bool) - chkViStatusBarHide - setEnabled(bool) - - - 192 - 48 - - - 192 - 106 - - - - - diff --git a/part/document/katebuffer.cpp b/part/document/katebuffer.cpp deleted file mode 100644 index c1b22fe..0000000 --- a/part/document/katebuffer.cpp +++ /dev/null @@ -1,743 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (c) 2000 Waldo Bastian - Copyright (C) 2002-2004 Christoph Cullmann - Copyright (C) 2007 Mirko Stocker - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katebuffer.h" -#include "katebuffer.moc" - -#include -#include -#include -#include - -#include "katedocument.h" -#include "katehighlight.h" -#include "kateconfig.h" -#include "kateglobal.h" -#include "kateautoindent.h" - -#include -#include -#include -#include - -// on the fly compression -#include -#include - -#include -#include -#include -#include -#include - -#include - -/** - * hl will look at the next KATE_HL_LOOKAHEAD lines - * or until the current block ends if a line is requested - * will avoid to run doHighlight too often - */ -static const int KATE_HL_LOOKAHEAD = 64; - -/** - * Initial value for m_maxDynamicContexts - */ -static const int KATE_MAX_DYNAMIC_CONTEXTS = 512; - -/** - * Create an empty buffer. (with one block with one empty line) - */ -KateBuffer::KateBuffer(KateDocument *doc) - : Kate::TextBuffer (doc), - m_doc (doc), - m_brokenEncoding (false), - m_highlight (0), - m_regionTree (this), - m_tabWidth (8), - m_lineHighlighted (0), - m_ctxChanged (true), - m_maxDynamicContexts (KATE_MAX_DYNAMIC_CONTEXTS) -{ - // we need kate global to stay alive - KateGlobal::incRef (); -} - -/** - * Cleanup on destruction - */ -KateBuffer::~KateBuffer() -{ - // release HL - if (m_highlight) - m_highlight->release(); - - // release kate global - KateGlobal::decRef (); -} - -void KateBuffer::editStart () -{ - if (!startEditing ()) - return; -} - -void KateBuffer::editEnd () -{ - if (!finishEditing()) - return; - - if (editingChangedBuffer ()) - { - // hl update !!! - if (m_highlight && editingMinimalLineChanged () <= editingMaximalLineChanged () && editingMaximalLineChanged () <= m_lineHighlighted) - { - // look one line too far, needed for linecontinue stuff - int editTagLineEnd = editingMaximalLineChanged () + 1; - int editTagLineStart = editingMinimalLineChanged (); - - // look one line before, needed nearly 100% only for indentation based folding ! - if (editTagLineStart > 0) - --editTagLineStart; - - m_ctxChanged = doHighlight ( - editTagLineStart, - editTagLineEnd, - true); - - m_lineHighlighted = editTagLineEnd; - } - } -} - -void KateBuffer::clear() -{ - // call original clear function - Kate::TextBuffer::clear (); - - m_regionTree.clear(); - - // reset the state - m_brokenEncoding = false; - - m_lineHighlighted = 0; - m_ctxChanged = true; -} - -bool KateBuffer::openFile (const QString &m_file) -{ - // first: setup fallback and normal encoding - setEncodingProberType (KateGlobalConfig::global()->proberType ()); - setFallbackTextCodec (KateGlobalConfig::global()->fallbackCodec ()); - setTextCodec (m_doc->config()->codec ()); - - // setup eol - setEndOfLineMode ((EndOfLineMode) m_doc->config()->eol()); - - // remove trailing spaces? - // NOTE: The buffer won't actually remove trailing space on load. This is because - // we need to do it later, after the config and variables have been parsed. - setRemoveTrailingSpaces (m_doc->config()->removeSpaces()); - - // then, try to load the file - m_brokenEncoding = false; - if (!load (m_file, m_brokenEncoding)) - return false; - - // save back encoding - m_doc->config()->setEncoding (textCodec()->name()); - - // set eol mode, if a eol char was found - if (m_doc->config()->allowEolDetection()) - m_doc->config()->setEol (endOfLineMode ()); - - // generate a bom? - if (generateByteOrderMark()) - m_doc->config()->setBom (true); - - // fix region tree - m_regionTree.fixRoot (lines ()); - - // okay, loading did work - return true; -} - -bool KateBuffer::canEncode () -{ - QTextCodec *codec = m_doc->config()->codec(); - - kDebug(13020) << "ENC NAME: " << codec->name(); - - // hardcode some unicode encodings which can encode all chars - if ((QString(codec->name()) == "UTF-8") || (QString(codec->name()) == "ISO-10646-UCS-2")) - return true; - - for (int i=0; i < lines(); i++) - { - if (!codec->canEncode (line(i)->string())) - { - kDebug(13020) << "STRING LINE: " << line(i)->string(); - kDebug(13020) << "ENC WORKING: FALSE"; - - return false; - } - } - - return true; -} - -bool KateBuffer::saveFile (const QString &m_file) -{ - // first: setup fallback and normal encoding - setEncodingProberType (KateGlobalConfig::global()->proberType ()); - setFallbackTextCodec (KateGlobalConfig::global()->fallbackCodec ()); - setTextCodec (m_doc->config()->codec ()); - - // setup eol - setEndOfLineMode ((EndOfLineMode) m_doc->config()->eol()); - - // generate bom? - setGenerateByteOrderMark (m_doc->config()->bom()); - - // remove trailing spaces? - setRemoveTrailingSpaces (m_doc->config()->removeSpaces()); - - // try to save - if (!save (m_file)) - return false; - - // no longer broken encoding, or we don't care - m_brokenEncoding = false; - - // okay - return true; -} - -void KateBuffer::ensureHighlighted (int line) -{ - // valid line at all? - if (line < 0 || line >= lines ()) - return; - - // already hl up-to-date for this line? - if (line < m_lineHighlighted) - return; - - // update hl until this line + max KATE_HL_LOOKAHEAD - int end = qMin(line + KATE_HL_LOOKAHEAD, lines ()-1); - - m_ctxChanged = doHighlight ( m_lineHighlighted, end, m_ctxChanged ); - - m_lineHighlighted = end; -} - -void KateBuffer::wrapLine (const KTextEditor::Cursor &position) -{ - // call original - Kate::TextBuffer::wrapLine (position); - - if (m_lineHighlighted > position.line()+1) - m_lineHighlighted++; - - m_regionTree.lineHasBeenInserted (position.line()+1); - -} - -void KateBuffer::unwrapLine (int line) -{ - // call original - Kate::TextBuffer::unwrapLine (line); - - if (m_lineHighlighted > line) - m_lineHighlighted--; - - m_regionTree.lineHasBeenRemoved (line); -} - -void KateBuffer::setTabWidth (int w) -{ - if ((m_tabWidth != w) && (m_tabWidth > 0)) - { - m_tabWidth = w; - - if (m_highlight && m_highlight->foldingIndentationSensitive()) - invalidateHighlighting(); - } -} - -void KateBuffer::setHighlight(int hlMode) -{ - KateHighlighting *h = KateHlManager::self()->getHl(hlMode); - - // aha, hl will change - if (h != m_highlight) - { - bool invalidate = !h->noHighlighting(); - - if (m_highlight) - { - m_highlight->release(); - invalidate = true; - } - - h->use(); - - // Clear code folding tree (see bug #124102) - m_regionTree.clear(); - m_regionTree.fixRoot(lines()); - - m_highlight = h; - - if (invalidate) - invalidateHighlighting(); - - // inform the document that the hl was really changed - // needed to update attributes and more ;) - m_doc->bufferHlChanged (); - - // try to set indentation - if (!h->indentation().isEmpty()) - m_doc->config()->setIndentationMode (h->indentation()); - } -} - -void KateBuffer::invalidateHighlighting() -{ - m_lineHighlighted = 0; - m_ctxChanged = true; -} - - -void KateBuffer::updatePreviousNotEmptyLine(int current_line,bool addindent,int deindent) -{ - Kate::TextLine textLine; - do { - if (current_line == 0) return; - - --current_line; - - textLine = plainLine (current_line); - } while (textLine->firstChar()==-1); - - kDebug(13020)<<"updatePreviousNotEmptyLine: updating line:"< foldingList=textLine->foldingListArray(); - while ( !foldingList.isEmpty() && abs(foldingList.at(foldingList.size()-2)) == 1) { - foldingList.resize(foldingList.size()-2); - } - addIndentBasedFoldingInformation(foldingList,textLine->length(),addindent,deindent); - textLine->setFoldingList(foldingList); - - bool retVal_folding = false; - m_regionTree.updateLine (current_line, &foldingList, &retVal_folding, true,false); - - // tagLines() is emitted from KatBuffer::doHighlight()! -} - -void KateBuffer::addIndentBasedFoldingInformation(QVector &foldingList,int linelength,bool addindent,int deindent) -{ - if (addindent) { - //kDebug(13020)<<"adding indent for line :"<startLine()<<" textLine->noIndentBasedFoldingAtStart"<noIndentBasedFoldingAtStart(); - //kDebug(13020)<<"adding ident"; - foldingList.resize (foldingList.size() + 2); - foldingList[foldingList.size()-2] = 1; - foldingList[foldingList.size()-1] = 0; - } - //kDebug(13020)<<"DEINDENT: "< 0) - { - //foldingList.resize (foldingList.size() + (deindent*2)); - - //Make the whole last line marked as still belonging to the block - for (int z=0;z l; - l=m_highlight->emptyLines(textline->attribute(0)); - if (l.isEmpty()) return false; - QString txt=textline->string(); - foreach(const QRegExp &re,l) { - if (re.exactMatch(txt)) return true; - } - return false; -} - -bool KateBuffer::doHighlight (int startLine, int endLine, bool invalidate) -{ - // no hl around, no stuff to do - if (!m_highlight) - return false; - -#ifdef BUFFER_DEBUGGING - QTime t; - t.start(); - kDebug (13020) << "HIGHLIGHTED START --- NEED HL, LINESTART: " << startLine << " LINEEND: " << endLine; - kDebug (13020) << "HL UNTIL LINE: " << m_lineHighlighted; - kDebug (13020) << "HL DYN COUNT: " << KateHlManager::self()->countDynamicCtxs() << " MAX: " << m_maxDynamicContexts; -#endif - - // see if there are too many dynamic contexts; if yes, invalidate HL of all documents - if (KateHlManager::self()->countDynamicCtxs() >= m_maxDynamicContexts) - { - { - if (KateHlManager::self()->resetDynamicCtxs()) - { -#ifdef BUFFER_DEBUGGING - kDebug (13020) << "HL invalidated - too many dynamic contexts ( >= " << m_maxDynamicContexts << ")"; -#endif - - // avoid recursive invalidation - KateHlManager::self()->setForceNoDCReset(true); - - foreach(KateDocument* doc, KateGlobal::self()->kateDocuments()) - doc->makeAttribs(); - - // doHighlight *shall* do his work. After invalidation, some highlight has - // been recalculated, but *maybe not* until endLine ! So we shall force it manually... - m_ctxChanged = doHighlight ( m_lineHighlighted, endLine, false ); - m_lineHighlighted = endLine; - - KateHlManager::self()->setForceNoDCReset(false); - - return false; - } - else - { - m_maxDynamicContexts *= 2; - -#ifdef BUFFER_DEBUGGING - kDebug (13020) << "New dynamic contexts limit: " << m_maxDynamicContexts; -#endif - } - } - } - - // get previous line, if any - Kate::TextLine prevLine; - - if (startLine >= 1) - prevLine = plainLine (startLine-1); - else - prevLine = Kate::TextLine (new Kate::TextLineData ()); - - // does we need to emit a signal for the folding changes ? - bool codeFoldingUpdate = false; - - // here we are atm, start at start line in the block - int current_line = startLine; - int start_spellchecking = -1; - int last_line_spellchecking = -1; - // do we need to continue - bool stillcontinue=false; - bool indentContinueWhitespace=false; - bool indentContinueNextWhitespace=false; - bool ctxChanged = false; - // loop over the lines of the block, from startline to endline or end of block - // if stillcontinue forces us to do so - while ( (current_line < lines()) && (stillcontinue || (current_line <= endLine)) ) - { - // current line - Kate::TextLine textLine = plainLine (current_line); - - QVector foldingList; - ctxChanged = false; - - m_highlight->doHighlight (prevLine.data(), textLine.data(), foldingList, ctxChanged); - -#ifdef BUFFER_DEBUGGING - // debug stuff - kDebug( 13020 ) << "current line to hl: " << current_line + buf->startLine(); - kDebug( 13020 ) << "text length: " << textLine->length() << " attribute list size: " << textLine->attributesList().size(); - - const QVector &ml (textLine->attributesList()); - for (int i=2; i < ml.size(); i+=3) - { - kDebug( 13020 ) << "start: " << ml.at(i-2) << " len: " << ml.at(i-1) << " at: " << ml.at(i) << " "; - } - kDebug( 13020 ); -#endif - - // - // indentation sensitive folding - // - bool indentChanged = false; - if (m_highlight->foldingIndentationSensitive()) - { - // get the indentation array of the previous line to start with ! - QVector indentDepth (prevLine->indentationDepthArray()); - - // current indentation of this line - int iDepth = textLine->indentDepth(m_tabWidth); - if (current_line==0) - { - indentDepth.resize (1); - indentDepth[0] = iDepth; - } - - textLine->setNoIndentBasedFoldingAtStart(prevLine->noIndentBasedFolding()); - - // this line is empty, beside spaces, or has indentaion based folding disabled, use indentation depth of the previous line ! - -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"current_line:"<noIndentBasedFoldingAtStart"<noIndentBasedFoldingAtStart(); -#endif - - if ( (textLine->firstChar() == -1) || textLine->noIndentBasedFoldingAtStart() || isEmptyLine(textLine) ) - { - // do this to get skipped empty lines indent right, which was given in the indenation array - if (!prevLine->indentationDepthArray().isEmpty()) - { - iDepth = prevLine->indentationDepthArray().last(); - -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"reusing old depth as current"; -#endif - } - else - { - iDepth = prevLine->indentDepth(m_tabWidth); - -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"creating indentdepth for previous line"; -#endif - } - } - -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"iDepth:"<firstChar() == -1) || isEmptyLine(plainLine (current_line+1)) ) - { - nextLineIndentation = iDepth; - indentContinueNextWhitespace=true; - } - else - nextLineIndentation = plainLine (current_line+1)->indentDepth(m_tabWidth); - } - else - { - nextLineIndentationValid=false; - } - - if (!textLine->noIndentBasedFoldingAtStart()) { - - if ((iDepth > 0) && (indentDepth.isEmpty() || (indentDepth.last() < iDepth))) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"adding depth to \"stack\":"< -1; z--) - if (indentDepth.at(z) > iDepth) - indentDepth.resize(z); - if ((iDepth > 0) && (indentDepth.isEmpty() || (indentDepth.last() < iDepth))) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"adding depth to \"stack\":"<firstChar()==-1) { - - } - } - } - } - } - - if (!textLine->noIndentBasedFolding()) - { - if (nextLineIndentationValid) - { - //if (textLine->firstChar()!=-1) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"nextLineIndentation:"< 0 && ( indentDepth.isEmpty() || indentDepth.last() < nextLineIndentation)) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"addindent==true"; -#endif - - addindent=true; - } else { - if (!indentDepth.isEmpty() && indentDepth.last() > nextLineIndentation) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)<<"...."; -#endif - - for (int z=indentDepth.size()-1; z > -1; z--) - { -#ifdef BUFFER_DEBUGGING - kDebug(13020)< nextLineIndentation) - deindent++; - } - } - } -/* } - if (textLine->noIndentBasedFolding()) kDebug(13020)<<"=============================indentation based folding disabled======================"; - if (!textLine->noIndentBasedFolding()) {*/ - if ((textLine->firstChar()==-1)) { - updatePreviousNotEmptyLine(current_line,addindent,deindent); - codeFoldingUpdate=true; - } - else - { - addIndentBasedFoldingInformation(foldingList,textLine->length(),addindent,deindent); - } - } - } - } - indentChanged = !(indentDepth == textLine->indentationDepthArray()); - - // assign the new array to the textline ! - if (indentChanged) - textLine->setIndentationDepth (indentDepth); - - indentContinueWhitespace=textLine->firstChar()==-1; - } - bool foldingColChanged=false; - bool foldingChanged = false; //!(foldingList == textLine->foldingListArray()); - if (foldingList.size()!=textLine->foldingListArray().size()) { - foldingChanged=true; - } else { - QVector::ConstIterator it=foldingList.constBegin(); - QVector::ConstIterator it1=textLine->foldingListArray().constBegin(); - bool markerType=true; - for(;it!=foldingList.constEnd();++it,++it1) { - if (markerType) { - if ( ((*it)!=(*it1))) { - foldingChanged=true; - foldingColChanged=false; - break; - } - } else { - if ((*it)!=(*it1)) { - foldingColChanged=true; - } - } - markerType=!markerType; - } - } - - if (foldingChanged || foldingColChanged) { - textLine->setFoldingList(foldingList); - if (foldingChanged==false){ - textLine->setFoldingColumnsOutdated(textLine->foldingColumnsOutdated() | foldingColChanged); - } else textLine->setFoldingColumnsOutdated(false); - } - bool retVal_folding = false; - //perhaps make en enums out of the change flags - m_regionTree.updateLine (current_line, &foldingList, &retVal_folding, foldingChanged,foldingColChanged); - - codeFoldingUpdate = codeFoldingUpdate | retVal_folding; - - // need we to continue ? - stillcontinue = indentChanged || indentContinueWhitespace || indentContinueNextWhitespace; - if (stillcontinue && start_spellchecking < 0) { - start_spellchecking=current_line; - } - else if (!stillcontinue && start_spellchecking >= 0) { - last_line_spellchecking=current_line; - } - // move around the lines - prevLine = textLine; - - // increment line - current_line++; - } - - // tag the changed lines ! - if (invalidate) { - // prevent infinite recursion - int temp = m_lineHighlighted; - m_lineHighlighted = INT_MAX; - emit tagLines (startLine, current_line); - m_lineHighlighted = temp; - - if(start_spellchecking >= 0 && lines() > 0) { - emit respellCheckBlock(start_spellchecking, - qMin(lines()-1, (last_line_spellchecking==-1)?current_line:last_line_spellchecking)); - } - } - // emit that we have changed the folding - if (codeFoldingUpdate) - emit codeFoldingUpdated(); - -#ifdef BUFFER_DEBUGGING - kDebug (13020) << "HIGHLIGHTED END --- NEED HL, LINESTART: " << startLine << " LINEEND: " << endLine; - kDebug (13020) << "HL UNTIL LINE: " << m_lineHighlighted; - kDebug (13020) << "HL DYN COUNT: " << KateHlManager::self()->countDynamicCtxs() << " MAX: " << m_maxDynamicContexts; - kDebug (13020) << "TIME TAKEN: " << t.elapsed(); -#endif - - // if we are at the last line of the block + we still need to continue - // return the need of that ! - return ctxChanged; -} - -void KateBuffer::codeFoldingColumnUpdate(int lineNr) { - Kate::TextLine line=plainLine(lineNr); - if (!line) return; - if (line->foldingColumnsOutdated()) { - line->setFoldingColumnsOutdated(false); - bool tmp; - QVector folding=line->foldingListArray(); - m_regionTree.updateLine(lineNr,&folding,&tmp,true,false); - } -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/document/katebuffer.h b/part/document/katebuffer.h deleted file mode 100644 index 9f4c640..0000000 --- a/part/document/katebuffer.h +++ /dev/null @@ -1,264 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (c) 2000 Waldo Bastian - Copyright (C) 2002-2004 Christoph Cullmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_BUFFER_H__ -#define __KATE_BUFFER_H__ - -#include "katetextbuffer.h" -#include "katecodefolding.h" - -#include "katepartprivate_export.h" - -#include - -class KateLineInfo; -class KateDocument; -class KateHighlighting; - -/** - * The KateBuffer class maintains a collections of lines. - * - * @author Waldo Bastian - * @author Christoph Cullmann - */ -class KATEPART_TESTS_EXPORT KateBuffer : public Kate::TextBuffer -{ - Q_OBJECT - - public: - /** - * Create an empty buffer. - * @param doc parent document - */ - explicit KateBuffer (KateDocument *doc); - - /** - * Goodbye buffer - */ - ~KateBuffer (); - - public: - /** - * start some editing action - */ - void editStart (); - - /** - * finish some editing action - */ - void editEnd (); - - /** - * were there changes in the current running - * editing session? - * @return changes done? - */ - inline bool editChanged () const { return editingChangedBuffer (); } - - /** - * dirty lines start - * @return start line - */ - inline int editTagStart () const { return editingMinimalLineChanged (); } - - /** - * dirty lines end - * @return end line - */ - inline int editTagEnd () const { return editingMaximalLineChanged (); } - - /** - * line inserted/removed? - * @return line inserted/removed? - */ - inline bool editTagFrom () const { return editingChangedNumberOfLines() != 0; } - - public: - /** - * Clear the buffer. - */ - void clear(); - - /** - * Open a file, use the given filename - * @param m_file filename to open - * @return success - */ - bool openFile (const QString &m_file); - - /** - * Did encoding errors occured on load? - * @return encoding errors occured on load? - */ - bool brokenEncoding () const { return m_brokenEncoding; } - - /** - * Can the current codec handle all chars - * @return chars can be encoded - */ - bool canEncode (); - - /** - * Save the buffer to a file, use the given filename + codec + end of line chars (internal use of qtextstream) - * @param m_file filename to save to - * @return success - */ - bool saveFile (const QString &m_file); - - public: - /** - * Return line @p lineno. - * Highlighting of returned line might be out-dated, which may be sufficient - * for pure text manipulation functions, like search/replace. - * If you require highlighting to be up to date, call @ref ensureHighlighted - * prior to this method. - */ - inline Kate::TextLine plainLine (int lineno) - { - if (lineno < 0 || lineno >= lines()) - return Kate::TextLine (); - - return line (lineno); - } - - /** - * Update highlighting of given line @p line, if needed. - */ - void ensureHighlighted(int line); - - /** - * Return the total number of lines in the buffer. - */ - inline int count() const { return lines(); } - - /** - * Wrap line at given cursor position. - * @param position line/column as cursor where to wrap - */ - void wrapLine (const KTextEditor::Cursor &position); - - /** - * Unwrap given line. - * @param line line to unwrap - */ - void unwrapLine (int line); - - private: - inline void addIndentBasedFoldingInformation(QVector &foldingList,int linelength,bool addindent,int deindent); - inline void updatePreviousNotEmptyLine(int current_line,bool addindent,int deindent); - - public: - inline int countVisible () { return lines() - m_regionTree.getHiddenLinesCount(lines()); } - - inline int lineNumber (int visibleLine) { return m_regionTree.getRealLine (visibleLine); } - - inline int lineVisibleNumber (int line) { return m_regionTree.getVirtualLine (line); } - - inline void lineInfo (KateLineInfo *info, int line) { m_regionTree.getLineInfo(info,line); } - - inline int tabWidth () const { return m_tabWidth; } - - public: - void setTabWidth (int w); - - /** - * Use @p highlight for highlighting - * - * @p highlight may be 0 in which case highlighting - * will be disabled. - */ - void setHighlight (int hlMode); - - KateHighlighting *highlight () { return m_highlight; } - - /** - * Invalidate highlighting of whole buffer. - */ - void invalidateHighlighting(); - - KateCodeFoldingTree *foldingTree () { return &m_regionTree; } - - void codeFoldingColumnUpdate(int lineNr); - - private: - /** - * Highlight information needs to be updated. - * - * @param from first line in range - * @param to last line in range - * @param invalidat should the rehighlighted lines be tagged ? - * - * @returns true when the highlighting in the next block needs to be updated, - * false otherwise. - */ - bool doHighlight (int from, int to, bool invalidate); - bool isEmptyLine(Kate::TextLine textline); - - Q_SIGNALS: - /** - * Emittend if codefolding returned with a changed list - */ - void codeFoldingUpdated(); - - /** - * Emitted when the highlighting of a certain range has - * changed. - */ - void tagLines(int start, int end); - void respellCheckBlock(int start, int end); - private: - /** - * document we belong to - */ - KateDocument *const m_doc; - - /** - * file loaded with encoding problems? - */ - bool m_brokenEncoding; - - /** - * highlighting & folding relevant stuff - */ - private: - /** - * current highlighting mode or 0 - */ - KateHighlighting *m_highlight; - - /** - * folding tree - */ - KateCodeFoldingTree m_regionTree; - - // for the scrapty indent sensitive langs - int m_tabWidth; - - int m_lineHighlighted; - bool m_ctxChanged; - - /** - * number of dynamic contexts causing a full invalidation - */ - int m_maxDynamicContexts; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/document/katedocument.cpp b/part/document/katedocument.cpp deleted file mode 100644 index 9ab5db0..0000000 --- a/part/document/katedocument.cpp +++ /dev/null @@ -1,5303 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001-2004 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - Copyright (C) 2006 Hamish Rodda - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2009-2010 Michel Ludwig - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02111-13020, USA. -*/ - -//BEGIN includes -#include "katedocument.h" -#include "katedocument.moc" -#include "kateglobal.h" -#include "katedialogs.h" -#include "katehighlight.h" -#include "kateview.h" -#include "kateautoindent.h" -#include "katetextline.h" -#include "katedocumenthelpers.h" -#include "kateprinter.h" -#include "katerenderer.h" -#include "kateregexp.h" -#include "kateplaintextsearch.h" -#include "kateregexpsearch.h" -#include "kateconfig.h" -#include "katemodemanager.h" -#include "kateschema.h" -#include "katetemplatehandler.h" -#include "katebuffer.h" -#include "kateundomanager.h" -#include "katepartpluginmanager.h" -#include "katevireplacemode.h" -#include "spellcheck/prefixstore.h" -#include "spellcheck/ontheflycheck.h" -#include "spellcheck/spellcheck.h" -#include "katescriptmanager.h" -#include "kateswapfile.h" - -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -//END includes - - -static int dummy = 0; - -class KateTemplateScript; - -class KateDocument::LoadSaveFilterCheckPlugins -{ - public: - LoadSaveFilterCheckPlugins() { - KService::List traderList = KServiceTypeTrader::self()->query("KTextEditor/LoadSaveFilterCheckPlugin"); - - foreach(const KService::Ptr &ptr, traderList) - { - QString libname; - libname=ptr->library(); - libname=libname.right(libname.length()-12); //ktexteditor_ == 12 - m_plugins[libname]=0;//new KatePythonEncodingCheck(); - m_plugins2Service[libname] = ptr; - } - - } - ~LoadSaveFilterCheckPlugins() { - if ( m_plugins.count()==0) return; - QHashIteratori(m_plugins); - while (i.hasNext()) - i.next(); - delete i.value(); - m_plugins.clear(); - } - bool preSavePostDialogFilterCheck(const QString& pluginName,KateDocument *document,QWidget *parentWidget) { - KTextEditor::LoadSaveFilterCheckPlugin *plug=getPlugin(pluginName); - if (!plug) { - if (KMessageBox::warningContinueCancel (parentWidget - , i18n ("The filter/check plugin '%1' could not be found, still continue saving of %2", pluginName,document->url().pathOrUrl()) - , i18n ("Saving problems") - , KGuiItem(i18n("Save Nevertheless")) - , KStandardGuiItem::cancel()) != KMessageBox::Continue) - return false; - else - return true; - } - return plug->preSavePostDialogFilterCheck(document); - } - void postLoadFilter(const QString& pluginName,KateDocument *document) { - KTextEditor::LoadSaveFilterCheckPlugin *plug=getPlugin(pluginName); - if (!plug) return; - plug->postLoadFilter(document); - } - bool postSaveFilterCheck(const QString& pluginName,KateDocument *document,bool saveas) { - KTextEditor::LoadSaveFilterCheckPlugin *plug=getPlugin(pluginName); - if (!plug) return false; - return plug->postSaveFilterCheck(document,saveas); - } - private: - KTextEditor::LoadSaveFilterCheckPlugin *getPlugin(const QString & pluginName) - { - if (!m_plugins.contains(pluginName)) return 0; - if (!m_plugins.value(pluginName, 0)) { - m_plugins[pluginName]=m_plugins2Service.value(pluginName)->createInstance(); - } - return m_plugins.value(pluginName); - } - QHash m_plugins; - QHash m_plugins2Service; -}; - -//BEGIN d'tor, c'tor -// -// KateDocument Constructor -// -KateDocument::KateDocument ( bool bSingleViewMode, bool bBrowserView, - bool bReadOnly, QWidget *parentWidget, - QObject *parent) -: KTextEditor::Document (parent), - m_bSingleViewMode(bSingleViewMode), - m_bBrowserView(bBrowserView), - m_bReadOnly(bReadOnly), - m_activeView(0), - editSessionNumber(0), - editIsRunning(false), - m_undoManager(new KateUndoManager(this)), - m_editableMarks(markType01), - m_annotationModel(0), - m_saveAs(false), - m_isasking(0), - m_blockRemoveTrailingSpaces(false), - m_buffer(new KateBuffer(this)), - m_indenter(new KateAutoIndent(this)), - hlSetByUser(false), - m_bomSetByUser(false), - m_modOnHd(false), - m_modOnHdReason(OnDiskUnmodified), - m_docName("need init"), - m_docNameNumber(0), - m_fileTypeSetByUser(false), - m_reloading(false), - m_config(new KateDocumentConfig(this)), - m_fileChangedDialogsActivated(false), - m_savingToUrl(false), - m_onTheFlyChecker(0) -{ - setComponentData ( KateGlobal::self()->componentData () ); - - QString pathName ("/Kate/Document/%1"); - pathName = pathName.arg (++dummy); - - // my dbus object - QDBusConnection::sessionBus().registerObject (pathName, this); - - // register doc at factory - KateGlobal::self()->registerDocument(this); - - // normal hl - m_buffer->setHighlight (0); - - // swap file - m_swapfile = new Kate::SwapFile(this); - - new KateBrowserExtension( this ); // deleted by QObject memory management - - // important, fill in the config into the indenter we use... - m_indenter->updateConfig (); - - // some nice signals from the buffer - connect(m_buffer, SIGNAL(tagLines(int,int)), this, SLOT(tagLines(int,int))); - connect(m_buffer, SIGNAL(respellCheckBlock(int, int)), this , SLOT(respellCheckBlock(int, int))); - connect(m_buffer, SIGNAL(codeFoldingUpdated()),this,SIGNAL(codeFoldingUpdated())); - - // if the user changes the highlight with the dialog, notify the doc - connect(KateHlManager::self(),SIGNAL(changed()),SLOT(internalHlChanged())); - - // signals for mod on hd - connect( KateGlobal::self()->dirWatch(), SIGNAL(dirty (const QString &)), - this, SLOT(slotModOnHdDirty (const QString &)) ); - - connect( KateGlobal::self()->dirWatch(), SIGNAL(created (const QString &)), - this, SLOT(slotModOnHdCreated (const QString &)) ); - - connect( KateGlobal::self()->dirWatch(), SIGNAL(deleted (const QString &)), - this, SLOT(slotModOnHdDeleted (const QString &)) ); - - connect (this,SIGNAL(completed()),this,SLOT(slotCompleted())); - connect (this,SIGNAL(canceled(const QString&)),this,SLOT(slotCanceled())); - // update doc name - setDocName (QString()); - - // if single view mode, like in the konqui embedding, create a default view ;) - // be lazy, only create it now, if any parentWidget is given, otherwise widget() - // will create it on demand... - if ( m_bSingleViewMode && parentWidget ) - { - KTextEditor::View *view = (KTextEditor::View*)createView( parentWidget ); - insertChildClient( view ); - view->show(); - setWidget( view ); - } - - connect(m_undoManager, SIGNAL(undoChanged()), this, SIGNAL(undoChanged())); - connect(m_undoManager, SIGNAL(undoStart(KTextEditor::Document*)), this, SIGNAL(exclusiveEditStart(KTextEditor::Document*))); - connect(m_undoManager, SIGNAL(undoEnd(KTextEditor::Document*)), this, SIGNAL(exclusiveEditEnd(KTextEditor::Document*))); - connect(m_undoManager, SIGNAL(redoStart(KTextEditor::Document*)), this, SIGNAL(exclusiveEditStart(KTextEditor::Document*))); - connect(m_undoManager, SIGNAL(redoEnd(KTextEditor::Document*)), this, SIGNAL(exclusiveEditEnd(KTextEditor::Document*))); - - connect(this,SIGNAL(sigQueryClose(bool *, bool*)),this,SLOT(slotQueryClose_save(bool *, bool*))); - - onTheFlySpellCheckingEnabled(config()->onTheFlySpellCheck()); - - // register document in plugins - KatePartPluginManager::self()->addDocument(this); -} - -// -// KateDocument Destructor -// -KateDocument::~KateDocument() -{ - /** - * we are about to delete cursors/ranges/... - */ - emit aboutToDeleteMovingInterfaceContent (this); - - // kill it early, it has ranges! - delete m_onTheFlyChecker; - m_onTheFlyChecker = NULL; - - clearDictionaryRanges(); - - // Tell the world that we're about to close (== destruct) - // Apps must receive this in a direct signal-slot connection, and prevent - // any further use of interfaces once they return. - emit aboutToClose(this); - - // remove file from dirwatch - deactivateDirWatch (); - - // thanks for offering, KPart, but we're already self-destructing - setAutoDeleteWidget(false); - setAutoDeletePart(false); - - // clean up remaining views - while (!m_views.isEmpty()) { - delete m_views.takeFirst(); - } - - // de-register from plugin - KatePartPluginManager::self()->removeDocument(this); - - // cu marks - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - delete i.value(); - m_marks.clear(); - - delete m_config; - KateGlobal::self()->deregisterDocument (this); -} -//END - -// on-demand view creation -QWidget *KateDocument::widget() -{ - // no singleViewMode -> no widget()... - if (!singleViewMode()) - return 0; - - // does a widget exist already? use it! - if (KTextEditor::Document::widget()) - return KTextEditor::Document::widget(); - - // create and return one... - KTextEditor::View *view = (KTextEditor::View*)createView(0); - insertChildClient( view ); - setWidget( view ); - return view; -} - -//BEGIN KTextEditor::Document stuff - -KTextEditor::View *KateDocument::createView( QWidget *parent ) -{ - KateView* newView = new KateView( this, parent); - if ( m_fileChangedDialogsActivated ) - connect( newView, SIGNAL(focusIn( KTextEditor::View * )), this, SLOT(slotModifiedOnDisk()) ); - - emit viewCreated (this, newView); - - return newView; -} - -const QList &KateDocument::views () const -{ - return m_textEditViews; -} - -KTextEditor::Editor *KateDocument::editor () -{ - return KateGlobal::self(); -} - -KTextEditor::Range KateDocument::rangeOnLine(KTextEditor::Range range, int line) const -{ - int col1 = const_cast(this)->toVirtualColumn(range.start()); - int col2 = const_cast(this)->toVirtualColumn(range.end()); - - Kate::TextLine tl = const_cast(this)->kateTextLine(line); - col1 = tl->fromVirtualColumn(col1, config()->tabWidth()); - col2 = tl->fromVirtualColumn(col2, config()->tabWidth()); - - return KTextEditor::Range(line, col1, line, col2); -} - -//BEGIN KTextEditor::EditInterface stuff - -QString KateDocument::text() const -{ - return m_buffer->text (); -} - -QString KateDocument::text( const KTextEditor::Range& range, bool blockwise ) const -{ - if (!range.isValid()) { - kWarning() << k_funcinfo << "Text requested for invalid range" << range; - return QString(); - } - - QString s; - - if (range.start().line() == range.end().line()) - { - if (range.start().column() > range.end().column()) - return QString (); - - Kate::TextLine textLine = m_buffer->plainLine(range.start().line()); - - if ( !textLine ) - return QString (); - - return textLine->string(range.start().column(), range.end().column()-range.start().column()); - } - else - { - - for (int i = range.start().line(); (i <= range.end().line()) && (i < m_buffer->count()); ++i) - { - Kate::TextLine textLine = m_buffer->plainLine(i); - - if ( !blockwise ) - { - if (i == range.start().line()) - s.append (textLine->string(range.start().column(), textLine->length()-range.start().column())); - else if (i == range.end().line()) - s.append (textLine->string(0, range.end().column())); - else - s.append (textLine->string()); - } - else - { - KTextEditor::Range subRange = rangeOnLine(range, i); - s.append(textLine->string(subRange.start().column(), subRange.columnWidth())); - } - - if ( i < range.end().line() ) - s.append(QChar::fromAscii('\n')); - } - } - - return s; -} - -QChar KateDocument::character( const KTextEditor::Cursor & position ) const -{ - Kate::TextLine textLine = m_buffer->plainLine(position.line()); - - if ( !textLine ) - return QChar(); - - if (position.column() >= 0 && position.column() < textLine->string().length()) - return textLine->string().at(position.column()); - - return QChar(); -} - -QStringList KateDocument::textLines( const KTextEditor::Range & range, bool blockwise ) const -{ - QStringList ret; - - if (!range.isValid()) { - kWarning() << k_funcinfo << "Text requested for invalid range" << range; - return ret; - } - - if ( blockwise && (range.start().column() > range.end().column()) ) - return ret; - - if (range.start().line() == range.end().line()) - { - Q_ASSERT(range.start() <= range.end()); - - Kate::TextLine textLine = m_buffer->plainLine(range.start().line()); - - if ( !textLine ) - return ret; - - ret << textLine->string(range.start().column(), range.end().column() - range.start().column()); - } - else - { - for (int i = range.start().line(); (i <= range.end().line()) && (i < m_buffer->count()); ++i) - { - Kate::TextLine textLine = m_buffer->plainLine(i); - - if ( !blockwise ) - { - if (i == range.start().line()) - ret << textLine->string(range.start().column(), textLine->length() - range.start().column()); - else if (i == range.end().line()) - ret << textLine->string(0, range.end().column()); - else - ret << textLine->string(); - } - else - { - KTextEditor::Range subRange = rangeOnLine(range, i); - ret << textLine->string(subRange.start().column(), subRange.columnWidth()); - } - } - } - - return ret; -} - -QString KateDocument::line( int line ) const -{ - Kate::TextLine l = m_buffer->plainLine(line); - - if (!l) - return QString(); - - return l->string(); -} - -bool KateDocument::setText(const QString &s) -{ - if (!isReadWrite()) - return false; - - QList msave; - - foreach (KTextEditor::Mark* mark, m_marks) - msave.append(*mark); - - editStart (); - - // delete the text - clear(); - - // insert the new text - insertText (KTextEditor::Cursor(), s); - - editEnd (); - - foreach (const KTextEditor::Mark& mark, msave) - setMark (mark.line, mark.type); - - return true; -} - -bool KateDocument::setText( const QStringList & text ) -{ - if (!isReadWrite()) - return false; - - QList msave; - - foreach (KTextEditor::Mark* mark, m_marks) - msave.append(*mark); - - editStart (); - - // delete the text - clear(); - - // insert the new text - insertText (KTextEditor::Cursor::start(), text); - - editEnd (); - - foreach (const KTextEditor::Mark& mark, msave) - setMark (mark.line, mark.type); - - return true; -} - -bool KateDocument::clear() -{ - if (!isReadWrite()) - return false; - - foreach (KateView *view, m_views) { - view->clear(); - view->tagAll(); - view->update(); - } - - clearMarks (); - - emit aboutToInvalidateMovingInterfaceContent(this); - m_buffer->invalidateRanges(); - - emit aboutToRemoveText(documentRange()); - - return editRemoveLines(0, lastLine()); -} - -bool KateDocument::insertText( const KTextEditor::Cursor& position, const QString& text, bool block ) -{ - if (!isReadWrite()) - return false; - - if (text.isEmpty()) - return true; - - editStart(); - - int currentLine = position.line(); - int currentLineStart = 0; - int totalLength = text.length(); - int insertColumn = position.column(); - - if (position.line() > lines()) - { - int line = lines(); - while (line != position.line() + totalLength + 1) - { - editInsertLine(line,QString()); - line++; - } - } - - bool replacetabs = ( config()->replaceTabsDyn() ); - int tabWidth = config()->tabWidth(); - - static const QChar newLineChar('\n'); - static const QChar tabChar('\t'); - static const QChar spaceChar(' '); - - int insertColumnExpanded = insertColumn; - Kate::TextLine l = kateTextLine( currentLine ); - if (l) - insertColumnExpanded = l->toVirtualColumn( insertColumn, tabWidth ); - - int pos = 0; - for (; pos < totalLength; pos++) - { - const QChar& ch = text.at(pos); - - if (ch == newLineChar) - { - // Only perform the text insert if there is text to insert - if (currentLineStart < pos) - editInsertText(currentLine, insertColumn, text.mid(currentLineStart, pos - currentLineStart)); - - if ( !block ) - { - editWrapLine(currentLine, insertColumn + pos - currentLineStart); - insertColumn = 0; - } - else - { - if ( currentLine == lastLine() ) - editWrapLine(currentLine , insertColumn + pos - currentLineStart); - insertColumn = position.column(); // tab expansion might change this - } - - currentLine++; - currentLineStart = pos + 1; - l = kateTextLine( currentLine ); - if (l) - insertColumnExpanded = l->toVirtualColumn( insertColumn, tabWidth ); - } - else - { - if ( replacetabs && ch == tabChar ) - { - int spacesRequired = tabWidth - ( (insertColumnExpanded + pos - currentLineStart) % tabWidth ); - editInsertText(currentLine, insertColumn, text.mid(currentLineStart, pos - currentLineStart) + QString(spacesRequired, spaceChar)); - - insertColumn += pos - currentLineStart + spacesRequired; - currentLineStart = pos + 1; - l = kateTextLine( currentLine ); - if (l) - insertColumnExpanded = l->toVirtualColumn( insertColumn, tabWidth ); - } - } - } - - // Only perform the text insert if there is text to insert - if (currentLineStart < pos) - editInsertText(currentLine, insertColumn, text.mid(currentLineStart, pos - currentLineStart)); - - editEnd(); - return true; -} - -bool KateDocument::insertText( const KTextEditor::Cursor & position, const QStringList & textLines, bool block ) -{ - if (!isReadWrite()) - return false; - - // just reuse normal function - return insertText (position, textLines.join ("\n"), block); -} - -bool KateDocument::removeText ( const KTextEditor::Range &_range, bool block ) -{ - KTextEditor::Range range = _range; - - if (!isReadWrite()) - return false; - - // Should now be impossible to trigger with the new Range class - Q_ASSERT( range.start().line() <= range.end().line() ); - - if ( range.start().line() > lastLine() ) - return false; - - if (!block) - emit aboutToRemoveText(range); - - editStart(); - - if ( !block ) - { - if ( range.end().line() > lastLine() ) - { - range.end().setPosition(lastLine()+1, 0); - } - - if (range.onSingleLine()) - { - editRemoveText(range.start().line(), range.start().column(), range.columnWidth()); - } - else - { - int from = range.start().line(); - int to = range.end().line(); - - // remove last line - if (to <= lastLine()) - editRemoveText(to, 0, range.end().column()); - - // editRemoveLines() will be called on first line (to remove bookmark) - if (range.start().column() == 0 && from > 0) - --from; - - // remove middle lines - editRemoveLines(from+1, to-1); - - // remove first line if not already removed by editRemoveLines() - if (range.start().column() > 0 || range.start().line() == 0) { - editRemoveText(from, range.start().column(), m_buffer->plainLine(from)->length() - range.start().column()); - editUnWrapLine(from); - } - } - } // if ( ! block ) - else - { - int startLine = qMax(0, range.start().line()); - int vc1 = toVirtualColumn(range.start()); - int vc2 = toVirtualColumn(range.end()); - for (int line = qMin(range.end().line(), lastLine()); line >= startLine; --line) { - Kate::TextLine tl = const_cast(this)->kateTextLine(line); - int col1 = tl->fromVirtualColumn(vc1, config()->tabWidth()); - int col2 = tl->fromVirtualColumn(vc2, config()->tabWidth()); - editRemoveText(line, qMin(col1, col2), qAbs(col2 - col1)); - } - } - - editEnd (); - return true; -} - -bool KateDocument::insertLine( int l, const QString &str ) -{ - if (!isReadWrite()) - return false; - - if (l < 0 || l > lines()) - return false; - - return editInsertLine (l, str); -} - -bool KateDocument::insertLines( int line, const QStringList & text ) -{ - if (!isReadWrite()) - return false; - - if (line < 0 || line > lines()) - return false; - - bool success = true; - foreach (const QString &string, text) - success &= editInsertLine (line++, string); - - return success; -} - -bool KateDocument::removeLine( int line ) -{ - if (!isReadWrite()) - return false; - - if (line < 0 || line > lastLine()) - return false; - - return editRemoveLine (line); -} - -int KateDocument::totalCharacters() const -{ - int l = 0; - - for (int i = 0; i < m_buffer->count(); ++i) - { - Kate::TextLine line = m_buffer->plainLine(i); - - if (line) - l += line->length(); - } - - return l; -} - -int KateDocument::lines() const -{ - return m_buffer->count(); -} - -int KateDocument::numVisLines() const -{ - return m_buffer->countVisible (); -} - -int KateDocument::lineLength ( int line ) const -{ - if (line < 0 || line > lastLine()) - return -1; - - Kate::TextLine l = m_buffer->plainLine(line); - - if (!l) - return -1; - - return l->length(); -} -//END - -//BEGIN KTextEditor::EditInterface internal stuff -// -// Starts an edit session with (or without) undo, update of view disabled during session -// -void KateDocument::editStart () -{ - editSessionNumber++; - - if (editSessionNumber > 1) - return; - - editIsRunning = true; - - m_undoManager->editStart(); - - foreach(KateView *view,m_views) - view->editStart (); - - m_buffer->editStart (); -} - -// -// End edit session and update Views -// -void KateDocument::editEnd () -{ - if (editSessionNumber == 0) { - Q_ASSERT(0); - return; - } - - // wrap the new/changed text, if something really changed! - if (m_buffer->editChanged() && (editSessionNumber == 1)) - if (m_undoManager->isActive() && config()->wordWrap()) - wrapText (m_buffer->editTagStart(), m_buffer->editTagEnd()); - - editSessionNumber--; - - if (editSessionNumber > 0) - return; - - // end buffer edit, will trigger hl update - // this will cause some possible adjustment of tagline start/end - m_buffer->editEnd (); - - m_undoManager->editEnd(); - - // edit end for all views !!!!!!!!! - foreach(KateView *view, m_views) - view->editEnd (m_buffer->editTagStart(), m_buffer->editTagEnd(), m_buffer->editTagFrom()); - - if (m_buffer->editChanged()) { - setModified(true); - emit textChanged (this); - } - - editIsRunning = false; -} - -void KateDocument::pushEditState () -{ - editStateStack.push(editSessionNumber); -} - -void KateDocument::popEditState () -{ - if (editStateStack.isEmpty()) return; - - int count = editStateStack.pop() - editSessionNumber; - while (count < 0) { ++count; editEnd(); } - while (count > 0) { --count; editStart(); } -} - -void KateDocument::inputMethodStart() -{ - m_undoManager->inputMethodStart(); -} - -void KateDocument::inputMethodEnd() -{ - m_undoManager->inputMethodEnd(); -} - -bool KateDocument::wrapText(int startLine, int endLine) -{ - if (startLine < 0 || endLine < 0) - return false; - - if (!isReadWrite()) - return false; - - int col = config()->wordWrapAt(); - - if (col == 0) - return false; - - editStart (); - - for (int line = startLine; (line <= endLine) && (line < lines()); line++) - { - Kate::TextLine l = kateTextLine(line); - - if (!l) - return false; - - kDebug (13020) << "try wrap line: " << line; - - if (l->virtualLength(m_buffer->tabWidth()) > col) - { - Kate::TextLine nextl = kateTextLine(line+1); - - kDebug (13020) << "do wrap line: " << line; - - int eolPosition = l->length()-1; - - // take tabs into account here, too - int x = 0; - const QString & t = l->string(); - int z2 = 0; - for ( ; z2 < l->length(); z2++) - { - static const QChar tabChar('\t'); - if (t.at(z2) == tabChar) - x += m_buffer->tabWidth() - (x % m_buffer->tabWidth()); - else - x++; - - if (x > col) - break; - } - - int searchStart = qMin (z2, l->length()-1); - - // If where we are wrapping is an end of line and is a space we don't - // want to wrap there - if (searchStart == eolPosition && t.at(searchStart).isSpace()) - searchStart--; - - // Scan backwards looking for a place to break the line - // We are not interested in breaking at the first char - // of the line (if it is a space), but we are at the second - // anders: if we can't find a space, try breaking on a word - // boundary, using KateHighlight::canBreakAt(). - // This could be a priority (setting) in the hl/filetype/document - int z = 0; - int nw = 0; // alternative position, a non word character - for (z=searchStart; z > 0; z--) - { - if (t.at(z).isSpace()) break; - if ( ! nw && highlight()->canBreakAt( t.at(z) , l->attribute(z) ) ) - nw = z; - } - - bool removeTrailingSpace = false; - if (z > 0) - { - // So why don't we just remove the trailing space right away? - // Well, the (view's) cursor may be directly in front of that space - // (user typing text before the last word on the line), and if that - // happens, the cursor would be moved to the next line, which is not - // what we want (bug #106261) - z++; - removeTrailingSpace = true; - } - else - { - // There was no space to break at so break at a nonword character if - // found, or at the wrapcolumn ( that needs be configurable ) - // Don't try and add any white space for the break - if ( nw && nw < col ) nw++; // break on the right side of the character - z = nw ? nw : col; - } - - if (nextl && !nextl->isAutoWrapped()) - { - editWrapLine (line, z, true); - editMarkLineAutoWrapped (line+1, true); - - endLine++; - } - else - { - if (nextl && (nextl->length() > 0) && !nextl->at(0).isSpace() && ((l->length() < 1) || !l->at(l->length()-1).isSpace())) - editInsertText (line+1, 0, QString (" ")); - - bool newLineAdded = false; - editWrapLine (line, z, false, &newLineAdded); - - editMarkLineAutoWrapped (line+1, true); - - endLine++; - } - - if (removeTrailingSpace) { - // cu space - editRemoveText (line, z - 1, 1); - } - } - } - - editEnd (); - - return true; -} - -bool KateDocument::editInsertText ( int line, int col, const QString &s ) -{ - if (line < 0 || col < 0) - return false; - - if (!isReadWrite()) - return false; - - Kate::TextLine l = kateTextLine(line); - - if (!l) - return false; - - // nothing to do, do nothing! - if (s.isEmpty()) - return true; - - editStart (); - - QString s2 = s; - int col2 = col; - if (col2 > l->length()) { - s2 = QString(col2 - l->length(), QLatin1Char(' ')) + s; - col2 = l->length(); - } - - m_undoManager->slotTextInserted(line, col2, s2); - - // insert text into line - m_buffer->insertText (KTextEditor::Cursor (line, col2), s2); - - emit KTextEditor::Document::textInserted(this, KTextEditor::Range(line, col2, line, col2 + s2.length())); - - editEnd(); - - return true; -} - -bool KateDocument::editRemoveText ( int line, int col, int len ) -{ - if (line < 0 || col < 0 || len < 0) - return false; - - if (!isReadWrite()) - return false; - - Kate::TextLine l = kateTextLine(line); - - if (!l) - return false; - - // nothing to do, do nothing! - if (len == 0) - return true; - - // wrong column - if (col >= l->text().size()) - return false; - - editStart (); - - QString oldText = l->string().mid(col, len); - - m_undoManager->slotTextRemoved(line, col, oldText); - - // remove text from line - m_buffer->removeText (KTextEditor::Range (KTextEditor::Cursor (line, col), KTextEditor::Cursor (line, col+len))); - - removeTrailingSpace( line ); - - emit KTextEditor::Document::textRemoved(this, KTextEditor::Range(line, col, line, col + len)); - emit KTextEditor::Document::textRemoved(this, KTextEditor::Range(line, col, line, col + len), oldText); - - editEnd (); - - return true; -} - -bool KateDocument::editMarkLineAutoWrapped ( int line, bool autowrapped ) -{ - if (line < 0) - return false; - - if (!isReadWrite()) - return false; - - Kate::TextLine l = kateTextLine(line); - - if (!l) - return false; - - editStart (); - - m_undoManager->slotMarkLineAutoWrapped(line, autowrapped); - - l->setAutoWrapped (autowrapped); - - editEnd (); - - return true; -} - -bool KateDocument::editWrapLine ( int line, int col, bool newLine, bool *newLineAdded) -{ - if (line < 0 || col < 0) - return false; - - if (!isReadWrite()) - return false; - - Kate::TextLine l = kateTextLine(line); - - if (!l) - return false; - - editStart (); - - Kate::TextLine nextLine = kateTextLine(line+1); - - int pos = l->length() - col; - - if (pos < 0) - pos = 0; - - m_undoManager->slotLineWrapped(line, col, pos, (!nextLine || newLine)); - - if (!nextLine || newLine) - { - m_buffer->wrapLine (KTextEditor::Cursor (line, col)); - - QList list; - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - { - if( i.value()->line >= line ) - { - if ((col == 0) || (i.value()->line > line)) - list.append( i.value() ); - } - } - - for( int i=0; i < list.size(); ++i ) - m_marks.take( list.at(i)->line ); - - for( int i=0; i < list.size(); ++i ) - { - list.at(i)->line++; - m_marks.insert( list.at(i)->line, list.at(i) ); - } - - if( !list.isEmpty() ) - emit marksChanged( this ); - - // yes, we added a new line ! - if (newLineAdded) - (*newLineAdded) = true; - } - else - { - m_buffer->wrapLine (KTextEditor::Cursor (line, col)); - m_buffer->unwrapLine (line + 2); - - // no, no new line added ! - if (newLineAdded) - (*newLineAdded) = false; - } - - emit KTextEditor::Document::textInserted(this, KTextEditor::Range(line, col, line+1, pos)); - - editEnd (); - - return true; -} - -bool KateDocument::editUnWrapLine ( int line, bool removeLine, int length ) -{ - if (line < 0 || length < 0) - return false; - - if (!isReadWrite()) - return false; - - Kate::TextLine l = kateTextLine(line); - Kate::TextLine nextLine = kateTextLine(line+1); - - if (!l || !nextLine) - return false; - - editStart (); - - int col = l->length (); - - m_undoManager->slotLineUnWrapped(line, col, length, removeLine); - - if (removeLine) - { - m_buffer->unwrapLine (line+1); - } - else - { - m_buffer->insertText (KTextEditor::Cursor (line, col), nextLine->string().left((nextLine->length() < length) ? nextLine->length() : length)); - m_buffer->removeText (KTextEditor::Range (KTextEditor::Cursor (line + 1, 0), KTextEditor::Cursor (line + 1, (nextLine->length() < length) ? nextLine->length() : length))); - } - - QList list; - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - { - if( i.value()->line >= line+1 ) - list.append( i.value() ); - - if ( i.value()->line == line+1 ) - { - KTextEditor::Mark* mark = m_marks.take( line ); - - if (mark) - { - i.value()->type |= mark->type; - } - } - } - - for( int i=0; i < list.size(); ++i ) - m_marks.take( list.at(i)->line ); - - for( int i=0; i < list.size(); ++i ) - { - list.at(i)->line--; - m_marks.insert( list.at(i)->line, list.at(i) ); - } - - if( !list.isEmpty() ) - emit marksChanged( this ); - - emit KTextEditor::Document::textRemoved(this, KTextEditor::Range(line, col, line+1, 0)); - emit KTextEditor::Document::textRemoved(this, KTextEditor::Range(line, col, line+1, 0), "\n"); - - editEnd (); - - return true; -} - -bool KateDocument::editInsertLine ( int line, const QString &s ) -{ - if (line < 0) - return false; - - if (!isReadWrite()) - return false; - - if ( line > lines() ) - return false; - - editStart (); - - m_undoManager->slotLineInserted(line, s); - - removeTrailingSpace( line ); // old line - - // wrap line - if (line > 0) { - Kate::TextLine previousLine = m_buffer->line (line-1); - m_buffer->wrapLine (KTextEditor::Cursor (line-1, previousLine->text().size())); - } else { - m_buffer->wrapLine (KTextEditor::Cursor (0, 0)); - } - - // insert text - m_buffer->insertText (KTextEditor::Cursor (line, 0), s); - - removeTrailingSpace( line ); // new line - - Kate::TextLine tl = m_buffer->line (line); - - QList list; - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - { - if( i.value()->line >= line ) - list.append( i.value() ); - } - - for( int i=0; i < list.size(); ++i ) - m_marks.take( list.at(i)->line ); - - for( int i=0; i < list.size(); ++i ) - { - list.at(i)->line++; - m_marks.insert( list.at(i)->line, list.at(i) ); - } - - if( !list.isEmpty() ) - emit marksChanged( this ); - - KTextEditor::Range rangeInserted(line, 0, line, tl->length()); - - if (line) { - Kate::TextLine prevLine = plainKateTextLine(line - 1); - rangeInserted.start().setPosition(line - 1, prevLine->length()); - } else { - rangeInserted.end().setPosition(line + 1, 0); - } - - emit KTextEditor::Document::textInserted(this, rangeInserted); - - editEnd (); - - return true; -} - -bool KateDocument::editRemoveLine ( int line ) -{ - return editRemoveLines(line, line); -} - -bool KateDocument::editRemoveLines ( int from, int to ) -{ - if (to < from || from < 0 || to > lastLine()) - return false; - - if (!isReadWrite()) - return false; - - if (lines() == 1) - return editRemoveText(0, 0, kateTextLine(0)->length()); - - editStart(); - QStringList oldText; - - for (int line = to; line >= from; line--) { - KateLineInfo info; - lineInfo(&info, line); - if (info.startsInVisibleBlock) - foldingTree()->toggleRegionVisibility(line); - } - - for (int line = to; line >= from; line--) { - Kate::TextLine tl = m_buffer->line (line); - oldText << this->line(line); - m_undoManager->slotLineRemoved(line, this->line(line)); - - m_buffer->removeText (KTextEditor::Range (KTextEditor::Cursor (line, 0), KTextEditor::Cursor (line, tl->text().size()))); - if (line + 1 <= lastLine()) - m_buffer->unwrapLine (line+1); - else if (line != 0) - m_buffer->unwrapLine (line); - } - - QList rmark; - QList list; - - foreach (KTextEditor::Mark* mark, m_marks) { - int line = mark->line; - if (line > to) - list << line; - else if (line >= from) - rmark << line; - } - - foreach (int line, rmark) - delete m_marks.take(line); - - foreach (int line, list) - { - KTextEditor::Mark* mark = m_marks.take(line); - mark->line -= to - from + 1; - m_marks.insert(mark->line, mark); - } - - if (!list.isEmpty()) - emit marksChanged(this); - - KTextEditor::Range rangeRemoved(from, 0, to + 1, 0); - - if (to == lastLine() + to - from + 1) { - rangeRemoved.end().setPosition(to, oldText.first().length()); - if (from > 0) { - Kate::TextLine prevLine = plainKateTextLine(from - 1); - rangeRemoved.start().setPosition(from - 1, prevLine->length()); - } - } - - emit KTextEditor::Document::textRemoved(this, rangeRemoved); - emit KTextEditor::Document::textRemoved(this, rangeRemoved, oldText.join("\n")); - - editEnd(); - - return true; -} -//END - -//BEGIN KTextEditor::UndoInterface stuff - -uint KateDocument::undoCount () const -{ - return m_undoManager->undoCount (); -} - -uint KateDocument::redoCount () const -{ - return m_undoManager->redoCount (); -} - -void KateDocument::undo() -{ - m_undoManager->undo(); -} - -void KateDocument::redo() -{ - m_undoManager->redo(); -} -//END - -//BEGIN KTextEditor::SearchInterface stuff -QVector KateDocument::searchText( - const KTextEditor::Range & range, - const QString & pattern, - const KTextEditor::Search::SearchOptions options) -{ - // TODO - // * support BlockInputRange - // * support DotMatchesNewline - - const bool escapeSequences = options.testFlag(KTextEditor::Search::EscapeSequences); - const bool regexMode = options.testFlag(KTextEditor::Search::Regex); - const bool backwards = options.testFlag(KTextEditor::Search::Backwards); - const bool wholeWords = options.testFlag(KTextEditor::Search::WholeWords); - const Qt::CaseSensitivity caseSensitivity = options.testFlag(KTextEditor::Search::CaseInsensitive) ? Qt::CaseInsensitive : Qt::CaseSensitive; - - if (regexMode) - { - // regexp search - // escape sequences are supported by definition - KateRegExpSearch searcher(this, caseSensitivity); - return searcher.search(pattern, range, backwards); - } - - if (escapeSequences) - { - // escaped search - KatePlainTextSearch searcher(this, caseSensitivity, wholeWords); - KTextEditor::Range match = searcher.search(KateRegExpSearch::escapePlaintext(pattern), range, backwards); - - QVector result; - result.append(match); - return result; - } - - // plaintext search - KatePlainTextSearch searcher(this, caseSensitivity, wholeWords); - KTextEditor::Range match = searcher.search(pattern, range, backwards); - - QVector result; - result.append(match); - return result; -} - - - -KTextEditor::Search::SearchOptions KateDocument::supportedSearchOptions() const -{ - KTextEditor::Search::SearchOptions supported(KTextEditor::Search::Default); - supported |= KTextEditor::Search::Regex; - supported |= KTextEditor::Search::CaseInsensitive; - supported |= KTextEditor::Search::Backwards; -// supported |= KTextEditor::Search::BlockInputRange; - supported |= KTextEditor::Search::EscapeSequences; - supported |= KTextEditor::Search::WholeWords; -// supported |= KTextEditor::Search::DotMatchesNewline; - return supported; -} -//END - -QWidget * KateDocument::dialogParent() -{ - QWidget *w=widget(); - - if(!w) - { - w=activeView(); - - if(!w) - w=QApplication::activeWindow(); - } - - return w; -} - -//BEGIN KTextEditor::HighlightingInterface stuff -bool KateDocument::setMode (const QString &name) -{ - updateFileType (name); - return true; -} - -QString KateDocument::mode () const -{ - return m_fileType; -} - -QStringList KateDocument::modes () const -{ - QStringList m; - - const QList &modeList = KateGlobal::self()->modeManager()->list(); - foreach(KateFileType* type, modeList) - m << type->name; - - return m; -} - -bool KateDocument::setHighlightingMode (const QString &name) -{ - m_buffer->setHighlight (KateHlManager::self()->nameFind(name)); - return true; -} - -QString KateDocument::highlightingMode () const -{ - return highlight()->name (); -} - -QStringList KateDocument::highlightingModes () const -{ - QStringList hls; - - for (int i = 0; i < KateHlManager::self()->highlights(); ++i) - hls << KateHlManager::self()->hlName (i); - - return hls; -} - -QString KateDocument::highlightingModeSection( int index ) const -{ - return KateHlManager::self()->hlSection( index ); -} - -QString KateDocument::modeSection( int index ) const -{ - return KateGlobal::self()->modeManager()->list().at( index )->section; -} - -void KateDocument::bufferHlChanged () -{ - // update all views - makeAttribs(false); - - // deactivate indenter if necessary - m_indenter->checkRequiredStyle(); - - emit highlightingModeChanged(this); -} - - -void KateDocument::setDontChangeHlOnSave() -{ - hlSetByUser = true; -} - -void KateDocument::bomSetByUser() -{ - m_bomSetByUser=true; -} -//END - -//BEGIN KTextEditor::SessionConfigInterface and KTextEditor::ParameterizedSessionConfigInterface stuff -void KateDocument::readSessionConfig(const KConfigGroup &kconfig) -{ - readParameterizedSessionConfig(kconfig, SkipNone); -} - -void KateDocument::readParameterizedSessionConfig(const KConfigGroup &kconfig, - unsigned long configParameters) -{ - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipEncoding)) { - // get the encoding - QString tmpenc=kconfig.readEntry("Encoding"); - if (!tmpenc.isEmpty() && (tmpenc != encoding())) - setEncoding(tmpenc); - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipUrl)) { - // restore the url - KUrl url (kconfig.readEntry("URL")); - - // open the file if url valid - if (!url.isEmpty() && url.isValid()) - openUrl (url); - else completed(); //perhaps this should be emitted at the end of this function - } - else { - completed(); //perhaps this should be emitted at the end of this function - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipMode)) { - // restore the filetype - updateFileType (kconfig.readEntry("Mode", "Normal")); - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipHighlighting)) { - // restore the hl stuff - m_buffer->setHighlight(KateHlManager::self()->nameFind(kconfig.readEntry("Highlighting"))); - } - - // read only mode - // todo: what does m_bReadOnly mean? - setReadWrite(kconfig.readEntry("ReadWrite", true)); - - // indent mode - config()->setIndentationMode( kconfig.readEntry("Indentation Mode", config()->indentationMode() ) ); - - // Restore Bookmarks - const QList marks = kconfig.readEntry("Bookmarks", QList()); - for( int i = 0; i < marks.count(); i++ ) - addMark( marks.at(i), KateDocument::markType01 ); -} - -void KateDocument::writeSessionConfig(KConfigGroup &kconfig) -{ - writeParameterizedSessionConfig(kconfig, SkipNone); -} - -void KateDocument::writeParameterizedSessionConfig(KConfigGroup &kconfig, - unsigned long configParameters) -{ - if ( this->url().isLocalFile() ) { - const QString path = this->url().toLocalFile(); - if ( KGlobal::dirs()->relativeLocation( "tmp", path ) != path ) { - return; // inside tmp resource, do not save - } - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipUrl)) { - // save url - kconfig.writeEntry("URL", this->url().prettyUrl() ); - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipEncoding)) { - // save encoding - kconfig.writeEntry("Encoding",encoding()); - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipMode)) { - // save file type - kconfig.writeEntry("Mode", m_fileType); - } - - if(!(configParameters & KTextEditor::ParameterizedSessionConfigInterface::SkipHighlighting)) { - // save hl - kconfig.writeEntry("Highlighting", highlight()->name()); - } - - // read only mode - kconfig.writeEntry("ReadWrite", isReadWrite()); - - // indent mode - kconfig.writeEntry("Indentation Mode", config()->indentationMode() ); - - // Save Bookmarks - QList marks; - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - if (i.value()->type & KTextEditor::MarkInterface::markType01) - marks << i.value()->line; - - kconfig.writeEntry( "Bookmarks", marks ); -} - -//END KTextEditor::SessionConfigInterface and KTextEditor::ParameterizedSessionConfigInterface stuff - -uint KateDocument::mark( int line ) -{ - KTextEditor::Mark* m = m_marks.value(line); - if( !m ) - return 0; - - return m->type; -} - -void KateDocument::setMark( int line, uint markType ) -{ - clearMark( line ); - addMark( line, markType ); -} - -void KateDocument::clearMark( int line ) -{ - if( line > lastLine() ) - return; - - if( !m_marks.value(line) ) - return; - - KTextEditor::Mark* mark = m_marks.take( line ); - emit markChanged( this, *mark, MarkRemoved ); - emit marksChanged( this ); - delete mark; - tagLines( line, line ); - repaintViews(true); -} - -void KateDocument::addMark( int line, uint markType ) -{ - if( line > lastLine()) - return; - - if( markType == 0 ) - return; - - if( KTextEditor::Mark* mark = m_marks.value(line) ) { - // Remove bits already set - markType &= ~mark->type; - - if( markType == 0 ) - return; - - // Add bits - mark->type |= markType; - } else { - KTextEditor::Mark *mark = new KTextEditor::Mark; - mark->line = line; - mark->type = markType; - m_marks.insert( line, mark ); - } - - // Emit with a mark having only the types added. - KTextEditor::Mark temp; - temp.line = line; - temp.type = markType; - emit markChanged( this, temp, MarkAdded ); - - emit marksChanged( this ); - tagLines( line, line ); - repaintViews(true); -} - -void KateDocument::removeMark( int line, uint markType ) -{ - if( line > lastLine() ) - return; - - KTextEditor::Mark* mark = m_marks.value(line); - - if( !mark ) - return; - - // Remove bits not set - markType &= mark->type; - - if( markType == 0 ) - return; - - // Subtract bits - mark->type &= ~markType; - - // Emit with a mark having only the types removed. - KTextEditor::Mark temp; - temp.line = line; - temp.type = markType; - emit markChanged( this, temp, MarkRemoved ); - - if( mark->type == 0 ) - m_marks.remove( line ); - - emit marksChanged( this ); - tagLines( line, line ); - repaintViews(true); -} - -const QHash &KateDocument::marks() -{ - return m_marks; -} - -void KateDocument::requestMarkTooltip( int line, QPoint position ) -{ - KTextEditor::Mark* mark = m_marks.value(line); - if(!mark) - return; - - bool handled = false; - emit markToolTipRequested( this, *mark, position, handled ); -} - -bool KateDocument::handleMarkClick( int line ) -{ - KTextEditor::Mark* mark = m_marks.value(line); - if(!mark) - return false; - - bool handled = false; - emit markClicked( this, *mark, handled ); - - return handled; -} - -bool KateDocument::handleMarkContextMenu( int line, QPoint position ) -{ - KTextEditor::Mark* mark = m_marks.value(line); - if(!mark) - return false; - - bool handled = false; - - emit markContextMenuRequested( this, *mark, position, handled ); - - return handled; -} - -void KateDocument::clearMarks() -{ - while (!m_marks.isEmpty()) - { - QHash::iterator it = m_marks.begin(); - KTextEditor::Mark mark = *it.value(); - delete it.value(); - m_marks.erase (it); - - emit markChanged( this, mark, MarkRemoved ); - tagLines( mark.line, mark.line ); - } - - m_marks.clear(); - - emit marksChanged( this ); - repaintViews(true); -} - -void KateDocument::setMarkPixmap( MarkInterface::MarkTypes type, const QPixmap& pixmap ) -{ - m_markPixmaps.insert( type, pixmap ); -} - -void KateDocument::setMarkDescription( MarkInterface::MarkTypes type, const QString& description ) -{ - m_markDescriptions.insert( type, description ); -} - -QPixmap KateDocument::markPixmap( MarkInterface::MarkTypes type ) const -{ - return m_markPixmaps.value(type, QPixmap()); -} - -QColor KateDocument::markColor( MarkInterface::MarkTypes type ) const -{ - uint reserved = (0x1 << KTextEditor::MarkInterface::reservedMarkersCount()) - 1; - if ((uint)type >= (uint)markType01 && (uint)type <= reserved) { - return KateRendererConfig::global()->lineMarkerColor(type); - } else { - return QColor(); - } -} - -QString KateDocument::markDescription( MarkInterface::MarkTypes type ) const -{ - return m_markDescriptions.value(type, QString()); -} - -void KateDocument::setEditableMarks( uint markMask ) -{ - m_editableMarks = markMask; -} - -uint KateDocument::editableMarks() const -{ - return m_editableMarks; -} -//END - -//BEGIN KTextEditor::PrintInterface stuff -bool KateDocument::printDialog () -{ - return KatePrinter::print (this); -} - -bool KateDocument::print () -{ - return KatePrinter::print (this); -} -//END - -//BEGIN KTextEditor::DocumentInfoInterface (### unfinished) -QString KateDocument::mimeType() -{ - KMimeType::Ptr result = KMimeType::defaultMimeTypePtr(); - - // if the document has a URL, try KMimeType::findByURL - if ( ! this->url().isEmpty() ) - result = KMimeType::findByUrl( this->url() ); - - else if ( this->url().isEmpty() || ! this->url().isLocalFile() ) - result = mimeTypeForContent(); - - return result->name(); -} - -KMimeType::Ptr KateDocument::mimeTypeForContent() -{ - QByteArray buf (1024,'\0'); - uint bufpos = 0; - - for (int i=0; i < lines(); ++i) - { - QString line = this->line( i ); - uint len = line.length() + 1; - - if (bufpos + len > 1024) - len = 1024 - bufpos; - - QString ld (line + QChar::fromAscii('\n')); - buf.replace(bufpos,len,ld.toLatin1()); //memcpy(buf.data() + bufpos, ld.toLatin1().constData(), len); - - bufpos += len; - - if (bufpos >= 1024) - break; - } - buf.resize( bufpos ); - - int accuracy = 0; - KMimeType::Ptr mt = KMimeType::findByContent(buf, &accuracy); - return mt ? mt : KMimeType::defaultMimeTypePtr(); -} -//END KTextEditor::DocumentInfoInterface - - -//BEGIN KParts::ReadWrite stuff -bool KateDocument::openFile() -{ - /** - * we are about to invalidate all cursors/ranges/.. => m_buffer->openFile will do so - */ - emit aboutToInvalidateMovingInterfaceContent (this); - - // no open errors until now... - setOpeningError(false); - - // add new m_file to dirwatch - activateDirWatch (); - - // - // mime type magic to get encoding right - // - QString mimeType = arguments().mimeType(); - int pos = mimeType.indexOf(';'); - if (pos != -1) - setEncoding (mimeType.mid(pos+1)); - - // do we have success ? - emit KTextEditor::Document::textRemoved(this, documentRange()); - emit KTextEditor::Document::textRemoved(this, documentRange(), m_buffer->text()); - - bool success = m_buffer->openFile (localFilePath()); - - // disable view updates - foreach (KateView * view, m_views) - view->setUpdatesEnabled (false); - - // - // yeah, success - // - if (success) - { - // update file type - updateFileType (KateGlobal::self()->modeManager()->fileType (this)); - - // read dir config (if possible and wanted) - readDirConfig (); - - // read vars - readVariables(); - - // remove trailing space - // NOTE: wait until now because the config or variables might tell us not to do this! - m_buffer->setRemoveTrailingSpaces (config()->removeSpaces()); - if ( m_buffer->removeTrailingSpaces() ) - { - int n = lines(); - while (n--) - removeTrailingSpace (n); - } - - // update the md5 digest - createDigest( m_digest ); - - if (!m_postLoadFilterChecks.isEmpty()) - { - LoadSaveFilterCheckPlugins *lscps=loadSaveFilterCheckPlugins(); - foreach(const QString& checkplugin, m_postLoadFilterChecks) - { - lscps->postLoadFilter(checkplugin,this); - } - } - } - - // - // update views - // - foreach (KateView * view, m_views) - { - // This is needed here because inserting the text moves the view's start position (it is a MovingCursor) - view->setCursorPosition (KTextEditor::Cursor()); - view->setUpdatesEnabled (true); - view->updateView (true); - } - - // emit all signals about new text after view updates - emit KTextEditor::Document::textInserted(this, documentRange()); - - // Inform that the text has changed (required as we're not inside the usual editStart/End stuff) - emit textChanged (this); - - if (!m_reloading) - { - // - // emit the signal we need for example for kate app - // - emit documentUrlChanged (this); - - // - // set doc name, dummy value as arg, don't need it - // - setDocName (QString()); - } - // - // to houston, we are not modified - // - if (m_modOnHd) - { - m_modOnHd = false; - m_modOnHdReason = OnDiskUnmodified; - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } - - // - // display errors - // - QWidget *parentWidget(dialogParent()); - - if (!suppressOpeningErrorDialogs()) - { - if (!success) - KMessageBox::error (parentWidget, i18n ("The file %1 could not be loaded, as it was not possible to read from it.\n\nCheck if you have read access to this file.", this->url().pathOrUrl())); - } - - if (!success) { - setOpeningError(true); - setOpeningErrorMessage(i18n ("The file %1 could not be loaded, as it was not possible to read from it.\n\nCheck if you have read access to this file.",this->url().pathOrUrl())); - } - - // warn: broken encoding - if (m_buffer->brokenEncoding()) - { - // this file can't be saved again without killing it - setReadWrite( false ); - - if (!suppressOpeningErrorDialogs()) - KMessageBox::information (parentWidget - , i18n ("The file %1 was opened with %2 encoding but contained invalid characters." - " It is set to read-only mode, as saving might destroy its content." - " Either reopen the file with the correct encoding chosen or enable the read-write mode again in the menu to be able to edit it.", this->url().pathOrUrl(), - QString (m_buffer->textCodec()->name ())) - , i18n ("Broken Encoding") - , "Broken Encoding Warning"); - setOpeningError(true); - setOpeningErrorMessage(i18n ("The file %1 was opened with %2 encoding but contained invalid characters." - " It is set to read-only mode, as saving might destroy its content." - " Either reopen the file with the correct encoding chosen or enable the read-write mode again in the menu to be able to edit it.", this->url().pathOrUrl(), QString (m_buffer->textCodec()->name ()))); - } - - // - // return the success - // - return success; -} - -bool KateDocument::saveFile() -{ - QWidget *parentWidget(dialogParent()); - - // - // warn -> try to save binary file!!!!!!! - // -#if 0 - if (m_buffer->binary() && (KMessageBox::warningContinueCancel (parentWidget - , i18n ("The file %1 is a binary, saving it will result in a corrupt file.", url().pathOrUrl()) - , i18n ("Trying to Save Binary File") - , KGuiItem(i18n("Save Nevertheless")) - , KStandardGuiItem::cancel(), "Binary File Save Warning") != KMessageBox::Continue)) - return false; -#endif - - // some warnings, if file was changed by the outside! - if ( !url().isEmpty() ) - { - if (m_fileChangedDialogsActivated && m_modOnHd) - { - QString str = reasonedMOHString() + "\n\n"; - - if (!isModified()) - { - if (KMessageBox::warningContinueCancel(parentWidget, - str + i18n("Do you really want to save this unmodified file? You could overwrite changed data in the file on disk."),i18n("Trying to Save Unmodified File"),KGuiItem(i18n("Save Nevertheless"))) != KMessageBox::Continue) - return false; - } - else - { - if (KMessageBox::warningContinueCancel(parentWidget, - str + i18n("Do you really want to save this file? Both your open file and the file on disk were changed. There could be some data lost."),i18n("Possible Data Loss"),KGuiItem(i18n("Save Nevertheless"))) != KMessageBox::Continue) - return false; - } - } - } - - // - // can we encode it if we want to save it ? - // - if (!m_buffer->canEncode () - && (KMessageBox::warningContinueCancel(parentWidget, - i18n("The selected encoding cannot encode every unicode character in this document. Do you really want to save it? There could be some data lost."),i18n("Possible Data Loss"),KGuiItem(i18n("Save Nevertheless"))) != KMessageBox::Continue)) - { - return false; - } - - // - // try to create backup file.. - // - - // local file or not is here the question - bool l ( url().isLocalFile() ); - - // does the user want any backup, if not, not our problem? - if ( ( l && config()->backupFlags() & KateDocumentConfig::LocalFiles ) - || ( ! l && config()->backupFlags() & KateDocumentConfig::RemoteFiles ) ) - { - KUrl u( url() ); - u.setFileName( config()->backupPrefix() + url().fileName() + config()->backupSuffix() ); - - kDebug( 13020 ) << "backup src file name: " << url(); - kDebug( 13020 ) << "backup dst file name: " << u; - - // handle the backup... - bool backupSuccess = false; - - // local file mode, no kio - if (u.isLocalFile ()) - { - if (QFile::exists (url().toLocalFile ())) - { - // first: check if backupFile is already there, if true, unlink it - QFile backupFile (u.toLocalFile ()); - if (backupFile.exists()) backupFile.remove (); - - backupSuccess = QFile::copy (url().toLocalFile (), u.toLocalFile ()); - } - else - backupSuccess = true; - } - else // remote file mode, kio - { - QWidget *w = widget (); - if (!w && !m_views.isEmpty ()) - w = m_views.first(); - - // get the right permissions, start with safe default - mode_t perms = 0600; - KIO::UDSEntry fentry; - if (KIO::NetAccess::stat (url(), fentry, QApplication::activeWindow())) - { - kDebug( 13020 ) << "stating succesfull: " << url(); - KFileItem item (fentry, url()); - perms = item.permissions(); - - // do a evil copy which will overwrite target if possible - KIO::FileCopyJob *job = KIO::file_copy ( url(), u, -1, KIO::Overwrite ); - backupSuccess = KIO::NetAccess::synchronousRun(job, w); - } - else - backupSuccess = true; - } - - // backup has failed, ask user how to proceed - if (!backupSuccess && (KMessageBox::warningContinueCancel (parentWidget - , i18n ("For file %1 no backup copy could be created before saving." - " If an error occurs while saving, you might lose the data of this file." - " A reason could be that the media you write to is full or the directory of the file is read-only for you.", url().pathOrUrl()) - , i18n ("Failed to create backup copy.") - , KGuiItem(i18n("Try to Save Nevertheless")) - , KStandardGuiItem::cancel(), "Backup Failed Warning") != KMessageBox::Continue)) - { - return false; - } - } - - // update file type - updateFileType (KateGlobal::self()->modeManager()->fileType (this)); - - if (!m_preSavePostDialogFilterChecks.isEmpty()) - { - LoadSaveFilterCheckPlugins *lscps=loadSaveFilterCheckPlugins(); - foreach(const QString& checkplugin, m_preSavePostDialogFilterChecks) - { - if (lscps->preSavePostDialogFilterCheck(checkplugin,this,parentWidget)==false) - return false; - } - } - - // remember the oldpath... - QString oldPath = m_dirWatchFile; - - // remove file from dirwatch - deactivateDirWatch (); - - // - // try to save - // - if (!m_buffer->saveFile (localFilePath())) - { - // add m_file again to dirwatch - activateDirWatch (oldPath); - - KMessageBox::error (parentWidget, i18n ("The document could not be saved, as it was not possible to write to %1.\n\nCheck that you have write access to this file or that enough disk space is available.", this->url().pathOrUrl())); - - return false; - } - - // update the md5 digest - createDigest( m_digest ); - - // add m_file again to dirwatch - activateDirWatch (); - - // update file type -// updateFileType (KateGlobal::self()->modeManager()->fileType (this)); - - // read dir config (if possible and wanted) - if ( url().isLocalFile()) - { - QFileInfo fo (oldPath), fn (m_dirWatchFile); - - if (fo.path() != fn.path()) - readDirConfig(); - } - - // read our vars - readVariables(); - - // - // we are not modified - // - if (m_modOnHd) - { - m_modOnHd = false; - m_modOnHdReason = OnDiskUnmodified; - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } - - // update document name... - setDocName( QString() ); - - // url may have changed... - emit documentUrlChanged (this); - - m_savingToUrl=true; - - // (dominik) mark last undo group as not mergeable, otherwise the next - // edit action might be merged and undo will never stop at the saved state - m_undoManager->undoSafePoint(); - - // - // return success - // - return true; -} - -void KateDocument::readDirConfig () -{ - int depth = config()->searchDirConfigDepth (); - - if (this->url().isLocalFile() && (depth > -1)) - { - QString currentDir = QFileInfo (localFilePath()).absolutePath(); - - // only search as deep as specified or not at all ;) - while (depth > -1) - { - //kDebug (13020) << "search for config file in path: " << currentDir; - - // try to open config file in this dir - QFile f (currentDir + "/.kateconfig"); - - if (f.open (QIODevice::ReadOnly)) - { - QTextStream stream (&f); - - uint linesRead = 0; - QString line = stream.readLine(); - while ((linesRead < 32) && !line.isNull()) - { - readVariableLine( line ); - - line = stream.readLine(); - - linesRead++; - } - - break; - } - - QString newDir = QFileInfo (currentDir).absolutePath(); - - // bail out on looping (for example reached /) - if (currentDir == newDir) - break; - - currentDir = newDir; - --depth; - } - } -} - -void KateDocument::activateDirWatch (const QString &useFileName) -{ - QString fileToUse = useFileName; - if (fileToUse.isEmpty()) - fileToUse = localFilePath(); - - // same file as we are monitoring, return - if (fileToUse == m_dirWatchFile) - return; - - // remove the old watched file - deactivateDirWatch (); - - // add new file if needed - if (url().isLocalFile() && !fileToUse.isEmpty()) - { - KateGlobal::self()->dirWatch ()->addFile (fileToUse); - m_dirWatchFile = fileToUse; - } -} - -void KateDocument::deactivateDirWatch () -{ - if (!m_dirWatchFile.isEmpty()) - KateGlobal::self()->dirWatch ()->removeFile (m_dirWatchFile); - - m_dirWatchFile.clear(); -} - -bool KateDocument::closeUrl() -{ - // - // file mod on hd - // - if ( !m_reloading && !url().isEmpty() ) - { - if (m_fileChangedDialogsActivated && m_modOnHd) - { - QWidget *parentWidget(dialogParent()); - - if (!(KMessageBox::warningContinueCancel( - parentWidget, - reasonedMOHString() + "\n\n" + i18n("Do you really want to continue to close this file? Data loss may occur."), - i18n("Possible Data Loss"), KGuiItem(i18n("Close Nevertheless")), KStandardGuiItem::cancel(), - QString("kate_close_modonhd_%1").arg( m_modOnHdReason ) ) == KMessageBox::Continue)) - return false; - } - } - - // - // first call the normal kparts implementation - // - if (!KParts::ReadWritePart::closeUrl ()) - return false; - - // Tell the world that we're about to go ahead with the close - if (!m_reloading) - emit aboutToClose(this); - - /** - * we are about to invalidate all cursors/ranges/.. => m_buffer->clear will do so - */ - emit aboutToInvalidateMovingInterfaceContent (this); - - // remove file from dirwatch - deactivateDirWatch (); - - // - // empty url + fileName - // - setUrl(KUrl()); - setLocalFilePath(QString()); - - // we are not modified - if (m_modOnHd) - { - m_modOnHd = false; - m_modOnHdReason = OnDiskUnmodified; - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } - - emit KTextEditor::Document::textRemoved(this, documentRange()); - emit KTextEditor::Document::textRemoved(this, documentRange(), m_buffer->text()); - - { - // remove all marks - clearMarks (); - - // clear the buffer - m_buffer->clear(); - - // clear undo/redo history - m_undoManager->clearUndo(); - m_undoManager->clearRedo(); - } - - // no, we are no longer modified - setModified(false); - - // we have no longer any hl - m_buffer->setHighlight(0); - - // update all our views - foreach (KateView * view, m_views ) - { - view->clearSelection(); // fix bug #118588 - view->clear(); - } - - if (!m_reloading) - { - // uh, fileName changed - emit documentUrlChanged (this); - - // update doc name - setDocName (QString()); - } - - // purge swap file - m_swapfile->fileClosed (); - - // success - return true; -} - -bool KateDocument::haveRecovery() const -{ - return m_swapfile->shouldRecover(); -} - -void KateDocument::doRecovery() -{ - m_swapfile->recover(); -} - -void KateDocument::discardRecovery() -{ - m_swapfile->discard(); -} - -void KateDocument::setReadWrite( bool rw ) -{ - if (isReadWrite() != rw) - { - KParts::ReadWritePart::setReadWrite (rw); - - foreach( KateView* view, m_views) - { - view->slotUpdateUndo(); - view->slotReadWriteChanged (); - } - } -} - -void KateDocument::setModified(bool m) { - - if (isModified() != m) { - KParts::ReadWritePart::setModified (m); - - foreach( KateView* view,m_views) - { - view->slotUpdateUndo(); - } - - emit modifiedChanged (this); - } - - m_undoManager->setModified (m); -} -//END - -//BEGIN Kate specific stuff ;) - -void KateDocument::makeAttribs(bool needInvalidate) -{ - foreach(KateView *view,m_views) - view->renderer()->updateAttributes (); - - if (needInvalidate) - m_buffer->invalidateHighlighting(); - - foreach(KateView *view,m_views) - { - view->tagAll(); - view->updateView (true); - } -} - -// the attributes of a hl have changed, update -void KateDocument::internalHlChanged() -{ - makeAttribs(); -} - -void KateDocument::addView(KTextEditor::View *view) { - if (!view) - return; - - m_views.append( static_cast(view) ); - m_textEditViews.append( view ); - - // apply the view & renderer vars from the file type - if (!m_fileType.isEmpty()) - readVariableLine(KateGlobal::self()->modeManager()->fileType(m_fileType).varLine, true); - - // apply the view & renderer vars from the file - readVariables (true); - - setActiveView(view); -} - -void KateDocument::removeView(KTextEditor::View *view) { - if (!view) - return; - - if (activeView() == view) - setActiveView(0L); - - m_views.removeAll( (KateView *) view ); - m_textEditViews.removeAll( view ); -} - -void KateDocument::setActiveView(KTextEditor::View* view) -{ - if ( m_activeView == view ) - return; - - m_activeView = (KateView*)view; -} - -bool KateDocument::ownedView(KateView *view) { - // do we own the given view? - return (m_views.contains(view)); -} - -uint KateDocument::toVirtualColumn( const KTextEditor::Cursor& cursor ) -{ - Kate::TextLine textLine = m_buffer->plainLine(cursor.line()); - - if (textLine) - return textLine->toVirtualColumn(cursor.column(), config()->tabWidth()); - else - return 0; -} - -bool KateDocument::typeChars ( KateView *view, const QString &chars ) -{ - Kate::TextLine textLine = m_buffer->plainLine(view->cursorPosition().line ()); - - if (!textLine) - return false; - - bool bracketInserted = false; - QString buf; - QChar c; - foreach(const QChar& ch, chars) - { - if (ch.isPrint() || ch == QChar::fromAscii('\t')) - { - buf.append (ch); - - if (!bracketInserted && (config()->autoBrackets())) - { - QChar end_ch; - - if (ch == '(') { end_ch = ')'; } - if (ch == '[') { end_ch = ']'; } - if (ch == '{') { end_ch = '}'; } - if (ch == '"') { end_ch = '"'; } - if (ch == '\'') { end_ch = '\''; } - - if (!end_ch.isNull()) { - bracketInserted = true; - - if (view->selection()) { - buf.append(view->selectionText()); - } - - buf.append(end_ch); - } - } - } - } - - if (buf.isEmpty()) - return false; - - editStart (); - - if (!view->config()->persistentSelection() && view->selection() ) - view->removeSelectedText(); - - KTextEditor::Cursor oldCur (view->cursorPosition()); - - if (config()->ovr() - || (view->viInputMode() && view->getViInputModeManager()->getCurrentViMode() == ReplaceMode)) { - - KTextEditor::Range r = KTextEditor::Range(view->cursorPosition(), qMin(buf.length(), - textLine->length() - view->cursorPosition().column())); - - // replace mode needs to know what was removed so it can be restored with backspace - if (view->viInputMode() && view->getViInputModeManager()->getCurrentViMode() == ReplaceMode - && oldCur.column() < line( view->cursorPosition().line() ).length() ) { - QChar removed = line( view->cursorPosition().line() ).at( r.start().column() ); - view->getViInputModeManager()->getViReplaceMode()->overwrittenChar( removed ); - } - - removeText(r); - } - - insertText(view->cursorPosition(), buf); - if (bracketInserted) - view->setCursorPositionInternal (view->cursorPosition() - KTextEditor::Cursor(0,1)); - - KTextEditor::Cursor b(view->cursorPosition()); - m_indenter->userTypedChar (view, b, c); - - editEnd (); - - view->slotTextInserted (view, oldCur, chars); - return true; -} - -void KateDocument::newLine( KateView *v ) -{ - editStart(); - - if( !v->config()->persistentSelection() && v->selection() ) - v->removeSelectedText(); - - // query cursor position - KTextEditor::Cursor c = v->cursorPosition(); - - if (c.line() > (int)lastLine()) - c.setLine(lastLine()); - - if (c.line() < 0) - c.setLine(0); - - uint ln = c.line(); - - Kate::TextLine textLine = plainKateTextLine(ln); - - if (c.column() > (int)textLine->length()) - c.setColumn(textLine->length()); - - // first: wrap line - editWrapLine (c.line(), c.column()); - - // second: indent the new line, if needed... - m_indenter->userTypedChar(v, v->cursorPosition(), '\n'); - - removeTrailingSpace( ln ); - - editEnd(); -} - -void KateDocument::transpose( const KTextEditor::Cursor& cursor) -{ - Kate::TextLine textLine = m_buffer->plainLine(cursor.line()); - - if (!textLine || (textLine->length() < 2)) - return; - - uint col = cursor.column(); - - if (col > 0) - col--; - - if ((textLine->length() - col) < 2) - return; - - uint line = cursor.line(); - QString s; - - //clever swap code if first character on the line swap right&left - //otherwise left & right - s.append (textLine->at(col+1)); - s.append (textLine->at(col)); - //do the swap - - // do it right, never ever manipulate a textline - editStart (); - editRemoveText (line, col, 2); - editInsertText (line, col, s); - editEnd (); -} - -void KateDocument::backspace( KateView *view, const KTextEditor::Cursor& c ) -{ - if ( !view->config()->persistentSelection() && view->selection() ) { - view->removeSelectedText(); - return; - } - - uint col = qMax( c.column(), 0 ); - uint line = qMax( c.line(), 0 ); - - if ((col == 0) && (line == 0)) - return; - - int complement = 0; - if (col > 0) - { - if (config()->autoBrackets()) - { - // if inside empty (), {}, [], '', "" delete both - Kate::TextLine tl = m_buffer->plainLine(line); - if(!tl) return; - QChar prevChar = tl->at(col-1); - QChar nextChar = tl->at(col); - - if ( (prevChar == '"' && nextChar == '"') || - (prevChar == '\'' && nextChar == '\'') || - (prevChar == '(' && nextChar == ')') || - (prevChar == '[' && nextChar == ']') || - (prevChar == '{' && nextChar == '}') ) - { - complement = 1; - } - } - if (!(config()->backspaceIndents())) - { - // ordinary backspace - //c.cursor.col--; - removeText(KTextEditor::Range(line, col-1, line, col+complement)); - } - else - { - // backspace indents: erase to next indent position - Kate::TextLine textLine = m_buffer->plainLine(line); - - // don't forget this check!!!! really!!!! - if (!textLine) - return; - - int colX = textLine->toVirtualColumn(col, config()->tabWidth()); - int pos = textLine->firstChar(); - if (pos > 0) - pos = textLine->toVirtualColumn(pos, config()->tabWidth()); - - if (pos < 0 || pos >= (int)colX) - { - // only spaces on left side of cursor - indent( KTextEditor::Range( line, 0, line, 0), -1); - } - else - removeText(KTextEditor::Range(line, col-1, line, col+complement)); - } - } - else - { - // col == 0: wrap to previous line - if (line >= 1) - { - Kate::TextLine textLine = m_buffer->plainLine(line-1); - - // don't forget this check!!!! really!!!! - if (!textLine) - return; - - if (config()->wordWrap() && textLine->endsWith(QLatin1String(" "))) - { - // gg: in hard wordwrap mode, backspace must also eat the trailing space - removeText (KTextEditor::Range(line-1, textLine->length()-1, line, 0)); - } - else - removeText (KTextEditor::Range(line-1, textLine->length(), line, 0)); - } - } -} - -void KateDocument::del( KateView *view, const KTextEditor::Cursor& c ) -{ - if ( !view->config()->persistentSelection() && view->selection() ) { - view->removeSelectedText(); - return; - } - - if( c.column() < (int) m_buffer->plainLine(c.line())->length()) - { - removeText(KTextEditor::Range(c, 1)); - } - else if ( c.line() < lastLine() ) - { - removeText(KTextEditor::Range(c.line(), c.column(), c.line()+1, 0)); - } -} - -void KateDocument::paste ( KateView* view, QClipboard::Mode mode ) -{ - QString s = QApplication::clipboard()->text(mode); - - if (s.isEmpty()) - return; - - int lines = s.count (QChar::fromAscii ('\n')); - - m_undoManager->undoSafePoint(); - - editStart (); - - KTextEditor::Cursor pos = view->cursorPosition(); - if (!view->config()->persistentSelection() && view->selection()) { - pos = view->selectionRange().start(); - if (view->blockSelection()) - pos = rangeOnLine(view->selectionRange(), pos.line()).start(); - view->removeSelectedText(); - } - - if (config()->ovr()) { - QStringList pasteLines = s.split(QLatin1Char('\n')); - - if (!view->blockSelectionMode()) { - int endColumn = (pasteLines.count() == 1 ? pos.column() : 0) + pasteLines.last().length(); - removeText(KTextEditor::Range(pos, - pos.line()+pasteLines.count()-1, endColumn)); - } else { - int maxi = qMin(pos.line() + pasteLines.count(), this->lines()); - - for (int i = pos.line(); i < maxi; ++i) { - int pasteLength = pasteLines.at(i-pos.line()).length(); - removeText(KTextEditor::Range(i, pos.column(), - i, qMin(pasteLength + pos.column(), lineLength(i)))); - } - } - } - - - blockRemoveTrailingSpaces(true); - insertText(pos, s, view->blockSelectionMode()); - blockRemoveTrailingSpaces(false); - - for (int i = pos.line(); i < pos.line() + lines; ++i) - removeTrailingSpace(i); - - editEnd(); - - // move cursor right for block select, as the user is moved right internal - // even in that case, but user expects other behavior in block selection - // mode ! - if (view->blockSelectionMode()) - view->setCursorPositionInternal(view->cursorPosition() + KTextEditor::Cursor(lines, 0)); - - if (config()->indentPastedText()) - { - KTextEditor::Range range = KTextEditor::Range(KTextEditor::Cursor(pos.line(), 0), - KTextEditor::Cursor(pos.line() + lines, 0)); - - int start = view->selectionRange().start().line(); - const int end = view->selectionRange().end().line(); - - editStart(); - - blockRemoveTrailingSpaces(true); - m_indenter->indent(view, range); - blockRemoveTrailingSpaces(false); - - for (; start <= end; ++start) - removeTrailingSpace(start); - - editEnd(); - } - - if (!view->blockSelectionMode()) - emit charactersSemiInteractivelyInserted (pos, s); - m_undoManager->undoSafePoint(); -} - -void KateDocument::indent (KTextEditor::Range range, int change) -{ - // dominik: if there is a selection, iterate afterwards over all lines and - // remove trailing spaces - int start = range.start().line(); - const int end = range.end().line(); - - editStart(); - blockRemoveTrailingSpaces(true); - m_indenter->changeIndent(range, change); - blockRemoveTrailingSpaces(false); - - if (range.numberOfLines() > 1) { - for (; start <= end; ++start) - removeTrailingSpace(start); - } - editEnd(); -} - -void KateDocument::align(KateView *view, const KTextEditor::Range &range) -{ - editStart(); - - blockRemoveTrailingSpaces(true); - m_indenter->indent(view, range); - blockRemoveTrailingSpaces(false); - - for (int start = range.start().line(); start <= range.end().line(); ++start) { - removeTrailingSpace(start); - } - - editEnd(); -} - -void KateDocument::insertTab( KateView *, const KTextEditor::Cursor& c ) -{ - if (!isReadWrite()) - return; - - editStart(); - editInsertText(c.line(), c.column(), QChar('\t')); - editEnd(); -} - -/* - Remove a given string at the beginning - of the current line. -*/ -bool KateDocument::removeStringFromBeginning(int line, const QString &str) -{ - Kate::TextLine textline = m_buffer->plainLine(line); - - KTextEditor::Cursor cursor (line, 0); - bool there = textline->startsWith(str); - - if (!there) - { - cursor.setColumn(textline->firstChar()); - there = textline->matchesAt(cursor.column(), str); - } - - if (there) - { - // Remove some chars - removeText (KTextEditor::Range(cursor, str.length())); - } - - return there; -} - -/* - Remove a given string at the end - of the current line. -*/ -bool KateDocument::removeStringFromEnd(int line, const QString &str) -{ - Kate::TextLine textline = m_buffer->plainLine(line); - - KTextEditor::Cursor cursor (line, 0); - bool there = textline->endsWith(str); - - if (there) - { - cursor.setColumn(textline->length() - str.length()); - } - else - { - cursor.setColumn(textline->lastChar() - str.length() + 1); - there = textline->matchesAt(cursor.column(), str); - } - - if (there) - { - // Remove some chars - removeText (KTextEditor::Range(cursor, str.length())); - } - - return there; -} - -/* - Add to the current line a comment line mark at the beginning. -*/ -void KateDocument::addStartLineCommentToSingleLine( int line, int attrib ) -{ - QString commentLineMark = highlight()->getCommentSingleLineStart(attrib); - int pos = -1; - - if (highlight()->getCommentSingleLinePosition(attrib) == KateHighlighting::CSLPosColumn0) - { - pos = 0; - commentLineMark += ' '; - } else { - const Kate::TextLine l = kateTextLine(line); - pos = l->firstChar(); - } - - if (pos >= 0) - insertText (KTextEditor::Cursor(line, pos), commentLineMark); -} - -/* - Remove from the current line a comment line mark at - the beginning if there is one. -*/ -bool KateDocument::removeStartLineCommentFromSingleLine( int line, int attrib ) -{ - const QString shortCommentMark = highlight()->getCommentSingleLineStart( attrib ); - const QString longCommentMark = shortCommentMark + ' '; - - editStart(); - - // Try to remove the long comment mark first - bool removed = (removeStringFromBeginning(line, longCommentMark) - || removeStringFromBeginning(line, shortCommentMark)); - - editEnd(); - - return removed; -} - -/* - Add to the current line a start comment mark at the - beginning and a stop comment mark at the end. -*/ -void KateDocument::addStartStopCommentToSingleLine( int line, int attrib ) -{ - const QString startCommentMark = highlight()->getCommentStart( attrib ) + ' '; - const QString stopCommentMark = ' ' + highlight()->getCommentEnd( attrib ); - - editStart(); - - // Add the start comment mark - insertText (KTextEditor::Cursor(line, 0), startCommentMark); - - // Go to the end of the line - const int col = m_buffer->plainLine(line)->length(); - - // Add the stop comment mark - insertText (KTextEditor::Cursor(line, col), stopCommentMark); - - editEnd(); -} - -/* - Remove from the current line a start comment mark at - the beginning and a stop comment mark at the end. -*/ -bool KateDocument::removeStartStopCommentFromSingleLine( int line, int attrib ) -{ - QString shortStartCommentMark = highlight()->getCommentStart( attrib ); - QString longStartCommentMark = shortStartCommentMark + ' '; - QString shortStopCommentMark = highlight()->getCommentEnd( attrib ); - QString longStopCommentMark = ' ' + shortStopCommentMark; - - editStart(); - - // TODO "that's a bad idea, can lead to stray endings, FIXME" - - // Try to remove the long start comment mark first - bool removedStart = (removeStringFromBeginning(line, longStartCommentMark) - || removeStringFromBeginning(line, shortStartCommentMark)); - - bool removedStop = false; - if (removedStart) - { - // Try to remove the long stop comment mark first - removedStop = (removeStringFromEnd(line, longStopCommentMark) - || removeStringFromEnd(line, shortStopCommentMark)); - } - - editEnd(); - - return (removedStart || removedStop); -} - -/* - Add to the current selection a start comment mark at the beginning - and a stop comment mark at the end. -*/ -void KateDocument::addStartStopCommentToSelection( KateView *view, int attrib ) -{ - const QString startComment = highlight()->getCommentStart( attrib ); - const QString endComment = highlight()->getCommentEnd( attrib ); - - KTextEditor::Range range = view->selectionRange(); - - if ((range.end().column() == 0) && (range.end().line() > 0)) - range.end().setPosition(range.end().line() - 1, lineLength(range.end().line() - 1)); - - editStart(); - - if (!view->blockSelection()) { - insertText(range.end(), endComment); - insertText(range.start(), startComment); - } else { - for (int line = range.start().line(); line <= range.end().line(); line++ ) { - KTextEditor::Range subRange = rangeOnLine(range, line); - insertText(subRange.end(), endComment); - insertText(subRange.start(), startComment); - } - } - - editEnd (); - // selection automatically updated (MovingRange) -} - -/* - Add to the current selection a comment line mark at the beginning of each line. -*/ -void KateDocument::addStartLineCommentToSelection( KateView *view, int attrib ) -{ - const QString commentLineMark = highlight()->getCommentSingleLineStart( attrib ) + ' '; - - int sl = view->selectionRange().start().line(); - int el = view->selectionRange().end().line(); - - // if end of selection is in column 0 in last line, omit the last line - if ((view->selectionRange().end().column() == 0) && (el > 0)) - { - el--; - } - - editStart(); - - // For each line of the selection - for (int z = el; z >= sl; z--) { - //insertText (z, 0, commentLineMark); - addStartLineCommentToSingleLine(z, attrib ); - } - - editEnd (); - // selection automatically updated (MovingRange) -} - -bool KateDocument::nextNonSpaceCharPos(int &line, int &col) -{ - for(; line < (int)m_buffer->count(); line++) { - Kate::TextLine textLine = m_buffer->plainLine(line); - - if (!textLine) - break; - - col = textLine->nextNonSpaceChar(col); - if(col != -1) - return true; // Next non-space char found - col = 0; - } - // No non-space char found - line = -1; - col = -1; - return false; -} - -bool KateDocument::previousNonSpaceCharPos(int &line, int &col) -{ - while(true) - { - Kate::TextLine textLine = m_buffer->plainLine(line); - - if (!textLine) - break; - - col = textLine->previousNonSpaceChar(col); - if(col != -1) return true; - if(line == 0) return false; - --line; - col = textLine->length(); - } - // No non-space char found - line = -1; - col = -1; - return false; -} - -/* - Remove from the selection a start comment mark at - the beginning and a stop comment mark at the end. -*/ -bool KateDocument::removeStartStopCommentFromSelection( KateView *view, int attrib ) -{ - const QString startComment = highlight()->getCommentStart( attrib ); - const QString endComment = highlight()->getCommentEnd( attrib ); - - int sl = qMax (0, view->selectionRange().start().line()); - int el = qMin (view->selectionRange().end().line(), lastLine()); - int sc = view->selectionRange().start().column(); - int ec = view->selectionRange().end().column(); - - // The selection ends on the char before selectEnd - if (ec != 0) { - --ec; - } else if (el > 0) { - --el; - ec = m_buffer->plainLine(el)->length() - 1; - } - - const int startCommentLen = startComment.length(); - const int endCommentLen = endComment.length(); - - // had this been perl or sed: s/^\s*$startComment(.+?)$endComment\s*/$2/ - - bool remove = nextNonSpaceCharPos(sl, sc) - && m_buffer->plainLine(sl)->matchesAt(sc, startComment) - && previousNonSpaceCharPos(el, ec) - && ( (ec - endCommentLen + 1) >= 0 ) - && m_buffer->plainLine(el)->matchesAt(ec - endCommentLen + 1, endComment); - - if (remove) { - editStart(); - - removeText (KTextEditor::Range(el, ec - endCommentLen + 1, el, ec + 1)); - removeText (KTextEditor::Range(sl, sc, sl, sc + startCommentLen)); - - editEnd (); - // selection automatically updated (MovingRange) - } - - return remove; -} - -bool KateDocument::removeStartStopCommentFromRegion(const KTextEditor::Cursor &start,const KTextEditor::Cursor &end,int attrib) -{ - const QString startComment = highlight()->getCommentStart( attrib ); - const QString endComment = highlight()->getCommentEnd( attrib ); - const int startCommentLen = startComment.length(); - const int endCommentLen = endComment.length(); - - const bool remove = m_buffer->plainLine(start.line())->matchesAt(start.column(), startComment) - && m_buffer->plainLine(end.line())->matchesAt(end.column() - endCommentLen , endComment); - if (remove) { - editStart(); - removeText(KTextEditor::Range(end.line(), end.column() - endCommentLen, end.line(), end.column())); - removeText(KTextEditor::Range(start, startCommentLen)); - editEnd(); - } - return remove; -} - -/* - Remove from the beginning of each line of the - selection a start comment line mark. -*/ -bool KateDocument::removeStartLineCommentFromSelection( KateView *view, int attrib ) -{ - const QString shortCommentMark = highlight()->getCommentSingleLineStart( attrib ); - const QString longCommentMark = shortCommentMark + ' '; - - int sl = view->selectionRange().start().line(); - int el = view->selectionRange().end().line(); - - if ((view->selectionRange().end().column() == 0) && (el > 0)) - { - el--; - } - - bool removed = false; - - editStart(); - - // For each line of the selection - for (int z = el; z >= sl; z--) - { - // Try to remove the long comment mark first - removed = (removeStringFromBeginning(z, longCommentMark) - || removeStringFromBeginning(z, shortCommentMark) - || removed); - } - - editEnd(); - // selection automatically updated (MovingRange) - - return removed; -} - -/* - Comment or uncomment the selection or the current - line if there is no selection. -*/ -void KateDocument::comment( KateView *v, uint line,uint column, int change) -{ - bool hassel = v->selection(); - int l = line; - int c = 0; - - if ( hassel ) - { - l = v->selectionRange().start().line(); - c = v->selectionRange().start().column(); - } - - int startAttrib = 0; - Kate::TextLine ln = kateTextLine( line ); - - if ( c < ln->length() ) - startAttrib = ln->attribute( c ); - else if ( !ln->contextStack().isEmpty() ) - startAttrib = highlight()->attribute( ln->contextStack().last() ); - - bool hasStartLineCommentMark = !(highlight()->getCommentSingleLineStart( startAttrib ).isEmpty()); - bool hasStartStopCommentMark = ( !(highlight()->getCommentStart( startAttrib ).isEmpty()) - && !(highlight()->getCommentEnd( startAttrib ).isEmpty()) ); - - bool removed = false; - - if (change > 0) // comment - { - if ( !hassel ) - { - if ( hasStartLineCommentMark ) - addStartLineCommentToSingleLine( line, startAttrib ); - else if ( hasStartStopCommentMark ) - addStartStopCommentToSingleLine( line, startAttrib ); - } - else - { - // anders: prefer single line comment to avoid nesting probs - // If the selection starts after first char in the first line - // or ends before the last char of the last line, we may use - // multiline comment markers. - // TODO We should try to detect nesting. - // - if selection ends at col 0, most likely she wanted that - // line ignored - if ( hasStartStopCommentMark && - ( !hasStartLineCommentMark || ( - ( v->selectionRange().start().column() > m_buffer->plainLine( v->selectionRange().start().line() )->firstChar() ) || - ( v->selectionRange().end().column() < ((int)m_buffer->plainLine( v->selectionRange().end().line() )->length()) ) - ) ) ) - addStartStopCommentToSelection( v, startAttrib ); - else if ( hasStartLineCommentMark ) - addStartLineCommentToSelection( v, startAttrib ); - } - } - else // uncomment - { - if ( !hassel ) - { - removed = ( hasStartLineCommentMark - && removeStartLineCommentFromSingleLine( line, startAttrib ) ) - || ( hasStartStopCommentMark - && removeStartStopCommentFromSingleLine( line, startAttrib ) ); - if ((!removed) && foldingTree()) { - kDebug(13020)<<"easy approach for uncommenting did not work, trying harder (folding tree)"; - int commentRegion=(highlight()->commentRegion(startAttrib)); - if (commentRegion){ - KateCodeFoldingNode *n=foldingTree()->findNodeForPosition(line,column); - if (n) { - KTextEditor::Cursor start,end; - if ((n->nodeType()==(int)commentRegion) && n->getBegin(foldingTree(), &start) && n->getEnd(foldingTree(), &end)) { - kDebug(13020)<<"Enclosing region found:"<nodeType()<<" region needed: "<selection() ) - { - editStart(); - - // remember cursor - KTextEditor::Cursor cursor = c; - - // cache the selection and cursor, so we can be sure to restore. - KTextEditor::Range selection = v->selectionRange(); - - KTextEditor::Range range(selection.start(), 0); - while ( range.start().line() <= selection.end().line() ) - { - int start = 0; - int end = lineLength( range.start().line() ); - - if (range.start().line() == selection.start().line() || v->blockSelectionMode()) - start = selection.start().column(); - - if (range.start().line() == selection.end().line() || v->blockSelectionMode()) - end = selection.end().column(); - - if ( start > end ) - { - int swapCol = start; - start = end; - end = swapCol; - } - range.start().setColumn( start ); - range.end().setColumn( end ); - - QString s = text( range ); - QString old = s; - - if ( t == Uppercase ) - s = s.toUpper(); - else if ( t == Lowercase ) - s = s.toLower(); - else // Capitalize - { - Kate::TextLine l = m_buffer->plainLine( range.start().line() ); - int p ( 0 ); - while( p < s.length() ) - { - // If bol or the character before is not in a word, up this one: - // 1. if both start and p is 0, upper char. - // 2. if blockselect or first line, and p == 0 and start-1 is not in a word, upper - // 3. if p-1 is not in a word, upper. - if ( ( ! range.start().column() && ! p ) || - ( ( range.start().line() == selection.start().line() || v->blockSelectionMode() ) && - ! p && ! highlight()->isInWord( l->at( range.start().column() - 1 )) ) || - ( p && ! highlight()->isInWord( s.at( p-1 ) ) ) - ) { - s[p] = s.at(p).toUpper(); - } - p++; - } - } - - if ( s != old ) - { - removeText( range ); - insertText( range.start(), s ); - } - - range.setBothLines(range.start().line() + 1); - } - - editEnd(); - - // restore selection & cursor - v->setSelection( selection ); - v->setCursorPosition( c ); - - } else { // no selection - editStart(); - - // get cursor - KTextEditor::Cursor cursor = c; - - QString old = text( KTextEditor::Range(cursor, 1) ); - QString s; - switch ( t ) { - case Uppercase: - s = old.toUpper(); - break; - case Lowercase: - s = old.toLower(); - break; - case Capitalize: - { - Kate::TextLine l = m_buffer->plainLine( cursor.line() ); - while ( cursor.column() > 0 && highlight()->isInWord( l->at( cursor.column() - 1 ), l->attribute( cursor.column() - 1 ) ) ) - cursor.setColumn(cursor.column() - 1); - old = text( KTextEditor::Range(cursor, 1) ); - s = old.toUpper(); - } - break; - default: - break; - } - - removeText( KTextEditor::Range(cursor, 1) ); - insertText( cursor, s ); - - editEnd(); - } - -} - -void KateDocument::joinLines( uint first, uint last ) -{ -// if ( first == last ) last += 1; - editStart(); - int line( first ); - while ( first < last ) - { - // Normalize the whitespace in the joined lines by making sure there's - // always exactly one space between the joined lines - // This cannot be done in editUnwrapLine, because we do NOT want this - // behavior when deleting from the start of a line, just when explicitly - // calling the join command - Kate::TextLine l = kateTextLine( line ); - Kate::TextLine tl = kateTextLine( line + 1 ); - - if ( !l || !tl ) - { - editEnd(); - return; - } - - int pos = tl->firstChar(); - if ( pos >= 0 ) - { - if (pos != 0) - editRemoveText( line + 1, 0, pos ); - if ( !( l->length() == 0 || l->at( l->length() - 1 ).isSpace() ) ) - editInsertText( line + 1, 0, " " ); - } - else - { - // Just remove the whitespace and let Kate handle the rest - editRemoveText( line + 1, 0, tl->length() ); - } - - editUnWrapLine( line ); - first++; - } - editEnd(); -} - -QString KateDocument::getWord( const KTextEditor::Cursor& cursor ) -{ - int start, end, len; - - Kate::TextLine textLine = m_buffer->plainLine(cursor.line()); - len = textLine->length(); - start = end = cursor.column(); - if (start > len) // Probably because of non-wrapping cursor mode. - return QString(); - - while (start > 0 && highlight()->isInWord(textLine->at(start - 1), textLine->attribute(start - 1))) start--; - while (end < len && highlight()->isInWord(textLine->at(end), textLine->attribute(end))) end++; - len = end - start; - return textLine->string().mid(start, len); -} - -void KateDocument::tagLines(int start, int end) -{ - foreach(KateView *view,m_views) - view->tagLines (start, end, true); -} - -void KateDocument::tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end) -{ - // May need to switch start/end cols if in block selection mode -/* if (blockSelectionMode() && start.column() > end.column()) { - int sc = start.column(); - start.setColumn(end.column()); - end.setColumn(sc); - } -*/ - foreach (KateView* view, m_views) - view->tagLines(start, end, true); -} - -void KateDocument::repaintViews(bool paintOnlyDirty) -{ - foreach(KateView *view,m_views) - view->repaintText(paintOnlyDirty); -} - -inline bool isStartBracket( const QChar& c ) { return c == '{' || c == '[' || c == '('; } -inline bool isEndBracket ( const QChar& c ) { return c == '}' || c == ']' || c == ')'; } -inline bool isBracket ( const QChar& c ) { return isStartBracket( c ) || isEndBracket( c ); } - -/* - Bracket matching uses the following algorithm: - If in overwrite mode, match the bracket currently underneath the cursor. - Otherwise, if the character to the left is a bracket, - match it. Otherwise if the character to the right of the cursor is a - bracket, match it. Otherwise, don't match anything. -*/ -void KateDocument::newBracketMark( const KTextEditor::Cursor& cursor, KTextEditor::Range& bm, int maxLines ) -{ - // search from cursor for brackets - KTextEditor::Range range (cursor, cursor); - - // if match found, remember the range - if( findMatchingBracket( range, maxLines ) ) { - bm = range; - return; - } - - // else, invalidate, if still valid - if (bm.isValid()) - bm = KTextEditor::Range::invalid(); -} - -bool KateDocument::findMatchingBracket( KTextEditor::Range& range, int maxLines ) -{ - Kate::TextLine textLine = m_buffer->plainLine( range.start().line() ); - if( !textLine ) - return false; - - QChar right = textLine->at( range.start().column() ); - QChar left = textLine->at( range.start().column() - 1 ); - QChar bracket; - - if ( config()->ovr() ) { - if( isBracket( right ) ) { - bracket = right; - } else { - return false; - } - } else if ( isBracket( left ) ) { - range.start().setColumn(range.start().column() - 1); - bracket = left; - } else if ( isBracket( right ) ) { - bracket = right; - } else { - return false; - } - - QChar opposite; - - switch( bracket.toAscii() ) { - case '{': opposite = '}'; break; - case '}': opposite = '{'; break; - case '[': opposite = ']'; break; - case ']': opposite = '['; break; - case '(': opposite = ')'; break; - case ')': opposite = '('; break; - default: return false; - } - - const int searchDir = isStartBracket( bracket ) ? 1 : -1; - uint nesting = 0; - - int minLine = qMax( range.start().line() - maxLines, 0 ); - int maxLine = qMin( range.start().line() + maxLines, documentEnd().line() ); - - range.end() = range.start(); - QScopedPointer cursor(newMovingCursor(range.start())); - int validAttr = kateTextLine(cursor->line())->attribute(cursor->column()); - - while( cursor->line() >= minLine && cursor->line() <= maxLine ) { - - if (!cursor->move(searchDir)) - return false; - - if (kateTextLine(cursor->line())->attribute(cursor->column()) == validAttr ) - { - /* Check for match */ - QChar c = character(cursor->toCursor()); - if( c == bracket ) { - nesting++; - } else if( c == opposite ) { - if( nesting == 0 ) { - if (searchDir > 0) // forward - range.end() = cursor->toCursor(); - else - range.start() = cursor->toCursor(); - return true; - } - nesting--; - } - } - } - - return false; -} - -void KateDocument::setDocName (QString name ) -{ - /** - * avoid senseless name changes - */ - if ( name == m_docName ) - return; - - /** - * if name given, use it! - */ - if ( !name.isEmpty() ) { - m_docName = name; - emit documentNameChanged (this); - return; - } - - // if the name is set, and starts with FILENAME, it should not be changed! - if ( ! url().isEmpty() - && (m_docName == url().fileName() || m_docName.startsWith (url().fileName() + " (") ) ) return; - - int count = -1; - - foreach(KateDocument* doc, KateGlobal::self()->kateDocuments()) - { - if ( (doc != this) && (doc->url().fileName() == url().fileName()) ) - if ( doc->m_docNameNumber > count ) - count = doc->m_docNameNumber; - } - - m_docNameNumber = count + 1; - - QString oldName = m_docName; - m_docName = url().fileName(); - - if (m_docName.isEmpty()) - m_docName = i18n ("Untitled"); - - if (m_docNameNumber > 0) - m_docName = QString(m_docName + " (%1)").arg(m_docNameNumber+1); - - /** - * avoid to emit this, if name doesn't change! - */ - if (oldName != m_docName) - emit documentNameChanged (this); -} - -void KateDocument::slotModifiedOnDisk( KTextEditor::View * /*v*/ ) -{ - if ( m_isasking < 0 ) - { - m_isasking = 0; - return; - } - - if ( !m_fileChangedDialogsActivated || m_isasking ) - return; - - if (m_modOnHd && !url().isEmpty()) - { - m_isasking = 1; - - QWidget *parentWidget(dialogParent()); - - KateModOnHdPrompt p( this, m_modOnHdReason, reasonedMOHString(), parentWidget ); - switch ( p.exec() ) - { - case KateModOnHdPrompt::Save: - { - m_modOnHd = false; - KEncodingFileDialog::Result res=KEncodingFileDialog::getSaveUrlAndEncoding(config()->encoding(), - url().url(),QString(),parentWidget,i18n("Save File")); - - kDebug(13020)<<"got "< tmp; - - for (QHash::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) - { - KateDocumentTmpMark m; - - m.line = line (i.value()->line); - m.mark = *i.value(); - - tmp.append (m); - } - - const QString oldMode = mode (); - const bool byUser = m_fileTypeSetByUser; - const QString hl_mode = highlightingMode (); - KTextEditor::View* oldActiveView = activeView(); - - m_storedVariables.clear(); - - // save cursor positions for all views - QVector cursorPositions; - cursorPositions.reserve(m_views.size()); - foreach (KateView *v, m_views) - cursorPositions.append( v->cursorPosition() ); - - m_reloading = true; - KateDocument::openUrl( url() ); - m_reloading = false; - - // restore cursor positions for all views - QLinkedList::iterator it = m_views.begin(); - for(int i = 0; i < m_views.size(); ++i, ++it) { - setActiveView(*it); - (*it)->setCursorPositionInternal( cursorPositions.at(i), m_config->tabWidth(), false ); - if ((*it)->isVisible()) { - (*it)->repaintText(false); - } - } - setActiveView(oldActiveView); - - for (int z=0; z < tmp.size(); z++) - { - if (z < (int)lines()) - { - if (line(tmp.at(z).mark.line) == tmp.at(z).line) - setMark (tmp.at(z).mark.line, tmp.at(z).mark.type); - } - } - - if (byUser) - setMode (oldMode); - setHighlightingMode (hl_mode); - - emit reloaded(this); - - return true; - } - - return false; -} - -bool KateDocument::documentSave() -{ - if( !url().isValid() || !isReadWrite() ) - return documentSaveAs(); - - return save(); -} - -bool KateDocument::documentSaveAs() -{ - QWidget *parentWidget(dialogParent()); - - KEncodingFileDialog::Result res=KEncodingFileDialog::getSaveUrlAndEncoding(config()->encoding(), - url().url(),QString(),parentWidget,i18n("Save File")); - - if( res.URLs.isEmpty() || !checkOverwrite( res.URLs.first(), parentWidget ) ) - return false; - - setEncoding( res.encoding ); - - return saveAs( res.URLs.first() ); -} - -void KateDocument::setWordWrap (bool on) -{ - config()->setWordWrap (on); -} - -bool KateDocument::wordWrap () const -{ - return config()->wordWrap (); -} - -void KateDocument::setWordWrapAt (uint col) -{ - config()->setWordWrapAt (col); -} - -unsigned int KateDocument::wordWrapAt () const -{ - return config()->wordWrapAt (); -} - -void KateDocument::setPageUpDownMovesCursor (bool on) -{ - config()->setPageUpDownMovesCursor (on); -} - -bool KateDocument::pageUpDownMovesCursor () const -{ - return config()->pageUpDownMovesCursor (); -} - -void KateDocument::dumpRegionTree() -{ - m_buffer->foldingTree()->debugDump(); -} -//END - -void KateDocument::lineInfo (KateLineInfo *info, unsigned int line) -{ - m_buffer->lineInfo(info,line); -} - -KateCodeFoldingTree *KateDocument::foldingTree () -{ - return m_buffer->foldingTree(); -} - -bool KateDocument::setEncoding (const QString &e) -{ - return m_config->setEncoding(e); -} - -const QString &KateDocument::encoding() const -{ - return m_config->encoding(); -} - -void KateDocument::updateConfig () -{ - m_undoManager->updateConfig (); - - // switch indenter if needed and update config.... - m_indenter->setMode (m_config->indentationMode()); - m_indenter->updateConfig(); - - // set tab width there, too - m_buffer->setTabWidth (config()->tabWidth()); - - // update all views, does tagAll and updateView... - foreach (KateView * view, m_views) - view->updateDocumentConfig (); - - // update on-the-fly spell checking as spell checking defaults might have changes - if(m_onTheFlyChecker) { - m_onTheFlyChecker->updateConfig(); - } - - emit configChanged(); -} - -//BEGIN Variable reader -// "local variable" feature by anders, 2003 -/* TODO - add config options (how many lines to read, on/off) - add interface for plugins/apps to set/get variables - add view stuff -*/ -QRegExp KateDocument::kvLine = QRegExp("kate:(.*)"); -QRegExp KateDocument::kvLineWildcard = QRegExp("kate-wildcard\\((.*)\\):(.*)"); -QRegExp KateDocument::kvLineMime = QRegExp("kate-mimetype\\((.*)\\):(.*)"); -QRegExp KateDocument::kvVar = QRegExp("([\\w\\-]+)\\s+([^;]+)"); - -void KateDocument::readVariables(bool onlyViewAndRenderer) -{ - if (!onlyViewAndRenderer) - m_config->configStart(); - - // views! - KateView *v; - foreach (v,m_views) - { - v->config()->configStart(); - v->renderer()->config()->configStart(); - } - // read a number of lines in the top/bottom of the document - for (int i=0; i < qMin( 9, lines() ); ++i ) - { - readVariableLine( line( i ), onlyViewAndRenderer ); - } - if ( lines() > 10 ) - { - for ( int i = qMax( 10, lines() - 10); i < lines(); i++ ) - { - readVariableLine( line( i ), onlyViewAndRenderer ); - } - } - - if (!onlyViewAndRenderer) - m_config->configEnd(); - - foreach (v,m_views) - { - v->config()->configEnd(); - v->renderer()->config()->configEnd(); - } -} - -void KateDocument::readVariableLine( QString t, bool onlyViewAndRenderer ) -{ - // simple check first, no regex - // no kate inside, no vars, simple... - if (!t.contains("kate")) - return; - - // found vars, if any - QString s; - - // now, try first the normal ones - if ( kvLine.indexIn( t ) > -1 ) - { - s = kvLine.cap(1); - - kDebug (13020) << "normal variable line kate: matched: " << s; - } - else if (kvLineWildcard.indexIn( t ) > -1) // regex given - { - const QStringList wildcards (kvLineWildcard.cap(1).split (';', QString::SkipEmptyParts)); - const QString nameOfFile = url().fileName(); - - bool found = false; - foreach(const QString& pattern, wildcards) - { - QRegExp wildcard (pattern, Qt::CaseSensitive, QRegExp::Wildcard); - - found = wildcard.exactMatch (nameOfFile); - } - - // nothing usable found... - if (!found) - return; - - s = kvLineWildcard.cap(2); - - kDebug (13020) << "guarded variable line kate-wildcard: matched: " << s; - } - else if (kvLineMime.indexIn( t ) > -1) // mime-type given - { - const QStringList types (kvLineMime.cap(1).split (';', QString::SkipEmptyParts)); - - // no matching type found - if (!types.contains (mimeType ())) - return; - - s = kvLineMime.cap(2); - - kDebug (13020) << "guarded variable line kate-mimetype: matched: " << s; - } - else // nothing found - { - return; - } - - QStringList vvl; // view variable names - vvl << "dynamic-word-wrap" << "dynamic-word-wrap-indicators" - << "line-numbers" << "icon-border" << "folding-markers" - << "bookmark-sorting" << "auto-center-lines" - << "icon-bar-color" - // renderer - << "background-color" << "selection-color" - << "current-line-color" << "bracket-highlight-color" - << "word-wrap-marker-color" - << "font" << "font-size" << "scheme"; - int spaceIndent = -1; // for backward compatibility; see below - bool replaceTabsSet = false; - int p( 0 ); - - QString var, val; - while ( (p = kvVar.indexIn( s, p )) > -1 ) - { - p += kvVar.matchedLength(); - var = kvVar.cap( 1 ); - val = kvVar.cap( 2 ).trimmed(); - bool state; // store booleans here - int n; // store ints here - - // only apply view & renderer config stuff - if (onlyViewAndRenderer) - { - if ( vvl.contains( var ) ) // FIXME define above - setViewVariable( var, val ); - } - else - { - // BOOL SETTINGS - if ( var == "word-wrap" && checkBoolValue( val, &state ) ) - setWordWrap( state ); // ??? FIXME CHECK - // KateConfig::configFlags - // FIXME should this be optimized to only a few calls? how? - else if ( var == "backspace-indents" && checkBoolValue( val, &state ) ) - m_config->setBackspaceIndents( state ); - else if ( var == "replace-tabs" && checkBoolValue( val, &state ) ) - { - m_config->setReplaceTabsDyn( state ); - replaceTabsSet = true; // for backward compatibility; see below - } - else if ( var == "remove-trailing-space" && checkBoolValue( val, &state ) ) - m_config->setRemoveTrailingDyn( state ); - else if ( var == "wrap-cursor" && checkBoolValue( val, &state ) ) - m_config->setWrapCursor( state ); - else if ( var == "auto-brackets" && checkBoolValue( val, &state ) ) - m_config->setAutoBrackets( state ); - else if ( var == "overwrite-mode" && checkBoolValue( val, &state ) ) - m_config->setOvr( state ); - else if ( var == "keep-extra-spaces" && checkBoolValue( val, &state ) ) - m_config->setKeepExtraSpaces( state ); - else if ( var == "tab-indents" && checkBoolValue( val, &state ) ) - m_config->setTabIndents( state ); - else if ( var == "show-tabs" && checkBoolValue( val, &state ) ) - m_config->setShowTabs( state ); - else if ( var == "show-trailing-spaces" && checkBoolValue( val, &state ) ) - m_config->setShowSpaces( state ); - else if ( var == "space-indent" && checkBoolValue( val, &state ) ) - { - // this is for backward compatibility; see below - spaceIndent = state; - } - else if ( var == "smart-home" && checkBoolValue( val, &state ) ) - m_config->setSmartHome( state ); - else if ( var == "replace-trailing-space-save" && checkBoolValue( val, &state ) ) - m_config->setRemoveSpaces( state ); - - // INTEGER SETTINGS - else if ( var == "tab-width" && checkIntValue( val, &n ) ) - m_config->setTabWidth( n ); - else if ( var == "indent-width" && checkIntValue( val, &n ) ) - m_config->setIndentationWidth( n ); - else if ( var == "indent-mode" ) - { - m_config->setIndentationMode( val ); - } - else if ( var == "word-wrap-column" && checkIntValue( val, &n ) && n > 0 ) // uint, but hard word wrap at 0 will be no fun ;) - m_config->setWordWrapAt( n ); - - // STRING SETTINGS - else if ( var == "eol" || var == "end-of-line" ) - { - QStringList l; - l << "unix" << "dos" << "mac"; - if ( (n = l.indexOf( val.toLower() )) != -1 ) - m_config->setEol( n ); - } - else if (var == "bom" || var =="byte-order-marker") - { - if (checkBoolValue(val,&state)) { - m_config->setBom(state); - } - } - else if ( var == "encoding" ) - m_config->setEncoding( val ); - else if (var == "presave-postdialog") - setPreSavePostDialogFilterChecks(val.split(',')); - else if (var == "postsave") - setPostSaveFilterChecks(val.split(',')); - else if (var == "postload") - setPostLoadFilterChecks(val.split(',')); - else if ( var == "syntax" || var == "hl" ) - { - setHighlightingMode( val ); - } - else if ( var == "mode" ) - { - setMode( val ); - } - else if ( var == "default-dictionary" ) - { - setDefaultDictionary( val ); - } - else if ( var == "automatic-spell-checking" && checkBoolValue( val, &state ) ) - { - onTheFlySpellCheckingEnabled( state ); - } - - // VIEW SETTINGS - else if ( vvl.contains( var ) ) - setViewVariable( var, val ); - else - { - m_storedVariables.insert( var, val ); - emit variableChanged( this, var, val ); - } - } - } - - // Backward compatibility - // If space-indent was set, but replace-tabs was not set, we assume - // that the user wants to replace tabulators and set that flag. - // If both were set, replace-tabs has precedence. - // At this point spaceIndent is -1 if it was never set, - // 0 if it was set to off, and 1 if it was set to on. - // Note that if onlyViewAndRenderer was requested, spaceIndent is -1. - if ( !replaceTabsSet && spaceIndent >= 0 ) - { - m_config->setReplaceTabsDyn( spaceIndent > 0 ); - } -} - -void KateDocument::setViewVariable( QString var, QString val ) -{ - KateView *v; - bool state; - int n; - QColor c; - foreach (v,m_views) - { - if ( var == "dynamic-word-wrap" && checkBoolValue( val, &state ) ) - v->config()->setDynWordWrap( state ); - else if ( var == "persistent-selection" && checkBoolValue( val, &state ) ) - v->config()->setPersistentSelection( state ); - else if ( var == "block-selection" && checkBoolValue( val, &state ) ) - v->setBlockSelectionMode( state ); - //else if ( var = "dynamic-word-wrap-indicators" ) - else if ( var == "line-numbers" && checkBoolValue( val, &state ) ) - v->config()->setLineNumbers( state ); - else if (var == "icon-border" && checkBoolValue( val, &state ) ) - v->config()->setIconBar( state ); - else if (var == "folding-markers" && checkBoolValue( val, &state ) ) - v->config()->setFoldingBar( state ); - else if ( var == "auto-center-lines" && checkIntValue( val, &n ) ) - v->config()->setAutoCenterLines( n ); // FIXME uint, > N ?? - else if ( var == "icon-bar-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setIconBarColor( c ); - // RENDERER - else if ( var == "background-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setBackgroundColor( c ); - else if ( var == "selection-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setSelectionColor( c ); - else if ( var == "current-line-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setHighlightedLineColor( c ); - else if ( var == "bracket-highlight-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setHighlightedBracketColor( c ); - else if ( var == "word-wrap-marker-color" && checkColorValue( val, c ) ) - v->renderer()->config()->setWordWrapMarkerColor( c ); - else if ( var == "font" || ( var == "font-size" && checkIntValue( val, &n ) ) ) - { - QFont _f( v->renderer()->config()->font() ); - - if ( var == "font" ) - { - _f.setFamily( val ); - _f.setFixedPitch( QFont( val ).fixedPitch() ); - } - else - _f.setPointSize( n ); - - v->renderer()->config()->setFont( _f ); - } - else if ( var == "scheme" ) - { - v->renderer()->config()->setSchema( val ); - } - } -} - -bool KateDocument::checkBoolValue( QString val, bool *result ) -{ - val = val.trimmed().toLower(); - QStringList l; - l << "1" << "on" << "true"; - if ( l.contains( val ) ) - { - *result = true; - return true; - } - l.clear(); - l << "0" << "off" << "false"; - if ( l.contains( val ) ) - { - *result = false; - return true; - } - return false; -} - -bool KateDocument::checkIntValue( QString val, int *result ) -{ - bool ret( false ); - *result = val.toInt( &ret ); - return ret; -} - -bool KateDocument::checkColorValue( QString val, QColor &c ) -{ - c.setNamedColor( val ); - return c.isValid(); -} - -// KTextEditor::variable -QString KateDocument::variable( const QString &name ) const -{ - return m_storedVariables.value(name, QString()); -} - -//END - -void KateDocument::slotModOnHdDirty (const QString &path) -{ - if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != OnDiskModified)) - { - // compare md5 with the one we have (if we have one) - if ( ! m_digest.isEmpty() ) - { - QByteArray tmp; - if ( createDigest( tmp ) && tmp == m_digest ) - return; - } - - m_modOnHd = true; - m_modOnHdReason = OnDiskModified; - - // reenable dialog if not running atm - if (m_isasking == -1) - m_isasking = false; - - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } -} - -void KateDocument::slotModOnHdCreated (const QString &path) -{ - if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != OnDiskCreated)) - { - m_modOnHd = true; - m_modOnHdReason = OnDiskCreated; - - // reenable dialog if not running atm - if (m_isasking == -1) - m_isasking = false; - - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } -} - -void KateDocument::slotModOnHdDeleted (const QString &path) -{ - if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != OnDiskDeleted)) - { - m_modOnHd = true; - m_modOnHdReason = OnDiskDeleted; - - // reenable dialog if not running atm - if (m_isasking == -1) - m_isasking = false; - - emit modifiedOnDisk (this, m_modOnHd, m_modOnHdReason); - } -} - -bool KateDocument::createDigest( QByteArray &result ) -{ - bool ret = false; - result.clear(); - if ( url().isLocalFile() ) - { - QFile f ( url().toLocalFile() ); - if ( f.open( QIODevice::ReadOnly) ) - { - KMD5 md5; - ret = md5.update( f ); - md5.hexDigest( result ); - f.close(); - ret = true; - } - } - return ret; -} - -QString KateDocument::reasonedMOHString() const -{ - // squeeze path - QString str = KStringHandler::csqueeze(url().pathOrUrl()); - - switch( m_modOnHdReason ) - { - case OnDiskModified: - return i18n("The file '%1' was modified by another program.", str ); - break; - case OnDiskCreated: - return i18n("The file '%1' was created by another program.", str ); - break; - case OnDiskDeleted: - return i18n("The file '%1' was deleted by another program.", str ); - break; - default: - return QString(); - } - return QString(); -} - -void KateDocument::removeTrailingSpace(int line) -{ - // if undo/redo is active, never remove trailing spaces, because the undo/redo - // action also sets the cursor position. If the trailing spaces are removed, - // the cursor position can get invalid (i.e. it is behind the last column). - // Then, moving the cursor leads to a crash, see bug #152203. - if (!m_undoManager->isActive()) - return; - - // remove trailing spaces from left line if required - if (m_blockRemoveTrailingSpaces - || !(config()->removeTrailingDyn())) - return; - - Kate::TextLine ln = plainKateTextLine(line); - - if (!ln || ln->length() == 0) - return; - - if (activeView() && line == activeView()->cursorPosition().line() - && activeView()->cursorPosition().column() >= qMax(0, ln->lastChar())) - return; - - const int p = ln->lastChar() + 1; - const int l = ln->length() - p; - if (l > 0) { - m_blockRemoveTrailingSpaces = true; - editRemoveText(line, p, l); - m_blockRemoveTrailingSpaces = false; - } -} - -void KateDocument::updateFileType (const QString &newType, bool user) -{ - if (user || !m_fileTypeSetByUser) - { - if (!newType.isEmpty()) - { - m_fileType = newType; - - m_config->configStart(); - - if (!hlSetByUser && !KateGlobal::self()->modeManager()->fileType(newType).hl.isEmpty()) - { - int hl (KateHlManager::self()->nameFind (KateGlobal::self()->modeManager()->fileType(newType).hl)); - - if (hl >= 0) - m_buffer->setHighlight(hl); - } - - /** - * set the indentation mode, if any in the mode... - */ - if (!KateGlobal::self()->modeManager()->fileType(newType).indenter.isEmpty()) - config()->setIndentationMode (KateGlobal::self()->modeManager()->fileType(newType).indenter); - - // views! - KateView *v; - foreach (v,m_views) - { - v->config()->configStart(); - v->renderer()->config()->configStart(); - } - - bool bom_settings = false; - if (m_bomSetByUser) - bom_settings=m_config->bom(); - readVariableLine( KateGlobal::self()->modeManager()->fileType(newType).varLine ); - if (m_bomSetByUser) - m_config->setBom(bom_settings); - m_config->configEnd(); - foreach (v,m_views) - { - v->config()->configEnd(); - v->renderer()->config()->configEnd(); - } - } - } - - // fixme, make this better... - emit modeChanged (this); -} - -void KateDocument::slotQueryClose_save(bool *handled, bool* abortClosing) { - *handled=true; - *abortClosing=true; - if (this->url().isEmpty()) - { - QWidget *parentWidget(dialogParent()); - - KEncodingFileDialog::Result res=KEncodingFileDialog::getSaveUrlAndEncoding(config()->encoding(), - QString(),QString(),parentWidget,i18n("Save File")); - - if( res.URLs.isEmpty() || !checkOverwrite( res.URLs.first(), parentWidget ) ) { - *abortClosing=true; - return; - } - setEncoding( res.encoding ); - saveAs( res.URLs.first() ); - *abortClosing=false; - } - else - { - save(); - *abortClosing=false; - } - -} - -bool KateDocument::checkOverwrite( KUrl u, QWidget *parent ) -{ - if( !u.isLocalFile() ) - return true; - - QFileInfo info( u.path() ); - if( !info.exists() ) - return true; - - return KMessageBox::Cancel != KMessageBox::warningContinueCancel( parent, - i18n( "A file named \"%1\" already exists. " - "Are you sure you want to overwrite it?" , info.fileName() ), - i18n( "Overwrite File?" ), KStandardGuiItem::overwrite(), - KStandardGuiItem::cancel(), QString(), KMessageBox::Notify | KMessageBox::Dangerous ); -} - -//BEGIN KTextEditor::ConfigInterface - -// BEGIN ConfigInterface stff -QStringList KateDocument::configKeys() const -{ - return QStringList() << "auto-brackets"; -} - -QVariant KateDocument::configValue(const QString &key) -{ - if (key == "auto-brackets") { - return m_config->autoBrackets(); - } else if (key == "backup-on-save-local") { - return m_config->backupFlags() & KateDocumentConfig::LocalFiles; - } else if (key == "backup-on-save-remote") { - return m_config->backupFlags() & KateDocumentConfig::RemoteFiles; - } else if (key == "backup-on-save-suffix") { - return m_config->backupSuffix(); - } else if (key == "backup-on-save-prefix") { - return m_config->backupPrefix(); - } - - // return invalid variant - return QVariant(); -} - -void KateDocument::setConfigValue(const QString &key, const QVariant &value) -{ - if (value.type() == QVariant::String) { - if (key == "backup-on-save-suffix") { - m_config->setBackupSuffix(value.toString()); - } else if (key == "backup-on-save-prefix") { - m_config->setBackupPrefix(value.toString()); - } - } else if (value.canConvert(QVariant::Bool)) { - const bool bValue = value.toBool(); - if (key == "auto-brackets") { - m_config->setAutoBrackets(bValue); - } else if (key == "backup-on-save-local" && value.type() == QVariant::String) { - uint f = m_config->backupFlags(); - if (bValue) { - f |= KateDocumentConfig::LocalFiles; - } else { - f ^= KateDocumentConfig::LocalFiles; - } - - m_config->setBackupFlags(f); - } else if (key == "backup-on-save-remote") { - uint f = m_config->backupFlags(); - if (bValue) { - f |= KateDocumentConfig::RemoteFiles; - } else { - f ^= KateDocumentConfig::RemoteFiles; - } - - m_config->setBackupFlags(f); - } - } -} - -//END KTextEditor::ConfigInterface - -//BEGIN KTextEditor::TemplateInterface -bool KateDocument::insertTemplateTextImplementation( const KTextEditor::Cursor &c, - const QString &templateString, - const QMap &initialValues, - KTextEditor::TemplateScript* templateScript, - KateView* view) -{ - if (templateString.isEmpty()) return false; - - KateTemplateScript* kateTemplateScript = - KateGlobal::self()->scriptManager()->templateScript(templateScript); - - // the handler will delete itself when necessary - new KateTemplateHandler(view, c, templateString, initialValues, m_undoManager, kateTemplateScript); - - return true; -} -//END KTextEditor::TemplateInterface - - -KateView * KateDocument::activeKateView( ) const -{ - return static_cast(m_activeView); -} - -KTextEditor::Cursor KateDocument::documentEnd( ) const -{ - return KTextEditor::Cursor(lastLine(), lineLength(lastLine())); -} - -bool KateDocument::replaceText( const KTextEditor::Range & range, const QString & s, bool block ) -{ - // TODO more efficient? - editStart(); - bool changed = removeText(range, block); - changed |= insertText(range.start(), s, block); - editEnd(); - return changed; -} - -void KateDocument::ignoreModifiedOnDiskOnce( ) -{ - m_isasking = -1; -} - -KateHighlighting * KateDocument::highlight( ) const -{ - return m_buffer->highlight(); -} - -uint KateDocument::getRealLine( unsigned int virtualLine ) -{ - return m_buffer->lineNumber (virtualLine); -} - -uint KateDocument::getVirtualLine( unsigned int realLine ) -{ - return m_buffer->lineVisibleNumber (realLine); -} - -uint KateDocument::visibleLines( ) -{ - return m_buffer->countVisible (); -} - -Kate::TextLine KateDocument::kateTextLine( uint i ) -{ - m_buffer->ensureHighlighted (i); - return m_buffer->plainLine (i); -} - -Kate::TextLine KateDocument::plainKateTextLine( uint i ) -{ - return m_buffer->plainLine (i); -} - -bool KateDocument::isEditRunning() const -{ - return editIsRunning; -} - -void KateDocument::setUndoMergeAllEdits(bool merge) -{ - m_undoManager->undoSafePoint(); - m_undoManager->setAllowComplexMerge(merge); -} - -//BEGIN KTextEditor::MovingInterface -KTextEditor::MovingCursor *KateDocument::newMovingCursor (const KTextEditor::Cursor &position, KTextEditor::MovingCursor::InsertBehavior insertBehavior) -{ - return new Kate::TextCursor(buffer(), position, insertBehavior); -} - -KTextEditor::MovingRange *KateDocument::newMovingRange (const KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior) -{ - return new Kate::TextRange(buffer(), range, insertBehaviors, emptyBehavior); -} - -qint64 KateDocument::revision () const -{ - return m_buffer->history().revision (); -} - -qint64 KateDocument::lastSavedRevision () const -{ - return m_buffer->history().lastSavedRevision (); -} - -void KateDocument::lockRevision (qint64 revision) -{ - m_buffer->history().lockRevision (revision); -} - -void KateDocument::unlockRevision (qint64 revision) -{ - m_buffer->history().unlockRevision (revision); -} - -void KateDocument::transformCursor(int& line, int& column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision) -{ - m_buffer->history().transformCursor (line, column, insertBehavior, fromRevision, toRevision); -} - -void KateDocument::transformCursor (KTextEditor::Cursor &cursor, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision) -{ - int line = cursor.line(), column = cursor.column(); - m_buffer->history().transformCursor (line, column, insertBehavior, fromRevision, toRevision); - cursor.setLine(line); - cursor.setColumn(column); -} - -void KateDocument::transformRange (KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision) -{ - m_buffer->history().transformRange (range, insertBehaviors, emptyBehavior, fromRevision, toRevision); -} - -//END - -bool KateDocument::simpleMode () -{ - return KateGlobal::self()->simpleMode () && KateGlobal::self()->documentConfig()->allowSimpleMode (); -} - -KateDocument::LoadSaveFilterCheckPlugins* KateDocument::loadSaveFilterCheckPlugins() -{ - K_GLOBAL_STATIC(KateDocument::LoadSaveFilterCheckPlugins, s_loadSaveFilterCheckPlugins) - return s_loadSaveFilterCheckPlugins; -} - -//BEGIN KTextEditor::AnnotationInterface -void KateDocument::setAnnotationModel( KTextEditor::AnnotationModel* model ) -{ - KTextEditor::AnnotationModel* oldmodel = m_annotationModel; - m_annotationModel = model; - emit annotationModelChanged(oldmodel, m_annotationModel); -} - -KTextEditor::AnnotationModel* KateDocument::annotationModel() const -{ - return m_annotationModel; -} -//END KTextEditor::AnnotationInterface - -//TAKEN FROM kparts.h -bool KateDocument::queryClose() -{ - if ( !isReadWrite() || !isModified() ) - return true; - - QString docName = documentName(); - - int res = KMessageBox::warningYesNoCancel( dialogParent(), - i18n( "The document \"%1\" has been modified.\n" - "Do you want to save your changes or discard them?" , docName ), - i18n( "Close Document" ), KStandardGuiItem::save(), KStandardGuiItem::discard() ); - - bool abortClose=false; - bool handled=false; - - switch(res) { - case KMessageBox::Yes : - sigQueryClose(&handled,&abortClose); - if (!handled) - { - if (url().isEmpty()) - { - KUrl url = KFileDialog::getSaveUrl(KUrl(), QString(), dialogParent()); - if (url.isEmpty()) - return false; - - saveAs( url ); - } - else - { - save(); - } - } else if (abortClose) return false; - return waitSaveComplete(); - case KMessageBox::No : - return true; - default : // case KMessageBox::Cancel : - return false; - } -} - - -void KateDocument::slotCanceled() { - m_savingToUrl=false; - m_saveAs=false; -} - -void KateDocument::slotCompleted() { - if (m_savingToUrl) { - if (!m_postSaveFilterChecks.isEmpty()) - { - LoadSaveFilterCheckPlugins *lscps1=loadSaveFilterCheckPlugins(); - foreach(const QString& checkplugin, m_postSaveFilterChecks) - { - if (lscps1->postSaveFilterCheck(checkplugin,this,m_saveAs)==false) - break; - } - } - emit documentSavedOrUploaded(this,m_saveAs); - } - m_savingToUrl=false; - m_saveAs=false; -} - -bool KateDocument::save() { - m_saveAs = false; - return KTextEditor::Document::save(); -} - -bool KateDocument::saveAs( const KUrl &url ) { - m_saveAs = true; - return KTextEditor::Document::saveAs(url); -} - -QString KateDocument::defaultDictionary() const -{ - return m_defaultDictionary; -} - -QList > KateDocument::dictionaryRanges() const -{ - return m_dictionaryRanges; -} - -void KateDocument::clearDictionaryRanges() -{ - for(QList >::iterator i = m_dictionaryRanges.begin(); - i != m_dictionaryRanges.end();++i) - { - delete (*i).first; - } - m_dictionaryRanges.clear(); - if(m_onTheFlyChecker) - { - m_onTheFlyChecker->refreshSpellCheck(); - } - emit dictionaryRangesPresent(false); -} - -void KateDocument::setDictionary(const QString& newDictionary, const KTextEditor::Range &range) -{ - KTextEditor::Range newDictionaryRange = range; - if(!newDictionaryRange.isValid() || newDictionaryRange.isEmpty()) - { - return; - } - QList > newRanges; - // all ranges is 'm_dictionaryRanges' are assumed to be mutually disjoint - for(QList >::iterator i = m_dictionaryRanges.begin(); - i != m_dictionaryRanges.end();) - { - kDebug(13000) << "new iteration" << newDictionaryRange; - if(newDictionaryRange.isEmpty()) - { - break; - } - QPair pair = *i; - QString dictionarySet = pair.second; - KTextEditor::MovingRange *dictionaryRange = pair.first; - kDebug(13000) << *dictionaryRange << dictionarySet; - if(dictionaryRange->contains(newDictionaryRange) && newDictionary == dictionarySet) - { - kDebug(13000) << "dictionaryRange contains newDictionaryRange"; - return; - } - if(newDictionaryRange.contains(*dictionaryRange)) - { - delete dictionaryRange; - i = m_dictionaryRanges.erase(i); - kDebug(13000) << "newDictionaryRange contains dictionaryRange"; - continue; - } - - KTextEditor::Range intersection = dictionaryRange->toRange().intersect(newDictionaryRange); - if(!intersection.isEmpty() && intersection.isValid()) - { - if(dictionarySet == newDictionary) // we don't have to do anything for 'intersection' - { // except cut off the intersection - QList remainingRanges = KateSpellCheckManager::rangeDifference(newDictionaryRange, intersection); - Q_ASSERT(remainingRanges.size() == 1); - newDictionaryRange = remainingRanges.first(); - ++i; - kDebug(13000) << "dictionarySet == newDictionary"; - continue; - } - QList remainingRanges = KateSpellCheckManager::rangeDifference(*dictionaryRange, intersection); - for(QList::iterator j = remainingRanges.begin(); j != remainingRanges.end(); ++j) - { - KTextEditor::MovingRange *remainingRange = newMovingRange(*j, - KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - remainingRange->setFeedback(this); - newRanges.push_back(QPair(remainingRange, dictionarySet)); - } - i = m_dictionaryRanges.erase(i); - delete dictionaryRange; - } else { - ++i; - } - } - m_dictionaryRanges += newRanges; - if(!newDictionaryRange.isEmpty() && !newDictionary.isEmpty()) // we don't add anything for the default dictionary - { - KTextEditor::MovingRange *newDictionaryMovingRange = newMovingRange(newDictionaryRange, - KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - newDictionaryMovingRange->setFeedback(this); - m_dictionaryRanges.push_back(QPair(newDictionaryMovingRange, newDictionary)); - } - if(m_onTheFlyChecker && !newDictionaryRange.isEmpty()) - { - m_onTheFlyChecker->refreshSpellCheck(newDictionaryRange); - } - emit dictionaryRangesPresent(!m_dictionaryRanges.isEmpty()); -} - -void KateDocument::revertToDefaultDictionary(const KTextEditor::Range &range) -{ - setDictionary(QString(), range); -} - -void KateDocument::setDefaultDictionary(const QString& dict) -{ - if(m_defaultDictionary == dict) - { - return; - } - m_defaultDictionary = dict; - if(m_onTheFlyChecker) - { - m_onTheFlyChecker->updateConfig(); - } - refreshOnTheFlyCheck(); - emit defaultDictionaryChanged(this); -} - -void KateDocument::onTheFlySpellCheckingEnabled(bool enable) -{ - if (isOnTheFlySpellCheckingEnabled() == enable) - { - return; - } - if (enable) - { - if (!m_onTheFlyChecker) { - m_onTheFlyChecker = new KateOnTheFlyChecker(this); - } - } else { - delete m_onTheFlyChecker; - m_onTheFlyChecker = 0; - } - foreach(KateView *view, m_views) { - view->reflectOnTheFlySpellCheckStatus(enable); - } -} - -bool KateDocument::isOnTheFlySpellCheckingEnabled() const -{ - return m_onTheFlyChecker != 0; -} - -QString KateDocument::dictionaryForMisspelledRange(const KTextEditor::Range& range) const -{ - if (!m_onTheFlyChecker) - { - return QString(); - } else { - return m_onTheFlyChecker->dictionaryForMisspelledRange(range); - } -} - -void KateDocument::clearMisspellingForWord(const QString& word) -{ - if(m_onTheFlyChecker) { - m_onTheFlyChecker->clearMisspellingForWord(word); - } -} - -void KateDocument::refreshOnTheFlyCheck(const KTextEditor::Range &range) -{ - if(m_onTheFlyChecker) { - m_onTheFlyChecker->refreshSpellCheck(range); - } -} - -void KateDocument::rangeInvalid(KTextEditor::MovingRange *movingRange) -{ - deleteDictionaryRange(movingRange); -} - -void KateDocument::rangeEmpty(KTextEditor::MovingRange *movingRange) -{ - deleteDictionaryRange(movingRange); -} - -void KateDocument::deleteDictionaryRange(KTextEditor::MovingRange *movingRange) -{ - kDebug(13020) << "deleting" << movingRange; - for(QList >::iterator i = m_dictionaryRanges.begin(); - i != m_dictionaryRanges.end();) - { - KTextEditor::MovingRange *dictionaryRange = (*i).first; - if(dictionaryRange == movingRange) - { - delete movingRange; - i = m_dictionaryRanges.erase(i); - } else { - ++i; - } - } -} - -bool KateDocument::containsCharacterEncoding(const KTextEditor::Range& range) -{ - KateHighlighting *highlighting = highlight(); - Kate::TextLine textLine; - - const int rangeStartLine = range.start().line(); - const int rangeStartColumn = range.start().column(); - const int rangeEndLine = range.end().line(); - const int rangeEndColumn = range.end().column(); - - for(int line = range.start().line(); line <= rangeEndLine; ++line) { - textLine = kateTextLine(line); - int startColumn = (line == rangeStartLine) ? rangeStartColumn : 0; - int endColumn = (line == rangeEndLine) ? rangeEndColumn : textLine->length(); - for(int col = startColumn; col < endColumn; ++col) { - int attr = textLine->attribute(col); - const KatePrefixStore& prefixStore = highlighting->getCharacterEncodingsPrefixStore(attr); - if(!prefixStore.findPrefix(textLine, col).isEmpty()) { - return true; - } - } - } - - return false; -} - -int KateDocument::computePositionWrtOffsets(const OffsetList& offsetList, int pos) -{ - int previousOffset = 0; - for(OffsetList::const_iterator i = offsetList.begin(); i != offsetList.end(); ++i) { - if((*i).first > pos) { - break; - } - previousOffset = (*i).second; - } - return pos + previousOffset; -} - -QString KateDocument::decodeCharacters(const KTextEditor::Range& range, KateDocument::OffsetList& decToEncOffsetList, - KateDocument::OffsetList& encToDecOffsetList) -{ - QString toReturn; - KTextEditor::Cursor previous = range.start(); - int decToEncCurrentOffset = 0, encToDecCurrentOffset = 0; - int i = 0; - int newI = 0; - - KateHighlighting *highlighting = highlight(); - Kate::TextLine textLine; - - const int rangeStartLine = range.start().line(); - const int rangeStartColumn = range.start().column(); - const int rangeEndLine = range.end().line(); - const int rangeEndColumn = range.end().column(); - - for(int line = range.start().line(); line <= rangeEndLine; ++line) { - textLine = kateTextLine(line); - int startColumn = (line == rangeStartLine) ? rangeStartColumn : 0; - int endColumn = (line == rangeEndLine) ? rangeEndColumn : textLine->length(); - for(int col = startColumn; col < endColumn;) { - int attr = textLine->attribute(col); - const KatePrefixStore& prefixStore = highlighting->getCharacterEncodingsPrefixStore(attr); - const QHash& characterEncodingsHash = highlighting->getCharacterEncodings(attr); - QString matchingPrefix = prefixStore.findPrefix(textLine, col); - if(!matchingPrefix.isEmpty()) { - toReturn += text(KTextEditor::Range(previous, KTextEditor::Cursor(line, col))); - const QChar& c = characterEncodingsHash.value(matchingPrefix); - const bool isNullChar = c.isNull(); - if(!c.isNull()) { - toReturn += c; - } - i += matchingPrefix.length(); - col += matchingPrefix.length(); - previous = KTextEditor::Cursor(line, col); - decToEncCurrentOffset = decToEncCurrentOffset - (isNullChar ? 0 : 1) + matchingPrefix.length(); - encToDecCurrentOffset = encToDecCurrentOffset - matchingPrefix.length() + (isNullChar ? 0 : 1); - newI += (isNullChar ? 0 : 1); - decToEncOffsetList.push_back(QPair(newI, decToEncCurrentOffset)); - encToDecOffsetList.push_back(QPair(i, encToDecCurrentOffset)); - continue; - } - ++col; - ++i; - ++newI; - } - ++i; - ++newI; - } - if(previous < range.end()) { - toReturn += text(KTextEditor::Range(previous, range.end())); - } - return toReturn; -} - -void KateDocument::replaceCharactersByEncoding(const KTextEditor::Range& range) -{ - KateHighlighting *highlighting = highlight(); - Kate::TextLine textLine; - - const int rangeStartLine = range.start().line(); - const int rangeStartColumn = range.start().column(); - const int rangeEndLine = range.end().line(); - const int rangeEndColumn = range.end().column(); - - for(int line = range.start().line(); line <= rangeEndLine; ++line) { - textLine = kateTextLine(line); - int startColumn = (line == rangeStartLine) ? rangeStartColumn : 0; - int endColumn = (line == rangeEndLine) ? rangeEndColumn : textLine->length(); - for(int col = startColumn; col < endColumn;) { - int attr = textLine->attribute(col); - const QHash& reverseCharacterEncodingsHash = highlighting->getReverseCharacterEncodings(attr); - QHash::const_iterator it = reverseCharacterEncodingsHash.find(textLine->at(col)); - if(it != reverseCharacterEncodingsHash.end()) { - replaceText(KTextEditor::Range(line, col, line, col + 1), *it); - col += (*it).length(); - continue; - } - ++col; - } - } -} - -// -// KTextEditor::HighlightInterface -// - -KTextEditor::Attribute::Ptr KateDocument::defaultStyle(const KTextEditor::HighlightInterface::DefaultStyle ds) const -{ - ///TODO: move attributes to document, they are not view-dependant - KateView* view = activeKateView(); - if ( !view ) { - kWarning() << "ATTENTION: cannot access defaultStyle() without any View (will be fixed eventually)"; - return KTextEditor::Attribute::Ptr(0); - } - - KTextEditor::Attribute::Ptr style = highlight()->attributes(view->renderer()->config()->schema()).at(ds); - if (!style->hasProperty(QTextFormat::BackgroundBrush)) { - // make sure the returned style has the default background color set - style.attach(new KTextEditor::Attribute(*style)); - style->setBackground( QBrush(view->renderer()->config()->backgroundColor()) ); - } - return style; -} - -QList< KTextEditor::HighlightInterface::AttributeBlock > KateDocument::lineAttributes(const unsigned int line) -{ - ///TODO: move attributes to document, they are not view-dependant - - QList< KTextEditor::HighlightInterface::AttributeBlock > attribs; - - KateView* view = activeKateView(); - if ( !view ) { - kWarning() << "ATTENTION: cannot access lineAttributes() without any View (will be fixed eventually)"; - return attribs; - } - - Kate::TextLine kateLine = kateTextLine(line); - - if ( !kateLine ) { - return attribs; - } - - const QVector & intAttrs = kateLine->attributesList(); - - Q_ASSERT(intAttrs.size() % 3 == 0); - - for ( int i = 0; i < intAttrs.size(); i += 3 ) { - attribs << KTextEditor::HighlightInterface::AttributeBlock( - intAttrs.at(i), - intAttrs.at(i+1), - view->renderer()->attribute(intAttrs.at(i+2)) - ); - } - - return attribs; -} - -QStringList KateDocument::embeddedHighlightingModes() const -{ - return highlight()->getEmbeddedHighlightingModes(); -} - -QString KateDocument::highlightingModeAt(const KTextEditor::Cursor& position) -{ - Kate::TextLine kateLine = kateTextLine(position.line()); - -// const QVector< short >& attrs = kateLine->contextStack(); -// kDebug() << "----------------------------------------------------------------------"; -// foreach( short a, attrs ) { -// kDebug() << a; -// } -// kDebug() << "----------------------------------------------------------------------"; -// kDebug() << "col: " << position.column() << " lastchar:" << kateLine->lastChar() << " length:" << kateLine->length() << "global mode:" << highlightingMode(); - - int len = kateLine->length(); - int pos = position.column(); - if ( pos >= len ) { - const QVector< short >& ctxs = kateLine->contextStack(); - int ctxcnt = ctxs.count(); - if ( ctxcnt == 0 ) { - return highlightingMode(); - } - int ctx = ctxs.at(ctxcnt-1); - if ( ctx == 0 ) { - return highlightingMode(); - } - return KateHlManager::self()->nameForIdentifier(highlight()->hlKeyForContext(ctx)); - } - - int attr = kateLine->attribute(pos); - if ( attr == 0 ) { - return mode(); - } - - return KateHlManager::self()->nameForIdentifier(highlight()->hlKeyForAttrib(attr)); - -} - -Kate::SwapFile* KateDocument::swapFile() -{ - return m_swapfile; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/document/katedocument.h b/part/document/katedocument.h deleted file mode 100644 index 5180fb9..0000000 --- a/part/document/katedocument.h +++ /dev/null @@ -1,1166 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001-2004 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - Copyright (C) 2006 Hamish Rodda - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _KATE_DOCUMENT_H_ -#define _KATE_DOCUMENT_H_ - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "katepartprivate_export.h" -#include "katetextline.h" -#include "katetextcursor.h" -#include "katetextrange.h" - -namespace KTextEditor { - class Plugin; - class Attribute; - class TemplateScript; -} - -namespace KIO { class TransferJob; } - -namespace Kate { class SwapFile; } - -class KateCodeFoldingTree; -class KateBuffer; -class KateView; -class KateLineInfo; -class KateDocumentConfig; -class KateHighlighting; -class KateUndoManager; -class KateOnTheFlyChecker; - -class KateAutoIndent; - -// -// Kate KTextEditor::Document class (and even KTextEditor::Editor ;) -// -class KATEPART_TESTS_EXPORT KateDocument : public KTextEditor::Document, - public KTextEditor::SessionConfigInterface, - public KTextEditor::ParameterizedSessionConfigInterface, - public KTextEditor::SearchInterface, - public KTextEditor::MarkInterface, - public KTextEditor::VariableInterface, - public KTextEditor::ModificationInterface, - public KTextEditor::ConfigInterface, - public KTextEditor::AnnotationInterface, - public KTextEditor::HighlightInterface, - public KTextEditor::MovingInterface, - public KTextEditor::RecoveryInterface, - private KTextEditor::MovingRangeFeedback -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::SessionConfigInterface) - Q_INTERFACES(KTextEditor::ParameterizedSessionConfigInterface) - Q_INTERFACES(KTextEditor::SearchInterface) - Q_INTERFACES(KTextEditor::MarkInterface) - Q_INTERFACES(KTextEditor::VariableInterface) - Q_INTERFACES(KTextEditor::ModificationInterface) - Q_INTERFACES(KTextEditor::AnnotationInterface) - Q_INTERFACES(KTextEditor::ConfigInterface) - Q_INTERFACES(KTextEditor::HighlightInterface) - Q_INTERFACES(KTextEditor::MovingInterface) - Q_INTERFACES(KTextEditor::RecoveryInterface) - - public: - explicit KateDocument (bool bSingleViewMode=false, bool bBrowserView=false, bool bReadOnly=false, - QWidget *parentWidget = 0, QObject * = 0); - ~KateDocument (); - - using ReadWritePart::closeUrl; - virtual bool closeUrl(); - - virtual KTextEditor::Editor *editor (); - - KTextEditor::Range rangeOnLine(KTextEditor::Range range, int line) const; - - /* - * Overload this to have on-demand view creation - */ - public: - /** - * @return The widget defined by this part, set by setWidget(). - */ - virtual QWidget *widget(); - - public: - bool readOnly () const { return m_bReadOnly; } - bool browserView () const { return m_bBrowserView; } - bool singleViewMode () const { return m_bSingleViewMode; } - static bool simpleMode (); - - private: - // only to make part work, don't change it ! - const bool m_bSingleViewMode; - const bool m_bBrowserView; - const bool m_bReadOnly; - - // - // KTextEditor::Document stuff - // - public: - virtual KTextEditor::View *createView( QWidget *parent ); - virtual const QList &views () const; - - virtual KTextEditor::View* activeView() const { return m_activeView; } - // Invalid covariant returns my a$$... for some reason gcc won't let me return a KateView above! - KateView* activeKateView() const; - - private: - QLinkedList m_views; - QList m_textEditViews; - KTextEditor::View *m_activeView; - - // - // KTextEditor::EditInterface stuff - // - public Q_SLOTS: - virtual bool setText(const QString &); - virtual bool setText(const QStringList& text); - virtual bool clear (); - - virtual bool insertText ( const KTextEditor::Cursor &position, const QString &s, bool block = false ); - virtual bool insertText ( const KTextEditor::Cursor &position, const QStringList &text, bool block = false ); - - virtual bool insertLine ( int line, const QString &s ); - virtual bool insertLines ( int line, const QStringList &s ); - - virtual bool removeText ( const KTextEditor::Range &range, bool block = false ); - virtual bool removeLine ( int line ); - - virtual bool replaceText ( const KTextEditor::Range &range, const QString &s, bool block = false ); - - // unhide method... - virtual bool replaceText (const KTextEditor::Range &r, const QStringList &l, bool b) - { return KTextEditor::Document::replaceText (r, l, b); } - - public: - virtual QString text ( const KTextEditor::Range &range, bool blockwise = false ) const; - virtual QStringList textLines ( const KTextEditor::Range& range, bool block = false ) const; - virtual QString text() const; - virtual QString line(int line) const; - virtual QChar character(const KTextEditor::Cursor& position) const; - virtual int lines() const; - virtual KTextEditor::Cursor documentEnd() const; - int numVisLines() const; - virtual int totalCharacters() const; - virtual int lineLength(int line) const; - - Q_SIGNALS: - void charactersSemiInteractivelyInserted(const KTextEditor::Cursor& position, const QString& text); - - public: -//BEGIN editStart/editEnd (start, end, undo, cursor update, view update) - /** - * Enclose editor actions with @p editStart() and @p editEnd() to group - * them. - */ - void editStart (); - - /** - * Alias for @p editStart() - */ - void editBegin () { editStart(); } - - /** - * End a editor operation. - * @see editStart() - */ - void editEnd (); - - void pushEditState(); - void popEditState(); - - virtual bool startEditing () { editStart (); return true; } - virtual bool endEditing () { editEnd (); return true; } - -//END editStart/editEnd - - void inputMethodStart(); - void inputMethodEnd(); - -//BEGIN LINE BASED INSERT/REMOVE STUFF (editStart() and editEnd() included) - /** - * Add a string in the given line/column - * @param line line number - * @param col column - * @param s string to be inserted - * @return true on success - */ - bool editInsertText ( int line, int col, const QString &s ); - /** - * Remove a string in the given line/column - * @param line line number - * @param col column - * @param len length of text to be removed - * @return true on success - */ - bool editRemoveText ( int line, int col, int len ); - - /** - * Mark @p line as @p autowrapped. This is necessary if static word warp is - * enabled, because we have to know whether to insert a new line or add the - * wrapped words to the followin line. - * @param line line number - * @param autowrapped autowrapped? - * @return true on success - */ - bool editMarkLineAutoWrapped ( int line, bool autowrapped ); - - /** - * Wrap @p line. If @p newLine is true, ignore the textline's flag - * KateTextLine::flagAutoWrapped and force a new line. Whether a new line - * was needed/added you can grab with @p newLineAdded. - * @param line line number - * @param col column - * @param newLine if true, force a new line - * @param newLineAdded return value is true, if new line was added (may be 0) - * @return true on success - */ - bool editWrapLine ( int line, int col, bool newLine = true, bool *newLineAdded = 0 ); - /** - * Unwrap @p line. If @p removeLine is true, we force to join the lines. If - * @p removeLine is true, @p length is ignored (eg not needed). - * @param line line number - * @param removeLine if true, force to remove the next line - * @return true on success - */ - bool editUnWrapLine ( int line, bool removeLine = true, int length = 0 ); - - /** - * Insert a string at the given line. - * @param line line number - * @param s string to insert - * @return true on success - */ - bool editInsertLine ( int line, const QString &s ); - /** - * Remove a line - * @param line line number - * @return true on success - */ - bool editRemoveLine ( int line ); - - bool editRemoveLines ( int from, int to ); - - /** - * Remove a line - * @param startLine line to begin wrapping - * @param endLine line to stop wrapping - * @return true on success - */ - bool wrapText (int startLine, int endLine); -//END LINE BASED INSERT/REMOVE STUFF - - Q_SIGNALS: - /** - * Emmitted when text from @p line was wrapped at position pos onto line @p nextLine. - */ - void editLineWrapped ( int line, int col, int len ); - - /** - * Emitted each time text from @p nextLine was upwrapped onto @p line. - */ - void editLineUnWrapped ( int line, int col ); - - public: - bool isEditRunning() const; - - void setUndoMergeAllEdits(bool merge); - - private: - int editSessionNumber; - QStack editStateStack; - bool editIsRunning; - - // - // KTextEditor::UndoInterface stuff - // - public Q_SLOTS: - void undo (); - void redo (); - - public: - uint undoCount () const; - uint redoCount () const; - - protected: - KateUndoManager* const m_undoManager; - - Q_SIGNALS: - void undoChanged (); - - // - // KTextEditor::SearchInterface stuff - // - public: - virtual QVector searchText( - const KTextEditor::Range & range, - const QString & pattern, - const KTextEditor::Search::SearchOptions options); - - virtual KTextEditor::Search::SearchOptions supportedSearchOptions() const; - - private: - /** - * Return a widget suitable to be used as a dialog parent. - */ - QWidget * dialogParent(); - - /* - * Access to the mode/highlighting subsystem - */ - public: - /** - * Return the name of the currently used mode - * \return name of the used mode - * - */ - virtual QString mode() const; - - /** - * Return the name of the currently used mode - * \return name of the used mode - * - */ - virtual QString highlightingMode() const; - - /** - * Return a list of the names of all possible modes - * \return list of mode names - */ - virtual QStringList modes() const; - - /** - * Return a list of the names of all possible modes - * \return list of mode names - */ - virtual QStringList highlightingModes() const; - - /** - * Set the current mode of the document by giving its name - * \param name name of the mode to use for this document - * \return \e true on success, otherwise \e false - */ - virtual bool setMode(const QString &name); - - /** - * Set the current mode of the document by giving its name - * \param name name of the mode to use for this document - * \return \e true on success, otherwise \e false - */ - virtual bool setHighlightingMode(const QString &name); - /** - * Returns the name of the section for a highlight given its index in the highlight - * list (as returned by highlightModes()). - * You can use this function to build a tree of the highlight names, organized in sections. - * \param name the name of the highlight for which to find the section name. - */ - virtual QString highlightingModeSection( int index ) const; - - /** - * Returns the name of the section for a mode given its index in the highlight - * list (as returned by modes()). - * You can use this function to build a tree of the mode names, organized in sections. - * \param name the name of the highlight for which to find the section name. - */ - virtual QString modeSection( int index ) const; - - /* - * Helpers.... - */ - public: - void bufferHlChanged(); - - /** - * allow to mark, that we changed hl on user wish and should not reset it - * atm used for the user visible menu to select highlightings - */ - void setDontChangeHlOnSave(); - - /** - * Set that the BOM marker is forced via the tool menu - */ - void bomSetByUser(); - - // - // KTextEditor::SessionConfigInterface and KTextEditor::ParameterizedSessionConfigInterface stuff - // - public: - virtual void readSessionConfig (const KConfigGroup&); - virtual void writeSessionConfig (KConfigGroup&); - virtual void readParameterizedSessionConfig (const KConfigGroup&, unsigned long configParameters); - virtual void writeParameterizedSessionConfig (KConfigGroup&, unsigned long configParameters); - - Q_SIGNALS: - void configChanged(); - - // - // KTextEditor::MarkInterface - // - public Q_SLOTS: - virtual void setMark( int line, uint markType ); - virtual void clearMark( int line ); - - virtual void addMark( int line, uint markType ); - virtual void removeMark( int line, uint markType ); - - virtual void clearMarks(); - - void requestMarkTooltip( int line, QPoint position ); - - ///Returns true if the click on the mark should not be further processed - bool handleMarkClick( int line ); - - ///Returns true if the context-menu event should not further be processed - bool handleMarkContextMenu( int line, QPoint position ); - - virtual void setMarkPixmap( MarkInterface::MarkTypes, const QPixmap& ); - - virtual void setMarkDescription( MarkInterface::MarkTypes, const QString& ); - - virtual void setEditableMarks( uint markMask ); - - public: - virtual uint mark( int line ); - virtual const QHash &marks (); - virtual QPixmap markPixmap( MarkInterface::MarkTypes ) const; - virtual QString markDescription( MarkInterface::MarkTypes ) const; - virtual QColor markColor( MarkInterface::MarkTypes ) const; - virtual uint editableMarks() const; - - Q_SIGNALS: - void markToolTipRequested( KTextEditor::Document* document, KTextEditor::Mark mark, QPoint position, bool& handled ); - - void markContextMenuRequested( KTextEditor::Document* document, KTextEditor::Mark mark, QPoint pos, bool& handled ); - - void markClicked( KTextEditor::Document* document, KTextEditor::Mark mark, bool& handled ); - - void marksChanged( KTextEditor::Document* ); - void markChanged( KTextEditor::Document*, KTextEditor::Mark, KTextEditor::MarkInterface::MarkChangeAction ); - - private: - QHash m_marks; - QHash m_markPixmaps; - QHash m_markDescriptions; - uint m_editableMarks; - - // - // KTextEditor::PrintInterface - // - public Q_SLOTS: - bool printDialog (); - bool print (); - - // - // KTextEditor::DocumentInfoInterface ( ### unfinished ) - // - public: - /** - * @return the name of the mimetype for the document. - * - * This method is using KMimeType::findByUrl, and if the pointer - * is then still the default MimeType for a nonlocal or unsaved file, - * uses mimeTypeForContent(). - */ - virtual QString mimeType(); - - /** - * @return a pointer to the KMimeType for this document, found by analyzing the - * actual content. - * - * Note that this method is *not* part of the DocumentInfoInterface. - */ - KMimeType::Ptr mimeTypeForContent(); - - // - // KTextEditor::VariableInterface - // - public: - virtual QString variable( const QString &name ) const; - - Q_SIGNALS: - void variableChanged( KTextEditor::Document*, const QString &, const QString & ); - - private: - QMap m_storedVariables; - - // - // MovingInterface API - // - public: - /** - * Create a new moving cursor for this document. - * @param position position of the moving cursor to create - * @param insertBehavior insertion behavior - * @return new moving cursor for the document - */ - virtual KTextEditor::MovingCursor *newMovingCursor (const KTextEditor::Cursor &position, KTextEditor::MovingCursor::InsertBehavior insertBehavior = KTextEditor::MovingCursor::MoveOnInsert); - - /** - * Create a new moving range for this document. - * @param range range of the moving range to create - * @param insertBehaviors insertion behaviors - * @param emptyBehavior behavior on becoming empty - * @return new moving range for the document - */ - virtual KTextEditor::MovingRange *newMovingRange (const KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors = KTextEditor::MovingRange::DoNotExpand - , KTextEditor::MovingRange::EmptyBehavior emptyBehavior = KTextEditor::MovingRange::AllowEmpty); - - /** - * Current revision - * @return current revision - */ - virtual qint64 revision () const; - - /** - * Last revision the buffer got successful saved - * @return last revision buffer got saved, -1 if none - */ - virtual qint64 lastSavedRevision () const; - - /** - * Lock a revision, this will keep it around until released again. - * But all revisions will always be cleared on buffer clear() (and therefor load()) - * @param revision revision to lock - */ - virtual void lockRevision (qint64 revision); - - /** - * Release a revision. - * @param revision revision to release - */ - virtual void unlockRevision (qint64 revision); - - /** - * Transform a cursor from one revision to an other. - * @param cursor cursor to transform - * @param insertBehavior behavior of this cursor on insert of text at it's position - * @param fromRevision from this revision we want to transform - * @param toRevision to this revision we want to transform, default of -1 is current revision - */ - virtual void transformCursor (KTextEditor::Cursor &cursor, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1); - - /** - * Transform a cursor from one revision to an other. - * @param line line number of the cursor to transform - * @param column column number of the cursor to transform - * @param insertBehavior behavior of this cursor on insert of text at it's position - * @param fromRevision from this revision we want to transform - * @param toRevision to this revision we want to transform, default of -1 is current revision - */ - virtual void transformCursor (int& line, int& column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1); - - /** - * Transform a range from one revision to an other. - * @param range range to transform - * @param insertBehaviors behavior of this range on insert of text at it's position - * @param emptyBehavior behavior on becoming empty - * @param fromRevision from this revision we want to transform - * @param toRevision to this revision we want to transform, default of -1 is current revision - */ - virtual void transformRange (KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision = -1); - - // - // MovingInterface Signals - // - Q_SIGNALS: - /** - * This signal is emitted before the cursors/ranges/revisions of a document are destroyed as the document is deleted. - * @param document the document which the interface belongs too which is in the process of being deleted - */ - void aboutToDeleteMovingInterfaceContent (KTextEditor::Document *document); - - /** - * This signal is emitted before the ranges of a document are invalidated and the revisions are deleted as the document is cleared (for example on load/reload). - * While this signal is emitted, still the old document content is around before the clear. - * @param document the document which the interface belongs too which will invalidate its data - */ - void aboutToInvalidateMovingInterfaceContent (KTextEditor::Document *document); - - // - // Annotation Interface - // - public: - - virtual void setAnnotationModel( KTextEditor::AnnotationModel* model ); - virtual KTextEditor::AnnotationModel* annotationModel() const; - - Q_SIGNALS: - void annotationModelChanged( KTextEditor::AnnotationModel*, KTextEditor::AnnotationModel* ); - - private: - KTextEditor::AnnotationModel* m_annotationModel; - - // - // KParts::ReadWrite stuff - // - public: - /** - * open the file obtained by the kparts framework - * the framework abstracts the loading of remote files - * @return success - */ - virtual bool openFile (); - - /** - * save the file obtained by the kparts framework - * the framework abstracts the uploading of remote files - * @return success - */ - virtual bool saveFile (); - - virtual void setReadWrite ( bool rw = true ); - - virtual void setModified( bool m ); - - private: - void activateDirWatch (const QString &useFileName = QString()); - void deactivateDirWatch (); - - QString m_dirWatchFile; - - public: - /** - * Type chars in a view - */ - bool typeChars ( KateView *type, const QString &chars ); - - /** - * gets the last line number (lines() - 1) - */ - inline int lastLine() const { return lines()-1; } - - // Repaint all of all of the views - void repaintViews(bool paintOnlyDirty = true); - - KateHighlighting *highlight () const; - - public Q_SLOTS: //please keep prototypes and implementations in same order - void tagLines(int start, int end); - void tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end); - - //export feature, obsolute - public Q_SLOTS: - void exportAs(const QString&) { } - - Q_SIGNALS: - void preHighlightChanged(uint); - - private Q_SLOTS: - void internalHlChanged(); - - public: - void addView(KTextEditor::View *); - /** removes the view from the list of views. The view is *not* deleted. - * That's your job. Or, easier, just delete the view in the first place. - * It will remove itself. TODO: this could be converted to a private slot - * connected to the view's destroyed() signal. It is not currently called - * anywhere except from the KateView destructor. - */ - void removeView(KTextEditor::View *); - void setActiveView(KTextEditor::View*); - - bool ownedView(KateView *); - - uint toVirtualColumn( const KTextEditor::Cursor& ); - void newLine( KateView*view ); // Changes input - void backspace( KateView *view, const KTextEditor::Cursor& ); - void del( KateView *view, const KTextEditor::Cursor& ); - void transpose( const KTextEditor::Cursor& ); - - void paste ( KateView* view, QClipboard::Mode = QClipboard::Clipboard ); - - public: - void indent ( KTextEditor::Range range, int change ); - void comment ( KateView *view, uint line, uint column, int change ); - void align ( KateView *view, const KTextEditor::Range &range ); - void insertTab( KateView *view, const KTextEditor::Cursor& ); - - enum TextTransform { Uppercase, Lowercase, Capitalize }; - - /** - Handling uppercase, lowercase and capitalize for the view. - - If there is a selection, that is transformed, otherwise for uppercase or - lowercase the character right of the cursor is transformed, for capitalize - the word under the cursor is transformed. - */ - void transform ( KateView *view, const KTextEditor::Cursor &, TextTransform ); - /** - Unwrap a range of lines. - */ - void joinLines( uint first, uint last ); - - private: - bool removeStringFromBeginning(int line, const QString &str); - bool removeStringFromEnd(int line, const QString &str); - - /** - Find the position (line and col) of the next char - that is not a space. If found line and col point to the found character. - Otherwise they have both the value -1. - @param line Line of the character which is examined first. - @param col Column of the character which is examined first. - @return True if the specified or a following character is not a space - Otherwise false. - */ - bool nextNonSpaceCharPos(int &line, int &col); - - /** - Find the position (line and col) of the previous char - that is not a space. If found line and col point to the found character. - Otherwise they have both the value -1. - @return True if the specified or a preceding character is not a space. - Otherwise false. - */ - bool previousNonSpaceCharPos(int &line, int &col); - - /** - * Sets a comment marker as defined by the language providing the attribute - * @p attrib on the line @p line - */ - void addStartLineCommentToSingleLine(int line, int attrib=0); - /** - * Removes a comment marker as defined by the language providing the attribute - * @p attrib on the line @p line - */ - bool removeStartLineCommentFromSingleLine(int line, int attrib=0); - - /** - * @see addStartLineCommentToSingleLine. - */ - void addStartStopCommentToSingleLine(int line, int attrib=0); - /** - *@see removeStartLineCommentFromSingleLine. - */ - bool removeStartStopCommentFromSingleLine(int line, int attrib=0); - /** - *@see removeStartLineCommentFromSingleLine. - */ - bool removeStartStopCommentFromRegion(const KTextEditor::Cursor &start, const KTextEditor::Cursor &end, int attrib=0); - - /** - * Add a comment marker as defined by the language providing the attribute - * @p attrib to each line in the selection. - */ - void addStartStopCommentToSelection( KateView *view, int attrib=0 ); - /** - * @see addStartStopCommentToSelection. - */ - void addStartLineCommentToSelection( KateView *view, int attrib=0 ); - - /** - * Removes comment markers relevant to the language providing - * the attribuge @p attrib from each line in the selection. - * - * @return whether the operation succeeded. - */ - bool removeStartStopCommentFromSelection( KateView *view, int attrib=0 ); - /** - * @see removeStartStopCommentFromSelection. - */ - bool removeStartLineCommentFromSelection( KateView *view, int attrib=0 ); - - public: - QString getWord( const KTextEditor::Cursor& cursor ); - - public: - void newBracketMark( const KTextEditor::Cursor& start, KTextEditor::Range& bm, int maxLines = -1 ); - bool findMatchingBracket( KTextEditor::Range& range, int maxLines = -1 ); - - public: - virtual const QString &documentName () const { return m_docName; } - - void setDocName (QString docName); - - void lineInfo (KateLineInfo *info, unsigned int line); - - KateCodeFoldingTree *foldingTree (); - - public: - /** - * @return whether the document is modified on disk since last saved - */ - bool isModifiedOnDisc() { return m_modOnHd; } - - virtual void setModifiedOnDisk( ModifiedOnDiskReason reason ); - - virtual void setModifiedOnDiskWarning ( bool on ); - - public Q_SLOTS: - /** - * Ask the user what to do, if the file has been modified on disk. - * Reimplemented from KTextEditor::Document. - */ - virtual void slotModifiedOnDisk( KTextEditor::View *v = 0 ); - - /** - * Reloads the current document from disk if possible - */ - virtual bool documentReload (); - - virtual bool documentSave (); - virtual bool documentSaveAs (); - - virtual bool save(); - public: - virtual bool saveAs( const KUrl &url ); - private: - bool m_saveAs; - Q_SIGNALS: - /** - * Indicate this file is modified on disk - * @param doc the KTextEditor::Document object that represents the file on disk - * @param isModified indicates the file was modified rather than created or deleted - * @param reason the reason we are emitting the signal. - */ - void modifiedOnDisk (KTextEditor::Document *doc, bool isModified, KTextEditor::ModificationInterface::ModifiedOnDiskReason reason); - - public: - void ignoreModifiedOnDiskOnce(); - - private: - int m_isasking; // don't reenter slotModifiedOnDisk when this is true - // -1: ignore once, 0: false, 1: true - - public: - virtual bool setEncoding (const QString &e); - virtual const QString &encoding() const; - - - public Q_SLOTS: - void setWordWrap (bool on); - void setWordWrapAt (uint col); - - public: - bool wordWrap() const; - uint wordWrapAt() const; - - public Q_SLOTS: - void setPageUpDownMovesCursor(bool on); - - public: - bool pageUpDownMovesCursor() const; - - // code folding - public: - uint getRealLine(unsigned int virtualLine); - uint getVirtualLine(unsigned int realLine); - uint visibleLines (); - Kate::TextLine kateTextLine(uint i); - Kate::TextLine plainKateTextLine(uint i); - - Q_SIGNALS: - void codeFoldingUpdated(); - void aboutToRemoveText(const KTextEditor::Range&); - - private Q_SLOTS: - void slotModOnHdDirty (const QString &path); - void slotModOnHdCreated (const QString &path); - void slotModOnHdDeleted (const QString &path); - - private: - /** - * create a MD5 digest of the file, if it is a local file, - * and fill it into the string @p result. - * This is using KMD5::hexDigest(). - * - * @return wheather the operation was attempted and succeeded. - */ - bool createDigest ( QByteArray &result ); - - /** - * create a string for the modonhd warnings, giving the reason. - */ - QString reasonedMOHString() const; - - /** - * Removes all trailing whitespace form @p line, if - * the cfRemoveTrailingDyn confg flag is set, - * and the active view cursor is not on line and behind - * the last nonspace character. - */ - void removeTrailingSpace(int line); - inline void blockRemoveTrailingSpaces(bool block) - { m_blockRemoveTrailingSpaces = block; } - - private: - /// if true, removeTrailingSpace() returns immediately. - bool m_blockRemoveTrailingSpaces; - - public: - void updateFileType (const QString &newType, bool user = false); - - QString fileType () const { return m_fileType; } - - /** - * Get access to buffer of this document. - * Is needed to create cursors and ranges for example. - * @return document buffer - */ - KateBuffer &buffer () { return *m_buffer; } - - // - // REALLY internal data ;) - // - private: - // text buffer - KateBuffer *const m_buffer; - - // indenter - KateAutoIndent *const m_indenter; - - bool hlSetByUser; - bool m_bomSetByUser; - - bool m_modOnHd; - ModifiedOnDiskReason m_modOnHdReason; - QByteArray m_digest; // MD5 digest, updated on load/save - - QString m_docName; - int m_docNameNumber; - - // file type !!! - QString m_fileType; - bool m_fileTypeSetByUser; - - /** - * document is still reloading a file - */ - bool m_reloading; - - public Q_SLOTS: - void slotQueryClose_save(bool *handled, bool* abortClosing); - - public: - virtual bool queryClose(); - - void makeAttribs (bool needInvalidate = true); - - static bool checkOverwrite( KUrl u, QWidget *parent ); - - /** - * Configuration - */ - public: - KateDocumentConfig *config() { return m_config; } - KateDocumentConfig *config() const { return m_config; } - - void updateConfig (); - - private: - KateDocumentConfig *const m_config; - - /** - * Variable Reader - * TODO add register functionality/ktexteditor interface - */ - private: - /** - * read dir config file - */ - void readDirConfig (); - - /** - Reads all the variables in the document. - Called when opening/saving a document - */ - void readVariables(bool onlyViewAndRenderer = false); - - /** - Reads and applies the variables in a single line - TODO registered variables gets saved in a [map] - */ - void readVariableLine( QString t, bool onlyViewAndRenderer = false ); - /** - Sets a view variable in all the views. - */ - void setViewVariable( QString var, QString val ); - /** - @return weather a string value could be converted - to a bool value as supported. - The value is put in *result. - */ - static bool checkBoolValue( QString value, bool *result ); - /** - @return weather a string value could be converted - to a integer value. - The value is put in *result. - */ - static bool checkIntValue( QString value, int *result ); - /** - Feeds value into @p col using QColor::setNamedColor() and returns - wheather the color is valid - */ - static bool checkColorValue( QString value, QColor &col ); - - /** - * helper regex to capture the document variables - */ - static QRegExp kvLine; - static QRegExp kvLineWildcard; - static QRegExp kvLineMime; - static QRegExp kvVar; - - bool m_fileChangedDialogsActivated; - - // - // KTextEditor::ConfigInterface - // - public: - virtual QStringList configKeys() const; - virtual QVariant configValue(const QString &key); - virtual void setConfigValue(const QString &key, const QVariant &value); - - // - // KTextEditor::RecoveryInterface - // - virtual bool haveRecovery() const; - virtual void doRecovery(); - virtual void discardRecovery(); - - // - // KTextEditor::TemplateInterface + KTextEditor::TemplateInterface2 - // - public: - /** - * Starts a KateTemplateHandler for the given template. Multiple handlers may - * run at the same time, while only the last one created for this document - * will be active. - * - * \see KTextEditor::TemplateInterface::insertTemplateTextImplementation(), KateTemplateHandler - */ - virtual bool insertTemplateTextImplementation ( const KTextEditor::Cursor &c, - const QString &templateString, - const QMap &initialValues, - KTextEditor::TemplateScript* templateScript, - KateView *view); - - // - // KTextEditor::HighlightInterface - // - public: - virtual KTextEditor::Attribute::Ptr defaultStyle(const KTextEditor::HighlightInterface::DefaultStyle ds) const; - virtual QList< KTextEditor::HighlightInterface::AttributeBlock > lineAttributes(const unsigned int line); - virtual QStringList embeddedHighlightingModes() const; - virtual QString highlightingModeAt(const KTextEditor::Cursor& position); - - protected Q_SLOTS: - void dumpRegionTree(); - - private slots: - void slotCompleted(); - void slotCanceled(); - - private: - class LoadSaveFilterCheckPlugins; - - private: - bool m_savingToUrl; - void setPreSavePostDialogFilterChecks(QStringList plugins) {m_preSavePostDialogFilterChecks=plugins;} - QStringList m_preSavePostDialogFilterChecks; - void setPostSaveFilterChecks(QStringList plugins) {m_postSaveFilterChecks=plugins;} - QStringList m_postSaveFilterChecks; - void setPostLoadFilterChecks(QStringList plugins) {m_postLoadFilterChecks=plugins;} - QStringList m_postLoadFilterChecks; - static LoadSaveFilterCheckPlugins* loadSaveFilterCheckPlugins(); - - public: - QString defaultDictionary() const; - QList > dictionaryRanges() const; - bool isOnTheFlySpellCheckingEnabled() const; - - QString dictionaryForMisspelledRange(const KTextEditor::Range& range) const; - void clearMisspellingForWord(const QString& word); - - public Q_SLOTS: - void clearDictionaryRanges(); - void setDictionary(const QString& dict, const KTextEditor::Range &range); - void revertToDefaultDictionary(const KTextEditor::Range &range); - void setDefaultDictionary(const QString& dict); - void onTheFlySpellCheckingEnabled(bool enable); - void respellCheckBlock(int start, int end) {respellCheckBlock(this,start,end);} - void refreshOnTheFlyCheck(const KTextEditor::Range &range = KTextEditor::Range::invalid()); - - Q_SIGNALS: - void respellCheckBlock(KateDocument *document,int start, int end); - void dictionaryRangesPresent(bool yesNo); - void defaultDictionaryChanged(KateDocument *document); - - public: - bool containsCharacterEncoding(const KTextEditor::Range& range); - - typedef QList > OffsetList; - - int computePositionWrtOffsets(const OffsetList& offsetList, int pos); - - /** - * The first OffsetList is from decoded to encoded, and the second OffsetList from - * encoded to decoded. - **/ - QString decodeCharacters(const KTextEditor::Range& range, - KateDocument::OffsetList& decToEncOffsetList, - KateDocument::OffsetList& encToDecOffsetList); - void replaceCharactersByEncoding(const KTextEditor::Range& range); - - enum EncodedCharaterInsertionPolicy {EncodeAlways, EncodeWhenPresent, EncodeNever}; - - protected: - KateOnTheFlyChecker *m_onTheFlyChecker; - QString m_defaultDictionary; - QList > m_dictionaryRanges; - - // from KTextEditor::MovingRangeFeedback - void rangeInvalid(KTextEditor::MovingRange *movingRange); - void rangeEmpty(KTextEditor::MovingRange *movingRange); - - void deleteDictionaryRange(KTextEditor::MovingRange *movingRange); - - private: - Kate::SwapFile *m_swapfile; - public: - Kate::SwapFile* swapFile(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/document/katedocumenthelpers.cpp b/part/document/katedocumenthelpers.cpp deleted file mode 100644 index 7d7f176..0000000 --- a/part/document/katedocumenthelpers.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katedocumenthelpers.h" -#include "katedocumenthelpers.moc" - -#include "katedocument.h" -#include "kateview.h" - -#include -#include - -namespace KTextEditor { class View; } - -KateBrowserExtension::KateBrowserExtension( KateDocument* doc ) -: KParts::BrowserExtension( doc ), - m_doc (doc) -{ - setObjectName( "katepartbrowserextension" ); - emit enableAction( "print", true ); -} - -void KateBrowserExtension::print() -{ - m_doc->printDialog(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/document/katedocumenthelpers.h b/part/document/katedocumenthelpers.h deleted file mode 100644 index b031131..0000000 --- a/part/document/katedocumenthelpers.h +++ /dev/null @@ -1,61 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef __KATE_DOCUMENT_HELPERS__ -#define __KATE_DOCUMENT_HELPERS__ - -#include - -#include -#include - -class KateDocument; - -/** - * Interface for embedding KateDocument into a browser - */ -class KateBrowserExtension : public KParts::BrowserExtension -{ - Q_OBJECT - - public: - /** - * Constructor - * @param doc parent document - */ - explicit KateBrowserExtension( KateDocument* doc ); - - public Q_SLOTS: - /** - * print the current file - */ - void print(); - - private: - /** - * parent document - */ - KateDocument* m_doc; -}; - -#endif - diff --git a/part/katepartprivate_export.h b/part/katepartprivate_export.h deleted file mode 100644 index 0ecac15..0000000 --- a/part/katepartprivate_export.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2007 David Faure - * Copyright (C) 2009 by Bernhard Beschow - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATEPARTPRIVATE_EXPORT_H -#define KATEPARTPRIVATE_EXPORT_H - -/* needed for KDE_EXPORT and KDE_IMPORT macros */ -#include - -#if defined(KDELIBS_STATIC_LIBS) - /* No export/import for static libraries */ -# define KATEPART_TESTS_EXPORT -#elif defined(MAKE_KATEPARTINTERFACES_LIB) - /* We build the test library, so export symbols */ - #define KATEPART_TESTS_EXPORT KDE_EXPORT -#else - /* We are using this library */ - #define KATEPART_TESTS_EXPORT KDE_IMPORT -#endif - -#endif // KATEPARTPRIVATE_EXPORT_H diff --git a/part/mode/katemodeconfigpage.cpp b/part/mode/katemodeconfigpage.cpp deleted file mode 100644 index 25c5062..0000000 --- a/part/mode/katemodeconfigpage.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN Includes -#include "katemodeconfigpage.h" -#include "katemodeconfigpage.moc" - -#include "katedocument.h" -#include "kateconfig.h" -#include "kateview.h" -#include "kateglobal.h" -#include "kateautoindent.h" -#include "katesyntaxmanager.h" -#include "katesyntaxdocument.h" - -#include "ui_filetypeconfigwidget.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#define KATE_FT_HOWMANY 1024 -//END Includes - -ModeConfigPage::ModeConfigPage( QWidget *parent ) - : KateConfigPage( parent ) -{ - m_lastType = -1; - - // This will let us have more separation between this page and - // the KTabWidget edge (ereslibre) - QVBoxLayout *layout = new QVBoxLayout; - QWidget *newWidget = new QWidget(this); - - ui = new Ui::FileTypeConfigWidget(); - ui->setupUi( newWidget ); - - ui->cmbHl->addItem(i18n(""), QVariant("")); - for( int i = 0; i < KateHlManager::self()->highlights(); i++) { - if (KateHlManager::self()->hlSection(i).length() > 0) - ui->cmbHl->addItem(KateHlManager::self()->hlSection(i) + QString ("/") - + KateHlManager::self()->hlNameTranslated(i), QVariant(KateHlManager::self()->hlName(i))); - else - ui->cmbHl->addItem(KateHlManager::self()->hlNameTranslated(i), QVariant(KateHlManager::self()->hlName(i))); - } - - QStringList indentationModes; - indentationModes << i18n ("Use Default"); - indentationModes << KateAutoIndent::listModes(); - ui->cmbIndenter->addItems (indentationModes); - - connect( ui->cmbFiletypes, SIGNAL(activated(int)), this, SLOT(typeChanged(int)) ); - connect( ui->btnNew, SIGNAL(clicked()), this, SLOT(newType()) ); - connect( ui->btnDelete, SIGNAL(clicked()), this, SLOT(deleteType()) ); - ui->btnMimeTypes->setIcon(KIcon("tools-wizard")); - connect(ui->btnMimeTypes, SIGNAL(clicked()), this, SLOT(showMTDlg())); - connect( ui->btnDownload, SIGNAL(clicked()), this, SLOT(hlDownload()) ); - - reload(); - - connect( ui->edtName, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( ui->edtSection, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( ui->edtVariables, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( ui->edtFileExtensions, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( ui->edtMimeTypes, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotChanged() ) ); - connect( ui->sbPriority, SIGNAL( valueChanged ( int ) ), this, SLOT( slotChanged() ) ); - connect( ui->cmbHl, SIGNAL(activated(int)), this, SLOT(slotChanged()) ); - connect( ui->cmbIndenter, SIGNAL(activated(int)), this, SLOT(slotChanged()) ); - - layout->addWidget(newWidget); - setLayout(layout); -} - -ModeConfigPage::~ModeConfigPage () -{ - qDeleteAll (m_types); - delete ui; -} - -void ModeConfigPage::apply() -{ - if (!hasChanged()) - return; - - save (); - - KateGlobal::self()->modeManager()->save(m_types); -} - -void ModeConfigPage::reload() -{ - qDeleteAll (m_types); - m_types.clear(); - - // deep copy... - foreach (KateFileType *type, KateGlobal::self()->modeManager()->list()) - { - KateFileType *t = new KateFileType (); - *t = *type; - m_types.append (t); - } - - update (); -} - -void ModeConfigPage::reset() -{ - reload (); -} - -void ModeConfigPage::defaults() -{ - reload (); -} - -void ModeConfigPage::update () -{ - m_lastType = -1; - - ui->cmbFiletypes->clear (); - - foreach (KateFileType *type, m_types) { - QString typeName = i18nc("Language", type->name.toUtf8()); - if (type->section.length() > 0) - ui->cmbFiletypes->addItem(type->section + QString ("/") + typeName); - else - ui->cmbFiletypes->addItem(typeName); - } - - ui->cmbFiletypes->setCurrentIndex (0); - - typeChanged (0); - - ui->cmbFiletypes->setEnabled (ui->cmbFiletypes->count() > 0); -} - -void ModeConfigPage::deleteType () -{ - int type = ui->cmbFiletypes->currentIndex (); - - if (type > -1 && type < m_types.count()) - { - delete m_types[type]; - m_types.removeAt(type); - update (); - } -} - -void ModeConfigPage::newType () -{ - QString newN = i18n("New Filetype"); - - for (int i = 0; i < m_types.count(); ++i) { - KateFileType *type = m_types.at(i); - if (type->name == newN) - { - ui->cmbFiletypes->setCurrentIndex (i); - typeChanged (i); - return; - } - } - - KateFileType *newT = new KateFileType (); - newT->priority = 0; - newT->name = newN; - newT->hlGenerated = false; - - m_types.prepend (newT); - - update (); -} - -void ModeConfigPage::save () -{ - if (m_lastType != -1) - { - m_types[m_lastType]->name = ui->edtName->text (); - m_types[m_lastType]->section = ui->edtSection->text (); - m_types[m_lastType]->varLine = ui->edtVariables->text (); - m_types[m_lastType]->wildcards = ui->edtFileExtensions->text().split (';', QString::SkipEmptyParts); - m_types[m_lastType]->mimetypes = ui->edtMimeTypes->text().split (';', QString::SkipEmptyParts); - m_types[m_lastType]->priority = ui->sbPriority->value(); - m_types[m_lastType]->hl = ui->cmbHl->itemData(ui->cmbHl->currentIndex()).toString(); - - if (ui->cmbIndenter->currentIndex() > 0) - m_types[m_lastType]->indenter = KateAutoIndent::modeName (ui->cmbIndenter->currentIndex() - 1); - else - m_types[m_lastType]->indenter = ""; - } -} - -void ModeConfigPage::typeChanged (int type) -{ - save (); - - ui->cmbHl->setEnabled (true); - ui->btnDelete->setEnabled (true); - ui->edtName->setEnabled (true); - ui->edtSection->setEnabled (true); - - if (type > -1 && type < m_types.count()) - { - KateFileType *t = m_types.at(type); - - ui->gbProperties->setTitle (i18n("Properties of %1", ui->cmbFiletypes->currentText())); - - ui->gbProperties->setEnabled (true); - ui->btnDelete->setEnabled (true); - - ui->edtName->setText(t->name); - ui->edtSection->setText(t->section); - ui->edtVariables->setText(t->varLine); - ui->edtFileExtensions->setText(t->wildcards.join (";")); - ui->edtMimeTypes->setText(t->mimetypes.join (";")); - ui->sbPriority->setValue(t->priority); - - ui->cmbHl->setEnabled (!t->hlGenerated); - ui->btnDelete->setEnabled (!t->hlGenerated); - ui->edtName->setEnabled (!t->hlGenerated); - ui->edtSection->setEnabled (!t->hlGenerated); - - // activate current hl... - for (int i = 0; i < ui->cmbHl->count(); ++i) - if (ui->cmbHl->itemData (i).toString() == t->hl) - ui->cmbHl->setCurrentIndex (i); - - // activate the right indenter - int indenterIndex = 0; - if (!t->indenter.isEmpty()) - indenterIndex = KateAutoIndent::modeNumber (t->indenter) + 1; - ui->cmbIndenter->setCurrentIndex (indenterIndex); - } - else - { - ui->gbProperties->setTitle (i18n("Properties")); - - ui->gbProperties->setEnabled (false); - ui->btnDelete->setEnabled (false); - - ui->edtName->clear(); - ui->edtSection->clear(); - ui->edtVariables->clear(); - ui->edtFileExtensions->clear(); - ui->edtMimeTypes->clear(); - ui->sbPriority->setValue(0); - ui->cmbHl->setCurrentIndex (0); - ui->cmbIndenter->setCurrentIndex (0); - } - - m_lastType = type; -} - -void ModeConfigPage::showMTDlg() -{ - QString text = i18n("Select the MimeTypes you want for this file type.\nPlease note that this will automatically edit the associated file extensions as well."); - QStringList list = ui->edtMimeTypes->text().split( QRegExp("\\s*;\\s*"), QString::SkipEmptyParts ); - KMimeTypeChooserDialog d( i18n("Select Mime Types"), text, list, "text", this ); - if ( d.exec() == KDialog::Accepted ) { - // do some checking, warn user if mime types or patterns are removed. - // if the lists are empty, and the fields not, warn. - ui->edtFileExtensions->setText( d.chooser()->patterns().join(";") ); - ui->edtMimeTypes->setText( d.chooser()->mimeTypes().join(";") ); - } -} - -void ModeConfigPage::hlDownload() -{ - KateHlDownloadDialog diag(this,"hlDownload",true); - diag.exec(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katemodeconfigpage.h b/part/mode/katemodeconfigpage.h deleted file mode 100644 index 74dfe14..0000000 --- a/part/mode/katemodeconfigpage.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_MODECONFIGPAGE_H__ -#define KATE_MODECONFIGPAGE_H__ - -#include -#include -#include - -#include "katedialogs.h" -#include "katemodemanager.h" - - -namespace Ui -{ - class FileTypeConfigWidget; -} - -class ModeConfigPage : public KateConfigPage -{ - Q_OBJECT - - public: - explicit ModeConfigPage( QWidget *parent ); - ~ModeConfigPage (); - - public Q_SLOTS: - void apply(); - void reload(); - void reset(); - void defaults(); - - private Q_SLOTS: - void update (); - void deleteType (); - void newType (); - void typeChanged (int type); - void showMTDlg(); - void save (); - void hlDownload (); - - private: - Ui::FileTypeConfigWidget *ui; - - QList m_types; - int m_lastType; -}; - -#endif -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katemodemanager.cpp b/part/mode/katemodemanager.cpp deleted file mode 100644 index dcf75c7..0000000 --- a/part/mode/katemodemanager.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN Includes -#include "katemodemanager.h" -#include "katewildcardmatcher.h" - -#include "katedocument.h" -#include "kateconfig.h" -#include "kateview.h" -#include "kateglobal.h" -#include "katesyntaxmanager.h" -#include "katesyntaxdocument.h" - -#include "ui_filetypeconfigwidget.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#define KATE_FT_HOWMANY 1024 -//END Includes - -KateModeManager::KateModeManager () -{ - update (); -} - -KateModeManager::~KateModeManager () -{ - qDeleteAll (m_types); -} - -// -// read the types from config file and update the internal list -// -void KateModeManager::update () -{ - KConfig config ("katemoderc", KConfig::NoGlobals); - - QStringList g (config.groupList()); - - qDeleteAll (m_types); - m_types.clear (); - m_name2Type.clear (); - for (int z=0; z < g.count(); z++) - { - KConfigGroup cg(&config, g[z]); - - KateFileType *type = new KateFileType (); - type->number = z; - type->name = g[z]; - type->section = cg.readEntry ("Section"); - type->wildcards = cg.readXdgListEntry ("Wildcards"); - type->mimetypes = cg.readXdgListEntry ("Mimetypes"); - type->priority = cg.readEntry ("Priority", 0); - type->varLine = cg.readEntry ("Variables"); - type->indenter = cg.readEntry ("Indenter"); - - type->hl = cg.readEntry ("Highlighting"); - - // only for generated types... - type->hlGenerated = cg.readEntry ("Highlighting Generated", false); - type->version = cg.readEntry ("Highlighting Version"); - - // insert into the list + hash... - m_types.append(type); - m_name2Type.insert (type->name, type); - } - - // try if the hl stuff is up to date... - const KateSyntaxModeList &modes = KateHlManager::self()->syntaxDocument()->modeList(); - for (int i = 0; i < modes.size(); ++i) - { - KateFileType *type = 0; - bool newType = false; - if (m_name2Type.contains (modes[i]->name)) - type = m_name2Type[modes[i]->name]; - else - { - newType = true; - type = new KateFileType (); - type->name = modes[i]->name; - type->priority = 0; - m_types.append (type); - m_name2Type.insert (type->name, type); - } - - if (newType || type->version != modes[i]->version) - { - type->name = modes[i]->name; - type->section = modes[i]->section; - type->wildcards = modes[i]->extension.split (';', QString::SkipEmptyParts); - type->mimetypes = modes[i]->mimetype.split (';', QString::SkipEmptyParts); - type->priority = modes[i]->priority.toInt(); - type->version = modes[i]->version; - type->indenter = modes[i]->indenter; - type->hl = modes[i]->name; - type->hlGenerated = true; - } - } - - // sort the list... - QList newList; - for (int i=0; i < m_types.count(); i++) - { - KateFileType *t = m_types[i]; - - int insert = 0; - for (; insert <= newList.count(); insert++) - { - if (insert == newList.count()) - break; - - if ( QString(newList.at(insert)->section + newList.at(insert)->name).toLower() - > QString(t->section + t->name).toLower() ) - break; - } - - newList.insert (insert, t); - } - - // replace old list with new sorted list... - m_types = newList; - - // add the none type... - KateFileType *t = new KateFileType (); - t->name = "Normal"; - t->hl = "None"; - t->hlGenerated = true; - - m_types.prepend (t); -} - -// -// save the given list to config file + update -// -void KateModeManager::save (const QList& v) -{ - KConfig katerc("katemoderc", KConfig::NoGlobals); - - QStringList newg; - foreach (const KateFileType *type, v) - { - KConfigGroup config(&katerc, type->name); - - config.writeEntry ("Section", type->section); - config.writeXdgListEntry ("Wildcards", type->wildcards); - config.writeXdgListEntry ("Mimetypes", type->mimetypes); - config.writeEntry ("Priority", type->priority); - config.writeEntry ("Indenter", type->indenter); - - QString varLine = type->varLine; - if (QRegExp("kate:(.*)").indexIn(varLine) < 0) - varLine.prepend ("kate: "); - - config.writeEntry ("Variables", varLine); - - config.writeEntry ("Highlighting", type->hl); - - // only for generated types... - config.writeEntry ("Highlighting Generated", type->hlGenerated); - config.writeEntry ("Highlighting Version", type->version); - - newg << type->name; - } - - foreach (const QString &groupName, katerc.groupList()) - { - if (newg.indexOf (groupName) == -1) - { - katerc.deleteGroup (groupName); - } - } - - katerc.sync (); - - update (); -} - -QString KateModeManager::fileType (KateDocument *doc) -{ - kDebug(13020); - if (!doc) - return ""; - - if (m_types.isEmpty()) - return ""; - - QString fileName = doc->url().prettyUrl(); - int length = doc->url().prettyUrl().length(); - - QString result; - - // Try wildcards - if ( ! fileName.isEmpty() ) - { - static const QStringList commonSuffixes = QString(".orig;.new;~;.bak;.BAK").split (';'); - - if (!(result = wildcardsFind(fileName)).isEmpty()) - return result; - - QString backupSuffix = KateDocumentConfig::global()->backupSuffix(); - if (fileName.endsWith(backupSuffix)) { - if (!(result = wildcardsFind(fileName.left(length - backupSuffix.length()))).isEmpty()) - return result; - } - - for (QStringList::ConstIterator it = commonSuffixes.begin(); it != commonSuffixes.end(); ++it) { - if (*it != backupSuffix && fileName.endsWith(*it)) { - if (!(result = wildcardsFind(fileName.left(length - (*it).length()))).isEmpty()) - return result; - } - } - } - - // Try content-based mimetype - KMimeType::Ptr mt = doc->mimeTypeForContent(); - - QList types; - - foreach (KateFileType *type, m_types) - { - if (type->mimetypes.indexOf (mt->name()) > -1) - types.append (type); - } - - if ( !types.isEmpty() ) - { - int pri = -1; - QString name; - - foreach (KateFileType *type, types) - { - if (type->priority > pri) - { - pri = type->priority; - name = type->name; - } - } - - return name; - } - - - return ""; -} - -QString KateModeManager::wildcardsFind (const QString &fileName) -{ - KateFileType * match = NULL; - int minPrio = -1; - foreach (KateFileType *type, m_types) - { - if (type->priority <= minPrio) { - continue; - } - - foreach (const QString &wildcard, type->wildcards) - { - if (KateWildcardMatcher::exactMatch(fileName, wildcard)) { - match = type; - minPrio = type->priority; - break; - } - } - } - - return (match == NULL) ? "" : match->name; -} - -const KateFileType& KateModeManager::fileType(const QString &name) const -{ - for (int i = 0; i < m_types.size(); ++i) - if (m_types[i]->name == name) - return *m_types[i]; - - static KateFileType notype; - return notype; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katemodemanager.h b/part/mode/katemodemanager.h deleted file mode 100644 index 85c3edf..0000000 --- a/part/mode/katemodemanager.h +++ /dev/null @@ -1,92 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_MODEMANAGER_H__ -#define KATE_MODEMANAGER_H__ - -#include -#include -#include - -#include "katedialogs.h" - -class KateDocument; - -class KateFileType -{ - public: - int number; - QString name; - QString section; - QStringList wildcards; - QStringList mimetypes; - int priority; - QString varLine; - QString hl; - bool hlGenerated; - QString version; - QString indenter; - - KateFileType() - : number(-1), priority(0), hlGenerated(false) - {} -}; - -class KateModeManager -{ - public: - KateModeManager (); - ~KateModeManager (); - - /** - * File Type Config changed, update all docs (which will take care of views/renderers) - */ - void update (); - - void save (const QList& v); - - /** - * get the right fileType for the given document - * -1 if none found ! - */ - QString fileType (KateDocument *doc); - - /** - * Don't store the pointer somewhere longer times, won't be valid after the next update() - */ - const KateFileType& fileType (const QString &name) const; - - /** - * Don't modify - */ - const QList& list() const { return m_types; } - - private: - QString wildcardsFind (const QString &fileName); - - private: - QList m_types; - QHash m_name2Type; - -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katemodemenu.cpp b/part/mode/katemodemenu.cpp deleted file mode 100644 index 4b1e5ce..0000000 --- a/part/mode/katemodemenu.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN Includes -#include "katemodemenu.h" -#include "katemodemenu.moc" - -#include "katedocument.h" -#include "kateconfig.h" -#include "kateview.h" -#include "kateglobal.h" -#include "katesyntaxmanager.h" -#include "katesyntaxdocument.h" - -#include "ui_filetypeconfigwidget.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#define KATE_FT_HOWMANY 1024 -//END Includes - -void KateModeMenu::init() -{ - m_doc = 0; - - connect( menu(), SIGNAL( triggered( QAction* ) ), this, SLOT( setType( QAction* ) ) ); - - connect(menu(),SIGNAL(aboutToShow()),this,SLOT(slotAboutToShow())); - - m_actionGroup = new QActionGroup(menu()); -} - -KateModeMenu::~KateModeMenu( ) -{ - qDeleteAll(subMenus); -} - -void KateModeMenu::updateMenu (KTextEditor::Document *doc) -{ - m_doc = (KateDocument *)doc; -} - -void KateModeMenu::slotAboutToShow() -{ - KateDocument *doc=m_doc; - int count = KateGlobal::self()->modeManager()->list().count(); - - for (int z=0; zmodeManager()->list().at(z)->name; - QString hlSection = KateGlobal::self()->modeManager()->list().at(z)->section; - - if ( !hlSection.isEmpty() && !names.contains(hlName) ) - { - if (!subMenusName.contains(hlSection)) - { - subMenusName << hlSection; - QMenu *qmenu = new QMenu (hlSection); - connect( qmenu, SIGNAL( triggered( QAction* ) ), this, SLOT( setType( QAction* ) ) ); - subMenus.append(qmenu); - menu()->addMenu (qmenu); - } - - int m = subMenusName.indexOf (hlSection); - names << hlName; - QAction *action = subMenus.at(m)->addAction ( hlName ); - m_actionGroup->addAction(action); - action->setCheckable( true ); - action->setData( hlName ); - } - else if (!names.contains(hlName)) - { - names << hlName; - - disconnect( menu(), SIGNAL( triggered( QAction* ) ), this, SLOT( setType( QAction* ) ) ); - connect( menu(), SIGNAL( triggered( QAction* ) ), this, SLOT( setType( QAction* ) ) ); - - QAction *action = menu()->addAction ( hlName ); - m_actionGroup->addAction(action); - action->setCheckable( true ); - action->setData( hlName ); - } - } - - if (!doc) return; - - for (int i=0;i actions = subMenus.at( i )->actions(); - for ( int j = 0; j < actions.count(); ++j ) - actions[ j ]->setChecked( false ); - } - - QList actions = menu()->actions(); - for ( int i = 0; i < actions.count(); ++i ) - actions[ i ]->setChecked( false ); - - if (doc->fileType().isEmpty() || doc->fileType() == "Normal") { - for ( int i = 0; i < actions.count(); ++i ) { - if ( actions[ i ]->data().toString() == "Normal" ) - actions[ i ]->setChecked( true ); - } - } else { - if (!doc->fileType().isEmpty()) - { - const KateFileType& t = KateGlobal::self()->modeManager()->fileType(doc->fileType()); - int i = subMenusName.indexOf (t.section); - if (i >= 0 && subMenus.at(i)) { - QList actions = subMenus.at( i )->actions(); - for ( int j = 0; j < actions.count(); ++j ) { - if ( actions[ j ]->data().toString() == doc->fileType() ) - actions[ j ]->setChecked( true ); - } - } else { - QList actions = menu()->actions(); - for ( int j = 0; j < actions.count(); ++j ) { - if ( actions[ j ]->data().toString().isEmpty() ) - actions[ j ]->setChecked( true ); - } - } - } - } -} - -void KateModeMenu::setType (QAction *action) -{ - KateDocument *doc=m_doc; - - if (doc) { - doc->updateFileType(action->data().toString(), true); - } -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katemodemenu.h b/part/mode/katemodemenu.h deleted file mode 100644 index 4cf6373..0000000 --- a/part/mode/katemodemenu.h +++ /dev/null @@ -1,63 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_MODEMENU_H__ -#define KATE_MODEMENU_H__ - -#include -#include -#include - -#include "katedialogs.h" -#include "katemodemanager.h" - -class KateDocument; - -class KateModeMenu : public KActionMenu -{ - Q_OBJECT - - public: - KateModeMenu(const QString& text, QObject *parent) - : KActionMenu(text, parent) { init(); } - - ~KateModeMenu(); - - void updateMenu (KTextEditor::Document *doc); - - private: - void init(); - - QPointer m_doc; - QStringList subMenusName; - QStringList names; - QList subMenus; - QActionGroup *m_actionGroup; - - public Q_SLOTS: - void slotAboutToShow(); - - private Q_SLOTS: - void setType (QAction*); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/mode/katewildcardmatcher.cpp b/part/mode/katewildcardmatcher.cpp deleted file mode 100644 index 270fbe3..0000000 --- a/part/mode/katewildcardmatcher.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Sebastian Pipping - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katewildcardmatcher.h" -#include -#include - - - -namespace KateWildcardMatcher { - - - -bool exactMatch(const QString & candidate, const QString & wildcard, int candidatePosFromRight, - int wildcardPosFromRight, bool caseSensitive = true) { - for (; wildcardPosFromRight >= 0; wildcardPosFromRight--) { - const ushort ch = wildcard[wildcardPosFromRight].unicode(); - switch (ch) { - case L'*': - if (candidatePosFromRight == -1) { - break; - } - - if (wildcardPosFromRight == 0) { - return true; - } - - // Eat all we can and go back as far as we have to - for (int j = -1; j <= candidatePosFromRight; j++) { - if (exactMatch(candidate, wildcard, j, wildcardPosFromRight - 1)) { - return true; - } - } - return false; - - case L'?': - if (candidatePosFromRight == -1) { - return false; - } - - candidatePosFromRight--; - break; - - default: - if (candidatePosFromRight == -1) { - return false; - } - - const ushort candidateCh = candidate[candidatePosFromRight].unicode(); - const bool match = caseSensitive - ? (candidateCh == ch) - : (QChar::toLower(candidateCh) == QChar::toLower(ch)); - if (match) { - candidatePosFromRight--; - } else { - return false; - } - } - } - return true; -} - - - -bool exactMatch(const QString & candidate, const QString & wildcard, - bool caseSensitive) { - return exactMatch(candidate, wildcard, candidate.length() - 1, - wildcard.length() - 1, caseSensitive); -} - - - -} - diff --git a/part/mode/katewildcardmatcher.h b/part/mode/katewildcardmatcher.h deleted file mode 100644 index 9b6cc46..0000000 --- a/part/mode/katewildcardmatcher.h +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Sebastian Pipping - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_WILDCARD_MATCHER_H -#define KATE_WILDCARD_MATCHER_H - - - -class QString; - - - -namespace KateWildcardMatcher { - - /** - * Matches a string against a given wildcard. - * The wildcard supports '*' (".*" in regex) and '?' ("." in regex), not more. - * - * @param candidate Text to match - * @param wildcard Wildcard to use - * @param caseSensitive Case-sensitivity flag - * @return True for an exact match, false otherwise - */ - bool exactMatch(const QString & candidate, const QString & wildcard, - bool caseSensitive = true); - -} - - - -#endif // KATE_WILDCARD_MATCHER_H - diff --git a/part/mode/testing/katewildcardmatcher_test.cpp b/part/mode/testing/katewildcardmatcher_test.cpp deleted file mode 100644 index 20c1167..0000000 --- a/part/mode/testing/katewildcardmatcher_test.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Sebastian Pipping - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "../katewildcardmatcher.h" -#include -#include - - - -bool testCase(const char * candidate, const char * wildcard) { - qDebug("\"%s\" / \"%s\"", candidate, wildcard); - return KateWildcardMatcher::exactMatch(QString(candidate), QString(wildcard)); -} - - - -int main() { - Q_ASSERT(testCase("abc.txt", "*.txt")); - Q_ASSERT(!testCase("abc.txt", "*.cpp")); - - Q_ASSERT(testCase("Makefile.am", "*Makefile*")); - - Q_ASSERT(testCase("control", "control")); - - Q_ASSERT(testCase("abcd", "a??d")); - - Q_ASSERT(testCase("a", "?")); - Q_ASSERT(testCase("a", "*?*")); - Q_ASSERT(testCase("a", "*")); - Q_ASSERT(testCase("a", "**")); - Q_ASSERT(testCase("a", "***")); - - Q_ASSERT(testCase("", "*")); - Q_ASSERT(testCase("", "**")); - Q_ASSERT(!testCase("", "?")); - - Q_ASSERT(testCase("ab", "a*")); - Q_ASSERT(testCase("ab", "*b")); - Q_ASSERT(testCase("ab", "a?")); - Q_ASSERT(testCase("ab", "?b")); - - Q_ASSERT(testCase("aXXbXXbYYaYc", "a*b*c")); - - - qDebug() << endl << "DONE"; - return 0; -} - diff --git a/part/mode/testing/testing.pro b/part/mode/testing/testing.pro deleted file mode 100644 index 1583780..0000000 --- a/part/mode/testing/testing.pro +++ /dev/null @@ -1,7 +0,0 @@ -SOURCES += \ - ../katewildcardmatcher.cpp \ - katewildcardmatcher_test.cpp \ - -HEADERS += \ - ../katewildcardmatcher.h \ - diff --git a/part/plugins/CMakeLists.txt b/part/plugins/CMakeLists.txt deleted file mode 100644 index c14d6c7..0000000 --- a/part/plugins/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -include_directories( ${KDE4_KIO_INCLUDES} ) - -add_subdirectory( hlselection ) -add_subdirectory( insertfile ) -add_subdirectory( kdatatool ) -add_subdirectory( exporter ) -add_subdirectory( autobrace ) -add_subdirectory( kte_iconinserter ) -add_subdirectory( kte_insanehtml_le ) -add_subdirectory( pythonencoding ) -# This plugin is for howto-write-a-plugin purposes. It is not meant to be -# installed. If you want to do so, just uncomment the add_subdirectory line. -# -# add_subdirectory( timedate ) diff --git a/part/plugins/Messages.sh b/part/plugins/Messages.sh deleted file mode 100644 index 7e0311d..0000000 --- a/part/plugins/Messages.sh +++ /dev/null @@ -1,9 +0,0 @@ -#! /usr/bin/env bash -$EXTRACTRC `find -name "*.rc"` >> rc.cpp -find -name "*.cpp" -print > files -find -name "*.cc" -print >> files -find -name "*.h" -print >> files -$XGETTEXT --files-from=files -o $podir/ktexteditor_plugins.pot -rm -f files -rm -f rc.cpp - diff --git a/part/plugins/autobookmarker/CMakeLists.txt b/part/plugins/autobookmarker/CMakeLists.txt deleted file mode 100644 index 81e9621..0000000 --- a/part/plugins/autobookmarker/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ - -########### next target ############### - -set(ktexteditor_autobookmarker_PART_SRCS autobookmarker.cpp ) - - -kde4_add_plugin(ktexteditor_autobookmarker ${ktexteditor_autobookmarker_PART_SRCS}) - -target_link_libraries(ktexteditor_autobookmarker ${KDE4_KDECORE_LIBS} ktexteditor ) - -install(TARGETS ktexteditor_autobookmarker DESTINATION ${PLUGIN_INSTALL_DIR} ) - - -########### install files ############### - -install( FILES ktexteditor_autobookmarkerrc DESTINATION ${CONFIG_INSTALL_DIR} ) -install( FILES ktexteditor_autobookmarker.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) - - - - diff --git a/part/plugins/autobookmarker/autobookmarker.cpp b/part/plugins/autobookmarker/autobookmarker.cpp deleted file mode 100644 index 39a2ca3..0000000 --- a/part/plugins/autobookmarker/autobookmarker.cpp +++ /dev/null @@ -1,519 +0,0 @@ -/* - This library is free software you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - - --- - file: autobookmarker.cpp - - KTextEditor plugin to add bookmarks to documents. - Copyright Anders Lund , 2003 -*/ - -//BEGIN includes -#include "autobookmarker.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -//Added by qt3to4: -#include -#include -#include - -//#include -//END includes - -//BEGIN AutoBookmarker -K_PLUGIN_FACTORY( AutoBookmarkerFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( AutoBookmarkerFactory( "ktexteditor_autobookmarker", "ktexteditor_plugins" ) ) - -AutoBookmarker::AutoBookmarker( QObject *parent, - const char* name, - const QVariantList& /*args*/ ) - : KTextEditor::Plugin ( (KTextEditor::Document*) parent, name ), - KTextEditor::ConfigInterfaceExtension() -{ - if ( parent ) - connect( parent, SIGNAL( completed() ), this, SLOT( slotCompleted() ) ); -} - -void AutoBookmarker::addView(KTextEditor::View */*view*/) -{ -} - -void AutoBookmarker::removeView(KTextEditor::View */*view*/) -{ -} - -KTextEditor::ConfigPage * AutoBookmarker::configPage( uint /*number*/, QWidget *parent, const char *name ) -{ - return new AutoBookmarkerConfigPage( parent, name ); -} - -QString AutoBookmarker::configPageName( uint /*p*/ ) const -{ -// switch (p) -// { -// case 0: - return i18n("AutoBookmarks"); -// default: -// return ""; -// } -} - -QString AutoBookmarker::configPageFullName( uint /*p*/ ) const -{ -// switch (p) -// { -// case 0: - return i18n("Configure AutoBookmarks"); -// default: -// return ""; -// } -} - -QPixmap AutoBookmarker::configPagePixmap( uint /*p*/, int size ) const -{ - return UserIcon("kte_bookmark", size); -} - -void AutoBookmarker::slotCompleted() -{ - // get the document info - KTextEditor::DocumentInfoInterface *di = - static_cast(document()-> - qt_cast("KTextEditor::DocumentInfoInterface")); - QString mt; - if ( di ) // we can still try match the URL otherwise - mt = di->mimeType(); - - QString fileName; - if ( document()->url().isValid() ) - fileName = document()->url().fileName(); - - ABEntityList *l = ABGlobal::self()->entities(); - // for each item, if either mask matches - // * apply if onLoad is true - ABEntityListIterator it( *l ); - int n( 0 ); - bool found; - AutoBookmarkEnt *e; - while ( ( e = it.current() ) != 0 ) - { - found = ( !e->mimemask.count() && !e->filemask.count() ); // no preferences - if ( ! found ) - found = ( ! mt.isEmpty() && e->mimemask.contains( mt ) ); - if ( ! found ) - for( QStringList::Iterator it1 = e->filemask.begin(); it1 != e->filemask.end(); ++it1 ) - { - QRegExp re(*it1, true, true); - if ( ( found = ( ( re.search( fileName ) > -1 ) && ( re.matchedLength() == (int)fileName.length() ) ) ) ) - break; - } - - if ( found ) - applyEntity( e ); - - n++; - ++it; - } - -} - -void AutoBookmarker::applyEntity( AutoBookmarkEnt *e ) -{ - KTextEditor::Document *doc = document(); - KTextEditor::EditInterface *ei = KTextEditor::editInterface( doc ); - KTextEditor::MarkInterface *mi = KTextEditor::markInterface( doc ); - - if ( ! ( ei && mi ) ) return; - - QRegExp re( e->pattern, e->flags & AutoBookmarkEnt::CaseSensitive ); - re.setMinimal( e->flags & AutoBookmarkEnt::MinimalMatching ); - - for ( uint l( 0 ); l < ei->numLines(); l++ ) - if ( re.search( ei->textLine( l ) ) > -1 ) - mi->setMark( l, KTextEditor::MarkInterface::Bookmark ); -} - -//END - -//BEGIN ABGlobal -ABGlobal::ABGlobal() -{ - m_ents = new ABEntityList; - readConfig(); -} - -ABGlobal::~ABGlobal() -{ - delete m_ents; -} - -ABGlobal *ABGlobal::self() -{ - K_STATIC_DELETER(ABGlobal, s_self) - return s_self; -} - -void ABGlobal::readConfig() -{ - if ( ! m_ents ) - m_ents = new ABEntityList; - else - m_ents->clear(); - KConfig *config = new KConfig("ktexteditor_autobookmarkerrc"); - - uint n( 0 ); - while ( config->hasGroup( QString("autobookmark%1").arg( n ) ) ) - { - KConfigGroup cg( config, QString("autobookmark%1").arg( n ) ); - QStringList filemask = cg.readXdgListEntry( "filemask" ); - QStringList mimemask = cg.readXdgListEntry( "mimemask" ); - int flags = cg.readEntry( "flags", 1 ); - AutoBookmarkEnt *e = new AutoBookmarkEnt( - cg.readEntry( "pattern", "" ), - filemask, - mimemask, - flags - ); - - m_ents->append( e ); - - ++n; - } - - delete config; -} - -void ABGlobal::writeConfig() -{ - KConfig *config = new KConfig("ktexteditor_autobookmarkerrc"); - - // clean the config object - QStringList l = config->groupList(); - for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) - config->deleteGroup( *it ); - - // fill in the current list - for ( uint i = 0; i < m_ents->count(); i++ ) - { - AutoBookmarkEnt *e = m_ents->at( i ); - KConfigGroup cg( config, QString("autobookmark%1").arg( i ) ); - cg.writeEntry( "pattern", e->pattern ); - cg.writeXdgListEntry( "filemask", e->filemask ); - cg.writeXdgListEntry( "mimemask", e->mimemask ); - cg.writeEntry( "flags", e->flags ); - } - - config->sync(); // explicit -- this is supposedly handled by the d'tor - delete config; -} -//END ABGlobal - -//BEGIN AutoBookmarkEntItem -// A QListviewItem which can hold a AutoBookmarkEnt pointer -class AutoBookmarkEntItem : public Q3ListViewItem -{ - public: - AutoBookmarkEntItem( K3ListView *lv, AutoBookmarkEnt *e ) - : Q3ListViewItem( lv ), - ent( e ) - { - redo(); - }; - ~AutoBookmarkEntItem(){}; - void redo() - { - setText( 0, ent->pattern ); - setText( 1, ent->mimemask.join("; ") ); - setText( 2, ent->filemask.join("; ") ); - } - AutoBookmarkEnt *ent; -}; -//END - -//BEGIN AutoBookmarkerEntEditor -// Dialog for editing a single autobookmark entity -// * edit the pattern -// * set the file/mime type masks -AutoBookmarkerEntEditor::AutoBookmarkerEntEditor( QWidget *parent, AutoBookmarkEnt *e ) - : KDialog( parent ), - e( e ) -{ - setObjectName( "autobookmark_ent_editor" ); - setModal( true ); - setCaption( i18n("Edit Entry") ); - setButtons( KDialog::Ok | KDialog::Cancel ); - - QFrame *w = new QFrame( this ); - setMainWidget( w ); - - QGridLayout * lo = new QGridLayout( w, 5, 3 ); - - QLabel *l = new QLabel( i18n("&Pattern:"), w ); - lePattern = new KLineEdit( e->pattern, w ); - l->setBuddy( lePattern ); - lo->addWidget( l, 0, 0 ); - lo->addMultiCellWidget( lePattern, 0, 0, 1, 2 ); - lePattern->setWhatsThis(i18n( - "

A regular expression. Matching lines will be bookmarked.

" ) ); - - connect( lePattern, SIGNAL(textChanged ( const QString & ) ),this, SLOT( slotPatternChanged( const QString& ) ) ); - - cbCS = new QCheckBox( i18n("Case &sensitive"), w ); - lo->addMultiCellWidget( cbCS, 1, 1, 0, 2 ); - cbCS->setChecked( e->flags & AutoBookmarkEnt::CaseSensitive ); - cbCS->setWhatsThis(i18n( - "

If enabled, the pattern matching will be case sensitive, otherwise " - "not.

") ); - - cbMM = new QCheckBox( i18n("&Minimal matching"), w ); - lo->addMultiCellWidget( cbMM, 2, 2, 0 ,2 ); - cbMM->setChecked( e->flags & AutoBookmarkEnt::MinimalMatching ); - cbMM->setWhatsThis(i18n( - "

If enabled, the pattern matching will use minimal matching; if you " - "do not know what that is, please read the appendix on regular expressions " - "in the kate manual.

") ); - - l = new QLabel( i18n("&File mask:"), w ); - leFileMask = new KLineEdit( e->filemask.join( "; " ), w ); - l->setBuddy( leFileMask ); - lo->addWidget( l, 3, 0 ); - lo->addMultiCellWidget( leFileMask, 3, 3, 1, 2 ); - leFileMask->setWhatsThis(i18n( - "

A list of filename masks, separated by semicolons. This can be used " - "to limit the usage of this entity to files with matching names.

" - "

Use the wizard button to the right of the mimetype entry below to " - "easily fill out both lists.

" ) ); - - l = new QLabel( i18n("MIME &types:"), w ); - leMimeTypes = new KLineEdit( e->mimemask.join( "; " ), w ); - l->setBuddy( leMimeTypes ); - lo->addWidget( l, 4, 0 ); - lo->addWidget( leMimeTypes, 4, 1 ); - leMimeTypes->setWhatsThis(i18n( - "

A list of mime types, separated by semicolon. This can be used to " - "limit the usage of this entity to files with matching mime types.

" - "

Use the wizard button on the right to get a list of existing file " - "types to choose from, using it will fill in the file masks as well.

" ) ); - - QToolButton *btnMTW = new QToolButton(w); - lo->addWidget( btnMTW, 4, 2 ); - btnMTW->setIcon(KIcon("tools-wizard")); - connect(btnMTW, SIGNAL(clicked()), this, SLOT(showMTDlg())); - btnMTW->setWhatsThis(i18n( - "

Click this button to display a checkable list of mimetypes available " - "on your system. When used, the file masks entry above will be filled in " - "with the corresponding masks.

") ); - slotPatternChanged( lePattern->text() ); -} - -void AutoBookmarkerEntEditor::slotPatternChanged( const QString&_pattern ) -{ - enableButtonOk( !_pattern.isEmpty() ); -} - -void AutoBookmarkerEntEditor::apply() -{ - if ( lePattern->text().isEmpty() ) return; - - e->pattern = lePattern->text(); - e->filemask = leFileMask->text().split( QRegExp("\\s*;\\s*"), QString::SkipEmptyParts ); - e->mimemask = leMimeTypes->text().split( QRegExp("\\s*;\\s*"), QString::SkipEmptyParts ); - e->flags = 0; - if ( cbCS->isOn() ) e->flags |= AutoBookmarkEnt::CaseSensitive; - if ( cbMM->isOn() ) e->flags |= AutoBookmarkEnt::MinimalMatching; -} - -void AutoBookmarkerEntEditor::showMTDlg() -{ - QString text = i18n("Select the MimeTypes for this pattern.\nPlease note that this will automatically edit the associated file extensions as well."); - QStringList list = leMimeTypes->text().split( QRegExp("\\s*;\\s*"), QString::SkipEmptyParts ); - KMimeTypeChooserDialog d( i18n("Select Mime Types"), text, list, "text", this ); - if ( d.exec() == KDialog::Accepted ) { - // do some checking, warn user if mime types or patterns are removed. - // if the lists are empty, and the fields not, warn. - leFileMask->setText(d.chooser()->patterns().join("; ")); - leMimeTypes->setText(d.chooser()->mimeTypes().join("; ")); - } -} -//END - -//BEGIN AutoBookmarkerConfigPage -// TODO allow custom mark types with icons -AutoBookmarkerConfigPage::AutoBookmarkerConfigPage( QWidget *parent, const char *name ) - : KTextEditor::ConfigPage( parent, name ) -{ - QVBoxLayout *lo = new QVBoxLayout( this ); - - QLabel *l = new QLabel( i18n("&Patterns"), this ); - lo->addWidget( l ); - lvPatterns = new K3ListView( this ); - lvPatterns->addColumn( i18n("Pattern") ); - lvPatterns->addColumn( i18n("Mime Types") ); - lvPatterns->addColumn( i18n("File Masks") ); - lo->addWidget( lvPatterns ); - l->setBuddy( lvPatterns ); - lvPatterns->setWhatsThis(i18n( - "

This list shows your configured autobookmark entities. When a document " - "is opened, each entity is used in the following way:

" - "

    " - "
  1. The entity is dismissed, if a mime and/or filename mask is defined, " - "and neither matches the document.
  2. " - "
  3. Otherwise each line of the document is tried against the pattern, " - "and a bookmark is set on matching lines.
" - "

Use the buttons below to manage your collection of entities.

") ); - - QHBoxLayout *lo1 = new QHBoxLayout ( lo ); - - btnNew = new QPushButton( i18n("&New..."), this ); - lo1->addWidget( btnNew ); - btnNew->setWhatsThis(i18n( - "Press this button to create a new autobookmark entity.") ); - - btnDel = new QPushButton( i18n("&Delete"), this ); - lo1->addWidget( btnDel ); - btnDel->setWhatsThis(i18n( - "Press this button to delete the currently selected entity.") ); - - btnEdit = new QPushButton( i18n("&Edit..."), this ); - lo1->addWidget( btnEdit ); - btnEdit->setWhatsThis(i18n( - "Press this button to edit the currently selected entity.") ); - - lo1->addStretch( 1 ); - - connect( btnNew, SIGNAL(clicked()), this, SLOT(slotNew()) ); - connect( btnDel, SIGNAL(clicked()), this, SLOT(slotDel()) ); - connect( btnEdit, SIGNAL(clicked()), this, SLOT(slotEdit()) ); - connect( lvPatterns, SIGNAL(doubleClicked(Q3ListViewItem *)), this, SLOT(slotEdit()) ); - - m_ents = new ABEntityList(); - m_ents->setAutoDelete( true ); - reset(); -} - -// replace the global list with the new one -void AutoBookmarkerConfigPage::apply() -{ - ABGlobal::self()->entities()->clear(); - - ABEntityListIterator it ( *m_ents ); - AutoBookmarkEnt *e; - - while ( (e = it.current()) != 0 ) - { - ABGlobal::self()->entities()->append( e ); - ++it; - } - - ABGlobal::self()->writeConfig(); - - // TODO -- how do i refresh all the view menus -} - -// renew our copy of the global list -void AutoBookmarkerConfigPage::reset() -{ - m_ents->clear(); // unused - no reset button currently - - ABEntityListIterator it ( *ABGlobal::self()->entities() ); - AutoBookmarkEnt *e; - while ( (e = it.current()) != 0 ) - { - AutoBookmarkEnt *me = new AutoBookmarkEnt( *e ); - m_ents->append( me ); - new AutoBookmarkEntItem( lvPatterns, me ); - ++it; - } -} - -// TODO (so far not used) we have no defaults (except deleting all items??) -void AutoBookmarkerConfigPage::defaults() -{ - // if KMessageBox::warningYesNo() - // clear all -} - -// open the edit dialog with a new entity, -// and add it if the dialog is accepted -void AutoBookmarkerConfigPage::slotNew() -{ - AutoBookmarkEnt *e = new AutoBookmarkEnt(); - AutoBookmarkerEntEditor dlg( this, e ); - if ( dlg.exec() ) - { - dlg.apply(); - new AutoBookmarkEntItem( lvPatterns, e ); - m_ents->append( e ); - } -} - -// delete the selected item and remove it from the list view and internal list -void AutoBookmarkerConfigPage::slotDel() -{ - AutoBookmarkEntItem *i = (AutoBookmarkEntItem*)lvPatterns->currentItem(); - int idx = m_ents->findRef( i->ent ); - m_ents->remove( idx ); - delete i; -} - -// open the edit dialog with the selected item -void AutoBookmarkerConfigPage::slotEdit() -{ - AutoBookmarkEnt *e = ((AutoBookmarkEntItem*)lvPatterns->currentItem())->ent; - AutoBookmarkerEntEditor dlg( this, e ); - if ( dlg.exec() ) - { - dlg.apply(); - ((AutoBookmarkEntItem*)lvPatterns->currentItem())->redo(); - } -} -//END AutoBookmarkerConfigPage - -//BEGIN AutoBookmarkEnt -AutoBookmarkEnt::AutoBookmarkEnt( const QString &p, const QStringList &f, const QStringList &m, int fl ) - : pattern( p ), - filemask( f ), - mimemask( m ), - flags( fl ) -{; -} -//END -// -#include "autobookmarker.moc" diff --git a/part/plugins/autobookmarker/autobookmarker.h b/part/plugins/autobookmarker/autobookmarker.h deleted file mode 100644 index edb4183..0000000 --- a/part/plugins/autobookmarker/autobookmarker.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - This library is free software you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - - --- - file: autobookmarker.h - - KTextEditor plugin to add bookmarks to documents. - Copyright Anders Lund , 2003 -*/ - -#ifndef AUTOBOOKMARKER_H -#define AUTOBOOKMARKER_H - -#include -#include - -#include - -#include - -class AutoBookmarkEnt -{ - public: - enum REFlags { CaseSensitive=1, MinimalMatching=2 }; - explicit AutoBookmarkEnt(const QString &p=QString(), - const QStringList &f=QStringList(), - const QStringList &m=QStringList(), - int flags=1 ); - ~AutoBookmarkEnt(){} - QString pattern; - QStringList filemask; - QStringList mimemask; - int flags; -}; - -class AutoBookmarker - : public KTextEditor::Plugin, public KTextEditor::PluginViewInterface, - public KTextEditor::ConfigInterfaceExtension -{ - Q_OBJECT - public: - explicit AutoBookmarker( QObject *parent = 0, - const char* name = 0, - const QVariantList &args = QVariantList() ); - virtual ~AutoBookmarker() {} - - void addView (KTextEditor::View *view); - void removeView (KTextEditor::View *view); - - // ConfigInterfaceExtention - uint configPages() const { return 1; }; - KTextEditor::ConfigPage * configPage( uint number, QWidget *parent, const char *name ); - QString configPageName( uint ) const; - QString configPageFullName( uint ) const; - QPixmap configPagePixmap( uint, int ) const; - bool abDone; - - private Q_SLOTS: - void slotCompleted(); - void applyEntity( AutoBookmarkEnt *e ); -}; - -typedef Q3PtrList ABEntityList; -typedef Q3PtrListIterator ABEntityListIterator; - -/* singleton to keep the data */ -class ABGlobal -{ - public: - ABGlobal(); - ~ABGlobal(); - - static ABGlobal* self(); - - ABEntityList* entities() { return m_ents; }; - void readConfig(); - void writeConfig(); - - private: - ABEntityList *m_ents; -}; - -class AutoBookmarkerConfigPage : public KTextEditor::ConfigPage -{ - Q_OBJECT - public: - AutoBookmarkerConfigPage( QWidget *parent, const char *name ); - virtual ~AutoBookmarkerConfigPage() {} - - virtual void apply(); - virtual void reset(); - virtual void defaults(); - - private Q_SLOTS: - void slotNew(); - void slotDel(); - void slotEdit(); - - private: - class K3ListView *lvPatterns; - class QPushButton *btnNew, *btnDel, *btnEdit; - ABEntityList *m_ents; -}; - -class AutoBookmarkerEntEditor : public KDialog -{ - Q_OBJECT - public: - AutoBookmarkerEntEditor( QWidget *parent, AutoBookmarkEnt *e ); - ~AutoBookmarkerEntEditor(){} - - void apply(); - - private Q_SLOTS: - void showMTDlg(); - void slotPatternChanged( const QString& ); - private: - class KLineEdit *lePattern, *leMimeTypes, *leFileMask; - class QCheckBox *cbCS, *cbMM; - AutoBookmarkEnt *e; -}; - -#endif //_AUTOBOOKMARKER_H_ diff --git a/part/plugins/autobookmarker/ktexteditor_autobookmarker.desktop b/part/plugins/autobookmarker/ktexteditor_autobookmarker.desktop deleted file mode 100644 index fc020c2..0000000 --- a/part/plugins/autobookmarker/ktexteditor_autobookmarker.desktop +++ /dev/null @@ -1,183 +0,0 @@ -[Desktop Entry] -X-KDE-Library=ktexteditor_autobookmarker -X-KDE-PluginInfo-Author= -X-KDE-PluginInfo-Email= -X-KDE-PluginInfo-Name=ktexteditorautobookmarker -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://kate.kde.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=true -X-KDE-ParentApp=kate -X-KDE-ServiceTypes=KTextEditor/Plugin -Type=Service -Icon=bookmark-new -Name=Autobookmarker -Name[ar]=مضي٠علامات آلي -Name[as]=Autobookmarker -Name[ast]=Automarcador -Name[be]=Ðўтаматычны закладкі -Name[be@latin]=AÅ­tamatyÄnyja zakÅ‚adki -Name[bg]=KTextEditor Autobookmarker -Name[bn]=অটো-বà§à¦•à¦®à¦¾à¦°à§à¦•à¦¾à¦° -Name[bn_IN]=Autobookmarker -Name[ca]=Marcador automàtic de punts -Name[ca@valencia]=Marcador automàtic de punts -Name[cs]=Automatické záložky -Name[csb]=Aùtomatné wstôwianié załóżków -Name[da]=Autobogmærker -Name[de]=Automatische Lesezeichenmarkierung -Name[el]=Αυτόματοι σελιδοδείκτες -Name[en_GB]=Autobookmarker -Name[eo]=AÅ­tomata legosignigilo -Name[es]=Marcador automático -Name[et]=Automaatne järjehoidjate märkija -Name[eu]=Laster-markatzaile automatikoa -Name[fa]=Autobookmarker -Name[fi]=Automaattinen kirjanmerkittäjä -Name[fr]=Signets automatiques -Name[fy]=Autoblêdwizers -Name[ga]=Leabharmharcálaí Uathoibríoch -Name[gl]=Marcador automático -Name[gu]=આપમેળેબà«àª•àª®àª¾àª°à«àª• કરનાર -Name[he]=מוסיף סימניות ×וטומטי -Name[hi]=आटोबà¥à¤•à¤®à¤¾à¤°à¥à¤•à¤° -Name[hne]=आटोबà¥à¤•à¤®à¤¾à¤°à¥à¤•à¤° -Name[hr]=Samostalni dodavaÄ knjižnih kratica -Name[hsb]=Awtobookmarker -Name[hu]=Automatikus könyvjelzÅ‘k -Name[ia]=Auto marcator de libro -Name[id]=Pembuat bookmark otomatis -Name[is]=Sjálfvirkur bókamerkjari -Name[it]=Segnalibri automatici -Name[ja]=自動ブックマーク -Name[kk]=Ðвтобетбелгігіші -Name[km]=កម្មវិធី​ចំណាំ​ស្វáŸáž™â€‹áž”្រវážáŸ’ážáž· -Name[kn]=ಸà³à²µà²¯à²‚ಕನಕಾರ (ಬà³à²•à³ ಮಾರà³à²•à²°à³) -Name[ko]=ìžë™ 책갈피 설정 -Name[ku]=Bixweberbijarteker -Name[lt]=KTextEditor automatinis žymelių įterpikas -Name[lv]=AutogrÄmatzÄ«mÄ“tÄjs -Name[mai]=आटोबà¥à¤•à¤®à¤¾à¤°à¥à¤•à¤° -Name[mk]=Ðвтом. обележувач -Name[ml]=à´“à´°àµâ€à´®àµà´®à´•àµà´•àµà´±à´¿à´ªàµà´ªàµ തനിയേ രേഖപàµà´ªàµ†à´Ÿàµà´¤àµà´¤àµà´¨àµà´¨à´¤àµàµ -Name[mr]=सà¥à¤µà¤“ळखचिनà¥à¤¹à¤•à¤°à¥à¤¤à¤¾ -Name[ms]=Penanda buku auto -Name[nb]=Automatisk bokmerke -Name[nds]=Leestekensetter -Name[ne]=सà¥à¤µà¤¾à¤šà¤¾à¤²à¤¿à¤¤ पà¥à¤¸à¥à¤¤à¤•à¤šà¤¿à¤¨à¥‹ -Name[nl]=Autobladwijzers -Name[nn]=Automatisk bokmerke -Name[or]=Autobookmarker -Name[pa]=ਆਟੋ-ਬà©à©±à¨•à¨®à¨¾à¨°à¨•à¨° -Name[pl]=Automatyczne wstawianie zakÅ‚adek -Name[ps]=خپله ليکنښوونکی -Name[pt]=Auto-Favoritos do KTextEditor -Name[pt_BR]=Marcador de favoritos automático -Name[ro]=Semne de carte automate pentru KTextEditor -Name[ru]=Ðвтозакладки -Name[se]=AutomáhtalaÅ¡ girjemerkejeaddji -Name[si]=ස්වයංක්â€à¶»à·“ය පිටුසලකුණු -Name[sk]=Automatické vytváranie záložiek -Name[sl]=Samodejni zaznamki -Name[sr]=ÐутоматÑко обележавање -Name[sr@ijekavian]=ÐутоматÑко обиљежавање -Name[sr@ijekavianlatin]=Automatsko obilježavanje -Name[sr@latin]=Automatsko obeležavanje -Name[sv]=Automatiska bokmärken -Name[ta]=தானான நினைவà¯à®•à¯ கà¯à®±à®¿ -Name[te]=ఆటొబà±à°•à± మారà±à°•à°°à± -Name[tg]=Хатчӯбмонии худкор -Name[th]=ตั้งที่คั่นหน้าอัตโนมัติ -Name[tr]=Otomatik Yer Ä°mi Ekleyici -Name[uk]=Програма автоматичних закладок -Name[vi]=Bá»™ tá»± Ä‘á»™ng lÆ°u liên kết -Name[wa]=RimÃ¥kes otomatikes -Name[x-test]=xxAutobookmarkerxx -Name[zh_CN]=自动书签 -Name[zh_TW]=Autobookmarker -Comment=Set bookmarks on lines matching a pattern when documents are loaded -Comment[af]=Plaas boekmerke by lyne wat met 'n patroon ooreenstem wanneer dokumente gelaai word. -Comment[ar]=ضع علامات ÙÙŠ الأسطر التي تواÙÙ‚ نموذجا معينا عند تحميل المل٠-Comment[as]=আলেখà§à¦¯à¦¨ তোলাৰ সময়ত à¦à¦Ÿà¦¾ ধৰণৰ সৈতে à¦à¦•à§‡ শাৰীত পতà§à§°à¦šà¦¿à¦¹à§à¦¨ দিব । -Comment[ast]=Afita marcadores nes llinies que concasen con un patrón al cargar los documentos -Comment[be]=Стварае закладкі Ð´Ð»Ñ Ñ€Ð°Ð´ÐºÐ¾Ñž, ÑÐºÑ–Ñ Ð°Ð´Ð¿Ð°Ð²Ñдаюць шаблону -Comment[be@latin]=ŹmiaÅ¡Äaje Å­ radkoch, jakija adpaviadajuć Å¡ablonu, zakÅ‚adki, paÅ›la adÄytaÅ„nia dakumenta. -Comment[bg]=УÑтановÑване на отметки на редовете, които отговарÑÑ‚ на зададен шаблон по време на зареждане на файла -Comment[bn]=ডকà§à¦®à§‡à¦¨à§à¦Ÿ লোড করাকালীন পà§à¦°à¦¦à¦¤à§à¦¤ নকশার সাথে মেলে à¦à¦®à¦¨ সমসà§à¦¤ লাইন বà§à¦•à¦®à¦¾à¦°à§à¦• করে -Comment[bn_IN]=ডকà§à¦®à§‡à¦¨à§à¦Ÿ লোড করা হলে সà§à¦¨à¦¿à¦°à§à¦¦à¦¿à¦·à§à¦Ÿ বিনà§à¦¯à¦¾à¦¸ অনà§à¦¯à¦¾à§Ÿà§€ সনাকà§à¦¤ পংকà§à¦¤à¦¿à¦—à§à¦²à¦¿à¦° জনà§à¦¯ বà§à¦•à¦®à¦¾à¦°à§à¦• নিরà§à¦§à¦¾à¦°à¦£ করা হবে। -Comment[ca]=Estableix punts a les línies coincidents amb un patró quan es carreguen documents -Comment[ca@valencia]=Estableix punts a les línies coincidents amb un patró quan es carreguen documents -Comment[cs]=Nastavení záložek do řádek vyhovujících vzoru po nahrání dokumentu -Comment[csb]=Wstôwiô, òbczas wczëtëwaniô, załóżczi w pasownëch réżkach do dónegò mùstra -Comment[da]=Sæt bogmærker pÃ¥ linjer der matcher et mønster nÃ¥r dokumenter er indlæst -Comment[de]=Lesezeichen nach bestimmten Mustern auf Zeilen setzen, sobald ein Dokument geladen wird -Comment[el]=ΟÏίζει σελιδοδείκτες σε γÏαμμές που ταιÏιάζουν σε ένα μοτίβο όταν τα έγγÏαφα φοÏτώνονται -Comment[en_GB]=Set bookmarks on lines matching a pattern when documents are loaded -Comment[eo]=Igas legosignojn en linioj, kiuj kongruas al Åablono, kiam dokumentoj estas Åargataj -Comment[es]=Pone marcadores en las líneas que coincidan con un patrón definido al cargar los documentos. -Comment[et]=Määrab dokumendi avamisel vastavalt mustrile ridadele järjehoidjad -Comment[eu]=Eredu batekin bat datozen lerroen laster-markak ezartzen ditu dokumentuak kargatzean -Comment[fa]=وقتی Ú©Ù‡ مستندات بار می‌شود، چوب الÙها را روی خطوط مطابق با الگو تنظیم کنید -Comment[fi]=Määrittele kirjanmerkkejä riveille, jotka vastaavat kuviota, kun asiakirjoja avataan -Comment[fr]=Positionne des signets sur les lignes qui correspondent à un motif quand les documents sont chargés -Comment[fy]=Blêdwizer ynstelle om by it laden fan dokuminten oerienkomstige patroanen -Comment[ga]=Cruthaigh leabharmharcanna ar línte atá comhoiriúnach do phatrún nuair a luchtaítear cáipéisí -Comment[gl]=Pon marcadores en liñas que se axusten a un patrón durante a carga de documentos -Comment[gu]=જà«àª¯àª¾àª°à«‡ દસà«àª¤àª¾àªµà«‡àªœ લાવવામાં આવે તà«àª¯àª¾àª°à«‡ મેળ ખાતી લીટીઓ પર બà«àª•àª®àª¾àª°à«àª•à«‹ ગોઠવો -Comment[he]=מוסיף סימניות בשורות המת×ימות לתבנית מסויימת בעת טעינת מסמך -Comment[hi]=जब दसà¥à¤¤à¤¾à¤µà¥‡à¤œ लोड होते हैं तो पैटरà¥à¤¨ से मिलते जà¥à¤²à¤¤à¥‡ बà¥à¤•à¤®à¤¾à¤°à¥à¤• लाइनों में सेट करें -Comment[hne]=जब कागद लोड होथे तो पैटरà¥à¤¨ से मिलत जà¥à¤²à¤¤ निसानी लाइन मन मं सेट करव -Comment[hr]=Pri uÄitavanju dokumenta postavlja oznake na redovima koji odgovaraju odreÄ‘enom uzorku. -Comment[hsb]=Staja pÅ™i zaÄitanju dokumenta znamjenja na linki, kiž wÄ›stemu mustrej wotpowÄ›duja. -Comment[hu]=Fájl betöltésekor könyvjelzÅ‘k automatikus létrehozása minta alapján -Comment[ia]=Il fixa le marcatores super lineas que incontra un modello quando le documentos es cargate -Comment[id]=Atur bookmark di baris yang cocok dengan pola ketika dokumen dimuat -Comment[is]=Setur bókamerki á línur sem passa ákveðnu mynstri, þegar skjöl eru lesin -Comment[it]=Imposta dei segnalibri sulle righe corrispondenti a uno schema quando si caricano dei documenti -Comment[ja]=文書ãŒèª­ã¿è¾¼ã¾ã‚ŒãŸã¨ãã«ã€ãƒ‘ターンã«ãƒžãƒƒãƒã—ãŸè¡Œã«ãƒ–ックマークを設定ã—ã¾ã™ -Comment[kk]=Құжаттар жүкелгенде үлгі бойынша бетбелгілерді коÑды -Comment[km]=កំណážáŸ‹â€‹áž€áž¶ážšáž…ំណាំ​ážáŸ’រង់​បន្ទាážáŸ‹â€‹ážŠáŸ‚ល​ផ្គូផ្គង​នឹង​លំនាំ នៅពáŸáž›â€‹ážŠáŸ‚ល​បាន​ផ្ទុក​ឯកសារ -Comment[kn]=ದಸà³à²¤à²¾à²µà³‡à²œà³à²—ಳನà³à²¨à³ ಉತà³à²¥à²¾à²ªà²¿à²¸à²¿à²¦à²¾à²— (ಲೋಡà³), ಒಂದೠನಮೂನೆಗೆ ಸರಿಹೊಂದà³à²µ ಸಾಲà³à²—ಳಿಗೆ ಅಂಕನ ಮಾಡೠ-Comment[ko]=문서를 불러올 ë•Œ íŒ¨í„´ì— ë”°ë¼ì„œ 책갈피를 설정합니다 -Comment[ku]=Danîşanan ava bike ser rêzên hevgirtî bi mînak re demê pelên nivîsê tên bar kirin -Comment[lb]=Setzt Lieszeechen op d'Zeilen, déi ee bestëmmtent Muster enthalen, wann d'Dokument geluede gëtt -Comment[lt]=Ä®terpia žymeles eilutÄ—se, kurios atitinka tam tikrÄ… derinį, dokumento įkÄ—limo metu -Comment[lv]=IelÄdÄ“jot dokumentu, uzstÄda grÄmatzÄ«mes tÄm rindÄm, kuras atbilst norÄdÄ«tajam paraugam -Comment[mai]=जखन दसà¥à¤¤à¤¾à¤¬à¥‡à¤œ लोड होइछ तठपैटरà¥à¤¨ सठमिलति जà¥à¤²à¤¤à¤¿ पà¥à¤¸à¥à¤¤à¤šà¤¿à¤¨à¥à¤¹ पंकà¥à¤¤à¤¿à¤®à¥‡ सेट करू -Comment[mk]=ПоÑтава обележувачи на линиите кои Ñе поклопуваат Ñо шема кога документите Ñе вчитуваат -Comment[ml]=ഡോകàµà´®àµ†à´¨àµà´±àµà´•à´³àµâ€ à´Žà´Ÿàµà´•àµà´•àµà´®àµà´ªàµ‹à´³àµâ€ ഒരൠപàµà´°à´¤àµà´¯àµ‡à´• പാറàµà´±àµ‡à´£àµà´®à´¾à´¯à´¿ യോജികàµà´•àµà´¨àµà´¨ വരികളàµà´Ÿàµ† à´“à´°àµâ€à´®àµà´®à´•àµà´•àµà´±à´¿à´ªàµà´ªàµ രേഖപàµà´ªàµ†à´Ÿàµà´¤àµà´¤àµà´• -Comment[mr]=दसà¥à¤¤à¤à¤µà¤œ दाखल होतेवेळी शैलीशी जà¥à¤³à¤£à¤¾à¤±à¥à¤¯à¤¾ ओळींना ओळखचिनà¥à¤¹à¤¾à¤•à¥ƒà¤¤ करा -Comment[ms]=Tetapkan penanda buku pada baris yang padan dengan paten apabila dokumen dimuatkan -Comment[nb]=Sett bokmerke pÃ¥ linjer som passer til et mønster nÃ¥r dokumenter blir Ã¥pnet -Comment[nds]=Sett al bi't Laden Leestekens för Regen, op de en Muster passt -Comment[ne]=कागजात लोड हà¥à¤à¤¦à¤¾ बाà¤à¤¨à¥à¤•à¥€ मिलà¥à¤¦à¥‹ पà¥à¤¸à¥à¤¤à¤•à¤šà¤¿à¤¨à¥‹ लाइनमा सेट गरà¥à¤¨à¥à¤¹à¥‹à¤¸à¥ -Comment[nl]=Plaatsen van bladwijzers op regels die voldoen aan een bepaald patroon zodra het document geopend wordt -Comment[nn]=Set bokmerke pÃ¥ linjer i samsvar med eit mønster ved opning av dokument -Comment[or]=Set bookmarks on lines matching a pattern when documents are loaded -Comment[pa]=ਜਦੋਂ ਵੀ ਡੌਕੂਮੈਂਟ ਨੂੰ ਲੋਡ ਕੀਤਾ ਜਾ ਰਿਹਾ ਹੋਵੇ ਤਾਂ ਬà©à©±à¨•à¨®à¨¾à¨°à¨• ਨੂੰ ਸਤਰ-ਮੇਲ ਇੱਕ ਪੈਟਰਨ ਦਿਓ -Comment[pl]=W czasie wczytywanie dokumentu ustawia zakÅ‚adki w liniach pasujÄ…cych do podanego wzorca -Comment[pt]=Coloca favoritos em linhas que condizem com um padrão quando os documentos são carregados. -Comment[pt_BR]=Quando os documentos são carregados, arranja os seus favoritos em linhas, separadas de acordo com uma expressão definida -Comment[ro]=La încărcarea documentului stabileÈ™te semne de carte la liniile care se potrivesc cu un model de text -Comment[ru]=РаÑÑтановка закладок в текÑтовом документе по шаблону -Comment[se]=Bidjá girjemearkkaid linnjáide mat heivehit dihto minsttáriid go dokumeanttat rahpejuvvot. -Comment[sk]=Nastavuje záložky na riadky zodpovedajúce vzorke pri naÄítaní dokumentu -Comment[sl]=Ob nalaganju dokumentov nastavi zaznamke za vrstice, ki se ujemajo z vzorcem -Comment[sr]=ПоÑтавља обележиваче на редове поклопљене обраÑцем по учитавању документа -Comment[sr@ijekavian]=ПоÑтавља обиљеживаче на редове поклопљене обраÑцем по учитавању документа -Comment[sr@ijekavianlatin]=Postavlja obilježivaÄe na redove poklopljene obrascem po uÄitavanju dokumenta -Comment[sr@latin]=Postavlja obeleživaÄe na redove poklopljene obrascem po uÄitavanju dokumenta -Comment[sv]=Lägg till bokmärken pÃ¥ rader som motsvarar ett mönster när dokument laddas -Comment[ta]= ஆவணஙà¯à®•à®³à¯ பதிவாகà¯à®®à¯ போத௠அமைபà¯à®ªà¯ பà¯à®¤à¯à®¤à®•à®•à¯à®•à¯à®±à®¿à®ªà¯à®ªà¯ கோடà¯à®•à®³à¯ பொரà¯à®¤à¯à®¤à¯à®®à¯ மாதிரி -Comment[te]=పతà±à°°à°¾à°²à± à°Žà°•à±à°•à°¿à°‚à°šà°¿à°¨ తరà±à°µà°¾à°¤ బాణీకి సరిపొయిన వరà±à°¸à°² మీద à°¬à±à°•à± మారà±à°•à±à°²à°¨à± à°à°°à±à°ªà°°à±à°šà±à°¨à± -Comment[tg]=Сабти хатчӯбҳо аз рӯи Ñатрҳои қолиб, вақте ки ҳуҷҷат кушода шудааÑÑ‚ -Comment[th]=ตั้งที่คั่นหน้าที่à¸à¸²à¸£à¸ˆà¸±à¸šà¸„ู่บรรทัดà¹à¸¥à¸°à¸£à¸¹à¸›à¹à¸šà¸š เมื่อมีà¸à¸²à¸£à¹‚หลดเอà¸à¸ªà¸²à¸£ -Comment[tr]=Belgeler yüklendiÄŸinde belirli bir özelliÄŸe uyan satırlara yer imi ekler -Comment[uk]=Ð’Ñтановлює закладки на Ñ€Ñдках, що відповідають взірцю, під Ñ‡Ð°Ñ Ð·Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð´Ð¾ÐºÑƒÐ¼ÐµÐ½Ñ‚Ñ–Ð² -Comment[vi]=Äặt đánh dấu trên các dòng khá»›p má»™t mẫu nào đó khi tải tài liệu. -Comment[wa]=Mete des rmÃ¥kes so les royes ki corespondèt a on dné patron, cwand les documints sont tcherdjîs -Comment[x-test]=xxSet bookmarks on lines matching a pattern when documents are loadedxx -Comment[zh_CN]=载入文档时对与模å¼åŒ¹é…的行设置书签 -Comment[zh_TW]=文件載入時以字串比å°æ¼”算法來設定書籤。 diff --git a/part/plugins/autobookmarker/ktexteditor_autobookmarkerrc b/part/plugins/autobookmarker/ktexteditor_autobookmarkerrc deleted file mode 100644 index 3ed8fe8..0000000 --- a/part/plugins/autobookmarker/ktexteditor_autobookmarkerrc +++ /dev/null @@ -1,18 +0,0 @@ -[autobookmark0] -filemask=*.pl;*.pm -flags=1 -mimemask=text/x-perl -pattern=sub \\w+ - -[autobookmark1] -filemask=*.hh;*.h -flags=1 -mimemask=text/x-c++hdr -pattern=^class\\s+[^;]+$ - -[autobookmark2] -filemask=*.js;*.html;*.HTML;*.htm;*.HTM;*.xhtml;*.asp -flags=1 -mimemask=application/x-javascript;text/html -pattern=\\s*function\\s+\\w+ - diff --git a/part/plugins/autobrace/.kateconfig b/part/plugins/autobrace/.kateconfig deleted file mode 100644 index 3dcd69d..0000000 --- a/part/plugins/autobrace/.kateconfig +++ /dev/null @@ -1 +0,0 @@ -kate: indent-width 4; mixedindent off; space-indent on; \ No newline at end of file diff --git a/part/plugins/autobrace/CMakeLists.txt b/part/plugins/autobrace/CMakeLists.txt deleted file mode 100644 index 8949d89..0000000 --- a/part/plugins/autobrace/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -project(ktexteditor_autobrace) - -add_subdirectory( icons ) - -########### next target ############### - -set(ktexteditor_autobrace_PART_SRCS autobrace.cpp autobrace_config.cpp) - -kde4_add_plugin(ktexteditor_autobrace ${ktexteditor_autobrace_PART_SRCS} ) - -target_link_libraries(ktexteditor_autobrace ${KDE4_KDECORE_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ) - -install(TARGETS ktexteditor_autobrace DESTINATION ${PLUGIN_INSTALL_DIR} ) - -########### install files ############### - -install(FILES ktexteditor_autobrace.desktop ktexteditor_autobrace_config.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) diff --git a/part/plugins/autobrace/autobrace.cpp b/part/plugins/autobrace/autobrace.cpp deleted file mode 100644 index 6f2b65f..0000000 --- a/part/plugins/autobrace/autobrace.cpp +++ /dev/null @@ -1,459 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2008 Jakob Petsovits - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "autobrace.h" -#include "autobrace_config.h" - -#include -#include - -#include -#include -#include -#include -#include - -AutoBracePlugin *AutoBracePlugin::plugin = 0; - -K_PLUGIN_FACTORY_DEFINITION(AutoBracePluginFactory, - registerPlugin("ktexteditor_autobrace"); - registerPlugin("ktexteditor_autobrace_config"); - ) -K_EXPORT_PLUGIN(AutoBracePluginFactory("ktexteditor_autobrace", "ktexteditor_plugins")) - -AutoBracePlugin::AutoBracePlugin(QObject *parent, const QVariantList &args) - : KTextEditor::Plugin(parent), m_autoBrackets(true), m_autoQuotations(true) -{ - Q_UNUSED(args); - plugin = this; - - readConfig(); -} - -AutoBracePlugin::~AutoBracePlugin() -{ - plugin = 0; -} - -void AutoBracePlugin::addView(KTextEditor::View *view) -{ - if ( KTextEditor::ConfigInterface* confIface = qobject_cast< KTextEditor::ConfigInterface* >(view->document()) ) { - QVariant brackets = confIface->configValue("auto-brackets"); - if ( brackets.isValid() && brackets.canConvert(QVariant::Bool) && brackets.toBool() ) { - confIface->setConfigValue("auto-brackets", false); - KMessageBox::information(view, i18n("The autobrace plugin supersedes the Kate-internal \"Auto Brackets\" feature.\n" - "The setting was automatically disabled for this document."), - i18n("Auto brackets feature disabled"), "AutoBraceSupersedesInformation"); - } - } - - AutoBracePluginDocument *docplugin; - - // We're not storing the brace inserter by view but by document, - // which makes signal connection and destruction a bit easier. - if (m_docplugins.contains(view->document())) { - docplugin = m_docplugins.value(view->document()); - } - else { - // Create Editor plugin and assign options through reference - docplugin = new AutoBracePluginDocument(view->document(), - m_autoBrackets, - m_autoQuotations); - m_docplugins.insert(view->document(), docplugin); - } - // Shouldn't be necessary in theory, but for removeView() the document - // might already be destroyed and removed. Also used as refcounter. - m_documents.insert(view, view->document()); -} - -void AutoBracePlugin::removeView(KTextEditor::View *view) -{ - if (m_documents.contains(view)) - { - KTextEditor::Document *document = m_documents.value(view); - m_documents.remove(view); - - // Only detach from the document if it was the last view pointing to that. - if (m_documents.keys(document).empty()) { - AutoBracePluginDocument *docplugin = m_docplugins.value(document); - m_docplugins.remove(document); - delete docplugin; - } - } -} - -void AutoBracePlugin::readConfig() -{ - KConfigGroup cg(KGlobal::config(), "AutoBrace Plugin"); - // Read configuration parameters, make them false by default - // TODO: set to true by default once https://bugs.kde.org/show_bug.cgi?id=234525 got resolved - m_autoBrackets = cg.readEntry("autobrackets", false); - m_autoQuotations = cg.readEntry("autoquotations", false); -} - -void AutoBracePlugin::writeConfig() -{ - KConfigGroup cg(KGlobal::config(), "AutoBrace Plugin"); - cg.writeEntry("autobrackets", m_autoBrackets); - cg.writeEntry("autoquotations", m_autoQuotations); -} - -/// AutoBracePluginDocument - -AutoBracePluginDocument::AutoBracePluginDocument(KTextEditor::Document* document, const bool& autoBrackets, const bool& autoQuotations) - : QObject(document), m_insertionLine(0), m_withSemicolon(false), - m_lastRange(KTextEditor::Range::invalid()), m_autoBrackets(autoBrackets), m_autoQuotations(autoQuotations) -{ - // Fill brackets map matching opening and closing brackets. - m_brackets["("] = ")"; - m_brackets["["] = "]"; - - connect(document, SIGNAL(exclusiveEditStart(KTextEditor::Document *)), - this, SLOT(disconnectSlots(KTextEditor::Document *))); - connect(document, SIGNAL(exclusiveEditEnd(KTextEditor::Document *)), - this, SLOT(connectSlots(KTextEditor::Document *))); - - connectSlots(document); -} - -AutoBracePluginDocument::~AutoBracePluginDocument() -{ - disconnect(parent() /* == document */, 0, this, 0); -} - -/** - * (Re-)setups slots for AutoBracePluginDocument. - * @param document Current document. - */ -void AutoBracePluginDocument::connectSlots(KTextEditor::Document *document) -{ - connect(document, SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextInserted(KTextEditor::Document*, KTextEditor::Range))); - connect(document, SIGNAL(textRemoved(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextRemoved(KTextEditor::Document*, KTextEditor::Range))); -} - -void AutoBracePluginDocument::disconnectSlots(KTextEditor::Document* document) -{ - disconnect(document, SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextInserted(KTextEditor::Document*, KTextEditor::Range))); - disconnect(document, SIGNAL(textRemoved(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextRemoved(KTextEditor::Document*, KTextEditor::Range))); - disconnect(document, SIGNAL(textChanged(KTextEditor::Document*)), - this, SLOT(slotTextChanged(KTextEditor::Document*))); -} - -/** - * Connected to KTextEditor::Document::textChanged() once slotTextInserted() - * found a line with an opening brace. This takes care of inserting the new - * line with its closing counterpart. - */ -void AutoBracePluginDocument::slotTextChanged(KTextEditor::Document *document) { - // Disconnect from all signals as we insert stuff by ourselves. - // Prevent infinite recursion. - disconnectSlots(document); - - // Make really sure that we want to insert the brace, paste guard and all. - if (m_insertionLine != 0 - && m_insertionLine == document->activeView()->cursorPosition().line() - && document->line(m_insertionLine).trimmed().isEmpty()) - { - KTextEditor::View *view = document->activeView(); - document->startEditing(); - - // If the document's View is a KateView then it's able to indent. - // We hereby ignore the indenter and always indent correctly. (Sorry!) - if (view->inherits("KateView")) { - // Correctly indent the empty line. Magic! - KTextEditor::Range lineRange( - m_insertionLine, 0, - m_insertionLine, document->lineLength(m_insertionLine) - ); - document->replaceText(lineRange, m_indentation); - - connect(this, SIGNAL(indent()), view, SLOT(indent())); - emit indent(); - disconnect(this, SIGNAL(indent()), view, SLOT(indent())); - } - // The line with the closing brace. (Inserted via insertLine() in order - // to avoid space removal by potential indenters.) - document->insertLine(m_insertionLine + 1, m_indentation + '}' + (m_withSemicolon ? ";" : "")); - - document->endEditing(); - view->setCursorPosition(document->endOfLine(m_insertionLine)); - } - m_insertionLine = 0; - - // Re-enable the textInserted() slot again. - connectSlots(document); -} - -/** - * Connected to KTextEditor::Documet::textRemoved. Allows to delete - * an automatically inserted closing bracket if the opening counterpart - * has been removed. - */ -void AutoBracePluginDocument::slotTextRemoved(KTextEditor::Document* document, const KTextEditor::Range& range) -{ - // If last range equals the deleted text range (last range - // is last inserted bracket), we also delete the associated closing bracket. - if (m_lastRange == range) { - // avoid endless recursion - disconnectSlots(document); - - // Delete the character at the same range because the opening - // bracket has already been removed so the closing bracket - // should now have been shifted to that same position - if (range.isValid()) { - document->removeText(range); - } - - connectSlots(document); - } -} - -/** - * Connected to KTextEditor::Document::textInserted(), which is emitted on all - * insertion changes. Line text and line breaks are emitted separately by - * KatePart, and pasted text gets the same treatment as manually entered text. - * Because of that, we discard paste operations by only remembering the - * insertion status for the last line that was entered. - */ -void AutoBracePluginDocument::slotTextInserted(KTextEditor::Document *document, - const KTextEditor::Range& range) -{ - // List of Tokens after which an automatic bracket expanion - // is allowed. - const static QStringList allowedNextToken = QStringList() << "]" << ")" << "," - << "." << ";" << "\n" << "\t" << " " << ""; - const QString text = document->text(range); - - // An insertion operation cancels any last range removal - // operation - m_lastRange = KTextEditor::Range::invalid(); - - // Make sure to handle only: - // 1.) New lines after { (brace openers) - // 2.) Opening braces like '(' and '[' - // 3.) Quotation marks like " and ' - - // Handle brace openers - if (text == "\n") { - // Remember this position as insertion candidate. - // We don't directly insert this here because of KatePart specifics: - // a) Setting the cursor position crashes at this point, and - // b) textChanged() only gets called once per edit operation, so we can - // ignore the same braces when they're being inserted via paste. - if (isInsertionCandidate(document, range.start().line())) { - m_insertionLine = range.end().line(); - connect(document, SIGNAL(textChanged(KTextEditor::Document*)), - this, SLOT(slotTextChanged(KTextEditor::Document*))); - } - else { - m_insertionLine = 0; - } - } - // Opening brackets (defined in ctor) - else if (m_autoBrackets && m_brackets.contains(text)) { - // Only insert auto closing brackets if current text range - // is followed by one of the allowed next tokens. - if (allowedNextToken.contains(nextToken(document,range))) { - insertAutoBracket(document, range, m_brackets[text]); - } - - } - // Check whether closing brackets are allowed. - // If a brace is not allowed remove it - // and set the cursor to the position after that text range. - // Bracket tests bases on this simple idea: A bracket can only be inserted - // if it is NOT followed by the same bracket. This results in overwriting closing brackets. - else if (m_autoBrackets && m_brackets.values().contains(text)) { - if (nextToken(document,range) == text) { - KTextEditor::Cursor saved = range.end(); - document->removeText(range); - document->activeView()->setCursorPosition(saved); - } - } - // Insert auto-quotation marks (if enabled). Same idea as with brackets - // applies here: double quotation marks are eaten up and only inserted if not - // followed by the same quoation mark. Additionally automatic quotation marks - // are inserted only if NOT followed by a back slash (escaping character). - else if (m_autoQuotations && (text == "\"" || text == "\'") && previousToken(document, range) != "\\") { - const QString next = nextToken(document, range); - // Eat it if already there - if (next == text) { - KTextEditor::Cursor saved = range.end(); - document->removeText(range); - document->activeView()->setCursorPosition(saved); - } - // Quotation marks only inserted if followed by one of the allowed - // next tokens and the number of marks in the insertion line is even - // (excluding the already inserted mark) - else if (allowedNextToken.contains(next) - && (document->line(range.start().line()).count(text) % 2) ) { - insertAutoBracket(document, range, text); - } - } -} - -/** - * Automatically inserts closing bracket. Cursor - * is placed in between the brackets. - * @param document Current document. - * @param range Inserted text range (by text-inserted slot) - * @param brace Brace to insert - */ -void AutoBracePluginDocument::insertAutoBracket(KTextEditor::Document *document, - const KTextEditor::Range& range, - const QString& brace) { - // Disconnect Slots to avoid check for redundant closing brackets - disconnectSlots(document); - - // Save range to allow following remove operation to - // detect the corresponding closing bracket - m_lastRange = range; - - KTextEditor::Cursor saved = range.end(); - // Depending on brace, insert corresponding closing brace. - document->insertText(range.end(), brace); - document->activeView()->setCursorPosition(saved); - - // Re-Enable insertion slot. - connectSlots(document); -} - -/** - * Returns next charater after specified text range in document. - * @param document Current document. - * @param range Inserted text range (by text-inserted slot) - * @return Next character after text range - */ -const QString AutoBracePluginDocument::nextToken(KTextEditor::Document* document, const KTextEditor::Range& range) -{ - // Calculate range after insertion (exactly one character) - KTextEditor::Range afterRange(range.end(), range.end().line(), range.end().column()+1); - - return (afterRange.isValid() ? document->text(afterRange) : ""); -} - -/** - * Returns previous charater before specified text range in document. - * @param document Current document. - * @param range Inserted text range (by text-inserted slot) - * @return Next character after text range - */ -const QString AutoBracePluginDocument::previousToken(KTextEditor::Document* document, const KTextEditor::Range& range) -{ - // Calculate range before insertion (exactly one character) - KTextEditor::Range beforeRange(range.start().line(), range.start().column()-1, range.start().line(), - range.start().column()); - - return (beforeRange.isValid() ? document->text(beforeRange) : ""); -} - -bool AutoBracePluginDocument::isInsertionCandidate(KTextEditor::Document *document, int openingBraceLine) { - QString line = document->line(openingBraceLine); - if (line.isEmpty() || !line.endsWith('{')) { - return false; - } - - // Get the indentation prefix. - QRegExp rx("^(\\s+)"); - QString indentation = (rx.indexIn(line) == -1) ? "" : rx.cap(1); - - // Determine whether to insert a brace or not, depending on the indentation - // of the upcoming (non-empty) line. - bool isCandidate = true; - QString indentationLength = QString::number(indentation.length()); - QString indentationLengthMinusOne = QString::number(indentation.length() - 1); - - ///TODO: make configurable - // these tokens must not start a line that is used to get the correct indendation width - QStringList forbiddenTokenList; - if ( line.contains("class") || line.contains("interface") || line.contains("struct") ) { - forbiddenTokenList << "private" << "public" << "protected"; - if ( document->mode() == "C++" ) { - forbiddenTokenList << "signals" << "Q_SIGNALS"; - } else { - // PHP and potentially others - forbiddenTokenList << "function"; - } - } - if ( (document->mode() == "C++" || document->mode() == "C") && line.contains("namespace", Qt::CaseInsensitive) ) { - // C++ specific - forbiddenTokenList << "class" << "struct"; - } - const QString forbiddenTokens = forbiddenTokenList.isEmpty() ? QLatin1String("") : QString(QLatin1String("(?!") + forbiddenTokenList.join(QLatin1String("|")) + QLatin1Char(')')); - - for (int i = openingBraceLine + 1; i < document->lines(); ++i) - { - line = document->line(i); - if (line.trimmed().isEmpty()) { - continue; // Empty lines are not a reliable source of information. - } - - if (indentation.length() == 0) { - // Inserting a brace is ok if there is a line (not starting with a - // brace) without indentation. - rx.setPattern("^(?=[^\\}\\s])" - // But it's not OK if the line starts with one of our forbidden tokens. - + forbiddenTokens - ); - } - else { - rx.setPattern("^(?:" - // Inserting a brace is ok if there is a closing brace with - // less indentation than the opener line. - "[\\s]{0," + indentationLengthMinusOne + "}\\}" - "|" - // Inserting a brace is ok if there is a line (not starting with a - // brace) with less or similar indentation as the original line. - "[\\s]{0," + indentationLength + "}(?=[^\\}\\s])" - // But it's not OK if the line starts with one of our forbidden tokens. - + forbiddenTokens + - ")" - ); - } - - if (rx.indexIn(line) == -1) { - // There is already a brace, or the line is indented more than the - // opener line (which means we expect a brace somewhere further down), - // or we found a forbidden token. - // So don't insert the brace, and just indent the line. - isCandidate = false; - } - // Quit the loop - a non-empty line always leads to a definitive decision. - break; - } - - if (isCandidate) { - m_indentation = indentation; - // in C++ automatically add a semicolon after the closing brace when we create a new class/struct - if ( (document->mode() == "C++" || document->mode() == "C") - && document->line(openingBraceLine).indexOf(QRegExp("(?:class|struct|enum)\\s+[^\\s]+(\\s*[:,](\\s*((public|protected|private)\\s+)?[^\\s]+))*\\s*\\{\\s*$")) != -1 ) - { - m_withSemicolon = true; - } else { - m_withSemicolon = false; - } - } - return isCandidate; -} - -#include "autobrace.moc" diff --git a/part/plugins/autobrace/autobrace.h b/part/plugins/autobrace/autobrace.h deleted file mode 100644 index 6be71f0..0000000 --- a/part/plugins/autobrace/autobrace.h +++ /dev/null @@ -1,106 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2008 Jakob Petsovits - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef AUTOBRACE_H -#define AUTOBRACE_H - -#include -#include -#include -#include - -#include -#include -#include -#include - -class AutoBracePlugin - : public KTextEditor::Plugin -{ - Q_OBJECT - - public: - explicit AutoBracePlugin(QObject *parent = 0, const QVariantList &args = QVariantList()); - virtual ~AutoBracePlugin(); - - static AutoBracePlugin *self() { return plugin; } - - void addView (KTextEditor::View *view); - void removeView (KTextEditor::View *view); - - void readConfig(); - void writeConfig(); - - virtual void readConfig (KConfig *) {} - virtual void writeConfig (KConfig *) {} - - /// Inline Option Get/Setters - bool autoBrackets() const { return m_autoBrackets; } - void setAutoBrackets(bool y) { m_autoBrackets = y; } - bool autoQuotations() const { return m_autoQuotations; } - void setAutoQuotations(bool y) { m_autoQuotations = y; } - private: - static AutoBracePlugin *plugin; - QHash m_documents; - QHash m_docplugins; - bool m_autoBrackets; - bool m_autoQuotations; -}; - -class AutoBracePluginDocument - : public QObject, public KXMLGUIClient -{ - Q_OBJECT - - public: - explicit AutoBracePluginDocument(KTextEditor::Document *document, const bool& autoBrackets, const bool& autoQuotations); - ~AutoBracePluginDocument(); - - private Q_SLOTS: - void slotTextChanged(KTextEditor::Document *document); - void slotTextInserted(KTextEditor::Document *document, const KTextEditor::Range& range); - void slotTextRemoved(KTextEditor::Document *document, const KTextEditor::Range& range); - - void connectSlots(KTextEditor::Document* document); - void disconnectSlots(KTextEditor::Document* document); - - private: - bool isInsertionCandidate(KTextEditor::Document *document, int openingBraceLine); - - Q_SIGNALS: - void indent(); - - private: - void insertAutoBracket(KTextEditor::Document *document,const KTextEditor::Range& range, - const QString& brace); - const QString previousToken(KTextEditor::Document *document,const KTextEditor::Range& range); - const QString nextToken(KTextEditor::Document *document,const KTextEditor::Range& range); - - int m_insertionLine; - QString m_indentation; - bool m_withSemicolon; - QMap m_brackets; - KTextEditor::Range m_lastRange; - const bool& m_autoBrackets; - const bool& m_autoQuotations; -}; - -K_PLUGIN_FACTORY_DECLARATION(AutoBracePluginFactory) - -#endif // AUTOBRACE_H diff --git a/part/plugins/autobrace/autobrace_config.cpp b/part/plugins/autobrace/autobrace_config.cpp deleted file mode 100644 index b44af51..0000000 --- a/part/plugins/autobrace/autobrace_config.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2010 André Stein - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "autobrace_config.h" -#include "autobrace.h" - -#include -#include - -#include -#include -#include -#include -#include - -AutoBraceConfig::AutoBraceConfig(QWidget *parent, const QVariantList &args) - : KCModule(AutoBracePluginFactory::componentData(), parent, args) -{ - QVBoxLayout *layout = new QVBoxLayout(this); - - m_autoBrackets = new QCheckBox(i18n("Automatically add closing brackets ) and ]"), this); - m_autoQuotations = new QCheckBox(i18n("Automatically add closing quotation marks"), this); - - layout->addWidget(m_autoBrackets); - layout->addWidget(m_autoQuotations); - - setLayout(layout); - - load(); - - // Changed slots - connect(m_autoBrackets, SIGNAL(toggled(bool)), this, SLOT(slotChanged(bool))); - connect(m_autoQuotations, SIGNAL(toggled(bool)), this, SLOT(slotChanged(bool))); -} - -AutoBraceConfig::~AutoBraceConfig() -{ -} - -void AutoBraceConfig::save() -{ - if (AutoBracePlugin::self()) - { - AutoBracePlugin::self()->setAutoBrackets(m_autoBrackets->isChecked()); - AutoBracePlugin::self()->setAutoQuotations(m_autoQuotations->isChecked()); - AutoBracePlugin::self()->writeConfig(); - } - else - { - KConfigGroup cg(KGlobal::config(), "AutoBrace Plugin"); - cg.writeEntry("autobrackets", m_autoBrackets->isChecked()); - cg.writeEntry("autoquotations", m_autoQuotations->isChecked()); - } - - emit changed(false); -} - -void AutoBraceConfig::load() -{ - if (AutoBracePlugin::self()) - { - AutoBracePlugin::self()->readConfig(); - m_autoBrackets->setChecked(AutoBracePlugin::self()->autoBrackets()); - m_autoQuotations->setChecked(AutoBracePlugin::self()->autoQuotations()); - } - else - { - KConfigGroup cg(KGlobal::config(), "AutoBrace Plugin" ); - m_autoBrackets->setChecked(cg.readEntry("autobrackets", QVariant(true)).toBool()); - m_autoQuotations->setChecked(cg.readEntry("autoquotations", QVariant(true)).toBool()); - } - - emit changed(false); -} - -void AutoBraceConfig::defaults() -{ - m_autoBrackets->setChecked(true); - m_autoQuotations->setChecked(true); - - emit changed(true); -} - -void AutoBraceConfig::slotChanged(bool) -{ - emit changed(true); -} - -#include "autobrace_config.moc" - diff --git a/part/plugins/autobrace/autobrace_config.h b/part/plugins/autobrace/autobrace_config.h deleted file mode 100644 index c2cf6e2..0000000 --- a/part/plugins/autobrace/autobrace_config.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2010 André Stein - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef TIMEDATE_CONFIG_H -#define TIMEDATE_CONFIG_H - -#include - -class QCheckBox; - -class AutoBraceConfig - : public KCModule -{ - Q_OBJECT - -public: - explicit AutoBraceConfig(QWidget *parent = 0, const QVariantList &args = QVariantList()); - virtual ~AutoBraceConfig(); - - virtual void save(); - virtual void load(); - virtual void defaults(); - -private Q_SLOTS: - void slotChanged(bool); - -private: - QCheckBox* m_autoBrackets; - QCheckBox* m_autoQuotations; -}; - -#endif // TIMEDATE_CONFIG_H - diff --git a/part/plugins/autobrace/icons/CMakeLists.txt b/part/plugins/autobrace/icons/CMakeLists.txt deleted file mode 100644 index ee02df8..0000000 --- a/part/plugins/autobrace/icons/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ - -kde4_install_icons( ${ICON_INSTALL_DIR} ) diff --git a/part/plugins/autobrace/icons/hisc-app-ktexteditorautobrace.svgz b/part/plugins/autobrace/icons/hisc-app-ktexteditorautobrace.svgz deleted file mode 100644 index c4a76ac..0000000 Binary files a/part/plugins/autobrace/icons/hisc-app-ktexteditorautobrace.svgz and /dev/null differ diff --git a/part/plugins/autobrace/ktexteditor_autobrace.desktop b/part/plugins/autobrace/ktexteditor_autobrace.desktop deleted file mode 100644 index 47e8de9..0000000 --- a/part/plugins/autobrace/ktexteditor_autobrace.desktop +++ /dev/null @@ -1,122 +0,0 @@ -[Desktop Entry] -X-KDE-Library=ktexteditor_autobrace -X-KDE-PluginKeyword=ktexteditor_autobrace -X-KDE-PluginInfo-Author=Jakob Petsovits -X-KDE-PluginInfo-Email=jpetso@gmx.at -X-KDE-PluginInfo-Name=ktexteditorautobrace -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://kate.kde.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-ParentApp=kate -X-KDE-Version=4.0 -X-KDE-ServiceTypes=KTextEditor/Plugin -Type=Service -Icon=ktexteditorautobrace -Name=AutoBrace -Name[ar]=الأقواس التلقائية -Name[ast]=AutoBrace -Name[bg]=Ðвтоматични Ñкоби -Name[ca]=Parèntesis automàtics -Name[ca@valencia]=Parèntesis automàtics -Name[da]=AutoKlamme -Name[de]=Automatische Klammern -Name[el]=Αυτόματες παÏενθέσεις -Name[en_GB]=AutoBrace -Name[eo]=AutoBrace -Name[es]=AutoBrace -Name[et]=Automaatsulud -Name[eu]=Parentesi automatikoak -Name[fi]=AutomaattiSulut -Name[fr]=Accolades automatiques -Name[ga]=AutoBrace -Name[gl]=Parénteses automáticos -Name[hr]=AutoBrace -Name[hu]=Automatikus járójelbezáró -Name[ia]=AutoParenthese -Name[id]=KurawalOtomatis -Name[is]=SjálfvirkirSvigar -Name[it]=Graffe automatiche -Name[ja]=è‡ªå‹•æ‹¬å¼§ç”Ÿæˆ -Name[kk]=ÐвтоЖақшаЖабу -Name[km]=AutoBrace -Name[kn]=AutoBrace -Name[ko]=괄호 닫기 -Name[lt]=Automatinis kabuÄių uždarymas -Name[nb]=AutoBrace -Name[nds]=Auto-Klemmen -Name[nl]=AutoHaakjes -Name[nn]=Autoparentes -Name[pa]=ਆਟੋ-ਬਰੈਕਟ -Name[pl]=Automatyczne nawiasy -Name[pt]=Auto-Parêntesis -Name[pt_BR]=Parênteses automático -Name[ro]=ParantezeAutomate -Name[ru]=ÐвтоматичеÑкое закрытие Ñкобок -Name[sk]=Automatické zátvorky -Name[sl]=SamodejniOklepaji -Name[sr]=ÐутоматÑке заграде -Name[sr@ijekavian]=ÐутоматÑке заграде -Name[sr@ijekavianlatin]=Automatske zagrade -Name[sr@latin]=Automatske zagrade -Name[sv]=Automatisk parentes -Name[tg]=AutoBrace -Name[th]=ปิดวงเล็บให้อัตโนมัติ -Name[tr]=AutoBrace -Name[uk]=AutoBrace -Name[x-test]=xxAutoBracexx -Name[zh_CN]=è‡ªåŠ¨åŠ æ‹¬å· -Name[zh_TW]=自動產生括號 -Comment=Insert closing braces on pressing Enter -Comment[ar]=تدخل قوس الاغلاق عند ضغط زر الإدخال -Comment[bg]=Вмъкване на затварÑщи Ñкоби при натиÑкане на Enter -Comment[ca]=Insereix els parèntesis de tancament en prémer Retorn -Comment[ca@valencia]=Insereix els parèntesis de tancament en prémer Retorn -Comment[da]=Insæt afsluttende klammer ved tryk pÃ¥ Retur -Comment[de]=Beim Drücken der Eingabetaste schließende Klammer einfügen -Comment[el]=Εισαγωγή τελικής παÏένθεσης με την πίεση του Enter -Comment[en_GB]=Insert closing braces on pressing Enter -Comment[es]=Insertar llaves de cierre al pulsar Intro -Comment[et]=Lõpetavate sulgude lisamine Enteri vajutamisel -Comment[eu]=Ipini ixteko parentesia Sartu sakatutakoan -Comment[fi]=Lisää sulkeva sulkumerkki enter-näppäintä painamalla -Comment[fr]=Insère une accolade fermante en appuyant sur « Entrée » -Comment[ga]=Ionsáigh lúibín deiridh nuair a bhrúitear Enter -Comment[gl]=Insire os parénteses de peche ao premer Intro -Comment[hr]=Umetni zatvarajuće vitiÄaste zagrade pritiskom na Enter -Comment[hu]=Az Enter megnyomásakor beszúr egy bezáró zárójelet -Comment[ia]=Il inserta un parentheses claudente quando premente Enter -Comment[id]=Masukkan kurawal penutup saat menekan Enter -Comment[is]=Setur lokunarsviga þegar ýtt er á Enter -Comment[it]=Inserisce parentesi graffe quando premi Invio -Comment[ja]=Enter キーを押ã™ã“ã¨ã§é–‰ã˜ã‚‹æ‹¬å¼§ã‚’挿入ã—ã¾ã™ -Comment[kk]=Enter пернені баÑқанда жақшаны жабу -Comment[km]=បញ្ចូល​រង្វង់ក្រចក​បិទ​នៅ​ពáŸáž›â€‹áž…ុច​គ្រាប់​ចុច​បញ្ចូល (Enter) -Comment[ko]=Enter 키를 누를 ë•Œ 닫는 괄호 삽입하기 -Comment[lt]=Ä®terpti užverianÄias kabutes nuspaudžiant Ä®vesti (Enter) -Comment[nb]=Sett inn avsluttende krøllparentes nÃ¥r Enter trykkes -Comment[nds]=Afsluten Klemmen mit de Ingaavtast infögen -Comment[nl]=Voert afsluithaakjes in bij indrukken van Enter -Comment[nn]=Set inn avsluttande parentesteikn nÃ¥r du trykkjer «Enter» -Comment[pa]=à¨à¨‚ਟਰ ਦੱਬਣ ਉੱਤੇ ਬਰੈਕਟ ਬੰਦ ਕਰੋ -Comment[pl]=Wstawia nawiasy zamykajÄ…ce po naciÅ›niÄ™ciu Enter -Comment[pt]=Colocar os parêntesis de fecho ao carregar em Enter -Comment[pt_BR]=Inserir parênteses de fechamento ao pressionar Enter -Comment[ro]=Inserează paranteze de închidere la apăsarea Enter -Comment[ru]=Ð’Ñтавка парной Ñкобки при нажатии клавиши Enter -Comment[sk]=Vloží uzatváracie zátvorky po stlaÄení klávesy Enter -Comment[sl]=Vstavi zakljuÄne oklepaje ob pritisku na Enter -Comment[sr]=Умеће затварајуће заграде кад Ñе притиÑне Enter -Comment[sr@ijekavian]=Умеће затварајуће заграде кад Ñе притиÑне Enter -Comment[sr@ijekavianlatin]=Umeće zatvarajuće zagrade kad se pritisne Enter -Comment[sr@latin]=Umeće zatvarajuće zagrade kad se pritisne Enter -Comment[sv]=Infoga avslutande parenteser när returtangenten trycks -Comment[tg]=Ҳангоми зеркунии Enter банди шимро ворид кунед -Comment[th]=à¹à¸—รà¸à¸§à¸‡à¹€à¸¥à¹‡à¸šà¸›à¸´à¸”ให้โดยอัตโนมัติเมื่อà¸à¸”ปุ่มพิมพ์ Enter à¹à¸¥à¹‰à¸§ -Comment[tr]=Enter'a basıldığında parantezi kapat -Comment[uk]=Ð’ÑтавлÑÑ” завершальні дужки піÑÐ»Ñ Ð½Ð°Ñ‚Ð¸ÑÐºÐ°Ð½Ð½Ñ Enter -Comment[x-test]=xxInsert closing braces on pressing Enterxx -Comment[zh_CN]=按下回车键å¯æ’å…¥ä¸€å¯¹æ‹¬å· -Comment[zh_TW]=按下 Enter 時自動æ’入關閉(å³å´ï¼‰æ‹¬è™Ÿ diff --git a/part/plugins/autobrace/ktexteditor_autobrace_config.desktop b/part/plugins/autobrace/ktexteditor_autobrace_config.desktop deleted file mode 100644 index 2b2ce5b..0000000 --- a/part/plugins/autobrace/ktexteditor_autobrace_config.desktop +++ /dev/null @@ -1,41 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule -X-KDE-Library=ktexteditor_autobrace -X-KDE-PluginKeyword=ktexteditor_autobrace_config -X-KDE-ParentComponents=ktexteditorautobrace -Name=AutoBrace Configuration -Name[bg]=ÐаÑтройки на автоматичните Ñкоби -Name[ca]=Configuració dels parèntesis automàtics -Name[ca@valencia]=Configuració dels parèntesis automàtics -Name[da]=Indstilling af AutoBrace -Name[de]=Einstellungen zu automatischer Klammersetzung -Name[el]=ΡÏθμιση αυτόματων παÏενθέσεων -Name[en_GB]=AutoBrace Configuration -Name[es]=Configuración de los paréntesis automáticos -Name[et]=Automaatsete sulgude seadistamine -Name[gl]=Configuración de AutoBrace -Name[ia]=Configuration de AutoBrace (Parentheses Automatic) -Name[id]=Konfigurasi KurawalOtomatis -Name[is]=Stillingar Sjálfvirkra Sviga -Name[ja]=自動括弧設定 -Name[kk]=ÐвтоЖақшаЖабу баптауы -Name[km]=ការ​កំណážáŸ‹â€‹ážšáž…នាសម្ពáŸáž“្ធ AutoBrace -Name[kn]=AutoBrace ಸಂರಚನೆ -Name[nb]=Oppsett for automatisk parenteslukking -Name[nds]=Auto-Klemmen instellen -Name[nl]=Configuratie voor automatische haakjes -Name[pa]=AutoBrace ਸੰਰਚਨਾ -Name[pt]=Configuração dos Parêntesis Automáticos -Name[pt_BR]=Configuração automática do parêntesis -Name[ru]=ÐаÑтройка автоматичеÑкого Ð·Ð°ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ñкобок -Name[sr]=Подешавање аутоматÑких заграда -Name[sr@ijekavian]=Подешавање аутоматÑких заграда -Name[sr@ijekavianlatin]=PodeÅ¡avanje automatskih zagrada -Name[sr@latin]=PodeÅ¡avanje automatskih zagrada -Name[sv]=Automatisk parentesinställning -Name[tr]=AutoBrace Yapılandırması -Name[uk]=ÐÐ°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸Ñ… дужок -Name[x-test]=xxAutoBrace Configurationxx -Name[zh_CN]=自动加括å·é…ç½® -Name[zh_TW]=AutoBrace 組態 diff --git a/part/plugins/exporter/CMakeLists.txt b/part/plugins/exporter/CMakeLists.txt deleted file mode 100644 index 08fa89b..0000000 --- a/part/plugins/exporter/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -project( ktexteditor_exporter ) - -########### next target ############### - -set( ktexteditor_exporter_PART_SRCS - exporterplugin.cpp - exporterpluginview.cpp - htmlexporter.cpp -) - -kde4_add_plugin( ktexteditor_exporter ${ktexteditor_exporter_PART_SRCS} ) - -target_link_libraries( ktexteditor_exporter ${KDE4_KDECORE_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ) - -install( TARGETS ktexteditor_exporter DESTINATION ${PLUGIN_INSTALL_DIR} ) - -########### install files ############### - -install( FILES ktexteditor_exporter.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) -install( FILES ktexteditor_exporterui.rc DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_exporter ) diff --git a/part/plugins/exporter/TODO b/part/plugins/exporter/TODO deleted file mode 100644 index d8ca015..0000000 --- a/part/plugins/exporter/TODO +++ /dev/null @@ -1,13 +0,0 @@ -1) add more exporters -- LaTeX -- Bash color codes -- ??? - -2) add dialog for export action -- select exporter -- copy to clipboard -- save to file - -3) make it possible to run this from the outside - -4) optionally add linenumbers \ No newline at end of file diff --git a/part/plugins/exporter/abstractexporter.h b/part/plugins/exporter/abstractexporter.h deleted file mode 100644 index 0c8f72e..0000000 --- a/part/plugins/exporter/abstractexporter.h +++ /dev/null @@ -1,80 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef ABSTRACTEXPORTER_H -#define ABSTRACTEXPORTER_H - -#include - -#include -#include -#include -#include -#include -#include - -class AbstractExporter -{ - public: - /// If \p m_encapsulate is set, you should add some kind of header in the ctor - /// to \p m_output. - AbstractExporter(KTextEditor::View* view, - QTextStream &output, const bool encapsulate = false) - : m_view(view), m_output(output), m_encapsulate(encapsulate), - m_defaultAttribute(0) - { - QColor defaultBackground; - if ( KTextEditor::ConfigInterface* ciface = qobject_cast< KTextEditor::ConfigInterface* >(m_view) ) { - QVariant variant = ciface->configValue("background-color"); - if ( variant.canConvert() ) { - defaultBackground = variant.value(); - } - } - if ( KTextEditor::HighlightInterface* hiface = qobject_cast< KTextEditor::HighlightInterface* >(m_view->document()) ) { - m_defaultAttribute = hiface->defaultStyle(KTextEditor::HighlightInterface::dsNormal); - m_defaultAttribute->setBackground(QBrush(defaultBackground)); - } - } - - /// Gets called after everything got exported. - /// Hence, if \p m_encapsulate is set, you should probably add some kind of footer here. - virtual ~AbstractExporter() - {} - - /// Begin a new line. - virtual void openLine() = 0; - - /// Finish the current line. - virtual void closeLine(const bool lastLine) = 0; - - /// Export \p text with given text attribute \p attrib. - /// NOTE: Check \p attrib, it might be null for KTextEditors that do not implement the - /// HighlightInterface. - virtual void exportText(const QString& text, const KTextEditor::Attribute::Ptr& attrib) = 0; - - protected: - KTextEditor::View* m_view; - QTextStream &m_output; - bool m_encapsulate; - KTextEditor::Attribute::Ptr m_defaultAttribute; -}; - -#endif // ABSTRACTEXPORTER_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/exporter/exporterplugin.cpp b/part/plugins/exporter/exporterplugin.cpp deleted file mode 100644 index 9f835c6..0000000 --- a/part/plugins/exporter/exporterplugin.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "exporterplugin.h" - -#include - -#include - -#include "exporterpluginview.h" - -K_PLUGIN_FACTORY_DEFINITION(ExporterPluginFactory, - registerPlugin("ktexteditor_exporter"); - ) -K_EXPORT_PLUGIN(ExporterPluginFactory("ktexteditor_exporter", "ktexteditor_plugins")) - -ExporterPlugin::ExporterPlugin(QObject *parent, const QVariantList &args) - : KTextEditor::Plugin(parent) -{ - Q_UNUSED(args); -} - -ExporterPlugin::~ExporterPlugin() -{ -} - -void ExporterPlugin::addView(KTextEditor::View *view) -{ - // need to keep track of, since the plugin might get disabled and we have to delete the views - m_views[view] = new ExporterPluginView(view); -} - -void ExporterPlugin::removeView(KTextEditor::View* view) -{ - delete m_views.take(view); -} - -#include "exporterplugin.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/exporter/exporterplugin.h b/part/plugins/exporter/exporterplugin.h deleted file mode 100644 index 6e8225c..0000000 --- a/part/plugins/exporter/exporterplugin.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef EXPORTERPLUGIN_H -#define EXPORTERPLUGIN_H - -#include - -#include - -#include - -namespace KTextEditor { -class View; -} - -class ExporterPluginView; - -class ExporterPlugin - : public KTextEditor::Plugin -{ - Q_OBJECT - - public: - explicit ExporterPlugin(QObject *parent = 0, const QVariantList &args = QVariantList()); - virtual ~ExporterPlugin(); - - virtual void addView (KTextEditor::View *view); - virtual void removeView(KTextEditor::View* view); - - private: - QMap m_views; -}; - -K_PLUGIN_FACTORY_DECLARATION(ExporterPluginFactory) - -#endif // EXPORTERPLUGIN_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/exporter/exporterpluginview.cpp b/part/plugins/exporter/exporterpluginview.cpp deleted file mode 100644 index b6ee9e2..0000000 --- a/part/plugins/exporter/exporterpluginview.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * Copyright (C) 2002 John Firebaugh - * Copyright (C) 2001 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "exporterpluginview.h" - -#include "exporterplugin.h" -#include "abstractexporter.h" -#include "htmlexporter.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -ExporterPluginView::ExporterPluginView(KTextEditor::View* view) - : QObject(view), KXMLGUIClient(view), m_view(view) -{ - setComponentData( ExporterPluginFactory::componentData() ); - setXMLFile("ktexteditor_exporterui.rc"); - - m_copyAction = actionCollection()->addAction("edit_copy_html", this, SLOT(exportToClipboard())); - m_copyAction->setIcon(KIcon("edit-copy")); - m_copyAction->setText(i18n("Copy as &HTML")); - m_copyAction->setWhatsThis(i18n("Use this command to copy the currently selected text as HTML to the system clipboard.")); - m_copyAction->setEnabled(m_view->selection()); - - m_fileExportAction = actionCollection()->addAction("file_export_html", this, SLOT(exportToFile())); - m_fileExportAction->setText(i18n("E&xport as HTML...")); - m_fileExportAction->setWhatsThis(i18n("This command allows you to export the current document" - " with all highlighting information into a HTML document.")); - - connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), - this, SLOT(updateSelectionAction(KTextEditor::View*))); -} - -ExporterPluginView::~ExporterPluginView() -{ -} - -void ExporterPluginView::updateSelectionAction(KTextEditor::View* view) -{ - Q_ASSERT(view == m_view); Q_UNUSED(view) - m_copyAction->setEnabled(m_view->selection()); -} - -void ExporterPluginView::exportToClipboard() -{ - if (!m_view->selection()) { - return; - } - - QMimeData *data = new QMimeData(); - - QString s; - QTextStream output( &s, QIODevice::WriteOnly ); - exportData(true, output); - - data->setHtml(s); - data->setText(s); - - QApplication::clipboard()->setMimeData(data); -} - -void ExporterPluginView::exportToFile() -{ - KUrl url = KFileDialog::getSaveUrl(m_view->document()->documentName(), "text/html", - m_view, i18n("Export File as HTML")); - - if ( url.isEmpty() ) { - return; - } - - QString filename; - - if ( url.isLocalFile() ) { - filename = url.toLocalFile(); - } else { - ///TODO: cleanup! don't let the temp files lay around - KTemporaryFile tmp; // ### only used for network export - tmp.setAutoRemove(false); - tmp.open(); - filename = tmp.fileName(); - } - - KSaveFile savefile(filename); - if (savefile.open()) { - QTextStream outputStream ( &savefile ); - - exportData(false, outputStream); - - savefile.finalize(); //check error? - } -// else -// {/*ERROR*/} - - if ( !url.isLocalFile() ) { - KIO::NetAccess::upload( filename, url, 0 ); - } -} - -void ExporterPluginView::exportData(const bool useSelection, QTextStream &output) -{ - const KTextEditor::Range range = useSelection ? m_view->selectionRange() : m_view->document()->documentRange(); - const bool blockwise = useSelection ? m_view->blockSelection() : false; - - if ( (blockwise || range.onSingleLine()) && (range.start().column() > range.end().column() ) ) { - return; - } - - //outputStream.setEncoding(QTextStream::UnicodeUTF8); - output.setCodec(QTextCodec::codecForName("UTF-8")); - - ///TODO: add more exporters - AbstractExporter* exporter; - - exporter = new HTMLExporter(m_view, output, !useSelection); - - KTextEditor::HighlightInterface* hiface = qobject_cast(m_view->document()); - - const KTextEditor::Attribute::Ptr noAttrib(0); - - for (int i = range.start().line(); (i <= range.end().line()) && (i < m_view->document()->lines()); ++i) - { - const QString &line = m_view->document()->line(i); - - QList attribs; - if ( hiface ) { - attribs = hiface->lineAttributes(i); - } - - int lineStart = 0; - int remainingChars = line.length(); - if ( blockwise || range.onSingleLine() ) { - lineStart = range.start().column(); - remainingChars = range.columnWidth(); - } else if ( i == range.start().line() ) { - lineStart = range.start().column(); - } else if ( i == range.end().line() ) { - remainingChars = range.end().column(); - } - - int handledUntil = lineStart; - - foreach ( const KTextEditor::HighlightInterface::AttributeBlock& block, attribs ) { - // honor (block-) selections - if ( block.start + block.length <= lineStart ) { - continue; - } else if ( block.start >= lineStart + remainingChars ) { - break; - } - int start = qMax(block.start, lineStart); - if ( start > handledUntil ) { - exporter->exportText( line.mid( handledUntil, start - handledUntil ), noAttrib ); - } - int length = qMin(block.length, remainingChars); - exporter->exportText( line.mid( start, length ), block.attribute); - handledUntil = start + length; - } - - if ( handledUntil < lineStart + remainingChars ) { - exporter->exportText( line.mid( handledUntil, remainingChars ), noAttrib ); - } - - exporter->closeLine(i == range.end().line()); - } - - delete exporter; - - output.flush(); -} - -#include "exporterpluginview.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/exporter/exporterpluginview.h b/part/plugins/exporter/exporterpluginview.h deleted file mode 100644 index 9e3e52a..0000000 --- a/part/plugins/exporter/exporterpluginview.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef EXPORTERPLUGINVIEW_H -#define EXPORTERPLUGINVIEW_H - -#include -#include - -#include - -namespace KTextEditor { -class View; -} - -class ExporterPluginView : public QObject, public KXMLGUIClient -{ - Q_OBJECT - - public: - ExporterPluginView(KTextEditor::View* view = 0); - ~ExporterPluginView(); - - private: - ///TODO: maybe make this scriptable for additional exporters? - void exportData(const bool useSelction, QTextStream& output); - - private slots: - void exportToClipboard(); - void exportToFile(); - - void updateSelectionAction(KTextEditor::View *view); - - private: - KTextEditor::View* m_view; - QAction* m_copyAction; - QAction* m_fileExportAction; -}; - -#endif // EXPORTERPLUGINVIEW_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/exporter/htmlexporter.cpp b/part/plugins/exporter/htmlexporter.cpp deleted file mode 100644 index 5edfa64..0000000 --- a/part/plugins/exporter/htmlexporter.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2009 Milian Wolff - * Copyright (C) 2002 John Firebaugh - * Copyright (C) 2001 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "htmlexporter.h" - -#include - -#include - -HTMLExporter::HTMLExporter(KTextEditor::View* view, QTextStream& output, const bool encapsulate) - : AbstractExporter(view, output, encapsulate) -{ - if ( m_encapsulate ) { - // let's write the HTML header : - m_output << "" << endl; - m_output << "" << endl; - m_output << "" << endl; - m_output << "" << endl; - m_output << "" << endl; - m_output << "" << endl; - // for the title, we write the name of the file (/usr/local/emmanuel/myfile.cpp -> myfile.cpp) - m_output << "" << view->document()->documentName() << "" << endl; - m_output << "" << endl; - m_output << "" << endl; - } - - if ( !m_defaultAttribute ) { - m_output << "
" << endl;
-  } else {
-    m_output << QString("
")
-                  .arg(m_defaultAttribute->fontBold() ? "font-weight:bold;" : "")
-                  .arg(m_defaultAttribute->fontItalic() ? "text-style:italic;" : "")
-                  .arg("color:" + m_defaultAttribute->foreground().color().name() + ';')
-                  .arg("background-color:" + m_defaultAttribute->background().color().name() + ';')
-             << endl;
-  }
-}
-
-HTMLExporter::~HTMLExporter()
-{
-  m_output << "
" << endl; - - if ( m_encapsulate ) { - m_output << "" << endl; - m_output << "" << endl; - } -} - -void HTMLExporter::openLine() -{ -} - -void HTMLExporter::closeLine(const bool lastLine) -{ - if ( !lastLine ) { - //we are inside a
, so a \n is a new line
-    m_output << "\n";
-  }
-}
-
-void HTMLExporter::exportText(const QString& text, const KTextEditor::Attribute::Ptr& attrib)
-{
-  if ( !attrib || !attrib->hasAnyProperty() || attrib == m_defaultAttribute ) {
-    m_output << Qt::escape(text);
-    return;
-  }
-
-  if ( attrib->fontBold() ) {
-    m_output << "";
-  }
-  if ( attrib->fontItalic() ) {
-    m_output << "";
-  }
-
-  bool writeForeground = attrib->hasProperty(QTextCharFormat::ForegroundBrush)
-    && (!m_defaultAttribute || attrib->foreground().color() != m_defaultAttribute->foreground().color());
-  bool writeBackground = attrib->hasProperty(QTextCharFormat::BackgroundBrush)
-    && (!m_defaultAttribute || attrib->background().color() != m_defaultAttribute->background().color());
-
-  if ( writeForeground || writeBackground ) {
-    m_output << QString("")
-                  .arg(writeForeground ? QString(QLatin1String("color:") + attrib->foreground().color().name() + QLatin1Char(';')) : QString())
-                  .arg(writeBackground ? QString(QLatin1String("background:") + attrib->background().color().name() + QLatin1Char(';')) : QString());
-  }
-
-  m_output << Qt::escape(text);
-
-  if ( writeBackground || writeForeground ) {
-    m_output << "";
-  }
-  if ( attrib->fontItalic() ) {
-    m_output << "";
-  }
-  if ( attrib->fontBold() ) {
-    m_output << "";
-  }
-}
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/part/plugins/exporter/htmlexporter.h b/part/plugins/exporter/htmlexporter.h
deleted file mode 100644
index 1d47acf..0000000
--- a/part/plugins/exporter/htmlexporter.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * This file is part of the KDE libraries
- * Copyright (C) 2009 Milian Wolff 
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef HTMLEXPORTER_H
-#define HTMLEXPORTER_H
-
-#include "abstractexporter.h"
-
-/// TODO: add abstract interface for future exporters
-class HTMLExporter : public AbstractExporter
-{
-  public:
-    HTMLExporter(KTextEditor::View* view, QTextStream& output, const bool withHeaderFooter = false);
-    virtual ~HTMLExporter();
-
-    virtual void openLine();
-    virtual void closeLine(const bool lastLine);
-    virtual void exportText(const QString& text, const KTextEditor::Attribute::Ptr& attrib);
-};
-
-#endif // HTMLEXPORTER_H
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/part/plugins/exporter/ktexteditor_exporter.desktop b/part/plugins/exporter/ktexteditor_exporter.desktop
deleted file mode 100644
index d164eca..0000000
--- a/part/plugins/exporter/ktexteditor_exporter.desktop
+++ /dev/null
@@ -1,122 +0,0 @@
-[Desktop Entry]
-X-KDE-Library=ktexteditor_exporter
-X-KDE-PluginKeyword=ktexteditor_exporter
-X-KDE-PluginInfo-Author=Milian Wolff
-X-KDE-PluginInfo-Email=mail@milianw.de
-X-KDE-PluginInfo-Name=ktexteditorexporter
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-Website=http://kate.kde.org
-X-KDE-PluginInfo-Category=Editor
-X-KDE-PluginInfo-Depends=
-X-KDE-PluginInfo-License=GPL
-X-KDE-PluginInfo-EnabledByDefault=true
-X-KDE-ParentApp=kate
-X-KDE-Version=4.0
-X-KDE-ServiceTypes=KTextEditor/Plugin
-Type=Service
-Icon=ktexteditorexporter
-Name=Exporter
-Name[ar]=المصدّر
-Name[ast]=Exporter
-Name[bg]=ИзнаÑÑне
-Name[ca]=Exportador
-Name[ca@valencia]=Exportador
-Name[cs]=Exportér
-Name[da]=Eksport
-Name[de]=Exporter
-Name[el]=Εξαγωγέας
-Name[en_GB]=Exporter
-Name[eo]=Eksportilo
-Name[es]=Exportador
-Name[et]=Eksport
-Name[eu]=Esportatzailea
-Name[fi]=Viejä
-Name[fr]=Exportation
-Name[ga]=Easpórtálaí
-Name[gl]=Exportador
-Name[hr]=Izvoznik
-Name[hu]=Exportáló
-Name[ia]=Exportator
-Name[id]=Pengekspor
-Name[is]=Útflytjari
-Name[it]=Esportatore
-Name[ja]=エクスãƒãƒ¼ãƒˆ
-Name[kk]=ЭкÑпорттау
-Name[km]=កម្មវិធីនាំចáŸáž‰
-Name[ko]=내보내기
-Name[lt]=Eksportas
-Name[nb]=Exporter
-Name[nds]=Export
-Name[nl]=Exportprogramma
-Name[nn]=Eksporter
-Name[pa]=à¨à¨•à¨¸à¨ªà©‹à¨°à¨Ÿà¨°
-Name[pl]=Eksportowanie
-Name[pt]=Exportação
-Name[pt_BR]=Exportação
-Name[ro]=Exportator
-Name[ru]=ЭкÑпорт
-Name[sk]=Export
-Name[sl]=Izvoznik
-Name[sr]=Извозник
-Name[sr@ijekavian]=Извозник
-Name[sr@ijekavianlatin]=Izvoznik
-Name[sr@latin]=Izvoznik
-Name[sv]=Export
-Name[tg]=Содирот
-Name[th]=ตัวส่งออà¸
-Name[tr]=Exporter
-Name[uk]=ІнÑтрумент екÑпортуваннÑ
-Name[x-test]=xxExporterxx
-Name[zh_CN]=导出器
-Name[zh_TW]=匯出器
-Comment=Export highlighted document to HTML
-Comment[ar]=صدر المستند المبرز إلى HTML
-Comment[bg]=ИзнаÑÑне на Ð¸Ð·Ð±Ñ€Ð°Ð½Ð¸Ñ Ð´Ð¾ÐºÑƒÐ¼ÐµÐ½Ñ‚ към HTML
-Comment[ca]=Exporta el document ressaltat a HTML
-Comment[ca@valencia]=Exporta el document ressaltat a HTML
-Comment[da]=Eksportér fremhævet dokument til HTML
-Comment[de]=Hervorgehobenes HTML-Dokument exportieren
-Comment[el]=Εξαγωγή επιλεγμένου εγγÏάφου σε HTML
-Comment[en_GB]=Export highlighted document to HTML
-Comment[es]=Exportar documento resaltado a HTML
-Comment[et]=Esiletõstetud dokumenti eksport HTML-i
-Comment[eu]=Esportatu nabarmendutako dokumentua HTML-ra
-Comment[fi]=Vie korostettu asiakirja HTML-muotoon
-Comment[fr]=Exporte le document sélectionné en HTML
-Comment[ga]=Easpórtáil an cháipéis aibhsithe mar HTML
-Comment[gl]=Exporta o documento realzado a HTML
-Comment[hr]=Izvezi osvijetljene dokumente u HTML
-Comment[hu]=HTML formátumban exportálja a kijelölt dokumentumot
-Comment[ia]=Il Exporta le documento evidentiate a HTML
-Comment[id]=Ekspor dokumen tersorot ke HTML
-Comment[is]=Flytur ljómaða skjalið í HTML
-Comment[it]=Esporta in HTML il documento evidenziato
-Comment[ja]=é¸æŠžã—ãŸæ–‡æ›¸ã‚’ HTML ã«ã‚¨ã‚¯ã‚¹ãƒãƒ¼ãƒˆã—ã¾ã™
-Comment[kk]=Белгіленген құжатты HTML-ге ÑкÑпорттау
-Comment[km]=នាំចáŸáž‰â€‹áž¯áž€ážŸáž¶ážšâ€‹ážŠáŸ‚លបានបន្លិច​ទៅ HTML
-Comment[ko]=강조한 문서를 HTML로 내보내기
-Comment[lt]=Eksportuoti pažymėtą dokumentą į HTML
-Comment[nb]=Eksporterer fremhevede dokumenter til HTML
-Comment[nds]=Syntaxmarkeert Dokment as HTML exporteren
-Comment[nl]=Geaccentueerd document exporteren naar HTML
-Comment[nn]=Eksporter det valde dokumentet til HTML
-Comment[pa]=ਹਾਈਲਾਈਟ ਕੀਤਾ ਡੌਕੂਮੈਂਟ HTML à¨à¨•à¨¸à¨ªà©‹à¨°à¨Ÿ ਕਰੋ
-Comment[pl]=Eksportuje podświetlone dokumenty do HTML
-Comment[pt]=Exportar o documento seleccionado para HTML
-Comment[pt_BR]=Exportar o documento selecionado para HTML
-Comment[ro]=Exportă documentul evidențiat în HTML
-Comment[ru]=ЭкÑпорт документов в HTML
-Comment[sk]=Exportuje zvýraznený dokument do HTML
-Comment[sl]=Izvozi oznaÄen dokument v HTML
-Comment[sr]=Извози документе Ñ Ð¸Ñтицањем у ХТМЛ
-Comment[sr@ijekavian]=Извози документе Ñ Ð¸Ñтицањем у ХТМЛ
-Comment[sr@ijekavianlatin]=Izvozi dokumente s isticanjem u HTML
-Comment[sr@latin]=Izvozi dokumente s isticanjem u HTML
-Comment[sv]=Exportera markerat dokument till HTML
-Comment[tg]=Ҳуҷҷати интихобшударо ба HTML захира кунед
-Comment[th]=ส่งออà¸à¹€à¸­à¸à¸ªà¸²à¸£à¸—ี่ถูà¸à¹€à¸™à¹‰à¸™à¹„ปเป็นรูปà¹à¸šà¸š HTML
-Comment[tr]=Açık olan belgeyi HTML olarak dışa aktar
-Comment[uk]=ЕкÑпорт позначеного документа до HTML
-Comment[x-test]=xxExport highlighted document to HTMLxx
-Comment[zh_CN]=导出加亮显示的文档到 HTML
-Comment[zh_TW]=å°‡çªé¡¯çš„文件匯出為 HTML
diff --git a/part/plugins/exporter/ktexteditor_exporterui.rc b/part/plugins/exporter/ktexteditor_exporterui.rc
deleted file mode 100644
index 80c309d..0000000
--- a/part/plugins/exporter/ktexteditor_exporterui.rc
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-  &File
-    
-  
-
-  &Edit
-    
-  
-
-
-
diff --git a/part/plugins/hlselection/CMakeLists.txt b/part/plugins/hlselection/CMakeLists.txt
deleted file mode 100755
index dc4ff9b..0000000
--- a/part/plugins/hlselection/CMakeLists.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-
-########### next target ###############
-
-set(ktexteditor_hlselection_PART_SRCS hlselectionplugin.cpp )
-
-kde4_add_plugin(ktexteditor_hlselection ${ktexteditor_hlselection_PART_SRCS})
-
-target_link_libraries(ktexteditor_hlselection  ${KDE4_KIO_LIBS} ktexteditor kdeui kfile)
-
-install(TARGETS  ktexteditor_hlselection  DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-
-########### install files ###############
-
-install( FILES ktexteditor_hlselection.desktop  DESTINATION  ${SERVICES_INSTALL_DIR} )
-
-# Dominik: right now, we do not have any actions, so do not insall ui.rc file
-# install( FILES ktexteditor_hlselectionui.rc  DESTINATION  ${DATA_INSTALL_DIR}/ktexteditor_hlselection )
diff --git a/part/plugins/hlselection/hlselectionplugin.cpp b/part/plugins/hlselection/hlselectionplugin.cpp
deleted file mode 100755
index 3e51ddc..0000000
--- a/part/plugins/hlselection/hlselectionplugin.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/* This file is part of the KDE libraries
-   Copyright (C) 2010 Dominik Haumann 
-
-   This library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Library General Public
-   License version 2 as published by the Free Software Foundation.
-
-   This library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   Library General Public License for more details.
-
-   You should have received a copy of the GNU Library General Public License
-   along with this library; see the file COPYING.LIB.  If not, write to
-   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-   Boston, MA 02110-1301, USA.
-*/
-
-#include "hlselectionplugin.h"
-#include "hlselectionplugin.moc"
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-
-K_PLUGIN_FACTORY( HighlightSelectionPluginFactory, registerPlugin(); )
-K_EXPORT_PLUGIN( HighlightSelectionPluginFactory( KAboutData( "ktexteditor_insertfile", "ktexteditor_plugins", ki18n("Highlight Selection"), "1.0", ki18n("Highlight Selection"), KAboutData::License_LGPL_V2 ) ) )
-
-//BEGIN HighlightSelectionPlugin
-HighlightSelectionPlugin::HighlightSelectionPlugin( QObject *parent, const QVariantList& )
-  : KTextEditor::Plugin ( parent )
-{
-}
-
-HighlightSelectionPlugin::~HighlightSelectionPlugin()
-{
-}
-
-void HighlightSelectionPlugin::addView(KTextEditor::View *view)
-{
-  HighlightSelectionPluginView *nview = new HighlightSelectionPluginView (view);
-  m_views.append (nview);
-}
-
-void HighlightSelectionPlugin::removeView(KTextEditor::View *view)
-{
-  foreach (HighlightSelectionPluginView *pluginView, m_views) {
-    if (pluginView->view() == view) {
-      m_views.removeAll(pluginView);
-      delete pluginView;
-      break;
-    }
-  }
-}
-//END HighlightSelectionPlugin
-
-//BEGIN HighlightSelectionPluginView
-HighlightSelectionPluginView::HighlightSelectionPluginView( KTextEditor::View *view)
-  : QObject( view )
-//   , KXMLGUIClient( view ) // XMLGUI stuff not needed right now
-{
-  setObjectName("highlight-selection-plugin");
-
-  m_view = view;
-
-  // we don't need any XMLGUI stuff, so comment out
-//  setComponentData( HighlightSelectionPluginFactory::componentData() );
-//  setXMLFile( "ktexteditor_hlselectionui.rc" );
-
-  connect(view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(selectionChanged()));
-  connect(view->document(), SIGNAL(aboutToReload(KTextEditor::Document*)), this, SLOT(clearHighlights()));
-}
-
-HighlightSelectionPluginView::~HighlightSelectionPluginView()
-{
-  clearHighlights();
-}
-
-KTextEditor::View* HighlightSelectionPluginView::view() const
-{
-  return m_view;
-}
-
-void HighlightSelectionPluginView::clearHighlights()
-{
-  qDeleteAll(m_ranges);
-  m_ranges.clear();
-  m_currentText.clear();
-}
-
-void HighlightSelectionPluginView::selectionChanged()
-{
-  QString text;
-  // if text of selection is still the same, abort
-  if (m_view->selection() && m_view->selectionRange().onSingleLine()) {
-    text = m_view->selectionText();
-    if (text == m_currentText) {
-      return;
-    }
-  }
-
-  // text changed: remove all highlights + create new ones
-  // (do not call clearHighlights(), since this also resets the m_currentText
-  qDeleteAll(m_ranges);
-  m_ranges.clear();
-  
-  // do not highlight strings with leading and trailing spaces
-  if (!text.isEmpty() && (text.at(0).isSpace() || text.at(text.length()-1).isSpace())) {
-    return; 
-  }
-
-  m_currentText = text;
-  if (!m_currentText.isEmpty()) {
-    createHighlights();
-  }
-}
-
-void HighlightSelectionPluginView::createHighlights()
-{
-  m_currentText = m_view->selectionText();
-
-  KTextEditor::SearchInterface* siface =
-    qobject_cast(m_view->document());
-
-  if (!siface) {
-    return;
-  }
-
-  KTextEditor::MovingInterface* miface =
-    qobject_cast(m_view->document());
-
-  KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute());
-  attr->setFontBold(true);
-  attr->setBackground(Qt::yellow);
-
-  KTextEditor::Cursor start(0, 0);
-  KTextEditor::Range searchRange;
-
-  QVector matches;
-
-  do {
-    searchRange.setRange(start, m_view->document()->documentEnd());
-
-    matches = siface->searchText(searchRange, m_currentText, KTextEditor::Search::WholeWords);
-
-    if (matches.first().isValid()) {
-      KTextEditor::MovingRange* mr = miface->newMovingRange(matches.first());
-      mr->setAttribute(attr);
-      mr->setView(m_view);
-      mr->setAttributeOnlyForViews(true);
-      m_ranges.append(mr);
-      start = matches.first().end();
-    }
-  } while (matches.first().isValid());
-}
-//END HighlightSelectionPluginView
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/part/plugins/hlselection/hlselectionplugin.h b/part/plugins/hlselection/hlselectionplugin.h
deleted file mode 100755
index c575655..0000000
--- a/part/plugins/hlselection/hlselectionplugin.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* This file is part of the KDE libraries
-   Copyright (C) 2010 Dominik Haumann 
-
-   This library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Library General Public
-   License version 2 as published by the Free Software Foundation.
-
-   This library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   Library General Public License for more details.
-
-   You should have received a copy of the GNU Library General Public License
-   along with this library; see the file COPYING.LIB.  If not, write to
-   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-   Boston, MA 02110-1301, USA.
- */
-
-#ifndef _HIGHLIGHT_SELECTION_PLUGIN_H_
-#define _HIGHLIGHT_SELECTION_PLUGIN_H_
-
-#include 
-#include 
-
-// #include 
-#include 
-#include 
-#include 
-#include 
-
-namespace KTextEditor {
-  class MovingRange;
-}
-
-class HighlightSelectionPlugin : public KTextEditor::Plugin
-{
-  Q_OBJECT
-
-  public:
-    explicit HighlightSelectionPlugin( QObject *parent = 0,
-                      const QVariantList &args = QVariantList() );
-    virtual ~HighlightSelectionPlugin();
-
-    void addView (KTextEditor::View *view);
-    void removeView (KTextEditor::View *view);
-
-
-  private:
-    QList m_views;
-};
-
-class HighlightSelectionPluginView
-  : public QObject
-//   , public KXMLGUIClient
-{
-  Q_OBJECT
-  public:
-    explicit HighlightSelectionPluginView(KTextEditor::View *view);
-    ~HighlightSelectionPluginView();
-
-    void createHighlights();
-    KTextEditor::View* view() const;
-
-  public Q_SLOTS:
-    void selectionChanged();
-    void clearHighlights();
-
-  private:
-    KTextEditor::View* m_view;
-    QString m_currentText;
-
-    QList m_ranges;
-};
-
-#endif // _HIGHLIGHT_SELECTION_PLUGIN_H_
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/part/plugins/hlselection/ktexteditor_hlselection.desktop b/part/plugins/hlselection/ktexteditor_hlselection.desktop
deleted file mode 100755
index 69414a2..0000000
--- a/part/plugins/hlselection/ktexteditor_hlselection.desktop
+++ /dev/null
@@ -1,18 +0,0 @@
-[Desktop Entry]
-X-KDE-Library=ktexteditor_hlselection
-X-KDE-PluginInfo-Author=
-X-KDE-PluginInfo-Email=
-X-KDE-PluginInfo-Name=ktexteditorhlselection
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-Website=http://kate.kde.org
-X-KDE-PluginInfo-Category=Editor
-X-KDE-PluginInfo-Depends=
-X-KDE-PluginInfo-License=GPL
-X-KDE-PluginInfo-EnabledByDefault=true
-X-KDE-ParentApp=kate
-X-KDE-Version=4.3
-X-KDE-ServiceTypes=KTextEditor/Plugin
-Type=Service
-Icon=document-import
-Name=Highlight Selection
-Comment=Highlight all words based on the text selection
diff --git a/part/plugins/hlselection/ktexteditor_hlselectionui.rc b/part/plugins/hlselection/ktexteditor_hlselectionui.rc
deleted file mode 100755
index ce41a04..0000000
--- a/part/plugins/hlselection/ktexteditor_hlselectionui.rc
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- &Tools
-    
-    
- 
-
-
diff --git a/part/plugins/insertfile/CMakeLists.txt b/part/plugins/insertfile/CMakeLists.txt
deleted file mode 100644
index ca00ff0..0000000
--- a/part/plugins/insertfile/CMakeLists.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-
-########### next target ###############
-
-set(ktexteditor_insertfile_PART_SRCS insertfileplugin.cpp )
-
-
-kde4_add_plugin(ktexteditor_insertfile ${ktexteditor_insertfile_PART_SRCS})
-
-target_link_libraries(ktexteditor_insertfile  ${KDE4_KIO_LIBS} ktexteditor kdeui kfile)
-
-install(TARGETS  ktexteditor_insertfile  DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-
-########### install files ###############
-
-install( FILES ktexteditor_insertfile.desktop  DESTINATION  ${SERVICES_INSTALL_DIR} )
-install( FILES ktexteditor_insertfileui.rc  DESTINATION  ${DATA_INSTALL_DIR}/ktexteditor_insertfile )
-
-
-
-
diff --git a/part/plugins/insertfile/insertfileplugin.cpp b/part/plugins/insertfile/insertfileplugin.cpp
deleted file mode 100644
index 7f04693..0000000
--- a/part/plugins/insertfile/insertfileplugin.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/* This file is part of the KDE libraries
-   Copyright (C) 2002 Anders Lund 
-
-   This library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Library General Public
-   License version 2 as published by the Free Software Foundation.
-
-   This library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   Library General Public License for more details.
-
-   You should have received a copy of the GNU Library General Public License
-   along with this library; see the file COPYING.LIB.  If not, write to
-   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-   Boston, MA 02110-1301, USA.
-*/
-
-#include "insertfileplugin.h"
-#include "insertfileplugin.moc"
-
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-
-K_PLUGIN_FACTORY( InsertFilePluginFactory, registerPlugin(); )
-K_EXPORT_PLUGIN( InsertFilePluginFactory( KAboutData( "ktexteditor_insertfile", "ktexteditor_plugins", ki18n("Insert File"), "0.1", ki18n("Insert File"), KAboutData::License_LGPL_V2 ) ) )
-
-//BEGIN InsertFilePlugin
-InsertFilePlugin::InsertFilePlugin( QObject *parent, const QVariantList& )
-	: KTextEditor::Plugin ( parent )
-{
-}
-
-InsertFilePlugin::~InsertFilePlugin()
-{
-}
-
-void InsertFilePlugin::addView(KTextEditor::View *view)
-{
-  InsertFilePluginView *nview = new InsertFilePluginView (view, "Insert File Plugin");
-  m_views.append (nview);
-}
-
-void InsertFilePlugin::removeView(KTextEditor::View *view)
-{
-    int z=0;
-    // Loop written for the unlikely case of a view being added more than once
-    while (z < m_views.count())
-    {
-      InsertFilePluginView *nview = m_views.at(z);
-      if (nview->parentClient() == view)
-      {
-         m_views.removeAll (nview);
-         delete nview;
-      }
-      else
-         ++z;
-    }
-}
-//END InsertFilePlugin
-
-//BEGIN InsertFilePluginView
-InsertFilePluginView::InsertFilePluginView( KTextEditor::View *view, const char *name )
-  : QObject( view ),
-    KXMLGUIClient( view )
-{
-  setObjectName( name );
-
-  setComponentData( InsertFilePluginFactory::componentData() );
-  _job = 0;
-
-  KAction *action = new KAction( i18n("Insert File..."), this );
-  actionCollection()->addAction( "tools_insert_file", action );
-  connect( action, SIGNAL( triggered( bool ) ), this, SLOT(slotInsertFile()) );
-
-  setXMLFile( "ktexteditor_insertfileui.rc" );
-}
-
-void InsertFilePluginView::slotInsertFile()
-{
-  KFileDialog dlg( KUrl( "kfiledialog:///insertfile?global" ), "", (QWidget*)parent());
-  dlg.setOperationMode( KFileDialog::Opening );
-
-  dlg.setCaption(i18n("Choose File to Insert"));
-  dlg.okButton()->setText(i18n("&Insert"));
-  dlg.setMode( KFile::File );
-  dlg.exec();
-
-  _file = dlg.selectedUrl().url();
-  if ( _file.isEmpty() ) return;
-
-  if ( _file.isLocalFile() ) {
-    _tmpfile = _file.toLocalFile();
-    insertFile();
-  }
-  else {
-    KTemporaryFile tempFile;
-    tempFile.setAutoRemove(false);
-    tempFile.open();
-    _tmpfile = tempFile.fileName();
-
-    KUrl destURL;
-    destURL.setPath( _tmpfile );
-    _job = KIO::file_copy( _file, destURL, 0600, KIO::Overwrite );
-    connect( _job, SIGNAL( result( KJob * ) ), this, SLOT( slotFinished ( KJob * ) ) );
-  }
-}
-
-void InsertFilePluginView::slotFinished( KJob *job )
-{
-  assert( job == _job );
-  _job = 0;
-  if ( job->error() )
-    KMessageBox::error( (QWidget*)parent(), i18n("Failed to load file:\n\n") + job->errorString(), i18n("Insert File Error") );
-  else
-    insertFile();
-}
-
-void InsertFilePluginView::insertFile()
-{
-  QString error;
-  if ( _tmpfile.isEmpty() )
-    return;
-
-  QFileInfo fi;
-  fi.setFile( _tmpfile );
-  if (!fi.exists() || !fi.isReadable())
-    error = i18n("

The file %1 does not exist or is not readable, aborting.

", _file.fileName()); - - QFile f( _tmpfile ); - if ( !f.open(QIODevice::ReadOnly) ) - error = i18n("

Unable to open file %1, aborting.

", _file.fileName()); - - if ( ! error.isEmpty() ) { - KMessageBox::sorry( (QWidget*)parent(), error, i18n("Insert File Error") ); - return; - } - - // now grab file contents - QTextStream stream(&f); - QString str, tmp; - uint numlines = 0; - uint len = 0; - while (!stream.atEnd()) { - if ( numlines ) - str += '\n'; - tmp = stream.readLine(); - str += tmp; - len = tmp.length(); - numlines++; - } - f.close(); - - if ( str.isEmpty() ) - error = i18n("

File %1 had no contents.

", _file.fileName()); - if ( ! error.isEmpty() ) { - KMessageBox::sorry( (QWidget*)parent(), error, i18n("Insert File Error") ); - return; - } - - // insert !! - KTextEditor::View *v = (KTextEditor::View*)parent(); - int line, col; - line = v->cursorPosition().line(); - col = v->cursorPosition().column(); - v->document()->insertText( v->cursorPosition(), str ); - - // move the cursor - v->setCursorPosition ( KTextEditor::Cursor (line + numlines - 1, numlines > 1 ? len : col + len) ); - - // clean up - _file = KUrl (); - _tmpfile.truncate( 0 ); -} - -//END InsertFilePluginView - diff --git a/part/plugins/insertfile/insertfileplugin.h b/part/plugins/insertfile/insertfileplugin.h deleted file mode 100644 index 1d9f450..0000000 --- a/part/plugins/insertfile/insertfileplugin.h +++ /dev/null @@ -1,67 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 Anders Lund - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _INSERT_FILE_PLUGIN_H_ -#define _INSERT_FILE_PLUGIN_H_ - -#include -#include - -#include -#include -#include -#include -#include - -class InsertFilePlugin : public KTextEditor::Plugin -{ - Q_OBJECT - - public: - explicit InsertFilePlugin( QObject *parent = 0, - const QVariantList &args = QVariantList() ); - virtual ~InsertFilePlugin(); - - void addView (KTextEditor::View *view); - void removeView (KTextEditor::View *view); - - - private: - QList m_views; -}; - -class InsertFilePluginView : public QObject, public KXMLGUIClient -{ - Q_OBJECT - public: - explicit InsertFilePluginView( KTextEditor::View *view, const char *name=0 ); - ~InsertFilePluginView() {} - public Q_SLOTS: - /* display a file dialog, and insert the chosen file */ - void slotInsertFile(); - private Q_SLOTS: - void slotFinished( KJob *job ); - //slotAborted( KIO::Job *job ); - private: - void insertFile(); - KUrl _file; - QString _tmpfile; - KIO::FileCopyJob *_job; -}; - -#endif // _INSERT_FILE_PLUGIN_H_ diff --git a/part/plugins/insertfile/ktexteditor_insertfile.desktop b/part/plugins/insertfile/ktexteditor_insertfile.desktop deleted file mode 100644 index ab8e515..0000000 --- a/part/plugins/insertfile/ktexteditor_insertfile.desktop +++ /dev/null @@ -1,191 +0,0 @@ -[Desktop Entry] -X-KDE-Library=ktexteditor_insertfile -X-KDE-PluginInfo-Author= -X-KDE-PluginInfo-Email= -X-KDE-PluginInfo-Name=ktexteditorinsertfile -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://kate.kde.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-ParentApp=kate -X-KDE-Version=4.0 -X-KDE-ServiceTypes=KTextEditor/Plugin -Type=Service -Icon=document-import -Name=Insert File -Name[ar]=أدرج ملÙاً -Name[as]=নথিপতà§à§° ভৰাওক -Name[ast]=Inxertar Ficheru -Name[be]=УÑтавіць файл -Name[be@latin]=UstaÅ­leÅ„nie fajÅ‚a -Name[bg]=Вмъкване на файл -Name[bn]=ফাইল ঢোকাও -Name[bn_IN]=ফাইল সনà§à¦¨à¦¿à¦¬à§‡à¦¶ করà§à¦¨ -Name[br]=Enlakkat ur restr -Name[ca]=Inserció de fitxer -Name[ca@valencia]=Inserció de fitxer -Name[cs]=Vložit soubor -Name[csb]=Wstôwi lopk -Name[da]=Indsæt fil -Name[de]=Datei einfügen -Name[el]=Εισαγωγή αÏχείου -Name[en_GB]=Insert File -Name[eo]=Enmeti dosieron -Name[es]=Insertar archivo -Name[et]=Faililisaja -Name[eu]=Txertatu fitxategia -Name[fa]=درج پرونده -Name[fi]=Lisää tiedosto -Name[fr]=Ajouter un fichier -Name[fy]=Triem ynfoegje -Name[ga]=Ionsáigh Comhad -Name[gl]=Inserir un ficheiro -Name[gu]=ફાઇલ ઉમેરો -Name[he]=הוספת קובץ -Name[hi]=फ़ाइल पà¥à¤°à¤µà¤¿à¤·à¥à¤Ÿ करें -Name[hne]=फाइल भरव -Name[hr]=Umetni datoteku -Name[hsb]=Dokument zasunyć -Name[hu]=Fájl beszúrása -Name[ia]=Il Inserta le File -Name[id]=Masukkan berkas -Name[is]=Skjóta inn skrá -Name[it]=Inserisci file -Name[ja]=ファイル挿入 -Name[kk]=Файлды ендіру -Name[km]=បញ្ចូល​ឯកសារ -Name[kn]=ಕಡತವನà³à²¨à³ ಒಳಸೇರಿಸೠ-Name[ko]=íŒŒì¼ ì‚½ìž… -Name[ku]=Pelî lê zêde bike -Name[lt]=Ä®terpti failÄ… -Name[lv]=Ievietot failu -Name[mai]=फाइलक जोड़ू -Name[mk]=Внетнување датотека -Name[ml]=ഫയലàµâ€ ചേരàµâ€à´•àµà´•àµà´• -Name[mr]=फाइल समाविषà¥à¤Ÿ करा -Name[ms]=Selit Fail -Name[nb]=Sett inn fil -Name[nds]=Datei infögen -Name[ne]=फाइल घà¥à¤¸à¤¾à¤‰à¤à¤¨à¥à¤¹à¥‹à¤¸à¥ -Name[nl]=Bestand invoegen -Name[nn]=Set inn fil -Name[oc]=Inserir un fichièr -Name[or]=Insert File -Name[pa]=ਫਾਇਲ ਸ਼ਾਮਲ -Name[pl]=Wstaw plik -Name[ps]=دوتنه ورننويستل -Name[pt]=Inserir um Ficheiro -Name[pt_BR]=Inserir arquivo -Name[ro]=Inserează fiÈ™ier -Name[ru]=Ð’Ñтавка файла -Name[se]=Bija fiilla sisa -Name[si]=ගොනුව එක් කරන්න -Name[sk]=VložiÅ¥ súbor -Name[sl]=Vstavi datoteko -Name[sr]=Уметање фајла -Name[sr@ijekavian]=Уметање фајла -Name[sr@ijekavianlatin]=Umetanje fajla -Name[sr@latin]=Umetanje fajla -Name[sv]=Infoga fil -Name[ta]=கோபà¯à®ªà®¿à®©à¯ˆ நà¯à®´à¯ˆà®•à¯à®•à®µà¯à®®à¯ -Name[te]=దసà±à°¤à±à°°à°‚ చేరà±à°šà± -Name[tg]=Вориди файл -Name[th]=à¹à¸—รà¸à¹à¸Ÿà¹‰à¸¡ -Name[tr]=İçeriye Dosya Aktar -Name[uk]=Ð’Ñтавити файл -Name[uz]=Faylni qoÊ»yish -Name[uz@cyrillic]=Файлни қўйиш -Name[vi]=Chèn tập tin -Name[wa]=Sititchî fitchî -Name[x-test]=xxInsert Filexx -Name[zh_CN]=æ’入文件 -Name[zh_TW]=æ’入檔案 -Comment=Insert any readable file at cursor position -Comment[af]=Voeg enige leesbare lêer in by die merker posisie -Comment[ar]=أدرج أي مل٠قابل للقراءة عند موضع المؤشر -Comment[as]=কাৰà§à¦›à§°à§° সà§à¦¥à¦¾à¦¨à¦¤ যিকোনো পà§à¦¿à¦¬ পৰা নথিপতà§à§° ভৰাওক -Comment[ast]=Inxertar un ficheru lleíble na posición del cursor -Comment[be]=УÑтаўлÑе файл у пазіцыю курÑора -Comment[be@latin]=UstaÅ­laje źmieÅ›civa fajÅ‚a, jaki možna praÄytać, u miescy kursora. -Comment[bg]=Вмъкване на файл от мÑÑтото на курÑора -Comment[bn]=কারà§à¦¸à¦¾à¦° অবসà§à¦¥à¦¾à¦¨à§‡ যে কোনো (পাঠযোগà§à¦¯) ফাইল অনà§à¦¤à¦°à§à¦­à§à¦•à§à¦¤ করতে পারে -Comment[bn_IN]=কারà§à¦¸à¦¾à¦°à§‡à¦° অবসà§à¦¥à¦¾à¦¨à§‡ পাঠযোগà§à¦¯ কোনো ফাইল সনà§à¦¨à¦¿à¦¬à§‡à¦¶ করা হবে -Comment[ca]=Inserir qualsevol fitxer llegible en la posició del cursor -Comment[ca@valencia]=Inserir qualsevol fitxer llegible en la posició del cursor -Comment[cs]=Vloží jakýkoliv Äitelný soubor na místo kurzoru -Comment[csb]=Wstôwiô zamkÅ‚osc lopka przë kursorze -Comment[da]=Indsæt en vilkÃ¥rlig læsbar fil ved markørens position -Comment[de]=Beliebige lesbare Datei an Cursor-Position einfügen -Comment[el]=Εισαγωγή οποιουδήποτε αναγνώσιμου αÏχείου στη θέση του δÏομέα -Comment[en_GB]=Insert any readable file at cursor position -Comment[eo]=Enmeti iun legeblan dosieron je ĉi tiu kursora pozicio -Comment[es]=Insertar cualquier archivo legible en la posición del cursor -Comment[et]=Suvalise loetava faili lisamine kursori asukohta -Comment[eu]=Kurtsorearen posizioan fitxategi irakurgarri bat txertatzen du -Comment[fa]=درج هر پروندۀ قابل خواندن در موقعیت مکان‌نما -Comment[fi]=Lisää mikä tahansa luettava tiedosto kohdistimen kohdalle -Comment[fr]=Insérer tout fichier lisible à la position du curseur -Comment[fy]=Els lêsber Triem by it rinnerke ynfoegje -Comment[ga]=Ionsáigh aon chomhad inléite ag an gcúrsóir -Comment[gl]=Insire calquera ficheiro lexíbel na posición do cursor -Comment[gu]=કરà«àª¸àª° સà«àª¥àª¿àª¤àª¿ પર કોઇપણ વાંચી શકાય તેવી ફાઇલ દાખલ કરો -Comment[he]=מוסיף כל קובץ הניתן לקרי××” ×‘×ž×™×§×•× ×”×¡×ž×Ÿ -Comment[hi]=संकेतक के सà¥à¤¥à¤¾à¤¨ पर कोई भी पढ़ने योगà¥à¤¯ फ़ाइल पà¥à¤°à¤µà¤¿à¤·à¥à¤Ÿ करें -Comment[hne]=संकेतक के जगह तिर कोनो पढ़े जा सके फाइल भरव -Comment[hr]=Na položaj pokazivaÄa umetnite bilo koju Äitljivu datoteku -Comment[hsb]=Zasunje lubowólnu Äitajomnu dataju na poziciji cursora -Comment[hu]=TetszÅ‘leges olvasható fájl beszúrása a kurzorpozíciónál -Comment[ia]=Il inserta omne le legibile file a le position del cursor -Comment[id]=Masukkan berkas dapat terbaca di posisi kursor -Comment[is]=Setur inn hvaða lesanlegu skrá sem er í stöðu bendilsins -Comment[it]=Inserisce un qualsiasi file leggibile alla posizione del cursore -Comment[ja]=カーソルä½ç½®ã«èª­ã¿è¾¼ã¿å¯èƒ½ãªãƒ•ã‚¡ã‚¤ãƒ«ã‚’挿入ã—ã¾ã™ -Comment[kk]=Меңзер көрÑететін орынға кез-келген оқылатын файлды ендіру -Comment[km]=បញ្ចូល​ឯកសារ​ដែល​អាច​អាន​បាន​ណាមួយ​នៅ​ទីážáž¶áŸ†áž„​ទស្សនáŸâ€‹áž‘្រនិច -Comment[kn]=ಸà³à²¥à²³à²¸à³‚ಚಕದ (ಕರà³à²¸à²°à³) ಸà³à²¥à²³à²¦à²²à³à²²à²¿ ಯಾವà³à²¦à³‡ ಓದಬಹà³à²¦à²¾à²¦ ಕಡತವನà³à²¨à³ ಒಳಸೇರಿಸೠ-Comment[ko]=커서 ìœ„ì¹˜ì— ì½ì„ 수 있는 파ì¼ì„ 삽입합니다 -Comment[ku]=Çi pelê paknivîs hebe bike di cihê bernîşane de -Comment[lb]=Setzt eng liesbar Datei bei der Cursorpositioun an -Comment[lt]=Ä®terpiÄ… bet kokį skaitomÄ… failÄ… ties žymekliu -Comment[lv]=Ievieto jebkuru lasÄmu failu kursora atraÅ¡anÄs vietÄ -Comment[mai]=संकेतक केर सà¥à¤¥à¤¾à¤¨ पर कोनो पढ़बा योगà¥à¤¯ फाइलकेठपà¥à¤°à¤µà¤¿à¤·à¥à¤Ÿ करू -Comment[mk]=ВнеÑува било која читлива датотека на позицијата на курÑорот -Comment[ml]=വായികàµà´•à´¾à´¨àµâ€ സാധികàµà´•àµà´¨àµà´¨ à´à´¤àµŠà´°àµ ഫയലàµà´‚ സൂചകം ഇരിയàµà´•àµà´•àµà´¨àµà´¨ à´¸àµà´¥à´²à´¤àµà´¤àµàµ ചേരàµâ€à´•àµà´•àµà´• -Comment[mr]=करà¥à¤¸à¤° सà¥à¤¥à¤¾à¤¨à¤¾à¤µà¤° वाचणà¥à¤¯à¤¾à¤œà¥‹à¤—ी फाइल अंतरà¥à¤­à¥‚त करा -Comment[ms]=Sisipkan sebarang fail boleh baca di posisi kursor -Comment[nb]=Sett inn en lesbar fil ved skrivemerket -Comment[nds]=Jichtenseen leesbore Datei bi'n Blinker infögen -Comment[ne]=करà¥à¤¸à¤° सà¥à¤¥à¤¿à¤¤à¤¿à¤®à¤¾ कà¥à¤¨à¥ˆ पनि पढà¥à¤¨à¤¯à¥‹à¤—à¥à¤¯ फाइल घà¥à¤¸à¤¾à¤‰à¤à¤¨à¥à¤¹à¥‹à¤¸à¥ -Comment[nl]=Voeg een willekeurig leesbaar bestand in op de cursorpositie -Comment[nn]=Set inn ei lesbar fil ved skrivemerket -Comment[or]=Insert any readable file at cursor position -Comment[pa]=ਕੋਈ ਪੜà©à¨¹à¨¨à¨¯à©‹à¨— ਫਾਇਲ ਕਰਸਰ ਸਥਿਤੀ ਤੇ ਸ਼ਾਮਿਲ ਕਰੋ -Comment[pl]=Wstawia zawartość pliku w pozycji kursora -Comment[pt]=Introduza qualquer ficheiro legível na posição do cursor -Comment[pt_BR]=Insere qualquer arquivo com permissões de leitura na posição do cursor -Comment[ro]=Inserează la poziÈ›ia cursorului orice fiÈ™ier citibil -Comment[ru]=Ð’Ñтавка любого читаемого файла в позицию курÑора -Comment[se]=Lasiha logahahtti fiilla Äállinmearkka sajádahkii -Comment[sk]=Vloží akýkoľvek Äitateľný súbor na pozíciu kurzora -Comment[sl]=Vstavi katerokoli berljivo datoteko na položaju kazalca -Comment[sr]=Умеће било који читљиви фајл на положају курÑора -Comment[sr@ijekavian]=Умеће било који читљиви фајл на положају курÑора -Comment[sr@ijekavianlatin]=Umeće bilo koji Äitljivi fajl na položaju kursora -Comment[sr@latin]=Umeće bilo koji Äitljivi fajl na položaju kursora -Comment[sv]=Infoga vilken läsbar fil som helst vid markörens plats -Comment[ta]=சà¯à®Ÿà¯à®Ÿà¯à®®à¯ இடதà¯à®¤à®¿à®²à¯ படிகà¯à®•à®•à¯à®•à¯‚டிய கோபà¯à®ªà®¿à®©à¯ˆ உளà¯à®³à®¿à®Ÿà¯ -Comment[te]=à°®à±à°²à±à°•à± à°µà±à°¨à±à°¨ చోట చదవగలిగే దసà±à°¤à±à°°à°¾à°¨à±à°¨à°¿ దూరà±à°šà±à°¨à± -Comment[tg]=Вориди ҳар Ñк файли хондашаванда дар макони курÑор -Comment[th]=ทำà¸à¸²à¸£à¹à¸—รà¸à¹à¸Ÿà¹‰à¸¡à¸—ี่สามารถอ่านได้ที่ตำà¹à¸«à¸™à¹ˆà¸‡à¸‚องเคอร์เซอร์ -Comment[tr]=Ä°mleç konumunda herhangi bir dosyanın içeriÄŸini ekle -Comment[uk]=Ð’ÑтавлÑÑ” вміÑÑ‚ будь-Ñкого файла, Ñкий можна прочитати, у позицію курÑора -Comment[uz]=Har qanday oÊ»qib boÊ»ladigan faylni kursorning joyidan qoÊ»yish -Comment[uz@cyrillic]=Ҳар қандай ўқиб бўладиган файлни курÑорнинг жойидан қўйиш -Comment[vi]=Chèn bất kỳ tập tin có khả năng Ä‘á»c tại vị trí của con chạy. -Comment[wa]=Sititchî tot l' minme li ké fitchî lijhÃ¥ve al pôzucion do cursoe -Comment[x-test]=xxInsert any readable file at cursor positionxx -Comment[zh_CN]=在光标ä½ç½®æ’入任何å¯è¯»æ–‡ä»¶ -Comment[zh_HK]=在游標處æ’入任æ„的檔案 -Comment[zh_TW]=在游標處æ’入任æ„çš„å¯è®€æª”案 diff --git a/part/plugins/insertfile/ktexteditor_insertfileui.rc b/part/plugins/insertfile/ktexteditor_insertfileui.rc deleted file mode 100644 index c3ad9b1..0000000 --- a/part/plugins/insertfile/ktexteditor_insertfileui.rc +++ /dev/null @@ -1,9 +0,0 @@ - - - - &Tools - - - - - diff --git a/part/plugins/kdatatool/CMakeLists.txt b/part/plugins/kdatatool/CMakeLists.txt deleted file mode 100644 index 7f2dc8e..0000000 --- a/part/plugins/kdatatool/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ - -########### next target ############### - -set(ktexteditor_kdatatool_PART_SRCS kate_kdatatool.cpp ) - - -kde4_add_plugin(ktexteditor_kdatatool ${ktexteditor_kdatatool_PART_SRCS}) - -target_link_libraries(ktexteditor_kdatatool ${KDE4_KDECORE_LIBS} ktexteditor kio kdeui ) - -install(TARGETS ktexteditor_kdatatool DESTINATION ${PLUGIN_INSTALL_DIR} ) - - -########### install files ############### - -install( FILES ktexteditor_kdatatoolui.rc DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_kdatatool ) -install( FILES ktexteditor_kdatatool.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) - - - - diff --git a/part/plugins/kdatatool/kate_kdatatool.cpp b/part/plugins/kdatatool/kate_kdatatool.cpp deleted file mode 100644 index a4566e3..0000000 --- a/part/plugins/kdatatool/kate_kdatatool.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 Joseph Wenninger and Daniel Naber - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN includes -#include "kate_kdatatool.h" -#include "kate_kdatatool.moc" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -//END includes - -K_PLUGIN_FACTORY( KDataToolPluginFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( KDataToolPluginFactory( KAboutData("ktexteditor_kdatatool", "ktexteditor_plugins", ki18n("DataTool"), "0.1", ki18n("Data tool"), KAboutData::License_LGPL_V2) ) ) - -namespace KTextEditor { - -KDataToolPlugin::KDataToolPlugin( QObject *parent, const QVariantList& ) - : KTextEditor::Plugin ( parent ) -{ -} - - -KDataToolPlugin::~KDataToolPlugin () -{ -} - -void KDataToolPlugin::addView(KTextEditor::View *view) -{ - KDataToolPluginView *nview = new KDataToolPluginView (view); - nview->setView (view); - m_views.append (nview); -} - -void KDataToolPlugin::removeView(KTextEditor::View *view) -{ - for (int z=0; z < m_views.count(); z++) - { - if (m_views.at(z)->parentClient() == view) - { - KDataToolPluginView *nview = m_views.at(z); - m_views.removeAll (nview); - delete nview; - } - } -} - - -KDataToolPluginView::KDataToolPluginView( KTextEditor::View *view ) - :QObject(view),KXMLGUIClient(view),m_menu(0),m_notAvailable(0) -{ - setComponentData( KDataToolPluginFactory::componentData() ); - setXMLFile("ktexteditor_kdatatoolui.rc"); - - m_menu = new KActionMenu(i18n("Data Tools"), this); - actionCollection()->addAction("popup_dataTool", m_menu); - connect(m_menu->menu(), SIGNAL(aboutToShow()), this, SLOT(aboutToShow())); - - m_view = view; -} - -KDataToolPluginView::~KDataToolPluginView() -{ - m_view->removeChildClient (this); - delete m_menu; -} - -void KDataToolPluginView::aboutToShow() -{ - kDebug( 13040 )<<"KTextEditor::KDataToolPluginView::aboutToShow"; - QString word; - m_singleWord = false; - m_wordUnderCursor.clear(); - - // unplug old actions, if any: - foreach (QAction *ac, m_actionList) { - m_menu->removeAction(ac); - } - if (m_notAvailable) { - m_menu->removeAction(m_notAvailable); - delete m_notAvailable; - m_notAvailable=0; - } - if ( m_view->selection() ) - { - word = m_view->selectionText(); - if ( word.indexOf(' ') == -1 && word.indexOf('\t') == -1 && word.indexOf('\n') == -1 ) - m_singleWord = true; - else - m_singleWord = false; - } else { - // No selection -> use word under cursor - KTextEditor::View *v = (KTextEditor::View*)m_view; - int line, col; - line = v->cursorPosition().line(); - col = v->cursorPosition().column(); - QString tmp_line = v->document()->line(line); - m_wordUnderCursor = ""; - // find begin of word: - m_singleWord_start = 0; - for(int i = qMin(col,tmp_line.length()-1); i >= 0; i--) { - QChar ch = tmp_line.at(i); - if( ! (ch.isLetter() || ch == '-' || ch == '\'') ) - { - m_singleWord_start = i+1; - break; - } - m_wordUnderCursor = ch + m_wordUnderCursor; - } - // find end of word: - m_singleWord_end = tmp_line.length(); - for(int i = col+1; i < tmp_line.length(); i++) { - QChar ch = tmp_line.at(i); - if( ! (ch.isLetter() || ch == '-' || ch == '\'') ) - { - m_singleWord_end = i; - break; - } - m_wordUnderCursor += ch; - } - if( ! m_wordUnderCursor.isEmpty() ) - { - m_singleWord = true; - m_singleWord_line = line; - } else { - m_notAvailable = new KAction(i18n("(not available)"), this ); - actionCollection()->addAction("dt_n_av", m_notAvailable); - connect( m_notAvailable, SIGNAL( triggered( bool ) ), this, SLOT(slotNotAvailable()) ); - m_menu->addAction(m_notAvailable); - return; - } - } - - KComponentData inst=componentData(); - - QList tools; - tools += KDataToolInfo::query( "QString", "text/plain", inst ); - if( m_singleWord ) - tools += KDataToolInfo::query( "QString", "application/x-singleword", inst ); - - m_actionList = KDataToolAction::dataToolActionList( tools, this, - SLOT( slotToolActivated( const KDataToolInfo &, const QString & ) ), - actionCollection()); - - foreach (QAction* ac, m_actionList) - m_menu->addAction(ac); - - if( m_actionList.isEmpty() ) { - m_notAvailable = new KAction(i18n("(not available)"), this); - actionCollection()->addAction("dt_n_av", m_notAvailable); - connect( m_notAvailable, SIGNAL( triggered( bool ) ), this, SLOT(slotNotAvailable()) ); - m_menu->addAction(m_notAvailable); - } -} - -void KDataToolPluginView::slotNotAvailable() -{ - KMessageBox::sorry(0, i18n("Data tools are only available when text is selected, " - "or when the right mouse button is clicked over a word. If no data tools are offered " - "even when text is selected, you need to install them. Some data tools are part " - "of the KOffice package.")); -} - -void KDataToolPluginView::slotToolActivated( const KDataToolInfo &info, const QString &command ) -{ - - KDataTool* tool = info.createTool( ); - if ( !tool ) - { - kWarning() << "Could not create Tool !"; - return; - } - - QString text; - if ( m_view->selection() ) - text = m_view->selectionText(); - else - text = m_wordUnderCursor; - - QString mimetype = "text/plain"; - QString datatype = "QString"; - - // If unsupported (and if we have a single word indeed), try application/x-singleword - if ( !info.mimeTypes().contains( mimetype ) && m_singleWord ) - mimetype = "application/x-singleword"; - - kDebug( 13040 ) << "Running tool with datatype=" << datatype << " mimetype=" << mimetype; - - QString origText = text; - - if ( tool->run( command, &text, datatype, mimetype) ) - { - kDebug( 13040 ) << "Tool ran. Text is now " << text; - if ( origText != text ) - { - int line, col; - line = m_view->cursorPosition().line(); - col = m_view->cursorPosition().column(); - if ( !m_view->selection() ) - { - m_view->setSelection(KTextEditor::Range(m_singleWord_line, m_singleWord_start, m_singleWord_line, m_singleWord_end)); - } - - // replace selection with 'text' - m_view->removeSelectionText(); - m_view->document()->insertText(m_view->cursorPosition(), text); - // fixme: place cursor at the end: - /* No idea yet (Joseph Wenninger) - for ( uint i = 0; i < text.length(); i++ ) { - viewCursorInterface(m_view)->cursorRight(); - } */ - } - } - - delete tool; -} - - -} diff --git a/part/plugins/kdatatool/kate_kdatatool.h b/part/plugins/kdatatool/kate_kdatatool.h deleted file mode 100644 index 5dbba85..0000000 --- a/part/plugins/kdatatool/kate_kdatatool.h +++ /dev/null @@ -1,74 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 Joseph Wenninger and Daniel Naber - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_KDATATOOL_ -#define _KATE_KDATATOOL_ - -#include -#include -#include -#include - -class KActionMenu; -class KDataToolInfo; - -namespace KTextEditor -{ - -class View; - -class KDataToolPlugin : public KTextEditor::Plugin -{ - Q_OBJECT - -public: - explicit KDataToolPlugin( QObject *parent = 0, const QVariantList &args = QVariantList() ); - virtual ~KDataToolPlugin(); - void addView (KTextEditor::View *view); - void removeView (KTextEditor::View *view); - - private: - QList m_views; -}; - - -class KDataToolPluginView : public QObject, public KXMLGUIClient -{ - Q_OBJECT - -public: - KDataToolPluginView( KTextEditor::View *view ); - virtual ~KDataToolPluginView(); - void setView( KTextEditor::View* ){;} -private: - View *m_view; - bool m_singleWord; - int m_singleWord_line, m_singleWord_start, m_singleWord_end; - QString m_wordUnderCursor; - QList m_actionList; - QPointer m_menu; - QAction *m_notAvailable; -protected Q_SLOTS: - void aboutToShow(); - void slotToolActivated( const KDataToolInfo &datatoolinfo, const QString &string ); - void slotNotAvailable(); -}; - -} - -#endif diff --git a/part/plugins/kdatatool/ktexteditor_kdatatool.desktop b/part/plugins/kdatatool/ktexteditor_kdatatool.desktop deleted file mode 100644 index ad0aca1..0000000 --- a/part/plugins/kdatatool/ktexteditor_kdatatool.desktop +++ /dev/null @@ -1,183 +0,0 @@ -[Desktop Entry] -X-KDE-Library=ktexteditor_kdatatool -X-KDE-PluginInfo-Author= -X-KDE-PluginInfo-Email= -X-KDE-PluginInfo-Name=ktexteditorkdatatool -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://kate.kde.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-ParentApp=kate -X-KDE-Version=4.0 -X-KDE-ServiceTypes=KTextEditor/Plugin -Type=Service -Icon=tools-check-spelling -Name=Data Tools -Name[ar]=أدوات البيانات -Name[as]=তথà§à¦¯à§° সৰঞà§à¦œà¦¾à¦® -Name[ast]=Ferramientes de datos -Name[be@latin]=Infarmacyjnaje pryÅ‚adździe -Name[bg]=ТекÑтообработващи интрументи -Name[bn]=তথà§à¦¯ টà§à¦² -Name[bn_IN]=তথà§à¦¯ সংকà§à¦°à¦¾à¦¨à§à¦¤ সামগà§à¦°à§€ -Name[ca]=Eines de dades -Name[ca@valencia]=Eines de dades -Name[cs]=Datové nástroje -Name[csb]=Nôrzãdze pòdôwków -Name[da]=Dataværktøjer -Name[de]=Datenwerkzeuge -Name[el]=ΕÏγαλεία δεδομένων -Name[en_GB]=Data Tools -Name[eo]=Datumiloj -Name[es]=Herramientas de datos -Name[et]=Andmete tööriistad -Name[eu]=Datu tresnak -Name[fi]=Datatyökalut -Name[fr]=Outils de données -Name[fy]=Gegevensark -Name[ga]=Uirlisí Sonraí -Name[gl]=Ferramentas de datos -Name[gu]=માહિતી સાધનો -Name[he]=כלי × ×ª×•× ×™× -Name[hi]=डेटा औजार -Name[hne]=डाटा औजार -Name[hr]=Podatkovni alati -Name[hsb]=Datowe nastroje -Name[hu]=AdatkezelÅ‘ programok -Name[ia]=Instrumentos de datos -Name[id]=Alat Data -Name[is]=Gagnatól -Name[it]=Strumenti per i dati -Name[ja]=データツール -Name[kk]=Дерек құралдары -Name[km]=ឧបករណáŸâ€‹áž‘ិន្ននáŸáž™ -Name[kn]=ದತà³à²¤ ಸಲಕರಣೆಗಳೠ-Name[ko]=ë°ì´í„° ë„구 -Name[ku]=Amûrên Dane yan -Name[lt]=Duomenų įrankiai -Name[lv]=Datu rÄ«ki -Name[mai]=डेटा अओजार -Name[ml]=ഡാറàµà´±à´¯àµ‹à´ŸàµŠà´ªàµà´ªà´®àµà´ªà´¯àµ‹à´—à´¿à´¯àµà´•àµà´•à´¾à´µàµà´¨àµà´¨ ഉപകരണങàµà´™à´³àµâ€ -Name[mr]=माहिती साधन -Name[ms]=Alatan Data -Name[nb]=Dataverktøy -Name[nds]=Datenwarktüüch -Name[nl]=Datagereedschappen -Name[nn]=Dataverktøy -Name[or]=Data Tools -Name[pa]=ਡਾਟਾ ਟੂਲ -Name[pl]=NarzÄ™dzia danych -Name[ps]=اومتوک توکي -Name[pt]=Ferramentas de Dados -Name[pt_BR]=Ferramentas de dados -Name[ro]=Utilitare de date -Name[ru]=Обработка данных -Name[se]=Dáhtareaiddut -Name[si]=දත්ත මෙවලම් -Name[sk]=Dátové nástroje -Name[sl]=Podatkovna orodja -Name[sr]=Ðлатке за податке -Name[sr@ijekavian]=Ðлатке за податке -Name[sr@ijekavianlatin]=Alatke za podatke -Name[sr@latin]=Alatke za podatke -Name[sv]=Dataverktyg -Name[ta]=தரவà¯à®•à¯ கரà¯à®µà®¿à®•à®³à¯ -Name[te]=దతà±à°¤à°¾à°‚శపౠపనిమà±à°Ÿà±à°²à± -Name[tg]=ÐÑбобҳои маълумотӣ -Name[th]=เครื่องมือข้อมูล -Name[tr]=Veri Araçları -Name[uk]=ЗаÑоби Ð´Ð»Ñ Ð´Ð°Ð½Ð¸Ñ… -Name[x-test]=xxData Toolsxx -Name[zh_CN]=æ•°æ®å·¥å…· -Name[zh_TW]=資料工具 -Comment=Enable data tools like thesaurus and spell check (if installed) -Comment[af]=Aktiveer data nutsprogramme soos thesaurus en spel bevestig (as geïnstalleer) -Comment[ar]=Ùعّل أدوات البيانات مثل المترادÙات والتدقيق الإملائي (إذا كانت مثبتة) -Comment[as]=থিচ'ৰাছ আৰৠবানান পৰীকà§à¦·à¦¾ (যদি সংসà§à¦¥à¦¾à¦ªà¦¨ কৰা হৈছে)ৰ নিচিনা তথà§à¦¯à§° সৰঞà§à¦œà¦¾à¦® সকà§à§°à¦¿à§Ÿ কৰক -Comment[ast]=Activar ferramientes de datos como'l diccionariu de sinónimos y l'iguador ortográficu (si tan instalaos) -Comment[be]=ІнÑтрументы працы з даннÑмі: Ñ‚ÑзаўруÑ, Ñпраўджванне правапіÑу Ñ– інш. (калі Ñны ÑžÑтаноўленыÑ) -Comment[be@latin]=UkluÄaje infarmacyjnaje pryÅ‚adździe, naprykÅ‚ad, tezaÅ­rus i spraÅ­džvaÅ„nie pravapisu (kali jany zainstalavanyja) -Comment[bg]=Поддръжка на текÑтообработващи инÑтрументи, като проверка на правопиÑа и Ñинонимен речник -Comment[bn]=থিসরার বা বানান পরীকà§à¦·à¦• ইতà§à¦¯à¦¾à¦¦à¦¿ সকà§à¦°à¦¿à§Ÿ করে (যদি পাওয়া যায়) -Comment[bn_IN]=তথà§à¦¯ সংকà§à¦°à¦¾à¦¨à§à¦¤ সামগà§à¦°à§€ যেমন শবà§à¦¦à¦•à§‹à¦· ও বানান পরীকà§à¦·à¦£ বà§à¦¯à¦¬à¦¸à§à¦¥à¦¾ (ইনসà§à¦Ÿà¦² করা থাকলে) সকà§à¦°à¦¿à§Ÿ করà§à¦¨ -Comment[ca]=Habilita les eines per a la gestió de dades, com ara el tesaurus i el corrector ortogràfic (si estan instal·lats) -Comment[ca@valencia]=Habilita les eines per a la gestió de dades, com ara el tesaurus i el corrector ortogràfic (si estan instal·lats) -Comment[cs]=Povolí datové nástroje jako tezaurus nebo kontrolu pravopisu, pokud jsou nainstalovány -Comment[csb]=Ã’bsÅ‚użënk nôrzãdzów ôrtu tezaurus ë sprôwdzanié pisënkù -Comment[cy]=Alluogi offer data fel theawrws a cywirydd sillafu (os maent wedi'u gosod) -Comment[da]=Aktivér dataværktøjer som begrebsordbog og stavekontrol (hvis installeret) -Comment[de]=Aktivierung von Dienstprogrammen wie Thesaurus und Rechtschreibprüfung (falls installiert) -Comment[el]=ΕνεÏγοποίηση εÏγαλείων δεδομένων όπως ο θησαυÏός λέξεων και ο οÏθογÏαφικός έλεγχος (αν είναι εγκατεστημένα) -Comment[en_GB]=Enable data tools like thesaurus and spell check (if installed) -Comment[eo]=EnÅalti datumilojn kiel "thesaurus" kaj literumilo (se instalita) -Comment[es]=Habilita las herramientas de datos como el diccionario de sinónimos y la verificación ortográfica (si están instalados) -Comment[et]=Andmete tööriistad, näiteks thesaurus ja õigekirja kontroll -Comment[eu]=Gaitu thesaurus-a eta ortografia zuzentzailea bezalako tresnak (instalatua badaude) -Comment[fa]=Ùعال‌سازی ابزارهای داده مانند واژه‌نامه Ùˆ غلط‌گیر (در صورت نصب) -Comment[fi]=Käytä tekstinkäsittelytyökaluja, kuten tekstin oikolukua ja sanakirjaa (jos asennettuna) -Comment[fr]=Activer les outils de données comme le thésaurus et la correction orthographique (s'ils sont installés) -Comment[fy]=Aktivearjen fan dataprogramma's, lykas de tesaurus en stavering (wannear't dy ynstallearre binne) -Comment[ga]=Cumasaigh uirlisí mar litreoir agus foclóir (má tá siad ar fáil) -Comment[gl]=Activa as ferramentas de datos como sinónimos e corrección ortográfica (se están instalados) -Comment[gu]=થીસોરસ અને જોડણી ચકાસણી જેવા માહિતી સાધનો દાખલ કરો (જો સà«àª¥àª¾àªªàª¿àª¤ હોય) -Comment[he]=מ×פשר שימוש בכלי × ×ª×•× ×™× ×›×’×•×Ÿ ×גרון ×ž×™×œ×™× ×•×‘×•×“×§ ×יות (×× ×ž×•×ª×§× ×™× ×›×œ×™× ×›×לה) -Comment[hi]=डाटा औजार जैसे कि थिसॉरस और वरà¥à¤¤à¤¨à¥€ जांचक (यदि संसà¥à¤¥à¤¾à¤ªà¤¿à¤¤ हैं) को सकà¥à¤·à¤® करें -Comment[hne]=डाटा औजार जइसन कि थिसारस अउ हिजà¥à¤œà¤¾ जांचक (यदि इनसà¥à¤Ÿà¤¾à¤² हे) ल सकà¥à¤›à¤® करव -Comment[hr]=Omogućavanje alata poput rjeÄnika sinonima i antonima, te provjere pravopisa (ako su instalirani) -Comment[hsb]=Staja graty kaž tezawrus abo prawopisnu kontrolu k dispoziciji (jeli instalowane) -Comment[hu]=AdatkezelÅ‘ eszközök (pl. szinonimaszótár, helyesírás-ellenÅ‘rzÅ‘) támogatása -Comment[ia]=Il habilita instrumentos de datos como le thesauro e le controlo orthographic (si illos es installate) -Comment[id]=Aktifkan alat data seperti tesaurus dan pemeriksa ejaan (jika terinstal) -Comment[is]=Virkir gagnatól eins og stafsetningaforrit og leiðréttingar (ef uppsett) -Comment[it]=Abilita gli strumenti per i dati come il dizionario dei sinonimi e il controllo ortografico (se installati) -Comment[ja]=åŒç¾©èªžãƒ„ールやスペルãƒã‚§ãƒƒã‚¯ãªã©ã®ãƒ‡ãƒ¼ã‚¿ãƒ„ールを有効ã«ã—ã¾ã™ (インストールã•ã‚Œã¦ã„ã‚‹å ´åˆ) -Comment[kk]=Ð¢ÐµÑƒÐ·Ð°ÑƒÑ€ÑƒÑ Ð¿ÐµÐ½ емле текÑеру Ñекілді (егер орнатылған болÑа) деректерді өңдеу құралдарды пайдалануға мүмкіншілік береді -Comment[km]=បើក​ឧបករណáŸâ€‹áž‘ិន្ននáŸáž™â€‹ ដូច​ជា​កម្រង​វáŸážœáž…នសព្ទ និង​ពិនិážáŸ’យ​អក្ážážšáž¶ážœáž·ážšáž»áž‘្ធ (ប្រសិន​បើ​បាន​ដំឡើង) -Comment[kn]=ಸಮಾನಾರà³à²¥à²•-ವಿರà³à²¦à³à²§à²¾à²°à³à²¥à²• ಪದಕೋಶ ಹಾಗೂ ಕಾಗà³à²£à²¿à²¤ ಪರೀಕà³à²·à²£à³†à²¯à²‚ತಹ ದತà³à²¤ ಸಂಬಂಧೀ ಸಲಕರಣೆಗಳನà³à²¨à³ (ಅನà³à²¸à³à²¥à²¾à²ªà²¨à³†à²—ೊಂಡಿದà³à²¦à²²à³à²²à²¿), ಶಕà³à²¤à²—ೊಳಿಸೠ-Comment[ko]=설치ë˜ì–´ 있다면 ë™ì˜ì–´ 사전과 맞춤법 검사기 ê°™ì€ ë°ì´í„° ë„구를 사용합니다 -Comment[ku]=Amûrên dane wekî ferheng û kontrola rastnivîsê (heke saz kirî be) çalak bike -Comment[lb]=Hëllefsprogrammer, wéi Thésaurus an Rechtschreifkontroll, uschalten (wann installéiert) -Comment[lt]=Ä®jungia duomenų įrankius, tokius kaip sinonimų žodynas ir raÅ¡ybos tikrinimas (jei įdiegta) -Comment[lv]=IeslÄ“dz instalÄ“tos datu rÄ«kus, tÄdus kÄ tÄ“zaurs un pareizrakstÄ«bas pÄrbaudÄ«tÄjs -Comment[mai]=डाटा अओजार जहिना जे थेसारस आओर वरà¥à¤¤à¤¨à¥€ जांचक (जठसंसà¥à¤¥à¤¾à¤ªà¤¿à¤¤ अछि) केठसकà¥à¤·à¤® करू -Comment[mk]=Овозможување на алатки како енциклопедија или проверка на Ð¿Ñ€Ð°Ð²Ð¾Ð¿Ð¸Ñ (ако Ñе инÑталирани) -Comment[ml]=à´…à´•àµà´·à´° വിനàµà´¯à´¾à´¸ പരിശോധന, നാനാരàµâ€à´¤àµà´¥à´™àµà´™à´³àµâ€ à´®àµà´¤à´²à´¾à´¯ ഡാറàµà´±à´¯àµ‹à´ŸàµŠà´ªàµà´ªà´®àµà´ªà´¯àµ‹à´—à´¿à´¯àµà´•àµà´•à´¾à´µàµà´¨àµà´¨ ഉപകരണങàµà´™à´³àµâ€ നിലവിലàµà´£àµà´Ÿàµ†à´™àµà´•à´¿à´²àµâ€ ഉപയോഗിയàµà´•àµà´•àµà´• -Comment[mr]=शबà¥à¤¦à¤•à¥‹à¤· व शबà¥à¤¦à¤²à¥‡à¤–न तपासणी नà¥à¤°à¥‚प साधन (पà¥à¤°à¤¤à¤¿à¤·à¥à¤ à¤¾à¤ªà¥€à¤¤ असलà¥à¤¯à¤¾à¤¸) कारà¥à¤¯à¤¾à¤¨à¥à¤µà¥€à¤¤ करा -Comment[ms]=Membolehkan alatan data seperti tesaurus dan periksa ejaan(jika dipasang) -Comment[nb]=Skru pÃ¥ dataverktøy som ordbok og stavekontroll (hvis det er installert) -Comment[nds]=Warktüüch as Thesaurus oder Klookschriever anmaken (wenn installeert) -Comment[ne]=यदि सà¥à¤¥à¤¾à¤ªà¤¿à¤¤ भà¤à¤®à¤¾, परà¥à¤¯à¤¾à¤¯à¤•à¥‹à¤¶ र हिजà¥à¤œà¥‡ परीकà¥à¤·à¤£ जसà¥à¤¤à¥ˆ डेटा उपकरण सकà¥à¤·à¤® पारà¥à¤¨à¥à¤¹à¥‹à¤¸à¥ -Comment[nl]=Activering van hulpprogramma's, zoals de thesaurus en spellingcontrole (indien geïnstalleerd) -Comment[nn]=Tilgang til dataverktøy som stavekontroll og synonymordlister -Comment[or]=Enable data tools like thesaurus and spell check (if installed) -Comment[pa]=ਡਾਟਾ ਟੂਲ ਜਿਵੇਂ ਕਿ ਥੀਸਾਰਾਉਸ ਤੇ ਸ਼ਬਦ-ਜੋੜ ਆਦਿ ਯੋਗ (ਜੇਕਰ ਇੰਸਟਾਲ ਹੋਵੇ) -Comment[pl]=ObsÅ‚uga narzÄ™dzi typu tezaurus i sprawdzanie pisowni -Comment[pt]=Activa as ferramentas de dados como os sinónimos e a verificação ortográfica (se estiverem instalados) -Comment[pt_BR]=Habilita ferramentas de dados, como dicionário de sinônimos e verificador ortográfico (se instalados) -Comment[ro]=Activează utilitare de date precum dicÈ›ionarul È™i verificarea ortografică (dacă sînt instalate) -Comment[ru]=Обработка данных, например, показ Ñинонимов и проверка орфографии (еÑли они уÑтановлены) -Comment[se]=Geavat diehtoreaidduid nugo synonymasátnelisttu ja Äállindárkkisteami (jos leat sajáiduhttojuvvon) -Comment[sk]=Povolí dátové nástroje, ako je slovník synoným a kontrolu pravopisu (ak sú nainÅ¡talované) -Comment[sl]=OmogoÄi orodja za podatke, kot so slovar sopomenk in preverjanje Ärkovanja (Äe so nameÅ¡Äena) -Comment[sr]=Ðлатке попут Ñинонимара и правопиÑара (ако Ñу инÑталирани) -Comment[sr@ijekavian]=Ðлатке попут Ñинонимара и правопиÑара (ако Ñу инÑталирани) -Comment[sr@ijekavianlatin]=Alatke poput sinonimara i pravopisara (ako su instalirani) -Comment[sr@latin]=Alatke poput sinonimara i pravopisara (ako su instalirani) -Comment[sv]=Aktivera dataverktyg som synonymordlista och stavningskontroll (om installerade) -Comment[ta]=அகராதி, எழà¯à®¤à¯à®¤à¯à®ªà¯à®ªà®¿à®´à¯ˆ திரà¯à®¤à¯à®¤à®¿ போனà¯à®± தகவல௠கரà¯à®µà®¿à®•à®³à¯ˆ இயகà¯à®•à¯à®®à¯ (நிறà¯à®µà®ªà¯à®ªà®Ÿà¯à®Ÿà®¿à®°à¯à®¨à¯à®¤à®¾à®²à¯) -Comment[te]=పదకోశం మరయూ à°…à°•à±à°·à°° తపà±à°ªà±à°²à°¨à± పటà±à°Ÿà±à°•à±Šà°¨à± పనిమà±à°Ÿà±à°²à°¨à± ఉపయోగించౠ(ఇంసà±à°Ÿà°¾à°²à± చేసిన పనిచేయà±à°¨à±) -Comment[tg]=ФаъолÑозии аÑбобҳои маълумотӣ монанди thesaurus ва spell check (агар Ñабт карда шуда бошанд) -Comment[th]=เปิดใช้งานเครื่องมือจัดà¸à¸²à¸£à¸‚้อมูลอย่างเช่น พจนานุà¸à¸£à¸¡à¸„ำพ้อง หรือตรวจคำสะà¸à¸” (ถ้าได้ติดตั้งไว้) -Comment[tr]=Thesaurus ve imla denetimi gibi araçları etkinleÅŸtir -Comment[uk]=Ðадає доÑтуп до заÑобів на кшталт Ñловників та перевірки правопиÑу (Ñкщо вÑтановлені) -Comment[uz]=LugÊ»at va imloni tekshirish vositalarni yoqish (agar oÊ»rnatilgan boÊ»lsa) -Comment[uz@cyrillic]=Луғат ва имлони текшириш воÑиталарни ёқиш (агар ўрнатилган бўлÑа) -Comment[vi]=Hiệu lá»±c công cụ dữ liệu nhÆ° từ Ä‘iển đồng nghÄ©a và bá»™ bắt lá»—i chính tả (nếu được cài đặt). -Comment[wa]=Mete en alaedje les usteyes po manaedjî les dnêyes, come les diccionaires ou les coridjreces (si astalés) -Comment[xh]=Yenza izixhobo ze data ezinjenge thesaurus nomkhangeli wopelo (ukuba ifakelwe) -Comment[x-test]=xxEnable data tools like thesaurus and spell check (if installed)xx -Comment[zh_CN]=å¯ç”¨åƒè¾žå…¸å’Œæ‹¼å†™æ£€æŸ¥è¿™æ ·çš„æ•°æ®å·¥å…·(如果安装了的è¯) -Comment[zh_HK]=如果有安è£çš„話,啟用åƒåŒç¾©å­—字典和拼字檢查等的文字工具 -Comment[zh_TW]=打開資料工具如åŒç¾©å­—典與拼字檢查 (如果有安è£çš„話) diff --git a/part/plugins/kdatatool/ktexteditor_kdatatoolui.rc b/part/plugins/kdatatool/ktexteditor_kdatatoolui.rc deleted file mode 100644 index 08e0fb4..0000000 --- a/part/plugins/kdatatool/ktexteditor_kdatatoolui.rc +++ /dev/null @@ -1,15 +0,0 @@ - - - - - &Tools - - - - - - - - - - diff --git a/part/plugins/kte_iconinserter/CMakeLists.txt b/part/plugins/kte_iconinserter/CMakeLists.txt deleted file mode 100644 index b079a8e..0000000 --- a/part/plugins/kte_iconinserter/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ - -set(ktexteditor_iconinserter_SRCS - iconinserterplugin.cpp -) - -kde4_add_plugin(ktexteditor_iconinserter ${ktexteditor_iconinserter_SRCS}) - -target_link_libraries(ktexteditor_iconinserter - ${KDE4_KDEUI_LIBS} - ${KDE4_KTEXTEDITOR_LIBS} -) - -install(TARGETS ktexteditor_iconinserter DESTINATION ${PLUGIN_INSTALL_DIR}) - -install(FILES ktexteditor_iconinserter.desktop DESTINATION ${SERVICES_INSTALL_DIR}) -install( FILES ktexteditor_iconinserterui.rc DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_iconinserter ) diff --git a/part/plugins/kte_iconinserter/iconinserterplugin.cpp b/part/plugins/kte_iconinserter/iconinserterplugin.cpp deleted file mode 100644 index fb072f4..0000000 --- a/part/plugins/kte_iconinserter/iconinserterplugin.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** - * This file is part of the KTextEditor-Icon-Inserter-Plugin * - * Copyright 2009-2010 Jonathan Schmidt-Dominé * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU Library General Public License version * - * 3, or (at your option) any later version, as published by the Free * - * Software Foundation. * - * * - * This library is distributed in the hope that it will be useful, but * - * WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public * - * License along with the kdelibs library; see the file COPYING.LIB. If * - * not, write to the Free Software Foundation, Inc., 51 Franklin Street, * - * Fifth Floor, Boston, MA 02110-1301, USA. or see * - * . * - ****************************************************************************/ - -#include "iconinserterplugin.h" - -#include - -#include -#include -#include -#include -#include -#include - - - -K_PLUGIN_FACTORY_DEFINITION(IconInserterPluginFactory, - registerPlugin("ktexteditor_iconinserter"); - ) -K_EXPORT_PLUGIN(IconInserterPluginFactory(KAboutData ("ktexteditor_iconinserter","ktexteditor_iconinserter", ki18n ("Select an Icon to use it inside the Code"), "0.1", ki18n ("Insert Code for KIcon-Creation"), KAboutData::License_LGPL_V3))) - - -IconInserterPluginView::IconInserterPluginView(IconInserterPlugin *plugin, KTextEditor::View *view): QObject(plugin),KXMLGUIClient(view),m_view(view) -{ - setComponentData( IconInserterPluginFactory::componentData() ); - setXMLFile("ktexteditor_iconinserterui.rc"); - QAction *a=actionCollection()->addAction("iconinserter_inserticon",this,SLOT(insertIcon())); - a->setIcon(KIcon("kcoloredit")); - a->setText(i18n ("Insert KIcon-Code")); - a->setToolTip (i18n ("Insert Code for KIcon-Creation")); - a->setWhatsThis (i18n ("IconInserter

Select an icon and use it as a KIcon in your source code.")); -} - -IconInserterPluginView::~IconInserterPluginView() -{ -} - - -void IconInserterPluginView::insertIcon() -{ - if (m_view.isNull()) return; - QString iconName = KIconDialog::getIcon ( KIconLoader::Desktop, - KIconLoader::Application, - false, - 0, - false, - 0, - i18n( "Select the Icon you want to use in your code as KIcon." ) - ); - if(iconName == "") - return; - - View *view=m_view.data(); - Document *doc=view->document(); - - - QString suffix = doc->url().url(); - suffix = suffix.right(suffix.size() - suffix.lastIndexOf('.') - 1); - QString code; - if(suffix == "cpp" || suffix == "h" || suffix == "py") - code = "KIcon (\"" + iconName + "\")"; - else if(suffix == "rb") - code = "KDE::Icon.new (:\"" + iconName + "\")"; - else if(suffix == "js" || suffix == "qts" || suffix == "cs") - code = "new KIcon (\"" + iconName + "\")"; - else if(suffix == "java") - code = "new org.kde.kdeui.KIcon (\"" + iconName + "\")"; - else if(suffix == "fal" || suffix == "ftd") - code = "KIcon ('" + iconName + "')"; - else if(suffix == "php") - code = "new KIcon ('" + iconName + "')"; - else if(suffix == "pl") - code = "KDE::Icon (\"" + iconName + "\")"; - else if(suffix == "pas") - code = "KIcon_create ('" + iconName + "')"; - else if(suffix == "scm") - code = "(make KIcon '" + iconName + ")"; - else if(suffix == "hs") - code = "kIcon \"" + iconName + "\""; - else if(suffix == "ads" || suffix == "adb") - code = "KDEui.Icons.Constructos.Create (\"" + iconName + "\")"; - else - code = iconName; - doc->insertText(view->cursorPosition(), code); -} - - - - -IconInserterPlugin::IconInserterPlugin (QObject *parent, const QVariantList &) - : Plugin (parent) -{ -} - -IconInserterPlugin::~IconInserterPlugin() -{ -} - - -void IconInserterPlugin::addView (KTextEditor::View *view) -{ - m_views.insert(view,new IconInserterPluginView(this,view)); -} - -void IconInserterPlugin::removeView(KTextEditor::View *view) -{ - kDebug(); - delete m_views.take(view); -} - -#include "iconinserterplugin.moc" diff --git a/part/plugins/kte_iconinserter/iconinserterplugin.h b/part/plugins/kte_iconinserter/iconinserterplugin.h deleted file mode 100644 index 8f94a6a..0000000 --- a/part/plugins/kte_iconinserter/iconinserterplugin.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** - * This file is part of the KTextEditor-Icon-Inserter-Plugin * - * Copyright 2009-2010 Jonathan Schmidt-Dominé * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU Library General Public License version * - * 3, or (at your option) any later version, as published by the Free * - * Software Foundation. * - * * - * This library is distributed in the hope that it will be useful, but * - * WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public * - * License along with the kdelibs library; see the file COPYING.LIB. If * - * not, write to the Free Software Foundation, Inc., 51 Franklin Street, * - * Fifth Floor, Boston, MA 02110-1301, USA. or see * - * . * - ****************************************************************************/ - -#ifndef KDEVICONINSERTERPLUGIN_H -#define KDEVICONINSERTERPLUGIN_H - -#include - -#include - -#include - -#include -#include - -using namespace KTextEditor; - -class IconInserterPlugin; - -class IconInserterPluginView: public QObject, public KXMLGUIClient -{ - Q_OBJECT - public: - IconInserterPluginView(IconInserterPlugin *plugin, KTextEditor::View *view); - virtual ~IconInserterPluginView(); - private slots: - void insertIcon(); - private: - QPointer m_view; -}; - -class IconInserterPlugin: public Plugin -{ - Q_OBJECT - public: - IconInserterPlugin (QObject *parent, const QVariantList & = QVariantList()); - ~IconInserterPlugin(); - void addView (View *view); - void removeView(View *view); - virtual void readConfig (KConfig*) {} - virtual void writeConfig (KConfig*) {} - private: - QMap m_views; -}; - -K_PLUGIN_FACTORY_DECLARATION(IconInserterPluginFactory) - -#endif diff --git a/part/plugins/kte_iconinserter/ktexteditor_iconinserter.desktop b/part/plugins/kte_iconinserter/ktexteditor_iconinserter.desktop deleted file mode 100644 index 69a29fd..0000000 --- a/part/plugins/kte_iconinserter/ktexteditor_iconinserter.desktop +++ /dev/null @@ -1,127 +0,0 @@ -[Desktop Entry] -Type=Service -Comment=Select an icon and use it as a KIcon in your source-code -Comment[bg]=Изберете икона за използване като KIcon в Ð¸Ð·Ñ…Ð¾Ð´Ð½Ð¸Ñ Ð²Ð¸ код -Comment[ca]=Seleccioneu una icona i utilitzeu-la com a «KIcon» en el codi font -Comment[ca@valencia]=Seleccioneu una icona i utilitzeu-la com a «KIcon» en el codi font -Comment[da]=Vælg et ikon og brug det som et KIcon i din kildekode -Comment[de]=Wählen Sie ein Symbol und verwenden Sie dieses als KIcon innerhalb Ihres Quelltextes. -Comment[el]=Επιλέξτε ένα εικονίδιο και χÏησιμοποιήστε το ως KIcon στον πηγαίο κώδικα σας -Comment[en_GB]=Select an icon and use it as a KIcon in your source-code -Comment[es]=Seleccionar un icono y usarlo como KIcon en su código fuente -Comment[et]=Ikooni valimine ja selle kasutamine KIconina oma lähtekoodis -Comment[gl]=Escolle unha icona e emprégaa como un KIcon no código fonte -Comment[hr]=Odaberite ikonu i koristite je kao KIcon u svom izvornom kodu -Comment[ia]=Il Selectiona un icone e le usa como un Kicon in tu codice fonte -Comment[id]=Pilih sebuah ikon dan gunakan itu sebagai KIcon di kode program anda -Comment[is]=Veldu táknmynd og notaðu hana sem KIcon í grunnkóðanum þínum -Comment[ja]=アイコンをé¸æŠžã—ã¦ã€ã‚½ãƒ¼ã‚¹ã®ä¸­ã§ KIcon ã¨ã—ã¦ä½¿ç”¨ -Comment[kk]=БаÑтапқы кодыңызда KIcon ретінде қолданатын таңбашаны таңдау -Comment[km]=ជ្រើស​រូបážáŸ†ážŽáž¶áž„ ហើយ​ប្រើ​វា​ជា​ KIcon នៅ​ក្នុង​កូដ​ប្រភព​របស់​អ្នក -Comment[nb]=Velg et ikon og bruk det som et KIcon i din kildekode -Comment[nds]=Söök en Lüttbild ut, un bruuk dat binnen Dien Bornkode as KIcon. -Comment[nl]=Selecteer een pictogram en gebruik het als een KIcon in uw broncode -Comment[pt]=Seleccione um ícone e use-o como um KIcon no seu código-fonte -Comment[pt_BR]=Selecione um ícone e use-o como um KIcon no seu código-fonte -Comment[ru]=Ð’Ñтавка значка Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ ÐºÐ°Ðº KIcon в коде программы -Comment[sr]=Изаберите икону која ће бити KIcon у вашем изворном коду -Comment[sr@ijekavian]=Изаберите икону која ће бити KIcon у вашем изворном коду -Comment[sr@ijekavianlatin]=Izaberite ikonu koja će biti KIcon u vaÅ¡em izvornom kodu -Comment[sr@latin]=Izaberite ikonu koja će biti KIcon u vaÅ¡em izvornom kodu -Comment[sv]=Välj en ikon och använd den som en KIcon i källkoden -Comment[tg]=Ðишонаро интихоб кунед ва онро ҳамчун KIcon иÑтифода баред -Comment[th]=เลือà¸à¹„อคอนà¹à¸¥à¸°à¹ƒà¸Šà¹‰à¸¡à¸±à¸™à¹ƒà¸«à¹‰à¹€à¸›à¹‡à¸™à¹à¸šà¸š KIcon ในโค้ดต้นฉบับของคุณ -Comment[tr]=Bir simge seçin ve kaynak kodunuzda KIcon olarak kullanın -Comment[uk]=Виберіть піктограму Ñ– викориÑтайте Ñ—Ñ— Ñк KIcon у коді вашої програми -Comment[x-test]=xxSelect an icon and use it as a KIcon in your source-codexx -Comment[zh_CN]=选择一个图标,然åŽåœ¨æ‚¨çš„æºä»£ç ä¸­å°†å…¶ç”¨ä½œ KIcon -Comment[zh_TW]=é¸æ“‡ä¸€å€‹åœ–示,並在您的程å¼ç¢¼ä¸­åšç‚º KIcon -Name=IconInserter -Name[bg]=Вмъкване на икона -Name[ca]=Inserció d'icona -Name[ca@valencia]=Inserció d'icona -Name[da]=IconInserter -Name[de]=Symboleinfüger -Name[el]=Εισαγωγή εικονιδίου -Name[en_GB]=IconInserter -Name[es]=IconInserter -Name[et]=Ikoonilisaja -Name[gl]=IconInserter -Name[hr]=IconInserter -Name[ia]=Insertator de Icones -Name[id]=IconInserter -Name[is]=TáknmyndaInnsetning -Name[ja]=アイコンインサーター -Name[kk]=Таңбашаны ендіру -Name[km]=កម្មវិធី​បញ្ចូល​រូបážáŸ†ážŽáž¶áž„ -Name[nb]=Ikoninnsetting -Name[nds]=Lüttbild infögen -Name[nl]=PictogramInvoegen -Name[nn]=Set inn -Name[pa]=IconInserter -Name[pt]=Inserção de Ãcones -Name[pt_BR]=Inserção de Ãcones -Name[ru]=Ð’Ñтавка значка -Name[sr]=Уметач икона -Name[sr@ijekavian]=Уметач икона -Name[sr@ijekavianlatin]=UmetaÄ ikona -Name[sr@latin]=UmetaÄ ikona -Name[sv]=Infoga ikon -Name[tg]=Вориди нишона -Name[th]=ตัวà¹à¸—รà¸à¹„อคอน -Name[tr]=IconInserter -Name[uk]=IconInserter -Name[x-test]=xxIconInserterxx -Name[zh_CN]=图标æ’入器 -Name[zh_TW]=IconInserter -GenericName=Insert Code for KIcon-Creation -GenericName[bg]=Въведете код за Ñъздаване на KIcon -GenericName[ca]=Inseriu el codi per a la creació de KIcon -GenericName[ca@valencia]=Inseriu el codi per a la creació de KIcon -GenericName[da]=Indsæt kode til KIcon-Creation -GenericName[de]=Quelltext zur KIcon-Erstellung einfügen -GenericName[el]=Εισαγωγή κώδικα για δημιουÏγία KIcon -GenericName[en_GB]=Insert Code for KIcon-Creation -GenericName[es]=Insertar código para la creación de un KIcon -GenericName[et]=Koodi lisamine KIconi loomiseks -GenericName[gl]=Insere código para a creación de KIcon -GenericName[hr]=Umetnite kod za KIcon-Creation -GenericName[ia]=Il Inserta codice pro le creation de KIcon -GenericName[id]=Masukkan Kode untuk Membuat KIcon -GenericName[is]=Settu inn kóða fyrir KIcon-gerð -GenericName[ja]=KIcon 作æˆã®ãŸã‚ã®ã‚³ãƒ¼ãƒ‰ã‚’挿入 -GenericName[kk]=KIcon-құру үшін кодын енгізу -GenericName[km]=បញ្ចូល​កូដ​សម្រាប់​ការ​បង្កើážâ€‹ KIcon -GenericName[nb]=Sett inn kode for Ã¥ lage KIcon -GenericName[nds]=Kode för't KIcon-Opstellen infögen -GenericName[nl]=Voeg code in voor het aanmaken met KIcon -GenericName[nn]=Set inn før deklarasjon -GenericName[pt]=Inserir o Código de Criação de KIcon's -GenericName[pt_BR]=Inserir o código de criação de KIcons -GenericName[sr]=Уметање кода за Ñтварање KIcon‑а -GenericName[sr@ijekavian]=Уметање кода за Ñтварање KIcon‑а -GenericName[sr@ijekavianlatin]=Umetanje koda za stvaranje KIcon‑a -GenericName[sr@latin]=Umetanje koda za stvaranje KIcon‑a -GenericName[sv]=Infoga kod för att skapa en KIcon -GenericName[tg]=Рамзро барои Ñҷоди KIcon ворид намоед -GenericName[th]=à¹à¸—รà¸à¹‚ค้ดต้นรหัสสำหรับà¸à¸²à¸£à¸ªà¸£à¹‰à¸²à¸‡à¹€à¸›à¹‡à¸™à¹à¸šà¸š KIcon -GenericName[tr]=KIcon-Creation için Kod Ekle -GenericName[uk]=Ð”Ð¾Ð´Ð°Ð²Ð°Ð½Ð½Ñ ÐºÐ¾Ð´Ñƒ Ð´Ð»Ñ ÑÑ‚Ð²Ð¾Ñ€ÐµÐ½Ð½Ñ KIcon -GenericName[x-test]=xxInsert Code for KIcon-Creationxx -GenericName[zh_CN]=KDE 图标的æ’å…¥ä»£ç  -GenericName[zh_TW]=æ’入程å¼ç¢¼ç”¢ç”Ÿ KIcon -Icon=kcoloredit -ServiceTypes=KTextEditor/Plugin -X-KDE-ServiceTypes=KTextEditor/Plugin -X-KDE-Library=ktexteditor_iconinserter -X-KDE-PluginKeyword=ktexteditor_iconinserter -X-KDE-PluginInfo-Name=kdeviconinserter -X-KDE-PluginInfo-Author=Jonathan Schmidt-Dominé (The User) -X-KDE-PluginInfo-Email=devel@the-user.org -X-KDE-PluginInfo-Website=the-user.org -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-License=LGPL_V3 -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-Category=Editor -X-KDE-ParentApp=kate -X-KDE-Version=4.0 diff --git a/part/plugins/kte_iconinserter/ktexteditor_iconinserterui.rc b/part/plugins/kte_iconinserter/ktexteditor_iconinserterui.rc deleted file mode 100644 index ce6c14a..0000000 --- a/part/plugins/kte_iconinserter/ktexteditor_iconinserterui.rc +++ /dev/null @@ -1,8 +0,0 @@ - - - -

- - - - diff --git a/part/plugins/kte_insanehtml_le/CMakeLists.txt b/part/plugins/kte_insanehtml_le/CMakeLists.txt deleted file mode 100644 index 7a201a8..0000000 --- a/part/plugins/kte_insanehtml_le/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ - -include_directories( ${KDE4_INCLUDE_DIR} ${QT_INCLUDES} ) - -########### next target ############### - -set(ktexteditor_insanehtml_le_PART_SRCS - insanehtmlplugin_le.cpp) - -#kde4_add_ui_files(ktexteditor_insanehtml_le_PART_SRCS insanehtml.ui ) - -kde4_add_plugin(ktexteditor_insanehtml_le ${ktexteditor_insanehtml_le_PART_SRCS}) - -target_link_libraries(ktexteditor_insanehtml_le ${KDE4_KDECORE_LIBS} ${KDE4_KDEUI_LIBS} ktexteditor) - -install(TARGETS ktexteditor_insanehtml_le DESTINATION ${PLUGIN_INSTALL_DIR} ) - - -########### install files ############### - -install( FILES data/insanehtml_le_ui.rc DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_insanehtml_le ) -install( FILES data/xhtml.cfg DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_insanehtml_le ) -install( FILES data/ktexteditor_insanehtml_le.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) - - diff --git a/part/plugins/kte_insanehtml_le/data/insanehtml_le_ui.rc b/part/plugins/kte_insanehtml_le/data/insanehtml_le_ui.rc deleted file mode 100644 index f727c37..0000000 --- a/part/plugins/kte_insanehtml_le/data/insanehtml_le_ui.rc +++ /dev/null @@ -1,9 +0,0 @@ - - - - &Tools - - - - - \ No newline at end of file diff --git a/part/plugins/kte_insanehtml_le/data/ktexteditor_insanehtml_le.desktop b/part/plugins/kte_insanehtml_le/data/ktexteditor_insanehtml_le.desktop deleted file mode 100644 index 904fde0..0000000 --- a/part/plugins/kte_insanehtml_le/data/ktexteditor_insanehtml_le.desktop +++ /dev/null @@ -1,78 +0,0 @@ -[Desktop Entry] -Type=Service -ServiceTypes=KTextEditor/Plugin -X-KDE-PluginInfo-Author=Joseph Wenninger -X-KDE-PluginInfo-Email=jowenn@kde.org -X-KDE-PluginInfo-Name=ktexteditorinsanehtml_le -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://www.kate-editor.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=BSD -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-Library=ktexteditor_insanehtml_le -X-KDE-Version=4.0 -Name=Insane (not ZEN) HTML coding (light edition) -Name[bg]=Insane (не ZEN) HTML-кодиране (олекотена верÑиÑ) -Name[ca]=Codi (edició lleugera) HTML insà (no ZEN) -Name[ca@valencia]=Codi (edició lleugera) HTML insà (no ZEN) -Name[da]=Insane (ikke ZEN) HTML-kodning (light-udgave) -Name[de]=Irrsinnige HTML-Kodierung (nicht ZEN, Basisversion) -Name[el]=Insane (όχι ZEN) κωδικοποίηση HTML (ελαφÏιά έκδοση) -Name[en_GB]=Insane (not ZEN) HTML coding (light edition) -Name[es]=Codificación HTML insensata (no zen) (edición ligera) -Name[et]=Hullumeelne (mitte ZEN) HTML kodeering (kerge versioon) -Name[gl]=Código HTML Insane (non ZEN) (edición light) -Name[ia]=Codifica Insane (non ZEN) de HTML (edition legier) -Name[id]=Pengodean HTML (edisi ringan) Insane (bukan ZEN) -Name[is]=Insane (ekki ZEN) HTML kóðun (léttútgáfa) -Name[ja]= éžæ­£å¸¸ (ZENã§ã¯ã‚ã‚Šã¾ã›ã‚“) HTML コーディング (ライトエディション) -Name[kk]=Жынды (дзен емеÑ) HTML коды (жеңілдеткен нұÑқаÑÑ‹) -Name[km]=Insane (មិនមែន ZEN) HTML coding (light edition) -Name[nb]=Spinnvill (ikke ZEN) HTML-koding (lett utgave) -Name[nds]="Insane"-HTML-Koderen (nich "ZEN") (Eenfach-Verschoon) -Name[nl]=Insane (niet ZEN) HTML-codering (lichte editie) -Name[pt]=Codificação de HTML louca (não ZEN) HTML (edição leve) -Name[pt_BR]=Codificação de HTML louca (não ZEN) HTML (edição leve) -Name[sr]=Лудо кодирање ХТМЛ‑а (лагано издање) -Name[sr@ijekavian]=Лудо кодирање ХТМЛ‑а (лагано издање) -Name[sr@ijekavianlatin]=Ludo kodiranje HTML‑a (lagano izdanje) -Name[sr@latin]=Ludo kodiranje HTML‑a (lagano izdanje) -Name[sv]=Insane (inte ZEN) HTML-kodning (enkel version) -Name[tr]=Insane (ZEN olmayan) HTML kodlama (hafif sürüm) -Name[uk]=Божевільне (не дзен) HTML-Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼ÑƒÐ²Ð°Ð½Ð½Ñ (Ñпрощена верÑÑ–Ñ) -Name[x-test]=xxInsane (not ZEN) HTML coding (light edition)xx -Name[zh_CN]=疯狂 HTML 代ç (è½»é‡çº§) -Name[zh_TW]=Insaneï¼ˆéž ZEN)HTML 編碼(輕é‡ç‰ˆï¼‰ -Comment=A plugin, which does zen-coding like selector completion -Comment[bg]=ПриÑтавка, коÑто оÑигурÑва подобно на zen автоматично завършване -Comment[ca]=Un connector que genera codi zen, com un selector de compleció -Comment[ca@valencia]=Un connector que genera codi zen, com un selector de compleció -Comment[da]=Et plugin som udfører zen-coding-lignende udvælgerfuldførelse -Comment[de]=Ein Modul zur ZEN-ähnlichen Auswahlvervollständigung. -Comment[el]=Ένα Ï€Ïόσθετο, το οποίο δημιουÏγεί κωδικοποίηση Ï„Ïπου zen όπως είναι η συμπλήÏωση επιλογέα -Comment[en_GB]=A plugin, which does zen-coding like selector completion -Comment[es]=Un complemento que realiza codificación zen, como el selector de terminación -Comment[et]=Plugin, mis kasutab zen-kodeerimise laadset selektori lõpetamist -Comment[gl]=Unha extensión que fai selección de completado de código estilo zen -Comment[ia]=Un plugin, que il face completion de selector al modo de codifica zen. -Comment[id]=Plugin, yang melakukan penyelesaian pemilih seperti pengodean zen -Comment[is]=Ãforrit sem framkvæmir zen-kóðun á borð við valklárun -Comment[ja]=zen-コーディングã«ä¼¼ãŸã‚»ãƒ¬ã‚¯ã‚¿è£œå®Œã‚’è¡Œã†ãƒ—ラグイン -Comment[kk]=Толықтыруды таңдау Ñекілді дзен-кодтауын Ñ–Ñке аÑыратын плагині -Comment[km]=កម្មវិធី​ជំនួយ ដែល​ zen-coding ដូច​ជា​កា​របំពáŸáž‰â€‹áž€áž˜áŸ’មវិធី​ជ្រើស -Comment[nb]=Et programtillegg som gjør velgerfullføring som i zen-coding -Comment[nds]=En Moduul för ZEN-liek Koderen, a.B. Köörkompletteren -Comment[nl]=Een plugin, die zen-codering doet zoals keuze-voltooiing -Comment[pt]=Um 'plugin' que efectua uma codificação 'zen, como a completação de selectores -Comment[pt_BR]=Um plug-in que efetua uma codificação zen, como a completação de seletores -Comment[sr]=Прикључак за проширивање налик на зен‑кодирање -Comment[sr@ijekavian]=Прикључак за проширивање налик на зен‑кодирање -Comment[sr@ijekavianlatin]=PrikljuÄak za proÅ¡irivanje nalik na zen‑kodiranje -Comment[sr@latin]=PrikljuÄak za proÅ¡irivanje nalik na zen‑kodiranje -Comment[sv]=Ett insticksprogram som utför zen-kodning, sÃ¥som komplettering av selektorer -Comment[tr]=zen kodlama benzeri seçim tamamlama saÄŸlayan bir eklenti -Comment[uk]=Додаток дзен-Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼ÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾Ð´Ñ–Ð±Ð½Ð¸Ð¹ до Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñ–Ð² вибору -Comment[x-test]=xxA plugin, which does zen-coding like selector completionxx -Comment[zh_CN]=一个类似 zen-coding 工具的选择器补全æ’件 -Comment[zh_TW]=一個執行類似 zen-coding é¸æ“‡å™¨è£œå®Œçš„å¤–æŽ›ç¨‹å¼ diff --git a/part/plugins/kte_insanehtml_le/data/xhtml.cfg b/part/plugins/kte_insanehtml_le/data/xhtml.cfg deleted file mode 100644 index 4b0ad1e..0000000 --- a/part/plugins/kte_insanehtml_le/data/xhtml.cfg +++ /dev/null @@ -1,5 +0,0 @@ -[Default Attributes] -img=src,alt -form=method,action -input=name,type,value -a=href diff --git a/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.cpp b/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.cpp deleted file mode 100644 index 9098281..0000000 --- a/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.cpp +++ /dev/null @@ -1,499 +0,0 @@ -/* -Copyright (C) 2010 Joseph Wenninger - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "insanehtmlplugin_le.h" -#include "insanehtmlplugin_le.moc" -#include -#include -#include -#include -#include -#include -#include - -#undef IHP_DEBUG - -K_PLUGIN_FACTORY_DECLARATION(InsaneHTMLPluginLEFactory) -K_PLUGIN_FACTORY_DEFINITION(InsaneHTMLPluginLEFactory, - registerPlugin(); - ) -K_EXPORT_PLUGIN(InsaneHTMLPluginLEFactory("ktexteditor_insanehtml_le", "ktexteditor_plugins")) - -InsaneHTMLPluginLE::InsaneHTMLPluginLE(QObject *parent, const QList data): - KTextEditor::Plugin(parent) { - Q_UNUSED(data); - -} - - -void InsaneHTMLPluginLE::addView (KTextEditor::View *view) { - m_map.insert(view,new InsaneHTMLPluginLEView(this,view)); -} - -void InsaneHTMLPluginLE::removeView (KTextEditor::View *view) { - delete m_map.take(view); -} - - -InsaneHTMLPluginLEView::InsaneHTMLPluginLEView(QObject* parent,KTextEditor::View* view): - QObject(parent),KXMLGUIClient(),m_view(view) { - - setComponentData(InsaneHTMLPluginLEFactory::componentData()); - - KAction *a=actionCollection()->addAction( "tools_insanehtml_le", this,SLOT(expand()) ); - a->setText(i18n("Insane HTML (LE) Expansion")); - a->setShortcut( Qt::CTRL + Qt::Key_Period ); - - setXMLFile( "insanehtml_le_ui.rc" ); - - m_view->insertChildClient(this); - - m_emptyTags<<"br"<<"hr"<<"img"<<"input"<<"meta"<<"link"; - QStringList cfgFiles=KGlobal::dirs()->findAllResources("data", "ktexteditor_insanehtml_le/xhtml.cfg",KStandardDirs::NoDuplicates); - if (cfgFiles.count()>0) { - KConfig attribConfig(cfgFiles[0],KConfig::SimpleConfig); - KConfigGroup group(&attribConfig,"Default Attributes"); - foreach (const QString& tag, group.keyList()) { - QStringList attribs=group.readEntry(tag,QStringList()); - foreach (const QString& attrib,attribs) { - m_defaultAttributes.insert(tag,attrib); - } - } - } -} - -InsaneHTMLPluginLEView::~InsaneHTMLPluginLEView() { - m_view->removeChildClient(this); -} - - -/* - We expect the cursor to be in them middle or at the end of a tag and don't allow attribute definitions on the right hand side, only quantifiers -*/ - -int InsaneHTMLPluginLEView::find_region_end(int cursor_x, const QString& line, int *filtercount) { - int end_x=cursor_x; - const int len=line.length(); - while (end_x=0) && (tmp')) return -1; - return end_x; -} - - -/* everything is allowed in the front*/ -int InsaneHTMLPluginLEView::find_region_start(int cursor_x, const QString& line, int *filtercount) { - int len=line.length(); - int start_x=cursor_x; - bool in_attrib=false; - bool in_string=false; - while (start_x>0) { - int tmp_x=start_x-1; - if (tmp_x==-1) break; - QChar c=line.at(tmp_x); - if (c==QChar('"')) { - if (!in_attrib) break; - in_string=!in_string; - start_x=tmp_x; - continue; - } - if (in_string) { - start_x=tmp_x; - continue; - } - - if (c==QChar(']')) { - in_attrib=true; - start_x=tmp_x; - continue; - } - - if (c==QChar('[')) { - if (in_attrib) { - in_attrib=false; - start_x=tmp_x; - continue; - } else { - break; - } - } - - if (in_attrib) { - start_x=tmp_x; - continue; - } - - if ( (c.isSpace() || c==QChar('=')) && (!in_attrib)) - break; - - - if (c.isLetter() || c.isDigit() || (c==QChar('*')) || (c==QChar('_')) || - (c==QChar('-')) || (c==QChar(':')) || (c==QChar('.')) || (c==QChar('#')) || - (c==QChar('>')) || (c==QChar('$')) || (c==QChar('+')) || (c==QChar('(')) || - (c==QChar(')'))) { - start_x=tmp_x; - continue; - } - - if (c==QChar('|')) { - (*filtercount)++; - start_x=tmp_x; - continue; - } - - break; - } - - if (in_attrib || in_string) return -1; - if (start_x>=len) return -1; - if (start_x>=0) { - if (!( (line.at(start_x).isLetter()) || (line.at(start_x)==QChar('(')) ) ) return -1; - } - return start_x; -} - - -QString InsaneHTMLPluginLEView::parseIdentifier(const QString& input, int *offset,bool firstDigit) { - int offset_tmp=*offset; - int len=input.length(); - QString identifier; - if (!firstDigit) { - if (offset_tmp attributes; - QString attributesString; - int multiply=1; - bool error=false; - tag=parseIdentifier(input,&offset); - QStringList defAttribs=m_defaultAttributes.values(tag); - foreach (const QString& defAttr,defAttribs) - attributes.insert(defAttr,""); - while (offset')) { - offset++; - sub=parse(input,offset,&offset); - break; - } else if (c==QChar('+')) { - offset++; - relatives=parse(input,offset,&offset); - break; - } else if (c==QChar('*')) { - offset++; - multiply=parseNumber(input,&offset); - } else if (c==QChar('#')) { - offset++; - id=parseIdentifier(input,&offset); - } else if (c==QChar('[')) { - offset++; - while (offset=input.length()) { - error=true; - break; - } - while (offset=input.length()) { - error=true; - break; - } - c=input.at(offset); - if (c==QChar('=')) { - offset++; - //PARSE PARAMETER - if (offset>=input.length()) { - error=true; - break; - } - if (input.at(offset)==QChar('"')) { - // parse quoted string - offset++; - int stringStart=offset; - while (offset=input.length()) { - error=true; - break; - } - //skip whitespace and , - while (offset=input.length()) { - error=true; - break; - } - //skip whitespace and , - while (offset=input.length()) { - error=true; - break; - } - //skip whitespace and , - while (offset::const_iterator it=attributes.constBegin();it!=attributes.constEnd();++it) { - attributesString+=" "+it.key(); - if (!it.value().isNull()) attributesString+="=\""+it.value()+"\""; - } - QStringList result; - if (!compound) { - QString idAttrib; - if (!id.isEmpty()) idAttrib=QString(" id=\"%1\"").arg(id); - QString classAttrib=classes.join(" "); - QString classComment; - if (!classAttrib.isEmpty()) classComment="."+classes.join(" ."); - if (!classAttrib.isEmpty()) classAttrib=QString(" class=\"%1\"").arg(classAttrib); - - if (!sub.isEmpty()) - sub=sub.replaceInStrings(QRegExp("^")," "); - - for (int i=1;i<=multiply;i++) { - bool done=false; - if (!idAttrib.isEmpty()) result<").arg(tag).arg(idAttrib).arg(classAttrib).arg(attributesString); - done=true; - } - } - if (!done){ - if (!sub.isEmpty()) { - result<").arg(tag).arg(idAttrib).arg(classAttrib).arg(attributesString); - result<").arg(tag); - } else - result<").arg(tag).arg(idAttrib).arg(classAttrib).arg(attributesString); - } - - if (!idAttrib.isEmpty()) result<replaceInStrings("&","&"); - lines->replaceInStrings("<","<"); - lines->replaceInStrings(">",">"); -} - -void InsaneHTMLPluginLEView::apply_filter_c(QStringList *lines) { - lines->replaceInStrings("|c-",""); -} - -void InsaneHTMLPluginLEView::expand() { - KTextEditor::Cursor c=m_view->cursorPosition(); - QString line=m_view->document()->line(c.line()); - int filtercount=0; - int start_x=find_region_start(c.column(),line,&filtercount); - int end_x=find_region_end(c.column(),line,&filtercount); - if ( (start_x<0) || (end_x<0) || (start_x==end_x) ) { - KPassivePopup::message(i18n("No valid Insane HTML markup detected at current cursor position"),m_view); - return; - } -#ifdef IHP_DEBUG - KPassivePopup::message(i18n("This looks like valid Insane HTML markup: %1",line.mid(start_x,end_x-start_x)),m_view); -#endif - QString region_text=line.mid(start_x,end_x-start_x); - QStringList filters; - while(filtercount>0) { - int li=region_text.lastIndexOf("|"); - filters<=0;i--) { - QString tmp=result_list[i]; - tmp.remove(rcm); - if (tmp.trimmed().isEmpty()) - result_list.takeAt(i); - else - result_list[i]=tmp; - } - //prefix with indentation - QString line_prefix=line.left(start_x); - line_prefix.replace(QRegExp("\\S")," "); - for (int i=1;idocument(); - KTextEditor::Range r(c.line(),start_x,c.line(),end_x); - doc->replaceText(r,result); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.h b/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.h deleted file mode 100644 index 48e4f10..0000000 --- a/part/plugins/kte_insanehtml_le/insanehtmlplugin_le.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 2010 Joseph Wenninger - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef INSANE_HTML_PLUGIN_H -#define INSANE_HTML_PLUGIN_H - -#include -#include -#include -#include - -class InsaneHTMLPluginLEView: public QObject, public KXMLGUIClient { - Q_OBJECT -public: - InsaneHTMLPluginLEView(QObject *parent, KTextEditor::View *view); - virtual ~InsaneHTMLPluginLEView(); -public Q_SLOTS: - void expand(); -private: - KTextEditor::View *m_view; - QStringList m_emptyTags; - QMultiMap m_defaultAttributes; - int find_region_start(int cursor_x, const QString& line, int * filtercount); - int find_region_end(int cursor_x, const QString& line, int * filtercount); - QStringList parse(const QString& input, int offset, int *newOffset=0); - QString parseIdentifier(const QString& input, int *offset,bool firstDigit=false); - int parseNumber(const QString& input, int *offset); - void apply_filter_e(QStringList *lines); - void apply_filter_c(QStringList *lines); -}; - -class InsaneHTMLPluginLE: public KTextEditor::Plugin { - Q_OBJECT -public: - InsaneHTMLPluginLE(QObject *parent, const QList data=QList()); - virtual ~InsaneHTMLPluginLE(){} - virtual void addView (KTextEditor::View *view); - virtual void removeView (KTextEditor::View *view); -private: - QMap m_map; -}; -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/pythonencoding/CMakeLists.txt b/part/plugins/pythonencoding/CMakeLists.txt deleted file mode 100644 index 83c5545..0000000 --- a/part/plugins/pythonencoding/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ - -########### next target ############### - -set(ktexteditor_python-encoding_PART_SRCS python_encoding.cpp ) - - -kde4_add_plugin(ktexteditor_python-encoding ${ktexteditor_python-encoding_PART_SRCS}) - -target_link_libraries(ktexteditor_python-encoding ${KDE4_KIO_LIBS} ktexteditor kdeui kfile) - -install(TARGETS ktexteditor_python-encoding DESTINATION ${PLUGIN_INSTALL_DIR} ) - - -########### install files ############### - -install( FILES ktexteditor_python-encoding.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) - - - - diff --git a/part/plugins/pythonencoding/ktexteditor_python-encoding.desktop b/part/plugins/pythonencoding/ktexteditor_python-encoding.desktop deleted file mode 100644 index bb91b15..0000000 --- a/part/plugins/pythonencoding/ktexteditor_python-encoding.desktop +++ /dev/null @@ -1,141 +0,0 @@ -[Desktop Entry] -Type=Service -ServiceTypes=KTextEditor/LoadSaveFilterCheckPlugin -X-KDE-Library=ktexteditor_python-encoding -Name=Python encoding checker/adder -Name[ar]=مدقق/مضي٠ترميز بايثون -Name[as]=Python encoding checker/adder -Name[ast]=Verificador/inclusor de la codificación Python -Name[be@latin]=SpraÅ­džvaÅ„nie j dadaÅ„nie aznaÄeÅ„nia kadavaÅ„nia dla Pythona -Name[bg]=Проверка и добавÑне на кодировка за Python -Name[ca]=Verificador/afegidor de codificació Python -Name[ca@valencia]=Verificador/afegidor de codificació Python -Name[cs]=Kontroler/pÅ™idavaÄ kódování pythonu -Name[da]=Tjek og tilføjelse af Python-tegnsæt -Name[de]=Python-Kodierungsprüfung und Hinzufügung -Name[el]=Έλεγχος κωδικοποίησης Python -Name[en_GB]=Python encoding checker/adder -Name[eo]=Pitona enkodiga kontrolilo/aldonilo -Name[es]=Comprobador/generador de codificación para Python -Name[et]=Pythoni kodeeringu kontrollija/lisaja -Name[eu]=Phyton-en kodeaketaren egiaztatzea/gehitzea -Name[fi]=Python-merkistötarkistin -Name[fr]=Vérification / ajout de l'encodage Python -Name[fy]=Python kodear kontroler/taheaker -Name[ga]=Seiceálaí ionchódaithe Python -Name[gl]=Comprobador/Adicionador da codificación para Python -Name[gu]=પાયથોન àªàª¨àª•à«‹àª¡àª¿àª‚ગ ચકાસનાર/ઉમેરનાર -Name[he]=בודק/מוסיף קידוד Python -Name[hne]=पायथन à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग जंचइया/जोड़इया -Name[hr]=ProvjeravaÄ/dodavaÄ enkodinga u Pythonu -Name[hsb]=Python encoding checker/adder -Name[hu]=Python kódolásellenÅ‘rzÅ‘ -Name[ia]=Controlator e summator de codice Python -Name[id]=Pemeriksa/penambah penyandian Python -Name[is]=Python kóðaprófun/línuendingar -Name[it]=Controllo/aggiunta codifica per Python -Name[ja]=Python エンコーディングã®ãƒã‚§ãƒƒã‚¯ã¨è¿½åŠ  -Name[kk]=Python кодын теÑеру/қоÑу -Name[km]=កម្មវិធី​បន្ážáŸ‚ម/​ážáŸ’ážšáž½ážáž–áž·áž“áž·ážáŸ’យ​ការ​អ៊ិនកុដ​របស់ Python -Name[kn]=ಪೈಥಾನೠಸಂಕೇತೀಕರಣ (ಎಂಕೋಡಿಂಗà³) ಪರಿಶೀಲಕ/ಸೇರಿಸà³à²— -Name[ko]=파ì´ì¬ ì¸ì½”딩 검사 ë° ì¶”ê°€ê¸° -Name[ku]=Python kod kirina kontrolker/lê zêdeker ê -Name[lt]=Python koduoÄių tikrinimo/pridÄ—jimo priemonÄ— -Name[lv]=Python kodÄ“juma pÄrbaudÄ«tÄjs/pievienotÄjs -Name[mai]=पाइथन à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग जाà¤à¤šà¤•à¤à¤¨à¤¿à¤¹à¤¾à¤°/जोड़निहार -Name[ml]=പൈതàµà´¤à´£àµâ€ à´Žà´¨àµâ€à´•àµ‹à´¡à´¿à´™àµà´™àµ ചെകàµà´•à´°àµâ€/ആഡരàµâ€ -Name[ms]=Pemeriksa/penambah pengenkod Phython -Name[nb]=Python sjekker/innlegger for tegnkoding -Name[nds]=Python-Koderenprööv -Name[nl]=Python-codering controleren/toevoegen -Name[nn]=Python-kodesjekkar -Name[pa]=ਪਾਈਥਨ ਇੰਕੋਡਿੰਗ ਚੈੱਕਰ/à¨à¨¡à¨° -Name[pl]=Dodawanie i sprawdzanie kodowania w Pythonie -Name[pt]=Verificação/adição da codificação em Python -Name[pt_BR]=Verificação/adição da codificação em Python -Name[ro]=Verificator/adăugător de codări Python -Name[ru]=Проверка кодировки иÑходного кода на Python -Name[se]=Pythonkodera iskkadeaddji/lasideaddji -Name[sk]=Pridávanie/kontrola kódovania Pythonu -Name[sl]=Preverjanje/dodajanje kodnega nabora za Python -Name[sr]=Оверивач и додавач кодирања у питону -Name[sr@ijekavian]=Овјеривач и додавач кодирања у питону -Name[sr@ijekavianlatin]=OvjerivaÄ i dodavaÄ kodiranja u Pythonu -Name[sr@latin]=OverivaÄ i dodavaÄ kodiranja u Pythonu -Name[sv]=Python kodningskontroll/tillägg -Name[ta]=பைதான௠எழà¯à®¤à¯à®¤à¯à®°à¯à®µà®¾à®•à¯à®•à®®à¯ சோதி/சேரà¯à®¤à¯à®¤à®¿ -Name[tg]=Санҷидан/Иловаи рамзгузории Python -Name[th]=ตัวตรวจ/ตัวเพิ่มชุดรหัสอัà¸à¸‚ระของไพธอน -Name[tr]=Python karakter kodlaması denetleyici/ekleyici -Name[uk]=ЗаÑіб Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸/Ð´Ð¾Ð´Ð°Ð²Ð°Ð½Ð½Ñ ÐºÐ¾Ð´ÑƒÐ²Ð°Ð½Ð½Ñ Ð´Ð¾ Python -Name[x-test]=xxPython encoding checker/adderxx -Name[zh_CN]=Python ç¼–ç æ£€æŸ¥/添加器 -Name[zh_TW]=Python 編碼檢查器/加入器 -Comment=While saving check encoding of python files and add an encoding line -Comment[ar]=عند الحÙظ تأكد من ترميز ملÙات البايثون Ùˆ أض٠سطر الترميز -Comment[as]=ৰকà§à¦·à¦¾ কৰোà¦à¦¤à§‡ python নথিপতà§à§°à§° encoding পৰীকà§à¦·à¦¾ কৰিব আৰৠà¦à¦Ÿà¦¾ encoding শাৰী যোগ কৰিব । -Comment[ast]=Al guardar comprueba la codificación de los ficheros Python y amesta una llinia de codificación -Comment[be@latin]=SpraÅ­džvaje dla zapisvanych fajÅ‚aÅ­ Pythona kadavaÅ„nie j dadaje radok ź jahonym aznaÄeÅ„niem -Comment[bg]=Проверка за кодировка на файлове на python и добавÑне на ред за кодировката при запиÑване -Comment[ca]=Mentre desa els fitxers Python verifica la codificació i afegeix una línia de codificació -Comment[ca@valencia]=Mentre alça els fitxers Python verifica la codificació i afig una línia de codificació -Comment[cs]=Zkontrolovat kódování bÄ›hem ukládání souborů pythonu a pÅ™idat řádek s kódováním -Comment[da]=Tjek tegnsæt for python-filer ved gemning og tilføj en tegnsæt-linje -Comment[de]=Prüft beim Speichern die Kodierung von Python-Dateien und fügt eine Kodierungszeile hinzu. -Comment[el]=Κατά την αποθήκευση, έλεγχος κωδικοποίησης αÏχείων python και Ï€Ïοσθήκη γÏαμμής κωδικοποίησης -Comment[en_GB]=While saving check encoding of python files and add an encoding line -Comment[es]=Comprueba la codificación al guardar archivos Python y añade una línea de codificación -Comment[et]=Kontrollib salvestamisel Pythoni failide kodeeringut ja lisab kodeeringurea -Comment[eu]=Gordetzerakoan phyton fitxategien kodeaketa egiaztatu eta kodeaketa lerro bat gehitu -Comment[fi]=Tallennettaessa Python-tiedostoja tarkista merkistö ja lisää merkistöotsikko tarvittaessa -Comment[fr]=Vérification de l'encodage des fichiers Python lors de l'enregistrement, et ajout d'une ligne d'encodage si nécessaire -Comment[fy]=Under it laden kontrolearje de kodearring fan python triemmen en heakje in kodearringrigel ta -Comment[ga]=Le linn sábhála, seiceáil ionchódú de chomhaid python agus cuir líne ionchódaithe leo más gá -Comment[gl]=Comproba a codificación ao gardar ficheiros python e engade unha liña de codificación -Comment[gu]=પાયથોન ફાઇલો સંગà«àª°àª¹ કરતી વખતે àªàª¨àª•à«‹àª¡àª¿àª‚ગ ચકાસો અને àªàª¨àª•à«‹àª¡àª¿àª‚ગ વાકà«àª¯ ઉમેરો -Comment[he]=בעת שמירה בדוק ×ת הקידוד של קבצי פייתון והוסף שורת קידוד -Comment[hne]=पायथन फाइल के à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग जांचे अऊ à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग लाइन जोड़े के बेरा में -Comment[hr]=Prilikom spremanja provjerite enkoding pyhtonovih datoteka i dodajte liniju s enkodingom -Comment[hsb]=PÅ™epruwuje kodÄ›rowanje python-datajow a doda linku z informaciju wo kodÄ›rowanju -Comment[hu]=Mentéskor ellenÅ‘rzi vagy létrehozza a kódolást megadó sort -Comment[ia]=Durante que il salva il controla le codifica de archivos python e il adde un linea de codifica -Comment[id]=Ketika menyimpan periksa penyandian berkas python dan tambah baris penyandian -Comment[is]=Þegar python skrár eru vistaðar er farið yfir kóðann og bætt við endalínum -Comment[it]=Controlla la codifica dei file python durante il salvataggio e aggiunge una riga con la codifica -Comment[ja]=ä¿å­˜ã™ã‚‹éš›ã« Python ファイルã®ã‚¨ãƒ³ã‚³ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°ã‚’ãƒã‚§ãƒƒã‚¯ã—ã€ã‚¨ãƒ³ã‚³ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°è¡Œã‚’追加ã—ã¾ã™ -Comment[kk]=Python файлын Ñақтағанда текÑеру және код жолын қоÑу -Comment[km]=ážážŽáŸˆáž–áŸáž›â€‹ážšáž€áŸ’សាទុក​ការ​ážáŸ’ážšáž½ážáž–áž·áž“áž·ážáŸ’យ​កា​រអ៊ិនកូដ​របស់​ឯកសារ python និ​ងបន្ážáŸ‚ម​បន្ទាážáŸ‹â€‹áž¢áŸŠáž·áž“កូដ -Comment[kn]=ಉಳಿಸà³à²µà²¾à²— ಪೈಥಾನೠಕಡತಗಳ ಸಂಕೇತೀಕರಣವನà³à²¨à³ (ಎಂಕೋಡಿಂಗà³) ಪರಿಶೀಲಿಸಿ, ಸಂಕೇತೀಕರಣ ಸಾಲನà³à²¨à³ ಸೇರಿಸೠ-Comment[ko]=파ì´ì¬ 파ì¼ì„ 저장할 ë•Œ ì¸ì½”ë”©ì„ ê²€ì‚¬í•˜ì—¬ ì¸ì½”딩 줄 추가하기 -Comment[ku]=Demê tomar kirinê de kod kirina pelên python kontrol bike û rêzekê kod kirinê lê zêde bike -Comment[lt]=Ä®raÅ¡ant python failus patikrinti koduotÄ™ ir pridÄ—ti koduotÄ—s eilutÄ™ -Comment[lv]=SaglabÄjot pÄrbauda kodÄ“jumu python failiem un pievieno kodÄ“juma rindu -Comment[mai]=सहेजबाक काले पाà¤à¤¥à¤¨à¤• à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग जाà¤à¤šà¥‚ आओर कोनो à¤à¤¨à¤•à¥‹à¤¡à¤¿à¤‚ग फाइलकेठजोड़ू -Comment[ml]=സൂകàµà´·à´¿à´¯àµà´•àµà´•àµà´®àµà´ªàµ‹à´³àµâ€ പൈതàµà´¤à´£àµâ€ ഫയലàµà´•à´³àµà´Ÿàµ† à´Žà´¨àµâ€à´•àµ‹à´¡à´¿à´™àµà´™àµ പരിശോദിയàµà´•àµà´•àµà´•à´¯àµà´‚ à´Žà´¨àµâ€à´•àµ‹à´¡à´¿à´™àµà´™àµ വരി ചേരàµâ€à´•àµà´•àµà´•à´¯àµà´‚ ചെയàµà´¯àµà´• -Comment[ms]=Semasa menyimpan, periksa enkod fail Phyton dan tambah baris pengenkodan -Comment[nb]=Under lagring sjekkes tegnkodingen i Python-filer og en tegnkodingslinje legges inn -Comment[nds]=Bi't Sekern de Koderen vun Python-Dateien pröven un en Koderen-Reeg tofögen -Comment[nl]=Tijdens het opslaan, controleer de codering van python-bestanden en voeg een coderegel toe -Comment[nn]=Sjekk kodinga av Python-filer og legg til ei teiknkodingslinje ved lagring -Comment[pa]=ਸੰਭਾਲਣ ਦੌਰਾਨ, ਪਾਈਥਨ ਫਾਇਲਾਂ ਦੀ ਇੰਕੋਡਿੰਗ ਚੈੱਕ ਕਰੋ ਅਤੇ ਇੱਕ ਇੰਕੋਡਿੰਗ ਲਾਈਨ ਸ਼ਾਮਲ ਕਰੋ -Comment[pl]=Podczas zapisywania sprawdza kodowanie plików Pythona i dodaje wiersz z kodowaniem -Comment[pt]=Ao gravar, verifica a codificação dos ficheiros em Python e adiciona uma linha de codificação -Comment[pt_BR]=Ao salvar, verifica a codificação dos arquivos em python e adiciona uma linha de codificação -Comment[ro]=Verifică codarea fiÈ™ierelor python în timpul salvării È™i adaugă o linie de codare -Comment[ru]=Проверка кодировки при Ñохранении файла иÑходного кода на Python и вÑтавка кодировки в текÑÑ‚ -Comment[se]=Vurkedettiin pythonfiillaid, iskka kodema ja lasit kodenlinnjá -Comment[sk]=Pri ukladaní kontroluje kódovanie súborov pythonu a pridáva riadok kódovania -Comment[sl]=Med shranjevanje datotek pythona preveri kodiranje in doda kodno vrstico -Comment[sr]=При упиÑивању питонÑких фајлова проверава и додаје ред о кодирању -Comment[sr@ijekavian]=При упиÑивању питонÑких фајлова провјерава и додаје ред о кодирању -Comment[sr@ijekavianlatin]=Pri upisivanju Python fajlova provjerava i dodaje red o kodiranju -Comment[sr@latin]=Pri upisivanju Python fajlova proverava i dodaje red o kodiranju -Comment[sv]=När Python-filer sparas, kontrollera kodning och lägg till en kodningsrad -Comment[ta]=பைதான௠கோபà¯à®ªà¯à®•à®³à®¿à®©à¯ எழà¯à®¤à¯à®¤à¯à®°à¯à®µà®¾à®•à¯à®•à®®à¯ எனà¯à®©à®µà¯†à®© சோதிதà¯à®¤à¯ எழà¯à®¤à¯à®¤à¯à®°à¯à®µà®¾à®•à¯à®• வரியொனà¯à®±à¯ˆ உளà¯à®³à®¿à®Ÿà¯à®• -Comment[tg]=Ҳангоми захиракунӣ, рамзгузории файлҳои python-ро тафтиш кунед ва хати рамзгузориро илова диҳед -Comment[th]=ระหว่างà¸à¸²à¸£à¸šà¸±à¸™à¸—ึภตรวจสอบชุดรหัสอัà¸à¸‚ระของà¹à¸Ÿà¹‰à¸¡à¹„พธอน à¹à¸¥à¸°à¹€à¸žà¸´à¹ˆà¸¡à¸šà¸£à¸£à¸—ัดระบุชุดรหัสอัà¸à¸‚ระ -Comment[tr]=Python dosyalarını kaydederken karakter kodlamalarını denetle ve bir kodlama satırı ekle -Comment[uk]=Під Ñ‡Ð°Ñ Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÑÑ” ÐºÐ¾Ð´ÑƒÐ²Ð°Ð½Ð½Ñ Ñ„Ð°Ð¹Ð»Ñ–Ð² на python Ñ– додає Ñ€Ñдок ÐºÐ¾Ð´ÑƒÐ²Ð°Ð½Ð½Ñ -Comment[x-test]=xxWhile saving check encoding of python files and add an encoding linexx -Comment[zh_CN]=当ä¿å­˜ python 文件时,å¯ä»¥è‡ªåŠ¨æ£€æŸ¥å…¶ç¼–ç å¹¶æŒ‰éœ€æ·»åŠ ç¼–ç è¡Œ -Comment[zh_TW]=儲存時檢查 python 檔案的編碼,並加入編碼行 diff --git a/part/plugins/pythonencoding/python_encoding.cpp b/part/plugins/pythonencoding/python_encoding.cpp deleted file mode 100644 index 6fc3090..0000000 --- a/part/plugins/pythonencoding/python_encoding.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001,2006 Joseph Wenninger - [katedocument.cpp, LGPL v2 only] - -================RELICENSED================= - - This file is part of the KDE libraries - Copyright (C) 2008 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN includes -#include "python_encoding.h" -#include "python_encoding.moc" -#include -#include -#include -//END includes - -K_PLUGIN_FACTORY( KTextEditorPythonEncodingFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( KTextEditorPythonEncodingFactory( KAboutData( "ktexteditor_python-encoding", "ktexteditor_plugins", ki18n("PythonEncoding"), "0.1", ki18n("Python Encoding check"), KAboutData::License_LGPL_V2 ) ) ) - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/pythonencoding/python_encoding.h b/part/plugins/pythonencoding/python_encoding.h deleted file mode 100644 index 0f006d1..0000000 --- a/part/plugins/pythonencoding/python_encoding.h +++ /dev/null @@ -1,98 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001,2006 Joseph Wenninger - [katedocument.cpp, LGPL v2 only] - -================RELICENSED================= - - This file is part of the KDE libraries - Copyright (C) 2008 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KTEXTEDITOR_PYTHON_ENCODING -#define KTEXTEDITOR_PYTHON_ENCODING - -#include -#include -#include -#include -#include -#include - -class KTextEditorPythonEncodingCheck: public KTextEditor::LoadSaveFilterCheckPlugin { - Q_OBJECT - public: - KTextEditorPythonEncodingCheck(QObject *parent, QList):KTextEditor::LoadSaveFilterCheckPlugin(parent){interpreterLine=QRegExp(QString("#!.*$"));} - virtual ~KTextEditorPythonEncodingCheck(){} - virtual bool postSaveFilterCheck(KTextEditor::Document */*document*/,bool /*saveas*/) {return true;} - virtual bool preSavePostDialogFilterCheck(KTextEditor::Document *document) - { - kDebug(13020); - //QString codec=document->config()->codec()->name().toLower(); - QString codec=document->encoding().toLower(); - codec.replace(' ','-'); -// "#\s*-\*\-\s*coding[:=]\s*([-\w.]+)\s*-\*-\s*$" - bool firstIsInterpreter=false; - QRegExp encoding_regex(QString("#\\s*-\\*-\\s*coding[:=]\\s*%1").arg(codec)); - bool correctencoding=false; - if (document->lines()>0) - { - if (encoding_regex.indexIn(document->line(0)) != -1) correctencoding=true; - else if (document->lines()>1) { - if (interpreterLine.exactMatch(document->line(0))) - { - firstIsInterpreter=true; - if (encoding_regex.indexIn(document->line(1)) != -1) correctencoding=true; - } - } - } - if (!correctencoding) { - QString addLine(QString("# -*- coding: %1 -*-").arg(codec)); - int what=KMessageBox::warningYesNoCancel (document->activeView() - , i18n ("You are trying to save a python file as non ASCII, without specifiying a correct source encoding line for encoding \"%1\"", codec) - , i18n ("No encoding header") - , KGuiItem(i18n("Insert: %1",addLine)) - , KGuiItem(i18n("Save Nevertheless")) - , KStandardGuiItem::cancel(), "OnSave-WrongPythonEncodingHeader"); - switch (what) { - case KMessageBox::Yes: - { - int line=firstIsInterpreter?1:0; - QRegExp checkReplace_regex(QString("#\\s*-\\*-\\s*coding[:=]\\s*[-\\w]+\\s*-\\*-\\s*$")); - if (checkReplace_regex.exactMatch(document->line(line))) - document->removeLine(line); - document->insertLine(line,addLine); - break; - } - case KMessageBox::No: - return true; - break; - default: - return false; - break; - } - } - return true; - } - virtual void postLoadFilter(KTextEditor::Document*){ } - private: - QRegExp interpreterLine; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/plugins/timedate/CMakeLists.txt b/part/plugins/timedate/CMakeLists.txt deleted file mode 100644 index 5585005..0000000 --- a/part/plugins/timedate/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ - -########### next target ############### - -set(ktexteditor_timedate_PART_SRCS timedate.cpp timedate_config.cpp ) - -kde4_add_plugin(ktexteditor_timedate ${ktexteditor_timedate_PART_SRCS} ) - -target_link_libraries(ktexteditor_timedate ${KDE4_KDECORE_LIBS} ktexteditor ) - -install(TARGETS ktexteditor_timedate DESTINATION ${PLUGIN_INSTALL_DIR} ) - -########### install files ############### - -install(FILES timedateui.rc DESTINATION ${DATA_INSTALL_DIR}/ktexteditor_timedate ) - -install(FILES ktexteditor_timedate.desktop - ktexteditor_timedate_config.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) diff --git a/part/plugins/timedate/ktexteditor_timedate.desktop b/part/plugins/timedate/ktexteditor_timedate.desktop deleted file mode 100644 index 78478fb..0000000 --- a/part/plugins/timedate/ktexteditor_timedate.desktop +++ /dev/null @@ -1,187 +0,0 @@ -[Desktop Entry] -X-KDE-Library=ktexteditor_timedate -X-KDE-PluginKeyword=ktexteditor_timedate -X-KDE-PluginInfo-Author=Rafael Fernández López -X-KDE-PluginInfo-Email=ereslibre@kde.org -X-KDE-PluginInfo-Name=ktexteditortimedate -X-KDE-PluginInfo-Version=0.1 -X-KDE-PluginInfo-Website=http://kate.kde.org -X-KDE-PluginInfo-Category=Editor -X-KDE-PluginInfo-Depends= -X-KDE-PluginInfo-License=GPL -X-KDE-PluginInfo-EnabledByDefault=false -X-KDE-ParentApp=kate -X-KDE-Version=4.0 -X-KDE-ServiceTypes=KTextEditor/Plugin -Type=Service -Icon=office-calendar -Name=Time & Date -Name[af]=Tyd en Datum -Name[ar]=الوقت والتاريخ -Name[as]=সময় & দিন -Name[ast]=Hora y Data -Name[be@latin]=ÄŒas i data -Name[bg]=Време и дата -Name[bn]=সময় ও তারিখ -Name[bn_IN]=সময় ও তারিখ -Name[br]=Deiziad hag eur -Name[ca]=Data i hora -Name[ca@valencia]=Data i hora -Name[cs]=Datum a Äas -Name[csb]=Czas ë datum -Name[da]=Tid & dato -Name[de]=Uhrzeit & Datum -Name[el]=ÎÏα & ημεÏομηνία -Name[en_GB]=Time & Date -Name[eo]=Tempo kaj dato -Name[es]=Hora y fecha -Name[et]=Kuupäev ja kellaaeg -Name[eu]=Ordua eta data -Name[fa]=زمان Ùˆ تاریخ -Name[fi]=Aika ja päiväys -Name[fr]=Heure & Date -Name[fy]=Tiid & Datum -Name[ga]=Am agus Dáta -Name[gl]=Data e hora -Name[gu]=સમય & તારીખ -Name[he]=ת×ריך ושעה -Name[hi]=समय व तिथि -Name[hne]=समय व तारीक -Name[hr]=Vrijeme & Datum -Name[hsb]=ÄŒas a datum -Name[hu]=Dátum és idÅ‘ -Name[hy]=ÔºÕ¡Õ´ Ö‡ Ô±Õ´Õ½Õ¡Õ©Õ«Õ¾ -Name[ia]=Tempore e Data -Name[id]=Waktu & Tanggal -Name[is]=Tími og dagsetning -Name[it]=Data e ora -Name[ja]=日付ã¨æ™‚刻 -Name[kk]=Уақыт пен күн -Name[km]=áž–áŸáž›ážœáŸáž›áž¶ និង​កាលបរិច្ឆáŸáž‘ -Name[kn]=ಸಮಯ ಮತà³à²¤à³ ದಿನಾಂಕ -Name[ko]=시간과 날짜 -Name[ku]=Dem & Dîrok -Name[lt]=Laikas ir data -Name[lv]=Laiks un datums -Name[mai]=समय आ तिथि -Name[mk]=Датум и време -Name[ml]=സമയവàµà´‚ തിയàµà´¯à´¤à´¿à´¯àµà´‚ -Name[mr]=वेळ व दिनांक -Name[ms]=Masa & Tarikh -Name[nb]=Dato og klokkeslett -Name[nds]=Datum un Tiet -Name[ne]=समय र मिति -Name[nl]=Datum & tijd -Name[nn]=Dato og klokkeslett -Name[or]=Time & Date -Name[pa]=ਟਾਇਮ ਅਤੇ ਮਿਤੀ -Name[pl]=Czas i data -Name[ps]=Ù†Ûټه او مهال -Name[pt]=Hora & Data -Name[pt_BR]=Data e hora -Name[ro]=Oră È™i dată -Name[ru]=Дата и Ð²Ñ€ÐµÐ¼Ñ -Name[se]=Dáhton ja áigi -Name[si]=දිනය සහ වේලà·à·€ -Name[sk]=Dátum a Äas -Name[sl]=ÄŒas in datum -Name[sr]=Време и датум -Name[sr@ijekavian]=Вријеме и датум -Name[sr@ijekavianlatin]=Vrijeme i datum -Name[sr@latin]=Vreme i datum -Name[sv]=Tid och datum -Name[ta]=நேரமà¯à®®à¯ & தேதியà¯à®®à¯ -Name[tg]=Вақт ва Ñана -Name[th]=เวลาà¹à¸¥à¸°à¸§à¸±à¸™ -Name[tr]=Saat ve Tarih -Name[uk]=Ð§Ð°Ñ Ñ– дата -Name[uz]=Vaqt va sana -Name[uz@cyrillic]=Вақт ва Ñана -Name[wa]=Date et eure -Name[x-test]=xxTime & Datexx -Name[zh_CN]=时间和日期 -Name[zh_TW]=時間與日期 -Comment=Insert current Time & Date -Comment[af]=Voeg tyd en datum in -Comment[ar]=أدرج الوقت والتاريخ الحاليين -Comment[as]=বৰà§à¦¤à§à¦¤à¦®à¦¾à¦¨à§° সময় & দিন ভৰাওক -Comment[ast]=Inxertar la hora y data actual -Comment[be@latin]=UstaÅ­laje ciapieraÅ¡ni Äas i datu -Comment[bg]=Вмъкване на време и дата -Comment[bn]=বরà§à¦¤à¦®à¦¾à¦¨ সময় ও তারিখ ঢোকাও -Comment[bn_IN]=বরà§à¦¤à¦®à¦¾à¦¨ সময় ও তারিখ সনà§à¦¨à¦¿à¦¬à§‡à¦¶ করা হবে -Comment[ca]=Insereix la data i l'hora actual -Comment[ca@valencia]=Insereix la data i l'hora actual -Comment[cs]=Vložit aktuální datum a Äas -Comment[csb]=Wpiszë biéżny datum ë czas -Comment[da]=Indsæt nuværende tid & dato -Comment[de]=Einfügen von Uhrzeit & Datum -Comment[el]=Εισαγωγή Ï„Ïέχουσας ÏŽÏας & ημεÏομηνίας -Comment[en_GB]=Insert current Time & Date -Comment[eo]=Enmeti nunan tempon kaj daton -Comment[es]=Insertar hora y fecha actuales -Comment[et]=Praeguse kellaaja ja kuupäeva lisamine -Comment[eu]=Sartu uneko ordua eta data -Comment[fa]=درج زمان Ùˆ تارخ جاری -Comment[fi]=Lisää aika ja päiväys -Comment[fr]=Ajouter l'heure et la date actuelle -Comment[fy]=Hjoeddeiske datum en tijd ynfoegje -Comment[ga]=Ionsáigh an tAm agus an Dáta reatha -Comment[gl]=Insire a data e hora actuais -Comment[gu]=હાલનો સમય & તારીખ ઉમેરો -Comment[he]=הוספת הת×ריך והשעה ×”× ×•×›×—×™×™× -Comment[hi]=वरà¥à¤¤à¤®à¤¾à¤¨ समय व तिथि पà¥à¤°à¤µà¤¿à¤·à¥à¤Ÿ करें -Comment[hne]=अभी हाल के समय व तारीक भरव -Comment[hr]=Unesi trenutno vrijeme & datum -Comment[hsb]=Zasunje aktualny Äas a datum -Comment[hu]=Az aktuális dátum és idÅ‘ beszúrása -Comment[hy]=Õ„Õ¿ÖÖ€Õ¥Ö„ Õ¨Õ¶Õ©Õ¡ÖÕ«Ö„ ÔºÕ¡Õ´Õ¨ Ö‡ Ô±Õ´Õ½Õ¡Õ©Õ«Õ¾Õ¨ -Comment[ia]=Insertar le Tempore e le data currente -Comment[id]=Masukkan Waktu & Tanggal saat ini -Comment[is]=Setja inn núverandi tíma- og dagsetningu -Comment[it]=Inserisce la data e ora attuali -Comment[ja]=ç¾åœ¨ã®æ—¥ä»˜ã¨æ™‚刻を挿入 -Comment[kk]=Уақыт пен күн белгіÑін қою -Comment[km]=បញ្ចូល​ពáŸáž›ážœáŸáž›áž¶ និង​កាលបរិច្ឆáŸáž‘​បច្ចុប្បន្ន -Comment[kn]=ಪà³à²°à²¸à³à²¤à³à²¤ ಸಮಯ ಮತà³à²¤à³ ಮತà³à²¤à³ ದಿನಾಂಕವನà³à²¨à³ ಒಳಸೇರಿಸೠ-Comment[ko]=현재 시간과 날짜를 삽입합니다 -Comment[ku]=Dem & Dîroka heyî pê ve bike -Comment[lt]=Ä®terpti dabartinį laikÄ… ir datÄ… -Comment[lv]=Ievieto paÅ¡reizÄ“jo laiku un datumu -Comment[mai]=वरà¥à¤¤à¤®à¤¾à¤¨ समय आ तिथि पà¥à¤°à¤µà¤¿à¤·à¥à¤Ÿ करू -Comment[mk]=Ги вметнува тековните датум и време -Comment[ml]=ഇപàµà´ªàµ‹à´´àµà´³àµà´³ സമയവàµà´‚ തിയàµà´¯à´¤à´¿à´¯àµà´‚ ചേരàµâ€à´•àµà´•àµà´• -Comment[mr]=वेळ व दिनांक दाखल करा -Comment[ms]=Masukkan Masa & Tarikh semasa -Comment[nb]=Sett inn nÃ¥værende dato og klokkeslett -Comment[nds]=Aktuell Datum un Tiet infögen -Comment[ne]=हालको समय र मिति घà¥à¤¸à¤¾à¤‰à¤¨à¥à¤¹à¥‹à¤¸à¥ -Comment[nl]=Huidige datum en tijd invoegen -Comment[nn]=Set inn gjeldande dato og klokkeslett -Comment[or]=Insert current Time & Date -Comment[pa]=ਮੌਜੂਦਾ ਟਾਇਮ ਅਤੇ ਮਿਤੀ ਸ਼ਾਮਲ ਕਰੋ -Comment[pl]=Wstawia bieżący czas i datÄ™ -Comment[ps]=Ø§ÙˆØ³Ù†Û Ù†Ûټه او مهال ورننويستل -Comment[pt]=Inserir a Data & Hora actual -Comment[pt_BR]=Inserir a data e hora atual -Comment[ro]=Inserează timpul È™i data curentă -Comment[ru]=Ð’Ñтавка текущей даты и времени -Comment[se]=Bija sisa dálá dáhtona ja áiggi -Comment[sk]=Vloží aktuálny dátum a Äas -Comment[sl]=Vstavi trenuten Äas in datum -Comment[sr]=Умеће тренутно време и датум -Comment[sr@ijekavian]=Умеће тренутно вријеме и датум -Comment[sr@ijekavianlatin]=Umeće trenutno vrijeme i datum -Comment[sr@latin]=Umeće trenutno vreme i datum -Comment[sv]=Infoga aktuell tid och datum -Comment[ta]=தறà¯à®ªà¯‹à®¤à¯ˆà®¯ நேரதà¯à®¤à®¿à®©à¯ˆà®¯à¯à®®à¯ தேதியினையà¯à®®à¯ நà¯à®´à¯ˆà®•à¯à®•à®µà¯à®®à¯ -Comment[tg]=Вориди вақт ва Ñанаи ҷорӣ -Comment[th]=à¹à¸—รà¸à¹€à¸§à¸¥à¸²à¹à¸¥à¸°à¸§à¸±à¸™ -Comment[tr]=Geçerli Saat ve Tarihi Ekle -Comment[uk]=Ð’Ñтавити поточний Ñ‡Ð°Ñ Ñ– дату -Comment[uz]=Joriy sana va vaqtni qoÊ»yish -Comment[uz@cyrillic]=Жорий Ñана ва вақтни қўйиш -Comment[wa]=Sititchî l' date et eure do moumint -Comment[x-test]=xxInsert current Time & Datexx -Comment[zh_CN]=æ’入当å‰æ—¶é—´å’Œæ—¥æœŸ -Comment[zh_TW]=æ’入目å‰çš„時間與日期 diff --git a/part/plugins/timedate/ktexteditor_timedate_config.desktop b/part/plugins/timedate/ktexteditor_timedate_config.desktop deleted file mode 100644 index 67810b0..0000000 --- a/part/plugins/timedate/ktexteditor_timedate_config.desktop +++ /dev/null @@ -1,87 +0,0 @@ -[Desktop Entry] -Type=Service -X-KDE-ServiceTypes=KCModule -X-KDE-Library=ktexteditor_timedate -X-KDE-PluginKeyword=ktexteditor_timedate_config -X-KDE-ParentComponents=ktexteditortimedate -Name=Format of Time & Date insertion -Name[af]=Formaat van tyd en datum invoeging -Name[ar]=تنسيق كيÙية إدخال الوقت والتاريخ -Name[as]=সময় & দিন ভৰà§à§±à¦¾à§° আকৃতি -Name[ast]=Formatu d'inxertu de la hora y data -Name[be@latin]=Farmat ustaÅ­lanaha Äasu j daty -Name[bg]=Формат на време и дата -Name[bn]=সময় ও তারিখ ঢোকানোর ফরà§à¦®à§à¦¯à¦¾à¦Ÿ -Name[bn_IN]=সময় ও তারিখ সনà§à¦¨à¦¿à¦¬à§‡à¦¶à§‡à¦° বিনà§à¦¯à¦¾à¦¸ -Name[ca]=Format d'inserció de la data i l'hora -Name[ca@valencia]=Format d'inserció de la data i l'hora -Name[cs]=Formát vložení data a Äasu -Name[csb]=Fòrmat wprowadzaniô czasu ë datuma -Name[da]=Format for indsættelse af tid & dato -Name[de]=Format für das Einfügen von Uhrzeit & Datum -Name[el]=ΜοÏφή εισαγωγής ÏŽÏας & ημεÏομηνίας -Name[en_GB]=Format of Time & Date insertion -Name[eo]=AranÄo de la tempa kaj data enmeto -Name[es]=Formato de la inserción de hora y fecha -Name[et]=Kellaaja ja kuupäeva lisamise vorming -Name[eu]=Ordua eta dataren formatua -Name[fa]=قالب درج زمان Ùˆ تاریخ -Name[fi]=Ajan ja päiväyksen muoto -Name[fr]=Format de la date et de l'heure -Name[fy]=Opmaak fan ynfoegde tiid en datum -Name[ga]=Formáid Ionsáite Ama agus Dáta -Name[gl]=Formato da data e hora inseridas -Name[gu]=સમય & તારીખ ઉમેરાનà«àª‚ બંધારણ -Name[he]=הגדרות תבנית הת×ריך והשעה ×”×ž×•×¡×¤×™× -Name[hi]=समय व तिथि भरने का फ़ॉरà¥à¤®à¥‡à¤Ÿ -Name[hne]=समय व तारीक भरे के फारमेट -Name[hr]=Format vremena & Unos datuma -Name[hsb]=Format Äasa a datuma, kiž so zasunjetej -Name[hu]=A beszúrt dátum és idÅ‘ formátuma -Name[ia]=Insertion de le formato de tempore e data -Name[id]=Format masukan Waktu & Tanggal -Name[is]=Snið innskotins tíma- og dagsetningar -Name[it]=Inserimento del formato data e ora -Name[ja]=挿入ã™ã‚‹æ—¥ä»˜ã¨æ™‚刻ã®ãƒ•ã‚©ãƒ¼ãƒžãƒƒãƒˆ -Name[kk]=Уақыт пен күннің қойылатын пішімі -Name[km]=ទ្រង់ទ្រាយ​នៃ​ការ​បញ្ចូល​ពáŸáž›ážœáŸáž›áž¶ និង​កាលបរិច្ឆáŸáž‘ -Name[kn]=ಸಮಯ ಮತà³à²¤à³ ದಿನಾಂಕ ಒಳಸೇರಿಸà³à²µà²¿à²•à³†à²¯ ಶೈಲಿ -Name[ko]=날짜 ë° ì‹œê°„ 삽입 í˜•ì‹ -Name[ku]=TeÅŸe ya pê ve kirina Dem & Dîrok -Name[lt]=Ä®terpiamos datos ir laiko formatas -Name[lv]=Laika un datuma ievietoÅ¡anas formÄts -Name[mai]=समय आ तिथि भरबाक पà¥à¤°à¤¾à¤°à¥‚प -Name[mk]=Формат на вметнатите датум и време -Name[ml]=സമയവàµà´‚ തിയàµà´¯à´¤à´¿à´¯àµà´‚ ചേരàµâ€à´•àµà´•àµà´¨àµà´¨à´¤à´¿à´¨àµà´±àµ† ഫോരàµâ€à´®à´¾à´±àµà´±àµ -Name[mr]=वेळ व दिनांक सà¥à¤µà¤°à¥à¤ªà¤¨à¤šà¥‡ पà¥à¤°à¤¾à¤°à¥‚प -Name[ms]=Pemasukkan format Masa & Tarikh -Name[nb]=Format for innsatt dato og klokkeslett -Name[nds]=Formaat för inföögt Datum un Tiet -Name[ne]=घà¥à¤¸à¤¾à¤‡à¤¨à¥‡ समय र मितिको ढाà¤à¤šà¤¾ -Name[nl]=Opmaak van ingevoegde datum en tijd -Name[nn]=Format for innsett dato og klokkeslett -Name[or]=Format of Time & Date insertion -Name[pa]=ਟਾਇਮ ਅਤੇ ਮਿਤੀ ਸ਼ਾਮਲ ਕਰਨ ਲਈ ਫਾਰਮੈਟ -Name[pl]=Format wstawianego czasu i daty -Name[ps]=د Ù†ÛÙ¼Û Ø§Ùˆ مهال د ورننويستلو بڼه -Name[pt]=Formato da inserção da Data & Hora -Name[pt_BR]=Formato da inserção da data e hora -Name[ro]=Formatul de inserare a timpului È™i datei -Name[ru]=Формат даты и времени -Name[se]=Sisabidjon áiggi ja dáhtona formáhtta -Name[sk]=Formát vloženia dátumu a Äasu -Name[sl]=Oblika vstavljenega Äasa in datuma -Name[sr]=Формат уметања времена и датума -Name[sr@ijekavian]=Формат уметања времена и датума -Name[sr@ijekavianlatin]=Format umetanja vremena i datuma -Name[sr@latin]=Format umetanja vremena i datuma -Name[sv]=Format för att infoga tid och datum -Name[ta]=நேரம௠& தேதியை நà¯à®´à¯ˆà®ªà¯à®ªà®¤à®±à¯à®•à®¾à®© à®®à¯à®±à¯ˆ -Name[tg]=Ðамуди вақт ва вориди Ñана -Name[th]=รูปà¹à¸šà¸šà¸‚องà¸à¸²à¸£à¹à¸—รà¸à¹€à¸§à¸¥à¸²à¹à¸¥à¸°à¸§à¸±à¸™ -Name[tr]=Saat ve Tarih Ekleme biçimi -Name[uk]=Формат чаÑу Ñ– дати Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð½Ñ -Name[wa]=Cogne pol date et l' eure -Name[x-test]=xxFormat of Time & Date insertionxx -Name[zh_CN]=æ’å…¥çš„æ—¶é—´å’Œæ—¥æœŸçš„æ ¼å¼ -Name[zh_TW]=æ’å…¥æ™‚é–“èˆ‡æ—¥æœŸçš„æ ¼å¼ diff --git a/part/plugins/timedate/timedate.cpp b/part/plugins/timedate/timedate.cpp deleted file mode 100644 index 67fbbee..0000000 --- a/part/plugins/timedate/timedate.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2007 Rafael Fernández López - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "timedate.h" -#include "timedate_config.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -TimeDatePlugin *TimeDatePlugin::plugin = 0; - -K_PLUGIN_FACTORY_DEFINITION(TimeDatePluginFactory, - registerPlugin("ktexteditor_timedate"); - registerPlugin("ktexteditor_timedate_config"); - ) -K_EXPORT_PLUGIN(TimeDatePluginFactory("ktexteditor_timedate", "ktexteditor_plugins")) - -TimeDatePlugin::TimeDatePlugin(QObject *parent, const QVariantList &args) - : KTextEditor::Plugin(parent) -{ - Q_UNUSED(args); - - if (localizedTimeDate.isNull()) - { - localizedTimeDate = i18nc("This is a localized string for default time & date printing on kate document." - "%d means day in XX format." - "%m means month in XX format." - "%Y means year in XXXX format." - "%H means hours in XX format." - "%M means minutes in XX format." - "Please, if in your language time or date is written in a different order, change it here", - "%d-%m-%Y %H:%M"); - } - - plugin = this; - readConfig(); -} - -TimeDatePlugin::~TimeDatePlugin() -{ - plugin = 0; -} - -void TimeDatePlugin::addView(KTextEditor::View *view) -{ - TimeDatePluginView *nview = new TimeDatePluginView(m_string, view); - m_views.append(nview); -} - -void TimeDatePlugin::removeView(KTextEditor::View *view) -{ - for (int z = 0; z < m_views.size(); z++) - { - if (m_views.at(z)->parentClient() == view) - { - TimeDatePluginView *nview = m_views.at(z); - m_views.removeAll(nview); - delete nview; - } - } -} - -void TimeDatePlugin::readConfig() -{ - KConfigGroup cg(KGlobal::config(), "TimeDate Plugin"); - m_string = cg.readEntry("string", localizedTimeDate); -} - -void TimeDatePlugin::writeConfig() -{ - KConfigGroup cg(KGlobal::config(), "TimeDate Plugin" ); - cg.writeEntry("string", m_string ); -} - -void TimeDatePlugin::setFormat(const QString &format) -{ - m_string = format; - - // If the property has been set for the plugin in general, let's set that - // property to that value on all views where the plugin has been loaded. - foreach (TimeDatePluginView *pluginView, m_views) - { - pluginView->setFormat(format); - } -} - -QString TimeDatePlugin::format() const -{ - return m_string; -} - -TimeDatePluginView::TimeDatePluginView(const QString &string, - KTextEditor::View *view) - : QObject(view) - , KXMLGUIClient(view) - , m_view(view) - , m_string(string) -{ - setComponentData(TimeDatePluginFactory::componentData()); - - KAction *action = new KAction(i18n("Insert Time && Date"), this); - actionCollection()->addAction("tools_insert_timedate", action); - action->setShortcut(Qt::CTRL + Qt::Key_D); - connect(action, SIGNAL(triggered()), this, SLOT(slotInsertTimeDate())); - - setXMLFile("timedateui.rc"); -} - -TimeDatePluginView::~TimeDatePluginView() -{ -} - -void TimeDatePluginView::setFormat(const QString &format) -{ - m_string = format; -} - -QString TimeDatePluginView::format() const -{ - return m_string; -} - -void TimeDatePluginView::slotInsertTimeDate() -{ - KDateTime dt(QDateTime::currentDateTime()); - m_view->document()->insertText(m_view->cursorPosition(), dt.toString(m_string)); -} - -#include "timedate.moc" diff --git a/part/plugins/timedate/timedate.h b/part/plugins/timedate/timedate.h deleted file mode 100644 index 63bf51b..0000000 --- a/part/plugins/timedate/timedate.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2007 Rafael Fernández López - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef TIMEDATE_H -#define TIMEDATE_H - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -static QString localizedTimeDate; - -class TimeDatePlugin - : public KTextEditor::Plugin -{ - public: - explicit TimeDatePlugin(QObject *parent = 0, - const QVariantList &args = QVariantList()); - virtual ~TimeDatePlugin(); - - static TimeDatePlugin *self() { return plugin; } - - void addView (KTextEditor::View *view); - void removeView (KTextEditor::View *view); - - void readConfig(); - void writeConfig(); - - virtual void readConfig (KConfig *) {} - virtual void writeConfig (KConfig *) {} - - void setFormat(const QString &format); - QString format() const; - - private: - static TimeDatePlugin *plugin; - QList m_views; - QString m_string; -}; - -class TimeDatePluginView - : public QObject, public KXMLGUIClient -{ - Q_OBJECT - - public: - explicit TimeDatePluginView(const QString &string, - KTextEditor::View *view = 0); - ~TimeDatePluginView(); - - void setFormat(const QString &format); - QString format() const; - - private Q_SLOTS: - void slotInsertTimeDate(); - - private: - KTextEditor::View *m_view; - QString m_string; -}; - -K_PLUGIN_FACTORY_DECLARATION(TimeDatePluginFactory) - -#endif // TIMEDATE_H diff --git a/part/plugins/timedate/timedate_config.cpp b/part/plugins/timedate/timedate_config.cpp deleted file mode 100644 index b4235e2..0000000 --- a/part/plugins/timedate/timedate_config.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2007 Rafael Fernández López - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "timedate_config.h" -#include "timedate.h" - -#include -#include - -#include -#include -#include -#include -#include - -TimeDateConfig::TimeDateConfig(QWidget *parent, const QVariantList &args) - : KCModule(TimeDatePluginFactory::componentData(), parent, args) -{ - QVBoxLayout *layout = new QVBoxLayout(this); - - QLabel *info = new QLabel(i18n( - "%y\t2-digit year excluding century (00 - 99)\n" - "%Y\tfull year number\n" - "%:m\tmonth number, without leading zero (1 - 12)\n" - "%m\tmonth number, 2 digits (01 - 12)\n" - "%b\tabbreviated month name\n" - "%B\tfull month name\n" - "%e\tday of the month (1 - 31)\n" - "%d\tday of the month, 2 digits (01 - 31)\n" - "%a\tabbreviated weekday name\n" - "%A\tfull weekday name\n" - "\n" - "%H\thour in the 24 hour clock, 2 digits (00 - 23)\n" - "%k\thour in the 24 hour clock, without leading zero (0 - 23)\n" - "%I\thour in the 12 hour clock, 2 digits (01 - 12)\n" - "%l\thour in the 12 hour clock, without leading zero (1 - 12)\n" - "%M\tminute, 2 digits (00 - 59)\n" - "%S\tseconds (00 - 59)\n" - "%P\t\"am\" or \"pm\"\n" - "%p\t\"AM\" or \"PM\"\n")); - - // It is possible that the plugin has not been loaded yet, and the - // configuration dialog has been asked to be shown. In that case, it is our - // turn to set the static string to the correct value. - if (localizedTimeDate.isNull()) - { - localizedTimeDate = i18nc("This is a localized string for default time & date printing on kate document." - "%d means day in XX format." - "%m means month in XX format." - "%Y means year in XXXX format." - "%H means hours in XX format." - "%M means minutes in XX format." - "Please, if in your language time or date is written in a different order, change it here", - "%d-%m-%Y %H:%M"); - } - - QHBoxLayout *hlayout = new QHBoxLayout(this); - QLabel *lformat = new QLabel(i18n("Format")); - format = new KLineEdit(this); - hlayout->addWidget(lformat); - hlayout->addWidget(format); - - layout->addWidget(info); - layout->addLayout(hlayout); - - setLayout(layout); - - load(); - - QObject::connect(format, SIGNAL(textChanged(QString)), this, SLOT(slotChanged())); -} - -TimeDateConfig::~TimeDateConfig() -{ -} - -void TimeDateConfig::save() -{ - if (TimeDatePlugin::self()) - { - TimeDatePlugin::self()->setFormat(format->text()); - TimeDatePlugin::self()->writeConfig(); - } - else - { - KConfigGroup cg(KGlobal::config(), "TimeDate Plugin"); - cg.writeEntry("string", format->text()); - } - - emit changed(false); -} - -void TimeDateConfig::load() -{ - if (TimeDatePlugin::self()) - { - TimeDatePlugin::self()->readConfig(); - format->setText(TimeDatePlugin::self()->format()); - } - else - { - KConfigGroup cg(KGlobal::config(), "TimeDate Plugin" ); - format->setText(cg.readEntry("string", localizedTimeDate)); - } - - emit changed(false); -} - -void TimeDateConfig::defaults() -{ - format->setText(localizedTimeDate); - - emit changed(true); -} - -void TimeDateConfig::slotChanged() -{ - emit changed(true); -} - -#include "timedate_config.moc" diff --git a/part/plugins/timedate/timedate_config.h b/part/plugins/timedate/timedate_config.h deleted file mode 100644 index ecd5bd1..0000000 --- a/part/plugins/timedate/timedate_config.h +++ /dev/null @@ -1,47 +0,0 @@ -/** - * This file is part of the KDE libraries - * Copyright (C) 2007 Rafael Fernández López - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef TIMEDATE_CONFIG_H -#define TIMEDATE_CONFIG_H - -#include - -class KLineEdit; - -class TimeDateConfig - : public KCModule -{ - Q_OBJECT - -public: - explicit TimeDateConfig(QWidget *parent = 0, const QVariantList &args = QVariantList()); - virtual ~TimeDateConfig(); - - virtual void save(); - virtual void load(); - virtual void defaults(); - -private Q_SLOTS: - void slotChanged(); - -private: - KLineEdit *format; -}; - -#endif // TIMEDATE_CONFIG_H diff --git a/part/plugins/timedate/timedateui.rc b/part/plugins/timedate/timedateui.rc deleted file mode 100644 index 27a7db1..0000000 --- a/part/plugins/timedate/timedateui.rc +++ /dev/null @@ -1,9 +0,0 @@ - - - - &Tools - - - - - diff --git a/part/render/katelayoutcache.cpp b/part/render/katelayoutcache.cpp deleted file mode 100644 index cc211c7..0000000 --- a/part/render/katelayoutcache.cpp +++ /dev/null @@ -1,549 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005 Hamish Rodda - * Copyright (C) 2008 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katelayoutcache.h" -#include "katelayoutcache.moc" - -#include - -#include "katerenderer.h" -#include "kateview.h" -#include "katedocument.h" -#include "katebuffer.h" - -static bool enableLayoutCache = false; - -//BEGIN KateLineLayoutMap -KateLineLayoutMap::KateLineLayoutMap() -{ -} - -KateLineLayoutMap::~KateLineLayoutMap() -{ -} - -bool lessThan(const KateLineLayoutMap::LineLayoutPair& lhs, - const KateLineLayoutMap::LineLayoutPair& rhs) -{ - return lhs.first < rhs.first; -} - -void KateLineLayoutMap::clear() -{ - m_lineLayouts.clear(); -} - -bool KateLineLayoutMap::contains(int i) const -{ - LineLayoutMap::const_iterator it = - qBinaryFind(m_lineLayouts.constBegin(), m_lineLayouts.constEnd(), LineLayoutPair(i,KateLineLayoutPtr()), lessThan); - return (it != m_lineLayouts.constEnd()); -} - -void KateLineLayoutMap::insert(int realLine, const KateLineLayoutPtr& lineLayoutPtr) -{ - LineLayoutMap::iterator it = - qBinaryFind(m_lineLayouts.begin(), m_lineLayouts.end(), LineLayoutPair(realLine,KateLineLayoutPtr()), lessThan); - if (it != m_lineLayouts.end()) { - (*it).second = lineLayoutPtr; - } else { - it = qUpperBound(m_lineLayouts.begin(), m_lineLayouts.end(), LineLayoutPair(realLine,KateLineLayoutPtr()), lessThan); - m_lineLayouts.insert(it, LineLayoutPair(realLine, lineLayoutPtr)); - } -} - -void KateLineLayoutMap::viewWidthIncreased() -{ - LineLayoutMap::iterator it = m_lineLayouts.begin(); - for ( ; it != m_lineLayouts.end(); ++it) { - if ((*it).second->isValid() && (*it).second->viewLineCount() > 1) - (*it).second->invalidateLayout(); - } -} - -void KateLineLayoutMap::viewWidthDecreased(int newWidth) -{ - LineLayoutMap::iterator it = m_lineLayouts.begin(); - for ( ; it != m_lineLayouts.end(); ++it) { - if ((*it).second->isValid() - && ((*it).second->viewLineCount() > 1 || (*it).second->width() > newWidth)) - (*it).second->invalidateLayout(); - } -} - -void KateLineLayoutMap::relayoutLines(int startRealLine, int endRealLine) -{ - LineLayoutMap::iterator start = - qLowerBound(m_lineLayouts.begin(), m_lineLayouts.end(), LineLayoutPair(startRealLine, KateLineLayoutPtr()), lessThan); - LineLayoutMap::iterator end = - qUpperBound(start, m_lineLayouts.end(), LineLayoutPair(endRealLine, KateLineLayoutPtr()), lessThan); - - while (start != end) { - (*start).second->setLayoutDirty(); - ++start; - } -} - -void KateLineLayoutMap::slotEditDone(int fromLine, int toLine, int shiftAmount) -{ - LineLayoutMap::iterator start = - qLowerBound(m_lineLayouts.begin(), m_lineLayouts.end(), LineLayoutPair(fromLine, KateLineLayoutPtr()), lessThan); - LineLayoutMap::iterator end = - qUpperBound(start, m_lineLayouts.end(), LineLayoutPair(toLine, KateLineLayoutPtr()), lessThan); - LineLayoutMap::iterator it; - - if (shiftAmount != 0) { - for (it = end; it != m_lineLayouts.end(); ++it) { - (*it).first += shiftAmount; - (*it).second->setLine((*it).second->line() + shiftAmount); - } - - for (it = start; it != end; ++it) { - (*it).second->clear(); - } - - m_lineLayouts.erase(start, end); - } else { - for (it = start; it != end; ++it) { - (*it).second->setLayoutDirty(); - } - } -} - - -KateLineLayoutPtr& KateLineLayoutMap::operator[](int i) -{ - LineLayoutMap::iterator it = - qBinaryFind(m_lineLayouts.begin(), m_lineLayouts.end(), LineLayoutPair(i, KateLineLayoutPtr()), lessThan); - return (*it).second; -} -//END KateLineLayoutMap - -KateLayoutCache::KateLayoutCache(KateRenderer* renderer, QObject* parent) - : QObject(parent) - , m_renderer(renderer) - , m_startPos(-1,-1) - , m_viewWidth(0) - , m_wrap(false) - , m_acceptDirtyLayouts (false) -{ - Q_ASSERT(m_renderer); - - /** - * connect to all possible editing primitives - */ - connect(&m_renderer->doc()->buffer(), SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&))); - connect(&m_renderer->doc()->buffer(), SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int))); - connect(&m_renderer->doc()->buffer(), SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &))); - connect(&m_renderer->doc()->buffer(), SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &))); -} - -void KateLayoutCache::updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount, int viewLinesScrolled) -{ - //kDebug( 13033 ) << startPos << " nvlc " << newViewLineCount << " vls " << viewLinesScrolled; - - int oldViewLineCount = m_textLayouts.count(); - if (newViewLineCount == -1) - newViewLineCount = oldViewLineCount; - - enableLayoutCache = true; - - int realLine = m_renderer->doc()->getRealLine(startPos.line()); - int _viewLine = 0; - - if (wrap()) { - // TODO check these assumptions are ok... probably they don't give much speedup anyway? - if (startPos == m_startPos && m_textLayouts.count()) { - _viewLine = m_textLayouts.first().viewLine(); - - } else if (viewLinesScrolled > 0 && viewLinesScrolled < m_textLayouts.count()) { - _viewLine = m_textLayouts[viewLinesScrolled].viewLine(); - - } else { - KateLineLayoutPtr l = line(realLine); - if (l) { - Q_ASSERT(l->isValid()); - Q_ASSERT(l->length() >= startPos.column() || m_renderer->view()->wrapCursor()); - - for (; _viewLine < l->viewLineCount(); ++_viewLine) { - const KateTextLayout& t = l->viewLine(_viewLine); - if (t.startCol() >= startPos.column() || _viewLine == l->viewLineCount() - 1) - goto foundViewLine; - } - - // FIXME FIXME need to calculate past-end-of-line position here... - Q_ASSERT(false); - - foundViewLine: - Q_ASSERT(true); - } - } - } - - m_startPos = startPos; - - // Move the text layouts if we've just scrolled... - if (viewLinesScrolled != 0) { - // loop backwards if we've just scrolled up... - bool forwards = viewLinesScrolled >= 0 ? true : false; - for (int z = forwards ? 0 : m_textLayouts.count() - 1; forwards ? (z < m_textLayouts.count()) : (z >= 0); forwards ? z++ : z--) { - int oldZ = z + viewLinesScrolled; - if (oldZ >= 0 && oldZ < m_textLayouts.count()) - m_textLayouts[z] = m_textLayouts[oldZ]; - } - } - - // Resize functionality - if (newViewLineCount > oldViewLineCount) { - m_textLayouts.reserve(newViewLineCount); - - } else if (newViewLineCount < oldViewLineCount) { - /* FIXME reintroduce... check we're not missing any - int lastLine = m_textLayouts[newSize - 1].line(); - for (int i = oldSize; i < newSize; i++) { - const KateTextLayout& layout = m_textLayouts[i]; - if (layout.line() > lastLine && !layout.viewLine()) - layout.kateLineLayout()->layout()->setCacheEnabled(false); - }*/ - m_textLayouts.resize(newViewLineCount); - } - - KateLineLayoutPtr l = line(realLine); - for (int i = 0; i < newViewLineCount; ++i) { - if (!l) { - if (i < m_textLayouts.count()) { - if (m_textLayouts[i].isValid()) - m_textLayouts[i] = KateTextLayout::invalid(); - } else { - m_textLayouts.append(KateTextLayout::invalid()); - } - continue; - } - - Q_ASSERT(l->isValid()); - Q_ASSERT(_viewLine < l->viewLineCount()); - - if (i < m_textLayouts.count()) { - bool dirty = false; - if (m_textLayouts[i].line() != realLine || m_textLayouts[i].viewLine() != _viewLine || (!m_textLayouts[i].isValid() && l->viewLine(_viewLine).isValid())) - dirty = true; - m_textLayouts[i] = l->viewLine(_viewLine); - if (dirty) - m_textLayouts[i].setDirty(true); - - } else { - m_textLayouts.append(l->viewLine(_viewLine)); - } - - //kDebug( 13033 ) << "Laid out line " << realLine << " (" << l << "), viewLine " << _viewLine << " (" << m_textLayouts[i].kateLineLayout().data() << ")"; - //m_textLayouts[i].debugOutput(); - - _viewLine++; - - if (_viewLine > l->viewLineCount() - 1) { - int virtualLine = l->virtualLine() + 1; - realLine = m_renderer->doc()->getRealLine(virtualLine); - _viewLine = 0; - if (realLine < m_renderer->doc()->lines()) { - l = line(realLine, virtualLine); - } else { - l = 0; - } - } - } - - enableLayoutCache = false; -} - -KateLineLayoutPtr KateLayoutCache::line( int realLine, int virtualLine ) -{ - if (m_lineLayouts.contains(realLine)) { - KateLineLayoutPtr l = m_lineLayouts[realLine]; - - if (virtualLine != -1) - l->setVirtualLine(virtualLine); - - if (!l->isValid()) - { - l->setUsePlainTextLine (acceptDirtyLayouts()); - l->textLine (!acceptDirtyLayouts()); - m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); - } - else if (l->isLayoutDirty() && !acceptDirtyLayouts()) - { - // reset textline - l->setUsePlainTextLine (false); - l->textLine (true); - m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); - } - - Q_ASSERT(l->isValid() && (!l->isLayoutDirty() || acceptDirtyLayouts())); - - return l; - } - - if (realLine < 0 || realLine >= m_renderer->doc()->lines()) - return KateLineLayoutPtr(); - - KateLineLayoutPtr l(new KateLineLayout(m_renderer->doc())); - l->setLine(realLine, virtualLine); - - // Mark it dirty, because it may not have the syntax highlighting applied - // mark this here, to allow layoutLine to use plainLines... - if (acceptDirtyLayouts()) - l->setUsePlainTextLine (true); - - m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache); - Q_ASSERT(l->isValid()); - - if (acceptDirtyLayouts()) - l->setLayoutDirty (true); - - m_lineLayouts.insert(realLine, l); - return l; -} - -KateLineLayoutPtr KateLayoutCache::line( const KTextEditor::Cursor & realCursor ) -{ - return line(realCursor.line()); -} - -KateTextLayout KateLayoutCache::textLayout( const KTextEditor::Cursor & realCursor ) -{ - /*if (realCursor >= viewCacheStart() && (realCursor < viewCacheEnd() || realCursor == viewCacheEnd() && !m_textLayouts.last().wrap())) - foreach (const KateTextLayout& l, m_textLayouts) - if (l.line() == realCursor.line() && (l.endCol() < realCursor.column() || !l.wrap())) - return l;*/ - - return line(realCursor.line())->viewLine(viewLine(realCursor)); -} - -KateTextLayout KateLayoutCache::textLayout( uint realLine, int _viewLine ) -{ - /*if (m_textLayouts.count() && (realLine >= m_textLayouts.first().line() && _viewLine >= m_textLayouts.first().viewLine()) && - (realLine <= m_textLayouts.last().line() && _viewLine <= m_textLayouts.first().viewLine())) - foreach (const KateTextLayout& l, m_textLayouts) - if (l.line() == realLine && l.viewLine() == _viewLine) - return const_cast(l);*/ - - return line(realLine)->viewLine(_viewLine); -} - -KateTextLayout & KateLayoutCache::viewLine( int _viewLine ) -{ - Q_ASSERT(_viewLine >= 0 && _viewLine < m_textLayouts.count()); - return m_textLayouts[_viewLine]; -} - -int KateLayoutCache::viewCacheLineCount( ) const -{ - return m_textLayouts.count(); -} - -KTextEditor::Cursor KateLayoutCache::viewCacheStart( ) const -{ - return m_textLayouts.count() ? m_textLayouts.first().start() : KTextEditor::Cursor(); -} - -KTextEditor::Cursor KateLayoutCache::viewCacheEnd( ) const -{ - return m_textLayouts.count() ? m_textLayouts.last().end() : KTextEditor::Cursor(); -} - -int KateLayoutCache::viewWidth( ) const -{ - return m_viewWidth; -} - -/** - * This returns the view line upon which realCursor is situated. - * The view line is the number of lines in the view from the first line - * The supplied cursor should be in real lines. - */ -int KateLayoutCache::viewLine(const KTextEditor::Cursor& realCursor) -{ - if (realCursor.column() == 0) return 0; - - KateLineLayoutPtr thisLine = line(realCursor.line()); - - for (int i = 0; i < thisLine->viewLineCount(); ++i) { - const KateTextLayout& l = thisLine->viewLine(i); - if (realCursor.column() >= l.startCol() && realCursor.column() < l.endCol()) - return i; - } - - return thisLine->viewLineCount() - 1; -} - -int KateLayoutCache::displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible) -{ - KTextEditor::Cursor work = viewCacheStart(); - work.setLine(m_renderer->doc()->getVirtualLine(work.line())); - - if (!work.isValid()) - return virtualCursor.line(); - - int limit = m_textLayouts.count(); - - // Efficient non-word-wrapped path - if (!m_renderer->view()->dynWordWrap()) { - int ret = virtualCursor.line() - work.line(); - if (limitToVisible && (ret < 0 || ret > limit)) - return -1; - else - return ret; - } - - if (work == virtualCursor) { - return 0; - } - - int ret = -(int)viewLine(viewCacheStart()); - bool forwards = (work < virtualCursor); - - // FIXME switch to using ranges? faster? - if (forwards) { - while (work.line() != virtualCursor.line()) { - ret += viewLineCount(m_renderer->doc()->getRealLine(work.line())); - work.setLine(work.line() + 1); - if (limitToVisible && ret > limit) - return -1; - } - } else { - while (work.line() != virtualCursor.line()) { - work.setLine(work.line() - 1); - ret -= viewLineCount(m_renderer->doc()->getRealLine(work.line())); - if (limitToVisible && ret < 0) - return -1; - } - } - - // final difference - KTextEditor::Cursor realCursor = virtualCursor; - realCursor.setLine(m_renderer->doc()->getRealLine(realCursor.line())); - if (realCursor.column() == -1) realCursor.setColumn(m_renderer->doc()->lineLength(realCursor.line())); - ret += viewLine(realCursor); - - if (limitToVisible && (ret < 0 || ret > limit)) - return -1; - - return ret; -} - -int KateLayoutCache::lastViewLine(int realLine) -{ - if (!m_renderer->view()->dynWordWrap()) return 0; - - KateLineLayoutPtr l = line(realLine); - Q_ASSERT(l); - return l->viewLineCount() - 1; -} - -int KateLayoutCache::viewLineCount(int realLine) -{ - return lastViewLine(realLine) + 1; -} - -void KateLayoutCache::viewCacheDebugOutput( ) const -{ - kDebug( 13033 ) << "Printing values for " << m_textLayouts.count() << " lines:"; - if (m_textLayouts.count()) - foreach (const KateTextLayout& t, m_textLayouts) - if (t.isValid()) - t.debugOutput(); - else - kDebug( 13033 ) << "Line Invalid."; -} - -void KateLayoutCache::wrapLine (const KTextEditor::Cursor &position) -{ - m_lineLayouts.slotEditDone (position.line(), position.line() + 1, 1); -} - -void KateLayoutCache::unwrapLine (int line) -{ - m_lineLayouts.slotEditDone (line - 1, line, -1); -} - -void KateLayoutCache::insertText (const KTextEditor::Cursor &position, const QString &) -{ - m_lineLayouts.slotEditDone(position.line(), position.line(), 0); -} - -void KateLayoutCache::removeText (const KTextEditor::Range &range) -{ - m_lineLayouts.slotEditDone(range.start().line(), range.start().line(), 0); -} - -void KateLayoutCache::clear( ) -{ - m_textLayouts.clear(); - m_lineLayouts.clear(); - m_startPos = KTextEditor::Cursor(-1,-1); -} - -void KateLayoutCache::setViewWidth( int width ) -{ - bool wider = width > m_viewWidth; - - m_viewWidth = width; - - m_lineLayouts.clear(); - m_startPos = KTextEditor::Cursor(-1,-1); - - // Only get rid of layouts that we have to - if (wider) { - m_lineLayouts.viewWidthIncreased(); - } else { - m_lineLayouts.viewWidthDecreased(width); - } -} - -bool KateLayoutCache::wrap( ) const -{ - return m_wrap; -} - -void KateLayoutCache::setWrap( bool wrap ) -{ - m_wrap = wrap; - clear(); -} - -void KateLayoutCache::relayoutLines( int startRealLine, int endRealLine ) -{ - if (startRealLine > endRealLine) - kWarning() << "start" << startRealLine << "before end" << endRealLine; - - m_lineLayouts.relayoutLines(startRealLine, endRealLine); -} - -bool KateLayoutCache::acceptDirtyLayouts() -{ - return m_acceptDirtyLayouts; -} - -void KateLayoutCache::setAcceptDirtyLayouts(bool accept) -{ - m_acceptDirtyLayouts = accept; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/render/katelayoutcache.h b/part/render/katelayoutcache.h deleted file mode 100644 index ef633ae..0000000 --- a/part/render/katelayoutcache.h +++ /dev/null @@ -1,174 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2005 Hamish Rodda - * Copyright (C) 2008 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATELAYOUTCACHE_H -#define KATELAYOUTCACHE_H - -#include - -#include - -#include "katetextlayout.h" - -class KateRenderer; - -namespace KTextEditor { class Document; } - -class KateLineLayoutMap -{ - public: - KateLineLayoutMap(); - ~KateLineLayoutMap(); - - inline void clear(); - - inline bool contains(int i) const; - - inline void insert(int realLine, const KateLineLayoutPtr& lineLayoutPtr); - - inline void viewWidthIncreased(); - inline void viewWidthDecreased(int newWidth); - - inline void relayoutLines(int startRealLine, int endRealLine); - - inline void slotEditDone(int fromLine, int toLine, int shiftAmount); - - KateLineLayoutPtr& operator[](int i); - - typedef QPair LineLayoutPair; - private: - typedef QVector LineLayoutMap; - LineLayoutMap m_lineLayouts; -}; - -/** - * This class handles Kate's caching of layouting information (in KateLineLayout - * and KateTextLayout). This information is used primarily by both the view and - * the renderer. - * - * We outsource the hardcore layouting logic to the renderer, but other than - * that, this class handles all manipulation of the layout objects. - * - * This is separate from the renderer 1) for clarity 2) so you can have separate - * caches for separate views of the same document, even for view and printer - * (if the renderer is made to support rendering onto different targets). - * - * @warning The smart-mutex must be locked whenever this is used - * - * @author Hamish Rodda \ - */ - -class KateLayoutCache : public QObject -{ - Q_OBJECT - - public: - explicit KateLayoutCache(KateRenderer* renderer, QObject* parent); - - void clear(); - - int viewWidth() const; - void setViewWidth(int width); - - bool wrap() const; - void setWrap(bool wrap); - - bool acceptDirtyLayouts(); - void setAcceptDirtyLayouts(bool accept); - - // BEGIN generic methods to get/set layouts - /** - * Returns the KateLineLayout for the specified line. - * - * If one does not exist, it will be created and laid out. - * Layouts which are not directly part of the view will be kept until the - * cache is full or until they are invalidated by other means (eg. the text - * changes). - * - * \param realLine real line number of the layout to retrieve. - * \param virtualLine virtual line number. only needed if you think it may have changed - * (ie. basically internal to KateLayoutCache) - */ - KateLineLayoutPtr line(int realLine, int virtualLine = -1); - /// \overload - KateLineLayoutPtr line(const KTextEditor::Cursor& realCursor); - - /// Returns the layout describing the text line which is occupied by \p realCursor. - KateTextLayout textLayout(const KTextEditor::Cursor& realCursor); - - /// Returns the layout of the specified realLine + viewLine. - /// if viewLine is -1, return the last. - KateTextLayout textLayout(uint realLine, int viewLine); - // END - - // BEGIN methods to do with the caching of lines visible within a view - /// Returns the layout of the corresponding line in the view - KateTextLayout& viewLine(int viewLine); - - // find the view line of the cursor, relative to the display (0 = top line of view, 1 = second line, etc.) - // if limitToVisible is true, only lines which are currently visible will be searched for, and -1 returned if the line is not visible. - int displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible = false); - - int viewCacheLineCount() const; - KTextEditor::Cursor viewCacheStart() const; - KTextEditor::Cursor viewCacheEnd() const; - void updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount = -1, int viewLinesScrolled = 0); - - void relayoutLines(int startRealLine, int endRealLine); - - // find the index of the last view line for a specific line - int lastViewLine(int realLine); - // find the view line of cursor c (0 = same line, 1 = down one, etc.) - int viewLine(const KTextEditor::Cursor& realCursor); - int viewLineCount(int realLine); - - void viewCacheDebugOutput() const; - // END - -private Q_SLOTS: - void wrapLine (const KTextEditor::Cursor &position); - void unwrapLine (int line); - void insertText (const KTextEditor::Cursor &position, const QString &text); - void removeText (const KTextEditor::Range &range); - -private: - KateRenderer* m_renderer; - - /** - * The master cache of all line layouts. - * - * Layouts which are not within the current view cache and whose - * refcount == 1 are only known to the cache and can be safely deleted. - */ - mutable KateLineLayoutMap m_lineLayouts; - - // Convenience vector for quick direct access to the specific text layout - KTextEditor::Cursor m_startPos; - mutable QVector m_textLayouts; - - int m_viewWidth; - bool m_wrap; - bool m_acceptDirtyLayouts; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/render/katelinelayout.cpp b/part/render/katelinelayout.cpp deleted file mode 100644 index 1dceb26..0000000 --- a/part/render/katelinelayout.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002-2005 Hamish Rodda - Copyright (C) 2003 Anakim Border - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katelinelayout.h" -#include "katetextlayout.h" - -#include - -#include - -#include "katedocument.h" - -KateLineLayout::KateLineLayout(KateDocument* doc) - : m_doc(doc) - , m_textLine(0L) - , m_line(-1) - , m_virtualLine(-1) - , m_shiftX(0) - , m_layout(0L) - , m_layoutDirty(true) - , m_usePlainTextLine(false) -{ - Q_ASSERT(doc); -} - -KateLineLayout::~KateLineLayout() -{ - delete m_layout; -} - -void KateLineLayout::clear() -{ - m_textLine = Kate::TextLine (); - m_line = -1; - m_virtualLine = -1; - m_shiftX = 0; - // not touching dirty - delete m_layout; - m_layout = 0L; - // not touching layout dirty -} - -bool KateLineLayout::includesCursor(const KTextEditor::Cursor& realCursor) const -{ - return realCursor.line() == line(); -} - -const Kate::TextLine& KateLineLayout::textLine(bool reloadForce) const -{ - if (reloadForce || !m_textLine) - m_textLine = usePlainTextLine() ? m_doc->plainKateTextLine (line()) : m_doc->kateTextLine(line()); - - Q_ASSERT(m_textLine); - - return m_textLine; -} - -int KateLineLayout::line( ) const -{ - return m_line; -} - -void KateLineLayout::setLine( int line, int virtualLine ) -{ - m_line = line; - m_virtualLine = (virtualLine == -1) ? m_doc->getVirtualLine(line) : virtualLine; - m_textLine = Kate::TextLine (); -} - -int KateLineLayout::virtualLine( ) const -{ - return m_virtualLine; -} - -void KateLineLayout::setVirtualLine( int virtualLine ) -{ - m_virtualLine = virtualLine; -} - -bool KateLineLayout::startsInvisibleBlock() const -{ - if (!isValid()) - return false; - - return (virtualLine() + 1) != (int)m_doc->getVirtualLine(line() + 1); -} - -int KateLineLayout::shiftX() const -{ - return m_shiftX; -} - -void KateLineLayout::setShiftX(int shiftX) -{ - m_shiftX = shiftX; -} - -KateDocument* KateLineLayout::doc() const -{ - return m_doc; -} - -bool KateLineLayout::isValid( ) const -{ - return line() != -1 && layout() && textLine(); -} - -QTextLayout* KateLineLayout::layout() const -{ - return m_layout; -} - -void KateLineLayout::setLayout(QTextLayout* layout) -{ - if (m_layout != layout) { - delete m_layout; - m_layout = layout; - } - - m_layoutDirty = !m_layout; - m_dirtyList.clear(); - if (m_layout) - for (int i = 0; i < qMax(1, m_layout->lineCount()); ++i) - m_dirtyList.append(true); -} - -void KateLineLayout::invalidateLayout( ) -{ - setLayout(0L); -} - -bool KateLineLayout::isDirty( int viewLine ) const -{ - Q_ASSERT(isValid() && viewLine >= 0 && viewLine < viewLineCount()); - return m_dirtyList[viewLine]; -} - -bool KateLineLayout::setDirty( int viewLine, bool dirty ) -{ - Q_ASSERT(isValid() && viewLine >= 0 && viewLine < viewLineCount()); - m_dirtyList[viewLine] = dirty; - return dirty; -} - -KTextEditor::Cursor KateLineLayout::start( ) const -{ - return KTextEditor::Cursor(line(), 0); -} - -int KateLineLayout::length( ) const -{ - return textLine()->length(); -} - -int KateLineLayout::viewLineCount( ) const -{ - return m_layout->lineCount(); -} - -KateTextLayout KateLineLayout::viewLine( int viewLine ) const -{ - if (viewLine < 0) - viewLine += viewLineCount(); - Q_ASSERT(isValid()); - Q_ASSERT(viewLine >= 0 && viewLine < viewLineCount()); - return KateTextLayout(KateLineLayoutPtr(const_cast(this)), viewLine); -} - -int KateLineLayout::width( ) const -{ - int width = 0; - - for (int i = 0; i < m_layout->lineCount(); ++i) - width = qMax((int)m_layout->lineAt(i).naturalTextWidth(), width); - - return width; -} - -int KateLineLayout::widthOfLastLine( ) const -{ - const KateTextLayout& lastLine = viewLine(viewLineCount() - 1); - return lastLine.width() + lastLine.xOffset(); -} - -bool KateLineLayout::isOutsideDocument( ) const -{ - return line() < 0 || line() >= m_doc->lines(); -} - -void KateLineLayout::debugOutput() const -{ - kDebug( 13033 ) << "KateLineLayout: " << this << " valid " << isValid() << " line " << line() << " length " << length() << " width " << width() << " viewLineCount " << viewLineCount(); -} - -int KateLineLayout::viewLineForColumn( int column ) const -{ - int len = 0; - int i = 0; - for (; i < m_layout->lineCount() - 1; ++i) { - len += m_layout->lineAt(i).textLength(); - if (column < len) - return i; - } - return i; -} - -bool KateLineLayout::isLayoutDirty( ) const -{ - return m_layoutDirty; -} - -void KateLineLayout::setLayoutDirty( bool dirty ) -{ - m_layoutDirty = dirty; -} - -bool KateLineLayout::usePlainTextLine () const -{ - return m_usePlainTextLine; -} - -void KateLineLayout::setUsePlainTextLine (bool plain) -{ - m_usePlainTextLine = plain; -} - -bool KateLineLayout::isRightToLeft() const -{ - if (!m_layout) - return false; - - return m_layout->textOption().textDirection() == Qt::RightToLeft; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/render/katelinelayout.h b/part/render/katelinelayout.h deleted file mode 100644 index 038aed3..0000000 --- a/part/render/katelinelayout.h +++ /dev/null @@ -1,121 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002-2005 Hamish Rodda - Copyright (C) 2003 Anakim Border - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _KATE_LINELAYOUT_H_ -#define _KATE_LINELAYOUT_H_ - -#include - -#include "katetextline.h" - -#include - -class QTextLayout; -class KateDocument; -class KateTextLayout; - -class KateLineLayout : public KShared -{ - public: - KateLineLayout(KateDocument* doc = 0L); - ~KateLineLayout(); - - KateDocument* doc() const; - void debugOutput() const; - - void clear(); - bool isValid() const; - bool isOutsideDocument() const; - - bool isRightToLeft() const; - - bool includesCursor(const KTextEditor::Cursor& realCursor) const; - - friend bool operator> (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator>= (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator< (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator<= (const KateLineLayout& r, const KTextEditor::Cursor& c); - - const Kate::TextLine& textLine(bool forceReload = false) const; - int length() const; - - int line() const; - /** - * Only pass virtualLine if you know it (and thus we shouldn't try to look it up) - */ - void setLine(int line, int virtualLine = -1); - KTextEditor::Cursor start() const; - - int virtualLine() const; - void setVirtualLine(int virtualLine); - - bool isDirty(int viewLine) const; - bool setDirty(int viewLine, bool dirty = true); - - int width() const; - int widthOfLastLine() const; - - int viewLineCount() const; - KateTextLayout viewLine(int viewLine) const; - int viewLineForColumn(int column) const; - - bool startsInvisibleBlock() const; - - // This variable is used as follows: - // non-dynamic-wrapping mode: unused - // dynamic wrapping mode: - // first viewLine of a line: the X position of the first non-whitespace char - // subsequent viewLines: the X offset from the left of the display. - // - // this is used to provide a dynamic-wrapping-retains-indent feature. - int shiftX() const; - void setShiftX(int shiftX); - - QTextLayout* layout() const; - void setLayout(QTextLayout* layout); - void invalidateLayout(); - - bool isLayoutDirty() const; - void setLayoutDirty(bool dirty = true); - - bool usePlainTextLine () const; - void setUsePlainTextLine (bool plain = true); - -private: - // Disable copy - KateLineLayout(const KateLineLayout& copy); - - QTextLayout* takeLayout() const; - - KateDocument* m_doc; - mutable Kate::TextLine m_textLine; - int m_line; - int m_virtualLine; - int m_shiftX; - - QTextLayout* m_layout; - QList m_dirtyList; - - bool m_layoutDirty; - bool m_usePlainTextLine; -}; - -typedef KSharedPtr KateLineLayoutPtr; - -#endif diff --git a/part/render/katerenderer.cpp b/part/render/katerenderer.cpp deleted file mode 100644 index b1099c6..0000000 --- a/part/render/katerenderer.cpp +++ /dev/null @@ -1,1061 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2003-2005 Hamish Rodda - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katerenderer.h" - -#include "katedocument.h" -#include "kateconfig.h" -#include "katehighlight.h" -#include "kateview.h" -#include "katerenderrange.h" -#include "katetextlayout.h" -#include "katebuffer.h" - -#include "katevivisualmode.h" - -#include - -#include - -#include -#include -#include -#include - -#include - -static const QChar tabChar('\t'); -static const QChar spaceChar(' '); -static const QChar nbSpaceChar(0xa0); // non-breaking space - -KateRenderer::KateRenderer(KateDocument* doc, KateView *view) - : m_doc(doc) - , m_view (view) - , m_tabWidth(m_doc->config()->tabWidth()) - , m_indentWidth(m_doc->config()->indentationWidth()) - , m_caretStyle(KateRenderer::Line) - , m_drawCaret(true) - , m_showSelections(true) - , m_showTabs(true) - , m_showSpaces(true) - , m_printerFriendly(false) - , m_config(new KateRendererConfig(this)) -{ - updateAttributes (); -} - -KateRenderer::~KateRenderer() -{ - delete m_config; -} - -void KateRenderer::updateAttributes () -{ - m_attributes = m_doc->highlight()->attributes (config()->schema ()); -} - -KTextEditor::Attribute::Ptr KateRenderer::attribute(uint pos) const -{ - if (pos < (uint)m_attributes.count()) - return m_attributes[pos]; - - return m_attributes[0]; -} - -KTextEditor::Attribute::Ptr KateRenderer::specificAttribute( int context ) const -{ - if (context >= 0 && context < m_attributes.count()) - return m_attributes[context]; - - return m_attributes[0]; -} - -void KateRenderer::setDrawCaret(bool drawCaret) -{ - m_drawCaret = drawCaret; -} - -void KateRenderer::setCaretStyle(KateRenderer::caretStyles style) -{ - m_caretStyle = style; -} - -void KateRenderer::setShowTabs(bool showTabs) -{ - m_showTabs = showTabs; -} - -void KateRenderer::setShowTrailingSpaces(bool showSpaces) -{ - m_showSpaces = showSpaces; -} - -void KateRenderer::setTabWidth(int tabWidth) -{ - m_tabWidth = tabWidth; -} - -bool KateRenderer::showIndentLines() const -{ - return m_config->showIndentationLines(); -} - -void KateRenderer::setShowIndentLines(bool showIndentLines) -{ - m_config->setShowIndentationLines(showIndentLines); -} - -void KateRenderer::setIndentWidth(int indentWidth) -{ - m_indentWidth = indentWidth; -} - -void KateRenderer::setShowSelections(bool showSelections) -{ - m_showSelections = showSelections; -} - -void KateRenderer::increaseFontSizes() -{ - QFont f ( config()->font () ); - f.setPointSize (f.pointSize ()+1); - - config()->setFont (f); -} - -void KateRenderer::decreaseFontSizes() -{ - QFont f ( config()->font () ); - - if ((f.pointSize ()-1) > 0) - f.setPointSize (f.pointSize ()-1); - - config()->setFont (f); -} - -bool KateRenderer::isPrinterFriendly() const -{ - return m_printerFriendly; -} - -void KateRenderer::setPrinterFriendly(bool printerFriendly) -{ - m_printerFriendly = printerFriendly; - setShowTabs(false); - setShowTrailingSpaces(false); - setShowSelections(false); - setDrawCaret(false); -} - -void KateRenderer::paintTextLineBackground(QPainter& paint, KateLineLayoutPtr layout, int currentViewLine, int xStart, int xEnd) -{ - if (isPrinterFriendly()) - return; - - // Normal background color - QColor backgroundColor( config()->backgroundColor() ); - - // paint the current line background if we're on the current line - QColor currentLineColor = config()->highlightedLineColor(); - - // Check for mark background - int markRed = 0, markGreen = 0, markBlue = 0, markCount = 0; - - // Retrieve marks for this line - uint mrk = m_doc->mark( layout->line() ); - if (mrk) - { - for (uint bit = 0; bit < 32; bit++) - { - KTextEditor::MarkInterface::MarkTypes markType = (KTextEditor::MarkInterface::MarkTypes)(1<lineMarkerColor(markType); - - if (markColor.isValid()) { - markCount++; - markRed += markColor.red(); - markGreen += markColor.green(); - markBlue += markColor.blue(); - } - } - } // for - } // Marks - - if (markCount) { - markRed /= markCount; - markGreen /= markCount; - markBlue /= markCount; - backgroundColor.setRgb( - int((backgroundColor.red() * 0.9) + (markRed * 0.1)), - int((backgroundColor.green() * 0.9) + (markGreen * 0.1)), - int((backgroundColor.blue() * 0.9) + (markBlue * 0.1)) - ); - } - - // Draw line background - paint.fillRect(0, 0, xEnd - xStart, config()->fontMetrics().height() * layout->viewLineCount(), backgroundColor); - - // paint the current line background if we're on the current line - if (currentViewLine != -1) { - if (markCount) { - markRed /= markCount; - markGreen /= markCount; - markBlue /= markCount; - currentLineColor.setRgb( - int((currentLineColor.red() * 0.9) + (markRed * 0.1)), - int((currentLineColor.green() * 0.9) + (markGreen * 0.1)), - int((currentLineColor.blue() * 0.9) + (markBlue * 0.1)) - ); - } - - paint.fillRect(0, config()->fontMetrics().height() * currentViewLine, xEnd - xStart, config()->fontMetrics().height(), currentLineColor); - } -} - -void KateRenderer::paintTabstop(QPainter &paint, qreal x, qreal y) -{ - QPen penBackup( paint.pen() ); - QPen pen( config()->tabMarkerColor() ); - pen.setWidth(qMax(1u, spaceWidth() / 10)); - paint.setPen( pen ); - paint.setRenderHint(QPainter::Antialiasing, false); - - int dist = spaceWidth() * 0.3; - QPoint points[8]; - points[0] = QPoint(x - dist, y - dist); - points[1] = QPoint(x, y); - points[2] = QPoint(x, y); - points[3] = QPoint(x - dist, y + dist); - x += spaceWidth() / 3.0; - points[4] = QPoint(x - dist, y - dist); - points[5] = QPoint(x, y); - points[6] = QPoint(x, y); - points[7] = QPoint(x - dist, y + dist); - paint.drawLines(points, 4); - paint.setPen( penBackup ); -} - -void KateRenderer::paintTrailingSpace(QPainter &paint, qreal x, qreal y) -{ - QPen penBackup( paint.pen() ); - QPen pen( config()->tabMarkerColor() ); - pen.setWidthF(spaceWidth() / 3.5); - pen.setCapStyle(Qt::RoundCap); - paint.setPen( pen ); - - paint.drawPoint( QPointF(x, y) ); - paint.setPen( penBackup ); -} - -void KateRenderer::paintNonBreakSpace(QPainter &paint, qreal x, qreal y) -{ - QPen penBackup( paint.pen() ); - QPen pen( config()->tabMarkerColor() ); - pen.setWidth(qMax(1u, spaceWidth() / 10)); - paint.setPen( pen ); - paint.setRenderHint(QPainter::Antialiasing, false); - - const int height = config()->fontMetrics().height(); - const int width = spaceWidth(); - - QPoint points[6]; - points[0] = QPoint(x+width/10, y+height/4); - points[1] = QPoint(x+width/10, y+height/3); - points[2] = QPoint(x+width/10, y+height/3); - points[3] = QPoint(x+width-width/10, y+height/3); - points[4] = QPoint(x+width-width/10, y+height/3); - points[5] = QPoint(x+width-width/10, y+height/4); - paint.drawLines(points, 3); - paint.setPen( penBackup ); -} - -void KateRenderer::paintIndentMarker(QPainter &paint, uint x, uint row) -{ - QPen penBackup( paint.pen() ); - paint.setPen( config()->tabMarkerColor() ); - - const int height = config()->fontMetrics().height(); - const int top = 0; - const int bottom = height-1; - const int h = bottom - top + 1; - - // Dot padding. - int pad = 0; - if(row & 1 && h & 1) pad = 1; - - for(int i = top; i <= bottom; i++) - { - if((i + pad) & 1) - { - paint.drawPoint(x + 2, i); - } - } - - paint.setPen( penBackup ); -} - -static bool rangeLessThanForRenderer (const Kate::TextRange *a, const Kate::TextRange *b) -{ - // compare Z-Depth first - // smaller Z-Depths should win! - if (a->zDepth() > b->zDepth()) - return true; - else if (a->zDepth() < b->zDepth()) - return false; - - // end of a > end of b? - if (a->end().toCursor() > b->end().toCursor()) - return true; - - // if ends are equal, start of a < start of b? - if (a->end().toCursor() == b->end().toCursor()) - return a->start().toCursor() < b->start().toCursor(); - - return false; -} - -QList KateRenderer::decorationsForLine( const Kate::TextLine& textLine, int line, bool selectionsOnly, KateRenderRange* completionHighlight, bool completionSelected ) const -{ - QList newHighlight; - - // Don't compute the highlighting if there isn't going to be any highlighting - QList rangesWithAttributes = m_doc->buffer().rangesForLine (line, m_printerFriendly ? 0 : m_view, true); - if (selectionsOnly || textLine->attributesList().count() || rangesWithAttributes.count()) { - RenderRangeList renderRanges; - - // Add the inbuilt highlighting to the list - NormalRenderRange* inbuiltHighlight = new NormalRenderRange(); - const QVector &al = textLine->attributesList(); - for (int i = 0; i+2 < al.count(); i += 3) { - inbuiltHighlight->addRange(new KTextEditor::Range(KTextEditor::Cursor(line, al[i]), al[i+1]), specificAttribute(al[i+2])); - } - renderRanges.append(inbuiltHighlight); - - if (!completionHighlight) { - // check for dynamic hl stuff - const QSet *rangesMouseIn = m_view ? m_view->rangesMouseIn () : 0; - const QSet *rangesCaretIn = m_view ? m_view->rangesCaretIn () : 0; - bool anyDynamicHlsActive = m_view && (!rangesMouseIn->empty() || !rangesCaretIn->empty()); - - // sort all ranges, we want that the most specific ranges win during rendering, multiple equal ranges are kind of random, still better than old smart rangs behavior ;) - qSort (rangesWithAttributes.begin(), rangesWithAttributes.end(), rangeLessThanForRenderer); - - // loop over all ranges - for (int i = 0; i < rangesWithAttributes.size(); ++i) { - // real range - Kate::TextRange *kateRange = rangesWithAttributes[i]; - - // calculate attribute, default: normal attribute - KTextEditor::Attribute::Ptr attribute = kateRange->attribute(); - if (anyDynamicHlsActive) { - // check mouse in - if (KTextEditor::Attribute::Ptr attributeMouseIn = attribute->dynamicAttribute (KTextEditor::Attribute::ActivateMouseIn)) { - if (rangesMouseIn->contains (kateRange)) - attribute = attributeMouseIn; - } - - // check caret in - if (KTextEditor::Attribute::Ptr attributeCaretIn = attribute->dynamicAttribute (KTextEditor::Attribute::ActivateCaretIn)) { - if (rangesCaretIn->contains (kateRange)) - attribute = attributeCaretIn; - } - } - - // span range - NormalRenderRange *additionaHl = new NormalRenderRange(); - additionaHl->addRange(new KTextEditor::Range (*kateRange), attribute); - renderRanges.append(additionaHl); - } - } else { - // Add the code completion arbitrary highlight to the list - renderRanges.append(completionHighlight); - } - - // Add selection highlighting if we're creating the selection decorations - if ((selectionsOnly && showSelections() && m_view->selection()) || (completionHighlight && completionSelected) || m_view->blockSelection()) { - NormalRenderRange* selectionHighlight = new NormalRenderRange(); - - // Set up the selection background attribute TODO: move this elsewhere, eg. into the config? - static KTextEditor::Attribute::Ptr backgroundAttribute; - if (!backgroundAttribute) - backgroundAttribute = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); - - backgroundAttribute->setBackground(config()->selectionColor()); - backgroundAttribute->setForeground(attribute(KTextEditor::HighlightInterface::dsNormal)->selectedForeground().color()); - - // Create a range for the current selection - if (completionHighlight && completionSelected) - selectionHighlight->addRange(new KTextEditor::Range(line, 0, line + 1, 0), backgroundAttribute); - else - if(m_view->blockSelection() && m_view->selectionRange().overlapsLine(line)) - selectionHighlight->addRange(new KTextEditor::Range(m_doc->rangeOnLine(m_view->selectionRange(), line)), backgroundAttribute); - else { - selectionHighlight->addRange(new KTextEditor::Range(m_view->selectionRange()), backgroundAttribute); - } - - renderRanges.append(selectionHighlight); - // hihglighting for the vi visual modes - } else if ( m_view->getViInputModeManager()->getCurrentViMode() == VisualMode - || m_view->getViInputModeManager()->getCurrentViMode() == VisualLineMode - || m_view->getViInputModeManager()->getCurrentViMode() == VisualBlockMode ) { - - KTextEditor::Range r = m_view->getViInputModeManager()->getViVisualMode()->getVisualRange(); - - if ( r.isValid() && (r.end().line() == line || r.start().line() == line || r.containsLine( line ) )) { - NormalRenderRange* selectionHighlight = new NormalRenderRange(); - static KTextEditor::Attribute::Ptr backgroundAttribute; - if (!backgroundAttribute) - backgroundAttribute = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); - - backgroundAttribute->setBackground(config()->selectionColor()); - - if ( m_view->getViInputModeManager()->getCurrentViMode() == VisualBlockMode ) { - selectionHighlight->addRange(new KTextEditor::Range(line, r.start().column(), line, r.end().column()+1), backgroundAttribute); - } else if ( m_view->getViInputModeManager()->getCurrentViMode() == VisualLineMode ) { - selectionHighlight->addRange(new KTextEditor::Range(line, 0, line, m_view->doc()->lineLength( line )), backgroundAttribute); - } else { - selectionHighlight->addRange(new KTextEditor::Range(r), backgroundAttribute); - } - renderRanges.append(selectionHighlight); - } - } - - KTextEditor::Cursor currentPosition, endPosition; - - // Calculate the range which we need to iterate in order to get the highlighting for just this line - if (selectionsOnly) { - if(m_view->blockSelection()) { - KTextEditor::Range subRange = m_doc->rangeOnLine(m_view->selectionRange(), line); - currentPosition = subRange.start(); - endPosition = subRange.end(); - } else { - KTextEditor::Range rangeNeeded = m_view->selectionRange() & KTextEditor::Range(line, 0, line + 1, 0); - - currentPosition = qMax(KTextEditor::Cursor(line, 0), rangeNeeded.start()); - endPosition = qMin(KTextEditor::Cursor(line + 1, 0), rangeNeeded.end()); - } - } else { - currentPosition = KTextEditor::Cursor(line, 0); - endPosition = KTextEditor::Cursor(line + 1, 0); - } - - // Main iterative loop. This walks through each set of highlighting ranges, and stops each - // time the highlighting changes. It then creates the corresponding QTextLayout::FormatRanges. - while (currentPosition < endPosition) { - renderRanges.advanceTo(currentPosition); - - if (!renderRanges.hasAttribute()) { - // No attribute, don't need to create a FormatRange for this text range - currentPosition = renderRanges.nextBoundary(); - continue; - } - - KTextEditor::Cursor nextPosition = renderRanges.nextBoundary(); - - // Create the format range and populate with the correct start, length and format info - QTextLayout::FormatRange fr; - fr.start = currentPosition.column(); - - if (nextPosition < endPosition || endPosition.line() <= line) { - fr.length = nextPosition.column() - currentPosition.column(); - - } else { - // +1 to force background drawing at the end of the line when it's warranted - fr.length = textLine->length() - currentPosition.column() + 1; - } - - KTextEditor::Attribute::Ptr a = renderRanges.generateAttribute(); - if (a) { - fr.format = *a; - - if(selectionsOnly) { - assignSelectionBrushesFromAttribute(fr, *a); - } else if ( m_view->getCurrentViMode() == VisualMode || m_view->getCurrentViMode() == VisualLineMode ) { - if (m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().contains(currentPosition)) { - assignSelectionBrushesFromAttribute(fr, *a); - } - } else if ( m_view->getCurrentViMode() == VisualBlockMode ) { - if (m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().contains(currentPosition) - || m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().start().line() == currentPosition.line() - || m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().end().line() == currentPosition.line()) { - int c1 = m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().start().column(); - int c2 = m_view->getViInputModeManager()->getViVisualMode()->getVisualRange().end().column(); - - if(currentPosition.column() >= c1 && currentPosition.column() <= c2) { - assignSelectionBrushesFromAttribute(fr, *a); - } - } - } - } - - newHighlight.append(fr); - - currentPosition = nextPosition; - } - - if (completionHighlight) - // Don't delete external completion render range - renderRanges.removeAll(completionHighlight); - - qDeleteAll(renderRanges); - } - - return newHighlight; -} - -void KateRenderer::assignSelectionBrushesFromAttribute(QTextLayout::FormatRange& target, const KTextEditor::Attribute& attribute) const -{ - if(attribute.hasProperty(KTextEditor::Attribute::SelectedForeground)) { - target.format.setForeground(attribute.selectedForeground()); - } - if(attribute.hasProperty(KTextEditor::Attribute::SelectedBackground)) { - target.format.setBackground(attribute.selectedBackground()); - } -} - -/* -The ultimate line painting function. -Currently missing features: -- draw indent lines -*/ -void KateRenderer::paintTextLine(QPainter& paint, KateLineLayoutPtr range, int xStart, int xEnd, const KTextEditor::Cursor* cursor) -{ - Q_ASSERT(range->isValid()); - -// kDebug( 13033 )<<"KateRenderer::paintTextLine"; - - // font data - const QFontMetrics& fm = config()->fontMetrics(); - - int currentViewLine = -1; - if (cursor && cursor->line() == range->line()) - currentViewLine = range->viewLineForColumn(cursor->column()); - - paintTextLineBackground(paint, range, currentViewLine, xStart, xEnd); - - if (range->layout()) { - QVector additionalFormats; - if (range->length() > 0) { - // We may have changed the pen, be absolutely sure it gets set back to - // normal foreground color before drawing text for text that does not - // set the pen color - paint.setPen(attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color()); - // Draw the text :) - if (m_view->selection() && showSelections() && m_view->selectionRange().overlapsLine(range->line())) { - // FIXME toVector() may be a performance issue - additionalFormats = decorationsForLine(range->textLine(), range->line(), true).toVector(); - range->layout()->draw(&paint, QPoint(-xStart,0), additionalFormats); - - } else { - range->layout()->draw(&paint, QPoint(-xStart,0)); - } - } - - QBrush backgroundBrush; - bool backgroundBrushSet = false; - - // Loop each individual line for additional text decoration etc. - QListIterator it = range->layout()->additionalFormats(); - QVectorIterator it2 = additionalFormats; - for (int i = 0; i < range->viewLineCount(); ++i) { - KateTextLayout line = range->viewLine(i); - - // Determine the background to use, if any, for the end of this view line - backgroundBrushSet = false; - while (it2.hasNext()) { - const QTextLayout::FormatRange& fr = it2.peekNext(); - if (fr.start > line.endCol()) - break; - - if (fr.start + fr.length > line.endCol()) { - if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) { - backgroundBrushSet = true; - backgroundBrush = fr.format.background(); - } - - goto backgroundDetermined; - } - - it2.next(); - } - - while (it.hasNext()) { - const QTextLayout::FormatRange& fr = it.peekNext(); - if (fr.start > line.endCol()) - break; - - if (fr.start + fr.length > line.endCol()) { - if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) { - backgroundBrushSet = true; - backgroundBrush = fr.format.background(); - } - - break; - } - - it.next(); - } - - backgroundDetermined: - - // Draw selection or background color outside of areas where text is rendered - if (!m_printerFriendly ) { - bool draw = false; - QBrush drawBrush; - if (m_view->selection() && !m_view->blockSelection() && m_view->lineEndSelected(line.end(true))) { - draw = true; - drawBrush = config()->selectionColor(); - } else if (backgroundBrushSet && !m_view->blockSelection()) { - draw = true; - drawBrush = backgroundBrush; - } - - if (draw) { - int fillStartX = line.endX() - line.startX() + line.xOffset() - xStart; - int fillStartY = lineHeight() * i; - int width= xEnd - xStart - fillStartX; - int height= lineHeight(); - - // reverse X for right-aligned lines - if (range->layout()->textOption().alignment() == Qt::AlignRight) - fillStartX = 0; - - if (width > 0) { - QRect area(fillStartX, fillStartY, width, height); - paint.fillRect(area, drawBrush); - } - } - } - // Draw indent lines - if (showIndentLines() && i == 0) - { - const int w = spaceWidth(); - const int lastIndentColumn = range->textLine()->indentDepth(m_tabWidth); - - for (int x = m_indentWidth; x < lastIndentColumn; x += m_indentWidth) - { - paintIndentMarker(paint, x * w + 1 - xStart, range->line()); - } - } - - // draw an open box to mark non-breaking spaces - const QString& text = range->textLine()->string(); - int y = lineHeight() * i + fm.ascent() - fm.strikeOutPos(); - int nbSpaceIndex = text.indexOf(nbSpaceChar, line.lineLayout().xToCursor(xStart)); - - while (nbSpaceIndex != -1 && nbSpaceIndex < line.endCol()) { - int x = line.lineLayout().cursorToX(nbSpaceIndex); - if (x > xEnd) - break; - paintNonBreakSpace(paint, x - xStart, y); - nbSpaceIndex = text.indexOf(nbSpaceChar, nbSpaceIndex + 1); - } - - // Draw tab stops and trailing spaces - if (showTabs() || showTrailingSpaces()) { - if (showTabs()) { - int tabIndex = text.indexOf(tabChar, line.lineLayout().xToCursor(xStart)); - while (tabIndex != -1 && tabIndex < line.endCol()) { - int x = line.lineLayout().cursorToX(tabIndex); - if (x > xEnd) - break; - paintTabstop(paint, x - xStart + spaceWidth()/2.0, y); - tabIndex = text.indexOf(tabChar, tabIndex + 1); - } - } - - if (showTrailingSpaces()) { - int spaceIndex = line.endCol() - 1; - int trailingPos = range->textLine()->lastChar(); - if (trailingPos < 0) - trailingPos = 0; - if (spaceIndex >= trailingPos) { - while (spaceIndex >= line.startCol() && text.at(spaceIndex).isSpace()) { - if (text.at(spaceIndex) != '\t' || !showTabs()) - paintTrailingSpace(paint, line.lineLayout().cursorToX(spaceIndex) - xStart + spaceWidth()/2.0, y); - --spaceIndex; - } - } - } - } - } - - // draw word-wrap-honor-indent filling - if ( (range->viewLineCount() > 1) && range->shiftX() && (range->shiftX() > xStart) ) - { - if (backgroundBrushSet) - paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1), - backgroundBrush); - paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1), - QBrush(config()->wordWrapMarkerColor(), Qt::Dense4Pattern)); - } - - // Draw caret - if (drawCaret() && cursor && range->includesCursor(*cursor)) { - // Make the caret the desired width - int caretWidth = 2; - QTextLine line = range->layout()->lineForTextPosition(cursor->column()); - if (caretStyle() == Block || (m_view->viInputMode() && m_view->getCurrentViMode() != InsertMode)) { - if (line.isValid() && cursor->column() < range->length()) { - caretWidth = int(line.cursorToX(cursor->column() + 1) - line.cursorToX(cursor->column())); - if (caretWidth < 0) - caretWidth = -caretWidth; - - } else { - caretWidth = spaceWidth(); - } - } - - QColor c; - // Could actually use the real highlighting system for this... would be slower but more accurate for corner cases - if (m_caretOverrideColor.isValid()) { - c = m_caretOverrideColor; - - } else { - // search for the FormatRange that includes the cursor - foreach (const QTextLayout::FormatRange &r, range->layout()->additionalFormats()) { - if ( (r.start <= cursor->column() ) && ( (r.start + r.length) > cursor->column()) ) { - // check for Qt::NoBrush, as the returned color is black() and no invalid QColor - QBrush foregroundBrush = r.format.foreground(); - if (foregroundBrush != Qt::NoBrush) { - c = r.format.foreground().color(); - } - break; - } - } - - // still no color found, fall back to default style - if (!c.isValid()) - c = attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color(); - } - - // make it possible to see the selected character in the vi input mode's normal/visual mode - if (m_view->viInputMode() && m_view->getCurrentViMode() != InsertMode ) { - c.setAlpha(128); - } - - if (cursor->column() <= range->length()) { - paint.save(); - paint.setPen(QPen(c, caretWidth)); - - // Clip the caret - Qt's caret has a habit of intruding onto other lines - paint.setClipRect(0, line.lineNumber() * lineHeight(), xEnd - xStart, lineHeight()); - - range->layout()->drawCursor(&paint, QPoint(-xStart,0), cursor->column(), caretWidth); - - paint.restore(); - - } else { - // Off the end of the line... must be block mode. Draw the caret ourselves. - const KateTextLayout& lastLine = range->viewLine(range->viewLineCount() - 1); - int x = range->widthOfLastLine() + spaceWidth() * (cursor->column() - range->length()); - if ( (x >= xStart) && (x <= xEnd)) - paint.fillRect(x-xStart, (int)lastLine.lineLayout().y(), caretWidth, lineHeight(), c); - } - } - } - - // Draws the dashed underline at the start of a folded block of text. - if (range->startsInvisibleBlock()) { - paint.setRenderHint(QPainter::Antialiasing, false); - QPen pen(config()->wordWrapMarkerColor()); - pen.setCosmetic(true); - pen.setStyle(Qt::DashLine); - pen.setDashOffset(xStart); - paint.setPen(pen); - paint.drawLine(0, (lineHeight() * range->viewLineCount()) - 1, xEnd - xStart, (lineHeight() * range->viewLineCount()) - 1); - } - - // show word wrap marker if desirable - if ((!isPrinterFriendly()) && config()->wordWrapMarker() && QFontInfo(config()->font()).fixedPitch()) - { - paint.setRenderHint(QPainter::Antialiasing, false); - paint.setPen( config()->wordWrapMarkerColor() ); - int _x = m_doc->config()->wordWrapAt() * fm.width('x') - xStart; - paint.drawLine( _x,0,_x,lineHeight() ); - } -} - -const QFont& KateRenderer::currentFont() const -{ - return config()->font(); -} - -const QFontMetrics& KateRenderer::currentFontMetrics() const -{ - return config()->fontMetrics(); -} - -uint KateRenderer::fontHeight() -{ - return config()->fontMetrics().height(); -} - -uint KateRenderer::documentHeight() -{ - return m_doc->lines() * lineHeight(); -} - -int KateRenderer::lineHeight() -{ - return fontHeight(); // for now -} - -bool KateRenderer::getSelectionBounds(int line, int lineLength, int &start, int &end) const -{ - bool hasSel = false; - - if (m_view->selection() && !m_view->blockSelectionMode()) - { - if (m_view->lineIsSelection(line)) - { - start = m_view->selectionRange().start().column(); - end = m_view->selectionRange().end().column(); - hasSel = true; - } - else if (line == m_view->selectionRange().start().line()) - { - start = m_view->selectionRange().start().column(); - end = lineLength; - hasSel = true; - } - else if (m_view->selectionRange().containsLine(line)) - { - start = 0; - end = lineLength; - hasSel = true; - } - else if (line == m_view->selectionRange().end().line()) - { - start = 0; - end = m_view->selectionRange().end().column(); - hasSel = true; - } - } - else if (m_view->lineHasSelected(line)) - { - start = m_view->selectionRange().start().column(); - end = m_view->selectionRange().end().column(); - hasSel = true; - } - - if (start > end) { - int temp = end; - end = start; - start = temp; - } - - return hasSel; -} - -void KateRenderer::updateConfig () -{ - // update the attibute list pointer - updateAttributes (); - - if (m_view) - m_view->updateRendererConfig(); -} - -uint KateRenderer::spaceWidth() const -{ - return config()->fontMetrics().width(spaceChar); -} - -void KateRenderer::layoutLine(KateLineLayoutPtr lineLayout, int maxwidth, bool cacheLayout) const -{ - // if maxwidth == -1 we have no wrap - - Kate::TextLine textLine = lineLayout->textLine(); - Q_ASSERT(textLine); - - QTextLayout* l = lineLayout->layout(); - if (!l) { - l = new QTextLayout(textLine->string(), config()->font()); - } else { - l->setText(textLine->string()); - l->setFont(config()->font()); - } - - l->setCacheEnabled(cacheLayout); - - // Initial setup of the QTextLayout. - - // Tab width - QTextOption opt; - opt.setFlags(QTextOption::IncludeTrailingSpaces); - opt.setTabStop(m_tabWidth * config()->fontMetrics().width(spaceChar)); - opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); - - // Find the first strong character in the string. - // If it is an RTL character, set the base layout direction of the string to RTL. - // - // See http://www.unicode.org/reports/tr9/#The_Paragraph_Level (Sections P2 & P3). - // Qt's text renderer ("scribe") version 4.2 assumes a "higher-level protocol" - // (such as KatePart) will specify the paragraph level, so it does not apply P2 & P3 - // by itself. If this ever change in Qt, the next code block could be removed. - if (isLineRightToLeft(lineLayout)) { - opt.setAlignment( Qt::AlignRight ); - opt.setTextDirection( Qt::RightToLeft ); - } - else { - opt.setAlignment( Qt::AlignLeft ); - opt.setTextDirection( Qt::LeftToRight ); - } - - l->setTextOption(opt); - - // Syntax highlighting, inbuilt and arbitrary - l->setAdditionalFormats(decorationsForLine(textLine, lineLayout->line())); - - // Begin layouting - l->beginLayout(); - - int height = 0; - int shiftX = 0; - - bool needShiftX = (maxwidth != -1) - && (m_view->config()->dynWordWrapAlignIndent() > 0); - - forever { - QTextLine line = l->createLine(); - if (!line.isValid()) - break; - - if (maxwidth > 0) - line.setLineWidth(maxwidth); - - line.setPosition(QPoint(line.lineNumber() ? shiftX : 0, height)); - - if (needShiftX) { - needShiftX = false; - // Determine x offset for subsequent-lines-of-paragraph indenting - int pos = textLine->nextNonSpaceChar(0); - - if (pos > 0) { - shiftX = (int)line.cursorToX(pos); - } - - // check for too deep shift value and limit if necessary - if (shiftX > ((double)maxwidth / 100 * m_view->config()->dynWordWrapAlignIndent())) - shiftX = 0; - - // if shiftX > 0, the maxwidth has to adapted - maxwidth -= shiftX; - - lineLayout->setShiftX(shiftX); - } - - height += config()->fontMetrics().height(); - } - - l->endLayout(); - - lineLayout->setLayout(l); -} - - -// 1) QString::isRightToLeft() sux -// 2) QString::isRightToLeft() is marked as internal (WTF?) -// 3) QString::isRightToLeft() does not seem to work on my setup -// 4) isStringRightToLeft() should behave much better than QString::isRightToLeft() therefore: -// 5) isStringRightToLeft() kicks ass -bool KateRenderer::isLineRightToLeft( KateLineLayoutPtr lineLayout ) const -{ - QString s = lineLayout->textLine()->string(); - int i = 0; - - // borrowed from QString::updateProperties() - while( i != s.length() ) - { - QChar c = s.at(i); - - switch(c.direction()) { - case QChar::DirL: - case QChar::DirLRO: - case QChar::DirLRE: - return false; - - case QChar::DirR: - case QChar::DirAL: - case QChar::DirRLO: - case QChar::DirRLE: - return true; - - default: - break; - } - i ++; - } - - return false; -#if 0 - // or should we use the direction of the widget? - QWidget* display = qobject_cast(view()->parent()); - if (!display) - return false; - return display->layoutDirection() == Qt::RightToLeft; -#endif -} - -int KateRenderer::cursorToX(const KateTextLayout& range, int col) const -{ - return cursorToX(range, KTextEditor::Cursor(range.line(), col)); -} - -int KateRenderer::cursorToX(const KateTextLayout& range, const KTextEditor::Cursor & pos) const -{ - Q_ASSERT(range.isValid()); - - return (int)range.lineLayout().cursorToX(pos.column()); -} - -int KateRenderer::cursorToX(const KateTextLayout& range, const KTextEditor::Cursor & pos, bool returnPastLine) const -{ - int x = cursorToX(range, pos); - int over = pos.column() - range.endCol(); - - if (returnPastLine && over > 0) - x += over * spaceWidth(); - - return x; -} - -KTextEditor::Cursor KateRenderer::xToCursor(const KateTextLayout & range, int x, bool returnPastLine ) const -{ - Q_ASSERT(range.isValid()); - KTextEditor::Cursor ret(range.line(), range.lineLayout().xToCursor(x)); - - // TODO wrong for RTL lines? - if (returnPastLine && range.endCol(true) == -1 && x > range.width() + range.xOffset()) - ret.setColumn(ret.column() + ((x - (range.width() + range.xOffset())) / spaceWidth())); - - return ret; -} - -void KateRenderer::setCaretOverrideColor(const QColor& color) -{ - m_caretOverrideColor = color; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/render/katerenderer.h b/part/render/katerenderer.h deleted file mode 100644 index 64a39f6..0000000 --- a/part/render/katerenderer.h +++ /dev/null @@ -1,349 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2003-2005 Hamish Rodda - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_RENDERER_H__ -#define __KATE_RENDERER_H__ - -#include -#include "katetextline.h" -#include "katelinelayout.h" - -#include -#include -#include -#include - -class KateDocument; -class KateView; -class KateRendererConfig; -class KateRenderRange; -namespace KTextEditor { class Range; } - -class KateLineLayout; -typedef KSharedPtr KateLineLayoutPtr; - -/** - * Handles all of the work of rendering the text - * (used for the views and printing) - * - **/ -class KateRenderer -{ -public: - /** - * Style of Caret (Vertical line or block) - */ - enum caretStyles { - Line, - Block - }; - - /** - * Constructor - * @param doc document to render - * @param view view which is output (0 for example for rendering to print) - */ - explicit KateRenderer(KateDocument* doc, KateView *view = 0); - - /** - * Destructor - */ - ~KateRenderer(); - - /** - * Returns the document to which this renderer is bound - */ - KateDocument* doc() const { return m_doc; } - - /** - * Returns the view to which this renderer is bound - */ - KateView* view() const { return m_view; } - - /** - * update the highlighting attributes - * (for example after an hl change or after hl config changed) - */ - void updateAttributes (); - - /** - * Determine whether the caret (text cursor) will be drawn. - * @return should it be drawn? - */ - inline bool drawCaret() const { return m_drawCaret; } - - /** - * Set whether the caret (text cursor) will be drawn. - * @param drawCaret should caret be drawn? - */ - void setDrawCaret(bool drawCaret); - - /** - * The style of the caret (text cursor) to be painted. - * @return caretStyle - */ - inline KateRenderer::caretStyles caretStyle() const { return m_caretStyle; } - - /** - * Set the style of caret to be painted. - * @param style style to set - */ - void setCaretStyle(KateRenderer::caretStyles style); - - /** - * Set a \a brush with which to override drawing of the caret. Set to QColor() to clear. - */ - void setCaretOverrideColor(const QColor& color); - - /** - * @returns whether tabs should be shown (ie. a small mark - * drawn to identify a tab) - * @return tabs should be shown - */ - inline bool showTabs() const { return m_showTabs; } - - /** - * Set whether a mark should be painted to help identifying tabs. - * @param showTabs show the tabs? - */ - void setShowTabs(bool showTabs); - - /** - * @returns whether trailing spaces should be shown. - */ - inline bool showTrailingSpaces() const { return m_showSpaces; } - - /** - * Set whether a mark should be painted for trailing spaces. - */ - void setShowTrailingSpaces(bool showSpaces); - - /** - * Sets the width of the tab. Helps performance. - * @param tabWidth new tab width - */ - void setTabWidth(int tabWidth); - - /** - * @returns whether indent lines should be shown - * @return indent lines should be shown - */ - bool showIndentLines() const; - - /** - * Set whether a guide should be painted to help identifying indent lines. - * @param showLines show the indent lines? - */ - void setShowIndentLines(bool showLines); - - /** - * Sets the width of the tab. Helps performance. - * @param indentWidth new indent width - */ - void setIndentWidth(int indentWidth); - - /** - * Show the view's selection? - * @return show sels? - */ - inline bool showSelections() const { return m_showSelections; } - - /** - * Set whether the view's selections should be shown. - * The default is true. - * @param showSelections show the selections? - */ - void setShowSelections(bool showSelections); - - /** - * Change to a different font (soon to be font set?) - */ - void increaseFontSizes(); - void decreaseFontSizes(); - const QFont& currentFont() const; - const QFontMetrics& currentFontMetrics() const; - - /** - * @return whether the renderer is configured to paint in a - * printer-friendly fashion. - */ - bool isPrinterFriendly() const; - - /** - * Configure this renderer to paint in a printer-friendly fashion. - * - * Sets the other options appropriately if true. - */ - void setPrinterFriendly(bool printerFriendly); - - /** - * Text width & height calculation functions... - */ - void layoutLine(KateLineLayoutPtr line, int maxwidth = -1, bool cacheLayout = false) const; - - /** - * This is a smaller QString::isRightToLeft(). It's also marked as internal to kate - * instead of internal to Qt, so we can modify. This method searches for the first - * strong character in the paragraph and then returns its direction. In case of a - * line without any strong characters, the direction is forced to be LTR. - * - * Back in KDE 4.1 this method counted chars, which lead to unwanted side effects. - * (see https://bugs.kde.org/show_bug.cgi?id=178594). As this function is internal - * the way it work will probably change between releases. Be warned! - */ - bool isLineRightToLeft( KateLineLayoutPtr lineLayout ) const; - - /** - * The ultimate decoration creation function. - * - * \param range line to return decoration for - * \param selectionsOnly return decorations for selections and/or dynamic highlighting. - */ - QList decorationsForLine(const Kate::TextLine& textLine, int line, bool selectionsOnly = false, KateRenderRange* completionHighlight = 0L, bool completionSelected = false) const; - - // Width calculators - uint spaceWidth() const; -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED uint textWidth(const Kate::TextLine &, int cursorCol); - KDE_DEPRECATED uint textWidth(const Kate::TextLine &textLine, uint startcol, uint maxwidth, bool *needWrap, int *endX = 0); - KDE_DEPRECATED uint textWidth(const KTextEditor::Cursor& cursor); -#endif - - /** - * Returns the x position of cursor \p col on the line \p range. - */ - int cursorToX(const KateTextLayout& range, int col) const; - /// \overload - int cursorToX(const KateTextLayout& range, const KTextEditor::Cursor& pos) const; - /// \overload - int cursorToX(const KateTextLayout& range, const KTextEditor::Cursor& pos, bool returnPastLine) const; - - /** - * Returns the real cursor which is occupied by the specified x value, or that closest to it. - * If \p returnPastLine is true, the column will be extrapolated out with the assumption - * that the extra characters are spaces. - */ - KTextEditor::Cursor xToCursor(const KateTextLayout& range, int x, bool returnPastLine = false) const; - - // Font height - uint fontHeight(); - - // Line height - int lineHeight(); - - // Document height - uint documentHeight(); - - // Selection boundaries - bool getSelectionBounds(int line, int lineLength, int &start, int &end) const; - - /** - * This is the ultimate function to perform painting of a text line. - * - * The text line is painted from the upper limit of (0,0). To move that, - * apply a transform to your painter. - * - * @param paint painter to use - * @param range layout to use in painting this line - * @param xStart starting width in pixels. - * @param xEnd ending width in pixels. - * @param cursor position of the caret, if placed on the current line. - */ - void paintTextLine(QPainter& paint, KateLineLayoutPtr range, int xStart, int xEnd, const KTextEditor::Cursor* cursor = 0L); - - /** - * Paint the background of a line - * - * Split off from the main @ref paintTextLine method to make it smaller. As it's being - * called only once per line it shouldn't noticably affect performance and it - * helps readability a LOT. - * - * @param paint painter to use - * @param layout layout to use in painting this line - * @param currentViewLine if one of the view lines is the current line, set - * this to the index; otherwise -1. - * @param xStart starting width in pixels. - * @param xEnd ending width in pixels. - */ - void paintTextLineBackground(QPainter& paint, KateLineLayoutPtr layout, int currentViewLine, int xStart, int xEnd); - - /** - * This takes an in index, and returns all the attributes for it. - * For example, if you have a ktextline, and want the KTextEditor::Attribute - * for a given position, do: - * - * attribute(myktextline->attribute(position)); - */ - KTextEditor::Attribute::Ptr attribute(uint pos) const; - KTextEditor::Attribute::Ptr specificAttribute(int context) const; - - private: - /** - * Paint a trailing space on position (x, y). - */ - void paintTrailingSpace(QPainter &paint, qreal x, qreal y); - /** - * Paint a tab stop marker on position (x, y). - */ - void paintTabstop(QPainter &paint, qreal x, qreal y); - - /** - * Paint a non-breaking space marker on position (x, y). - */ - void paintNonBreakSpace(QPainter &paint, qreal x, qreal y); - - /** Paint a SciTE-like indent marker. */ - void paintIndentMarker(QPainter &paint, uint x, uint y); - - void assignSelectionBrushesFromAttribute(QTextLayout::FormatRange& target, const KTextEditor::Attribute& attribute) const; - - KateDocument *const m_doc; - KateView *const m_view; - - // cache of config values - int m_tabWidth; - int m_indentWidth; - - // some internal flags - KateRenderer::caretStyles m_caretStyle; - bool m_drawCaret; - bool m_showSelections; - bool m_showTabs; - bool m_showSpaces; - bool m_printerFriendly; - QColor m_caretOverrideColor; - - QList m_attributes; - - /** - * Configuration - */ - public: - inline KateRendererConfig *config () const { return m_config; } - - void updateConfig (); - - private: - KateRendererConfig *const m_config; -}; - -#endif diff --git a/part/render/katerenderrange.cpp b/part/render/katerenderrange.cpp deleted file mode 100644 index f6793df..0000000 --- a/part/render/katerenderrange.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003-2005 Hamish Rodda - * Copyright (C) 2007 Mirko Stocker - * Copyright (C) 2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katerenderrange.h" - -#include - -#include - -void mergeAttributes(KTextEditor::Attribute::Ptr base, KTextEditor::Attribute::Ptr add) -{ - if(!add) - return; - - bool hadBg = base->hasProperty(KTextEditor::Attribute::BackgroundBrush); - bool hasBg = add->hasProperty(KTextEditor::Attribute::BackgroundBrush); - - bool hadFg = base->hasProperty(KTextEditor::Attribute::ForegroundBrush); - bool hasFg = add->hasProperty(KTextEditor::Attribute::ForegroundBrush); - - if(((!hadBg || !hasBg) && (!hadFg || !hasFg))) { - //Nothing to blend - *base += *add; - return; - } - - //We eventually have to blend - - QBrush baseBgBrush, baseFgBrush; - - if(hadBg) - baseBgBrush = base->background(); - - if(hadFg) - baseFgBrush = base->foreground(); - - *base += *add; - - if(hadBg && hasBg) - { - QBrush bg = add->background(); - if(!bg.isOpaque()) { - QColor mixWithColor = bg.color(); - mixWithColor.setAlpha(255); - bg.setColor(KColorUtils::mix(baseBgBrush.color(), mixWithColor, bg.color().alphaF())); - base->setBackground(bg); - } - } - if(hadFg && hasFg) - { - QBrush fg = add->foreground(); - if(!fg.isOpaque()) { - QColor mixWithColor = fg.color(); - mixWithColor.setAlpha(255); - fg.setColor(KColorUtils::mix(baseFgBrush.color(), mixWithColor, fg.color().alphaF())); - base->setForeground(fg); - } - } -} - -bool KateRenderRange::isReady() const { - return false; -} - -NormalRenderRange::NormalRenderRange() - : m_currentRange(0) -{ -} - -NormalRenderRange::~NormalRenderRange() -{ - QListIterator it = m_ranges; - while (it.hasNext()) - delete it.next().first; -} - -void NormalRenderRange::addRange(KTextEditor::Range* range, KTextEditor::Attribute::Ptr attribute) -{ - m_ranges.append(pairRA(range, attribute)); -} - -KTextEditor::Cursor NormalRenderRange::nextBoundary() const -{ - return m_nextBoundary; -} - -bool NormalRenderRange::advanceTo(const KTextEditor::Cursor& pos) -{ - int index = m_currentRange; - while (index < m_ranges.count()) { - const pairRA& p = m_ranges.at(index); - KTextEditor::Range* r = p.first; - if (r->end() <= pos) { - ++index; - } else { - bool ret = index != m_currentRange; - m_currentRange = index; - - if (r->start() > pos) { - m_nextBoundary = r->start(); - } else { - m_nextBoundary = r->end(); - } - if (r->contains(pos)) { - m_currentAttribute = p.second; - } else { - m_currentAttribute.clear(); - } - - return ret; - } - } - - m_nextBoundary = KTextEditor::Cursor(INT_MAX, INT_MAX); - m_currentAttribute.clear(); - return false; -} - -KTextEditor::Attribute::Ptr NormalRenderRange::currentAttribute() const -{ - return m_currentAttribute; -} - -KTextEditor::Cursor RenderRangeList::nextBoundary() const -{ - KTextEditor::Cursor ret = m_currentPos; - bool first = true; - foreach (KateRenderRange* r, *this) { - if (first) { - ret = r->nextBoundary(); - first = false; - - } else { - KTextEditor::Cursor nb = r->nextBoundary(); - if (ret > nb) - ret = nb; - } - } - return ret; -} - -RenderRangeList::~RenderRangeList() -{ -} - -void RenderRangeList::advanceTo(const KTextEditor::Cursor& pos) -{ - foreach (KateRenderRange* r, *this) - r->advanceTo(pos); - - //Delete lists that are ready, else the list may get too large due to temporaries - for(int a = size()-1; a >= 0; --a) { - KateRenderRange* r = at(a); - if(r->isReady()) { - delete r; - removeAt(a); - } - } -} - -bool RenderRangeList::hasAttribute() const -{ - foreach (KateRenderRange* r, *this) - if (r->currentAttribute()) - return true; - - return false; -} - -KTextEditor::Attribute::Ptr RenderRangeList::generateAttribute() const -{ - KTextEditor::Attribute::Ptr a; - bool ownsAttribute = false; - - foreach (KateRenderRange* r, *this) { - if (KTextEditor::Attribute::Ptr a2 = r->currentAttribute()) { - if(!a) { - a = a2; - }else { - if(!ownsAttribute) { - //Make an own copy of the attribute.. - ownsAttribute = true; - a = new KTextEditor::Attribute(*a); - } - mergeAttributes(a, a2); - } - } - } - - return a; -} - diff --git a/part/render/katerenderrange.h b/part/render/katerenderrange.h deleted file mode 100644 index 69cda87..0000000 --- a/part/render/katerenderrange.h +++ /dev/null @@ -1,79 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003-2005 Hamish Rodda - * Copyright (C) 2008 David Nolden - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATERENDERRANGE_H -#define KATERENDERRANGE_H - -#include -#include - -#include -#include -#include - -class KateView; -class RenderRangeList; - -class KateRenderRange -{ - public: - virtual ~KateRenderRange() {} - virtual KTextEditor::Cursor nextBoundary() const = 0; - virtual bool advanceTo(const KTextEditor::Cursor& pos) = 0; - virtual KTextEditor::Attribute::Ptr currentAttribute() const = 0; - virtual bool isReady() const; -}; - -typedef QPair pairRA; - -class NormalRenderRange : public KateRenderRange -{ - public: - NormalRenderRange(); - virtual ~NormalRenderRange(); - - void addRange(KTextEditor::Range* range, KTextEditor::Attribute::Ptr attribute); - - virtual KTextEditor::Cursor nextBoundary() const; - virtual bool advanceTo(const KTextEditor::Cursor& pos); - virtual KTextEditor::Attribute::Ptr currentAttribute() const; - - private: - QList m_ranges; - KTextEditor::Cursor m_nextBoundary; - KTextEditor::Attribute::Ptr m_currentAttribute; - int m_currentRange; -}; - -class RenderRangeList : public QList -{ - public: - ~RenderRangeList(); - KTextEditor::Cursor nextBoundary() const; - void advanceTo(const KTextEditor::Cursor& pos); - bool hasAttribute() const; - KTextEditor::Attribute::Ptr generateAttribute() const; - - private: - KTextEditor::Cursor m_currentPos; -}; - -#endif diff --git a/part/render/katetextlayout.cpp b/part/render/katetextlayout.cpp deleted file mode 100644 index 86c02ca..0000000 --- a/part/render/katetextlayout.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002-2005 Hamish Rodda - Copyright (C) 2003 Anakim Border - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katetextlayout.h" - -#include - -KateTextLayout::KateTextLayout(KateLineLayoutPtr line, int viewLine) - : m_lineLayout(line) - , m_viewLine(viewLine) - , m_startX(m_viewLine ? -1 : 0) - , m_invalidDirty(true) -{ - if (isValid()) - m_textLayout = m_lineLayout->layout()->lineAt(m_viewLine); -} - -bool KateTextLayout::isDirty( ) const -{ - if (!isValid()) - return m_invalidDirty; - - return m_lineLayout->isDirty(viewLine()); -} - -bool KateTextLayout::setDirty( bool dirty ) -{ - if (!isValid()) - return (m_invalidDirty = dirty); - - return m_lineLayout->setDirty(viewLine(), dirty); -} - -bool KateTextLayout::includesCursor(const KTextEditor::Cursor& realCursor) const -{ - return realCursor.line() == line() && realCursor.column() >= startCol() && (!wrap() || realCursor.column() < endCol()); -} - -int KateTextLayout::xOffset() const -{ - if (!isValid()) - return 0; - - return startX() ? m_lineLayout->shiftX() : 0; -} - -void KateTextLayout::debugOutput() const -{ - kDebug( 13033 ) << "KateTextLayout: " << m_lineLayout << " valid " << isValid() << " line " << m_lineLayout->line() << " (" << line() << ") cols [" << startCol() << " -> " << endCol() << "] x [" << startX() << " -> " << endX() << " off " << m_lineLayout->shiftX() << "] wrap " << wrap(); -} - -bool operator> (const KateTextLayout& r, const KTextEditor::Cursor& c) -{ - return r.line() > c.line() || r.endCol() > c.column(); -} - -bool operator>= (const KateTextLayout& r, const KTextEditor::Cursor& c) -{ - return r.line() > c.line() || r.endCol() >= c.column(); -} - -bool operator< (const KateTextLayout& r, const KTextEditor::Cursor& c) -{ - return r.line() < c.line() || r.startCol() < c.column(); -} - -bool operator<= (const KateTextLayout& r, const KTextEditor::Cursor& c) -{ - return r.line() < c.line() || r.startCol() <= c.column(); -} - -bool KateTextLayout::isValid( ) const -{ - return m_lineLayout && m_lineLayout->isValid() && m_viewLine >= 0 && m_viewLine < m_lineLayout->viewLineCount(); -} - -int KateTextLayout::line( ) const -{ - if (!isValid()) - return -1; - - return m_lineLayout->line(); -} - -int KateTextLayout::virtualLine( ) const -{ - if (!isValid()) - return -1; - - return m_lineLayout->virtualLine(); -} - -int KateTextLayout::viewLine( ) const -{ - if (!isValid()) - return 0; - - return m_viewLine; -} - -const QTextLine & KateTextLayout::lineLayout( ) const -{ - return m_textLayout; -} - -KateLineLayoutPtr KateTextLayout::kateLineLayout( ) const -{ - return m_lineLayout; -} - -int KateTextLayout::startCol( ) const -{ - if (!isValid()) - return 0; - - return lineLayout().textStart(); -} - -KTextEditor::Cursor KateTextLayout::start( ) const -{ - return KTextEditor::Cursor(line(), startCol()); -} - -int KateTextLayout::endCol(bool indicateEOL) const -{ - if (!isValid()) - return 0; - - if (indicateEOL) - if (viewLine() == kateLineLayout()->viewLineCount() - 1) - return -1; - - return startCol() + m_textLayout.textLength(); -} - -KTextEditor::Cursor KateTextLayout::end(bool indicateEOL) const -{ - return KTextEditor::Cursor(line(), endCol(indicateEOL)); -} - -int KateTextLayout::length( ) const -{ - if (!isValid()) - return 0; - - return m_textLayout.textLength(); -} - -bool KateTextLayout::isEmpty( ) const -{ - if (!isValid()) - return true; - - return startCol() == 0 && endCol() == 0; -} - -bool KateTextLayout::wrap( ) const -{ - if (!isValid()) - return false; - - return viewLine() < m_lineLayout->viewLineCount() - 1; -} - -int KateTextLayout::startX( ) const -{ - if (!isValid()) - return 0; - - if (m_startX == -1) - // viewLine is already > 0, from the constructor - for (int i = 0; i < viewLine(); ++i) - m_startX += (int)m_lineLayout->layout()->lineAt(i).naturalTextWidth(); - - return m_startX; -} - -int KateTextLayout::endX( ) const -{ - if (!isValid()) - return 0; - - return startX() + (int)m_textLayout.naturalTextWidth(); -} - -int KateTextLayout::width( ) const -{ - if (!isValid()) - return 0; - - return (int)m_textLayout.naturalTextWidth(); -} - -KateTextLayout KateTextLayout::invalid( ) -{ - return KateTextLayout(); -} - -bool KateTextLayout::isRightToLeft() const -{ - if (m_lineLayout) - return m_lineLayout->isRightToLeft(); - - return false; -} diff --git a/part/render/katetextlayout.h b/part/render/katetextlayout.h deleted file mode 100644 index ce5f617..0000000 --- a/part/render/katetextlayout.h +++ /dev/null @@ -1,112 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002-2005 Hamish Rodda - Copyright (C) 2003 Anakim Border - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _KATE_TEXTLAYOUT_H_ -#define _KATE_TEXTLAYOUT_H_ - -#include - -#include - -#include "katelinelayout.h" - - -class KateLineLayout; -typedef KSharedPtr KateLineLayoutPtr; - -/** - * This class represents one visible line of text; with dynamic wrapping, - * many KateTextLayouts can be needed to represent one actual line of text - * (ie. one KateLineLayout) - */ -class KateTextLayout -{ - friend class KateLineLayout; - friend class KateLayoutCache; - template friend class QVector; - - public: - bool isValid() const; - static KateTextLayout invalid(); - - int line() const; - int virtualLine() const; - /** Return the index of this visual line inside the document line - (KateLineLayout). */ - int viewLine() const; - - const QTextLine& lineLayout() const; - KateLineLayoutPtr kateLineLayout() const; - - int startCol() const; - KTextEditor::Cursor start() const; - - /** - * Return the end column of this text line. - * - * \param indicateEOL set to true to return -1 if this layout is the - * end of the line, otherwise false to return the end column number - */ - int endCol(bool indicateEOL = false) const; - - /** - * Return the end position of this text line. - * - * \param indicateEOL set to true to return -1 if this layout is the - * end of the line, otherwise false to return the end column number - */ - KTextEditor::Cursor end(bool indicateEOL = false) const; - - int length() const; - bool isEmpty() const; - - bool wrap() const; - - bool isDirty() const; - bool setDirty(bool dirty = true); - - int startX() const; - int endX() const; - int width() const; - - int xOffset() const; - - bool isRightToLeft() const; - - bool includesCursor(const KTextEditor::Cursor& realCursor) const; - - friend bool operator> (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator>= (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator< (const KateLineLayout& r, const KTextEditor::Cursor& c); - friend bool operator<= (const KateLineLayout& r, const KTextEditor::Cursor& c); - - void debugOutput() const; - - private: - explicit KateTextLayout(KateLineLayoutPtr line = KateLineLayoutPtr(), int viewLine = 0); - - KateLineLayoutPtr m_lineLayout; - QTextLine m_textLayout; - - int m_viewLine; - mutable int m_startX; - bool m_invalidDirty; -}; - -#endif diff --git a/part/script/data/05_cursor.js b/part/script/data/05_cursor.js deleted file mode 100644 index c3fe081..0000000 --- a/part/script/data/05_cursor.js +++ /dev/null @@ -1,77 +0,0 @@ -// This file is part of the Kate project within KDE. -// (C) 2009 Dominik Haumann -// License: LGPL v2 or v3 - -/** - * Prototype Cursor. - * - * \section cursor_intro Introduction - * The Cursor class provides the two properties \p line and \p column. Since a - * lot of text operations are based on lines and columns such as inserting text - * at a cursor position, the Cursor class plays a central role in KatePart - * scripting. The entire scripting API is usually based on cursors whenever - * possible. - * - * \section cursor_usage Using Cursors - * There are several ways to construct a Cursor: - * \code - * var cursor1 = new Cursor(); // constructs a (valid) cursor at position (0, 0) - * var cursor2 = new Cursor(2, 4); // constructs a cursor at position (2, 4) - * var cursor3 = new Cursor(cursor2); // copies the cursor2 - * var cursor4 = new Cursor().invalid(); // constructs invalid cursor at (-1, -1) - * \endcode - * - * There are several convenience member functions that easy working with - * Cursors. Use isValid() to check whether a Cursor is a valid text cursor. - * To compare two cursors either use equals() or compareTo(). - * - * \see Range - */ -function Cursor() -{ - if (arguments.length == 0) { - return new Cursor(0, 0); - } else if (arguments.length == 1 && typeof arguments[0] == "object") { - // assume: cursor = new Cursor(otherCursor); - return arguments[0].clone(); - } else if (arguments.length == 2 && typeof arguments[0] == "number" - && typeof arguments[1] == "number") { - // assume: cursor = new Cursor(line, column); - this.line = parseInt(arguments[0]); - this.column = parseInt(arguments[1]); - } else { - throw "Wrong usage of Cursor constructor"; - } - - this.clone = function() { - return new Cursor(this.line, this.column); - }; - - this.isValid = function() { - return (this.line >= 0) && (this.column >= 0); - }; - - this.invalid = function() { - return new Cursor(-1, -1); - }; - - this.compareTo = function(other) { - if (this.line > other.line || (this.line == other.line && this.column > other.column)) { - return 1; - } else if (this.line < other.line || (this.line == other.line && this.column < other.column)) { - return -1; - } else { - return 0; - } - }; - - this.equals = function(other) { - return (this.line == other.line && this.column == other.column); - }; - - this.toString = function() { - return "Cursor(" + this.line+ ", " + this.column+ ")"; - }; -} - - diff --git a/part/script/data/10_range.js b/part/script/data/10_range.js deleted file mode 100644 index a4dbc5b..0000000 --- a/part/script/data/10_range.js +++ /dev/null @@ -1,88 +0,0 @@ -// This file is part of the Kate project within KDE. -// (C) 2009 Dominik Haumann -// License: LGPL v2 or v3 - -/** - * Prototype Range. - */ -function Range() -{ - if (arguments.length == 0) { - return new Range(0, 0, 0, 0); - } else if (arguments.length == 1 && typeof arguments[0] == "object") { - // assume: range = new Range(otherRange); - return arguments[0].clone(); - } else if (arguments.length == 2 && typeof arguments[0] == "object" - && typeof arguments[1] == "object") { - // assume: range = new Range(startCursor, endCursor); - this.start = arguments[0].clone(); - this.end = arguments[1].clone(); - } else if (arguments.length == 4 && typeof arguments[0] == "number" - && typeof arguments[1] == "number" - && typeof arguments[2] == "number" - && typeof arguments[3] == "number") { - this.start = new Cursor(arguments[0], arguments[1]); - this.end = new Cursor(arguments[2], arguments[3]); - } else { - throw "Wrong usage of Range constructor"; - } - - this.clone = function() { - return new Range(this.start, this.end); - }; - - this.isValid = function() { - return this.start.isValid() && this.end.isValid(); - }; - - this.invalid = function() { - return new Range(-1, -1, -1, -1); - }; - - this.contains = function(cursorOrRange) { - if (cursorOrRange.start && cursorOrRange.end) { - // assume a range - return (cursorOrRange.start.compareTo(this.start) >= 0 && - cursorOrRange.end.compareTo(this.end) <= 0); - } else { - // assume a cursor - return (cursorOrRange.compareTo(this.start) >= 0 && - cursorOrRange.compareTo(this.end) < 0); - } - }; - - this.containsColumn = function(column) { - return (column >= this.start.column) && (column < this.end.column); - }; - - this.containsLine = function(line) { - return (line > this.start.line || (line == this.start.line && this.start.column == 0)) && line < this.end.line; - }; - - this.overlaps = function(range) { - if (range.start.compareTo(this.start) <= 0) { - return range.end.compareTo(this.start) > 0; - } else if (range.end.compareTo(this.end) >= 0) { - return range.start.compareTo(this.end) < 0; - } else { - return this.contains(range); - } - }; - - this.overlapsLine = function(line) { - return (line >= this.start.line && line <= this.end.line); - } - - this.overlapsColumn = function(column) { - return column >= this.start.column && column <= this.end.column; - } - - this.equals = function(other) { - return (this.start.equals(other.start) && this.end.equals(other.end)); - }; - - this.toString = function() { - return "Range(" + this.start + ", " + this.end + ")"; - }; -} - diff --git a/part/script/data/CMakeLists.txt b/part/script/data/CMakeLists.txt deleted file mode 100644 index 5093a5d..0000000 --- a/part/script/data/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -# install default api -install( FILES 05_cursor.js 10_range.js DESTINATION ${DATA_INSTALL_DIR}/katepart/api ) - -# install some javascripts -install( FILES utils.js lisp.js lua.js cstyle.js python.js ruby.js lilypond.js haskell.js xml.js DESTINATION ${DATA_INSTALL_DIR}/katepart/script ) diff --git a/part/script/data/cstyle.js b/part/script/data/cstyle.js deleted file mode 100644 index ce2d857..0000000 --- a/part/script/data/cstyle.js +++ /dev/null @@ -1,883 +0,0 @@ -/** kate-script - * name: C Style - * license: LGPL - * author: Dominik Haumann , Milian Wolff - * revision: 1 - * kate-version: 3.4 - * type: indentation - * - * This file is part of the Kate Project. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN USER CONFIGURATION -var cfgIndentCase = true; // indent 'case' and 'default' in a switch? -var cfgIndentNamespace = true; // indent after 'namespace'? -var cfgAutoInsertStar = true; // auto insert '*' in C-comments -var cfgSnapSlash = true; // snap '/' to '*/' in C-comments -var cfgAutoInsertSlashes = false; // auto insert '//' after C++-comments -var cfgAccessModifiers = 0; // indent level of access modifiers, relative to the class indent level - // set to -1 to disable auto-indendation after access modifiers. -//END USER CONFIGURATION - -// indent gets three arguments: line, indentwidth in spaces, typed character -// indent - -// specifies the characters which should trigger indent, beside the default '\n' -triggerCharacters = "{})/:;#"; - -var debugMode = false; - -function dbg() { - if (debugMode) { - debug.apply(this, arguments); - } -} - - -//BEGIN global variables and functions -// maximum number of lines we look backwards/forward to find out the indentation -// level (the bigger the number, the longer might be the delay) -var gLineDelimiter = 50; // number - -var gIndentWidth = 4; -var gMode = "C"; -//END global variables and functions - - -/** - * Search for a corresponding '{' and return its indentation level. If not found - * return null; (line/column) are the start of the search. - */ -function findLeftBrace(line, column) -{ - var cursor = document.anchor(line, column, '{'); - if (cursor.isValid()) { - var parenthesisCursor = tryParenthesisBeforeBrace(cursor.line, cursor.column); - if (parenthesisCursor.isValid()) - cursor = parenthesisCursor; - - dbg("findLeftBrace: success in line " + cursor.line); - return document.firstVirtualColumn(cursor.line); - } - - return -1; -} - -/** - * Find last non-empty line that is not inside a comment or preprocessor - */ -function lastNonEmptyLine(line) -{ - while (true) { - line = document.prevNonEmptyLine(line); - if ( line == -1 ) { - return -1; - } - var string = document.line(line).ltrim(); - ///TODO: cpp multiline comments - ///TODO: multiline macros - if ( string.startsWith("//") || string.startsWith('#') ) { - --line; - continue; - } - break; - } - - return line; -} - -/** - * Returns true when string ends with @p needle. - * False otherwise. - */ -String.prototype.endsWith = function(needle) -{ - return this.substr(- needle.length) == needle; -} - -/** - * Returns true when string starts with @p needle. - * False otherwise. - */ -String.prototype.startsWith = function(needle) -{ - return this.substr(0, needle.length) == needle; -} - -/** - * Returns @p string without leading spaces. - */ -String.prototype.ltrim = function() -{ - var i = 0; - for ( ; i < this.length && (this[i] == ' ' || this[i] == '\t'); ++i ) { - // continue - } - return this.substr(i); -} - -/** - * Returns @p string without trailing spaces. - */ -String.prototype.rtrim = function() -{ - if ( this.length == 0 ) { - return ""; - } - var i = this.length - 1; - for ( ; i >= 0 && (this[i] == ' ' || this[i] == '\t'); --i ) { - // continue - } - return this.substr(0, i + 1); -} - -/** - * Returns @p string without leading or trailing spaces. - */ -String.prototype.trim = function() -{ - return this.rtrim().ltrim(); -} - -/** - * Returns true when @p needle is contained in this string, false otherwise. - */ -String.prototype.contains = function(needle) -{ - return this.indexOf(needle) !== -1; -} - -/** - * Fills with @p size @p char's. - * @return the string itself (for chain calls) - */ -String.prototype.fill = function(char, size) -{ - var string = ""; - for ( var i = 0; i < size; ++i ) { - string += char; - } - return string; -} - -/** - * Character at (line, column) has to be a '{'. - * Now try to find the right line for indentation for constructs like: - * if (a == b - * && c == d) { <- check for ')', and find '(', then return its indentation - * Returns null, if no success, otherwise an object {line, column} - */ -function tryParenthesisBeforeBrace(line, column) -{ - var firstColumn = document.firstColumn(line); - while (column > firstColumn && document.isSpace(line, --column)); - if (document.charAt(line, column) == ')') - return document.anchor(line, column, '('); - return new Cursor().invalid(); -} - -/** - * Check for default and case keywords and assume we are in a switch statement. - * Try to find a previous default, case or switch and return its indentation or - * -1 if not found. - */ -function trySwitchStatement(line) -{ - var currentString = document.line(line); - if (currentString.search(/^\s*(default\s*|case\b.*):/) == -1) - return -1; - - var indentation = -1; - var lineDelimiter = gLineDelimiter; - var currentLine = line; - - while (currentLine > 0 && lineDelimiter > 0) { - --currentLine; - --lineDelimiter; - if (document.firstColumn(currentLine) == -1) - continue; - - currentString = document.line(currentLine); - if (currentString.search(/^\s*(default\s*|case\b.*):/) != -1) { - indentation = document.firstVirtualColumn(currentLine); - break; - } else if (currentString.search(/^\s*switch\b/) != -1) { - indentation = document.firstVirtualColumn(currentLine); - if (cfgIndentCase) - indentation += gIndentWidth; - break; - } - } - - if (indentation != -1) dbg("trySwitchStatement: success in line " + currentLine); - return indentation; -} - -/** - * Check for private, protected, public, signals etc... and assume we are in a - * class definition. Try to find a previous private/protected/private... or - * class and return its indentation or null if not found. - */ -function tryAccessModifiers(line) -{ - if (cfgAccessModifiers < 0) - return -1; - - var currentString = document.line(line); - if (currentString.search(/^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$/) == -1) - return -1; - - var cursor = document.anchor(line, 0, '{'); - if (!cursor.isValid()) - return -1; - - var indentation = document.firstVirtualColumn(cursor.line); - for ( var i = 0; i < cfgAccessModifiers; ++i ) { - indentation += gIndentWidth; - } - - if (indentation != -1) dbg("tryAccessModifiers: success in line " + cursor.line); - return indentation; -} - - - -/** - * Get the position of the first non-space character - * return: position or -1, if there is no non-space character - */ -function firstNonSpace(text) -{ - if (text && text.search(/^(\s*)\S/) != -1) - return RegExp.$1.length; - - return -1; -} - -/** - * Get the position of the last non-space character - * return: position or -1, if there is no non-space character - */ -function lastNonSpace(text) -{ - if (text && text.search(/(.*)\S\s*$/) != -1) - return RegExp.$1.length; - - return -1; -} - -// /** -// * Check, whether the beginning of line is inside a "..." string context. -// * Note: the function does not check for comments -// * return: leading whitespaces as string, or null if not in a string -// */ -// function inString(line) -// { -// var currentLine = line; -// var currentString; -// -// // go line up as long as the previous line ends with an escape character '\' -// while (currentLine >= 0) { -// currentString = document.line(currentLine - 1); -// if (currentString.charAt(document.lastColumn(currentLine - 1)) != '\\') -// break; -// --currentLine; -// } -// -// // iterate through all lines and toggle bool insideString for every quote -// var insideString = false; -// var indentation = null; -// while (currentLine < line) { -// currentString = document.line(currentLine); -// var char1; -// var i; -// var lineLength = document.lineLength(currentLine); -// for (i = 0; i < lineLength; ++i) { -// char1 = currentString.charAt(i); -// if (char1 == "\\") { -// // skip escaped character -// ++i; -// } else if (char1 == "\"") { -// insideString = !insideString; -// if (insideString) -// indentation = currentString.substring(0, document.firstColumn(currentLine) + 1); -// } -// } -// ++currentLine; -// } -// -// return insideString ? indentation : null; -// } - -/** - * C comment checking. If the previous line begins with a "/*" or a "* ", then - * return its leading white spaces + ' *' + the white spaces after the * - * return: filler string or null, if not in a C comment - */ -function tryCComment(line) -{ - var currentLine = document.prevNonEmptyLine(line - 1); - if (currentLine < 0) - return -1; - - var indentation = -1; - - // we found a */, search the opening /* and return its indentation level - if (document.endsWith(currentLine, "*/", true)) { - var cursor = document.rfind(currentLine, document.lastColumn(currentLine), "/*"); - if (cursor.isValid() && cursor.column == document.firstColumn(cursor.line)) - indentation = document.firstVirtualColumn(cursor.line); - - if (indentation != -1) dbg("tryCComment: success (1) in line " + cursor.line); - return indentation; - } - - // inbetween was an empty line, so do not copy the "*" character - if (currentLine != line - 1) - return -1; - - var firstPos = document.firstColumn(currentLine); - var lastPos = document.lastColumn(currentLine); - var char1 = document.charAt(currentLine, firstPos); - var char2 = document.charAt(currentLine, firstPos + 1); - - if (char1 == '/' && char2 == '*') { - indentation = document.firstVirtualColumn(currentLine); - if (cfgAutoInsertStar) { - // only add '*', if there is none yet. - indentation += 1; - if (document.firstChar(line) != '*') - document.insertText(line, view.cursorPosition().column, '*'); - if (!document.isSpace(line, document.firstColumn(line) + 1) && !document.endsWith(line, "*/", true)) - document.insertText(line, document.firstColumn(line) + 1, ' '); - } - } else if (char1 == '*' && (firstPos == lastPos || document.isSpace(currentLine, firstPos + 1))) { - var currentString = document.line(currentLine); - currentString.search(/^\s*\*(\s*)/); - // in theory, we could search for opening /*, and use its indentation - // and then one alignment character. Let's not do this for now, though. - var end = RegExp.$1; - indentation = document.firstVirtualColumn(currentLine); - // only add '*', if there is none yet. - if (cfgAutoInsertStar && document.firstChar(line) != '*') { - document.insertText(line, view.cursorPosition().column, '*'); - if (!document.isSpace(line, document.firstColumn(line) + 1)) - document.insertText(line, document.firstColumn(line) + 1, ' '); - } - } - - if (indentation != -1) dbg("tryCComment: success (2) in line " + currentLine); - return indentation; -} - -/** - * C++ comment checking. when we want to insert slashes: - * //, ///, //! ///<, //!< and ////... - * return: filler string or null, if not in a star comment - * NOTE: otherwise comments get skipped generally and we use the last code-line - */ -function tryCppComment(line) -{ - var currentLine = line - 1; - if (currentLine < 0 || !cfgAutoInsertSlashes) - return -1; - - var indentation = -1; - var comment = document.startsWith(currentLine, "//", true); - - // allowed are: //, ///, //! ///<, //!< and ////... - if (comment) { - var firstPos = document.firstColumn(currentLine); - var currentString = document.line(currentLine); - - var char3 = currentString.charAt(firstPos + 2); - var char4 = currentString.charAt(firstPos + 3); - indentation = document.firstVirtualColumn(currentLine); - - if (cfgAutoInsertSlashes) { - if (char3 == '/' && char4 == '/') { - // match ////... and replace by only two: // - currentString.search(/^\s*(\/\/)/); - } else if (char3 == '/' || char3 == '!') { - // match ///, //!, ///< and //! - currentString.search(/^\s*(\/\/[\/!][<]?\s*)/); - } else { - // only //, nothing else - currentString.search(/^\s*(\/\/\s*)/); - } - document.insertText(line, view.cursorPosition().column, RegExp.$1); - } - } - - if (indentation != -1) dbg("tryCppComment: success in line " + currentLine); - return indentation; -} - -/** - * If the last non-empty line ends with a {, take its indentation level (or - * maybe the one found by tryParenthesisBeforeBrace()) and return it increased - * by 1 indetation level (special case: namespaces indentation depends on - * cfgIndentNamespace). If not found, return null. - */ -function tryBrace(line) -{ - function isNamespace(line, column) - { - if (document.firstColumn(line) == column && line > 0) - --line; - var currentString = document.line(line); - return (currentString.search(/^\s*namespace\b/) != -1); - } - - var currentLine = document.prevNonEmptyLine(line - 1); - if (currentLine < 0) - return -1; - - var lastPos = document.lastColumn(currentLine); - var indentation = -1; - - if (document.charAt(currentLine, lastPos) == '{') { - var cursor = tryParenthesisBeforeBrace(currentLine, lastPos); - if (cursor.isValid()) { - indentation = document.firstVirtualColumn(cursor.line) + gIndentWidth; - } else { - indentation = document.firstVirtualColumn(currentLine); - if (cfgIndentNamespace || !isNamespace(currentLine, lastPos)) - // take its indentation and add one indentation level - indentation += gIndentWidth; - } - } - - if (indentation != -1) dbg("tryBrace: success in line " + currentLine); - return indentation; -} - -/** - * Check for if, else, while, do, switch, private, public, protected, signals, - * default, case etc... keywords, as we want to indent then. If is - * non-null/true, then indentation is not increased. - * Note: The code is written to be called *after* tryCComment and tryCppComment! - */ -function tryCKeywords(line, isBrace) -{ - var currentLine = document.prevNonEmptyLine(line - 1); - if (currentLine < 0) - return -1; - - // if line ends with ')', find the '(' and check this line then. - var lastPos = document.lastColumn(currentLine); - var cursor = new Cursor().invalid(); - if (document.charAt(currentLine, lastPos) == ')') - cursor = document.anchor(currentLine, lastPos, '('); - if (cursor.isValid()) - currentLine = cursor.line; - - // found non-empty line - var currentString = document.line(currentLine); - if (currentString.search(/^\s*(if\b|for|do\b|while|switch|[}]?\s*else|((private|public|protected|case|default|signals|Q_SIGNALS).*:))/) == -1) - return -1; - dbg("Found first word: " + RegExp.$1); - lastPos = document.lastColumn(currentLine); - var lastChar = currentString.charAt(lastPos); - var indentation = -1; - - // ignore trailing comments see: https://bugs.kde.org/show_bug.cgi?id=189339 - var commentPos = currentString.indexOf("//") - if (commentPos != -1) { - currentString = currentString.substring(0, pos).rtrim(); - lastChar = currentString.charAt(currentString.length - 1); - } - - // try to ignore lines like: if (a) b; or if (a) { b; } - if (lastChar != ';' && lastChar != '}') { - // take its indentation and add one indentation level - indentation = document.firstVirtualColumn(currentLine); - if (!isBrace) - indentation += gIndentWidth; - } else if (lastChar == ';') { - // stuff like: - // for(int b; - // b < 10; - // --b) - cursor = document.anchor(currentLine, lastPos, '('); - if (cursor.isValid()) { - indentation = document.toVirtualColumn(cursor.line, cursor.column + 1); - } - } - - if (indentation != -1) dbg("tryCKeywords: success in line " + currentLine); - return indentation; -} - -/** - * Search for if, do, while, for, ... as we want to indent then. - * Return null, if nothing useful found. - * Note: The code is written to be called *after* tryCComment and tryCppComment! - */ -function tryCondition(line) -{ - var currentLine = document.prevNonEmptyLine(line - 1); - if (currentLine < 0) - return -1; - - // found non-empty line - var currentString = document.line(currentLine); - var lastPos = document.lastColumn(currentLine); - var lastChar = currentString.charAt(lastPos); - var indentation = -1; - - if (lastChar == ';' - && currentString.search(/^\s*(if\b|[}]?\s*else|do\b|while\b|for)/) == -1) - { - // idea: we had something like: - // if/while/for (expression) - // statement(); <-- we catch this trailing ';' - // Now, look for a line that starts with if/for/while, that has one - // indent level less. - var currentIndentation = document.firstVirtualColumn(currentLine); - if (currentIndentation == 0) - return -1; - - var lineDelimiter = 10; // 10 limit search, hope this is a sane value - while (currentLine > 0 && lineDelimiter > 0) { - --currentLine; - --lineDelimiter; - var firstPosVirtual = document.firstVirtualColumn(currentLine); - if (firstPosVirtual == -1) - continue; - - if (firstPosVirtual < currentIndentation) { - currentString = document.line(currentLine); - if (currentString.search(/^\s*(if\b|[}]?\s*else|do\b|while\b|for)[^{]*$/) != -1) - indentation = firstPosVirtual; - break; - } - } - } - - if (indentation != -1) dbg("tryCondition: success in line " + currentLine); - return indentation; -} - -/** - * If the non-empty line ends with ); or ',', then search for '(' and return its - * indentation; also try to ignore trailing comments. - */ -function tryStatement(line) -{ - var currentLine = lastNonEmptyLine(line - 1); - if (currentLine < 0) - return -1; - - var indentation = -1; - var currentString = document.line(currentLine); - if (currentString.endsWith('(')) { - // increase indent level - indentation = document.firstVirtualColumn(currentLine) + gIndentWidth; - dbg("tryStatement: success in line " + currentLine); - return indentation; - } - var alignOnSingleQuote = gMode == "PHP/PHP" || gMode == "JavaScript"; - // align on strings "..."\n => below the opening quote - // multi-language support: [\.+] for javascript or php - var result = /^(.*)(,|"|'|\))(;?)\s*[\.+]?\s*(\/\/.*|\/\*.*\*\/\s*)?$/.exec(currentString); - if (result != null && result.index == 0) { - var alignOnAnchor = result[3].length == 0 && result[2] != ')'; - // search for opening ", ' or ( - var cursor = new Cursor().invalid(); - if (result[2] == '"' || (alignOnSingleQuote && result[2] == "'")) { - while(true) { - var i = result[1].length - 1; // start from matched closing ' or " - // find string opener - for ( ; i >= 0; --i ) { - // make sure it's not commented out - if (currentString[i] == result[2] && (i == 0 || currentString[i - 1] != '\\')) { - // also make sure that this is not a line like '#include "..."' <-- we don't want to indent here - if (currentString.match(/^#include/)) { - return indentation; - } - cursor = new Cursor(currentLine, i); - break; - } - } - if (!alignOnAnchor && currentLine) { - // when we finished the statement (;) we need to get the first line and use it's indentation - // i.e.: $foo = "asdf"; -> align on $ - --i; // skip " or ' - // skip whitespaces and stuff like + or . (for PHP, JavaScript, ...) - for ( ; i >= 0; --i ) { - if (currentString[i] == ' ' || currentString[i] == "\t" - || currentString[i] == '.' || currentString[i] == '+') - { - continue; - } else { - break; - } - } - if ( i > 0 ) { - // there's something in this line, use it's indentation - break; - } else { - // go to previous line - --currentLine; - currentString = document.line(currentLine); - } - } else { - break; - } - } - } else if (result[2] == ',' && !currentString.match(/\(/)) { - // assume a function call: check for '(' brace - // - if not found, use previous indentation - // - if found, compare the indentation depth of current line and open brace line - // - if current indentation depth is smaller, use that - // - otherwise, use the '(' indentation + following white spaces - var currentIndentation = document.firstVirtualColumn(currentLine); - var braceCursor = document.anchor(currentLine, result[1].length, '('); - - if (!braceCursor.isValid() || currentIndentation < braceCursor.column) - indentation = currentIndentation; - else { - indentation = braceCursor.column + 1; - while (document.isSpace(braceCursor.line, indentation)) - ++indentation; - } - } else { - cursor = document.anchor(currentLine, result[1].length, '('); - } - if (cursor.isValid()) { - if (alignOnAnchor) { - currentLine = cursor.line; - var column = cursor.column; - if (result[2] != '"' && result[2] != "'") { - // place one column after the opening parens - column++; - } - var lastColumn = document.lastColumn(currentLine); - while (column < lastColumn && document.isSpace(currentLine, column)) - ++column; - indentation = document.toVirtualColumn(currentLine, column); - } else { - currentLine = cursor.line; - indentation = document.firstVirtualColumn(currentLine); - } - } - } else if ( currentString.rtrim().endsWith(';') ) { - indentation = document.firstVirtualColumn(currentLine); - } - - if (indentation != -1) dbg("tryStatement: success in line " + currentLine); - return indentation; -} - -/** - * find out whether we pressed return in something like {} or () or [] and indent properly: - * {} - * becomes: - * { - * | - * } - */ -function tryMatchedAnchor(line, alignOnly) -{ - var char = document.firstChar(line); - if ( char != '}' && char != ')' && char != ']' ) { - return -1; - } - // we pressed enter in e.g. () - var closingAnchor = document.anchor(line, 0, document.firstChar(line)); - if (!closingAnchor.isValid()) { - // nothing found, continue with other cases - return -1; - } - if (alignOnly) { - // when aligning only, don't be too smart and just take the indent level of the open anchor - return document.firstVirtualColumn(closingAnchor.line); - } - var lastChar = document.lastChar(line - 1); - var charsMatch = ( lastChar == '(' && char == ')' ) || - ( lastChar == '{' && char == '}' ) || - ( lastChar == '[' && char == ']' ); - var indentLine = -1; - var indentation = -1; - if ( !charsMatch && char != '}' ) { - // otherwise check whether the last line has the expected - // indentation, if not use it instead and place the closing - // anchor on the level of the openeing anchor - var expectedIndentation = document.firstVirtualColumn(closingAnchor.line) + gIndentWidth; - var actualIndentation = document.firstVirtualColumn(line - 1); - var indentation = -1; - if ( expectedIndentation <= actualIndentation ) { - if ( lastChar == ',' ) { - // use indentation of last line instead and place closing anchor - // in same column of the openeing anchor - document.insertText(line, document.firstColumn(line), "\n"); - view.setCursorPosition(line, actualIndentation); - // indent closing anchor - document.indent(new Range(line + 1, 0, line + 1, 1), document.toVirtualColumn(closingAnchor) / gIndentWidth); - // make sure we add spaces to align perfectly on closing anchor - var padding = document.toVirtualColumn(closingAnchor) % gIndentWidth; - if ( padding > 0 ) { - document.insertText(line + 1, document.column - padding, String().fill(' ', padding)); - } - indentation = actualIndentation; - } else if ( expectedIndentation == actualIndentation ) { - // otherwise don't add a new line, just use indentation of closing anchor line - indentation = document.firstVirtualColumn(closingAnchor.line); - } else { - // otherwise don't add a new line, just align on closing anchor - indentation = document.toVirtualColumn(closingAnchor); - } - dbg("tryMatchedAnchor: success in line " + closingAnchor.line); - return indentation; - } - } - // otherwise we i.e. pressed enter between (), [] or when we enter before curly brace - // increase indentation and place closing anchor on the next line - indentation = document.firstVirtualColumn(closingAnchor.line); - document.insertText(line, document.firstColumn(line), "\n"); - view.setCursorPosition(line, indentation); - // indent closing brace - document.indent(new Range(line + 1, 0, line + 1, 1), indentation / gIndentWidth); - dbg("tryMatchedAnchor: success in line " + closingAnchor.line); - return indentation + gIndentWidth; -} - -/** - * Indent line. - * Return filler or null. - */ -function indentLine(line, alignOnly) -{ - var firstChar = document.firstChar(line); - var lastChar = document.lastChar(line); - - var filler = -1; - - if (filler == -1) - filler = tryMatchedAnchor(line, alignOnly); - if (filler == -1) - filler = tryCComment(line); - if (filler == -1 && !alignOnly) - filler = tryCppComment(line); - if (filler == -1) - filler = trySwitchStatement(line); - if (filler == -1) - filler = tryAccessModifiers(line); - if (filler == -1) - filler = tryBrace(line); - if (filler == -1) - filler = tryCKeywords(line, firstChar == '{'); - if (filler == -1) - filler = tryCondition(line); - if (filler == -1) - filler = tryStatement(line); - - return filler; -} - -function processChar(line, c) -{ - if (c == ';' || !triggerCharacters.contains(c)) - return -2; - - var cursor = view.cursorPosition(); - if (!cursor) - return -2; - - var column = cursor.column; - var firstPos = document.firstColumn(line); - var lastPos = document.lastColumn(line); - - dbg("firstPos: " + firstPos); - dbg("column..: " + column); - - if (firstPos == column - 1 && c == '{') { - // todo: maybe look for if etc. - var filler = tryBrace(line); - if (filler == -1) - filler = tryCKeywords(line, true); - if (filler == -1) - filler = tryCComment(line); // checks, whether we had a "*/" - if (filler == -1) - filler = tryStatement(line); - if (filler == -1) - filler = -2; - - return filler; - } else if (firstPos == column - 1 && c == '}') { - var indentation = findLeftBrace(line, firstPos); - if (indentation == -1) - indentation = -2; - return indentation; - } else if (cfgSnapSlash && c == '/' && lastPos == column - 1) { - // try to snap the string "* /" to "*/" - var currentString = document.line(line); - if (currentString.search(/^(\s*)\*\s+\/\s*$/) != -1) { - currentString = RegExp.$1 + "*/"; - document.editBegin(); - document.removeLine(line); - document.insertLine(line, currentString); - view.setCursorPosition(line, currentString.length); - document.editEnd(); - } - return -2; - } else if (c == ':') { - // todo: handle case, default, signals, private, public, protected, Q_SIGNALS - var filler = trySwitchStatement(line); - if (filler == -1) - filler = tryAccessModifiers(line); - if (filler == -1) - filler = -2; - return filler; - } else if (c == ')' && firstPos == column - 1) { - // align on start of identifier of function call - var openParen = document.anchor(line, column - 1, '('); - if (openParen.isValid()) { - // get identifier - var callLine = document.line(openParen.line); - // strip starting from opening paren - callLine = callLine.substring(0, openParen.column - 1); - indentation = callLine.search(/\b(\w+)\s*$/); - if (indentation != -1) { - return document.toVirtualColumn(openParen.line, indentation); - } - } - } else if (firstPos == column - 1 && c == '#' && ( gMode == 'C' || gMode == 'C++' ) ) { - // always put preprocessor stuff upfront - return 0; - } - return -2; -} - -/** - * Process a newline character. - * This function is called whenever the user hits . - */ -function indent(line, indentWidth, ch) -{ - gIndentWidth = indentWidth; - gMode = document.highlightingModeAt(new Cursor(line, document.lineLength(line))); - var alignOnly = (ch == ""); - - if (ch != '\n' && !alignOnly) - return processChar(line, ch); - - return indentLine(line, alignOnly); -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/haskell.js b/part/script/data/haskell.js deleted file mode 100644 index 3f73bed..0000000 --- a/part/script/data/haskell.js +++ /dev/null @@ -1,369 +0,0 @@ -/** kate-script - * name: Haskell - * license: LGPL - * author: Erlend Hamberg - * revision: 2 - * kate-version: 3.4 - * type: indentation - */ - -// based on Paul Giannaro's Python indenter - -var debugMode = false; - -// words for which space character-triggered indentation should be done -var re_spaceIndent = /\bwhere\b|\bin\b|\belse\b/ - -// ‘|’-triggered indentation should only indent if the line starts with ‘|’ -var re_pipeIndent = /^\s*\|/ - -// regex for symbols -var re_symbols = /^\s*[!$#%&*+.\/<=>?@\\^|~-]/ - -// escapes text w.r.t. regex special chars -function escape(text) { - return text.replace(/(\/|\.|,|\+|\?|\||\*|\(|\)|\[|\]|\{|\}|\\)/g, "\\$1"); -} - -String.prototype.startsWith = function(prefix) { - return this.search(RegExp("^"+escape(prefix)+"(\\b|\\s|$)")) != -1; -} - -String.prototype.endsWith = function(suffix) { - return this.search(RegExp("(\\b|\\s|^)"+escape(suffix)+"\\s*$")) != -1; -} - -String.prototype.lastCharacter = function() { - var l = this.length; - if (l == 0) - return ''; - else - return this.charAt(l - 1); -} - -String.prototype.stripWhiteSpace = function() { - return this.replace(/^[ \t\n\r]+/, '').replace(/[ \t\n\r]+$/, ''); -} - - -function dbg(s) { - // debug to the term in blue so that it's easier to make out amongst all - // of Kate's other debug output. - if (debugMode) - debug("\u001B[34m" + s + "\u001B[0m"); -} - -var triggerCharacters = "|} "; - -// General notes: -// indent() returns the amount of characters (in spaces) to be indented. -// Special indent() return values: -// -2 = no indent -// -1 = keep last indent - -function indent(line, indentWidth, character) { - dbg(document.attribute.toString()); - dbg("indent character: '" + character + "'"); - var currentLine = document.line(line); - dbg("current line: " + currentLine); - var lastLine = document.line(line - 1); - dbg("last line: " + lastLine); - var lastCharacter = lastLine.lastCharacter(); - - // invocations triggered by a space character should be ignored unless the - // line starts with one of the words in re_spaceIndent - if (character == ' ') { - if (currentLine.search(re_spaceIndent) == -1 || - !document.isCode(line, document.lineLength(line) - 2)) { - dbg("skipping..."); - return -2; - } - } else if (character == '|') { - if (currentLine.search(re_pipeIndent) == -1 || - !document.isCode(line, document.lineLength(line) - 2)) { - dbg("skipping..."); - return -2; - } - } - - // we can't really indent line 0 - if (line == 0) - return -2; - - // make sure [some of] the last line is code - if (!document.isCode(line - 1, document.lineLength(line - 1) - 1) - && !document.isCode(line - 1, 0) - && lastCharacter != "\"" && lastCharacter != "'") { - dbg("attributes that we don't want! Returning"); - return -1; - } - - // check the line contents ... - - // rules that check the end of the last line. - // first, check that the end of the last line actually is code... - if (document.isCode(line - 1, document.lineLength(line - 1) - 1)) { - // indent lines following a line ending with '=' - if (lastLine.endsWith("=")) { - dbg('indenting for ='); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // indent lines following a line ending with '{' - if (lastLine.endsWith("{")) { - dbg('indenting for {'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // indent lines following a line ending with 'do' - if (lastLine.endsWith("do")) { - dbg('indenting for do'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // indent line after myFunction = do ... - // foo = do bar <- baz - // >>>>>>>>>qzx <- qqx - if (lastLine.search(/\s=\sdo\s\S/)!= -1) { - dbg('indenting line for “... = do ...â€'); - var doCol = lastLine.search(/do\s/); - return document.firstVirtualColumn(line - 1) + doCol + 3; - } - - - // indent line after 'where' unless it starts with 'module' - // instance Functor Tree where - // >>>>fmap = treeMap - if (lastLine.endsWith('where') && !lastLine.startsWith('module')) { - dbg('indenting line for where (3)'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - } - - // indent line after 'where' 6 characters for alignment: - // ... where foo = 3 - // >>>>>>bar = 4 - if (lastLine.search(/\s*where\s+[^-]/) != -1) { - dbg('indenting line for where (0)'); - return document.firstVirtualColumn(line - 1) + 6; - } - - // indent line after 'where' 6 characters for alignment: - // ... where -- comment - // >>>>foo = 4 - if (lastLine.stripWhiteSpace().startsWith('where')) { - dbg('indenting line for where (1)'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // indent 'where' to column 0 + indentWidth - // fun x = y - // >>>>where y = x+1 - if (currentLine.stripWhiteSpace().startsWith('where')) { - dbg('indenting line for where (2)'); - - if (lastLine.startsWith('else')) { - return document.firstVirtualColumn(line - 1) + indentWidth; - } else { - return indentWidth; - } - } - - // indent line after 'let' 4 characters for alignment: - // ... let foo = 3 - // >>>>bar = 4 - // - // unless - // * we're in a do block OR - // * the current line starts with 'in' - var letCol = lastLine.search(/\blet\b/); - if (letCol != -1 && !currentLine.stripWhiteSpace().startsWith('in')) { - - // do a basic test of whether we are in a do block or not - l = line - 2; - - // find the last non-empty line with an indentation level different - // from the current line ... - while (document.firstVirtualColumn(l) == document.firstVirtualColumn(line-1) - || document.line(l).search(/^\s*$/) != -1) { - l = l - 1; - } - - // ... if that line ends with 'do', don't indent - if (document.line(l).endsWith('do')) { - dbg('not indenting for let; in a do block'); - return -1; - } - - dbg('indenting line for let'); - return letCol + 4; - } - - // deindent line starting with 'in' to the level of its corresponding 'let': - // ... let foo = 3 - // bar = 4 - // in foo+bar - if (currentLine.stripWhiteSpace().startsWith('in')) { - dbg('indenting line for in'); - var t = line-1; - var indent = -1; - while (t >= 0 && line-t < 100) { - var letCol = document.line(t).search(/\blet\b/); - if (letCol != -1) { - indent = letCol; - break; - } - t--; - } - return indent; - } - - // deindent line starting with 'else' to the level of 'then': - // ... if foo - // then do - // bar baz - // else return [] - if (currentLine.stripWhiteSpace().startsWith('else')) { - dbg('indenting line for else'); - var t = line-1; - var indent = -1; - while (t >= 0 && line-t < 100) { - var thenCol = document.line(t).search(/\bthen\b/); // \s*\bthen\b - if (thenCol != -1) { - indent = thenCol; - break; - } - t--; - } - return indent; - } - - // indent line after a line with just 'in' one indent width: - // ... let foo = 3 - // bar = 4 - // in - // >>>>foo+bar - if (lastLine.stripWhiteSpace() == 'in') { - dbg('indenting line after in'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // indent line after 'case' 5 characters for alignment: - // case xs of - // >>>>>[] -> ... - // >>>>>(y:ys) -> ... - var caseCol = lastLine.search(/\bcase\b/); - if (caseCol != -1) { - dbg('indenting line for case'); - return caseCol + 5; - } - - // indent line after 'if/else' 3 characters for alignment: - // if foo == bar - // >>>then baz - // >>>else vaff - var ifCol = lastLine.search(/\bif\b/); - var thenCol = lastLine.search(/\bthen\b/); - var elseCol = lastLine.search(/\belse\b/); - if (ifCol != -1 && thenCol == -1 && elseCol == -1) { - dbg('indenting line for if'); - return ifCol + 3; - } - - // indent line starting with "deriving: ": - // data Tree a = Node a (Tree a) (Tree a) - // | Empty - // >>>>>>>>>>>>>>deriving (Show) - // - // - OR - - // - // data Bool = True | False - // >>>>>deriving (Show) - if (currentLine.stripWhiteSpace().startsWith('deriving')) { - dbg('indenting line for deriving'); - - var pipeCol = lastLine.search(/\|/); - if (lastLine.stripWhiteSpace().startsWith('data')) { - return document.firstVirtualColumn(line - 1) + indentWidth; - } - else if (pipeCol != -1) { - var t = 1; - while (lastLine[document.firstVirtualColumn(line - 1)+pipeCol+t] == ' ') { - t++; - } - return pipeCol + t + 1; - } - else { - return document.firstVirtualColumn(line - 1) + 2; - } - } - - // indent lines starting with '|' (guards or alternate constructors): - // f x - // >>| x == 0 = 1 - // >>| x == 0 = x - // - // OR - // - // data Bool = True - // >>>>>>>>>>| False - if (currentLine.stripWhiteSpace().startsWith("|")) { - dbg('indenting line for |'); - var equalsCol = lastLine.search(/=/); - var pipeCol = lastLine.search(/\|/); - if (equalsCol != -1 && lastLine.stripWhiteSpace().startsWith('data')) { - return equalsCol; - } - else if (pipeCol != -1) { - return pipeCol; - } - else { - return document.firstVirtualColumn(line - 1) + indentWidth; - } - } - - // line starting with !#$%&*+./<=>?@\^|~- - if (document.isCode(line, document.lineLength(line) - 1) - && currentLine.search(re_symbols) != -1 - && lastLine.search(re_symbols) == -1) { - dbg('indenting for operator'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // the line after aline ending with a comma should be indented - if (document.isCode(line - 1, document.lineLength(lastLine) - 1) - && lastLine.search(',\s*$') != -1) { - dbg('indenting after line ending with comma'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - - // [de]indent line starting wih '}' to match the indentation level of '{': - // data Foo { - // a :: Int - // , b :: Double - // }<<< - if (currentLine.stripWhiteSpace().endsWith('}')) { - dbg('indenting line for }'); - var t = line-1; - var indent = -1; - while (t >= 0 && line-t < 100) { - var braceCol = document.line(t).search(/{/); - if (braceCol != -1) { - indent = document.firstVirtualColumn(t); - break; - } - t--; - } - return indent; - } - - //if (lastLine.search(/^\s*$/) != -1) { - // dbg('indenting for empty line'); - // return 0; - //} - - dbg('continuing with regular indent'); - return -1; -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/indentation_template.js b/part/script/data/indentation_template.js deleted file mode 100644 index 2cb63ce..0000000 --- a/part/script/data/indentation_template.js +++ /dev/null @@ -1,52 +0,0 @@ -/* kate-script - * name: Indenter name (appears in the menu) - * license: license (BSD, GPL, LGPL, Artistic, etc) - * author: first name last name - * revision: 1 (simple integer number) - * kate-version: 3.4 - */ - -// specifies the characters which should trigger indent, beside the default '\n' -triggerCharacters = "{}/:;"; - -/** - * Indent a line. - * This function is called for every and for all trigger - * characters. ch is the character typed by the user. ch is - * - '\n' for newlines - * - "" empty for the action "Tools > Align" - * - all other characters are really typed by the user. - * - * Return value: - * - return -2; - do nothing - * - return -1; - keep indentation (searches for previous non-blank line) - * - return 0; - All numbers >= 0 are the indent-width in spaces - * - * Alternatively, an array of two elements can be returned: - * return [ indent, align ]; - * - * The first element is the indent-width like above, with the same meaning - * of the special values. - * - * The second element is an absolute value representing a column for - * "alignment". If this value is higher than the indent value, the - * difference represents a number of spaces to be added after the indent. - * Otherwise, it's ignored. - * - * Example: - * Assume using tabs to indent, and tab width is 4. Here ">" represents a - * tab, and "." represents a space: - * 1: > > foobar("hello", - * 2: > > ......."world") - * - * When indenting line 2, the script returns [8, 15]. Two tabs are inserted - * to indent to column 8, and 7 spaces are added to align the second - * parameter under the first, so that it stays aligned if the file is viewed - * with a different tab width. - */ -function indent(line, indentWidth, ch) -{ - return -2; -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/lilypond.js b/part/script/data/lilypond.js deleted file mode 100644 index 0bc32f7..0000000 --- a/part/script/data/lilypond.js +++ /dev/null @@ -1,125 +0,0 @@ -/** kate-script - * name: LilyPond - * license: LGPL - * author: Wilbert Berendsen - * revision: 2 - * kate-version: 3.4 - * type: indentation - * required-syntax-style: lilypond - * indent-languages: lilypond - * - * - * Copyright (c) 2008 Wilbert Berendsen - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * See http://www.gnu.org/licenses/ for more information. - */ - -var triggerCharacters = "}>%;"; - -function dbg(s) { - // debug to the term in blue so that it's easier to make out amongst all - // of Kate's other debug output. - debug("\u001B[34m" + s + "\u001B[0m"); -} - -reCloser = /\}|\>\>/g; -reStartClosers = /^(\s*([%#]?\}|\>\>))+/ -reSkipLine = /^\s*$|^%(?![{}])|^;/; -reFullCommentLine = /^\s*(;;;|%%%)/; - -function indent(line, indentWidth, ch) -{ - // not necessary to indent the first line - if (line == 0) - return -2; - - var c = document.line(line); // current line - - // no indent for triple commented lines - if (c.match(reFullCommentLine)) - return 0; - - // Search backwards for first non-space, non-comment line. - var prev = line; - while (prev--) { - if (!document.line(prev).match(reSkipLine)) { - var p = document.line(prev); // previous non-space line - var prevIndent = document.firstVirtualColumn(prev); - var pos = 0; - var end = document.lineLength(prev); - // Discard first closers: } and >> as they already influenced the indent. - if (m = p.match(reStartClosers)) - var pos = m[0].length; - - var delta = 0; // count normal openers/closers: { << } >> - var level = 0; // count opened Scheme parens - var paren = []; // save their positions - // Walk over openers and closers in the remainder of the previous line. - while (pos < end) { - if (!document.isString(prev, pos)) { - var one = document.charAt(prev, pos); - var two = one + (pos+1 < end ? document.charAt(prev, pos+1) : ""); - if (two == "%{" || two == "#{" || two == "<<") - ++delta, ++pos; - else if (two == "%}" || two == "#}" || two == ">>") - --delta, ++pos; - else if (one == "%" || one == ";") - break; // discard rest of line - else if (one == "{") - ++delta; - else if (one == "}") - --delta; - // match parens only if they are Scheme code (not LilyPond slurs) - else if (document.attribute(prev, pos) == 25 || - document.attribute(prev, pos) == 26) { - if (one == "(") { - // save position of first - if (level >= 0 && paren[level] == null) - paren[level] = pos; - ++level, ++delta; - } - else if (one == ")") { - --level, --delta; - // is this the final closing paren of a Scheme expression? - isLast = document.attribute(prev, pos) == 26 - // have we seen an opening parenthesis in this line? - if (level >= 0 && paren[level] != null && !isLast) { - delta = 0; - prevIndent = document.toVirtualColumn(prev, paren[level]); - } - else { - var cur = document.anchor(prev, pos, "("); - if (cur.isValid()) { - delta = 0; - if (isLast) - prevIndent = document.firstVirtualColumn(cur.line); - else - prevIndent = document.toVirtualColumn(cur.line, cur.column); - } - } - } - } - } - ++pos; - } - // now count the number of closers in the beginning of the current line. - if (m = c.match(reStartClosers)) - delta -= m[0].match(reCloser).length; - return Math.max(0, prevIndent + delta * indentWidth); - } - } - return 0; -} diff --git a/part/script/data/lisp.js b/part/script/data/lisp.js deleted file mode 100644 index 0d00985..0000000 --- a/part/script/data/lisp.js +++ /dev/null @@ -1,57 +0,0 @@ -/** kate-script - * name: LISP - * license: LGPL - * author: Dominik Haumann - * revision: 2 - * kate-version: 3.4 - * type: indentation - * - * This file is part of the Kate Project. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -triggerCharacters = ";"; - -/** - * Process a newline character. - * This function is called whenever the user hits . - */ -function indent(line, indentWidth, ch) -{ - // special rules: ;;; -> indent 0 - // ;; -> align with next line, if possible - // ; -> usually on the same line as code -> ignore - - textLine = document.line(line); - if (textLine.search(/^\s*;;;/) != -1) { - return 0; - } else if (textLine.search(/^\s*;;/) != -1) { - // try to align with the next line - nextLine = document.nextNonEmptyLine(line + 1); - if (nextLine != -1) { - return document.firstVirtualColumn(nextLine); - } - } - - cursor = document.anchor(line, 0, '('); - if (cursor.isValid()) { - return document.toVirtualColumn(cursor) + indentWidth; - } else { - return 0; - } -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/lua.js b/part/script/data/lua.js deleted file mode 100644 index 7cf8fe9..0000000 --- a/part/script/data/lua.js +++ /dev/null @@ -1,356 +0,0 @@ -/** kate-script - * name: Lua - * license: LGPL - * author: Jonathan Schmidt-Dominé - * revision: 1 - * kate-version: 3.4 - * type: indentation - * - * This file is part of the Kate Project. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN USER CONFIGURATION -//END USER CONFIGURATION - - -// specifies the characters which should trigger indent, beside the default '\n' -var triggerCharacters = "defl})"; - -// Indent after lines that match this regexp -var rxIndent = /(\bfunction\s|(\b(else|then|do)\s*$)|([\{][^\}]*$)|([\(][^\)]*$))/; - -// Unindent lines that match this regexp -var rxUnindent = /^\s*([\}\)]|(end|else|elseif|until)\b)(.*)$/; - -function assert(cond) -{ - if (!cond) - throw "assertion failure"; -} - -// Return the closest non-empty line, ignoring comments -// (result <= line). Return -1 if the document -function findPrevNonCommentLine(line) -{ - line = document.prevNonEmptyLine(line); - while (line >= 0 && document.isComment(line, document.firstColumn(line))) { - line = document.prevNonEmptyLine(line - 1); - } - return line; -} - -function isLineContinuing(line) -{ - return /\\$/.test(document.line(line)); -} - -// Return true if the given column is at least equal to the column that -// contains the last non-whitespace character at the given line, or if -// the rest of the line is a comment. -function isLastCodeColumn(line, column) -{ - if (column >= document.lastColumn(line)) - return true; - else if (document.isComment(line, document.nextNonSpaceColumn(line, column+1))) - return true; - else - return false; -} - -// Look for a pattern at the end of the statement. -// -// Returns true if the pattern is found, in a position -// that is not inside a string or a comment, and the position + -// the length of the matching part is either the end of the -// statement, or a comment. -// -// The regexp must be global, and the search is continued until -// a match is found, or the end of the string is reached. -function testAtEnd(stmt, rx) -{ - assert(rx.global); - - var cnt = stmt.content(); - var res; - while (res = rx.exec(cnt)) { - var start = res.index; - var end = rx.lastIndex; - if (stmt.isCode(start)) { - if (end == cnt.length) - return true; - if (stmt.isComment(end)) - return true; - } - } - return false; -} - -function isStmtContinuing(line) -{ - // Is there an open parenthesis? - var anch = lastAnchor(line+1, 0); - if (anch.line >= 0) - return true; - - var stmt = new Statement(line, line); - var rx = /(\+|\-|\*|\/|\%|\^|\=|\<|\>|\band\b|\bor\b|\bnot\b|#|,|[^\.]\.\.|^\.\.|[^\.]\.|^\.)\s*/g; - - return testAtEnd(stmt, rx); -} - -// Return the first line that is not preceded by a "continuing" line. -// Return currLine if currLine <= 0 -function findStmtStart(currLine) -{ - var p, l = currLine; - do { - if (l <= 0) return l; - p = l; - l = findPrevNonCommentLine(l - 1); - } while ((l == p-1 && isLineContinuing(l)) || isStmtContinuing(l)); - return p; -} - -// Statement class -function Statement(start, end) -{ - this.start = start; - this.end = end; - - // Convert to string for debugging - this.toString = function() { - return "{" + this.start + "," + this.end + "}"; - } - - // Return an object having 'line' and 'column' set to the given offset in a statement - this.offsetToCursor = function(offset) { - // TODO Provide helper function for this when API is converted to using cursors: - var line = this.start; - while (line < this.end && document.lineLength(line) < offset) { - offset -= document.lineLength(line++) + 1; - } - return {line: line, column: offset}; - } - - // Return document.attribute at the given offset in a statement - this.attribute = function(offset) { - var cur = this.offsetToCursor(offset); - return document.attribute(cur.line, cur.column); - } - - // Return document.isCode at the given offset in a statement - this.isCode = function(offset) { - var cur = this.offsetToCursor(offset); - return document.isCode(cur.line, cur.column); - } - - // Return document.isComment at the given offset in a statement - this.isComment = function(offset) { - var cur = this.offsetToCursor(offset); - return document.isComment(cur.line, cur.column); - } - - // Return the indent at the beginning of the statement - this.indent = function() { - return document.firstVirtualColumn(this.start) - } - - // Return the content of the statement from the document - this.content = function() { - var cnt = ""; - for (var l = this.start; l <= this.end; l++) { - cnt += document.line(l).replace(/\\$/, " "); - if (l < this.end) - cnt += " "; - } - return cnt; - } -} - -// Returns a tuple that contains the first and last line of the -// previous statement before line. -function findPrevStmt(line) -{ - var stmtEnd = findPrevNonCommentLine(line); - var stmtStart = findStmtStart(stmtEnd); - - return new Statement(stmtStart, stmtEnd); -} - -function isBlockStart(stmt) -{ - var cnt = stmt.content(); - var len = cnt.length; - - if (rxIndent.test(cnt)) - return true; - - var rx = /((\b(do|then|else)\b)|\bfunction\s+\([\w\,]*\))/g; - - return testAtEnd(stmt, rx); -} - -function isBlockEnd(stmt) -{ - var cnt = stmt.content(); - - return rxUnindent.test(cnt); -} - -function findBlockStart(line) -{ - var nested = 0; - var stmt = new Statement(line, line); - while (true) { - if (stmt.start < 0) return stmt; - - stmt = findPrevStmt(stmt.start - 1); - if (isBlockEnd(stmt)) { - nested++; - } - if (isBlockStart(stmt)) { - if (nested == 0) - return stmt; - else - nested--; - } - } -} - -// check if the trigger characters are in the right context, -// otherwise running the indenter might be annoying to the user -function isValidTrigger(line, ch) -{ - if (ch == "" || ch == "\n") - return true; // Explicit align or new line - - var res = rxUnindent.exec(document.line(line)); - if (res) { - if (res[3] == "") - return true; // Exact match - } - return false; -} - -// Helper function to compare two KTextEditor::Cursor objects. -// Returns 0 if equal, 1 if ca > cb, -1 if ca < cb -function compare(ca, cb) -{ - if (ca.line != cb.line) { - return (ca.line > cb.line) ? 1 : -1; - } else if (ca.column != cb.column) { - return (ca.column > cb.column) ? 1 : -1; - } else { - return 0; - } -} - -// Find the last open bracket before the current line. -// Result is a KTextEditor::Cursor object, with an extra attribute, 'ch' -// containing the type of bracket. -function lastAnchor(line, column) -{ - var anch = document.anchor(line, column, '('); - anch.ch = '('; - var tmp1 = document.anchor(line, column, '{'); - tmp1.ch = '{'; - var tmp2 = document.anchor(line, column, '['); - tmp2.ch = '['; - - if (compare(tmp1, anch) == 1) - anch = tmp1; - if (compare(tmp2, anch) == 1) - anch = tmp2; - - return anch; -} - -// indent gets three arguments: line, indentWidth in spaces, -// typed character indent -function indent(line, indentWidth, ch) -{ - if (!isValidTrigger(line, ch)) - return -2; - - var prevStmt = findPrevStmt(line - 1); - if (prevStmt.end < 0) - return -2; // Can't indent the first line - - var prev = document.prevNonEmptyLine(line); - - // HACK Detect here documents - if (document.isAttributeName(prev, document.lineLength(prev)-1, "Ruby:Here Document")) { - return -1; // HERE-DOCUMENT - } - // HACK Detect embedded comments - if (document.isAttributeName(prev, document.lineLength(prev)-1, "Ruby:Blockcomment")) { - return -1; - } - - var prevStmtCnt = prevStmt.content(); - var prevStmtInd = prevStmt.indent(); - - // Are we inside a parameter list, array or hash? - var anch = lastAnchor(line, 0); - if (anch.line >= 0) { - var shouldIndent = (anch.line == prevStmt.end) || testAtEnd(prevStmt, /,\s*/g); - if (!isLastCodeColumn(anch.line, anch.column) || lastAnchor(anch.line, anch.column).line >= 0) { - // TODO This is alignment, should force using spaces instead of tabs: - if (shouldIndent) { - anch.column += 1; - var nextCol = document.nextNonSpaceColumn(anch.line, anch.column); - if (nextCol > 0 && !document.isComment(anch.line, nextCol)) - anch.column = nextCol; - } - // Keep indent of previous statement, while aligning to the anchor column - return [prevStmtInd, document.toVirtualColumn(anch.line, anch.column)]; - } else { - return document.firstVirtualColumn(anch.line) + (shouldIndent ? indentWidth : 0); - } - } - - // Handle indenting of multiline statements. - if ((prevStmt.end == line-1 && isLineContinuing(prevStmt.end)) || isStmtContinuing(prevStmt.end)) { - if (prevStmt.start == prevStmt.end) { - if (ch == '' && document.firstVirtualColumn(line) > document.firstVirtualColumn(prevStmt.end)) { - return -2; // Don't force a specific indent level when aligning manually - } - return prevStmtInd + indentWidth * 2; - } else { - return document.firstVirtualColumn(prevStmt.end); - } - } - - if (rxUnindent.test(document.line(line))) { - var startStmt = findBlockStart(line); - if (startStmt.start >= 0) - return startStmt.indent(); - else - return -2; - } - - if (isBlockStart(prevStmt)) { - return prevStmtInd + indentWidth; - } else if (prevStmtCnt.search(/[\[\{]\s*$/) != -1) { - return prevStmtInd + indentWidth; - } - - // Keep current - return prevStmtInd; -} - -// kate: indent-width 2; indent-spaces on; diff --git a/part/script/data/python.js b/part/script/data/python.js deleted file mode 100644 index f09fcb2..0000000 --- a/part/script/data/python.js +++ /dev/null @@ -1,107 +0,0 @@ -/** kate-script - * name: Python - * license: LGPL - * author: Paul Giannaros - * revision: 1 - * kate-version: 3.4 - * type: indentation - */ - - -// niceties - -String.prototype.startsWith = function(prefix) { - return this.substring(0, prefix.length) == prefix; -} - -String.prototype.endsWith = function(suffix) { - var startPos = this.length - suffix.length; - if (startPos < 0) - return false; - return (this.lastIndexOf(suffix, startPos) == startPos); -} - -String.prototype.lastCharacter = function() { - var l = this.length; - if(l == 0) - return ''; - else - return this.charAt(l - 1); -} - -String.prototype.sansWhiteSpace = function() { - return this.replace(/[ \t\n\r]/g, ''); -} -String.prototype.stripWhiteSpace = function() { - return this.replace(/^[ \t\n\r]+/, '').replace(/[ \t\n\r]+$/, ''); -} - - -function dbg(s) { - // debug to the term in blue so that it's easier to make out amongst all - // of Kate's other debug output. - debug("\u001B[34m" + s + "\u001B[0m"); -} - -var triggerCharacters = ""; - -// General notes: -// indent() returns the amount of characters (in spaces) to be indented. -// Special indent() return values: -// -2 = no indent -// -1 = keep last indent - -function indent(line, indentWidth, character) { -// dbg(document.attribute.toString()); -// dbg("indent character: " + character); -// dbg("line text: " + document.line(line)); - var currentLine = document.line(line); -// dbg("current line: " + currentLine); - var lastLine = document.line(line - 1); - var lastCharacter = lastLine.lastCharacter(); - // we can't really indent line 0 - if(line == 0) - return -2; - // make sure the last line is code - if(!document.isCode(line - 1, document.lineLength(line - 1) - 1) && lastCharacter != "\"" && lastCharacter != "'") { -// dbg("attributes that we don't want! Returning"); - return -1; - } - // otherwise, check the line contents - // for :, we simply indent -// dbg('line without white space: ' + currentLine.sansWhiteSpace().length); - if(lastLine.endsWith(':')) { -// dbg('indenting line for :'); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - // generally, when a brace is on its own at the end of a regular line - // (i.e a data structure is being started), indent is wanted. - // For example: - // dictionary = { - // 'foo': 'bar', - // } - // etc.. - else if(lastCharacter == '{' || lastCharacter == '[') { -// dbg('indenting for { or ['); - return document.firstVirtualColumn(line - 1) + indentWidth; - } - // XX this introduces irritating bugs. Commenting it out for now - // -// // relatively simplistic heuristic for determining whether or not to unindent: -// // if a }] has been typed and it's the sole letter on the line, unindent -// else if((character == '}' || character == ']') && (currentLine.sansWhiteSpace().length == 1)) { -// dbg('unindenting line for } or ]'); -// return Math.max(0, document.firstVirtualColumn(line - 1) - indentWidth); -// } - // finally, a raise, pass, and continue should unindent - lastLine = lastLine.stripWhiteSpace(); - if(lastLine == 'continue' || lastLine == 'pass' || lastLine == 'raise' || lastLine.startsWith('raise ')) { -// dbg('unindenting line for keyword'); - return Math.max(0, document.firstVirtualColumn(line - 1) - indentWidth); - } -// dbg('continuing with regular indent'); - return -1; -} - - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/ruby.js b/part/script/data/ruby.js deleted file mode 100644 index b17bddd..0000000 --- a/part/script/data/ruby.js +++ /dev/null @@ -1,359 +0,0 @@ -/** kate-script - * name: Ruby - * license: LGPL - * author: Robin Pedersen - * revision: 1 - * kate-version: 3.4 - * type: indentation - * required-syntax-style: ruby - * indent-languages: ruby - * priority: 0 - * - * This file is part of the Kate Project. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN USER CONFIGURATION -//END USER CONFIGURATION - - -// specifies the characters which should trigger indent, beside the default '\n' -var triggerCharacters = "cdefhilnrsuw}]"; - -// Indent after lines that match this regexp -var rxIndent = /^\s*(def|if|unless|for|while|until|class|module|else|elsif|case|when|begin|rescue|ensure|catch)\b/; - -// Unindent lines that match this regexp -var rxUnindent = /^\s*((end|when|else|elsif|rescue|ensure)\b|[\]\}])(.*)$/; - -function assert(cond) -{ - if (!cond) - throw "assertion failure"; -} - -// Return the closest non-empty line, ignoring comments -// (result <= line). Return -1 if the document -function findPrevNonCommentLine(line) -{ - line = document.prevNonEmptyLine(line); - while (line >= 0 && document.isComment(line, document.firstColumn(line))) { - line = document.prevNonEmptyLine(line - 1); - } - return line; -} - -function isLineContinuing(line) -{ - return /\\$/.test(document.line(line)); -} - -// Return true if the given column is at least equal to the column that -// contains the last non-whitespace character at the given line, or if -// the rest of the line is a comment. -function isLastCodeColumn(line, column) -{ - if (column >= document.lastColumn(line)) - return true; - else if (document.isComment(line, document.nextNonSpaceColumn(line, column+1))) - return true; - else - return false; -} - -// Look for a pattern at the end of the statement. -// -// Returns true if the pattern is found, in a position -// that is not inside a string or a comment, and the position + -// the length of the matching part is either the end of the -// statement, or a comment. -// -// The regexp must be global, and the search is continued until -// a match is found, or the end of the string is reached. -function testAtEnd(stmt, rx) -{ - assert(rx.global); - - var cnt = stmt.content(); - var res; - while (res = rx.exec(cnt)) { - var start = res.index; - var end = rx.lastIndex; - if (stmt.isCode(start)) { - if (end == cnt.length) - return true; - if (stmt.isComment(end)) - return true; - } - } - return false; -} - -function isStmtContinuing(line) -{ - // Is there an open parenthesis? - var anch = lastAnchor(line+1, 0); - if (anch.line >= 0) - return true; - - var stmt = new Statement(line, line); - var rx = /((\+|\-|\*|\/|\=|&&|\|\||\band\b|\bor\b|,)\s*)/g; - - return testAtEnd(stmt, rx); -} - -// Return the first line that is not preceded by a "continuing" line. -// Return currLine if currLine <= 0 -function findStmtStart(currLine) -{ - var p, l = currLine; - do { - if (l <= 0) return l; - p = l; - l = findPrevNonCommentLine(l - 1); - } while ((l == p-1 && isLineContinuing(l)) || isStmtContinuing(l)); - return p; -} - -// Statement class -function Statement(start, end) -{ - this.start = start; - this.end = end; - - // Convert to string for debugging - this.toString = function() { - return "{" + this.start + "," + this.end + "}"; - } - - // Return an object having 'line' and 'column' set to the given offset in a statement - this.offsetToCursor = function(offset) { - // TODO Provide helper function for this when API is converted to using cursors: - var line = this.start; - while (line < this.end && document.lineLength(line) < offset) { - offset -= document.lineLength(line++) + 1; - } - return {line: line, column: offset}; - } - - // Return document.attribute at the given offset in a statement - this.attribute = function(offset) { - var cur = this.offsetToCursor(offset); - return document.attribute(cur.line, cur.column); - } - - // Return document.isCode at the given offset in a statement - this.isCode = function(offset) { - var cur = this.offsetToCursor(offset); - return document.isCode(cur.line, cur.column); - } - - // Return document.isComment at the given offset in a statement - this.isComment = function(offset) { - var cur = this.offsetToCursor(offset); - return document.isComment(cur.line, cur.column); - } - - // Return the indent at the beginning of the statement - this.indent = function() { - return document.firstVirtualColumn(this.start) - } - - // Return the content of the statement from the document - this.content = function() { - var cnt = ""; - for (var l = this.start; l <= this.end; l++) { - cnt += document.line(l).replace(/\\$/, " "); - if (l < this.end) - cnt += " "; - } - return cnt; - } -} - -// Returns a tuple that contains the first and last line of the -// previous statement before line. -function findPrevStmt(line) -{ - var stmtEnd = findPrevNonCommentLine(line); - var stmtStart = findStmtStart(stmtEnd); - - return new Statement(stmtStart, stmtEnd); -} - -function isBlockStart(stmt) -{ - var cnt = stmt.content(); - var len = cnt.length; - - if (rxIndent.test(cnt)) - return true; - - var rx = /((\bdo\b|\{)(\s*\|.*\|)?\s*)/g; - - return testAtEnd(stmt, rx); -} - -function isBlockEnd(stmt) -{ - var cnt = stmt.content(); - - return rxUnindent.test(cnt); -} - -function findBlockStart(line) -{ - var nested = 0; - var stmt = new Statement(line, line); - while (true) { - if (stmt.start < 0) return stmt; - - stmt = findPrevStmt(stmt.start - 1); - if (isBlockEnd(stmt)) { - nested++; - } - if (isBlockStart(stmt)) { - if (nested == 0) - return stmt; - else - nested--; - } - } -} - -// check if the trigger characters are in the right context, -// otherwise running the indenter might be annoying to the user -function isValidTrigger(line, ch) -{ - if (ch == "" || ch == "\n") - return true; // Explicit align or new line - - var res = rxUnindent.exec(document.line(line)); - if (res) { - if (res[3] == "") - return true; // Exact match - } - return false; -} - -// Helper function to compare two KTextEditor::Cursor objects. -// Returns 0 if equal, 1 if ca > cb, -1 if ca < cb -function compare(ca, cb) -{ - if (ca.line != cb.line) { - return (ca.line > cb.line) ? 1 : -1; - } else if (ca.column != cb.column) { - return (ca.column > cb.column) ? 1 : -1; - } else { - return 0; - } -} - -// Find the last open bracket before the current line. -// Result is a KTextEditor::Cursor object, with an extra attribute, 'ch' -// containing the type of bracket. -function lastAnchor(line, column) -{ - var anch = document.anchor(line, column, '('); - anch.ch = '('; - var tmp1 = document.anchor(line, column, '{'); - tmp1.ch = '{'; - var tmp2 = document.anchor(line, column, '['); - tmp2.ch = '['; - - if (compare(tmp1, anch) == 1) - anch = tmp1; - if (compare(tmp2, anch) == 1) - anch = tmp2; - - return anch; -} - -// indent gets three arguments: line, indentWidth in spaces, -// typed character indent -function indent(line, indentWidth, ch) -{ - if (!isValidTrigger(line, ch)) - return -2; - - var prevStmt = findPrevStmt(line - 1); - if (prevStmt.end < 0) - return -2; // Can't indent the first line - - var prev = document.prevNonEmptyLine(line); - - // HACK Detect here documents - if (document.isAttributeName(prev, document.lineLength(prev)-1, "Ruby:Here Document")) { - return -1; // HERE-DOCUMENT - } - // HACK Detect embedded comments - if (document.isAttributeName(prev, document.lineLength(prev)-1, "Ruby:Blockcomment")) { - return -1; - } - - var prevStmtCnt = prevStmt.content(); - var prevStmtInd = prevStmt.indent(); - - // Are we inside a parameter list, array or hash? - var anch = lastAnchor(line, 0); - if (anch.line >= 0) { - var shouldIndent = (anch.line == prevStmt.end) || testAtEnd(prevStmt, /,\s*/g); - if (!isLastCodeColumn(anch.line, anch.column) || lastAnchor(anch.line, anch.column).line >= 0) { - // TODO This is alignment, should force using spaces instead of tabs: - if (shouldIndent) { - anch.column += 1; - var nextCol = document.nextNonSpaceColumn(anch.line, anch.column); - if (nextCol > 0 && !document.isComment(anch.line, nextCol)) - anch.column = nextCol; - } - // Keep indent of previous statement, while aligning to the anchor column - return [prevStmtInd, document.toVirtualColumn(anch.line, anch.column)]; - } else { - return document.firstVirtualColumn(anch.line) + (shouldIndent ? indentWidth : 0); - } - } - - // Handle indenting of multiline statements. - if ((prevStmt.end == line-1 && isLineContinuing(prevStmt.end)) || isStmtContinuing(prevStmt.end)) { - if (prevStmt.start == prevStmt.end) { - if (ch == '' && document.firstVirtualColumn(line) > document.firstVirtualColumn(prevStmt.end)) { - return -2; // Don't force a specific indent level when aligning manually - } - return prevStmtInd + indentWidth * 2; - } else { - return document.firstVirtualColumn(prevStmt.end); - } - } - - if (rxUnindent.test(document.line(line))) { - var startStmt = findBlockStart(line); - if (startStmt.start >= 0) - return startStmt.indent(); - else - return -2; - } - - if (isBlockStart(prevStmt)) { - return prevStmtInd + indentWidth; - } else if (prevStmtCnt.search(/[\[\{]\s*$/) != -1) { - return prevStmtInd + indentWidth; - } - - // Keep current - return prevStmtInd; -} - -// kate: indent-width 2; indent-spaces on; diff --git a/part/script/data/test.js b/part/script/data/test.js deleted file mode 100644 index bca670a..0000000 --- a/part/script/data/test.js +++ /dev/null @@ -1,16 +0,0 @@ -// kate-script -// help: Stupid test script. -var test = 1; -var start = document.lines(); - -document.editBegin(); - -for (var t = 0; t < 100; t++) { - document.insertLine(start+t, document.lineLength(0)); - document.insertText(start+t, 0, " muh"); - document.insertText(start+t, 0, view.cursorLine()); - document.insertText(start+t, 0, "// "); -} - -document.editEnd(); - diff --git a/part/script/data/test_selectioniface.js b/part/script/data/test_selectioniface.js deleted file mode 100644 index b08e2f3..0000000 --- a/part/script/data/test_selectioniface.js +++ /dev/null @@ -1,27 +0,0 @@ -// kate-script -// If you select some text before running the script, this line will be overwritten. -if ( view.hasSelection() ) -{ - document.removeText( 0, 0, 0, document.lineLength(0) ); - document.insertText( 0, 0, "// initial selection: " + view.selectionStartLine + "," + view.selectionStartColumn + " - " + view.selectionEndLine + "," + view.selectionEndColumn ); -} -// test selection interface -view.selectAll(); -view.setSelection( 0, 0, 0, 20 ); -view.clearSelection(); - -// insert some text and select that -var line = document.lines(); -document.insertLine( line, "foo" ); -document.insertText( line, 0, "// This is a new line" ); -view.setSelection( line, 0, line, document.lineLength(line) ); -// Delete that text -view.removeSelectedText(); - -// insert some text and select that -var line = document.lines(); -document.insertLine( line, "bar" ); -document.insertText( line, 0, "// This is a new line" ); -view.setSelection( line, 0, line, document.lineLength(line) ); - -document.insertText( line, document.lineLength( line ), " Selection is " + view.selectionStartLine + "," + view.selectionStartColumn + " - " + view.selectionEndLine + "," + view.selectionEndColumn ); diff --git a/part/script/data/utils.js b/part/script/data/utils.js deleted file mode 100644 index aad46bc..0000000 --- a/part/script/data/utils.js +++ /dev/null @@ -1,544 +0,0 @@ -/* kate-script - * author: Dominik Haumann , Milian Wolff - * license: LGPL - * revision: 3 - * kate-version: 3.4 - * type: commands - * functions: sort, moveLinesDown, moveLinesUp, natsort, uniq, rtrim, ltrim, trim, join, rmblank, unwrap, each, filter, map, duplicateLinesUp, duplicateLinesDown - */ - -function sort() -{ - each(function(lines){return lines.sort()}); -} - -function uniq() -{ - each(function(lines) { - for ( var i = 1; i < lines.length; ++i ) { - for ( var j = i - 1; j >= 0; --j ) { - if ( lines[i] == lines[j] ) { - lines.splice(i, 1); - // gets increased in the for - --i; - break; - } - } - } - return lines; - }); -} - -function natsort() -{ - each(function(lines){return lines.sort(natcompare);}); -} - -function rtrim() -{ - map(function(l){ return l.replace(/\s+$/, ''); }); -} - -function ltrim() -{ - map(function(l){ return l.replace(/^\s+/, ''); }); -} - -function trim() -{ - map(function(l){ return l.replace(/^\s+|\s+$/, ''); }); -} - -function rmblank() -{ - filter(function(l) { return l.length > 0; }); -} - -function join(separator) -{ - if (typeof(separator) != "string") { - separator = ""; - } - each(function(lines){ - return [lines.join(separator)]; - }); -} - -// unwrap does the opposite of the script word wrap -function unwrap () -{ - var selectionRange = view.selection(); - if (selectionRange.isValid()) { - // unwrap all paragraphs in the selection range - var currentLine = selectionRange.start.line; - var count = selectionRange.end.line - selectionRange.start.line; - - document.editBegin(); - while (count >= 0) { - // skip empty lines - while (count >= 0 && document.firstColumn(currentLine) == -1) { - --count; - ++currentLine; - } - - // find block of text lines to join - var anchorLine = currentLine; - while (count >= 0 && document.firstColumn(currentLine) != -1) { - --count; - ++currentLine; - } - - if (currentLine != anchorLine) { - document.joinLines(anchorLine, currentLine - 1); - currentLine -= currentLine - anchorLine - 1; - } - } - document.editEnd(); - } else { - // unwrap paragraph under the cursor - var cursorPosition = view.cursorPosition(); - if (document.firstColumn(cursorPosition.line) != -1) { - var startLine = cursorPosition.line; - while (startLine > 0) { - if (document.firstColumn(startLine - 1) == -1) { - break; - } - --startLine; - } - - var endLine = cursorPosition.line; - var lineCount = document.lines(); - while (endLine < lineCount) { - if (document.firstColumn(endLine + 1) == -1) { - break; - } - ++endLine; - } - - if (startLine != endLine) { - document.editBegin(); - document.joinLines(startLine, endLine); - document.editEnd(); - } - } - } -} - -function moveLinesDown() -{ - var fromLine = -1; - var toLine = -1; - - var selectionRange = view.selection(); - if (selectionRange.isValid() && selectionRange.end.line < document.lines() - 1) { - toLine = selectionRange.start.line; - fromLine = selectionRange.end.line + 1; - } else if (view.cursorPosition().line < document.lines() - 1) { - toLine = view.cursorPosition().line; - fromLine = toLine + 1; - } - if (fromLine != -1 && toLine != -1) { - var text = document.line(fromLine); - - document.editBegin(); - document.removeLine(fromLine); - document.insertLine(toLine, text); - document.editEnd(); - } -} - -function moveLinesUp() -{ - var fromLine = -1; - var toLine = -1; - - var selectionRange = view.selection(); - if (selectionRange.isValid() && selectionRange.start.line > 0) { - fromLine = selectionRange.start.line - 1; - toLine = selectionRange.end.line; - } else if (view.cursorPosition().line > 0) { - toLine = view.cursorPosition().line; - fromLine = toLine - 1; - } - - if (fromLine != -1 && toLine != -1) { - var text = document.line(fromLine); - - document.editBegin(); - document.removeLine(fromLine); - document.insertLine(toLine, text); - document.editEnd(); - } -} - -//private -function _duplicateLines(up) -{ - var fromLine = -1; - var toLine = -1; - - var selectionRange = view.selection(); - if (selectionRange.isValid() && selectionRange.start.line > 0) { - fromLine = selectionRange.start.line; - toLine = selectionRange.end.line; - if (selectionRange.end.column==0) toLine--; //if selection ends at beginning of line, skip that line - } else if (view.cursorPosition().line > 0) { - toLine = view.cursorPosition().line; - fromLine = toLine; - } - - var text = []; - for (var i=fromLine; i<=toLine; ++i) { - text.push(document.line(i)); - } - - document.editBegin(); - for (var i=text.length-1; i>=0; --i) { - if (up) { - document.insertLine(fromLine, text[i]); - } else { - document.insertLine(toLine+1, text[i]); - } - } - document.editEnd(); - - if (up) { - view.setSelection(new Range(new Cursor(fromLine, 0), new Cursor(toLine+1, 0))); - view.setCursorPosition(new Cursor(fromLine, 0)); - } else { - view.setSelection(new Range(new Cursor(toLine+1, 0), new Cursor(toLine+text.length+1, 0))); - view.setCursorPosition(new Cursor(toLine+1, 0)); - } -} - -function duplicateLinesUp() -{ - _duplicateLines(true); -} - -function duplicateLinesDown() -{ - _duplicateLines(false); -} - -function action(cmd) -{ - var a = new Object(); - if (cmd == "sort") { - a.text = i18n("Sort Selected Text"); - a.icon = ""; - a.category = ""; - a.interactive = false; - a.shortcut = ""; - } else if (cmd == "moveLinesDown") { - a.text = i18n("Move Lines Down"); - a.icon = ""; - a.category = ""; - a.interactive = false; - a.shortcut = "Ctrl+Shift+Down"; - } else if (cmd == "moveLinesUp") { - a.text = i18n("Move Lines Up"); - a.icon = ""; - a.category = ""; - a.interactive = false; - a.shortcut = "Ctrl+Shift+Up"; - } else if (cmd == "duplicateLinesUp") { - a.text = i18n("Duplicate Selected Lines Up"); - a.icon = ""; - a.category = ""; - a.interactive = false; - a.shortcut = "Ctrl+Alt+Up"; - } else if (cmd == "duplicateLinesDown") { - a.text = i18n("Duplicate Selected Lines Down"); - a.icon = ""; - a.category = ""; - a.interactive = false; - a.shortcut = "Ctrl+Alt+Down"; - } - - return a; -} - -function help(cmd) -{ - if (cmd == "sort") { - return i18n("Sort the selected text or whole document."); - } else if (cmd == "moveLinesDown") { - return i18n("Move selected lines down."); - } else if (cmd == "moveLinesUp") { - return i18n("Move selected lines up."); - } else if (cmd == "uniq") { - return i18n("Remove duplicate lines from the selected text or whole document."); - } else if (cmd == "natsort") { - return i18n("Sort the selected text or whole document in natural order.
" - +"Here's an example to show the difference to the normal sort method:
" - +"sort(a10, a1, a2) => a1, a10, a2
" - +"natsort(a10, a1, a2) => a1, a2, a10"); - } else if (cmd == "rtrim") { - return i18n("Trims trailing whitespace from selection or whole document."); - } else if (cmd == "ltrim") { - return i18n("Trims leading whitespace from selection or whole document."); - } else if (cmd == "trim") { - return i18n("Trims leading and trailing whitespace from selection or whole document."); - } else if (cmd == "join") { - return i18n("Joins selected lines or whole document. Optionally pass a separator to put between each line:
" + - "join ', ' will e.g. join lines and separate them by a comma."); - } else if (cmd == "rmblank") { - return i18n("Removes empty lines from selection or whole document."); - } else if (cmd == "unwrap") { - return "Unwraps all paragraphs in the text selection, or the paragraph under the text cursor if there is no selected text."; - } else if (cmd == "each") { - return i18n("Given a JavaScript function as argument, call that for the list of (selected) lines and" + - "replace them with the return value of that callback.
" + - "Example (join selected lines):
" + - "each 'function(lines){return lines.join(\", \"}'
" + - "To save you some typing, you can also do this to achieve the same:
" + - "each 'lines.join(\", \")'"); - } else if (cmd == "filter") { - return i18n("Given a JavaScript function as argument, call that for the list of (selected) lines " + - "and remove those where the callback returns false.
" + - "Example (see also rmblank):
" + - "filter 'function(l){return l.length > 0;}'
" + - "To save you some typing, you can also do this to achieve the same:
" + - "filter 'line.length > 0'"); - } else if (cmd == "map") { - return i18n("Given a JavaScript function as argument, call that for the list of (selected) lines " + - "and replace the line with the return value of the callback.
" + - "Example (see also ltrim):
" + - "map 'function(line){return line.replace(/^\s+/, \"\");}'
" + - "To save you some typing, you can also do this to achieve the same:
" + - "map 'line.replace(/^\s+/, \"\")'"); - } else if (cmd == "duplicateLinesUp") { - return i18n("Duplicates the selected lines up."); - } else if (cmd == "duplicateLinesDown") { - return i18n("Duplicates the selected lines down."); - } -} - -/// helper code below: - -function __toFunc(func, defaultArgName) -{ - if ( typeof(func) != "function" ) { - try { - func = eval("(" + func + ")"); - } catch(e) {} - debug(func, typeof(func)) - if ( typeof(func) != "function" ) { - try { - // one more try to support e.g.: - // map 'l+l' - // or: - // each 'lines.join("\n")' - func = eval("(function(" + defaultArgName + "){ return " + func + ";})"); - debug(func, typeof(func)) - } catch(e) {} - if ( typeof(func) != "function" ) { - throw "parameter is not a valid JavaScript callback function: " + typeof(func); - } - } - } - return func; -} - -function each(func) -{ - func = __toFunc(func, 'lines'); - - var selection = view.selection(); - if (!selection.isValid()) { - // use whole range - selection = document.documentRange(); - } else { - selection.start.column = 0; - selection.end.column = document.lineLength(selection.end.line); - } - - var text = document.text(selection); - - var lines = text.split("\n"); - lines = func(lines); - if ( typeof(lines) == "object" ) { - text = lines.join("\n"); - } else if ( typeof(lines) == "string" ) { - text = lines - } else { - throw "callback function for each has to return object or array of lines"; - } - - view.clearSelection(); - - document.editBegin(); - document.removeText(selection); - document.insertText(selection.start, text); - document.editEnd(); -} - -function filter(func) -{ - each(function(lines) { return lines.filter(__toFunc(func, 'line')); }); -} - -function map(func) -{ - each(function(lines) { return lines.map(__toFunc(func, 'line')); }); -} - -/* -natcompare.js -- Perform 'natural order' comparisons of strings in JavaScript. -Copyright (C) 2005 by SCK-CEN (Belgian Nucleair Research Centre) -Written by Kristof Coomans - -Based on the Java version by Pierre-Luc Paour, of which this is more or less a straight conversion. -Copyright (C) 2003 by Pierre-Luc Paour - -The Java version was based on the C version by Martin Pool. -Copyright (C) 2000 by Martin Pool - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software -in a product, an acknowledgment in the product documentation would be -appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be -misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - -function isWhitespaceChar(a) -{ - var charCode; - charCode = a.charCodeAt(0); - - if ( charCode <= 32 ) - { - return true; - } - else - { - return false; - } -} - -function isDigitChar(a) -{ - var charCode; - charCode = a.charCodeAt(0); - - if ( charCode >= 48 && charCode <= 57 ) - { - return true; - } - else - { - return false; - } -} - -function compareRight(a,b) -{ - var bias = 0; - var ia = 0; - var ib = 0; - - var ca; - var cb; - - // The longest run of digits wins. That aside, the greatest - // value wins, but we can't know that it will until we've scanned - // both numbers to know that they have the same magnitude, so we - // remember it in BIAS. - for (;; ia++, ib++) { - ca = a.charAt(ia); - cb = b.charAt(ib); - - if (!isDigitChar(ca) - && !isDigitChar(cb)) { - return bias; - } else if (!isDigitChar(ca)) { - return -1; - } else if (!isDigitChar(cb)) { - return +1; - } else if (ca < cb) { - if (bias == 0) { - bias = -1; - } - } else if (ca > cb) { - if (bias == 0) - bias = +1; - } else if (ca == 0 && cb == 0) { - return bias; - } - } -} - -function natcompare(a,b) { - - var ia = 0, ib = 0; - var nza = 0, nzb = 0; - var ca, cb; - var result; - - while (true) - { - // only count the number of zeroes leading the last number compared - nza = nzb = 0; - - ca = a.charAt(ia); - cb = b.charAt(ib); - - // skip over leading spaces or zeros - while ( isWhitespaceChar( ca ) || ca =='0' ) { - if (ca == '0') { - nza++; - } else { - // only count consecutive zeroes - nza = 0; - } - - ca = a.charAt(++ia); - } - - while ( isWhitespaceChar( cb ) || cb == '0') { - if (cb == '0') { - nzb++; - } else { - // only count consecutive zeroes - nzb = 0; - } - - cb = b.charAt(++ib); - } - - // process run of digits - if (isDigitChar(ca) && isDigitChar(cb)) { - if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0) { - return result; - } - } - - if (ca == 0 && cb == 0) { - // The strings compare the same. Perhaps the caller - // will want to call strcmp to break the tie. - return nza - nzb; - } - - if (ca < cb) { - return -1; - } else if (ca > cb) { - return +1; - } - - ++ia; ++ib; - } -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/script/data/xml.js b/part/script/data/xml.js deleted file mode 100644 index 7a2f4a0..0000000 --- a/part/script/data/xml.js +++ /dev/null @@ -1,159 +0,0 @@ -/** kate-script - * name: XML Style - * license: LGPL - * author: Milian Wolff - * revision: 1 - * kate-version: 3.4 - * type: indentation - * - * This file is part of the Kate Project. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -var debugMode = true; - -// specifies the characters which should trigger indent, beside the default '\n' -triggerCharacters = "/>"; - -function dbg(s) { - if (debugMode) - debug(s); -} - -/** - * Process a newline character. - * This function is called whenever the user hits . - * - * It gets three arguments: line, indentwidth in spaces, typed character. - */ -function indent(line, indentWidth, char) -{ - var prevLine = line; - var prevLineString = " "; - while (prevLine >= 0 && prevLineString.match(/^\s+$/)) { - prevLine--; - prevLineString = document.line(prevLine); - } - var prevIndent = document.firstVirtualColumn(prevLine); - var lineString = document.line(line); - - var alignOnly = (char == ""); - if (alignOnly) { - // XML might be all in one line, in which case we - // want to break that up. - var tokens = lineString.split(/>\s* 1) { - var oldLine = line; - var oldPrevIndent = prevIndent; - for (var l in tokens) { - var newLine = tokens[l]; - if (l > 0) { - newLine = '<' + newLine; - } - if (l < tokens.length - 1) { - newLine += '>'; - } - - if (newLine.match(/^\s*<\//)) { - char = '/'; - } else if (newLine.match(/\>[^<>]*$/)) { - char = '>'; - } else { - char = '\n'; - } - var indentation = processChar(line, newLine, prevLineString, prevIndent, char, indentWidth); - prevIndent = indentation; - while (indentation > 0) { - //TODO: what about tabs - newLine = " " + newLine; - --indentation; - } - ++line; - prevLineString = newLine; - tokens[l] = newLine; - } - dbg(tokens.join('\n')); - dbg(oldLine); - document.editBegin(); - document.truncate(oldLine, 0); - document.insertText(oldLine, 0, tokens.join('\n')); - document.editEnd(); - return oldPrevIndent; - } else { - if (lineString.match(/^\s*<\//)) { - char = '/'; - } else if (lineString.match(/\>[^<>]*$/)) { - char = '>'; - } else { - char = '\n'; - } - } - } - - dbg(line); - dbg(lineString); - dbg(prevLineString); - dbg(prevIndent); - dbg(char); - return processChar(line, lineString, prevLineString, prevIndent, char, indentWidth); -} - -function processChar(line, lineString, prevLineString, prevIndent, char, indentWidth) -{ - if (char == '/') { - if (!lineString.match(/^\s*<\//)) { - // might happen when we have something like - // don't change indentation then - return document.firstVirtualColumn(line); - } - if (!prevLineString.match(/<[^\/][^>]*[^\/]>[^<>]*$/)) { - // decrease indent when we write ') { - // increase indent width when we write <...> or <.../> but not - // and the prior line didn't close a tag - if (line == 0) { - return 0; - } else if (prevLineString.match(/^<(\?xml|!DOCTYPE)/)) { - return 0; - } else if (lineString.match(/^\s*<\//)) { - // closing tag, decrease indentation when previous didn't open a tag - if (prevLineString.match(/<[^\/][^>]*[^\/]>[^<>]*$/)) { - // keep indent when prev line opened a tag - return prevIndent; - } else { - return prevIndent - indentWidth; - } - } else if (prevLineString.match(/<([\/!][^>]+|[^>]+\/)>\s*$/)) { - // keep indent when prev line closed a tag or was empty or a comment - return prevIndent; - } - return prevIndent + indentWidth; - } else if (char == '\n') { - if (prevLineString.match(/^<(\?xml|!DOCTYPE)/)) { - return 0; - } - if (prevLineString.match(/<[^\/!][^>]*[^\/]>[^<>]*$/)) { - // increase indent when prev line opened a tag (but not for comments) - return prevIndent + indentWidth; - } - } - - return prevIndent; -} - -// kate: space-indent on; indent-width 4; replace-tabs on; \ No newline at end of file diff --git a/part/script/katecommandlinescript.cpp b/part/script/katecommandlinescript.cpp deleted file mode 100644 index d035eab..0000000 --- a/part/script/katecommandlinescript.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecommandlinescript.h" - -#include -#include - -#include - -#include "katedocument.h" -#include "kateview.h" -#include "katecmd.h" -#include "kshell.h" - -KateCommandLineScript::KateCommandLineScript(const QString &url, const KateCommandLineScriptHeader &header) - : KateScript(url) - , m_commandHeader(header) -{ - KateCmd::self()->registerCommand (this); -} - -KateCommandLineScript::~KateCommandLineScript() -{ - KateCmd::self()->unregisterCommand (this); -} - -const KateCommandLineScriptHeader& KateCommandLineScript::commandHeader() -{ - return m_commandHeader; -} - - -bool KateCommandLineScript::callFunction(const QString& cmd, const QStringList args, QString &errorMessage) -{ - clearExceptions(); - QScriptValue command = function(cmd); - if(!command.isValid()) { - errorMessage = i18n("Function '%1' not found in script: %2", cmd, url()); - return false; - } - - // add the arguments that we are going to pass to the function - QScriptValueList arguments; - foreach (const QString& arg, args) { - arguments << QScriptValue(m_engine, arg); - } - - QScriptValue result = command.call(QScriptValue(), arguments); - // error during the calling? - if(m_engine->hasUncaughtException()) { - errorMessage = backtrace(result, i18n("Error calling %1", cmd)); - return false; - } - - return true; -} - -ScriptActionInfo KateCommandLineScript::actionInfo(const QString& cmd) -{ - clearExceptions(); - QScriptValue actionFunc = function("action"); - if(!actionFunc.isValid()) { - kDebug() << i18n("Function 'action' not found in script: %1", url()); - return ScriptActionInfo(); - } - - // add the arguments that we are going to pass to the function - QScriptValueList arguments; - arguments << cmd; - - QScriptValue result = actionFunc.call(QScriptValue(), arguments); - // error during the calling? - if(m_engine->hasUncaughtException()) { - displayBacktrace(result, i18n("Error calling action(%1)", cmd)); - return ScriptActionInfo(); - } - - ScriptActionInfo info; - info.setCommand(cmd); - info.setText(result.property("text").toString()); - info.setIcon(result.property("icon").toString()); - info.setCategory(result.property("category").toString()); - info.setInteractive(result.property("interactive").toBool()); - info.setShortcut(result.property("shortcut").toString()); - - return info; -} - -const QStringList &KateCommandLineScript::cmds () -{ - return m_commandHeader.functions(); -} - -bool KateCommandLineScript::exec (KTextEditor::View *view, const QString &_cmd, QString &errorMsg) -{ - KShell::Errors errorCode; - QStringList args(KShell::splitArgs(_cmd, KShell::NoOptions, &errorCode)); - - if (errorCode != KShell::NoError) { - errorMsg = i18n("Bad quoting in call: %1. Please escape single quotes with a backslash.", _cmd); - return false; - } - - QString cmd(args.first()); - args.removeFirst(); - - if (!view) { - errorMsg = i18n("Could not access view"); - return false; - } - - if (setView(qobject_cast(view))) { - // setView fails, if the script cannot be loaded - return callFunction(cmd, args, errorMsg); - } - - return false; -} - - -bool KateCommandLineScript::help(KTextEditor::View* view, const QString& cmd, QString &msg) -{ - if (!setView(qobject_cast(view))) { - // setView fails, if the script cannot be loaded - return false; - } - - clearExceptions(); - QScriptValue helpFunction = function("help"); - if(!helpFunction.isValid()) { - return false; - } - - // add the arguments that we are going to pass to the function - QScriptValueList arguments; - arguments << QScriptValue(m_engine, cmd); - - QScriptValue result = helpFunction.call(QScriptValue(), arguments); - - // error during the calling? - if(m_engine->hasUncaughtException()) { - msg = backtrace(result, i18n("Error calling 'help %1'", cmd)); - return false; - } - - if (result.isUndefined() || !result.isString()) { - kDebug(13050) << i18n("No help specified for command '%1' in script %2", cmd, url()); - return false; - } - msg = result.toString(); - - return !msg.isEmpty(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katecommandlinescript.h b/part/script/katecommandlinescript.h deleted file mode 100644 index fce2e49..0000000 --- a/part/script/katecommandlinescript.h +++ /dev/null @@ -1,106 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_COMMANDLINE_SCRIPT_H -#define KATE_COMMANDLINE_SCRIPT_H - -#include "katescript.h" -#include "kateview.h" - -#include -#include - -class KateScriptDocument; - -class KateCommandLineScriptHeader -{ - public: - KateCommandLineScriptHeader() - {} - - inline void setFunctions(const QStringList& functions) - { m_functions = functions; } - inline const QStringList& functions() const - { return m_functions; } - - private: - QStringList m_functions; ///< the functions the script contains -}; - -class ScriptActionInfo -{ - public: - ScriptActionInfo() {} - - inline bool isValid() const { return !(m_command.isEmpty() || m_text.isEmpty()); } - - inline void setCommand(const QString& command) { m_command = command; } - inline QString command() const { return m_command; } - inline void setText(const QString& text) { m_text = text; } - inline QString text() const { return m_text; } - inline void setIcon(const QString& icon) { m_icon = icon; } - inline QString icon() const { return m_icon; } - inline void setCategory(const QString& category) { m_category = category; } - inline QString category() const { return m_category; } - inline void setInteractive(bool interactive) { m_interactive = interactive; } - inline bool interactive() const { return m_interactive; } - inline void setShortcut(const QString& shortcut) { m_shortcut = shortcut; } - inline QString shortcut() const { return m_shortcut; } - - private: - QString m_command; - QString m_text; - QString m_icon; - QString m_category; - bool m_interactive; - QString m_shortcut; -}; - -/** - * A specialized class for scripts that are of type - * KateScriptInformation::IndentationScript - */ -class KateCommandLineScript : public KateScript, public KTextEditor::Command -{ - public: - KateCommandLineScript(const QString &url, const KateCommandLineScriptHeader &header); - virtual ~KateCommandLineScript(); - - const KateCommandLineScriptHeader& commandHeader(); - - bool callFunction(const QString& cmd, const QStringList args, QString &errorMessage); - - ScriptActionInfo actionInfo(const QString& cmd); - - // - // KTextEditor::Command interface - // - public: - virtual const QStringList &cmds (); - virtual bool exec (KTextEditor::View *view, const QString &cmd, QString &msg); - virtual bool help (KTextEditor::View *view, const QString &cmd, QString &msg); - - private: - KateCommandLineScriptHeader m_commandHeader; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/kateindentscript.cpp b/part/script/kateindentscript.cpp deleted file mode 100644 index 91c6314..0000000 --- a/part/script/kateindentscript.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#include "kateindentscript.h" - -#include -#include - -#include "katedocument.h" -#include "kateview.h" - -KateIndentScript::KateIndentScript(const QString &url, const KateIndentScriptHeader &header) - : KateScript(url) - , m_triggerCharactersSet (false) - , m_indentHeader(header) -{ -} - -const KateIndentScriptHeader& KateIndentScript::indentHeader() const -{ - return m_indentHeader; -} - -const QString &KateIndentScript::triggerCharacters() -{ - // already set, perfect, just return... - if (m_triggerCharactersSet) - return m_triggerCharacters; - - m_triggerCharactersSet = true; - - m_triggerCharacters = global("triggerCharacters").toString(); - - //kDebug( 13050 ) << "trigger chars: '" << m_triggerCharacters << "'"; - - return m_triggerCharacters; -} - -QPair KateIndentScript::indent(KateView* view, const KTextEditor::Cursor& position, - QChar typedCharacter, int indentWidth) -{ - // if it hasn't loaded or we can't load, return - if(!setView(view)) - return qMakePair(-2,-2); - - clearExceptions(); - QScriptValue indentFunction = function("indent"); - if(!indentFunction.isValid()) { - return qMakePair(-2,-2); - } - // add the arguments that we are going to pass to the function - QScriptValueList arguments; - arguments << QScriptValue(m_engine, position.line()); - arguments << QScriptValue(m_engine, indentWidth); - arguments << QScriptValue(m_engine, typedCharacter.isNull() ? QString("") : QString(typedCharacter)); - // get the required indent - QScriptValue result = indentFunction.call(QScriptValue(), arguments); - // error during the calling? - if(m_engine->hasUncaughtException()) { - displayBacktrace(result, "Error calling indent()"); - return qMakePair(-2,-2); - } - int indentAmount = -2; - int alignAmount = -2; - if (result.isArray()) { - indentAmount = result.property(0).toInt32(); - alignAmount = result.property(1).toInt32(); - } else { - indentAmount = result.toInt32(); - } - if(m_engine->hasUncaughtException()) { - displayBacktrace(QScriptValue(), "Bad return type (must be integer)"); - return qMakePair(-2,-2); - } - return qMakePair(indentAmount, alignAmount); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/kateindentscript.h b/part/script/kateindentscript.h deleted file mode 100644 index b0ede0d..0000000 --- a/part/script/kateindentscript.h +++ /dev/null @@ -1,119 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#ifndef KATE_INDENT_SCRIPT_H -#define KATE_INDENT_SCRIPT_H - -#include "katescript.h" -#include "kateview.h" - -#include - -class KateScriptDocument; - -class KateIndentScriptHeader -{ - public: - KateIndentScriptHeader() : m_priority(0) - {} - - inline void setName(const QString& name) - { m_name = name; } - inline const QString& name() const - { return m_name; } - - inline void setRequiredStyle(const QString& requiredStyle) - { m_requiredStyle = requiredStyle; } - inline const QString& requiredStyle() const - { return m_requiredStyle; } - - inline void setIndentLanguages(const QStringList& indentLanguages) - { m_indentLanguages = indentLanguages; } - inline const QStringList& indentLanguages() const - { return m_indentLanguages; } - - inline void setPriority(int priority) - { m_priority = priority; } - inline int priority() const - { return m_priority; } - - inline void setBaseName(const QString& baseName) - { m_baseName = baseName; } - inline const QString& baseName() const - { return m_baseName; } - - private: - QString m_name; ///< indenter name, e.g. Python - - /** - * If this is an indenter, then this specifies the required syntax - * highlighting style that must be used for this indenter to work properly. - * If this property is empty, the indenter doesn't require a specific style. - */ - QString m_requiredStyle; - /** - * If this script is an indenter, then the indentLanguages member specifies - * which languages this is an indenter for. The values must correspond with - * the name of a programming language given in a highlighting file (e.g "TI Basic") - */ - QStringList m_indentLanguages; - /** - * If this script is an indenter, this value controls the priority it will take - * when an indenter for one of the supported languages is requested and multiple - * indenters are found - */ - int m_priority; - - /** - * basename of script - */ - QString m_baseName; -}; - - -/** - * A specialized class for scripts that are of type - * KateScriptInformation::IndentationScript - */ -class KateIndentScript : public KateScript -{ - public: - KateIndentScript(const QString &url, const KateIndentScriptHeader &header); - - const QString &triggerCharacters(); - - const KateIndentScriptHeader& indentHeader() const; - - /** - * Returns a pair where the first value is the indent amount, and the second - * value is the alignment. - */ - QPair indent(KateView* view, const KTextEditor::Cursor& position, - QChar typedCharacter, int indentWidth); - - private: - QString m_triggerCharacters; - bool m_triggerCharactersSet; - KateIndentScriptHeader m_indentHeader; -}; - - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescript.cpp b/part/script/katescript.cpp deleted file mode 100644 index 95f7818..0000000 --- a/part/script/katescript.cpp +++ /dev/null @@ -1,322 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009, 2010 Dominik Haumann -// Copyright (C) 2010 Joseph Wenninger -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#include "katescript.h" -#include "katescriptdocument.h" -#include "katescriptview.h" -#include "katescripthelpers.h" -#include "kateview.h" -#include "katedocument.h" - -#include - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -//BEGIN conversion functions for Cursors and Ranges -/** Converstion function from KTextEditor::Cursor to QtScript cursor */ -static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor) -{ - QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) - .arg(cursor.column()); - return engine->evaluate(code); -} - -/** Converstion function from QtScript cursor to KTextEditor::Cursor */ -static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor) -{ - cursor.setPosition(obj.property("line").toInt32(), - obj.property("column").toInt32()); -} - -/** Converstion function from QtScript range to KTextEditor::Range */ -static QScriptValue rangeToScriptValue(QScriptEngine *engine, const KTextEditor::Range &range) -{ - QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) - .arg(range.start().column()) - .arg(range.end().line()) - .arg(range.end().column()); - return engine->evaluate(code); -} - -/** Converstion function from QtScript range to KTextEditor::Range */ -static void rangeFromScriptValue(const QScriptValue &obj, KTextEditor::Range &range) -{ - range.start().setPosition(obj.property("start").property("line").toInt32(), - obj.property("start").property("column").toInt32()); - range.end().setPosition(obj.property("end").property("line").toInt32(), - obj.property("end").property("column").toInt32()); -} -//END - - - -bool KateScript::s_scriptingApiLoaded = false; - -void KateScript::reloadScriptingApi() -{ - s_scriptingApiLoaded = false; -} - -bool KateScript::readFile(const QString& sourceUrl, QString& sourceCode) -{ - sourceCode = QString(); - - QFile file(sourceUrl); - if (!file.open(QIODevice::ReadOnly)) { - kDebug(13050) << i18n("Unable to find '%1'", sourceUrl); - return false; - } else { - QTextStream stream(&file); - stream.setCodec("UTF-8"); - sourceCode = stream.readAll(); - file.close(); - } - return true; -} - - -KateScript::KateScript(const QString &urlOrScript, enum InputType inputType) - : m_loaded(false) - , m_loadSuccessful(false) - , m_url(inputType == InputURL ? urlOrScript : QString()) - , m_engine(0) - , m_document(0) - , m_view(0) - , m_inputType(inputType) - , m_script(inputType == InputSCRIPT ? urlOrScript : QString()) -{ -} - -KateScript::~KateScript() -{ - if(m_loadSuccessful) { - // unload i18n catalog if available + loaded - if (!generalHeader().catalog().isEmpty()) { - kDebug() << "unloading i18n catalog" << generalHeader().catalog(); - KGlobal::locale()->removeCatalog(generalHeader().catalog()); - } - - // remove data... - delete m_engine; - delete m_document; - delete m_view; - } -} - -QString KateScript::backtrace( const QScriptValue& error, const QString& header ) -{ - QString bt; - if(!header.isNull()) - bt += header + ":\n"; - if(error.isError()) - bt += error.toString() + '\n'; - - bt += m_engine->uncaughtExceptionBacktrace().join("\n") + '\n'; - - return bt; -} - -void KateScript::displayBacktrace(const QScriptValue &error, const QString &header) -{ - if(!m_engine) { - std::cerr << "KateScript::displayBacktrace: no engine, cannot display error\n"; - return; - } - std::cerr << "\033[31m" << qPrintable(backtrace(error, header)) << "\033[0m" << '\n'; -} - -void KateScript::clearExceptions() -{ - if (!load()) - return; - m_engine->clearExceptions(); -} - -QScriptValue KateScript::global(const QString &name) -{ - // load the script if necessary - if(!load()) - return QScriptValue(); - return m_engine->globalObject().property(name); -} - -QScriptValue KateScript::function(const QString &name) -{ - QScriptValue value = global(name); - if(!value.isFunction()) - return QScriptValue(); - return value; -} - -bool KateScript::initApi () -{ - // cache file names - static QStringList apiFileBaseNames; - static QHash apiBaseName2FileName; - static QHash apiBaseName2Content; - - // read katepart javascript api - if (!s_scriptingApiLoaded) { - s_scriptingApiLoaded = true; - apiFileBaseNames.clear (); - apiBaseName2FileName.clear (); - apiBaseName2Content.clear (); - - // get all api files - const QStringList list = KGlobal::dirs()->findAllResources("data","katepart/api/*.js", KStandardDirs::NoDuplicates); - - for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) - { - // get abs filename.... - QFileInfo fi(*it); - const QString absPath = fi.absoluteFilePath(); - const QString baseName = fi.baseName (); - - // remember filenames - apiFileBaseNames.append (baseName); - apiBaseName2FileName[baseName] = absPath; - - // read the file - QString content; - readFile(absPath, content); - apiBaseName2Content[baseName] = content; - } - - // sort... - apiFileBaseNames.sort (); - } - - // register all script apis found - for ( QStringList::ConstIterator it = apiFileBaseNames.constBegin(); it != apiFileBaseNames.constEnd(); ++it ) - { - // try to load into engine, bail out one error, use fullpath for error messages - QScriptValue apiObject = m_engine->evaluate(apiBaseName2Content[*it], apiBaseName2FileName[*it]); - if (hasException(apiObject, apiBaseName2FileName[*it])) { - return false; - } - } - - // success ;) - return true; -} - -bool KateScript::load() -{ - if(m_loaded) - return m_loadSuccessful; - - m_loaded = true; - m_loadSuccessful = false; // here set to false, and at end of function to true - - // read the script file into memory - QString source; - if (m_inputType == InputURL) { - if (!readFile(m_url, source)) { - return false; - } - } else source = m_script; - - // create script engine, register meta types - m_engine = new QScriptEngine(); - qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue); - qScriptRegisterMetaType (m_engine, rangeToScriptValue, rangeFromScriptValue); - - // init API - if (!initApi ()) - return false; - - // register scripts itself - QScriptValue result = m_engine->evaluate(source, m_url); - if (hasException(result, m_url)) { - return false; - } - - // yip yip! - initEngine(); - m_loadSuccessful = true; - // load i18n catalog if available - if (!generalHeader().catalog().isEmpty()) { - kDebug() << "loading i18n catalog" << generalHeader().catalog(); - KGlobal::locale()->insertCatalog(generalHeader().catalog()); - } - return true; -} - -bool KateScript::hasException(const QScriptValue& object, const QString& file) -{ - if(m_engine->hasUncaughtException()) { - displayBacktrace(object, i18n("Error loading script %1\n", file)); - m_errorMessage = i18n("Error loading script %1", file); - delete m_engine; - m_engine = 0; - m_loadSuccessful = false; - return true; - } - return false; -} - - -void KateScript::initEngine() -{ - // set the view/document objects as necessary - m_engine->globalObject().setProperty("document", m_engine->newQObject(m_document = new KateScriptDocument())); - m_engine->globalObject().setProperty("view", m_engine->newQObject(m_view = new KateScriptView())); - - // export debug function - m_engine->globalObject().setProperty("debug", m_engine->newFunction(Kate::Script::debug)); - - // export translation functions - m_engine->globalObject().setProperty("i18n", m_engine->newFunction(Kate::Script::i18n)); - m_engine->globalObject().setProperty("i18nc", m_engine->newFunction(Kate::Script::i18nc)); - m_engine->globalObject().setProperty("i18ncp", m_engine->newFunction(Kate::Script::i18ncp)); - m_engine->globalObject().setProperty("i18np", m_engine->newFunction(Kate::Script::i18np)); -} - -bool KateScript::setView(KateView *view) -{ - if (!load()) - return false; - // setup the stuff - m_document->setDocument (view->doc()); - m_view->setView (view); - return true; -} - -void KateScript::setGeneralHeader(const KateScriptHeader& generalHeader) -{ - m_generalHeader = generalHeader; -} - -KateScriptHeader& KateScript::generalHeader() -{ - return m_generalHeader; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescript.h b/part/script/katescript.h deleted file mode 100644 index d2bd6e7..0000000 --- a/part/script/katescript.h +++ /dev/null @@ -1,220 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// Copyright (C) 2010 Joseph Wenninger -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#ifndef KATE_SCRIPT_H -#define KATE_SCRIPT_H - -#include -#include -#include - -#include -#include - -class QScriptEngine; -class QScriptContext; - -class KateDocument; -class KateView; - -class KateScriptDocument; -class KateScriptView; - -namespace Kate { - enum ScriptType { - /** The script is an indenter */ - IndentationScript, - /** The script contains command line commands */ - CommandLineScript, - /** Don't know what kind of script this is */ - UnknownScript - }; -} - -//BEGIN KateScriptHeader - -class KateScriptHeader -{ - public: - KateScriptHeader() : m_revision(0), m_scriptType(Kate::UnknownScript) - {} - virtual ~KateScriptHeader() - {} - - inline void setLicense(const QString& license) - { m_license = license; } - inline const QString& license() const - { return m_license; } - - inline void setAuthor(const QString& author) - { m_author = author; } - inline const QString& author() const - { return m_author; } - - inline void setRevision(int revision) - { m_revision = revision; } - inline int revision() const - { return m_revision; } - - inline void setKateVersion(const QString& kateVersion) - { m_kateVersion = kateVersion; } - inline const QString& kateVersion() const - { return m_kateVersion; } - - inline void setCatalog(const QString& catalog) - { m_i18nCatalog = catalog; } - inline const QString& catalog() const - { return m_i18nCatalog; } - - inline void setScriptType(Kate::ScriptType scriptType) - { m_scriptType = scriptType; } - inline Kate::ScriptType scriptType() const - { return m_scriptType; } - - private: - QString m_license; ///< the script's license, e.g. LGPL - QString m_author; ///< the script author, e.g. "John Smith " - int m_revision; ///< script revision, a simple number, e.g. 1, 2, 3, ... - QString m_kateVersion; ///< required katepart version - QString m_i18nCatalog; ///< i18n catalog - Kate::ScriptType m_scriptType; ///< the script type -}; -//END - -//BEGIN KateScript - -/** - * KateScript objects represent a script that can be executed and inspected. - */ -class KateScript { - public: - - enum InputType { - InputURL, - InputSCRIPT - }; - - /** - * Create a new script representation, passing either a file or the script - * content @p urlOrScript to it. - * In case of a file, loading of the script will happen lazily. - */ - KateScript(const QString &urlOrScript, enum InputType inputType = InputURL); - virtual ~KateScript(); - - /** The script's URL */ - const QString &url() { return m_url; } - - /** - * Load the script. If loading is successful, returns true. Otherwise, returns - * returns false and an error message will be set (see errorMessage()). - * Note that you don't have to call this -- it is called as necessary by the - * functions that require it. - * Subsequent calls to load will return the value it returned the first time. - */ - bool load(); - - /** - * set view for this script for the execution - * will trigger load! - */ - bool setView (KateView *view); - - /** - * Get a QScriptValue for a global item in the script given its name, or an - * invalid QScriptValue if no such global item exists. - */ - QScriptValue global(const QString &name); - - /** - * Return a function in the script of the given name, or an invalid QScriptValue - * if no such function exists. - */ - QScriptValue function(const QString &name); - - /** Return a context-specific error message */ - const QString &errorMessage() { return m_errorMessage; } - - /** Returns the backtrace when a script has errored out */ - QString backtrace(const QScriptValue &error, const QString &header = QString()); - - /** Displays the backtrace when a script has errored out */ - void displayBacktrace(const QScriptValue &error, const QString &header = QString()); - - /** Clears any uncaught exceptions in the script engine. */ - void clearExceptions(); - - /** set the general header after construction of the script */ - void setGeneralHeader(const KateScriptHeader& generalHeader); - /** Return the general header */ - KateScriptHeader& generalHeader(); - - protected: - /** Checks for exception and gives feedback on the console. */ - bool hasException(const QScriptValue& object, const QString& file); - - /** read complete file contents */ - static bool readFile(const QString& sourceUrl, QString& sourceCode); - - private: - /** init API, can fail on error in api files */ - bool initApi (); - - /** Add our custom functions to m_engine when it has been initialised */ - void initEngine(); - - /** Whether or not there has been a call to load */ - bool m_loaded; - /** Whether or not the script loaded successfully into memory */ - bool m_loadSuccessful; - /** The script's URL */ - QString m_url; - /** An error message set when an error occurs */ - QString m_errorMessage; - - protected: - /** The Qt interpreter for this script */ - QScriptEngine *m_engine; - - private: - /** general header data */ - KateScriptHeader m_generalHeader; - - /** document/view wrapper objects */ - KateScriptDocument *m_document; - KateScriptView *m_view; - - public: - static void reloadScriptingApi(); - - private: - /** True, if the katepartapi.js file is already loaded, otherwise false */ - static bool s_scriptingApiLoaded; - - /** if input is script or url**/ - enum InputType m_inputType; - QString m_script; -}; - -//END - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptaction.cpp b/part/script/katescriptaction.cpp deleted file mode 100644 index f55e1a5..0000000 --- a/part/script/katescriptaction.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katescriptaction.h" -#include "katecommandlinescript.h" -#include "katescriptmanager.h" -#include "kateview.h" -#include "katedocument.h" -#include "kateglobal.h" -#include "kateviewhelpers.h" -#include "kactioncollection.h" - -#include -#include -#include -#include - -//BEGIN KateScriptAction -KateScriptAction::KateScriptAction(const ScriptActionInfo& info, KateView* view) - : KAction(info.text(), view) - , m_view(view) - , m_command(info.command()) - , m_interactive(info.interactive()) -{ - if (!info.icon().isEmpty()) { - setIcon(KIcon(info.icon())); - } - - if (!info.shortcut().isEmpty()) { - setShortcut(info.shortcut()); - } - - connect(this, SIGNAL(triggered(bool)), this, SLOT(exec())); -} - -KateScriptAction::~KateScriptAction() -{ -} - -void KateScriptAction::exec() -{ - KateCommandLineBar* cmdLine = m_view->cmdLineBar(); - - if (m_interactive) { - m_view->bottomViewBar()->showBarWidget(cmdLine); - cmdLine->setText(m_command + ' ', false); - } else { - cmdLine->execute(m_command); - } -} -//END KateScriptAction - - -//BEGIN KateScriptActionMenu -KateScriptActionMenu::KateScriptActionMenu(KateView *view, const QString& text) - : KActionMenu (KIcon("code-context"), text, view) - , m_view(view) -{ - repopulate(); - - // on script-reload signal, repopulate script menu - connect(KateGlobal::self()->scriptManager(), SIGNAL(reloaded()), - this, SLOT(repopulate())); -} - -KateScriptActionMenu::~KateScriptActionMenu() -{ - cleanup(); -} - -void KateScriptActionMenu::cleanup() -{ - // delete menus and actions for real - qDeleteAll(m_menus); - m_menus.clear(); - - qDeleteAll(m_actions); - m_actions.clear(); -} - -void KateScriptActionMenu::repopulate() -{ - // if the view is already hooked into the GUI, first remove it - // now and add it later, so that the changes we do here take effect - KXMLGUIFactory *viewFactory = m_view->factory(); - if (viewFactory) - viewFactory->removeClient(m_view); - - // remove existing menu actions - cleanup(); - - // now add all command line script commands - QVector scripts = - KateGlobal::self()->scriptManager()->commandLineScripts(); - - QHash menus; - - foreach (KateCommandLineScript* script, scripts) { - - const QStringList &cmds = script->cmds(); - foreach (const QString& cmd, cmds) { - - ScriptActionInfo info = script->actionInfo(cmd); - if (!info.isValid()) - continue; - - QMenu* m = menu(); - - // show in a category submenu? - if (!info.category().isEmpty()) { - if (!menus.contains(info.category())) { - m = menu()->addMenu(info.category()); - menus.insert(info.category(), m); - m_menus.append(m); - } - } - - // create action + add to menu - KAction* a = new KateScriptAction(info, m_view); - m->addAction(a); - m_view->actionCollection()->addAction("tools_scripts_" + cmd, a); - m_actions.append(a); - } - } - - // finally add the view to the xml factory again, if it initially was there - if (viewFactory) - viewFactory->addClient(m_view); -} - -//END KateScriptActionMenu - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptaction.h b/part/script/katescriptaction.h deleted file mode 100644 index cb59c8d..0000000 --- a/part/script/katescriptaction.h +++ /dev/null @@ -1,76 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_SCRIPT_ACTION_H -#define KATE_SCRIPT_ACTION_H - -#include "katecommandlinescript.h" - -#include -#include - -class KateView; - -/** - * KateScriptAction is an action that executes a commandline-script - * if triggered. It is shown in Tools > Scripts. - */ -class KateScriptAction : public KAction -{ - Q_OBJECT - - public: - KateScriptAction(const ScriptActionInfo& info, KateView* view); - virtual ~KateScriptAction(); - - public Q_SLOTS: - void exec(); - - private: - KateView* m_view; - QString m_command; - bool m_interactive; -}; - -/** - * Tools > Scripts menu - * This menu is filled with the command line scripts exported - * via the scripting support. - */ -class KateScriptActionMenu : public KActionMenu -{ - Q_OBJECT - - public: - KateScriptActionMenu(KateView* view, const QString& text); - ~KateScriptActionMenu(); - - void cleanup(); - - public Q_SLOTS: - void repopulate(); - - private: - KateView* m_view; - QList m_menus; - QList m_actions; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptconsole.cpp b/part/script/katescriptconsole.cpp deleted file mode 100644 index b81a825..0000000 --- a/part/script/katescriptconsole.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2010 Miquel Sabaté - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -//BEGIN Includes -// Qt -#include -#include -#include -#include -#include - -// KDE -#include -#include - -// Kate -#include "katescriptconsole.h" -#include "katetemplatescript.h" -//END Includes - - -//BEGIN KateScriptConsoleEngine -KateScriptConsoleEngine::KateScriptConsoleEngine(KateView * view) - : m_view (view) -{ - m_utilsUrl = KGlobal::dirs()->findResource("data", "katepart/script/utils.js"); -} - -KateScriptConsoleEngine::~KateScriptConsoleEngine() -{ - /* There's nothing to do here */ -} - -const QString & KateScriptConsoleEngine::execute(const QString & text) -{ - static QString msg; - msg = ""; - QString name = getFirstFunctionName(text, msg); - if (name.isEmpty() && !msg.isEmpty()) // Error - return msg; - - QFile file(m_utilsUrl); - if (!file.open(QFile::ReadOnly)) { - msg = "Error: can't open utils.js"; - return msg; - } - QString utilsCode = file.readAll(); - file.close(); - - QString funcCode; - if (name.isEmpty()) { // It's a command - name = "foo"; - funcCode = utilsCode + "function foo() { " + text + " }"; - } else // It's a set of functions - funcCode = utilsCode + text; - KateTemplateScript script(funcCode); - msg = script.invoke(m_view, name, ""); - if (msg.isEmpty()) - msg = "SyntaxError: Parse error"; - return msg; -} - -const QString KateScriptConsoleEngine::getFirstFunctionName(const QString & text, QString & msg) -{ - QString name = ""; - QRegExp reg("(function)"); - int i = reg.indexIn(text); - if (i < 0) // there's no defined functions - return ""; - i += 8; // "function" - for (; text[i] != '('; ++i) { - if (text[i] == ' ') // avoid blank spaces - continue; - if (text[i] == '{' || text[i] == '}' || text[i] == ')') { // bad ... - msg = "Error: There are bad defined functions"; - return ""; - } - name.append(text[i]); - } - return name; -} -//END KateScriptConsoleEngine - - -//BEGIN KateScriptConsole -KateScriptConsole::KateScriptConsole(KateView * view, QWidget * parent) - : KateViewBarWidget (true, parent) - , m_view (view) -{ - Q_ASSERT(m_view != NULL); - - initialSize = parent->size(); - layout = new QVBoxLayout(); - centralWidget()->setLayout(layout); - layout->setMargin(0); - hLayout = new QHBoxLayout; - m_result = new QLabel(this); - m_edit = new QTextEdit(this); - m_execute = new QPushButton(i18n("Execute"), this); - m_execute->setIcon(KIcon("quickopen")); - connect(m_execute, SIGNAL(clicked()), this, SLOT(executePressed())); - - layout->addWidget(m_edit); - hLayout->addWidget(m_result); - hLayout->addWidget(m_execute, 1, Qt::AlignRight); - layout->addLayout(hLayout); - - m_engine = new KateScriptConsoleEngine(m_view); -} - -void KateScriptConsole::setupLayout() -{ - resize(endSize); - layout->setMargin(0); - hLayout = new QHBoxLayout; - layout->addWidget(m_edit); - hLayout->addWidget(m_result); - hLayout->addWidget(m_execute, 1, Qt::AlignRight); - layout->addLayout(hLayout); -} - -KateScriptConsole::~KateScriptConsole() -{ - delete m_engine; -} - -void KateScriptConsole::closed() -{ - endSize = this->size(); - layout->removeWidget(m_edit); - hLayout->removeWidget(m_result); - hLayout->removeWidget(m_execute); - delete hLayout; - resize(initialSize); -} - -void KateScriptConsole::switched() -{ - if (this->size() != initialSize) - closed(); -} - -void KateScriptConsole::executePressed() -{ - QString text = m_edit->toPlainText(); - QString msg; - if (!text.isEmpty()) { - msg = m_engine->execute(text); - m_result->setText("" + msg + ""); - } else - m_result->setText("There's no code to execute"); -} -//END KateScriptConsole - - -#include "katescriptconsole.moc" - - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/script/katescriptconsole.h b/part/script/katescriptconsole.h deleted file mode 100644 index 8f0a127..0000000 --- a/part/script/katescriptconsole.h +++ /dev/null @@ -1,105 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2010 Miquel Sabaté - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#ifndef KATE_SCRIPT_CONSOLE_H -#define KATE_SCRIPT_CONSOLE_H - - -#include "kateviewhelpers.h" - -class QTextEdit; -class QPushButton; -class QLabel; -class QVBoxLayout; -class QHBoxLayout; - - -/** - * Manage JavaScript, allowing the user directly type commands as in - * KateCommnadLineBar environment. It also allows the user to define - * his own JavaScript functions and to redefine each one of them. - */ -class KateScriptConsoleEngine -{ - public: - /** Constructor + Destructor */ - KateScriptConsoleEngine(KateView * view); - virtual ~KateScriptConsoleEngine(); - - /** - * Execute a command or a set of functions - * @param text text containing a command or a set of functions. - * @return a printable message about the execution. - */ - const QString & execute(const QString & text); - - private: - /** Url of utils.js file */ - QString m_utilsUrl; - - /** Just a Kate view :) */ - KateView * m_view; - - private: - /** - * Get the name of the first defined function - * @param text text containing a command or a set of functions. - * @param msg an error string - * @return the name of the first function defined or a void QString if - * there's no functions. - */ - const QString getFirstFunctionName(const QString & text, QString & msg); -}; - - -class KateScriptConsole : public KateViewBarWidget -{ - Q_OBJECT - - public: - KateScriptConsole(KateView * view, QWidget * parent = NULL); - virtual ~KateScriptConsole(); - - void setupLayout(); - - protected: - // overriden - virtual void closed(); - virtual void switched(); - - private: - QVBoxLayout * layout; - QHBoxLayout * hLayout; - QTextEdit * m_edit; - QPushButton * m_execute; - QLabel * m_result; - QSize initialSize, endSize; - KateView * m_view; - KateScriptConsoleEngine * m_engine; - - public slots: - void executePressed(); -}; - - -#endif /* KATE_SCRIPT_CONSOLE_H */ - - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/script/katescriptdocument.cpp b/part/script/katescriptdocument.cpp deleted file mode 100644 index 4727576..0000000 --- a/part/script/katescriptdocument.cpp +++ /dev/null @@ -1,701 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#include "katescriptdocument.h" - -#include "katedocument.h" -#include "kateview.h" -#include "katerenderer.h" -#include "kateconfig.h" -#include "katehighlight.h" -#include "katescript.h" - -#include -#include - -#include - -KateScriptDocument::KateScriptDocument(QObject *parent) - : QObject(parent), m_document(0) -{ -} - -void KateScriptDocument::setDocument(KateDocument *document) -{ - m_document = document; -} - -KateDocument *KateScriptDocument::document() -{ - return m_document; -} - -int KateScriptDocument::defStyleNum(int line, int column) -{ - QList attributes = m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema()); - KTextEditor::Attribute::Ptr a = attributes[document()->plainKateTextLine(line)->attribute(column)]; - return a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt(); -} - -int KateScriptDocument::defStyleNum(const KTextEditor::Cursor& cursor) -{ - return defStyleNum(cursor.line(), cursor.column()); -} - - -bool KateScriptDocument::isCode(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return _isCode(defaultStyle); -} - -bool KateScriptDocument::isCode(const KTextEditor::Cursor& cursor) -{ - return isCode(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isComment(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return defaultStyle == KTextEditor::HighlightInterface::dsComment; -} - -bool KateScriptDocument::isComment(const KTextEditor::Cursor& cursor) -{ - return isComment(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isString(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return defaultStyle == KTextEditor::HighlightInterface::dsString; -} - -bool KateScriptDocument::isString(const KTextEditor::Cursor& cursor) -{ - return isString(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isRegionMarker(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return defaultStyle == KTextEditor::HighlightInterface::dsRegionMarker; -} - -bool KateScriptDocument::isRegionMarker(const KTextEditor::Cursor& cursor) -{ - return isRegionMarker(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isChar(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return defaultStyle == KTextEditor::HighlightInterface::dsChar; -} - -bool KateScriptDocument::isChar(const KTextEditor::Cursor& cursor) -{ - return isChar(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isOthers(int line, int column) -{ - const int defaultStyle = defStyleNum(line, column); - return defaultStyle == KTextEditor::HighlightInterface::dsOthers; -} - -bool KateScriptDocument::isOthers(const KTextEditor::Cursor& cursor) -{ - return isOthers(cursor.line(), cursor.column()); -} - -int KateScriptDocument::firstVirtualColumn(int line) -{ - const int tabWidth = m_document->config()->tabWidth(); - Kate::TextLine textLine = m_document->plainKateTextLine(line); - const int firstPos = textLine ? textLine->firstChar() : -1; - if(!textLine || firstPos == -1) - return -1; - return textLine->indentDepth(tabWidth); -} - -int KateScriptDocument::lastVirtualColumn(int line) -{ - const int tabWidth = m_document->config()->tabWidth(); - Kate::TextLine textLine = m_document->plainKateTextLine(line); - const int lastPos = textLine ? textLine->lastChar() : -1; - if(!textLine || lastPos == -1) - return -1; - return textLine->toVirtualColumn(lastPos, tabWidth); -} - -int KateScriptDocument::toVirtualColumn(int line, int column) -{ - const int tabWidth = m_document->config()->tabWidth(); - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if (!textLine || column < 0 || column > textLine->length()) return -1; - return textLine->toVirtualColumn(column, tabWidth); -} - -int KateScriptDocument::toVirtualColumn(const KTextEditor::Cursor& cursor) -{ - return toVirtualColumn(cursor.line(), cursor.column()); -} - -KTextEditor::Cursor KateScriptDocument::toVirtualCursor(const KTextEditor::Cursor& cursor) -{ - return KTextEditor::Cursor(cursor.line(), - toVirtualColumn(cursor.line(), cursor.column())); -} - -int KateScriptDocument::fromVirtualColumn(int line, int virtualColumn) -{ - const int tabWidth = m_document->config()->tabWidth(); - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if(!textLine || virtualColumn < 0 || virtualColumn > textLine->virtualLength(tabWidth)) - return -1; - return textLine->fromVirtualColumn(virtualColumn, tabWidth); -} - -int KateScriptDocument::fromVirtualColumn(const KTextEditor::Cursor& virtualCursor) -{ - return fromVirtualColumn(virtualCursor.line(), virtualCursor.column()); -} - -KTextEditor::Cursor KateScriptDocument::fromVirtualCursor(const KTextEditor::Cursor& virtualCursor) -{ - return KTextEditor::Cursor(virtualCursor.line(), - fromVirtualColumn(virtualCursor.line(), virtualCursor.column())); -} - -KTextEditor::Cursor KateScriptDocument::rfind(int line, int column, const QString& text, int attribute) -{ - QScopedPointer cursor(document()->newMovingCursor(KTextEditor::Cursor(line, column))); - const int start = cursor->line(); - QList attributes = - m_document->highlight()->attributes(((KateView*)m_document->activeView())->renderer()->config()->schema()); - - do { - Kate::TextLine textLine = m_document->plainKateTextLine(cursor->line()); - if (!textLine) - break; - - if (cursor->line() != start) { - cursor->setColumn(textLine->length()); - } else if (column >= textLine->length()) { - cursor->setColumn(qMax(textLine->length(), 0)); - } - - int foundAt; - while ((foundAt = textLine->string().left(cursor->column()).lastIndexOf(text, -1, Qt::CaseSensitive)) >= 0) { - bool hasStyle = true; - if (attribute != -1) { - KTextEditor::Attribute::Ptr a = attributes[textLine->attribute(foundAt)]; - const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt(); - hasStyle = (ds == attribute); - } - - if (hasStyle) { - return KTextEditor::Cursor(cursor->line(), foundAt); - } else { - cursor->setColumn(foundAt); - } - } - } while (cursor->gotoPreviousLine()); - - return KTextEditor::Cursor::invalid(); -} - -KTextEditor::Cursor KateScriptDocument::rfind(const KTextEditor::Cursor& cursor, const QString& text, int attribute) -{ - return rfind(cursor.line(), cursor.column(), text, attribute); -} - -KTextEditor::Cursor KateScriptDocument::anchor(int line, int column, QChar character) -{ - QList attributes = - m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema()); - int count = 1; - QChar lc; - QChar rc; - if (character == '(' || character == ')') { - lc = '('; - rc = ')'; - } else if (character == '{' || character == '}') { - lc = '{'; - rc = '}'; - } else if (character == '[' || character == ']') { - lc = '['; - rc = ']'; - } else { - kDebug(13060) << "invalid anchor character:" << character << " allowed are: (){}[]"; - return KTextEditor::Cursor::invalid(); - } - - QScopedPointer cursor(document()->newMovingCursor(KTextEditor::Cursor(line, column))); - - // Move backwards char by char and find the opening character - while (cursor->move(-1)) { - QChar ch = document()->character(cursor->toCursor()); - if (ch == lc) { - KTextEditor::Attribute::Ptr a = attributes[document()->plainKateTextLine(cursor->line())->attribute(cursor->column())]; - const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt(); - if (_isCode(ds)) { - --count; - } - } - else if (ch == rc) { - KTextEditor::Attribute::Ptr a = attributes[document()->plainKateTextLine(cursor->line())->attribute(cursor->column())]; - const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt(); - if (_isCode(ds)) { - ++count; - } - } - - if (count == 0) { - return cursor->toCursor(); - } - } - return KTextEditor::Cursor::invalid (); -} - -KTextEditor::Cursor KateScriptDocument::anchor(const KTextEditor::Cursor& cursor, QChar character) -{ - return anchor(cursor.line(), cursor.column(), character); -} - -bool KateScriptDocument::startsWith (int line, const QString &pattern, bool skipWhiteSpaces) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - - if (!textLine) - return false; - - if (skipWhiteSpaces) - return textLine->matchesAt(textLine->firstChar(), pattern); - - return textLine->startsWith (pattern); -} - -bool KateScriptDocument::endsWith (int line, const QString &pattern, bool skipWhiteSpaces) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - - if (!textLine) - return false; - - if (skipWhiteSpaces) - return textLine->matchesAt(textLine->lastChar() - pattern.length() + 1, pattern); - - return textLine->endsWith (pattern); -} - -//BEGIN Automatically generated - -QString KateScriptDocument::fileName() -{ - return m_document->documentName(); -} - -QString KateScriptDocument::url() -{ - return m_document->url().prettyUrl(); -} - -QString KateScriptDocument::mimeType() -{ - return m_document->mimeType(); -} - -QString KateScriptDocument::encoding() -{ - return m_document->encoding(); -} - -QString KateScriptDocument::highlightingMode() -{ - return m_document->highlightingMode(); -} - -QStringList KateScriptDocument::embeddedHighlightingModes() -{ - return m_document->embeddedHighlightingModes(); -} - -QString KateScriptDocument::highlightingModeAt(const KTextEditor::Cursor& pos) -{ - return m_document->highlightingModeAt(pos); -} - -bool KateScriptDocument::isModified() -{ - return m_document->isModified(); -} - -QString KateScriptDocument::text() -{ - return m_document->text(); -} - -QString KateScriptDocument::text(int fromLine, int fromColumn, int toLine, int toColumn) -{ - return text(KTextEditor::Range(fromLine, fromColumn, toLine, toColumn)); -} - -QString KateScriptDocument::text(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to) -{ - return text(KTextEditor::Range(from, to)); -} - -QString KateScriptDocument::text(const KTextEditor::Range& range) -{ - return m_document->text(range); -} - -QString KateScriptDocument::line(int line) -{ - return m_document->line(line); -} - -QString KateScriptDocument::wordAt(int line, int column) -{ - return m_document->getWord(KTextEditor::Cursor(line, column)); -} - -QString KateScriptDocument::wordAt(const KTextEditor::Cursor& cursor) -{ - return m_document->getWord(cursor); -} - -QString KateScriptDocument::charAt(int line, int column) -{ - return charAt(KTextEditor::Cursor(line, column)); -} - -QString KateScriptDocument::charAt(const KTextEditor::Cursor& cursor) -{ - const QChar c = m_document->character(cursor); - return c.isNull() ? "" : QString(c); -} - -QString KateScriptDocument::firstChar(int line) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if(!textLine) return ""; - // check for isNull(), as the returned character then would be "\0" - const QChar c = textLine->at(textLine->firstChar()); - return c.isNull() ? "" : QString(c); -} - -QString KateScriptDocument::lastChar(int line) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if(!textLine) return ""; - // check for isNull(), as the returned character then would be "\0" - const QChar c = textLine->at(textLine->lastChar()); - return c.isNull() ? "" : QString(c); -} - -bool KateScriptDocument::isSpace(int line, int column) -{ - return isSpace(KTextEditor::Cursor(line, column)); -} - -bool KateScriptDocument::isSpace(const KTextEditor::Cursor& cursor) -{ - return m_document->character(cursor).isSpace(); -} - -bool KateScriptDocument::matchesAt(int line, int column, const QString &s) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - return textLine ? textLine->matchesAt(column, s) : false; -} - -bool KateScriptDocument::matchesAt(const KTextEditor::Cursor& cursor, const QString &s) -{ - return matchesAt(cursor.line(), cursor.column(), s); -} - -bool KateScriptDocument::setText(const QString &s) -{ - return m_document->setText(s); -} - -bool KateScriptDocument::clear() -{ - return m_document->clear(); -} - -bool KateScriptDocument::truncate(int line, int column) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if (!textLine || textLine->text().size() < column) - return false; - - KTextEditor::Cursor from (line, column), to (line, textLine->text().size() - column); - return removeText(KTextEditor::Range(from, to)); -} - -bool KateScriptDocument::truncate(const KTextEditor::Cursor& cursor) -{ - return truncate(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::insertText(int line, int column, const QString &s) -{ - return insertText(KTextEditor::Cursor(line, column), s); -} - -bool KateScriptDocument::insertText(const KTextEditor::Cursor& cursor, const QString &s) -{ - return m_document->insertText(cursor, s); -} - -bool KateScriptDocument::removeText(int fromLine, int fromColumn, int toLine, int toColumn) -{ - return removeText(KTextEditor::Range(fromLine, fromColumn, toLine, toColumn)); -} - -bool KateScriptDocument::removeText(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to) -{ - return removeText(KTextEditor::Range(from, to)); -} - -bool KateScriptDocument::removeText(const KTextEditor::Range& range) -{ - return m_document->removeText(range); -} - -bool KateScriptDocument::insertLine(int line, const QString &s) -{ - return m_document->insertLine (line, s); -} - -bool KateScriptDocument::removeLine(int line) -{ - return m_document->removeLine (line); -} - -void KateScriptDocument::joinLines(int startLine, int endLine) -{ - m_document->joinLines (startLine, endLine); -} - -int KateScriptDocument::lines() -{ - return m_document->lines(); -} - -int KateScriptDocument::length() -{ - return m_document->totalCharacters(); -} - -int KateScriptDocument::lineLength(int line) -{ - return m_document->lineLength(line); -} - -void KateScriptDocument::editBegin() -{ - m_document->editBegin(); -} - -void KateScriptDocument::editEnd() -{ - m_document->editEnd (); -} - -int KateScriptDocument::firstColumn(int line) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - return textLine ? textLine->firstChar() : -1; -} - -int KateScriptDocument::lastColumn(int line) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - return textLine ? textLine->lastChar() : -1; -} - -int KateScriptDocument::prevNonSpaceColumn(int line, int column) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if(!textLine) return -1; - return textLine->previousNonSpaceChar(column); -} - -int KateScriptDocument::prevNonSpaceColumn(const KTextEditor::Cursor& cursor) -{ - return prevNonSpaceColumn(cursor.line(), cursor.column()); -} - -int KateScriptDocument::nextNonSpaceColumn(int line, int column) -{ - Kate::TextLine textLine = m_document->plainKateTextLine(line); - if(!textLine) return -1; - return textLine->nextNonSpaceChar(column); -} - -int KateScriptDocument::nextNonSpaceColumn(const KTextEditor::Cursor& cursor) -{ - return nextNonSpaceColumn(cursor.line(), cursor.column()); -} - -int KateScriptDocument::prevNonEmptyLine(int line) -{ - const int startLine = line; - for (int currentLine = startLine; currentLine >= 0; --currentLine) { - Kate::TextLine textLine = m_document->plainKateTextLine(currentLine); - if(!textLine) - return -1; - if(textLine->firstChar() != -1) - return currentLine; - } - return -1; -} - -int KateScriptDocument::nextNonEmptyLine(int line) -{ - const int startLine = line; - for (int currentLine = startLine; currentLine < m_document->lines(); ++currentLine) { - Kate::TextLine textLine = m_document->plainKateTextLine(currentLine); - if(!textLine) - return -1; - if(textLine->firstChar() != -1) - return currentLine; - } - return -1; -} - -bool KateScriptDocument::isInWord(const QString &character, int attribute) -{ - return m_document->highlight()->isInWord(character.at(0), attribute); -} - -bool KateScriptDocument::canBreakAt(const QString &character, int attribute) -{ - return m_document->highlight()->canBreakAt(character.at(0), attribute); -} - -bool KateScriptDocument::canComment(int startAttribute, int endAttribute) -{ - return m_document->highlight()->canComment(startAttribute, endAttribute); -} - -QString KateScriptDocument::commentMarker(int attribute) -{ - return m_document->highlight()->getCommentSingleLineStart(attribute); -} - -QString KateScriptDocument::commentStart(int attribute) -{ - return m_document->highlight()->getCommentStart(attribute); -} - -QString KateScriptDocument::commentEnd(int attribute) -{ - return m_document->highlight()->getCommentEnd(attribute); -} - -KTextEditor::Range KateScriptDocument::documentRange() -{ - return m_document->documentRange(); -} - -KTextEditor::Cursor KateScriptDocument::documentEnd() -{ - return m_document->documentEnd(); -} - -int KateScriptDocument::attribute(int line, int column) -{ - Kate::TextLine textLine = m_document->kateTextLine(line); - if(!textLine) return 0; - return textLine->attribute(column); -} - -int KateScriptDocument::attribute(const KTextEditor::Cursor& cursor) -{ - return attribute(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isAttribute(int line, int column, int attr) -{ - return attr == attribute(line, column); -} - -bool KateScriptDocument::isAttribute(const KTextEditor::Cursor& cursor, int attr) -{ - return isAttribute(cursor.line(), cursor.column(), attr); -} - -QString KateScriptDocument::attributeName(int line, int column) -{ - QList attributes = m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema()); - KTextEditor::Attribute::Ptr a = attributes[document()->plainKateTextLine(line)->attribute(column)]; - return a->property(KateExtendedAttribute::AttributeName).toString(); -} - -QString KateScriptDocument::attributeName(const KTextEditor::Cursor& cursor) -{ - return attributeName(cursor.line(), cursor.column()); -} - -bool KateScriptDocument::isAttributeName(int line, int column, const QString &name) -{ - return name == attributeName(line, column); -} - -bool KateScriptDocument::isAttributeName(const KTextEditor::Cursor& cursor, const QString &name) -{ - return isAttributeName(cursor.line(), cursor.column(), name); -} - -QString KateScriptDocument::variable(const QString &s) -{ - return m_document->variable(s); -} - -//END - -bool KateScriptDocument::_isCode(int defaultStyle) -{ - return (defaultStyle != KTextEditor::HighlightInterface::dsComment - && defaultStyle != KTextEditor::HighlightInterface::dsString - && defaultStyle != KTextEditor::HighlightInterface::dsRegionMarker - && defaultStyle != KTextEditor::HighlightInterface::dsChar - && defaultStyle != KTextEditor::HighlightInterface::dsOthers); -} - -void KateScriptDocument::indent(KTextEditor::Range range, int change) -{ - m_document->indent(range, change); -} - -void KateScriptDocument::align(const KTextEditor::Range& range) -{ - if (m_document->activeKateView()) { - m_document->align(m_document->activeKateView(), range); - } -} - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/script/katescriptdocument.h b/part/script/katescriptdocument.h deleted file mode 100644 index 90c8901..0000000 --- a/part/script/katescriptdocument.h +++ /dev/null @@ -1,187 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#ifndef KATE_SCRIPT_DOCUMENT_H -#define KATE_SCRIPT_DOCUMENT_H - -#include -#include -#include - -#include "katepartprivate_export.h" - -#include - -#include -#include - -class KateDocument; - -/** - * Thinish wrapping around KateDocument, exposing the methods we want exposed - * and adding some helper methods. - * - * We inherit from QScriptable to have more thight access to the scripting - * engine. - * - * setDocument _must_ be called before using any other method. This is not checked - * for the sake of speed. - */ -class KATEPART_TESTS_EXPORT KateScriptDocument : public QObject, protected QScriptable -{ - Q_OBJECT - // Note: we have no Q_PROPERTIES due to consistency: everything is a function. - - public: - KateScriptDocument(QObject *parent=0); - void setDocument(KateDocument *document); - KateDocument *document(); - - //BEGIN - Q_INVOKABLE QString fileName(); - Q_INVOKABLE QString url(); - Q_INVOKABLE QString mimeType(); - Q_INVOKABLE QString encoding(); - Q_INVOKABLE QString highlightingMode(); - Q_INVOKABLE QStringList embeddedHighlightingModes(); - Q_INVOKABLE QString highlightingModeAt(const KTextEditor::Cursor& pos); - Q_INVOKABLE bool isModified(); - Q_INVOKABLE QString text(); - Q_INVOKABLE QString text(int fromLine, int fromColumn, int toLine, int toColumn); - Q_INVOKABLE QString text(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); - Q_INVOKABLE QString text(const KTextEditor::Range& range); - Q_INVOKABLE QString line(int line); - Q_INVOKABLE QString wordAt(int line, int column); - Q_INVOKABLE QString wordAt(const KTextEditor::Cursor& cursor); - Q_INVOKABLE QString charAt(int line, int column); - Q_INVOKABLE QString charAt(const KTextEditor::Cursor& cursor); - Q_INVOKABLE QString firstChar(int line); - Q_INVOKABLE QString lastChar(int line); - Q_INVOKABLE bool isSpace(int line, int column); - Q_INVOKABLE bool isSpace(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool matchesAt(int line, int column, const QString &s); - Q_INVOKABLE bool matchesAt(const KTextEditor::Cursor& cursor, const QString &s); - Q_INVOKABLE bool setText(const QString &s); - Q_INVOKABLE bool clear(); - Q_INVOKABLE bool truncate(int line, int column); - Q_INVOKABLE bool truncate(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool insertText(int line, int column, const QString &s); - Q_INVOKABLE bool insertText(const KTextEditor::Cursor& cursor, const QString &s); - Q_INVOKABLE bool removeText(int fromLine, int fromColumn, int toLine, int toColumn); - Q_INVOKABLE bool removeText(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); - Q_INVOKABLE bool removeText(const KTextEditor::Range& range); - Q_INVOKABLE bool insertLine(int line, const QString &s); - Q_INVOKABLE bool removeLine(int line); - Q_INVOKABLE void joinLines(int startLine, int endLine); - Q_INVOKABLE int lines(); - Q_INVOKABLE int length(); - Q_INVOKABLE int lineLength(int line); - Q_INVOKABLE void editBegin(); - Q_INVOKABLE void editEnd(); - Q_INVOKABLE int firstColumn(int line); - Q_INVOKABLE int lastColumn(int line); - Q_INVOKABLE int prevNonSpaceColumn(int line, int column); - Q_INVOKABLE int prevNonSpaceColumn(const KTextEditor::Cursor& cursor); - Q_INVOKABLE int nextNonSpaceColumn(int line, int column); - Q_INVOKABLE int nextNonSpaceColumn(const KTextEditor::Cursor& cursor); - Q_INVOKABLE int prevNonEmptyLine(int line); - Q_INVOKABLE int nextNonEmptyLine(int line); - Q_INVOKABLE bool isInWord(const QString &character, int attribute); - Q_INVOKABLE bool canBreakAt(const QString &character, int attribute); - Q_INVOKABLE bool canComment(int startAttribute, int endAttribute); - Q_INVOKABLE QString commentMarker(int attribute); - Q_INVOKABLE QString commentStart(int attribute); - Q_INVOKABLE QString commentEnd(int attribute); - - Q_INVOKABLE KTextEditor::Range documentRange(); - Q_INVOKABLE KTextEditor::Cursor documentEnd(); - - /** - * Get the syntax highlighting attribute at a given position in the document. - */ - Q_INVOKABLE int attribute(int line, int column); - Q_INVOKABLE int attribute(const KTextEditor::Cursor& cursor); - - /** - * Return true if the highlight attribute equals @p attr. - */ - Q_INVOKABLE bool isAttribute(int line, int column, int attr); - Q_INVOKABLE bool isAttribute(const KTextEditor::Cursor& cursor, int attr); - - /** - * Get the name of the syntax highlighting attribute at the given position. - */ - Q_INVOKABLE QString attributeName(int line, int column); - Q_INVOKABLE QString attributeName(const KTextEditor::Cursor& cursor); - - /** - * Return true is the name of the syntax attribute equals @p name. - */ - Q_INVOKABLE bool isAttributeName(int line, int column, const QString &name); - Q_INVOKABLE bool isAttributeName(const KTextEditor::Cursor& cursor, const QString &name); - - Q_INVOKABLE QString variable(const QString &s); - //END - - Q_INVOKABLE int firstVirtualColumn(int line); - Q_INVOKABLE int lastVirtualColumn(int line); - Q_INVOKABLE int toVirtualColumn(int line, int column); - Q_INVOKABLE int toVirtualColumn(const KTextEditor::Cursor& cursor); - Q_INVOKABLE KTextEditor::Cursor toVirtualCursor(const KTextEditor::Cursor& cursor); - Q_INVOKABLE int fromVirtualColumn(int line, int virtualColumn); - Q_INVOKABLE int fromVirtualColumn(const KTextEditor::Cursor& virtualCursor); - Q_INVOKABLE KTextEditor::Cursor fromVirtualCursor(const KTextEditor::Cursor& virtualCursor); - - Q_INVOKABLE KTextEditor::Cursor anchor(int line, int column, QChar character); - Q_INVOKABLE KTextEditor::Cursor anchor(const KTextEditor::Cursor& cursor, QChar character); - Q_INVOKABLE KTextEditor::Cursor rfind(int line, int column, const QString& text, int attribute = -1); - Q_INVOKABLE KTextEditor::Cursor rfind(const KTextEditor::Cursor& cursor, const QString& text, int attribute = -1); - - Q_INVOKABLE int defStyleNum(int line, int column); - Q_INVOKABLE int defStyleNum(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isCode(int line, int column); - Q_INVOKABLE bool isCode(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isComment(int line, int column); - Q_INVOKABLE bool isComment(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isString(int line, int column); - Q_INVOKABLE bool isString(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isRegionMarker(int line, int column); - Q_INVOKABLE bool isRegionMarker(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isChar(int line, int column); - Q_INVOKABLE bool isChar(const KTextEditor::Cursor& cursor); - Q_INVOKABLE bool isOthers(int line, int column); - Q_INVOKABLE bool isOthers(const KTextEditor::Cursor& cursor); - - - Q_INVOKABLE bool startsWith (int line, const QString &pattern, bool skipWhiteSpaces); - Q_INVOKABLE bool endsWith (int line, const QString &pattern, bool skipWhiteSpaces); - - Q_INVOKABLE void indent(KTextEditor::Range range, int change); - Q_INVOKABLE void align(const KTextEditor::Range& range); - - private: - bool _isCode(int defaultStyle); - - KateDocument *m_document; -}; - - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescripthelpers.cpp b/part/script/katescripthelpers.cpp deleted file mode 100644 index b82c185..0000000 --- a/part/script/katescripthelpers.cpp +++ /dev/null @@ -1,199 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2010 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#include "katescript.h" -#include "katescriptdocument.h" -#include "katescriptview.h" -#include "kateview.h" -#include "katedocument.h" - -#include - -#include -#include -#include - -#include -#include -#include - -namespace Kate { -namespace Script { - -QScriptValue debug(QScriptContext *context, QScriptEngine *engine) -{ - QStringList message; - for(int i = 0; i < context->argumentCount(); ++i) { - message << context->argument(i).toString(); - } - // debug in blue to distance from other debug output if necessary - std::cerr << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n"; - return engine->nullValue(); -} - -//BEGIN code adapted from kdelibs/kross/modules/translation.cpp -/// helper function to do the substitution from QtScript > QVariant > real values -KLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 ) -{ - KLocalizedString ls = kls; - int cnt = qMin( arguments.count(), max ); // QString supports max 99 - for ( int i = 0; i < cnt; ++i ) { - QVariant arg = arguments[i]; - switch ( arg.type() ) { - case QVariant::Int: ls = ls.subs(arg.toInt()); break; - case QVariant::UInt: ls = ls.subs(arg.toUInt()); break; - case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break; - case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break; - case QVariant::Double: ls = ls.subs(arg.toDouble()); break; - default: ls = ls.subs(arg.toString()); break; - } - } - return ls; -} - -/// i18n("text", arguments [optional]) -QScriptValue i18n( QScriptContext *context, QScriptEngine *engine ) -{ - Q_UNUSED(engine) - QString text; - QVariantList args; - const int argCount = context->argumentCount(); - - if (argCount == 0) { - kWarning(13050) << "wrong usage of i18n:" << context->backtrace().join("\n\t"); - } - - if (argCount > 0) { - text = context->argument(0).toString(); - } - - for (int i = 1; i < argCount; ++i) { - args << context->argument(i).toVariant(); - } - - KLocalizedString ls = ki18n(text.toUtf8()); - return substituteArguments( ls, args ).toString(); -} - -/// i18nc("context", "text", arguments [optional]) -QScriptValue i18nc( QScriptContext *context, QScriptEngine *engine ) -{ - Q_UNUSED(engine) - QString text; - QString textContext; - QVariantList args; - const int argCount = context->argumentCount(); - - if (argCount < 2) { - kWarning(13050) << "wrong usage of i18nc:" << context->backtrace().join("\n\t"); - } - - if (argCount > 0) { - textContext = context->argument(0).toString(); - } - - if (argCount > 1) { - text = context->argument(1).toString(); - } - - for (int i = 2; i < argCount; ++i) { - args << context->argument(i).toVariant(); - } - - KLocalizedString ls = ki18nc(textContext.toUtf8(), text.toUtf8()); - return substituteArguments( ls, args ).toString(); -} - -/// i18np("singular", "plural", number, arguments [optional]) -QScriptValue i18np( QScriptContext *context, QScriptEngine *engine ) -{ - Q_UNUSED(engine) - QString trSingular; - QString trPlural; - int number; - QVariantList args; - const int argCount = context->argumentCount(); - - if (argCount < 3) { - kWarning(13050) << "wrong usage of i18np:" << context->backtrace().join("\n\t"); - } - - if (argCount > 0) { - trSingular = context->argument(0).toString(); - } - - if (argCount > 1) { - trPlural = context->argument(1).toString(); - } - - if (argCount > 2) { - number = context->argument(2).toInt32(); - } - - for (int i = 3; i < argCount; ++i) { - args << context->argument(i).toVariant(); - } - - KLocalizedString ls = ki18np(trSingular.toUtf8(), trPlural.toUtf8()).subs(number); - return substituteArguments( ls, args, 98 ).toString(); -} - -/// i18ncp("context", "singular", "plural", number, arguments [optional]) -QScriptValue i18ncp( QScriptContext *context, QScriptEngine *engine ) -{ - Q_UNUSED(engine) - QString trContext; - QString trSingular; - QString trPlural; - int number; - QVariantList args; - const int argCount = context->argumentCount(); - - if (argCount < 4) { - kWarning(13050) << "wrong usage of i18ncp:" << context->backtrace().join("\n\t"); - } - - if (argCount > 0) { - trContext = context->argument(0).toString(); - } - - if (argCount > 1) { - trSingular = context->argument(1).toString(); - } - - if (argCount > 2) { - trPlural = context->argument(2).toString(); - } - - if (argCount > 3) { - number = context->argument(3).toInt32(); - } - - for (int i = 4; i < argCount; ++i) { - args << context->argument(i).toVariant(); - } - - KLocalizedString ls = ki18ncp(trContext.toUtf8(), trSingular.toUtf8(), trPlural.toUtf8()).subs( number ); - return substituteArguments( ls, args, 98 ).toString(); -} -//END code adapted from kdelibs/kross/modules/translation.cpp - -} -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescripthelpers.h b/part/script/katescripthelpers.h deleted file mode 100644 index c8470ac..0000000 --- a/part/script/katescripthelpers.h +++ /dev/null @@ -1,40 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2010 Dominik Haumann -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#ifndef KATE_SCRIPTHELPERS_H -#define KATE_SCRIPTHELPERS_H - -#include - -class QScriptEngine; -class QScriptContext; - -namespace Kate { - /** Top-level script functions */ - namespace Script { - QScriptValue debug(QScriptContext *context, QScriptEngine *engine); - QScriptValue i18n(QScriptContext *context, QScriptEngine *engine); - QScriptValue i18nc(QScriptContext *context, QScriptEngine *engine); - QScriptValue i18np(QScriptContext *context, QScriptEngine *engine); - QScriptValue i18ncp(QScriptContext *context, QScriptEngine *engine); - } -} - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptmanager.cpp b/part/script/katescriptmanager.cpp deleted file mode 100644 index 857b369..0000000 --- a/part/script/katescriptmanager.cpp +++ /dev/null @@ -1,410 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2005 Christoph Cullmann -// Copyright (C) 2005 Joseph Wenninger -// Copyright (C) 2006, 2009 Dominik Haumann -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2010 Joseph Wenninger -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License version 2 as published by the Free Software Foundation. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#include "katescriptmanager.h" - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "kateglobal.h" -#include "katecmd.h" - -KateScriptManager::KateScriptManager() : QObject(), KTextEditor::Command() -{ - KateCmd::self()->registerCommand (this); - - // false = force (ignore cache) - collect("katepartscriptrc", "katepart/script/*.js", false); -} - -KateScriptManager::~KateScriptManager() -{ - KateCmd::self()->unregisterCommand (this); - qDeleteAll(m_indentationScripts); - qDeleteAll(m_commandLineScripts); -} - -KateIndentScript *KateScriptManager::indenter(const QString &language) -{ - KateIndentScript *highestPriorityIndenter = 0; - foreach(KateIndentScript *indenter, m_languageToIndenters.value(language.toLower())) { - // don't overwrite if there is already a result with a higher priority - if(highestPriorityIndenter && indenter->indentHeader().priority() < highestPriorityIndenter->indentHeader().priority()) { -#ifdef DEBUG_SCRIPTMANAGER - kDebug(13050) << "Not overwriting indenter for" - << language << "as the priority isn't big enough (" << - indenter->indentHeader().priority() << '<' - << highestPriorityIndenter->indentHeader().priority() << ')'; -#endif - } - else { - highestPriorityIndenter = indenter; - } - } - -#ifdef DEBUG_SCRIPTMANAGER - if(highestPriorityIndenter) { - kDebug(13050) << "Found indenter" << highestPriorityIndenter->url() << "for" << language; - } else { - kDebug(13050) << "No indenter for" << language; - } -#endif - - return highestPriorityIndenter; -} - -void KateScriptManager::collect(const QString& resourceFile, - const QString& directory, - bool force) -{ - KConfig cfgFile(resourceFile, KConfig::NoGlobals); - - force = false; - { - KConfigGroup config(&cfgFile, "General"); - // If KatePart version does not match, better force a true reload - if(KateGlobal::katePartVersion() != config.readEntry("kate-version", QString("0.0"))) { - config.writeEntry("kate-version", KateGlobal::katePartVersion()); - force = true; - } - } - // get a list of all .js files - const QStringList list = KGlobal::dirs()->findAllResources("data", directory, KStandardDirs::NoDuplicates); - // clear out the old scripts and reserve enough space - qDeleteAll(m_indentationScripts); - qDeleteAll(m_commandLineScripts); - m_indentationScripts.clear(); - m_commandLineScripts.clear(); - - m_languageToIndenters.clear(); - m_indentationScriptMap.clear(); - - // iterate through the files and read info out of cache or file - foreach(const QString &fileName, list) { - // get abs filename.... - QFileInfo fi(fileName); - const QString absPath = fi.absoluteFilePath(); - const QString baseName = fi.baseName (); - - // each file has a group - const QString group = "Cache "+ fileName; - KConfigGroup config(&cfgFile, group); - - // stat the file to get the last-modified-time - KDE_struct_stat sbuf; - memset(&sbuf, 0, sizeof(sbuf)); - KDE::stat(fileName, &sbuf); - - // check whether file is already cached - bool useCache = false; - if(!force && cfgFile.hasGroup(group)) { - useCache = (sbuf.st_mtime == config.readEntry("last-modified", 0)); - } - - // read key/value pairs from the cached file if possible - // otherwise, parse it and then save the needed information to the cache. - QHash pairs; - if(useCache) { - const QMap entries = config.entryMap(); - for(QMap::ConstIterator entry = entries.constBegin(); - entry != entries.constEnd(); - ++entry) - pairs[entry.key()] = entry.value(); - } - else if(parseMetaInformation(fileName, pairs)) { - config.writeEntry("last-modified", int(sbuf.st_mtime)); - // iterate keys and save cache - for(QHash::ConstIterator item = pairs.constBegin(); - item != pairs.constEnd(); - ++item) - config.writeEntry(item.key(), item.value()); - } - else { - // parseMetaInformation will have informed the user of the problem - continue; - } - // make sure we have the necessary meta data items we need for proper execution - KateScriptHeader generalHeader; - QString type = pairs.take("type"); - if(type == "indentation") { - generalHeader.setScriptType(Kate::IndentationScript); - } else if (type == "commands") { - generalHeader.setScriptType(Kate::CommandLineScript); - } else { - kDebug(13050) << "Script value error: No type specified in script meta data: " - << qPrintable(fileName) << '\n'; - continue; - } - - generalHeader.setLicense(pairs.take("license")); - generalHeader.setAuthor(pairs.take("author")); - generalHeader.setRevision(pairs.take("revision").toInt()); - generalHeader.setKateVersion(pairs.take("kate-version")); - generalHeader.setCatalog(pairs.take("i18n-catalog")); - - // now, cast accordingly based on type - switch(generalHeader.scriptType()) { - case Kate::IndentationScript: { - KateIndentScriptHeader indentHeader; - indentHeader.setName(pairs.take("name")); - indentHeader.setBaseName(baseName); - if (indentHeader.name().isNull()) { - kDebug( 13050 ) << "Script value error: No name specified in script meta data: " - << qPrintable(fileName) << '\n' << "-> skipping indenter" << '\n'; - continue; - } - - // required style? - indentHeader.setRequiredStyle(pairs.take("required-syntax-style")); - // which languages does this support? - QString indentLanguages = pairs.take("indent-languages"); - if(!indentLanguages.isNull()) { - indentHeader.setIndentLanguages(indentLanguages.split(',')); - } - else { - indentHeader.setIndentLanguages(QStringList() << indentHeader.name()); - -#ifdef DEBUG_SCRIPTMANAGER - kDebug( 13050 ) << "Script value warning: No indent-languages specified for indent " - << "script " << qPrintable(fileName) << ". Using the name (" - << qPrintable(indentHeader.name()) << ")\n"; -#endif - } - // priority? - bool convertedToInt; - int priority = pairs.take("priority").toInt(&convertedToInt); - -#ifdef DEBUG_SCRIPTMANAGER - if(!convertedToInt) { - kDebug( 13050 ) << "Script value warning: Unexpected or no priority value " - << "in: " << qPrintable(fileName) << ". Setting priority to 0\n"; - } -#endif - - indentHeader.setPriority(convertedToInt ? priority : 0); - KateIndentScript *script = new KateIndentScript(fileName, indentHeader); - script->setGeneralHeader(generalHeader); - foreach(const QString &language, indentHeader.indentLanguages()) { - m_languageToIndenters[language.toLower()].push_back(script); - } - - m_indentationScriptMap.insert(indentHeader.baseName(), script); - m_indentationScripts.append(script); - break; - } - case Kate::CommandLineScript: { - KateCommandLineScriptHeader commandHeader; - commandHeader.setFunctions(pairs.take("functions").split(QRegExp("\\s*,\\s*"), QString::SkipEmptyParts)); - if (commandHeader.functions().isEmpty()) { - kDebug(13050) << "Script value error: No functions specified in script meta data: " - << qPrintable(fileName) << '\n' << "-> skipping script" << '\n'; - continue; - } - KateCommandLineScript* script = new KateCommandLineScript(fileName, commandHeader); - script->setGeneralHeader(generalHeader); - m_commandLineScripts.push_back(script); - break; - } - case Kate::UnknownScript: - default: - kDebug( 13050 ) << "Script value warning: Unknown type ('" << qPrintable(type) << "'): " - << qPrintable(fileName) << '\n'; - } - } - - - -#ifdef DEBUG_SCRIPTMANAGER - // XX Test - if(indenter("Python")) { - kDebug( 13050 ) << "Python: " << indenter("Python")->global("triggerCharacters").isValid() << "\n"; - kDebug( 13050 ) << "Python: " << indenter("Python")->function("triggerCharacters").isValid() << "\n"; - kDebug( 13050 ) << "Python: " << indenter("Python")->global("blafldsjfklas").isValid() << "\n"; - kDebug( 13050 ) << "Python: " << indenter("Python")->function("indent").isValid() << "\n"; - } - if(indenter("C")) - kDebug( 13050 ) << "C: " << qPrintable(indenter("C")->url()) << "\n"; - if(indenter("lisp")) - kDebug( 13050 ) << "LISP: " << qPrintable(indenter("Lisp")->url()) << "\n"; -#endif - - cfgFile.sync(); -} - - -bool KateScriptManager::parseMetaInformation(const QString& url, - QHash &pairs) -{ - // a valid script file -must- have the following format: - // The first line must contain the string 'kate-script'. - // All following lines have to have the format 'key : value'. So the value - // is separated by a colon. Leading non-letter characters are ignored, that - // include C and C++ comments for example. - // Parsing the header stops at the first line with no ':'. - - QFile file(url); - if(!file.open(QIODevice::ReadOnly)) { - kDebug( 13050 ) << "Script parse error: Cannot open file " << qPrintable(url) << '\n'; - return false; - } - - kDebug(13050) << "Update script: " << url; - QTextStream ts(&file); - ts.setCodec("UTF-8"); - if(!ts.readLine().contains("kate-script")) { - kDebug( 13050 ) << "Script parse error: No header found in " << qPrintable(url) << '\n'; - file.close(); - return false; - } - - QString line; - while(!(line = ts.readLine()).isNull()) { - int colon = line.indexOf(':'); - if(colon <= 0) - break; // no colon -> end of header found - - // if -1 then 0. if >= 0, move after star. - int start = 0; // start points to first letter. idea: skip '*' and '//' - while(start < line.length() && !line.at(start).isLetter()) - ++start; - - QString key = line.mid(start, colon - start).trimmed(); - QString value = line.right(line.length() - (colon + 1)).trimmed(); - pairs[key] = value; - -#ifdef DEBUG_SCRIPTMANAGER - kDebug(13050) << "KateScriptManager::parseMetaInformation: found pair: " - << "(" << key << " | " << value << ")"; -#endif - } - - file.close(); - return true; -} - -void KateScriptManager::reload() -{ - KateScript::reloadScriptingApi(); - collect("katepartscriptrc", "katepart/script/*.js", true); - emit reloaded(); -} - -/// Kate::Command stuff - -bool KateScriptManager::exec(KTextEditor::View *view, const QString &_cmd, QString &errorMsg) -{ - QStringList args(_cmd.split(QRegExp("\\s+"), QString::SkipEmptyParts)); - QString cmd(args.first()); - args.removeFirst(); - - if(!view) { - errorMsg = i18n("Could not access view"); - return false; - } - - if (cmd == "reload-scripts") { - reload(); - return true; - } else { - errorMsg = i18n("Command not found: %1", cmd); - return false; - } -} - -bool KateScriptManager::help(KTextEditor::View *view, const QString &cmd, QString &msg) -{ - Q_UNUSED(view) - - if (cmd == "reload-scripts") { - msg = i18n("Reload all JavaScript files (indenters, command line scripts, etc)."); - return true; - } else { - msg = i18n("Command not found: %1", cmd); - return false; - } -} - -const QStringList &KateScriptManager::cmds() -{ - static QStringList l; - - l.clear(); - l << "reload-scripts"; - - return l; -} - - - -KTextEditor::TemplateScript* KateScriptManager::registerTemplateScript (QObject* owner, const QString& script) -{ - KateTemplateScript* kts = new KateTemplateScript(script); - m_templateScripts.append(kts); - - connect(owner, SIGNAL(destroyed(QObject*)), - this, SLOT(slotTemplateScriptOwnerDestroyed(QObject*))); - m_ownerScript.insertMulti(owner, kts); - return kts; -} - -void KateScriptManager::unregisterTemplateScript(KTextEditor::TemplateScript* templateScript) -{ - int index = m_templateScripts.indexOf(templateScript); - if (index != -1) { - QObject* k = m_ownerScript.key(templateScript); - m_ownerScript.remove(k, templateScript); - m_templateScripts.removeAt(index); - delete templateScript; - } -} - -void KateScriptManager::slotTemplateScriptOwnerDestroyed(QObject* owner) -{ - while (m_ownerScript.contains(owner)) { - KTextEditor::TemplateScript* templateScript = m_ownerScript.take(owner); - kDebug() << "Destroying template script" << templateScript; - m_templateScripts.removeAll(templateScript); - delete templateScript; - } -} - -KateTemplateScript* KateScriptManager::templateScript(KTextEditor::TemplateScript* templateScript) -{ - if (m_templateScripts.contains(templateScript)) { - return static_cast(templateScript); - } - - return 0; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptmanager.h b/part/script/katescriptmanager.h deleted file mode 100644 index 741b428..0000000 --- a/part/script/katescriptmanager.h +++ /dev/null @@ -1,162 +0,0 @@ -// This file is part of the KDE libraries -// Copyright (C) 2008 Paul Giannaros -// Copyright (C) 2009 Dominik Haumann -// Copyright (C) 2010 Joseph Wenninger -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Library General Public -// License as published by the Free Software Foundation; either -// version 2 of the License, or (at your option) version 3. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Library General Public License for more details. -// -// You should have received a copy of the GNU Library General Public License -// along with this library; see the file COPYING.LIB. If not, write to -// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -// Boston, MA 02110-1301, USA. - -#ifndef KATE_SCRIPT_MANAGER_H -#define KATE_SCRIPT_MANAGER_H - -#include -#include - -#include - -#include - -#include "katescript.h" -#include "kateindentscript.h" -#include "katecommandlinescript.h" -#include "katetemplatescript.h" - -class QString; - - -/** - * Manage the scripts on disks -- find them and query them. - * Provides access to loaded scripts too. - */ -class KateScriptManager : public QObject, public KTextEditor::Command -{ - Q_OBJECT - - public: - KateScriptManager(); - virtual ~KateScriptManager(); - - /** Get all scripts available in the command line */ - const QVector &commandLineScripts() { return m_commandLineScripts; } - - /** - * Get an indentation script for the given language -- if there is more than - * one result, this will return the script with the highest priority. If - * both have the same priority, an arbitrary script will be returned. - * If no scripts are found, 0 is returned. - */ - KateIndentScript *indenter(const QString &language); - - // - // KTextEditor::Command - // - public: - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @return success - */ - bool exec(KTextEditor::View *view, const QString &cmd, QString &errorMsg); - - /** - * get help for a command - * @param view view to use - * @param cmd cmd name - * @param msg help message - * @return help available or not - */ - bool help(KTextEditor::View *view, const QString &cmd, QString &msg); - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds(); - - // - // Helper methods - // - public: - /** - * Find all of the scripts matching the wildcard \p directory. The resource file - * with the name \p resourceFile is used for caching. If \p force is true, then the - * cache will not be used. This populates the internal lists of scripts. - * This is automatically called by init so you shouldn't call it yourself unless - * you want to refresh the collected list. - */ - void collect(const QString& resourceFile, - const QString& directory, - bool force = false); - - /** - * Extract the meta data from the script at \p url and put in \p pairs. - * Returns true if metadata was found and extracted successfuly, false otherwise. - */ - static bool parseMetaInformation(const QString& url, QHash &pairs); - - public: - KateIndentScript *indentationScript (const QString &scriptname) { return m_indentationScriptMap.value(scriptname); } - - int indentationScriptCount () { return m_indentationScripts.size(); } - KateIndentScript *indentationScriptByIndex (int index) { return m_indentationScripts[index]; } - - public: - /** explicitly reload all scripts */ - void reload(); - - Q_SIGNALS: - /** this signal is emitted when all scripts are _deleted_ and reloaded again. */ - void reloaded(); - - private: - /** List of all command line scripts */ - QVector m_commandLineScripts; - - /** list of all indentation scripts */ - QList m_indentationScripts; - - /** hash of all existing indenter scripts, hashes basename -> script */ - QHash m_indentationScriptMap; - - /** Map of language to indent scripts */ - QHash > m_languageToIndenters; - - - // - // Template handling - // - public: - /** managing of scripts for the template handler. The scripts are given as string content, not as files*/ - KTextEditor::TemplateScript* registerTemplateScript (QObject* owner, const QString& script); - /** unregister a given script */ - void unregisterTemplateScript(KTextEditor::TemplateScript* templateScript); - - KateTemplateScript* templateScript(KTextEditor::TemplateScript* templateScript); - - public Q_SLOTS: - void slotTemplateScriptOwnerDestroyed(QObject* owner); - - private: - QMultiMap m_ownerScript; - QList m_templateScripts; -}; - - - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katescriptview.cpp b/part/script/katescriptview.cpp deleted file mode 100644 index d1fb734..0000000 --- a/part/script/katescriptview.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/// This file is part of the KDE libraries -/// Copyright (C) 2008 Paul Giannaros -/// Copyright (C) 2008 Christoph Cullmann -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) version 3. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public License -/// along with this library; see the file COPYING.LIB. If not, write to -/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -/// Boston, MA 02110-1301, USA. - -#include "katescriptview.h" - -#include "katedocument.h" -#include "kateview.h" -#include "katerenderer.h" -#include "katehighlight.h" -#include "katescript.h" - -KateScriptView::KateScriptView(QObject *parent) - : QObject(parent), m_view(0) -{ -} - -void KateScriptView::setView (KateView *view) -{ - m_view = view; -} - -KateView *KateScriptView::view() -{ - return m_view; -} - -KTextEditor::Cursor KateScriptView::cursorPosition () -{ - return m_view->cursorPosition(); -} - -void KateScriptView::setCursorPosition(int line, int column) -{ - KTextEditor::Cursor c(line, column); - m_view->setCursorPosition(c); -} - -void KateScriptView::setCursorPosition (const KTextEditor::Cursor& cursor) -{ - m_view->setCursorPosition(cursor); -} - -KTextEditor::Cursor KateScriptView::virtualCursorPosition() -{ - return m_view->cursorPositionVirtual(); -} - -void KateScriptView::setVirtualCursorPosition(int line, int column) -{ - setVirtualCursorPosition(KTextEditor::Cursor(line, column)); -} - -void KateScriptView::setVirtualCursorPosition(const KTextEditor::Cursor& cursor) -{ - m_view->setCursorPositionVisual(cursor); -} - -QString KateScriptView::selectedText() -{ - return m_view->selectionText(); -} - -bool KateScriptView::hasSelection() -{ - return m_view->selection(); -} - -KTextEditor::Range KateScriptView::selection() -{ - return m_view->selectionRange(); -} - -void KateScriptView::setSelection(const KTextEditor::Range& range) -{ - m_view->setSelection(range); -} - -void KateScriptView::removeSelectedText() -{ - m_view->removeSelectedText(); -} - -void KateScriptView::selectAll() -{ - m_view->selectAll(); -} - -void KateScriptView::clearSelection() -{ - m_view->clearSelection(); -} - - - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/script/katescriptview.h b/part/script/katescriptview.h deleted file mode 100644 index 5bef8f1..0000000 --- a/part/script/katescriptview.h +++ /dev/null @@ -1,80 +0,0 @@ -/// This file is part of the KDE libraries -/// Copyright (C) 2008 Paul Giannaros -/// Copyright (C) 2008 Christoph Cullmann -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) version 3. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public License -/// along with this library; see the file COPYING.LIB. If not, write to -/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -/// Boston, MA 02110-1301, USA. - -#ifndef KATE_SCRIPT_VIEW_H -#define KATE_SCRIPT_VIEW_H - -#include -#include - -#include "katepartprivate_export.h" - -#include -#include - -class KateView; - -/** - * Thinish wrapping around KateView, exposing the methods we want exposed - * and adding some helper methods. - * - * We inherit from QScriptable to have more thight access to the scripting - * engine. - * - * setView _must_ be called before using any other method. This is not checked - * for the sake of speed. - */ -class KATEPART_TESTS_EXPORT KateScriptView : public QObject, protected QScriptable -{ - /// Properties are accessible with a nicer syntax from JavaScript - Q_OBJECT - - public: - KateScriptView (QObject *parent=0); - void setView (KateView *view); - KateView *view(); - - Q_INVOKABLE KTextEditor::Cursor cursorPosition (); - /** - * Set the cursor position in the view. - * @since 4.4 - */ - Q_INVOKABLE void setCursorPosition(int line, int column); - Q_INVOKABLE void setCursorPosition(const KTextEditor::Cursor& cursor); - - - Q_INVOKABLE KTextEditor::Cursor virtualCursorPosition(); - Q_INVOKABLE void setVirtualCursorPosition(int line, int column); - Q_INVOKABLE void setVirtualCursorPosition(const KTextEditor::Cursor& cursor); - - Q_INVOKABLE QString selectedText(); - Q_INVOKABLE bool hasSelection(); - Q_INVOKABLE KTextEditor::Range selection(); - Q_INVOKABLE void setSelection(const KTextEditor::Range& range); - Q_INVOKABLE void removeSelectedText(); - Q_INVOKABLE void selectAll(); - Q_INVOKABLE void clearSelection(); - - private: - KateView *m_view; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katetemplatescript.cpp b/part/script/katetemplatescript.cpp deleted file mode 100644 index 26ee556..0000000 --- a/part/script/katetemplatescript.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katetemplatescript.h" - -#include -#include - -#include "katedocument.h" -#include "kateview.h" - -KateTemplateScript::KateTemplateScript(const QString& script) - : KateScript(script,InputSCRIPT) {} - -KateTemplateScript::~KateTemplateScript(){} - -QString KateTemplateScript::invoke(KateView* view, const QString& functionName, const QString &srcText) { - - if(!setView(view)) - return QString(); - - clearExceptions(); - QScriptValue myFunction = function(functionName); - if(!myFunction.isValid()) { - return QString(); - } - - QScriptValueList arguments; - arguments << QScriptValue(m_engine, srcText); - - QScriptValue result = myFunction.call(QScriptValue(), arguments); - - if(m_engine->hasUncaughtException()) { - displayBacktrace(result, "Error while calling helper function"); - return QString(); - } - - - if (result.isNull()) { - return QString(); - } - - return result.toString(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/script/katetemplatescript.h b/part/script/katetemplatescript.h deleted file mode 100644 index 3823c81..0000000 --- a/part/script/katetemplatescript.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_TEMPLATE_SCRIPT_H -#define KATE_TEMPLATE_SCRIPT_H - -#include "katescript.h" -#include "kateview.h" -#include - - -class KateTemplateScript : public KateScript, public KTextEditor::TemplateScript -{ - public: - KateTemplateScript(const QString& script); - virtual ~KateTemplateScript(); - - QString invoke(KateView* view, const QString& functionName, const QString& srcText/*, ....*/); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/search/katematch.cpp b/part/search/katematch.cpp deleted file mode 100644 index 744b206..0000000 --- a/part/search/katematch.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - Copyright (C) 2007 Sebastian Pipping - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katematch.h" - -#include "kateregexpsearch.h" -#include "katedocument.h" -#include - -KateMatch::KateMatch(KateDocument *document, KTextEditor::Search::SearchOptions options) - : m_document(document) - , m_options(options) -{ - m_resultRanges.append(KTextEditor::Range::invalid()); -} - - -KTextEditor::Range KateMatch::searchText(const KTextEditor::Range &range, const QString &pattern) -{ - m_resultRanges = m_document->searchText(range, pattern, m_options); - - return m_resultRanges[0]; -} - - -KTextEditor::Range KateMatch::replace(const QString &replacement, bool blockMode, int replacementCounter) -{ - // Placeholders depending on search mode - const bool usePlaceholders = m_options.testFlag(KTextEditor::Search::Regex) || - m_options.testFlag(KTextEditor::Search::EscapeSequences); - - const QString finalReplacement = usePlaceholders ? buildReplacement(replacement, blockMode, replacementCounter) - : replacement; - - // Track replacement operation - KTextEditor::MovingRange *const afterReplace = m_document->newMovingRange(range(), KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - - blockMode = blockMode && !range().onSingleLine(); - m_document->replaceText(range(), finalReplacement, blockMode); - - const KTextEditor::Range result = *afterReplace; - delete afterReplace; - - return result; -} - - -KTextEditor::Range KateMatch::range() const -{ - if (m_resultRanges.size() > 0) - return m_resultRanges[0]; - - return KTextEditor::Range::invalid(); -} - - -bool KateMatch::isEmpty() const -{ - return range().isEmpty(); -} - - -bool KateMatch::isValid() const -{ - return range().isValid(); -} - - -QString KateMatch::buildReplacement(const QString &replacement, bool blockMode, int replacementCounter) const { - QStringList capturedTexts; - foreach (const KTextEditor::Range &captureRange, m_resultRanges) { - // Copy capture content - capturedTexts << m_document->text(captureRange, blockMode); - } - - return KateRegExpSearch::buildReplacement(replacement, capturedTexts, replacementCounter); -} - - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/search/katematch.h b/part/search/katematch.h deleted file mode 100644 index e3663c3..0000000 --- a/part/search/katematch.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_MATCH_H -#define KATE_MATCH_H - -#include - -class KateDocument; - - -class KateMatch -{ -public: - KateMatch(KateDocument *document, KTextEditor::Search::SearchOptions options); - KTextEditor::Range searchText(const KTextEditor::Range &range, const QString &pattern); - KTextEditor::Range replace(const QString &replacement, bool blockMode, int replacementCounter = 1); - bool isValid() const; - bool isEmpty() const; - KTextEditor::Range range() const; - -private: - /** - * Resolve references and escape sequences. - */ - QString buildReplacement(const QString &replacement, bool blockMode, int replacementCounter) const; - -private: - KateDocument *const m_document; - const KTextEditor::Search::SearchOptions m_options; - QVector m_resultRanges; -}; - -#endif // KATE_MATCH_H - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/search/kateplaintextsearch.cpp b/part/search/kateplaintextsearch.cpp deleted file mode 100644 index e1d24ed..0000000 --- a/part/search/kateplaintextsearch.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009-2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN includes -#include "kateplaintextsearch.h" - -#include "kateregexpsearch.h" - -#include - -#include -//END includes - - -//BEGIN d'tor, c'tor -// -// KateSearch Constructor -// -KatePlainTextSearch::KatePlainTextSearch ( KTextEditor::Document *document, Qt::CaseSensitivity caseSensitivity, bool wholeWords ) -: m_document (document) -, m_caseSensitivity (caseSensitivity) -, m_wholeWords (wholeWords) -{ -} - -// -// KateSearch Destructor -// -KatePlainTextSearch::~KatePlainTextSearch() -{ -} -//END - -KTextEditor::Range KatePlainTextSearch::search (const QString & text, const KTextEditor::Range & inputRange, bool backwards) -{ - // abuse regex for whole word plaintext search - if (m_wholeWords) - { - // escape dot and friends - const QString workPattern = "\\b" + QRegExp::escape(text) + "\\b"; - - return KateRegExpSearch(m_document, m_caseSensitivity).search(workPattern, inputRange, backwards)[0]; - } - - if (text.isEmpty() || !inputRange.isValid() || (inputRange.start() == inputRange.end())) - { - return KTextEditor::Range::invalid(); - } - - // split multi-line needle into single lines - const QStringList needleLines = text.split("\n"); - - if (needleLines.count() > 1) - { - // multi-line plaintext search (both forwards or backwards) - const int forMin = inputRange.start().line(); // first line in range - const int forMax = inputRange.end().line() + 1 - needleLines.count(); // last line in range - const int forInit = backwards ? forMax : forMin; - const int forInc = backwards ? -1 : +1; - - for (int j = forInit; (forMin <= j) && (j <= forMax); j += forInc) - { - // try to match all lines - const int startCol = m_document->lineLength(j) - needleLines[0].length(); - for (int k = 0; k < needleLines.count(); k++) - { - // which lines to compare - const QString & needleLine = needleLines[k]; - const QString & hayLine = m_document->line(j + k); - - // position specific comparison (first, middle, last) - if (k == 0) { - // first line - if (forMin == j && startCol < inputRange.start().column()) - break; - if (!hayLine.endsWith(needleLine, m_caseSensitivity)) - break; - } else if (k == needleLines.count() - 1) { - // last line - const int maxRight = (j + k == inputRange.end().line()) ? inputRange.end().column() : hayLine.length(); - - if (hayLine.startsWith(needleLine, m_caseSensitivity) && needleLine.length() <= maxRight) - return KTextEditor::Range(j, startCol, j + k, needleLine.length()); - } else { - // mid lines - if (hayLine.compare(needleLine, m_caseSensitivity) != 0) { - break; - } - } - } - } - - // not found - return KTextEditor::Range::invalid(); - } - else - { - // single-line plaintext search (both forward of backward mode) - const int startCol = inputRange.start().column(); - const int endCol = inputRange.end().column(); // first not included - const int startLine = inputRange.start().line(); - const int endLine = inputRange.end().line(); - const int forInc = backwards ? -1 : +1; - - for (int line = backwards ? endLine : startLine; (startLine <= line) && (line <= endLine); line += forInc) - { - if ((line < 0) || (m_document->lines() <= line)) - { - kWarning() << "line " << line << " is not within interval [0.." << m_document->lines() << ") ... returning invalid range"; - return KTextEditor::Range::invalid(); - } - - const QString textLine = m_document->line(line); - - const int offset = (line == startLine) ? startCol : 0; - const int line_end = (line == endLine) ? endCol : textLine.length(); - const int foundAt = backwards ? textLine.lastIndexOf(text, line_end-text.length(), m_caseSensitivity) : - textLine.indexOf(text, offset, m_caseSensitivity); - - if ((offset <= foundAt) && (foundAt + text.length() <= line_end)) - return KTextEditor::Range(line, foundAt, line, foundAt + text.length()); - } - } - return KTextEditor::Range::invalid(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/search/kateplaintextsearch.h b/part/search/kateplaintextsearch.h deleted file mode 100644 index 6937b97..0000000 --- a/part/search/kateplaintextsearch.h +++ /dev/null @@ -1,73 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009-2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_PLAINTEXTSEARCH_H_ -#define _KATE_PLAINTEXTSEARCH_H_ - -#include - -#include - -#include "katepartprivate_export.h" - -namespace KTextEditor { - class Document; -} - -/** - * Object to help to search for plain text. - * This should be NO QObject, it is created to often! - * I measured that, if you create it 20k times to replace for example " " in a document, that takes seconds on a modern machine! - */ -class KATEPART_TESTS_EXPORT KatePlainTextSearch -{ - public: - explicit KatePlainTextSearch (KTextEditor::Document *document, Qt::CaseSensitivity caseSensitivity, bool wholeWords); - ~KatePlainTextSearch (); - - public: - /** - * Search for the given \p text inside the range \p inputRange taking - * into account whether to search \p casesensitive and \p backwards. - * - * \param text text to search for - * \param inputRange Range to search in - * \param casesensitive if \e true, the search is performed case - * sensitive, otherwise case insensitive - * \param backwards if \e true, the search will be backwards - * \return The valid range of the matched text if \p text was found. If - * the \p text was not found, the returned range is not valid - * (see Range::isValid()). - * \see KTextEditor::Range - */ - KTextEditor::Range search (const QString & text, - const KTextEditor::Range & inputRange, bool backwards = false); - - private: - KTextEditor::Document *m_document; - Qt::CaseSensitivity m_caseSensitivity; - bool m_wholeWords; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/search/kateregexp.cpp b/part/search/kateregexp.cpp deleted file mode 100644 index f2af989..0000000 --- a/part/search/kateregexp.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateregexp.h" - -KateRegExp::KateRegExp(const QString &pattern, Qt::CaseSensitivity cs, - QRegExp::PatternSyntax syntax) - : m_regExp(pattern, cs, syntax) -{ -} - -// these things can besides '.' and '\s' make apptern multi-line: -// \n, \x000A, \x????-\x????, \0012, \0???-\0??? -// a multi-line pattern must not pass as single-line, the other -// way around will just result in slower searches and is therefore -// not as critical -int KateRegExp::repairPattern(bool & stillMultiLine) -{ - const QString & text = pattern(); // read-only input for parsing - - // get input - const int inputLen = text.length(); - int input = 0; // walker index - - // prepare output - QString output; - output.reserve(2 * inputLen + 1); // twice should be enough for the average case - - // parser state - stillMultiLine = false; - int replaceCount = 0; - bool insideClass = false; - - while (input < inputLen) - { - if (insideClass) - { - // wait for closing, unescaped ']' - switch (text[input].unicode()) - { - case L'\\': - switch (text[input + 1].unicode()) - { - case L'x': - if (input + 5 < inputLen) - { - // copy "\x????" unmodified - output.append(text.mid(input, 6)); - input += 6; - } else { - // copy "\x" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - stillMultiLine = true; - break; - - case L'0': - if (input + 4 < inputLen) - { - // copy "\0???" unmodified - output.append(text.mid(input, 5)); - input += 5; - } else { - // copy "\0" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - stillMultiLine = true; - break; - - case L's': - // replace "\s" with "[ \t]" - output.append("[ \\t]"); - input += 2; - replaceCount++; - break; - - case L'n': - stillMultiLine = true; - // FALLTROUGH - - default: - // copy "\?" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - break; - - case L']': - // copy "]" unmodified - insideClass = false; - output.append(text[input]); - input++; - break; - - default: - // copy "?" unmodified - output.append(text[input]); - input++; - - } - } - else - { - // search for real dots and \S - switch (text[input].unicode()) - { - case L'\\': - switch (text[input + 1].unicode()) - { - case L'x': - if (input + 5 < inputLen) - { - // copy "\x????" unmodified - output.append(text.mid(input, 6)); - input += 6; - } else { - // copy "\x" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - stillMultiLine = true; - break; - - case L'0': - if (input + 4 < inputLen) - { - // copy "\0???" unmodified - output.append(text.mid(input, 5)); - input += 5; - } else { - // copy "\0" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - stillMultiLine = true; - break; - - case L's': - // replace "\s" with "[ \t]" - output.append("[ \\t]"); - input += 2; - replaceCount++; - break; - - case L'n': - stillMultiLine = true; - // FALLTROUGH - - default: - // copy "\?" unmodified - output.append(text.mid(input, 2)); - input += 2; - } - break; - - case L'.': - // replace " with "[^\n]" - output.append("[^\\n]"); - input++; - replaceCount++; - break; - - case L'[': - // copy "]" unmodified - insideClass = true; - output.append(text[input]); - input++; - break; - - default: - // copy "?" unmodified - output.append(text[input]); - input++; - - } - } - } - - // Overwrite with repaired pattern - m_regExp.setPattern(output); - return replaceCount; -} - - - -bool KateRegExp::isMultiLine() const -{ - const QString &text = pattern(); - - // parser state - bool insideClass = false; - - for (int input = 0; input < text.length(); /*empty*/ ) - { - if (insideClass) - { - // wait for closing, unescaped ']' - switch (text[input].unicode()) - { - case L'\\': - switch (text[input + 1].unicode()) - { - case L'x': - return true; - - case L'0': - return true; - - case L's': - // replace "\s" with "[ \t]" - input += 2; - break; - - case L'n': - return true; - // FALLTROUGH - - default: - // copy "\?" unmodified - input += 2; - } - break; - - case L']': - // copy "]" unmodified - insideClass = false; - input++; - break; - - default: - // copy "?" unmodified - input++; - - } - } - else - { - // search for real dots and \S - switch (text[input].unicode()) - { - case L'\\': - switch (text[input + 1].unicode()) - { - case L'x': - return true; - - case L'0': - return true; - - case L's': - // replace "\s" with "[ \t]" - input += 2; - break; - - case L'n': - return true; - - default: - // copy "\?" unmodified - input += 2; - } - break; - - case L'.': - // replace " with "[^\n]" - input++; - break; - - case L'[': - // copy "]" unmodified - insideClass = true; - input++; - break; - - default: - // copy "?" unmodified - input++; - - } - } - } - - return false; -} - - - -int KateRegExp::indexIn(const QString &str, int start, int end) const -{ - return m_regExp.indexIn(str.left(end), start, QRegExp::CaretAtZero); -} - - - -int KateRegExp::lastIndexIn(const QString &str, int start, int end) const -{ - const int index = m_regExp.lastIndexIn(str.mid(start, end-start), -1, QRegExp::CaretAtZero); - - if (index == -1) - return -1; - - const int index2 = m_regExp.indexIn(str.left(end), start+index, QRegExp::CaretAtZero); - - return index2; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/search/kateregexp.h b/part/search/kateregexp.h deleted file mode 100644 index 4cd02e8..0000000 --- a/part/search/kateregexp.h +++ /dev/null @@ -1,81 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_REGEXP_H_ -#define _KATE_REGEXP_H_ - -#include - -class KateRegExp -{ - public: - explicit KateRegExp(const QString &pattern, Qt::CaseSensitivity cs = Qt::CaseSensitive, - QRegExp::PatternSyntax syntax = QRegExp::RegExp2); - - bool isEmpty() const { return m_regExp.isEmpty(); } - bool isValid() const { return m_regExp.isValid(); } - QString pattern() const { return m_regExp.pattern(); } - int numCaptures() const { return m_regExp.numCaptures(); } - int pos(int nth = 0) const { return m_regExp.pos(nth); } - QString cap(int nth = 0) const { return m_regExp.cap(nth); } - int matchedLength() const { return m_regExp.matchedLength(); } - - int indexIn(const QString &str, int offset, int end) const; - - /** - * This function is a replacement for QRegExp.lastIndexIn that - * returns the last match that would have been found when - * searching forwards, which QRegExp.lastIndexIn does not. - * We need this behavior to allow the user to jump back to - * the last match. - * - * \param str Text to search in - * \param offset Offset (-1 starts from end, -2 from one before the end) - * \return Index of match or -1 if no match is found - */ - int lastIndexIn(const QString &str, int offset, int end) const; - - /** - * Repairs a regular Expression pattern. - * This is a workaround to make "." and "\s" not match - * newlines, which currently is the unconfigurable - * default in QRegExp. - * - * \param stillMultiLine Multi-line after reparation flag - * \return Number of replacements done - */ - int repairPattern(bool & stillMultiLine); - - /** - * States, whether the pattern matches multiple lines, - * even if it was repaired using @p repairPattern(). - * - * \return Whether the pattern matches multiple lines - */ - bool isMultiLine() const; - - private: - QRegExp m_regExp; -}; - -#endif // KATEREGEXP_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/search/kateregexpsearch.cpp b/part/search/kateregexpsearch.cpp deleted file mode 100644 index 0f4d42c..0000000 --- a/part/search/kateregexpsearch.cpp +++ /dev/null @@ -1,820 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -//BEGIN includes -#include "kateregexpsearch.h" -#include "kateregexp.h" - -#include -//END includes - - - -// Turn debug messages on/off here -// #define FAST_DEBUG_ENABLE - -#ifdef FAST_DEBUG_ENABLE -# define FAST_DEBUG(x) kDebug( 13020 ) << x -#else -# define FAST_DEBUG(x) -#endif - - -class KateRegExpSearch::ReplacementStream -{ -public: - struct counter { - counter(int value, int minWidth) - : value(value) - , minWidth(minWidth) - {} - - const int value; - const int minWidth; - }; - - struct cap { - cap(int n) - : n(n) - {} - - const int n; - }; - - enum CaseConversion { - upperCase, ///< \U ... uppercase from now on - upperCaseFirst, ///< \u ... uppercase the first letter - lowerCase, ///< \L ... lowercase from now on - lowerCaseFirst, ///< \l ... lowercase the first letter - keepCase ///< \E ... back to original case - }; - -public: - ReplacementStream(const QStringList &capturedTexts); - - QString str() const { return m_str; } - - ReplacementStream &operator<<(const QString &); - ReplacementStream &operator<<(const counter &); - ReplacementStream &operator<<(const cap &); - ReplacementStream &operator<<(CaseConversion); - -private: - const QStringList m_capturedTexts; - CaseConversion m_caseConversion; - QString m_str; -}; - - -KateRegExpSearch::ReplacementStream::ReplacementStream(const QStringList &capturedTexts) - : m_capturedTexts(capturedTexts) - , m_caseConversion(keepCase) -{ -} - -KateRegExpSearch::ReplacementStream &KateRegExpSearch::ReplacementStream::operator<<(const QString &str) -{ - switch (m_caseConversion) { - case upperCase: - // Copy as uppercase - m_str.append(str.toUpper()); - break; - - case upperCaseFirst: - if (str.length() > 0) { - m_str.append(str.at(0).toUpper()); - m_str.append(str.mid(1)); - m_caseConversion = keepCase; - } - break; - - case lowerCase: - // Copy as lowercase - m_str.append(str.toLower()); - break; - - case lowerCaseFirst: - if (str.length() > 0) { - m_str.append(str.at(0).toLower()); - m_str.append(str.mid(1)); - m_caseConversion = keepCase; - } - break; - - case keepCase: // FALLTHROUGH - default: - // Copy unmodified - m_str.append(str); - break; - - } - - return *this; -} - - -KateRegExpSearch::ReplacementStream &KateRegExpSearch::ReplacementStream::operator<<(const counter &c) -{ - // Zero padded counter value - m_str.append(QString("%1").arg(c.value, c.minWidth, 10, QLatin1Char('0'))); - - return *this; -} - - -KateRegExpSearch::ReplacementStream &KateRegExpSearch::ReplacementStream::operator<<(const cap &cap) -{ - if (0 <= cap.n && cap.n < m_capturedTexts.size()) { - (*this) << m_capturedTexts[cap.n]; - } else { - // Insert just the number to be consistent with QRegExp ("\c" becomes "c") - m_str.append(QString::number(cap.n)); - } - - return *this; -} - - -KateRegExpSearch::ReplacementStream &KateRegExpSearch::ReplacementStream::operator<<(CaseConversion caseConversion) -{ - m_caseConversion = caseConversion; - - return *this; -} - - -//BEGIN d'tor, c'tor -// -// KateSearch Constructor -// -KateRegExpSearch::KateRegExpSearch ( KTextEditor::Document *document, Qt::CaseSensitivity caseSensitivity ) -: m_document (document) -, m_caseSensitivity (caseSensitivity) -{ -} - -// -// KateSearch Destructor -// -KateRegExpSearch::~KateRegExpSearch() -{ -} - - -// helper structs for captures re-construction -struct TwoViewCursor { - int index; - int openLine; - int openCol; - int closeLine; - int closeCol; - // note: open/close distinction does not seem needed - // anymore. i keep it to make a potential way back - // easier. overhead is minimal. -}; - -struct IndexPair { - int openIndex; - int closeIndex; -}; - - - -QVector KateRegExpSearch::search( - const QString &pattern, - const KTextEditor::Range & inputRange, - bool backwards) -{ - // regex search - KateRegExp regexp(pattern, m_caseSensitivity); - - if (regexp.isEmpty() || !regexp.isValid() || !inputRange.isValid() || (inputRange.start() == inputRange.end())) - { - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - - - // detect pattern type (single- or mutli-line) - bool isMultiLine; - - // detect '.' and '\s' and fix them - const bool dotMatchesNewline = false; // TODO - const int replacements = regexp.repairPattern(isMultiLine); - if (dotMatchesNewline && (replacements > 0)) - { - isMultiLine = true; - } - - const int firstLineIndex = inputRange.start().line(); - const int minColStart = inputRange.start().column(); -// const int maxColEnd = inputRange.end().column(); - if (isMultiLine) - { - // multi-line regex search (both forward and backward mode) - QString wholeDocument; - const int inputLineCount = inputRange.end().line() - inputRange.start().line() + 1; - FAST_DEBUG("multi line search (lines " << firstLineIndex << ".." << firstLineIndex + inputLineCount - 1 << ")"); - - // nothing to do... - if (firstLineIndex >= m_document->lines()) - { - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - - QVector lineLens (inputLineCount); - - // first line - if (firstLineIndex < 0 || m_document->lines() <= firstLineIndex) - { - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - - const QString firstLine = m_document->line(firstLineIndex); - - const int firstLineLen = firstLine.length() - minColStart; - wholeDocument.append(firstLine.right(firstLineLen)); - lineLens[0] = firstLineLen; - FAST_DEBUG(" line" << 0 << "has length" << lineLens[0]); - - // second line and after - const QString sep("\n"); - for (int i = 1; i < inputLineCount; i++) - { - const int lineNum = firstLineIndex + i; - if (lineNum < 0 || m_document->lines() <= lineNum) - { - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - const QString text = m_document->line(lineNum); - - lineLens[i] = text.length(); - wholeDocument.append(sep); - wholeDocument.append(text); - FAST_DEBUG(" line" << i << "has length" << lineLens[i]); - } - - const int pos = backwards - ? regexp.lastIndexIn(wholeDocument, 0, wholeDocument.length()) - : regexp.indexIn(wholeDocument, 0, wholeDocument.length()); - if (pos == -1) - { - // no match - FAST_DEBUG("not found"); - { - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - } - -#ifdef FAST_DEBUG_ENABLE - const int matchLen = regexp.matchedLength(); - FAST_DEBUG("found at relative pos " << pos << ", length " << matchLen); -#endif - - // save opening and closing indices and build a map. - // the correct values will be written into it later. - QMap indicesToCursors; - const int numCaptures = regexp.numCaptures(); - QVector indexPairs(1 + numCaptures); - for (int z = 0; z <= numCaptures; z++) - { - const int openIndex = regexp.pos(z); - IndexPair & pair = indexPairs[z]; - if (openIndex == -1) - { - // empty capture gives invalid - pair.openIndex = -1; - pair.closeIndex = -1; - FAST_DEBUG("capture []"); - } - else - { - const int closeIndex = openIndex + regexp.cap(z).length(); - pair.openIndex = openIndex; - pair.closeIndex = closeIndex; - FAST_DEBUG("capture [" << pair.openIndex << ".." << pair.closeIndex << "]"); - - // each key no more than once - if (!indicesToCursors.contains(openIndex)) - { - TwoViewCursor * twoViewCursor = new TwoViewCursor; - twoViewCursor->index = openIndex; - indicesToCursors.insert(openIndex, twoViewCursor); - FAST_DEBUG(" border index added: " << openIndex); - } - if (!indicesToCursors.contains(closeIndex)) - { - TwoViewCursor * twoViewCursor = new TwoViewCursor; - twoViewCursor->index = closeIndex; - indicesToCursors.insert(closeIndex, twoViewCursor); - FAST_DEBUG(" border index added: " << closeIndex); - } - } - } - - // find out where they belong - int curRelLine = 0; - int curRelCol = 0; - int curRelIndex = 0; - QMap::const_iterator iter = indicesToCursors.constBegin(); - while (iter != indicesToCursors.constEnd()) - { - // forward to index, save line/col - const int index = (*iter)->index; - FAST_DEBUG("resolving position" << index); - TwoViewCursor & twoViewCursor = *(*iter); - while (curRelIndex <= index) - { - FAST_DEBUG("walk pos (" << curRelLine << "," << curRelCol << ") = " - << curRelIndex << "relative, steps more to go" << index - curRelIndex); - const int curRelLineLen = lineLens[curRelLine]; - const int curLineRemainder = curRelLineLen - curRelCol; - const int lineFeedIndex = curRelIndex + curLineRemainder; - if (index <= lineFeedIndex) { - if (index == lineFeedIndex) { - // on this line _on_ line feed - FAST_DEBUG(" on line feed"); - const int absLine = curRelLine + firstLineIndex; - twoViewCursor.openLine - = twoViewCursor.closeLine - = absLine; - twoViewCursor.openCol - = twoViewCursor.closeCol - = ((curRelLine == 0) ? minColStart : 0) + curRelLineLen; - - // advance to next line - const int advance = (index - curRelIndex) + 1; - curRelLine++; - curRelCol = 0; - curRelIndex += advance; - } else { // index < lineFeedIndex - // on this line _before_ line feed - FAST_DEBUG(" before line feed"); - const int diff = (index - curRelIndex); - const int absLine = curRelLine + firstLineIndex; - const int absCol = ((curRelLine == 0) ? minColStart : 0) + curRelCol + diff; - twoViewCursor.openLine - = twoViewCursor.closeLine - = absLine; - twoViewCursor.openCol - = twoViewCursor.closeCol - = absCol; - - // advance on same line - const int advance = diff + 1; - curRelCol += advance; - curRelIndex += advance; - } - FAST_DEBUG("open(" << twoViewCursor.openLine << "," << twoViewCursor.openCol - << ") close(" << twoViewCursor.closeLine << "," << twoViewCursor.closeCol << ")"); - } - else // if (index > lineFeedIndex) - { - // not on this line - // advance to next line - FAST_DEBUG(" not on this line"); - const int advance = curLineRemainder + 1; - curRelLine++; - curRelCol = 0; - curRelIndex += advance; - } - } - - ++iter; - } - - // build result array - QVector result(1 + numCaptures); - for (int y = 0; y <= numCaptures; y++) - { - IndexPair & pair = indexPairs[y]; - if ((pair.openIndex == -1) || (pair.closeIndex == -1)) - { - result[y] = KTextEditor::Range::invalid(); - } - else - { - const TwoViewCursor * const openCursors = indicesToCursors[pair.openIndex]; - const TwoViewCursor * const closeCursors = indicesToCursors[pair.closeIndex]; - const int startLine = openCursors->openLine; - const int startCol = openCursors->openCol; - const int endLine = closeCursors->closeLine; - const int endCol = closeCursors->closeCol; - FAST_DEBUG("range " << y << ": (" << startLine << ", " << startCol << ")..(" << endLine << ", " << endCol << ")"); - result[y] = KTextEditor::Range(startLine, startCol, endLine, endCol); - } - } - - // free structs allocated for indicesToCursors - iter = indicesToCursors.constBegin(); - while (iter != indicesToCursors.constEnd()) - { - TwoViewCursor * const twoViewCursor = *iter; - delete twoViewCursor; - ++iter; - } - return result; - } - else - { - // single-line regex search (both forward of backward mode) - const int minLeft = inputRange.start().column(); - const uint maxRight = inputRange.end().column(); // first not included - const int forMin = inputRange.start().line(); - const int forMax = inputRange.end().line(); - const int forInit = backwards ? forMax : forMin; - const int forInc = backwards ? -1 : +1; - FAST_DEBUG("single line " << (backwards ? forMax : forMin) << ".." - << (backwards ? forMin : forMax)); - for (int j = forInit; (forMin <= j) && (j <= forMax); j += forInc) - { - if (j < 0 || m_document->lines() <= j) - { - FAST_DEBUG("searchText | line " << j << ": no"); - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; - } - const QString textLine = m_document->line(j); - - // Find (and don't match ^ in between...) - const int first = (j == forMin) ? minLeft : 0; - const int last = (j == forMax) ? maxRight : textLine.length(); - const int foundAt = (backwards ? regexp.lastIndexIn(textLine, first, last) - : regexp.indexIn(textLine, first, last)); - const bool found = (foundAt != -1); - - /* - TODO do we still need this? - - // A special case which can only occur when searching with a regular expression consisting - // only of a lookahead (e.g. ^(?=\{) for a function beginning without selecting '{'). - if (myMatchLen == 0 && line == startPosition.line() && foundAt == (uint) col) - { - if (col < lineLength(line)) - col++; - else { - line++; - col = 0; - } - continue; - } - */ - - if (found) - { - FAST_DEBUG("line " << j << ": yes"); - - // build result array - const int numCaptures = regexp.numCaptures(); - QVector result(1 + numCaptures); - result[0] = KTextEditor::Range(j, foundAt, j, foundAt + regexp.matchedLength()); - FAST_DEBUG("result range " << 0 << ": (" << j << ", " << foundAt << ")..(" << j << ", " << - foundAt + regexp.matchedLength() << ")"); - for (int y = 1; y <= numCaptures; y++) - { - const int openIndex = regexp.pos(y); - if (openIndex == -1) - { - result[y] = KTextEditor::Range::invalid(); - FAST_DEBUG("capture []"); - } - else - { - const int closeIndex = openIndex + regexp.cap(y).length(); - FAST_DEBUG("result range " << y << ": (" << j << ", " << openIndex << ")..(" << j << ", " << closeIndex << ")"); - result[y] = KTextEditor::Range(j, openIndex, j, closeIndex); - } - } - return result; - } - else - { - FAST_DEBUG("searchText | line " << j << ": no"); - } - } - } - - QVector result; - result.append(KTextEditor::Range::invalid()); - return result; -} - - -/*static*/ QString KateRegExpSearch::escapePlaintext(const QString & text) -{ - return buildReplacement(text, QStringList(), 0, false); -} - - -/*static*/ QString KateRegExpSearch::buildReplacement(const QString & text, const QStringList &capturedTexts, int replacementCounter) -{ - return buildReplacement(text, capturedTexts, replacementCounter, true); -} - - -/*static*/ QString KateRegExpSearch::buildReplacement(const QString & text, const QStringList &capturedTexts, int replacementCounter, bool replacementGoodies) { - // get input - const int inputLen = text.length(); - int input = 0; // walker index - - // prepare output - ReplacementStream out(capturedTexts); - - while (input < inputLen) - { - switch (text[input].unicode()) - { - case L'\n': - out << text[input]; - input++; - break; - - case L'\\': - if (input + 1 >= inputLen) - { - // copy backslash - out << text[input]; - input++; - break; - } - - switch (text[input + 1].unicode()) - { - case L'0': // "\0000".."\0377" - if (input + 4 >= inputLen) - { - out << ReplacementStream::cap(0); - input += 2; - } - else - { - bool stripAndSkip = false; - const ushort text_2 = text[input + 2].unicode(); - if ((text_2 >= L'0') && (text_2 <= L'3')) - { - const ushort text_3 = text[input + 3].unicode(); - if ((text_3 >= L'0') && (text_3 <= L'7')) - { - const ushort text_4 = text[input + 4].unicode(); - if ((text_4 >= L'0') && (text_4 <= L'7')) - { - int digits[3]; - for (int i = 0; i < 3; i++) - { - digits[i] = 7 - (L'7' - text[input + 2 + i].unicode()); - } - const int ch = 64 * digits[0] + 8 * digits[1] + digits[2]; - out << QChar(ch); - input += 5; - } - else - { - stripAndSkip = true; - } - } - else - { - stripAndSkip = true; - } - } - else - { - stripAndSkip = true; - } - - if (stripAndSkip) - { - out << ReplacementStream::cap(0); - input += 2; - } - } - break; - - case L'1': - case L'2': - case L'3': - case L'4': - case L'5': - case L'6': - case L'7': - case L'8': - case L'9': - out << ReplacementStream::cap(9 - (L'9' - text[input + 1].unicode())); - input += 2; - break; - - case L'E': // FALLTHROUGH - case L'L': // FALLTHROUGH - case L'l': // FALLTHROUGH - case L'U': // FALLTHROUGH - case L'u': - if (!replacementGoodies) { - // strip backslash ("\?" -> "?") - out << text[input + 1]; - } else { - // handle case switcher - switch (text[input + 1].unicode()) { - case L'L': - out << ReplacementStream::lowerCase; - break; - - case L'l': - out << ReplacementStream::lowerCaseFirst; - break; - - case L'U': - out << ReplacementStream::upperCase; - break; - - case L'u': - out << ReplacementStream::upperCaseFirst; - break; - - case L'E': // FALLTHROUGH - default: - out << ReplacementStream::keepCase; - - } - } - input += 2; - break; - - case L'#': - if (!replacementGoodies) { - // strip backslash ("\?" -> "?") - out << text[input + 1]; - input += 2; - } else { - // handle replacement counter - // eat and count all following hash marks - // each hash stands for a leading zero: \### will produces 001, 002, ... - int minWidth = 1; - while ((input + minWidth + 1 < inputLen) && (text[input + minWidth + 1].unicode() == L'#')) { - minWidth++; - } - out << ReplacementStream::counter(replacementCounter, minWidth); - input += 1 + minWidth; - } - break; - - case L'a': - out << QChar(0x07); - input += 2; - break; - - case L'f': - out << QChar(0x0c); - input += 2; - break; - - case L'n': - out << QChar(0x0a); - input += 2; - break; - - case L'r': - out << QChar(0x0d); - input += 2; - break; - - case L't': - out << QChar(0x09); - input += 2; - break; - - case L'v': - out << QChar(0x0b); - input += 2; - break; - - case L'x': // "\x0000".."\xffff" - if (input + 5 >= inputLen) - { - // strip backslash ("\x" -> "x") - out << text[input + 1]; - input += 2; - } - else - { - bool stripAndSkip = false; - const ushort text_2 = text[input + 2].unicode(); - if (((text_2 >= L'0') && (text_2 <= L'9')) - || ((text_2 >= L'a') && (text_2 <= L'f')) - || ((text_2 >= L'A') && (text_2 <= L'F'))) - { - const ushort text_3 = text[input + 3].unicode(); - if (((text_3 >= L'0') && (text_3 <= L'9')) - || ((text_3 >= L'a') && (text_3 <= L'f')) - || ((text_3 >= L'A') && (text_3 <= L'F'))) - { - const ushort text_4 = text[input + 4].unicode(); - if (((text_4 >= L'0') && (text_4 <= L'9')) - || ((text_4 >= L'a') && (text_4 <= L'f')) - || ((text_4 >= L'A') && (text_4 <= L'F'))) - { - const ushort text_5 = text[input + 5].unicode(); - if (((text_5 >= L'0') && (text_5 <= L'9')) - || ((text_5 >= L'a') && (text_5 <= L'f')) - || ((text_5 >= L'A') && (text_5 <= L'F'))) - { - int digits[4]; - for (int i = 0; i < 4; i++) - { - const ushort cur = text[input + 2 + i].unicode(); - if ((cur >= L'0') && (cur <= L'9')) - { - digits[i] = 9 - (L'9' - cur); - } - else if ((cur >= L'a') && (cur <= L'f')) - { - digits[i] = 15 - (L'f' - cur); - } - else // if ((cur >= L'A') && (cur <= L'F'))) - { - digits[i] = 15 - (L'F' - cur); - } - } - - const int ch = 4096 * digits[0] + 256 * digits[1] + 16 * digits[2] + digits[3]; - out << QChar(ch); - input += 6; - } - else - { - stripAndSkip = true; - } - } - else - { - stripAndSkip = true; - } - } - else - { - stripAndSkip = true; - } - } - - if (stripAndSkip) - { - // strip backslash ("\x" -> "x") - out << text[input + 1]; - input += 2; - } - } - break; - - default: - // strip backslash ("\?" -> "?") - out << text[input + 1]; - input += 2; - - } - break; - - default: - out << text[input]; - input++; - - } - } - - return out.str(); -} - - -// Kill our helpers again -#ifdef FAST_DEBUG_ENABLE -# undef FAST_DEBUG_ENABLE -#endif -#undef FAST_DEBUG - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/search/kateregexpsearch.h b/part/search/kateregexpsearch.h deleted file mode 100644 index bb16ce9..0000000 --- a/part/search/kateregexpsearch.h +++ /dev/null @@ -1,108 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_REGEXPSEARCH_H_ -#define _KATE_REGEXPSEARCH_H_ - -#include - -#include - -#include "katepartprivate_export.h" - -namespace KTextEditor { - class Document; -} - -/** - * Object to help to search for regexp. - * This should be NO QObject, it is created to often! - * I measured that, if you create it 20k times to replace for example " " in a document, that takes seconds on a modern machine! - */ -class KATEPART_TESTS_EXPORT KateRegExpSearch -{ - public: - explicit KateRegExpSearch (KTextEditor::Document *document, Qt::CaseSensitivity caseSensitivity); - ~KateRegExpSearch (); - - // - // KTextEditor::SearchInterface stuff - // - public: - /** - * Search for the regular expression \p regexp inside the range - * \p inputRange. If \p backwards is \e true, the search direction will - * be reversed. - * - * \param regexp text to search for - * \param inputRange Range to search in - * \param backwards if \e true, the search will be backwards - * \return Vector of ranges, one for each capture. The first range (index zero) - * spans the full match. If the pattern does not match the vector - * has length 1 and holds the invalid range (see Range::isValid()). - * \see KTextEditor::Range, QRegExp - */ - QVector search (const QString &pattern, - const KTextEditor::Range & inputRange, bool backwards = false); - - /** - * Returns a mofified version of text where escape sequences are resolved, e.g. "\\n" to "\n". - * - * \param text text containing escape sequences - * \return text with resolved escape sequences - */ - static QString escapePlaintext(const QString &text); - - /** - * Returns a mofified version of text where - * \li escape sequences are resolved, e.g. "\\n" to "\n", - * \li references are resolved, e.g. "\\1" to 1st entry in capturedTexts, and - * \li counter sequences are resolved, e.g. "\\#...#" to replacementCounter. - * - * \param text text containing escape sequences, references, and counter sequences - * \param capturedTexts list of substitutes for references - * \param replacementCounter value for replacement counter - * \return resolved text - */ - static QString buildReplacement(const QString &text, const QStringList &capturedTexts, int replacementCounter); - - private: - /** - * Implementation of escapePlainText() and public buildReplacement(). - * - * \param text text containing escape sequences and possibly references and counters - * \param capturedTexts list of substitutes for references - * \param replacementCounter value for replacement counter (only used when replacementGoodies == true) - * \param replacementGoodies true for buildReplacement(), false for escapePlainText() - * \return resolved text - */ - static QString buildReplacement(const QString &text, const QStringList &capturedTexts, int replacementCounter, bool replacementGoodies); - - private: - KTextEditor::Document *const m_document; - Qt::CaseSensitivity m_caseSensitivity; - class ReplacementStream; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/search/katesearchbar.cpp b/part/search/katesearchbar.cpp deleted file mode 100644 index db8cad6..0000000 --- a/part/search/katesearchbar.cpp +++ /dev/null @@ -1,1549 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2010 Bernhard Beschow - Copyright (C) 2007 Sebastian Pipping - Copyright (C) 2007 Matthew Woehlke - Copyright (C) 2007 Thomas Friedrichsmeier - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katesearchbar.h" -#include "katesearchbar.moc" - -#include "kateregexp.h" -#include "katematch.h" -#include "kateview.h" -#include "katedocument.h" -#include "kateconfig.h" - -#include -#include - -#include "ui_searchbarincremental.h" -#include "ui_searchbarpower.h" - -#include -#include -#include - -#include -#include -#include -#include -#include - -// Turn debug messages on/off here -// #define FAST_DEBUG_ENABLE - -#ifdef FAST_DEBUG_ENABLE -# define FAST_DEBUG(x) kDebug() << x -#else -# define FAST_DEBUG(x) -#endif - -using namespace KTextEditor; - -namespace { - -class AddMenuManager { - -private: - QVector m_insertBefore; - QVector m_insertAfter; - QSet m_actionPointers; - uint m_indexWalker; - QMenu * m_menu; - -public: - AddMenuManager(QMenu * parent, int expectedItemCount) - : m_insertBefore(QVector(expectedItemCount)), - m_insertAfter(QVector(expectedItemCount)), - m_indexWalker(0), - m_menu(NULL) { - Q_ASSERT(parent != NULL); - m_menu = parent->addMenu(i18n("Add...")); - if (m_menu == NULL) { - return; - } - m_menu->setIcon(KIcon("list-add")); - } - - void enableMenu(bool enabled) { - if (m_menu == NULL) { - return; - } - m_menu->setEnabled(enabled); - } - - void addEntry(const QString & before, const QString after, - const QString description, const QString & realBefore = QString(), - const QString & realAfter = QString()) { - if (m_menu == NULL) { - return; - } - QAction * const action = m_menu->addAction(before + after + '\t' + description); - m_insertBefore[m_indexWalker] = QString(realBefore.isEmpty() ? before : realBefore); - m_insertAfter[m_indexWalker] = QString(realAfter.isEmpty() ? after : realAfter); - action->setData(QVariant(m_indexWalker++)); - m_actionPointers.insert(action); - } - - void addSeparator() { - if (m_menu == NULL) { - return; - } - m_menu->addSeparator(); - } - - void handle(QAction * action, QLineEdit * lineEdit) { - if (!m_actionPointers.contains(action)) { - return; - } - - const int cursorPos = lineEdit->cursorPosition(); - const int index = action->data().toUInt(); - const QString & before = m_insertBefore[index]; - const QString & after = m_insertAfter[index]; - lineEdit->insert(before + after); - lineEdit->setCursorPosition(cursorPos + before.count()); - lineEdit->setFocus(); - } -}; - -} // anon namespace - - - -KateSearchBar::KateSearchBar(bool initAsPower, KateView* view, KateViewConfig *config) - : KateViewBarWidget(true, view), - m_view(view), - m_config(config), - m_layout(new QVBoxLayout()), - m_widget(NULL), - m_incUi(NULL), - m_incInitCursor(view->cursorPosition()), - m_powerUi(NULL), - highlightMatchAttribute (new Attribute()), - highlightReplacementAttribute (new Attribute()), - m_incHighlightAll(false), - m_incFromCursor(true), - m_incMatchCase(false), - m_powerMatchCase(true), - m_powerFromCursor(false), - m_powerHighlightAll(false), - m_powerMode(0) -{ - - connect(view, SIGNAL(cursorPositionChanged(KTextEditor::View *, KTextEditor::Cursor const &)), - this, SLOT(updateIncInitCursor())); - - // init match attribute - highlightMatchAttribute->setBackground(Qt::yellow); // TODO make this part of the color scheme - - Attribute::Ptr mouseInAttribute(new Attribute()); - mouseInAttribute->setFontBold(true); - mouseInAttribute->setBackground(Qt::yellow); // TODO make this part of the color scheme - highlightMatchAttribute->setDynamicAttribute (Attribute::ActivateMouseIn, mouseInAttribute); - - Attribute::Ptr caretInAttribute(new Attribute()); - caretInAttribute->setFontItalic(true); - caretInAttribute->setBackground(Qt::yellow); // TODO make this part of the color scheme - highlightMatchAttribute->setDynamicAttribute (Attribute::ActivateCaretIn, caretInAttribute); - - // init replacement attribute - highlightReplacementAttribute->setBackground(Qt::green); // TODO make this part of the color scheme - - // Modify parent - QWidget * const widget = centralWidget(); - widget->setLayout(m_layout); - m_layout->setMargin(0); - - - // Copy global to local config backup - const long searchFlags = m_config->searchFlags(); - m_incHighlightAll = (searchFlags & KateViewConfig::IncHighlightAll) != 0; - m_incFromCursor = (searchFlags & KateViewConfig::IncFromCursor) != 0; - m_incMatchCase = (searchFlags & KateViewConfig::IncMatchCase) != 0; - m_powerMatchCase = (searchFlags & KateViewConfig::PowerMatchCase) != 0; - m_powerFromCursor = (searchFlags & KateViewConfig::PowerFromCursor) != 0; - m_powerHighlightAll = (searchFlags & KateViewConfig::PowerHighlightAll) != 0; - m_powerMode = ((searchFlags & KateViewConfig::PowerModeRegularExpression) != 0) - ? MODE_REGEX - : (((searchFlags & KateViewConfig::PowerModeEscapeSequences) != 0) - ? MODE_ESCAPE_SEQUENCES - : (((searchFlags & KateViewConfig::PowerModeWholeWords) != 0) - ? MODE_WHOLE_WORDS - : MODE_PLAIN_TEXT)); - - - // Load one of either dialogs - if (initAsPower) { - enterPowerMode(); - } else { - enterIncrementalMode(); - } - - updateSelectionOnly(); - connect(view, SIGNAL(selectionChanged(KTextEditor::View *)), - this, SLOT(updateSelectionOnly())); -} - - - -KateSearchBar::~KateSearchBar() { - clearHighlights(); - delete m_layout; - delete m_widget; - - delete m_incUi; - delete m_powerUi; -} - - - - -void KateSearchBar::setReplacePattern(const QString &replacementPattern) { - Q_ASSERT(isPower()); - - if (this->replacementPattern() == replacementPattern) - return; - - m_powerUi->replacement->setEditText(replacementPattern); -} - - - -QString KateSearchBar::replacementPattern() const { - Q_ASSERT(isPower()); - - return m_powerUi->replacement->currentText(); -} - - - -void KateSearchBar::setSearchMode(KateSearchBar::SearchMode mode) { - Q_ASSERT(isPower()); - - m_powerUi->searchMode->setCurrentIndex(mode); -} - - - -void KateSearchBar::findNext() { - const bool found = find(); - - if (found) { - QComboBox *combo = m_powerUi != 0 ? m_powerUi->pattern : m_incUi->pattern; - - // Add to search history - addCurrentTextToHistory(combo); - } -} - - - -void KateSearchBar::findPrevious() { - const bool found = find(SearchBackward); - - if (found) { - QComboBox *combo = m_powerUi != 0 ? m_powerUi->pattern : m_incUi->pattern; - - // Add to search history - addCurrentTextToHistory(combo); - } -} - -void KateSearchBar::highlightMatch(const Range & range) { - KTextEditor::MovingRange* const highlight = m_view->doc()->newMovingRange(range, Kate::TextRange::DoNotExpand); - highlight->setView(m_view); // show only in this view - highlight->setAttributeOnlyForViews(true); - // use z depth defined in moving ranges interface - highlight->setZDepth (-10000.0); - highlight->setAttribute(highlightMatchAttribute); - m_hlRanges.append(highlight); -} - -void KateSearchBar::highlightReplacement(const Range & range) { - KTextEditor::MovingRange* const highlight = m_view->doc()->newMovingRange(range, Kate::TextRange::DoNotExpand); - highlight->setView(m_view); // show only in this view - highlight->setAttributeOnlyForViews(true); - // use z depth defined in moving ranges interface - highlight->setZDepth (-10000.0); - highlight->setAttribute(highlightReplacementAttribute); - m_hlRanges.append(highlight); -} - -void KateSearchBar::indicateMatch(MatchResult matchResult) { - QLineEdit * const lineEdit = isPower() ? m_powerUi->pattern->lineEdit() - : m_incUi->pattern->lineEdit(); - QPalette background(lineEdit->palette()); - - switch (matchResult) { - case MatchFound: // FALLTHROUGH - case MatchWrappedForward: - case MatchWrappedBackward: - // Green background for line edit - KColorScheme::adjustBackground(background, KColorScheme::PositiveBackground); - break; - case MatchMismatch: - // Red background for line edit - KColorScheme::adjustBackground(background, KColorScheme::NegativeBackground); - break; - case MatchNothing: - // Reset background of line edit - background = QPalette(); - break; - case MatchNeutral: - KColorScheme::adjustBackground(background, KColorScheme::NeutralBackground); - break; - } - - // Update status label - if (m_incUi != NULL) { - QPalette foreground(m_incUi->status->palette()); - switch (matchResult) { - case MatchFound: // FALLTHROUGH - case MatchNothing: - KColorScheme::adjustForeground(foreground, KColorScheme::NormalText, QPalette::WindowText, KColorScheme::Window); - m_incUi->status->setText(""); - break; - case MatchWrappedForward: - case MatchWrappedBackward: - KColorScheme::adjustForeground(foreground, KColorScheme::ActiveText, QPalette::WindowText, KColorScheme::Window); - if (matchResult == MatchWrappedBackward) { - m_incUi->status->setText(i18n("Reached top, continued from bottom")); - } else { - m_incUi->status->setText(i18n("Reached bottom, continued from top")); - } - break; - case MatchMismatch: - KColorScheme::adjustForeground(foreground, KColorScheme::NegativeText, QPalette::WindowText, KColorScheme::Window); - m_incUi->status->setText(i18n("Not found")); - break; - case MatchNeutral: - /* do nothing */ - break; - } - m_incUi->status->setPalette(foreground); - } - - lineEdit->setPalette(background); -} - - - -/*static*/ void KateSearchBar::selectRange(KateView * view, const KTextEditor::Range & range) { - view->setCursorPositionInternal(range.end()); - - // don't make a selection if the vi input mode is used - if (!view->viInputMode()) - view->setSelection(range); -} - - - -void KateSearchBar::selectRange2(const KTextEditor::Range & range) { - disconnect(m_view, SIGNAL(selectionChanged(KTextEditor::View *)), this, SLOT(updateSelectionOnly())); - selectRange(m_view, range); - connect(m_view, SIGNAL(selectionChanged(KTextEditor::View *)), this, SLOT(updateSelectionOnly())); -} - - - -void KateSearchBar::onIncPatternChanged(const QString & pattern) { - clearHighlights(); - - m_incUi->next->setDisabled(pattern.isEmpty()); - m_incUi->prev->setDisabled(pattern.isEmpty()); - - KateMatch match(m_view->doc(), searchOptions()); - - if (!pattern.isEmpty()) { - // Find, first try - const Range inputRange = KTextEditor::Range(m_incInitCursor, m_view->document()->documentEnd()); - match.searchText(inputRange, pattern); - } - - const bool wrap = !match.isValid() && !pattern.isEmpty(); - - if (wrap) { - // Find, second try - const KTextEditor::Range inputRange = m_view->document()->documentRange(); - match.searchText(inputRange, pattern); - } - - const MatchResult matchResult = match.isValid() ? (wrap ? MatchWrappedForward : MatchFound) : - pattern.isEmpty() ? MatchNothing : - MatchMismatch; - - const Range selectionRange = pattern.isEmpty() ? Range(m_incInitCursor, m_incInitCursor) : - match.isValid() ? match.range() : - Range::invalid(); - - // don't update m_incInitCursor when we move the cursor - disconnect(m_view, SIGNAL(cursorPositionChanged(KTextEditor::View*,KTextEditor::Cursor const&)), - this, SLOT(updateIncInitCursor())); - selectRange2(selectionRange); - connect(m_view, SIGNAL(cursorPositionChanged(KTextEditor::View*,KTextEditor::Cursor const&)), - this, SLOT(updateIncInitCursor())); - - indicateMatch(matchResult); -} - - - -void KateSearchBar::setMatchCase(bool matchCase) { - if (this->matchCase() == matchCase) - return; - - if (isPower()) - m_powerUi->matchCase->setChecked(matchCase); - else - m_incUi->matchCase->setChecked(matchCase); -} - - - -void KateSearchBar::onMatchCaseToggled(bool /*matchCase*/) { - sendConfig(); - - if (m_incUi != 0) { - // Re-search with new settings - const QString pattern = m_incUi->pattern->currentText(); - onIncPatternChanged(pattern); - } else { - indicateMatch(MatchNothing); - } -} - - - -bool KateSearchBar::matchCase() const -{ - return isPower() ? m_powerUi->matchCase->isChecked() - : m_incUi->matchCase->isChecked(); -} - - - -void KateSearchBar::fixForSingleLine(Range & range, SearchDirection searchDirection) { - FAST_DEBUG("Single-line workaround checking BEFORE" << range); - if (searchDirection == SearchForward) { - const int line = range.start().line(); - const int col = range.start().column(); - const int maxColWithNewline = m_view->document()->lineLength(line) + 1; - if (col == maxColWithNewline) { - FAST_DEBUG("Starting on a newline" << range); - const int maxLine = m_view->document()->lines() - 1; - if (line < maxLine) { - range.setRange(Cursor(line + 1, 0), range.end()); - FAST_DEBUG("Search range fixed to " << range); - } else { - FAST_DEBUG("Already at last line"); - range = Range::invalid(); - } - } - } else { - const int col = range.end().column(); - if (col == 0) { - FAST_DEBUG("Ending after a newline" << range); - const int line = range.end().line(); - if (line > 0) { - const int maxColWithNewline = m_view->document()->lineLength(line - 1); - range.setRange(range.start(), Cursor(line - 1, maxColWithNewline)); - FAST_DEBUG("Search range fixed to " << range); - } else { - FAST_DEBUG("Already at first line"); - range = Range::invalid(); - } - } - } - FAST_DEBUG("Single-line workaround checking AFTER" << range); -} - - - -void KateSearchBar::onReturnPressed() { - const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers(); - const bool shiftDown = (modifiers & Qt::ShiftModifier) != 0; - const bool controlDown = (modifiers & Qt::ControlModifier) != 0; - - // if vi input mode is active, the search box should be closed when hitting enter - if (m_view->viInputMode()) { - emit hideMe(); - return; - } - - if (shiftDown) { - // Shift down, search backwards - findPrevious(); - } else { - // Shift up, search forwards - findNext(); - } - - if (controlDown) { - emit hideMe(); - } -} - - - -bool KateSearchBar::find(SearchDirection searchDirection, const QString * replacement) { - // What to find? - if (searchPattern().isEmpty()) { - return false; // == Pattern error - } - - const Search::SearchOptions enabledOptions = searchOptions(searchDirection); - - // Where to find? - Range inputRange; - const Range selection = m_view->selection() ? m_view->selectionRange() : Range::invalid(); - if (selection.isValid()) { - if (selectionOnly()) { - // First match in selection - inputRange = selection; - } else { - // Next match after/before selection if a match was selected before - if (searchDirection == SearchForward) { - inputRange.setRange(selection.start(), m_view->document()->documentEnd()); - } else { - inputRange.setRange(Cursor(0, 0), selection.end()); - } - } - } else { - // No selection - const Cursor cursorPos = m_view->cursorPosition(); - if (searchDirection == SearchForward) { - // if the vi input mode is used, the cursor will stay a the first character of the - // matched pattern (no selection will be made), so the next search should start from - // match column + 1 - if (!m_view->viInputMode()) { - inputRange.setRange(cursorPos, m_view->document()->documentEnd()); - } else { - inputRange.setRange(Cursor(cursorPos.line(), cursorPos.column()+1), m_view->document()->documentEnd()); - } - } else { - inputRange.setRange(Cursor(0, 0), cursorPos); - } - } - FAST_DEBUG("Search range is" << inputRange); - - { - const bool regexMode = enabledOptions.testFlag(Search::Regex); - const bool multiLinePattern = regexMode ? KateRegExp(searchPattern()).isMultiLine() : false; - - // Single-line pattern workaround - if (regexMode && !multiLinePattern) { - fixForSingleLine(inputRange, searchDirection); - } - } - - KateMatch match(m_view->doc(), enabledOptions); - Range afterReplace = Range::invalid(); - - // Find, first try - match.searchText(inputRange, searchPattern()); - if (match.isValid() && match.range() == selection) { - // Same match again - if (replacement != 0) { - // Selection is match -> replace - KTextEditor::MovingRange *smartInputRange = m_view->doc()->newMovingRange (inputRange, KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - afterReplace = match.replace(*replacement, m_view->blockSelection()); - inputRange = *smartInputRange; - delete smartInputRange; - } - - if (!selectionOnly()) { - // Find, second try after old selection - if (searchDirection == SearchForward) { - const Cursor start = (replacement != 0) ? afterReplace.end() : selection.end(); - inputRange.setRange(start, inputRange.end()); - } else { - const Cursor end = (replacement != 0) ? afterReplace.start() : selection.start(); - inputRange.setRange(inputRange.start(), end); - } - } - - // Single-line pattern workaround - fixForSingleLine(inputRange, searchDirection); - - match.searchText(inputRange, searchPattern()); - } - - const bool wrap = !match.isValid() && (!selection.isValid() || !selectionOnly()); - if (wrap) { - inputRange = m_view->document()->documentRange(); - match.searchText(inputRange, searchPattern()); - } - - if (match.isValid()) { - selectRange2(match.range()); - } - - const MatchResult matchResult = !match.isValid() ? MatchMismatch : - !wrap ? MatchFound : - searchDirection == SearchForward ? MatchWrappedForward : - MatchWrappedBackward; - indicateMatch(matchResult); - - // Reset highlighting for all matches and highlight replacement if there is one - clearHighlights(); - if (afterReplace.isValid()) { - highlightReplacement(afterReplace); - } - - return true; // == No pattern error -} - - - - -void KateSearchBar::findAll() -{ - clearHighlights(); - Range inputRange = (m_view->selection() && selectionOnly()) - ? m_view->selectionRange() - : m_view->document()->documentRange(); - const int occurrences = findAll(inputRange, NULL); - - KPassivePopup::message(i18np("1 match found", "%1 matches found", occurrences), this); - - indicateMatch(occurrences > 0 ? MatchFound : MatchMismatch); -} - - - -void KateSearchBar::onPowerPatternChanged(const QString & /*pattern*/) { - givePatternFeedback(); - indicateMatch(MatchNothing); -} - - - -bool KateSearchBar::isPatternValid() const { - if (searchPattern().isEmpty()) - return false; - - return searchOptions().testFlag(Search::WholeWords) ? searchPattern().trimmed() == searchPattern() : - searchOptions().testFlag(Search::Regex) ? QRegExp(searchPattern()).isValid() : - true; -} - - - -void KateSearchBar::givePatternFeedback() { - // Enable/disable next/prev and replace next/all - m_powerUi->findNext->setEnabled(isPatternValid()); - m_powerUi->findPrev->setEnabled(isPatternValid()); - m_powerUi->replaceNext->setEnabled(isPatternValid()); - m_powerUi->replaceAll->setEnabled(isPatternValid()); -} - - - -void KateSearchBar::addCurrentTextToHistory(QComboBox * combo) { - const QString text = combo->currentText(); - const int index = combo->findText(text); - - if (index > 0) - combo->removeItem(index); - if (index != 0) - combo->insertItem(0, text); -} - - - -void KateSearchBar::backupConfig(bool ofPower) { - if (ofPower) { - m_powerMatchCase = m_powerUi->matchCase->isChecked(); - m_powerMode = m_powerUi->searchMode->currentIndex(); - } else { - m_incMatchCase = m_incUi->matchCase->isChecked(); - } -} - - - -void KateSearchBar::sendConfig() { - const long pastFlags = m_config->searchFlags(); - long futureFlags = pastFlags; - - if (m_powerUi != NULL) { - const bool OF_POWER = true; - backupConfig(OF_POWER); - - // Update power search flags only - const long incFlagsOnly = pastFlags - & (KateViewConfig::IncHighlightAll - | KateViewConfig::IncFromCursor - | KateViewConfig::IncMatchCase); - - futureFlags = incFlagsOnly - | (m_powerMatchCase ? KateViewConfig::PowerMatchCase : 0) - | (m_powerFromCursor ? KateViewConfig::PowerFromCursor : 0) - | (m_powerHighlightAll ? KateViewConfig::PowerHighlightAll : 0) - | ((m_powerMode == MODE_REGEX) - ? KateViewConfig::PowerModeRegularExpression - : ((m_powerMode == MODE_ESCAPE_SEQUENCES) - ? KateViewConfig::PowerModeEscapeSequences - : ((m_powerMode == MODE_WHOLE_WORDS) - ? KateViewConfig::PowerModeWholeWords - : KateViewConfig::PowerModePlainText))); - - } else if (m_incUi != NULL) { - const bool OF_INCREMENTAL = false; - backupConfig(OF_INCREMENTAL); - - // Update incremental search flags only - const long powerFlagsOnly = pastFlags - & (KateViewConfig::PowerMatchCase - | KateViewConfig::PowerFromCursor - | KateViewConfig::PowerHighlightAll - | KateViewConfig::PowerModeRegularExpression - | KateViewConfig::PowerModeEscapeSequences - | KateViewConfig::PowerModeWholeWords - | KateViewConfig::PowerModePlainText); - - futureFlags = powerFlagsOnly - | (m_incHighlightAll ? KateViewConfig::IncHighlightAll : 0) - | (m_incFromCursor ? KateViewConfig::IncFromCursor : 0) - | (m_incMatchCase ? KateViewConfig::IncMatchCase : 0); - } - - // Adjust global config - m_config->setSearchFlags(futureFlags); -} - - - -void KateSearchBar::replaceNext() { - const QString replacement = m_powerUi->replacement->currentText(); - - if (find(SearchForward, &replacement)) { - // Add to search history - addCurrentTextToHistory(m_powerUi->pattern); - - // Add to replace history - addCurrentTextToHistory(m_powerUi->replacement); - } -} - - - -// replacement == NULL --> Highlight all matches -// replacement != NULL --> Replace and highlight all matches -int KateSearchBar::findAll(Range inputRange, const QString * replacement) { - const Search::SearchOptions enabledOptions = searchOptions(SearchForward); - - const bool regexMode = enabledOptions.testFlag(Search::Regex); - const bool multiLinePattern = regexMode ? KateRegExp(searchPattern()).isMultiLine() : false; - - // Before first match - clearHighlights(); - - KTextEditor::MovingRange * workingRange = m_view->doc()->newMovingRange(inputRange); - QList highlightRanges; - int matchCounter = 0; - - bool block = m_view->selection() && m_view->blockSelection(); - int line = inputRange.start().line(); - do { - if (block) - workingRange = m_view->doc()->newMovingRange(m_view->doc()->rangeOnLine(inputRange, line)); - - for (;;) { - KateMatch match(m_view->doc(), enabledOptions); - match.searchText(*workingRange, searchPattern()); - if (!match.isValid()) { - break; - } - bool const originalMatchEmpty = match.isEmpty(); - - // Work with the match - if (replacement != NULL) { - if (matchCounter == 0) { - m_view->document()->startEditing(); - } - - // Replace - const Range afterReplace = match.replace(*replacement, false, ++matchCounter); - - // Highlight and continue after adjusted match - //highlightReplacement(*afterReplace); - highlightRanges << afterReplace; - } else { - // Highlight and continue after original match - //highlightMatch(match); - highlightRanges << match.range(); - matchCounter++; - } - - // Continue after match - if (highlightRanges.last().end() >= workingRange->end()) - break; - KTextEditor::MovingCursor* workingStart = - static_cast(m_view->document())->newMovingCursor(highlightRanges.last().end()); - if (originalMatchEmpty) { - // Can happen for regex patterns like "^". - // If we don't advance here we will loop forever... - workingStart->move(1); - } else if (regexMode && !multiLinePattern && workingStart->atEndOfLine()) { - // single-line regexps might match the naked line end - // therefore we better advance to the next line - workingStart->move(1); - } - workingRange->setRange(*workingStart, workingRange->end()); - - const bool atEndOfDocument = workingStart->atEndOfDocument(); - delete workingStart; - // Are we done? - if (!workingRange->toRange().isValid() || atEndOfDocument) { - break; - } - } - - } while (block && ++line <= inputRange.end().line()); - - // After last match - if (matchCounter > 0) { - if (replacement != NULL) { - m_view->document()->endEditing(); - } - } - - if (replacement == NULL) - foreach (const Range &r, highlightRanges) { - highlightMatch(r); - } - else - foreach (const Range &r, highlightRanges) { - highlightReplacement(r); - } - - delete workingRange; - - return matchCounter; -} - - - -void KateSearchBar::replaceAll() { - // What to find/replace? - const QString replacement = m_powerUi->replacement->currentText(); - - // Where to replace? - Range selection; - const bool selected = m_view->selection(); - Range inputRange = (selected && selectionOnly()) - ? m_view->selectionRange() - : m_view->document()->documentRange(); - - - // Pass on the hard work - int replacementsDone=findAll(inputRange, &replacement); - KPassivePopup::message(i18np("1 replacement has been made","%1 replacements have been made",replacementsDone),this); - - // Add to search history - addCurrentTextToHistory(m_powerUi->pattern); - - // Add to replace history - addCurrentTextToHistory(m_powerUi->replacement); -} - - - -void KateSearchBar::setSearchPattern(const QString &searchPattern) -{ - if (searchPattern == this->searchPattern()) - return; - - if (isPower()) - m_powerUi->pattern->setEditText(searchPattern); - else - m_incUi->pattern->setEditText(searchPattern); -} - - - -QString KateSearchBar::searchPattern() const { - return (m_powerUi != 0) ? m_powerUi->pattern->currentText() - : m_incUi->pattern->currentText(); -} - - - -void KateSearchBar::setSelectionOnly(bool selectionOnly) -{ - if (this->selectionOnly() == selectionOnly) - return; - - if (isPower()) - m_powerUi->selectionOnly->setChecked(selectionOnly); -} - - - - -bool KateSearchBar::selectionOnly() const { - return isPower() ? m_powerUi->selectionOnly->isChecked() - : false; -} - - - -KTextEditor::Search::SearchOptions KateSearchBar::searchOptions(SearchDirection searchDirection) const { - Search::SearchOptions enabledOptions = KTextEditor::Search::Default; - - if (!matchCase()) { - enabledOptions |= Search::CaseInsensitive; - } - - if (searchDirection == SearchBackward) { - enabledOptions |= Search::Backwards; - } - - if (m_powerUi != NULL) { - switch (m_powerUi->searchMode->currentIndex()) { - case MODE_WHOLE_WORDS: - enabledOptions |= Search::WholeWords; - break; - - case MODE_ESCAPE_SEQUENCES: - enabledOptions |= Search::EscapeSequences; - break; - - case MODE_REGEX: - enabledOptions |= Search::Regex; - break; - - case MODE_PLAIN_TEXT: // FALLTHROUGH - default: - break; - - } - } - - return enabledOptions; -} - - - - -struct ParInfo { - int openIndex; - bool capturing; - int captureNumber; // 1..9 -}; - - - -QVector KateSearchBar::getCapturePatterns(const QString & pattern) const { - QVector capturePatterns; - capturePatterns.reserve(9); - QStack parInfos; - - const int inputLen = pattern.length(); - int input = 0; // walker index - bool insideClass = false; - int captureCount = 0; - - while (input < inputLen) { - if (insideClass) { - // Wait for closing, unescaped ']' - if (pattern[input].unicode() == L']') { - insideClass = false; - } - input++; - } - else - { - switch (pattern[input].unicode()) - { - case L'\\': - // Skip this and any next character - input += 2; - break; - - case L'(': - ParInfo curInfo; - curInfo.openIndex = input; - curInfo.capturing = (input + 1 >= inputLen) || (pattern[input + 1].unicode() != '?'); - if (curInfo.capturing) { - captureCount++; - } - curInfo.captureNumber = captureCount; - parInfos.push(curInfo); - - input++; - break; - - case L')': - if (!parInfos.empty()) { - ParInfo & top = parInfos.top(); - if (top.capturing && (top.captureNumber <= 9)) { - const int start = top.openIndex + 1; - const int len = input - start; - if (capturePatterns.size() < top.captureNumber) { - capturePatterns.resize(top.captureNumber); - } - capturePatterns[top.captureNumber - 1] = pattern.mid(start, len); - } - parInfos.pop(); - } - - input++; - break; - - case L'[': - input++; - insideClass = true; - break; - - default: - input++; - break; - - } - } - } - - return capturePatterns; -} - - - -void KateSearchBar::showExtendedContextMenu(bool forPattern, const QPoint& pos) { - // Make original menu - QComboBox* comboBox = forPattern ? m_powerUi->pattern : m_powerUi->replacement; - QMenu* const contextMenu = comboBox->lineEdit()->createStandardContextMenu(); - - if (contextMenu == NULL) { - return; - } - - bool extendMenu = false; - bool regexMode = false; - switch (m_powerUi->searchMode->currentIndex()) { - case MODE_REGEX: - regexMode = true; - // FALLTHROUGH - - case MODE_ESCAPE_SEQUENCES: - extendMenu = true; - break; - - default: - break; - } - - AddMenuManager addMenuManager(contextMenu, 37); - if (!extendMenu) { - addMenuManager.enableMenu(extendMenu); - } else { - // Build menu - if (forPattern) { - if (regexMode) { - addMenuManager.addEntry("^", "", i18n("Beginning of line")); - addMenuManager.addEntry("$", "", i18n("End of line")); - addMenuManager.addSeparator(); - addMenuManager.addEntry(".", "", i18n("Any single character (excluding line breaks)")); - addMenuManager.addSeparator(); - addMenuManager.addEntry("+", "", i18n("One or more occurrences")); - addMenuManager.addEntry("*", "", i18n("Zero or more occurrences")); - addMenuManager.addEntry("?", "", i18n("Zero or one occurrences")); - addMenuManager.addEntry("{a", ",b}", i18n(" through occurrences"), "{", ",}"); - addMenuManager.addSeparator(); - addMenuManager.addEntry("(", ")", i18n("Group, capturing")); - addMenuManager.addEntry("|", "", i18n("Or")); - addMenuManager.addEntry("[", "]", i18n("Set of characters")); - addMenuManager.addEntry("[^", "]", i18n("Negative set of characters")); - addMenuManager.addSeparator(); - } - } else { - addMenuManager.addEntry("\\0", "", i18n("Whole match reference")); - addMenuManager.addSeparator(); - if (regexMode) { - const QString pattern = m_powerUi->pattern->currentText(); - const QVector capturePatterns = getCapturePatterns(pattern); - - const int captureCount = capturePatterns.count(); - for (int i = 1; i <= 9; i++) { - const QString number = QString::number(i); - const QString & captureDetails = (i <= captureCount) - ? (QString(" = (") + capturePatterns[i - 1].left(30)) + QString(")") - : QString(); - addMenuManager.addEntry("\\" + number, "", - i18n("Reference") + ' ' + number + captureDetails); - } - - addMenuManager.addSeparator(); - } - } - - addMenuManager.addEntry("\\n", "", i18n("Line break")); - addMenuManager.addEntry("\\t", "", i18n("Tab")); - - if (forPattern && regexMode) { - addMenuManager.addEntry("\\b", "", i18n("Word boundary")); - addMenuManager.addEntry("\\B", "", i18n("Not word boundary")); - addMenuManager.addEntry("\\d", "", i18n("Digit")); - addMenuManager.addEntry("\\D", "", i18n("Non-digit")); - addMenuManager.addEntry("\\s", "", i18n("Whitespace (excluding line breaks)")); - addMenuManager.addEntry("\\S", "", i18n("Non-whitespace (excluding line breaks)")); - addMenuManager.addEntry("\\w", "", i18n("Word character (alphanumerics plus '_')")); - addMenuManager.addEntry("\\W", "", i18n("Non-word character")); - } - - addMenuManager.addEntry("\\0???", "", i18n("Octal character 000 to 377 (2^8-1)"), "\\0"); - addMenuManager.addEntry("\\x????", "", i18n("Hex character 0000 to FFFF (2^16-1)"), "\\x"); - addMenuManager.addEntry("\\\\", "", i18n("Backslash")); - - if (forPattern && regexMode) { - addMenuManager.addSeparator(); - addMenuManager.addEntry("(?:E", ")", i18n("Group, non-capturing"), "(?:"); - addMenuManager.addEntry("(?=E", ")", i18n("Lookahead"), "(?="); - addMenuManager.addEntry("(?!E", ")", i18n("Negative lookahead"), "(?!"); - } - - if (!forPattern) { - addMenuManager.addSeparator(); - addMenuManager.addEntry("\\L", "", i18n("Begin lowercase conversion")); - addMenuManager.addEntry("\\U", "", i18n("Begin uppercase conversion")); - addMenuManager.addEntry("\\E", "", i18n("End case conversion")); - addMenuManager.addEntry("\\l", "", i18n("Lowercase first character conversion")); - addMenuManager.addEntry("\\u", "", i18n("Uppercase first character conversion")); - addMenuManager.addEntry("\\#[#..]", "", i18n("Replacement counter (for Replace All)"), "\\#"); - } - } - - // Show menu - QAction * const result = contextMenu->exec(comboBox->mapToGlobal(pos)); - if (result != NULL) { - addMenuManager.handle(result, comboBox->lineEdit()); - } -} - - - -void KateSearchBar::onPowerModeChanged(int /*index*/) { - if (m_powerUi->searchMode->currentIndex() == MODE_REGEX) { - m_powerUi->matchCase->setChecked(true); - } - - sendConfig(); - indicateMatch(MatchNothing); - - givePatternFeedback(); -} - - - -/*static*/ void KateSearchBar::nextMatchForSelection(KateView * view, SearchDirection searchDirection) { - const bool selected = view->selection(); - if (selected) { - const QString pattern = view->selectionText(); - - // How to find? - Search::SearchOptions enabledOptions(KTextEditor::Search::Default); - if (searchDirection == SearchBackward) { - enabledOptions |= Search::Backwards; - } - - // Where to find? - const Range selRange = view->selectionRange(); - Range inputRange; - if (searchDirection == SearchForward) { - inputRange.setRange(selRange.end(), view->doc()->documentEnd()); - } else { - inputRange.setRange(Cursor(0, 0), selRange.start()); - } - - // Find, first try - KateMatch match(view->doc(), enabledOptions); - match.searchText(inputRange, pattern); - - if (match.isValid()) { - selectRange(view, match.range()); - } else { - // Find, second try - if (searchDirection == SearchForward) { - inputRange.setRange(Cursor(0, 0), selRange.start()); - } else { - inputRange.setRange(selRange.end(), view->doc()->documentEnd()); - } - KateMatch match2(view->doc(), enabledOptions); - match2.searchText(inputRange, pattern); - if (match2.isValid()) { - selectRange(view, match2.range()); - } - } - } else { - // Select current word so we can search for that the next time - const Cursor cursorPos = view->cursorPosition(); - view->selectWord(cursorPos); - } -} - - - -void KateSearchBar::enterPowerMode() { - QString initialPattern; - bool selectionOnly = false; - - // Guess settings from context: init pattern with current selection - const bool selected = m_view->selection(); - if (selected) { - const Range & selection = m_view->selectionRange(); - if (selection.onSingleLine()) { - // ... with current selection - initialPattern = m_view->selectionText(); - } else { - // Enable selection only - selectionOnly = true; - } - } - - // If there's no new selection, we'll use the existing pattern - if (initialPattern.isNull()) { - // Coming from power search? - const bool fromReplace = (m_powerUi != NULL) && (m_widget->isVisible()); - if (fromReplace) { - QLineEdit * const patternLineEdit = m_powerUi->pattern->lineEdit(); - Q_ASSERT(patternLineEdit != NULL); - patternLineEdit->selectAll(); - m_powerUi->pattern->setFocus(Qt::MouseFocusReason); - return; - } - - // Coming from incremental search? - const bool fromIncremental = (m_incUi != NULL) && (m_widget->isVisible()); - if (fromIncremental) { - initialPattern = m_incUi->pattern->currentText(); - } - } - - // Create dialog - const bool create = (m_powerUi == NULL); - if (create) { - // Kill incremental widget - if (m_incUi != NULL) { - // Backup current settings - const bool OF_INCREMENTAL = false; - backupConfig(OF_INCREMENTAL); - - // Kill widget - delete m_incUi; - m_incUi = NULL; - m_layout->removeWidget(m_widget); - m_widget->deleteLater(); // I didn't get a crash here but for symmetrie to the other mutate slot^ - } - - // Add power widget - m_widget = new QWidget(this); - m_powerUi = new Ui::PowerSearchBar; - m_powerUi->setupUi(m_widget); - m_layout->addWidget(m_widget); - - // Bind to shared history models - m_powerUi->pattern->setDuplicatesEnabled(false); - m_powerUi->pattern->setInsertPolicy(QComboBox::InsertAtTop); - m_powerUi->pattern->setMaxCount(m_config->maxHistorySize()); - m_powerUi->pattern->setModel(m_config->patternHistoryModel()); - m_powerUi->replacement->setDuplicatesEnabled(false); - m_powerUi->replacement->setInsertPolicy(QComboBox::InsertAtTop); - m_powerUi->replacement->setMaxCount(m_config->maxHistorySize()); - m_powerUi->replacement->setModel(m_config->replacementHistoryModel()); - - // Icons - m_powerUi->mutate->setIcon(KIcon("arrow-down-double")); - m_powerUi->findNext->setIcon(KIcon("go-down-search")); - m_powerUi->findPrev->setIcon(KIcon("go-up-search")); - m_powerUi->findAll->setIcon(KIcon("edit-find")); - - // Focus proxy - centralWidget()->setFocusProxy(m_powerUi->pattern); - - // Make completers case-sensitive - QLineEdit * const patternLineEdit = m_powerUi->pattern->lineEdit(); - Q_ASSERT(patternLineEdit != NULL); - patternLineEdit->completer()->setCaseSensitivity(Qt::CaseSensitive); - - QLineEdit * const replacementLineEdit = m_powerUi->replacement->lineEdit(); - Q_ASSERT(replacementLineEdit != NULL); - replacementLineEdit->completer()->setCaseSensitivity(Qt::CaseSensitive); - } - - m_powerUi->selectionOnly->setChecked(selectionOnly); - - // Restore previous settings - if (create) { - m_powerUi->matchCase->setChecked(m_powerMatchCase); - m_powerUi->searchMode->setCurrentIndex(m_powerMode); - } - - // force current index of -1 --> shows 1st completion entry instead of 2nd - m_powerUi->pattern->setCurrentIndex(-1); - m_powerUi->replacement->setCurrentIndex(-1); - - // Set initial search pattern - QLineEdit * const patternLineEdit = m_powerUi->pattern->lineEdit(); - Q_ASSERT(patternLineEdit != NULL); - patternLineEdit->setText(initialPattern); - patternLineEdit->selectAll(); - - // Set initial replacement text - QLineEdit * const replacementLineEdit = m_powerUi->replacement->lineEdit(); - Q_ASSERT(replacementLineEdit != NULL); - replacementLineEdit->setText(""); - - // Propagate settings (slots are still inactive on purpose) - onPowerPatternChanged(initialPattern); - givePatternFeedback(); - - if (create) { - // Slots - connect(m_powerUi->mutate, SIGNAL(clicked()), this, SLOT(enterIncrementalMode())); - connect(patternLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onPowerPatternChanged(const QString &))); - connect(m_powerUi->findNext, SIGNAL(clicked()), this, SLOT(findNext())); - connect(m_powerUi->findPrev, SIGNAL(clicked()), this, SLOT(findPrevious())); - connect(m_powerUi->replaceNext, SIGNAL(clicked()), this, SLOT(replaceNext())); - connect(m_powerUi->replaceAll, SIGNAL(clicked()), this, SLOT(replaceAll())); - connect(m_powerUi->searchMode, SIGNAL(currentIndexChanged(int)), this, SLOT(onPowerModeChanged(int))); - connect(m_powerUi->matchCase, SIGNAL(toggled(bool)), this, SLOT(onMatchCaseToggled(bool))); - connect(m_powerUi->findAll, SIGNAL(clicked()), this, SLOT(findAll())); - - // Make [return] in pattern line edit trigger action - connect(patternLineEdit, SIGNAL(returnPressed()), this, SLOT(onReturnPressed())); - connect(replacementLineEdit, SIGNAL(returnPressed()), this, SLOT(replaceNext())); - - // Hook into line edit context menus - m_powerUi->pattern->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_powerUi->pattern, SIGNAL(customContextMenuRequested(const QPoint&)), this, - SLOT(onPowerPatternContextMenuRequest(const QPoint&))); - m_powerUi->replacement->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_powerUi->replacement, SIGNAL(customContextMenuRequested(const QPoint&)), this, - SLOT(onPowerReplacmentContextMenuRequest(const QPoint&))); - } - - // Focus - if (m_widget->isVisible()) { - m_powerUi->pattern->setFocus(Qt::MouseFocusReason); - } -} - - - -void KateSearchBar::enterIncrementalMode() { - QString initialPattern; - - // Guess settings from context: init pattern with current selection - const bool selected = m_view->selection(); - if (selected) { - const Range & selection = m_view->selectionRange(); - if (selection.onSingleLine()) { - // ... with current selection - initialPattern = m_view->selectionText(); - } - } - - // If there's no new selection, we'll use the existing pattern - if (initialPattern.isNull()) { - // Coming from incremental search? - const bool fromIncremental = (m_incUi != NULL) && (m_widget->isVisible()); - if (fromIncremental) { - m_incUi->pattern->lineEdit()->selectAll(); - m_incUi->pattern->setFocus(Qt::MouseFocusReason); - return; - } - - // Coming from power search? - const bool fromReplace = (m_powerUi != NULL) && (m_widget->isVisible()); - if (fromReplace) { - initialPattern = m_powerUi->pattern->currentText(); - } - } - - // Still no search pattern? Use the word under the cursor - if (initialPattern.isNull()) { - const KTextEditor::Cursor cursorPosition = m_view->cursorPosition(); - initialPattern = m_view->doc()->getWord( cursorPosition ); - } - - // Create dialog - const bool create = (m_incUi == NULL); - if (create) { - // Kill power widget - if (m_powerUi != NULL) { - // Backup current settings - const bool OF_POWER = true; - backupConfig(OF_POWER); - - // Kill widget - delete m_powerUi; - m_powerUi = NULL; - m_layout->removeWidget(m_widget); - m_widget->deleteLater(); //deleteLater, because it's not a good idea too delete the widget and there for the button triggering this slot - } - - // Add incremental widget - m_widget = new QWidget(this); - m_incUi = new Ui::IncrementalSearchBar; - m_incUi->setupUi(m_widget); - m_layout->addWidget(m_widget); - -// new QShortcut(KStandardShortcut::paste().primary(), m_incUi->pattern, SLOT(paste()), 0, Qt::WidgetWithChildrenShortcut); -// if (!KStandardShortcut::paste().alternate().isEmpty()) -// new QShortcut(KStandardShortcut::paste().alternate(), m_incUi->pattern, SLOT(paste()), 0, Qt::WidgetWithChildrenShortcut); - - - // Icons - m_incUi->mutate->setIcon(KIcon("arrow-up-double")); - m_incUi->next->setIcon(KIcon("go-down-search")); - m_incUi->prev->setIcon(KIcon("go-up-search")); - - // Ensure minimum size - m_incUi->pattern->setMinimumWidth(12 * m_incUi->pattern->fontMetrics().height()); - - // Customize status area - m_incUi->status->setTextElideMode(Qt::ElideLeft); - - // Focus proxy - centralWidget()->setFocusProxy(m_incUi->pattern); - - m_incUi->pattern->setDuplicatesEnabled(false); - m_incUi->pattern->setInsertPolicy(QComboBox::InsertAtTop); - m_incUi->pattern->setMaxCount(m_config->maxHistorySize()); - m_incUi->pattern->setModel(m_config->patternHistoryModel()); - m_incUi->pattern->setAutoCompletion(false); - } - - // Restore previous settings - if (create) { - m_incUi->matchCase->setChecked(m_incMatchCase); - } - - // force current index of -1 --> shows 1st completion entry instead of 2nd - m_incUi->pattern->setCurrentIndex(-1); - - // Set initial search pattern - if (!create) - disconnect(m_incUi->pattern, SIGNAL(textChanged(const QString&)), this, SLOT(onIncPatternChanged(const QString&))); - m_incUi->pattern->setEditText(initialPattern); - connect(m_incUi->pattern, SIGNAL(textChanged(const QString&)), this, SLOT(onIncPatternChanged(const QString&))); - m_incUi->pattern->lineEdit()->selectAll(); - - // Propagate settings (slots are still inactive on purpose) - if (initialPattern.isEmpty()) { - // Reset edit color - indicateMatch(MatchNothing); - } - - // Enable/disable next/prev - m_incUi->next->setDisabled(initialPattern.isEmpty()); - m_incUi->prev->setDisabled(initialPattern.isEmpty()); - - if (create) { - // Slots - connect(m_incUi->mutate, SIGNAL(clicked()), this, SLOT(enterPowerMode())); - connect(m_incUi->pattern->lineEdit(), SIGNAL(returnPressed()), this, SLOT(onReturnPressed())); - connect(m_incUi->next, SIGNAL(clicked()), this, SLOT(findNext())); - connect(m_incUi->prev, SIGNAL(clicked()), this, SLOT(findPrevious())); - connect(m_incUi->matchCase, SIGNAL(toggled(bool)), this, SLOT(onMatchCaseToggled(bool))); - } - - // Focus - if (m_widget->isVisible()) { - m_incUi->pattern->setFocus(Qt::MouseFocusReason); - } -} - - -void KateSearchBar::clearHighlights() { - qDeleteAll(m_hlRanges); - m_hlRanges.clear(); -} - - -void KateSearchBar::showEvent(QShowEvent * event) { - // Update init cursor - if (m_incUi != NULL) { - m_incInitCursor = m_view->cursorPosition(); - } - - updateSelectionOnly(); - KateViewBarWidget::showEvent(event); -} - - - -void KateSearchBar::closed() { - // empty, can probably be removed -} - - - -void KateSearchBar::updateSelectionOnly() { - if (m_powerUi == NULL) { - return; - } - - // Re-init "Selection only" checkbox if power search bar open - const bool selected = m_view->selection(); - bool selectionOnly = selected; - if (selected) { - Range const & selection = m_view->selectionRange(); - selectionOnly = !selection.onSingleLine(); - } - m_powerUi->selectionOnly->setChecked(selectionOnly); -} - - -void KateSearchBar::updateIncInitCursor() { - if (m_incUi == NULL) { - return; - } - - // Update init cursor - m_incInitCursor = m_view->cursorPosition(); -} - - -void KateSearchBar::onPowerPatternContextMenuRequest(const QPoint& pos) { - const bool FOR_PATTERN = true; - showExtendedContextMenu(FOR_PATTERN, pos); -} - -void KateSearchBar::onPowerPatternContextMenuRequest() { - onPowerPatternContextMenuRequest(m_powerUi->pattern->mapFromGlobal(QCursor::pos())); -} - - -void KateSearchBar::onPowerReplacmentContextMenuRequest(const QPoint& pos) { - const bool FOR_REPLACEMENT = false; - showExtendedContextMenu(FOR_REPLACEMENT, pos); -} - -void KateSearchBar::onPowerReplacmentContextMenuRequest() { - onPowerReplacmentContextMenuRequest(m_powerUi->replacement->mapFromGlobal(QCursor::pos())); -} - - -bool KateSearchBar::isPower() const { - return m_powerUi != 0; -} - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/search/katesearchbar.h b/part/search/katesearchbar.h deleted file mode 100644 index 40c2839..0000000 --- a/part/search/katesearchbar.h +++ /dev/null @@ -1,191 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009-2010 Bernhard Beschow - * Copyright (C) 2007 Sebastian Pipping - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_SEARCH_BAR_H -#define KATE_SEARCH_BAR_H 1 - -#include "kateviewhelpers.h" -#include "katepartprivate_export.h" - -#include -#include - -class KateView; -class KateViewConfig; -class QVBoxLayout; -class QComboBox; - -namespace Ui { - class IncrementalSearchBar; - class PowerSearchBar; -} - -namespace KTextEditor { - class MovingRange; -} - - -class KATEPART_TESTS_EXPORT KateSearchBar : public KateViewBarWidget { - Q_OBJECT - - friend class SearchBarTest; - -public: - enum SearchMode { - // NOTE: Concrete values are important here - // to work with the combobox index! - MODE_PLAIN_TEXT = 0, - MODE_WHOLE_WORDS = 1, - MODE_ESCAPE_SEQUENCES = 2, - MODE_REGEX = 3 - }; - - enum MatchResult { - MatchFound, - MatchWrappedForward, - MatchWrappedBackward, - MatchMismatch, - MatchNothing, - MatchNeutral - }; - - enum SearchDirection { - SearchForward, - SearchBackward - }; - -public: - explicit KateSearchBar(bool initAsPower, KateView* view, KateViewConfig *config); - ~KateSearchBar(); - - bool isPower() const; - - QString searchPattern() const; - QString replacementPattern() const; - - bool selectionOnly() const; - bool matchCase() const; - - // Only used by KateView - static void nextMatchForSelection(KateView * view, SearchDirection searchDirection); - -public Q_SLOTS: - void setSearchPattern(const QString &searchPattern); - void setReplacePattern(const QString &replacePattern); - void setSearchMode(SearchMode mode); - - void setSelectionOnly(bool selectionOnly); - void setMatchCase(bool matchCase); - - // Called for and + - void findNext(); - void findPrevious(); - void findAll(); - - void replaceNext(); - void replaceAll(); - - // Also used by KateView - void enterPowerMode(); - void enterIncrementalMode(); - - void clearHighlights(); - -protected: - // Overridden - virtual void showEvent(QShowEvent * event); - virtual void closed(); - -private Q_SLOTS: - void onIncPatternChanged(const QString & pattern); - void onMatchCaseToggled(bool matchCase); - - void onReturnPressed(); - void updateSelectionOnly(); - void updateIncInitCursor(); - - void onPowerPatternChanged(const QString & pattern); - - void onPowerModeChanged(int index); - void onPowerPatternContextMenuRequest(); - void onPowerPatternContextMenuRequest(const QPoint&); - void onPowerReplacmentContextMenuRequest(); - void onPowerReplacmentContextMenuRequest(const QPoint&); - -private: - // Helpers - bool find(SearchDirection searchDirection = SearchForward, const QString * replacement = 0); - int findAll(KTextEditor::Range inputRange, const QString * replacement); - - bool isPatternValid() const; - - KTextEditor::Search::SearchOptions searchOptions(SearchDirection searchDirection = SearchForward) const; - - void highlightMatch(const KTextEditor::Range & range); - void highlightReplacement(const KTextEditor::Range & range); - void indicateMatch(MatchResult matchResult); - static void selectRange(KateView * view, const KTextEditor::Range & range); - void selectRange2(const KTextEditor::Range & range); - - QVector getCapturePatterns(const QString & pattern) const; - void showExtendedContextMenu(bool forPattern, const QPoint& pos); - - void givePatternFeedback(); - void addCurrentTextToHistory(QComboBox * combo); - void backupConfig(bool ofPower); - void sendConfig(); - void fixForSingleLine(KTextEditor::Range & range, SearchDirection searchDirection); - -private: - KateView *const m_view; - KateViewConfig *const m_config; - QList m_hlRanges; - - // Shared by both dialogs - QVBoxLayout *const m_layout; - QWidget * m_widget; - - // Incremental search related - Ui::IncrementalSearchBar * m_incUi; - KTextEditor::Cursor m_incInitCursor; - - // Power search related - Ui::PowerSearchBar * m_powerUi; - - // attribute to highlight matches with - KTextEditor::Attribute::Ptr highlightMatchAttribute; - KTextEditor::Attribute::Ptr highlightReplacementAttribute; - - // Status backup - bool m_incHighlightAll : 1; - bool m_incFromCursor : 1; - bool m_incMatchCase : 1; - bool m_powerMatchCase : 1; - bool m_powerFromCursor : 1; - bool m_powerHighlightAll : 1; - unsigned int m_powerMode : 2; -}; - - - -#endif // KATE_SEARCH_BAR_H - -// kate: space-indent on; indent-width 4; replace-tabs on; diff --git a/part/search/searchbarincremental.ui b/part/search/searchbarincremental.ui deleted file mode 100644 index 17ee05e..0000000 --- a/part/search/searchbarincremental.ui +++ /dev/null @@ -1,173 +0,0 @@ - - - Sebastian Pipping - IncrementalSearchBar - - - - 0 - 0 - 734 - 31 - - - - - 0 - 0 - - - - - 0 - - - - - 0 - - - - - F&ind: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - pattern - - - - - - - - 0 - 0 - - - - false - - - Qt::StrongFocus - - - true - - - Text to search for - - - true - - - QComboBox::AdjustToMinimumContentsLengthWithIcon - - - - - - - Jump to next match - - - &Next - - - - - - - - - - - - Jump to previous match - - - &Previous - - - - - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 12 - 26 - - - - - - - - &Match case - - - - - - - - 0 - 0 - - - - - - - Qt::AlignCenter - - - false - - - - - - - Switch to power search and replace bar - - - - - - - - - - - true - - - - - - - - - - KSqueezedTextLabel - QLabel -
ksqueezedtextlabel.h
-
-
- - -
diff --git a/part/search/searchbarpower.ui b/part/search/searchbarpower.ui deleted file mode 100644 index 3add1c0..0000000 --- a/part/search/searchbarpower.ui +++ /dev/null @@ -1,308 +0,0 @@ - - - Sebastian Pipping - PowerSearchBar - - - - 0 - 0 - 569 - 99 - - - - - 0 - 0 - - - - - 0 - - - - - 0 - - - - - F&ind: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - pattern - - - - - - - - 0 - 0 - - - - Qt::StrongFocus - - - Text to search for - - - true - - - QComboBox::AdjustToMinimumContentsLengthWithIcon - - - - - - - Jump to next match - - - &Next - - - - - - - Jump to previous match - - - &Previous - - - - - - - - - - - - Rep&lace: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - replacement - - - - - - - - 0 - 0 - - - - Text to replace with - - - true - - - QComboBox::AdjustToMinimumContentsLengthWithIcon - - - - - - - Replace next match - - - &Replace - - - - - - - Replace all matches - - - Replace &All - - - - - - - Qt::Horizontal - - - - - - - 6 - - - 6 - - - - - - 0 - 0 - - - - Search mode - - - 4 - - - true - - - - Plain text - - - - - Whole words - - - - - Escape sequences - - - - - Regular expression - - - - - - - - Qt::Horizontal - - - - 0 - 20 - - - - - - - - Case-sensitive searching - - - &Match case - - - - - - - Selection &only - - - - - - - - - Mo&de: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - searchMode - - - - - - - &Find All - - - - - - - - - - - Switch to incremental search bar - - - - - - - - - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- - pattern - replacement - findNext - findPrev - replaceNext - replaceAll - searchMode - matchCase - selectionOnly - findAll - mutate - - - -
diff --git a/part/spellcheck/ontheflycheck.cpp b/part/spellcheck/ontheflycheck.cpp deleted file mode 100644 index fd11031..0000000 --- a/part/spellcheck/ontheflycheck.cpp +++ /dev/null @@ -1,940 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2010 by Michel Ludwig - * Copyright (C) 2009 by Joseph Wenninger - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -/* If ever threads should be used again, thread communication and - * synchronization ought to be done with blocking queued signal connections. - */ - -#include "ontheflycheck.h" - -#include - -#include "kateconfig.h" -#include "kateglobal.h" -#include "katerenderer.h" -#include "kateview.h" -#include "spellcheck.h" -#include "spellingmenu.h" - -#define ON_THE_FLY_DEBUG kDebug(debugArea()) - -KateOnTheFlyChecker::KateOnTheFlyChecker(KateDocument *document) -: QObject(document), - m_document(document), - m_backgroundChecker(NULL), - m_currentlyCheckedItem(invalidSpellCheckQueueItem), - m_refreshView(NULL) -{ - ON_THE_FLY_DEBUG << "created"; - - m_viewRefreshTimer = new QTimer(this); - m_viewRefreshTimer->setSingleShot(true); - connect(m_viewRefreshTimer, SIGNAL(timeout()), this, SLOT(viewRefreshTimeout())); - - connect(document, SIGNAL(textInserted(KTextEditor::Document*, const KTextEditor::Range&)), - this, SLOT(textInserted(KTextEditor::Document*, const KTextEditor::Range&))); - connect(document, SIGNAL(textRemoved(KTextEditor::Document*, const KTextEditor::Range&)), - this, SLOT(textRemoved(KTextEditor::Document*, const KTextEditor::Range&))); - connect(document, SIGNAL(viewCreated(KTextEditor::Document*, KTextEditor::View*)), - this, SLOT(addView(KTextEditor::Document*, KTextEditor::View*))); - connect(document, SIGNAL(highlightingModeChanged (KTextEditor::Document*)), - this, SLOT(updateConfig())); - connect(document, SIGNAL(respellCheckBlock(KateDocument*, int, int)), - this, SLOT(handleRespellCheckBlock(KateDocument*, int, int))); - - // load the settings for the speller - updateConfig(); - - foreach(KTextEditor::View* view, document->views()) { - addView(document, view); - } - refreshSpellCheck(); -} - -KateOnTheFlyChecker::~KateOnTheFlyChecker() -{ - freeDocument(); -} - -int KateOnTheFlyChecker::debugArea() -{ - static int s_area = KDebug::registerArea("Kate (On-The-Fly Spellcheck)"); - return s_area; -} - -QPair KateOnTheFlyChecker::getMisspelledItem(const KTextEditor::Cursor &cursor) const -{ - foreach(const MisspelledItem &item, m_misspelledList) { - KTextEditor::MovingRange *movingRange = item.first; - if(movingRange->contains(cursor)) { - return QPair(*movingRange, item.second); - } - } - return QPair(KTextEditor::Range::invalid(), QString()); -} - -QString KateOnTheFlyChecker::dictionaryForMisspelledRange(const KTextEditor::Range& range) const -{ - foreach(const MisspelledItem &item, m_misspelledList) { - KTextEditor::MovingRange *movingRange = item.first; - if(*movingRange == range) { - return item.second; - } - } - return QString(); -} - -void KateOnTheFlyChecker::clearMisspellingForWord(const QString& word) -{ - MisspelledList misspelledList = m_misspelledList; // make a copy - foreach(const MisspelledItem &item, misspelledList) { - KTextEditor::MovingRange *movingRange = item.first; - if(m_document->text(*movingRange) == word) { - deleteMovingRange(movingRange); - } - } -} - -const KateOnTheFlyChecker::SpellCheckItem KateOnTheFlyChecker::invalidSpellCheckQueueItem = - SpellCheckItem(NULL, ""); - -void KateOnTheFlyChecker::handleRespellCheckBlock(KateDocument *kateDocument, int start, int end) -{ - Q_ASSERT(kateDocument == m_document); - Q_UNUSED(kateDocument); - - ON_THE_FLY_DEBUG << start << end; - KTextEditor::Range range(start, 0, end, m_document->lineLength(end)); - bool listEmpty = m_modificationList.isEmpty(); - KTextEditor::MovingRange *movingRange = m_document->newMovingRange(range); - movingRange->setFeedback(this); - // we don't handle this directly as the highlighting information might not be up-to-date yet - m_modificationList.push_back(ModificationItem(TEXT_INSERTED, movingRange)); - ON_THE_FLY_DEBUG << "added" << *movingRange; - if(listEmpty) { - QTimer::singleShot(0, this, SLOT(handleModifiedRanges())); - } -} - -void KateOnTheFlyChecker::textInserted(KTextEditor::Document *document, const KTextEditor::Range &range) -{ - Q_ASSERT(document == m_document); - Q_UNUSED(document); - if(!range.isValid()) { - return; - } - - bool listEmptyAtStart = m_modificationList.isEmpty(); - - // don't consider a range that is not within the document range - const KTextEditor::Range documentIntersection = m_document->documentRange().intersect(range); - if(!documentIntersection.isValid()) { - return; - } - // for performance reasons we only want to schedule spellchecks for ranges that are visible - foreach(KTextEditor::View* i, m_document->views()) { - KateView *view = static_cast(i); - KTextEditor::Range visibleIntersection = documentIntersection.intersect(view->visibleRange()); - if(visibleIntersection.isValid()) { // allow empty intersections - // we don't handle this directly as the highlighting information might not be up-to-date yet - KTextEditor::MovingRange *movingRange = m_document->newMovingRange(visibleIntersection); - movingRange->setFeedback(this); - m_modificationList.push_back(ModificationItem(TEXT_INSERTED, movingRange)); - ON_THE_FLY_DEBUG << "added" << *movingRange; - } - } - - if(listEmptyAtStart && !m_modificationList.isEmpty()) { - QTimer::singleShot(0, this, SLOT(handleModifiedRanges())); - } -} - -void KateOnTheFlyChecker::handleInsertedText(const KTextEditor::Range &range) -{ - KTextEditor::Range consideredRange = range; - ON_THE_FLY_DEBUG << m_document << range; - - bool spellCheckInProgress = m_currentlyCheckedItem != invalidSpellCheckQueueItem; - - if(spellCheckInProgress) { - KTextEditor::MovingRange *spellCheckRange = m_currentlyCheckedItem.first; - if(spellCheckRange->contains(consideredRange)) { - consideredRange = *spellCheckRange; - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(spellCheckRange); - } - else if(consideredRange.contains(*spellCheckRange)) { - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(spellCheckRange); - } - else if(consideredRange.overlaps(*spellCheckRange)) { - consideredRange.expandToRange(*spellCheckRange); - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(spellCheckRange); - } - else { - spellCheckInProgress = false; - } - } - for(QList::iterator i = m_spellCheckQueue.begin(); - i != m_spellCheckQueue.end();) { - KTextEditor::MovingRange *spellCheckRange = (*i).first; - if(spellCheckRange->contains(consideredRange)) { - consideredRange = *spellCheckRange; - ON_THE_FLY_DEBUG << "erasing range " << *i; - i = m_spellCheckQueue.erase(i); - deleteMovingRangeQuickly(spellCheckRange); - } - else if(consideredRange.contains(*spellCheckRange)) { - ON_THE_FLY_DEBUG << "erasing range " << *i; - i = m_spellCheckQueue.erase(i); - deleteMovingRangeQuickly(spellCheckRange); - } - else if(consideredRange.overlaps(*spellCheckRange)) { - consideredRange.expandToRange(*spellCheckRange); - ON_THE_FLY_DEBUG << "erasing range " << *i; - i = m_spellCheckQueue.erase(i); - deleteMovingRangeQuickly(spellCheckRange); - } - else { - ++i; - } - } - KTextEditor::Range spellCheckRange = findWordBoundaries(consideredRange.start(), - consideredRange.end()); - const bool emptyAtStart = m_spellCheckQueue.isEmpty(); - - queueSpellCheckVisibleRange(spellCheckRange); - - if(spellCheckInProgress || (emptyAtStart && !m_spellCheckQueue.isEmpty())) { - QTimer::singleShot(0, this, SLOT(performSpellCheck())); - } -} - -void KateOnTheFlyChecker::textRemoved(KTextEditor::Document *document, const KTextEditor::Range &range) -{ - Q_ASSERT(document == m_document); - Q_UNUSED(document); - if(!range.isValid()) { - return; - } - - bool listEmptyAtStart = m_modificationList.isEmpty(); - - // don't consider a range that is behind the end of the document - const KTextEditor::Range documentIntersection = m_document->documentRange().intersect(range); - if(!documentIntersection.isValid()) { // the intersection might however be empty if the last - return; // word has been removed, for example - } - - // for performance reasons we only want to schedule spellchecks for ranges that are visible - foreach(KTextEditor::View *i, m_document->views()) { - KateView *view = static_cast(i); - KTextEditor::Range visibleIntersection = documentIntersection.intersect(view->visibleRange()); - if(visibleIntersection.isValid()) { // see above - // we don't handle this directly as the highlighting information might not be up-to-date yet - KTextEditor::MovingRange *movingRange = m_document->newMovingRange(visibleIntersection); - movingRange->setFeedback(this); - m_modificationList.push_back(ModificationItem(TEXT_REMOVED, movingRange)); - ON_THE_FLY_DEBUG << "added" << *movingRange << view->visibleRange(); - } - } - if(listEmptyAtStart && !m_modificationList.isEmpty()) { - QTimer::singleShot(0, this, SLOT(handleModifiedRanges())); - } -} - -inline bool rangesAdjacent(const KTextEditor::Range &r1, const KTextEditor::Range &r2) -{ - return (r1.end() == r2.start()) || (r2.end() == r1.start()); -} - -void KateOnTheFlyChecker::handleRemovedText(const KTextEditor::Range &range) -{ - - ON_THE_FLY_DEBUG << range; - - QList rangesToReCheck; - for(QList::iterator i = m_spellCheckQueue.begin(); - i != m_spellCheckQueue.end();) { - KTextEditor::MovingRange *spellCheckRange = (*i).first; - if(rangesAdjacent(*spellCheckRange, range) || spellCheckRange->contains(range)) { - ON_THE_FLY_DEBUG << "erasing range " << *i; - if(!spellCheckRange->isEmpty()) { - rangesToReCheck.push_back(*spellCheckRange); - } - deleteMovingRangeQuickly(spellCheckRange); - i = m_spellCheckQueue.erase(i); - } - else { - ++i; - } - } - bool spellCheckInProgress = m_currentlyCheckedItem != invalidSpellCheckQueueItem; - const bool emptyAtStart = m_spellCheckQueue.isEmpty(); - if(spellCheckInProgress) { - KTextEditor::MovingRange *spellCheckRange = m_currentlyCheckedItem.first; - ON_THE_FLY_DEBUG << *spellCheckRange; - if(m_document->documentRange().contains(*spellCheckRange) - && (rangesAdjacent(*spellCheckRange, range) || spellCheckRange->contains(range)) - && !spellCheckRange->isEmpty()) { - rangesToReCheck.push_back(*spellCheckRange); - ON_THE_FLY_DEBUG << "added the range " << *spellCheckRange; - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(spellCheckRange); - } - else if(spellCheckRange->isEmpty()) { - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(spellCheckRange); - } - else { - spellCheckInProgress = false; - } - } - for(QList::iterator i = rangesToReCheck.begin(); i != rangesToReCheck.end(); ++i) { - queueSpellCheckVisibleRange(*i); - } - - KTextEditor::Range spellCheckRange = findWordBoundaries(range.start(), range.start()); - KTextEditor::Cursor spellCheckEnd = spellCheckRange.end(); - - queueSpellCheckVisibleRange(spellCheckRange); - - if(range.numberOfLines() > 0) { - //FIXME: there is no currently no way of doing this better as we only get notifications for removals of - // of single lines, i.e. we don't know here how many lines have been removed in total - KTextEditor::Cursor nextLineStart(spellCheckEnd.line() + 1, 0); - const KTextEditor::Cursor documentEnd = m_document->documentEnd(); - if(nextLineStart < documentEnd) { - KTextEditor::Range rangeBelow = KTextEditor::Range(nextLineStart, documentEnd); - - const QList& viewList = m_document->views(); - for(QList::const_iterator i = viewList.begin(); i != viewList.end(); ++i) { - KateView *view = static_cast(*i); - const KTextEditor::Range visibleRange = view->visibleRange(); - KTextEditor::Range intersection = visibleRange.intersect(rangeBelow); - if(intersection.isValid()) { - queueSpellCheckVisibleRange(view, intersection); - } - } - } - } - - ON_THE_FLY_DEBUG << "finished"; - if(spellCheckInProgress || (emptyAtStart && !m_spellCheckQueue.isEmpty())) { - QTimer::singleShot(0, this, SLOT(performSpellCheck())); - } -} - -void KateOnTheFlyChecker::freeDocument() -{ - ON_THE_FLY_DEBUG; - - // empty the spell check queue - for(QList::iterator i = m_spellCheckQueue.begin(); - i != m_spellCheckQueue.end();) { - ON_THE_FLY_DEBUG << "erasing range " << *i; - KTextEditor::MovingRange *movingRange = (*i).first; - deleteMovingRangeQuickly(movingRange); - i = m_spellCheckQueue.erase(i); - } - if(m_currentlyCheckedItem != invalidSpellCheckQueueItem) { - KTextEditor::MovingRange *movingRange = m_currentlyCheckedItem.first; - deleteMovingRangeQuickly(movingRange); - } - stopCurrentSpellCheck(); - - MisspelledList misspelledList = m_misspelledList; // make a copy! - foreach(const MisspelledItem &i, misspelledList) { - deleteMovingRange(i.first); - } - m_misspelledList.clear(); - clearModificationList(); -} - -void KateOnTheFlyChecker::performSpellCheck() -{ - if(m_currentlyCheckedItem != invalidSpellCheckQueueItem) { - ON_THE_FLY_DEBUG << "exited as a check is currently in progress"; - return; - } - if(m_spellCheckQueue.isEmpty()) { - ON_THE_FLY_DEBUG << "exited as there is nothing to do"; - return; - } - m_currentlyCheckedItem = m_spellCheckQueue.takeFirst(); - - KTextEditor::MovingRange *spellCheckRange = m_currentlyCheckedItem.first; - const QString& language = m_currentlyCheckedItem.second; - ON_THE_FLY_DEBUG << "for the range " << *spellCheckRange; - // clear all the highlights that are currently present in the range that - // is supposed to be checked - const MovingRangeList highlightsList = installedMovingRanges(*spellCheckRange); // make a copy! - deleteMovingRanges(highlightsList); - - m_currentDecToEncOffsetList.clear(); - KateDocument::OffsetList encToDecOffsetList; - QString text = m_document->decodeCharacters(*spellCheckRange, - m_currentDecToEncOffsetList, - encToDecOffsetList); - ON_THE_FLY_DEBUG << "next spell checking" << text; - if(text.isEmpty()) { // passing an empty string to Sonnet can lead to a bad allocation exception - spellCheckDone(); // (bug 225867) - return; - } - if(m_speller.language() != language) { - m_speller.setLanguage(language); - } - if(!m_backgroundChecker) { - m_backgroundChecker = new Sonnet::BackgroundChecker(m_speller, this); - connect(m_backgroundChecker, - SIGNAL(misspelling(const QString&,int)), - this, - SLOT(misspelling(const QString&,int))); - connect(m_backgroundChecker, SIGNAL(done()), this, SLOT(spellCheckDone())); - -#if KDE_IS_VERSION(4,5,2) -// guard necessary to ensure compilation of KatePart's git repository against <= 4.5.1 - m_backgroundChecker->restore(KGlobal::config().data()); -#endif - } - m_backgroundChecker->setSpeller(m_speller); - m_backgroundChecker->setText(text); // don't call 'start()' after this! -} - -void KateOnTheFlyChecker::removeRangeFromEverything(KTextEditor::MovingRange *movingRange) -{ - Q_ASSERT(m_document == movingRange->document()); - ON_THE_FLY_DEBUG << *movingRange << "(" << movingRange << ")"; - - if(removeRangeFromModificationList(movingRange)) { - return; // range was part of the modification queue, so we don't have - // to look further for it - } - - if(removeRangeFromSpellCheckQueue(movingRange)) { - return; // range was part of the spell check queue, so it cannot have been - // a misspelled range - } - - for(MisspelledList::iterator i = m_misspelledList.begin(); i != m_misspelledList.end();) { - if((*i).first == movingRange) { - i = m_misspelledList.erase(i); - } - else { - ++i; - } - } -} - -bool KateOnTheFlyChecker::removeRangeFromCurrentSpellCheck(KTextEditor::MovingRange *range) -{ - if(m_currentlyCheckedItem != invalidSpellCheckQueueItem - && m_currentlyCheckedItem.first == range) { - stopCurrentSpellCheck(); - return true; - } - return false; -} - -void KateOnTheFlyChecker::stopCurrentSpellCheck() -{ - m_currentDecToEncOffsetList.clear(); - m_currentlyCheckedItem = invalidSpellCheckQueueItem; - if(m_backgroundChecker) { - m_backgroundChecker->stop(); - } -} - -bool KateOnTheFlyChecker::removeRangeFromSpellCheckQueue(KTextEditor::MovingRange *range) -{ - if(removeRangeFromCurrentSpellCheck(range)) { - if(!m_spellCheckQueue.isEmpty()) { - QTimer::singleShot(0, this, SLOT(performSpellCheck())); - } - return true; - } - bool found = false; - for(QList::iterator i = m_spellCheckQueue.begin(); - i != m_spellCheckQueue.end();) { - if((*i).first == range) { - i = m_spellCheckQueue.erase(i); - found = true; - } - else { - ++i; - } - } - return found; -} - -void KateOnTheFlyChecker::rangeEmpty(KTextEditor::MovingRange *range) -{ - ON_THE_FLY_DEBUG << range->start() << range->end() << "(" << range << ")"; - deleteMovingRange (range); -} - -void KateOnTheFlyChecker::rangeInvalid (KTextEditor::MovingRange* range) -{ - ON_THE_FLY_DEBUG << range->start() << range->end() << "(" << range << ")"; - deleteMovingRange (range); -} - -void KateOnTheFlyChecker::mouseEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) -{ - KateView *kateView = static_cast(view); - kateView->spellingMenu()->mouseEnteredMisspelledRange(range); -} - -void KateOnTheFlyChecker::mouseExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) -{ - KateView *kateView = static_cast(view); - kateView->spellingMenu()->mouseExitedMisspelledRange(range); -} - -/** - * It is not enough to use 'caret/Entered/ExitedRange' only as the cursor doesn't move when some - * text has been selected. - **/ -void KateOnTheFlyChecker::caretEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) -{ - KateView *kateView = static_cast(view); - kateView->spellingMenu()->caretEnteredMisspelledRange(range); -} - -void KateOnTheFlyChecker::caretExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) -{ - KateView *kateView = static_cast(view); - kateView->spellingMenu()->caretExitedMisspelledRange(range); -} - -void KateOnTheFlyChecker::deleteMovingRange(KTextEditor::MovingRange *range) -{ - ON_THE_FLY_DEBUG << range; - // remove it from all our structures - removeRangeFromEverything(range); - range->setFeedback(NULL); - foreach(KTextEditor::View *view, m_document->views()) { - static_cast(view)->spellingMenu()->rangeDeleted(range); - } - delete(range); -} - -void KateOnTheFlyChecker::deleteMovingRanges(const QList& list) -{ - foreach(KTextEditor::MovingRange *r, list) { - deleteMovingRange(r); - } -} - -KTextEditor::Range KateOnTheFlyChecker::findWordBoundaries(const KTextEditor::Cursor& begin, - const KTextEditor::Cursor& end) -{ - // FIXME: QTextBoundaryFinder should be ideally used for this, but it is currently - // still broken in Qt - const QRegExp boundaryRegExp("\\b"); - const QRegExp boundaryQuoteRegExp("\\b\\w+'\\w*$"); // handle spell checking of "isn't", "doesn't", etc. - const QRegExp extendedBoundaryRegExp("(\\W|$)"); - const QRegExp extendedBoundaryQuoteRegExp("^\\w*'\\w+\\b"); // see above - KateDocument::OffsetList decToEncOffsetList, encToDecOffsetList; - const int startLine = begin.line(); - const int startColumn = begin.column(); - KTextEditor::Cursor boundaryStart, boundaryEnd; - // first we take care of the start position - const KTextEditor::Range startLineRange(startLine, 0, startLine, m_document->lineLength(startLine)); - QString decodedLineText = m_document->decodeCharacters(startLineRange, - decToEncOffsetList, - encToDecOffsetList); - int translatedColumn = m_document->computePositionWrtOffsets(encToDecOffsetList, - startColumn); - QString text = decodedLineText.mid(0, translatedColumn); - boundaryStart.setLine(startLine); - int match = text.lastIndexOf(boundaryQuoteRegExp); - if(match < 0) { - match = text.lastIndexOf(boundaryRegExp); - } - boundaryStart.setColumn(m_document->computePositionWrtOffsets(decToEncOffsetList, qMax(0, match))); - // and now the end position - const int endLine = end.line(); - const int endColumn = end.column(); - if(endLine != startLine) { - decToEncOffsetList.clear(); - encToDecOffsetList.clear(); - const KTextEditor::Range endLineRange(endLine, 0, endLine, m_document->lineLength(endLine)); - decodedLineText = m_document->decodeCharacters(endLineRange, - decToEncOffsetList, - encToDecOffsetList); - } - translatedColumn = m_document->computePositionWrtOffsets(encToDecOffsetList, - endColumn); - text = decodedLineText.mid(translatedColumn); - boundaryEnd.setLine(endLine); - match = extendedBoundaryQuoteRegExp.indexIn(text); - if(match == 0) { - match = extendedBoundaryQuoteRegExp.matchedLength(); - } - else { - match = extendedBoundaryRegExp.indexIn(text); - } - boundaryEnd.setColumn(m_document->computePositionWrtOffsets(decToEncOffsetList, - translatedColumn + qMax(0, match))); - return KTextEditor::Range(boundaryStart, boundaryEnd); -} - -void KateOnTheFlyChecker::misspelling(const QString &word, int start) -{ - if(m_currentlyCheckedItem == invalidSpellCheckQueueItem) { - ON_THE_FLY_DEBUG << "exited as no spell check is taking place"; - return; - } - int translatedStart = m_document->computePositionWrtOffsets(m_currentDecToEncOffsetList, - start); -// ON_THE_FLY_DEBUG << "misspelled " << word -// << " at line " -// << *m_currentlyCheckedItem.first -// << " column " << start; - - KTextEditor::MovingRange *spellCheckRange = m_currentlyCheckedItem.first; - int line = spellCheckRange->start().line(); - int rangeStart = spellCheckRange->start().column(); - int translatedEnd = m_document->computePositionWrtOffsets(m_currentDecToEncOffsetList, - start + word.length()); - - KTextEditor::MovingRange *movingRange = - m_document->newMovingRange(KTextEditor::Range(line, - rangeStart + translatedStart, - line, - rangeStart + translatedEnd)); - movingRange->setFeedback(this); - KTextEditor::Attribute *attribute = new KTextEditor::Attribute(); - attribute->setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); - attribute->setUnderlineColor(KateRendererConfig::global()->spellingMistakeLineColor()); - - // don't print this range - movingRange->setAttributeOnlyForViews (true); - - movingRange->setAttribute(KTextEditor::Attribute::Ptr(attribute)); - m_misspelledList.push_back(MisspelledItem(movingRange, m_currentlyCheckedItem.second)); - - if(m_backgroundChecker) { - m_backgroundChecker->continueChecking(); - } -} - -void KateOnTheFlyChecker::spellCheckDone() -{ - ON_THE_FLY_DEBUG << "on-the-fly spell check done, queue length " << m_spellCheckQueue.size(); - if(m_currentlyCheckedItem == invalidSpellCheckQueueItem) { - return; - } - KTextEditor::MovingRange *movingRange = m_currentlyCheckedItem.first; - stopCurrentSpellCheck(); - deleteMovingRangeQuickly(movingRange); - - if(!m_spellCheckQueue.empty()) { - QTimer::singleShot(0, this, SLOT(performSpellCheck())); - } -} - -QList KateOnTheFlyChecker::installedMovingRanges(const KTextEditor::Range& range) -{ - ON_THE_FLY_DEBUG << range; - MovingRangeList toReturn; - - for(QList::iterator i = m_misspelledList.begin(); - i != m_misspelledList.end(); ++i) { - KTextEditor::MovingRange *movingRange = (*i).first; - if(movingRange->overlaps(range)) { - toReturn.push_back(movingRange); - } - } - return toReturn; -} - -void KateOnTheFlyChecker::updateConfig() -{ - ON_THE_FLY_DEBUG; - m_speller.restore(KGlobal::config().data()); - -#if KDE_IS_VERSION(4,5,2) -// guard necessary to ensure compilation of KatePart's git repository against <= 4.5.1 - if(m_backgroundChecker) { - m_backgroundChecker->restore(KGlobal::config().data()); - } -#endif -} - -void KateOnTheFlyChecker::refreshSpellCheck(const KTextEditor::Range &range) -{ - if(range.isValid()) { - textInserted(m_document, range); - } - else { - freeDocument(); - textInserted(m_document, m_document->documentRange()); - } -} - -void KateOnTheFlyChecker::addView(KTextEditor::Document *document, KTextEditor::View *view) -{ - Q_ASSERT(document == m_document); - Q_UNUSED(document); - ON_THE_FLY_DEBUG; - connect(view, SIGNAL(destroyed(QObject*)), this, SLOT(viewDestroyed(QObject*))); - connect(view, SIGNAL(displayRangeChanged(KateView*)), this, SLOT(restartViewRefreshTimer(KateView*))); - updateInstalledMovingRanges(static_cast(view)); -} - -void KateOnTheFlyChecker::viewDestroyed(QObject* obj) -{ - ON_THE_FLY_DEBUG; - KTextEditor::View *view = static_cast(obj); - m_displayRangeMap.remove(view); -} - -void KateOnTheFlyChecker::removeView(KTextEditor::View *view) -{ - ON_THE_FLY_DEBUG; - m_displayRangeMap.remove(view); -} - -void KateOnTheFlyChecker::updateInstalledMovingRanges(KateView *view) -{ - Q_ASSERT(m_document == view->document()); - ON_THE_FLY_DEBUG; - KTextEditor::Range oldDisplayRange = m_displayRangeMap[view]; - - KTextEditor::Range newDisplayRange = view->visibleRange(); - ON_THE_FLY_DEBUG << "new range: " << newDisplayRange; - ON_THE_FLY_DEBUG << "old range: " << oldDisplayRange; - QList toDelete; - foreach(const MisspelledItem &item, m_misspelledList) { - KTextEditor::MovingRange *movingRange = item.first; - if(!movingRange->overlaps(newDisplayRange)) { - bool stillVisible = false; - foreach(KTextEditor::View *it2, m_document->views()) { - KateView *view2 = static_cast(it2); - if(view != view2 && movingRange->overlaps(view2->visibleRange())) { - stillVisible = true; - break; - } - } - if(!stillVisible) { - toDelete.push_back(movingRange); - } - } - } - deleteMovingRanges (toDelete); - m_displayRangeMap[view] = newDisplayRange; - if(oldDisplayRange.isValid()) { - bool emptyAtStart = m_spellCheckQueue.empty(); - for(int line = newDisplayRange.end().line(); line >= newDisplayRange.start().line(); --line) { - if(!oldDisplayRange.containsLine(line)) { - bool visible = false; - foreach(KTextEditor::View *it2, m_document->views()) { - KateView *view2 = static_cast(it2); - if(view != view2 && view2->visibleRange().containsLine(line)) { - visible = true; - break; - } - } - if(!visible) { - queueLineSpellCheck(m_document, line); - } - } - } - if(emptyAtStart && !m_spellCheckQueue.isEmpty()) { - QTimer::singleShot(0, this, SLOT(performSpellCheck())); - } - } -} - -void KateOnTheFlyChecker::queueSpellCheckVisibleRange(const KTextEditor::Range& range) -{ - const QList& viewList = m_document->views(); - for(QList::const_iterator i = viewList.begin(); i != viewList.end(); ++i) { - queueSpellCheckVisibleRange(static_cast(*i), range); - } -} - -void KateOnTheFlyChecker::queueSpellCheckVisibleRange(KateView *view, const KTextEditor::Range& range) -{ - Q_ASSERT(m_document == view->doc()); - KTextEditor::Range visibleRange = view->visibleRange(); - KTextEditor::Range intersection = visibleRange.intersect(range); - if(intersection.isEmpty()) { - return; - } - - // clear all the highlights that are currently present in the range that - // is supposed to be checked, necessary due to highlighting - const MovingRangeList highlightsList = installedMovingRanges(intersection); - deleteMovingRanges(highlightsList); - - QList > spellCheckRanges - = KateGlobal::self()->spellCheckManager()->spellCheckRanges(m_document, - intersection, - true); - //we queue them up in reverse - QListIterator > i(spellCheckRanges); - i.toBack(); - while(i.hasPrevious()) { - QPair p = i.previous(); - queueLineSpellCheck(p.first, p.second); - } -} - -void KateOnTheFlyChecker::queueLineSpellCheck(KateDocument *kateDocument, int line) -{ - const KTextEditor::Range range = KTextEditor::Range(line, 0, line, kateDocument->lineLength(line)); - // clear all the highlights that are currently present in the range that - // is supposed to be checked, necessary due to highlighting - - const MovingRangeList highlightsList = installedMovingRanges(range); - deleteMovingRanges(highlightsList); - - QList > spellCheckRanges - = KateGlobal::self()->spellCheckManager()->spellCheckRanges(kateDocument, - range, - true); - //we queue them up in reverse - QListIterator > i(spellCheckRanges); - i.toBack(); - while(i.hasPrevious()) { - QPair p = i.previous(); - queueLineSpellCheck(p.first, p.second); - } -} - -void KateOnTheFlyChecker::queueLineSpellCheck(const KTextEditor::Range& range, const QString& dictionary) -{ - ON_THE_FLY_DEBUG << m_document << range; - - Q_ASSERT(range.onSingleLine()); - - if(range.isEmpty()) { - return; - } - - addToSpellCheckQueue(range, dictionary); -} - -void KateOnTheFlyChecker::addToSpellCheckQueue(const KTextEditor::Range& range, const QString& dictionary) -{ - addToSpellCheckQueue(m_document->newMovingRange(range), dictionary); -} - -void KateOnTheFlyChecker::addToSpellCheckQueue(KTextEditor::MovingRange *range, const QString& dictionary) -{ - ON_THE_FLY_DEBUG << m_document << *range << dictionary; - - range->setFeedback(this); - - // if the queue contains a subrange of 'range', we remove that one - for(QList::iterator i = m_spellCheckQueue.begin(); - i != m_spellCheckQueue.end();) { - KTextEditor::MovingRange *spellCheckRange = (*i).first; - if(range->contains(*spellCheckRange)) { - deleteMovingRangeQuickly(spellCheckRange); - i = m_spellCheckQueue.erase(i); - } - else { - ++i; - } - } - // leave 'push_front' here as it is a LIFO queue, i.e. a stack - m_spellCheckQueue.push_front(SpellCheckItem(range, dictionary)); - ON_THE_FLY_DEBUG << "added" - << *range << dictionary - << "to the queue, which has a length of" << m_spellCheckQueue.size(); -} - -void KateOnTheFlyChecker::viewRefreshTimeout() -{ - if(m_refreshView) { - updateInstalledMovingRanges(m_refreshView); - } - m_refreshView = NULL; -} - -void KateOnTheFlyChecker::restartViewRefreshTimer(KateView *view) -{ - if(m_refreshView && view != m_refreshView) { // a new view should be refreshed - updateInstalledMovingRanges(m_refreshView); // so refresh the old one first - } - m_refreshView = view; - m_viewRefreshTimer->start(100); -} - -void KateOnTheFlyChecker::deleteMovingRangeQuickly(KTextEditor::MovingRange *range) -{ - range->setFeedback(NULL); - foreach(KTextEditor::View *view, m_document->views()) { - static_cast(view)->spellingMenu()->rangeDeleted(range); - } - delete(range); -} - -void KateOnTheFlyChecker::handleModifiedRanges() -{ - foreach(const ModificationItem &item, m_modificationList) { - KTextEditor::MovingRange *movingRange = item.second; - KTextEditor::Range range = *movingRange; - deleteMovingRangeQuickly(movingRange); - if(item.first == TEXT_INSERTED) { - handleInsertedText(range); - } - else { - handleRemovedText(range); - } - } - m_modificationList.clear(); -} - -bool KateOnTheFlyChecker::removeRangeFromModificationList(KTextEditor::MovingRange *range) -{ - bool found = false; - for(ModificationList::iterator i = m_modificationList.begin(); i != m_modificationList.end();) { - ModificationItem item = *i; - KTextEditor::MovingRange *movingRange = item.second; - if(movingRange == range) { - found = true; - i = m_modificationList.erase(i); - } - else { - ++i; - } - } - return found; -} - -void KateOnTheFlyChecker::clearModificationList() -{ - foreach(const ModificationItem &item, m_modificationList) { - KTextEditor::MovingRange *movingRange = item.second; - deleteMovingRangeQuickly(movingRange); - } - m_modificationList.clear(); -} - -#include "ontheflycheck.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/ontheflycheck.h b/part/spellcheck/ontheflycheck.h deleted file mode 100644 index 991f7d0..0000000 --- a/part/spellcheck/ontheflycheck.h +++ /dev/null @@ -1,143 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2010 by Michel Ludwig - * Copyright (C) 2009 by Joseph Wenninger - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef ONTHEFLYCHECK_H -#define ONTHEFLYCHECK_H - -#include -#include -#include -#include -#include -#include - -#include - -#include "katedocument.h" - -namespace Sonnet { - class BackgroundChecker; -} - -class KateOnTheFlyChecker : public QObject, private KTextEditor::MovingRangeFeedback { - Q_OBJECT - - enum ModificationType {TEXT_INSERTED = 0, TEXT_REMOVED}; - - typedef QPair SpellCheckItem; - typedef QList MovingRangeList; - typedef QPair MisspelledItem; - typedef QList MisspelledList; - - typedef QPair ModificationItem; - typedef QList ModificationList; - - public: - KateOnTheFlyChecker(KateDocument *document); - ~KateOnTheFlyChecker(); - - static int debugArea(); - - QPair getMisspelledItem(const KTextEditor::Cursor &cursor) const; - QString dictionaryForMisspelledRange(const KTextEditor::Range& range) const; - - void clearMisspellingForWord(const QString& word); - - public Q_SLOTS: - void textInserted(KTextEditor::Document *document, const KTextEditor::Range &range); - void textRemoved(KTextEditor::Document *document, const KTextEditor::Range &range); - - void updateConfig(); - void refreshSpellCheck(const KTextEditor::Range &range = KTextEditor::Range::invalid()); - - void updateInstalledMovingRanges(KateView *view); - - protected: - KateDocument *const m_document; - Sonnet::Speller m_speller; - QList m_spellCheckQueue; - Sonnet::BackgroundChecker *m_backgroundChecker; - SpellCheckItem m_currentlyCheckedItem; - static const SpellCheckItem invalidSpellCheckQueueItem; - MisspelledList m_misspelledList; - ModificationList m_modificationList; - KateDocument::OffsetList m_currentDecToEncOffsetList; - QMap m_displayRangeMap; - - void freeDocument(); - - MovingRangeList installedMovingRanges(const KTextEditor::Range& range); - - void queueLineSpellCheck(KateDocument *document, int line); - /** - * 'range' must be on a single line - **/ - void queueLineSpellCheck(const KTextEditor::Range& range, const QString& dictionary); - void queueSpellCheckVisibleRange(const KTextEditor::Range& range); - void queueSpellCheckVisibleRange(KateView *view, const KTextEditor::Range& range); - - void addToSpellCheckQueue(const KTextEditor::Range& range, const QString& dictionary); - void addToSpellCheckQueue(KTextEditor::MovingRange *range, const QString& dictionary); - - QTimer *m_viewRefreshTimer; - QPointer m_refreshView; - - virtual void removeRangeFromEverything(KTextEditor::MovingRange *range); - bool removeRangeFromCurrentSpellCheck(KTextEditor::MovingRange *range); - bool removeRangeFromSpellCheckQueue(KTextEditor::MovingRange *range); - virtual void rangeEmpty(KTextEditor::MovingRange *range); - virtual void rangeInvalid (KTextEditor::MovingRange* range); - virtual void mouseEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view); - virtual void mouseExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view); - virtual void caretEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view); - virtual void caretExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view); - - KTextEditor::Range findWordBoundaries(const KTextEditor::Cursor& begin, - const KTextEditor::Cursor& end); - - void deleteMovingRange(KTextEditor::MovingRange *range); - void deleteMovingRanges(const QList& list); - void deleteMovingRangeQuickly(KTextEditor::MovingRange *range); - void stopCurrentSpellCheck(); - - protected Q_SLOTS: - void performSpellCheck(); - void misspelling(const QString &word, int start); - void spellCheckDone(); - - void viewDestroyed(QObject* obj); - void addView(KTextEditor::Document *document, KTextEditor::View *view); - void removeView(KTextEditor::View *view); - - void restartViewRefreshTimer(KateView *view); - void viewRefreshTimeout(); - - void handleModifiedRanges(); - void handleInsertedText(const KTextEditor::Range &range); - void handleRemovedText(const KTextEditor::Range &range); - void handleRespellCheckBlock(KateDocument *document, int start, int end); - bool removeRangeFromModificationList(KTextEditor::MovingRange *range); - void clearModificationList(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/prefixstore.cpp b/part/spellcheck/prefixstore.cpp deleted file mode 100644 index 3252890..0000000 --- a/part/spellcheck/prefixstore.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "prefixstore.h" - -#include - -#include "katetextline.h" - -KatePrefixStore::KatePrefixStore() -: m_longestPrefixLength(0), - m_lastAssignedState(0) -{ -} - -KatePrefixStore::~KatePrefixStore() -{ -} - -void KatePrefixStore::addPrefix(const QString& prefix) -{ - if(prefix.isEmpty()) { - return; - } - if(m_prefixSet.contains(prefix)) { - return; - } - unsigned long long state = 0; - for(int i = 0; i < prefix.length(); ++i) { - QChar c = prefix.at(i); - - CharToOccurrenceStateHash& hash = m_transitionFunction[state]; - CharToOccurrenceStateHash::iterator it = hash.find(c.unicode()); - if(it == hash.end()) { - state = nextFreeState(); - hash[c.unicode()] = QPair(1, state); - continue; - } - - ++(*it).first; - state = (*it).second; - } - // add the last state as accepting state - m_acceptingStates.insert(state); - - m_prefixSet.insert(prefix); - - if(prefix.length() > m_longestPrefixLength) { - m_longestPrefixLength = prefix.length(); - } -} - -void KatePrefixStore::removePrefix(const QString& prefix) -{ - if(prefix.isEmpty()) { - return; - } - if(!m_prefixSet.contains(prefix)) { - return; - } - m_prefixSet.remove(prefix); - - unsigned long long state = 0; - for(int i = 0; i < prefix.length(); ++i) { - QChar c = prefix.at(i); - - CharToOccurrenceStateHash& hash = m_transitionFunction[state]; - CharToOccurrenceStateHash::iterator it = hash.find(c.unicode()); - if(it == hash.end()) { - continue; - } - - state = (*it).second; - if(m_acceptingStates.contains(state) && i == prefix.length() - 1) { - m_acceptingStates.remove(state); - } - - if((*it).first <= 1) { - hash.erase(it); - m_stateFreeList.push_back(state); - } - else { - --(*it).first; - } - } - - if(prefix.length() == m_longestPrefixLength) { - m_longestPrefixLength = computeLongestPrefixLength(); - } -} - -void KatePrefixStore::dump() -{ - for(unsigned long long i = 0; i < m_lastAssignedState; ++i) { - CharToOccurrenceStateHash& hash = m_transitionFunction[i]; - for(CharToOccurrenceStateHash::iterator it = hash.begin(); it != hash.end(); ++it) { - kDebug() << i << "x" << QChar(it.key()) << "->" << it.value().first << "x" << it.value().second; - } - } - kDebug() << "Accepting states" << m_acceptingStates; -} - -QString KatePrefixStore::findPrefix(const QString& s, int start) const -{ - unsigned long long state = 0; - for(int i = start; i < s.length(); ++i) { - QChar c = s.at(i); - const CharToOccurrenceStateHash& hash = m_transitionFunction[state]; - CharToOccurrenceStateHash::const_iterator it = hash.find(c.unicode()); - if(it == hash.end()) { - return QString(); - } - - state = (*it).second; - if(m_acceptingStates.contains(state)) { - return s.mid(start, i + 1 - start); - } - } - return QString(); -} - -QString KatePrefixStore::findPrefix(const Kate::TextLine& line, int start) const -{ - unsigned long long state = 0; - for(int i = start; i < line->length(); ++i) { - QChar c = line->at(i); - const CharToOccurrenceStateHash& hash = m_transitionFunction[state]; - CharToOccurrenceStateHash::const_iterator it = hash.find(c.unicode()); - if(it == hash.end()) { - return QString(); - } - - state = (*it).second; - if(m_acceptingStates.contains(state)) { - return line->string(start, i + 1 - start); - } - } - return QString(); -} - -int KatePrefixStore::longestPrefixLength() const -{ - return m_longestPrefixLength; -} - -void KatePrefixStore::clear() -{ - m_longestPrefixLength = 0; - m_prefixSet.clear(); - m_transitionFunction.clear(); - m_acceptingStates.clear(); - m_stateFreeList.clear(); - m_lastAssignedState = 0; -} - -int KatePrefixStore::computeLongestPrefixLength() -{ - int toReturn = 0; - for(QSet::iterator i = m_prefixSet.begin(); - i != m_prefixSet.end(); ++i) { - kDebug() << "length" << (*i).length(); - toReturn = qMax(toReturn, (*i).length()); - } - return toReturn; -} - -unsigned long long KatePrefixStore::nextFreeState() -{ - if(!m_stateFreeList.isEmpty()) { - return m_stateFreeList.takeFirst(); - } - return ++m_lastAssignedState; -} diff --git a/part/spellcheck/prefixstore.h b/part/spellcheck/prefixstore.h deleted file mode 100644 index 465e3a8..0000000 --- a/part/spellcheck/prefixstore.h +++ /dev/null @@ -1,88 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2009 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef PREFIXSTORE_H -#define PREFIXSTORE_H - -#include -#include -#include -#include -#include -#include - -#include "katetextline.h" - -/** - * This class can be used to efficiently search for occurrences of strings in - * a given string. Theoretically speaking, a finite deterministic automaton is - * constructed which exactly accepts the strings that are to be recognized. In - * order to check whether a given string contains one of the strings that are being - * searched for the constructed automaton has to applied on each position in the - * given string. - **/ -class KatePrefixStore { - public: - typedef QPair BooleanPair; - - KatePrefixStore(); - virtual ~KatePrefixStore(); - - void addPrefix(const QString& prefix); - void removePrefix(const QString& prefix); - - /** - * Returns the shortest prefix of the given string that is contained in - * this prefix store starting at position 'start'. - **/ - QString findPrefix(const QString& s, int start = 0) const; - - /** - * Returns the shortest prefix of the given string that is contained in - * this prefix store starting at position 'start'. - **/ - QString findPrefix(const Kate::TextLine& line, int start = 0) const; - - int longestPrefixLength() const; - - void clear(); - - void dump(); - - protected: - int m_longestPrefixLength; - QSet m_prefixSet; - - // State x Char -> Nr. of char occurrences in prefixes x State - typedef QHash > CharToOccurrenceStateHash; - typedef QHash TransitionFunction; - TransitionFunction m_transitionFunction; - QSet m_acceptingStates; - QList m_stateFreeList; - unsigned long long m_lastAssignedState; - - int computeLongestPrefixLength(); - unsigned long long nextFreeState(); -// bool containsPrefixOfLengthEndingWith(int length, const QChar& c); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellcheck.cpp b/part/spellcheck/spellcheck.cpp deleted file mode 100644 index 83fa6ad..0000000 --- a/part/spellcheck/spellcheck.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -/* If ever threads should be used again, thread communication and - * synchronization ought to be done with blocking queued signal connections. - */ - -#include "spellcheck.h" - -#include -#include -#include - -#include -#include -#include - -#include "katedocument.h" -#include "katehighlight.h" - -KateSpellCheckManager::KateSpellCheckManager(QObject *parent) -: QObject(parent) -{ -} - -KateSpellCheckManager::~KateSpellCheckManager() -{ -} - -QStringList KateSpellCheckManager::suggestions(const QString& word, const QString& dictionary) -{ - Sonnet::Speller speller; - speller.setLanguage(dictionary); - return speller.suggest(word); -} - -void KateSpellCheckManager::ignoreWord(const QString& word, const QString& dictionary) -{ - Sonnet::Speller speller; - speller.setLanguage(dictionary); - speller.addToSession(word); -} - -void KateSpellCheckManager::addToDictionary(const QString& word, const QString& dictionary) -{ - Sonnet::Speller speller; - speller.setLanguage(dictionary); - speller.addToPersonal(word); -} - -QList KateSpellCheckManager::rangeDifference(const KTextEditor::Range& r1, - const KTextEditor::Range& r2) -{ - Q_ASSERT(r1.contains(r2)); - QList toReturn; - KTextEditor::Range before(r1.start(), r2.start()); - KTextEditor::Range after(r2.end(), r1.end()); - if(!before.isEmpty()) { - toReturn.push_back(before); - } - if(!after.isEmpty()) { - toReturn.push_back(after); - } - return toReturn; -} - -namespace { - bool lessThanRangeDictionaryPair(const QPair &s1, - const QPair &s2) - { - return s1.first.end() <= s2.first.start(); - } -} - -QList > KateSpellCheckManager::spellCheckLanguageRanges(KateDocument *doc, - const KTextEditor::Range& range) -{ - QString defaultDict = doc->defaultDictionary(); - QList toReturn; - QList > dictionaryRanges = doc->dictionaryRanges(); - if(dictionaryRanges.isEmpty()) { - toReturn.push_back(RangeDictionaryPair(range, defaultDict)); - return toReturn; - } - QList splitQueue; - splitQueue.push_back(range); - while(!splitQueue.isEmpty()) { - bool handled = false; - KTextEditor::Range consideredRange = splitQueue.takeFirst(); - for(QList >::iterator i = dictionaryRanges.begin(); - i != dictionaryRanges.end(); ++i) { - KTextEditor::Range languageRange = *((*i).first); - KTextEditor::Range intersection = languageRange.intersect(consideredRange); - if(intersection.isEmpty()) { - continue; - } - toReturn.push_back(RangeDictionaryPair(intersection, (*i).second)); - splitQueue += rangeDifference(consideredRange, intersection); - handled = true; - break; - } - if(!handled) { - // 'consideredRange' did not intersect with any dictionary range, so we add it with the default dictionary - toReturn.push_back(RangeDictionaryPair(consideredRange, defaultDict)); - } - } - // finally, we still have to sort the list - qStableSort(toReturn.begin(), toReturn.end(), lessThanRangeDictionaryPair); - return toReturn; -} - -QList > KateSpellCheckManager::spellCheckWrtHighlightingRanges(KateDocument *document, - const KTextEditor::Range& range, - const QString& dictionary, - bool singleLine, - bool returnSingleRange) -{ - QList > toReturn; - if(range.isEmpty()) { - return toReturn; - } - - KateHighlighting *highlighting = document->highlight(); - - QList rangesToSplit; - if(!singleLine || range.onSingleLine()) { - rangesToSplit.push_back(range); - } - else { - const int startLine = range.start().line(); - const int startColumn = range.start().column(); - const int endLine = range.end().line(); - const int endColumn = range.end().column(); - for(int line = startLine; line <= endLine; ++line) { - const int start = (line == startLine) ? startColumn : 0; - const int end = (line == endLine) ? endColumn : document->lineLength(line); - KTextEditor::Range toAdd(line, start, line, end); - if(!toAdd.isEmpty()) { - rangesToSplit.push_back(toAdd); - } - } - } - for(QList::iterator i = rangesToSplit.begin(); i != rangesToSplit.end(); ++i) { - KTextEditor::Range rangeToSplit = *i; - KTextEditor::Cursor begin = KTextEditor::Cursor::invalid(); - const int startLine = rangeToSplit.start().line(); - const int startColumn = rangeToSplit.start().column(); - const int endLine = rangeToSplit.end().line(); - const int endColumn = rangeToSplit.end().column(); - bool inSpellCheckArea = false; - for(int line = startLine; line <= endLine; ++line) { - Kate::TextLine kateTextLine = document->kateTextLine(line); - const int start = (line == startLine) ? startColumn : 0; - const int end = (line == endLine) ? endColumn : kateTextLine->length(); - const KTextEditor::Cursor startCursor(); - for(int i = start; i < end;) { // WARNING: 'i' has to be incremented manually! - int attr = kateTextLine->attribute(i); - const KatePrefixStore& prefixStore = highlighting->getCharacterEncodingsPrefixStore(attr); - QString prefixFound = prefixStore.findPrefix(kateTextLine, i); - unsigned int attribute = kateTextLine->attribute(i); - if(!document->highlight()->attributeRequiresSpellchecking(attribute) - && prefixFound.isEmpty()) { - if(i == start) { - ++i; - continue; - } - else if(inSpellCheckArea) { - KTextEditor::Range spellCheckRange(begin, KTextEditor::Cursor(line, i)); - // work around Qt bug 6498 - trimRange(document, spellCheckRange); - if(!spellCheckRange.isEmpty()) { - toReturn.push_back(RangeDictionaryPair(spellCheckRange, dictionary)); - if(returnSingleRange) { - return toReturn; - } - } - begin = KTextEditor::Cursor::invalid(); - inSpellCheckArea = false; - } - } - else if(!inSpellCheckArea) { - begin = KTextEditor::Cursor(line, i); - inSpellCheckArea = true; - } - if(!prefixFound.isEmpty()) { - i += prefixFound.length(); - } - else { - ++i; - } - } - } - if(inSpellCheckArea) { - KTextEditor::Range spellCheckRange(begin, rangeToSplit.end()); - // work around Qt bug 6498 - trimRange(document, spellCheckRange); - if(!spellCheckRange.isEmpty()) { - toReturn.push_back(RangeDictionaryPair(spellCheckRange, dictionary)); - if(returnSingleRange) { - return toReturn; - } - } - } - } - - return toReturn; -} - -QList > KateSpellCheckManager::spellCheckRanges(KateDocument *doc, - const KTextEditor::Range& range, - bool singleLine) -{ - QList toReturn; - QList languageRangeList = spellCheckLanguageRanges(doc, range); - for(QList::iterator i = languageRangeList.begin(); i != languageRangeList.end(); ++i) { - const RangeDictionaryPair& p = *i; - toReturn += spellCheckWrtHighlightingRanges(doc, p.first, p.second, singleLine); - } - return toReturn; -} - -void KateSpellCheckManager::replaceCharactersEncodedIfNecessary(const QString& newWord, KateDocument *doc, - const KTextEditor::Range& replacementRange) -{ - const QString replacedString = doc->text(replacementRange); - int attr = doc->kateTextLine(replacementRange.start().line())->attribute(replacementRange.start().column()); - int p = doc->highlight()->getEncodedCharactersInsertionPolicy(attr); - - if((p == KateDocument::EncodeAlways) - || (p == KateDocument::EncodeWhenPresent && doc->containsCharacterEncoding(replacementRange))) { - doc->replaceText(replacementRange, newWord); - doc->replaceCharactersByEncoding(KTextEditor::Range(replacementRange.start(), - replacementRange.start() + KTextEditor::Cursor(0, newWord.length()))); - } - else { - doc->replaceText(replacementRange, newWord); - } -} - -void KateSpellCheckManager::trimRange(KateDocument *doc, KTextEditor::Range &r) -{ - if(r.isEmpty()) { - return; - } - KTextEditor::Cursor cursor = r.start(); - while(cursor < r.end()) { - if(doc->lineLength(cursor.line()) > 0 - && !doc->character(cursor).isSpace() && doc->character(cursor).category() != QChar::Other_Control) { - break; - } - cursor.setColumn(cursor.column() + 1); - if(cursor.column() >= doc->lineLength(cursor.line())) { - cursor.setPosition(cursor.line() + 1, 0); - } - } - r.start() = cursor; - if(r.isEmpty()) { - return; - } - - cursor = r.end(); - KTextEditor::Cursor prevCursor = cursor; - // the range cannot be empty now - do { - prevCursor = cursor; - if(cursor.column() <= 0) { - cursor.setPosition(cursor.line() - 1, doc->lineLength(cursor.line() - 1)); - } - else { - cursor.setColumn(cursor.column() - 1); - } - if(cursor.column() < doc->lineLength(cursor.line()) - && !doc->character(cursor).isSpace() && doc->character(cursor).category() != QChar::Other_Control) { - break; - } - } - while(cursor > r.start()); - r.end() = prevCursor; -} - -#include "spellcheck.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellcheck.h b/part/spellcheck/spellcheck.h deleted file mode 100644 index 87d5d53..0000000 --- a/part/spellcheck/spellcheck.h +++ /dev/null @@ -1,73 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2009 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef SPELLCHECK_H -#define SPELLCHECK_H - -#include -#include -#include -#include - -#include -#include -#include - -class KateDocument; -class KateView; - -class KateSpellCheckManager : public QObject { - Q_OBJECT - - typedef QPair RangeDictionaryPair; - - public: - KateSpellCheckManager(QObject* parent = NULL); - virtual ~KateSpellCheckManager(); - - QStringList suggestions(const QString& word, const QString& dictionary); - - void ignoreWord(const QString& word, const QString& dictionary); - void addToDictionary(const QString& word, const QString& dictionary); - - /** - * 'r2' is a subrange of 'r1', which is extracted from 'r1' and the remaining ranges are returned - **/ - static QList rangeDifference(const KTextEditor::Range& r1, const KTextEditor::Range& r2); - - public: - QList > spellCheckLanguageRanges(KateDocument *doc, const KTextEditor::Range& range); - - QList > spellCheckWrtHighlightingRanges(KateDocument *doc, const KTextEditor::Range& range, - const QString& dictionary = QString(), - bool singleLine = false, - bool returnSingleRange = false); - QList > spellCheckRanges(KateDocument *doc, const KTextEditor::Range& range, - bool singleLine = false); - - void replaceCharactersEncodedIfNecessary(const QString& newWord, KateDocument *doc, const KTextEditor::Range& replacementRange); - - private: - void trimRange(KateDocument *doc, KTextEditor::Range &r); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellcheckdialog.cpp b/part/spellcheck/spellcheckdialog.cpp deleted file mode 100644 index 302cb47..0000000 --- a/part/spellcheck/spellcheckdialog.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009-2010 by Michel Ludwig - * Copyright (C) 2008 Mirko Stocker - * Copyright (C) 2004-2005 Anders Lund - * Copyright (C) 2002 John Firebaugh - * Copyright (C) 2001-2004 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "spellcheckdialog.h" -#include "spellcheckdialog.moc" - -#include "katedocument.h" -#include "kateglobal.h" -#include "kateview.h" -#include "spellcheck/spellcheck.h" - -#include -#include -#include -#include -#include -#include -#include - -KateSpellCheckDialog::KateSpellCheckDialog( KateView* view ) - : QObject( view ) - , m_view (view) - , m_speller (NULL) - , m_backgroundChecker(NULL) - , m_sonnetDialog(NULL) - , m_globalSpellCheckRange(NULL) - , m_spellCheckCancelledByUser(false) -{ -} - -KateSpellCheckDialog::~KateSpellCheckDialog() -{ - delete m_globalSpellCheckRange; - delete m_sonnetDialog; - delete m_backgroundChecker; - delete m_speller; -} - -void KateSpellCheckDialog::createActions( KActionCollection* ac ) -{ - ac->addAction( KStandardAction::Spelling, this, SLOT(spellcheck()) ); - - KAction *a = new KAction( i18n("Spelling (from cursor)..."), this); - ac->addAction("tools_spelling_from_cursor", a ); - a->setIcon( KIcon( "tools-check-spelling" ) ); - a->setWhatsThis(i18n("Check the document's spelling from the cursor and forward")); - connect( a, SIGNAL( triggered() ), this, SLOT(spellcheckFromCursor()) ); - - m_spellcheckSelection = new KAction( i18n("Spellcheck Selection..."), this ); - ac->addAction("tools_spelling_selection", m_spellcheckSelection); - m_spellcheckSelection->setIcon( KIcon( "tools-check-spelling" ) ); - m_spellcheckSelection->setWhatsThis(i18n("Check spelling of the selected text")); - connect( m_spellcheckSelection, SIGNAL( triggered() ), this, SLOT(spellcheckSelection()) ); -} - -void KateSpellCheckDialog::updateActions () -{ - m_spellcheckSelection->setEnabled (m_view->selection ()); -} - -void KateSpellCheckDialog::spellcheckFromCursor() -{ - spellcheck( m_view->cursorPosition() ); -} - -void KateSpellCheckDialog::spellcheckSelection() -{ - spellcheck( m_view->selectionRange().start(), m_view->selectionRange().end() ); -} - -void KateSpellCheckDialog::spellcheck() -{ - spellcheck( KTextEditor::Cursor( 0, 0 ) ); -} - -void KateSpellCheckDialog::spellcheck( const KTextEditor::Cursor &from, const KTextEditor::Cursor &to ) -{ - KTextEditor::Cursor start = from; - KTextEditor::Cursor end = to; - - if ( end.line() == 0 && end.column() == 0 ) - { - end = m_view->doc()->documentEnd(); - } - - if ( !m_speller ) - { - m_speller = new Sonnet::Speller(); - } - m_speller->restore(KGlobal::config().data()); - - if ( !m_backgroundChecker ) - { - m_backgroundChecker = new Sonnet::BackgroundChecker(*m_speller); - } - -#if KDE_IS_VERSION(4,5,2) -// guard necessary to ensure compilation of KatePart's git repository against <= 4.5.1 - m_backgroundChecker->restore(KGlobal::config().data()); -#endif - - if ( !m_sonnetDialog ) - { - m_sonnetDialog = new Sonnet::Dialog(m_backgroundChecker, m_view); - m_sonnetDialog->showProgressDialog(200); - m_sonnetDialog->showSpellCheckCompletionMessage(); - m_sonnetDialog->setSpellCheckContinuedAfterReplacement(false); - - connect(m_sonnetDialog,SIGNAL(done(const QString&)),this,SLOT(installNextSpellCheckRange())); - - connect(m_sonnetDialog,SIGNAL(replace(const QString&,int,const QString&)), - this,SLOT(corrected(const QString&,int,const QString&))); - - connect(m_sonnetDialog,SIGNAL(misspelling(const QString&,int)), - this,SLOT(misspelling(const QString&,int))); - - connect(m_sonnetDialog,SIGNAL(cancel()), - this,SLOT(cancelClicked())); - - connect(m_sonnetDialog,SIGNAL(destroyed(QObject*)), - this,SLOT(objectDestroyed(QObject*))); - } - - delete m_globalSpellCheckRange; - // we expand to handle the situation when the last word in the range is replace by a new one - m_globalSpellCheckRange = m_view->doc()->newMovingRange (KTextEditor::Range( start, end ), - KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - m_spellCheckCancelledByUser = false; - performSpellCheck( *m_globalSpellCheckRange ); -} - -KTextEditor::Cursor KateSpellCheckDialog::locatePosition( int pos ) -{ - uint remains; - - while ( m_spellLastPos < (uint)pos ) - { - remains = pos - m_spellLastPos; - uint l = m_view->doc()->lineLength( m_spellPosCursor.line() ) - m_spellPosCursor.column(); - if ( l > remains ) - { - m_spellPosCursor.setColumn( m_spellPosCursor.column() + remains ); - m_spellLastPos = pos; - } - else - { - m_spellPosCursor.setLine( m_spellPosCursor.line() + 1 ); - m_spellPosCursor.setColumn(0); - m_spellLastPos += l + 1; - } - } - - return m_spellPosCursor; -} - -void KateSpellCheckDialog::misspelling( const QString& word, int pos ) -{ - KTextEditor::Cursor cursor; - int length; - int origPos = m_view->doc()->computePositionWrtOffsets( m_currentDecToEncOffsetList, pos ); - cursor = locatePosition( origPos ); - length = m_view->doc()->computePositionWrtOffsets( m_currentDecToEncOffsetList, pos + word.length() ) - - origPos; - - m_view->setCursorPositionInternal (cursor, 1); - m_view->setSelection( KTextEditor::Range(cursor, length) ); -} - -void KateSpellCheckDialog::corrected( const QString& word, int pos, const QString& newWord ) -{ - int origPos = m_view->doc()->computePositionWrtOffsets( m_currentDecToEncOffsetList, pos ); - - int length = m_view->doc()->computePositionWrtOffsets( m_currentDecToEncOffsetList, pos + word.length() ) - - origPos; - - KTextEditor::Cursor replacementStartCursor = locatePosition( origPos ); - KTextEditor::Range replacementRange = KTextEditor::Range( replacementStartCursor, length ); - KateDocument *doc = m_view->doc(); - KateGlobal::self()->spellCheckManager()->replaceCharactersEncodedIfNecessary( newWord, doc, replacementRange ); - - m_currentSpellCheckRange.setRange( KTextEditor::Range( replacementStartCursor, m_currentSpellCheckRange.end() ) ); - // we have to be careful here: due to static word wrapping the text might change in addition to simply - // the misspelled word being replaced, i.e. new line breaks might be inserted as well. As such, the text - // in the 'Sonnet::Dialog' might be eventually out of sync with the visible text. Therefore, we 'restart' - // spell checking from the current position. - performSpellCheck( KTextEditor::Range( replacementStartCursor, m_globalSpellCheckRange->end() ) ); -} - -void KateSpellCheckDialog::performSpellCheck(const KTextEditor::Range& range) -{ - if(range.isEmpty()) { - spellCheckDone(); - } - m_languagesInSpellCheckRange = KateGlobal::self()->spellCheckManager()->spellCheckLanguageRanges(m_view->doc(), range); - m_currentLanguageRangeIterator = m_languagesInSpellCheckRange.begin(); - m_currentSpellCheckRange = KTextEditor::Range::invalid(); - installNextSpellCheckRange(); - // first check if there is really something to spell check - if(m_currentSpellCheckRange.isValid()) { - m_sonnetDialog->show(); - } -} - -void KateSpellCheckDialog::installNextSpellCheckRange() -{ - if ( m_spellCheckCancelledByUser - || m_currentLanguageRangeIterator == m_languagesInSpellCheckRange.end() ) - { - spellCheckDone(); - return; - } - KateSpellCheckManager *spellCheckManager = KateGlobal::self()->spellCheckManager(); - KTextEditor::Cursor nextRangeBegin = (m_currentSpellCheckRange.isValid() ? m_currentSpellCheckRange.end() - : KTextEditor::Cursor::invalid()); - m_currentSpellCheckRange = KTextEditor::Range::invalid(); - m_currentDecToEncOffsetList.clear(); - QList > rangeDictionaryPairList; - while ( m_currentLanguageRangeIterator != m_languagesInSpellCheckRange.end() ) - { - const KTextEditor::Range& currentLanguageRange = (*m_currentLanguageRangeIterator).first; - const QString& dictionary = (*m_currentLanguageRangeIterator).second; - KTextEditor::Range languageSubRange = (nextRangeBegin.isValid() ? KTextEditor::Range(nextRangeBegin, currentLanguageRange.end()) - : currentLanguageRange); - rangeDictionaryPairList = spellCheckManager->spellCheckWrtHighlightingRanges(m_view->doc(), - languageSubRange, - dictionary, - false, true); - Q_ASSERT(rangeDictionaryPairList.size() <= 1); - if(rangeDictionaryPairList.size() == 0) { - ++m_currentLanguageRangeIterator; - if ( m_currentLanguageRangeIterator != m_languagesInSpellCheckRange.end() ) - { - nextRangeBegin = (*m_currentLanguageRangeIterator).first.start(); - } - } - else { - m_currentSpellCheckRange = rangeDictionaryPairList.first().first; - const QString& dictionary = rangeDictionaryPairList.first().second; - - m_spellPosCursor = m_currentSpellCheckRange.start(); - m_spellLastPos = 0; - - m_currentDecToEncOffsetList.clear(); - KateDocument::OffsetList encToDecOffsetList; - QString text = m_view->doc()->decodeCharacters(m_currentSpellCheckRange, - m_currentDecToEncOffsetList, - encToDecOffsetList); - // ensure that no empty string is passed on to Sonnet as this can lead to a crash - // (bug 228789) - if(text.isEmpty()) { - nextRangeBegin = m_currentSpellCheckRange.end(); - continue; - } - - if(m_speller->language() != dictionary) { - m_speller->setLanguage(dictionary); - m_backgroundChecker->setSpeller(*m_speller); - } - - m_sonnetDialog->setBuffer(text); - break; - } - } - if ( m_currentLanguageRangeIterator == m_languagesInSpellCheckRange.end() ) - { - spellCheckDone(); - return; - } -} - -void KateSpellCheckDialog::cancelClicked() -{ - m_spellCheckCancelledByUser = true; -} - -void KateSpellCheckDialog::spellCheckDone() -{ - m_currentSpellCheckRange = KTextEditor::Range::invalid(); - m_currentDecToEncOffsetList.clear(); - m_view->clearSelection(); -} - -void KateSpellCheckDialog::objectDestroyed(QObject *object) -{ - Q_UNUSED(object); - m_sonnetDialog = NULL; -} - -//END - - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellcheckdialog.h b/part/spellcheck/spellcheckdialog.h deleted file mode 100644 index 20129db..0000000 --- a/part/spellcheck/spellcheckdialog.h +++ /dev/null @@ -1,118 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009 by Michel Ludwig - * Copyright (C) 2008 Mirko Stocker - * Copyright (C) 2004-2005 Anders Lund - * Copyright (C) 2002 John Firebaugh - * Copyright (C) 2001-2004 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 1999 Jochen Wilhelmy - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef __KATE_SPELLCHECKDIALOG_H__ -#define __KATE_SPELLCHECKDIALOG_H__ - -#include - -class KateView; - -class KAction; -class KActionCollection; -class KProgressDialog; -namespace Sonnet { - class Dialog; - class BackgroundChecker; - class Speller; -} - -#include "ktexteditor/range.h" - -namespace KTextEditor { - class MovingRange; -} - -class KateSpellCheckDialog : public QObject -{ - Q_OBJECT - - public: - explicit KateSpellCheckDialog( KateView* ); - ~KateSpellCheckDialog(); - - void createActions( KActionCollection* ); - - void updateActions (); - - // spellcheck from cursor, selection - private Q_SLOTS: - void spellcheckFromCursor(); - - // defined here in anticipation of per view selections ;) - void spellcheckSelection(); - - void spellcheck(); - - /** - * Spellcheck a defined portion of the text. - * - * @param from Where to start the check - * @param to Where to end. If this is (0,0), it will be set to the end of the document. - */ - void spellcheck( const KTextEditor::Cursor &from, const KTextEditor::Cursor &to=KTextEditor::Cursor() ); - - void misspelling( const QString&, int ); - void corrected ( const QString&, int, const QString&); - - void performSpellCheck(const KTextEditor::Range& range); - void installNextSpellCheckRange(); - - void cancelClicked(); - - void objectDestroyed(QObject *object); - - private: - KTextEditor::Cursor locatePosition( int pos ); - - KateView *m_view; - KAction *m_spellcheckSelection; - - Sonnet::Speller *m_speller; - Sonnet::BackgroundChecker *m_backgroundChecker; - Sonnet::Dialog *m_sonnetDialog; - - // define the part of the text to check - KTextEditor::Range m_currentSpellCheckRange; - KTextEditor::MovingRange *m_globalSpellCheckRange; - - QList > m_currentDecToEncOffsetList; - - QList > m_languagesInSpellCheckRange; - QList >::iterator m_currentLanguageRangeIterator; - - // keep track of where we are. - KTextEditor::Cursor m_spellPosCursor; - uint m_spellLastPos; - - bool m_spellCheckCancelledByUser; - - void spellCheckDone(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellingmenu.cpp b/part/spellcheck/spellingmenu.cpp deleted file mode 100644 index 517ffaf..0000000 --- a/part/spellcheck/spellingmenu.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2009-2010 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "spellingmenu.h" -#include "spellingmenu.moc" - -#include "katedocument.h" -#include "kateglobal.h" -#include "kateview.h" -#include "spellcheck/spellcheck.h" - -#include - -KateSpellingMenu::KateSpellingMenu(KateView *view) - : QObject(view), - m_view (view), - m_spellingMenuAction(NULL), - m_ignoreWordAction(NULL), - m_addToDictionaryAction(NULL), - m_spellingMenu(NULL), - m_currentMisspelledRange(NULL), // we have to use 'm_currentMisspelledRange' - // as QSignalMapper doesn't work with pairs of objects; - // it just points to the object pointed to by either - // 'm_currentMouseMisspelledRange' or 'm_currentCaretMisspelledRange' - m_currentMouseMisspelledRange(NULL), - m_currentCaretMisspelledRange(NULL), - m_useMouseForMisspelledRange(false), - m_suggestionsSignalMapper(new QSignalMapper(this)) -{ - connect(m_suggestionsSignalMapper, SIGNAL(mapped(const QString&)), - this, SLOT(replaceWordBySuggestion(const QString&))); -} - -KateSpellingMenu::~KateSpellingMenu() -{ - m_currentMisspelledRange = NULL; // it shouldn't be accessed anymore as it could - // point to a non-existing object (bug 226724) - // (for example, when it pointed to m_currentCaretMisspelledRange - // and that range got deleted after the caret had left) - m_currentCaretMisspelledRange = NULL; - m_currentMouseMisspelledRange = NULL; -} - -bool KateSpellingMenu::isEnabled() const -{ - if(!m_spellingMenuAction) { - return false; - } - return m_spellingMenuAction->isEnabled(); -} - -void KateSpellingMenu::setEnabled(bool b) -{ - if(m_spellingMenuAction) { - m_spellingMenuAction->setEnabled(b); - } - if(m_ignoreWordAction) { - m_ignoreWordAction->setEnabled(b); - } - if(m_addToDictionaryAction) { - m_addToDictionaryAction->setEnabled(b); - } -} - -void KateSpellingMenu::setVisible(bool b) -{ - if(m_spellingMenuAction) { - m_spellingMenuAction->setVisible(b); - } - if(m_ignoreWordAction) { - m_ignoreWordAction->setVisible(b); - } - if(m_addToDictionaryAction) { - m_addToDictionaryAction->setVisible(b); - } -} - -void KateSpellingMenu::createActions(KActionCollection *ac) -{ - m_spellingMenuAction = new KActionMenu(i18n("Spelling"), this); - ac->addAction("spelling_suggestions", m_spellingMenuAction); - m_spellingMenu = m_spellingMenuAction->menu(); - connect(m_spellingMenu, SIGNAL(aboutToShow()), this, SLOT(populateSuggestionsMenu())); - - m_ignoreWordAction = new KAction(i18n("Ignore Word"), this); - connect(m_ignoreWordAction, SIGNAL(triggered()), this, SLOT(ignoreCurrentWord())); - - m_addToDictionaryAction = new KAction(i18n("Add to Dictionary"), this); - connect(m_addToDictionaryAction, SIGNAL(triggered()), this, SLOT(addCurrentWordToDictionary())); - - setEnabled(false); - setVisible(false); -} - -void KateSpellingMenu::caretEnteredMisspelledRange(KTextEditor::MovingRange *range) -{ - if(m_currentCaretMisspelledRange == range) { - return; - } - m_currentCaretMisspelledRange = NULL; - setEnabled(true); - m_currentCaretMisspelledRange = range; -} - -void KateSpellingMenu::caretExitedMisspelledRange(KTextEditor::MovingRange *range) -{ - if(range != m_currentCaretMisspelledRange) { // order of 'exit' and 'entered' signals - return; // was wrong - } - setEnabled(false); - m_currentCaretMisspelledRange = NULL; -} - -void KateSpellingMenu::mouseEnteredMisspelledRange(KTextEditor::MovingRange *range) -{ - if(m_currentMouseMisspelledRange == range) { - return; - } - m_currentMouseMisspelledRange = range; -} - -void KateSpellingMenu::mouseExitedMisspelledRange(KTextEditor::MovingRange *range) -{ - if(range != m_currentMouseMisspelledRange) { // order of 'exit' and 'entered' signals - return; // was wrong - } - m_currentMouseMisspelledRange = NULL; -} - -void KateSpellingMenu::rangeDeleted(KTextEditor::MovingRange *range) -{ - if(m_currentCaretMisspelledRange == range) { - m_currentCaretMisspelledRange = NULL; - } - if(m_currentMouseMisspelledRange == range) { - m_currentMouseMisspelledRange = NULL; - } - if(m_currentMisspelledRange == range) { - m_currentMisspelledRange = NULL; - } - setEnabled(m_currentCaretMisspelledRange != NULL); -} - -void KateSpellingMenu::setUseMouseForMisspelledRange(bool b) -{ - m_useMouseForMisspelledRange = b; - if(m_useMouseForMisspelledRange) { - setEnabled(m_currentMouseMisspelledRange != NULL); - } - else if(!m_useMouseForMisspelledRange) { - setEnabled(m_currentCaretMisspelledRange != NULL); - } -} - -void KateSpellingMenu::populateSuggestionsMenu() -{ - m_spellingMenu->clear(); - if((m_useMouseForMisspelledRange && !m_currentMouseMisspelledRange) - || (!m_useMouseForMisspelledRange && !m_currentCaretMisspelledRange)) { - return; - } - m_currentMisspelledRange = (m_useMouseForMisspelledRange ? m_currentMouseMisspelledRange - : m_currentCaretMisspelledRange); - m_spellingMenu->addAction(m_ignoreWordAction); - m_spellingMenu->addAction(m_addToDictionaryAction); - m_spellingMenu->addSeparator(); - const QString& misspelledWord = m_view->doc()->text(*m_currentMisspelledRange); - const QString dictionary = m_view->doc()->dictionaryForMisspelledRange(*m_currentMisspelledRange); - m_currentSuggestions = KateGlobal::self()->spellCheckManager()->suggestions(misspelledWord, dictionary); - - int counter = 0; - for(QStringList::iterator i = m_currentSuggestions.begin(); i != m_currentSuggestions.end() && counter < 10; ++i) { - const QString& suggestion = *i; - KAction *action = new KAction(suggestion, m_spellingMenu); - connect(action, SIGNAL(triggered()), m_suggestionsSignalMapper, SLOT(map())); - m_suggestionsSignalMapper->setMapping(action, suggestion); - m_spellingMenu->addAction(action); - ++counter; - } -} - -void KateSpellingMenu::replaceWordBySuggestion(const QString& suggestion) -{ - KateDocument *doc = m_view->doc(); - KateGlobal::self()->spellCheckManager()->replaceCharactersEncodedIfNecessary(suggestion, doc, *m_currentMisspelledRange); -} - -void KateSpellingMenu::addCurrentWordToDictionary() -{ - if(!m_currentMisspelledRange) { - return; - } - const QString& misspelledWord = m_view->doc()->text(*m_currentMisspelledRange); - const QString dictionary = m_view->doc()->dictionaryForMisspelledRange(*m_currentMisspelledRange); - KateGlobal::self()->spellCheckManager()->addToDictionary(misspelledWord, dictionary); - m_view->doc()->clearMisspellingForWord(misspelledWord); // WARNING: 'm_currentMisspelledRange' is deleted here! -} - -void KateSpellingMenu::ignoreCurrentWord() -{ - if(!m_currentMisspelledRange) { - return; - } - const QString& misspelledWord = m_view->doc()->text(*m_currentMisspelledRange); - const QString dictionary = m_view->doc()->dictionaryForMisspelledRange(*m_currentMisspelledRange); - KateGlobal::self()->spellCheckManager()->ignoreWord(misspelledWord, dictionary); - m_view->doc()->clearMisspellingForWord(misspelledWord); // WARNING: 'm_currentMisspelledRange' is deleted here! -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/spellcheck/spellingmenu.h b/part/spellcheck/spellingmenu.h deleted file mode 100644 index 680e134..0000000 --- a/part/spellcheck/spellingmenu.h +++ /dev/null @@ -1,93 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2009 by Michel Ludwig - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef SPELLINGMENU_H -#define SPELLINGMENU_H - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -class KateDocument; -class KateView; - -class KateOnTheFlyChecker; - -class KateSpellingMenu : public QObject { - Q_OBJECT - friend class KateOnTheFlyChecker; - - public: - KateSpellingMenu(KateView *view); - virtual ~KateSpellingMenu(); - - bool isEnabled() const; - - void createActions(KActionCollection *ac); - - /** - * This method has to be called before the menu is shown in response to a context - * menu event. It will trigger that the misspelled range located under the mouse pointer - * is considered for the spelling suggestions. - **/ - void setUseMouseForMisspelledRange(bool b); - - public Q_SLOTS: - void setEnabled(bool b); - void setVisible(bool b); - - protected: - KateView *m_view; - KActionMenu *m_spellingMenuAction; - KAction *m_ignoreWordAction, *m_addToDictionaryAction; - KMenu *m_spellingMenu; - KTextEditor::MovingRange *m_currentMisspelledRange; - KTextEditor::MovingRange *m_currentMouseMisspelledRange; - KTextEditor::MovingRange *m_currentCaretMisspelledRange; - bool m_useMouseForMisspelledRange; - QStringList m_currentSuggestions; - QSignalMapper *m_suggestionsSignalMapper; - - // These methods are called from KateOnTheFlyChecker to inform about events involving - // moving ranges. - void rangeDeleted(KTextEditor::MovingRange *range); - void caretEnteredMisspelledRange(KTextEditor::MovingRange *range); - void caretExitedMisspelledRange(KTextEditor::MovingRange *range); - void mouseEnteredMisspelledRange(KTextEditor::MovingRange *range); - void mouseExitedMisspelledRange(KTextEditor::MovingRange *range); - - protected Q_SLOTS: - void populateSuggestionsMenu(); - void replaceWordBySuggestion(const QString& suggestion); - - void addCurrentWordToDictionary(); - void ignoreCurrentWord(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/brokenswapfilewidget.ui b/part/swapfile/brokenswapfilewidget.ui deleted file mode 100644 index 8abd3d3..0000000 --- a/part/swapfile/brokenswapfilewidget.ui +++ /dev/null @@ -1,94 +0,0 @@ - - - BrokenSwapFileWidget - - - - 0 - 0 - 721 - 139 - - - - - - - - 15 - 0 - - - - Qt::AlignCenter - - - - - - - QLayout::SetMinAndMaxSize - - - - - - 0 - 0 - - - - <html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body> -<p><b>Data Recovery</b> <a href="Kate stores the things you changed in a swap file. Using the original file you started from plus the swap file you can mostly recover your work."><span>(Help)</span></a></p><p>Could not recover all data. The swap file was probably incomplete.</p></body></html> - - - true - - - Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse - - - - - - - - - Qt::Horizontal - - - QSizePolicy::MinimumExpanding - - - - 0 - 0 - - - - - - - - OK - - - - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- - -
diff --git a/part/swapfile/katebrokenswapfilebar.cpp b/part/swapfile/katebrokenswapfilebar.cpp deleted file mode 100644 index 06b817b..0000000 --- a/part/swapfile/katebrokenswapfilebar.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katebrokenswapfilebar.h" -#include "ui_brokenswapfilewidget.h" -#include "kateview.h" - -#include - -//BEGIN KateBrokenSwapFileBar -KateBrokenSwapFileBar::KateBrokenSwapFileBar(KateView *view, QWidget *parent) - : KateViewBarWidget( false, parent ) - , m_view ( view ) - , m_ui (new Ui::BrokenSwapFileWidget()) -{ - m_ui->setupUi( centralWidget() ); - - // set warning icon - m_ui->lblIcon->setPixmap(KIcon("dialog-warning").pixmap(64, 64)); - - m_ui->btnOk->setGuiItem(KGuiItem(m_ui->btnOk->text(), KIcon("dialog-ok"))); - - // clicking on the "Help" link pops up the content as what's this - connect(m_ui->lblSwap, SIGNAL(linkActivated(const QString&)), - this, SLOT(showWhatsThis(const QString&))); - connect(m_ui->btnOk, SIGNAL(clicked()), this, SIGNAL(hideMe())); -} - -KateBrokenSwapFileBar::~KateBrokenSwapFileBar () -{ - delete m_ui; -} - -void KateBrokenSwapFileBar::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -//END KateBrokenSwapFileBar - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/katebrokenswapfilebar.h b/part/swapfile/katebrokenswapfilebar.h deleted file mode 100644 index 4c817d8..0000000 --- a/part/swapfile/katebrokenswapfilebar.h +++ /dev/null @@ -1,50 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_BROKEN_SWAP_H__ -#define _KATE_BROEKN_SWAP_H__ - -#include "kateviewhelpers.h" - -class KateView; - -namespace Ui { - class BrokenSwapFileWidget; -} - -class KateBrokenSwapFileBar : public KateViewBarWidget -{ - Q_OBJECT - - public: - explicit KateBrokenSwapFileBar(KateView *view, QWidget *parent = 0); - ~KateBrokenSwapFileBar (); - - protected Q_SLOTS: - void showWhatsThis(const QString&); - - private: - KateView *const m_view; - Ui::BrokenSwapFileWidget *m_ui; -}; - -#endif //_KATE_BROKEN_SWAP_H__ - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/katerecoverbar.cpp b/part/swapfile/katerecoverbar.cpp deleted file mode 100644 index 5c314c3..0000000 --- a/part/swapfile/katerecoverbar.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Dominik Haumann - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katerecoverbar.h" -#include "ui_recoverwidget.h" -#include "kateswapfile.h" -#include "kateview.h" -#include "katedocument.h" - -#include -#include -#include -#include - -#include - -//BEGIN KateRecoverBar -KateRecoverBar::KateRecoverBar(KateView *view, QWidget *parent) - : KateViewBarWidget( false, parent ) - , m_view ( view ) - , m_ui (new Ui::RecoverWidget()) - , m_proc(0) -{ - m_ui->setupUi( centralWidget() ); - - // clicking on the "Help" link pops up the content as what's this - connect(m_ui->lblSwap, SIGNAL(linkActivated(const QString&)), - this, SLOT(showWhatsThis(const QString&))); - - // set icons, but keep text from ui file - m_ui->btnRecover->setGuiItem(KGuiItem(m_ui->btnRecover->text(), KIcon("edit-redo"))); - m_ui->btnDiscard->setGuiItem(KStandardGuiItem::discard()); - m_ui->lblIcon->setPixmap(KIcon("dialog-warning").pixmap(64, 64)); - - // use queued connections because this (all) KateRecoverBar widgets are deleted - connect(m_ui->btnRecover, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(recover()), Qt::QueuedConnection); - connect(m_ui->btnDiscard, SIGNAL(clicked()), m_view->doc()->swapFile(), SLOT(discard()), Qt::QueuedConnection); - connect(m_ui->btnDiff, SIGNAL(clicked()), this, SLOT(viewDiff())); -} - -KateRecoverBar::~KateRecoverBar () -{ - delete m_ui; -} - -void KateRecoverBar::showWhatsThis(const QString& text) -{ - QWhatsThis::showText(QCursor::pos(), text); -} - -void KateRecoverBar::viewDiff() -{ - // create a document with the recovered data - KateDocument recoverDoc; - recoverDoc.setText(m_view->doc()->text()); - - QString path = m_view->doc()->swapFile()->fileName(); - - if (path.isNull()) - return; - - QFile swp(path); - if (!swp.open(QIODevice::ReadOnly)) { - kWarning( 13020 ) << "Can't open swap file"; - return; - } - - QDataStream stream(&swp); - - recoverDoc.swapFile()->recover(stream); - - // create a KProcess proc - m_proc = new KProcess(this); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - *m_proc << "diff" << "-u" << "-" << m_view->doc()->url().toLocalFile(); - - connect(m_proc, SIGNAL(readyRead()), this, SLOT(slotDataAvailable())); - connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotDiffFinished())); - - setCursor(Qt::WaitCursor); - - // disable the "View Changes" button, so the user won't click it twice - m_ui->btnDiff->setEnabled(false); - - m_diffContent.clear(); - - m_proc->start(); - - QTextStream ts(m_proc); - int lineCount = recoverDoc.lines(); - for (int line = 0; line < lineCount; ++line) - ts << recoverDoc.line(line) << '\n'; - ts.flush(); - m_proc->closeWriteChannel(); -} - -void KateRecoverBar::slotDataAvailable() -{ - // collect diff output - m_diffContent += m_proc->readAll(); -} - -void KateRecoverBar::slotDiffFinished() -{ - m_ui->btnDiff->setEnabled(true); - unsetCursor(); - - // get the exit status to check whether diff command run successfully - const QProcess::ExitStatus es = m_proc->exitStatus(); - delete m_proc; - m_proc = 0; - - KTemporaryFile tempFile; - tempFile.setSuffix(".diff"); - if (!tempFile.open()) { - kWarning( 13020 ) << "Can't open diff temporary file"; - return; - } - - // write the buffered data to the temporary file - tempFile.write(m_diffContent); - - // check exit status - if (es != QProcess::NormalExit) - { - KMessageBox::sorry(this, - i18n("The diff command failed. Please make sure that " - "diff(1) is installed and in your PATH."), - i18n("Error Creating Diff")); - return; - } - - // sanity check: is there any diff content? - if ( tempFile.size() == 0 ) - { - KMessageBox::information(this, - i18n("The files are identical."), - i18n("Diff Output")); - return; - } - - tempFile.setAutoRemove(false); - KUrl url = KUrl::fromPath(tempFile.fileName()); - - // KRun::runUrl should delete the file, once the client exits - KRun::runUrl(url, "text/x-patch", this, true ); -} - -//END KateRecoverBar - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/katerecoverbar.h b/part/swapfile/katerecoverbar.h deleted file mode 100644 index 46acac1..0000000 --- a/part/swapfile/katerecoverbar.h +++ /dev/null @@ -1,64 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Dominik Haumann - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_RECOVER_H__ -#define _KATE_RECOVER_H__ - -#include "kateviewhelpers.h" - -#include - -class KProcess; -class KateView; -class KateDocument; - -namespace Ui { - class RecoverWidget; -} - -class KateRecoverBar : public KateViewBarWidget -{ - Q_OBJECT - - public: - explicit KateRecoverBar(KateView *view, QWidget *parent = 0); - ~KateRecoverBar (); - - protected Q_SLOTS: - void showWhatsThis(const QString&); - void viewDiff(); - - private: - KateView *const m_view; - Ui::RecoverWidget *m_ui; - - protected Q_SLOTS: - void slotDataAvailable(); - void slotDiffFinished(); - - private: - KProcess* m_proc; - QByteArray m_diffContent; -}; - -#endif //_KATE_RECOVER_H__ - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/kateswapfile.cpp b/part/swapfile/kateswapfile.cpp deleted file mode 100644 index c5a4c66..0000000 --- a/part/swapfile/kateswapfile.cpp +++ /dev/null @@ -1,464 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Dominik Haumann - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" - -#include "kateswapfile.h" -#include "kateview.h" -#include "kateconfig.h" - -#include - -#include -#include -#include - -// swap file version header -const static char * const swapFileVersionString = "Kate Swap File - Version 1.0"; - -// tokens for swap files -const static qint8 EA_StartEditing = 'S'; -const static qint8 EA_FinishEditing = 'E'; -const static qint8 EA_WrapLine = 'W'; -const static qint8 EA_UnwrapLine = 'U'; -const static qint8 EA_InsertText = 'I'; -const static qint8 EA_RemoveText = 'R'; - -namespace Kate { - -QTimer* SwapFile::s_timer = 0; - -SwapFile::SwapFile(KateDocument *document) - : QObject(document) - , m_document(document) - , m_trackingEnabled(false) - , m_recovered(false) - , m_modified(false) -{ - // fixed version of serialisation - m_stream.setVersion (QDataStream::Qt_4_6); - - // conect the timer - connect(syncTimer(), SIGNAL(timeout()), this, SLOT(writeFileToDisk()), Qt::DirectConnection); - - // connecting the signals - connect(&m_document->buffer(), SIGNAL(saved(const QString &)), this, SLOT(fileSaved(const QString&))); - connect(&m_document->buffer(), SIGNAL(loaded(const QString &, bool)), this, SLOT(fileLoaded(const QString&))); - - setTrackingEnabled(true); -} - -SwapFile::~SwapFile() -{ - removeSwapFile(); -} - -void SwapFile::setTrackingEnabled(bool enable) -{ - if (m_trackingEnabled == enable) { - return; - } - - m_trackingEnabled = enable; - - TextBuffer &buffer = m_document->buffer(); - - if (m_trackingEnabled) { - connect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing())); - connect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing())); - - connect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&))); - connect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int))); - connect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &))); - connect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &))); - } else { - disconnect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing())); - disconnect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing())); - - disconnect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&))); - disconnect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int))); - disconnect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &))); - disconnect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &))); - } -} - -void SwapFile::fileClosed () -{ - // remove old swap file, file is now closed - removeSwapFile(); - - // purge filename - updateFileName(); -} - -void SwapFile::fileLoaded(const QString&) -{ - // look for swap file - if (!updateFileName()) - return; - - if (!m_swapfile.exists()) - { - kDebug (13020) << "No swap file"; - return; - } - - if (!QFileInfo(m_swapfile).isReadable()) - { - kWarning( 13020 ) << "Can't open swap file (missing permissions)"; - return; - } - - // emit signal in case the document has more views - emit swapFileFound(); -} - -void SwapFile::recover() -{ - // if isOpen() returns true, the swap file likely changed already (appended data) - // Example: The document was falsely marked as writable and the user changed - // text even though the recover bar was visible. In this case, a replay of - // the swap file across wrong document content would happen -> certainly wrong - if (m_swapfile.isOpen()) { - kWarning( 13020 ) << "Attempt to recover an already modified document. Aborting"; - emit swapFileBroken(); - return; - } - - // if the file doesn't exist, abort (user might have deleted it, or use two editor instances) - if (!m_swapfile.open(QIODevice::ReadOnly)) - { - kWarning( 13020 ) << "Can't open swap file"; - emit swapFileHandled(); - return; - } - - // remember that the file has recovered - m_recovered = true; - - // open data stream - m_stream.setDevice(&m_swapfile); - - // replay the swap file - recover(m_stream); - - // close swap file - m_stream.setDevice(0); - m_swapfile.close(); - - // emit signal in case the document has more views - emit swapFileHandled(); -} - -bool SwapFile::recover(QDataStream& stream) -{ - // read and check header - QByteArray header; - stream >> header; - if (header != swapFileVersionString) - { - stream.setDevice (0); - m_swapfile.close (); - kWarning( 13020 ) << "Can't open swap file, wrong version"; - return false; - } - - // disconnect current signals - setTrackingEnabled(false); - - // replay swapfile - bool editStarted = false; - bool brokenSwapFile = false; - while (!stream.atEnd()) { - if (brokenSwapFile) - break; - - qint8 type; - stream >> type; - switch (type) { - case EA_StartEditing: { - m_document->editStart(); - editStarted = true; - break; - } - case EA_FinishEditing: { - m_document->editEnd(); - editStarted = false; - break; - } - case EA_WrapLine: { - if (!editStarted) { - brokenSwapFile = true; - break; - } - - int line = 0, column = 0; - stream >> line >> column; - - // emulate buffer unwrapLine with document - m_document->editWrapLine(line, column, true); - break; - } - case EA_UnwrapLine: { - if (!editStarted) { - brokenSwapFile = true; - break; - } - - int line = 0; - stream >> line; - - // assert valid line - Q_ASSERT (line > 0); - - // emulate buffer unwrapLine with document - m_document->editUnWrapLine(line - 1, true, 0); - break; - } - case EA_InsertText: { - if (!editStarted) { - brokenSwapFile = true; - break; - } - - int line, column; - QByteArray text; - stream >> line >> column >> text; - m_document->insertText(KTextEditor::Cursor(line, column), QString::fromUtf8 (text.data (), text.size())); - break; - } - case EA_RemoveText: { - if (!editStarted) { - brokenSwapFile = true; - break; - } - - int line, startColumn, endColumn; - stream >> line >> startColumn >> endColumn; - m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn))); - break; - } - default: { - kWarning( 13020 ) << "Unknown type:" << type; - } - } - } - - // balance editStart and editEnd - if (editStarted) { - brokenSwapFile = true; - m_document->editEnd(); - } - - // warn the user if the swap file is not complete - if (brokenSwapFile) { - kWarning ( 13020 ) << "Some data might be lost"; - emit swapFileBroken(); - } - - // reconnect the signals - setTrackingEnabled(true); - - return true; -} - -void SwapFile::fileSaved(const QString&) -{ - m_modified = false; - - // remove old swap file (e.g. if a file A was "saved as" B) - removeSwapFile(); - - // set the name for the new swap file - updateFileName(); -} - -void SwapFile::startEditing () -{ - // no swap file, no work - if (m_swapfile.fileName().isEmpty()) - return; - - // if swap file doesn't exists, open it in WriteOnly mode - // if it does, append the data to the existing swap file, - // in case you recover and start edititng again - if (!m_swapfile.exists()) { - // TODO set file as read-only - m_swapfile.open(QIODevice::WriteOnly); - m_stream.setDevice(&m_swapfile); - - // write file header - m_stream << QByteArray (swapFileVersionString); - } else if (m_stream.device() == 0) { - m_swapfile.open(QIODevice::Append); - m_stream.setDevice(&m_swapfile); - } - - // format: qint8 - m_stream << EA_StartEditing; -} - -void SwapFile::finishEditing () -{ - // skip if not open - if (!m_swapfile.isOpen ()) - return; - - // write the file to the disk every 15 seconds - if (!syncTimer()->isActive() && !m_document->config()->swapFileNoSync()) - syncTimer()->start(15000); - - // format: qint8 - m_stream << EA_FinishEditing; - m_swapfile.flush(); -} - -void SwapFile::wrapLine (const KTextEditor::Cursor &position) -{ - // skip if not open - if (!m_swapfile.isOpen ()) - return; - - // format: qint8, int, int - m_stream << EA_WrapLine << position.line() << position.column(); - - m_modified = true; -} - -void SwapFile::unwrapLine (int line) -{ - // skip if not open - if (!m_swapfile.isOpen ()) - return; - - // format: qint8, int - m_stream << EA_UnwrapLine << line; - - m_modified = true; -} - -void SwapFile::insertText (const KTextEditor::Cursor &position, const QString &text) -{ - // skip if not open - if (!m_swapfile.isOpen ()) - return; - - // format: qint8, int, int, bytearray - m_stream << EA_InsertText << position.line() << position.column() << text.toUtf8 (); - - m_modified = true; -} - -void SwapFile::removeText (const KTextEditor::Range &range) -{ - // skip if not open - if (!m_swapfile.isOpen ()) - return; - - // format: qint8, int, int, int - Q_ASSERT (range.start().line() == range.end().line()); - m_stream << EA_RemoveText - << range.start().line() << range.start().column() - << range.end().column(); - - m_modified = true; -} - -bool SwapFile::shouldRecover() const -{ - // should not recover if the file has already recovered in another view - if (m_recovered) - return false; - - return !m_swapfile.fileName().isEmpty() && m_swapfile.exists() && m_stream.device() == 0; -} - -void SwapFile::discard() -{ - removeSwapFile(); - emit swapFileHandled(); -} - -void SwapFile::removeSwapFile() -{ - if (!m_swapfile.fileName().isEmpty() && m_swapfile.exists()) { - m_stream.setDevice(0); - m_swapfile.close(); - m_swapfile.remove(); - } -} - -bool SwapFile::updateFileName() -{ - // first clear filename - m_swapfile.setFileName (""); - - // get the new path - QString path = fileName(); - if (path.isNull()) - return false; - - m_swapfile.setFileName(path); - return true; -} - -QString SwapFile::fileName() -{ - const KUrl &url = m_document->url(); - if (url.isEmpty() || !url.isLocalFile()) - return QString(); - - QString path = url.toLocalFile(); - int poz = path.lastIndexOf(QDir::separator()); - path.insert(poz+1, ".swp."); - - return path; -} - -QTimer* SwapFile::syncTimer() -{ - if (s_timer == 0) { - s_timer = new QTimer(QApplication::instance()); - s_timer->setSingleShot(true); - } - - return s_timer; -} - -void SwapFile::writeFileToDisk() -{ - if (m_modified) { - m_modified = false; - - #ifndef Q_OS_WIN - // ensure that the file is written to disk - #ifdef HAVE_FDATASYNC - fdatasync (m_swapfile.handle()); - #else - fsync (m_swapfile.handle()); - #endif - #endif - } -} - -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/kateswapfile.h b/part/swapfile/kateswapfile.h deleted file mode 100644 index cbf9102..0000000 --- a/part/swapfile/kateswapfile.h +++ /dev/null @@ -1,105 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Dominik Haumann - * Copyright (C) 2010 Diana-Victoria Tiriplica - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_SWAPFILE_H -#define KATE_SWAPFILE_H - -#include -#include -#include -#include - -#include "katepartprivate_export.h" -#include "katetextbuffer.h" -#include "katebuffer.h" -#include "katedocument.h" - -class KateView; - -namespace Kate { - -/** - * Class for tracking editing actions. - * In case Kate crashes, this can be used to replay all edit actions to - * recover the lost data. - */ -class KATEPART_TESTS_EXPORT SwapFile : public QObject -{ - Q_OBJECT - - public: - explicit SwapFile(KateDocument* document); - ~SwapFile(); - bool shouldRecover() const; - - void fileClosed (); - QString fileName(); - - private: - void setTrackingEnabled(bool trackingEnabled); - void removeSwapFile(); - bool updateFileName(); - - private: - KateDocument *m_document; - bool m_trackingEnabled; - - protected Q_SLOTS: - void fileSaved(const QString& filename); - void fileLoaded(const QString &filename); - - void startEditing (); - void finishEditing (); - - void wrapLine (const KTextEditor::Cursor &position); - void unwrapLine (int line); - void insertText (const KTextEditor::Cursor &position, const QString &text); - void removeText (const KTextEditor::Range &range); - - Q_SIGNALS: - void swapFileFound(); - void swapFileHandled(); - void swapFileBroken(); - - public Q_SLOTS: - void discard(); - void recover(); - bool recover(QDataStream&); - - private: - QDataStream m_stream; - QFile m_swapfile; - bool m_recovered; - bool m_modified; - static QTimer *s_timer; - - protected Q_SLOTS: - void writeFileToDisk(); - - private: - QTimer* syncTimer(); -}; - -} - -#endif // KATE_SWAPFILE_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/swapfile/recoverwidget.ui b/part/swapfile/recoverwidget.ui deleted file mode 100644 index 4e0f5b6..0000000 --- a/part/swapfile/recoverwidget.ui +++ /dev/null @@ -1,113 +0,0 @@ - - - RecoverWidget - - - - 0 - 0 - 721 - 123 - - - - - - - - 15 - 0 - - - - Qt::AlignCenter - - - - - - - QLayout::SetMinAndMaxSize - - - - - - 0 - 0 - - - - <html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body> -<p><b>Data Recovery</b> <a href="The application stores the things you changed in a swap file. Using the original file you started from plus the swap file you can mostly recover your work."><span>(Help)</span></a></p><p>The file was not closed appropriately. Do you want to recover the data?</p></body></html> - - - true - - - Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse - - - - - - - - - View Changes - - - - - - - Qt::Horizontal - - - QSizePolicy::MinimumExpanding - - - - 0 - 0 - - - - - - - - Recover - - - - - - - Discard - - - - - - - - - - - - KPushButton - QPushButton -
kpushbutton.h
-
-
- - btnDiff - btnRecover - btnDiscard - - - -
diff --git a/part/syntax/data/asp.xml b/part/syntax/data/asp.xml deleted file mode 100644 index 1aa4f92..0000000 --- a/part/syntax/data/asp.xml +++ /dev/null @@ -1,393 +0,0 @@ - - - - - - select - case - end select - - if - then - else - elseif - end if - - - while - do - until - loop - wend - - for - each - to - in - next - - exit - continue - - - dim - redim - preserve - - const - erase - nothing - set - - new - me - - - function - sub - call - - class - private - public - with - - randomize - - open - close - movenext - execute - eof - - not - true - false - or - and - xor - - - response - write - redirect - end - - request - form - querystring - servervariables - cookies - - session - - server - createobject - - abs - array - asc - atn - cbool - cbyte - ccur - cdate - cdbl - chr - cint - clng - cos - csng - cstr - date - dateadd - - DateDiff - DatePart - DateSerial - DateValue - Date - Day - Exp - Filter - Fix - FormatCurrency - FormatDateTime - FormatNumber - FormatPercent - - GetObject - Hex - Hour - InputBox - InStr - InStrRev - Int - IsArray - IsDate - IsEmpty - IsNull - IsNumeric - IsObject - Join - LBound - LCase - - Left - Len - LoadPicture - Log - LTrim - Mid - Minute - Month - MonthName - MsgBox - Now - Oct - Replace - - RGB - Right - Rnd - Round - RTrim - - ScriptEngine - ScriptEngineBuildVersion - ScriptEngineMajorVersion - ScriptEngineMinorVersion - Second - Sgn - Sin - Space - Split - Sqr - StrComp - StrReverse - String - Tan - Time - Timer - TimeSerial - TimeValue - Trim - TypeName - UBound - UCase - VarType - Weekday - WeekdayName - Year - - Add - AddFolders - BuildPath - Clear - Close - Copy - CopyFile - CopyFolder - CreateFolder - CreateTextFile - Delete - DeleteFile - DeleteFolder - DriveExists - Exists - FileExists - FolderExists - GetAbsolutePathName - GetBaseName - GetDrive - GetDriveName - GetExtensionName - GetFile - GetFileName - GetFolder - GetParentFolderName - - GetSpecialFolder - GetTempName - Items - item - Keys - Move - MoveFile - MoveFolder - OpenAsTextStream - OpenTextFile - Raise - Read - ReadAll - ReadLine - Remove - RemoveAll - Skip - SkipLine - Write - WriteBlankLines - WriteLine - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/awk.xml b/part/syntax/data/awk.xml deleted file mode 100644 index 0f16ca4..0000000 --- a/part/syntax/data/awk.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - if - else - while - do - for - in - continue - break - print - printf - getline - function - return - next - exit - - - ARGC - ARGV - CONVFMT - ENVIRON - FILENAME - FNR - FS - NF - NR - OFMT - OFS - ORS - RS - RSTART - RLENGTH - SUBSEP - - - gsub - gensub - index - length - match - split - sprintf - sub - substr - tolower - toupper - atan2 - cos - exp - int - log - rand - sin - sqrt - srand - close - fflush - system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/bash.xml b/part/syntax/data/bash.xml deleted file mode 100644 index f9f1885..0000000 --- a/part/syntax/data/bash.xml +++ /dev/null @@ -1,901 +0,0 @@ - - - - - - - -]> - - - - - - - else - for - function - in - select - until - while - elif - then - set - - - - : - source - alias - bg - bind - break - builtin - cd - caller - command - compgen - complete - continue - dirs - disown - echo - enable - eval - exec - exit - fc - fg - getopts - hash - help - history - jobs - kill - let - logout - popd - printf - pushd - pwd - return - set - shift - shopt - suspend - test - time - times - trap - type - ulimit - umask - unalias - wait - - - - export - unset - declare - typeset - local - read - readonly - - - - - arch - awk - bash - bunzip2 - bzcat - bzcmp - bzdiff - bzegrep - bzfgrep - bzgrep - bzip2 - bzip2recover - bzless - bzmore - cat - chattr - chgrp - chmod - chown - chvt - cp - date - dd - deallocvt - df - dir - dircolors - dmesg - dnsdomainname - domainname - du - dumpkeys - echo - ed - egrep - false - fgconsole - fgrep - fuser - gawk - getkeycodes - gocr - grep - groff - groups - gunzip - gzexe - gzip - hostname - igawk - install - kbd_mode - kbdrate - killall - last - lastb - link - ln - loadkeys - loadunimap - login - ls - lsattr - lsmod - lsmod.old - lzcat - lzcmp - lzdiff - lzegrep - lzfgrep - lzgrep - lzless - lzcat - lzma - lzmainfo - lzmore - mapscrn - mesg - mkdir - mkfifo - mknod - mktemp - more - mount - mv - nano - netstat - nisdomainname - nroff - openvt - pgawk - pidof - ping - ps - pstree - pwd - rbash - readlink - red - resizecons - rm - rmdir - run-parts - sash - sed - setfont - setkeycodes - setleds - setmetamode - setserial - sh - showkey - shred - sleep - ssed - stat - stty - su - sync - tar - tempfile - touch - troff - true - umount - uname - unicode_start - unicode_stop - unlink - unlzma - unxz - utmpdump - uuidgen - vdir - wall - wc - xz - xzcat - ypdomainname - zcat - zcmp - zdiff - zegrep - zfgrep - zforce - zgrep - zless - zmore - znew - zsh - - - aclocal - aconnect - aplay - apm - apmsleep - apropos - ar - arecord - as - as86 - autoconf - autoheader - automake - awk - basename - bc - bison - c++ - cal - cat - cc - cdda2wav - cdparanoia - cdrdao - cd-read - cdrecord - chfn - chgrp - chmod - chown - chroot - chsh - clear - cmp - co - col - comm - cp - cpio - cpp - cut - dc - dd - df - diff - diff3 - dir - dircolors - directomatic - dirname - du - env - expr - fbset - file - find - flex - flex++ - fmt - free - ftp - funzip - fuser - g++ - gawk - gc - gcc - gdb - getent - getopt - gettext - gettextize - gimp - gimp-remote - gimptool - gmake - gs - head - hexdump - id - install - join - kill - killall - ld - ld86 - ldd - less - lex - ln - locate - lockfile - logname - lp - lpr - ls - lynx - m4 - make - man - mkdir - mknod - msgfmt - mv - namei - nasm - nawk - nice - nl - nm - nm86 - nmap - nohup - nop - od - passwd - patch - pcregrep - pcretest - perl - perror - pidof - pr - printf - procmail - prune - ps2ascii - ps2epsi - ps2frag - ps2pdf - ps2ps - psbook - psmerge - psnup - psresize - psselect - pstops - rcs - rev - rm - scp - sed - seq - setterm - shred - size - size86 - skill - slogin - snice - sort - sox - split - ssh - ssh-add - ssh-agent - ssh-keygen - ssh-keyscan - stat - strings - strip - sudo - suidperl - sum - tac - tail - tee - test - tr - uniq - unlink - unzip - updatedb - updmap - uptime - users - vmstat - w - wc - wget - whatis - whereis - which - who - whoami - write - xargs - yacc - yes - zip - zsoelim - - - dcop - kdialog - kfile - xhost - xmodmap - xset - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/c.xml b/part/syntax/data/c.xml deleted file mode 100644 index 0389f78..0000000 --- a/part/syntax/data/c.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - - - - - break - case - continue - default - do - else - enum - extern - for - goto - if - inline - return - sizeof - struct - switch - typedef - union - while - - - auto - char - const - double - float - int - long - register - restrict - short - signed - static - unsigned - void - volatile - int8_t - int16_t - int32_t - int64_t - uint8_t - uint16_t - uint32_t - uint64_t - wchar_t - _Imaginary - _Complex - _Bool - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/cg.xml b/part/syntax/data/cg.xml deleted file mode 100644 index 338d0d2..0000000 --- a/part/syntax/data/cg.xml +++ /dev/null @@ -1,288 +0,0 @@ - - - - - - - - - POSITION - COLOR - COLOR0 - COLOR1 - COLOR2 - COLOR3 - TEXCOORD0 - TEXCOORD1 - TEXCOORD2 - TEXCOORD3 - TEXCOORD4 - TEXCOORD5 - TEXCOORD6 - TEXCOORD7 - TEXCOORD8 - TEXCOORD9 - TEXCOORD10 - TEXCOORD11 - TEXCOORD12 - TEXCOORD13 - TEXCOORD14 - TEXCOORD15 - TEXUNIT0 - TEXUNIT1 - TEXUNIT2 - TEXUNIT3 - TEXUNIT4 - TEXUNIT5 - TEXUNIT6 - TEXUNIT7 - TEXUNIT8 - TEXUNIT9 - TEXUNIT10 - TEXUNIT11 - TEXUNIT12 - TEXUNIT13 - TEXUNIT14 - TEXUNIT15 - WPOS - DEPTH - BLENDWEIGHT - NORMAL - TESSFACTOR - FOGCOORD - PSIZE - BLENDINDICES - TANGENT - BINORMAL - FOG - BCOL0 - BCOL1 - FACE - - - do - while - if - else - for - struct - return - static - typedef - discard - true - false - - - bool - int - fixed - half - float - - void - sampler - sampler1D - sampler2D - sampler3D - samplerCUBE - samplerRECT - - packed - const - uniform - in - out - inout - - - FIXME - TODO - BUG - - - abs - acos - all - any - asin - atan - atan2 - ceil - clamp - cos - cosh - cross - degrees - determinant - dot - exp - exp2 - floor - fmod - frac - frexp - isfinite - isinf - isnan - ldexp - lerp - lit - log - log2 - log10 - max - min - modf - mul - noise - pow - radians - round - rsqrt - saturate - sign - sin - sincos - sinh - smoothstep - step - sqrt - tan - tanh - transpose - distance - faceforward - length - normalize - reflect - refract - tex1D - tex1Dproj - tex2D - tex2Dproj - texRECT - texRECTproj - tex3D - tex3Dproj - texCUBE - texCUBEproj - ddx - ddy - debug - pack_2half - unpack_2half - pack_2ushort - unpack_2ushort - pack_4byte - unpack_4byte - pack_4ubyte - unpack_4ubyte - - - fragout - fragout_float - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/cpp.xml b/part/syntax/data/cpp.xml deleted file mode 100644 index 74252cf..0000000 --- a/part/syntax/data/cpp.xml +++ /dev/null @@ -1,317 +0,0 @@ - - - - - - - asm - break - case - catch - class - const_cast - continue - default - delete - do - dynamic_cast - else - enum - explicit - export - extern - false - friend - for - goto - if - inline - namespace - new - operator - private - protected - public - qobject_cast - reinterpret_cast - return - sizeof - static_cast - struct - switch - template - this - throw - true - try - typedef - typeid - type_info - typename - union - using - virtual - while - - and - and_eq - bad_cast - bad_typeid - bitand - bitor - compl - not - not_eq - or - or_eq - xor - xor_eq - - - K_DCOP - Q_ARG - Q_ASSERT - Q_ASSERT_X - Q_CHECK_PTR - Q_CLASSINFO - Q_CLEANUP_RESOURCE - Q_D - Q_DECLARE_FLAGS - Q_DECLARE_FLAGS - Q_DECLARE_INTERFACE - Q_DECLARE_METATYPE - Q_DECLARE_OPERATORS_FOR_FLAGS - Q_DECLARE_PRIVATE - Q_DECLARE_PUBLIC - Q_DECLARE_SHARED - Q_DECLARE_TYPEINFO - Q_DISABLE_COPY - Q_ENUMS - Q_EXPORT - Q_FLAGS - Q_FOREACH - Q_FOREVER - Q_GADGET - Q_GLOBAL_STATIC - Q_GLOBAL_STATIC_WITH_ARGS - Q_INIT_RESOURCE - Q_INTERFACES - Q_INVOKABLE - Q_NOREPLY - Q_OBJECT - Q_OVERRIDE - Q_PRIVATE_SLOT - Q_PROPERTY - Q_Q - Q_RETURN_ARG - Q_SCRIPTABLE - Q_SETS - Q_SIGNALS - Q_SLOTS - Q_UNUSED - SIGNAL - SLOT - TRUE - FALSE - connect - disconnect - emit - signals - slots - foreach - forever - - qint8 - qint16 - qint32 - qint64 - qlonglong - qptrdiff - qreal - quint8 - quint16 - quint32 - quint64 - quintptr - qulonglong - - - auto - bool - char - const - double - float - int - long - mutable - register - short - signed - static - unsigned - void - volatile - uchar - uint - int8_t - int16_t - int32_t - int64_t - uint8_t - uint16_t - uint32_t - uint64_t - wchar_t - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/css.xml b/part/syntax/data/css.xml deleted file mode 100644 index 774511d..0000000 --- a/part/syntax/data/css.xml +++ /dev/null @@ -1,704 +0,0 @@ - - - - - - - - - - - azimuth - background - background-attachment - background-color - background-image - background-position - background-repeat - border - border-bottom - border-bottom-color - border-bottom-style - border-bottom-width - border-collapse - border-color - border-left - border-left-color - border-left-style - border-left-width - border-right - border-right-color - border-right-style - border-right-width - border-spacing - border-style - border-top - border-top-color - border-top-style - border-top-width - border-width - bottom - caption-side - clear - clip - color - content - counter-increment - counter-reset - cue - cue-after - cue-before - cursor - direction - display - elevation - empty-cells - float - font - font-family - font-size - font-size-adjust - font-stretch - font-style - font-variant - font-weight - height - left - letter-spacing - line-height - list-style - list-style-image - list-style-keyword - list-style-position - list-style-type - margin - margin-bottom - margin-left - margin-right - margin-top - marker-offset - max-height - max-width - min-height - min-width - orphans - outline - outline-color - outline-style - outline-width - overflow - padding - padding-bottom - padding-left - padding-right - padding-top - page - page-break-after - page-break-before - page-break-inside - pause - pause-after - pause-before - pitch - pitch-range - play-during - position - quotes - richness - right - size - speak - speak-header - speak-numeral - speak-punctuation - speech-rate - stress - table-layout - text-align - text-decoration - text-decoration-color - text-indent - text-shadow - text-transform - top - unicode-bidi - vertical-align - visibility - voice-family - volume - white-space - widows - width - word-spacing - z-index - - - border-bottom-image - border-bottom-left-image - border-bottom-left-radius - border-bottom-right-image - border-bottom-right-radius - border-corner-image - border-image - border-left-image - border-radius - border-right-image - border-top-image - border-top-left-image - border-top-left-radius - border-top-right-image - border-top-right-radius - box-shadow - box-sizing - opacity - outline-offset - overflow-x - overflow-y - text-overflow - text-shadow - - - -moz-border-bottom-colors - -moz-border-left-colors - -moz-border-radius - -moz-border-right-colors - -moz-border-top-colors - -moz-box-flex - - - -o-background-size - -o-text-overflow - - - -khtml-background-size - konq_bgpos_x - konq_bgpos_y - - - -webkit-background-size - - - font-family - font-size - font-stretch - font-style - font-variant - font-weight - unicode-range - units-per-em - src - panose-1 - stemv - stemh - slope - cap-height - x-height - ascent - descent - widths - bbox - definition-src - baseline - centerline - mathline - topline - - - - inherit - none - hidden - dotted - dashed - solid - double - groove - ridge - inset - outset - xx-small - x-small - small - medium - large - x-large - xx-large - smaller - larger - italic - oblique - small-caps - normal - bold - bolder - lighter - light - 100 - 200 - 300 - 400 - 500 - 600 - 700 - 800 - 900 - transparent - repeat - repeat-x - repeat-y - no-repeat - baseline - sub - super - top - text-top - middle - bottom - text-bottom - left - right - center - justify - konq-center - disc - circle - square - box - decimal - decimal-leading-zero - lower-roman - upper-roman - lower-greek - lower-alpha - lower-latin - upper-alpha - upper-latin - hebrew - armenian - georgian - cjk-ideographic - hiragana - katakana - hiragana-iroha - katakana-iroha - inline - inline-block - block - list-item - run-in - compact - marker - table - inline-table - table-row-group - table-header-group - table-footer-group - table-row - table-column-group - table-column - table-cell - table-caption - auto - crosshair - default - pointer - move - e-resize - ne-resize - nw-resize - n-resize - se-resize - sw-resize - s-resize - w-resize - text - wait - help - above - absolute - always - avoid - below - bidi-override - blink - both - capitalize - caption - clip - close-quote - collapse - condensed - crop - cross - ellipsis - ellipsis-word - embed - expanded - extra-condensed - extra-expanded - fixed - hand - hide - higher - icon - inside - invert - landscape - level - line-through - loud - lower - lowercase - ltr - menu - message-box - mix - narrower - no-close-quote - no-open-quote - nowrap - open-quote - outside - overline - portrait - pre - pre-line - pre-wrap - relative - rtl - scroll - semi-condensed - semi-expanded - separate - show - small-caption - static - static-position - status-bar - thick - thin - ultra-condensed - ultra-expanded - underline - uppercase - visible - wider - break - serif - sans-serif - cursive - fantasy - monospace - border-box - content-box - - - -moz-box - - - - - - aqua - black - blue - cyan - fuchsia - gray - green - lime - maroon - navy - olive - purple - red - silver - teal - white - yellow - ActiveBorder - ActiveCaption - AppWorkspace - Background - ButtonFace - ButtonHighlight - ButtonShadow - ButtonText - CaptionText - GrayText - Highlight - HighlightText - InactiveBorder - InactiveCaption - InactiveCaptionText - InfoBackground - InfoText - Menu - MenuText - Scrollbar - ThreeDDarkShadow - ThreeDFace - ThreeDHighlight - ThreeDLightShadow - ThreeDShadow - Window - WindowFrame - WindowText - - - - url - attr - rect - rgb - rgba - hsl - hsla - counter - counters - - - local - format - - - expression - - - - - all - aural - braille - embossed - handheld - print - projection - screen - tty - tv - - - - hover - link - visited - active - focus - first-child - last-child - only-child - first-of-type - last-of-type - only-of-type - first-letter - first-line - before - after - selection - root - empty - target - enabled - disabled - checked - indeterminate - nth-child - nth-last-child - nth-of-type - nth-last-of-type - not - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/d.xml b/part/syntax/data/d.xml deleted file mode 100644 index 2ed3a5f..0000000 --- a/part/syntax/data/d.xml +++ /dev/null @@ -1,818 +0,0 @@ - - - - - - - - - - - asm - body - break - case - catch - continue - default - do - else - finally - for - foreach - foreach_reverse - goto - if - mixin - return - switch - throw - try - while - with - - - synchronized - - - - - - abstract - align - auto - const - export - final - inout - invariant - lazy - nothrow - override - package - private - protected - public - pure - ref - static - - - - out - scope - - - - - false - null - super - this - true - typeid - - - assert - cast - is - new - delete - in - - - delegate - function - - - - module - import - - - - alias - enum - typedef - class - interface - struct - union - - - - typeof - - void - bool - byte - ubyte - short - ushort - int - uint - long - ulong - cent - ucent - float - double - real - ireal - ifloat - idouble - creal - cfloat - cdouble - char - wchar - dchar - - - - macro - template - - - - init - sizeof - alignof - mangleof - stringof - tupleof - offsetof - max - min - infinity - nan - dig - epsilon - mant_dig - max_10_exp - max_exp - min_10_exp - min_exp - re - im - length - ptr - dup - idup - reverse - sort - keys - values - rehash - - - - - size_t - ptrdiff_t - hash_t - Error - Exception - Object - TypeInfo - ClassInfo - ModuleInfo - Interface - OffsetTypeInfo - TypeInfo_Typedef - TypeInfo_Enum - TypeInfo_Pointer - TypeInfo_Array - TypeInfo_StaticArray - TypeInfo_AssociativeArray - TypeInfo_Function - TypeInfo_Delegate - TypeInfo_Class - TypeInfo_Interface - TypeInfo_Struct - TypeInfo_Tuple - - - string - wstring - dstring - bit - TypeInfo_Const - TypeInfo_Invariant - - - - extern - - - C - - D - Windows - Pascal - System - - - - msg - lib - - - - exit - success - failure - - - - DigitalMars - X86 - X86_64 - Windows - Win32 - Win64 - linux - LittleEndian - BigEndian - D_Coverage - D_InlineAsm_X86 - unittest - D_Version2 - none - all - - - - __FILE__ - __LINE__ - __DATE__ - __TIME__ - __TIMESTAMP__ - __VENDOR__ - __VERSION__ - __EOF__ - - - - debug - unittest - - - - pragma - - - - version - - - - deprecated - volatile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/debianchangelog.xml b/part/syntax/data/debianchangelog.xml deleted file mode 100644 index 858926b..0000000 --- a/part/syntax/data/debianchangelog.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - urgency - - - - stable - stable-security - testing - testing-proposed-updates - frozen - unstable - experimental - UNRELEASED - - sarge-backports - sarge-volatile - etch-backports - etch-volatile - lenny-backports - lenny-volatile - squeeze-backports - squeeze-volatile - - dapper - dapper-security - dapper-proposed - dapper-updates - dapper-backports - dapper-commercial - edgy - edgy-security - edgy-proposed - edgy-updates - edgy-backports - edgy-commercial - feisty - feisty-security - feisty-proposed - feisty-updates - feisty-backports - feisty-commercial - gutsy - gutsy-security - gutsy-proposed - gutsy-updates - gutsy-backports - gutsy-partner - hardy - hardy-security - hardy-proposed - hardy-updates - hardy-backports - hardy-partner - intrepid - intrepid-security - intrepid-proposed - intrepid-updates - intrepid-backports - intrepid-partner - jaunty - jaunty-security - jaunty-proposed - jaunty-updates - jaunty-backports - jaunty-partner - karmic - karmic-security - karmic-proposed - karmic-updates - karmic-backports - lucid - lucid-security - lucid-proposed - lucid-updates - lucid-backports - - - - low - medium - high - emergency - bug - critical - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/debiancontrol.xml b/part/syntax/data/debiancontrol.xml deleted file mode 100644 index a1eb5f7..0000000 --- a/part/syntax/data/debiancontrol.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/djangotemplate.xml b/part/syntax/data/djangotemplate.xml deleted file mode 100644 index 2e817ad..0000000 --- a/part/syntax/data/djangotemplate.xml +++ /dev/null @@ -1,328 +0,0 @@ - - - -]> - - - - - - - - for - block - if - ifequal - ifnotequal - ifchanged - blocktrans - spaceless - - - - endfor - endblock - endif - endifequal - endifnotequal - endifchanged - endblocktrans - endspaceless - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/doxygen.xml b/part/syntax/data/doxygen.xml deleted file mode 100644 index a465866..0000000 --- a/part/syntax/data/doxygen.xml +++ /dev/null @@ -1,667 +0,0 @@ - - -]> - - - - - - - - - \arg - - \attention - \author - \callgraph - \callergraph - - - \details - \dot - \else - - \endcond - - \enddot - \endhtmlonly - \endif - \endlatexonly - \endlink - - \endmanonly - \endmsc - \endverbatim - \endxmlonly - \f[ - - \f] - \f$ - \hideinitializer - \htmlonly - \interface - - \internal - \invariant - \~ - \@ - \$ - - \\ - \# - \latexonly - \li - \manonly - - \msc - \n - \nosubgrouping - \note - \only - - \post - \pre - \private - \privatesection - \protected - - \protectedsection - \public - \publicsection - \remarks - \return - - \returns - - - \showinitializer - \since - \test - - \todo - \verbatim - \warning - \xmlonly - - @arg - @attention - @author - @callgraph - @callergraph - - - @details - @dot - @else - - @endcond - - @enddot - @endhtmlonly - @endif - @endlatexonly - @endlink - - @endmanonly - @endmsc - @endverbatim - @endxmlonly - @f[ - - @f] - @f$ - @hideinitializer - @htmlonly - @interface - - @internal - @invariant - @~ - @@ - @$ - - @\ - @# - @latexonly - @li - @manonly - - @msc - @n - @nosubgrouping - @note - @only - - @post - @pre - @pivate - @pivatesection - @protected - - @protectedsection - @public - @publicsection - @remarks - @return - - @returns - - - @showinitializer - @since - @test - - @todo - @verbatim - @warning - @xmlonly - - - - \addtogroup - \a - \anchor - \b - - \c - \class - \cond - \copybrief - \copydetails - - \copydoc - \def - \dir - \dontinclude - \dotfile - - \e - \elseif - \em - \enum - \example - - \exception - \exceptions - \extends - \file - \htmlinclude - - \if - \ifnot - \implements - \include - \includelineno - - \link - \memberof - \namespace - \p - \package - - \property - \protocol - \ref - \relatesalso - \relates - - \retval - \throw - \throws - \verbinclude - \version - - \xrefitem - - @addtogroup - @a - @anchor - - @b - @c - @class - @cond - @copybrief - - @copydetails - @copydoc - @def - @dir - @dontinclude - - @dotfile - @e - @elseif - @em - @enum - - @example - @exception - @exceptions - @extends - @file - - @htmlinclude - @if - @ifnot - @implements - @include - - @includelineno - @link - @memberof - @namespace - @p - - @package - @property - @prtocol - @ref - @relatesalso - - @relates - @retval - @throw - @throws - @verbinclude - - @version - @xrefitem - - - \param - \tparam - - @param - @tparam - - - \image - - @image - - - \category - \defgroup - - \headerfile - \page - \paragraph - \section - \struct - - \subpage - \subsection - \subsubsection - \union - \weakgroup - - @category - @defgroup - @headerfile - @page - - @paragraph - @section - @struct - @subpage - @subsection - - @subsubsection - @union - @weakgroup - - - \addindex - - \brief - \bug - \date - \deprecated - \fn - - \ingroup - \line - \mainpage - \name - \overload - - \par - \sa - \see - \short - \skip - - \skipline - \typedef - \until - \var - - @addindex - @brief - @bug - @date - @deprecated - - @fn - @ingroup - @line - @mainpage - @name - - @overload - @par - @sa - @see - @short - - @skip - @skipline - @typedef - @until - @var - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/e.xml b/part/syntax/data/e.xml deleted file mode 100644 index a1fa75f..0000000 --- a/part/syntax/data/e.xml +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - FALSE - MAX_INT - MIN_INT - NULL - TRUE - UNDEF - bit - bits - body - bool - byte - byte_array - continue - copy - default - external_pointer - files - file - form - global - index - init - int - it - list - load - long - me - method - module - ntv - of - pat - print - result - source_ref - string - symtab - sys - test - uint - untyped - vec - - - run - init - pre_generate - dut_error - pack - unpack - post_generate - pre_generate - set_config - hex - stop_run - append - size - delete - is_empty - deep_compare - deep_compare_physical - clear - pop0 - setup - crc_32 - - - chars - define - extend - event - ECHO - DOECHO - import - initialize - non_terminal - struct - unit - script - testgroup - type - - - C - add - also - and - as - as_a - break - code - compute - computed - delayed - do - else - each - emit - empty - end - exit - finish - for - from - if - in - is - like - log - new - no - not - only - or - out - read - repeat - return - reverse - routine - step - then - to - traceable - untraceable - var - when - while - with - write - xor - - - before - by - choose - gen - keep - keeping - matches - next - select - sequence - soft - using - - - address - cover - error - events - event - length - kind - ranges - range - sample - text - value - item - transition - illegal - - - always - all - basic - call - cycles - cycle - clock - change - check - expect - fall - first - forever - idle - initial - negedge - others - on - posedge - rise - start - that - time - task - until - verilog - vhdl - wait - within - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/fortran.xml b/part/syntax/data/fortran.xml deleted file mode 100644 index 4a83a70..0000000 --- a/part/syntax/data/fortran.xml +++ /dev/null @@ -1,580 +0,0 @@ - - - - - - - - - - - allocate - break - call - case - common - - continue - cycle - deallocate - default - - forall - where - elsewhere - - - equivalence - exit - external - for - go - goto - if - implicit - include - interface - intrinsic - namelist - none - nullify - operator - assignment - pause - procedure - pure - elemental - record - recursive - result - return - select - selectcase - stop - - to - use - only - entry - while - - - access - backspace - close - inquire - open - print - read - rewind - write - format - - - - unit - end - err - fmt - iostat - status - advance - size - eor - - - - unit - iostat - err - file - status - access - form - recl - blank - position - action - delim - pad - - - - unit - iostat - err - file - exist - opened - number - named - name - access - sequential - direct - form - formatted - unformatted - recl - nextrec - blank - position - action - read - write - readwrite - delim - pad - - - double - precision - parameter - save - pointer - public - private - target - allocatable - optional - sequence - - - - - - - - abs - cabs - dabs - iabs - aimag - aint - dint - anint - dnint - ceiling - cmplx - dcmplx - dimag - floor - nint - idnint - int - idint - ifix - real - float - sngl - dble - dreal - aprime - dconjg - dfloat - ddmim - rand - - modulo - conjg - dprod - dim - ddim - idim - max - amax0 - amax1 - max0 - max1 - dmax1 - min - amin0 - amin1 - min0 - min1 - dmin1 - mod - amod - dmod - sign - dsign - isign - - acos - dacos - asin - dasin - atan - datan - atan2 - datan2 - cos - ccos - dcos - cosh - dcosh - exp - cexp - dexp - log - alog - dlog - clog - log10 - alog10 - dlog10 - sin - csin - dsin - sinh - dsinh - sqrt - csqrt - dsqrt - tan - dtan - tanh - dtanh - - - achar - char - iachar - ichar - - lge - lgt - lle - llt - - adjustl - adjustr - index - len_trim - scan - verify - - logical - - exponent - fraction - nearest - rrspacing - scale - set_exponent - spacing - - btest - iand - ibclr - ibits - ibset - ieor - ior - ishft - ishftc - not - - mvbits - - merge - - - - - - associated - present - kind - - len - - digits - epsilon - huge - maxexponent - minexponent - precision - radix - range - tiny - - bit_size - - allocated - lbound - ubound - shape - size - - - - - - repeat - trim - - selected_int_kind - selected_real_kind - - transfer - - dot_product - matmul - - all - any - count - maxval - minval - product - sum - - pack - unpack - - reshape - - spread - - cshift - eoshift - - transpose - - maxloc - minloc - - - - - - date_and_time - system_clock - - random_number - random_seed - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/glsl.xml b/part/syntax/data/glsl.xml deleted file mode 100644 index 21ef312..0000000 --- a/part/syntax/data/glsl.xml +++ /dev/null @@ -1,323 +0,0 @@ - - - - - - break - continue - do - for - while - - if - else - - true - false - - discard - return - - struct - - - float - int - void - bool - - mat2 - mat3 - mat4 - - vec2 - vec3 - vec4 - ivec2 - ivec3 - ivec4 - bvec2 - bvec3 - bvec4 - - sampler1D - sampler2D - sampler3D - samplerCube - sampler1DShadow - sampler2DShadow - - - attribute - const - uniform - varying - - in - out - inout - - - FIXME - TODO - BUG - - - - radians - degrees - sin - cos - tan - asin - acos - atan - - - pow - exp - log - exp2 - log2 - sqrt - inversesqrt - - - abs - sign - floor - ceil - fract - mod - min - max - clamp - mix - step - smoothstep - - - length - distance - dot - cross - normalize - ftransform - faceforward - reflect - refract - - - matrixCompMult - - - lessThan - lessThenEqual - greaterThan - greaterThanEqual - equal - notEqual - any - all - not - - - texture1D - texture1DProj - texture1DLod - texture1DProjLod - texture2D - texture2DProj - texture2DLod - texture2DProjLod - texture3D - texture3DProj - texture3DLod - texture3DProjLod - textureCube - textureCubeLod - shadow1D - shadow2D - shadow1DProj - shadow2DProj - shadow1DLod - shadow2DLod - shadow1DProjLod - shadow2DProjLod - - - dFdx - dFdy - fwidth - - - noise1 - noise2 - noise3 - noise4 - - - - gl_Position - gl_PointSize - gl_ClipVertex - - - gl_FragCoord - gl_FragFacing - gl_FragColor - gl_FragData - gl_FragDepth - - - gl_Color - gl_SecondaryColor - gl_Normal - gl_Vertex - gl_MultiTexCoord0 - gl_MultiTexCoord1 - gl_MultiTexCoord2 - gl_MultiTexCoord2 - gl_MultiTexCoord3 - gl_MultiTexCoord4 - gl_MultiTexCoord5 - gl_MultiTexCoord6 - gl_MultiTexCoord7 - gl_FogColor - - - gl_MaxLights - gl_MaxClipPlanes - gl_MaxTextureUnits - gl_MaxTextureCoords - gl_MaxVertexAttributes - gl_MaxVertexUniformComponents - gl_MaxVaryingFloats - gl_MaxVertexTextureImageUnits - gl_MaxCombinedTextureImageUnits - gl_MaxTextureImageUnits - gl_MaxFragmentUniformComponents - gl_MaxDrawBuffers - - - gl_ModelViewMatrix - gl_ProjectionMatrix - gl_ModelViewProjectionMatrix - gl_TextureMatrix - gl_NormalMatrix - gl_ModelViewMatrixInverse - gl_ProjectionMatrixInverse - gl_ModelViewProjectionMatrixInverse - gl_TextureMatrixInverse - gl_ModelViewMatrixTranspose - gl_ProjectionMatrixTranspose - gl_ModelViewProjectionMatrixTranspose - gl_TextureMatrixTranspose - gl_ModelViewMatrixInverseTranspose - gl_ProjectionMatrixInverseTranspose - gl_ModelViewProjectionMatrixInverseTranspose - gl_TextureMatrixInverseTranspose - gl_NormScale - gl_DepthRangeParameters - gl_DepthRange - gl_ClipPlane - gl_PointParameters - gl_Point - gl_MaterialParameters - gl_FrontMaterial - gl_BackMaterial - gl_LightSourceParameters - gl_LightSource - gl_LightModelParameters - gl_LightModel - gl_LightModelProducts - gl_FrontLightModelProduct - gl_BackLightModelProduct - gl_LightProducts - gl_FrontLightProduct - gl_BackLightProduct - gl_TextureEnvColor - gl_EyePlaneS - gl_EyePlaneT - gl_EyePlaneR - gl_EyePlaneQ - gl_ObjectPlaneS - gl_ObjectPlaneT - gl_ObjectPlaneR - gl_ObjectPlaneQ - gl_FogParameters - gl_Fog - - - gl_FrontColor - gl_BackColor - gl_FrontSecondaryColor - gl_BackSecondaryColor - gl_TexCoord - gl_FogFragCoord - gl_Color - gl_SecondaryColor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/gnuassembler.xml b/part/syntax/data/gnuassembler.xml deleted file mode 100644 index ff9e104..0000000 --- a/part/syntax/data/gnuassembler.xml +++ /dev/null @@ -1,300 +0,0 @@ - - - - - - - - .abort - .align - .app-file - .appline - .ascii - .asciz - .att_syntax - .balign - .balignl - .balignw - .byte - .code16 - .code32 - .comm - .common.s - .common - .data - .dc.b - .dc.d - .dc.l - .dc.s - .dc.w - .dc.x - .dc - .dcb.b - .dcb.d - .dcb.l - .dcb.s - .dcb.w - .dcb.x - .dcb - .debug - .def - .desc - .dim - .double - .ds.b - .ds.d - .ds.l - .ds.p - .ds.s - .ds.w - .ds.x - .ds - .dsect - .eject - .else - .elsec - .elseif - .end - .endc - .endef - .endfunc - .endif - .endm - .endr - .equ - .equiv - .err - .exitm - .extend - .extern - .fail - .file - .fill - .float - .format - .func - .global - .globl - .hidden - .hword - .ident - .if - .ifc - .ifdef - .ifeq - .ifeqs - .ifge - .ifgt - .ifle - .iflt - .ifnc - .ifndef - .ifne - .ifnes - .ifnotdef - .include - .int - .intel_syntax - .internal - .irep - .irepc - .irp - .irpc - .lcomm - .lflags - .line - .linkonce - .list - .llen - .ln - .long - .lsym - .macro - .mexit - .name - .noformat - .nolist - .nopage - noprefix - .octa - .offset - .org - .p2align - .p2alignl - .p2alignw - .page - .plen - .popsection - .previous - .print - .protected - .psize - .purgem - .pushsection - .quad - .rodata - .rep - .rept - .rva - .sbttl - .scl - .sect.s - .sect - .section.s - .section - .set - .short - .single - .size - .skip - .sleb128 - .space - .spc - .stabd - .stabn - .stabs - .string - .struct - .subsection - .symver - .tag - .text - .title - .ttl - .type - .uleb128 - .use - .val - .version - .vtable_entry - .vtable_inherit - .weak - .word - .xcom - .xdef - .xref - .xstabs - .zero - - .arm - .bss - .code - .even - .force_thumb - .ldouble - .loc - .ltorg - .packed - .pool - .req - .thumb - .thumb_func - .thumb_set - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/go.xml b/part/syntax/data/go.xml deleted file mode 100755 index 1c99428..0000000 --- a/part/syntax/data/go.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - break - case - chan - const - continue - default - defer - else - fallthrough - for - func - go - goto - if - import - interface - map - - range - return - select - struct - switch - type - var - - - bool - byte - complex64 - complex128 - float - float32 - float64 - int - int8 - int16 - int32 - int64 - string - uint - uint8 - uint16 - uint32 - uint64 - - - cap - len - make - new - panic - recover - - - false - nil - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/haskell.xml b/part/syntax/data/haskell.xml deleted file mode 100644 index 1d73e31..0000000 --- a/part/syntax/data/haskell.xml +++ /dev/null @@ -1,380 +0,0 @@ - - - - - - as - case - class - data - deriving - do - else - hiding - if - import - in - infixl - infixr - instance - let - module - newtype - of - primitive - qualified - then - type - where - - - FilePath - IOError - abs - acos - acosh - all - and - any - appendFile - approxRational - asTypeOf - asin - asinh - atan - atan2 - atanh - basicIORun - break - catch - ceiling - chr - compare - concat - concatMap - const - cos - cosh - curry - cycle - decodeFloat - denominator - digitToInt - div - divMod - drop - dropWhile - either - elem - encodeFloat - enumFrom - enumFromThen - enumFromThenTo - enumFromTo - error - even - exp - exponent - fail - filter - flip - floatDigits - floatRadix - floatRange - floor - fmap - foldl - foldl1 - foldr - foldr1 - fromDouble - fromEnum - fromInt - fromInteger - fromIntegral - fromRational - fst - gcd - getChar - getContents - getLine - group - head - id - inRange - index - init - intToDigit - interact - ioError - isAlpha - isAlphaNum - isAscii - isControl - isDenormalized - isDigit - isHexDigit - isIEEE - isInfinite - isLower - isNaN - isNegativeZero - isOctDigit - isPrint - isSpace - isUpper - iterate - last - lcm - length - lex - lexDigits - lexLitChar - lines - log - logBase - lookup - map - mapM - mapM_ - max - maxBound - maximum - maybe - min - minBound - minimum - mod - negate - not - notElem - null - numerator - odd - or - ord - otherwise - pack - pi - pred - primExitWith - print - product - properFraction - putChar - putStr - putStrLn - quot - quotRem - range - rangeSize - read - readDec - readFile - readFloat - readHex - readIO - readInt - readList - readLitChar - readLn - readOct - readParen - readSigned - reads - readsPrec - realToFrac - recip - rem - repeat - replicate - return - reverse - round - scaleFloat - scanl - scanl1 - scanr - scanr1 - seq - sequence - sequence_ - show - showChar - showInt - showList - showLitChar - showParen - showSigned - showString - shows - showsPrec - significand - signum - sin - sinh - snd - sort - span - splitAt - sqrt - subtract - succ - sum - tail - take - takeWhile - tan - tanh - threadToIOResult - toEnum - toInt - toInteger - toLower - toRational - toUpper - truncate - uncurry - undefined - unlines - until - unwords - unzip - unzip3 - userError - words - writeFile - zip - zip3 - zipWith - zipWith3 - - - Bounded - Enum - Eq - Floating - Fractional - Functor - Integral - Ix - Monad - Num - Ord - Read - Real - RealFloat - RealFrac - Show - - - Bool - Char - Double - Either - FilePath - Float - Int - Integer - IO - IOError - Maybe - Ordering - Ratio - Rational - ReadS - ShowS - String - ByteString - - - False - True - Left - Right - Just - Nothing - EQ - LT - GT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/java.xml b/part/syntax/data/java.xml deleted file mode 100644 index c7f0f39..0000000 --- a/part/syntax/data/java.xml +++ /dev/null @@ -1,3864 +0,0 @@ - - - - - - ACTIVE - ACTIVITY_COMPLETED - ACTIVITY_REQUIRED - ARG_IN - ARG_INOUT - ARG_OUT - AWTError - AWTEvent - AWTEventListener - AWTEventListenerProxy - AWTEventMulticaster - AWTException - AWTKeyStroke - AWTPermission - AbstractAction - AbstractBorder - AbstractButton - AbstractCellEditor - AbstractCollection - AbstractColorChooserPanel - AbstractDocument - AbstractDocument.AttributeContext - AbstractDocument.Content - AbstractDocument.ElementEdit - AbstractExecutorService - AbstractInterruptibleChannel - AbstractLayoutCache - AbstractLayoutCache.NodeDimensions - AbstractList - AbstractListModel - AbstractMap - AbstractMethodError - AbstractPreferences - AbstractQueue - AbstractQueuedSynchronizer - AbstractSelectableChannel - AbstractSelectionKey - AbstractSelector - AbstractSequentialList - AbstractSet - AbstractSpinnerModel - AbstractTableModel - AbstractUndoableEdit - AbstractWriter - AccessControlContext - AccessControlException - AccessController - AccessException - Accessible - AccessibleAction - AccessibleAttributeSequence - AccessibleBundle - AccessibleComponent - AccessibleContext - AccessibleEditableText - AccessibleExtendedComponent - AccessibleExtendedTable - AccessibleExtendedText - AccessibleHyperlink - AccessibleHypertext - AccessibleIcon - AccessibleKeyBinding - AccessibleObject - AccessibleRelation - AccessibleRelationSet - AccessibleResourceBundle - AccessibleRole - AccessibleSelection - AccessibleState - AccessibleStateSet - AccessibleStreamable - AccessibleTable - AccessibleTableModelChange - AccessibleText - AccessibleTextSequence - AccessibleValue - AccountException - AccountExpiredException - AccountLockedException - AccountNotFoundException - Acl - AclEntry - AclNotFoundException - Action - ActionEvent - ActionListener - ActionMap - ActionMapUIResource - Activatable - ActivateFailedException - ActivationDesc - ActivationException - ActivationGroup - ActivationGroupDesc - ActivationGroupDesc.CommandEnvironment - ActivationGroupID - ActivationGroup_Stub - ActivationID - ActivationInstantiator - ActivationMonitor - ActivationSystem - Activator - ActiveEvent - ActivityCompletedException - ActivityRequiredException - AdapterActivator - AdapterActivatorOperations - AdapterAlreadyExists - AdapterAlreadyExistsHelper - AdapterInactive - AdapterInactiveHelper - AdapterManagerIdHelper - AdapterNameHelper - AdapterNonExistent - AdapterNonExistentHelper - AdapterStateHelper - AddressHelper - Adjustable - AdjustmentEvent - AdjustmentListener - Adler32 - AffineTransform - AffineTransformOp - AlgorithmParameterGenerator - AlgorithmParameterGeneratorSpi - AlgorithmParameterSpec - AlgorithmParameters - AlgorithmParametersSpi - AllPermission - AlphaComposite - AlreadyBound - AlreadyBoundException - AlreadyBoundHelper - AlreadyBoundHolder - AlreadyConnectedException - AncestorEvent - AncestorListener - AnnotatedElement - Annotation - Annotation - AnnotationFormatError - AnnotationTypeMismatchException - Any - AnyHolder - AnySeqHelper - AnySeqHelper - AnySeqHolder - AppConfigurationEntry - AppConfigurationEntry.LoginModuleControlFlag - Appendable - Applet - AppletContext - AppletInitializer - AppletStub - ApplicationException - Arc2D - Arc2D.Double - Arc2D.Float - Area - AreaAveragingScaleFilter - ArithmeticException - Array - Array - ArrayBlockingQueue - ArrayIndexOutOfBoundsException - ArrayList - ArrayStoreException - ArrayType - Arrays - AssertionError - AsyncBoxView - AsynchronousCloseException - AtomicBoolean - AtomicInteger - AtomicIntegerArray - AtomicIntegerFieldUpdater - AtomicLong - AtomicLongArray - AtomicLongFieldUpdater - AtomicMarkableReference - AtomicReference - AtomicReferenceArray - AtomicReferenceFieldUpdater - AtomicStampedReference - Attr - Attribute - Attribute - Attribute - AttributeChangeNotification - AttributeChangeNotificationFilter - AttributeException - AttributeInUseException - AttributeList - AttributeList - AttributeList - AttributeListImpl - AttributeModificationException - AttributeNotFoundException - AttributeSet - AttributeSet - AttributeSet.CharacterAttribute - AttributeSet.ColorAttribute - AttributeSet.FontAttribute - AttributeSet.ParagraphAttribute - AttributeSetUtilities - AttributeValueExp - AttributedCharacterIterator - AttributedCharacterIterator.Attribute - AttributedString - Attributes - Attributes - Attributes - Attributes.Name - Attributes2 - Attributes2Impl - AttributesImpl - AudioClip - AudioFileFormat - AudioFileFormat.Type - AudioFileReader - AudioFileWriter - AudioFormat - AudioFormat.Encoding - AudioInputStream - AudioPermission - AudioSystem - AuthPermission - AuthProvider - AuthenticationException - AuthenticationException - AuthenticationNotSupportedException - Authenticator - Authenticator.RequestorType - AuthorizeCallback - Autoscroll - BAD_CONTEXT - BAD_INV_ORDER - BAD_OPERATION - BAD_PARAM - BAD_POLICY - BAD_POLICY_TYPE - BAD_POLICY_VALUE - BAD_QOS - BAD_TYPECODE - BMPImageWriteParam - BackingStoreException - BadAttributeValueExpException - BadBinaryOpValueExpException - BadKind - BadLocationException - BadPaddingException - BadStringOperationException - BandCombineOp - BandedSampleModel - BaseRowSet - BasicArrowButton - BasicAttribute - BasicAttributes - BasicBorders - BasicBorders.ButtonBorder - BasicBorders.FieldBorder - BasicBorders.MarginBorder - BasicBorders.MenuBarBorder - BasicBorders.RadioButtonBorder - BasicBorders.RolloverButtonBorder - BasicBorders.SplitPaneBorder - BasicBorders.ToggleButtonBorder - BasicButtonListener - BasicButtonUI - BasicCheckBoxMenuItemUI - BasicCheckBoxUI - BasicColorChooserUI - BasicComboBoxEditor - BasicComboBoxEditor.UIResource - BasicComboBoxRenderer - BasicComboBoxRenderer.UIResource - BasicComboBoxUI - BasicComboPopup - BasicControl - BasicDesktopIconUI - BasicDesktopPaneUI - BasicDirectoryModel - BasicEditorPaneUI - BasicFileChooserUI - BasicFormattedTextFieldUI - BasicGraphicsUtils - BasicHTML - BasicIconFactory - BasicInternalFrameTitlePane - BasicInternalFrameUI - BasicLabelUI - BasicListUI - BasicLookAndFeel - BasicMenuBarUI - BasicMenuItemUI - BasicMenuUI - BasicOptionPaneUI - BasicOptionPaneUI.ButtonAreaLayout - BasicPanelUI - BasicPasswordFieldUI - BasicPermission - BasicPopupMenuSeparatorUI - BasicPopupMenuUI - BasicProgressBarUI - BasicRadioButtonMenuItemUI - BasicRadioButtonUI - BasicRootPaneUI - BasicScrollBarUI - BasicScrollPaneUI - BasicSeparatorUI - BasicSliderUI - BasicSpinnerUI - BasicSplitPaneDivider - BasicSplitPaneUI - BasicStroke - BasicTabbedPaneUI - BasicTableHeaderUI - BasicTableUI - BasicTextAreaUI - BasicTextFieldUI - BasicTextPaneUI - BasicTextUI - BasicTextUI.BasicCaret - BasicTextUI.BasicHighlighter - BasicToggleButtonUI - BasicToolBarSeparatorUI - BasicToolBarUI - BasicToolTipUI - BasicTreeUI - BasicViewportUI - BatchUpdateException - BeanContext - BeanContextChild - BeanContextChildComponentProxy - BeanContextChildSupport - BeanContextContainerProxy - BeanContextEvent - BeanContextMembershipEvent - BeanContextMembershipListener - BeanContextProxy - BeanContextServiceAvailableEvent - BeanContextServiceProvider - BeanContextServiceProviderBeanInfo - BeanContextServiceRevokedEvent - BeanContextServiceRevokedListener - BeanContextServices - BeanContextServicesListener - BeanContextServicesSupport - BeanContextServicesSupport.BCSSServiceProvider - BeanContextSupport - BeanContextSupport.BCSIterator - BeanDescriptor - BeanInfo - Beans - BevelBorder - Bidi - BigDecimal - BigInteger - BinaryRefAddr - BindException - Binding - Binding - BindingHelper - BindingHolder - BindingIterator - BindingIteratorHelper - BindingIteratorHolder - BindingIteratorOperations - BindingIteratorPOA - BindingListHelper - BindingListHolder - BindingType - BindingTypeHelper - BindingTypeHolder - BitSet - Blob - BlockView - BlockingQueue - Book - Boolean - BooleanControl - BooleanControl.Type - BooleanHolder - BooleanSeqHelper - BooleanSeqHolder - Border - BorderFactory - BorderLayout - BorderUIResource - BorderUIResource.BevelBorderUIResource - BorderUIResource.CompoundBorderUIResource - BorderUIResource.EmptyBorderUIResource - BorderUIResource.EtchedBorderUIResource - BorderUIResource.LineBorderUIResource - BorderUIResource.MatteBorderUIResource - BorderUIResource.TitledBorderUIResource - BoundedRangeModel - Bounds - Bounds - Box - Box.Filler - BoxLayout - BoxView - BoxedValueHelper - BreakIterator - BrokenBarrierException - Buffer - BufferCapabilities - BufferCapabilities.FlipContents - BufferOverflowException - BufferStrategy - BufferUnderflowException - BufferedImage - BufferedImageFilter - BufferedImageOp - BufferedInputStream - BufferedOutputStream - BufferedReader - BufferedWriter - Button - ButtonGroup - ButtonModel - ButtonUI - Byte - ByteArrayInputStream - ByteArrayOutputStream - ByteBuffer - ByteChannel - ByteHolder - ByteLookupTable - ByteOrder - CDATASection - CMMException - CODESET_INCOMPATIBLE - COMM_FAILURE - CRC32 - CRL - CRLException - CRLSelector - CSS - CSS.Attribute - CTX_RESTRICT_SCOPE - CacheRequest - CacheResponse - CachedRowSet - Calendar - Callable - CallableStatement - Callback - CallbackHandler - CancelablePrintJob - CancellationException - CancelledKeyException - CannotProceed - CannotProceedException - CannotProceedHelper - CannotProceedHolder - CannotRedoException - CannotUndoException - Canvas - CardLayout - Caret - CaretEvent - CaretListener - CellEditor - CellEditorListener - CellRendererPane - CertPath - CertPath.CertPathRep - CertPathBuilder - CertPathBuilderException - CertPathBuilderResult - CertPathBuilderSpi - CertPathParameters - CertPathTrustManagerParameters - CertPathValidator - CertPathValidatorException - CertPathValidatorResult - CertPathValidatorSpi - CertSelector - CertStore - CertStoreException - CertStoreParameters - CertStoreSpi - Certificate - Certificate - Certificate - Certificate.CertificateRep - CertificateEncodingException - CertificateEncodingException - CertificateException - CertificateException - CertificateExpiredException - CertificateExpiredException - CertificateFactory - CertificateFactorySpi - CertificateNotYetValidException - CertificateNotYetValidException - CertificateParsingException - CertificateParsingException - ChangeEvent - ChangeListener - ChangedCharSetException - Channel - ChannelBinding - Channels - CharArrayReader - CharArrayWriter - CharBuffer - CharConversionException - CharHolder - CharSeqHelper - CharSeqHolder - CharSequence - Character - Character.Subset - Character.UnicodeBlock - CharacterCodingException - CharacterData - CharacterIterator - Charset - CharsetDecoder - CharsetEncoder - CharsetProvider - Checkbox - CheckboxGroup - CheckboxMenuItem - CheckedInputStream - CheckedOutputStream - Checksum - Choice - ChoiceCallback - ChoiceFormat - Chromaticity - Cipher - CipherInputStream - CipherOutputStream - CipherSpi - Class - ClassCastException - ClassCircularityError - ClassDefinition - ClassDesc - ClassFileTransformer - ClassFormatError - ClassLoader - ClassLoaderRepository - ClassLoadingMXBean - ClassNotFoundException - ClientRequestInfo - ClientRequestInfoOperations - ClientRequestInterceptor - ClientRequestInterceptorOperations - Clip - Clipboard - ClipboardOwner - Clob - CloneNotSupportedException - Cloneable - Closeable - ClosedByInterruptException - ClosedChannelException - ClosedSelectorException - CodeSets - CodeSigner - CodeSource - Codec - CodecFactory - CodecFactoryHelper - CodecFactoryOperations - CodecOperations - CoderMalfunctionError - CoderResult - CodingErrorAction - CollationElementIterator - CollationKey - Collator - Collection - CollectionCertStoreParameters - Collections - Color - ColorChooserComponentFactory - ColorChooserUI - ColorConvertOp - ColorModel - ColorSelectionModel - ColorSpace - ColorSupported - ColorType - ColorUIResource - ComboBoxEditor - ComboBoxModel - ComboBoxUI - ComboPopup - Comment - CommunicationException - Comparable - Comparator - CompilationMXBean - Compiler - CompletionService - CompletionStatus - CompletionStatusHelper - Component - ComponentAdapter - ComponentColorModel - ComponentEvent - ComponentIdHelper - ComponentInputMap - ComponentInputMapUIResource - ComponentListener - ComponentOrientation - ComponentSampleModel - ComponentUI - ComponentView - Composite - CompositeContext - CompositeData - CompositeDataSupport - CompositeName - CompositeType - CompositeView - CompoundBorder - CompoundControl - CompoundControl.Type - CompoundEdit - CompoundName - Compression - ConcurrentHashMap - ConcurrentLinkedQueue - ConcurrentMap - ConcurrentModificationException - Condition - Configuration - ConfigurationException - ConfirmationCallback - ConnectException - ConnectException - ConnectIOException - Connection - ConnectionEvent - ConnectionEventListener - ConnectionPendingException - ConnectionPoolDataSource - ConsoleHandler - Constructor - Container - ContainerAdapter - ContainerEvent - ContainerListener - ContainerOrderFocusTraversalPolicy - ContentHandler - ContentHandler - ContentHandlerFactory - ContentModel - Context - Context - ContextList - ContextNotEmptyException - ContextualRenderedImageFactory - Control - Control - Control.Type - ControlFactory - ControllerEventListener - ConvolveOp - CookieHandler - CookieHolder - Copies - CopiesSupported - CopyOnWriteArrayList - CopyOnWriteArraySet - CountDownLatch - CounterMonitor - CounterMonitorMBean - CredentialException - CredentialExpiredException - CredentialNotFoundException - CropImageFilter - CubicCurve2D - CubicCurve2D.Double - CubicCurve2D.Float - Currency - Current - Current - Current - CurrentHelper - CurrentHelper - CurrentHelper - CurrentHolder - CurrentOperations - CurrentOperations - CurrentOperations - Cursor - CustomMarshal - CustomValue - Customizer - CyclicBarrier - DATA_CONVERSION - DESKeySpec - DESedeKeySpec - DGC - DHGenParameterSpec - DHKey - DHParameterSpec - DHPrivateKey - DHPrivateKeySpec - DHPublicKey - DHPublicKeySpec - DISCARDING - DOMConfiguration - DOMError - DOMErrorHandler - DOMException - DOMImplementation - DOMImplementationLS - DOMImplementationList - DOMImplementationRegistry - DOMImplementationSource - DOMLocator - DOMLocator - DOMResult - DOMSource - DOMStringList - DSAKey - DSAKeyPairGenerator - DSAParameterSpec - DSAParams - DSAPrivateKey - DSAPrivateKeySpec - DSAPublicKey - DSAPublicKeySpec - DTD - DTDConstants - DTDHandler - DataBuffer - DataBufferByte - DataBufferDouble - DataBufferFloat - DataBufferInt - DataBufferShort - DataBufferUShort - DataFlavor - DataFormatException - DataInput - DataInputStream - DataInputStream - DataLine - DataLine.Info - DataOutput - DataOutputStream - DataOutputStream - DataSource - DataTruncation - DatabaseMetaData - DatagramChannel - DatagramPacket - DatagramSocket - DatagramSocketImpl - DatagramSocketImplFactory - DatatypeConfigurationException - DatatypeConstants - DatatypeConstants.Field - DatatypeFactory - Date - Date - DateFormat - DateFormat.Field - DateFormatSymbols - DateFormatter - DateTimeAtCompleted - DateTimeAtCreation - DateTimeAtProcessing - DateTimeSyntax - DebugGraphics - DecimalFormat - DecimalFormatSymbols - DeclHandler - DefaultBoundedRangeModel - DefaultButtonModel - DefaultCaret - DefaultCellEditor - DefaultColorSelectionModel - DefaultComboBoxModel - DefaultDesktopManager - DefaultEditorKit - DefaultEditorKit.BeepAction - DefaultEditorKit.CopyAction - DefaultEditorKit.CutAction - DefaultEditorKit.DefaultKeyTypedAction - DefaultEditorKit.InsertBreakAction - DefaultEditorKit.InsertContentAction - DefaultEditorKit.InsertTabAction - DefaultEditorKit.PasteAction - DefaultFocusManager - DefaultFocusTraversalPolicy - DefaultFormatter - DefaultFormatterFactory - DefaultHandler - DefaultHandler2 - DefaultHighlighter - DefaultHighlighter.DefaultHighlightPainter - DefaultKeyboardFocusManager - DefaultListCellRenderer - DefaultListCellRenderer.UIResource - DefaultListModel - DefaultListSelectionModel - DefaultLoaderRepository - DefaultLoaderRepository - DefaultMenuLayout - DefaultMetalTheme - DefaultMutableTreeNode - DefaultPersistenceDelegate - DefaultSingleSelectionModel - DefaultStyledDocument - DefaultStyledDocument.AttributeUndoableEdit - DefaultStyledDocument.ElementSpec - DefaultTableCellRenderer - DefaultTableCellRenderer.UIResource - DefaultTableColumnModel - DefaultTableModel - DefaultTextUI - DefaultTreeCellEditor - DefaultTreeCellRenderer - DefaultTreeModel - DefaultTreeSelectionModel - DefinitionKind - DefinitionKindHelper - Deflater - DeflaterOutputStream - DelayQueue - Delayed - Delegate - Delegate - Delegate - DelegationPermission - Deprecated - Descriptor - DescriptorAccess - DescriptorSupport - DesignMode - DesktopIconUI - DesktopManager - DesktopPaneUI - Destination - DestroyFailedException - Destroyable - Dialog - Dictionary - DigestException - DigestInputStream - DigestOutputStream - Dimension - Dimension2D - DimensionUIResource - DirContext - DirObjectFactory - DirStateFactory - DirStateFactory.Result - DirectColorModel - DirectoryManager - DisplayMode - DnDConstants - Doc - DocAttribute - DocAttributeSet - DocFlavor - DocFlavor.BYTE_ARRAY - DocFlavor.CHAR_ARRAY - DocFlavor.INPUT_STREAM - DocFlavor.READER - DocFlavor.SERVICE_FORMATTED - DocFlavor.STRING - DocFlavor.URL - DocPrintJob - Document - Document - DocumentBuilder - DocumentBuilderFactory - DocumentEvent - DocumentEvent.ElementChange - DocumentEvent.EventType - DocumentFilter - DocumentFilter.FilterBypass - DocumentFragment - DocumentHandler - DocumentListener - DocumentName - DocumentParser - DocumentType - Documented - DomainCombiner - DomainManager - DomainManagerOperations - Double - DoubleBuffer - DoubleHolder - DoubleSeqHelper - DoubleSeqHolder - DragGestureEvent - DragGestureListener - DragGestureRecognizer - DragSource - DragSourceAdapter - DragSourceContext - DragSourceDragEvent - DragSourceDropEvent - DragSourceEvent - DragSourceListener - DragSourceMotionListener - Driver - DriverManager - DriverPropertyInfo - DropTarget - DropTarget.DropTargetAutoScroller - DropTargetAdapter - DropTargetContext - DropTargetDragEvent - DropTargetDropEvent - DropTargetEvent - DropTargetListener - DuplicateFormatFlagsException - DuplicateName - DuplicateNameHelper - Duration - DynAny - DynAny - DynAnyFactory - DynAnyFactoryHelper - DynAnyFactoryOperations - DynAnyHelper - DynAnyOperations - DynAnySeqHelper - DynArray - DynArray - DynArrayHelper - DynArrayOperations - DynEnum - DynEnum - DynEnumHelper - DynEnumOperations - DynFixed - DynFixed - DynFixedHelper - DynFixedOperations - DynSequence - DynSequence - DynSequenceHelper - DynSequenceOperations - DynStruct - DynStruct - DynStructHelper - DynStructOperations - DynUnion - DynUnion - DynUnionHelper - DynUnionOperations - DynValue - DynValue - DynValueBox - DynValueBoxOperations - DynValueCommon - DynValueCommonOperations - DynValueHelper - DynValueOperations - DynamicImplementation - DynamicImplementation - DynamicMBean - ECField - ECFieldF2m - ECFieldFp - ECGenParameterSpec - ECKey - ECParameterSpec - ECPoint - ECPrivateKey - ECPrivateKeySpec - ECPublicKey - ECPublicKeySpec - ENCODING_CDR_ENCAPS - EOFException - EditorKit - Element - Element - Element - ElementIterator - ElementType - Ellipse2D - Ellipse2D.Double - Ellipse2D.Float - EllipticCurve - EmptyBorder - EmptyStackException - EncodedKeySpec - Encoder - Encoding - EncryptedPrivateKeyInfo - Entity - Entity - EntityReference - EntityResolver - EntityResolver2 - Enum - EnumConstantNotPresentException - EnumControl - EnumControl.Type - EnumMap - EnumSet - EnumSyntax - Enumeration - Environment - Error - ErrorHandler - ErrorListener - ErrorManager - EtchedBorder - Event - EventContext - EventDirContext - EventHandler - EventListener - EventListenerList - EventListenerProxy - EventObject - EventQueue - EventSetDescriptor - Exception - ExceptionDetailMessage - ExceptionInInitializerError - ExceptionList - ExceptionListener - Exchanger - ExecutionException - Executor - ExecutorCompletionService - ExecutorService - Executors - ExemptionMechanism - ExemptionMechanismException - ExemptionMechanismSpi - ExpandVetoException - ExportException - Expression - ExtendedRequest - ExtendedResponse - Externalizable - FREE_MEM - FactoryConfigurationError - FailedLoginException - FeatureDescriptor - Fidelity - Field - FieldNameHelper - FieldNameHelper - FieldPosition - FieldView - File - FileCacheImageInputStream - FileCacheImageOutputStream - FileChannel - FileChannel.MapMode - FileChooserUI - FileDescriptor - FileDialog - FileFilter - FileFilter - FileHandler - FileImageInputStream - FileImageOutputStream - FileInputStream - FileLock - FileLockInterruptionException - FileNameMap - FileNotFoundException - FileOutputStream - FilePermission - FileReader - FileSystemView - FileView - FileWriter - FilenameFilter - Filter - FilterInputStream - FilterOutputStream - FilterReader - FilterWriter - FilteredImageSource - FilteredRowSet - Finishings - FixedHeightLayoutCache - FixedHolder - FlatteningPathIterator - FlavorEvent - FlavorException - FlavorListener - FlavorMap - FlavorTable - Float - FloatBuffer - FloatControl - FloatControl.Type - FloatHolder - FloatSeqHelper - FloatSeqHolder - FlowLayout - FlowView - FlowView.FlowStrategy - Flushable - FocusAdapter - FocusEvent - FocusListener - FocusManager - FocusTraversalPolicy - Font - FontFormatException - FontMetrics - FontRenderContext - FontUIResource - FormSubmitEvent - FormSubmitEvent.MethodType - FormView - Format - Format.Field - FormatConversionProvider - FormatFlagsConversionMismatchException - FormatMismatch - FormatMismatchHelper - Formattable - FormattableFlags - Formatter - Formatter - FormatterClosedException - ForwardRequest - ForwardRequest - ForwardRequestHelper - ForwardRequestHelper - Frame - Future - FutureTask - GSSContext - GSSCredential - GSSException - GSSManager - GSSName - GZIPInputStream - GZIPOutputStream - GapContent - GarbageCollectorMXBean - GatheringByteChannel - GaugeMonitor - GaugeMonitorMBean - GeneralPath - GeneralSecurityException - GenericArrayType - GenericDeclaration - GenericSignatureFormatError - GlyphJustificationInfo - GlyphMetrics - GlyphVector - GlyphView - GlyphView.GlyphPainter - GradientPaint - GraphicAttribute - Graphics - Graphics2D - GraphicsConfigTemplate - GraphicsConfiguration - GraphicsDevice - GraphicsEnvironment - GrayFilter - GregorianCalendar - GridBagConstraints - GridBagLayout - GridLayout - Group - Guard - GuardedObject - HOLDING - HTML - HTML.Attribute - HTML.Tag - HTML.UnknownTag - HTMLDocument - HTMLDocument.Iterator - HTMLEditorKit - HTMLEditorKit.HTMLFactory - HTMLEditorKit.HTMLTextAction - HTMLEditorKit.InsertHTMLTextAction - HTMLEditorKit.LinkController - HTMLEditorKit.Parser - HTMLEditorKit.ParserCallback - HTMLFrameHyperlinkEvent - HTMLWriter - Handler - HandlerBase - HandshakeCompletedEvent - HandshakeCompletedListener - HasControls - HashAttributeSet - HashDocAttributeSet - HashMap - HashPrintJobAttributeSet - HashPrintRequestAttributeSet - HashPrintServiceAttributeSet - HashSet - Hashtable - HeadlessException - HierarchyBoundsAdapter - HierarchyBoundsListener - HierarchyEvent - HierarchyListener - Highlighter - Highlighter.Highlight - Highlighter.HighlightPainter - HostnameVerifier - HttpRetryException - HttpURLConnection - HttpsURLConnection - HyperlinkEvent - HyperlinkEvent.EventType - HyperlinkListener - ICC_ColorSpace - ICC_Profile - ICC_ProfileGray - ICC_ProfileRGB - IDLEntity - IDLType - IDLTypeHelper - IDLTypeOperations - ID_ASSIGNMENT_POLICY_ID - ID_UNIQUENESS_POLICY_ID - IIOByteBuffer - IIOException - IIOImage - IIOInvalidTreeException - IIOMetadata - IIOMetadataController - IIOMetadataFormat - IIOMetadataFormatImpl - IIOMetadataNode - IIOParam - IIOParamController - IIOReadProgressListener - IIOReadUpdateListener - IIOReadWarningListener - IIORegistry - IIOServiceProvider - IIOWriteProgressListener - IIOWriteWarningListener - IMPLICIT_ACTIVATION_POLICY_ID - IMP_LIMIT - INACTIVE - INITIALIZE - INTERNAL - INTF_REPOS - INVALID_ACTIVITY - INVALID_TRANSACTION - INV_FLAG - INV_IDENT - INV_OBJREF - INV_POLICY - IOException - IOR - IORHelper - IORHolder - IORInfo - IORInfoOperations - IORInterceptor - IORInterceptorOperations - IORInterceptor_3_0 - IORInterceptor_3_0Helper - IORInterceptor_3_0Holder - IORInterceptor_3_0Operations - IRObject - IRObjectOperations - Icon - IconUIResource - IconView - IdAssignmentPolicy - IdAssignmentPolicyOperations - IdAssignmentPolicyValue - IdUniquenessPolicy - IdUniquenessPolicyOperations - IdUniquenessPolicyValue - IdentifierHelper - Identity - IdentityHashMap - IdentityScope - IllegalAccessError - IllegalAccessException - IllegalArgumentException - IllegalBlockSizeException - IllegalBlockingModeException - IllegalCharsetNameException - IllegalClassFormatException - IllegalComponentStateException - IllegalFormatCodePointException - IllegalFormatConversionException - IllegalFormatException - IllegalFormatFlagsException - IllegalFormatPrecisionException - IllegalFormatWidthException - IllegalMonitorStateException - IllegalPathStateException - IllegalSelectorException - IllegalStateException - IllegalThreadStateException - Image - ImageCapabilities - ImageConsumer - ImageFilter - ImageGraphicAttribute - ImageIO - ImageIcon - ImageInputStream - ImageInputStreamImpl - ImageInputStreamSpi - ImageObserver - ImageOutputStream - ImageOutputStreamImpl - ImageOutputStreamSpi - ImageProducer - ImageReadParam - ImageReader - ImageReaderSpi - ImageReaderWriterSpi - ImageTranscoder - ImageTranscoderSpi - ImageTypeSpecifier - ImageView - ImageWriteParam - ImageWriter - ImageWriterSpi - ImagingOpException - ImplicitActivationPolicy - ImplicitActivationPolicyOperations - ImplicitActivationPolicyValue - IncompatibleClassChangeError - IncompleteAnnotationException - InconsistentTypeCode - InconsistentTypeCode - InconsistentTypeCodeHelper - IndexColorModel - IndexOutOfBoundsException - IndexedPropertyChangeEvent - IndexedPropertyDescriptor - IndirectionException - Inet4Address - Inet6Address - InetAddress - InetSocketAddress - Inflater - InflaterInputStream - InheritableThreadLocal - Inherited - InitialContext - InitialContextFactory - InitialContextFactoryBuilder - InitialDirContext - InitialLdapContext - InlineView - InputContext - InputEvent - InputMap - InputMapUIResource - InputMethod - InputMethodContext - InputMethodDescriptor - InputMethodEvent - InputMethodHighlight - InputMethodListener - InputMethodRequests - InputMismatchException - InputSource - InputStream - InputStream - InputStream - InputStreamReader - InputSubset - InputVerifier - Insets - InsetsUIResource - InstanceAlreadyExistsException - InstanceNotFoundException - InstantiationError - InstantiationException - Instrument - Instrumentation - InsufficientResourcesException - IntBuffer - IntHolder - Integer - IntegerSyntax - Interceptor - InterceptorOperations - InternalError - InternalFrameAdapter - InternalFrameEvent - InternalFrameFocusTraversalPolicy - InternalFrameListener - InternalFrameUI - InternationalFormatter - InterruptedException - InterruptedIOException - InterruptedNamingException - InterruptibleChannel - IntrospectionException - IntrospectionException - Introspector - Invalid - InvalidActivityException - InvalidAddress - InvalidAddressHelper - InvalidAddressHolder - InvalidAlgorithmParameterException - InvalidApplicationException - InvalidAttributeIdentifierException - InvalidAttributeValueException - InvalidAttributeValueException - InvalidAttributesException - InvalidClassException - InvalidDnDOperationException - InvalidKeyException - InvalidKeyException - InvalidKeySpecException - InvalidMarkException - InvalidMidiDataException - InvalidName - InvalidName - InvalidName - InvalidNameException - InvalidNameHelper - InvalidNameHelper - InvalidNameHolder - InvalidObjectException - InvalidOpenTypeException - InvalidParameterException - InvalidParameterSpecException - InvalidPolicy - InvalidPolicyHelper - InvalidPreferencesFormatException - InvalidPropertiesFormatException - InvalidRelationIdException - InvalidRelationServiceException - InvalidRelationTypeException - InvalidRoleInfoException - InvalidRoleValueException - InvalidSearchControlsException - InvalidSearchFilterException - InvalidSeq - InvalidSlot - InvalidSlotHelper - InvalidTargetObjectTypeException - InvalidTransactionException - InvalidTypeForEncoding - InvalidTypeForEncodingHelper - InvalidValue - InvalidValue - InvalidValueHelper - InvocationEvent - InvocationHandler - InvocationTargetException - InvokeHandler - IstringHelper - ItemEvent - ItemListener - ItemSelectable - Iterable - Iterator - IvParameterSpec - JApplet - JButton - JCheckBox - JCheckBoxMenuItem - JColorChooser - JComboBox - JComboBox.KeySelectionManager - JComponent - JDesktopPane - JDialog - JEditorPane - JFileChooser - JFormattedTextField - JFormattedTextField.AbstractFormatter - JFormattedTextField.AbstractFormatterFactory - JFrame - JInternalFrame - JInternalFrame.JDesktopIcon - JLabel - JLayeredPane - JList - JMException - JMRuntimeException - JMXAuthenticator - JMXConnectionNotification - JMXConnector - JMXConnectorFactory - JMXConnectorProvider - JMXConnectorServer - JMXConnectorServerFactory - JMXConnectorServerMBean - JMXConnectorServerProvider - JMXPrincipal - JMXProviderException - JMXServerErrorException - JMXServiceURL - JMenu - JMenuBar - JMenuItem - JOptionPane - JPEGHuffmanTable - JPEGImageReadParam - JPEGImageWriteParam - JPEGQTable - JPanel - JPasswordField - JPopupMenu - JPopupMenu.Separator - JProgressBar - JRadioButton - JRadioButtonMenuItem - JRootPane - JScrollBar - JScrollPane - JSeparator - JSlider - JSpinner - JSpinner.DateEditor - JSpinner.DefaultEditor - JSpinner.ListEditor - JSpinner.NumberEditor - JSplitPane - JTabbedPane - JTable - JTable.PrintMode - JTableHeader - JTextArea - JTextComponent - JTextComponent.KeyBinding - JTextField - JTextPane - JToggleButton - JToggleButton.ToggleButtonModel - JToolBar - JToolBar.Separator - JToolTip - JTree - JTree.DynamicUtilTreeNode - JTree.EmptySelectionModel - JViewport - JWindow - JarEntry - JarException - JarFile - JarInputStream - JarOutputStream - JarURLConnection - JdbcRowSet - JobAttributes - JobAttributes.DefaultSelectionType - JobAttributes.DestinationType - JobAttributes.DialogType - JobAttributes.MultipleDocumentHandlingType - JobAttributes.SidesType - JobHoldUntil - JobImpressions - JobImpressionsCompleted - JobImpressionsSupported - JobKOctets - JobKOctetsProcessed - JobKOctetsSupported - JobMediaSheets - JobMediaSheetsCompleted - JobMediaSheetsSupported - JobMessageFromOperator - JobName - JobOriginatingUserName - JobPriority - JobPrioritySupported - JobSheets - JobState - JobStateReason - JobStateReasons - JoinRowSet - Joinable - KerberosKey - KerberosPrincipal - KerberosTicket - Kernel - Key - KeyAdapter - KeyAgreement - KeyAgreementSpi - KeyAlreadyExistsException - KeyEvent - KeyEventDispatcher - KeyEventPostProcessor - KeyException - KeyFactory - KeyFactorySpi - KeyGenerator - KeyGeneratorSpi - KeyListener - KeyManagementException - KeyManager - KeyManagerFactory - KeyManagerFactorySpi - KeyPair - KeyPairGenerator - KeyPairGeneratorSpi - KeyRep - KeyRep.Type - KeySpec - KeyStore - KeyStore.Builder - KeyStore.CallbackHandlerProtection - KeyStore.Entry - KeyStore.LoadStoreParameter - KeyStore.PasswordProtection - KeyStore.PrivateKeyEntry - KeyStore.ProtectionParameter - KeyStore.SecretKeyEntry - KeyStore.TrustedCertificateEntry - KeyStoreBuilderParameters - KeyStoreException - KeyStoreSpi - KeyStroke - KeyboardFocusManager - Keymap - LDAPCertStoreParameters - LIFESPAN_POLICY_ID - LOCATION_FORWARD - LSException - LSInput - LSLoadEvent - LSOutput - LSParser - LSParserFilter - LSProgressEvent - LSResourceResolver - LSSerializer - LSSerializerFilter - Label - LabelUI - LabelView - LanguageCallback - LastOwnerException - LayeredHighlighter - LayeredHighlighter.LayerPainter - LayoutFocusTraversalPolicy - LayoutManager - LayoutManager2 - LayoutQueue - LdapContext - LdapName - LdapReferralException - Lease - Level - LexicalHandler - LifespanPolicy - LifespanPolicyOperations - LifespanPolicyValue - LimitExceededException - Line - Line.Info - Line2D - Line2D.Double - Line2D.Float - LineBorder - LineBreakMeasurer - LineEvent - LineEvent.Type - LineListener - LineMetrics - LineNumberInputStream - LineNumberReader - LineUnavailableException - LinkException - LinkLoopException - LinkRef - LinkageError - LinkedBlockingQueue - LinkedHashMap - LinkedHashSet - LinkedList - List - List - ListCellRenderer - ListDataEvent - ListDataListener - ListIterator - ListModel - ListResourceBundle - ListSelectionEvent - ListSelectionListener - ListSelectionModel - ListUI - ListView - ListenerNotFoundException - LoaderHandler - LocalObject - Locale - LocateRegistry - Locator - Locator2 - Locator2Impl - LocatorImpl - Lock - LockSupport - LogManager - LogRecord - LogStream - Logger - LoggingMXBean - LoggingPermission - LoginContext - LoginException - LoginModule - Long - LongBuffer - LongHolder - LongLongSeqHelper - LongLongSeqHolder - LongSeqHelper - LongSeqHolder - LookAndFeel - LookupOp - LookupTable - MARSHAL - MBeanAttributeInfo - MBeanConstructorInfo - MBeanException - MBeanFeatureInfo - MBeanInfo - MBeanNotificationInfo - MBeanOperationInfo - MBeanParameterInfo - MBeanPermission - MBeanRegistration - MBeanRegistrationException - MBeanServer - MBeanServerBuilder - MBeanServerConnection - MBeanServerDelegate - MBeanServerDelegateMBean - MBeanServerFactory - MBeanServerForwarder - MBeanServerInvocationHandler - MBeanServerNotification - MBeanServerNotificationFilter - MBeanServerPermission - MBeanTrustPermission - MGF1ParameterSpec - MLet - MLetMBean - Mac - MacSpi - MalformedInputException - MalformedLinkException - MalformedObjectNameException - MalformedParameterizedTypeException - MalformedURLException - ManageReferralControl - ManagementFactory - ManagementPermission - ManagerFactoryParameters - Manifest - Map - Map.Entry - MappedByteBuffer - MarshalException - MarshalledObject - MaskFormatter - MatchResult - Matcher - Math - MathContext - MatteBorder - Media - MediaName - MediaPrintableArea - MediaSize - MediaSize.Engineering - MediaSize.ISO - MediaSize.JIS - MediaSize.NA - MediaSize.Other - MediaSizeName - MediaTracker - MediaTray - Member - MemoryCacheImageInputStream - MemoryCacheImageOutputStream - MemoryHandler - MemoryImageSource - MemoryMXBean - MemoryManagerMXBean - MemoryNotificationInfo - MemoryPoolMXBean - MemoryType - MemoryUsage - Menu - MenuBar - MenuBarUI - MenuComponent - MenuContainer - MenuDragMouseEvent - MenuDragMouseListener - MenuElement - MenuEvent - MenuItem - MenuItemUI - MenuKeyEvent - MenuKeyListener - MenuListener - MenuSelectionManager - MenuShortcut - MessageDigest - MessageDigestSpi - MessageFormat - MessageFormat.Field - MessageProp - MetaEventListener - MetaMessage - MetalBorders - MetalBorders.ButtonBorder - MetalBorders.Flush3DBorder - MetalBorders.InternalFrameBorder - MetalBorders.MenuBarBorder - MetalBorders.MenuItemBorder - MetalBorders.OptionDialogBorder - MetalBorders.PaletteBorder - MetalBorders.PopupMenuBorder - MetalBorders.RolloverButtonBorder - MetalBorders.ScrollPaneBorder - MetalBorders.TableHeaderBorder - MetalBorders.TextFieldBorder - MetalBorders.ToggleButtonBorder - MetalBorders.ToolBarBorder - MetalButtonUI - MetalCheckBoxIcon - MetalCheckBoxUI - MetalComboBoxButton - MetalComboBoxEditor - MetalComboBoxEditor.UIResource - MetalComboBoxIcon - MetalComboBoxUI - MetalDesktopIconUI - MetalFileChooserUI - MetalIconFactory - MetalIconFactory.FileIcon16 - MetalIconFactory.FolderIcon16 - MetalIconFactory.PaletteCloseIcon - MetalIconFactory.TreeControlIcon - MetalIconFactory.TreeFolderIcon - MetalIconFactory.TreeLeafIcon - MetalInternalFrameTitlePane - MetalInternalFrameUI - MetalLabelUI - MetalLookAndFeel - MetalMenuBarUI - MetalPopupMenuSeparatorUI - MetalProgressBarUI - MetalRadioButtonUI - MetalRootPaneUI - MetalScrollBarUI - MetalScrollButton - MetalScrollPaneUI - MetalSeparatorUI - MetalSliderUI - MetalSplitPaneUI - MetalTabbedPaneUI - MetalTextFieldUI - MetalTheme - MetalToggleButtonUI - MetalToolBarUI - MetalToolTipUI - MetalTreeUI - Method - MethodDescriptor - MidiChannel - MidiDevice - MidiDevice.Info - MidiDeviceProvider - MidiEvent - MidiFileFormat - MidiFileReader - MidiFileWriter - MidiMessage - MidiSystem - MidiUnavailableException - MimeTypeParseException - MinimalHTMLWriter - MissingFormatArgumentException - MissingFormatWidthException - MissingResourceException - Mixer - Mixer.Info - MixerProvider - ModelMBean - ModelMBeanAttributeInfo - ModelMBeanConstructorInfo - ModelMBeanInfo - ModelMBeanInfoSupport - ModelMBeanNotificationBroadcaster - ModelMBeanNotificationInfo - ModelMBeanOperationInfo - ModificationItem - Modifier - Monitor - MonitorMBean - MonitorNotification - MonitorSettingException - MouseAdapter - MouseDragGestureRecognizer - MouseEvent - MouseInfo - MouseInputAdapter - MouseInputListener - MouseListener - MouseMotionAdapter - MouseMotionListener - MouseWheelEvent - MouseWheelListener - MultiButtonUI - MultiColorChooserUI - MultiComboBoxUI - MultiDesktopIconUI - MultiDesktopPaneUI - MultiDoc - MultiDocPrintJob - MultiDocPrintService - MultiFileChooserUI - MultiInternalFrameUI - MultiLabelUI - MultiListUI - MultiLookAndFeel - MultiMenuBarUI - MultiMenuItemUI - MultiOptionPaneUI - MultiPanelUI - MultiPixelPackedSampleModel - MultiPopupMenuUI - MultiProgressBarUI - MultiRootPaneUI - MultiScrollBarUI - MultiScrollPaneUI - MultiSeparatorUI - MultiSliderUI - MultiSpinnerUI - MultiSplitPaneUI - MultiTabbedPaneUI - MultiTableHeaderUI - MultiTableUI - MultiTextUI - MultiToolBarUI - MultiToolTipUI - MultiTreeUI - MultiViewportUI - MulticastSocket - MultipleComponentProfileHelper - MultipleComponentProfileHolder - MultipleDocumentHandling - MultipleMaster - MutableAttributeSet - MutableComboBoxModel - MutableTreeNode - NON_EXISTENT - NO_IMPLEMENT - NO_MEMORY - NO_PERMISSION - NO_RESOURCES - NO_RESPONSE - NVList - Name - NameAlreadyBoundException - NameCallback - NameClassPair - NameComponent - NameComponentHelper - NameComponentHolder - NameDynAnyPair - NameDynAnyPairHelper - NameDynAnyPairSeqHelper - NameHelper - NameHolder - NameList - NameNotFoundException - NameParser - NameValuePair - NameValuePair - NameValuePairHelper - NameValuePairHelper - NameValuePairSeqHelper - NamedNodeMap - NamedValue - NamespaceChangeListener - NamespaceContext - NamespaceSupport - Naming - NamingContext - NamingContextExt - NamingContextExtHelper - NamingContextExtHolder - NamingContextExtOperations - NamingContextExtPOA - NamingContextHelper - NamingContextHolder - NamingContextOperations - NamingContextPOA - NamingEnumeration - NamingEvent - NamingException - NamingExceptionEvent - NamingListener - NamingManager - NamingSecurityException - NavigationFilter - NavigationFilter.FilterBypass - NegativeArraySizeException - NetPermission - NetworkInterface - NoClassDefFoundError - NoConnectionPendingException - NoContext - NoContextHelper - NoInitialContextException - NoPermissionException - NoRouteToHostException - NoServant - NoServantHelper - NoSuchAlgorithmException - NoSuchAttributeException - NoSuchElementException - NoSuchFieldError - NoSuchFieldException - NoSuchMethodError - NoSuchMethodException - NoSuchObjectException - NoSuchPaddingException - NoSuchProviderException - Node - NodeChangeEvent - NodeChangeListener - NodeList - NonReadableChannelException - NonWritableChannelException - NoninvertibleTransformException - NotActiveException - NotBoundException - NotCompliantMBeanException - NotContextException - NotEmpty - NotEmptyHelper - NotEmptyHolder - NotFound - NotFoundHelper - NotFoundHolder - NotFoundReason - NotFoundReasonHelper - NotFoundReasonHolder - NotOwnerException - NotSerializableException - NotYetBoundException - NotYetConnectedException - Notation - Notification - NotificationBroadcaster - NotificationBroadcasterSupport - NotificationEmitter - NotificationFilter - NotificationFilterSupport - NotificationListener - NotificationResult - NullCipher - NullPointerException - Number - NumberFormat - NumberFormat.Field - NumberFormatException - NumberFormatter - NumberOfDocuments - NumberOfInterveningJobs - NumberUp - NumberUpSupported - NumericShaper - OAEPParameterSpec - OBJECT_NOT_EXIST - OBJ_ADAPTER - OMGVMCID - ORB - ORB - ORBIdHelper - ORBInitInfo - ORBInitInfoOperations - ORBInitializer - ORBInitializerOperations - ObjID - Object - Object - ObjectAlreadyActive - ObjectAlreadyActiveHelper - ObjectChangeListener - ObjectFactory - ObjectFactoryBuilder - ObjectHelper - ObjectHolder - ObjectIdHelper - ObjectIdHelper - ObjectImpl - ObjectImpl - ObjectInput - ObjectInputStream - ObjectInputStream.GetField - ObjectInputValidation - ObjectInstance - ObjectName - ObjectNotActive - ObjectNotActiveHelper - ObjectOutput - ObjectOutputStream - ObjectOutputStream.PutField - ObjectReferenceFactory - ObjectReferenceFactoryHelper - ObjectReferenceFactoryHolder - ObjectReferenceTemplate - ObjectReferenceTemplateHelper - ObjectReferenceTemplateHolder - ObjectReferenceTemplateSeqHelper - ObjectReferenceTemplateSeqHolder - ObjectStreamClass - ObjectStreamConstants - ObjectStreamException - ObjectStreamField - ObjectView - Observable - Observer - OceanTheme - OctetSeqHelper - OctetSeqHolder - Oid - OpenDataException - OpenMBeanAttributeInfo - OpenMBeanAttributeInfoSupport - OpenMBeanConstructorInfo - OpenMBeanConstructorInfoSupport - OpenMBeanInfo - OpenMBeanInfoSupport - OpenMBeanOperationInfo - OpenMBeanOperationInfoSupport - OpenMBeanParameterInfo - OpenMBeanParameterInfoSupport - OpenType - OpenType - OperatingSystemMXBean - Operation - OperationNotSupportedException - OperationsException - Option - OptionPaneUI - OptionalDataException - OrientationRequested - OutOfMemoryError - OutputDeviceAssigned - OutputKeys - OutputStream - OutputStream - OutputStream - OutputStreamWriter - OverlappingFileLockException - OverlayLayout - Override - Owner - PBEKey - PBEKeySpec - PBEParameterSpec - PDLOverrideSupported - PERSIST_STORE - PKCS8EncodedKeySpec - PKIXBuilderParameters - PKIXCertPathBuilderResult - PKIXCertPathChecker - PKIXCertPathValidatorResult - PKIXParameters - POA - POAHelper - POAManager - POAManagerOperations - POAOperations - PRIVATE_MEMBER - PSSParameterSpec - PSource - PSource.PSpecified - PUBLIC_MEMBER - Pack200 - Pack200.Packer - Pack200.Unpacker - Package - PackedColorModel - PageAttributes - PageAttributes.ColorType - PageAttributes.MediaType - PageAttributes.OrientationRequestedType - PageAttributes.OriginType - PageAttributes.PrintQualityType - PageFormat - PageRanges - Pageable - PagedResultsControl - PagedResultsResponseControl - PagesPerMinute - PagesPerMinuteColor - Paint - PaintContext - PaintEvent - Panel - PanelUI - Paper - ParagraphView - ParagraphView - Parameter - ParameterBlock - ParameterDescriptor - ParameterMetaData - ParameterMode - ParameterModeHelper - ParameterModeHolder - ParameterizedType - ParseException - ParsePosition - Parser - Parser - ParserAdapter - ParserConfigurationException - ParserDelegator - ParserFactory - PartialResultException - PasswordAuthentication - PasswordCallback - PasswordView - Patch - PathIterator - Pattern - PatternSyntaxException - Permission - Permission - PermissionCollection - Permissions - PersistenceDelegate - PersistentMBean - PhantomReference - Pipe - Pipe.SinkChannel - Pipe.SourceChannel - PipedInputStream - PipedOutputStream - PipedReader - PipedWriter - PixelGrabber - PixelInterleavedSampleModel - PlainDocument - PlainView - Point - Point2D - Point2D.Double - Point2D.Float - PointerInfo - Policy - Policy - Policy - PolicyError - PolicyErrorCodeHelper - PolicyErrorHelper - PolicyErrorHolder - PolicyFactory - PolicyFactoryOperations - PolicyHelper - PolicyHolder - PolicyListHelper - PolicyListHolder - PolicyNode - PolicyOperations - PolicyQualifierInfo - PolicyTypeHelper - Polygon - PooledConnection - Popup - PopupFactory - PopupMenu - PopupMenuEvent - PopupMenuListener - PopupMenuUI - Port - Port.Info - PortUnreachableException - PortableRemoteObject - PortableRemoteObjectDelegate - Position - Position.Bias - Predicate - PreferenceChangeEvent - PreferenceChangeListener - Preferences - PreferencesFactory - PreparedStatement - PresentationDirection - Principal - Principal - PrincipalHolder - PrintEvent - PrintException - PrintGraphics - PrintJob - PrintJobAdapter - PrintJobAttribute - PrintJobAttributeEvent - PrintJobAttributeListener - PrintJobAttributeSet - PrintJobEvent - PrintJobListener - PrintQuality - PrintRequestAttribute - PrintRequestAttributeSet - PrintService - PrintServiceAttribute - PrintServiceAttributeEvent - PrintServiceAttributeListener - PrintServiceAttributeSet - PrintServiceLookup - PrintStream - PrintWriter - Printable - PrinterAbortException - PrinterException - PrinterGraphics - PrinterIOException - PrinterInfo - PrinterIsAcceptingJobs - PrinterJob - PrinterLocation - PrinterMakeAndModel - PrinterMessageFromOperator - PrinterMoreInfo - PrinterMoreInfoManufacturer - PrinterName - PrinterResolution - PrinterState - PrinterStateReason - PrinterStateReasons - PrinterURI - PriorityBlockingQueue - PriorityQueue - PrivateClassLoader - PrivateCredentialPermission - PrivateKey - PrivateMLet - PrivilegedAction - PrivilegedActionException - PrivilegedExceptionAction - Process - ProcessBuilder - ProcessingInstruction - ProfileDataException - ProfileIdHelper - ProgressBarUI - ProgressMonitor - ProgressMonitorInputStream - Properties - PropertyChangeEvent - PropertyChangeListener - PropertyChangeListenerProxy - PropertyChangeSupport - PropertyDescriptor - PropertyEditor - PropertyEditorManager - PropertyEditorSupport - PropertyPermission - PropertyResourceBundle - PropertyVetoException - ProtectionDomain - ProtocolException - Provider - Provider.Service - ProviderException - Proxy - Proxy - Proxy.Type - ProxySelector - PublicKey - PushbackInputStream - PushbackReader - QName - QuadCurve2D - QuadCurve2D.Double - QuadCurve2D.Float - Query - QueryEval - QueryExp - Queue - QueuedJobCount - RC2ParameterSpec - RC5ParameterSpec - REBIND - REQUEST_PROCESSING_POLICY_ID - RGBImageFilter - RMIClassLoader - RMIClassLoaderSpi - RMIClientSocketFactory - RMIConnection - RMIConnectionImpl - RMIConnectionImpl_Stub - RMIConnector - RMIConnectorServer - RMICustomMaxStreamFormat - RMIFailureHandler - RMIIIOPServerImpl - RMIJRMPServerImpl - RMISecurityException - RMISecurityManager - RMIServer - RMIServerImpl - RMIServerImpl_Stub - RMIServerSocketFactory - RMISocketFactory - RSAKey - RSAKeyGenParameterSpec - RSAMultiPrimePrivateCrtKey - RSAMultiPrimePrivateCrtKeySpec - RSAOtherPrimeInfo - RSAPrivateCrtKey - RSAPrivateCrtKeySpec - RSAPrivateKey - RSAPrivateKeySpec - RSAPublicKey - RSAPublicKeySpec - RTFEditorKit - Random - RandomAccess - RandomAccessFile - Raster - RasterFormatException - RasterOp - Rdn - ReadOnlyBufferException - ReadWriteLock - Readable - ReadableByteChannel - Reader - RealmCallback - RealmChoiceCallback - Receiver - Rectangle - Rectangle2D - Rectangle2D.Double - Rectangle2D.Float - RectangularShape - ReentrantLock - ReentrantReadWriteLock - ReentrantReadWriteLock.ReadLock - ReentrantReadWriteLock.WriteLock - Ref - RefAddr - Reference - Reference - ReferenceQueue - ReferenceUriSchemesSupported - Referenceable - ReferralException - ReflectPermission - ReflectionException - RefreshFailedException - Refreshable - Region - RegisterableService - Registry - RegistryHandler - RejectedExecutionException - RejectedExecutionHandler - Relation - RelationException - RelationNotFoundException - RelationNotification - RelationService - RelationServiceMBean - RelationServiceNotRegisteredException - RelationSupport - RelationSupportMBean - RelationType - RelationTypeNotFoundException - RelationTypeSupport - RemarshalException - Remote - RemoteCall - RemoteException - RemoteObject - RemoteObjectInvocationHandler - RemoteRef - RemoteServer - RemoteStub - RenderContext - RenderableImage - RenderableImageOp - RenderableImageProducer - RenderedImage - RenderedImageFactory - Renderer - RenderingHints - RenderingHints.Key - RepaintManager - ReplicateScaleFilter - RepositoryIdHelper - Request - RequestInfo - RequestInfoOperations - RequestProcessingPolicy - RequestProcessingPolicyOperations - RequestProcessingPolicyValue - RequestingUserName - RequiredModelMBean - RescaleOp - ResolutionSyntax - ResolveResult - Resolver - ResourceBundle - ResponseCache - ResponseHandler - Result - ResultSet - ResultSetMetaData - Retention - RetentionPolicy - ReverbType - Robot - Role - RoleInfo - RoleInfoNotFoundException - RoleList - RoleNotFoundException - RoleResult - RoleStatus - RoleUnresolved - RoleUnresolvedList - RootPaneContainer - RootPaneUI - RoundRectangle2D - RoundRectangle2D.Double - RoundRectangle2D.Float - RoundingMode - RowMapper - RowSet - RowSetEvent - RowSetInternal - RowSetListener - RowSetMetaData - RowSetMetaDataImpl - RowSetReader - RowSetWarning - RowSetWriter - RuleBasedCollator - RunTime - RunTimeOperations - Runnable - Runtime - RuntimeErrorException - RuntimeException - RuntimeMBeanException - RuntimeMXBean - RuntimeOperationsException - RuntimePermission - SAXException - SAXNotRecognizedException - SAXNotSupportedException - SAXParseException - SAXParser - SAXParserFactory - SAXResult - SAXSource - SAXTransformerFactory - SERVANT_RETENTION_POLICY_ID - SQLData - SQLException - SQLInput - SQLInputImpl - SQLOutput - SQLOutputImpl - SQLPermission - SQLWarning - SSLContext - SSLContextSpi - SSLEngine - SSLEngineResult - SSLEngineResult.HandshakeStatus - SSLEngineResult.Status - SSLException - SSLHandshakeException - SSLKeyException - SSLPeerUnverifiedException - SSLPermission - SSLProtocolException - SSLServerSocket - SSLServerSocketFactory - SSLSession - SSLSessionBindingEvent - SSLSessionBindingListener - SSLSessionContext - SSLSocket - SSLSocketFactory - SUCCESSFUL - SYNC_WITH_TRANSPORT - SYSTEM_EXCEPTION - SampleModel - Sasl - SaslClient - SaslClientFactory - SaslException - SaslServer - SaslServerFactory - Savepoint - Scanner - ScatteringByteChannel - ScheduledExecutorService - ScheduledFuture - ScheduledThreadPoolExecutor - Schema - SchemaFactory - SchemaFactoryLoader - SchemaViolationException - ScrollBarUI - ScrollPane - ScrollPaneAdjustable - ScrollPaneConstants - ScrollPaneLayout - ScrollPaneLayout.UIResource - ScrollPaneUI - Scrollable - Scrollbar - SealedObject - SearchControls - SearchResult - SecretKey - SecretKeyFactory - SecretKeyFactorySpi - SecretKeySpec - SecureCacheResponse - SecureClassLoader - SecureRandom - SecureRandomSpi - Security - SecurityException - SecurityManager - SecurityPermission - Segment - SelectableChannel - SelectionKey - Selector - SelectorProvider - Semaphore - SeparatorUI - Sequence - SequenceInputStream - Sequencer - Sequencer.SyncMode - SerialArray - SerialBlob - SerialClob - SerialDatalink - SerialException - SerialJavaObject - SerialRef - SerialStruct - Serializable - SerializablePermission - Servant - ServantActivator - ServantActivatorHelper - ServantActivatorOperations - ServantActivatorPOA - ServantAlreadyActive - ServantAlreadyActiveHelper - ServantLocator - ServantLocatorHelper - ServantLocatorOperations - ServantLocatorPOA - ServantManager - ServantManagerOperations - ServantNotActive - ServantNotActiveHelper - ServantObject - ServantRetentionPolicy - ServantRetentionPolicyOperations - ServantRetentionPolicyValue - ServerCloneException - ServerError - ServerException - ServerIdHelper - ServerNotActiveException - ServerRef - ServerRequest - ServerRequestInfo - ServerRequestInfoOperations - ServerRequestInterceptor - ServerRequestInterceptorOperations - ServerRuntimeException - ServerSocket - ServerSocketChannel - ServerSocketFactory - ServiceContext - ServiceContextHelper - ServiceContextHolder - ServiceContextListHelper - ServiceContextListHolder - ServiceDetail - ServiceDetailHelper - ServiceIdHelper - ServiceInformation - ServiceInformationHelper - ServiceInformationHolder - ServiceNotFoundException - ServicePermission - ServiceRegistry - ServiceRegistry.Filter - ServiceUI - ServiceUIFactory - ServiceUnavailableException - Set - SetOfIntegerSyntax - SetOverrideType - SetOverrideTypeHelper - Severity - Shape - ShapeGraphicAttribute - SheetCollate - Short - ShortBuffer - ShortBufferException - ShortHolder - ShortLookupTable - ShortMessage - ShortSeqHelper - ShortSeqHolder - Sides - Signature - SignatureException - SignatureSpi - SignedObject - Signer - SimpleAttributeSet - SimpleBeanInfo - SimpleDateFormat - SimpleDoc - SimpleFormatter - SimpleTimeZone - SimpleType - SinglePixelPackedSampleModel - SingleSelectionModel - Size2DSyntax - SizeLimitExceededException - SizeRequirements - SizeSequence - Skeleton - SkeletonMismatchException - SkeletonNotFoundException - SliderUI - Socket - SocketAddress - SocketChannel - SocketException - SocketFactory - SocketHandler - SocketImpl - SocketImplFactory - SocketOptions - SocketPermission - SocketSecurityException - SocketTimeoutException - SoftBevelBorder - SoftReference - SortControl - SortKey - SortResponseControl - SortedMap - SortedSet - SortingFocusTraversalPolicy - Soundbank - SoundbankReader - SoundbankResource - Source - SourceDataLine - SourceLocator - SpinnerDateModel - SpinnerListModel - SpinnerModel - SpinnerNumberModel - SpinnerUI - SplitPaneUI - Spring - SpringLayout - SpringLayout.Constraints - SslRMIClientSocketFactory - SslRMIServerSocketFactory - Stack - StackOverflowError - StackTraceElement - StandardMBean - StartTlsRequest - StartTlsResponse - State - StateEdit - StateEditable - StateFactory - Statement - Statement - StreamCorruptedException - StreamHandler - StreamPrintService - StreamPrintServiceFactory - StreamResult - StreamSource - StreamTokenizer - Streamable - StreamableValue - StrictMath - String - StringBuffer - StringBufferInputStream - StringBuilder - StringCharacterIterator - StringContent - StringHolder - StringIndexOutOfBoundsException - StringMonitor - StringMonitorMBean - StringNameHelper - StringReader - StringRefAddr - StringSelection - StringSeqHelper - StringSeqHolder - StringTokenizer - StringValueExp - StringValueHelper - StringWriter - Stroke - Struct - StructMember - StructMemberHelper - Stub - StubDelegate - StubNotFoundException - Style - StyleConstants - StyleConstants.CharacterConstants - StyleConstants.ColorConstants - StyleConstants.FontConstants - StyleConstants.ParagraphConstants - StyleContext - StyleSheet - StyleSheet.BoxPainter - StyleSheet.ListPainter - StyledDocument - StyledEditorKit - StyledEditorKit.AlignmentAction - StyledEditorKit.BoldAction - StyledEditorKit.FontFamilyAction - StyledEditorKit.FontSizeAction - StyledEditorKit.ForegroundAction - StyledEditorKit.ItalicAction - StyledEditorKit.StyledTextAction - StyledEditorKit.UnderlineAction - Subject - SubjectDelegationPermission - SubjectDomainCombiner - SupportedValuesAttribute - SuppressWarnings - SwingConstants - SwingPropertyChangeSupport - SwingUtilities - SyncFactory - SyncFactoryException - SyncFailedException - SyncProvider - SyncProviderException - SyncResolver - SyncScopeHelper - SynchronousQueue - SynthConstants - SynthContext - SynthGraphicsUtils - SynthLookAndFeel - SynthPainter - SynthStyle - SynthStyleFactory - Synthesizer - SysexMessage - System - SystemColor - SystemException - SystemFlavorMap - TAG_ALTERNATE_IIOP_ADDRESS - TAG_CODE_SETS - TAG_INTERNET_IOP - TAG_JAVA_CODEBASE - TAG_MULTIPLE_COMPONENTS - TAG_ORB_TYPE - TAG_POLICIES - TAG_RMI_CUSTOM_MAX_STREAM_FORMAT - TCKind - THREAD_POLICY_ID - TIMEOUT - TRANSACTION_MODE - TRANSACTION_REQUIRED - TRANSACTION_ROLLEDBACK - TRANSACTION_UNAVAILABLE - TRANSIENT - TRANSPORT_RETRY - TabExpander - TabSet - TabStop - TabableView - TabbedPaneUI - TableCellEditor - TableCellRenderer - TableColumn - TableColumnModel - TableColumnModelEvent - TableColumnModelListener - TableHeaderUI - TableModel - TableModelEvent - TableModelListener - TableUI - TableView - TabularData - TabularDataSupport - TabularType - TagElement - TaggedComponent - TaggedComponentHelper - TaggedComponentHolder - TaggedProfile - TaggedProfileHelper - TaggedProfileHolder - Target - TargetDataLine - TargetedNotification - Templates - TemplatesHandler - Text - TextAction - TextArea - TextAttribute - TextComponent - TextEvent - TextField - TextHitInfo - TextInputCallback - TextLayout - TextLayout.CaretPolicy - TextListener - TextMeasurer - TextOutputCallback - TextSyntax - TextUI - TexturePaint - Thread - Thread.State - Thread.UncaughtExceptionHandler - ThreadDeath - ThreadFactory - ThreadGroup - ThreadInfo - ThreadLocal - ThreadMXBean - ThreadPolicy - ThreadPolicyOperations - ThreadPolicyValue - ThreadPoolExecutor - ThreadPoolExecutor.AbortPolicy - ThreadPoolExecutor.CallerRunsPolicy - ThreadPoolExecutor.DiscardOldestPolicy - ThreadPoolExecutor.DiscardPolicy - Throwable - Tie - TileObserver - Time - TimeLimitExceededException - TimeUnit - TimeZone - TimeoutException - Timer - Timer - Timer - TimerAlarmClockNotification - TimerMBean - TimerNotification - TimerTask - Timestamp - Timestamp - TitledBorder - TooManyListenersException - ToolBarUI - ToolTipManager - ToolTipUI - Toolkit - Track - TransactionRequiredException - TransactionRolledbackException - TransactionService - TransactionalWriter - TransferHandler - Transferable - TransformAttribute - Transformer - TransformerConfigurationException - TransformerException - TransformerFactory - TransformerFactoryConfigurationError - TransformerHandler - Transmitter - Transparency - TreeCellEditor - TreeCellRenderer - TreeExpansionEvent - TreeExpansionListener - TreeMap - TreeModel - TreeModelEvent - TreeModelListener - TreeNode - TreePath - TreeSelectionEvent - TreeSelectionListener - TreeSelectionModel - TreeSet - TreeUI - TreeWillExpandListener - TrustAnchor - TrustManager - TrustManagerFactory - TrustManagerFactorySpi - Type - TypeCode - TypeCodeHolder - TypeInfo - TypeInfoProvider - TypeMismatch - TypeMismatch - TypeMismatch - TypeMismatchHelper - TypeMismatchHelper - TypeNotPresentException - TypeVariable - Types - UID - UIDefaults - UIDefaults.ActiveValue - UIDefaults.LazyInputMap - UIDefaults.LazyValue - UIDefaults.ProxyLazyValue - UIManager - UIManager.LookAndFeelInfo - UIResource - ULongLongSeqHelper - ULongLongSeqHolder - ULongSeqHelper - ULongSeqHolder - UNKNOWN - UNKNOWN - UNSUPPORTED_POLICY - UNSUPPORTED_POLICY_VALUE - URI - URIException - URIResolver - URISyntax - URISyntaxException - URL - URLClassLoader - URLConnection - URLDecoder - URLEncoder - URLStreamHandler - URLStreamHandlerFactory - URLStringHelper - USER_EXCEPTION - UShortSeqHelper - UShortSeqHolder - UTFDataFormatException - UUID - UndeclaredThrowableException - UndoManager - UndoableEdit - UndoableEditEvent - UndoableEditListener - UndoableEditSupport - UnexpectedException - UnicastRemoteObject - UnionMember - UnionMemberHelper - UnknownEncoding - UnknownEncodingHelper - UnknownError - UnknownException - UnknownFormatConversionException - UnknownFormatFlagsException - UnknownGroupException - UnknownHostException - UnknownHostException - UnknownObjectException - UnknownServiceException - UnknownUserException - UnknownUserExceptionHelper - UnknownUserExceptionHolder - UnmappableCharacterException - UnmarshalException - UnmodifiableClassException - UnmodifiableSetException - UnrecoverableEntryException - UnrecoverableKeyException - Unreferenced - UnresolvedAddressException - UnresolvedPermission - UnsatisfiedLinkError - UnsolicitedNotification - UnsolicitedNotificationEvent - UnsolicitedNotificationListener - UnsupportedAddressTypeException - UnsupportedAudioFileException - UnsupportedCallbackException - UnsupportedCharsetException - UnsupportedClassVersionError - UnsupportedEncodingException - UnsupportedFlavorException - UnsupportedLookAndFeelException - UnsupportedOperationException - UserDataHandler - UserException - Util - UtilDelegate - Utilities - VMID - VM_ABSTRACT - VM_CUSTOM - VM_NONE - VM_TRUNCATABLE - Validator - ValidatorHandler - ValueBase - ValueBaseHelper - ValueBaseHolder - ValueExp - ValueFactory - ValueHandler - ValueHandlerMultiFormat - ValueInputStream - ValueMember - ValueMemberHelper - ValueOutputStream - VariableHeightLayoutCache - Vector - VerifyError - VersionSpecHelper - VetoableChangeListener - VetoableChangeListenerProxy - VetoableChangeSupport - View - ViewFactory - ViewportLayout - ViewportUI - VirtualMachineError - Visibility - VisibilityHelper - VoiceStatus - Void - VolatileImage - WCharSeqHelper - WCharSeqHolder - WStringSeqHelper - WStringSeqHolder - WStringValueHelper - WeakHashMap - WeakReference - WebRowSet - WildcardType - Window - WindowAdapter - WindowConstants - WindowEvent - WindowFocusListener - WindowListener - WindowStateListener - WrappedPlainView - WritableByteChannel - WritableRaster - WritableRenderedImage - WriteAbortedException - Writer - WrongAdapter - WrongAdapterHelper - WrongPolicy - WrongPolicyHelper - WrongTransaction - WrongTransactionHelper - WrongTransactionHolder - X500Principal - X500PrivateCredential - X509CRL - X509CRLEntry - X509CRLSelector - X509CertSelector - X509Certificate - X509Certificate - X509EncodedKeySpec - X509ExtendedKeyManager - X509Extension - X509KeyManager - X509TrustManager - XAConnection - XADataSource - XAException - XAResource - XMLConstants - XMLDecoder - XMLEncoder - XMLFilter - XMLFilterImpl - XMLFormatter - XMLGregorianCalendar - XMLParseException - XMLReader - XMLReaderAdapter - XMLReaderFactory - XPath - XPathConstants - XPathException - XPathExpression - XPathExpressionException - XPathFactory - XPathFactoryConfigurationException - XPathFunction - XPathFunctionException - XPathFunctionResolver - XPathVariableResolver - Xid - XmlReader - XmlWriter - ZipEntry - ZipException - ZipFile - ZipInputStream - ZipOutputStream - ZoneView - _BindingIteratorImplBase - _BindingIteratorStub - _DynAnyFactoryStub - _DynAnyStub - _DynArrayStub - _DynEnumStub - _DynFixedStub - _DynSequenceStub - _DynStructStub - _DynUnionStub - _DynValueStub - _IDLTypeStub - _NamingContextExtStub - _NamingContextImplBase - _NamingContextStub - _PolicyStub - _Remote_Stub - _ServantActivatorStub - _ServantLocatorStub - - - - AbstractAnnotationValueVisitor6 - AbstractElementVisitor6 - AbstractMarshallerImpl - AbstractOwnableSynchronizer - AbstractProcessor - AbstractQueuedLongSynchronizer - AbstractScriptEngine - AbstractTypeVisitor6 - AbstractUnmarshallerImpl - ActivationDataFlavor - AlgorithmMethod - AnnotationMirror - AnnotationValue - AnnotationValueVisitor - ArrayDeque - AsyncHandler - AttachmentMarshaller - AttachmentPart - AttachmentUnmarshaller - Binder - BindingProvider - Bindings - BlockingDeque - BreakIteratorProvider - C14NMethodParameterSpec - CanonicalizationMethod - Characters - ClientInfoStatus - CollapsedStringAdapter - CollatorProvider - CommandInfo - CommandMap - CommandObject - CommonDataSource - Compilable - CompiledScript - Completion - Completions - CompositeDataInvocationHandler - CompositeDataView - ConcurrentNavigableMap - ConcurrentSkipListMap - ConcurrentSkipListSet - ConfigurationSpi - Console - ConstructorProperties - CookieManager - CookiePolicy - CookieStore - CurrencyNameProvider - Data - DataContentHandler - DataContentHandlerFactory - DataHandler - DatatypeConverter - DatatypeConverterInterface - DateFormatProvider - DateFormatSymbolsProvider - DecimalFormatSymbolsProvider - DeclaredType - DefaultRowSorter - DefaultValidationEventHandler - DeflaterInputStream - Deque - DescriptorKey - DescriptorRead - Desktop - Detail - DetailEntry - Diagnostic - DiagnosticCollector - DiagnosticListener - DigestMethod - DigestMethodParameterSpec - Dispatch - DOMCryptoContext - DomHandler - DOMSignContext - DOMStructure - DOMURIReference - DOMValidateContext - DropMode - ElementFilter - ElementKind - ElementKindVisitor6 - Elements - ElementScanner6 - ElementVisitor - EndDocument - EndElement - Endpoint - EntityDeclaration - ErrorType - EventException - EventFilter - EventReaderDelegate - EventTarget - ExcC14NParameterSpec - ExecutableElement - ExecutableType - FileDataSource - FileNameExtensionFilter - FileObject - Filer - FilerException - FileTypeMap - ForwardingFileObject - ForwardingJavaFileManager - ForwardingJavaFileObject - Generated - GridBagLayoutInfo - GroupLayout - HandlerChain - HandlerResolver - HexBinaryAdapter - HMACParameterSpec - Holder - HTTPBinding - HttpCookie - HTTPException - IDN - ImmutableDescriptor - InflaterOutputStream - InitParam - InterfaceAddress - Invocable - IOError - JavaCompiler - JavaFileManager - JavaFileObject - JAXBContext - JAXBElement - JAXBException - JAXBIntrospector - JAXBResult - JAXBSource - JMX - JMXAddressable - KeyInfo - KeyInfoFactory - KeyName - KeySelector - KeySelectorException - KeySelectorResult - KeyValue - LayoutPath - LayoutStyle - LinearGradientPaint - LinkedBlockingDeque - LocaleNameProvider - LocaleServiceProvider - Location - LockInfo - LogicalHandler - LogicalMessage - LogicalMessageContext - MailcapCommandMap - Marshaller - MessageContext - MessageFactory - Messager - MimeHeader - MimeHeaders - MimeType - MimeTypeParameterList - MimetypesFileTypeMap - MirroredTypeException - MirroredTypesException - MLetContent - MonitorInfo - MultipleGradientPaint - MutationEvent - MXBean - Namespace - NavigableMap - NavigableSet - NClob - NestingKind - NodeSetData - NormalizedStringAdapter - Normalizer - NoSuchMechanismException - NotationDeclaration - NotIdentifiableEvent - NotIdentifiableEventImpl - NoType - NullType - NumberFormatProvider - OctetStreamData - Oneway - OptionChecker - PackageElement - ParseConversionEvent - ParseConversionEventImpl - Path2D - PGPData - PolicySpi - PortInfo - PostConstruct - PreDestroy - PrimitiveType - PrintConversionEvent - PrintConversionEventImpl - ProcessingEnvironment - Processor - PropertyException - RadialGradientPaint - ReferenceType - RequestWrapper - Resource - Resources - Response - ResponseWrapper - RetrievalMethod - RoundEnvironment - RowFilter - RowId - RowIdLifetime - RowSorter - RowSorterEvent - RowSorterListener - RunnableFuture - RunnableScheduledFuture - SAAJMetaFactory - SAAJResult - SchemaOutputResolver - ScriptContext - ScriptEngine - ScriptEngineFactory - ScriptEngineManager - ScriptException - Service - ServiceConfigurationError - ServiceDelegate - ServiceLoader - ServiceMode - SignatureMethod - SignatureMethodParameterSpec - SignatureProperties - SignatureProperty - SignedInfo - SimpleAnnotationValueVisitor6 - SimpleBindings - SimpleElementVisitor6 - SimpleJavaFileObject - SimpleScriptContext - SimpleTypeVisitor6 - SOAPBinding - SOAPBinding - SOAPBody - SOAPBodyElement - SOAPConnection - SOAPConnectionFactory - SOAPConstants - SOAPElement - SOAPElementFactory - SOAPEnvelope - SOAPException - SOAPFactory - SOAPFault - SOAPFaultElement - SOAPFaultException - SOAPHandler - SOAPHeader - SOAPHeaderElement - SOAPMessage - SOAPMessageContext - SOAPMessageHandler - SOAPMessageHandlers - SOAPPart - SortOrder - SourceVersion - SplashScreen - SQLClientInfoException - SQLDataException - SQLFeatureNotSupportedException - SQLIntegrityConstraintViolationException - SQLInvalidAuthorizationSpecException - SQLNonTransientConnectionException - SQLNonTransientException - SQLRecoverableException - SQLSyntaxErrorException - SQLTimeoutException - SQLTransactionRollbackException - SQLTransientConnectionException - SQLTransientException - SQLXML - SSLParameters - StandardEmitterMBean - StandardJavaFileManager - StandardLocation - StartDocument - StartElement - StatementEvent - StatementEventListener - StAXResult - StAXSource - StreamFilter - StreamReaderDelegate - SupportedAnnotationTypes - SupportedOptions - SupportedSourceVersion - SwingWorker - SystemTray - TableRowSorter - TableStringConverter - TimeZoneNameProvider - Tool - ToolProvider - Transform - TransformException - TransformParameterSpec - TransformService - TrayIcon - TypeConstraintException - TypeElement - TypeKind - TypeKindVisitor6 - TypeMirror - TypeParameterElement - TypeVisitor - UIEvent - UnknownAnnotationValueException - UnknownElementException - UnknownTypeException - Unmarshaller - UnmarshallerHandler - UnsupportedDataTypeException - URIDereferencer - URIParameter - URIReference - URIReferenceException - URLDataSource - ValidationEvent - ValidationEventCollector - ValidationEventHandler - ValidationEventImpl - ValidationEventLocator - ValidationEventLocatorImpl - ValidationException - VariableElement - W3CDomHandler - WebEndpoint - WebFault - WebMethod - WebParam - WebResult - WebService - WebServiceClient - WebServiceContext - WebServiceException - WebServicePermission - WebServiceProvider - WebServiceRef - WebServiceRefs - Wrapper - X509Data - X509IssuerSerial - XmlAccessOrder - XmlAccessorOrder - XmlAccessorType - XmlAccessType - XmlAdapter - XmlAnyAttribute - XmlAnyElement - XmlAttachmentRef - XmlAttribute - XMLCryptoContext - XmlElement - XmlElementDecl - XmlElementRef - XmlElementRefs - XmlElements - XmlElementWrapper - XmlEnum - XmlEnumValue - XMLEvent - XMLEventAllocator - XMLEventConsumer - XMLEventFactory - XMLEventReader - XMLEventWriter - XmlID - XmlIDREF - XmlInlineBinaryData - XMLInputFactory - XmlJavaTypeAdapter - XmlJavaTypeAdapters - XmlList - XmlMimeType - XmlMixed - XmlNs - XmlNsForm - XMLObject - XMLOutputFactory - XmlRegistry - XMLReporter - XMLResolver - XmlRootElement - XmlSchema - XmlSchemaType - XmlSchemaTypes - XMLSignature - XMLSignatureException - XMLSignatureFactory - XMLSignContext - XMLStreamConstants - XMLStreamException - XMLStreamReader - XMLStreamWriter - XMLStructure - XmlTransient - XmlType - XMLValidateContext - XmlValue - XPathFilter2ParameterSpec - XPathFilterParameterSpec - XPathType - XSLTTransformParameterSpec - ZipError - - - - - abstract - break - case - catch - class - continue - default - do - else - enum - extends - false - finally - for - goto - if - implements - instanceof - @interface - interface - native - new - null - private - protected - public - return - super - strictfp - switch - synchronized - this - throws - throw - transient - true - try - volatile - while - - - boolean - byte - char - const - double - final - float - int - long - short - static - void - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/javascript.xml b/part/syntax/data/javascript.xml deleted file mode 100644 index 3e849d2..0000000 --- a/part/syntax/data/javascript.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - if - else - for - in - while - do - continue - break - with - try - catch - finally - switch - case - new - var - function - return - delete - true - false - void - throw - typeof - const - default - - - escape - isFinite - isNaN - Number - parseFloat - parseInt - reload - taint - unescape - untaint - write - - - Anchor - Applet - Area - Array - Boolean - Button - Checkbox - Date - document - window - Image - FileUpload - Form - Frame - Function - Hidden - Link - MimeType - Math - Max - Min - Layer - navigator - Object - Password - Plugin - Radio - RegExp - Reset - Screen - Select - String - Text - Textarea - this - Window - - - abs - acos - asin - atan - atan2 - ceil - cos - ctg - E - exp - floor - LN2 - LN10 - log - LOG2E - LOG10E - PI - pow - round - sin - sqrt - SQRT1_2 - SQRT2 - tan - - - onAbort - onBlur - onChange - onClick - onError - onFocus - onLoad - onMouseOut - onMouseOver - onReset - onSelect - onSubmit - onUnload - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/latex.xml b/part/syntax/data/latex.xml deleted file mode 100644 index 1fd208c..0000000 --- a/part/syntax/data/latex.xml +++ /dev/null @@ -1,572 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/literate-haskell.xml b/part/syntax/data/literate-haskell.xml deleted file mode 100644 index 52dcebe..0000000 --- a/part/syntax/data/literate-haskell.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/lua.xml b/part/syntax/data/lua.xml deleted file mode 100644 index a2ac9f6..0000000 --- a/part/syntax/data/lua.xml +++ /dev/null @@ -1,300 +0,0 @@ - - - - - - - and - function - in - local - not - or - - - break - do - else - elseif - end - for - if - repeat - return - then - until - while - - - nil - false - true - - - string.byte string.char - string.find string.len - string.lower string.rep - string.sub string.upper - string.format string.gfind - string.gsub table.concat - table.getn table.sort - table.insert table.remove - table.setn math.abs - math.sin math.cos - math.tan math.asin - math.acos math.atan - math.atan2 math.ceil - math.floor math.mod - math.frexp math.ldexp - math.squrt math.min - math.max math.log - math.log10 math.exp - math.deg math.rad - math.random math.randomseed - io.close io.flush - io.input io.lines - io.open io.output - io.read io.stderr - io.stdin io.stdout - io.tmpfile io.write - os.clock os.date - os.difftime os.execute - os.exit os.getenv - os.remove os.rename - os.setlocale os.time - os.tmpname debug.getinfo - debug.getlocal debug.setlocal - debug.sethook debug.gethook - assert collectgarbage - dofile error - next print - rawget rawset - tonumber tostring - type _ALERT - _ERRORMESSAGE call - getmetatable gcinfo - ipairs loadfile - loadstring pairs - pcall require - LUA_PATH setmetatable - _LOADED _VERSION - gettagmethod globals - newtag setglobal - settag settagmethod - setlinehook getglobals - copytagmethods dostring - getglobal tag - setglobals unpack - exit readfrom - writeto appendto - read write - getinfo getlocal - setlocal setcallhook - tinsert tremove - flush seek - setlocale execute - remove rename - tmpname getenv - getn sort - table.foreach table.foreachi - foreach foreachi - abs sin - cos tan - asin acos - atan atan2 - ceil floor - mod frexp - ldexp squrt - min max - log log10 - exp deg - rad random - randomseed strlen - strsub strlower - strupper strchar - strrep ascii - strbyte format - strfind gsub - openfile closefile - date clock - - - cgilua cgilua.lp.translate - cgilua.contentheader cgilua.script_file - cgilua.header cgilua.script_path - cgilua.htmlheader cgilua.script_pdir - cgilua.redirect cgilua.script_vdir - cgilua.mkabsoluteurl cgilua.script_vpath - cgilua.mkurlpath cgilua.servervariable - cgilua.put cgilua.urlpath - cgilua.handlelp cgilua.errorlog - cgilua.lp.compile cgilua.seterrorhandler - cgilua.lp.include cgilua.seterroroutput - cgilua.lp.setcompatmode cgilua.addclosefunction - cgilua.lp.setoutfunc cgilua.addopenfunction - cgilua.addscripthandler cgilua.addscripthandler - cgilua.buildprocesshandler cgilua.setmaxfilesize - cgilua.setmaxinput cgilua.urlcode.encodetable - cgilua.urlcode.escape cgilua.urlcode.parsequery - cgilua.urlcode.unescape cgilua.urlcode.insertfield - cgilua.setoutfunc cgilua.addopenfunction - cgilua.doif cgilua.doscript - cgilua.pack cgilua.splitpath - cgilua.cookies.get cgilua.cookies.set - cgilua.cookies.sethtml cgilua.cookies.delete - cgilua.serialize cgilua.session.close - cgilua.session.data cgilua.session.load - cgilua.session.new cgilua.session.open - cgilua.session.save cgilua.session.setsessiondir - cgilua.session.delete cgilua.session - cgilua.cookies - - numrows connect - close fetch - getcolnames getcoltypes - commit rollback - setautocommit - - lfs lfs.attributes - lfs.chdir lfs.currentdir - lfs.dir lfs.lock - lfs.mkdir lfs.rmdir - lfs.touch lfs.unlock - - zip zip.open - zip.openfile files - seek close - lines - - - - - TODO - FIXME - NOTE - - - table.foreach table.foreachi - foreach foreachi - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/makefile.xml b/part/syntax/data/makefile.xml deleted file mode 100644 index 6ac766f..0000000 --- a/part/syntax/data/makefile.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - include - define - else - endef - endif - ifdef - ifeq - ifndef - ifneq - - - call - subst - patsubst - strip - findstring - filter - filter-out - sort - word - wordlist - words - firstword - lastword - dir - notdir - suffix - basename - addsuffix - addprefix - join - wildcard - realpath - abspath - if - or - and - foreach - value - eval - origin - flavor - shell - error - warning - info - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/mason.xml b/part/syntax/data/mason.xml deleted file mode 100644 index 3fd1b49..0000000 --- a/part/syntax/data/mason.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - sub - bless - caller - cmp - print - echo - die - import - lt - le - local - last - ! - || - eq - ne - use - elsif - my - foreach - wantarray - push - pop - dbmclose - dbmopen - dump - each - ge - gt - split - open - close - eval - chomp - chop - unless - undef - next - unlink - new - and - not - no - ref - redo - require - tied - tie - untie - or - xor - continue - do - else - for - goto - if - return - switch - while - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/mediawiki.xml b/part/syntax/data/mediawiki.xml deleted file mode 100644 index 42ec1dd..0000000 --- a/part/syntax/data/mediawiki.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/mup.xml b/part/syntax/data/mup.xml deleted file mode 100644 index 890cf8c..0000000 --- a/part/syntax/data/mup.xml +++ /dev/null @@ -1,865 +0,0 @@ - - - - - - - - score - music - header - header2 - footer - footer2 - top - top2 - bottom - bottom2 - staff - voice - grids - music - headshapes - block - - - - - aboveorder - addtranspose - barstyle - beamslope - beamstyle - beloworder - betweenorder - bottommargin - brace - bracket - cancelkey - chorddist - clef - crescdist - defoct - dist - division - dyndist - endingstyle - firstpage - font - fontfamily - gridfret - gridsatend - gridscale - gridswhereused - key - label - label2 - leftmargin - lyricsalign - lyricsfont - lyricsfontfamily - lyricssize - measnum - measnumfont - measnumfontfamily - measnumsize - noteheads - numbermrpt - ontheline - packexp - packfact - pad - pageheight - pagewidth - panelsperpage - pedstyle - printmultnum - rehstyle - release - restcombine - restsymmult - rightmargin - scale - scorepad - scoresep - size - stafflines - staffpad - staffs - staffscale - staffsep - stemlen - swingunit - sylposition - tabwhitebox - time - timeunit - topmargin - transpose - units - visible - vscheme - warn - - - - - y - n - 2f - 2o - 3f - 3o - mussym - octave - dyn - othertext - chord - lyrics - ending - reh - up - down - major - minor - perfect - augmented - diminished - maj - min - per - aug - dim - pedal - 8treble - treble8 - treble - frenchviolin - soprano - mezzosoprano - alto - tenor - baritone - bass - cut - common - line - alt - pedstar - top - barred - grouped - times - boxed - circled - plain - 1n - 5n - 1drum - 5drum - drum - tab - inches - cm - whereused - - - - - define - ifdef - ifndef - - - - - @ - endif - - - - - else - include - undef - - - - - exclamdown - questiondown - sterling - yen - cent - quotedblbase - quotedblleft - `` - quotedblright - '' - guillemotleft - << - guillemotright - >> - guildsinglleft - guilsinglright - dagger - daggerdbl - grave - acute - macron - breve - dotaccent - dieresis - ring - cedilla - hungarumlaut - ogonek - caron - emdash - AE - ae - ordfeminine - ordmasculine - Lslash - L/ - lslash - l/ - Oslash - O/ - oslash - o/ - OE - oe - dotlessi - germandbls - ss - Aacute - A' - aacute - a' - Acircumflex - A^ - acircumflex - a^ - Adieresis - A: - adieresis - a: - Agrave - A` - agrave - a` - Aring - Ao - aring - ao - Atilde - A~ - atilde - a~ - Ccedilla - C, - ccedilla - c, - Eacute - E' - eacute - e' - Ecircumflex - E^ - ecircumflex - e^ - Edieresis - E: - edieresis - e: - Egrave - E` - egrave - e` - Iacute - I' - iacute - i' - Icircumflex - I^ - icircumflex - i^ - Idieresis - i: - idieresis - i: - Igrave - I` - igrave - i` - Ntilde - N~ - ntilde - n~ - Oacute - O' - oacute - o' - Ocircumflex - O^ - ocircumflex - o^ - Odieresis - O: - odieresis - o: - Ograve - O` - ograve - o` - Otilde - O~ - otilde - o~ - Scaron - Sv - scaron - sv - Uacute - U' - uacute - u' - Ucircumflex - U^ - ucircumflex - u^ - Udieresis - U: - udieresis - u: - Ugrave - U` - ugrave - u` - Ydieresis - Y: - ydieresis - y: - Zcaron - Zv - zcaron - zv - bullet - space - - - - - gclef - fclef - cclef - com - cut - flat - dblflat - sharp - dblsharp - nat - 4n - 2n - 1n - dblwhole - xnote - diamond - filldiamond - dwhdiamond - dn2n - dn4n - dn8n - dn16n - dn32n - dn64n - dn128n - dn256n - up2n - up4n - up8n - up16n - up32n - up64n - up128n - up256n - upflag - dnflag - qwhrest - dwhrest - 1rest - 2rest - 4rest - 8rest - 16rest - 32rest - 64rest - 128rest - 256rest - begped - endped - pedal - tr - mor - invmor - turn - invturn - ferm - uferm - acc_gt - acc_hat - acc_uhat - leg - dot - wedge - uwedge - sign - coda - upbow - dnbow - rr - measrpt - copyright - dim - halfdim - triangle - - smgclef - smfclef - smcclef - smcom - smcut - smflat - smdblflat - smsharp - smdblsharp - smnat - sm4n - sm2n - sm1n - smdblwhole - smxnote - smdiamond - smfilldiamond - smdwhdiamond - smdn2n - smdn4n - smdn8n - smdn16n - smdn32n - smdn64n - smdn128n - smdn256n - smup2n - smup4n - smup8n - smup16n - smup32n - smup64n - smup128n - smup256n - smupflag - smdnflag - smqwhrest - smdwhrest - sm1rest - sm2rest - sm4rest - sm8rest - sm16rest - sm32rest - sm64rest - sm128rest - sm256rest - smbegped - smendped - smpedal - smtr - smmor - sminvmor - smturn - sminvturn - smferm - smuferm - smacc_gt - smacc_hat - smacc_uhat - smleg - smdot - smwedge - smuwedge - smsign - smcoda - smupbow - smdnbow - smrr - smmeasrpt - smcopyright - smdim - smhalfdim - smtriangle - - - - - print - left - right - center - title - paragraph - postscript - - - - - avantgarde - bookman - courier - helvetica - newcentury - palatino - times - - - - - rom - bold - ital - boldital - - - - - chord - analysis - figbass - dyn - - - - - dotted - dashed - wavy - wide - medium - - line - curve - to - bulge - - octave - mussym - phrase - pedal - roll - to - - down - up - with - - midi - - - - - above - below - between - all - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/nasm.xml b/part/syntax/data/nasm.xml deleted file mode 100644 index 17e435f..0000000 --- a/part/syntax/data/nasm.xml +++ /dev/null @@ -1,888 +0,0 @@ - - - - - - - - eax - ax - ah - al - ebx - bx - bh - bl - ecx - cx - ch - cl - edx - dx - dh - dl - ebp - bp - esi - si - edi - di - - esp - sp - - cs - ds - es - fs - gs - ss - - cr0 - - cr2 - cr3 - cr4 - - dr0 - dr1 - dr2 - dr3 - dr6 - dr7 - - st - - mm0 - mm1 - mm2 - mm3 - mm4 - mm5 - mm6 - mm7 - - xmm0 - xmm1 - xmm2 - xmm3 - xmm4 - xmm5 - xmm6 - xmm7 - - - aaa - aad - aam - aas - adc - add - addpd - addps - addsd - addss - addsubpd - addsubps - and - andnpd - andnps - andpd - andps - arpl - bound - bsf - bsr - bswap - bt - btc - btr - bts - call - cbw - cwde - cwd - cdq - cdqe - cqo - clc - cld - clgi - cli - clts - clflush - cmc - cmova - cmovae - cmovb - cmovbe - cmovc - cmove - cmovg - cmovge - cmovl - cmovle - cmovna - cmovnae - cmovnb - cmovnbe - cmovnc - cmovne - cmovng - cmovnge - cmovnl - cmovnle - cmovno - cmovnp - cmovns - cmovnz - cmovo - cmovp - cmovpe - cmovpo - cmovs - cmovz - cmp - cmpeqpd - cmpeqps - cmpeqsd - cmpeqss - cmplepd - cmpleps - cmplesd - cmpless - cmpltpd - cmpltps - cmpltsd - cmpltss - cmpneqpd - cmpneqps - cmpneqsd - cmpneqss - cmpnlepd - cmpnleps - cmpnlesd - cmpnless - cmpnltpd - cmpnltps - cmpnltsd - cmpnltss - cmpordpd - cmpordps - cmpordsd - cmpordss - cmppd - cmpps - cmps - cmpsb - cmpsd - cmpss - cmpsw - cmpunordpd - cmpunordps - cmpunordsd - cmpunordss - cmpxchg - cmpxchg486 - cmpxchg8b - cmpxchg16b - comisd - comiss - cpuid - cvtdq2pd - cvtdq2ps - cvtpd2dq - cvtpd2pi - cvtpd2ps - cvtpi2pd - cvtpi2ps - cvtps2dq - cvtps2pd - cvtps2pi - cvtsd2si - cvtsd2ss - cvtsi2sd - cvtsi2ss - cvtss2sd - cvtss2si - cvttpd2dq - cvttpd2pi - cvttps2dq - cvttps2pi - cvttsd2si - cvttss2si - daa - das - dec - div - divpd - divps - divsd - divss - emms - enter - f2xm1 - fabs - fadd - faddp - fbld - fbstp - fchs - fclex - fnclex - fcmovb - fcmovbe - fcmove - fcmovnb - fcmovnbe - fcmovne - fcmovnu - fcmovu - fcom - fcomp - fcompp - fcomi - fcomip - fcos - fdecstp - fdisi - feni - fdiv - fdivr - fdivp - fdivrp - femms - ffree - ffreep - fiadd - ficom - ficomp - fidiv - fidivr - fild - fimul - fincstp - finit - fist - fistp - fisttp - fisub - fisubr - fld - fld1 - fldl2e - fldl2t - fldlg2 - fldln2 - fldcw - fldenv - fldpi - fldz - fmul - fmulp - fndisi - fneni - fninit - fnop - fnsave - fnstcw - fnstenv - fnstsw - fnwait - fpatan - fptan - fprem - fprem1 - frndint - frstor - fsave - fscale - fsetpm - fsin - fsincos - fsqrt - fst - fstp - fstcw - fstenv - fstsw - fsub - fsubr - fsubp - fsubrp - ftst - fucom - fucomp - fucompp - fucomi - fucomip - fwait - fxam - fxch - fxrstor - fxsave - fxtract - fyl2x - fyl2xp1 - haddpd - haddps - hlt - hsubpd - hsubps - ibts - idiv - imul - in - inc - ins - insb - insd - insw - int - int1 - int3 - into - invd - invlpg - invlpga - iret - iretd - iretq - iretw - ja - jae - jb - jbe - jc - je - jg - jge - jl - jle - jna - jnae - jnb - jnbe - jnc - jne - jng - jnge - jnl - jnle - jno - jnp - jns - jnz - jo - jp - jpe - jpo - js - jz - jcxz - jecxz - jrcxz - jmp - lahf - lar - lddqu - ldmxcsr - lds - les - lea - leave - lfence - lfs - lgdt - lgs - lidt - lldt - lmsw - loadall - loadall286 - lods - lodsb - lodsd - lodsq - lodsw - loop - loope - loopne - loopnz - loopz - lsl - lss - ltr - maskmovdqu - maskmovq - maxpd - maxps - maxsd - maxss - mfence - minpd - minps - minsd - minss - monitor - mov - movapd - movaps - movd - movddup - movdq2q - movdqa - movdqu - movhlps - movhpd - movhps - movlhps - movlpd - movlps - movmskpd - movmskps - movntdq - movnti - movntpd - movntps - movntq - movq - movq2dq - movs - movsb - movsd - movshdup - movsldup - movsq - movss - movsx - movsxd - movsw - movupd - movups - movzx - mul - mulpd - mulps - mulsd - mulss - mwait - neg - nop - not - or - orpd - orps - out - outs - outsb - outsw - outsd - packssdw - packsswb - packuswb - paddb - paddd - paddq - paddsb - paddsw - paddusb - paddusw - paddw - pand - pandn - pause - pavgb - pavgusb - pavgw - pcmpeqb - pcmpeqw - pcmpeqd - pcmpgtb - pcmpgtw - pcmpgtd - pdistib - pextrw - pf2id - pf2iw - pfacc - pfadd - pfcmpeq - pfcmpge - pfcmpgt - pfmax - pfmin - pfmul - pfnacc - pfpnacc - pfrcp - pfrcpit1 - pfrcpit2 - pfrsqit1 - pfrsqrt - pfsub - pfsubr - pi2fd - pi2fw - pinsrw - pmachriw - pmaddwd - pmagw - pmaxsw - pmaxub - pminsw - pminub - pmovmskb - pmulhrw - pmulhuw - pmulhw - pmullw - pmuludq - pmvgezb - pmvlzb - pmvnzb - pmvzb - pop - popa - popaw - popad - popf - popfw - popfd - popfq - por - prefetch - prefetchnta - prefetcht0 - prefetcht1 - prefetcht2 - prefetchw - psadbw - pshufd - pshufhw - pshuflw - pshufw - pslld - pslldq - psllq - psllw - psrad - psraw - psrld - psrldq - psrlq - psrlw - psubb - psubd - psubq - psubsb - psubsiw - psubsw - psubusb - psubusw - psubw - pswapd - punpckhbw - punpckhdq - punpckhqdq - punpckhwd - punpcklbw - punpckldq - punpcklqdq - punpcklwd - push - pusha - pushad - pushaw - pushf - pushfd - pushfq - pushfw - pxor - rcl - rcr - rcpps - rcpss - rdmsr - rdpmc - rdshr - rdtsc - rdtscp - ret - retf - retn - rol - ror - rsdc - rsldt - rsm - rsqrtps - rsqrtss - rsts - sahf - sal - sar - salc - sbb - scas - scasb - scasd - scasq - scasw - seta - setae - setb - setbe - setc - sete - setg - setge - setl - setle - setna - setnae - setnb - setnbe - setnc - setne - setng - setnge - setnl - setnle - setno - setnp - setns - setnz - seto - setp - setpe - setpo - sets - setz - sfence - sgdt - shl - shld - shr - shrd - shufpd - shufps - sidt - skinit - sldt - smi - smint - smintold - smsw - sqrtpd - sqrtps - sqrtsd - sqrtss - stc - std - stgi - sti - stmxcsr - stos - stosb - stosd - stosq - stosw - str - sub - subpd - subps - subsd - subss - svdc - svldt - svts - swapgs - syscall - sysenter - sysexit - sysret - test - ucomisd - ucomiss - ud0 - ud1 - ud2 - umov - unpckhpd - unpckhps - unpcklpd - unpcklps - verr - verw - vmload - vmmcall - vmrun - vmsave - wait - wbinvd - wrmsr - wrshr - xadd - xbts - xchg - xlat - xlatb - xor - xorpd - xorps - - - - times - - equ - - db - dw - dd - dq - dt - - resb - resw - resd - resq - rest - - incbin - - byte - word - dword - qword - short - ptr - - - - absolute - bits - common - extern - global - org - section - seg - segment - strict - use16 - use32 - wrt - - struc - endstruc - istruc - at - iend - align - alignb - - __SECT__ - __NASM_MAJOR__ - __NASM_MINOR__ - __NASM_SUBMINOR__ - ___NASM_PATCHLEVEL__ - __NASM_VERSION_ID__ - __NASM_VER__ - __FILE__ - __LINE__ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/perl.xml b/part/syntax/data/perl.xml deleted file mode 100644 index 6de9368..0000000 --- a/part/syntax/data/perl.xml +++ /dev/null @@ -1,835 +0,0 @@ - - - - - - - if - unless - else - elsif - while - until - for - each - foreach - next - last - break - continue - return - use - no - require - my - our - local - BEGIN - END - require - package - sub - do - __END__ - __DATA__ - __FILE__ - __LINE__ - __PACKAGE__ - - - = - != - ~= - += - -= - *= - /= - **= - |= - ||= - //= - &= - &&= - ?= - + - - - * - - % - || - // - && - | - & - < - << - > - >> - ^ - -> - => - . - , - ; - :: - \ - and - or - not - eq - ne - lt - gt - le - ge - cmp - - - abs - accept - alarm - atan2 - bind - binmode - bless - caller - chdir - chmod - chomp - chop - chown - chr - chroot - close - closedir - connect - cos - crypt - dbmclose - dbmopen - defined - delete - die - dump - endgrent - endhostent - endnetent - endprotoent - endpwent - endservent - eof - eval - exec - exists - exit - exp - fcntl - fileno - flock - fork - format - formline - getc - getgrent - getgrgid - getgrnam - gethostbyaddr - gethostbyname - gethostent - getlogin - getnetbyaddr - getnetbyname - getnetent - getpeername - getpgrp - getppid - getpriority - getprotobyname - getprotobynumber - getprotoent - getpwent - getpwnam - getpwuid - getservbyname - getservbyport - getservent - getsockname - getsockopt - glob - gmtime - goto - grep - hex - import - index - int - ioctl - join - keys - kill - last - lc - lcfirst - length - link - listen - localtime - lock - log - lstat - map - mkdir - msgctl - msgget - msgrcv - msgsnd - oct - open - opendir - ord - pack - package - pipe - pop - pos - print - printf - prototype - push - quotemeta - rand - read - readdir - readline - readlink - recv - redo - ref - rename - reset - return - reverse - rewinddir - rindex - rmdir - scalar - seek - seekdir - select - semctl - semget - semop - send - setgrent - sethostent - setnetent - setpgrp - setpriority - setprotoent - setpwent - setservent - setsockopt - shift - shmctl - shmget - shmread - shmwrite - shutdown - sin - sleep - socket - socketpair - sort - splice - split - sprintf - sqrt - srand - stat - study - sub - substr - symlink - syscall - sysread - sysseek - system - syswrite - tell - telldir - tie - time - times - truncate - uc - ucfirst - umask - undef - unlink - unpack - unshift - untie - utime - values - vec - wait - waitpid - wantarray - warn - write - - - strict - english - warnings - vars - subs - utf8 - sigtrap - locale - open - less - integer - filetest - constant - bytes - diagnostics - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/php.xml b/part/syntax/data/php.xml deleted file mode 100644 index 34d58d0..0000000 --- a/part/syntax/data/php.xml +++ /dev/null @@ -1,5590 +0,0 @@ - - - -]> - - diff --git a/part/syntax/data/prolog.xml b/part/syntax/data/prolog.xml deleted file mode 100644 index 2f6e468..0000000 --- a/part/syntax/data/prolog.xml +++ /dev/null @@ -1,230 +0,0 @@ - - - - - - abstract - align - as - and - class - clauses - constants - database - determ - domains - elsedef - endclass - enddef - erroneous - facts - failure - global - goal - if - ifdef - ifndef - implement - include - language - multi - nocopy - nondeterm - object - or - procedure - protected - predicates - reference - single - static - struct - this - - - - ABSTRACT - ALIGN - AS - AND - CLASS - CLAUSES - CONSTANTS - DATABASE - DETERM - DOMAINS - ELSEDEF - ENDCLASS - ENDDEF - ERRONEOUS - FACTS - FAILURE - GLOBAL - GOAL - IF - IFDEF - IFNDEF - IMPLEMENT - INCLUDE - LANGUAGE - MULTI - NOCOPY - NONDETERM - OBJECT - OR - PROCEDURE - PROTECTED - PREDICATES - REFERENCE - SINGLE - STATIC - STRUCT - THIS - - - - - assert - asserta - assertz - bound - chain_inserta - chain_insertafter - chain_insertz - chain_terms - consult - db_btrees - db_chains - fail - findall - format - free - msgrecv - msgsend - nl - not - readterm - ref_term - retract - retractall - save - term_bin - term_replace - term_str - trap - write - writef - - - - bgidriver - bgifont - check_determ - code - config - diagnostics - error - errorlevel - heap - gstacksize - nobreak - nowarnings - printermenu - project - - - - mod - div - abs - exp - ln - log - sqrt - round - trunc - val - cos - sin - tan - arctan - random - randominit - - - - char - real - string - symbol - byte - sbyte - short - ushort - word - integer - unsigned - dword - long - ulong - binary - ref - - - - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/python.xml b/part/syntax/data/python.xml deleted file mode 100644 index 55528eb..0000000 --- a/part/syntax/data/python.xml +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - - - - - - - - - - - - import - from - as - - - class - def - del - global - lambda - nonlocal - - - and - in - is - not - or - - - exec - print - - - assert - break - continue - elif - else - except - finally - for - if - pass - raise - return - try - while - with - yield - - - __future__ - __import__ - __name__ - abs - all - any - apply - basestring - bin - bool - buffer - callable - chr - classmethod - cmp - coerce - compile - complex - delattr - dict - dir - divmod - enumerate - eval - execfile - file - filter - float - format - frozenset - getattr - globals - hasattr - hash - help - hex - id - input - int - intern - isinstance - issubclass - iter - len - list - locals - long - map - max - min - next - object - oct - open - ord - pow - property - range - raw_input - reduce - reload - repr - reversed - round - set - setattr - slice - sorted - staticmethod - str - sum - super - tuple - type - unichr - unicode - vars - xrange - zip - - - None - self - True - False - NotImplemented - Ellipsis - __debug__ - __file__ - - - SIGNAL - SLOT - connect - - - __new__ - __init__ - __del__ - __repr__ - __str__ - __lt__ - __le__ - __eq__ - __ne__ - __gt__ - __ge__ - __cmp__ - __rcmp__ - __hash__ - __nonzero__ - __unicode__ - __getattr__ - __setattr__ - __delattr__ - __getattribute__ - __get__ - __set__ - __delete__ - __call__ - __len__ - __getitem__ - __setitem__ - __delitem__ - __iter__ - __reversed__ - __contains__ - __getslice__ - __setslice__ - __delslice__ - __add__ - __sub__ - __mul__ - __floordiv__ - __mod__ - __divmod__ - __pow__ - __lshift__ - __rshift__ - __and__ - __xor__ - __or__ - __div__ - __truediv__ - __radd__ - __rsub__ - __rmul__ - __rdiv__ - __rtruediv__ - __rfloordiv__ - __rmod__ - __rdivmod__ - __rpow__ - __rlshift__ - __rrshift__ - __rand__ - __rxor__ - __ror__ - __iadd__ - __isub__ - __imul__ - __idiv__ - __itruediv__ - __ifloordiv__ - __imod__ - __ipow__ - __ilshift__ - __irshift__ - __iand__ - __ixor__ - __ior__ - __neg__ - __pos__ - __abs__ - __invert__ - __complex__ - __int__ - __long__ - __float__ - __oct__ - __hex__ - __index__ - __coerce__ - __enter__ - __exit__ - - - ArithmeticError - AssertionError - AttributeError - BaseException - DeprecationWarning - EnvironmentError - EOFError - Exception - FloatingPointError - FutureWarning - GeneratorExit - IOError - ImportError - ImportWarning - IndexError - KeyError - KeyboardInterrupt - LookupError - MemoryError - NameError - NotImplementedError - OSError - OverflowError - PendingDeprecationWarning - ReferenceError - RuntimeError - RuntimeWarning - StandardError - StopIteration - SyntaxError - SyntaxWarning - SystemError - SystemExit - TypeError - UnboundLocalError - UserWarning - UnicodeError - UnicodeWarning - UnicodeEncodeError - UnicodeDecodeError - UnicodeTranslateError - ValueError - Warning - WindowsError - ZeroDivisionError - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/qml.xml b/part/syntax/data/qml.xml deleted file mode 100644 index d4ad815..0000000 --- a/part/syntax/data/qml.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - State - PropertyChanges - StateGroup - ParentChange - StateChangeScript - AnchorChanges - PropertyAnimation - NumberAnimation - ColorAnimation - SequentialAnimation - ParallelAnimation - PauseAnimation - PropertyAction - ParentAction - ScriptAction - Transition - SpringFollow - EaseFollow - Behavior - Binding - ListModel - ListElement - VisualItemModel - XmlListModel - XmlRole - DateTimeFormatter - NumberFormatter - Script - Connection - Component - Timer - QtObject - Item - Rectangle - Image - BorderImage - Text - TextInput - TextEdit - MouseArea - FocusScope - Flickable - Flipable - WebView - Loader - Repeater - SystemPalette - GraphicsObjectContainer - LayoutItem - ListView - GridView - PathView - Path - PathLine - PathQuad - PathCubic - PathAttribute - PathPercent - Column - Row - Grid - Scale - Rotation - Blur - Colorize - DropShadow - Opacity - Particles - ParticleMotionLinear - ParticleMotionGravity - ParticleMotionWander - - Gradient - GradientStop - MouseRegion - - - - string - int - bool - date - color - url - real - double - var - variant - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/part/syntax/data/r.xml b/part/syntax/data/r.xml deleted file mode 100644 index ada76ec..0000000 --- a/part/syntax/data/r.xml +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - for - in - next - break - while - repeat - if - else - switch - function - - - TRUE - FALSE - NULL - NA - NA_integer_ - NA_real_ - NA_complex_ - NA_character_ - Inf - NaN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/rpmspec.xml b/part/syntax/data/rpmspec.xml deleted file mode 100644 index 385aae8..0000000 --- a/part/syntax/data/rpmspec.xml +++ /dev/null @@ -1,506 +0,0 @@ - - - - - - - -]> - - - - - - Mon - Tue - Wed - Thu - Fri - Sat - Sun - - - - Jan - Feb - Mar - Apr - May - Jun - Jul - Aug - Sep - Oct - Nov - Dec - - - - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 01 - 02 - 03 - 04 - 05 - 06 - 07 - 08 - 09 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21 - 22 - 23 - 24 - 25 - 26 - 27 - 28 - 29 - 30 - 31 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/ruby.xml b/part/syntax/data/ruby.xml deleted file mode 100644 index c59f015..0000000 --- a/part/syntax/data/ruby.xml +++ /dev/null @@ -1,915 +0,0 @@ - - - - - - - - - - - - - - BEGIN - END - and - begin - break - case - defined? - do - else - elsif - end - ensure - for - if - in - include - next - not - or - redo - rescue - retry - return - then - unless - until - when - while - yield - - - - private_class_method - private - protected - public_class_method - public - - - - attr_reader - attr_writer - attr_accessor - - - - alias - module - class - def - undef - - - - self - super - nil - false - true - caller - __FILE__ - __LINE__ - - - - $stdout - $defout - $stderr - $deferr - $stdin - - - - - - abort - at_exit - autoload - autoload? - binding - block_given? - callcc - caller - catch - chomp - chomp! - chop - chop! - eval - exec - exit - exit! - fail - fork - format - getc - gets - global_variables - gsub - gsub! - iterator? - lambda - load - local_variables - loop - method_missing - open - p - print - printf - proc - putc - puts - raise - rand - readline - readlines - require - scan - select - set_trace_func - sleep - split - sprintf - srand - sub - sub! - syscall - system - test - throw - trace_var - trap - untrace_var - warn - - - - TODO - FIXME - NOTE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/spice.xml b/part/syntax/data/spice.xml deleted file mode 100644 index 03b183a..0000000 --- a/part/syntax/data/spice.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/stata.xml b/part/syntax/data/stata.xml deleted file mode 100644 index c8eb249..0000000 --- a/part/syntax/data/stata.xml +++ /dev/null @@ -1,478 +0,0 @@ - - - - - - about - ado - adjust - alpha - anova - anovadef - append - assert - arch - areg - args - arima - bar - binreg - biprobit - bitest - boxcox - brier - break - browse - bstrap - by - canon - cap - capture - cat - cd - centile - cf - checksum - ci - clavg - class - clist - clcomp - clear - clgen - clkmeans - clkmed - clnote - clogit - cloglog - clsing - cltree - cluster - clutil - cmdlog - cnreg - cnsreg - creturn - codebook - collapse - compare - compress - confirm - constraint - contract - continue - copy - copyright - corr2data - corr - correlate - corrgram - count - cox - cross - ct - ctset - cttost - cumsp - cumul - cusum - datatypes - decode - define - describe - destring - dfuller - diagplots - dir - discard - di - display - do - doedit - dotplot - drawnorm - drop - dstdize - edit - egen - eivreg - else - encode - end - epitab - erase - ereturn - exit - expand - export - factor - fdadescribe - fdasave - fdause - fillin - file - filefilter - flist - for - foreach - forv - forval - forvalues - format - fracpoly - g - gen - generate - gettoken - glm - glogit - gprefs - gr7 - graph7 - gr - graph - grmeanby - gsort - hadimvo - hausman - haver - heckman - heckprob - help - hetprob - hexdump - hilite - hist - hotel - if - icd9 - impute - in - infile - infile1 - infile2 - infiling - infix - input - insheet - inspect - ipolate - ivreg - jknife - joinby - kappa - kdensity - keep - ksm - ksmirnov - kwallis - label - ladder - levels - limits - lincom - line - linktest - list - lnskew0 - log - logistic - lowess - lfit - lstat - lroc - lsens - logit - loneway - lrtest - ltable - lv - manova - manovatest - mark - markin - markout - marksample - matsize - maximize - means - median - memory - merge - mfx - mkdir - mkspline - ml - mleval - mlmatbysum - mlmatsum - mlsum - mlvecsum - mlogit - more - move - mvencode - mvreg - nbreg - net - newey - news - nl - nlogit - nobreak - nois - noisily - notes - nptrend - numlist - obs - odbc - ologit - oneway - oprobit - order - orthog - outfile - outsheet - parse - pcorr - _pctile - pctile - pergram - pk - pkcollapse - pkcross - pkequiv - pkexamine - pkshape - pksumm - plot - poisson - post - postclose - postfile - postutil - pperron - prais - predict - preserve - probit - program - prtest - pwcorr - qc - qreg - quadchk - query - qui - quietly - ranksum - range - recast - recode - reg3 - regdiag - reg - regress - rename - replace - reshape - restore - return - roc - rocplot - rotate - rreg - runtest - run - sample - sampsi - save - scatter - scobit - score - sdtest - search - separate - serrbar - set - shell - signrank - signtest - simul - sktest - smooth - snapspan - sort - spearman - spikeplot - sreturn - st - stack - statsby - stb - stbase - stci - stcox - stdes - stem - stfill - stgen - stir - stphplot - stptime - strate - streg - sts - stset - stsplit - stsum - sttocc - sttoct - stvary - sum - summarize - sureg - svy - svydes - svylc - svymean - svyset - svytab - svytest - sw - swilk - symmetry - syntax - tab - table - tabdisp - tabstat - tabsum - tabulate - tempname - tempvar - tempfile - test - testnl - tobit - tokenize - translate - translator - transmap - treatreg - truncreg - tsreport - tsrevar - tsset - ttest - tutorials - twoway - type - unabcmd - unabbr - update - use - using - version - vce - view - vwls - weibull - whelp - while - which - wntestb - wntestq - xcorr - xi - xpose - xt - xtabond - xtclog - xtdata - xtdes - xtgee - xtgls - xtintreg - xtile - xtivreg - xtlogit - xtnbreg - xtpcse - xtpois - xtprobit - xtrchh - xtreg - xtregar - xtsum - xttab - xttobit - zip - - - char - double - error - text - result - float - int - long - local - global - macro - mat - matrix - scalar - variable - var - varlist - varname - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/tcl.xml b/part/syntax/data/tcl.xml deleted file mode 100644 index cb74c1f..0000000 --- a/part/syntax/data/tcl.xml +++ /dev/null @@ -1,536 +0,0 @@ - - - - - - - - - - - - after - append - AppleScript - argv - argc - array - auto_execk - auto_load - auto_mkindex - auto_path - auto_reset - beep - bell - binary - bind - bindtags - bgerror - break - button - canvas - case - catch - cd - checkbutton - clipboard - clock - close - concat - console - continue - dde - destroy - else - elseif - encoding - entry - env - eof - error - errorCode - errorInfo - eval - event - exec - exit - expr - fblocked - fconfigure - fcopy - file - fileevent - flush - focus - font - for - foreach - format - frame - gets - glob - global - grab - grid - history - if - image - incr - info - interp - join - label - lappend - lindex - linsert - list - listbox - llength - load - lower - lrange - lreplace - lsearch - lsort - menu - menubutton - message - namespace - open - option - OptProc - pack - package - parray - pid - place - pkg_mkindex - proc - puts - pwd - radiobutton - raise - read - regexp - registry - regsub - rename - resource - return - scale - scan - scrollbar - seek - selection - send - set - socket - source - split - string - subst - switch - tclLog - tcl_endOfWord - tcl_findLibrary - tcl_library - tcl_patchLevel - tcl_platform - tcl_precision - tcl_rcFileName - tcl_rcRsrcName - tcl_startOfNextWord - tcl_startOfPreviousWord - tcl_traceCompile - tcl_traceExec - tcl_version - tcl_wordBreakAfter - tcl_wordBreakBefore - tell - text - time - tk - tkTabToWindow - tkwait - tk_chooseColor - tk_chooseDirectory - tk_focusFollowMouse - tk_focusNext - tk_focusPrev - tk_getOpenFile - tk_getSaveFile - tk_library - tk_messageBox - tk_optionMenu - tk_patchLevel - tk_popup - tk_strictMotif - tk_version - toplevel - trace - unknown - unset - update - uplevel - upvar - variable - vwait - while - winfo - wm - - - - add - args - atime - attributes - body - bytelength - cancel - channels - clicks - cmdcount - commands - compare - complete - convertfrom - convertto - copy - default - delete - dirname - equal - executable - exists - extension - first - forget - format - functions - globals - hostname - idle - ifneeded - index - info - is - isdirectory - isfile - join - last - length - level - library - link - loaded - locals - lstat - map - match - mkdir - mtime - nameofexecutable - names - nativename - normalize - number - owned - patchlevel - pathtype - present - procs - provide - range - readable - readlink - remove - rename - repeat - replace - require - rootname - scan - script - seconds - separator - sharedlibextension - size - split - stat - system - tail - tclversion - tolower - totitle - toupper - trim - trimleft - trimright - type - unknown - variable - vars - vcompare - vdelete - versions - vinfo - volumes - vsatisfies - wordend - wordstart - writable - - activate - actual - addtag - append - appname - aspect - atom - atomname - bbox - bind - broadcast - canvasx - canvasy - caret - cells - cget - children - class - clear - client - clone - colormapfull - colormapwindows - command - configure - containing - coords - create - current - curselection - dchars - debug - deiconify - delta - depth - deselect - dlineinfo - dtag - dump - edit - entrycget - entryconfigure - families - find - flash - focus - focusmodel - fpixels - fraction - frame - generate - geometry - get - gettags - grid - group - handle - height - hide - iconbitmap - iconify - iconmask - iconname - iconposition - iconwindow - icursor - id - identify - image - insert - interps - inuse - invoke - ismapped - itemcget - itemconfigure - keys - lower - manager - mark - maxsize - measure - metrics - minsize - move - name - nearest - overrideredirect - own - panecget - paneconfigure - panes - parent - pathname - pixels - pointerx - pointerxy - pointery - positionfrom - post - postcascade - postscript - protocol - proxy - raise - release - reqheight - reqwidth - resizable - rgb - rootx - rooty - scale - scaling - screen - screencells - screendepth - screenheight - screenmmheight - screenmmwidth - screenvisual - screenwidth - search - see - select - selection - server - set - show - sizefrom - stackorder - state - status - tag - title - toplevel - transient - types - unpost - useinputmethods - validate - values - viewable - visual - visualid - visualsavailable - vrootheight - vrootwidth - vrootx - vrooty - width - window - windowingsystem - withdraw - x - xview - y - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/verilog.xml b/part/syntax/data/verilog.xml deleted file mode 100644 index ffb5bac..0000000 --- a/part/syntax/data/verilog.xml +++ /dev/null @@ -1,240 +0,0 @@ - - - - - - macromodule - task - endtask - function - endfunction - table - endtable - specify - specparam - endspecify - case - casex - casez - endcase - fork - join - - defparam - default - if - ifnone - else - forever - while - for - wait - repeat - disable - - assign - deassign - force - release - - always - initial - edge - posedge - negedge - - - - - strong0 - strong1 - pull0 - pull1 - weak0 - weak1 - highz0 - highz1 - - small - medium - large - - - - pullup - pulldown - cmos - rcmos - nmos - pmos - rnmos - rpmos - and - nand - or - nor - xor - xnor - not - buf - tran - rtran - tranif0 - tranif1 - rtranif0 - rtranif1 - bufif0 - bufif1 - notif0 - notif1 - - - - - input - output - inout - - wire - tri - tri0 - tri1 - wand - wor - triand - trior - supply0 - supply1 - - reg - integer - real - realtime - time - - vectored - scalared - trireg - - parameter - event - - - - begin - - - end - - - module - - - endmodule - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/wml.xml b/part/syntax/data/wml.xml deleted file mode 100644 index d2f9ca7..0000000 --- a/part/syntax/data/wml.xml +++ /dev/null @@ -1,196 +0,0 @@ - - - - - - - - wmllint - wmlindent - wmlscope - - - #textdomain - #else - #undef - - - #define - #ifdef - #ifndef - - - #enddef - #endif - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/xml.xml b/part/syntax/data/xml.xml deleted file mode 100644 index a576e49..0000000 --- a/part/syntax/data/xml.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - - -]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/katecodefolding.cpp b/part/syntax/katecodefolding.cpp deleted file mode 100644 index 4d2121d..0000000 --- a/part/syntax/katecodefolding.cpp +++ /dev/null @@ -1,1730 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katecodefolding.h" -#include "katecodefolding.moc" - -#include "katebuffer.h" -#include - -#include - -/*#define JW_DEBUG 1*/ -#undef JW_DEBUG - -bool KateCodeFoldingTree::trueVal = true; - -KateCodeFoldingNode::KateCodeFoldingNode() : - parentNode(0), - startLineRel(0), - endLineRel(0), - startCol(0), - endCol(0), - startLineValid(false), - endLineValid(false), - type(0), - visible(true), - deleteOpening(false), - deleteEnding(false), - allowDestruction(true) -{ -}//the endline fields should be initialised to not valid - -KateCodeFoldingNode::KateCodeFoldingNode(KateCodeFoldingNode *par, signed char typ, unsigned int sLRel): - parentNode(par), - startLineRel(sLRel), - endLineRel(10000), - startCol(0), - endCol(0), - startLineValid(true), - endLineValid(false), - type(typ), - visible(true), - deleteOpening(false), - deleteEnding(false), - allowDestruction(true) -{ -}//the endline fields should be initialised to not valid - -KateCodeFoldingNode::~KateCodeFoldingNode() -{ - // delete all child nodes - clearChildren (); -} - -bool KateCodeFoldingNode::getBegin(KateCodeFoldingTree *tree, KTextEditor::Cursor* begin) { - if (!startLineValid) return false; - unsigned int line=startLineRel; - for (KateCodeFoldingNode *n=parentNode;n;n=n->parentNode) - line+=n->startLineRel; - - tree->m_buffer->codeFoldingColumnUpdate(line); - begin->setLine(line); - begin->setColumn(startCol); - - return true; -} - -bool KateCodeFoldingNode::getEnd(KateCodeFoldingTree *tree, KTextEditor::Cursor *end) { - if (!endLineValid) return false; - unsigned int line=startLineRel+endLineRel; - for (KateCodeFoldingNode *n=parentNode;n;n=n->parentNode) - line+=n->startLineRel; - - tree->m_buffer->codeFoldingColumnUpdate(line); - end->setLine(line); - end->setColumn(endCol); - - return true; -} - -int KateCodeFoldingNode::cmpPos(KateCodeFoldingTree *tree, uint line,uint col) { - KTextEditor::Cursor cur(line,col); - KTextEditor::Cursor start,end; - kDebug(13000)<<"KateCodeFoldingNode::cmpPos (1)"; - bool startValid=getBegin(tree, &start); - kDebug(13000)<<"KateCodeFoldingNode::cmpPos (2)"; - bool endValid=getEnd(tree, &end); - kDebug(13000)<<"KateCodeFoldingNode::cmpPos (3)"; - if ((!endValid) && startValid) { - return ((start>cur)?-1:0); - } - if ((!startValid) && endValid) { - return ((cur>end)?1:0); - } - //here both have to be valid, both invalid must not happen - Q_ASSERT(startValid && endValid); - return ( (curend) ? 1:0)); -} - -void KateCodeFoldingNode::insertChild (uint index, KateCodeFoldingNode *node) -{ - uint s = m_children.size (); - - if (index > s) - return; - - m_children.resize (++s); - - for (uint i=s-1; i > index; --i) - m_children[i] = m_children[i-1]; - - m_children[index] = node; -} - -KateCodeFoldingNode *KateCodeFoldingNode::takeChild (uint index) -{ - uint s = m_children.size (); - - if (index >= s) - return 0; - - KateCodeFoldingNode *n = m_children[index]; - - for (uint i=index; (i+1) < s; ++i) - m_children[i] = m_children[i+1]; - - m_children.resize (s-1); - - return n; -} - -void KateCodeFoldingNode::clearChildren () -{ - for (int i=0; i < m_children.size(); ++i) - delete m_children[i]; - - m_children.resize (0); - - startLineValid=true; - endLineValid=true; // temporary, should be false; - endLineRel=1; // temporary; -} - -KateCodeFoldingTree::KateCodeFoldingTree(KateBuffer *buffer) - : QObject(buffer) - , m_buffer(buffer) - , hiddenLinesCountCacheValid(false) - , m_clearCache(false) -{ -} - -void KateCodeFoldingTree::fixRoot(int endLRel) -{ - m_root.endLineRel = endLRel; -} - -void KateCodeFoldingTree::clear() -{ - m_root.clearChildren(); - - hiddenLinesCountCacheValid=false; - hiddenLines.clear(); - lineMapping.clear(); - nodesForLine.clear(); - markedForDeleting.clear(); - dontIgnoreUnchangedLines.clear(); -} - -KateCodeFoldingTree::~KateCodeFoldingTree() -{ -} - -bool KateCodeFoldingTree::isTopLevel(unsigned int line) -{ - if (m_root.noChildren()) - return true; // no children - - // look if a given lines belongs to a sub node - for ( int i=0; i < m_root.childCount(); ++i ) - { - KateCodeFoldingNode *node = m_root.child(i); - - if ((node->startLineRel<=line) && (line<=node->startLineRel+node->endLineRel)) - return false; // the line is within the range of a subnode -> return toplevel=false - } - - return true; // the root node is the only node containing the given line, return toplevel=true -} - -void KateCodeFoldingTree::getLineInfo(KateLineInfo *info, unsigned int line) -{ - // Initialze the returned structure, this will also be returned if the root node has no child nodes - // or the line is not within a childnode's range. - info->topLevel = true; - info->startsVisibleBlock = false; - info->startsInVisibleBlock = false; - info->endsBlock = false; - info->invalidBlockEnd = false; - info->depth=0; - if (m_root.noChildren()) - return; - - //let's look for some information - for ( int i=0; i < m_root.childCount(); ++i ) - { - KateCodeFoldingNode *node = m_root.child(i); - - if ((node->startLineRel<=line) && (line<=node->startLineRel+node->endLineRel)) // we found a node, which contains the given line -> do a complete lookup - { - info->topLevel = false; //we are definitly not toplevel - findAllNodesOpenedOrClosedAt(line); //lookup all nodes, which start or and at the given line - - foreach (KateCodeFoldingNode* node, nodesForLine) - { - uint startLine = getStartLine(node); - - // type<0 means, that a region has been closed, but not opened - // eg. parantheses missmatch - if (node->type < 0) - info->invalidBlockEnd=true; - else - { - if (startLine != line) // does the region we look at not start at the given line - info->endsBlock = true; // than it has to be an ending - else - { - // The line starts a new region, now determine, if it's a visible or a hidden region - if (node->visible) - info->startsVisibleBlock=true; - else - info->startsInVisibleBlock=true; - } - } - } - KateCodeFoldingNode *node = findNodeForLine(line); - int depth=0; - while (node) - { - node = node->getParentNode(); - depth++; - } - if (depth>0) depth--; - info->depth=depth; - return; - } - } - - return; -} - - -KateCodeFoldingNode *KateCodeFoldingTree::findNodeForLine(unsigned int line) -{ - if (m_root.noChildren()) // do we have child list + nodes ? - return &m_root; - - // lets look, if given line is within a subnode range, and then return the deepest one. - for ( int i=0; i < m_root.childCount(); ++i ) - { - KateCodeFoldingNode *node = m_root.child(i); - - if (node->startLineValid && (node->startLineRel<=line) && (line<=node->startLineRel+node->endLineRel)) - { - // a region surounds the line, look in the next deeper hierarchy step - return findNodeForLineDescending(node,line,0); - } - } - - return &m_root; -} - - -KateCodeFoldingNode *KateCodeFoldingTree::findNodeForLineDescending ( KateCodeFoldingNode *node, - unsigned int line, unsigned int offset, bool oneStepOnly ) -{ - if (node->noChildren()) - return node; - - // calculate the offset, between a subnodes real start line and its relative start - offset += node->startLineRel; - - for ( int i=0; i < node->childCount(); ++i ) - { - KateCodeFoldingNode *subNode = node->child(i); - - if ((subNode->startLineRel+offset<=line) && (line<=subNode->endLineRel+subNode->startLineRel+offset)) //warning fix me for invalid ends - { - // a subnode contains the line. - // if oneStepOnly is true, we don't want to search for the deepest node, just return the found one - - if (oneStepOnly) - return subNode; - else - return findNodeForLineDescending (subNode,line,offset); // look into the next deeper hierarchy step - } - } - - return node; // the current node has no sub nodes, or the line couldn'te be found within a subregion -} - -KateCodeFoldingNode *KateCodeFoldingTree::findNodeForPosition(unsigned int line, unsigned int column) -{ - KateCodeFoldingNode *node=findNodeForLine(line); - - if (node==&m_root) return &m_root; - - kDebug(13000)<<"initial cmpPos"; - - KateCodeFoldingNode *tmp; - int leq=node->cmpPos(this, line,column); - while (true) { - switch (leq) { - case 0: { - if (node->noChildren()) - return node; - else - { - tmp=node; - for ( int i=0; i < node->childCount(); ++i ) - { - KateCodeFoldingNode *subNode = node->child(i); - kDebug(13000)<<"cmdPos(case0):calling"; - leq=subNode->cmpPos(this, line,column); - kDebug(13000)<<"cmdPos(case0):returned"; - if (leq==0) { - tmp=subNode; - break; - } else if (leq==-1) break; - } - if (tmp!=node) node=tmp; else return node; - } - break; - } - //this could be optimized a littlebit - case -1: - case 1: { - if (!(node->parentNode)) return &m_root; - kDebug(13000)<<"current node type"<type; - node=node->parentNode; - kDebug(13000)<<"cmdPos(case-1/1):calling:"<cmpPos(this, line,column); - kDebug(13000)<<"cmdPos(case-1/1):returned"; - break; - } - } - - } - Q_ASSERT(false); - return &m_root; -} - -void KateCodeFoldingTree::debugDump() -{ - //dump all nodes for debugging - kDebug(13000)<<"The parsed region/block tree for code folding"; - dumpNode(&m_root, ""); -} - -void KateCodeFoldingTree::dumpNode(KateCodeFoldingNode *node, const QString &prefix) -{ - //output node properties - kDebug(13000)<type).arg(node->startLineValid).arg(node->startLineRel).arg(node->endLineValid). - arg(node->endLineRel).arg(node->visible)<<"Parent:"<parentNode<noChildren()) - return; - - QString newprefix(prefix + " "); - for ( int i=0; i < node->childCount(); ++i ) - dumpNode (node->child(i),newprefix); -} - -/* - That's one of the most important functions ;) -*/ -void KateCodeFoldingTree::updateLine(unsigned int line, - QVector *regionChanges, bool *updated,bool changed,bool colsChanged) -{ - if ( (!changed) || colsChanged) - { - if (dontIgnoreUnchangedLines.isEmpty()) - return; - - if (dontIgnoreUnchangedLines.contains(line)) - dontIgnoreUnchangedLines.remove(line); - else - return; - } - - something_changed = false; - - findAndMarkAllNodesforRemovalOpenedOrClosedAt(line); - - if (regionChanges->isEmpty()) - { - // KateCodeFoldingNode *node=findNodeForLine(line); - // if (node->type!=0) - // if (getStartLine(node)+node->endLineRel==line) removeEnding(node,line); - } - else - { - for (int i=0;isize() / 4;i++) - { - signed char tmp=(*regionChanges)[regionChanges->size()-2-i*2]; - uint tmppos=(*regionChanges)[regionChanges->size()-1-i*2]; - (*regionChanges)[regionChanges->size()-2-i*2]=(*regionChanges)[i*2]; - (*regionChanges)[regionChanges->size()-1-i*2]=(*regionChanges)[i*2+1]; - (*regionChanges)[i*2]=tmp; - (*regionChanges)[i*2+1]=tmppos; - } - - - signed char data= (*regionChanges)[regionChanges->size()-2]; - uint charPos=(*regionChanges)[regionChanges->size()-1]; - regionChanges->resize (regionChanges->size()-2); - - int insertPos=-1; - KateCodeFoldingNode *node = findNodeForLine(line); - - if (data<0) - { - // if (insertPos==-1) - { - unsigned int tmpLine=line-getStartLine(node); - - for ( int i=0; i < node->childCount(); ++i ) - { - if (node->child(i)->startLineRel >= tmpLine) - { - insertPos=i; - break; - } - } - } - } - else - { - for (; (node->parentNode) && (getStartLine(node->parentNode)==line) && - (node->parentNode->type!=0); node=node->parentNode) { - ; - } - - if ((getStartLine(node)==line) && (node->type!=0)) - { - insertPos=node->parentNode->findChild(node); - node = node->parentNode; - } - else - { - for ( int i=0; i < node->childCount(); ++i ) - { - if (getStartLine(node->child(i))>=line) - { - insertPos=i; - break; - } - } - } - } - - do - { - if (data<0) - { - if (correctEndings(data,node,line,charPos,insertPos)) - { - insertPos=node->parentNode->findChild(node)+1; - node=node->parentNode; - } - else - { - if (insertPos!=-1) insertPos++; - } - } - else - { - int startLine=getStartLine(node); - if ((insertPos==-1) || (insertPos>=(int)node->childCount())) - { - KateCodeFoldingNode *newNode = new KateCodeFoldingNode (node,data,line-startLine); - something_changed = true; - node->appendChild(newNode); - addOpening(newNode, data, regionChanges, line,charPos); - insertPos = node->findChild(newNode)+1; - } - else - { - if (node->child(insertPos)->startLineRel == line-startLine) - { - addOpening(node->child(insertPos), data, regionChanges, line,charPos); - insertPos++; - } - else - { -// kDebug(13000)<<"ADDING NODE "; - KateCodeFoldingNode *newNode = new KateCodeFoldingNode (node,data,line-startLine); - something_changed = true; - node->insertChild(insertPos, newNode); - addOpening(newNode, data, regionChanges, line,charPos); - insertPos++; - } - } - } - - if (regionChanges->isEmpty()) - data = 0; - else - { - data = (*regionChanges)[regionChanges->size()-2]; - charPos=(*regionChanges)[regionChanges->size()-1]; - regionChanges->resize (regionChanges->size()-2); - } - } while (data!=0); - } - - cleanupUnneededNodes(line); -// if (something_changed) emit regionBeginEndAddedRemoved(line); - (*updated) = something_changed; -} - - -bool KateCodeFoldingTree::removeOpening(KateCodeFoldingNode *node,unsigned int line) -{ - signed char type; - if ((type=node->type) == 0) - { - dontDeleteOpening(node); - dontDeleteEnding(node); - return false; - } - - if (!node->visible) - { - m_clearCache=true; - node->setAllowDestruction(false); - toggleRegionVisibility(getStartLine(node)); - node->setAllowDestruction(true); - m_clearCache=false; - } - - KateCodeFoldingNode *parent = node->parentNode; - int mypos = parent->findChild(node); - - if (mypos > -1) - { - //move childnodes() up - for(; node->childCount()>0 ;) - { - KateCodeFoldingNode *tmp; - parent->insertChild(mypos, tmp=node->takeChild(0)); - tmp->parentNode = parent; - tmp->startLineRel += node->startLineRel; - mypos++; - } - - // remove the node - //mypos = parent->findChild(node); - bool endLineValid = node->endLineValid; - int endLineRel = node->endLineRel; - uint endCol=node->endCol; - - // removes + deletes - KateCodeFoldingNode *child = parent->takeChild(mypos); - markedForDeleting.removeAll(child); -// removeParentReferencesFromChilds(child); - delete child; - - if ((type>0) && (endLineValid)) - correctEndings(-type, parent, line+endLineRel/*+1*/,endCol, mypos); // why the hell did I add a +1 here ? - } - - return true; -} - -bool KateCodeFoldingTree::removeEnding(KateCodeFoldingNode *node,unsigned int /* line */) -{ - KateCodeFoldingNode *parent = node->parentNode; - - if (!parent) - return false; - - if (node->type == 0) - return false; - - if (node->type < 0) - { - // removes + deletes - int i = parent->findChild (node); - if (i >= 0) - { - KateCodeFoldingNode *child = parent->takeChild(i); - markedForDeleting.removeAll(child); -// removeParentReferencesFromChilds(child); - delete child; - } - - return true; - } - - int mypos = parent->findChild(node); - int count = parent->childCount(); - - for (int i=mypos+1; ichild(i)->type == -node->type) - { - node->endLineValid = true; - node->endLineRel = parent->child(i)->startLineRel - node->startLineRel; - - KateCodeFoldingNode *child = parent->takeChild(i); - markedForDeleting.removeAll(child); -// removeParentReferencesFromChilds(child); - delete child; - - count = i-mypos-1; - if (count > 0) - { - for (int i=0; itakeChild(mypos+1); - tmp->startLineRel -= node->startLineRel; - tmp->parentNode = node; //should help 16.04.2002 - node->appendChild(tmp); - } - } - return false; - } - } - - if ( (parent->type == node->type) || /*temporary fix */ (!parent->parentNode)) - { - for (int i=mypos+1; i<(int)parent->childCount(); i++) - { - KateCodeFoldingNode *tmp = parent->takeChild(mypos+1); - tmp->startLineRel -= node->startLineRel; - tmp->parentNode = node; // SHOULD HELP 16.04.2002 - node->appendChild(tmp); - } - - // this should fix the bug of wrongly closed nodes - if (!parent->parentNode) - node->endLineValid=false; - else - node->endLineValid = parent->endLineValid; - - node->endLineRel = parent->endLineRel-node->startLineRel; - - if (node->endLineValid) - return removeEnding(parent, getStartLine(parent)+parent->endLineRel); - - return false; - } - - node->endLineValid = false; - node->endLineRel = parent->endLineRel - node->startLineRel; - - return false; -} - - -bool KateCodeFoldingTree::correctEndings(signed char data, KateCodeFoldingNode *node,unsigned int line,unsigned int endCol,int insertPos) -{ -// if (node->type==0) {kError()<<"correct Ending should never be called with the root node"<type) - { -#ifdef JW_DEBUG - kDebug(13000)<<"data!=-node->type (correctEndings)"; -#endif - //invalid close -> add to unopend list - dontDeleteEnding(node); - if (data == node->type) { - node->endCol=endCol; - return false; - } - KateCodeFoldingNode *newNode = new KateCodeFoldingNode (node,data,line-startLine); - something_changed = true; - newNode->startLineValid = false; - newNode->endLineValid = true; - newNode->endLineRel = 0; - newNode->endCol=endCol; - - if ((insertPos==-1) || (insertPos==(int)node->childCount())) - node->appendChild(newNode); - else - node->insertChild(insertPos,newNode); - - // find correct position - return false; - } - else - { - something_changed = true; - dontDeleteEnding(node); - - // valid closing region - if (!node->endLineValid) - { - node->endLineValid = true; - node->endLineRel = line - startLine; - node->endCol=endCol; - //moving - - moveSubNodesUp(node); - } - else - { -#ifdef JW_DEBUG - kDebug(13000)<<"Closing a node which had already a valid end"; -#endif - // block has already an ending - if (startLine+node->endLineRel == line) - { - node->endCol=endCol; - // we won, just skip -#ifdef JW_DEBUG - kDebug(13000)<< "We won, just skipping (correctEndings)"; -#endif - } - else - { - int bakEndLine = node->endLineRel+startLine; - uint bakEndCol = node->endCol; - node->endLineRel = line-startLine; - node->endCol=endCol; - -#ifdef JW_DEBUG - kDebug(13000)<< "reclosed node had childnodes()"; - kDebug(13000)<<"It could be, that childnodes() need to be moved up"; -#endif - moveSubNodesUp(node); - - if (node->parentNode) - { - correctEndings(data,node->parentNode,bakEndLine, bakEndCol,node->parentNode->findChild(node)+1); // ???? - } - else - { - //add to unopened list (bakEndLine) - } - } - } - } - return true; -} - -void KateCodeFoldingTree::moveSubNodesUp(KateCodeFoldingNode *node) -{ - int mypos = node->parentNode->findChild(node); - int removepos=-1; - int count = node->childCount(); - for (int i=0; ichild(i)->startLineRel >= node->endLineRel) - { - removepos=i; - break; - } -#ifdef JW_DEBUG - kDebug(13000)<-1) - { -#ifdef JW_DEBUG - kDebug(13000)<<"Children need to be moved"; -#endif - KateCodeFoldingNode *moveNode; - if (mypos == (int)node->parentNode->childCount()-1) - { - while (removepos<(int)node->childCount()) - { - node->parentNode->appendChild(moveNode=node->takeChild(removepos)); - moveNode->parentNode = node->parentNode; - moveNode->startLineRel += node->startLineRel; - } - } - else - { - int insertPos=mypos; - while (removepos < (int)node->childCount()) - { - insertPos++; - node->parentNode->insertChild(insertPos, moveNode=node->takeChild(removepos)); - moveNode->parentNode = node->parentNode; // That should solve a crash - moveNode->startLineRel += node->startLineRel; - } - } - } - -} - - - -void KateCodeFoldingTree::addOpening(KateCodeFoldingNode *node,signed char nType, QVector* list,unsigned int line,unsigned int charPos) -{ - uint startLine = getStartLine(node); - if ((startLine==line) && (node->type!=0)) - { -#ifdef JW_DEBUG - kDebug(13000)<<"startLine equals line"; -#endif - if (nType == node->type) - { -#ifdef JW_DEBUG - kDebug(13000)<<"Node exists"; -#endif - node->deleteOpening = false; - node->startCol=charPos; - KateCodeFoldingNode *parent = node->parentNode; - - if (!node->endLineValid) - { - int current = parent->findChild(node); - int count = parent->childCount()-(current+1); - node->endLineRel = parent->endLineRel - node->startLineRel; - -// EXPERIMENTAL TEST BEGIN -// move this afte the test for unopened, but closed regions within the parent node, or if there are no siblings, bubble up - if (parent->type == node->type) - { - if (parent->endLineValid) - { - removeEnding(parent, line); - node->endLineValid = true; - } - } - -// EXPERIMENTAL TEST BEGIN - - if (current != (int)parent->childCount()-1) - { - //search for an unopened but closed region, even if the parent is of the same type -#ifdef __GNUC__ -#warning "FIXME: why does this seem to work?" -#endif -// if (node->type != parent->type) - { - for (int i=current+1; i<(int)parent->childCount(); i++) - { - if (parent->child(i)->type == -node->type) - { - count = (i-current-1); - node->endLineValid = true; - node->endLineRel = getStartLine(parent->child(i))-line; - node->endCol = parent->child(i)->endCol; - KateCodeFoldingNode *child = parent->takeChild(i); - markedForDeleting.removeAll( child ); -// removeParentReferencesFromChilds(child); - delete child; - break; - } - } - } -// else -// { -// parent->endLineValid = false; -// parent->endLineRel = 20000; -// } - - if (count>0) - { - for (int i=0;iappendChild(tmp=parent->takeChild(current+1)); - tmp->startLineRel -= node->startLineRel; - tmp->parentNode = node; - } - } - } - - } - - addOpening_further_iterations(node, nType, list, line, 0, startLine,node->startCol); - - } //else ohoh, much work to do same line, but other region type - } - else - { // create a new region - KateCodeFoldingNode *newNode = new KateCodeFoldingNode (node,nType,line-startLine); - something_changed = true; - - int insert_position=-1; - for (int i=0; i<(int)node->childCount(); i++) - { - if (startLine+node->child(i)->startLineRel > line) - { - insert_position=i; - break; - } - } - - int current; - if (insert_position==-1) - { - node->appendChild(newNode); - current = node->childCount()-1; - } - else - { - node->insertChild(insert_position, newNode); - current = insert_position; - } - -// if (node->type==newNode->type) -// { -// newNode->endLineValid=true; -// node->endLineValid=false; -// newNode->endLineRel=node->endLineRel-newNode->startLineRel; -// node->endLineRel=20000; //FIXME - - int count = node->childCount() - (current+1); - newNode->endLineRel -= newNode->startLineRel; - if (current != (int)node->childCount()-1) - { - if (node->type != newNode->type) - { - for (int i=current+1; i<(int)node->childCount(); i++) - { - if (node->child(i)->type == -newNode->type) - { - count = node->childCount() - i - 1; - newNode->endLineValid = true; - newNode->endLineRel = line - getStartLine(node->child(i)); - KateCodeFoldingNode *child = node->takeChild(i); - markedForDeleting.removeAll( child ); -// removeParentReferencesFromChilds(child); - delete child; - break; - } - } - } - else - { - node->endLineValid = false; - node->endLineRel = 10000; - } - if (count > 0) - { - for (int i=0;iappendChild(tmp=node->takeChild(current+1)); - tmp->parentNode=newNode; - } - } -// } - } - - addOpening(newNode, nType, list, line,charPos); - - addOpening_further_iterations(node, node->type, list, line, current, startLine,node->startCol); - } -} - - -void KateCodeFoldingTree::addOpening_further_iterations(KateCodeFoldingNode *node,signed char /* nType */, QVector* - list,unsigned int line,int current, unsigned int startLine,unsigned int charPos) -{ - Q_UNUSED(charPos) - - while (!(list->isEmpty())) - { - if (list->isEmpty()) - return; - else - { - signed char data = (*list)[list->size()-2]; - uint charPos=(*list)[list->size()-1]; - list->resize (list->size()-2); - - if (data<0) - { -#ifdef JW_DEBUG - kDebug(13000)<<"An ending was found"; -#endif - - if (correctEndings(data,node,line,charPos,-1)) - return; // -1 ? - -#if 0 - if(data == -nType) - { - if (node->endLineValid) - { - if (node->endLineRel+startLine==line) // We've won again - { - //handle next node; - } - else - { // much moving - node->endLineRel=line-startLine; - node->endLineValid=true; - } - return; // next higher level should do the rest - } - else - { - node->endLineRel=line-startLine; - node->endLineValid=true; - //much moving - } - } //else add to unopened list -#endif - } - else - { - bool needNew = true; - if (current < (int)node->childCount()) - { - if (getStartLine(node->child(current)) == line) - needNew=false; - } - if (needNew) - { - something_changed = true; - KateCodeFoldingNode *newNode = new KateCodeFoldingNode(node, data, line-startLine); - node->insertChild(current, newNode); //find the correct position later - } - - addOpening(node->child(current), data, list, line,charPos); - current++; - //lookup node or create subnode - } - } - } // end while -} - -unsigned int KateCodeFoldingTree::getStartLine(KateCodeFoldingNode *node) -{ - unsigned int lineStart=0; - for (KateCodeFoldingNode *iter=node; iter->type != 0; iter=iter->parentNode) - lineStart += iter->startLineRel; - - return lineStart; -} - - -void KateCodeFoldingTree::lineHasBeenRemoved(unsigned int line) -{ - - lineMapping.clear(); - dontIgnoreUnchangedLines.insert(line); - dontIgnoreUnchangedLines.insert(line-1); - dontIgnoreUnchangedLines.insert(line+1); - hiddenLinesCountCacheValid = false; -#ifdef JW_DEBUG - kDebug(13000)<endLineValid) - { - int startLine = getStartLine(node); - if (startLine == (int)line) - node->startLineRel--; - else - { - if (node->endLineRel == 0) - node->endLineValid = false; - node->endLineRel--; - } - - int count = node->childCount(); - for (int i=0; ichild(i)->startLineRel+startLine >= line) - node->child(i)->startLineRel--; - } - } - - if (node->parentNode) - decrementBy1(node->parentNode, node); - - for (QList::iterator it=hiddenLines.begin(); it != hiddenLines.end(); ++it) - { - if ((*it).start > line) - (*it).start--; - else if ((*it).start+(*it).length > line) - (*it).length--; - } -} - - -void KateCodeFoldingTree::decrementBy1(KateCodeFoldingNode *node, KateCodeFoldingNode *after) -{ - if (node->endLineRel == 0) - node->endLineValid = false; - node->endLineRel--; - - for (int i=node->findChild(after)+1; i < node->childCount(); ++i) - node->child(i)->startLineRel--; - - if (node->parentNode) - decrementBy1(node->parentNode,node); -} - - -void KateCodeFoldingTree::lineHasBeenInserted(unsigned int line) -{ - lineMapping.clear(); - dontIgnoreUnchangedLines.insert(line); - dontIgnoreUnchangedLines.insert(line-1l); - dontIgnoreUnchangedLines.insert(line+1); - hiddenLinesCountCacheValid = false; -//return; -#ifdef JW_DEBUG - kDebug(13000)<endLineValid) - { - int startLine=getStartLine(node); - if (node->type < 0) - node->startLineRel++; - else - node->endLineRel++; - - for (int i=0; i < node->childCount(); ++i) - { - KateCodeFoldingNode *iter = node->child(i); - - if (iter->startLineRel+startLine >= line) - iter->startLineRel++; - } - } - - if (node->parentNode) - incrementBy1(node->parentNode, node); - - for (QList::iterator it=hiddenLines.begin(); it!=hiddenLines.end(); ++it) - { - if ((*it).start > line) - (*it).start++; - else if ((*it).start+(*it).length > line) - (*it).length++; - } -} - -void KateCodeFoldingTree::incrementBy1(KateCodeFoldingNode *node, KateCodeFoldingNode *after) -{ - node->endLineRel++; - - for (int i=node->findChild(after)+1; i < node->childCount(); ++i) - node->child(i)->startLineRel++; - - if (node->parentNode) - incrementBy1(node->parentNode,node); -} - - -void KateCodeFoldingTree::findAndMarkAllNodesforRemovalOpenedOrClosedAt(unsigned int line) -{ -#ifdef __GNUC__ -#warning "FIXME: make this multiple region changes per line save"; -#endif -// return; - markedForDeleting.clear(); - KateCodeFoldingNode *node = findNodeForLine(line); - if (node->type == 0) - return; - - addNodeToRemoveList(node, line); - - while (((node->parentNode) && (node->parentNode->type!=0)) && (getStartLine(node->parentNode)==line)) - { - node = node->parentNode; - addNodeToRemoveList(node, line); - } -#ifdef JW_DEBUG - kDebug(13000)<<" added line to markedForDeleting list"; -#endif -} - - -void KateCodeFoldingTree::addNodeToRemoveList(KateCodeFoldingNode *node,unsigned int line) -{ - bool add=false; -#ifdef __GNUC__ -#warning "FIXME: make this multiple region changes per line save"; -#endif - unsigned int startLine=getStartLine(node); - if ((startLine==line) && (node->startLineValid)) - { - add=true; - node->deleteOpening = true; - } - if ((startLine+node->endLineRel==line) || ((node->endLineValid==false) && (node->deleteOpening))) - { - int myPos=node->parentNode->findChild(node); // this has to be implemented nicely - if ((int)node->parentNode->childCount()>myPos+1) - addNodeToRemoveList(node->parentNode->child(myPos+1),line); - add=true; - node->deleteEnding = true; - } - - if(add) - markedForDeleting.append(node); - -#ifdef JW_DEBUG - kDebug(13000)<<"marking for deletion:"<type == 0) - return; - - unsigned int startLine = getStartLine(node); - if (startLine == line) - nodesForLine.append(node); - else if ((startLine+node->endLineRel == line)) - nodesForLine.append(node); - - while (node->parentNode) - { - addNodeToFoundList(node->parentNode, line, node->parentNode->findChild(node)); - node = node->parentNode; - } -/*#ifdef JW_DEBUG - kDebug(13000)<<" added line to nodesForLine list"; -#endif*/ -} - - -void KateCodeFoldingTree::addNodeToFoundList(KateCodeFoldingNode *node,unsigned int line,int childpos) -{ - unsigned int startLine = getStartLine(node); - - if ((startLine==line) && (node->type!=0)) - nodesForLine.append(node); - else if ((startLine+node->endLineRel==line) && (node->type!=0)) - nodesForLine.append(node); - - for (int i=childpos+1; i<(int)node->childCount(); i++) - { - KateCodeFoldingNode *child = node->child(i); - - if (startLine+child->startLineRel == line) - { - nodesForLine.append(child); - addNodeToFoundList(child, line, 0); - } - else - break; - } -} - - -void KateCodeFoldingTree::cleanupUnneededNodes(unsigned int line) -{ -#ifdef JW_DEBUG - kDebug(13000)<<"void KateCodeFoldingTree::cleanupUnneededNodes(unsigned int line):"<deleteOpening) - kDebug(13000)<<"DELETE OPENING SET"; - if (node->deleteEnding) - kDebug(13000)<<"DELETE ENDING SET"; -#endif - - if ((node->deleteOpening) && (node->deleteEnding)) - { -#ifdef JW_DEBUG - kDebug(13000)<<"Deleting complete node"; -#endif - if (node->endLineValid) // just delete it, it has been opened and closed on this line - { - int f = node->parentNode->findChild (node); - - if (f >= 0 && node->allowDestruction) { - KateCodeFoldingNode *delN=node->parentNode->takeChild(f); -// removeParentReferencesFromChilds(delN); - delete delN; - } - } - else - { - removeOpening(node, line); - // the node has subnodes which need to be moved up and this one has to be deleted - } - something_changed = true; - } - else - { - if ((node->deleteOpening) && (node->startLineValid)) - { -#ifdef JW_DEBUG - kDebug(13000)<<"calling removeOpening"; -#endif - removeOpening(node, line); - something_changed = true; - } - else - { - dontDeleteOpening(node); - - if ((node->deleteEnding) && (node->endLineValid)) - { - dontDeleteEnding(node); - removeEnding(node, line); - something_changed = true; - } - else - dontDeleteEnding(node); - } - } - } -} - -void KateCodeFoldingTree::dontDeleteEnding(KateCodeFoldingNode* node) -{ - node->deleteEnding = false; -} - - -void KateCodeFoldingTree::dontDeleteOpening(KateCodeFoldingNode* node) -{ - node->deleteOpening = false; -} - - -KateCodeFoldingNode *KateCodeFoldingTree::findNodeStartingAt(unsigned int line){ - findAllNodesOpenedOrClosedAt(line); - for (int i=0; i<(int)nodesForLine.count(); i++) - { - KateCodeFoldingNode *node=nodesForLine.at(i); - if ( (!node->startLineValid) || (getStartLine(node) != line) ) - { - nodesForLine.removeAt(i); - if (!node->startLineValid) addNodeToRemoveList(node, line); - i--; - } - } - - if (nodesForLine.isEmpty()) - return 0; - return nodesForLine.at(0); -} - - -void KateCodeFoldingTree::toggleRegionVisibility(unsigned int line) -{ - // hl whole file - m_buffer->ensureHighlighted (m_buffer->count()-1); - - lineMapping.clear(); - hiddenLinesCountCacheValid = false; - kDebug(13000)<startLineValid) || (getStartLine(node) != line) ) - { - nodesForLine.removeAt(i); - if (!node->startLineValid) addNodeToRemoveList(node, line); - i--; - } - } - - if (nodesForLine.isEmpty()) - return; - - nodesForLine.at(0)->visible = !nodesForLine.at(0)->visible; - - if (!nodesForLine.at(0)->visible) - addHiddenLineBlock(nodesForLine.at(0),line); - else - { - for (QList::iterator it=hiddenLines.begin(); it!=hiddenLines.end();++it) - if ((*it).start == line+1) - { - hiddenLines.erase(it); - break; - } - - updateHiddenSubNodes(nodesForLine.at(0)); - } - - emit regionVisibilityChangedAt(line,m_clearCache); -} - -void KateCodeFoldingTree::updateHiddenSubNodes(KateCodeFoldingNode *node) -{ - for (int i=0; i < node->childCount(); ++i) - { - KateCodeFoldingNode *iter = node->child(i); - - if (!iter->visible) - addHiddenLineBlock(iter, getStartLine(iter)); - else - updateHiddenSubNodes(iter); - } -} - -void KateCodeFoldingTree::addHiddenLineBlock(KateCodeFoldingNode *node,unsigned int line) -{ - KateHiddenLineBlock data; - data.start = line+1; - data.length = node->endLineRel-(existsOpeningAtLineAfter(line+node->endLineRel,node)?1:0); // without -1; - bool inserted = false; - - for (QList::iterator it=hiddenLines.begin(); it!=hiddenLines.end(); ++it) - { - if (((*it).start>=data.start) && ((*it).start<=data.start+data.length-1)) // another hidden block starting at the within this block already exits -> adapt new block - { - // the existing block can't have lines behind the new one, because a newly hidden - // block has to encapsulate already hidden ones - it=hiddenLines.erase(it); - --it; - } - else - { - if ((*it).start > line) - { - hiddenLines.insert(it, data); - inserted = true; - - break; - } - } - } - - if (!inserted) - hiddenLines.append(data); -} - -bool KateCodeFoldingTree::existsOpeningAtLineAfter(unsigned int line, KateCodeFoldingNode *node) -{ - for(KateCodeFoldingNode *tmp = node->parentNode; tmp; tmp=tmp->parentNode) - { - KateCodeFoldingNode *tmp2; - unsigned int startLine=getStartLine(tmp); - - if ( (tmp->findChild(node)+1) >= tmp->childCount()) return false; - if ((tmp2 = tmp->child(tmp->findChild(node) + 1)) - && ((tmp2->startLineRel + startLine) == line)) - return true; - - if ((startLine + tmp->endLineRel) > line) - return false; - } - - return false; -} - - -// -// get the real line number for a virtual line -// -unsigned int KateCodeFoldingTree::getRealLine(unsigned int virtualLine) -{ - // he, if nothing is hidden, why look at it ;) - if (hiddenLines.isEmpty()) - return virtualLine; - - // kDebug(13000) << "virtualLine" << virtualLine; - - if (lineMapping.contains(virtualLine)) - return lineMapping[virtualLine]; - - unsigned int realLine = virtualLine; - for (QList::const_iterator it=hiddenLines.constBegin();it!=hiddenLines.constEnd();++it) - { - if ((*it).start <= realLine) - realLine += (*it).length; - else - break; - } - - // kDebug(13000) << "realLine" << realLine; - - lineMapping.insert(virtualLine, realLine); - return realLine; -} - -// -// get the virtual line number for a real line -// -unsigned int KateCodeFoldingTree::getVirtualLine(unsigned int realLine) -{ - // he, if nothing is hidden, why look at it ;) - if (hiddenLines.isEmpty()) - return realLine; - - // kDebug(13000) << "realLine" << realLine; - int virtualLine = realLine; - - for (int i = hiddenLines.size()-1; i >= 0; --i) { - if ((int)hiddenLines[i].start <= virtualLine) { - virtualLine -= hiddenLines[i].length; - if (virtualLine < (int)hiddenLines[i].start) - virtualLine = hiddenLines[i].start-1; - } - // else - // break; - } - - // kDebug(13000) << "virtualLine" << virtualLine; - - return virtualLine; -} - -// -// get the number of hidden lines -// -unsigned int KateCodeFoldingTree::getHiddenLinesCount(unsigned int doclen) -{ - // he, if nothing is hidden, why look at it ;) - if (hiddenLines.isEmpty()) - return 0; - - if (hiddenLinesCountCacheValid) - return hiddenLinesCountCache; - - hiddenLinesCountCacheValid = true; - hiddenLinesCountCache = 0; - - for (QList::const_iterator it=hiddenLines.constBegin(); it!=hiddenLines.constEnd(); ++it) - { - if ((*it).start+(*it).length<=doclen) - hiddenLinesCountCache += (*it).length; - else - { - hiddenLinesCountCache += ((*it).length- ((*it).length + (*it).start - doclen)); - break; - } - } - - return hiddenLinesCountCache; -} - -void KateCodeFoldingTree::collapseToplevelNodes() -{ - // hl whole file - m_buffer->ensureHighlighted (m_buffer->count()-1); - - if (m_root.noChildren ()) - return; - - for ( int i=0; i < m_root.childCount(); ++i ) - { - KateCodeFoldingNode *node = m_root.child(i); - - if (node->visible && node->startLineValid && node->endLineValid) - { - node->visible=false; - lineMapping.clear(); - hiddenLinesCountCacheValid = false; - addHiddenLineBlock(node,node->startLineRel); - emit regionVisibilityChangedAt(node->startLineRel,m_clearCache); - } - } -} - -void KateCodeFoldingTree::expandToplevelNodes(int numLines) -{ - // hl whole file - m_buffer->ensureHighlighted (m_buffer->count()-1); - - KateLineInfo line; - for (int i = 0; i < numLines; i++) { - getLineInfo(&line, i); - - if (line.startsInVisibleBlock) - toggleRegionVisibility(i); - } -} - -int KateCodeFoldingTree::collapseOne(int realLine) -{ - // hl whole file - m_buffer->ensureHighlighted (m_buffer->count()-1); - - KateLineInfo line; - int unrelatedBlocks = 0; - for (int i = realLine; i >= 0; i--) { - getLineInfo(&line, i); - - if (line.topLevel && !line.endsBlock) - // optimization - break; - - if (line.endsBlock && !line.invalidBlockEnd && (i != realLine)) { - unrelatedBlocks++; - } - - if (line.startsVisibleBlock) { - unrelatedBlocks--; - if (unrelatedBlocks == -1) { - toggleRegionVisibility(i); - return i; - } - } - } - return -1; -} - -void KateCodeFoldingTree::expandOne(int realLine, int numLines) -{ - // hl whole file - m_buffer->ensureHighlighted (m_buffer->count()-1); - - KateLineInfo line; - int blockTrack = 0; - for (int i = realLine; i >= 0; i--) { - getLineInfo(&line, i); - - if (line.topLevel) - // done - break; - - if (line.startsInVisibleBlock && i != realLine) { - if (blockTrack == 0) - toggleRegionVisibility(i); - - blockTrack--; - } - - if (line.endsBlock) - blockTrack++; - - if (blockTrack < 0) - // too shallow - break; - } - - blockTrack = 0; - for (int i = realLine; i < numLines; i++) { - getLineInfo(&line, i); - - if (line.topLevel) - // done - break; - - if (line.startsInVisibleBlock) { - if (blockTrack == 0) - toggleRegionVisibility(i); - - blockTrack++; - } - - if (line.endsBlock) - blockTrack--; - - if (blockTrack < 0) - // too shallow - break; - } -} - -void KateCodeFoldingTree::ensureVisible( uint line ) -{ - // first have a look, if the line is really hidden - bool found=false; - for (QList::const_iterator it=hiddenLines.constBegin();it!=hiddenLines.constEnd();++it) - { - if ( ((*it).start<=line) && ((*it).start+(*it).length>line) ) - { - found=true; - break; - } - } - - - if (!found) return; - - kDebug(13000)<<"line "<
user guide - * and repeated briefly here. - */ -class KateSyntaxModeListItem -{ - public: - QString name; ///< Name of the mode (eg. Asm6502) - QString nameTranslated; ///< i18n of same, for display purposes - QString section; ///< Submenu section (eg. Assembly) - QString mimetype; ///< Mimetypes this mode applies to - QString extension; ///< Semicolon-separated list of file extensions - QString identifier; - QString version; - QString priority; /**< Priority (mapped to an integer?) for conflict- - resolution when the same file extension has - multiple highlihgting definitions. */ - QString style; ///< Default styles provided by the highlighter - QString author; ///< Author's name - QString license; ///< License; for example: "LGPL" - QString indenter; ///< Indenter to use for this highlighting - bool hidden; ///< Hides the mode from Kate's menus -}; - -/** - * List of the KateSyntaxModeListItems holding all the syntax mode list items - */ -typedef QList KateSyntaxModeList; - -/** - * Class holding the data around the current QDomElement - */ -class KateSyntaxContextData -{ - public: - QDomElement parent; - QDomElement currentGroup; - QDomElement item; -}; - -/** - * Store and manage the information about Syntax Highlighting. - */ -class KateSyntaxDocument : public QDomDocument -{ - public: - /** - * Constructor - * Sets the current file to nothing and build the ModeList (katesyntaxhighlightingrc) - * @param force fore the update of the hl cache - */ - explicit KateSyntaxDocument(KConfig *config, bool force = false); - - /** - * Desctructor - */ - ~KateSyntaxDocument(); - - /** - * If the open hl file is different from the one needed, it opens - * the new one and assign some other things. - * @param identifier file name and path of the new xml needed - * @return success - */ - bool setIdentifier(const QString& identifier); - - /** - * Get the mode list - * @return mode list - */ - const KateSyntaxModeList &modeList() { return myModeList; } - - /** - * Jump to the next group, KateSyntaxContextData::currentGroup will point to the next group - * @param data context - * @return success - */ - bool nextGroup(KateSyntaxContextData* data); - - /** - * Jump to the next item, KateSyntaxContextData::item will point to the next item - * @param data context - * @return success - */ - bool nextItem(KateSyntaxContextData* data); - - /** - * This function is used to fetch the atributes of the tags. - */ - QString groupItemData(const KateSyntaxContextData* data,const QString& name); - QString groupData(const KateSyntaxContextData* data,const QString& name); - - void freeGroupInfo(KateSyntaxContextData* data); - KateSyntaxContextData* getSubItems(KateSyntaxContextData* data); - - /** - * Get the KateSyntaxContextData of the DomElement Config inside mainGroupName - * It just fills KateSyntaxContextData::item - */ - KateSyntaxContextData* getConfig(const QString& mainGroupName, const QString &config); - - /** - * Get the KateSyntaxContextData of the QDomElement Config inside mainGroupName - * KateSyntaxContextData::parent will contain the QDomElement found - */ - KateSyntaxContextData* getGroupInfo(const QString& mainGroupName, const QString &group); - - /** - * Returns a list with all the keywords inside the list type - */ - QStringList& finddata(const QString& mainGroup,const QString& type,bool clearList=true); - - private: - /** - * Generate the list of hl modes, store them in myModeList - * @param force if true forces to rebuild the Mode List from the xml files (instead of katesyntax...rc) - */ - void setupModeList(bool force); - - /** - * Used by getConfig and getGroupInfo to traverse the xml nodes and - * evenually return the found element - */ - bool getElement (QDomElement &element, const QString &mainGroupName, const QString &config); - - /** - * List of mode items - */ - KateSyntaxModeList myModeList; - - /** - * current parsed filename - */ - QString currentFile; - - /** - * last found data out of the xml - */ - QStringList m_data; - - /** - * global config, deleted by hlmanager... - */ - KConfig *m_config; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/syntax/katesyntaxmanager.cpp b/part/syntax/katesyntaxmanager.cpp deleted file mode 100644 index d81becd..0000000 --- a/part/syntax/katesyntaxmanager.cpp +++ /dev/null @@ -1,420 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007 Matthew Woehlke - Copyright (C) 2003, 2004 Anders Lund - Copyright (C) 2003 Hamish Rodda - Copyright (C) 2001,2002 Joseph Wenninger - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN INCLUDES -#include "katesyntaxmanager.h" -#include "katesyntaxmanager.moc" - -#include "katetextline.h" -#include "katedocument.h" -#include "katesyntaxdocument.h" -#include "katerenderer.h" -#include "kateglobal.h" -#include "kateschema.h" -#include "kateconfig.h" -#include "kateextendedattribute.h" -#include "katehighlight.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -//END - -using namespace KTextEditor; - -//BEGIN KateHlManager -KateHlManager::KateHlManager() - : QObject() - , m_config ("katesyntaxhighlightingrc", KConfig::NoGlobals) - , commonSuffixes (QString(".orig;.new;~;.bak;.BAK").split(';')) - , syntax (new KateSyntaxDocument(&m_config)) - , dynamicCtxsCount(0) - , forceNoDCReset(false) -{ - KateSyntaxModeList modeList = syntax->modeList(); - for (int i=0; i < modeList.count(); i++) - { - KateHighlighting *hl = new KateHighlighting(modeList[i]); - - int insert = 0; - for (; insert <= hlList.count(); insert++) - { - if (insert == hlList.count()) - break; - - if ( QString(hlList.at(insert)->section() + hlList.at(insert)->nameTranslated()).toLower() - > QString(hl->section() + hl->nameTranslated()).toLower() ) - break; - } - - hlList.insert (insert, hl); - hlDict.insert (hl->name(), hl); - } - - // Normal HL - KateHighlighting *hl = new KateHighlighting(0); - hlList.prepend (hl); - hlDict.insert (hl->name(), hl); - - lastCtxsReset.start(); -} - -KateHlManager::~KateHlManager() -{ - delete syntax; - qDeleteAll(hlList); -} - -KateHlManager *KateHlManager::self() -{ - return KateGlobal::self ()->hlManager (); -} - -KateHighlighting *KateHlManager::getHl(int n) -{ - if (n < 0 || n >= hlList.count()) - n = 0; - - return hlList.at(n); -} - -int KateHlManager::nameFind(const QString &name) -{ - const QString lower_name = name.toLower(); - int z (hlList.count() - 1); - for (; z > 0; z--) - if (hlList.at(z)->name().toLower() == lower_name) - return z; - - return z; -} - -uint KateHlManager::defaultStyles() -{ - return 14; -} - -QString KateHlManager::defaultStyleName(int n, bool translateNames) -{ - static QStringList names; - static QStringList translatedNames; - - if (names.isEmpty()) - { - names << "Normal"; - names << "Keyword"; - names << "Data Type"; - names << "Decimal/Value"; - names << "Base-N Integer"; - names << "Floating Point"; - names << "Character"; - names << "String"; - names << "Comment"; - names << "Others"; - names << "Alert"; - names << "Function"; - // this next one is for denoting the beginning/end of a user defined folding region - names << "Region Marker"; - // this one is for marking invalid input - names << "Error"; - - translatedNames << i18nc("@item:intable Text context", "Normal"); - translatedNames << i18nc("@item:intable Text context", "Keyword"); - translatedNames << i18nc("@item:intable Text context", "Data Type"); - translatedNames << i18nc("@item:intable Text context", "Decimal/Value"); - translatedNames << i18nc("@item:intable Text context", "Base-N Integer"); - translatedNames << i18nc("@item:intable Text context", "Floating Point"); - translatedNames << i18nc("@item:intable Text context", "Character"); - translatedNames << i18nc("@item:intable Text context", "String"); - translatedNames << i18nc("@item:intable Text context", "Comment"); - translatedNames << i18nc("@item:intable Text context", "Others"); - translatedNames << i18nc("@item:intable Text context", "Alert"); - translatedNames << i18nc("@item:intable Text context", "Function"); - // this next one is for denoting the beginning/end of a user defined folding region - translatedNames << i18nc("@item:intable Text context", "Region Marker"); - // this one is for marking invalid input - translatedNames << i18nc("@item:intable Text context", "Error"); - } - - return translateNames ? translatedNames[n] : names[n]; -} - -void KateHlManager::getDefaults(const QString &schema, KateAttributeList &list) -{ - KColorScheme scheme(QPalette::Active, KColorScheme::View); - KColorScheme schemeSelected(QPalette::Active, KColorScheme::Selection); - - ///NOTE: it's important to append in the order of the HighlightInterface::DefaultStyle - /// enum, to make KateDocument::defaultStyle() work properly. - - { // dsNormal - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground().color() ); - attrib->setSelectedForeground( schemeSelected.foreground().color() ); - list.append(attrib); - } - { // dsKeyword - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground().color() ); - attrib->setSelectedForeground( schemeSelected.foreground().color() ); - attrib->setFontBold(true); - list.append(attrib); - } - { // dsDataType - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::LinkText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::LinkText).color() ); - list.append(attrib); - } - { // dsDecVal - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NeutralText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NeutralText).color() ); - list.append(attrib); - } - { // dsBaseN - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NeutralText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NeutralText).color() ); - list.append(attrib); - } - { // dsFloat - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NeutralText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NeutralText).color() ); - list.append(attrib); - } - { // dsChar - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::ActiveText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::ActiveText).color() ); - list.append(attrib); - } - { // dsString - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NegativeText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NegativeText).color() ); - list.append(attrib); - } - { // dsComment - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::InactiveText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::InactiveText).color() ); - attrib->setFontItalic(true); - list.append(attrib); - } - { // dsOthers - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::PositiveText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::PositiveText).color() ); - list.append(attrib); - } - { // dsAlert - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NegativeText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NegativeText).color() ); - attrib->setFontBold(true); - attrib->setBackground( scheme.background(KColorScheme::NegativeBackground).color() ); - list.append(attrib); - } - { // dsFunction - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::VisitedText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::VisitedText).color() ); - list.append(attrib); - } - { // dsRegionMarker - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::LinkText).color() ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::LinkText).color() ); - attrib->setBackground( scheme.background(KColorScheme::LinkBackground).color() ); - list.append(attrib); - } - { // dsError - Attribute::Ptr attrib(new KTextEditor::Attribute()); - attrib->setForeground( scheme.foreground(KColorScheme::NegativeText) ); - attrib->setSelectedForeground( schemeSelected.foreground(KColorScheme::NegativeText).color() ); - attrib->setFontUnderline(true); - list.append(attrib); - } - - KConfigGroup config(KateHlManager::self()->self()->getKConfig(), - "Default Item Styles - Schema " + schema); - - for (uint z = 0; z < defaultStyles(); z++) - { - KTextEditor::Attribute::Ptr i = list.at(z); - QStringList s = config.readEntry(defaultStyleName(z), QStringList()); - if (!s.isEmpty()) - { - while( s.count()<9) - s << ""; - - QString tmp; - QRgb col; - - tmp=s[0]; if (!tmp.isEmpty()) { - col=tmp.toUInt(0,16); i->setForeground(QColor(col)); } - - tmp=s[1]; if (!tmp.isEmpty()) { - col=tmp.toUInt(0,16); i->setSelectedForeground(QColor(col)); } - - tmp=s[2]; if (!tmp.isEmpty()) i->setFontBold(tmp!="0"); - - tmp=s[3]; if (!tmp.isEmpty()) i->setFontItalic(tmp!="0"); - - tmp=s[4]; if (!tmp.isEmpty()) i->setFontStrikeOut(tmp!="0"); - - tmp=s[5]; if (!tmp.isEmpty()) i->setFontUnderline(tmp!="0"); - - tmp=s[6]; if (!tmp.isEmpty()) { - if ( tmp != "-" ) - { - col=tmp.toUInt(0,16); - i->setBackground(QColor(col)); - } - else - i->clearBackground(); - } - tmp=s[7]; if (!tmp.isEmpty()) { - if ( tmp != "-" ) - { - col=tmp.toUInt(0,16); - i->setSelectedBackground(QColor(col)); - } - else - i->clearProperty(KTextEditor::Attribute::SelectedBackground); - } - tmp=s[8]; if (!tmp.isEmpty() && tmp!=QLatin1String("---")) i->setFontFamily(tmp); - } - } -} - -void KateHlManager::setDefaults(const QString &schema, KateAttributeList &list) -{ - KConfigGroup config(KateHlManager::self()->self()->getKConfig(), - "Default Item Styles - Schema " + schema); - - for (uint z = 0; z < defaultStyles(); z++) - { - QStringList settings; - KTextEditor::Attribute::Ptr p = list.at(z); - - settings<<(p->hasProperty(QTextFormat::ForegroundBrush)?QString::number(p->foreground().color().rgb(),16):""); - settings<<(p->hasProperty(KTextEditor::Attribute::SelectedForeground)?QString::number(p->selectedForeground().color().rgb(),16):""); - settings<<(p->hasProperty(QTextFormat::FontWeight)?(p->fontBold()?"1":"0"):""); - settings<<(p->hasProperty(QTextFormat::FontItalic)?(p->fontItalic()?"1":"0"):""); - settings<<(p->hasProperty(QTextFormat::FontStrikeOut)?(p->fontStrikeOut()?"1":"0"):""); - settings<<(p->hasProperty(QTextFormat::FontUnderline)?(p->fontUnderline()?"1":"0"):""); - settings<<(p->hasProperty(QTextFormat::BackgroundBrush)?QString::number(p->background().color().rgb(),16):""); - settings<<(p->hasProperty(KTextEditor::Attribute::SelectedBackground)?QString::number(p->selectedBackground().color().rgb(),16):""); - settings<<(p->hasProperty(QTextFormat::FontFamily)?(p->fontFamily()):QString()); - settings<<"---"; - - config.writeEntry(defaultStyleName(z),settings); - } - - emit changed(); -} - -int KateHlManager::highlights() -{ - return (int) hlList.count(); -} - -QString KateHlManager::hlName(int n) -{ - return hlList.at(n)->name(); -} - -QString KateHlManager::hlNameTranslated(int n) -{ - return hlList.at(n)->nameTranslated(); -} - -QString KateHlManager::hlSection(int n) -{ - return hlList.at(n)->section(); -} - -bool KateHlManager::hlHidden(int n) -{ - return hlList.at(n)->hidden(); -} - -QString KateHlManager::identifierForName(const QString& name) -{ - KateHighlighting *hl = 0; - - if ((hl = hlDict[name])) - return hl->getIdentifier (); - - return QString(); -} - -QString KateHlManager::nameForIdentifier(const QString& identifier) -{ - for ( QHash::iterator it = hlDict.begin(); - it != hlDict.end(); ++it ) - { - if ( (*it)->getIdentifier() == identifier ) { - return it.key(); - } - } - - return QString(); -} - -bool KateHlManager::resetDynamicCtxs() -{ - if (forceNoDCReset) - return false; - - if (lastCtxsReset.elapsed() < KATE_DYNAMIC_CONTEXTS_RESET_DELAY) - return false; - - foreach (KateHighlighting *hl, hlList) - hl->dropDynamicContexts(); - - dynamicCtxsCount = 0; - lastCtxsReset.start(); - - return true; -} -//END - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/syntax/katesyntaxmanager.h b/part/syntax/katesyntaxmanager.h deleted file mode 100644 index e37f852..0000000 --- a/part/syntax/katesyntaxmanager.h +++ /dev/null @@ -1,115 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001,2002 Joseph Wenninger - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_SYNTAXMANAGER_H__ -#define __KATE_SYNTAXMANAGER_H__ - -#include "katetextline.h" -#include "kateextendedattribute.h" - -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -class KateSyntaxDocument; -class KateHighlighting; - - -class KateHlManager : public QObject -{ - Q_OBJECT - - public: - KateHlManager(); - ~KateHlManager(); - - static KateHlManager *self(); - - KateSyntaxDocument *syntaxDocument () { return syntax; } - - inline KConfig *getKConfig() { return &m_config; } - - KateHighlighting *getHl(int n); - int nameFind(const QString &name); - - QString identifierForName(const QString&); - /** - * Returns the mode name for a given identifier, as e.g. - * returned by KateHighlighting::hlKeyForAttrib(). - */ - QString nameForIdentifier(const QString&); - - // methodes to get the default style count + names - static uint defaultStyles(); - static QString defaultStyleName(int n, bool translateNames = false); - - void getDefaults(const QString &schema, KateAttributeList &); - void setDefaults(const QString &schema, KateAttributeList &); - - int highlights(); - QString hlName(int n); - QString hlNameTranslated (int n); - QString hlSection(int n); - bool hlHidden(int n); - - void incDynamicCtxs() { ++dynamicCtxsCount; } - int countDynamicCtxs() { return dynamicCtxsCount; } - void setForceNoDCReset(bool b) { forceNoDCReset = b; } - - // be carefull: all documents hl should be invalidated after having successfully called this method! - bool resetDynamicCtxs(); - - Q_SIGNALS: - void changed(); - - private: - friend class KateHighlighting; - - // This list owns objects it holds, thus they should be deleted when the object is removed - QList hlList; - // This hash does not own the objects it holds, thus they should not be deleted - QHash hlDict; - - KConfig m_config; - QStringList commonSuffixes; - - KateSyntaxDocument *syntax; - - int dynamicCtxsCount; - QTime lastCtxsReset; - bool forceNoDCReset; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/CMakeLists.txt b/part/tests/CMakeLists.txt deleted file mode 100644 index f0c8918..0000000 --- a/part/tests/CMakeLists.txt +++ /dev/null @@ -1,186 +0,0 @@ -set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} ) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/.. - ${CMAKE_CURRENT_SOURCE_DIR}/../buffer - ${CMAKE_CURRENT_SOURCE_DIR}/../completion - ${CMAKE_CURRENT_SOURCE_DIR}/../dialogs - ${CMAKE_CURRENT_SOURCE_DIR}/../document - ${CMAKE_CURRENT_SOURCE_DIR}/../script - ${CMAKE_CURRENT_SOURCE_DIR}/../mode - ${CMAKE_CURRENT_SOURCE_DIR}/../render - ${CMAKE_CURRENT_SOURCE_DIR}/../search - ${CMAKE_CURRENT_SOURCE_DIR}/../smart - ${CMAKE_CURRENT_SOURCE_DIR}/../syntax - ${CMAKE_CURRENT_SOURCE_DIR}/../undo - ${CMAKE_CURRENT_SOURCE_DIR}/../utils - ${CMAKE_CURRENT_SOURCE_DIR}/../vimode - ${CMAKE_CURRENT_SOURCE_DIR}/../view - ${CMAKE_CURRENT_BINARY_DIR}/.. - ${KDE4_KIO_INCLUDES} -) - -set (KATE_TEST_LINK_LIBS ${KDE4_KDECORE_LIBS} ${QT_QTSCRIPT_LIBRARY} ${QT_QTTEST_LIBRARY} ${KDE4_KCMUTILS_LIBS} ${KDE_4_4_LIBS_NEEDED} ktexteditor katepartinterfaces) - -# buffer test -kde4_add_unit_test(katetextbuffertest katetextbuffertest.cpp katetextbuffertest.h) -target_link_libraries (katetextbuffertest ${KATE_TEST_LINK_LIBS}) - -########### range test ############### - -kde4_add_unit_test(range_test TESTNAME kate-range_test range_test.cpp) - -target_link_libraries( range_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### next target ############### - -if(NOT MINGW) - -########### undomanager test ############### - -kde4_add_unit_test(undomanager_test TESTNAME kate-undomanager_test undomanager_test.cpp) - -target_link_libraries( undomanager_test ${KATE_TEST_LINK_LIBS} -) - -########### plaintextsearch test ############### - -kde4_add_unit_test(plaintextsearch_test TESTNAME kate-plaintextsearch_test plaintextsearch_test.cpp) - -target_link_libraries( plaintextsearch_test ${KATE_TEST_LINK_LIBS} -) - -########### regexpsearch test ############### - -kde4_add_unit_test(regexpsearch_test TESTNAME kate-regexpsearch_test regexpsearch_test.cpp) - -target_link_libraries( regexpsearch_test ${KATE_TEST_LINK_LIBS} -) - -########### scriptdocument test ############### - -kde4_add_unit_test(scriptdocument_test TESTNAME kate-scriptdocument_test scriptdocument_test.cpp) - -target_link_libraries( scriptdocument_test ${KATE_TEST_LINK_LIBS} -) - -########### completion test ############### - -set(completion_test_SRCS - completion_test.cpp - codecompletiontestmodel.cpp -) - -kde4_add_unit_test(completion_test TESTNAME kate-completion_test ${completion_test_SRCS}) - -target_link_libraries( completion_test ${KATE_TEST_LINK_LIBS} -) - -########### searchbar test ############### - -kde4_add_unit_test(searchbar_test TESTNAME kate-searchbar_test searchbar_test.cpp) - -target_link_libraries( searchbar_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### cursor test ############### - -kde4_add_unit_test(movingcursor_test TESTNAME kate-movingcursor_test movingcursor_test.cpp) - -target_link_libraries( movingcursor_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### moving range and feedback test ############### - -kde4_add_unit_test(movingrange_test TESTNAME kate-movingrange_test movingrange_test.cpp) - -target_link_libraries( movingrange_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### document test ############### - -kde4_add_unit_test(katedocument_test TESTNAME kate-katedocument_test katedocument_test.cpp) - -target_link_libraries( katedocument_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### view test ############### - -kde4_add_unit_test(kateview_test TESTNAME kate-kateview_test kateview_test.cpp) - -target_link_libraries( kateview_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### revision test ############### - -kde4_add_unit_test(revision_test TESTNAME kate-revision_test revision_test.cpp) - -target_link_libraries( revision_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### templatehandler test ############### - -kde4_add_unit_test(templatehandler_test TESTNAME kate-templatehandler_test templatehandler_test.cpp) - -target_link_libraries( templatehandler_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -########### indenting test ################ - -set(indenttest_SRCS - indenttest.cpp - testutils.cpp -) - -kde4_add_unit_test(indenttest TESTNAME kate-indenttest ${indenttest_SRCS}) - -target_link_libraries(indenttest ${KATE_TEST_LINK_LIBS}) - -########### bug 213964 test ############### - -kde4_add_unit_test(bug213964_test TESTNAME kate-bug213964_test bug213964.cpp) - -target_link_libraries( bug213964_test - ${KDE4_KDEUI_LIBS} - ${QT_QTTEST_LIBRARY} - ${KATE_TEST_LINK_LIBS} - katepartinterfaces -) - -endif(NOT MINGW) - -# encoding tets -add_subdirectory (encoding) diff --git a/part/tests/bug213964.cpp b/part/tests/bug213964.cpp deleted file mode 100644 index f2eaf57..0000000 --- a/part/tests/bug213964.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "bug213964.h" -#include "moc_bug213964.cpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -QTEST_KDEMAIN(BugTest, GUI) - -using namespace KTextEditor; - -static const char* text( -"# Instructions\n" -"# 1) Load this file. Do NOT edit anything.\n" -"# 2) Collapse the top level folding (Ctrl+Shift+-)\n" -"# 3) Type \"('\" on line 7 (without the double quotes, with the single quote) -> CRASH\n" -"# 4) Next time around, type the \"('\" on line 30 -> no crash\n" -"# 5) Delete the two chars again, and try step 3, now -> no crash\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"xxx (x xx 2:xxxx(xx3)) {\n" -" xx3[,x] <- xx2[,x] + (xxx(xx2[,x-1])-xxx(xx2[,x-1]))/2 + xx3[1,x-1] - xx2[1,x-1]\n" -"}\n"); - -BugTest::BugTest() - : QObject() -{ -} - -BugTest::~BugTest() -{ -} - -void BugTest::reproduceCrash() -{ - KateGlobal::self()->incRef(); - KateDocument doc(false, false, false); - doc.setText(text); - doc.setHighlightingMode("R Script"); - doc.buffer().ensureHighlighted (75); - doc.foldingTree()->collapseToplevelNodes(); - doc.buffer().ensureHighlighted (75); - - doc.insertText(Cursor(6, 0), "("); - qDebug() << "!!! The next line usually crashes in the code folding code"; - QTest::qWait(500); - doc.insertText(Cursor(6, 1), "'"); - qDebug() << "!!! Huh, no crash. qWait above not long enough?"; -} diff --git a/part/tests/bug213964.h b/part/tests/bug213964.h deleted file mode 100644 index 07e564d..0000000 --- a/part/tests/bug213964.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_BUG_213964_TEST_H -#define KATE_BUG_213964_TEST_H - -#include - -class BugTest : public QObject -{ - Q_OBJECT - -public: - BugTest(); - ~BugTest(); - -private Q_SLOTS: - void reproduceCrash(); - -}; - -#endif diff --git a/part/tests/codecompletiontestmodel.cpp b/part/tests/codecompletiontestmodel.cpp deleted file mode 100644 index 059074e..0000000 --- a/part/tests/codecompletiontestmodel.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2005 Hamish Rodda - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "codecompletiontestmodel.h" - -#include -#include -#include -#include -#include -#include - -CodeCompletionTestModel::CodeCompletionTestModel(KTextEditor::View* parent, const QString &startText) - : KTextEditor::CodeCompletionModel(parent), m_startText(startText), m_autoStartText(m_startText.isEmpty()) -{ - setRowCount(40); - - Q_ASSERT(cc()); - - cc()->setAutomaticInvocationEnabled(true); - cc()->unregisterCompletionModel(KateGlobal::self()->wordCompletionModel()); //would add additional items, we don't want that in tests - cc()->registerCompletionModel(this); -} - -// Fake a series of completions -QVariant CodeCompletionTestModel::data( const QModelIndex & index, int role ) const -{ - switch (role) { - case Qt::DisplayRole: - if (index.row() < rowCount() / 2) - switch (index.column()) { - case Prefix: - switch (index.row() % 3) { - default: - return "void "; - case 1: - return "const QString& "; - case 2: - if (index.row() % 6) - return "inline virtual bool "; - return "virtual bool "; - } - - case Scope: - switch (index.row() % 4) { - default: - return QString(); - case 1: - return "KTextEditor::"; - case 2: - return "::"; - case 3: - return "std::"; - } - - case Name: - return QString(m_startText + QString("%1%2%3").arg(QChar('a' + (index.row() % 3))).arg(QChar('a' + index.row())).arg(index.row())); - - case Arguments: - switch (index.row() % 5) { - default: - return "()"; - case 1: - return "(bool trigger)"; - case 4: - return "(const QString& name, Qt::CaseSensitivity cs)"; - case 5: - return "(int count)"; - } - - case Postfix: - switch (index.row() % 3) { - default: - return " const"; - case 1: - return " KDE_DEPRECATED"; - case 2: - return ""; - } - } - else - switch (index.column()) { - case Prefix: - switch (index.row() % 3) { - default: - return "void "; - case 1: - return "const QString "; - case 2: - return "bool "; - } - - case Scope: - switch (index.row() % 4) { - default: - return QString(); - case 1: - return "KTextEditor::"; - case 2: - return "::"; - case 3: - return "std::"; - } - - case Name: - return QString(m_startText + QString("%1%2%3").arg(QChar('a' + (index.row() % 3))).arg(QChar('a' + index.row())).arg(index.row())); - - default: - return ""; - } - break; - - case Qt::DecorationRole: - break; - - case CompletionRole: { - CompletionProperties p; - if (index.row() < rowCount() / 2) - p |= Function; - else - p |= Variable; - switch (index.row() % 3) { - case 0: - p |= Const | Public; - break; - case 1: - p |= Protected; - break; - case 2: - p |= Private; - break; - } - return (int)p; - } - - case ScopeIndex: - return (index.row() % 4 ) - 1; - } - - return QVariant(); -} - -KTextEditor::View* CodeCompletionTestModel::view( ) const -{ - return static_cast(const_cast(QObject::parent())); -} - -KTextEditor::CodeCompletionInterface * CodeCompletionTestModel::cc( ) const -{ - return dynamic_cast(const_cast(QObject::parent())); -} - -void CodeCompletionTestModel::completionInvoked(KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType) -{ - Q_UNUSED(invocationType) - - if (m_autoStartText) { - m_startText = view->document()->text(KTextEditor::Range(range.start(), view->cursorPosition())); - } - kDebug() << m_startText; -} - - -#include "codecompletiontestmodel.moc" diff --git a/part/tests/codecompletiontestmodel.h b/part/tests/codecompletiontestmodel.h deleted file mode 100644 index c33a200..0000000 --- a/part/tests/codecompletiontestmodel.h +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2005 Hamish Rodda - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef CODECOMPLETIONTEST_H -#define CODECOMPLETIONTEST_H - -#include - -namespace KTextEditor { - class View; - class CodeCompletionInterface; -} - -class CodeCompletionTestModel : public KTextEditor::CodeCompletionModel -{ - Q_OBJECT - - public: - CodeCompletionTestModel(KTextEditor::View* parent = 0L, const QString &startText = QString()); - - KTextEditor::View* view() const; - KTextEditor::CodeCompletionInterface* cc() const; - - virtual void completionInvoked(KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType); - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - - private: - QString m_startText; - bool m_autoStartText; -}; - -#endif diff --git a/part/tests/codecompletiontestmodels.h b/part/tests/codecompletiontestmodels.h deleted file mode 100644 index 138a66d..0000000 --- a/part/tests/codecompletiontestmodels.h +++ /dev/null @@ -1,166 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2008 Niko Sams - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_COMPLETIONTESTMODELS_H -#define KATE_COMPLETIONTESTMODELS_H - -#include "codecompletiontestmodel.h" -#include - -#include -#include - -using namespace KTextEditor; - - -class CustomRangeModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - CustomRangeModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - Range completionRange(View* view, const Cursor &position) - { - Range range = CodeCompletionModelControllerInterface3::completionRange(view, position); - if (range.start().column() > 0) { - KTextEditor::Range preRange(Cursor(range.start().line(), range.start().column()-1), - Cursor(range.start().line(), range.start().column())); - kDebug() << preRange << view->document()->text(preRange); - if (view->document()->text(preRange) == "$") { - range.expandToRange(preRange); - kDebug() << "using custom completion range" << range; - } - } - return range; - } - - bool shouldAbortCompletion(View* view, const Range& range, const QString ¤tCompletion) - { - Q_UNUSED(view); - Q_UNUSED(range); - static const QRegExp allowedText("^\\$?(\\w*)"); - return !allowedText.exactMatch(currentCompletion); - } -}; - -class CustomAbortModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - CustomAbortModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - - bool shouldAbortCompletion(View* view, const Range& range, const QString ¤tCompletion) - { - Q_UNUSED(view); - Q_UNUSED(range); - static const QRegExp allowedText("^([\\w-]*)"); - return !allowedText.exactMatch(currentCompletion); - } -}; - -class EmptyFilterStringModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - EmptyFilterStringModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - - QString filterString(View*, const Range&, const Cursor &) - { - return QString(); - } -}; - -class UpdateCompletionRangeModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - UpdateCompletionRangeModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - - Range updateCompletionRange(View* view, const Range& range) - { - Q_UNUSED(view); - if (view->document()->text(range) == QString("ab")) { - return Range(Cursor(range.start().line(), 0), range.end()); - } - return range; - } - bool shouldAbortCompletion(View* view, const Range &range, const QString ¤tCompletion) - { - Q_UNUSED(view); - Q_UNUSED(range); - Q_UNUSED(currentCompletion); - return false; - } -}; - -class StartCompletionModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - StartCompletionModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - - bool shouldStartCompletion(View* view, const QString &insertedText, bool userInsertion, const Cursor &position) - { - Q_UNUSED(view); - Q_UNUSED(userInsertion); - Q_UNUSED(position); - if(insertedText.isEmpty()) - return false; - - QChar lastChar = insertedText.at(insertedText.count() - 1); - if (lastChar == '%') { - return true; - } - return false; - } -}; - -class ImmideatelyAbortCompletionModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface3 -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface3) -public: - ImmideatelyAbortCompletionModel(KTextEditor::View* parent = 0L, const QString &startText = QString()) - : CodeCompletionTestModel(parent, startText) - {} - - virtual bool shouldAbortCompletion(KTextEditor::View* view, const KTextEditor::Range& range, const QString& currentCompletion) - { - Q_UNUSED(view); - Q_UNUSED(range); - Q_UNUSED(currentCompletion); - return true; - } -}; - -#endif diff --git a/part/tests/completion_test.cpp b/part/tests/completion_test.cpp deleted file mode 100644 index fad276b..0000000 --- a/part/tests/completion_test.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2008 Niko Sams - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "completion_test.h" - -#include "codecompletiontestmodels.h" -#include "codecompletiontestmodels.moc" - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -QTEST_KDEMAIN(CompletionTest, GUI) - - -using namespace KTextEditor; - -int countItems(KateCompletionModel *model) -{ - int ret = 0; - for (int i=0; i < model->rowCount(QModelIndex()); ++i) { - ret += model->rowCount(model->index(i, 0)); - } - return ret; -} - - -void CompletionTest::init() -{ - if ( !KSycoca::isAvailable() ) - QSKIP( "ksycoca not available", SkipAll ); - - Editor* editor = EditorChooser::editor(); - QVERIFY(editor); - - m_doc = editor->createDocument(this); - QVERIFY(m_doc); - m_doc->setText("aa bb cc\ndd"); - - KTextEditor::View *v = m_doc->createView(0); - QApplication::setActiveWindow(v); - m_view = static_cast(v); - Q_ASSERT(m_view); - - //view needs to be shown as completion won't work if the cursor is off screen - m_view->show(); -} - -void CompletionTest::cleanup() -{ - delete m_view; - delete m_doc; -} - -void CompletionTest::testFilterEmptyRange() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - new CodeCompletionTestModel(m_view, "a"); - m_view->setCursorPosition(Cursor(0, 0)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 40); - - m_view->insertText("aa"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 14); -} - -void CompletionTest::testFilterWithRange() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel = new CodeCompletionTestModel(m_view, "a"); - m_view->setCursorPosition(Cursor(0, 2)); - emit m_view->userInvokedCompletion(); - Range complRange = *m_view->completionWidget()->completionRange(testModel); - QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 2))); - QCOMPARE(countItems(model), 14); - - m_view->insertText("a"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 1); -} - - -void CompletionTest::testAbortCursorMovedOutOfRange() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - new CodeCompletionTestModel(m_view, "a"); - m_view->setCursorPosition(Cursor(0, 2)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 14); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - - m_view->setCursorPosition(Cursor(0, 4)); - QApplication::processEvents(); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); -} - -void CompletionTest::testAbortInvalidText() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - new CodeCompletionTestModel(m_view, "a"); - m_view->setCursorPosition(Cursor(0, 2)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 14); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - - m_view->insertText("."); - QApplication::processEvents(); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); -} - -void CompletionTest::testCustomRange1() -{ - m_doc->setText("$aa bb cc\ndd"); - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); - m_view->setCursorPosition(Cursor(0, 3)); - emit m_view->userInvokedCompletion(); - Range complRange = *m_view->completionWidget()->completionRange(testModel); - kDebug() << complRange; - QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 3))); - QCOMPARE(countItems(model), 14); - - m_view->insertText("a"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 1); -} - -void CompletionTest::testCustomRange2() -{ - m_doc->setText("$ bb cc\ndd"); - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); - m_view->setCursorPosition(Cursor(0, 1)); - emit m_view->userInvokedCompletion(); - Range complRange = *m_view->completionWidget()->completionRange(testModel); - QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 1))); - QCOMPARE(countItems(model), 40); - - m_view->insertText("aa"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 14); -} - -void CompletionTest::testCustomRangeMultipleModels() -{ - m_doc->setText("$a bb cc\ndd"); - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel1 = new CustomRangeModel(m_view, "$a"); - CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "a"); - m_view->setCursorPosition(Cursor(0, 1)); - emit m_view->userInvokedCompletion(); - QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel1)), Range(Cursor(0, 0), Cursor(0, 2))); - QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel2)), Range(Cursor(0, 1), Cursor(0, 2))); - QCOMPARE(model->currentCompletion(testModel1), QString("$")); - QCOMPARE(model->currentCompletion(testModel2), QString("")); - QCOMPARE(countItems(model), 80); - - - m_view->insertText("aa"); - QApplication::processEvents(); - QCOMPARE(model->currentCompletion(testModel1), QString("$aa")); - QCOMPARE(model->currentCompletion(testModel2), QString("aa")); - QCOMPARE(countItems(model), 14*2); -} - -void CompletionTest::testAbortController() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - new CustomRangeModel(m_view, "$a"); - m_view->setCursorPosition(Cursor(0, 0)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 40); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - - m_view->insertText("$a"); - QApplication::processEvents(); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - - m_view->insertText("."); - QApplication::processEvents(); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); -} - -void CompletionTest::testAbortControllerMultipleModels() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); - CodeCompletionTestModel* testModel2 = new CustomAbortModel(m_view, "a-"); - m_view->setCursorPosition(Cursor(0, 0)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 80); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - - m_view->insertText("a"); - QApplication::processEvents(); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - QCOMPARE(countItems(model), 80); - - m_view->insertText("-"); - QApplication::processEvents(); - QVERIFY(m_view->completionWidget()->isCompletionActive()); - QVERIFY(!m_view->completionWidget()->completionRanges().contains(testModel1)); - QVERIFY(m_view->completionWidget()->completionRanges().contains(testModel2)); - - QCOMPARE(countItems(model), 40); - - m_view->insertText(" "); - QApplication::processEvents(); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); -} - -void CompletionTest::testEmptyFilterString() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - new EmptyFilterStringModel(m_view, "aa"); - m_view->setCursorPosition(Cursor(0, 0)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 40); - - m_view->insertText("a"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 40); - - m_view->insertText("bam"); - QApplication::processEvents(); - QCOMPARE(countItems(model), 40); -} - -void CompletionTest::testUpdateCompletionRange() -{ - m_doc->setText("ab bb cc\ndd"); - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel = new UpdateCompletionRangeModel(m_view, "ab ab"); - m_view->setCursorPosition(Cursor(0, 3)); - emit m_view->userInvokedCompletion(); - QCOMPARE(countItems(model), 40); - QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 3), Cursor(0, 3))); - - m_view->insertText("ab"); - QApplication::processEvents(); - QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 0), Cursor(0, 5))); - QCOMPARE(countItems(model), 40); -} - -void CompletionTest::testCustomStartCompl() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - m_view->completionWidget()->setAutomaticInvocationDelay(1); - - new StartCompletionModel(m_view, "aa"); - - m_view->setCursorPosition(Cursor(0, 0)); - m_view->insertText("%"); - QTest::qWait(100); - - QVERIFY(m_view->completionWidget()->isCompletionActive()); - QCOMPARE(countItems(model), 40); -} - -void CompletionTest::testKateCompletionModel() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); - CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "bb"); - - model->setCompletionModel(testModel1); - QCOMPARE(countItems(model), 40); - - model->addCompletionModel(testModel2); - QCOMPARE(countItems(model), 80); - - model->removeCompletionModel(testModel2); - QCOMPARE(countItems(model), 40); -} - -void CompletionTest::testAbortImmideatelyAfterStart() -{ - KateCompletionModel *model = m_view->completionWidget()->model(); - - CodeCompletionTestModel* testModel = new ImmideatelyAbortCompletionModel(m_view); - m_view->setCursorPosition(Cursor(0, 3)); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); - emit m_view->userInvokedCompletion(); - QVERIFY(!m_view->completionWidget()->isCompletionActive()); -} - -#include "completion_test.moc" diff --git a/part/tests/completion_test.h b/part/tests/completion_test.h deleted file mode 100644 index 33f37ae..0000000 --- a/part/tests/completion_test.h +++ /dev/null @@ -1,61 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2008 Niko Sams - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_COMPLETIONTEST_H -#define KATE_COMPLETIONTEST_H - -#include - -namespace KTextEditor { - class Document; -} -class KateView; - -class CompletionTest : public QObject -{ - Q_OBJECT - - public: - CompletionTest() {} - virtual ~CompletionTest() {} - - private Q_SLOTS: - void init(); - void cleanup(); - void testFilterEmptyRange(); - void testFilterWithRange(); - void testCustomRange1(); - void testCustomRange2(); - void testCustomRangeMultipleModels(); - void testAbortCursorMovedOutOfRange(); - void testAbortInvalidText(); - void testAbortController(); - void testAbortControllerMultipleModels(); - void testEmptyFilterString(); - void testUpdateCompletionRange(); - void testCustomStartCompl(); - void testKateCompletionModel(); - void testAbortImmideatelyAfterStart(); - - private: - KTextEditor::Document* m_doc; - KateView *m_view; -}; - -#endif diff --git a/part/tests/encoding/CMakeLists.txt b/part/tests/encoding/CMakeLists.txt deleted file mode 100644 index 2053f8b..0000000 --- a/part/tests/encoding/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -# test executable for encoding -set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} ) -kde4_add_executable(kateencodingtest NOGUI kateencodingtest.cpp) -target_link_libraries(kateencodingtest ${KATE_TEST_LINK_LIBS}) - -# test macro for encoding tests -MACRO(KATE_ENCODING_TEST _encoding _testname) - ADD_TEST (${_testname}_create kateencodingtest ${_encoding} ${CMAKE_CURRENT_SOURCE_DIR}/${_testname} ${CMAKE_CURRENT_BINARY_DIR}/${_testname} ) - ADD_TEST (${_testname}_diff ${CMAKE_COMMAND} -E compare_files ${CMAKE_CURRENT_SOURCE_DIR}/${_testname} ${CMAKE_CURRENT_BINARY_DIR}/${_testname} ) -ENDMACRO(KATE_ENCODING_TEST) - -# add tests - -# this file is utf-8, simple -KATE_ENCODING_TEST ("utf-8" "utf8.txt") - -# this file is latin15, but fallback should work! -KATE_ENCODING_TEST ("utf-8" "latin15.txt") - -# this file is utf32, little endian, but fallback should work! -KATE_ENCODING_TEST ("utf-8" "utf32.txt") - -# this file is utf16, little endian, but fallback should work! -KATE_ENCODING_TEST ("utf-8" "utf16.txt") - -# this file is utf32, big endian, but fallback should work! -KATE_ENCODING_TEST ("utf-8" "utf32be.txt") - -# this file is utf16, big endian, but fallback should work! -KATE_ENCODING_TEST ("utf-8" "utf16be.txt") - -# cyrillic utf-8 -KATE_ENCODING_TEST ("utf-8" "cyrillic_utf8.txt") - -# cyrillic cp1251 -KATE_ENCODING_TEST ("utf-8" "cp1251.txt") - -# cyrillic koi8-r -KATE_ENCODING_TEST ("utf-8" "koi8-r.txt") - diff --git a/part/tests/encoding/cp1251.txt b/part/tests/encoding/cp1251.txt deleted file mode 100644 index eaac632..0000000 --- a/part/tests/encoding/cp1251.txt +++ /dev/null @@ -1,2 +0,0 @@ -Testing -Òåñòîâûé òåêñò ðàç äâà òðè \ No newline at end of file diff --git a/part/tests/encoding/cyrillic_utf8.txt b/part/tests/encoding/cyrillic_utf8.txt deleted file mode 100644 index 51888b2..0000000 --- a/part/tests/encoding/cyrillic_utf8.txt +++ /dev/null @@ -1,2 +0,0 @@ -Testing -ТеÑтовый текÑÑ‚ раз два три \ No newline at end of file diff --git a/part/tests/encoding/kateencodingtest.cpp b/part/tests/encoding/kateencodingtest.cpp deleted file mode 100644 index 12e0661..0000000 --- a/part/tests/encoding/kateencodingtest.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * Copyright (C) 2010 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextbuffer.h" - -#include -#include - -int main (int argc, char *argv[]) -{ - // construct core app - QCoreApplication app (argc, argv); - - // get arguments - QString encoding = app.arguments().at(1); - QString inFile = app.arguments().at(2); - QString outFile = app.arguments().at(3); - - Kate::TextBuffer buffer (0); - - // set codec - buffer.setFallbackTextCodec (QTextCodec::codecForName ("ISO 8859-15")); - buffer.setTextCodec (QTextCodec::codecForName (encoding.toLatin1())); - - // switch to Mac EOL, this will test eol detection, as files are normal unix or dos - buffer.setEndOfLineMode (Kate::TextBuffer::eolMac); - - // load file - bool encodingErrors = false; - if (!buffer.load (inFile, encodingErrors) || encodingErrors) - return 1; - - // save file - if (!buffer.save (outFile)) - return 1; - - return 0; -} diff --git a/part/tests/encoding/koi8-r.txt b/part/tests/encoding/koi8-r.txt deleted file mode 100644 index eb61ad7..0000000 --- a/part/tests/encoding/koi8-r.txt +++ /dev/null @@ -1,2 +0,0 @@ -Testing -ôÅÓÔÏ×ÙÊ ÔÅËÓÔ ÒÁÚ Ä×Á ÔÒÉ \ No newline at end of file diff --git a/part/tests/encoding/latin15.txt b/part/tests/encoding/latin15.txt deleted file mode 100644 index 974d9ab..0000000 --- a/part/tests/encoding/latin15.txt +++ /dev/null @@ -1,7 +0,0 @@ -Test -Straße -Christoph -Äußerung -Überall -Köhler -$perlvar \ No newline at end of file diff --git a/part/tests/encoding/utf16.txt b/part/tests/encoding/utf16.txt deleted file mode 100644 index 9c4a0ec..0000000 Binary files a/part/tests/encoding/utf16.txt and /dev/null differ diff --git a/part/tests/encoding/utf16be.txt b/part/tests/encoding/utf16be.txt deleted file mode 100644 index ec14d6a..0000000 Binary files a/part/tests/encoding/utf16be.txt and /dev/null differ diff --git a/part/tests/encoding/utf32.txt b/part/tests/encoding/utf32.txt deleted file mode 100644 index b234c06..0000000 Binary files a/part/tests/encoding/utf32.txt and /dev/null differ diff --git a/part/tests/encoding/utf32be.txt b/part/tests/encoding/utf32be.txt deleted file mode 100644 index 31e6e01..0000000 Binary files a/part/tests/encoding/utf32be.txt and /dev/null differ diff --git a/part/tests/encoding/utf8.txt b/part/tests/encoding/utf8.txt deleted file mode 100644 index 73c6f28..0000000 --- a/part/tests/encoding/utf8.txt +++ /dev/null @@ -1,7 +0,0 @@ -Test -Straße -Christoph -Äußerung -Ãœberall -Köhler -$perlvar \ No newline at end of file diff --git a/part/tests/hl/ejp1.asm b/part/tests/hl/ejp1.asm deleted file mode 100644 index e161d4e..0000000 --- a/part/tests/hl/ejp1.asm +++ /dev/null @@ -1,285 +0,0 @@ -; -; Decodeur de trame pulsadis EJP et préavis EJP -; (pic 12C508 ou 509) -; Alain Gibaud, 20-2-2001 -; -; ======================================================== - list r=hex,p=p12c508 - - include "p12c508.inc" -GP0 equ 0 -GP1 equ 1 -GP2 equ 2 -GP3 equ 3 -GP4 equ 4 -GP5 equ 5 -TO equ 4 -; masques pour acceder aux pattes -GP0bit equ 1 << GP0 -GP1bit equ 1 << GP1 -GP2bit equ 1 << GP2 -GP3bit equ 1 << GP3 -GP4bit equ 1 << GP4 -GP5bit equ 1 << GP5 -; ======================================================== -; affectation des pattes -; - -; sorties: (actives niv bas) -NORMAL equ GP0 ; LED verte -ALERTE equ GP1 ; LED orange -EJP equ GP2 ; LED rouge -; entrees:( actives niv bas) -SIGNAL equ GP3 ; avec pull-up, en provenance filtre 175 Hz -; GP4-5 sont utilisees par l'horloge -; ======================================================== -; variables: -TICKS equ 0x7 ; compteur de ticks (1 tick = 2/100 s) -SLOT equ 0x8 ; numero slot dans la trame -; ======================================================= -; Macros pour alleger le code ... -; -; Teste si min <= (var) < max -; branche en "in" si oui, en "out" si non. -; -Lminmax macro var,min,max,outm,in,outp - movlw min - subwf var,W ; (var) - min - btfss STATUS,C - goto outm ; C=0 => resutat < 0 => var < min - - movlw max - subwf var,W ; (var) - max - btfss STATUS,C - goto in - goto outp ; C=1 => resutat >= 0 => var >= min - endm -; -; Attend que le bit "bit" du registre "reg" soit a 1 -; -Waitbit1 macro reg,bit - local Wait1 -Wait1 btfss reg,bit - goto Wait1 - endm -; -; Attend que le bit "bit" du registre "reg" soit a 0 -; -Waitbit0 macro reg,bit - local Wait0 -Wait0 btfsc reg,bit - goto Wait0 - endm -; -; Branche en "label" si (reg) == num, sinon continue -; -Beq macro label,reg,num - movlw num - subwf reg,W - btfsc STATUS,Z - goto label - endm -; -; Branche en "label" si (reg) != num, sinon continue -; -Bne macro label,reg,num - movlw num - subwf reg,W - btfss STATUS,Z - goto label - endm - -; -; Branche en "label" si (reg) < num, sinon continue -; -Blt macro label,reg,num - movlw num - subwf reg,W ; reg - W - btfss STATUS,C - goto label ; C=0 => reg - W < 0 - endm - -; -; Branche en "label" si (reg) >= num, sinon continue -; -Bge macro label,reg,num - movlw num - subwf reg,W ; reg - W - btfsc STATUS,C - goto label ; C=1 => reg - W >= 0 - endm -; ======================================================== - ; CONFIG word ( en FFF ) - ; bits 11:5 don't care - ; bit 4 : MCLRE enabled = 1, tied to Vdd = 0 - ; bit 3 : code protection off = 1, on = 0 - ; bit 2 : no watchdog = 0, watchdog = 1 - ; bit 1-0 ; EXTRC = 00, INTRC = 10, XT = 01, LP = 00 - - __CONFIG B'000000001101' ; (horloge a quartz, avec watchdog) -; ======================================================== - org 0 - goto debut -;========================================================= -; sous-programmes -; ======================================================== -; regarde si le timer est passe a 0 -; si oui, le compteur de ticks est incremente -; et on attend le repassage a 1 -; Cette routine DOIT etre appelee tout les 2/100 s ou plus souvent -tickcount - clrwdt - movf TMR0,W - btfss STATUS,Z - retlw 0 - - incf TICKS,F -; attendre que le timer ait depasse 0 -waitnoZ - clrwdt - movf TMR0,W - btfsc STATUS,Z - goto waitnoZ - retlw 0 -; -; les 2 fct qui suivent maintiennent, le compteur de ticks -; (en plus de scruter une patte) -; attente d'un signal (logique negative) -waitsignal - call tickcount - btfsc GPIO,SIGNAL - goto waitsignal - retlw 0 -; attente fin signal -waitnosignal - call tickcount - btfss GPIO,SIGNAL - goto waitnosignal - retlw 0 -; remet a zero le compteur de ticks et le timer et le watchdog -clearticks - clrwdt - clrw - movwf TICKS - movwf TMR0 - ; pour eviter un timeout immediat, le timer est charge - ; a 1, et le 1er tick ne fait que 0.019922s au lieu de 0.2s - ; (ce n'est pas grave dans la mesure ou de toute facon, - ; le temps de traitement entre les different declenchements - ; de chrono n'est pas nul) - incf TMR0,F - retlw 0 - -; -; ========================================================== -; -debut - ; reset par Watchdog ? - btfsc STATUS,TO - goto notimeout - ; TO == 0 : OUI - clrwdt - goto 0x1FF ; recalibrage, 0x3FF sur 12C509 - - ; TO == 1 : NON -notimeout - movwf OSCCAL ; recalibrer l'horloge - clrf TMR0 ; RAZ timer - ; GPWU=1 : disable wake up on pin change - ; GPPU=0 : enable pullups (a voir avec le hard ..) - ; T0CS=0 : timer connected to F/4 - ; T0SE=x : dont't care - ; PSA=0 : prescaler assigned to timer - ; PS2-0= : timer prescaler 111= 1/256, 101 = 1/64, 011 = 1/16 - movlw B'10010101' - option - - ; config des pattes - movlw B'00001000' ; GP0-2 en sortie, GP3 entree - tris GPIO - - ; se mettre en mode normal - bcf GPIO,NORMAL - bsf GPIO,ALERTE - bsf GPIO,EJP - - -attendre_trame - call waitnosignal ; attendre ... - call waitsignal ; ... front montant - call clearticks - call waitnosignal - ; 45 tk = 0.9s, 55 tk = 1.1s - Lminmax TICKS,D'45',D'55',attendre_trame,pulse1s,attendre_trame -pulse1s - - ; attendre 162,5 tk = 2.75 s + 0.5 s = 3.25 s - call clearticks -again325 - call tickcount - Lminmax TICKS,D'162',D'162',again325,again325,end325 -end325 - - ; on est maintenant au centre du 1er bit - ; il suffit d'echantillonner toutes les 2.5s - movlw 1 - movwf SLOT - -sample btfsc GPIO,SIGNAL ; logique negative - goto slot40 - - ; signal detecte !! - Bne not5,SLOT,D'5' ; slot == 5 ? - ; oui - 5 = passage en alerte - bsf GPIO,NORMAL ; bit a 1 = LED eteinte - bsf GPIO,EJP ; bit a 1 = LED eteinte - bcf GPIO,ALERTE ; bit a 0 = LED allumee - goto nextslot -not5 - Bne not15,SLOT,D'15' ; slot == 15 ? - ; oui - btfsc GPIO,ALERTE ; deja en alerte ? - goto endejp - ; oui - 5 & 15 = debut ejp - bsf GPIO,NORMAL ; bit a 1 = LED eteinte - bsf GPIO,ALERTE ; bit a 1 = LED eteinte - bcf GPIO,EJP ; bit a 0 = LED allumee - goto nextslot -endejp - ; non - 15 seul = fin ejp - bsf GPIO,EJP ; bit a 1 = LED eteinte - bsf GPIO,ALERTE ; bit a 1 = LED eteinte - bcf GPIO,NORMAL ; bit a 0 = LED allumee - goto nextslot - -not15 -slot40 - ; slot 40 ? - Bne nextslot,SLOT,D'40' ; slot == 40 ? - ; et attendre une nouvelle trame - - goto attendre_trame -nextslot - incf SLOT,F - - ; si le signal est a 1, on en profite pour se resynchroniser - ; sur son front descendant, au cas ou l'emetteur ne soit pas - ; bien conforme au protocole. - btfss GPIO,SIGNAL - goto resynchro - ; attendre 125 ticks = 2.5s - call clearticks -again125 - call tickcount - Lminmax TICKS,D'125',D'126',again125,sample,again125 - -resynchro - call waitnosignal - call clearticks -again100 ; attente 2 s (100 ticks) - call tickcount - Lminmax TICKS,D'100',D'101',again100,sample,again100 - - end - - diff --git a/part/tests/hl/highlight.R b/part/tests/hl/highlight.R deleted file mode 100644 index d0a50b6..0000000 --- a/part/tests/hl/highlight.R +++ /dev/null @@ -1,239 +0,0 @@ -all.equal <- function(target, current, ...) UseMethod("all.equal") - -all.equal.default <- - function(target, current, check.attributes = TRUE, ...) -{ - ## Really a dispatcher given mode() of args : - ## use data.class as unlike class it does not give "Integer" - if(is.language(target) || is.function(target) || is.environment(target)) - return(all.equal.language(target, current, ...)) - if(is.recursive(target)) - return(all.equal.list(target, current, ...)) - msg <- c(if(check.attributes) attr.all.equal(target, current, ...), - if(is.numeric(target)) { - all.equal.numeric(target, current, check.attributes = check.attributes, ...) - } else - switch (mode(target), - logical = , - complex = , - numeric = all.equal.numeric(target, current, check.attributes = check.attributes, ...), - character = all.equal.character(target, current, check.attributes = check.attributes, ...), - if(data.class(target) != data.class(current)) { - paste("target is ", data.class(target), ", current is ", - data.class(current), sep = "") - } else NULL)) - if(is.null(msg)) TRUE else msg -} - -all.equal.numeric <- - function(target, current, tolerance = .Machine$double.eps ^ .5, - scale = NULL, check.attributes = TRUE, ...) -{ - msg <- if(check.attributes) attr.all.equal(target, current, ...) - if(data.class(target) != data.class(current)) { - msg <- c(msg, paste("target is ", data.class(target), ", current is ", - data.class(current), sep = "")) - return(msg) - } - - lt <- length(target) - lc <- length(current) - cplx <- is.complex(target) - if(lt != lc) { - ## *replace* the 'Lengths' msg[] from attr.all.equal(): - if(!is.null(msg)) msg <- msg[- grep("\\bLengths\\b", msg)] - msg <- c(msg, paste(if(cplx)"Complex" else "Numeric", - ": lengths (", lt, ", ", lc, ") differ", sep = "")) - return(msg) - } - target <- as.vector(target) - current <- as.vector(current) - out <- is.na(target) - if(any(out != is.na(current))) { - msg <- c(msg, paste("'is.NA' value mismatches:", sum(is.na(current)), - "in current,", sum(out), " in target")) - return(msg) - } - out <- out | target == current - if(all(out)) { if (is.null(msg)) return(TRUE) else return(msg) } - - target <- target[!out] - current <- current[!out] - if(is.integer(target) && is.integer(current)) target <- as.double(target) - xy <- mean((if(cplx)Mod else abs)(target - current)) - what <- - if(is.null(scale)) { - xn <- mean(abs(target)) - if(is.finite(xn) && xn > tolerance) { - xy <- xy/xn - "relative" - } else "absolute" - } else { - xy <- xy/scale - "scaled" - } - - if(is.na(xy) || xy > tolerance) - msg <- c(msg, paste("Mean", what, if(cplx)"Mod", "difference:", format(xy))) - - if(is.null(msg)) TRUE else msg -} - -all.equal.character <- - function(target, current, check.attributes = TRUE, ...) -{ - msg <- if(check.attributes) attr.all.equal(target, current, ...) - if(data.class(target) != data.class(current)) { - msg <- c(msg, paste("target is ", data.class(target), ", current is ", - data.class(current), sep = "")) - return(msg) - } - lt <- length(target) - lc <- length(current) - if(lt != lc) { - if(!is.null(msg)) msg <- msg[- grep("\\bLengths\\b", msg)] - msg <- c(msg, paste("Lengths (", lt, ", ", lc, - ") differ (string compare on first ", ll <- min(lt, lc), - ")", sep = "")) - ll <- seq(length = ll) - target <- target[ll] - current <- current[ll] - } - nas <- is.na(target) - if (any(nas != is.na(current))) { - msg <- c(msg, paste("'is.NA' value mismatches:", sum(is.na(current)), - "in current,", sum(nas), " in target")) - return(msg) - } - ne <- !nas & (target != current) - if(!any(ne) && is.null(msg)) TRUE - else if(any(ne)) c(msg, paste(sum(ne), "string mismatches")) - else msg -} - -all.equal.factor <- function(target, current, check.attributes = TRUE, ...) -{ - if(!inherits(current, "factor")) - return("'current' is not a factor") - msg <- if(check.attributes) attr.all.equal(target, current) - class(target) <- class(current) <- NULL - nax <- is.na(target) - nay <- is.na(current) - if(n <- sum(nax != nay)) - msg <- c(msg, paste("NA mismatches:", n)) - else { - target <- levels(target)[target[!nax]] - current <- levels(current)[current[!nay]] - if(is.character(n <- all.equal(target, current, check.attributes = check.attributes))) - msg <- c(msg, n) - } - if(is.null(msg)) TRUE else msg -} - -all.equal.formula <- function(target, current, ...) -{ - if(length(target) != length(current)) - return(paste("target, current differ in having response: ", - length(target) == 3, ", ", length(current) == 3)) - if(all(deparse(target) != deparse(current))) - "formulas differ in contents" - else TRUE -} - -all.equal.language <- function(target, current, check.attributes = TRUE, ...) -{ - mt <- mode(target) - mc <- mode(current) - if(mt == "expression" && mc == "expression") - return(all.equal.list(target, current, check.attributes = check.attributes, ...)) - ttxt <- paste(deparse(target), collapse = "\n") - ctxt <- paste(deparse(current), collapse = "\n") - msg <- c(if(mt != mc) - paste("Modes of target, current: ", mt, ", ", mc, sep = ""), - if(ttxt != ctxt) { - if(pmatch(ttxt, ctxt, FALSE)) - "target a subset of current" - else if(pmatch(ctxt, ttxt, FALSE)) - "current a subset of target" - else "target, current don't match when deparsed" - }) - if(is.null(msg)) TRUE else msg -} - -all.equal.list <- function(target, current, check.attributes = TRUE, ...) -{ - msg <- if(check.attributes) attr.all.equal(target, current, ...) -## nt <- names(target) -## nc <- names(current) - iseq <- - ## - ## Commenting this eliminates PR#674, and assumes that lists are - ## regarded as generic vectors, so that they are equal iff they - ## have identical names attributes and all components are equal. - ## if(length(nt) && length(nc)) { - ## if(any(not.in <- (c.in.t <- match(nc, nt, 0)) == 0)) - ## msg <- c(msg, paste("Components not in target:", - ## paste(nc[not.in], collapse = ", "))) - ## if(any(not.in <- match(nt, nc, 0) == 0)) - ## msg <- c(msg, paste("Components not in current:", - ## paste(nt[not.in], collapse = ", "))) - ## nt[c.in.t] - ## } else - ## - if(length(target) == length(current)) { - seq(along = target) - } else { - if(!is.null(msg)) msg <- msg[- grep("\\bLengths\\b", msg)] - nc <- min(length(target), length(current)) - msg <- c(msg, paste("Length mismatch: comparison on first", - nc, "components")) - seq(length = nc) - } - for(i in iseq) { - mi <- all.equal(target[[i]], current[[i]], check.attributes = check.attributes, ...) - if(is.character(mi)) - msg <- c(msg, paste("Component ", i, ": ", mi, sep="")) - } - if(is.null(msg)) TRUE else msg -} - - -attr.all.equal <- function(target, current, - check.attributes = TRUE, check.names = TRUE, ...) -{ - ##--- "all.equal(.)" for attributes --- - ##--- Auxiliary in all.equal(.) methods --- return NULL or character() - msg <- NULL - if(mode(target) != mode(current)) - msg <- paste("Modes: ", mode(target), ", ", mode(current), sep = "") - if(length(target) != length(current)) - msg <- c(msg, paste("Lengths: ", length(target), ", ", - length(current), sep = "")) - ax <- attributes(target) - ay <- attributes(current) - if(check.names) { - nx <- names(target) - ny <- names(current) - if((lx <- length(nx)) | (ly <- length(ny))) { - ## names() treated now; hence NOT with attributes() - ax$names <- ay$names <- NULL - if(lx && ly) { - if(is.character(m <- all.equal.character(nx, ny, check.attributes = check.attributes))) - msg <- c(msg, paste("Names:", m)) - } else if(lx) - msg <- c(msg, "names for target but not for current") - else msg <- c(msg, "names for current but not for target") - } - } - if(check.attributes && (length(ax) || length(ay))) {# some (more) attributes - ## order by names before comparison: - nx <- names(ax) - ny <- names(ay) - if(length(nx)) ax <- ax[order(nx)] - if(length(ny)) ay <- ay[order(ny)] - tt <- all.equal(ax, ay, check.attributes = check.attributes, ...) - if(is.character(tt)) msg <- c(msg, paste("Attributes: <", tt, ">")) - } - msg # NULL or character -} - diff --git a/part/tests/hl/highlight.abc b/part/tests/hl/highlight.abc deleted file mode 100644 index a7e45f7..0000000 --- a/part/tests/hl/highlight.abc +++ /dev/null @@ -1,8 +0,0 @@ -% Taken from http://www.gre.ac.uk/~c.walshaw/abc/#examples -T:Paddy O'Rafferty -C:Trad. -M:6/8 -K:D -dff cee|def gfe|dff cee|dfe dBA|dff cee|def gfe|faf gfe|1 dfe dBA:|2 dfe dcB|| -~A3 B3|gfe fdB|AFA B2c|dfe dcB|~A3 ~B3|efe efg|faf gfe|1 dfe dcB:|2 dfe dBA|| -fAA eAA|def gfe|fAA eAA|dfe dBA|fAA eAA|def gfe|faf gfe|dfe dBA:| diff --git a/part/tests/hl/highlight.ahdl b/part/tests/hl/highlight.ahdl deleted file mode 100644 index e059aa8..0000000 --- a/part/tests/hl/highlight.ahdl +++ /dev/null @@ -1,43 +0,0 @@ --- Test file for kate's syntax highlighting -Title "Test file"; - --- BEGIN region (a region marker region) :) - -% multiline comment -goes on here % - --- END - -FUNCTION FCT (Clk, Key) RETURNS (pulse); - -SUBDESIGN CDCLOCK2 -( -in : INPUT; -- go in -out[3..0] : OUTPUT; -- come out -) - -VARIABLE -start : soft; -usec[3..0] : node; - -BEGIN - -in = FCT(clock, some_key); -- senseless code - --- comment -blubb = (blobb[] == H"3ff"); - -IF in THEN asdf --- folde me -END IF; - -TABLE --- missing code -END TABLE - - -END; - --- hex, octal, binary -H"0" => B"1000000"; -O"01234567"; \ No newline at end of file diff --git a/part/tests/hl/highlight.asm-avr b/part/tests/hl/highlight.asm-avr deleted file mode 100644 index f1e0542..0000000 --- a/part/tests/hl/highlight.asm-avr +++ /dev/null @@ -1,75 +0,0 @@ -;******************************************************************** -;* LED flasher: LED will flash with a X on/off ratio at PD6 -;* -;* NOTE: delay depends in the value of X, 1 is fast, 255 is slow -;* -;* No copyright ©1998 RES® * FREEWARE * -;* -;* NOTE: Connect a low current LED with a 1k resistor in serie from -;* Vdd to pin 11 of the MCU. (Or a normal LED with a 330ohm) -;* -;* RES® can be reached by email: digitalaudio@mail.com -;* or visit the website: http://home.wanadoo.nl/electro1/avr -;* -;* Version :1.0 -;* Date :12/26/98 -;* Author :Rob's ElectroSoft® -;* Target MCU :AT90S1200-12PI@4MHz -;******************************************************************** - -.include "1200def.inc" - - rjmp RESET ;reset handle - - -;* Long delay - -;* Register variables - - .def T1 = r1 - .def T2 = r2 - .def temp = r19 - -;* Code - -longDelay: - clr T1 ;T1 used as delay 2nd count - clr T2 ;T2 used as delay 3d count -delay_1: - dec T2 - brne delay_1 - dec T1 - brne delay_1 - dec temp ;temp must be preset as - brne delay_1 ; delay master count - ret - - -;* Resets the data direction register D - -;* Defines - - .equ led = 6 ;LED at PD6 - -;* Code - -RESET: - sbi DDRD, led ;connect LED to PORTD pin 6 - - -;* Main program - -;* This part will let the LED go on and off by X - -;* Register variables - - .equ X = 10 ;enter delaytime X - -flash: - sbi PORTD, led ;LED on - ldi temp, X ;X sec delay - rcall longDelay - cbi PORTD, led ;LED off - ldi temp, X ;X sec delay - rcall longDelay - rjmp flash ;another run \ No newline at end of file diff --git a/part/tests/hl/highlight.asm-nasm b/part/tests/hl/highlight.asm-nasm deleted file mode 100644 index a5da4d1..0000000 --- a/part/tests/hl/highlight.asm-nasm +++ /dev/null @@ -1,27 +0,0 @@ -; Example file for nasm.xml kate syntax file -; compile with `nasm example.asm -f elf -o example.o` -; and link with 'gcc example.o -o example` -; Public domain -; kate: hl Intel x86 (NASM); - -section .data - -hello dd 'Hello World', 0x0A, 0h -printf_param dd '%s', 0q - -section .text - -extern printf - -global main -main: - push ebp - mov ebp, esp - - push hello - push printf_param - call printf - - mov eax, 0b - leave - ret diff --git a/part/tests/hl/highlight.asp b/part/tests/hl/highlight.asp deleted file mode 100644 index 07a8619..0000000 --- a/part/tests/hl/highlight.asp +++ /dev/null @@ -1,58 +0,0 @@ -<% 'kate: hl ASP; -if ( instr(request.servervariables("PATH_INFO"),"login.asp") <= 0 and instr(request.servervariables("PATH_INFO"),"inset") <= 0 and instr(request.servervariables("PATH_INFO"),"Data") <= 0 and instr(request.servervariables("PATH_INFO"),"dropDown") <= 0 ) then - Session("originalRequestedPage") = Request.ServerVariables("PATH_INFO") & "?" & Request.ServerVariables("QUERY_STRING") -end if - -function countRecords( rsToCount ) - numRecs = 0 - - do until rsToCount.eof - numRecs = numRecs + 1 - - rsToCount.movenext - loop - - rsToCount.close ' just to make sure nobody - ' tries to operate on the recordset, - ' which has already reached eof - - countRecords = numRecs -end function - -function unique( rs, sortColumn ) ' return unique instances of text in sortColumn within rs - dim sorted() - - redim sorted(1) - dim i - i = 0 - do until rs.eof - if (not find( rs(sortColumn), sorted )) then - redim preserve sorted(i+1) - sorted(i) = rs(sortColumn) - i = i + 1 - end if - rs.MoveNext - loop - - redim preserve sorted(i-1) ' the function will add an extra blank entry to the array - - rs.Close ' close the recordset - we'll be using it again - and reset i - well be using it again, too - - unique = sorted -end function - -sub testSub( variable ) ' do nothing impressive... - dim newVar - - newVar = variable - - if ( variable = true ) - response.end - else %> - -

We are writing text.

-

<%=newVar%>

-

We have written text and outputted a variable.

- -<% end if -end sub %> \ No newline at end of file diff --git a/part/tests/hl/highlight.awk b/part/tests/hl/highlight.awk deleted file mode 100644 index 47f10cf..0000000 --- a/part/tests/hl/highlight.awk +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr -# AWK hl test - -# BEGIN and END are also matched as patterns -BEGIN { - p = 0; -} - -/some pattern/ { - p++; -} - -# / inside brackets is not considered end of expression -# a loose division operator (/) is not mismatched as a pattern. -$1 =~ /[^abc/]def/ || b == 3 / 5 { - - gsub ( FILENAME ); - -} - -# TODO and FIXME also work in comments in Awk. - -# Also backslash in patterns works. -/\/usr\/bin\/awk/ { print "This is me"; } - -END { - print p; -} diff --git a/part/tests/hl/highlight.bib b/part/tests/hl/highlight.bib deleted file mode 100644 index 0ae404c..0000000 --- a/part/tests/hl/highlight.bib +++ /dev/null @@ -1,31 +0,0 @@ -% test file for kate's bibtex syntax highlighting - -@Article{artikel, -author = {Me}, -title = {Something}, -journal = {JHEP}, -year = {2003}, -} - -@Book - -{ - -boek, -author = "Someone", -title = "Something", -journal = "Nucl. Phys. B", -year = "2003", -} - -This is ignored by BibTeX, no special highlighting -%This is not a comment, it is just ignored (thanks to the people in #latex) :) - -@string{test="lange string die ik niet vaak opnieuw wil intikken"} - -@PhdThesis{thesis, -author = {Me}, -title = {Dunno}, -school = {ITFA}, -year = {2005, hopefully}, -} diff --git a/part/tests/hl/highlight.cmake b/part/tests/hl/highlight.cmake deleted file mode 100644 index 02a6c8f..0000000 --- a/part/tests/hl/highlight.cmake +++ /dev/null @@ -1,49 +0,0 @@ -#this CMakeLists.txt doesn't do anything useful, but it shoudl demonstrate the cmake syntax highlighting -#Alexander Neundorf - -#ok this is a comment -#and another line -#a built-in command, it's bold black -ADD_DEFINITIONS(-Wall -Wctor-dtor-privacy -Woverloaded-virtual -Wno-long-long -pipe -fno-builtin -fno-exceptions) - -#and another function -INCLUDE_DIRECTORIES( -#comments are also highlighted inside function parameters -#variables are Qt::blue -${CMAKE_CURRENT_SOURCE_DIR}/../../lib/qt4/include/Qt -) - -# BEGIN defining a macro -MACRO(ECOS_ADD_EXECUTABLE _exe_NAME ) - -#special parameters are italic, see the STATIC in the next line -ADD_LIBRARY(${_exe_NAME} STATIC ${ARGN}) -#but not in the following line ? - ADD_LIBRARY(${_exe_NAME} STATIC ${ARGN}) -# it seems the kate highlighting file could need some love, Alex - - -#another command with a bunch of variables and special parameters - ADD_CUSTOM_COMMAND( - TARGET ${_exe_NAME} - PRE_LINK - COMMAND ${CMAKE_C_COMPILER} - ARGS -o ${_exe_NAME} -$\(${_exe_NAME}_SRC_OBJS\) -nostdlib -nostartfiles -Lecos/install/lib -Ttarget.ld - ) - -#add the created files to the make_clean_files - SET(ECOS_ADD_MAKE_CLEAN_FILES ${ECOS_ADD_MAKE_CLEAN_FILES};${_exe_NAME};) -#and another command... - SET_DIRECTORY_PROPERTIES( - PROPERTIES - ADDITIONAL_MAKE_CLEAN_FILES "${ECOS_ADD_MAKE_CLEAN_FILES}" - ) -ENDMACRO(ECOS_ADD_EXECUTABLE) -# END of macro - -#calling a self-defined function, variables are also Qt::blue here -ECOS_ADD_EXECUTABLE(${PROJECT_NAME} ${the_sources} ${qt4_moc_SRCS}) - - - diff --git a/part/tests/hl/highlight.css b/part/tests/hl/highlight.css deleted file mode 100644 index 986c6c0..0000000 --- a/part/tests/hl/highlight.css +++ /dev/null @@ -1,49 +0,0 @@ -/** - * This is a pseudo CSS file to test Kate's CSS syntax highlighting. - */ - -@import url("othersheet.css") screen, tv; - -body { - font-size: 15pt; - font-family: Verdana, Helvetica, "Bitstream Vera Sans", sans-serif; - margin-top: 0px; /* yet another comment */ - margin-bottom: 0px; - // this is no comment, it's just broken! - margin-left: 0px; - margin-right: 0px; -} - -.something -{ - margin-right: 0px; - color: #cdd; - color: #AAFE04; - color: rgb(10%,30%,43%); - background: maroon; -} - -a:hover { -} - -#header, -p.intro:first-letter, -p:lang(nl), -img[align="right"] -{ - border: 1px solid Qt::red !important; - -moz-border-radius: 15px; /* unknown properties render italic */ -} - -@media print { - - #header - { - display: none; - } - -} - -/* -TODO: add more tests, e.g. media -*/ diff --git a/part/tests/hl/highlight.d b/part/tests/hl/highlight.d deleted file mode 100644 index b3daaf6..0000000 --- a/part/tests/hl/highlight.d +++ /dev/null @@ -1,195 +0,0 @@ -/******** -* Highlight testing module. -* -* Do not attempt to run this! -***********/ -module highlighttest; -import X = null; - -/++ Pragma directives. DDoc + DDoc embedded items. Special Tokens. -+ -+ --- -+ // comment -+ #line 12 "hightlighttest.d" /* block comment */ -+ #line __LINE__ __FILE__ /++ embedded block comment +/ -+ -+ pragma /* */ (msg, "what?"); -+ pragma(/++ +/ lib, "insane.a"); -+ pragma(D_Custom_Extension, "custom data"); -+ --- -+/ - -/// version condition -version = X; -version (X) ; -version(linux) {} - -/// linkage -extern - (C) {} -extern : -; -extern (Windows) {} - -/// alias & typedef -alias int.min minint; -typedef int myint; - -int main(char[][] args) { - /// statements - if (1) {} - else {} - with (N) {x = B} - - /// attributes - auto x = 1; - static if (true) {} - void (in X, out Y) {} // NOTE: using in like this is rare, more common to use as an expression and no way to tell apart? - - /// deprecated - deprecated void fct (); - - /// types - void a; - ushort u; - int[uint] AA; - class C; - enum N : int { A = 5, B } - typeof(u) u2; - - /// expressions - x = cast(int) 55; - void* p = null; - p = cast(void*) new int; - x = 1 in AA; // NOTE: a THIRD use of in. How to detect?? - assert (true); - - /// libsymbols - string s = ""; - throw new Exception; - TypeInfo ti = typeid(int); - - /// tests - debug {} - debug (2) {} - debug (DSymb) {} - unittest {} - - /// scope (as attribute and as statement) - scope struct S; - scope (exit) {} - scope - (success) {} // NOTE: rules cannot match across new-lines - scope (failure) {} - - /// Properties - x = int.min; - s = (5-3).stringof; - - /// strings - s = r"raw string"; - s = x"00FF"; - s = \n \a; - s = \u1234; - s = \U12345678; - s = \& ; - char c = 'a'; - s = "abc 012 \" \n \x12 \u1234 \U12345678"; - s = `BQString '"`; - - /// region markers - //BEGIN x - //END x - - /// DDoc - /******* - * DDoc - * - * Section: - * New section. - * $(I italic) - *******/ - /+++++++ - + DDoc - + /+ - + +/ - +++++++/ - - // comments - // FIXME NOTE - /* comment */ - /+ comment /+ nested comment +/ +/ - - /// brace folding - { - } - - /** normal text - * --- - * .x; - * .. - * ... - * .... - * ..... - * _._ - * _e1 - * --- - */ - - /// float and int literals - int i; - real r; - ireal ir; - r = .0; - r = 0f; - ir = 0e0i; - ir = 0.fi; - r = 0.0e0; - r = 0xF.Fp0; - r = 0x_._p0_; - i = 5; - i = -1; - i = 0b10; - i = 0070; - i = 00; - i = 0xF0; - - /// ranges - int[] A; - i = A[1]; - A = A[0..$]; - A = A[0..0]; - A = A[0..length]; - - /// labels - label: - goto label; - - /// function, delegate - creal function () fp = function creal() { return 0f+0fi; }; - void delegate (in int i, lazy int b) dg = delegate void (int, int) {} - - /// in, out, body - // NOTE: highlighting in & out as statements here could be difficult - float F () - in {} - out (result) {} - body {} - - /// try, catch, finally - try { - throw new Exception("oh no... "); - } catch (Exception e) { - } finally { - } - - /// mixin - mixin("return false;").stringof; - - /// templates - macro; // what does this do? - template Tp (T) { - Tp t; - } - Tp!(int) y; -} diff --git a/part/tests/hl/highlight.do b/part/tests/hl/highlight.do deleted file mode 100644 index 0b90b16..0000000 --- a/part/tests/hl/highlight.do +++ /dev/null @@ -1,89 +0,0 @@ -/* Test file for kate's stata syntax highlighting -*/ -*! version 1.2.0 2mar2003 E. Leuven -program define spellsplit - version 7 - syntax [anything], spell(varlist min=2 max=2) [ by(varlist)] - tokenize `spell' - local date0 `1' - local date1 `2' - local f0 : format `date0' - local f1 : format `date1' - - /* set default statistic */ - local current "mean" - - gettoken left anything : anything, match(prns) - while "`left'"!="" { - if "`prns'"!="" { - if !inlist("`left'","mean","sum") { - di as error "Statistic `left' not supported" - exit 198 - } - local current "`left'" - } - else { - local `current'vars ``current'vars' `left' - } - gettoken left anything : anything, match(prns) - } - if ("`meanvars'"!="") { - confirm var `meanvars' - unab meanvars : `meanvars' - } - if ("`sumvars'"!="") { - confirm var `sumvars' - unab sumvars : `sumvars' - } - - quietly { - g _count = 1 - local xvars `meanvars' `sumvars' _count - - /* create dummy by-var if no by option is specified */ - if "`by'"=="" { - tempvar by - g byte `by' = 1 - } - tempvar `xvars' `by' - - /* create negative for subtraction when spell ends */ - cap foreach v of varlist `xvars' { - g double ``v'' = -`v' - local txvars `txvars' ``v'' - } - cap foreach v of varlist `by' { - g double ``v'' = `v' - local txvars `txvars' ``v'' - } - - stack `date0' `xvars' `by' `date1' `txvars', into(`date0' `xvars' `by') clear - - /* calculate totals per date */ - cap foreach v of varlist `xvars' { - egen double ``v'' = sum(`v'), by(`by' `date0') - } - - /* unique dates only */ - by `by' `date0', sort: keep if _n==1 - - /* calculate totals (+ when spell starts - when ends) */ - sort `by' - cap foreach v of varlist `xvars' { - by `by': replace `v' = sum(``v'') - } - by `by': g `date1' = `date0'[_n + 1] - - drop if `date0'>`date1' - drop _stack - drop if _count==0 - order `by' `date0' `date1' `xvars' - format `date0' `f0' - format `date1' `f1' - - cap for var `meanvars': replace X = X/_count - - compress - } - -end \ No newline at end of file diff --git a/part/tests/hl/highlight.dox b/part/tests/hl/highlight.dox deleted file mode 100644 index 39b404f..0000000 --- a/part/tests/hl/highlight.dox +++ /dev/null @@ -1,227 +0,0 @@ -This is a pseudo doxygen file to test Kate's doxyge syntax highlighting. - -Normal text, no HL. -=================== -a multiline comment may begin with a /*! */, too. That should work, -because it is the same "entrance rule". - -popping tests: -/** multiline */ end of doxygen HL mode -/*! multiline */ end of doxygen HL mode -//! singleline, where */ should be ignored! still doxygen HL mode -/// singleline, where */ should be ignored! still doxygen HL mode -///< singleline, where */ should be ignored! still doxygen HL mode -begin and end immediately: -/********/ actually no doxygen comment - used for "info boxes" :) -/**/ <-- it really works --- end of doxygen HL mode -/*!*/ end of doxygen HL mode - - -/** \code rest of line is normal comment HL */ end of doxygen HL mode -/** \code rest of line is normal comment HL - * comment HL mode - */ end of doxygen HL mode - - -/** \file aword rest of line is normal comment HL */ end of doxygen HL mode -/** \file */aword <-- pop! no doxygen HL mode -/** \file aword rest of line is normal comment HL - * comment HL mode - */ end of doxygen HL mode - - -/** \brief A short description */ end of doxygen HL mode -/** \brief */A <-- pop! end of doxygen HL mode -/** \brief A short description - * comment HL mode - */ end of doxygen HL mode - - -/** \page aword rest of line is string */ end of doxygen HL mode -/** \page */aword <-- pop! end of doxygen HL mode -/** \page aword rest of line is string - * comment HL mode - */ end of doxygen HL mode - - -/** \image aword aword rest of line is normal HL */ end of doxygen HL mode -/** \image aword */aword <-- pop! end of doxygen HL mode -/** \image */aword aword <-- pop! end of doxygen HL mode -/** \image aword aword rest of line is normal HL - * comment HL mode - */ end of doxygen HL mode - -Tests for HTML tags in doxygen HL mode: -======================================= -/** */ end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** */ end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** end of doxygen HL mode -/** <*/a href="blubb"> end of doxygen HL mode - -//! */ stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! */ stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! stay in doygen HL mode -//! <*/a href="blubb"> stay in doygen HL mode -//! stay in doygen HL -/** \code rest of line is normal comment HL */ end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest of end of doxygen HL mode -/** \code rest <*/a href="blubb"> of end of doxygen HL mode -/** \code rest of line is normal comment HL - * comment HL mode text - */ end of doxygen HL mode - - -/** \file aword rest of line is normal comment HL */ end of doxygen HL mode -/** \file awo*/rd end of doxygen HL mode -/** \file aword end of doxygen HL mode -/** \file awo<*/html_should_be_ignored_here>rd end of doxygen HL mode -/** \file a*/word end of doxygen HL mode -/** \file aword rest of line is normal comment HL - * comment HL mode - */ end of doxygen HL mode - - -/** \brief A short of description */ end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of <*//a href='blubb'> end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of end of doxygen HL mode -/** \brief A short of description - * comment HL mode - */ end of doxygen HL mode - - -/** \page aword A short of description */ end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of <*//a href='blubb'> end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short of end of doxygen HL mode -/** \page aword A short <*/a href="blubb"> of end of doxygen HL mode -/** \page aword A shor*/t of end of doxygen HL mode -/** \page awor*/d A short of end of doxygen HL mode -/** \page */aword A short of end of doxygen HL mode -/** \page aword A short of description - * comment HL mode - */ end of doxygen HL mode - - -/** \image aword aword rest of line is normal HL */ end of doxygen HL mode -/** \image aword aword rest of line is*/ end of doxygen HL mode -/** \image aword aword*/ end of doxygen HL mode -/** \image aword aw*/ord end of doxygen HL mode -/** \image aword */aword end of doxygen HL mode -/** \image aword*/ end of doxygen HL mode -/** \image awo*/rd end of doxygen HL mode -/** \image */aword end of doxygen HL mode -/** \ima*/ge end of doxygen HL mode -/** \image aword aword rest of line is normal HL - * comment HL mode - */ end of doxygen HL mode - -Some further tests for singlelinecomments (* / should not pop!) -=============================================================== -/// a singlelinecommment blubb blubb */. stay in doxygen HL mode -/// \code a singlelinecommment blubb b*/lubb. stay in doxygen HL mode -/// \code*/ a singlelinecommment blubb blubb. stay in doxygen HL mode -/// \code a singlelinecommment blubb blubb -/// \brief a descriptive text (string) stay in doxygen HL mode -/// \brief a descriptive text (string)*/ description should go on here -/// \brief a descriptive text */(string) description should go on here -/// \brief */a descriptive text (string) description should go on here -/// \ref aword a descriptive text (string) */ description should go on here -/// \ref aword a descriptive text (str*/ing) description should go on here -/// \ref aword a des*/criptive text (string) description should go on here -/// \ref aword*/ a descriptive text (string) description should go on here -/// \ref aw*/ord a descriptive text (string) description should go on here -/// \ref */aword a descriptive text (string) description should go on here - -HTML comment tests: -=================== -//! \ref word descriptive text (string) -normal HL mode. -//! \ref w descriptive text (string) -/** \ref word descriptive text (string) -normal HL mode. -/** \ref w - * normal doxygen HL mode. - */ - - -And final tests for a word: a single char: -=========================================== - -//! \ref word descriptive text (string) -//! \ref w descriptive text (string) - - -//! \image word1 word2 b descriptive text (string) -//! \image a word b descriptive text (string) - - -//! \brief A b c d e description should go on here - - -//! \file word rest of line is normal comment HL -//! \file a word rest of line is normal comment HL - -no doxygen HL mode here. -== END OF TESTFILE == \ No newline at end of file diff --git a/part/tests/hl/highlight.e b/part/tests/hl/highlight.e deleted file mode 100644 index 6f07c83..0000000 --- a/part/tests/hl/highlight.e +++ /dev/null @@ -1,90 +0,0 @@ -<' - -extend TB_NAME_T : [ ETRC ]; - -extend fifo { - keep soft testbench == ETRC; -}; - -extend ETRC fifo { - - keep direction == POP; - keep soft type == CLASSIC; - - keep PORT_DATAOUT == appendf("esa_data[%d]" , id); - keep PORT_POP_EMPTY == appendf("fifo_empty[%d]", id); - keep PORT_POP_ALMOST_EMPTY == appendf("ESA_PopAE[%d]" , id); - keep PORT_POP_ALMOST_FULL == appendf("ESA_PopAF[%d]" , id); - keep PORT_POP_FULL == ""; - keep PORT_POP_ERROR == ""; - keep PORT_POP_REQ == appendf("etrc_popreq_n[%d]" , id); - keep soft PORT_POP_CLK == "sysclk"; - keep soft PORT_PUSH_CLK == "sysclk"; - -// keep logger.verbosity == HIGH; - - - reset_sig() is { - injector.reset_sig(); - '(PORT_DATAOUT)' = 0; - '(PORT_POP_EMPTY)' = 0; - '(PORT_POP_ALMOST_EMPTY)' = 0; - '(PORT_POP_ALMOST_FULL)' = 0; - '(PORT_POP_REQ)' = 0; - '(PORT_POP_CLK)' = 0; - '(PORT_POP_CLK)' = 1; - }; - - event clkSys is rise('sysclk'); - event bug001 is true('pkdescnt[0]' == 1)@clkSys; - - on bug001 - { - dut_error("Bug 001 found ... crash!"); - }; - -}; - - - -extend ETRC FIFO_INJECTOR { - - pkt_desc_if : pkt_desc_if is instance; - keep pkt_desc_if.MAC_uid == id; - - add_new_pkt_desc() is also { - pkt_desc_if.indicate_one_pck_desc_is_come_in_FIFO(); - }; - - reset_sig() is { - pkt_desc_if.reset_sig(); - }; - -}; - -extend ETRC CLASSIC fifo -{ - - keep ae_seuil == 1; - keep af_seuil == 46; - keep fifo_size == 56; - - - - setState() is also - { - if (fifo_plot &&(sys.time > 200000) && // avoid fifo plot before beginning of operation of RAMC - !((injector.generated_packet_nb == injector.max_generated_packets && injector.stream.size() == 0) - || injector.generated_packet_nb == 0)) - { - if (fifo_use_logger) { - messagef(HIGH, "ETRC[%d] : %d\n", id, fifo.size()); - } - else { - out("__fifo_plot: ", sys.time, " ", fifo.size() ); - }; - }; - }; -}; - -'> diff --git a/part/tests/hl/highlight.erl b/part/tests/hl/highlight.erl deleted file mode 100644 index 5b485cb..0000000 --- a/part/tests/hl/highlight.erl +++ /dev/null @@ -1,68 +0,0 @@ -% testing for the erlang syntax highlighter -% NOTE alerts work in comments to TODO ! - -% pragmas (show as keywords) --module --export --define --undef --ifdef --ifndef --else --endif --include --include_lib - -% key words -after begin case catch cond end fun if let of query receive all_true some_true - -% operators -div rem or xor bor bxor bsl bsr and band not bnot -+ - * / == /= =:= =/= < =< > >= ++ -- = ! <- - -% separators (show as functions) -( ) { } [ ] . : | || ; , ? -> # - -% functions - predefined (part of erlang module) - show as functions -abs accept alarm apply atom_to_list binary_to_list binary_to_term check_process_code -concat_binary date delete_module disconnect_node element erase exit float float_to_list -garbage_collect get get_keys group_leader halt hd integer_to_list is_alive is_atom is_binary -is_boolean is_float is_function is_integer is_list is_number is_pid is_port is_process_alive -is_record is_reference is_tuple length link list_to_atom list_to_binary list_to_float list_to_integer -list_to_pid list_to_tuple load_module loaded localtime make_ref module_loaded node nodes now -open_port pid_to_list port_close port_command port_connect port_control ports pre_loaded process_flag -process_info processes purge_module put register registered round self setelement size -spawn spawn_link spawn_opt split_binary statistics term_to_binary throw time tl trunc tuple_to_list -unlink unregister whereis - -% functions - inferred -module:function -function() - -% atoms (show as "char") -% begin with underscore, lowercase, contain numbers letters and @ - or anything between '' -middle_underscore -abc ab4d a@cd8 a@ -'And this is (\012) an atom \' Atoo' Variable 'atom again' - -% variables (begin with capital letter or underscore, contain numbers, letters and @) -_leadingUnderscore AbdD@ B45@c - -% this is a string -"a string sits between \" double quotes" atom "more string" - -% integers (decimal) -1. 234 $A - -% integers (specified base) -2#10101 34#567 - -% float -12.23 12.9e-67 12.8E+89 33.34e89 - -% and finally some real code, so we can see what it looks like... --module(codetest). % everything is in a module --export([fac/1]). % name and number of arguments - need this to be called outside of the module - -fac(N) when N > 0 -> N * fac(N-1); -fac(N) when N == 0 -> 1. diff --git a/part/tests/hl/highlight.exu b/part/tests/hl/highlight.exu deleted file mode 100644 index 3651adf..0000000 --- a/part/tests/hl/highlight.exu +++ /dev/null @@ -1,97 +0,0 @@ --- Test file for Kate's Euphoria syntax highlighting/code folding. --- BEGIN region marker test - --- code here - --- END region marker test - --- The N Queens Problem: --- Place N Queens on an NxN chess board --- such that they don't threaten each other. -constant N = 8 -- try some other sizes -constant ROW = 1, COLUMN = 2 -constant TRUE = 1, FALSE = 0 -type square(sequence x) --- a square on the board - return length(x) = 2 -end type -type row(integer x) --- a row on the board - return x >= 1 and x <= N -end type - -function threat(square q1, square q2) --- do two queens threaten each other? - if q1[COLUMN] = q2[COLUMN] then - return TRUE - elsif q1[ROW] - q1[COLUMN] = q2[ROW] - q2[COLUMN] then - return TRUE - elsif q1[ROW] + q1[COLUMN] = q2[ROW] + q2[COLUMN] then - return TRUE - elsif q1[ROW] = q2[ROW] then - return TRUE - else - return FALSE - end if -end function - -function conflict(square q, sequence queens) --- Would square p cause a conflict with other queens on board so far? - for i = 1 to length(queens) do - if threat(q, queens[i]) then - return TRUE - end if - end for - return FALSE -end function - -integer soln -soln = 0 -- solution number - -procedure print_board(sequence queens) --- print a solution, showing the Queens on the board - integer k - position(1, 1) - printf(1, "Solution #%d\n\n ", soln) - for c = 'a' to 'a' + N - 1 do - printf(1, "%2s", c) - end for - puts(1, "\n") - for r = 1 to N do - printf(1, "%2d ", r) - for c = 1 to N do - if find({r,c}, queens) then - puts(1, "Q ") - else - puts(1, ". ") - end if - end for - puts(1, "\n") - end for - puts(1, "\nPress Enter. (q to quit) ") - while TRUE do - k = get_key() - if k = 'q' then - abort(0) - elsif k != -1 then - exit - end if - end while -end procedure - -procedure place_queen(sequence queens) --- place queens on a NxN chess board --- (recursive procedure) - row r -- only need to consider one row for each queen - if length(queens) = N then - soln += 1 - print_board(queens) - return - end if - r = length(queens)+1 - for c = 1 to N do - if not conflict({r,c}, queens) then - place_queen(append(queens, {r,c})) - end if - end for -end procedure diff --git a/part/tests/hl/highlight.f90 b/part/tests/hl/highlight.f90 deleted file mode 100644 index e2008c2..0000000 --- a/part/tests/hl/highlight.f90 +++ /dev/null @@ -1,181 +0,0 @@ -! This file is an example to test the syntax highlighting file F.xml -! (for fortran 90 and F) - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! THIS IS AN EXAMPLE OF A MODULE ! -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -module module_example - - ! use 'implicit none' when you want all variables to be declared - implicit none - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! PUBLICS AND PRIVATES - - ! In fortran 90 you can define your own operator - public :: operator(.norm.) - public :: operator(+) ! <-- you can also overload the usual operators - public :: factorial - public :: example_fn - - private :: point3d_add - private :: point3d_norm - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! USER-DEFINED TYPES... - - ! This is a definition to use in declarations of real variables, - ! parameters, etc. - integer, parameter, public :: kr = selected_real_kind(10) - - ! This is a user-defined type - type, public :: point3d - real(kind=kr) :: x, y, z - end type point3d - - ! This type is useless: it is only an example of type definition! - type, public :: example_type - complex(kind=kr) :: c ! <-- a complex number (two reals of kind kr)! - real, dimension(-10:10) :: & ! <-- this line does not end here! - r1, r2 ! <-- this is the final part of the previous line - real, pointer, dimension(:) :: pointer_to_array_of_real - real, dimension(:), pointer :: array_of_pointer_to_real - end type example_type - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! INTERFACES... - - ! Interface for the norm of a 3-D vector - interface operator(.norm.) - module procedure point3d_norm - end interface - - ! Interface for the operator '+' - interface operator(+) - module procedure point3d_add - end interface - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! SOME DECLARATIONS... - - ! A real number can be declared with the following line: - real(kind=kr) :: real_var1 - ! But if you are not interested on the precision of floating point numbers, - ! you can use simply: - real :: real_var2 - - ! An array can be declared in two ways: - real(kind=kr), dimension(1:10, -4:5), private :: a, b, c - real(kind=kr), private :: d(1:10, -4:5) - - ! This is a string with fixed lenght - character(len=10) :: str_var - - ! This is an allocatable array, which can be a target of a pointer - type(example_type), private, dimension(:), allocatable, target :: & - many_examples - -! Fortran 90 hasn't got its own preprocessor, it uses the C preprocessor! -#ifdef XXX -c <-- this is a comment in the old fortran 77 style (fixed form) -c This is a free form file, so we shouldn't use this kind of comments! -c But fortran 90 still understands fixed form, when parsing sources with -c the *.f extension. - c ! <-- this 'c' shouldn't be highlighted as a comment! -#endif - -contains - - - ! The sum of two points - pure function point3d_add(a, b) result(rs) - type(point3d) :: rs - type(point3d), intent(in) :: a, b - rs%x = a%x + b%x - rs%y = a%y + b%y - rs%z = a%z + b%z - end function point3d_add - - - ! The norm of a point - pure function point3d_norm(a) result(rs) - real(kind=kr) :: rs - type(point3d), intent(in) :: a - rs = sqrt(a%x * a%x + a%y * a%y + a%z * a%z) - end function point3d_norm - - - ! A simple recursive function - recursive function factorial(i) result (rs) - integer :: rs - integer, intent(in) :: i - if ( i <= 1 ) then - rs = 1 - else - rs = i * factorial(i - 1) - end if - end function factorial - - - ! This is a useless function - subroutine example_fn(int_arg, real_arg, str_arg) - integer, intent(in) :: int_arg - real(kind=kr), intent(out) :: real_arg - character(len=*), intent(in) :: str_arg - - type(example_type), pointer :: p - integer :: n, i, j - logical :: flag - - flag = .true. ! .true. is not an operator! - if ( flag .and. flag ) then ! .and. is a pre-defined operator - print *, "blabla" - end if - - ! Examples of inquiry functions: allocated, lbound, ubound. - if ( .not. allocated(many_examples) ) then - allocate( many_examples(10) ) - end if - print *, "Lower bound = ", lbound(many_examples, 1) - print *, "Upper bound = ", ubound(many_examples, 1) - - p => many_examples(5) ! <-- p is a pointer - - ! A strange way to calculate i*i: add the first i odd numbers - i = 6 - j = 0 - do n = 1, i - j = j + (2*n - 1) - end do - print *, "i*i = ", i*i, j - - real_arg = real(j) ! <-- here the highlighting is not very good: - ! it is unable to distinguish between this and a definition like: - ! real(kind=kr) :: a - deallocate( many_examples ) - end subroutine example_fn - -end module module_example - - -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! THIS IS THE MAIN PROGRAM ! -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -program example - use module_example - - ! this is another example of use of the 'implicit' keyword - implicit double precision (a-h,o-z) - - real(kind=kr) :: var_out - - type(point3d) :: & - a = point3d(0.0_kr, 1.0_kr, 2.0_kr), & - b = point3d(4.0_kr, 5.0_kr, 6.0_kr) - - print *, "a + b = ", .norm. (a + b) - print *, "factorial of 5 = ", factorial(5) - - call example_fn(1, var_out, "hello!") - -end program example diff --git a/part/tests/hl/highlight.glsl b/part/tests/hl/highlight.glsl deleted file mode 100644 index 3495757..0000000 --- a/part/tests/hl/highlight.glsl +++ /dev/null @@ -1,62 +0,0 @@ -// This is a test file for the Katepart GLSL Syntax Highlighting. - -normal text -// this is a single-line comment -normal text -/* this -is a multi-line -comment */ -normal text - -some_symbol.some_member; -some_symbol.some_member_function(); -some_function(); - -// this is a function -void main() -{ - float f = 1.4e3; // decimal float literal - int i1 = 2884; // decimal int literal - int i2 = 0x44; // hex int literal - int i3 = 0456; // octal int literal -} - -// this is a structure -struct some_struct -{ - vec3 some_member_vector; -}; - -# this is -#preprocessor code - -// all keywords -break continue do for while -if else -true false -discard return -struct - -// all basic types -float int void bool -mat2 mat3 mat4 -vec2 vec3 vec4 -ivec2 ivec3 ivec4 -bvec2 bvec3 bvec4 -sampler1D sampler2D sampler3D -samplerCube sampler1DShadow sampler1DShadow - -// all type qualifiers -attribute const uniform varying -in out inout - -// attensions: -// FIXME -// TODO -// BUG - -// some of the std functions -radians degrees sin cos tan asin acos atan - -// some of the std variables -gl_Position gl_PointSize gl_ClipVertex diff --git a/part/tests/hl/highlight.hs b/part/tests/hl/highlight.hs deleted file mode 100644 index 057a3f3..0000000 --- a/part/tests/hl/highlight.hs +++ /dev/null @@ -1,124 +0,0 @@ --- test file for Haskell syntax highlighting in KDE's Kate - --- The test file for literate Haskell can be easily created like this: --- cat highlight.hs | sed -e "s|^|> |" -e "s|> -- ||" -e "s|^> $||" > highlight.lhs --- You only have to manually edit the multi-line comment below. - --- this is a single-line comment - -{- this is a multi-line comment - -Things like "a string" or a 'c' character shouldn't be highlighted in here. - --- I could even start a new --- one-line comment. - --} - --- a data definition - -data Tree a = Br (Tree a) (Tree a) | Leaf a | Nil deriving (Show, Eq) - - --- function definition, "funnyfunction::", "Integer", "Int", "Bool" should be highlighted - -funnyfunction::(Tree a)=>[a]->Integer->Int->Bool - - --- strings and chars --- first line of function definitions (type declaration) should be highlighted - -strangefunction::Int->String -strangefunction 1 = "hello" -strangefunction 2 = "what's up" -strangefunction 3 = (strangefunction 1) ++ ", " ++ (strangefunction 2) -strangefunction 4 = 'a':'b':'c':'"':[] -- will return "abc" -strangefunction 5 = '\n':[] -strangefunction 6 = '\invalidhaskell':[] - --- function name including the single quote character --- and infix operator (`div`) - -justtesting'::Int->Int -justtesting' 2 = 2+1 -justtesting' 9 = 7 `div` 2 - --- same definition as above, slightly different function name and a couple more whitespaces - -justtesting'' :: Int -> Int -justtesting'' 2 = 3 -justtesting'' 9 = 3 + 9 - 9 - --- the following lines are copied out of Haskell's "Prelude.hs" - -infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, % - - --- everything highlighted except the "a" - -class Bounded a where - minBound, maxBound :: a - -class (Num a, Ord a) => Real a where - toRational :: a -> Rational - --- finally, some keyword lists - --- keywords - -case, class, data, deriving, do, else, if, in, infixl, infixr, instance, let, module, of, primitive, -then, type, where - --- infix operators - -quot, rem, div, mod, elem, notElem, seq - --- this stuff is not handled yet - -!!, %, &&, $!, $, *, **, -,., /=, <, <=, =<<, ==, >, >=, >>, >>=, ^, ^^, ++, || - --- functions - -FilePath, IOError, abs, acos, acosh, all, and, any, appendFile, -approxRational, asTypeOf, asin, asinh, atan, atan2, atanh, basicIORun, -break, catch, ceiling, chr, compare, concat, concatMap, const, cos, cosh, -curry, cycle, decodeFloat, denominator, digitToInt, div, divMod, drop, -dropWhile, either, elem, encodeFloat, enumFrom, enumFromThen, -enumFromThenTo, enumFromTo, error, even, exp, exponent, fail, filter, flip, -floatDigits, floatRadix, floatRange, floor, fmap, foldl, foldl1, foldr, -foldr1, fromDouble, fromEnum, fromInt, fromInteger, fromIntegral, -fromRational, fst, gcd, getChar, getContents, getLine, head, id, inRange, -index, init, intToDigit, interact, ioError, isAlpha, isAlphaNum, isAscii, -isControl, isDenormalized, isDigit, isHexDigit, isIEEE, isInfinite, isLower, -isNaN, isNegativeZero, isOctDigit, isPrint, isSpace, isUpper, iterate, last, -lcm, length, lex, lexDigits, lexLitChar, lines, log, logBase, lookup, map, -mapM, mapM_, max, maxBound, maximum, maybe, min, minBound, minimum, mod, -negate, not, notElem, null, numerator, odd, or, ord, otherwise, pi, pred, -primExitWith, print, product, properFraction, putChar, putStr, putStrLn, -quot, quotRem, range, rangeSize, read, readDec, readFile, readFloat, -readHex, readIO, readInt, readList, readLitChar, readLn, readOct, readParen, -readSigned, reads, readsPrec, realToFrac, recip, rem, repeat, replicate, -return, reverse, round, scaleFloat, scanl, scanl1, scanr, scanr1, seq, -sequence, sequence_, show, showChar, showInt, showList, showLitChar, -showParen, showSigned, showString, shows, showsPrec, significand, signum, -sin, sinh, snd, span, splitAt, sqrt, subtract, succ, sum, tail, take, -either, elem, encodeFloat, enumFrom, enumFromThen, enumFromThenTo, -enumFromTo, error, even, exp, exponent, fail, filter, flip, floatDigits, -floatRadix, floatRange, floor, fmap, takeWhile, tan, tanh, threadToIOResult, -toEnum, toInt, toInteger, toLower, toRational, toUpper, truncate, uncurry, -undefined, unlines, until, unwords, unzip, unzip3, userError, words, -writeFile, zip, zip3, zipWith, zipWith3 - --- type constructors - -Bool, Char, Double, Either, Float, IO, Integer, Int, Maybe, Ordering, Rational, Ratio, ReadS, -ShowS, String - --- classes - -Bounded, Enum, Eq, Floating, Fractional, Functor, Integral, Ix, Monad, Num, Ord, Read, RealFloat, -RealFrac, Real, Show - --- data constructors - -EQ, False, GT, Just, LT, Left, Nothing, Right, True diff --git a/part/tests/hl/highlight.jsp b/part/tests/hl/highlight.jsp deleted file mode 100644 index d912836..0000000 --- a/part/tests/hl/highlight.jsp +++ /dev/null @@ -1,170 +0,0 @@ -<%-- - This page won't actually work, as it is simply designed to display jsp syntax highlighting. ---%> -<%@ page info="A Page to Test Kate Jsp Syntax Highlighting" language="java" errorPage="/test-error-page.jsp"%> -<%@ include file="/include/myglobalvars.jsp"%> --%> -<%@ page import="java.util.*, - java.io.*, - java.math.*" %> -<%@ taglib uri="/WEB-INF/lib/si_taglib.tld" prefix="si"%> - - -<% - // We can decipher our expected parameters here. - String parm1 = noNull(request.getParameter(PARAMETER_1)).trim(); - String parm2 = noNull(request.getParameter(PARAMETER_2)).trim(); - String parm3 = noNull(request.getParameter(PARAMETER_3)).trim(); - String parm4 = noNull(request.getParameter(PARAMETER_4)).trim(); - String parm5 = noNull(request.getParameter(PARAMETER_5)).trim(); - - // A sample collection of Integers to display some code folding. - List intList = getIntList(10); - - -%> - - A Sample Jsp - - - - - <%-- The top label table. --%> - - - - -
The following parameters were detected:
- - <%-- Display the parameters which might have been passed in. --%> - - <%-- Label; Actual Parameter String; Value Detected --%> - - - - - - - <%-- Label; Actual Parameter String; Value Detected --%> - - - - - - - <%-- Label; Actual Parameter String; Value Detected --%> - - - - - - - <%-- Label; Actual Parameter String; Value Detected --%> - - - - - - - <%-- Label; Actual Parameter String; Value Detected --%> - - - - - -
PARAMETER_1<%=PARAMETER_1%>"<%=parm1%>"
PARAMETER_2<%=PARAMETER_2%>"<%=parm2%>"
PARAMETER_3<%=PARAMETER_3%>"<%=parm3%>"
PARAMETER_4<%=PARAMETER_4%>"<%=parm4%>"
PARAMETER_5<%=PARAMETER_5%>"<%=parm5%>"
- -

- - <%-- Display our list of random Integers (shows code folding). --%> - -<% - if (intList != null && intList.size() > 0) { -%> - -<% - Iterator intListIt = intList.iterator(); - while (intListIt.hasNext()) { - Integer i = (Integer) intListIt.next(); -%> - -<% - } - } else { -%> - -<% - } -%> -
Here are the elements of intList...
<%=i.toString()%>
Oooops, we forgot to initialize intList!
- -

- - <%-- We can call javascript functions. --%> - - - - - - -
Test our javascript...
- -

- <%-- If we actually had defined a tag library. --%> - - -
- - - - -
- -

- <%-- Expression language. --%> - - - - - - -
myParam's value: ""
- - -<%! - /* A place for class variables and functions... */ - - // Define some sample parameter names that this page might understand. - private static final String PARAMETER_1 = "p1"; - private static final String PARAMETER_2 = "p2"; - private static final String PARAMETER_3 = "p3"; - private static final String PARAMETER_4 = "p4"; - private static final String PARAMETER_5 = "p5"; - - // Returns str trimmed, or an empty string if str is null. - private static String noNull(String str) { - String retStr; - if (str == null) - retStr = ""; - else - retStr = str.trim(); - - return retStr; - } - - // Returns a list of Integers with listSize elements. - private static List getIntList(int listSize) { - ArrayList retList = new ArrayList(listSize); - for (int i = 0; i < listSize; i++) - retList.add(new Integer( (int) (Math.random() * 100) )); - - return retList; - } -%> \ No newline at end of file diff --git a/part/tests/hl/highlight.lex b/part/tests/hl/highlight.lex deleted file mode 100644 index 33527bd..0000000 --- a/part/tests/hl/highlight.lex +++ /dev/null @@ -1,82 +0,0 @@ -/* This test file tests kates Lex/Flex highlighting */ - -%option c++ -%option yyclass="KateTester" -%option yylineno - - /* This is a C(++) comment */ - -/* This one is a lex comment ! */ - -%{ -#include -#include "realparser.hpp" -using namespace std; -%} - -/* Some definitions */ -DIGIT [0-9] -LETTER [_a-zA-Z] - -%% - - /* Comment *shall be indented here* */ -[ \t\n\r]+ - - /* Note: there is a bad } just here vvv */ -\/\*([^\*]|\*[^/])*\*\/ { foo(a, b, c); } } - - /* A start condition scope... */ -{ - "a" { - - /* C mode ! */ - return 0; -} - - "b" %{ - - /* C mode, too ! */ - return 0; -%} - - "c" return 0; // C++ comment -} - - /* Big rule */ -\"([^"\\]|\\.)*\" { - - yylval.string_val = new char[strlen(yytext) + 1]; - int j = 0, i = 1; - - while (yytext[i] != '"') - if (yytext[i] != '\\') - yylval.string_val[j++] = yytext[i++]; - else - switch (yytext[i + 1]) - { - case 'n': - yylval.string_val[j++] = '\n'; i += 2; - break; - default: - yylval.string_val[j++] << yytext[i + 1], i += 2; - } - - yylval.string_val[j] = 0; - return TOK_STRING; - -} - - /* Dot (match all) */ -. {return yylval.int_val = yytext[0];} - -%% - -// Here is pure C(++) -#include - -int main(void) -{ - std::cout << "Hello, World\n"; - return 0; -} diff --git a/part/tests/hl/highlight.lhs b/part/tests/hl/highlight.lhs deleted file mode 100644 index 9dc52e5..0000000 --- a/part/tests/hl/highlight.lhs +++ /dev/null @@ -1,124 +0,0 @@ -test file for Haskell syntax highlighting in KDE's Kate - -The test file for literate Haskell can be easily created like this: - cat highlight.hs | sed -e "s|^|> |" -e "s|> -- ||" -e "s|^> $||" > highlight.lhs -You only have to manually edit the multi-line comment below. - -this is a single-line comment - -{- this is a multi-line comment - -Things like "a string" or a 'c' character shouldn't be highlighted in here. - -I could even start a new -one-line comment. - --} - -a data definition - -> data Tree a = Br (Tree a) (Tree a) | Leaf a | Nil deriving (Show, Eq) - - -function definition, "funnyfunction::", "Integer", "Int", "Bool" should be highlighted - -> funnyfunction::(Tree a)=>[a]->Integer->Int->Bool - - -strings and chars -first line of function definitions (type declaration) should be highlighted - -> strangefunction::Int->String -> strangefunction 1 = "hello" -> strangefunction 2 = "what's up" -> strangefunction 3 = (strangefunction 1) ++ ", " ++ (strangefunction 2) -> strangefunction 4 = 'a':'b':'c':'"':[] -- will return "abc" -> strangefunction 5 = '\n':[] -> strangefunction 6 = '\invalidhaskell':[] - -function name including the single quote character -and infix operator (`div`) - -> justtesting'::Int->Int -> justtesting' 2 = 2+1 -> justtesting' 9 = 7 `div` 2 - -same definition as above, slightly different function name and a couple more whitespaces - -> justtesting'' :: Int -> Int -> justtesting'' 2 = 3 -> justtesting'' 9 = 3 + 9 - 9 - -the following lines are copied out of Haskell's "Prelude.hs" - -> infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, % - - -everything highlighted except the "a" - -> class Bounded a where -> minBound, maxBound :: a - -> class (Num a, Ord a) => Real a where -> toRational :: a -> Rational - -finally, some keyword lists - -keywords - -> case, class, data, deriving, do, else, if, in, infixl, infixr, instance, let, module, of, primitive, -> then, type, where - -infix operators - -> quot, rem, div, mod, elem, notElem, seq - -this stuff is not handled yet - -> !!, %, &&, $!, $, *, **, -,., /=, <, <=, =<<, ==, >, >=, >>, >>=, ^, ^^, ++, || - -functions - -> FilePath, IOError, abs, acos, acosh, all, and, any, appendFile, -> approxRational, asTypeOf, asin, asinh, atan, atan2, atanh, basicIORun, -> break, catch, ceiling, chr, compare, concat, concatMap, const, cos, cosh, -> curry, cycle, decodeFloat, denominator, digitToInt, div, divMod, drop, -> dropWhile, either, elem, encodeFloat, enumFrom, enumFromThen, -> enumFromThenTo, enumFromTo, error, even, exp, exponent, fail, filter, flip, -> floatDigits, floatRadix, floatRange, floor, fmap, foldl, foldl1, foldr, -> foldr1, fromDouble, fromEnum, fromInt, fromInteger, fromIntegral, -> fromRational, fst, gcd, getChar, getContents, getLine, head, id, inRange, -> index, init, intToDigit, interact, ioError, isAlpha, isAlphaNum, isAscii, -> isControl, isDenormalized, isDigit, isHexDigit, isIEEE, isInfinite, isLower, -> isNaN, isNegativeZero, isOctDigit, isPrint, isSpace, isUpper, iterate, last, -> lcm, length, lex, lexDigits, lexLitChar, lines, log, logBase, lookup, map, -> mapM, mapM_, max, maxBound, maximum, maybe, min, minBound, minimum, mod, -> negate, not, notElem, null, numerator, odd, or, ord, otherwise, pi, pred, -> primExitWith, print, product, properFraction, putChar, putStr, putStrLn, -> quot, quotRem, range, rangeSize, read, readDec, readFile, readFloat, -> readHex, readIO, readInt, readList, readLitChar, readLn, readOct, readParen, -> readSigned, reads, readsPrec, realToFrac, recip, rem, repeat, replicate, -> return, reverse, round, scaleFloat, scanl, scanl1, scanr, scanr1, seq, -> sequence, sequence_, show, showChar, showInt, showList, showLitChar, -> showParen, showSigned, showString, shows, showsPrec, significand, signum, -> sin, sinh, snd, span, splitAt, sqrt, subtract, succ, sum, tail, take, -> either, elem, encodeFloat, enumFrom, enumFromThen, enumFromThenTo, -> enumFromTo, error, even, exp, exponent, fail, filter, flip, floatDigits, -> floatRadix, floatRange, floor, fmap, takeWhile, tan, tanh, threadToIOResult, -> toEnum, toInt, toInteger, toLower, toRational, toUpper, truncate, uncurry, -> undefined, unlines, until, unwords, unzip, unzip3, userError, words, -> writeFile, zip, zip3, zipWith, zipWith3 - -type constructors - -> Bool, Char, Double, Either, Float, IO, Integer, Int, Maybe, Ordering, Rational, Ratio, ReadS, -> ShowS, String - -classes - -> Bounded, Enum, Eq, Floating, Fractional, Functor, Integral, Ix, Monad, Num, Ord, Read, RealFloat, -> RealFrac, Real, Show - -data constructors - -> EQ, False, GT, Just, LT, Left, Nothing, Right, True diff --git a/part/tests/hl/highlight.lisp b/part/tests/hl/highlight.lisp deleted file mode 100644 index e86c85f..0000000 --- a/part/tests/hl/highlight.lisp +++ /dev/null @@ -1,36 +0,0 @@ -;; This test file tests kates common lisp highlighting -#| -multilinecomment :) -|# - -;BEGIN region marker - -;END end - -(defun bin-search (obj vec) - (let ((len (length vec))) - (and (not (zerop len)) - (finder obj vec 0 (- len 1))))) - -(defun parse-date (str) - (let ((toks (tokens str #'constituent 0))) - (list (parse-integer (first toks)) - (parse-month (second toks)) - (parse-integer (third toks))))) - -(defconstant month-names - #("jan" "feb" "mar" "apr" "may" "jun" - "jul" "aug" "sep" "oct" "nov" "dec")) - -(defstruct buf - vec (start -1) (used -1) (new -1) (end -1)) - -(defparameter *words* (make-hash-table :size 10000)) - -(defmacro while (test &rest body) - `(do () - ((not ,test)) - ,@body)) - -(define-modify-macro append1f (val) - (lambda (lst val) (append lst (list val)))) diff --git a/part/tests/hl/highlight.ly b/part/tests/hl/highlight.ly deleted file mode 100644 index 29aa7a6..0000000 --- a/part/tests/hl/highlight.ly +++ /dev/null @@ -1,114 +0,0 @@ -% This is a file to test the Lilypond highlighting features of Katepart. -% This is NOT a valid lilypond file, because it also shows the -% highlighting of some invalid lilypond constructs! -% This is a line comment. - -%{ -this is a block comment, that can occur inside a line, or across -multiple lines. -%} - -\header { - title = "Katepart Lilypond syntax highlighting test file" - composer = %{"Wilbert Berendsen"%} "Anonymus" - poet = "The KDE team" - opus = "1" - copyright = "Share and enjoy!" -} - -\paper { - #(set-paper-size "a4") % a hash introduces scheme - indent = 0 % recognize variable names inside \paper, \layout etc. - between-system-space = 3\mm -} - -\layout { - \context { - \Score - \remove Bar_number_engraver % recognize engraver names - \remove "Bar_number_engraver" % also when quoted! - } -} - -% { and << block are folded -\score { - \new StaffGroup << - \new ChordNames \chordmode { c2sus4/f g2/d c1 } - \new Staff \new Voice ="mel" { - \key f \major - \time 4/4 - \partial 4 - \set Staff.instrumentName = "Bla." - \once \override Staff.NoteHead #'color = #red - % dynamics, articulations and markup - c8\p d\< e-. f-> g a\f c-5\markup {Hoi} - \notemode { c d e f } - \repeat volta 2 { - % complex durations are highlighted: - g4*2/3 - } - \times 2/3 {e8 f g} - % there is some error checking: - % often made mistake to have octavemarks after the duration: - c2' - % invalid durations are caught: - g3 - } - \context Lyrics \lyricsto "mel" { - \set fontSize = #1 - this is a line of ly -- rics. - with4 dur -- a -- tions.2. - % errors like forgetting spaces are found: - space-- flight %{i.s.o.%} space -- flight - space at end for -- got -- ten as well.} - - \new DrumStaff \drummode { hihat4 bassdrum8 } - \new FiguredBass \figuremode { - <5 4>8 <6-> - } - >> - \midi { - \context { - \Score - tempoWholesPerMinute = #(ly:make-moment 60 2) - } - } -} - -av = #(define-music-function (parser location voice) -(string?) -; scheme comments are recognized in scheme -; Lilypond inside scheme works as well: -#{ - \set associatedVoice = $voice -#}) - - - - -% inside scheme some elements are highlighted: -#(define (naturalise-pitch p) - (let* ((o (ly:pitch-octave p)) - (a (* 4 (ly:pitch-alteration p))) - (n (ly:pitch-notename p))) - (bla 'ArticulationEvent 'ChoirStaff) - (cond - ((> a 2) (set! a (- a 4)) (set! n (+ n 1))) - ((< a -2) (set! a (+ a 4)) (set! n (- n 1)))) - - (if (< n 0) (begin (set! o (- o 1)) (set! n (+ n 7)))) - (if (> n 6) (begin (set! o (+ o 1)) (set! n (- n 7)))) - - (ly:make-pitch o n (/ a 4)))) - -% markup is also highlighted -\markup { - \line { - text test Voice Staff % note Lilypond keywords are not highlighted here - } - \score { \relative c' { 2( d) } } - \italic bla - \override #'(baseline-skip . 2) { - \underline blu - } -} diff --git a/part/tests/hl/highlight.m b/part/tests/hl/highlight.m deleted file mode 100644 index f240138..0000000 --- a/part/tests/hl/highlight.m +++ /dev/null @@ -1,61 +0,0 @@ -%%===================================================== -% MATLAB test code for Kate/Kwrite syntax highlighting -% kate: hl Matlab -%%===================================================== - -% Numbers _____________________________________________ -5, 5.5, .1, 0.1, 0.4e5, 1.2e-5, 5i, 5.3i, 6j, .345+3i -5', 5.5', .1', 0.1', 0.4e5', 1.2e-5', 5i', 5.3i', 6j', .345+3i' - -% Operators ___________________________________________ -% relational operators -'asdf'~=4, c<=4, d>=4, ab, a==b, b||c, b&&c -% elementwise arithmetic operators -a.^b, a.*b a./b, 1:4:5 -% single-character binary arithmetic -a+3, a-3, a*2, a^3, a/3, a\3, a|b, a&b -% unary operators -a = ~g; g = @sfdgdsf(sdfsd,345); g.' + 1i.' - ('asdf').' -% separators and delimiter -(asd),[sadf];{asdf},;;,;;;() -% continuation -a = 1+ ... - 2; - -% Strings and adjoint _________________________________ -% incomplete strings -'string -'str'' -'str''ing -% complete strings -'string' % simple string -'''' % string containing ' -'str''ing' % one string containing ' -'string' 'string' % two strings -'asdf' 'asdf''' variable % two strings and a variable -'asdf''asdf'' fsgdfg' + (asdf)' - 'asdf'.' + []''''.';'' -'sadf'.' % string transpose -% adjoint -{'asdf'}' + 1 -('asdf')' + 1 -['asdf']' + 1 -'' var''' % empty string, var with >1 adjoints -[5]'*{5}'*('asd')'.'+(5)'*6'*asdf'*asdf'.' % many adjoints -A'*B + 1 % adjoint -A.'*B + 1 % transpose -A.'.'*B + 1 % double transpose -A'.' + 1 % adjoint, then transpose -A.'' % transpose, then adjoint - -% System command ______________________________________ -!hostname -!cp * /tmp - -% Reserved keywords ___________________________________ -function, persistent, global -switch, case, otherwise -if, else, elseif -try, catch -for, while, break, continue -end, return -function, FUNCTION, Function % case sensitive! \ No newline at end of file diff --git a/part/tests/hl/highlight.mac b/part/tests/hl/highlight.mac deleted file mode 100644 index 7db47b5..0000000 --- a/part/tests/hl/highlight.mac +++ /dev/null @@ -1,1828 +0,0 @@ -/* ------------------------------------------------------------------------- -Efficient Galois Fields in Maxima - -by Alasdair McAndrew -and later extended by Fabrizio Caruso and Jacopo Daurizio - -it is distribuited together with gf_roots by Jacopo Daurizio - -Authors: - -Fabrizio Caruso (optimizations, testing) -Jacopo D'Aurizio (optimizations, modular roots) -Alasdair McAndrew (original version of the package, pohlig-helman log, etc... ) -------------------------------------------------------------------------*/ - -/* Released under terms of the GNU General Public License, version 2, - * by permission of the authors to Robert Dodier circa 2007-12-02. - */ - -/* Defines a flag for dealing with large fields. If it is set to "false", -then lookup tables are used for exponentiation and logarithms. Otherwise -other algorithms are used */ - -define_variable(largefield,true,bool)$ -define_variable(gf_char,0,integer)$ -define_variable(gf_exp,0,integer)$ -define_variable(gf_order,0,integer)$ -define_variable (gf_one, 'gf_one, any_check)$ -define_variable (gf_prim, 'gf_prim, any_check)$ -define_variable (gf_irr, 'gf_irr, any_check)$ -define_variable (gf_list, 'gf_list, any_check)$ -define_variable (gen_powers, 'gf_list, any_check)$ -remvalue(x,z,gf_char,gf_exp,gf_irr,pg,gp,lg,gf_prim,gf_one,gf_order,gf_list,gen_powers)$ - - -/* --------------------------------------------------------------------------------------------- */ -/* Settings */ - -GF_VERBOSE:false; /* Verbosity */ -GF_WARNING: true; /* Warnings */ -GF_IRREDUCIBILITY_CHECK:false; /* Irreducibility test for the minimal polynomial of the extension */ - -/* ------------------------------------------------------------------------------------------------- */ - - -/* It defines a new current field with gf_char=b, min. pol.= p of deg= e*/ -gf_set([ars]):=block([gj,m,i,j,dg], - if length(ars)=1 then - ( - gf_setp(ars[1]), - return(true) - ) - else - ( - if length(ars)=2 then - ( - if numberp(ars[2]) then - ( - if ars[2]=0 and GF_WARNING then - ( - print("WARNING: the irreducible is zero! We assume GF(",ars[1],")"), - gf_setp(ars[1]), - return(true) - ) - else - ( - error("ERROR: you tried to extend with a non-zero constant!"), - return(false) - ) - ) - else - ( - dg:hipow(ars[2],x), - - if dg=1 then - gf_setp(ars[1]), - gf_irr:ars[2], - gf_exp:dg, - return(true) - ) - ) - else - ( - gf_exp:ars[2], - if gf_exp=1 then - ( - gf_setp(ars[1]), - gf_irr:rat(ars[3]), - return(true) - ), - gf_irr:rat(ars[3]) - ) - ), - - gf_char:ars[1], - gf_one:rat(1,x), - gf_order:gf_char^gf_exp-1, - - m:makelist(coeff(gf_irr,x,i),i,0,gf_exp), - gf_list:[[first(m),0]],j:1, - for i:2 thru gf_exp+1 do if m[i]=0 then j:j+1 else ( gf_list:endcons([m[i],j],gf_list), j:1 ), - - if not(primep(gf_char)) then error("ERROR: Gf_Char must be a prime number.") - else - modulus:gf_char, - if GF_IRREDUCIBILITY_CHECK and - hipow(args(factor(ars[3]))[1],x)#hipow(rat(ars[3]),x) then - error("ERROR: Polynomial is not irreducible"), - - if not(largefield) then - ( - pg:mkpowers(), - lg:mklogs() - ) - else - ( - if GF_VERBOSE then - print("finding a primitive element..."), - - gf_prim:rat(gf_findprim(),x), - if GF_VERBOSE then - print("...primitive element found.") - - ), - modulus:false, /* it resets the modulus */ - return(true) - - )$ - - -/* Prints out information about the field */ -gf_info():=block( - print("Prime gf_char value: ",gf_char), - print("Exponent: ", gf_exp), - print("Multiplicative order: ",gf_order), - print("Irreducible polynomial: ",gf_irr), - print("Primitive element: ",gf_prim), - if (largefield) then - print("Largefield flag is true; powers and logarithms not computed.") - else - print("Largefield flag is false; powers and logarithms computed."), - disp() -)$ - - -/* To test irreducibility, use factor! */ -/* modulus:prime; */ -/* px: x^n+.....; */ -/* if first(args(factor(px)))=(x^n) then ... */ - -/* isprimitive(p):=block([power:gf_char^gf_exp-1,flag1:false,flag2:false,f,fl,m], - if remainder(x^power-1,p)=0 then flag1:true, - f:ifactors(power), - fl:makelist(f[i][1],i,1,length(f)), - m:makelist(remainder(x^(power/fl[i])-1,p),i,1,length(f)), - if not(member(0,m)) then flag2:true, - return(flag1 and flag2) - )$ */ - - -/* Returns all coefficients of a polynomial, as a list of designated length. -The elements of the list are values in the range 0, 1, 2, ..., gf_char-1. */ -coeffs(poly,n):=block([m:makelist(coeff(poly,x,n-i),i,0,n)], - return(maplist(lambda([x],mod(x,gf_char)),m)) - )$ - - -/* Turns a list into a number, by treating the elements of the list as -coefficients of a polynomial */ - - -list2num(l,n):=block([ln:length(l)],sum(l[i]*n^(ln-i),i,1,ln))$ - - -/* Turns a polynomial into a number by evaluating it for the gf_char value */ -poly2num(p):=subst(gf_char,x,p); - - -/* Turns a number into a list, where the elements of the list are the "digits" -of the number in gf_char b */ -num2list(n,b):=block([lst:[],a:n], - for i:1 while a#0 do ( - lst:cons(?mod(a,b),lst), - a:(a-lst[1])/b - ), - return(lst) -); - - -rnum2list(n,b):=block([lst:[],a:n], - for i:1 while a#0 do ( - lst:endcons(?mod(a,b),lst), - a:(a-last(lst))/b - ), - return(lst) -); - - -/* Returns a polynomial in x whose coefficients are given by the list */ -list2poly(l):=block([s:length(l)], - return(sum(l[i]*x^(s-i),i,1,s))); - -poly2list(poly):=block([i,s:hipow(poly,x)], - return(makelist(coeff(poly,x,s-i),i,0,s))); - - -/* Turns a number into a polynomial - this is the inverse of the poly2num command */ -num2poly(n):=list2poly(num2list(n,gf_char)); - - -/* Creates a power table for the field, where the i-th element is the numerical -equivalent of the field element e^i, where e is a primitive element */ -mkpowers():=block([poly], - if not(largefield) then - gf_prim:gf_findprim(), - gp:makelist(0,i,1,gf_order), - gp[1]:1, - poly:1, - for i:2 thru gf_order do - ( - poly:gf_eval(fasttimes(gf_prim,poly)), - gp[i]:poly2num(list2poly(coeffs(poly,gf_exp))) - ), - return(gp) - ); - - -/* Creates a log table: the inverse lookup of the power table */ -mklogs():=block([lg:makelist(0,i,1,gf_order)], - for i:2 thru gf_order do lg[gp[i]]:i-1, - return(lg) - ); - - -/* Calculates powers using the standard "repeated squaring" algorithm */ -gf_binpower(p,n):=block([t:gf_one,ln], - ln : ?integer\-length(n), p:rat(p,x), - for i:1 thru ln do ( - if ?logbitp(ln-i,n) then t:gf_eval(fasttimes(gf_eval(fasttimes(t,t)),p)) - else t:gf_eval(fasttimes(t,t)) - ), - return(t) - ); - - -/* Creates an array of couples [a!, 1/(a!)] mod p */ -fact_array(p):=block([i,v2], -v2:make_array(fixnum,p,2), -for i:0 thru (p-2) do (v2[i,0]:1,v2[i,1]:1), -v2[p-1,0]:-1,v2[p-1,1]:-1, -if (p>3) then ( - for i:2 thru (p-1) do v2[i,0]: mod(i*v2[i-1,0],p), - for i:2 thru (p-2) do v2[i,1]: mod(((-1)^(p-i))*v2[p-i-1,0],p) -), -return(v2) -); - - -/* Calculates the product a(a+1)(a+2)...(b-1)b in Z_p */ -p_prod(a,b,p):=block([i,j,k,s], -if ((a=1) and (b=0)) then return(1), -if (a=b) then return(mod(a,p)), -if ((a=1) and (b=p-1)) then return(p-1), -if ((a=2) and (b=p-1)) then return(p-1), -s:1, -for i:a thru b do s:mod(s*i,p), -return(s) -); - - -/* Calculates (n!)^(-1) in Z_p using Wilson Theorem */ -/* This algorithm DOES NOT require explicit inversion through gcd() */ -inverse_fact(n,p):=block([i,j,k], -if ((n=0) or (n=1)) then return(1), -if (n=p-1) then return(p-1), -return(mod(-p_prod(n+1,p-1,p),p)) -); - - -/* Calculates the maximum exponent s for which p^s divides n! */ -max_pow(n,p):= block([i,j,k,s], -if (nmax_pow(n,p)) then return(0), -a:mod(n,p), na:mod(floor(n/p),2), -b:mod(m,p), nb:mod(floor(m/p),2), -c:mod(m-n,p), nc:mod(floor((m-n)/p),2), -return(?mod(p_prod(1,b,p)*inverse_fact(a,p)*inverse_fact(c,p)*(-1)^(na+nb+nc),p)) -); - - -/* p_powers(p)[a+1][b+1] = a^b in Z_p */ -p_powers(p):=block([i,j,k,l,v2:makelist(makelist(1,i,1,p),i,1,p)], -for i:1 thru p do v2[i][1]:1, -for i:1 thru p do v2[i][2]:i-1, -for i:1 thru p do v2[i][p]:1, -v2[1][1]:0, -v2[1][p]:0, -if (p>4) then - ( - for j:3 thru p-1 do - ( - for i:1 thru p do - v2[i][j]:?mod((i-1)*v2[i][j-1],p) - ) - ), -return(v2) -); - - -/* p_thagora[a+1][b+1] = a*b in Z_p */ -p_thagora(p):=block([i,j,k,l,v3:makelist(makelist(1,i,1,p),i,1,p)], - for j:1 thru p do v3[1][j]:0, - for j:1 thru p do v3[j][1]:0, - for j:1 thru p do v3[2][j]:j-1, - for j:1 thru p do v3[j][2]:j-1, - if (p>3) then - for j:3 thru p do ( - for i:3 thru p do v3[i][j]:?mod((i-1)+v3[i][j-1],p) - ), -return(v3) -); - - -/* Creates an array of polynomials x^(gf_char^h) with 0<=hmax) then max:ps[i], - rmatrix:zeromatrix(nf,max), - for i:1 thru nf do - ( - rmatrix[i,1]:1,rmatrix[i,2]:gf_binpower(a,order/ps[i]), - for j:3 thru ps[i] do - rmatrix[i,j]:gf_eval(fasttimes(rmatrix[i,j-1],rmatrix[i,2])) - ), - as:makelist(0,i,1,nf), - ms:makelist(0,i,1,nf), - for i:1 thru nf do - ( - b:makelist(p,j,1,alpha[i]), - xs:makelist(0,j,1,alpha[i]), - sum:0, - for j:1 thru alpha[i] do - ( - b[j]:gf_div(p,gf_binpower(a,sum)), - power:gf_binpower(b[j],order/(ps[i])^j),k:1,flag:true, - while k<=ps[i] and flag do (if(rmatrix[i,k]=power) then (xs[j]:k-1,flag:false), k:k+1), - sum:sum+xs[j]*ps[i]^(j-1) - ), - as[i]:sum, - ms[i]:ps[i]^alpha[i] - ), - return(chrem(as,ms)) - ); - - - -/* Routines related to polynomials over finite fields */ -polygf_eval(gf_elem,varname) := - sum(gf_eval(ratcoeff(rat(gf_elem,varname),varname,i))*varname^i, - i,0,hipow(gf_elem,varname)); - - - -/* Pohlig Hellmann with Pollard Rho algorithm */ -jump(poly,polyl1,polyl2,ele,gen,order):= - block([s:mod(ratsubst(0,x,poly),3)], - if s=1 then - ( - poly:gf_eval(fasttimes(poly,gen)), - polyl2:polyl2+1 - ) - else - if s=2 then - ( - poly:gf_eval(fasttimes(poly,poly)), - polyl1:?ash(polyl1,1), polyl2:?ash(polyl2,1) - ) - else - ( - poly:gf_eval(fasttimes(ele,poly)), - polyl1:polyl1+1 - ), - return([poly,polyl1,polyl2]) - ); - - -kang(ele,gen,order):= - block( - [newl1:0,newl2:0,oldl1:0,oldl2:0,new:rat(1,x),old:rat(1,x), - diff1,diff2,ll,unflag:true,index:true], - if (ele=1) then - return(0), - if (ele=gen) then - return(1), - while unflag do - ( - ll:jump(new,newl1,newl2,ele,gen,order), - new:first(ll), - newl1:second(ll), - newl2:last(ll), - index:not(index), - if index then - ( - ll:jump(old,oldl1,oldl2,ele,gen,order), - old:first(ll), - oldl1:second(ll), - oldl2:third(ll) - ), - - diff1:?mod(newl1-oldl1,order), - diff2:?mod(newl2-oldl2,order), - if (diff1#0 or diff2#0) and gf_eval(old-new)=0 then - unflag:false - ), - /* print(ele," ",gen," - collision found with ",eg), */ - /* if (a=0) then error("Zero") else */ - return(mod(-diff2*inv_mod(diff1,order),order)) - ); - - -gf_ind(some):= - if some=0 then - ( - if GF_WARNING then - ( - print("WARNING: logarithm of zero"), - -inf - ) - ) - else - ( - if some=1 then - 0 - else - ( - if gf_exp>1 then - kang_log(some) - else - kang_logp(some) - ) - ); - - -kang_log(some):= - block( - [f,primes,multiplicity,ilist:[],i,j,len,p,t,a,gen,ord,q], - f:ifactors(gf_order), - primes:map(first,f), - multiplicity:map(last,f), - len:length(multiplicity), - some:rat(some,x), - for i:1 thru len do /* ciclo per ogni primo */ - ( - p:primes[i], - gen:gf_binpower(gf_prim,gf_order/p), - t:rat(some,x), ord:0, - for j:1 thru multiplicity[i] do /* Hensel Lifting */ - ( - q:p^(j-1), - a:kang(gf_binpower(t,gf_order/(p*q)),gen,p), - ord:ord+a*q, - t:gf_eval(fasttimes(some,gf_inv(gf_binpower(gf_prim,ord)))) - ), - ilist:endcons(ord,ilist) - ), - if GF_VERBOSE then - print(ilist), - return(chrem(ilist,map(lambda([x],first(x)^last(x)),f))) -); - - -/* Complessita' : detta C la cardinalita' del campo, si hanno in media Osoft(C^(1/t)) operazioni, */ -/* dove t=log(C)/log(q), dove q e' il piu' grande primo che divide C */ -/* diff1,diff2,ll, --- allocare o non allocare? non cambia niente, sembra */ - - -/* Berlekamp-Massey Algorithm */ -bm(seq):= - block( - [m:length(seq),r,r0,r1,v,v0:rat(0,x),v1:rat(1,x),q,h,d,p], - r0:rat(x^m), - r1:rat(sum(seq[i]*x^(i-1),i,1,m)), - h:hipow(r1,x), - while (2*h>=m) do - ( - d:divide(r0,r1,x), - q:rat(first(d),x), - r:rat(last(d),x), - v:rat(v0-q*v1), - v0:v1, - v1:v, - r0:r1, - r1:r, - h:hipow(r1,x) - ), - d:max(1+h,hipow(v1,x)), - p:rat((x^d)*ratsubst(1/x,x,v1)), - h:hipow(p,x), - return(rat(p/coeff(p,x,h))) - ); - - -/* Generator for Fp --- semplice ma abbastanza inefficiente */ -fpgen(p):=block([unflag:true,n:2,t:x^(p-1)], modulus:p, - while unflag do if first(args(factor(t-n)))=t then unflag:false else n:n+1, - modulus:false, return(n)); - - - -/* Questa e' meglio, ma il bieco trucco di bypassare gf_char e' un po' zozzo */ -/* gf_gen */ -gf_findprimp(p):= - block( - [primes:map(first,ifactors(p-1)),len,unfound:true,unflag:true,i,b:2,og], - len:length(primes), - og:gf_char, - gf_char:p, - while unfound do - ( - i:1, - while i<=len and ffastpower(b,(p-1)/primes[i])#1 do - i:i+1, - if i=(len+1) then - unfound:false - else - b:next_prime(b) - ), - gf_char:og, - return(b) - ); - - -/* Questa e' meglio, ma il bieco trucco di bypassare gf_char e' un po' zozzo */ -/* gf_ggen */ -gf_findprimp_alt(p):= - block([primes:map(first,ifactors(p-1)), - len,unfound:true,unflag:true,i,b:prev_prime(p),og], - len:length(primes), - og:gf_char, - gf_char:p, - while unfound do - ( - i:1, - while i<=len and ffastpower(b,(p-1)/primes[i])#1 do - i:i+1, - if i=(len+1) then - unfound:false - else - b:prev_prime(b) - ), - gf_char:og, - return(b) - ); - - - -gf_isprimp(a):= if a=0 then false else gf_isgen(a,gf_char); -/* Check if a has maxmimum multiplicative order in F_p */ - -/* gf_isgen */ -gf_isgen(a,p):= - block([primes:map(first,ifactors(p-1)),len,i:1,temp], - temp:gf_char, gf_char:p, len:length(primes), - while i<=len and ffastpower(a,(p-1)/primes[i])#1 do - i:i+1, - gf_char:temp, - if i=(len+1) then - return(true) - else - return(false) - ); - - -/* ricerca binaria in una lista ordinata crescente - complessità massima ?integer\-length(length(list)) accessi */ -/* l'allocazione di liste non è ancora abbastanza efficiente da permettere un'implementazione parziale di un crivello ... */ -/* comunque può essere utilizzata per accelerare il gf_ind originario */ -binsearch(elem,list):= - block( - [l:length(list),l2,check,pos,k:1,j], - l2:?integer\-length(l)-1, - if GF_VERBOSE then - print(l2), - pos:?ash(2,l2-1), - while kl) then - ( - pos:pos-?ash(2,l2-k)+?ash(2,l2-k-1), - k:k+1 - ) - else - ( - check:list[pos], - if check=elem then - return(pos) - else - if check>elem then - pos:pos-?ash(2,l2-k)+?ash(2,l2-k-1) - else - if check x*p(x) (mod x^3+bx+a) */ - /* (0 1 0) It uses only 3 parameters (F_22,F_23,F_32) */ - /* that are sufficient to completely describe F^j for any j; */ - /* it returns (F^m)_22, corresponding to the evaluation of */ - /* x^m (mod x^3+bx+a) */ - /* in x=0. */ - f3power(a,b,p,m):= - block([v_22:1,v_23:0,v_32:0, - w_22:1,w_23:0,w_32:0, - c,i,j,k,l,n,index], - if m=0 then - return(1), - b:polymod(b,p), - a:polymod(a,p), - c:inv_mod(-a,p), - j:?integer\-length(m), - for i:1 thru j do - ( - k:polymod(v_23+b*v_32,p), - l:polymod(?ash(v_22,1),p), - if ?logbitp(j-i,m) then - ( - n : polymod(a*v_32,p), - w_22 : polymod(l*v_23-n*v_32,p), - w_32 : polymod(v_32*(k+v_23)+v_22*v_22,p), - w_23 : polymod(k*k-l*n-b*w_32,p) - ) - else - ( - w_22 : polymod(v_32*(k+v_23)+v_22*v_22,p), - w_23 : polymod(l*v_23-a*v_32*v_32,p), - w_32 : polymod(l*v_32+c*k*k,p) - ), - v_22:w_22, - v_23:w_23, - v_32:w_32 - ), - return(v_22) - )$ - - - /* This subroutine returns (1 0) A^(m) (1 0) mod p, where */ - /* ( 0 -a ) */ - /* A = ( 1 -b ) */ - /* i.e the m-th term of the recurrence */ - /* A_0 = 1, A_1 = 0, A_{n+2} = -b A_{n+1} - a A_{n} */ - /* with characteristic polynomial x^2 + b x + a */ - f2power(a,b,p,m):=block([v_11:0,v_21:1,w_11,w_21,u,v,i,index], - /* if m<2 then return(1-m), */ - /* b:polymod(b,p),a:polymod(a,p), */ - index:?integer\-length(m), - for i:2 thru index do - ( - if ?logbitp(index-i,m) then - ( - u:-a*v_21, - v:v_11-b*v_21, - w_11: polymod(u*(v+v_11),p), - w_21: polymod(v*v+v_21*u,p) - ) - else - ( - u:v_11*v_11, v:v_21*v_21, - w_11: polymod(u-a*v,p), - w_21: polymod((v_11+v_21)^2-(u+(b+1)*v),p) - ), - v_11:w_11, - v_21:w_21 - ), - return(mod(v_11,p)) - )$ - - - /* Stickelberger-Redei irreducibility test for cubic polynomial f(x)=x^3+bx+a */ - /* f(x) is irreducible over F_p iff its discriminant D=-4b^3-27a^2 */ - /* is a quadratic residue AND 2*(sqrt(D)+sqrt(-27a^2))^2 is NOT a cubic residue. */ - redei(a,b,p,ome,p3):= - block([d,g,y,r], - d:polymod(-4*b^3-27*a^2,p), - if jacobi(d,p)#1 then - return(false), - g:polymod(msqrt(d,p)[1]+3*a*ome,p), - y:polymod(?ash(g*g,1),p), - r:fastpower(y,p3,p), - if mod(r,p)=1 then - return(false) - else - return(true) - )$ - - - /* For VERY large p, it might be useful to factor (p-1) into prime factors */ - /* (p-1) = 2^(a_1) 3^(a_2) ... q_l^(a_l) */ - /* then use a factor-addition-chain instead of the binary one: */ - /* r:y, for i:l downto 1 do ( */ - /* r:polymod(fastpower(r,q_l^(a_l),p),p), */ - /* if r=1 then return(false) */ - /* ), if r=1 then return(true) else return(false) */ - /* to have great chances to shorten the cubic-residue test. */ - - - /* If a is a quadratic residue in F_p, this routine returns */ - /* two integers in [0, p-1] such that their squares */ - /* are congruent to a (mod p). */ - /* */ - /* If b^2-4a is a quadratic non-residue mod p, the polynomial */ - /* x^2 - bx + a */ - /* has two roots in F_(p^2) = (Z/pZ[x])/(x^2-bx+a) */ - /* the former being the Frobenius conjugate of the latter */ - /* y = y^p */ - /* so that sqrt(a)=y^((p+1)/2) for Viete's theorem. */ - /* The point is to compute */ - /* mu = (b/2 + sqrt(b^2-4a)/2)^((p+1)/2) = J + K sqrt(b^2-4a) */ - /* in a fast way. We notes that if a is a quadratic residue */ - /* mu can't be a proper element of the field extension */ - /* F_p (sqrt(b^2-4a)) */ - /* so we must have K=0, or, in the same way, */ - /* mu = (1/2) { (b/2 + sqrt(delta)/2)^((p+1)/2) */ - /* +(b/2 - sqrt(delta)/2)^((p+1)/2 } */ - /* that is the (p+1)/2-th term of the sequence */ - /* A_0 = 1, A_1 = b/2, A_{n+2}=b*A_{n+1}-a*A_{n} */ - /* All we need is the (p+1)/2-power of the matrix */ - /* ( b -a ) */ - /* A = ( 1 0 ) over Z/pZ */ - /* The subroutine "mpower" returns it with about 8 log(p) */ - /* multiplications and 4 log(p) mod-reductions in Z/pZ, */ - /* using the standard "repeat-squaring" algorithm. */ - - /* Field extension algorithm for square-root extraction through companion matrix powers */ - /* returns two integers in [0,p-1] whose square are congruent to a (mod p) */ - msqrt(a,p):= - block([b:0,term,nrflag:false], - if (mod(a,p)=0) then - return([0,0]), - /* if not(primep(p)) then error("ERROR: Second argument must be a prime number."), */ - if jacobi(a,p)#1 then - error("ERROR: First argument must be a quadratic residue."), - if p=2 then - return(mod(a,2)), - while not(nrflag) do - ( - b:b+1, - if jacobi(b*b-4*a,p)=-1 then - nrflag:true - ), - /*print(b,"^2 - 4*",a," is a quadratic non-residue"),*/ - term:mod(f2power(a,b,p,?ash(p+1,-1)),p), - return([term,p-term]) - )$ - - - /* Shank's algorithm for square-root extraction */ - /* returns two integers in [0,p-1] whose square are congruent to a (mod p) */ - ssqrt(a,p):= - block([i,j,nrflag:false,b:0,s:0,t,q:p-1,alpha,r,d], - if (mod(a,p)=0) then - return([0,0]), - /* if not(primep(p)) then error("ERROR: Second argument must be a prime number."), */ - if jacobi(a,p)#1 then - error("ERROR: First argument must be a quadratic residue."), - if p=2 then - return(mod(a,2)), - while not(nrflag) do - ( - b:b+1, - if jacobi(b,p)=-1 then - nrflag:true - ), - while not(?logbitp(0,q)) do - ( - s:s+1, - q:?ash(q,-1) - ), - t:q, - alpha:inv_mod(a,p), - c:fastpower(b,t,p), - r:fastpower(a,?ash((t+1),-1),p), - for i:1 thru s-1 do - ( - d:polymod(polymod(r*r,p)*alpha,p), - for j:1 thru (s-i-1) do - d:polymod(d*d,p), - if polymod(d+1,p)=0 then - r:polymod(r*c,p), - c:polymod(c*c,p) - ), - r:mod(r,p), - return([r,p-r]) - )$ - - - /* Field extension algorithm for cubic-root extraction */ - /* For a cubic residue a and a prime p=1(mod 3) mcbrt finds */ - /* an irreducible polynomial of the form x^3+bx+a over F_p */ - /* so that -a=x^(p^2+p+1) and returns x^((p^2+p+1)/3) */ - /* computed over F_(p^3) = (F_p)/(x^3+bx+a) */ - /* This subroutine returns three integers in [0,p-1] */ - /* whose third-power are congruent to a (mod p) */ - scbrt(a,p):=block( - [b:1,term,h1,h2,h3,q,c,c_1,c_2,om,omega_1,p3], - if (mod(a,p)=0) then - return(0), - /*if not(primep(p)) then error("ERROR: Second argument must be a prime number."),*/ - if p=2 then - return(mod(a,2)), - if mod(p,3)=2 then - return(fastpower(a,(?ash(p,1)-1)/3,p)), - om:msqrt(-3,p), p3:(p-1)/3, - if fastpower(a,p3,p)#1 then - error("ERROR: First argument must be a cubic residue."), - while not(redei(a,b,p,om[1],p3)) do - b:b+1, - q:x^3+b*x+a, - h1:polypower(x,p,q,p), - h2:polypower(h1,p3,q,p), - h3:polypower(x,(?ash(p,1)+1)/3,q,p), - c:polymod(-remainder(h2*h3,q),p), - c:mod(c,p), - omega_1:mod((-1+om[1])*(?ash(p+1,-1)),p), - c_1:mod(omega_1*c,p), - c_2:mod(-c-c_1,p), - return([c,c_1,c_2]) - )$ - - - /* Field extension algorithm for cubic-root extraction */ - /* through companion matrix powers. This subroutine returns three integers */ - /* in [0,p-1] whose third-power are congruent to a (mod p) */ - mcbrt(a,p):=block( - [b:1,c,c_1,c_2,om,omega_1,p3], - if (mod(a,p)=0) then - return(0), - /*if not(primep(p)) then error("ERROR: Second argument must be a prime number."),*/ - if p=2 then - return(mod(a,2)), - if mod(p,3)=2 then - return(fastpower(a,(?ash(p,1)-1)/3,p)), - om:msqrt(-3,p), p3:(p-1)/3, - if fastpower(a,p3,p)#1 then - error("ERROR: First argument must be a cubic residue."), - while not(redei(a,b,p,om[1],p3)) do - b:b+1, - c:mod(-f3power(a,b,p,(1+p*(p+1))/3),p), - omega_1:mod((-1+om[1])*(?ash(p+1,-1)),p), - c_1:mod(omega_1*c,p), - c_2:mod(-c-c_1,p), - return([c,c_1,c_2]) - )$ - - /* For each prime p in the form 4k+1 we find two positive integers */ - /* a and b such that p=a^2+b^2. Useful to extend a Z-factorization */ - /* into a Z[i]-factorization (order of Gaussian integers) */ - - qsplit(p):= - block([m,a,b:1,c,d,e,f,k,j], - if (p=2) then - return([1,1]), - m:msqrt(-1,p), - if (m[1] < m[2]) then - a:m[1] - else - a:m[2], - k:(a^2+1)/p, - while (k>1) do - ( - k:(a^2+b^2)/p, - c:polymod(a,k), - d:polymod(b,k), - j:(c^2+d^2)/k, - e:(a*c+b*d)/k, - f:(b*c-a*d)/k, - a:abs(e), - b:abs(f), - k:j - ), - return([a,b]) - )$ - - - /* For each prime p in the form 3k+1 we find two positive integers */ - /* a and b such that p=a^2+ab+b^2. Useful to extend a Z-factorization */ - /* into a Z[omega]-factorization (order of Eisenstein integers) */ - csplit(p):= - block( - [m,a,b,c,d,t,x,y], - if (p=3) then - return([1,1]), - m:msqrt(-3,p), - if (mod(m[1],2)=0) then - b:m[2] - else - b:m[1], - a:(b^2+3)/(4*p), - c:p, - x:0, - y:1, - while (b#1) do - ( - if (a>c) then - ( - d:a, - a:c, - c:d, - b:-b, - d:x, - x:-y, - y:d - ), - t:floor(b/?ash(a,1)), - b:b-?ash(a*t,1), - c:c-t*(b+a*t), - x:x+t*y - ), - if (x<0) then - if (y<-x) then - x:-(x+y) - else - ( - x:-x, - y:y-x - ), - if (y<0) then - if (x<-y) then - y:-(x+y) - else - ( - y:-y, - x:x-y - ), - return([x,y]) - ); - - -/* Fast Lucas Numbers Computation */ - fastlucas(n):=block([O:2,L:?integer\-length(n),i,f0:2,f1:1,u,v], - for i:1 thru L do ( - u:f0^2, v:f1^2, - if ?logbitp(L-i,n) then (f1:v+O, f0:f1-u+O, O:-2 ) - else (f0:u-O, f1:v+O-f0, O:2 )), - return(f0) - ); - - /* Fast Fibonacci Numbers Computation */ - fastfib(n):=block([O:2,L:?integer\-length(n),i,f0:2,f1:1,u,v], - for i:1 thru L do ( - u:f0^2, v:f1^2, - if ?logbitp(L-i,n) then (f1:v+O, f0:f1-u+O, O:-2 ) - else (f0:u-O, f1:v+O-f0, O:2 )), - return((?ash(f1,1)-f0)/5) - ); - - diff --git a/part/tests/hl/highlight.mup b/part/tests/hl/highlight.mup deleted file mode 100644 index ed5a03d..0000000 --- a/part/tests/hl/highlight.mup +++ /dev/null @@ -1,103 +0,0 @@ -// This is a MUP highlighting test. -// Mup is a shareware music publisher from www.arkkra.com - -// contexts -score -music -staff 1 -voice 1 3 - -top -top2 -bottom -bottom2 -grids - -headshapes - - -header -footer -header2 -footer2 - -// parameters and values -score - units = cm; - key = 3#minor - key = 3# minor - rehstyle=circled - - - - -mussym above all: 1 "ferm" ; - -define NAME -// this is a macro definition, these are collapsable -@ - -ifdef NAME -// this is conditionally "compiled" -endif - -ifndef NAME -// this is conditionally "compiled" when the macro has not been defined -else -// else clause -endif - - -// Various Tests - -// tablature -1: e ^f; f; b ^c5; c#5; -bar - -1: d+^e+ g^a; e+a; g ^/; c ^/ c+^/; -bar - -// cross-staff stems -1: 1e+g+c++; -2: cc+; ee+; g with g+ above; with c+c++ above; -bar - -1: 2+4ceg;4; // tie implied by added time values - -// slurs -1: 2f a c+; dbd+; -bar -1: 2fac+ slur; dbd+; -bar - -// alternation -1: 2c alt 2; 2c+;2g; -bar - -// bar to draw if repeatstart happens to be on new line -(dblbar) repeatstart -1: [up]8f bm with staff below;a;4s ebm;4s bm with staff below;8b;[len 11]d ebm; -2: 4s bm with staff above;8a;b ebm;[down;len 14]b bm with staff above;d;4s ebm; -bar - -// locations -3: 2cf; [=h] egc+; -1: [cue; with >; =_ch] fa; - - -roll up 1 1 to 1 2: 2; 4; -roll down 1 1 to 1 2: 2; 4; - -lyrics above 1,3 ; below 2,4 ; between 5&6 : "<1. >Hi, hi"; - -title "page \% of \#" - -// shaped whole rests -1: 4mr; // use a quarter rest symbol -1: 1/4mr; // use a quadruple whole rest symbol -2: 2.. mr; // use a double-dotted half rest - -// tuplets -1: {4f; g;}3num,4.+2. -bar - diff --git a/part/tests/hl/highlight.pb b/part/tests/hl/highlight.pb deleted file mode 100644 index 5560233..0000000 --- a/part/tests/hl/highlight.pb +++ /dev/null @@ -1,87 +0,0 @@ -; This is a test file for kate's PureBasic highlighting. - -; BMP2x Converter by Sven Langenkamp - -UseJPEGImageEncoder() -UsePNGImageEncoder() - -Declare Convert(JPEG) - -Enumeration 1 - #JPEG - #PNG -EndEnumeration - -; BEGIN section - - -; END - -Global Count -Global file.s -Global filename.s -Global fileext.s -Global OutputFormat -Global JPEGQuality - -Count = 0 -OutputFormat = 1 -JPEGQuality = -1 - -; MAIN PROGRAM------------------------------------------------------------------ - -;Request Options -PrintN("Output Format") -PrintN(" [1] JPEG") -PrintN(" [2] PNG") -Print ("> ") -OutputFormat = Int(Input()) - -Select OutputFormat - Case #JPEG: - fileext = ".jpg" - ;Request JPEG Quality - PrintN("") - PrintN("JPEG Quality") - PrintN(" [0-10]") - Print ("> ") - JPEGQuality = Int(Input()) - - Case #PNG: - fileext = ".png" -EndSelect - -;Convert all BMP files in the current directory -ExamineDirectory(0, "", "*.bmp") -While NextDirectoryEntry() - file = DirectoryEntryName() - filename = GetFilePart(file) - - If LoadImage(0, file) - Select OutputFormat - Case #JPEG: - Convert(JPEGQuality) - - Case #PNG: - Convert(-1) - EndSelect - Count = Count +1 - EndIf - -Wend - -PrintN(Str(Count) + " files converted") -CloseConsole() - -; PROCUDURES-------------------------------------------------------------------- - -Procedure Convert(JPEG) - Shared filename, fileext - - If JPEG > -1 - SaveImage(0, filename + fileext, #PB_ImagePlugin_JPEG, JPEG) - Else - SaveImage(0, filename + fileext, #PB_ImagePlugin_PNG) - EndIf - PrintN(file + " converted to " + filename + fileext) -EndProcedure \ No newline at end of file diff --git a/part/tests/hl/highlight.php b/part/tests/hl/highlight.php deleted file mode 100644 index d604e36..0000000 --- a/part/tests/hl/highlight.php +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - test"; ?> - - - \ No newline at end of file diff --git a/part/tests/hl/highlight.pike b/part/tests/hl/highlight.pike deleted file mode 100644 index 2f63144..0000000 --- a/part/tests/hl/highlight.pike +++ /dev/null @@ -1,24 +0,0 @@ -#! /bin/env pike - -/* This file is a syntax highlight test for Kate. - * FIXME: Improve it to contain more (and more unusual) syntax examples. - */ - - -#define PIKE_ON_THE_WEB /* Is this address correct? */ "http://pike.ida.liu.se/" - - -int main(int argc, array(string) args) -{ - // Write funny things with Pike :) - write(`+("Command line arguments (%d of them): ", @map(args, `+, " ")) + "\n", argc); - - write("\nVisit Pike site at %s\n\n", PIKE_ON_THE_WEB); - - for (int i = 1; i <= 3; i++) - write(":" + ")" * i + " "); - - write("\n" + ({"Bye", "bye"}) * "-" + "!\n"); - - return 0; -} diff --git a/part/tests/hl/highlight.pl b/part/tests/hl/highlight.pl deleted file mode 100644 index 991d1fe..0000000 --- a/part/tests/hl/highlight.pl +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/perl -w -# This is a pseudo Perl file to test Kate's Perl syntax highlighting. -# TODO: this is incomplete, add more syntax examples! - -sub prg($) -{ - my $var = shift; - - $var =~ s/bla/foo/igs; - $var =~ s!bla!foo!igs; - $var =~ s#bla#foo#igs; - $var =~ tr/a-z/A-Z/; - ($match) = ($var =~ m/(.*?)/igs); - - $test = 2/453453.21; - $test /= 2; - - print qq~d fsd fsdf sdfl sd~ - - $" = '/'; - - $foo = <<__EOF; -d ahfdklf klsdfl sdf sd -fsd sdf sdfsdlkf sd -__EOF - - $x = "dasds"; - - next if( $match eq "two" ); - next if( $match =~ /go/i ); - - @array = (1,2,3); # a comment - @array = qw(apple foo bar); - push(@array, 4); - %hash = (red => 'rot', - blue => 'blau'); - print keys(%hash); -} - -sub blah { -} - -&blah; -prg("test"); diff --git a/part/tests/hl/highlight.pov b/part/tests/hl/highlight.pov deleted file mode 100644 index 0bb3077..0000000 --- a/part/tests/hl/highlight.pov +++ /dev/null @@ -1,76 +0,0 @@ -//BEGIN TEST -// test scene for POV-Ray syntax highlighting - -/* test comment */ - -/* nested /* comments */ do not work */ - -#version 3.5; -//END -global_settings { assumed_gamma 1.0 } - -// ---------------------------------------- - -camera { - location <5.0, -12.0, 2.0> - up z sky z - look_at <0.0, 0.0, 0.5> - angle 40 -} - -sky_sphere { - pigment { - gradient z - color_map { - [0.0 rgb <0.6,0.7,1.0>] - [0.2 rgb <0.2,0.3,0.9>] - } - } -} - -light_source { - <3, 1, 2>*1000 - color rgb <2.2, 1.8, 1.5> -} - -// ---------------------------------------- - -#declare TEST=0; - -#ifdef (TEST) - plane { - z, 0 - texture { - pigment { - checker - color rgb 1, color rgb 0 - } - } - } -#end - -#macro Sphere(Pos, Radius) - sphere { - , Radius - texture { - pigment { color rgb 1 } - finish{ - diffuse 0.3 - ambient 0.0 - specular 0.6 - reflection 0.8 - } - } - } -#end - -#local Cnt=0; -#local Seed=seed(0); - -#while (Cnt<10000) - Sphere( - -100+*200, - 0.3+pow(rand(Seed),2)*0.7 - ) - #local Cnt=Cnt+1; -#end \ No newline at end of file diff --git a/part/tests/hl/highlight.prg b/part/tests/hl/highlight.prg deleted file mode 100644 index 713c605..0000000 --- a/part/tests/hl/highlight.prg +++ /dev/null @@ -1,71 +0,0 @@ -// Test file to test kate's clipper highlighting -// kate: hl Clipper; - -//BEGIN INCLUDES -#include -#include "logo.ch" - -#define PRGVERSION "0.0.1" -//END - -//BEGIN CODE -static ws, win -static driver := getDriver() -/* a multiline - comment -*/ - -function main( formName ) - local form - local fileName - - if empty(formName) - ?? "Usage: ./form_ui &\n" - CANCEL - else - fileName := formName - endif - ws := UIWorkSpace() - - form := UIForm( fileName ) - win := form:parseFile() -// ?? valtype(win),chr(10) - if win == NIL - CANCEL - endif - win:show() - - ws:run() - ws:quit() -return 0 - -/* Setting dialog */ -function settingsDialog() - ?? "TODO: Settings dialog&\n" -return - -/* About dialog */ -function aboutDialog() - local dlg := UIWindow("About", win, "aboutDlg", .F.) - local hl, lside, t, bb, bD - - hl := UIHBox(,4,8) - lside := UIVBox() - lside:add(UIImage(eas_logo_mini,.T.)) - hl:add(lside,.F.,.F.) - dlg:userSpace:add(hl,.T.,.T.) - t := UIVBox() - hl:add(t,.T.,.T.) - - t:add(UILabel("License: GPL version 2 or later")) - bb := UIButtonBar() - t:add(bb) - bD := UIButton(win, "&Close", {|o,e| dlg:close() } ) - bb:add( bD ) - - dlg:setFocus(bD) - dlg:setDefault(bD) - dlg:setPlacement( .T. ) - dlg:show() -return -//END \ No newline at end of file diff --git a/part/tests/hl/highlight.qml b/part/tests/hl/highlight.qml deleted file mode 100644 index b860512..0000000 --- a/part/tests/hl/highlight.qml +++ /dev/null @@ -1,59 +0,0 @@ -import Qt 4.6 - -// some random qml snippets stolen from the qt docs - -Rectangle { - important: true - propertyAsdf: - id: container - signalA: bla - property string label - signal clicked - radius: 5; border.color: "black" - color: mouse.pressed ? "steelblue" : "lightsteelblue" - gradient: Gradient { - GradientStop { position: mouse.pressed ? 1.0 : 0.0; color: "steelblue" } - GradientStop { position: mouse.pressed ? 0.0 : 1.0; color: "lightsteelblue" } - } - MouseRegion { id: mouse; anchors.fill: parent; onClicked: container.clicked() } - Text { anchors.fill: parent; text: container.label; anchors.centerIn: parent } -} - -Rectangle { - Script { - function calculateMyHeight() { - return Math.max(otherItem.height, thirdItem.height); - } - } - - anchors.centerIn: parent - width: Math.min(otherItem.width, 10) - height: calculateMyHeight() - color: { if (width > 10) "blue"; else "red" } -} - -Rectangle { - default property color innerColor: "black" - property color innerColor: "black" - property alias text: textElement.text - property alias aliasXYZ: testElement.text - signal bar - signal bar(var blah, string yxcv) - width: 240; height: 320; - width: 100; height: 30; source: "images/toolbutton.sci" - ListView { - anchors.fill: parent - model: contactModel - delegate: Component { - Text { - text: modelData.firstName + " " + modelData.lastName - } - } - } -} - -Item { - function say(text) { - console.log("You said " + text); - } -} diff --git a/part/tests/hl/highlight.rb b/part/tests/hl/highlight.rb deleted file mode 100644 index 2e52e5f..0000000 --- a/part/tests/hl/highlight.rb +++ /dev/null @@ -1,551 +0,0 @@ -# This file is a testcase for the highlighting of Ruby code -# It's not executable code, but a collection of code snippets -# - -require 'Config' -require 'DO/Clients' -require 'DO/DBClients' - - def CGI::escapeElement(string, *elements) - elements = elements[0] if elements[0].kind_of?(Array) - unless elements.empty? - string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do - CGI::escapeHTML($&) - end - else - string - end - end - -case inputLine - when "debug" - dumpDebugInfo - dumpSymbols - when /p\s+(\w+)/ - dumpVariable($1) - when "quit", "exit" - exit - else - print "Illegal command: #{inputLine}" -end - - -kind = case year #hi there - when 1850..1889 then "Blues" - when 1890..1909 then "Ragtime" - when 1910..1929 then "New Orleans Jazz" - when 1930..1939 then "Swing" - when 1940..1950 then "Bebop" - else "Jazz" - end - - # URL-encode a string. - # url_encoded_string = CGI::escape("'Stop!' said Fred") - # # => "%27Stop%21%27+said+Fred" - def CGI::escape(string) - string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do - '%' + $1.unpack('H2' * $1.size).join('%').upcase - end.tr(' ', '+') - end - - -# Class ClientManager -# -# definition : Import, store and export the various data used by the application. -# This class is the sole interface between the application and the underlying database. - -mon, day, year = $1, $2, $3 if /(\d\d)-(\d\d)-(\d\d)/ -puts "a = #{a}" if fDebug -print total unless total == 0 - -while gets - next if /^#/ # Skip comments - parseLine unless /^$/ # Don't parse empty lines -end - -if artist == "John Coltrane" #hi there - artist = "'Trane" #hi there -end unless nicknames == "no" #hi there - -handle = if aSong.artist == "Gillespie" then #hi there - "Dizzy" - elsif aSong.artist == "Parker" then - "Bird" - else #hi there - "unknown" - end - -if aSong.artist == "Gillespie" then handle = "Dizzy" -elsif aSong.artist == "Parker" then handle = "Bird" -else handle = "unknown" -end #hi there - -if aSong.artist == "Gillespie" then - handle = "Dizzy" -elsif aSong.artist == "Parker" then - handle = "Bird" -else - handle = "unknown" -end - -if aSong.artist == "Gillespie" - handle = "Dizzy" -elsif aSong.artist == "Parker" - handle = "Bird" -else - handle = "unknown" -end - - case line - when /title=(.*)/ - puts "Title is #$1" - when /track=(.*)/ - puts "Track is #$1" - when /artist=(.*)/ - puts "Artist is #$1" -end - -case shape - when Square, Rectangle - # ... - when Circle - # ... - when Triangle - # ... - else - # ... -end - - -until playList.duration > 60 #hi there - playList.add(songList.pop) -end - -3.times do - print "Ho! " -end - -loop { - # block ... -} - -songList.each do |aSong| - aSong.play -end - -for aSong in songList - aSong.play -end - -for i in ['fee', 'fi', 'fo', 'fum'] - print i, " " -end -for i in 1..3 - print i, " " -end -for i in File.open("ordinal").find_all { |l| l =~ /d$/} - print i.chomp, " " -end - -class Periods - def each - yield "Classical" - yield "Jazz" - yield "Rock" - end -end - - -periods = Periods.new -for genre in periods - print genre, " " -end - -while gets - next if /^\s*#/ # skip comments - break if /^END/ # stop at end - # substitute stuff in backticks and try again - redo if gsub!(/`(.*?)`/) { eval($1) } - # process line ... -end - -i=0 -loop do - i += 1 - next if i < 3 - print i - break if i > 4 -end - -for i in 1..100 - print "Now at #{i}. Restart? " - retry if gets =~ /^y/i -end - -def doUntil(cond) - yield - retry unless cond -end - -i = 0 -doUntil(i > 3) { - print i, " " - i += 1 -} - -def system_call - # ... code which throws SystemCallError -rescue SystemCallError - $stderr.print "IO failed: " + $! - opFile.close - File.delete(opName) - raise -end - -class ClientManager - - # constructor - def initialize(dbase) - @dbClient = DBClient.new(dbase) - @clients = Clients.new - end - - def prout(a, b, xy="jj") 24 end - ############################################################### - # - # CLIENTS SECTION - # - ############################################################### - - # update the clients object by retrieving the related data from the database - # returns the number of clients - def refreshClients - @clients.clean - unless @sqlQuery.nil? then - @sqlQuery.selectClient.each do |row| - @clients.addClient(row[0],row[1],row[2],row[3],row[4],row[5], row[6], row[7], row[8]) - end - else - puts "SqlQuery wasn't created : cannot read data from database" - end - return @clients.length - end - - # insert a client in the database and refreshes the local clients object - # we assume that none of the arguments is null - # we assume that the client, identified by raison_sociale doesn't already exists - def addClient(raison_sociale, division, departement, adresse, cp, ville, nom_contact, tel_contact) - id = "0" - unless @sqlQuery.nil? then - id = @sqlQuery.insertClient(raison_sociale, division, departement, adresse, cp, ville, nom_contact,tel_contact) - else - puts "SqlQuery wasn't created : database update cannot be performed" - end - @clients.addClient(id, raison_sociale, division, departement, adresse, cp, ville, nom_contact, tel_contact) # synchronize local object with DB - end - - # deletes a client from the database and updates the local Clients object accordingly - def delClient(nomclient_brut) - raison_sociale, div, dep = Clients.getIdentifiers(nomclient_brut) - listeContratsExp, listeContratsSup, listeContratsProd, listePropositionsExp, listePropositionsSup = [] - - listeContratsExp = @contratsExpertise.getContratsFromClient(nomclient_brut) - listeContratsSup = @contratsSupport.getContratsFromClient(nomclient_brut) - listeContratsProd = @contratsProduits.getContratsFromClient(nomclient_brut) - listePropositionsExp = @propositionsExpertise.getPropositionsFromClient(nomclient_brut) - listePropositionsSup = @propositionsSupport.getPropositionsFromClient(nomclient_brut) - - unless @sqlQuery.nil? then - @sqlQuery.deleteClient(raison_sociale, div, dep) - - @sqlQuery.deleteContracts(Config::EXPERTISE,listeContratsExp) - @sqlQuery.deleteContracts(Config::SUPPORT,listeContratsSup) - @sqlQuery.deleteContracts(Config::PRODUIT,listeContratsProd) - @sqlQuery.deletePropositions(Config::EXPERTISE,listePropositionsExp) - @sqlQuery.deletePropositions(Config::SUPPORT,listePropositionsSup) - else - puts "SqlQuery wasn't created : database update cannot be performed" - end - @clients.delClient(raison_sociale,div,dep) - - @contratsExpertise.deleteContracts(listeContratsExp) - @contratsSupport.deleteContracts(listeContratsSup) - @contratsProduits.deleteContracts(listeContratsProd) - @propositionsExpertise.deletePropositions(listePropositionsExp) - @propositionsSupport.deletePropositions(listePropositionsSup) - end -end - - # Mixin module for HTML version 3 generation methods. - module Html3 # :nodoc: - - # The DOCTYPE declaration for this version of HTML - def doctype - %|| - end - - # Initialise the HTML generation methods for this version. - def element_init - extend TagMaker - methods = "" - # - - - for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG - DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP - APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE - STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE - CAPTION ] - methods += <<-BEGIN + nn_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # - O EMPTY - for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT - ISINDEX META ] - methods += <<-BEGIN + nOE_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - - # O O or - O - for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr - th td ] - methods += <<-BEGIN + nO_element_def(element) + <<-END - def #{element.downcase}(attributes = {}) - BEGIN - end - END - end - eval(methods) - end - - end - -# following snippet from Webrick's log.rb -# notice the erronous handling of the query method is_a? -def format(arg) - str = if arg.is_a?(Exception) - "#{arg.class}: #{arg.message}\n\t" << - arg.backtrace.join("\n\t") << "\n" - elsif arg.respond_to?(:to_str) - arg.to_str - else - arg.inspect - end -end - -# following snippet from Webrick's httputils.rb -# Splitting regexps on several lines might be bad form, -# but not illegal in Ruby. -# This should probably be supported in the highlighting -def split_header_value(str) - str.scan(/((?:"(?:\\.|[^"])+?"|[^",]+)+) - (?:,\s*|\Z)/xn).collect{|v| v[0] } -end - -# snippet from Net::Telnet -string.gsub(/#{IAC}( - [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]| - [#{DO}#{DONT}#{WILL}#{WONT}] - [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]| - #{SB}[^#{IAC}]*#{IAC}#{SE} - )/xno) - -# following snippet from Webrick's httpresponse.rb -# the HEREDOC is not recognized as such -@body << <<-_end_of_html_ - - - #{HTMLUtils::escape(@reason_phrase)} - -

#{HTMLUtils::escape(@reason_phrase)}

- #{HTMLUtils::escape(ex.message)} -
-_end_of_html_ - - -# snippet from Webrick's httpproxy.rb -# here we should make sure that the symbol definition ':' doesn't override -# the module operator '::' -Net::HTTP::version_1_2 if RUBY_VERSION < "1.7" - -# snippet from Webrick's cookie.rb -# the beginning of the regexp is erronously highlighted like an operator -key, val = x.split(/=/,2) - -# the following are division operators -# it's a bit tricky to keep the operator apart from the regexp -result = 8 / 4 -result /= divisor - -# 2008-06-01 regexp and division operator syntax has been fixed: -result = 8/4 # division -result = 8/foo # division -result = /8/ # regexp -result = 8//4/ # division and regexp - -10/10 # division -10/ 10 # division -10 /10 # division -10 / 10 # division - -foo/10 # division -foo/ 10 # division -foo /10/ # regexp -foo / 10 # division - -foo/10/10 # both division -total/count/2 # both division -total/(count/2) # both division - -@foo/10 # division -@foo /10 # division - -"hello"/10 # division -"hello" / 10 # division - -/regexp//10 # division -/regexp/ / 10 # division - -Math::PI/10 # division -Math::foo /rx/ # regexp - -# 2008-06-05 similar fix for modulo operator: - -10%4 # modulo -10 %4 # modulo -10% 4 # modulo -10 % 4 # modulo - -foo%4 # modulo -# foo %4 # illegal %string -foo% 4 # modulo -foo % 4 # modulo - -foo % (4) # modulo - -foo %(4) # %string -foo %q(4) # %string -foo %Q(4) # %string -foo %%4% # %string - -foo = %|blah| # GDL input -foo % %|blah| # modulo and GDL - -# mix in any way you want -result = 10//regexp//20/foo//regexp//20 - -# test cases for general delimited input -# quoted strings -%Q|this is a string| -%Q{this is a string} -%Q(this is a string) -%Q -%Q[this is a string] - -%|also a string| -%{also a string} -%(also a string) -% -%[also a string] - -# apostrophed strings -%q|apostrophed| -%q{apostrophed} -%q(apostrophed) -%q -%q[apostrophed] - -# regular expressions -%r{expression} -%r(expression) -%r -%r[expression] -%r|expression| - -# shell commands -%x{ls -l} -%x(ls -l) -%x -%x[ls -l] - -# sometimes it's useful to have the command on multiple lines -%x{ls -l | -grep test } - -# alternative syntax -`ls -l` -`echo ' '` - -# token array -%w{one two three} -%w(one two three) -%w -%w[one two three] - -# snippet from Net::IMAP -# I object to putting String, Integer and Array into kernel methods. -# While these classes are builtin in Ruby, this is an implementation detail -# that should not be exposed to the user. -# If we want to handle all std-lib classes, fine. But then they should be in their -# own std-lib keyword category. - -def send_data(data) - case data - when nil - put_string("NIL") - when String - send_string_data(data) - when Integer - send_number_data(data) - when Array - send_list_data(data) - when Time - send_time_data(data) - when Symbol - send_symbol_data(data) - else - data.send_data(self) - end -end - -# snippet from Net::POP -# class names can have numbers in them as long as they don't begin with numbers -# Ruby doesn't internally really make much of a difference between a class name and a constant - -# class aliases - POP = POP3 - POPSession = POP3 - POP3Session = POP3 - -# "member access" -POP::Session.COUNT.attribute.calc_with(2){ |arg| puts arg } - -# snippet from Net::SMTP -# This breaks the code folding. I think we would need to -# handle the '\' that continues the statement to the next line -# in some way to make these kind of things not break something. -raise ArgumentError, 'both user and secret are required'\ - unless user and secret - -# string escapes must detect escaping the escape char -str = "\\" -str = "\\\\" -# this is not part of the string -%x{echo \\\}\\} # prints \}\ -# this is not part of the command - -# these are all symbols -:abc -:abc! -:abc? -:abc= -:[] -:[]= -:@abc -:@@abc -:$abc diff --git a/part/tests/hl/highlight.rib b/part/tests/hl/highlight.rib deleted file mode 100644 index 0ec8277..0000000 --- a/part/tests/hl/highlight.rib +++ /dev/null @@ -1,68 +0,0 @@ -# bulb.rib -# Author: Scott Iverson -# Date: 6/9/95 -# - -Display "bulb.tiff" "file" "rgb" - -Projection "perspective" "fov" 25 -Format 380 380 -1 -Rotate 0 0 0 1 -Rotate -0.570093918 1 0 0 -Rotate 5.71059326 0 1 0 -Translate -1 -2 10 - -WorldBegin - LightSource "ambientlight" 1 "intensity" .4 - LightSource "distantlight" 2 "intensity" .6 "from" [0 0 0] "to" [-.3 -.2 1] - AttributeBegin - Rotate -90 1 0 0 - - ShadingInterpolation "smooth" - -# base - Surface "metal" - Color 0 0 1 - AttributeBegin - Orientation "rh" - Disk 0 .18 360 - AttributeEnd - - Cylinder .18 0 .1 360 - - Translate 0 0 .1 - - Surface "matte" - Color 1 1 0 - Hyperboloid .18 0 0 .4 0 .15 360 - - Translate 0 0 .15 - - Surface "metal" - Color 1 .7 0 - - Translate 0 0 .05 - Torus .4 .05 -90 90 360 - Translate 0 0 0.10 - Torus .4 .05 -90 90 360 - Translate 0 0 0.10 - Torus .4 .05 -90 90 360 - Translate 0 0 0.10 - Torus .4 .05 -90 90 360 - Translate 0 0 0.10 - Torus .4 .05 -90 90 360 - Translate 0 0 0.10 - Translate 0 0 -0.05 - -# the glass part - - Surface "plastic" "roughness" .4 - - Color 1 1 1 - - PatchMesh "bicubic" 13 "nowrap" 7 "nowrap" "P" [ 0.40 0.00 0 0.40 0.220913867 0 0.220913867 0.40 0 0.00 0.40 0 -0.220913867 0.40 0 -0.40 0.220913867 0 -0.40 0.00 0 -0.40 -0.220913867 0 -0.220913867 -0.40 0 0.00 -0.40 0 0.220913867 -0.40 0 0.40 -0.220913867 0 0.40 0.00 0 0.40 0.00 .9 0.40 0.220913867 .9 0.220913867 0.40 .9 0.00 0.40 .9 -0.220913867 0.40 .9 -0.40 0.220913867 .9 -0.40 0.00 .9 -0.40 -0.220913867 .9 -0.220913867 -0.40 .9 0.00 -0.40 .9 0.220913867 -0.40 .9 0.40 -0.220913867 .9 0.40 0.00 .9 1.0 0.0 1.34771533 1.0 0.552284667 1.34771533 0.552284667 1.0 1.34771533 0.0 1.0 1.34771533 -0.552284667 1.0 1.34771533 -1.0 0.552284667 1.34771533 -1.0 0.0 1.34771533 -1.0 -0.552284667 1.34771533 -0.552284667 -1.0 1.34771533 0.0 -1.0 1.34771533 0.552284667 -1.0 1.34771533 1.0 -0.552284667 1.34771533 1.0 0.0 1.34771533 1.0 0.0 1.9 1.0 0.552284667 1.9 0.552284667 1.0 1.9 0.0 1.0 1.9 -0.552284667 1.0 1.9 -1.0 0.552284667 1.9 -1.0 0.0 1.9 -1.0 -0.552284667 1.9 -0.552284667 -1.0 1.9 0.0 -1.0 1.9 0.552284667 -1.0 1.9 1.0 -0.552284667 1.9 1.0 0.0 1.9 1.0 0.0 2.45228467 1.0 0.552284667 2.45228467 0.552284667 1.0 2.45228467 0.0 1.0 2.45228467 -0.552284667 1.0 2.45228467 -1.0 0.552284667 2.45228467 -1.0 0.0 2.45228467 -1.0 -0.552284667 2.45228467 -0.552284667 -1.0 2.45228467 0.0 -1.0 2.45228467 0.552284667 -1.0 2.45228467 1.0 -0.552284667 2.45228467 1.0 0.0 2.45228467 0.552284667 0 2.9 0.552284667 0.305018353 2.9 0.305018353 0.552284667 2.9 0 0.552284667 2.9 -0.305018353 0.552284667 2.9 -0.552284667 0.305018353 2.9 -0.552284667 0 2.9 -0.552284667 -0.305018353 2.9 -0.305018353 -0.552284667 2.9 0.00000000 -0.552284667 2.9 0.305018353 -0.552284667 2.9 0.552284667 -0.305018353 2.9 0.552284667 0 2.9 0.001 0 2.9 0.0010 0.000552284667 2.9 0.000552284667 0.001 2.9 0 0.0010 2.9 -0.000552284667 0.0010 2.9 -0.0010 0.000552284667 2.9 -0.001 0 2.9 -0.0010 -0.000552284667 2.9 -0.000552284667 -0.0010 2.9 0.0000 -0.0010 2.9 0.000552284667 -0.0010 2.9 0.0010 -0.000552284667 2.9 0.0010 0.0000 2.9 ] - -AttributeEnd - -WorldEnd - diff --git a/part/tests/hl/highlight.scheme b/part/tests/hl/highlight.scheme deleted file mode 100644 index 08c7351..0000000 --- a/part/tests/hl/highlight.scheme +++ /dev/null @@ -1,186 +0,0 @@ -; This is a test file to test kates scheme highlighting -; This is a comment - -;; Another comment, usually used. -;BEGIN region marker -;; a vektor -#(1 2 3 4 5) -;END region marker -;; this represents integer 28 (FIXME: does not work perfectly atm!) -28 028 #e28 #i28 ;; Normal, normal, exact, inexact -#b11100 #o34 #d28 #x1c ;; Bin, okt, dec, hex -#oe34 #eo34 ;; combined. - -;; char. -(#\y #\space) ;; list: `y' space. -(#\ #\\ #\)) ;; list of spaces, backslash and`)'. -#\newline ;; a newline-char -#\NewLine ;; another one :) - -"Hello, world" ;; a string - -"hoho, what do you -want to do ;; this is NO comment -with that?" - -;; R5RS definiert diese beiden. -"Das ist \"in Anführungszeichen\" und mit \\ Backslash." - -(let ((x (+ 1 2)) (y "blah")) ;; `let' highlighting. - (and (number? x) ;; `and' highlighting. - (string? y))) - -(let* ((x 2) (y (+ x 1))) ;; `let*' too. - (or (negative? x) ;; `or' anyways. - (negative? y))) - -(do ((vec (make-vector 5)) ;; `do' you may guess! - (i 0 (+ i 1))) - ((= i 5) vec) - (vector-set! vec i i)) - -(quasiquote ((+ 1 2) (unquote (+ 1 2)))) -;; same as: `((+ 1 2) ,(+ 1 2)) - -;; see above. -(quasiquote ((+ 1 2) (unquote-splicing (list 1 2 3)))) -;; same as: `((+ 1 2) ,@(+ 1 2)) - -;; not necessary. -(quote ()) - -(cond ((string? x) (string->symbol x)) ;; `cond' highlighting. - ((symbol? x) => (lambda (x) x)) ;; `=>' highlighting. - (else ;; `else' highlighting. - (error "Blah"))) - -(case x ;; `case' highlighting. - ((#t) 'true) ((#f) 'false) - ((()) 'null) - ((0) 'zero)) - -;; highlight `let-syntax' and `syntax-rules' . -(let-syntax ((when (syntax-rules () - ((when test stmt1 stmt2 ...) - ;; hl `begin' . - (if test (begin stmt1 stmt2 ...)))))) - (let ((if #t)) ;; here`if' is actually no keyword. - (when if (set! if 'now)) ;; nor here. - if)) - -(letrec-syntax ...) ;; hl `letrec-syntax'. - -(define-syntax when - (syntax-rules () - ((when test stmt1 stmt2 ...) - (if test (begin stmt1 stmt2 ...)))))) - -;; variable definitions. -(define natural-numbers ;; hl `define' and the var name - ;; endless stream of all natual numbers. - (letrec ((next-cell ;; hl `letrec'. - (lambda (x) ;; hl `lambda'. - ;; hl `delay' . - (cons x (delay (next-cell (+ x 1))))))) - (next-cell 0))) - -;; a procedure with unusual but allowed name. -(define 1+ - (lambda (x) - (+ x 1))) - -;; a predicate -(define between? - (lambda (x y z) - (if (and (>= x y) (<= x z)) - #t ;; True - #f))) ;; False. - -;; imperative procedure -(define set-something! - (lambda (required-argument another-one . all-remaining-args) - (set-car! another-one (lambda all-args - (set-cdr! required-argument - (append all-remaining-args - all-args)))))) - -(define compose - (lambda (f g) - (lambda (x) - (f (g x))))) - -;; syntactical sugar for procedure-definitions. -(define (compose f g) - (lambda (x) - (f (g x)))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; NOW: Guile extensions ;; -;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; procedure-generator. -(define ((compose f g) x) - (f (g x))) - -;; scheme doesn't say, which chars may be in variables... -;; At least: Guile accepts umlauts -(define-private (timetr??? sprache) ;; hl `define-private'. - (list-dialekt? sprache)) - -(define-public x #t) ;; hl `define-public'. -(define-module (foo bar)) ;; hl `define-module'. -(define-macro (neither . exprs) ;; hl `define-macro'. - `(and ,@(map (lambda (x) `(not ,x)) exprs))) - -(defmacro neither exprs ;; `defmacro' as well. - `(and ,@(map (lambda (x) `(not ,x)) exprs))) - -;; hl, but I really don't know what this is supposed to do :-) -(define-syntax-macro ...) - -;; hl GOOPS-`defines' -(define-method (foo bar (baz ) qux) ...) -(define-class ...) -(define-generic foo) -(define-accessor bar) - -;; Keywords! -(blah #:foo 33 #:bar 44) - -;; another convention for symbols: -#{foo}# - -#{a -few -lines}# - -#{4711}# - -;; more chars. -#\nul #\nl #\esc #\bs #\bel #\syn #\ack #\sp ;; etc, utc, itc, oops (this is boring) - -#! - guile block-comment. -!# - -;; now, a bit hairy: -#! comment !# -still comment!!! -!# -'now-no-comment-anymore - -;; more precise: -#! comment !# -still comment -!# still comment! -!# -'now-no-comment-anymore - -(while (> foo 10) ;; Highlight `while'. - (set! foo (- foo 1)) - (catch #t ;; Highlight `catch'. - (lambda () (display foo)) - (lambda (key . args) - (if (eq? key 'system-error) - (break) ;; Highlight `break'. - (continue))))) ;; Highlight `continue'. \ No newline at end of file diff --git a/part/tests/hl/highlight.sh b/part/tests/hl/highlight.sh deleted file mode 100644 index a354757..0000000 --- a/part/tests/hl/highlight.sh +++ /dev/null @@ -1,207 +0,0 @@ -#! /bin/sh -# This is a test script for the Katepart Bash Syntax Highlighting by -# Wilbert Berendsen. This is not runnable !!! - - -# The highlighting recognizes basic types of input, and has a few special cases that -# are all in FindCommands. The main objective is to create really proper nesting of -# (multiline) strings, variables, expressions, etc. - - - -# ============== Tests: =============== - -# basic types: -echo 'single quoted string' -echo "double quoted string" -echo $'string with esc\apes\x0din it' -echo $"string meant to be translated" - - -# comments: -# this is a comment -#this too -echo this is#nt a comment -dcop kate EditInterface#1 #this is - - -# brace expansion -mv my_file.{JPG,jpg} - - -# special characters are escaped: -echo \(output\) \&\| \> \< \" \' \* - - -# variable substitution: -echo $filename.ext -echo $filename_ext -echo ${filename}_ext -echo text${array[$subscript]}.text -echo text${array["string"]}.text -echo ${!prefix*} -echo ${!redir} -echo short are $_, $$, $?, ${@}, etc. -echo ${variable/a/d} -echo ${1:-default} - - -# expression subst: -echo $(( cd << ed + 1 )) - - -# command subst: -echo $(ls -l) -echo `cat myfile` - - -# file subst: -echo $(<$filename) -echo $( my_file.txt 2>&1 - - -# All substitutions also work in strings: -echo "subst ${in}side string" 'not $inside this ofcourse' -echo "The result is $(( $a + $b )). Thanks!" -echo "Your homedir contains `ls $HOME |wc -l` files." - - -# Escapes in strings: -p="String \` with \$ escapes \" "; - - -# keywords are black, builtins dark purple and common commands lighter purple -set -exit -login - - -# Other colorings: -error() { - cat /usr/bin/lesspipe.sh - runscript >& redir.bak - exec 3>&4 -} - - -# do - done make code blocks -while [ $p -lt $q ] -do - chown 0644 $file.$p -done - - -# braces as well -run_prog | sort -u | -{ - echo Header - while read a b d - do - echo $a/$b/$c - done - echo Footer -} - - -# Any constructions can be nested: -echo "A long string with $( - if [ $count -gt 100 ] ; then - echo "much" - else - echo "not much" - fi ) substitutions." ; - - -# Even the case construct is correctly folded: -test -f blaat && -( do_something - case $p in - *bak) - do_bak $p - ;; - *) - dont_bak $p - ;; - esac -) # despite the extra parentheses in the case construction. - - -# variable assignments: -DIR=/dev -p=`ls` -LC_ALL="nl" dcop 'kate*' -_VAR=val -ARR=(this is an array) -ARR2=([this]=too [and]="this too") -usage="$0 -- version $VERSION -Multiple lines of output -can be possible." -ANSWER=yes # here 'yes' isn't highlighed as command - - -# Some commands expect variable names, these are colored correctly: -export PATH=/my/bin:$PATH BLAAT -export A B D -local p=3 x y='\' -read x y z <<< $hallo -unset B -declare -a VAR1 VAR2 && exit -declare less a && b - -# options are recoqnized: -zip -f=file.zip -./configure --destdir=/usr -make destdir=/usr/ - - -# [[ and [ correctly need spaces to be regarded as structure, -# otherwise they are patterns (currently treated as normal text) -if [ "$p" == "" ] ; then - ls /usr/bin/[a-z]* -elif [[ $p == 0 ]] ; then - ls /usr/share/$p -fi - -# Fixed: -ls a[ab]* # dont try to interprete as assignment with subscript (fixed) -a[ab] -a[ab]=sa - - -# Here documents are difficult to catch: -cat > myfile << __EOF__ -You're right, this is definitely no bash code -But ls more $parameters should be expanded. -__EOF__ - - -# quoted: -cat << "EOF" | egrep "this" >&4 # the rest of the line is still considered bash source -You're right, this is definitely no bash code -But ls more $parameters should be expanded. :-> -EOF - - -# indented: -if true -then - cat <<- EOF - Indented text with a $dollar or \$two - EOF -elif [ -d $file ]; then - cat <<- "EOF" - Indented text without a $dollar - EOF -fi - - -case 1 in -2) echo xxx; -;; -1) echo yyy; -esac - -ls #should be outside of case 1 folding block \ No newline at end of file diff --git a/part/tests/hl/highlight.sp b/part/tests/hl/highlight.sp deleted file mode 100644 index 046dfea..0000000 --- a/part/tests/hl/highlight.sp +++ /dev/null @@ -1,32 +0,0 @@ -*current sink p-type inverter - dc sweep of voltage I/O -*file:invcsp0.sp - -*parameters -.PARAM ww=38.5 $ parameter for width which will be swept - -*circuit net list -Vdd vdd GND dc 5.0 -Vbias bias GND dc 2.5 -Vin src GND dc 0.0 -Mn out bias GND GND nmosl1 W=16 L=8 -Mp out in vdd vdd pmosl1 W=ww L=8 -Cl out GND 0.01P -Rs src in 10K - -*options & analysis -.OPTIONS POST=2 SCALE=1U $ output results for plot; scale mosfet L & W dimensions -.DC Vin 0 5 0.1 $sweep I/P voltage -.MEASURE DC vin_bal WHEN V(out)=2.5 - -*output -.plot DC v(src) v(in) v(out) - -*mosfet models - level 1 -.INC 'l1typ.inc' - -$ a comment -* another comment - -.END - - diff --git a/part/tests/hl/highlight.spec b/part/tests/hl/highlight.spec deleted file mode 100644 index 65c70a0..0000000 --- a/part/tests/hl/highlight.spec +++ /dev/null @@ -1,775 +0,0 @@ -# -# spec file for package kdevelop -# -# Copyright (c) 2008 SUSE LINUX Products GmbH, Nuernberg, Germany. -# This file and all modifications and additions to the pristine -# package are under the same license as the package itself. -# -# Copyright (c) 2007-2008 Amilcar Lucas -# Copyright (c) 2003-2006 Than Ngo -# Copyright (c) 2002-2006 Laurent Montel -# -# Please submit bugfixes or comments via http://bugs.opensuse.org/ -# - -# norootforbuild - -######################################################################################### -# Commom part -######################################################################################### -%define branch_source_date 20081218 -%define kdevelop_version 3.5.4 -%define kde_version 3.4.0 -%define qt_version 3.3.2 - -%if 0%{?suse_version} != 0 -%define name kdevelop3 -%else -%define name kdevelop -%endif -Name: %{name} -URL: http://www.kdevelop.org/ -Version: %{kdevelop_version} -Release: 1 -Summary: Integrated Development Environment for the X Window System, Qt, KDE, and GNOME -License: GPL (GNU General Public License) -Group: Development/Tools/IDE -Provides: kdevelop -Obsoletes: kdevelop -Obsoletes: gideon -Obsoletes: kdevelop2 -#Autoreqprov: on -Source: http://download.kde.org/download.php?url=stable/3.5.10/kdevelop-%{version}.tar.bz2 -#Source1: ftp://129.187.206.68/pub/unix/ide/KDevelop/c_cpp_reference-2.0.2_for_KDE_3.2.tar.bz2 -%if 0%{?mandriva_version} -Source2: kdevelop-3.0-Makefile.PL -Epoch: 3 -%endif -%if 0%{?fedora_version} -Epoch: 9 -Obsoletes: kdevelop-c_c++_ref -#Patch1: c_cpp_reference-2.0.2-config.patch -#Patch2: kde-libtool.patch -%endif -BuildRoot: %{_tmppath}/%{name}-%{version}-build -Packager: Amilcar Lucas - -######################################################################################### -# SuSE, openSUSE -######################################################################################### -%if 0%{?suse_version} - -# it is a qt3 based application -BuildRequires: qt3-devel >= %{qt_version} -# For the entire kdelibs infrastructure -BuildRequires: kdelibs3-devel >= %{kde_version} -%if %suse_version < 1010 -BuildRequires: update-desktop-files -# for the kdevassistant -BuildRequires: qt3-devel-doc >= %{qt_version} -%endif -%if %suse_version < 1000 -BuildRequires: libjpeg-devel -%endif -# for the cvsservice (cvs support) -BuildRequires: kdesdk3-devel >= %{kde_version} -# for the presistent class store (PCS) -BuildRequires: db-devel >= 4.1 -BuildRequires: doxygen -BuildRequires: graphviz >= 1.8.7 -# For the QMake parser -BuildRequires: flex >= 2.5.4 -# for svn support -BuildRequires: subversion-devel -#BuildRequires: apr -%if %suse_version > 1030 -# for the svn-merge functionality provided by subversion 1.5 -BuildRequires: sqlite-devel -%endif -# Nice to have KDE API documentation integrated in KDevelop -Requires: kdelibs3-devel-doc >= %{kde_version} -Requires: kdebase3 >= %{kde_version} -Requires: kdesdk3 >= %{kde_version} -Requires: cvs /usr/bin/make -Requires: perl >= 5.004 -Requires: graphviz >= 1.8.7 -Requires: db >= 4.1 -#For debugging with GDB-MI support -Requires: gdb >= 6.4 -Requires: ctags >= 5 -Requires: libtool >= 1.4 -Requires: qt3-devel-tools >= %{qt_version} - -# ruby templates in there -Requires: kdebindings3-ruby >= %{kde_version} -# python templates in there -Requires: kdebindings3-python >= %{kde_version} -%endif - -######################################################################################### -# Mandriva -######################################################################################### -%if 0%{?mandriva_version} -%define __libtoolize /bin/true - -%define use_enable_final 0 -%{?_no_enable_final: %{expand: %%global use_enable_final 0}} - -%define compile_apidox 0 -%{?_no_apidox: %{expand: %%global compile_apidox 0}} - -%define unstable 0 -%{?_unstable: %{expand: %%global unstable 1}} - -%if %unstable -%define dont_strip 1 -%endif - -%define lib_name_orig libkdevelop -%if 0%{?mandriva_version} < 2008 -%define lib_major 3 -%define lib_name %mklibname kdevelop %lib_major -%endif -%define old_lib_major 2 -%define old_lib_name %mklibname kdevelop %old_lib_major -%if 0%{?mandriva_version} >= 2008 -%define major 3 -%define libname %mklibname kdevelop %{major} -%define develname %mklibname %{name} -d -%endif - -#BuildRequires: libqt3 >= %{qt_version} -BuildRequires: qt3-devel >= %{qt_version} -BuildRequires: kdelibs-devel >= %{kde_version} -BuildRequires: python -BuildRequires: python-devel -BuildRequires: libjpeg-devel -BuildRequires: png-devel -%if 0%{?mandriva_version} <= 2006 -BuildRequires: XFree86-devel -%else -BuildRequires: X11-devel -%endif -# for the kdevassistant -BuildRequires: qt3-static-devel >= %{qt_version} -BuildRequires: libart_lgpl-devel -# For the QMake parser -#BuildRequires: flex >= 2.5.4 -# for the cvsservice -BuildRequires: libkdesdk-cervisia-devel >= %{kde_version} -BuildRequires: graphviz >= 1.8.6 -BuildRequires: qt3-doc >= %{qt_version} -BuildRequires: db-devel >= 4.1 -# for svn support -BuildRequires: subversion-devel -BuildRequires: apr-devel -BuildRequires: apr-util-devel -# doxygen is always required in order to build the parts/doxygen/ subdir -BuildRequires: doxygen -%py_requires -d - -#Requires: enscript -Requires: gcc-c++ -Requires: gcc-cpp -#Requires: arts -#Requires: openssl-devel -#Requires: kdegraphics kdelibs-devel kdesdk kdeutils -Requires: kdelibs-devel-doc >= %{kde_version} -Requires: kdesdk >= %{kde_version} -Requires: kdebase >= %{kde_version} -%if 0%{?mandriva_version} <= 2006 -Requires: XFree86-devel -%else -Requires: libx11-devel -%endif -Requires: jpeg-devel -Requires: qt3 >= %{qt_version} -Requires: make -Requires: perl >= 5.0004 -#Requires: sgml-tools -Requires: gettext -Requires: libz-devel -Requires: ctags >= 5 -Requires: png-devel libart_lgpl-devel -Requires: libtool >= 1.4 -Requires: automake >= 1.6 -Requires: autoconf >= 2.52 -# required by the autoconf/automake projects -Requires: awk -Requires: db >= 4.1 -%if 0%{?mandriva_version} < 2008 -Requires: %lib_name = %epoch:%version-%release -%else -Requires: %{libname} = %epoch:%version-%release -%endif -Requires: kdesdk-cervisia >= %{kde_version} -Requires: doxygen -Requires: graphviz >= 1.8.6 -Requires(post): desktop-file-utils -Requires(postun): desktop-file-utils -Conflicts: mandrake-mime <= 0.4-5mdk -%endif - -######################################################################################### -# Fedora, RHEL or CentOS -######################################################################################### -%if 0%{?fedora_version} || 0%{?rhel_version} || 0%{?centos_version} -%define debug 0 -%define final 0 - -%define qt_epoch 1 -%define kdelibs_epoch 6 - -%define make_cvs 1 - -%define disable_gcc_check_and_hidden_visibility 1 - -Requires(post): /sbin/ldconfig -Requires(postun): /sbin/ldconfig -Requires: kdelibs-devel >= %{kdelibs_epoch}:%{kde_version} -Requires: kdesdk >= %{kde_version} -Requires: make -Requires: perl >= 0:5.004 -Requires: libtool >= 1.4 -#Requires: flex >= 2.5.4 -Requires: qt-designer >= %{qt_epoch}:%{qt_version} -Requires: db4 >= 4.1 - -BuildRequires: autoconf -BuildRequires: automake -BuildRequires: libtool -%if 0%{?fedora_version} > 8 -BuildRequires: kdelibs3-devel >= %{kde_version} -%else -BuildRequires: kdelibs-devel >= %{kde_version} -%endif -BuildRequires: gcc-c++ -%if 0%{?fedora_version} > 8 -BuildRequires: qt3 -BuildRequires: qt3-devel >= %{qt_version} -BuildRequires: kdelibs3-devel >= %{kde_version} -%else -BuildRequires: qt -BuildRequires: qt-devel >= %{qt_version} -BuildRequires: kdelibs-devel >= %{kde_version} -%endif -BuildRequires: db4-devel >= 4.1 -%if 0%{?rhel_version} != 406 -BuildRequires: kdesdk-devel >= %{kde_version} -%endif -BuildRequires: doxygen -# Both RHEL and CentOS do not provide graphviz -%if 0%{?fedora_version} -BuildRequires: graphviz >= 1.8.6 -%endif -# For the QMake parser -BuildRequires: flex >= 2.5.4 -%if 0%{?rhel_version} != 406 -# for svn support -BuildRequires: subversion-devel >= 1.3 -BuildRequires: apr-devel -BuildRequires: neon-devel -%endif -%endif - -%description -An integrated development environment (IDE) that allows you to write -programs for the X Window System, the Qt library, or KDE. It includes a -documentation browser, a source code editor with syntax highlighting, a -GUI for the compiler, and much more. - - - -Authors: --------- - Andreas Pakulat - Robert Gruber - Jens Dagerbo - Alexander Dymo - Vladimir Prus - Matt Rogers - Megan Webb - Richard Dale - Anne-Marie Mahfouf - Amilcar do Carmo Lucas - David Nolden - Jonas Jacobi - Stephan Binner - Andras Mantia - Oliver Kellogg - - -######################################################################################### -# SUSE -######################################################################################### -%if 0%{?suse_version} -%prep -%setup -q -n kdevelop-%{version} -#%patch0 -#%patch1 -#%patch2 -#%patch4 -# source the standard build environment as defined in kdelibs3 package -. /etc/opt/kde3/common_options -# replace the admin/ folder with the version from kdelibs3 (will work for sure with -# current autoconf and automake) and create Makefile.in and configure script. -update_admin --no-unsermake --no-final - -%build -. /etc/opt/kde3/common_options -export CFLAGS="-fno-strict-aliasing $CFLAGS" -./configure $configkde \ - --with-kdelibsdoxy-dir=/opt/kde3/share/doc/HTML/en/kdelibs-apidocs \ - --with-pythondir=%_libdir/python \ - --with-qtdoc-dir=/usr/%_lib/qt3/doc/html \ -%if %suse_version < 1010 - --disable-subversion \ -%endif - --disable-final -do_make %{?jobs:-j %jobs} - -%install -. /etc/opt/kde3/common_options -make DESTDIR=${RPM_BUILD_ROOT} $INSTALL_TARGET -# use our admin tar ball (commented out because KDevelop already uses an updated admin/ ) -#tar cfvz ${RPM_BUILD_ROOT}/opt/kde3/share/apps/kdevappwizard/template-common/admin.tar.gz admin -%suse_update_desktop_file kdevelop Development IDE -%suse_update_desktop_file kdevelop_c_cpp Development IDE -%suse_update_desktop_file kdevelop_kde_cpp Development IDE -%suse_update_desktop_file kdevelop_ruby Development IDE -%suse_update_desktop_file kdevelop_scripting Development IDE -%suse_update_desktop_file kdevassistant Development Documentation -%suse_update_desktop_file kdevdesigner Development GUIDesigner -%find_lang kdevelop -rm -rf $RPM_BUILD_ROOT/opt/kde3/kdevbdb/docs/CVS -kde_post_install - -%clean -rm -rf $RPM_BUILD_ROOT - -%post -p /sbin/ldconfig - -%postun -p /sbin/ldconfig - -# the -devel package -%package devel -Group: Development/Tools/IDE -Summary: Integrated Development Environment: Build Environment -Requires: kdevelop3 = %version - -%description devel -Development files to develop KDevelop itself. KDevelop is an integrated -development environment (IDE) that allows you to write -programs for the X Window System, the Qt library, or KDE. It includes a -documentation browser, a source code editor with syntax highlighting, a -GUI for the compiler, and much more. - - -%files devel -%defattr(-,root,root) -/opt/kde3/include/* -/opt/kde3/%_lib/libprofileengine.so -/opt/kde3/%_lib/liblang_interfaces.so -/opt/kde3/%_lib/liblang_debugger.so -/opt/kde3/%_lib/libkinterfacedesigner.so -/opt/kde3/%_lib/libkdevwidgets.so -/opt/kde3/%_lib/libkdevshell.so -/opt/kde3/%_lib/libkdevqmakeparser.so -/opt/kde3/%_lib/libkdevpropertyeditor.so -/opt/kde3/%_lib/libkdevextras.so -/opt/kde3/%_lib/libkdevelop.so -/opt/kde3/%_lib/libkdevcppparser.so -/opt/kde3/%_lib/libkdevcatalog.so -/opt/kde3/%_lib/libkdevbuildtoolswidgets.so -/opt/kde3/%_lib/libkdevbuildbase.so -/opt/kde3/%_lib/libgdbmi_parser.so -/opt/kde3/%_lib/libdocumentation_interfaces.so -/opt/kde3/%_lib/libdesignerintegration.so -/opt/kde3/%_lib/libd.so -/opt/kde3/%_lib/libd.la -/opt/kde3/%_lib/libdesignerintegration.la -/opt/kde3/%_lib/libdocumentation_interfaces.la -/opt/kde3/%_lib/libgdbmi_parser.la -/opt/kde3/%_lib/libkdevbuildbase.la -/opt/kde3/%_lib/libkdevbuildtoolswidgets.la -/opt/kde3/%_lib/libkdevcatalog.la -/opt/kde3/%_lib/libkdevcppparser.la -/opt/kde3/%_lib/libkdevelop.la -/opt/kde3/%_lib/libkdevextras.la -/opt/kde3/%_lib/libkdevpropertyeditor.la -/opt/kde3/%_lib/libkdevqmakeparser.la -/opt/kde3/%_lib/libkdevshell.la -/opt/kde3/%_lib/libkdevwidgets.la -/opt/kde3/%_lib/libkinterfacedesigner.la -/opt/kde3/%_lib/liblang_debugger.la -/opt/kde3/%_lib/liblang_interfaces.la -/opt/kde3/%_lib/libprofileengine.la - -%files -f kdevelop.lang -%defattr(-,root,root) -%dir /opt/kde3/share/desktop-directories -%doc /opt/kde3/share/doc/HTML/en/kde_app_devel -%doc /opt/kde3/share/doc/HTML/en/kdevelop-apidocs -/opt/kde3/share/applications/kde/* -/opt/kde3/share/apps/* -%config /opt/kde3/share/config/* -/opt/kde3/share/icons/??color -/opt/kde3/bin/* -%dir /opt/kde3/%_lib/kconf_update_bin -/opt/kde3/%_lib/kconf_update_bin/kdev-gen-settings-kconf_update -/opt/kde3/%_lib/kde3/kded_kdevsvnd.so -/opt/kde3/%_lib/kde3/kio_chm.so -/opt/kde3/%_lib/kde3/kio_csharpdoc.so -/opt/kde3/%_lib/kde3/kio_kdevsvn.so -/opt/kde3/%_lib/kde3/kio_perldoc.so -/opt/kde3/%_lib/kde3/kio_pydoc.so -/opt/kde3/%_lib/kde3/libclearcaseintegrator.so -/opt/kde3/%_lib/kde3/libcvsserviceintegrator.so -/opt/kde3/%_lib/kde3/libdocchmplugin.so -/opt/kde3/%_lib/kde3/libdoccustomplugin.so -/opt/kde3/%_lib/kde3/libdocdevhelpplugin.so -/opt/kde3/%_lib/kde3/libdocdoxygenplugin.so -/opt/kde3/%_lib/kde3/libdockdevtocplugin.so -/opt/kde3/%_lib/kde3/libdocqtplugin.so -/opt/kde3/%_lib/kde3/libkchmpart.so -/opt/kde3/%_lib/kde3/libkdev*.so -/opt/kde3/%_lib/kde3/libperforceintegrator.so -/opt/kde3/%_lib/kde3/libsubversionintegrator.so -/opt/kde3/%_lib/kde3/kded_kdevsvnd.la -/opt/kde3/%_lib/kde3/kio_chm.la -/opt/kde3/%_lib/kde3/kio_csharpdoc.la -/opt/kde3/%_lib/kde3/kio_kdevsvn.la -/opt/kde3/%_lib/kde3/kio_perldoc.la -/opt/kde3/%_lib/kde3/kio_pydoc.la -/opt/kde3/%_lib/kde3/libclearcaseintegrator.la -/opt/kde3/%_lib/kde3/libcvsserviceintegrator.la -/opt/kde3/%_lib/kde3/libdocchmplugin.la -/opt/kde3/%_lib/kde3/libdoccustomplugin.la -/opt/kde3/%_lib/kde3/libdocdevhelpplugin.la -/opt/kde3/%_lib/kde3/libdocdoxygenplugin.la -/opt/kde3/%_lib/kde3/libdockdevtocplugin.la -/opt/kde3/%_lib/kde3/libdocqtplugin.la -/opt/kde3/%_lib/kde3/libkchmpart.la -/opt/kde3/%_lib/kde3/libkdev*.la -/opt/kde3/%_lib/kde3/libperforceintegrator.la -/opt/kde3/%_lib/kde3/libsubversionintegrator.la -/opt/kde3/%_lib/libprofileengine.so.* -/opt/kde3/%_lib/liblang_interfaces.so.* -/opt/kde3/%_lib/liblang_debugger.so.* -/opt/kde3/%_lib/libkinterfacedesigner.so.* -/opt/kde3/%_lib/libkdevwidgets.so.* -/opt/kde3/%_lib/libkdevshell.so.* -/opt/kde3/%_lib/libkdevqmakeparser.so.* -/opt/kde3/%_lib/libkdevpropertyeditor.so.* -/opt/kde3/%_lib/libkdevextras.so.* -/opt/kde3/%_lib/libkdevelop.so.* -/opt/kde3/%_lib/libkdevcppparser.so.* -/opt/kde3/%_lib/libkdevcatalog.so.* -/opt/kde3/%_lib/libkdevbuildtoolswidgets.so.* -/opt/kde3/%_lib/libkdevbuildbase.so.* -/opt/kde3/%_lib/libgdbmi_parser.so.* -/opt/kde3/%_lib/libdocumentation_interfaces.so.* -/opt/kde3/%_lib/libdesignerintegration.so.* -/opt/kde3/%_lib/libd.so.* -/opt/kde3/share/desktop-directories/kde-development-kdevelop.directory -/opt/kde3/share/mimelnk/*/*.desktop -/opt/kde3/share/services/* -/opt/kde3/share/servicetypes/* -%endif - - - -######################################################################################### -# Mandriva -######################################################################################### -%if 0%{?mandriva_version} - -%post -%update_menus -%if 0%{?mandriva_version} > 2006 -%{update_desktop_database} -%update_icon_cache crystalsvg -%endif - - -%postun -%clean_menus -%if 0%{?mandriva_version} > 2006 -%{clean_desktop_database} -%clean_icon_cache crystalsvg -%endif - -%files -%defattr(-,root,root) -%_bindir/* -%_datadir/applications/kde/* -%_libdir/kde3/* -%_datadir/apps/* -%_datadir/desktop-directories/kde-development-kdevelop.directory -%_datadir/icons/*/*/*/* -%_datadir/config/kdeveloprc -%_datadir/mimelnk/*/*.desktop -%_datadir/services/* -%_datadir/servicetypes/* -%if 0%{?mandriva_version} < 2008 -%_menudir/* -%endif -%_libdir/kconf_update_bin/kdev-gen-settings-kconf_update -%_datadir/config/kdevassistantrc - -#------------------------------------------------ - -%if 0%{?mandriva_version} < 2008 -%package -n %lib_name-devel -%else -%package -n %{develname} -%endif -Summary: Development files for kdevelop -Group: Development/KDE and Qt - -Obsoletes: kdevelop-devel, %old_lib_name-devel -Provides: kdevelop-devel = %epoch:%version-%release -%if 0%{?mandriva_version} < 2008 -Requires: %lib_name = %epoch:%version-%release -%else -Requires: %{libname} = %epoch:%version-%release -Obsoletes: %mklibname %{name} 3 -d -%endif - -%if 0%{?mandriva_version} < 2008 -%description -n %lib_name-devel -%else -%description -n %{develname} -%endif -Development files for kdevelop. - -%if 0%{?mandriva_version} < 2008 -%files -n %lib_name-devel -%else -%files -n %{develname} -%endif -%defattr(-,root,root) -%_libdir/*.so -%dir %_includedir/kdevelop -%dir %_includedir/kinterfacedesigner -%_includedir/*/* - -#------------------------------------------------ - -%if 0%{?mandriva_version} < 2008 -%package -n %lib_name -%else -%package -n %{libname} -%endif -Summary: Libraries files for kdevelop -Group: Development/KDE and Qt -Obsoletes: %old_lib_name -%if 0%{?mandriva_version} < 2008 -Provides: %lib_name_orig = %epoch:%version-%release - -%description -n %lib_name -Libraries files for kdevelop. - -%post -n %lib_name-devel -p /sbin/ldconfig -%postun -n %lib_name-devel -p /sbin/ldconfig - -%post -n %lib_name -p /sbin/ldconfig -%postun -n %lib_name -p /sbin/ldconfig - -%files -n %lib_name -%else -Provides: %{libname}_orig = %epoch:%version-%release - -%description -n %{libname} -Libraries files for kdevelop. - -%post -n %{develname} -p /sbin/ldconfig -%postun -n %{develname} -p /sbin/ldconfig - -%post -n %{libname} -p /sbin/ldconfig -%postun -n %{libname} -p /sbin/ldconfig - -%files -n %{libname} -%endif -%defattr(-,root,root) -%_libdir/*.la -%_libdir/*.so.* - - -#------------------------------------------------ - -%package doc -Summary: Development files for kdevelop -Group: Development/KDE and Qt - -%description doc -Documentation kdevelop. - -%files doc -%defattr(-,root,root) -%dir %_docdir/HTML/en/kdevelop -%_docdir/HTML/en/kdevelop/* -%dir %_docdir/HTML/en/kde_app_devel -%_docdir/HTML/en/kde_app_devel/* -%doc %_docdir/HTML/en/kdevelop-apidocs - -#------------------------------------------------ - -%prep -%setup -q - -%build -%if 0%{?mandriva_version} < 2008 -export QTDIR=%_prefix/lib/qt3 -%else -export QTDIR=%{qt3dir} -%endif -QTDOCDIR=%_defaultdocdir/qt-*/doc/html - -%configure2_5x \ -%if %unstable - --enable-debug=full \ -%else - --disable-debug \ -%endif -%if %use_enable_final - --enable-final \ -%endif - --disable-static \ - --disable-embedded \ - --disable-palmtop \ - --disable-rpath \ -%if "%{_lib}" != "lib" - --enable-libsuffix="%(A=%{_lib}; echo ${A/lib/})" \ -%endif - --with-pic \ - --with-qtdoc-dir=$QTDOCDIR \ - --enable-scripting \ -%if 0%{?mandriva_version} < 2005 - --disable-subversion \ -%endif - --with-apr-config=%_bindir/apr-1-config \ - --with-apu-config=%_bindir/apu-1-config \ - --with-kdelibsdoc-dir=%_docdir/HTML/en/ - -%make -%if %compile_apidox -make apidox -%endif - -%install -rm -fr %buildroot - -#### #### -#### Convert KDE menu structure to Mandriva menu structure #### -#### #### - -%makeinstall_std - -%if 0%{?mandriva_version} < 2008 -# Create LMDK menus -install -d %buildroot/%_datadir/applications/kde/ - -#Create LMDK menu entries -install -d %buildroot/%_menudir/ -for kdev in kdevelop kdevdesigner kdevassistant kdevelop_c_cpp kdevelop_kde_cpp kdevelop_ruby kdevelop_scripting; do - kdedesktop2mdkmenu.pl kdevelop "More Applications/Development/Development Environments" %buildroot/%_datadir/applications/kde/${kdev}.desktop %buildroot/%_menudir/kdevelop-${kdev} -done -%else -( -cd %{buildroot}/%name-%version/ -rm -rf perl-kdevelop -mkdir perl-kdevelop/ -cd perl-kdevelop/ -install -m 0755 %SOURCE2 Makefile.PL -ln ../parts/appwizard/common/kdevelop.pm kdevelop.pm -perl Makefile.PL INSTALLDIRS=vendor -make install DESTDIR=%buildroot -) -%endif - -%clean -rm -fr %buildroot -%endif - - - -######################################################################################### -# Fedora, RHEL or CentOS -######################################################################################### -%if 0%{?fedora_version} || 0%{?rhel_version} || 0%{?centos_version} -%prep - -%setup -q -#%setup -q -a1 - -%build -export KDEDIR=%{_prefix} -%if 0%{?fedora_version} >= 5 -QTDIR="" && source "%{_sysconfdir}/profile.d/qt.sh" -%else -QTDIR="" && source /etc/profile.d/qt.sh -%endif -export FLAGS="$RPM_OPT_FLAGS" -# c references -#pushd c_cpp_reference-2.0.2_for_KDE_3.2 -#%configure \ -# --with-qt-libraries=$QTDIR/lib \ -# --with-qt-includes=$QTDIR/include \ -# --with-extra-libs=%{_libdir} -#popd -%configure \ - --enable-new-ldflags \ - --disable-dependency-tracking \ -%if %{disable_gcc_check_and_hidden_visibility} - --disable-gcc-hidden-visibility \ -%endif - --disable-rpath \ -%if %{debug} == 0 - --disable-debug \ - --disable-warnings \ -%endif -%if %{final} - --enable-final \ -%endif - --with-qtdoc-dir=%{_docdir}/qt-devel-%{qt_version}/html/ \ - --with-kdelibsdoc-dir=%{_docdir}/HTML/en/kdelibs-apidocs/ \ - --with-qt-libraries=$QTDIR/lib \ - --with-extra-libs=%{_libdir} -make %{?_smp_mflags} - -%install -rm -rf $RPM_BUILD_ROOT - -make DESTDIR=$RPM_BUILD_ROOT install -#make -C c_cpp_reference-2.0.2_for_KDE_3.2 DESTDIR=$RPM_BUILD_ROOT install - -# remove useless files -rm -rf $RPM_BUILD_ROOT%{_prefix}/kdevbdb - -%post -p /sbin/ldconfig - -%postun -p /sbin/ldconfig - -%clean -rm -rf $RPM_BUILD_ROOT - -%files -%defattr(-,root,root) -%doc %{_docdir}/HTML/en/* -%{_bindir}/* -%{_libdir}/kde3/* -%{_libdir}/lib* -%{_libdir}/kconf_update_bin/* -%{_includedir}/* -%{_datadir}/applications/kde/* -%{_datadir}/apps/* -%config %{_datadir}/config/* -%{_datadir}/desktop-directories/* -%{_datadir}/icons/*/*/*/* -%{_datadir}/mimelnk/application/* -%{_datadir}/mimelnk/text/* -%{_datadir}/services/* -%{_datadir}/servicetypes/* -%endif - diff --git a/part/tests/hl/highlight.t2t b/part/tests/hl/highlight.t2t deleted file mode 100644 index 5b5f379..0000000 --- a/part/tests/hl/highlight.t2t +++ /dev/null @@ -1,90 +0,0 @@ -txt2tags sample - - -%!--includeconf: config.t2t -% disabled here because there is no external file -%!preproc: 'JUST A TEST' ' ' -%!postproc: '(?i)()' ' shots\1' - -%!--include: menu.t2t - -= Title 1 = - - -== My Subtitle 1 ==[some definition] - -Some examples: - -- A paragraph with **bold**, //italic// and --strike--. -- You can even __underline your docs__! - -- And use **//bold and italic//** -- or //**italic and bold**// - -Here is a nice pic: [img/t2tpowered.png]. - -- And a [link to a cool website http://txt2tags.sf.net]! - -- A table : - - || Name | Age | Gender | - | John | 33 | Male | - | Mary | 19 | Female | - - -``` A verbatim line - -And it's working for ``special code`` like this. - -``` -Unfortunately I can't color this verbatim content yet. -``` - - -== My Subtitle 2 == - - -Lorem ipsum etc -Lorem ipsum etc Lorem ipsum etc - -- Test d'écriture avec des accents à la française. Ça marche ou pas ? - -== My Subtitle 3 == - - -Lorem ipsum etc -Lorem ipsum etc - -Here is a direct link: http://kde.org - - -- Another boring part... - - - -=== My Subsubtitle 1 === - -//It's a level 3 header// - -- list 1 -- list 2 - - list 2b -- list 3 - - -=== My Subsubtitle 2 === - -//It's another level 3 header// - -+ ordered list 1 -+ list 2 - + list 2B - + list 2C -+ list 3 - - -== My Subtitle 4 == - -nothing to say here... - diff --git a/part/tests/hl/highlight.tcl b/part/tests/hl/highlight.tcl deleted file mode 100644 index d6b7276..0000000 --- a/part/tests/hl/highlight.tcl +++ /dev/null @@ -1,50 +0,0 @@ -# tcl syntax highlighting sample script for Kate -# -# author: JM. Philippe 15/03/04 - -# escaped characters -set String \{ -set String \{ -set String \" -set String " \" " -set String " \{ " - -#comments and not comments -# is comments -;#is comments - # is comments -#

is html comment

-puts ok; # is comments -set String [string map { {»is not comments}} $String] -set String \#not_a_comment - -# blocks -proc test {arg1 {arg2 {}} {arg3 {fr fq r}}} { - if {1} {; #comments - set String \{; # not a block start - } -} - -proc test args { - set String \}; # not a block end -} - -# BEGIN - collapsable comments -# blablabla -# END - -# strings -set String "feqr feqr $gqer gqe" -set String "feqr -feqr \" $gqer \ -gqe -" -set String {feqr -feqr \{ $gqer \ -gqe -} - -# variables -set b+1 [incr b] -set {incr-b} ${b+1} -puts ${incr-b} diff --git a/part/tests/hl/highlight.tex b/part/tests/hl/highlight.tex deleted file mode 100644 index b706f70..0000000 --- a/part/tests/hl/highlight.tex +++ /dev/null @@ -1,73 +0,0 @@ -% LaTeX test file for kate's syntax highlighting and code folding - -\ordinaryLaTeXcommandwithoption[10pt,a4paper]{article} -% BEGIN region -%comment, this is all ok % $ -\%no comments please -\\%comment -% END of region - -\newcommand{\nohighlighting} - -\section{normal} - -\ref{blue} -\pageref{blue} -\cite{blue} - -\begin{environmentshavespecialcolors} -normal -\end{environmentshavespecialcolors} - -$equations are green, \commands somewhat darker$ -normal -$$equations are green, \commands somewhat darker$$ -normal -\( -\frac{1}{2} -\begin{test} -\end{test} -\) -normal -\[ -%comment -displaymath -\] -normal -\begin{equation} -green\darkergreen -\begin{test} -\test -\end{test} -\end{equation} - -\begin{equation*} -green\darkergreen -%comment -\begin{test} -\test -\end{test} -\%no comment -\end{equation*} - -\{ %this should be comment - -\verb%this shouldn't be%and this should be normal text - -\begin{verbatim} -text inside a verbatim environment is also treated special $ %, -you can even put a \begin{verbatim} inside -\end{verbatim} - -normal - -\begin{Verbatim} -&@@#^%&^#$ -\end{Verbatim} - - -\begin{Verbatim*} -@*&^#@*(^#(*@& -\end{Verbatim*} - -normal \ No newline at end of file diff --git a/part/tests/hl/highlight.wrl b/part/tests/hl/highlight.wrl deleted file mode 100644 index 2fb4b41..0000000 --- a/part/tests/hl/highlight.wrl +++ /dev/null @@ -1,41 +0,0 @@ -#VRML V2.0 utf8 -# -# VRML highlighting test for Kate's syntax highlighting -# - -# Keywords -DEF, EXTERNPROTO, FALSE, IS, NULL, PROTO, ROUTE, TO, TRUE, USE, eventIn, -eventOut, exposedField, field - -# Data types -MFColor, MFFloat, MFInt32, MFNode. MFRotation, MFString, MFTime, MFVec2f, -MFVec3f, SFBool, SFColor, SFFloat, SFImage, SFInt32, SFNode, SFRotation, -SFString, SFTime, SFVec2f, SFVec3f - -# Predefined nodes -Anchor, Appearance, AudioClip, Background, Billboard, Box, Collision, Color, -ColorInterpolator, Cone, Coordinate, CoordinateInterpolator, Cylinder, -CylinderSensor, DirectionalLight, ElevationGrid, Extrusion, Fog, FontStyle, -Group, ImageTexture, IndexedFaceSet, IndexedLineSet, Inline, LOD, Material, -MovieTexture, NavigationInfo, Normal, NormalInterpolator, OrientationInterpolator, -PixelTexture, PlaneSensor, PointLight, PointSet, PositionInterpolator, -ProximitySensor, ScalarInterpolator, Script, Shape, Sound, Sphere, SphereSensor, -SpotLight, Switch, Text, TextureCoordinate, TextureTransform, TimeSensor, -TouchSensor, Transform, Viewpoint, VisibilitySensor, WorldInfo - -# Some real VRML constructs to see if highlighting of int, float etc. works -NavigationInfo { - avatarSize [0.25, 1.6, 0.75] - headlight TRUE - speed 1 - type ["WALK", "ANY"] - visibilityLimit 0.0 -} - -# some further testing for strings: linefeeds are allowed within strings -Text { - string ["some special in-string characters: \" \\ - some more text in the next line - and yet another line"] -} - diff --git a/part/tests/hl/highlight.xml b/part/tests/hl/highlight.xml deleted file mode 100644 index 007449c..0000000 --- a/part/tests/hl/highlight.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - -This is a pseudo XML file to test Kate's XML syntax highlighting. - -Doctype: - - -Processing instruction: - - -Comments: - - - -Comment inside element: - content - -Markup inside comment: - - -Empty element: - - - -Simple element plus content: - some content - some - content - -Namespace for elements and attributes: - content - content - -Elements containing allowed characters: - - - -Elements containing allowed start characters: - <:element foo="test"/> - <_element foo="test"/> - -Single quotes (the same as double quotes): - content - -Allowed Whitespace: - - content - -Entities: -   - å - å - å - И - 水 - - -Illegal XML, should not be highlighted: - <0foobar> -- no digit as first character - <-foo> -- no dash as first character diff --git a/part/tests/hl/highlight.xsl b/part/tests/hl/highlight.xsl deleted file mode 100644 index f6e0efb..0000000 --- a/part/tests/hl/highlight.xsl +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - - - -Linux at Home Links - - - - <xsl:value-of select="h:a/h:strong"/> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <xsl:value-of select="normalize-space($title)"/> - - - - - - - - - diff --git a/part/tests/hl/highlight.y b/part/tests/hl/highlight.y deleted file mode 100644 index f7715e6..0000000 --- a/part/tests/hl/highlight.y +++ /dev/null @@ -1,54 +0,0 @@ -/* Yacc / Bison hl test file. - * It won't compile :-) Sure ! - */ - -%{ - -#include -using namespace std; - -extern KateParser *parser; - -%} - -%locations - -%union { - int int_val; - double double_val; - bool bool_val; - char *string_val; - char *ident_val; - struct var *v; - void *ptr; -} - -%token TOK_NOT_EQUAL "!=" -%token TOK_LESSER_E "<=" -%token TOK_GREATER_E ">=" -%token TOK_EQUAL_2 "==" - -%type type type_proc - -%% - -prog: KW_PROGRAM ident { parser->start($2); } prog_beg_glob_decl instructions { parser->endproc(0); } dev_procedures KW_ENDP ; - -number: integer_number - | TOK_DOUBLE - { - $$ = new var; - $$->type = KW_REEL; - $$->cl = var::LITTERAL; - $$->real = $1; - }; - -%% - -#include - -int main(void) -{ - puts("Hello, World!"); - return 0; -} diff --git a/part/tests/hl/highlight1.spec b/part/tests/hl/highlight1.spec deleted file mode 100644 index bc3b95b..0000000 --- a/part/tests/hl/highlight1.spec +++ /dev/null @@ -1,212 +0,0 @@ -# Test file for rpmspec.xml - -# Comments start with a # in column="0": - -# Some comment - -# When they don't start in column="0", that they are recognized as comments, but with an alert: - # This is a bad comment. -# RPM spec says clear that comments must start at the begin of the line. However, in practice -# the RPM software is more permissive, depending on the context. But for our syntax highlighting, -# we give, while recognizing the as comment, at least a little alert. Comments should not contain -# the character % (which is marked as warning), but 2 of them are okay: %%. TODO is higlighted. - -# A spec file starts with "Normal" context. Here, you can specify values for some tags: -Name: kradioripper-unstable # Note that here in no comment possible! -Name: name only _one_ word allowed -Name: %macro no further syntax check after macro! -# Some tags support only _one_ word as value -Version: 0.4test5 up-from-the-space-this-is-an-error -# Some tag can have parameters: Any char in paranthesis: -Summary: Recorder for internet radios (based on Streamripper) -Summary(de.UTF-8): Aufnahmeprogramm für Internetradios (basiert auf Streamripper) -# requiere free text: -License: License 1 2 3 -# requiere a well defines value: -Requires( / ( = ): Some, value() -# new type "switch" accepts: yes, no, 0, 1 -AutoReq: yes -AutoReq: yes invalid -AutoReq: %macro no further syntax check after macro! -AutoReq: no -AutoReq: 0 -AutoReq: 1 -# requiere a number: -Epoch: 123123 -Epoch: 123123 invalid -Epoch: %macro no further syntax check afer macro! -# If tags are used that are not known, they are not highlighted: -Invalidtag: Some value -Invalid content in this section (only tags are allowed) - -# You can use conditions in specs (highlighted with region markers): -%if 0%{?mandriva_version} -# numbers and strings are distingished: string: -%if lsdksfj -# number: -%if 23472398 -# string: -%if lksdjfsl72939 -# invalid: -%if 92437lsdkfjdsl -# valid: -%if "lsdfj %ksdf(sdfs) 3489" -Release: %mkrel 1.2 -%else -Release: 0 -%endif -# requiere a well defined value: -%ifos fixed_value -# You must use these special macros (%%if etc.) always at the start of the line - if not, -# that's bad but not an arror. You must also always use the specified form. Everything else is an -# error: - %if -something %if -%{if} -%if(some options) -# However, this are different macros and therefore correct: -%ifx -%{ifx} -%ifx(some options) - -# the \ is escaped in the line. At the end of the line it escapes the line break: -echo This is \" a text \\ and here\ -it continues. - -%define name value -%define invalid_näme value -%define macroname multi\ -line content with references like %0 %* %# %{-f} %{-f*} %1 %2 and so on -%global name value -%global invalid_näme value -%undefine name -%undefine name too-many-parameters - -# This special comment is treated and highlighted like a tag: -# norootforbuild -# It can't have parameters, so every following non-whitespace character is not good: -# norootforbuild DONT WRITE ANYTHING HERE! -# wrong spacing is also recognized: -# norootforbuild -# and also an indeet is not fine for norootforbuild: - # norootforbuild - -# This following "Conflicts" tag will be removed by set-version.sh, -# if it is a "kradioripper" release (and not a "kradioripper-unstable" release)... -Conflicts: kradioripper - - -%description -# Here, a new section starts. It contains a value for the RPM field "description" and is therefor -# colored like values: -A KDE program for ripping internet radios. Based on StreamRipper. - - -# A section start can have parameters: -%description -l de.UTF-8 -Ein KDE-Aufnahmeprogramm für Internetradios. Basiert auf StreamRipper. - -# These sections starts are errors: - %description not at the first line -%{description} wrong form -%description(no options allowed, only parameters!) - - -%prep -# This starts a section that defines the commands to prepare the build. -# q means quit. n sets the directory: -%setup -q -n kradioripper -echo Test -# Macros can have different forms: Valid: -%abc -%abcÄndOfMacro -%abc(def)EndOfMacro -%{abc}EndOfMacro -%{something but no single %}EndOfMacro -%{abc:def}EndOfMacro -%(abc) -# Invalid: -%ÄInvalidChar -% -%) -%} -# You can use macros inside of macro calls: Fine: -%{something %but no %{sin%(fine)gle} }EndOfMacro -# Bad: -%{No closing paranthesis (No syntax highlightig for this error available) - - -%build -cmake ./ -DCMAKE_INSTALL_PREFIX=%{_prefix} -%__make %{?jobs:-j %jobs} - - -%install -%if 0%{?suse_version} -%makeinstall -%suse_update_desktop_file kradioripper -%endif -%if 0%{?fedora_version} || 0%{?rhel_version} || 0%{?centos_version} -make install DESTDIR=%{buildroot} -desktop-file-install --delete-original --vendor fedora --dir=%{buildroot}/%{_datadir}/applications/kde4 %{buildroot}/%{_datadir}/applications/kde4/kradioripper.desktop -%endif -%if 0%{?mandriva_version} -%makeinstall_std -%endif - - -%clean -rm -rf "%{buildroot}" - - -%files -%defattr(-,root,root) -%if 0%{?fedora_version} || 0%{?rhel_version} || 0%{?centos_version} -%{_datadir}/applications/kde4/fedora-kradioripper.desktop -%else -%{_datadir}/applications/kde4/kradioripper.desktop -%endif -%{_bindir}/kradioripper -%{_datadir}/locale/*/LC_MESSAGES/kradioripper.mo -%if 0%{?mandriva_version} -# TODO The %%doc macro is actually broken for mandriva 2009 in build service... -%dir %{_datadir}/apps/kradioripper -%{_datadir}/apps/kradioripper/* -%else -%doc COPYING LICENSE LICENSE.GPL2 LICENSE.GPL3 NEWS WARRANTY -%dir %{_datadir}/kde4/apps/kradioripper -%{_datadir}/kde4/apps/kradioripper/* -%endif - - -%changelog -* Sun May 04 2008 email@email.com -- some text -- some text - in two lines -- some text - in two lines - + with subtext - - and more subtext - in two lines -* Tue Apr 24 2007 Name -- text - * When the star isn't at column 0, than it doesn't indicate - a new date -* Wen Sep 08 2003 Wrong weekday -* Mon Mai 08 2003 Wrong month -* Mon Sep 0 2003 bad day -* Mon Sep 8 2003 good day -* Mon Sep 08 2003 good day -* Mon Sep 32 2003 bad day -* Mon Sep 08 03 bad year -* Mon Sep 08 2003 Name -# When using macros, the error check is disabled: -* %myDataMacro Title of the entry -- Text - - can - - be - - indeeded - - without - - problems - diff --git a/part/tests/hl/highlight_lpc.c b/part/tests/hl/highlight_lpc.c deleted file mode 100644 index fe5c629..0000000 --- a/part/tests/hl/highlight_lpc.c +++ /dev/null @@ -1,64 +0,0 @@ -// NOTE: This is a test file for kate's LPC syntax highlighting. - -// This is a Single-Line Comment -/* This is a Multi- - Line Comment */ - -// This again is a Single-Line Comment which should end here /* - -// And this is an evil single line comment \ - which should include this and the next line because of the \ - Do not use this style at home, kids. -// BEGIN region marker - -// END of region marker - -private void create() -{ -// Some Preprocessor stuff: -#define SOME_STUFF if(foo("bar")) \ - { \ - bar("foo"); \ - } // Preprocessor, Keyword, Preprocessor-String, Multiline - - // Some closures: - #'create; - #'?!; - - - /* Some other Data Types: */ - - int i = 1; // Integer. - float b = 2.34; // Float. - int c = 0b001; // Binary - int e = 0x019Beef; // Hexadecimal - int f = 0o2345; // Octal - string a = "Wheee"; // String - string x = "Wheee\ - heee"; // Multi-Line String, again, don't use this. - - - - /* Some keywords: */ - if(1) - { - switch(2) - { - case 3: - 4; - break; - } - } - - else - { - return 0; - } -} - -/* -WARNING: If the above function is part of a multi-line comment, - it's buggy. The WARNING: itself should be a comment-keyword. - That's not actually part of the language, but simply used - to highlight important stuff inside comments like TODO: etc. -*/ diff --git a/part/tests/hl/highlight_ocaml.ml b/part/tests/hl/highlight_ocaml.ml deleted file mode 100644 index dc1717a..0000000 --- a/part/tests/hl/highlight_ocaml.ml +++ /dev/null @@ -1,105 +0,0 @@ -(* ocaml test file -- a big stew of Objective Caml syntax to use to - test Kate's syntax highlighting. This will not run! :-) *) - -(* First a little piece of real OCaml that should look right: *) - - #load "basic";; - (* Return a default value for a BASIC variable given its identifer. *) - let default_value (ident : string) : basic_value = - assert (String.length ident > 0); - match ident.[String.length ident - 1] with - | '$' -> Str "" - | '%' -> Int 0 - | '!' -> Flt 0.0 - | _ -> Flt 0.0 - ;; - -(* Directives: *) -#load "pa_o";; - #load "pa_o";; -object # meth ;; (* not a directive - a method call *) -object - # meth ;; (* not a directive - a method call *) - -(* OCaml keywords: *) -and as assert asr (* etc. there so many... *) - -(* Additional OCaml Revised Syntax keywords: *) -(* These are in a seperate category so they can be coloured to look - like identifiers when ordinary OCaml syntax is being used: *) -declare where value - -(* There's no way to reliably highlight all OCaml type expressions, - (they can be very complex) so just the built-in type names are highlighted.*) -exn lazy_t format unit int real char string ref array bool list option - - -let integers : int list = [ - 123456789; (* decimal *) - -0xabcedf0123456789; (* hexadecimal *) - 0xABCDEF0123456789; (* hexadecimal *) - -0o1234567; (* octal *) - 0b01001010101010; (* binary *) - -0Xabcedf0123456789; (* hexadecimal *) - 0XABCDEF0123456789; (* hexadecimal *) - -0O1234567; (* octal *) - 0B01001010101010; (* binary *) - -123_456_789; (* Underscores are allowed in numeric constants. *) - 0x_abce_df01_2345_6789; - -0o12_34_567; - 0b_0100_1010_1010_1101; -];; - -let floats : real list = [ - 12345.6789; - -1.23456789e4; (* All variations of the exponent form *) - 1.23456789e+4; - -1.23456789e-4; - 1.23456789E-4; - -1.23456789E+4; - 12_345.6789; (* Underscores are allowed in numeric constants. *) - -1.23_456_789e+4; - 12_345.6789; -];; - -let characters : char list = [ - 'a'; - ' '; - 'ä'; - '\n'; '\r'; '\t'; '\b'; (* Control characters. Only these four: not the full C-language range. *) - '\000'; '\128'; (* Decimal character codes. These are always 3 digits. *) - '\x02'; '\xff'; '\xFF'; (* Hexadecimal character codes. These are always 3 digits. *) - '\\'; '\''; '\"'; '"' (* Quote character escapes. *) -];; - -(* Quotes used to mark constants in parsers should - not be confused with character constant quotes. - "Ticks" at the end of identifiers should - not be confused with character constant quotes. *) -let basic_identifier = - parser - [< ''F'; ''N'; name = s >] -> ID (s, 'f') - | [< name = s' >] -> ID (s','i') -;; - -let strings : string list = [ - ""; (* Empty string *) - "a"; " "; "ä"; "ab"; - "A\nB"; "A\rB"; "A\tB"; "A\bB"; (* Control characters. Only these four: not the full C-language range. *) - "A\000B"; "A\128B"; (* Decimal character codes. These are always 3 digits. *) - "A\x02B"; "A\xffB"; "A\xFFB"; (* Hexadecimal character codes. These are always 3 digits. *) - "A\\B"; "A\'B"; "A'B"; "A\"B"; (* Quote character escapes. *) - "A multiline\ - string"; -]; - -let camlp4_quotations = [ - <> ; - <:QUOTE> ; - <:QUÖTÈ> ; - << A quote with an escape: \>> (end-quote symbol) >> ; - << A quote with an escape: \<< (plain start quote-symbol) >> ; - << A quote with an escape: \<:Trouvé< (labelled start-quote symbol) >> ; -];; - -(* end *) diff --git a/part/tests/hl/highlight_octave.m b/part/tests/hl/highlight_octave.m deleted file mode 100644 index 1f96036..0000000 --- a/part/tests/hl/highlight_octave.m +++ /dev/null @@ -1,74 +0,0 @@ -##===================================================== -% Octave test code for Kate/Kwrite syntax highlighting -% (shamelessly copied from Matlab's, since the two -% are very similar) -% kate: hl Octave; -##===================================================== - -% Numbers _____________________________________________ -5, 5.5, .1, 0.1, 0.4e5, 1.2e-5, 5i, 5.3i, 6j, .345+3i -5', 5.5', .1', 0.1', 0.4e5', 1.2e-5', 5i', 5.3i', 6j', .345+3i' - -% Operators ___________________________________________ -% relational operators -'asdf'~=4, c<=4, d>=4, ab, a==b, b||c, b&&c -% elementwise arithmetic operators -a.^b, a.*b a./b, 1:4:5 -% single-character binary arithmetic -a+3, a-3, a*2, a^3, a/3, a\3, a|b, a&b -% unary operators -a = ~g; g = @sfdgdsf(sdfsd,345); g.' + 1i.' - ('asdf').' -% separators and delimiter -(asd),[sadf];{asdf},;;,;;;() -% continuation -a = 1+ ... - 2; - -% Strings and adjoint _________________________________ -% incomplete strings -'string -'str'' -'str''ing -'str''\' -% complete strings -'string' % simple string -'''' '\'' % strings containing ' -'str''ing' % one string containing ' -'string' 'string' % two strings -'asdf' "asdf""" variable % two strings and a variable -'asdf''asdf'' fsgdfg' + (asdf)' - 'asdf'.' + []''''.';'' -'sadf'.' % string transpose -% adjoint -{'asdf'}' + 1 -('asdf')' + 1 -['asdf']' + 1 -'' var''' % empty string, var with >1 adjoints -[5]'*{5}'*('asd')'.'+(5)'*6'*asdf'*asdf'.' % many adjoints -A'*B + 1 % adjoint -A.'*B + 1 % transpose -A.'.'*B + 1 % double transpose -A'.' + 1 % adjoint, then transpose -A.'' % transpose, then adjoint - -% System command ______________________________________ -!hostname -!cp * /tmp - -% Reserved keywords ___________________________________ -function, persistent, global -endfunction - -switch, case, otherwise -endswitch - -if, else, elseif -endif - -try, end_try_catch -for, while, break, continue -endfor - -endwhile -return -function, FUNCTION, Function % case sensitive! -endfunction \ No newline at end of file diff --git a/part/tests/hl/test.js b/part/tests/hl/test.js deleted file mode 100644 index 2dfe86c..0000000 --- a/part/tests/hl/test.js +++ /dev/null @@ -1,134 +0,0 @@ -/* test.js - test for javascript.xml syntax file */ -// Note: this script will not, and is not supposed to, comile in any js engine. - -/* - NOTE: The words "todo", "fixme" and "note" should be rendered in a different style - within comments, match should be caseless (to test for regexp insensitive attribute). - The regex used for this rule is */ - String = /\b(?:fixme|todo|note)\b/ - /* Thus, for example "Notebook" is not caught by - this rule. (the "?:" in the subpattern is there to avoid the regex engine wasting time - saving a backref, which is not used for anything. I do not know if the overhead of parsing - that is greater than the time saved by not capturing the text...) - The rule for catching these words is placed in a context "Comment common", which is used - by both comment contexts (single line, multiline) using the new "IncludeRules" item. -*/ - -// test if regex support works - nice with new fallthrough prop in context:) -somestring.replace( /dooh/ , "bah!"); -re=/foo/ig; // hehe - -somestring.search( - /^foo\w+\s\d{0,15}$/ - ); - - re = - /dooh/; - -// This is supposedly legal: -re = somebool ? /foo/ : /bar/; - -// NOTE - Special case: an empty regex, not a comment. -// The rule uses a positive lookahead assertion to catch it: "//(?=;)". -re = //; -re = /a|b/; - -/* - Tests for the regex parser. - It will parse classes, quanitfiers, special characters and regex operaters, - as specified in the netscape documentation for javascript. - Regexps are only parsed in their clean form, as the RegExp(string) constructor - is using a quoted string. - TODO: Find out if more regex feats should be supported. - Consider using more itemDatas - assertion, quantifier are options. -*/ - -re = /^text\s+\d+\s*$/; -re = /a pattern with caret \(^\) in it/; -re = /(\d{0,4})\D/; -re = /[a-zA-Z_]+/; -re = /[^\d^]+/; -re = /\s+?\w+\.$/; -re = /\/\//; -re = /a|b/; - -// a test if #pop back from a comment will work -re = /*/foo/*/ /bar/; -// ^ POP -// ^ we got back after pop in comment, if there is regexp attribs here :-) - -/* - Some tests if the fallthrough works. - The fallthrough happens if a regexp is not found in a possible (!) position, - which is after "search(" or "replace(" or "=" or "?" or ":" in version 0.1 of the xml file -*/ - -var foo = 'bar'; -// ^ fallthrough! - - -somestring.replace( new RegExp("\\b\\w+\\b"), "word: $1"); -// ^ fallthrough expected. ("new" whould be bold) - - -something.method = - function ( a, b, c ) { /* ... */ } -// ^ fallthrough ?! - -something.other = -function ( d, e, f ) { /* ... */ } -// fallthrough expected at col 0 ("function" should be bold) - -var ary = new Array(5); -// ^ fallthrough ? (if keyword is correctly rendered) - -var b = a ? 1 : 0; -// ^ ^ fallthroughs. numbers must be rendered correctly. - -var c = d ? true : false; - -var conditinalstring = b ? - "something" : - "something else"; -// guess... - - -/* - Normal program flow... -*/ - -if (something) - dostuff(); -else - dont(); - - return; - -try { bla() } catch (e) { alert("ERROR! : " + e) } - -for (int i=0; i < j; i++) - document.write("i is" + i + "
"); - -while (something) -{ - block(); - picky: - if (!1) - break; - else - continue; -} - -with (a) { - do { - stuff( b ); // a.b if it exists - } while (itmakessense); -} - -switch (i) { - case 0: - f(); - break; - default: - break; -} diff --git a/part/tests/indenttest.cpp b/part/tests/indenttest.cpp deleted file mode 100644 index bf83765..0000000 --- a/part/tests/indenttest.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/** - * This file is part of the KDE project - * - * Copyright (C) 2001,2003 Peter Kelly (pmk@post.com) - * Copyright (C) 2003,2004 Stephan Kulow (coolo@kde.org) - * Copyright (C) 2004 Dirk Mueller ( mueller@kde.org ) - * Copyright 2006, 2007 Leo Savernik (l.savernik@aon.at) - * Copyright (C) 2010 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -//BEGIN Includes -#include "indenttest.h" - -#include "kateview.h" -#include "katedocument.h" -#include "katedocumenthelpers.h" -#include "kateconfig.h" -#include "katecmd.h" -#include "kateglobal.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "testutils.h" - -QTEST_KDEMAIN(IndentTest, GUI) - -/// somepath/kdelibs/part/tests/ -const QString srcPath(KDESRCDIR); -const QString testDataPath(KDESRCDIR "../../testdata/indent/"); - -#define FAILURE( test, comment ) qMakePair( (test), (comment) ) - -void IndentTest::initTestCase() -{ - KateGlobal::self()->incRef(); - m_toplevel = new KMainWindow(); - m_document = new KateDocument(true, false, false, m_toplevel); - m_view = static_cast(m_document->widget()); - m_env = new TestScriptEnv(m_document, m_outputCustomised); -} - -void IndentTest::cleanupTestCase() -{ - KateGlobal::self()->decRef(); -} - -void IndentTest::getTestData(const QString& indenter) -{ - QTest::addColumn("testcase"); - - // make sure the indenters are valid - QFile indenterFile(srcPath + "/../script/data/" + indenter + ".js"); - if (!indenterFile.exists()) { - QSKIP(qPrintable(QString(indenterFile.fileName() + " does not exist")), SkipAll); - } - QVERIFY(indenterFile.open(QFile::ReadOnly)); - QScriptValue result = m_env->engine()->evaluate(indenterFile.readAll(), indenterFile.fileName()); - QVERIFY2( !result.isError(), qPrintable(result.toString() + "\nat " - + m_env->engine()->uncaughtExceptionBacktrace().join("\n")) ); - - const QString testDir( testDataPath + indenter + '/' ); - if ( !QFile::exists(testDir) ) { - QSKIP(qPrintable(QString(testDir + " does not exist")), SkipAll); - } - QDirIterator contents( testDir ); - while ( contents.hasNext() ) { - QString entry = contents.next(); - if ( entry.endsWith('.') ) { - continue; - } - QFileInfo info(entry); - if ( !info.isDir() ) { - continue; - } - QTest::newRow( info.baseName().toLocal8Bit() ) << info.absoluteFilePath(); - } -} - -void IndentTest::runTest(const ExpectedFailures& failures) -{ - if ( !QFile::exists(testDataPath) ) - QSKIP(qPrintable(QString(testDataPath + " does not exist")), SkipAll); - - QFETCH(QString, testcase); - - m_toplevel->resize( 800, 600); // restore size - - // load page - KUrl url; - url.setProtocol("file"); - url.setPath(testcase + "/origin"); - m_document->openUrl(url); - - // evaluate test-script - QFile sourceFile(testcase + "/input.js"); - QVERIFY( sourceFile.open(QFile::ReadOnly) ); - - QTextStream stream(&sourceFile); - stream.setCodec("UTF8"); - QString code = stream.readAll(); - sourceFile.close(); - - // Execute script - QScriptValue result = m_env->engine()->evaluate(code, testcase + "/input.js", 1); - QVERIFY2( !result.isError(), result.toString().toUtf8().constData() ); - - url.setPath(testcase + "/actual"); - m_document->saveAs(url); - - // diff actual and expected - QProcess diff; - QStringList args; - args << "-u" << (testcase + "/expected") << (testcase + "/actual"); - diff.start("diff", args); - diff.waitForFinished(); - QByteArray out = diff.readAllStandardOutput(); - QByteArray err = diff.readAllStandardError(); - if ( !err.isEmpty() ) { - qWarning() << err; - } - foreach( const Failure& failure, failures ) { - QEXPECT_FAIL(failure.first, failure.second, Abort); - } - QCOMPARE(QString::fromLocal8Bit(out), QString()); - QCOMPARE(diff.exitCode(), EXIT_SUCCESS); - - m_document->closeUrl(); -} - -void IndentTest::cstyle_data() -{ - getTestData( "cstyle" ); -} - -void IndentTest::cstyle() -{ - runTest( ExpectedFailures() << FAILURE( "using1", "this is insane, those who write such code can cope with it :P" ) - << FAILURE( "using2", "this is insane, those who write such code can cope with it :P" ) - << FAILURE( "plist14", "in function signatures it might be wanted to use the indentation of the\n" - "opening paren instead of just increasing the indentation level like in function calls" ) - << FAILURE( "switch10", "test for case where cfgSwitchIndent = false; needs proper config-interface" ) - << FAILURE( "switch11", "test for case where cfgSwitchIndent = false; needs proper config-interface" ) - << FAILURE( "visib2", "test for access modifier where cfgAccessModifiers = 1;needs proper config interface" ) - << FAILURE( "visib3", "test for access modifier where cfgAccessModifiers = 1;needs proper config interface" ) - << FAILURE( "plist10", "low low prio, maybe wontfix: if the user wants to add a arg, he should do so and press enter afterwards" ) - << FAILURE( "switch13", "pure insanity, whoever wrote this test and expects that to be indented properly should stop writing code" ) - ); -} - -void IndentTest::haskell_data() -{ - getTestData( "haskell" ); -} - -void IndentTest::haskell() -{ - runTest( ExpectedFailures() ); -} - - -void IndentTest::ruby_data() -{ - getTestData( "ruby" ); -} - -void IndentTest::ruby() -{ - runTest( ExpectedFailures() << FAILURE( "block01", "Multiline blocks using {} is not supported" ) - << FAILURE( "block02", "Multiline blocks using {} is not supported" ) - ); -} - -void IndentTest::normal_data() -{ - getTestData( "normal" ); -} - -void IndentTest::normal() -{ - runTest( ExpectedFailures() << FAILURE( "emptyline1", "is that really what we expect?" ) - << FAILURE( "emptyline3", "is that really what we expext?" ) - ); -} diff --git a/part/tests/indenttest.h b/part/tests/indenttest.h deleted file mode 100644 index d111ff8..0000000 --- a/part/tests/indenttest.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef INDENTTEST_H -#define INDENTTEST_H - -#include -#include -#include - -class TestScriptEnv; -class KateDocument; -class KateView; -class KMainWindow; - -class IndentTest : public QObject -{ - Q_OBJECT -private slots: - void initTestCase(); - void cleanupTestCase(); - - void cstyle_data(); - void cstyle(); - - void ruby_data(); - void ruby(); - - void haskell_data(); - void haskell(); - - void normal_data(); - void normal(); - -private: - void getTestData(const QString& indenter); - - typedef QPair Failure; - typedef QList< Failure > ExpectedFailures; - void runTest(const ExpectedFailures& failures); - - TestScriptEnv* m_env; - KateDocument* m_document; - KMainWindow* m_toplevel; - bool m_outputCustomised; - QStringList m_commands; - KateView* m_view; -}; - -#endif // INDENTTEST_H diff --git a/part/tests/katedocument_test.cpp b/part/tests/katedocument_test.cpp deleted file mode 100644 index 5afefa0..0000000 --- a/part/tests/katedocument_test.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katedocument_test.h" -#include "moc_katedocument_test.cpp" - -#include - -#include -#include -#include -#include - -///TODO: is there a FindValgrind cmake command we could use to -/// define this automatically? -// comment this out and run the test case with: -// valgrind --tool=callgrind --instr-atstart=no ./katedocument_test testSetTextPerformance -// or similar -// -// #define USE_VALGRIND - -#ifdef USE_VALGRIND - #include -#endif - -using namespace KTextEditor; - -QTEST_KDEMAIN(KateDocumentTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor[" + QByteArray::number(cursor.line()) - + ", " + QByteArray::number(cursor.column()) + "]"; - return qstrdup(ba.data()); - } -} - -class MovingRangeInvalidator : public QObject { - Q_OBJECT -public: - explicit MovingRangeInvalidator( QObject* parent = 0 ) - : QObject(parent) - { - } - - void addRange(MovingRange* range) - { - m_ranges << range; - } - QList ranges() const - { - return m_ranges; - } - -public slots: - void aboutToInvalidateMovingInterfaceContent() - { - qDeleteAll(m_ranges); - m_ranges.clear(); - } - -private: - QList m_ranges; -}; - - -KateDocumentTest::KateDocumentTest() - : QObject() -{ -} - -KateDocumentTest::~KateDocumentTest() -{ -} - -// tests: -// KateDocument::insertText with word wrap enabled. It is checked whether the -// text is correctly wrapped and whether the moving cursors maintain the correct -// position. -// see also: http://bugs.kde.org/show_bug.cgi?id=168534 -void KateDocumentTest::testWordWrap() -{ - KateDocument doc (false, false, false); - doc.setWordWrap(true); - doc.setWordWrapAt(80); - - const QString content = ".........1.........2.........3.........4.........5.........6 ........7 ........8"; - const QString firstWrap = ".........1.........2.........3.........4.........5.........6 ........7\n....x....8"; - const QString secondWrap = ".........1.........2.........3.........4.........5.........6\n....ooooooooooo....7 ....x....8"; - doc.setText(content); - MovingCursor* c = doc.newMovingCursor(Cursor(0, 75), MovingCursor::MoveOnInsert); - - QCOMPARE(doc.text(), content); - QCOMPARE(c->toCursor(), Cursor(0, 75)); - - // type a character at (0, 75) - doc.insertText (c->toCursor(), "x"); - QCOMPARE(doc.text(), firstWrap); - QCOMPARE(c->toCursor(), Cursor(1, 5)); - - // set cursor to (0, 65) and type "ooooooooooo" - c->setPosition(Cursor(0, 65)); - doc.insertText (c->toCursor(), "ooooooooooo"); - QCOMPARE(doc.text(), secondWrap); - QCOMPARE(c->toCursor(), Cursor(1, 15)); -} - -void KateDocumentTest::testReplaceQStringList() -{ - KateDocument doc(false, false, false); - doc.setWordWrap(false); - doc.setText("asdf\n" - "foo\n" - "foo\n" - "bar\n"); - doc.replaceText( Range(1, 0, 3, 0), QStringList() << "new" << "text" << "", false ); - QCOMPARE(doc.text(), QString("asdf\n" - "new\n" - "text\n" - "bar\n")); -} - -void KateDocumentTest::testRemoveTrailingSpace() -{ - // https://bugs.kde.org/show_bug.cgi?id=242611 - KateDocument doc(false, false, false); - doc.setText("asdf \t "); - doc.config()->setRemoveTrailingDyn(true); - doc.editRemoveText(0, 0, 1); - QCOMPARE(doc.text(), QString("sdf")); -} - -void KateDocumentTest::testMovingInterfaceSignals() -{ - KateDocument* doc = new KateDocument(false, false, false); - QSignalSpy aboutToDeleteSpy(doc, SIGNAL(aboutToDeleteMovingInterfaceContent(KTextEditor::Document *))); - QSignalSpy aboutToInvalidateSpy(doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document *))); - - QCOMPARE(doc->revision(), qint64(0)); - - QCOMPARE(aboutToInvalidateSpy.count(), 0); - QCOMPARE(aboutToDeleteSpy.count(), 0); - - KTemporaryFile f; - f.open(); - doc->openUrl(KUrl::fromLocalFile(f.fileName())); - QCOMPARE(doc->revision(), qint64(0)); - //TODO: gets emitted once in closeFile and once in openFile - is that OK? - QCOMPARE(aboutToInvalidateSpy.count(), 2); - QCOMPARE(aboutToDeleteSpy.count(), 0); - - doc->documentReload(); - QCOMPARE(doc->revision(), qint64(0)); - QCOMPARE(aboutToInvalidateSpy.count(), 4); - //TODO: gets emitted once in closeFile and once in openFile - is that OK? - QCOMPARE(aboutToDeleteSpy.count(), 0); - - delete doc; - QCOMPARE(aboutToInvalidateSpy.count(), 4); - QCOMPARE(aboutToDeleteSpy.count(), 1); -} - -void KateDocumentTest::testSetTextPerformance() -{ - const int lines = 150; - const int columns = 80; - const int rangeLength = 4; - const int rangeGap = 1; - - Q_ASSERT(columns % (rangeLength + rangeGap) == 0); - - KateDocument doc(false, false, false); - MovingRangeInvalidator invalidator; - connect(&doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)), - &invalidator, SLOT(aboutToInvalidateMovingInterfaceContent())); - - QString text; - QVector ranges; - ranges.reserve(lines * columns / (rangeLength + rangeGap)); - const QString line = QString().fill('a', columns); - for(int l = 0; l < lines; ++l) { - text.append(line); - text.append('\n'); - for(int c = 0; c < columns; c += rangeLength + rangeGap) { - ranges << Range(l, c, l, c + rangeLength); - } - } - - // replace - QBENCHMARK { - // init - doc.setText(text); - foreach(const Range& range, ranges) { - invalidator.addRange(doc.newMovingRange(range)); - } - QCOMPARE(invalidator.ranges().size(), ranges.size()); - - #ifdef USE_VALGRIND - CALLGRIND_START_INSTRUMENTATION - #endif - - doc.setText(text); - - #ifdef USE_VALGRIND - CALLGRIND_STOP_INSTRUMENTATION - #endif - - QCOMPARE(doc.text(), text); - QVERIFY(invalidator.ranges().isEmpty()); - } -} - -#include "katedocument_test.moc" diff --git a/part/tests/katedocument_test.h b/part/tests/katedocument_test.h deleted file mode 100644 index c3ff38c..0000000 --- a/part/tests/katedocument_test.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_DOCUMENT_TEST_H -#define KATE_DOCUMENT_TEST_H - -#include - -class KateDocumentTest : public QObject -{ - Q_OBJECT - -public: - KateDocumentTest(); - ~KateDocumentTest(); - -private Q_SLOTS: - void testWordWrap(); - void testReplaceQStringList(); - void testRemoveTrailingSpace(); - void testMovingInterfaceSignals(); - - void testSetTextPerformance(); -}; - -#endif // KATE_DOCUMENT_TEST_H diff --git a/part/tests/katetextbuffertest.cpp b/part/tests/katetextbuffertest.cpp deleted file mode 100644 index 5548145..0000000 --- a/part/tests/katetextbuffertest.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * Copyright (C) 2010 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katetextbuffertest.h" -#include "katetextbuffer.h" -#include "katetextcursor.h" - -QTEST_MAIN(KateTextBufferTest) - -KateTextBufferTest::KateTextBufferTest() - : QObject() -{ -} - -KateTextBufferTest::~KateTextBufferTest() -{ -} - -void KateTextBufferTest::basicBufferTest() -{ - // construct an empty text buffer - Kate::TextBuffer buffer (0, 1); - - // one line per default - QVERIFY (buffer.lines() == 1); - QVERIFY (buffer.text () == ""); - - //FIXME: use QTestLib macros for checking the correct state - // start editing - buffer.startEditing (); - - // end editing - buffer.finishEditing (); -} - -void KateTextBufferTest::wrapLineTest() -{ - // construct an empty text buffer - Kate::TextBuffer buffer (0, 1); - - // wrap first empty line -> we should have two empty lines - buffer.startEditing (); - buffer.wrapLine(KTextEditor::Cursor(0, 0)); - buffer.finishEditing (); - buffer.debugPrint ("Two empty lines"); - QVERIFY (buffer.text () == "\n"); - - // unwrap again -> only one empty line - buffer.startEditing (); - buffer.unwrapLine(1); - buffer.finishEditing (); - - // print debug - buffer.debugPrint ("Empty Buffer"); - QVERIFY (buffer.text () == ""); -} - -void KateTextBufferTest::insertRemoveTextTest() -{ - // construct an empty text buffer - Kate::TextBuffer buffer (0, 1); - - // wrap first line - buffer.startEditing (); - buffer.wrapLine (KTextEditor::Cursor (0, 0)); - buffer.finishEditing (); - buffer.debugPrint ("Two empty lines"); - QVERIFY (buffer.text () == "\n"); - - // remember second line - Kate::TextLine second = buffer.line (1); - - // unwrap second line - buffer.startEditing (); - buffer.unwrapLine (1); - buffer.finishEditing (); - buffer.debugPrint ("One empty line"); - QVERIFY (buffer.text () == ""); - - // second text line should be still there - //const QString &secondText = second->text (); - //QVERIFY (secondText == "") - - // insert text - buffer.startEditing (); - buffer.insertText (KTextEditor::Cursor (0, 0), "testremovetext"); - buffer.finishEditing (); - buffer.debugPrint ("One line"); - QVERIFY (buffer.text () == "testremovetext"); - - // remove text - buffer.startEditing (); - buffer.removeText (KTextEditor::Range (KTextEditor::Cursor (0, 4), KTextEditor::Cursor (0, 10))); - buffer.finishEditing (); - buffer.debugPrint ("One line"); - QVERIFY (buffer.text () == "testtext"); - - // wrap text - buffer.startEditing (); - buffer.wrapLine (KTextEditor::Cursor (0, 2)); - buffer.finishEditing (); - buffer.debugPrint ("Two line"); - QVERIFY (buffer.text () == "te\nsttext"); - - // unwrap text - buffer.startEditing (); - buffer.unwrapLine (1); - buffer.finishEditing (); - buffer.debugPrint ("One line"); - QVERIFY (buffer.text () == "testtext"); -} - -void KateTextBufferTest::cursorTest() -{ - // last buffer content, for consistence checks - QString lastBufferContent; - - // test with different block sizes - for (int i = 1; i <= 4; ++i) { - // construct an empty text buffer - Kate::TextBuffer buffer (0, i); - - // wrap first line - buffer.startEditing (); - buffer.insertText (KTextEditor::Cursor (0, 0), "sfdfjdsklfjlsdfjlsdkfjskldfjklsdfjklsdjkfl"); - buffer.wrapLine (KTextEditor::Cursor (0, 8)); - buffer.wrapLine (KTextEditor::Cursor (1, 8)); - buffer.wrapLine (KTextEditor::Cursor (2, 8)); - buffer.finishEditing (); - buffer.debugPrint ("Cursor buffer"); - - // construct cursor - Kate::TextCursor *cursor1 = new Kate::TextCursor (buffer, KTextEditor::Cursor (0, 0), Kate::TextCursor::MoveOnInsert); - QVERIFY (cursor1->toCursor () == KTextEditor::Cursor (0, 0)); - printf ("cursor %d, %d\n", cursor1->line(), cursor1->column()); - - Kate::TextCursor *cursor2 = new Kate::TextCursor (buffer, KTextEditor::Cursor (1, 8), Kate::TextCursor::MoveOnInsert); - printf ("cursor %d, %d\n", cursor2->line(), cursor2->column()); - - Kate::TextCursor *cursor3 = new Kate::TextCursor (buffer, KTextEditor::Cursor (0, 123), Kate::TextCursor::MoveOnInsert); - printf ("cursor %d, %d\n", cursor3->line(), cursor3->column()); - - Kate::TextCursor *cursor4 = new Kate::TextCursor (buffer, KTextEditor::Cursor (1323, 1), Kate::TextCursor::MoveOnInsert); - printf ("cursor %d, %d\n", cursor4->line(), cursor4->column()); - - // insert text - buffer.startEditing (); - buffer.insertText (KTextEditor::Cursor (0, 0), "hallo"); - buffer.finishEditing (); - buffer.debugPrint ("Cursor buffer"); - - printf ("cursor %d, %d\n", cursor1->line(), cursor1->column()); - QVERIFY (cursor1->toCursor () == KTextEditor::Cursor (0, 5)); - - // remove text - buffer.startEditing (); - buffer.removeText (KTextEditor::Range (KTextEditor::Cursor (0, 4), KTextEditor::Cursor (0, 10))); - buffer.finishEditing (); - buffer.debugPrint ("Cursor buffer"); - - printf ("cursor %d, %d\n", cursor1->line(), cursor1->column()); - QVERIFY (cursor1->toCursor () == KTextEditor::Cursor (0, 4)); - - // wrap line - buffer.startEditing (); - buffer.wrapLine (KTextEditor::Cursor (0, 3)); - buffer.finishEditing (); - buffer.debugPrint ("Cursor buffer"); - - printf ("cursor %d, %d\n", cursor1->line(), cursor1->column()); - QVERIFY (cursor1->toCursor () == KTextEditor::Cursor (1, 1)); - - // unwrap line - buffer.startEditing (); - buffer.unwrapLine (1); - buffer.finishEditing (); - buffer.debugPrint ("Cursor buffer"); - - printf ("cursor %d, %d\n", cursor1->line(), cursor1->column()); - QVERIFY (cursor1->toCursor () == KTextEditor::Cursor (0, 4)); - - // verify content - if (i > 1) - QVERIFY (lastBufferContent == buffer.text ()); - - // remember content - lastBufferContent = buffer.text (); - } -} diff --git a/part/tests/katetextbuffertest.h b/part/tests/katetextbuffertest.h deleted file mode 100644 index 3eb08ba..0000000 --- a/part/tests/katetextbuffertest.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the Kate project. - * - * Copyright (C) 2010 Christoph Cullmann - * Copyright (C) 2010 Dominik Haumann - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATEBUFFERTEST_H -#define KATEBUFFERTEST_H - -#include -#include - -class KateTextBufferTest : public QObject -{ - Q_OBJECT - - public: - KateTextBufferTest(); - virtual ~KateTextBufferTest(); - - private Q_SLOTS: - void basicBufferTest(); - void wrapLineTest(); - void insertRemoveTextTest(); - void cursorTest(); -}; - -#endif // KATEBUFFERTEST_H diff --git a/part/tests/kateview_test.cpp b/part/tests/kateview_test.cpp deleted file mode 100644 index ed15666..0000000 --- a/part/tests/kateview_test.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Milian Wolff - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateview_test.h" -#include "moc_kateview_test.cpp" - -#include - -#include -#include -#include -#include -#include - -using namespace KTextEditor; - -QTEST_KDEMAIN(KateViewTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor[" + QByteArray::number(cursor.line()) - + ", " + QByteArray::number(cursor.column()) + "]"; - return qstrdup(ba.data()); - } -} - - -KateViewTest::KateViewTest() - : QObject() -{ -} - -KateViewTest::~KateViewTest() -{ -} - -void KateViewTest::testReloadMultipleViews() -{ - KTemporaryFile file; - file.setSuffix(".cpp"); - file.open(); - QTextStream stream(&file); - const QString line = "const char* foo = \"asdf\"\n"; - for ( int i = 0; i < 200; ++i ) { - stream << line; - } - stream << flush; - file.close(); - - KateDocument doc(false, false, false); - QVERIFY(doc.openUrl(KUrl(file.fileName()))); - QCOMPARE(doc.highlightingMode(), QString("C++")); - - KateView* view1 = new KateView(&doc, 0); - KateView* view2 = new KateView(&doc, 0); - view1->show(); - view2->show(); - QCOMPARE(doc.views().count(), 2); - - QVERIFY(doc.documentReload()); -} diff --git a/part/tests/kateview_test.h b/part/tests/kateview_test.h deleted file mode 100644 index c34896c..0000000 --- a/part/tests/kateview_test.h +++ /dev/null @@ -1,37 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Milian Wolff - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_VIEW_TEST_H -#define KATE_VIEW_TEST_H - -#include - -class KateViewTest : public QObject -{ - Q_OBJECT - -public: - KateViewTest(); - ~KateViewTest(); - -private Q_SLOTS: - void testReloadMultipleViews(); -}; - -#endif // KATE_VIEW_TEST_H diff --git a/part/tests/movingcursor_test.cpp b/part/tests/movingcursor_test.cpp deleted file mode 100644 index a279b81..0000000 --- a/part/tests/movingcursor_test.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "movingcursor_test.h" -#include "moc_movingcursor_test.cpp" - -#include - -#include -#include - -using namespace KTextEditor; - -QTEST_KDEMAIN(MovingCursorTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor[" + QByteArray::number(cursor.line()) - + ", " + QByteArray::number(cursor.column()) + "]"; - return qstrdup(ba.data()); - } -} - -MovingCursorTest::MovingCursorTest() - : QObject() -{ -} - -MovingCursorTest::~MovingCursorTest() -{ -} - -// tests: -// - MovingCursor with StayOnInsert -// - MovingCursor with MoveOnInsert -void MovingCursorTest::testMovingCursor() -{ - KateDocument doc (false, false, false); - MovingCursor* invalid = doc.newMovingCursor(Cursor::invalid()); - MovingCursor* moveOnInsert = doc.newMovingCursor(Cursor(0, 0), MovingCursor::MoveOnInsert); - MovingCursor* stayOnInsert = doc.newMovingCursor(Cursor(0, 0), MovingCursor::StayOnInsert); - - // verify initial conditions - QVERIFY(!invalid->isValid()); - QCOMPARE(moveOnInsert->toCursor(), Cursor(0, 0)); - QCOMPARE(stayOnInsert->toCursor(), Cursor(0, 0)); - - // insert some text - doc.insertText(Cursor(0, 0), "\n" - "1\n" - "22"); - - // check new cursor positions - QCOMPARE(moveOnInsert->toCursor(), Cursor(2, 2)); - QCOMPARE(stayOnInsert->toCursor(), Cursor(0, 0)); - - // set position to (1, 1) and insert text before cursor - stayOnInsert->setPosition(Cursor(1, 1)); - QCOMPARE(stayOnInsert->toCursor(), Cursor(1, 1)); - doc.insertText(Cursor(1, 0), "test"); - QCOMPARE(stayOnInsert->toCursor(), Cursor(1, 5)); - doc.undo(); - QCOMPARE(stayOnInsert->toCursor(), Cursor(1, 1)); - - // position still at (1, 1). insert text at cursor - doc.insertText(Cursor(1, 1), "test"); - QCOMPARE(stayOnInsert->toCursor(), Cursor(1, 1)); - doc.undo(); - QCOMPARE(stayOnInsert->toCursor(), Cursor(1, 1)); - - // - // same tests with the moveOnInsert cursor - // - // set position to (1, 1) and insert text before cursor - moveOnInsert->setPosition(Cursor(1, 1)); - QCOMPARE(moveOnInsert->toCursor(), Cursor(1, 1)); - doc.insertText(Cursor(1, 0), "test"); - QCOMPARE(moveOnInsert->toCursor(), Cursor(1, 5)); - doc.undo(); - QCOMPARE(moveOnInsert->toCursor(), Cursor(1, 1)); - - // position still at (1, 1). insert text at cursor - doc.insertText(Cursor(1, 1), "test"); - QCOMPARE(moveOnInsert->toCursor(), Cursor(1, 5)); - doc.undo(); - QCOMPARE(moveOnInsert->toCursor(), Cursor(1, 1)); - - // set both cursors to (2, 1) then delete text range that contains cursors - moveOnInsert->setPosition(Cursor(2, 1)); - stayOnInsert->setPosition(Cursor(2, 1)); - doc.removeText(Range(Cursor(2, 0), Cursor(2, 2))); - QCOMPARE(moveOnInsert->toCursor(), Cursor(2, 0)); - QCOMPARE(moveOnInsert->toCursor(), Cursor(2, 0)); -} - -// tests: -// - atStartOfDocument -// - atStartOfLine -// - atEndOfDocument -// - atEndOfLine -// - move forward with Wrap -// - move forward with NoWrap -// - move backward -// - gotoNextLine -// - gotoPreviousLine -void MovingCursorTest::testConvenienceApi() -{ - KateDocument doc (false, false, false); - doc.setText("\n" - "1\n" - "22\n" - "333\n" - "4444\n" - "55555"); - - // check start and end of document - MovingCursor *startOfDoc = doc.newMovingCursor(Cursor(0, 0)); - MovingCursor *endOfDoc = doc.newMovingCursor(Cursor(5, 5)); - QVERIFY(startOfDoc->atStartOfDocument()); - QVERIFY(startOfDoc->atStartOfLine()); - QVERIFY(endOfDoc->atEndOfDocument()); - QVERIFY(endOfDoc->atEndOfLine()); - - // set cursor to (2, 2) and then move to the left two times - MovingCursor *moving = doc.newMovingCursor(Cursor(2, 2)); - QVERIFY(moving->atEndOfLine()); // at 2, 2 - QVERIFY(moving->move(-1)); // at 2, 1 - QCOMPARE(moving->toCursor(), Cursor(2, 1)); - QVERIFY(!moving->atEndOfLine()); - QVERIFY(moving->move(-1)); // at 2, 0 - QCOMPARE(moving->toCursor(), Cursor(2, 0)); - QVERIFY(moving->atStartOfLine()); - - // now move again to the left, should wrap to (1, 1) - QVERIFY(moving->move(-1)); // at 1, 1 - QCOMPARE(moving->toCursor(), Cursor(1, 1)); - QVERIFY(moving->atEndOfLine()); - - // advance 7 characters to position (3, 3) - QVERIFY(moving->move(7)); // at 3, 3 - QCOMPARE(moving->toCursor(), Cursor(3, 3)); - - // advance 20 characters in NoWrap mode, then go back 10 characters - QVERIFY(moving->move(20, MovingCursor::NoWrap)); // at 3, 23 - QCOMPARE(moving->toCursor(), Cursor(3, 23)); - QVERIFY(moving->move(-10)); // at 3, 13 - QCOMPARE(moving->toCursor(), Cursor(3, 13)); - - // still at invalid text position. move one char to wrap around - QVERIFY(!moving->isValidTextPosition()); // at 3, 13 - QVERIFY(moving->move(1)); // at 4, 0 - QCOMPARE(moving->toCursor(), Cursor(4, 0)); - - // moving 11 characters in wrap mode moves to (5, 6), which is not a valid - // text position anymore. Hence, moving should be rejected. - QVERIFY(!moving->move(11)); - QVERIFY(moving->move(10)); - QVERIFY(moving->atEndOfDocument()); - - // try to move to next line, which fails. then go to previous line - QVERIFY(!moving->gotoNextLine()); - QVERIFY(moving->gotoPreviousLine()); - QCOMPARE(moving->toCursor(), Cursor(4, 0)); -} - -void MovingCursorTest::testOperators() -{ - KateDocument doc (false, false, false); - doc.setText("--oo--\n" - "--oo--\n" - "--oo--"); - - // create lots of cursors for comparison - Cursor invalid = Cursor::invalid(); - Cursor c02(0, 2); - Cursor c04(0, 4); - Cursor c14(1, 4); - - MovingCursor* m02 = doc.newMovingCursor(Cursor(0, 2)); - MovingCursor* m04 = doc.newMovingCursor(Cursor(0, 4)); - MovingCursor* m14 = doc.newMovingCursor(Cursor(1, 4)); - - // invalid comparison - QVERIFY(invalid == invalid); - QVERIFY(invalid <= c02); - QVERIFY(invalid < c02); - QVERIFY(!(invalid > c02)); - QVERIFY(!(invalid >= c02)); - - QVERIFY(!(invalid == *m02)); - QVERIFY(invalid <= *m02); - QVERIFY(invalid < *m02); - QVERIFY(!(invalid > *m02)); - QVERIFY(!(invalid >= *m02)); - - QVERIFY(!(*m02 == invalid)); - QVERIFY(!(*m02 <= invalid)); - QVERIFY(!(*m02 < invalid)); - QVERIFY(*m02 > invalid); - QVERIFY(*m02 >= invalid); - - // MovingCursor <-> MovingCursor - QVERIFY(*m02 == *m02); - QVERIFY(*m02 <= *m02); - QVERIFY(*m02 >= *m02); - QVERIFY(!(*m02 < *m02)); - QVERIFY(!(*m02 > *m02)); - QVERIFY(!(*m02 != *m02)); - - QVERIFY(!(*m02 == *m04)); - QVERIFY(*m02 <= *m04); - QVERIFY(!(*m02 >= *m04)); - QVERIFY(*m02 < *m04); - QVERIFY(!(*m02 > *m04)); - QVERIFY(*m02 != *m04); - - QVERIFY(!(*m04 == *m02)); - QVERIFY(!(*m04 <= *m02)); - QVERIFY(*m04 >= *m02); - QVERIFY(!(*m04 < *m02)); - QVERIFY(*m04 > *m02); - QVERIFY(*m04 != *m02); - - QVERIFY(!(*m02 == *m14)); - QVERIFY(*m02 <= *m14); - QVERIFY(!(*m02 >= *m14)); - QVERIFY(*m02 < *m14); - QVERIFY(!(*m02 > *m14)); - QVERIFY(*m02 != *m14); - - QVERIFY(!(*m14 == *m02)); - QVERIFY(!(*m14 <= *m02)); - QVERIFY(*m14 >= *m02); - QVERIFY(!(*m14 < *m02)); - QVERIFY(*m14 > *m02); - QVERIFY(*m14 != *m02); - - // MovingCursor <-> Cursor - QVERIFY(*m02 == c02); - QVERIFY(*m02 <= c02); - QVERIFY(*m02 >= c02); - QVERIFY(!(*m02 < c02)); - QVERIFY(!(*m02 > c02)); - QVERIFY(!(*m02 != c02)); - - QVERIFY(!(*m02 == c04)); - QVERIFY(*m02 <= c04); - QVERIFY(!(*m02 >= c04)); - QVERIFY(*m02 < c04); - QVERIFY(!(*m02 > c04)); - QVERIFY(*m02 != c04); - - QVERIFY(!(*m04 == c02)); - QVERIFY(!(*m04 <= c02)); - QVERIFY(*m04 >= c02); - QVERIFY(!(*m04 < c02)); - QVERIFY(*m04 > c02); - QVERIFY(*m04 != c02); - - QVERIFY(!(*m02 == c14)); - QVERIFY(*m02 <= c14); - QVERIFY(!(*m02 >= c14)); - QVERIFY(*m02 < c14); - QVERIFY(!(*m02 > c14)); - QVERIFY(*m02 != c14); - - QVERIFY(!(*m14 == c02)); - QVERIFY(!(*m14 <= c02)); - QVERIFY(*m14 >= c02); - QVERIFY(!(*m14 < c02)); - QVERIFY(*m14 > c02); - QVERIFY(*m14 != c02); - - // Cursor <-> MovingCursor - QVERIFY(c02 == *m02); - QVERIFY(c02 <= *m02); - QVERIFY(c02 >= *m02); - QVERIFY(!(c02 < *m02)); - QVERIFY(!(c02 > *m02)); - QVERIFY(!(c02 != *m02)); - - QVERIFY(!(c02 == *m04)); - QVERIFY(c02 <= *m04); - QVERIFY(!(c02 >= *m04)); - QVERIFY(c02 < *m04); - QVERIFY(!(c02 > *m04)); - QVERIFY(c02 != *m04); - - QVERIFY(!(c04 == *m02)); - QVERIFY(!(c04 <= *m02)); - QVERIFY(c04 >= *m02); - QVERIFY(!(c04 < *m02)); - QVERIFY(c04 > *m02); - QVERIFY(c04 != *m02); - - QVERIFY(!(c02 == *m14)); - QVERIFY(c02 <= *m14); - QVERIFY(!(c02 >= *m14)); - QVERIFY(c02 < *m14); - QVERIFY(!(c02 > *m14)); - QVERIFY(c02 != *m14); - - QVERIFY(!(c14 == *m02)); - QVERIFY(!(c14 <= *m02)); - QVERIFY(c14 >= *m02); - QVERIFY(!(c14 < *m02)); - QVERIFY(c14 > *m02); - QVERIFY(c14 != *m02); -} diff --git a/part/tests/movingcursor_test.h b/part/tests/movingcursor_test.h deleted file mode 100644 index 03d814a..0000000 --- a/part/tests/movingcursor_test.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_MOVINGCURSOR_TEST_H -#define KATE_MOVINGCURSOR_TEST_H - -#include - -class MovingCursorTest : public QObject -{ - Q_OBJECT - -public: - MovingCursorTest(); - ~MovingCursorTest(); - -private Q_SLOTS: - void testMovingCursor(); - void testConvenienceApi(); - void testOperators(); -}; - -#endif // KATE_MOVINGCURSOR_TEST_H diff --git a/part/tests/movingrange_test.cpp b/part/tests/movingrange_test.cpp deleted file mode 100644 index 774c531..0000000 --- a/part/tests/movingrange_test.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "movingrange_test.h" -#include "moc_movingrange_test.cpp" - -#include -#include - -#include -#include -#include -#include - -using namespace KTextEditor; - -QTEST_KDEMAIN(MovingRangeTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor[" + QByteArray::number(cursor.line()) - + ", " + QByteArray::number(cursor.column()) + "]"; - return qstrdup(ba.data()); - } -} - - -class RangeFeedback : public MovingRangeFeedback -{ - public: - RangeFeedback() : MovingRangeFeedback() { reset(); } - - virtual void rangeEmpty (MovingRange* range) { - m_rangeEmptyCalled = true; - } - - virtual void rangeInvalid (MovingRange* range) { - m_rangeInvalidCalled = true; - } - - virtual void mouseEnteredRange (MovingRange* range, View* view) { - m_mouseEnteredRangeCalled = true; - } - - virtual void mouseExitedRange (MovingRange* range, View* view) { - m_mouseExitedRangeCalled = true; - } - - virtual void caretEnteredRange (MovingRange* range, View* view) { - m_caretEnteredRangeCalled = true; - } - - virtual void caretExitedRange (MovingRange* range, View* view) { - m_caretExitedRangeCalled = true; - } - - // - // Test functions to reset feedback watcher - // - public: - void reset() { - m_rangeEmptyCalled = false; - m_rangeInvalidCalled = false; - m_mouseEnteredRangeCalled = false; - m_mouseExitedRangeCalled = false; - m_caretEnteredRangeCalled = false; - m_caretExitedRangeCalled = false; - } - - void verifyReset() { - QVERIFY(!m_rangeEmptyCalled); - QVERIFY(!m_rangeInvalidCalled); - QVERIFY(!m_mouseEnteredRangeCalled); - QVERIFY(!m_mouseExitedRangeCalled); - QVERIFY(!m_caretEnteredRangeCalled); - QVERIFY(!m_caretExitedRangeCalled); - } - - bool rangeEmptyCalled() const { return m_rangeEmptyCalled; } - bool rangeInvalidCalled() const { return m_rangeInvalidCalled; } - bool mouseEnteredRangeCalled() const { return m_mouseEnteredRangeCalled; } - bool mouseExitedRangeCalled() const { return m_mouseExitedRangeCalled; } - bool caretEnteredRangeCalled() const { return m_caretEnteredRangeCalled; } - bool caretExitedRangeCalled() const { return m_caretExitedRangeCalled; } - - private: - bool m_rangeEmptyCalled; - bool m_rangeInvalidCalled; - bool m_mouseEnteredRangeCalled; - bool m_mouseExitedRangeCalled; - bool m_caretEnteredRangeCalled; - bool m_caretExitedRangeCalled; -}; - - -MovingRangeTest::MovingRangeTest() - : QObject() -{ -} - -MovingRangeTest::~MovingRangeTest() -{ -} - -// tests: -// - RangeFeedback::rangeEmpty -void MovingRangeTest::testFeedbackEmptyRange() -{ - KateDocument doc (false, false, false); - // the range created below will span the 'x' characters - QString text("..xxxx\n" - "xxxx.."); - doc.setText(text); - - // create range feedback - RangeFeedback rf; - - // allow empty - MovingRange* range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), - KTextEditor::MovingRange::DoNotExpand, - KTextEditor::MovingRange::AllowEmpty); - range->setFeedback(&rf); - rf.verifyReset(); - - // remove exact range - doc.removeText(range->toRange()); - QVERIFY(rf.rangeEmptyCalled()); - QVERIFY(!rf.rangeInvalidCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // clear document: should call rangeInvalid - rf.reset(); - rf.verifyReset(); - doc.clear(); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // setText: should behave just like clear document: call rangeInvalid again - doc.setText(text); - range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); - rf.reset(); - rf.verifyReset(); - doc.setText("--yyyy\nyyyy--"); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // now remove entire document range. In this case, emptyRange should be called - // instead of rangeInvalid - doc.setText(text); - range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); - rf.reset(); - rf.verifyReset(); - doc.removeText(doc.documentRange()); - QVERIFY(rf.rangeEmptyCalled()); - QVERIFY(!rf.rangeInvalidCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); -} - -// tests: -// - RangeFeedback::rangeInvalid -void MovingRangeTest::testFeedbackInvalidRange() -{ - KateDocument doc (false, false, false); - // the range created below will span the 'x' characters - QString text("..xxxx\n" - "xxxx.."); - doc.setText(text); - - // create range feedback - RangeFeedback rf; - - // allow empty - MovingRange* range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), - KTextEditor::MovingRange::DoNotExpand, - KTextEditor::MovingRange::InvalidateIfEmpty); - range->setFeedback(&rf); - rf.verifyReset(); - - // remove exact range - doc.removeText(range->toRange()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // clear document: should call rangeInvalid again - doc.setText(text); - range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); - rf.reset(); - rf.verifyReset(); - doc.clear(); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // setText: should behave just like clear document: call rangeInvalid again - doc.setText(text); - range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); - rf.reset(); - rf.verifyReset(); - doc.setText("--yyyy\nyyyy--"); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - // now remove entire document range. Call rangeInvalid again - doc.setText(text); - range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); - rf.reset(); - rf.verifyReset(); - doc.removeText(doc.documentRange()); - QVERIFY(rf.rangeInvalidCalled()); - QVERIFY(!rf.rangeEmptyCalled()); - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); -} - -// tests: -// - RangeFeedback::caretEnteredRange -// - RangeFeedback::caretExitedRange -void MovingRangeTest::testFeedbackCaret() -{ - KateDocument doc (false, false, false); - // the range created below will span the 'x' characters - QString text("..xxxx\n" - "xxxx.."); - doc.setText(text); - - KateView* view = static_cast(doc.createView(0)); - - // create range feedback - RangeFeedback rf; - - // first test: with ExpandLeft | ExpandRight - { - view->setCursorPosition(Cursor(1, 6)); - - MovingRange* range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), - KTextEditor::MovingRange::ExpandLeft | - KTextEditor::MovingRange::ExpandRight, - KTextEditor::MovingRange::InvalidateIfEmpty); - rf.reset(); - range->setFeedback(&rf); - rf.verifyReset(); - - // left - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 5)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 4)); - QVERIFY(rf.caretEnteredRangeCalled()); // ExpandRight: include cursor already now - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 3)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->up(); - QCOMPARE(view->cursorPosition(), Cursor(0, 3)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(0, 2)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(0, 1)); // ExpandLeft: now we left it, not before - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(rf.caretExitedRangeCalled()); - - delete range; - } - - - // second test: with DoNotExpand - { - view->setCursorPosition(Cursor(1, 6)); - - MovingRange* range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), - KTextEditor::MovingRange::DoNotExpand, - KTextEditor::MovingRange::InvalidateIfEmpty); - rf.reset(); - range->setFeedback(&rf); - rf.verifyReset(); - - // left - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 5)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 4)); - QVERIFY(!rf.caretEnteredRangeCalled()); // DoNotExpand: does not include cursor - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(1, 3)); - QVERIFY(rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->up(); - QCOMPARE(view->cursorPosition(), Cursor(0, 3)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(0, 2)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(rf.caretExitedRangeCalled()); // DoNotExpand: that's why we leave already now - - rf.reset(); - view->cursorLeft(); - QCOMPARE(view->cursorPosition(), Cursor(0, 1)); - QVERIFY(!rf.caretEnteredRangeCalled()); - QVERIFY(!rf.caretExitedRangeCalled()); - - delete range; - } -} - -// tests: -// - RangeFeedback::mouseEnteredRange -// - RangeFeedback::mouseExitedRange -void MovingRangeTest::testFeedbackMouse() -{ - KateDocument doc (false, false, false); - // the range created below will span the 'x' characters - QString text("..xxxx\n" - "xxxx.."); - doc.setText(text); - - KateView* view = static_cast(doc.createView(0)); - view->setCursorPosition(Cursor(1, 6)); - view->show(); - view->resize(200, 100); - - // create range feedback - RangeFeedback rf; - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - - // allow empty - MovingRange* range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), - KTextEditor::MovingRange::ExpandLeft | - KTextEditor::MovingRange::ExpandRight, - KTextEditor::MovingRange::InvalidateIfEmpty); - range->setFeedback(&rf); - rf.verifyReset(); - - // left (nothing) - QTest::mouseMove(view, view->cursorToCoordinate(Cursor(0, 0)) + QPoint(0, 5)); - QTest::qWait(200); // process mouse events. do not move mouse manually - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - - // middle (enter) - rf.reset(); - QTest::mouseMove(view, view->cursorToCoordinate(Cursor(0, 3)) + QPoint(0, 5)); - QTest::qWait(200); // process mouse events. do not move mouse manually - QVERIFY(rf.mouseEnteredRangeCalled()); - QVERIFY(!rf.mouseExitedRangeCalled()); - - // right (exit) - rf.reset(); - QTest::mouseMove(view, view->cursorToCoordinate(Cursor(1, 6)) + QPoint(10, 5)); - QTest::qWait(200); // process mouse events. do not move mouse manually - QVERIFY(!rf.mouseEnteredRangeCalled()); - QVERIFY(rf.mouseExitedRangeCalled()); -} diff --git a/part/tests/movingrange_test.h b/part/tests/movingrange_test.h deleted file mode 100644 index 3b9eade..0000000 --- a/part/tests/movingrange_test.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_MOVINGRANGE_TEST_H -#define KATE_MOVINGRANGE_TEST_H - -#include - -class MovingRangeTest : public QObject -{ - Q_OBJECT - -public: - MovingRangeTest(); - ~MovingRangeTest(); - -private Q_SLOTS: - void testFeedbackEmptyRange(); - void testFeedbackInvalidRange(); - void testFeedbackCaret(); - void testFeedbackMouse(); -}; - -#endif // KATE_MOVINGRANGE_TEST_H diff --git a/part/tests/plaintextsearch_test.cpp b/part/tests/plaintextsearch_test.cpp deleted file mode 100644 index 4ff5136..0000000 --- a/part/tests/plaintextsearch_test.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "plaintextsearch_test.h" -#include "moc_plaintextsearch_test.cpp" - -#include - -#include -#include - -Q_DECLARE_METATYPE(KTextEditor::Range) - -QTEST_KDEMAIN(PlainTextSearchTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Range &range) - { - QByteArray ba = "Range["; - ba += QByteArray::number(range.start().line()) + ", " + QByteArray::number(range.start().column()) + ", "; - ba += QByteArray::number(range.end().line()) + ", " + QByteArray::number(range.end().column()); - ba += "]"; - return qstrdup(ba.data()); - } -} - -QtMsgHandler PlainTextSearchTest::s_msgHandler = 0; - -void myMessageOutput(QtMsgType type, const char *msg) -{ - switch (type) { - case QtDebugMsg: - /* do nothing */ - break; - default: - PlainTextSearchTest::s_msgHandler(type, msg); - } -} - -void PlainTextSearchTest::initTestCase() -{ - s_msgHandler = qInstallMsgHandler(myMessageOutput); -} - -void PlainTextSearchTest::cleanupTestCase() -{ - qInstallMsgHandler(0); -} - -PlainTextSearchTest::PlainTextSearchTest() - : QObject() - , m_doc(0) - , m_search(0) -{ -} - -PlainTextSearchTest::~PlainTextSearchTest() -{ -} - -void PlainTextSearchTest::init() -{ - m_doc = new KateDocument(false, false, false, 0, this); - m_search = new KatePlainTextSearch(m_doc, Qt::CaseSensitive, false); -} - -void PlainTextSearchTest::cleanup() -{ - delete m_search; - delete m_doc; -} - -void PlainTextSearchTest::testSearchBackward_data() -{ - QTest::addColumn("searchRange"); - QTest::addColumn("expectedResult"); - - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 10) << KTextEditor::Range(1, 6, 1, 10); - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 5) << KTextEditor::Range(1, 0, 1, 4); - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 0) << KTextEditor::Range(0, 10, 0, 14); -} - -void PlainTextSearchTest::testSearchBackward() -{ - QFETCH(KTextEditor::Range, searchRange); - QFETCH(KTextEditor::Range, expectedResult); - - m_doc->setText("aaaa aaaa aaaa\n" - "aaaa aaaa"); - - QCOMPARE(m_search->search("aaaa", searchRange, true), expectedResult); -} - -void PlainTextSearchTest::testSingleLineDocument_data() -{ - QTest::addColumn("searchRange"); - QTest::addColumn("forwardResult"); - QTest::addColumn("backwardResult"); - - QTest::newRow("[a a a a a a a a a a a a]") << KTextEditor::Range(0, 0, 0, 23) << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 18, 0, 23); - QTest::newRow("[a a a a a a a a a a a ]a") << KTextEditor::Range(0, 0, 0, 22) << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 16, 0, 21); - QTest::newRow("a[ a a a a a a a a a a a]") << KTextEditor::Range(0, 1, 0, 23) << KTextEditor::Range(0, 2, 0, 7) << KTextEditor::Range(0, 18, 0, 23); - QTest::newRow("a[ a a a a a a a a a a ]a") << KTextEditor::Range(0, 1, 0, 22) << KTextEditor::Range(0, 2, 0, 7) << KTextEditor::Range(0, 16, 0, 21); - QTest::newRow("[a a a a] a a a a a a a a") << KTextEditor::Range(0, 0, 0, 7) << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 2, 0, 7); - QTest::newRow("[a a a ]a a a a a a a a a") << KTextEditor::Range(0, 0, 0, 6) << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 0, 0, 5); - QTest::newRow("[a a a] a a a a a a a a a") << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 0, 0, 5) << KTextEditor::Range(0, 0, 0, 5); - QTest::newRow("[a a ]a a a a a a a a a a") << KTextEditor::Range(0, 0, 0, 4) << KTextEditor::Range::invalid() << KTextEditor::Range::invalid(); - QTest::newRow("a a a a a a a a [a a a a]") << KTextEditor::Range(0, 16, 0, 23) << KTextEditor::Range(0, 16, 0, 21) << KTextEditor::Range(0, 18, 0, 23); - QTest::newRow("a a a a a a a a a[ a a a]") << KTextEditor::Range(0, 17, 0, 23) << KTextEditor::Range(0, 18, 0, 23) << KTextEditor::Range(0, 18, 0, 23); - QTest::newRow("a a a a a a a a a [a a a]") << KTextEditor::Range(0, 18, 0, 23) << KTextEditor::Range(0, 18, 0, 23) << KTextEditor::Range(0, 18, 0, 23); - QTest::newRow("a a a a a a a a a a[ a a]") << KTextEditor::Range(0, 19, 0, 23) << KTextEditor::Range::invalid() << KTextEditor::Range::invalid(); - QTest::newRow("a a a a a[ a a a a] a a a") << KTextEditor::Range(0, 9, 0, 17) << KTextEditor::Range(0, 10, 0, 15) << KTextEditor::Range(0, 12, 0, 17); - QTest::newRow("a a a a a[ a a] a a a a a") << KTextEditor::Range(0, 9, 0, 13) << KTextEditor::Range::invalid() << KTextEditor::Range::invalid(); -} - -void PlainTextSearchTest::testSingleLineDocument() -{ - QFETCH(KTextEditor::Range, searchRange); - QFETCH(KTextEditor::Range, forwardResult); - QFETCH(KTextEditor::Range, backwardResult); - - m_doc->setText("a a a a a a a a a a a a"); - - QCOMPARE(m_search->search("a a a", searchRange, false), forwardResult); - QCOMPARE(m_search->search("a a a", searchRange, true), backwardResult); -} - -void PlainTextSearchTest::testMultilineSearch_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("inputRange"); - QTest::addColumn("forwardResult"); - - QTest::newRow("") << "a a a\na a\na a a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 2, 5); - QTest::newRow("") << "a a a\na a\na a " << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 2, 4); - QTest::newRow("") << "a a a\na a\na a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 2, 3); - QTest::newRow("") << "a a a\na a\na" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 2, 1); - QTest::newRow("") << "a a a\na a\n" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 2, 0); - QTest::newRow("") << "a a a\na a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 0, 1, 3); - QTest::newRow("") << "a a\na a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 2, 1, 3); - QTest::newRow("") << "a a\na a\na a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 2, 2, 3); - QTest::newRow("") << "\na a\na a" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 5, 2, 3); - QTest::newRow("") << "\na a\n" << KTextEditor::Range(0, 0, 2, 5) << KTextEditor::Range(0, 5, 2, 0); - - QTest::newRow("") << "a a a\na a\na a a" << KTextEditor::Range(0, 0, 2, 4) << KTextEditor::Range::invalid(); - QTest::newRow("") << "a a a\na a\na a " << KTextEditor::Range(0, 0, 2, 4) << KTextEditor::Range(0, 0, 2, 4); - QTest::newRow("") << "a a a\na a\n" << KTextEditor::Range(0, 0, 2, 0) << KTextEditor::Range(0, 0, 2, 0); - QTest::newRow("") << "a a a\na a\n" << KTextEditor::Range(0, 0, 1, 3) << KTextEditor::Range::invalid(); - QTest::newRow("") << "a a\n" << KTextEditor::Range(0, 0, 1, 3) << KTextEditor::Range(0, 2, 1, 0); - QTest::newRow("") << "a \n" << KTextEditor::Range(0, 0, 1, 3) << KTextEditor::Range::invalid(); -} - -void PlainTextSearchTest::testMultilineSearch() -{ - QFETCH(QString, pattern); - QFETCH(KTextEditor::Range, inputRange); - QFETCH(KTextEditor::Range, forwardResult); - - m_doc->setText("a a a\n" - "a a\n" - "a a a"); - - QCOMPARE(m_search->search(pattern, inputRange, false), forwardResult); -} diff --git a/part/tests/plaintextsearch_test.h b/part/tests/plaintextsearch_test.h deleted file mode 100644 index 7b39ee5..0000000 --- a/part/tests/plaintextsearch_test.h +++ /dev/null @@ -1,60 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_PLAINTEXTSEARCH_TEST_H -#define KATE_PLAINTEXTSEARCH_TEST_H - -#include - -class KateDocument; -class KatePlainTextSearch; - -class PlainTextSearchTest : public QObject -{ - Q_OBJECT - - public: - PlainTextSearchTest(); - virtual ~PlainTextSearchTest(); - - private Q_SLOTS: - void initTestCase(); - void cleanupTestCase(); - - void init(); - void cleanup(); - - void testSearchBackward_data(); - void testSearchBackward(); - - void testSingleLineDocument_data(); - void testSingleLineDocument(); - - void testMultilineSearch_data(); - void testMultilineSearch(); - - private: - KateDocument *m_doc; - KatePlainTextSearch *m_search; - - public: - static QtMsgHandler s_msgHandler; -}; - -#endif diff --git a/part/tests/range_test.cpp b/part/tests/range_test.cpp deleted file mode 100644 index 8c2b1d3..0000000 --- a/part/tests/range_test.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Christoph Cullmann - Copyright (C) 2005 Hamish Rodda - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "range_test.h" -#include "moc_range_test.cpp" - -#include - -#include -#include -#include -#include -#include - -QTEST_KDEMAIN(RangeTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Range &range) - { - QByteArray ba = "Range["; - ba += QByteArray::number(range.start().line()) + ", " + QByteArray::number(range.start().column()) + ", "; - ba += QByteArray::number(range.end().line()) + ", " + QByteArray::number(range.end().column()); - ba += "]"; - return qstrdup(ba.data()); - } -} - -#define testNewRow() (QTest::newRow(QString("line %1").arg(__LINE__).toAscii().data())) - -RangeTest::RangeTest() - : QObject() -{ -} - -RangeTest::~RangeTest() -{ -} - -void RangeTest::rangeCheck ( KTextEditor::Range & valid ) -{ - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - - KTextEditor::Cursor before(0,1), start(0,2), end(1,4), after(1,10); - - KTextEditor::Range result(start, end); - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - - valid.setRange(start, end); - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - QCOMPARE(valid, result); - - valid.setRange(end, start); - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - QCOMPARE(valid, result); - - valid.start() = after; - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - QCOMPARE(valid, KTextEditor::Range(after, after)); - - valid = result; - QCOMPARE(valid, result); - - valid.end() = before; - QVERIFY(valid.isValid() && valid.start() <= valid.end()); - QCOMPARE(valid, KTextEditor::Range(before, before)); -} - -void RangeTest::testTextEditorRange() -{ - // test simple range - KTextEditor::Range range; - rangeCheck (range); -} - -void RangeTest::testTextRange() -{ - // test text range - KateDocument doc (false, false, false); - KTextEditor::MovingRange *complexRange = doc.newMovingRange (KTextEditor::Range()); - KTextEditor::Range range = *complexRange; - rangeCheck (range); - delete complexRange; -} - -void RangeTest::testInsertText() -{ - KateDocument doc (false, false, false); - - // Multi-line insert - KTextEditor::MovingCursor* cursor1 = doc.newMovingCursor(KTextEditor::Cursor(), KTextEditor::MovingCursor::StayOnInsert); - KTextEditor::MovingCursor* cursor2 = doc.newMovingCursor(KTextEditor::Cursor(), KTextEditor::MovingCursor::MoveOnInsert); - - doc.insertText(KTextEditor::Cursor(), "Test Text\nMore Test Text"); - QCOMPARE(doc.documentEnd(), KTextEditor::Cursor(1,14)); - - QString text = doc.text(KTextEditor::Range(1,0,1,14)); - QCOMPARE(text, QString("More Test Text")); - - // Check cursors and ranges have moved properly - QCOMPARE(cursor1->toCursor(), KTextEditor::Cursor(0,0)); - QCOMPARE(cursor2->toCursor(), KTextEditor::Cursor(1,14)); - - KTextEditor::Cursor cursor3 = doc.endOfLine(1); - - // Set up a few more lines - doc.insertText(*cursor2, "\nEven More Test Text"); - QCOMPARE(doc.documentEnd(), KTextEditor::Cursor(2,19)); - QCOMPARE(cursor3, doc.endOfLine(1)); -} - -void RangeTest::testCornerCaseInsertion() -{ - KateDocument doc (false, false, false); - - // lock first revision - doc.lockRevision (0); - - KTextEditor::MovingRange* rangeEdit = doc.newMovingRange(KTextEditor::Range(0,0,0,0)); - QCOMPARE(rangeEdit->toRange(), KTextEditor::Range(0,0,0,0)); - - doc.insertText(KTextEditor::Cursor(0,0), "\n"); - QCOMPARE(rangeEdit->toRange(), KTextEditor::Range(1,0,1,0)); - - // test translate - KTextEditor::Range translateTest (0,0,0,0); - doc.transformRange (translateTest, KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::AllowEmpty, 0); - QCOMPARE(translateTest, KTextEditor::Range(1,0,1,0)); - - // test translate reverse - KTextEditor::Range reverseTranslateTest (1,0,1,0); - doc.transformRange (reverseTranslateTest, KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::AllowEmpty, -1, 0); - QCOMPARE(reverseTranslateTest, KTextEditor::Range(0,0,0,0)); -} diff --git a/part/tests/range_test.h b/part/tests/range_test.h deleted file mode 100644 index abdf1e9..0000000 --- a/part/tests/range_test.h +++ /dev/null @@ -1,46 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Christoph Cullmann - Copyright (C) 2005 Hamish Rodda - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_RANGE_TEST_H -#define KATE_RANGE_TEST_H - -#include - -#include - -class RangeTest : public QObject -{ - Q_OBJECT - -public: - RangeTest(); - ~RangeTest(); - -private Q_SLOTS: - void testTextEditorRange(); - void testTextRange(); - void testInsertText(); - void testCornerCaseInsertion(); - -private: - void rangeCheck ( KTextEditor::Range & valid ); -}; - -#endif diff --git a/part/tests/regexpsearch_test.cpp b/part/tests/regexpsearch_test.cpp deleted file mode 100644 index 943cf99..0000000 --- a/part/tests/regexpsearch_test.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "regexpsearch_test.h" -#include "moc_regexpsearch_test.cpp" - -#include - -#include -#include - -Q_DECLARE_METATYPE(KTextEditor::Range) - -QTEST_KDEMAIN(RegExpSearchTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Range &range) - { - QByteArray ba = "Range["; - ba += QByteArray::number(range.start().line()) + ", " + QByteArray::number(range.start().column()) + ", "; - ba += QByteArray::number(range.end().line()) + ", " + QByteArray::number(range.end().column()); - ba += "]"; - return qstrdup(ba.data()); - } -} - -#define testNewRow() (QTest::newRow(QString("line %1").arg(__LINE__).toAscii().data())) - -using namespace KTextEditor; - -RegExpSearchTest::RegExpSearchTest() - : QObject() -{ -} - -RegExpSearchTest::~RegExpSearchTest() -{ -} - -void RegExpSearchTest::testReplaceEscapeSequences_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("expected"); - - testNewRow() << "\\" << "\\"; - testNewRow() << "\\0" << "0"; - testNewRow() << "\\00" << "00"; - testNewRow() << "\\000" << "000"; - testNewRow() << "\\0000" << QString(QChar(0)); - testNewRow() << "\\0377" << QString(QChar(0377)); - testNewRow() << "\\0378" << "0378"; - testNewRow() << "\\a" << "\a"; - testNewRow() << "\\f" << "\f"; - testNewRow() << "\\n" << "\n"; - testNewRow() << "\\r" << "\r"; - testNewRow() << "\\t" << "\t"; - testNewRow() << "\\v" << "\v"; - testNewRow() << "\\x" << "x"; - testNewRow() << "\\x0" << "x0"; - testNewRow() << "\\x00" << "x00"; - testNewRow() << "\\x000" << "x000"; - testNewRow() << "\\x0000" << QString(QChar(0x0000)); - testNewRow() << "\\x00000" << QString(QChar(0x0000) + '0'); - testNewRow() << "\\xaaaa" << QString(QChar(0xaaaa)); - testNewRow() << "\\xFFFF" << QString(QChar(0xFFFF)); - testNewRow() << "\\xFFFg" << "xFFFg"; -} - -void RegExpSearchTest::testReplaceEscapeSequences() -{ - QFETCH(QString, pattern); - QFETCH(QString, expected); - - const QString result1 = KateRegExpSearch::escapePlaintext(pattern); - const QString result2 = KateRegExpSearch::buildReplacement(pattern, QStringList(), 0); - - QCOMPARE(result1, expected); - QCOMPARE(result2, expected); -} - -void RegExpSearchTest::testReplacementReferences_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("expected"); - QTest::addColumn("capturedTexts"); - - testNewRow() << "\\0" << "b" << (QStringList() << "b"); - testNewRow() << "\\00" << "b0" << (QStringList() << "b"); - testNewRow() << "\\000" << "b00" << (QStringList() << "b"); - testNewRow() << "\\0000" << QString(QChar(0)) << (QStringList() << "b"); - testNewRow() << "\\1" << "1" << (QStringList() << "b"); - testNewRow() << "\\0" << "b" << (QStringList() << "b" << "c"); - testNewRow() << "\\1" << "c" << (QStringList() << "b" << "c"); -} - -void RegExpSearchTest::testReplacementReferences() -{ - QFETCH(QString, pattern); - QFETCH(QString, expected); - QFETCH(QStringList, capturedTexts); - - const QString result = KateRegExpSearch::buildReplacement(pattern, capturedTexts, 1); - - QCOMPARE(result, expected); -} - -void RegExpSearchTest::testReplacementCaseConversion_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("expected"); - - testNewRow() << "a\\Uaa" << "aAA"; - testNewRow() << "a\\UAa" << "aAA"; - testNewRow() << "a\\UaA" << "aAA"; - - testNewRow() << "a\\uaa" << "aAa"; - testNewRow() << "a\\uAa" << "aAa"; - testNewRow() << "a\\uaA" << "aAA"; - - testNewRow() << "A\\LAA" << "Aaa"; - testNewRow() << "A\\LaA" << "Aaa"; - testNewRow() << "A\\LAa" << "Aaa"; - - testNewRow() << "A\\lAA" << "AaA"; - testNewRow() << "A\\lAa" << "Aaa"; - testNewRow() << "A\\laA" << "AaA"; - - testNewRow() << "a\\EaA" << "aaA"; - testNewRow() << "A\\EAa" << "AAa"; -} - -void RegExpSearchTest::testReplacementCaseConversion() -{ - QFETCH(QString, pattern); - QFETCH(QString, expected); - - const QString result = KateRegExpSearch::buildReplacement(pattern, QStringList(), 1); - - QCOMPARE(result, expected); -} - -void RegExpSearchTest::testReplacementCounter_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("counter"); - QTest::addColumn("expected"); - - testNewRow() << "a\\#b" << 1 << "a1b"; - testNewRow() << "a\\#b" << 10 << "a10b"; - testNewRow() << "a\\#####b" << 1 << "a00001b"; -} - -void RegExpSearchTest::testReplacementCounter() -{ - QFETCH(QString, pattern); - QFETCH(int, counter); - QFETCH(QString, expected); - - const QString result = KateRegExpSearch::buildReplacement(pattern, QStringList(), counter); - - QCOMPARE(result, expected); -} - -void RegExpSearchTest::testAnchoredRegexp_data() -{ - QTest::addColumn("pattern"); - QTest::addColumn("inputRange"); - QTest::addColumn("backwards"); - QTest::addColumn("expected"); - - testNewRow() << "fe" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 2); - testNewRow() << "fe" << Range(0, 0, 0, 8) << true << Range(0, 6, 0, 8); - - testNewRow() << "^fe" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 2); - testNewRow() << "^fe" << Range(0, 0, 0, 1) << false << Range::invalid(); - testNewRow() << "^fe" << Range(0, 0, 0, 2) << false << Range(0, 0, 0, 2); - testNewRow() << "^fe" << Range(0, 3, 0, 8) << false << Range::invalid(); // only match at line start - testNewRow() << "^fe" << Range(0, 0, 0, 2) << true << Range(0, 0, 0, 2); - testNewRow() << "^fe" << Range(0, 0, 0, 1) << true << Range::invalid(); - testNewRow() << "^fe" << Range(0, 0, 0, 2) << true << Range(0, 0, 0, 2); - testNewRow() << "^fe" << Range(0, 3, 0, 8) << true << Range::invalid(); - - testNewRow() << "fe$" << Range(0, 0, 0, 8) << false << Range(0, 6, 0, 8); - testNewRow() << "fe$" << Range(0, 7, 0, 8) << false << Range::invalid(); - testNewRow() << "fe$" << Range(0, 6, 0, 8) << false << Range(0, 6, 0, 8); -// testNewRow() << "fe$" << Range(0, 0, 0, 5) << false << Range::invalid(); // only match at line end, fails - testNewRow() << "fe$" << Range(0, 0, 0, 8) << true << Range(0, 6, 0, 8); - testNewRow() << "fe$" << Range(0, 7, 0, 8) << true << Range::invalid(); - testNewRow() << "fe$" << Range(0, 6, 0, 8) << true << Range(0, 6, 0, 8); -// testNewRow() << "fe$" << Range(0, 0, 0, 5) << true << Range::invalid(); // fails due to $-shortcoming in QRegExp - - testNewRow() << "^fe fe fe$" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 8); - testNewRow() << "^fe fe fe$" << Range(0, 3, 0, 8) << false << Range::invalid(); - testNewRow() << "^fe fe fe$" << Range(0, 0, 0, 5) << false << Range::invalid(); - testNewRow() << "^fe fe fe$" << Range(0, 3, 0, 5) << false << Range::invalid(); - testNewRow() << "^fe fe fe$" << Range(0, 0, 0, 8) << true << Range(0, 0, 0, 8); - testNewRow() << "^fe fe fe$" << Range(0, 3, 0, 8) << true << Range::invalid(); - testNewRow() << "^fe fe fe$" << Range(0, 0, 0, 5) << true << Range::invalid(); - testNewRow() << "^fe fe fe$" << Range(0, 3, 0, 5) << true << Range::invalid(); - - testNewRow() << "^fe( fe)*$" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 8); - testNewRow() << "^fe( fe)*" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 8); - testNewRow() << "fe( fe)*$" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 8); - testNewRow() << "fe( fe)*" << Range(0, 0, 0, 8) << false << Range(0, 0, 0, 8); - testNewRow() << "^fe( fe)*$" << Range(0, 3, 0, 8) << false << Range::invalid(); - testNewRow() << "fe( fe)*$" << Range(0, 3, 0, 8) << false << Range(0, 3, 0, 8); -// testNewRow() << "^fe( fe)*$" << Range(0, 0, 0, 5) << false << Range::invalid(); // fails due to $-shortcoming in QRegExp - testNewRow() << "^fe( fe)*" << Range(0, 0, 0, 5) << false << Range(0, 0, 0, 5); - testNewRow() << "^fe( fe)*$" << Range(0, 0, 0, 8) << true << Range(0, 0, 0, 8); - testNewRow() << "^fe( fe)*" << Range(0, 0, 0, 8) << true << Range(0, 0, 0, 8); -// testNewRow() << "fe( fe)*$" << Range(0, 0, 0, 8) << true << Range(0, 0, 0, 8); // fails, shouldn't matching be greedy? -// testNewRow() << "fe( fe)*" << Range(0, 0, 0, 8) << true << Range(0, 0, 0, 8); // fails, shouldn't matching be greedy? - testNewRow() << "^fe( fe)*$" << Range(0, 3, 0, 8) << true << Range::invalid(); -// testNewRow() << "fe( fe)*$" << Range(0, 3, 0, 8) << true << Range(0, 3, 0, 8); // fails, shouldn't matching be greedy? -// testNewRow() << "^fe( fe)*$" << Range(0, 0, 0, 5) << true << Range::invalid(); // fails due to $-shortcoming in QRegExp - - testNewRow() << "^fe|fe$" << Range(0, 0, 0, 5) << false << Range(0, 0, 0, 2); - testNewRow() << "^fe|fe$" << Range(0, 3, 0, 8) << false << Range(0, 6, 0, 8); -// testNewRow() << "^fe|fe$" << Range(0, 0, 0, 5) << true << Range(0, 0, 0, 2); // fails due to $-shortcoming in QRegExp - testNewRow() << "^fe|fe$" << Range(0, 3, 0, 8) << true << Range(0, 6, 0, 8); -} - -void RegExpSearchTest::testAnchoredRegexp() -{ - QFETCH(QString, pattern); - QFETCH(Range, inputRange); - QFETCH(bool, backwards); - QFETCH(Range, expected); - - KateDocument doc(false, false, false); - doc.setText("fe fe fe"); - - KateRegExpSearch searcher(&doc, Qt::CaseInsensitive); - - static int i = 0; - if (i == 34 || i == 36) - qDebug() << i; - i++; - - const Range result = searcher.search(pattern, inputRange, backwards)[0]; - - QCOMPARE(result, expected); -} - -void RegExpSearchTest::testSearchForward() -{ - KateDocument doc(false, false, false); - doc.setText(" \\piinfercong"); - - KateRegExpSearch search(&doc, Qt::CaseSensitive); - const Range result = search.search("\\\\piinfer(\\w)", Range(0, 2, 0, 15))[0]; - - QCOMPARE(result, Range(0, 2, 0, 11)); -} - -void RegExpSearchTest::testSearchBackwardInSelection() -{ - KateDocument doc(false, false, false); - doc.setText("foobar foo bar foo bar foo"); - - KateRegExpSearch search(&doc, Qt::CaseSensitive); - const Range result = search.search("foo", Range(0, 0, 0, 15), true)[0]; - - QCOMPARE(result, Range(0, 7, 0, 10)); -} - -void RegExpSearchTest::test() -{ - KateDocument doc(false, false, false); - doc.setText("\\newcommand{\\piReductionOut}"); - - KateRegExpSearch search(&doc, Qt::CaseSensitive); - const QVector result = search.search("\\\\piReduction(\\S)", Range(0, 10, 0, 28), true); - - QCOMPARE(result.size(), 2); - QCOMPARE(result[0], Range(0, 12, 0, 25)); - QCOMPARE(result[1], Range(0, 24, 0, 25)); - QCOMPARE(doc.text(result[0]), QString("\\piReductionO")); - QCOMPARE(doc.text(result[1]), QString("O")); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/regexpsearch_test.h b/part/tests/regexpsearch_test.h deleted file mode 100644 index 967da4a..0000000 --- a/part/tests/regexpsearch_test.h +++ /dev/null @@ -1,58 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_REGEXPSEARCH_TEST_H -#define KATE_REGEXPSEARCH_TEST_H - -#include - -class RegExpSearchTest : public QObject -{ - Q_OBJECT - - public: - RegExpSearchTest(); - virtual ~RegExpSearchTest(); - - private Q_SLOTS: - void testReplaceEscapeSequences_data(); - void testReplaceEscapeSequences(); - - void testReplacementReferences_data(); - void testReplacementReferences(); - - void testReplacementCaseConversion_data(); - void testReplacementCaseConversion(); - - void testReplacementCounter_data(); - void testReplacementCounter(); - - void testAnchoredRegexp_data(); - void testAnchoredRegexp(); - - void testSearchForward(); - - void testSearchBackwardInSelection(); - - void test(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/revision_test.cpp b/part/tests/revision_test.cpp deleted file mode 100644 index c9830f2..0000000 --- a/part/tests/revision_test.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "revision_test.h" -#include "moc_revision_test.cpp" - -#include - -#include -#include -#include -#include - -using namespace KTextEditor; - -QTEST_KDEMAIN(RevisionTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor[" + QByteArray::number(cursor.line()) - + ", " + QByteArray::number(cursor.column()) + "]"; - return qstrdup(ba.data()); - } - - template<> - char *toString(const KTextEditor::Range &range) - { - QByteArray ba = "Range[" + QByteArray::number(range.start().line()) - + ", " + QByteArray::number(range.start().column()) + " - " - + QByteArray::number(range.end().line()) - + ", " + QByteArray::number(range.end().column()) + "]"; - return qstrdup(ba.data()); - } -} - - -RevisionTest::RevisionTest() - : QObject() -{ -} - -RevisionTest::~RevisionTest() -{ -} - -// tests: MovingInterface -// - lockRevision() -// - revision() -// - unlockRevision() -// - transformCursor() -void RevisionTest::testTransformCursor() -{ - KateDocument doc (false, false, false); - - // initial saved revision of unsaved document is -1 - QVERIFY(doc.lastSavedRevision() == -1); - - // initial revision is always 0 - QCOMPARE(doc.revision(), (qint64) 0); - - // one edit action -> revision now 1, last saved still -1 - doc.insertText(Cursor(0, 0), "0000"); - - qint64 rev = doc.revision(); - QCOMPARE(rev, (qint64) 1); - - // now lock current revision 1 - doc.lockRevision(rev); - - // wrapLine + insertText + wrapLine + insertText - doc.insertText(Cursor(0, 2), "\n1111\n2222"); - - // create some cursors, then transform them - Cursor c01(0, 1); - Cursor stayOnInsert(0, 2); - Cursor moveOnInsert(0, 2); - - doc.transformCursor(c01, MovingCursor::MoveOnInsert, rev, -1); - doc.transformCursor(moveOnInsert, MovingCursor::MoveOnInsert, rev, -1); - doc.transformCursor(stayOnInsert, MovingCursor::StayOnInsert, rev, -1); - - QCOMPARE(c01, Cursor(0, 1)); - QCOMPARE(stayOnInsert, Cursor(0, 2)); - QCOMPARE(moveOnInsert, Cursor(2, 4)); - - - // free revision and lock current again - doc.unlockRevision(rev); - rev = doc.revision(); - doc.lockRevision(rev); - - // now undo, the cursors should move to original positions again - doc.undo(); - - // inverse transformation - doc.transformCursor(c01, MovingCursor::MoveOnInsert, rev, -1); - doc.transformCursor(moveOnInsert, MovingCursor::MoveOnInsert, rev, -1); - doc.transformCursor(stayOnInsert, MovingCursor::StayOnInsert, rev, -1); - - QCOMPARE(c01, Cursor(0, 1)); - QCOMPARE(stayOnInsert, Cursor(0, 2)); - QCOMPARE(moveOnInsert, Cursor(0, 2)); -} - - -// tests: -// - transformRange() -void RevisionTest::testTransformRange() -{ - KateDocument doc (false, false, false); - - QCOMPARE(doc.revision(), (qint64) 0); - - doc.setText("00\n" - "11"); - - // now lock current revision - qint64 rev = doc.revision(); - doc.lockRevision(rev); - - - Range r1(Cursor(0, 0), Cursor(1, 2)); - Range r2(Cursor(0, 1), Cursor(1, 1)); - Range invalidOnEmpty(Cursor(0, 1), Cursor(1, 1)); - - // remove text - doc.removeText(Range(Cursor(0, 0), Cursor(1, 2))); - - doc.transformRange(r1, MovingRange::ExpandLeft | MovingRange::ExpandRight, - MovingRange::AllowEmpty, rev, -1); - doc.transformRange(r2, MovingRange::ExpandLeft | MovingRange::ExpandRight, - MovingRange::AllowEmpty, rev, -1); - doc.transformRange(invalidOnEmpty, MovingRange::ExpandLeft | MovingRange::ExpandRight, - MovingRange::InvalidateIfEmpty, rev, -1); - - - QCOMPARE(r1, Range(Cursor(0, 0), Cursor(0, 0))); - QCOMPARE(r2, Range(Cursor(0, 0), Cursor(0, 0))); - QCOMPARE(invalidOnEmpty, Range::invalid()); - - // free revision and lock current again - doc.unlockRevision(rev); - rev = doc.revision(); - doc.lockRevision(rev); - - // now undo - doc.undo(); - - // r1 should span the entire document - // r2 should be empty at end of document - // invalidOnEmpty should stay invalid - doc.transformRange(r1, MovingRange::ExpandLeft | MovingRange::ExpandRight, - MovingRange::AllowEmpty, rev, -1); - doc.transformRange(r2, MovingRange::ExpandRight, - MovingRange::AllowEmpty, rev, -1); - doc.transformRange(invalidOnEmpty, MovingRange::ExpandLeft | MovingRange::ExpandRight, - MovingRange::AllowEmpty, rev, -1); - - QCOMPARE(r1, Range(Cursor(0, 0), Cursor(1, 2))); - QCOMPARE(r2, Range(Cursor(1, 2), Cursor(1, 2))); - QCOMPARE(invalidOnEmpty, Range::invalid()); -} diff --git a/part/tests/revision_test.h b/part/tests/revision_test.h deleted file mode 100644 index f786918..0000000 --- a/part/tests/revision_test.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_REVISION_TEST_H -#define KATE_REVISION_TEST_H - -#include - -class RevisionTest : public QObject -{ - Q_OBJECT - -public: - RevisionTest(); - ~RevisionTest(); - -private Q_SLOTS: - void testTransformCursor(); - void testTransformRange(); -}; - -#endif // KATE_REVISION_TEST_H diff --git a/part/tests/sands_indentation_test.cpp b/part/tests/sands_indentation_test.cpp deleted file mode 100644 index a0bf38b..0000000 --- a/part/tests/sands_indentation_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// C++ S&S Indentation test. -// Copy this into kate and check that it indents corrently. -// Obviously that will be different for the different indentors, but this tries -// to check cases that I might not have thought of. -// TODO: Automate testing once the indentation actually works! - - -namespace Test -{ - -enum -{ - one, - two, - three, - four -}; - -bool function(int a, bool b, - int c, double d) -{ - for (int i = 0; i < b ? a : c; ++i) - cout << "Number: " << i << endl; - - switch (classType) - { - case '1': - case '/': - case ';': - break; - case ':': - colon: - break; - - case Test::one: - goto colon; - } - return Test::two; -} - -} - -class QWidget : public QObject -{ - Q_OBJECT -public: - QWidget() : parent(null) - { - } -private: - struct Car : Vehicle - { - - }; - -private slots: - Car test(); -} - -Car QWidget::test() -{ - // A comment. - cerr << "this" - << "is" << "a" << "test"; - /* A block - comment */ -} diff --git a/part/tests/scriptdocument_test.cpp b/part/tests/scriptdocument_test.cpp deleted file mode 100644 index fc5c5e2..0000000 --- a/part/tests/scriptdocument_test.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "scriptdocument_test.h" -#include "moc_scriptdocument_test.cpp" - -#include - -#include - -#include -#include - -Q_DECLARE_METATYPE(KTextEditor::Cursor) - -QTEST_KDEMAIN(ScriptDocumentTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Cursor &cursor) - { - QByteArray ba = "Cursor["; - ba += QByteArray::number(cursor.line()) + ", " + QByteArray::number(cursor.column()); - ba += "]"; - return qstrdup(ba.data()); - } -} - -QtMsgHandler ScriptDocumentTest::s_msgHandler = 0; - -void myMessageOutput(QtMsgType type, const char *msg) -{ - switch (type) { - case QtDebugMsg: - /* do nothing */ - break; - default: - ScriptDocumentTest::s_msgHandler(type, msg); - } -} - -void ScriptDocumentTest::initTestCase() -{ - s_msgHandler = qInstallMsgHandler(myMessageOutput); -} - -void ScriptDocumentTest::cleanupTestCase() -{ - qInstallMsgHandler(0); -} - -ScriptDocumentTest::ScriptDocumentTest() - : QObject() - , m_doc(0) - , m_view(0) - , m_scriptDoc(0) -{ -} - -ScriptDocumentTest::~ScriptDocumentTest() -{ -} - -void ScriptDocumentTest::init() -{ - m_doc = new KateDocument(false, false, false, 0, this); - m_view = m_doc->createView(0); - m_scriptDoc = new KateScriptDocument(this); - m_scriptDoc->setDocument(m_doc); -} - -void ScriptDocumentTest::cleanup() -{ - delete m_scriptDoc; - delete m_view; - delete m_doc; -} - -#if 0 -void ScriptDocumentTest::testRfind_data() -{ - QTest::addColumn("searchRange"); - QTest::addColumn("expectedResult"); - - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 10) << KTextEditor::Range(1, 6, 1, 10); - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 5) << KTextEditor::Range(1, 0, 1, 4); - QTest::newRow("") << KTextEditor::Range(0, 0, 1, 0) << KTextEditor::Range(0, 10, 0, 14); -} - -void ScriptDocumentTest::testRfind() -{ - QFETCH(KTextEditor::Range, searchRange); - QFETCH(KTextEditor::Range, expectedResult); - - m_doc->setText("aaaa aaaa aaaa\n" - "aaaa aaaa"); - - QCOMPARE(m_search->search(searchRange, "aaaa", true), expectedResult); -} -#endif - -void ScriptDocumentTest::testRfind_data() -{ - QTest::addColumn("searchStart"); - QTest::addColumn("result"); - - QTest::newRow("a a a a a a a a a a a a|") << KTextEditor::Cursor(0, 23) << KTextEditor::Cursor(0, 18); - QTest::newRow("a a a a a a a a a a a |a") << KTextEditor::Cursor(0, 22) << KTextEditor::Cursor(0, 16); - QTest::newRow("a a a a| a a a a a a a a") << KTextEditor::Cursor(0, 7) << KTextEditor::Cursor(0, 2); - QTest::newRow("a a a |a a a a a a a a a") << KTextEditor::Cursor(0, 6) << KTextEditor::Cursor(0, 0); - QTest::newRow("a a a| a a a a a a a a a") << KTextEditor::Cursor(0, 5) << KTextEditor::Cursor(0, 0); - QTest::newRow("a a |a a a a a a a a a a") << KTextEditor::Cursor(0, 4) << KTextEditor::Cursor::invalid(); -} - -void ScriptDocumentTest::testRfind() -{ - QFETCH(KTextEditor::Cursor, searchStart); - QFETCH(KTextEditor::Cursor, result); - - m_scriptDoc->setText("a a a a a a a a a a a a"); - - QCOMPARE(m_scriptDoc->rfind(searchStart.line(), searchStart.column(), "a a a"), result); -} diff --git a/part/tests/scriptdocument_test.h b/part/tests/scriptdocument_test.h deleted file mode 100644 index df5b9be..0000000 --- a/part/tests/scriptdocument_test.h +++ /dev/null @@ -1,59 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_SCRIPTDOCUMENT_TEST_H -#define KATE_SCRIPTDOCUMENT_TEST_H - -#include - -namespace KTextEditor { - class View; -} - -class KateDocument; -class KateScriptDocument; - -class ScriptDocumentTest : public QObject -{ - Q_OBJECT - - public: - ScriptDocumentTest(); - virtual ~ScriptDocumentTest(); - - private Q_SLOTS: - void initTestCase(); - void cleanupTestCase(); - - void init(); - void cleanup(); - - void testRfind_data(); - void testRfind(); - - private: - KateDocument *m_doc; - KTextEditor::View *m_view; - KateScriptDocument *m_scriptDoc; - - public: - static QtMsgHandler s_msgHandler; -}; - -#endif diff --git a/part/tests/searchbar_test.cpp b/part/tests/searchbar_test.cpp deleted file mode 100644 index 7ded62b..0000000 --- a/part/tests/searchbar_test.cpp +++ /dev/null @@ -1,607 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "searchbar_test.h" -#include "moc_searchbar_test.cpp" - -#include "ui_searchbarincremental.h" -#include "ui_searchbarpower.h" - -#include - -#include -#include -#include -#include -#include - -QTEST_KDEMAIN(SearchBarTest, GUI) - -namespace QTest { - template<> - char *toString(const KTextEditor::Range &range) - { - QByteArray ba = "Range["; - ba += QByteArray::number(range.start().line()) + ", " + QByteArray::number(range.start().column()) + ", "; - ba += QByteArray::number(range.end().line()) + ", " + QByteArray::number(range.end().column()); - ba += "]"; - return qstrdup(ba.data()); - } -} - -#define testNewRow() (QTest::newRow(QString("line %1").arg(__LINE__).toAscii().data())) - - -using namespace KTextEditor; - - -SearchBarTest::SearchBarTest() - : QObject() -{ -} - -SearchBarTest::~SearchBarTest() -{ -} - - -void SearchBarTest::testFindNextIncremental() -{ - KateDocument doc(false, false, false); - doc.setText("a a a b b"); - - KateView view(&doc, 0); - KateViewConfig config(&view); - - KateSearchBar bar(false, &view, &config); - - bar.setSearchPattern("b"); - - QCOMPARE(view.selectionRange(), Range(0, 6, 0, 7)); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 8, 0, 9)); - - bar.setSearchPattern("a"); - - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 4, 0, 5)); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); -} - - -void SearchBarTest::testSetMatchCaseIncremental() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a A a"); - KateSearchBar bar(false, &view, &config); - - QVERIFY(!bar.isPower()); - QVERIFY(!view.selection()); - - bar.setMatchCase(false); - bar.setSearchPattern("A"); - - QVERIFY(!bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - bar.setMatchCase(true); - - QVERIFY(bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); - - bar.setMatchCase(false); - - QVERIFY(!bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - bar.setMatchCase(true); - - QVERIFY(bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); -} - - -void SearchBarTest::testSetMatchCasePower() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a A a"); - view.setCursorPosition(Cursor(0, 0)); - - KateSearchBar bar(true, &view, &config); - - QVERIFY(bar.isPower()); - QVERIFY(!view.selection()); - - bar.setMatchCase(false); - bar.setSearchPattern("A"); - bar.findNext(); - - QCOMPARE(bar.searchPattern(), QString("A")); - QVERIFY(!bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - bar.setMatchCase(true); - - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - bar.findNext(); - - QVERIFY(bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); - - bar.setMatchCase(false); - - QVERIFY(!bar.matchCase()); - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 4, 0, 5)); -} - - - -void SearchBarTest::testSetSelectionOnlyPower() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - KateSearchBar bar(true, &view, &config); - - bar.setSearchPattern("a"); - - QVERIFY(bar.isPower()); - QVERIFY(!view.selection()); - - bar.setSelectionOnly(false); - bar.findNext(); - - QVERIFY(!bar.selectionOnly()); - QCOMPARE(view.selectionRange(), Range(0, 0, 0, 1)); - - view.setSelection(Range(0, 2, 0, 5)); - bar.setSelectionOnly(true); - - QVERIFY(bar.selectionOnly()); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 2, 0, 3)); - QVERIFY(bar.selectionOnly()); - - bar.setSelectionOnly(false); - bar.findNext(); - - QCOMPARE(view.selectionRange(), Range(0, 4, 0, 5)); - QVERIFY(!bar.selectionOnly()); -} - - -void SearchBarTest::testSetSearchPattern_data() -{ - QTest::addColumn("power"); - QTest::addColumn("numMatches2"); - - testNewRow() << false << 0; - testNewRow() << true << 3; -} - - -void SearchBarTest::testSetSearchPattern() -{ - QFETCH(bool, power); - QFETCH(int, numMatches2); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - - KateSearchBar bar(power, &view, &config); - - bar.setSearchPattern("a"); - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 3); - - bar.setSearchPattern("a "); - - QCOMPARE(bar.m_hlRanges.size(), numMatches2); - - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 2); -} - - -void SearchBarTest::testSetSelectionOnly() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - view.setSelection(Range(0, 0, 0, 3)); - - KateSearchBar bar(false, &view, &config); - - bar.setSelectionOnly(false); - bar.setSearchPattern("a"); - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 3); - - bar.setSelectionOnly(true); - - QCOMPARE(bar.m_hlRanges.size(), 3); -} - - -void SearchBarTest::testFindAll_data() -{ - QTest::addColumn("power"); - QTest::addColumn("numMatches2"); - QTest::addColumn("numMatches4"); - - testNewRow() << false << 0 << 0; - testNewRow() << true << 3 << 2; -} - - -void SearchBarTest::testFindAll() -{ - QFETCH(bool, power); - QFETCH(int, numMatches2); - QFETCH(int, numMatches4); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - KateSearchBar bar(power, &view, &config); - - QCOMPARE(bar.isPower(), power); - - bar.setSearchPattern("a"); - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 3); - QCOMPARE(bar.m_hlRanges.at(0)->toRange(), Range(0, 0, 0, 1)); - QCOMPARE(bar.m_hlRanges.at(1)->toRange(), Range(0, 2, 0, 3)); - QCOMPARE(bar.m_hlRanges.at(2)->toRange(), Range(0, 4, 0, 5)); - - bar.setSearchPattern("a "); - - QCOMPARE(bar.m_hlRanges.size(), numMatches2); - - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 2); - - bar.setSearchPattern("a "); - - QCOMPARE(bar.m_hlRanges.size(), numMatches4); - - bar.findAll(); - - QCOMPARE(bar.m_hlRanges.size(), 0); -} - -void SearchBarTest::testReplaceAll() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - KateSearchBar bar(true, &view, &config); - - bar.setSearchPattern("a"); - bar.setReplacePattern(""); - bar.replaceAll(); - - QCOMPARE(bar.m_hlRanges.size(), 3); - QCOMPARE(bar.m_hlRanges.at(0)->toRange(), Range(0, 0, 0, 0)); - QCOMPARE(bar.m_hlRanges.at(1)->toRange(), Range(0, 1, 0, 1)); - QCOMPARE(bar.m_hlRanges.at(2)->toRange(), Range(0, 2, 0, 2)); - - bar.setSearchPattern(" "); - bar.setReplacePattern("b"); - bar.replaceAll(); - - QCOMPARE(bar.m_hlRanges.size(), 2); - QCOMPARE(bar.m_hlRanges.at(0)->toRange(), Range(0, 0, 0, 1)); - QCOMPARE(bar.m_hlRanges.at(1)->toRange(), Range(0, 1, 0, 2)); -} - -void SearchBarTest::testFindSelectionForward_data() -{ - QTest::addColumn("text"); - QTest::addColumn("selectionOnly"); - QTest::addColumn("selectionRange"); - QTest::addColumn("match"); - - testNewRow() << "a a a" << false << Range(0, 0, 0, 1) << Range(0, 0, 0, 2); - testNewRow() << "a a a" << true << Range(0, 0, 0, 1) << Range(0, 0, 0, 1); - - testNewRow() << "a a a" << false << Range(0, 0, 0, 2) << Range(0, 2, 0, 4); - testNewRow() << "a a a" << true << Range(0, 0, 0, 2) << Range(0, 0, 0, 2); - - testNewRow() << "a a a" << false << Range(0, 0, 0, 3) << Range(0, 0, 0, 2); - testNewRow() << "a a a" << true << Range(0, 0, 0, 3) << Range(0, 0, 0, 2); - - testNewRow() << "a a a" << false << Range(0, 2, 0, 4) << Range(0, 0, 0, 2); - testNewRow() << "a a a" << true << Range(0, 2, 0, 4) << Range(0, 2, 0, 4); - - testNewRow() << "a a a" << false << Range(0, 3, 0, 4) << Range(0, 0, 0, 2); - testNewRow() << "a a a" << true << Range(0, 3, 0, 4) << Range(0, 3, 0, 4); -} - -void SearchBarTest::testFindSelectionForward() -{ - QFETCH(QString, text); - QFETCH(bool, selectionOnly); - QFETCH(Range, selectionRange); - QFETCH(Range, match); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText(text); - - view.setSelection(Range(0, 0, 0, 2)); - - KateSearchBar bar(true, &view, &config); - QVERIFY(bar.searchPattern() == QString("a ")); - - view.setSelection(selectionRange); - QCOMPARE(view.selectionRange(), selectionRange); - bar.setSelectionOnly(selectionOnly); - - bar.findNext(); - - QCOMPARE(view.selectionRange(), match); -} - -void SearchBarTest::testRemoveWithSelectionForward_data() -{ - QTest::addColumn("selectionRange"); - QTest::addColumn("match"); - - testNewRow() << Range(0, 0, 0, 1) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 0, 0, 2) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 0, 0, 3) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 2, 0, 4) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 3, 0, 4) << Range(0, 0, 0, 2); -} - -void SearchBarTest::testRemoveWithSelectionForward() -{ - QFETCH(Range, selectionRange); - QFETCH(Range, match); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - view.setSelection(selectionRange); - - KateSearchBar bar(true, &view, &config); - bar.setSearchPattern("a "); - bar.setSelectionOnly(false); - - bar.replaceNext(); - - QCOMPARE(view.selectionRange(), match); -} - -void SearchBarTest::testRemoveInSelectionForward_data() -{ - QTest::addColumn("selectionRange"); - QTest::addColumn("match"); - - testNewRow() << Range(0, 0, 0, 1) << Range(0, 0, 0, 1); - testNewRow() << Range(0, 0, 0, 2) << Range(0, 0, 0, 0); - testNewRow() << Range(0, 0, 0, 3) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 0, 0, 4) << Range(0, 0, 0, 2); - testNewRow() << Range(0, 2, 0, 4) << Range(0, 2, 0, 2); - testNewRow() << Range(0, 3, 0, 4) << Range(0, 3, 0, 4); -} - -void SearchBarTest::testRemoveInSelectionForward() -{ - QFETCH(Range, selectionRange); - QFETCH(Range, match); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("a a a"); - view.setSelection(selectionRange); - - KateSearchBar bar(true, &view, &config); - bar.setSearchPattern("a "); - bar.setSelectionOnly(true); - - QVERIFY(bar.replacementPattern().isEmpty()); - - bar.replaceNext(); - - QCOMPARE(view.selectionRange(), match); -} - -void SearchBarTest::testReplaceWithDoubleSelecion_data() -{ - QTest::addColumn("text"); - QTest::addColumn("selectionRange"); - QTest::addColumn("result"); - QTest::addColumn("match"); - -// testNewRow() << "a" << Range(0, 0, 0, 1) << "aa" << Range(?, ?, ?, ?); - testNewRow() << "aa" << Range(0, 1, 0, 2) << "aaa" << Range(0, 0, 0, 1); - testNewRow() << "aa" << Range(0, 0, 0, 1) << "aaa" << Range(0, 2, 0, 3); - -// testNewRow() << "ab" << Range(0, 0, 0, 1) << "aab" << Range(?, ?, ?, ?); - testNewRow() << "aab" << Range(0, 0, 0, 1) << "aaab" << Range(0, 2, 0, 3); - testNewRow() << "aba" << Range(0, 0, 0, 1) << "aaba" << Range(0, 3, 0, 4); - -// testNewRow() << "ab" << Range(0, 0, 0, 2) << "abab" << Range(?, ?, ?, ?); - testNewRow() << "abab" << Range(0, 0, 0, 2) << "ababab" << Range(0, 4, 0, 6); - testNewRow() << "abab" << Range(0, 2, 0, 4) << "ababab" << Range(0, 0, 0, 2); -} - -void SearchBarTest::testReplaceWithDoubleSelecion() -{ - QFETCH(QString, text); - QFETCH(Range, selectionRange); - QFETCH(QString, result); - QFETCH(Range, match); - - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText(text); - view.setSelection(selectionRange); - - KateSearchBar bar(true, &view, &config); - - bar.setSelectionOnly(false); - bar.setReplacePattern(bar.searchPattern() + bar.searchPattern()); - bar.replaceNext(); - - QCOMPARE(doc.text(), result); - QCOMPARE(view.selectionRange(), match); -} - -void SearchBarTest::testReplaceDollar() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig config(&view); - - doc.setText("aaa\nbbb\nccc\n\n\naaa\nbbb\nccc\nddd\n"); - - KateSearchBar bar(true, &view, &config); - - bar.setSearchPattern("$"); - bar.setSearchMode(KateSearchBar::MODE_REGEX); - bar.setReplacePattern("D"); - - bar.replaceAll(); - - QCOMPARE(doc.text(), QString("aaaD\nbbbD\ncccD\nD\nD\naaaD\nbbbD\ncccD\ndddD\n")); -} - -void SearchBarTest::testSearchHistoryIncremental() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig *const config = view.config(); - - doc.setText("foo bar"); - - QCOMPARE(config->patternHistoryModel()->stringList(), QStringList()); - - KateSearchBar bar(false, &view, config); - - bar.setSearchPattern("foo"); - bar.findNext(); - - QCOMPARE(bar.m_incUi->pattern->findText("foo"), 0); - - bar.setSearchPattern("bar"); - bar.findNext(); - - QCOMPARE(bar.m_incUi->pattern->findText("bar"), 0); - QCOMPARE(bar.m_incUi->pattern->findText("foo"), 1); - - KateDocument doc2(false, false, false); - KateView view2(&doc2, 0); - KateViewConfig *const config2 = view2.config(); - KateSearchBar bar2(false, &view2, config2); - - QCOMPARE(bar2.m_incUi->pattern->findText("bar"), 0); - QCOMPARE(bar2.m_incUi->pattern->findText("foo"), 1); -} - -void SearchBarTest::testSearchHistoryPower() -{ - KateDocument doc(false, false, false); - KateView view(&doc, 0); - KateViewConfig *const config = view.config(); - - doc.setText("foo bar"); - - KateSearchBar bar(true, &view, config); - - QCOMPARE(bar.m_powerUi->pattern->count(), 0); - - bar.setSearchPattern("foo"); - bar.findNext(); - - QCOMPARE(bar.m_powerUi->pattern->findText("foo"), 0); - - bar.findNext(); - - QCOMPARE(bar.m_powerUi->pattern->findText("foo"), 0); - QCOMPARE(bar.m_powerUi->pattern->count(), 1); - - bar.setSearchPattern("bar"); - bar.findNext(); - - QCOMPARE(bar.m_powerUi->pattern->findText("bar"), 0); - QCOMPARE(bar.m_powerUi->pattern->findText("foo"), 1); - QCOMPARE(bar.m_powerUi->pattern->count(), 2); - - KateDocument doc2(false, false, false); - KateView view2(&doc2, 0); - KateViewConfig *const config2 = view2.config(); - KateSearchBar bar2(true, &view2, config2); - - QCOMPARE(bar2.m_powerUi->pattern->findText("bar"), 0); - QCOMPARE(bar2.m_powerUi->pattern->findText("foo"), 1); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/searchbar_test.h b/part/tests/searchbar_test.h deleted file mode 100644 index 78ab26f..0000000 --- a/part/tests/searchbar_test.h +++ /dev/null @@ -1,72 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_SEARCHBAR_TEST_H -#define KATE_SEARCHBAR_TEST_H - -#include - -class SearchBarTest : public QObject -{ - Q_OBJECT - -public: - SearchBarTest(); - ~SearchBarTest(); - -private Q_SLOTS: - void testFindNextIncremental(); - - void testSetMatchCaseIncremental(); - - void testSetMatchCasePower(); - - void testSetSelectionOnlyPower(); - - void testSetSearchPattern_data(); - void testSetSearchPattern(); - - void testSetSelectionOnly(); - - void testFindAll_data(); - void testFindAll(); - - void testReplaceAll(); - - void testFindSelectionForward_data(); - void testFindSelectionForward(); - - void testRemoveWithSelectionForward_data(); - void testRemoveWithSelectionForward(); - - void testRemoveInSelectionForward_data(); - void testRemoveInSelectionForward(); - - void testReplaceWithDoubleSelecion_data(); - void testReplaceWithDoubleSelecion(); - - void testReplaceDollar(); - - void testSearchHistoryIncremental(); - void testSearchHistoryPower(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/templatehandler_test.cpp b/part/tests/templatehandler_test.cpp deleted file mode 100644 index da925c8..0000000 --- a/part/tests/templatehandler_test.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "templatehandler_test.h" -#include "moc_templatehandler_test.cpp" - -#include - -#include -#include - -QTEST_KDEMAIN(TemplateHandlerTest, GUI) - -using namespace KTextEditor; - - -void TemplateHandlerTest::testUndo() -{ - const QString snippet = "for (${type} ${index} = ; ${index} < ; ++${index})\n" - "{\n" - "\t${index}\n" - "}"; - QMap initialValues; - initialValues.insert("type", "int"); - initialValues.insert("index", "i"); - - KateDocument doc(false, false, false, 0, this); - KateView view(&doc, 0); - - doc.insertTemplateTextImplementation(Cursor(0, 0), snippet, initialValues, 0, &view); - - const QString result = "for (int i = ; i < ; ++i)\n" - "{\n" - "\ti\n" - "}"; - QCOMPARE(doc.text(), result); - - doc.replaceText(Range(0, 9, 0, 10), "j"); - - const QString result2 = "for (int j = ; j < ; ++j)\n" - "{\n" - "\tj\n" - "}"; - QCOMPARE(doc.text(), result2); - - doc.undo(); - - QCOMPARE(doc.text(), result); - - doc.redo(); - - QCOMPARE(doc.text(), result2); - - doc.insertText(Cursor(0, 10), "j"); - doc.insertText(Cursor(0, 11), "j"); - - const QString result3 = "for (int jjj = ; jjj < ; ++jjj)\n" - "{\n" - "\tjjj\n" - "}"; - QCOMPARE(doc.text(), result3); - - doc.undo(); - doc.undo(); - - QCOMPARE(doc.text(), result2); - - doc.redo(); - doc.redo(); - - QCOMPARE(doc.text(), result3); - - doc.undo(); - doc.undo(); - doc.undo(); - - QCOMPARE(doc.text(), result); -} diff --git a/part/tests/templatehandler_test.h b/part/tests/templatehandler_test.h deleted file mode 100644 index b414854..0000000 --- a/part/tests/templatehandler_test.h +++ /dev/null @@ -1,33 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_UNDOMANAGER_TEST_H -#define KATE_UNDOMANAGER_TEST_H - -#include - -class TemplateHandlerTest : public QObject -{ - Q_OBJECT - - private Q_SLOTS: - void testUndo(); -}; - -#endif diff --git a/part/tests/test.uc b/part/tests/test.uc deleted file mode 100644 index be53bcc..0000000 --- a/part/tests/test.uc +++ /dev/null @@ -1,266 +0,0 @@ -//============================================================================= -// Shield Gun -//============================================================================= -class ShieldGun extends Weapon - config(user); - -#EXEC OBJ LOAD FILE=InterfaceContent.utx - -var Sound ShieldHitSound; -var String ShieldHitForce; - -replication -{ - reliable if (Role == ROLE_Authority) - ClientTakeHit; -} - -simulated function DoAutoSwitch() -{ -} - -simulated event RenderOverlays( Canvas Canvas ) -{ - local int m; - - if ((Hand < -1.0) || (Hand > 1.0)) - { - for (m = 0; m < NUM_FIRE_MODES; m++) - { - if (FireMode[m] != None) - { - FireMode[m].DrawMuzzleFlash(Canvas); - } - } - } - Super.RenderOverlays(Canvas); -} - -// AI Interface -function GiveTo(Pawn Other, optional Pickup Pickup) -{ - Super.GiveTo(Other, Pickup); - - if ( Bot(Other.Controller) != None ) - Bot(Other.Controller).bHasImpactHammer = true; -} - -function bool CanAttack(Actor Other) -{ - return true; -} - -simulated function Timer() -{ - local Bot B; - - if (ClientState == WS_BringUp) - { - // check if owner is bot waiting to do impact jump - B = Bot(Instigator.Controller); - if ( (B != None) && B.bPreparingMove && (B.ImpactTarget != None) ) - { - B.ImpactJump(); - B = None; - } - } - Super.Timer(); - if ( (B != None) && (B.Enemy != None) ) - BotFire(false); -} - -function FireHack(byte Mode) -{ - if ( Mode == 0 ) - { - FireMode[0].PlayFiring(); - FireMode[0].FlashMuzzleFlash(); - FireMode[0].StartMuzzleSmoke(); - IncrementFlashCount(0); - } -} - -/* BestMode() -choose between regular or alt-fire -*/ -function byte BestMode() -{ - local float EnemyDist; - local bot B; - - B = Bot(Instigator.Controller); - if ( (B == None) || (B.Enemy == None) ) - return 1; - - EnemyDist = VSize(B.Enemy.Location - Instigator.Location); - if ( EnemyDist > 2 * Instigator.GroundSpeed ) - return 1; - if ( (B.MoveTarget != B.Enemy) && ((EnemyDist > 0.5 * Instigator.GroundSpeed) - || (((B.Enemy.Location - Instigator.Location) Dot vector(Instigator.Rotation)) <= 0)) ) - return 1; - return 0; -} - -// super desireable for bot waiting to impact jump -function float GetAIRating() -{ - local Bot B; - local float EnemyDist; - - B = Bot(Instigator.Controller); - if ( B == None ) - return AIRating; - - if ( B.bPreparingMove && (B.ImpactTarget != None) ) - return 9; - - if ( B.PlayerReplicationInfo.HasFlag != None ) - { - if ( Instigator.Health < 50 ) - return AIRating + 0.35; - return AIRating + 0.25; - } - - if ( B.Enemy == None ) - return AIRating; - - EnemyDist = VSize(B.Enemy.Location - Instigator.Location); - if ( B.Stopped() && (EnemyDist > 100) ) - return 0.1; - - if ( (EnemyDist < 750) && (B.Skill <= 2) && !B.Enemy.IsA('Bot') && (ShieldGun(B.Enemy.Weapon) != None) ) - return FClamp(300/(EnemyDist + 1), 0.6, 0.75); - - if ( EnemyDist > 400 ) - return 0.1; - if ( (Instigator.Weapon != self) && (EnemyDist < 120) ) - return 0.25; - - return ( FMin(0.6, 90/(EnemyDist + 1)) ); -} - -// End AI interface - -function AdjustPlayerDamage( out int Damage, Pawn InstigatedBy, Vector HitLocation, - out Vector Momentum, class DamageType) -{ - local int Drain; - local vector Reflect; - local vector HitNormal; - local float DamageMax; - - DamageMax = 100.0; - if ( DamageType == class'Fell' ) - DamageMax = 20.0; - else if( !DamageType.default.bArmorStops || (DamageType == class'DamTypeShieldImpact' && InstigatedBy == Instigator) ) - return; - - if ( CheckReflect(HitLocation, HitNormal, 0) ) - { - Drain = Min( Ammo[1].AmmoAmount*2, Damage ); - Drain = Min(Drain,DamageMax); - Reflect = MirrorVectorByNormal( Normal(Location - HitLocation), Vector(Instigator.Rotation) ); - Damage -= Drain; - Momentum *= 1.25; - Ammo[1].UseAmmo(Drain/2); - DoReflectEffect(Drain/2); - } -} - -function DoReflectEffect(int Drain) -{ - PlaySound(ShieldHitSound, SLOT_None); - ShieldAltFire(FireMode[1]).TakeHit(Drain); - ClientTakeHit(Drain); -} - -simulated function ClientTakeHit(int Drain) -{ - ClientPlayForceFeedback(ShieldHitForce); - ShieldAltFire(FireMode[1]).TakeHit(Drain); -} - -function bool CheckReflect( Vector HitLocation, out Vector RefNormal, int AmmoDrain ) -{ - local Vector HitDir; - local Vector FaceDir; - - if (!FireMode[1].bIsFiring || Ammo[0].AmmoAmount == 0) return false; - - FaceDir = Vector(Instigator.Controller.Rotation); - HitDir = Normal(Instigator.Location - HitLocation + Vect(0,0,8)); - //Log(self@"HitDir"@(FaceDir dot HitDir)); - - RefNormal = FaceDir; - - if ( FaceDir dot HitDir < -0.37 ) // 68 degree protection arc - { - if (AmmoDrain > 0) - Ammo[0].UseAmmo(AmmoDrain); - return true; - } - return false; -} - -function AnimEnd(int channel) -{ - if (FireMode[0].bIsFiring) - { - LoopAnim('Charged'); - } - else if (!FireMode[1].bIsFiring) - { - Super.AnimEnd(channel); - } -} - -function float SuggestAttackStyle() -{ - return 0.8; -} - -function float SuggestDefenseStyle() -{ - return -0.8; -} - -simulated function float ChargeBar() -{ - return FMin(1,FireMode[0].HoldTime/ShieldFire(FireMode[0]).FullyChargedTime); -} - -defaultproperties -{ - ItemName="Shield Gun" - IconMaterial=Material'InterfaceContent.Hud.SkinA' - IconCoords=(X1=200,Y1=281,X2=321,Y2=371) - - bShowChargingBar=true - bCanThrow=false - FireModeClass(0)=ShieldFire - FireModeClass(1)=ShieldAltFire - InventoryGroup=1 - Mesh=mesh'Weapons.ShieldGun_1st' - BobDamping=2.2 - PickupClass=class'ShieldGunPickup' - EffectOffset=(X=15.0,Y=6.7,Z=1.2) - bMeleeWeapon=true - ShieldHitSound=Sound'WeaponSounds.ShieldGun.ShieldReflection' - DrawScale=0.4 - PutDownAnim=PutDown - DisplayFOV=60 - PlayerViewOffset=(X=2,Y=-0.7,Z=-2.7) - PlayerViewPivot=(Pitch=500,Roll=0,Yaw=500) - - UV2Texture=Material'XGameShaders.WeaponEnvShader' - - AttachmentClass=class'ShieldAttachment' - SelectSound=Sound'WeaponSounds.ShieldGun_change' - SelectForce="ShieldGun_change" - ShieldHitForce="ShieldReflection" - - AIRating=0.35 - CurrentRating=0.35 - - DefaultPriority=2 -} diff --git a/part/tests/testutils.cpp b/part/tests/testutils.cpp deleted file mode 100644 index 2ef06ce..0000000 --- a/part/tests/testutils.cpp +++ /dev/null @@ -1,465 +0,0 @@ -/** - * This file is part of the KDE project - * - * Copyright (C) 2001,2003 Peter Kelly (pmk@post.com) - * Copyright (C) 2003,2004 Stephan Kulow (coolo@kde.org) - * Copyright (C) 2004 Dirk Mueller ( mueller@kde.org ) - * Copyright 2006, 2007 Leo Savernik (l.savernik@aon.at) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -//BEGIN Includes -#include "testutils.h" - -#include "kateview.h" -#include "katedocument.h" -#include "katedocumenthelpers.h" -#include "kateconfig.h" -#include "katecmd.h" -#include "kateglobal.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -//END Includes - -//BEGIN TestScriptEnv - -//BEGIN conversion functions for Cursors and Ranges -/** Converstion function from KTextEditor::Cursor to QtScript cursor */ -static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor) -{ - QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) - .arg(cursor.column()); - return engine->evaluate(code); -} - -/** Converstion function from QtScript cursor to KTextEditor::Cursor */ -static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor) -{ - cursor.setPosition(obj.property("line").toInt32(), - obj.property("column").toInt32()); -} - -/** Converstion function from QtScript range to KTextEditor::Range */ -static QScriptValue rangeToScriptValue(QScriptEngine *engine, const KTextEditor::Range &range) -{ - QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) - .arg(range.start().column()) - .arg(range.end().line()) - .arg(range.end().column()); - return engine->evaluate(code); -} - -/** Converstion function from QtScript range to KTextEditor::Range */ -static void rangeFromScriptValue(const QScriptValue &obj, KTextEditor::Range &range) -{ - range.start().setPosition(obj.property("start").property("line").toInt32(), - obj.property("start").property("column").toInt32()); - range.end().setPosition(obj.property("end").property("line").toInt32(), - obj.property("end").property("column").toInt32()); -} -//END - -TestScriptEnv::TestScriptEnv(KateDocument *part, bool &cflag) - : m_engine(0), m_viewObj(0), m_docObj(0), m_output(0) -{ - m_engine = new QScriptEngine(this); - - qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue); - qScriptRegisterMetaType (m_engine, rangeToScriptValue, rangeFromScriptValue); - - initApi(); - - KateView *view = qobject_cast(part->widget()); - - m_viewObj = new KateViewObject(view); - QScriptValue sv = m_engine->newQObject(m_viewObj); - - m_engine->globalObject().setProperty("view", sv); - m_engine->globalObject().setProperty("v", sv); - - m_docObj = new KateDocumentObject(view->doc()); - QScriptValue sd = m_engine->newQObject(m_docObj); - - m_engine->globalObject().setProperty("document", sd); - m_engine->globalObject().setProperty("d", sd); - - m_output = new OutputObject(view, cflag); - QScriptValue so = m_engine->newQObject(m_output); - - m_engine->globalObject().setProperty("output", so); - m_engine->globalObject().setProperty("out", so); - m_engine->globalObject().setProperty("o", so); -} - -TestScriptEnv::~TestScriptEnv() -{ - // delete explicitely, as the parent is the KTE::Document kpart, which is - // reused for all tests. Hence, we explicitely have to delete the bindings. - delete m_output; m_output = 0; - delete m_docObj; m_docObj = 0; - delete m_viewObj; m_viewObj = 0; - - // delete this too, although this should also be automagically be freed - delete m_engine; m_engine = 0; - -// kDebug() << "deleted"; -} - -void TestScriptEnv::initApi() -{ - // cache file names - static QStringList apiFileBaseNames; - static QHash apiBaseName2FileName; - static QHash apiBaseName2Content; - - // read katepart javascript api - apiFileBaseNames.clear (); - apiBaseName2FileName.clear (); - apiBaseName2Content.clear (); - - // get all api files - const QStringList list = KGlobal::dirs()->findAllResources("data","katepart/api/*.js", KStandardDirs::NoDuplicates); - - for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) - { - // get abs filename.... - QFileInfo fi(*it); - const QString absPath = fi.absoluteFilePath(); - const QString baseName = fi.baseName (); - - // remember filenames - apiFileBaseNames.append (baseName); - apiBaseName2FileName[baseName] = absPath; - - // read the file - QFile file(absPath); - QString content; - if (!file.open(QIODevice::ReadOnly)) { - kFatal() << i18n("Unable to find '%1'", absPath); - return; - } else { - QTextStream stream(&file); - stream.setCodec("UTF-8"); - content = stream.readAll(); - file.close(); - } - apiBaseName2Content[baseName] = content; - } - - // sort... - apiFileBaseNames.sort (); - - // register all script apis found - for ( QStringList::ConstIterator it = apiFileBaseNames.constBegin(); it != apiFileBaseNames.constEnd(); ++it ) - { - // try to load into engine, bail out one error, use fullpath for error messages - QScriptValue apiObject = m_engine->evaluate(apiBaseName2Content[*it], apiBaseName2FileName[*it]); - - if(m_engine->hasUncaughtException()) { - kFatal() << "Error loading script" << (*it); - return; - } - } - - // success ;) -} - -//END TestScriptEnv - -//BEGIN KateViewObject - -KateViewObject::KateViewObject(KateView *view) - : KateScriptView() -{ - setView(view); -} - -KateViewObject::~KateViewObject() -{ -// kDebug() << "deleted"; -} - -// Implements a function that calls an edit function repeatedly as specified by -// its first parameter (once if not specified). -#define REP_CALL(func) \ -void KateViewObject::func(int cnt) { \ - while (cnt--) { view()->func(); } \ -} -REP_CALL(keyReturn) -REP_CALL(backspace) -REP_CALL(deleteWordLeft) -REP_CALL(keyDelete) -REP_CALL(deleteWordRight) -REP_CALL(transpose) -REP_CALL(cursorLeft) -REP_CALL(shiftCursorLeft) -REP_CALL(cursorRight) -REP_CALL(shiftCursorRight) -REP_CALL(wordLeft) -REP_CALL(shiftWordLeft) -REP_CALL(wordRight) -REP_CALL(shiftWordRight) -REP_CALL(home) -REP_CALL(shiftHome) -REP_CALL(end) -REP_CALL(shiftEnd) -REP_CALL(up) -REP_CALL(shiftUp) -REP_CALL(down) -REP_CALL(shiftDown) -REP_CALL(scrollUp) -REP_CALL(scrollDown) -REP_CALL(topOfView) -REP_CALL(shiftTopOfView) -REP_CALL(bottomOfView) -REP_CALL(shiftBottomOfView) -REP_CALL(pageUp) -REP_CALL(shiftPageUp) -REP_CALL(pageDown) -REP_CALL(shiftPageDown) -REP_CALL(top) -REP_CALL(shiftTop) -REP_CALL(bottom) -REP_CALL(shiftBottom) -REP_CALL(toMatchingBracket) -REP_CALL(shiftToMatchingBracket) -#undef REP_CALL - -bool KateViewObject::type(const QString& str) { - return view()->doc()->typeChars(view(), str); -} - -#define ALIAS(alias, func) \ -void KateViewObject::alias(int cnt) { \ - func(cnt); \ -} -ALIAS(enter, keyReturn) -ALIAS(cursorPrev, cursorLeft) -ALIAS(left, cursorLeft) -ALIAS(prev, cursorLeft) -ALIAS(shiftCursorPrev, shiftCursorLeft) -ALIAS(shiftLeft, shiftCursorLeft) -ALIAS(shiftPrev, shiftCursorLeft) -ALIAS(cursorNext, cursorRight) -ALIAS(right, cursorRight) -ALIAS(next, cursorRight) -ALIAS(shiftCursorNext, shiftCursorRight) -ALIAS(shiftRight, shiftCursorRight) -ALIAS(shiftNext, shiftCursorRight) -ALIAS(wordPrev, wordLeft) -ALIAS(shiftWordPrev, shiftWordLeft) -ALIAS(wordNext, wordRight) -ALIAS(shiftWordNext, shiftWordRight) -#undef ALIAS - -//END KateViewObject - -//BEGIN KateDocumentObject - -KateDocumentObject::KateDocumentObject(KateDocument *doc) - : KateScriptDocument() -{ - setDocument(doc); -} - -KateDocumentObject::~KateDocumentObject() -{ -// kDebug() << "deleted"; -} -//END KateDocumentObject - -//BEGIN OutputObject - -OutputObject::OutputObject(KateView *v, bool &cflag) - : view(v), cflag(cflag) -{ -} - -OutputObject::~OutputObject() -{ -// kDebug() << "deleted"; -} - -void OutputObject::output(bool cp, bool ln) -{ - QFile out(filename); - - QString str; - for (int i = 0; i < context()->argumentCount(); ++i) { - QScriptValue arg = context()->argument(i); - str += arg.toString(); - } - - if (cp) { - KTextEditor::Cursor c = view->cursorPosition(); - str += '(' + QString::number(c.line()) + ',' + QString::number(c.column()) + ')'; - } - - if (ln) { - str += '\n'; - } - - QFile::OpenMode mode = QFile::WriteOnly | (cflag ? QFile::Append : QFile::Truncate); - if (!out.open(mode)) { - fprintf(stderr, "ERROR: Could not append to %s\n", filename.toLatin1().constData()); - } - out.write(str.toUtf8()); - cflag = true; -} - -void OutputObject::write() -{ - output(false, false); -} - -void OutputObject::writeln() -{ - output(false, true); -} - -void OutputObject::writeLn() -{ - output(false, true); -} - -void OutputObject::print() -{ - output(false, false); -} - -void OutputObject::println() -{ - output(false, true); -} - -void OutputObject::printLn() -{ - output(false, true); -} - -void OutputObject::writeCursorPosition() -{ - output(true, false); -} - -void OutputObject::writeCursorPositionln() -{ - output(true, true); -} - -void OutputObject::cursorPosition() -{ - output(true, false); -} - -void OutputObject::cursorPositionln() -{ - output(true, true); -} - -void OutputObject::cursorPositionLn() -{ - output(true, true); -} - -void OutputObject::pos() -{ - output(true, false); -} - -void OutputObject::posln() -{ - output(true, true); -} - -void OutputObject::posLn() -{ - output(true, true); -} - -void OutputObject::createMissingDirs(const QString& filename) -{ - QFileInfo dif(filename); - QFileInfo dirInfo( dif.dir().path() ); - if (dirInfo.exists()) - return; - - QStringList pathComponents; - QFileInfo parentDir = dirInfo; - pathComponents.prepend(parentDir.absoluteFilePath()); - while (!parentDir.exists()) { - QString parentPath = parentDir.absoluteFilePath(); - int slashPos = parentPath.lastIndexOf('/'); - if (slashPos < 0) - break; - parentPath = parentPath.left(slashPos); - pathComponents.prepend(parentPath); - parentDir = QFileInfo(parentPath); - } - for (int pathno = 1; pathno < pathComponents.count(); pathno++) { - if (!QFileInfo(pathComponents[pathno]).exists() && - !QDir(pathComponents[pathno-1]).mkdir(pathComponents[pathno])) { - fprintf(stderr,"Error creating directory %s\n",pathComponents[pathno].toLatin1().constData()); - exit(1); - } - } -} - -//END OutputObject diff --git a/part/tests/testutils.h b/part/tests/testutils.h deleted file mode 100644 index ebb4e2e..0000000 --- a/part/tests/testutils.h +++ /dev/null @@ -1,198 +0,0 @@ -/** - * This file is part of the KDE project - * - * Copyright (C) 2001,2003 Peter Kelly (pmk@post.com) - * Copyright 2006, 2007 Leo Savernik (l.savernik@aon.at) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ -#ifndef TESTUTILS_H -#define TESTUTILS_H - -#include "katescriptview.h" -#include "katescriptdocument.h" - -#include - -class KateView; -class RegressionTest; -class KCmdLineArgs; -class OutputObject; -class KateViewObject; -class KateDocumentObject; - -/** - * @internal - * The backbone of Kate's automatic regression tests. - */ -class TestScriptEnv : public QObject -{ - public: - explicit TestScriptEnv(KateDocument *part, bool &cflag); - virtual ~TestScriptEnv(); - - QScriptEngine *engine() const { return m_engine; } - - /** returns the output object */ - OutputObject *output() const { return m_output; } - - private: - void initApi(); - QScriptEngine *m_engine; - KateViewObject *m_viewObj; - KateDocumentObject *m_docObj; - - OutputObject *m_output; -}; - -/** - * @internal - */ -class KateViewObject : public KateScriptView -{ - Q_OBJECT - - public: - - explicit KateViewObject(KateView *view); - virtual ~KateViewObject(); - - // Edit functions - Q_INVOKABLE void keyReturn(int cnt = 1); - Q_INVOKABLE void backspace(int cnt = 1); - Q_INVOKABLE void deleteWordLeft(int cnt = 1); - Q_INVOKABLE void keyDelete(int cnt = 1); - Q_INVOKABLE void deleteWordRight(int cnt = 1); - Q_INVOKABLE void transpose(int cnt = 1); - Q_INVOKABLE void cursorLeft(int cnt = 1); - Q_INVOKABLE void shiftCursorLeft(int cnt = 1); - Q_INVOKABLE void cursorRight(int cnt = 1); - Q_INVOKABLE void shiftCursorRight(int cnt = 1); - Q_INVOKABLE void wordLeft(int cnt = 1); - Q_INVOKABLE void shiftWordLeft(int cnt = 1); - Q_INVOKABLE void wordRight(int cnt = 1); - Q_INVOKABLE void shiftWordRight(int cnt = 1); - Q_INVOKABLE void home(int cnt = 1); - Q_INVOKABLE void shiftHome(int cnt = 1); - Q_INVOKABLE void end(int cnt = 1); - Q_INVOKABLE void shiftEnd(int cnt = 1); - Q_INVOKABLE void up(int cnt = 1); - Q_INVOKABLE void shiftUp(int cnt = 1); - Q_INVOKABLE void down(int cnt = 1); - Q_INVOKABLE void shiftDown(int cnt = 1); - Q_INVOKABLE void scrollUp(int cnt = 1); - Q_INVOKABLE void scrollDown(int cnt = 1); - Q_INVOKABLE void topOfView(int cnt = 1); - Q_INVOKABLE void shiftTopOfView(int cnt = 1); - Q_INVOKABLE void bottomOfView(int cnt = 1); - Q_INVOKABLE void shiftBottomOfView(int cnt = 1); - Q_INVOKABLE void pageUp(int cnt = 1); - Q_INVOKABLE void shiftPageUp(int cnt = 1); - Q_INVOKABLE void pageDown(int cnt = 1); - Q_INVOKABLE void shiftPageDown(int cnt = 1); - Q_INVOKABLE void top(int cnt = 1); - Q_INVOKABLE void shiftTop(int cnt = 1); - Q_INVOKABLE void bottom(int cnt = 1); - Q_INVOKABLE void shiftBottom(int cnt = 1); - Q_INVOKABLE void toMatchingBracket(int cnt = 1); - Q_INVOKABLE void shiftToMatchingBracket(int cnt = 1); - - Q_INVOKABLE bool type(const QString& str); - - // Aliases - Q_INVOKABLE void enter(int cnt = 1); // KeyReturn - Q_INVOKABLE void cursorPrev(int cnt = 1); // CursorLeft - Q_INVOKABLE void left(int cnt = 1); // CursorLeft - Q_INVOKABLE void prev(int cnt = 1); // CursorLeft - Q_INVOKABLE void shiftCursorPrev(int cnt = 1); // ShiftCursorLeft - Q_INVOKABLE void shiftLeft(int cnt = 1); // ShiftCursorLeft - Q_INVOKABLE void shiftPrev(int cnt = 1); // ShiftCursorLeft - Q_INVOKABLE void cursorNext(int cnt = 1); // CursorRight - Q_INVOKABLE void right(int cnt = 1); // CursorRight - Q_INVOKABLE void next(int cnt = 1); // CursorRight - Q_INVOKABLE void shiftCursorNext(int cnt = 1); // ShiftCursorRight - Q_INVOKABLE void shiftRight(int cnt = 1); // ShiftCursorRight - Q_INVOKABLE void shiftNext(int cnt = 1); // ShiftCursorRight - Q_INVOKABLE void wordPrev(int cnt = 1); // WordLeft - Q_INVOKABLE void shiftWordPrev(int cnt = 1); // ShiftWordLeft - Q_INVOKABLE void wordNext(int cnt = 1); // WordRight - Q_INVOKABLE void shiftWordNext(int cnt = 1); // ShiftWordRight - - private: - Q_DISABLE_COPY(KateViewObject) -}; - -/** - * @internal - */ -class KateDocumentObject : public KateScriptDocument -{ - Q_OBJECT - - public: - explicit KateDocumentObject(KateDocument* doc); - virtual ~KateDocumentObject(); - - private: - Q_DISABLE_COPY(KateDocumentObject) -}; - -/** - * Customizing output to result-files. Writing any output into result files - * inhibits outputting the content of the katepart after script execution, - * enabling one to check for coordinates and the like. - * @internal - */ -class OutputObject : public QObject, protected QScriptable -{ - Q_OBJECT - - public: - OutputObject(KateView *v, bool &cflag); - virtual ~OutputObject(); - - void setOutputFile(const QString &filename) { this->filename = filename; } - static void createMissingDirs(const QString & filename); - - void output(bool cp, bool ln); - - Q_INVOKABLE void write(); - Q_INVOKABLE void writeln(); - Q_INVOKABLE void writeLn(); - - Q_INVOKABLE void print(); - Q_INVOKABLE void println(); - Q_INVOKABLE void printLn(); - - Q_INVOKABLE void writeCursorPosition(); - Q_INVOKABLE void writeCursorPositionln(); - - Q_INVOKABLE void cursorPosition(); - Q_INVOKABLE void cursorPositionln(); - Q_INVOKABLE void cursorPositionLn(); - - Q_INVOKABLE void pos(); - Q_INVOKABLE void posln(); - Q_INVOKABLE void posLn(); - - private: - KateView *view; - bool &cflag; - QString filename; -}; - -#endif // TESTUTILS_H diff --git a/part/tests/undomanager_test.cpp b/part/tests/undomanager_test.cpp deleted file mode 100644 index d51dcdf..0000000 --- a/part/tests/undomanager_test.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - Copyright (C) 2009 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "undomanager_test.h" -#include "moc_undomanager_test.cpp" - -#include - -#include -#include -#include - -QTEST_KDEMAIN(UndoManagerTest, GUI) - -using namespace KTextEditor; - -class UndoManagerTest::TestDocument : public KateDocument -{ -public: - TestDocument() - : KateDocument(false, false, false, 0, 0) - {} - - KateUndoManager *undoManager() { return m_undoManager; } -}; - -void UndoManagerTest::testUndoRedoCount() -{ - TestDocument doc; - KateUndoManager *undoManager = doc.undoManager(); - - // no undo/redo items at the beginning - QCOMPARE(undoManager->undoCount(), 0u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.insertText(Cursor(0, 0), "a"); - - // create one insert-group - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.undo(); - - // move insert-group to redo items - QCOMPARE(undoManager->undoCount(), 0u); - QCOMPARE(undoManager->redoCount(), 1u); - - doc.redo(); - - // move insert-group back to undo items - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.insertText(Cursor(0, 1), "b"); - - // merge "b" into insert-group - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.removeText(Range(0, 1, 0, 2)); - - // create an additional remove-group - QCOMPARE(undoManager->undoCount(), 2u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.undo(); - - // move remove-group to redo items - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 1u); - - doc.insertText(Cursor(0, 1), "b"); - - // merge "b" into insert-group - // and remove remove-group - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 0u); -} - -void UndoManagerTest::testSafePoint() -{ - TestDocument doc; - KateUndoManager *undoManager = doc.undoManager(); - - doc.insertText(Cursor(0, 0), "a"); - - // create one undo group - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 0u); - - undoManager->undoSafePoint(); - doc.insertText(Cursor(0, 1), "b"); - - // create a second undo group (don't merge) - QCOMPARE(undoManager->undoCount(), 2u); - - doc.undo(); - - // move second undo group to redo items - QCOMPARE(undoManager->undoCount(), 1u); - QCOMPARE(undoManager->redoCount(), 1u); - - doc.insertText(Cursor(0, 1), "b"); - - // create a second undo group again, (don't merge) - QCOMPARE(undoManager->undoCount(), 2u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.editStart(); - doc.insertText(Cursor(0, 2), "c"); - undoManager->undoSafePoint(); - doc.insertText(Cursor(0, 3), "d"); - doc.editEnd(); - - // merge both edits into second undo group - QCOMPARE(undoManager->undoCount(), 2u); - QCOMPARE(undoManager->redoCount(), 0u); - - doc.insertText(Cursor(0, 4), "e"); - - // create a third undo group (don't merge) - QCOMPARE(undoManager->undoCount(), 3u); - QCOMPARE(undoManager->redoCount(), 0u); -} - -void UndoManagerTest::testCursorPosition() -{ - TestDocument doc; - KateView *view = static_cast(doc.createView(0)); - - doc.setText("aaaa bbbb cccc\n" - "dddd ffff"); - view->setCursorPosition(KTextEditor::Cursor(1, 5)); - - doc.typeChars(view, "eeee"); - - // cursor position: "dddd eeee| ffff" - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(1, 9)); - - // undo once to remove "eeee", cursor position: "dddd | ffff" - doc.undo(); - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(1, 5)); - - // redo once to insert "eeee" again. cursor position: "dddd eeee| ffff" - doc.redo(); - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(1, 9)); - - delete view; -} - -void UndoManagerTest::testSelectionUndo() -{ - TestDocument doc; - KateView *view = static_cast(doc.createView(0)); - - doc.setText("aaaa bbbb cccc\n" - "dddd eeee ffff"); - view->setCursorPosition(KTextEditor::Cursor(1, 9)); - KTextEditor::Range selectionRange(KTextEditor::Cursor(0, 5), - KTextEditor::Cursor(1, 9)); - view->setSelection(selectionRange); - - doc.typeChars(view, "eeee"); - - // cursor position: "aaaa eeee| ffff", no selection anymore - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(0, 9)); - QCOMPARE(view->selection(), false); - - // undo to remove "eeee" and add selection and text again - doc.undo(); - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(1, 9)); - QCOMPARE(view->selection(), true); - QCOMPARE(view->selectionRange(), selectionRange); - - // redo to insert "eeee" again and remove selection - // cursor position: "aaaa eeee| ffff", no selection anymore - doc.redo(); - QCOMPARE(view->cursorPosition(), KTextEditor::Cursor(0, 9)); - QCOMPARE(view->selection(), false); - - delete view; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/tests/undomanager_test.h b/part/tests/undomanager_test.h deleted file mode 100644 index 2e5ea1f..0000000 --- a/part/tests/undomanager_test.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Bernhard Beschow - Copyright (C) 2009 Dominik Haumann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATE_UNDOMANAGER_TEST_H -#define KATE_UNDOMANAGER_TEST_H - -#include - -class UndoManagerTest : public QObject -{ - Q_OBJECT - - private Q_SLOTS: - void testUndoRedoCount(); - void testSafePoint(); - void testCursorPosition(); - void testSelectionUndo(); - - private: - class TestDocument; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/undo/kateundo.cpp b/part/undo/kateundo.cpp deleted file mode 100644 index 2cfa2b1..0000000 --- a/part/undo/kateundo.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2010 Bernhard Beschow - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateundo.h" - -#include "kateundomanager.h" -#include "katedocument.h" - -#include -#include - -KateUndo::KateUndo (KateDocument *document) -: m_document (document) -{ -} - -KateUndo::~KateUndo () -{ -} - -bool KateUndo::isEmpty() const -{ - return false; -} - -bool KateEditInsertTextUndo::isEmpty() const -{ - return len() == 0; -} - -bool KateEditRemoveTextUndo::isEmpty() const -{ - return len() == 0; -} - -bool KateUndo::mergeWith (const KateUndo* /*undo*/) -{ - return false; -} - -bool KateEditInsertTextUndo::mergeWith (const KateUndo* undo) -{ - const KateEditInsertTextUndo *u = dynamic_cast (undo); - if (u != 0 - && m_line == u->m_line - && (m_col + len()) == u->m_col) - { - m_text += u->m_text; - return true; - } - - return false; -} - -bool KateEditRemoveTextUndo::mergeWith (const KateUndo* undo) -{ - const KateEditRemoveTextUndo *u = dynamic_cast (undo); - - if (u != 0 - && m_line == u->m_line - && m_col == (u->m_col + u->len())) - { - m_text.prepend(u->m_text); - m_col = u->m_col; - return true; - } - - return false; -} - -void KateEditInsertTextUndo::undo () -{ - KateDocument *doc = document(); - - doc->editRemoveText (m_line, m_col, len()); -} - -void KateEditRemoveTextUndo::undo () -{ - KateDocument *doc = document(); - - doc->editInsertText (m_line, m_col, m_text); -} - -void KateEditWrapLineUndo::undo () -{ - KateDocument *doc = document(); - - doc->editUnWrapLine (m_line, m_newLine, m_len); -} - -void KateEditUnWrapLineUndo::undo () -{ - KateDocument *doc = document(); - - doc->editWrapLine (m_line, m_col, m_removeLine); -} - -void KateEditInsertLineUndo::undo () -{ - KateDocument *doc = document(); - - doc->editRemoveLine (m_line); -} - -void KateEditRemoveLineUndo::undo () -{ - KateDocument *doc = document(); - - doc->editInsertLine (m_line, m_text); -} - -void KateEditMarkLineAutoWrappedUndo::undo () -{ - KateDocument *doc = document(); - - doc->editMarkLineAutoWrapped (m_line, m_autowrapped); -} - -void KateEditRemoveTextUndo::redo () -{ - KateDocument *doc = document(); - - doc->editRemoveText (m_line, m_col, len()); -} - -void KateEditInsertTextUndo::redo () -{ - KateDocument *doc = document(); - - doc->editInsertText (m_line, m_col, m_text); -} - -void KateEditUnWrapLineUndo::redo () -{ - KateDocument *doc = document(); - - doc->editUnWrapLine (m_line, m_removeLine, m_len); -} - -void KateEditWrapLineUndo::redo () -{ - KateDocument *doc = document(); - - doc->editWrapLine (m_line, m_col, m_newLine); -} - -void KateEditRemoveLineUndo::redo () -{ - KateDocument *doc = document(); - - doc->editRemoveLine (m_line); -} - -void KateEditInsertLineUndo::redo () -{ - KateDocument *doc = document(); - - doc->editInsertLine (m_line, m_text); -} - -void KateEditMarkLineAutoWrappedUndo::redo () -{ - KateDocument *doc = document(); - - doc->editMarkLineAutoWrapped (m_line, m_autowrapped); -} - -KateUndoGroup::KateUndoGroup (KateUndoManager *manager, const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range &selectionRange) - : m_manager (manager) - , m_safePoint(false) - , m_undoSelection(selectionRange) - , m_redoSelection(-1, -1, -1, -1) - , m_undoCursor(cursorPosition) - , m_redoCursor(-1, -1) -{ -} - -KateUndoGroup::~KateUndoGroup () -{ - qDeleteAll (m_items); -} - -void KateUndoGroup::undo (KTextEditor::View *view) -{ - if (m_items.isEmpty()) - return; - - m_manager->startUndo (); - - for (int i=m_items.size()-1; i >= 0; --i) - m_items[i]->undo(); - - if (view != 0) { - if (m_undoSelection.isValid()) - view->setSelection(m_undoSelection); - else - view->removeSelection(); - - if (m_undoCursor.isValid()) - view->setCursorPosition(m_undoCursor); - } - - m_manager->endUndo (); -} - -void KateUndoGroup::redo (KTextEditor::View *view) -{ - if (m_items.isEmpty()) - return; - - m_manager->startUndo (); - - for (int i=0; i < m_items.size(); ++i) - m_items[i]->redo(); - - if (view != 0) { - if (m_redoSelection.isValid()) - view->setSelection(m_redoSelection); - else - view->removeSelection(); - - if (m_redoCursor.isValid()) - view->setCursorPosition(m_redoCursor); - } - - m_manager->endUndo (); -} - -void KateUndoGroup::editEnd(const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range selectionRange) -{ - m_redoCursor = cursorPosition; - m_redoSelection = selectionRange; -} - -void KateUndoGroup::addItem(KateUndo* u) -{ - if (u->isEmpty()) - delete u; - else if (!m_items.isEmpty() && m_items.last()->mergeWith(u)) - delete u; - else - m_items.append(u); -} - -bool KateUndoGroup::merge (KateUndoGroup* newGroup,bool complex) -{ - if (m_safePoint) - return false; - - if (newGroup->isOnlyType(singleType()) || complex) { - // Take all of its items first -> last - KateUndo* u = newGroup->m_items.isEmpty() ? 0 : newGroup->m_items.takeFirst (); - while (u) { - addItem(u); - u = newGroup->m_items.isEmpty() ? 0 : newGroup->m_items.takeFirst (); - } - - if (newGroup->m_safePoint) - safePoint(); - - m_redoCursor = newGroup->m_redoCursor; - m_redoSelection = newGroup->m_redoSelection; - - return true; - } - - return false; -} - -void KateUndoGroup::safePoint (bool safePoint) -{ - m_safePoint=safePoint; -} - -KTextEditor::Document *KateUndoGroup::document() -{ - return m_manager->document(); -} - -KateUndo::UndoType KateUndoGroup::singleType() const -{ - KateUndo::UndoType ret = KateUndo::editInvalid; - - Q_FOREACH(const KateUndo *item, m_items) { - if (ret == KateUndo::editInvalid) - ret = item->type(); - else if (ret != item->type()) - return KateUndo::editInvalid; - } - - return ret; -} - -bool KateUndoGroup::isOnlyType(KateUndo::UndoType type) const -{ - if (type == KateUndo::editInvalid) return false; - - Q_FOREACH(const KateUndo *item, m_items) - if (item->type() != type) - return false; - - return true; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/undo/kateundo.h b/part/undo/kateundo.h deleted file mode 100644 index 6ee28a2..0000000 --- a/part/undo/kateundo.h +++ /dev/null @@ -1,463 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2010 Bernhard Beschow - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 2001 Joseph Wenninger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef kate_undo_h -#define kate_undo_h - -#include - -#include - -class KateUndoManager; -class KateDocument; - -namespace KTextEditor { - class View; -} - -/** - * Base class for Kate undo commands. - */ -class KateUndo -{ - public: - /** - * Constructor - * @param document the document the undo item belongs to - */ - KateUndo (KateDocument *document); - - /** - * Destructor - */ - virtual ~KateUndo(); - - public: - /** - * Types for undo items - */ - enum UndoType - { - editInsertText, - editRemoveText, - editWrapLine, - editUnWrapLine, - editInsertLine, - editRemoveLine, - editMarkLineAutoWrapped, - editInvalid - }; - - public: - /** - * Check whether the item is empty. - * - * @return whether the item is empty - */ - virtual bool isEmpty() const; - - /** - * merge an undo item - * Saves a bit of memory and potentially many calls when undo/redoing. - * @param undo undo item to merge - * @return success - */ - virtual bool mergeWith(const KateUndo* undo); - - /** - * undo this item - */ - virtual void undo() = 0; - - /** - * redo this item - */ - virtual void redo() = 0; - - /** - * type of item - * @return type - */ - virtual KateUndo::UndoType type() const = 0; - - protected: - /** - * Return the document the undo item belongs to. - * @return the document the undo item belongs to - */ - inline KateDocument *document() { return m_document; } - - private: - /** - * the document the undo item belongs to - */ - KateDocument *m_document; -}; - -class KateEditInsertTextUndo : public KateUndo -{ - public: - KateEditInsertTextUndo (KateDocument *document, int line, int col, const QString &text) - : KateUndo (document) - , m_line (line) - , m_col (col) - , m_text (text) - {} - - /** - * @copydoc KateUndo::isEmpty() - */ - bool isEmpty() const; - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::mergeWith(const KateUndo) - */ - bool mergeWith (const KateUndo *undo); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editInsertText; } - - private: - int len() const { return m_text.length(); } - - private: - const int m_line; - const int m_col; - QString m_text; -}; - -class KateEditRemoveTextUndo : public KateUndo -{ - public: - KateEditRemoveTextUndo (KateDocument *document, int line, int col, const QString &text) - : KateUndo (document) - , m_line (line) - , m_col (col) - , m_text (text) - {} - - /** - * @copydoc KateUndo::isEmpty() - */ - bool isEmpty() const; - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::mergeWith(const KateUndo) - */ - bool mergeWith (const KateUndo *undo); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editRemoveText; } - - private: - int len() const { return m_text.length(); } - - private: - const int m_line; - int m_col; - QString m_text; -}; - -class KateEditMarkLineAutoWrappedUndo : public KateUndo -{ - public: - KateEditMarkLineAutoWrappedUndo (KateDocument *document, int line, bool autowrapped) - : KateUndo (document) - , m_line (line) - , m_autowrapped (autowrapped) - {} - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editMarkLineAutoWrapped; } - - private: - const int m_line; - const bool m_autowrapped; -}; - -class KateEditWrapLineUndo : public KateUndo -{ - public: - KateEditWrapLineUndo (KateDocument *document, int line, int col, int len, bool newLine) - : KateUndo (document) - , m_line (line) - , m_col (col) - , m_len (len) - , m_newLine (newLine) - {} - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editWrapLine; } - - private: - const int m_line; - const int m_col; - const int m_len; - const bool m_newLine; -}; - -class KateEditUnWrapLineUndo : public KateUndo -{ - public: - KateEditUnWrapLineUndo (KateDocument *document, int line, int col, int len, bool removeLine) - : KateUndo (document) - , m_line (line) - , m_col (col) - , m_len (len) - , m_removeLine (removeLine) - {} - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editUnWrapLine; } - - private: - const int m_line; - const int m_col; - const int m_len; - const bool m_removeLine; -}; - -class KateEditInsertLineUndo : public KateUndo -{ - public: - KateEditInsertLineUndo (KateDocument *document, int line, const QString &text) - : KateUndo (document) - , m_line (line) - , m_text (text) - {} - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editInsertLine; } - - private: - const int m_line; - const QString m_text; -}; - -class KateEditRemoveLineUndo : public KateUndo -{ - public: - KateEditRemoveLineUndo (KateDocument *document, int line, const QString &text) - : KateUndo (document) - , m_line (line) - , m_text (text) - {} - - /** - * @copydoc KateUndo::undo() - */ - void undo(); - - /** - * @copydoc KateUndo::redo() - */ - void redo(); - - /** - * @copydoc KateUndo::type() - */ - KateUndo::UndoType type() const { return KateUndo::editRemoveLine; } - - private: - const int m_line; - const QString m_text; -}; - -/** - * Class to manage a group of undo items - */ -class KateUndoGroup -{ - public: - /** - * Constructor - * @param manager KateUndoManager this undo group will belong to - */ - explicit KateUndoGroup (KateUndoManager *manager, const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range &selectionRange); - - /** - * Destructor - */ - ~KateUndoGroup(); - - public: - /** - * Undo the contained undo items - */ - void undo(KTextEditor::View *view); - - /** - * Redo the contained undo items - */ - void redo(KTextEditor::View *view); - - void editEnd(const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range selectionRange); - - /** - * merge this group with an other - * @param newGroup group to merge into this one - * @param complex set if a complex undo - * @return success - */ - bool merge (KateUndoGroup* newGroup,bool complex); - - /** - * set group as as savepoint. the next group will not merge with this one - */ - void safePoint (bool safePoint=true); - - /** - * is this undogroup empty? - */ - bool isEmpty() const { return m_items.isEmpty(); } - - private: - KTextEditor::Document *document(); - - /** - * singleType - * @return the type if it's only one type, or editInvalid if it contains multiple types. - */ - KateUndo::UndoType singleType() const; - - /** - * are we only of this type ? - * @param type type to query - * @return we contain only the given type - */ - bool isOnlyType(KateUndo::UndoType type) const; - - public: - /** - * add an undo item - * @param u item to add - */ - void addItem (KateUndo *u); - - private: - KateUndoManager *const m_manager; - - /** - * list of items contained - */ - QList m_items; - - /** - * prohibit merging with the next group - */ - bool m_safePoint; - - /** - * the text selection of the active view before the edit step - */ - const KTextEditor::Range m_undoSelection; - - /** - * the text selection of the active view after the edit step - */ - KTextEditor::Range m_redoSelection; - - /** - * the cursor position of the active view before the edit step - */ - const KTextEditor::Cursor m_undoCursor; - - /** - * the cursor position of the active view after the edit step - */ - KTextEditor::Cursor m_redoCursor; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/undo/kateundomanager.cpp b/part/undo/kateundomanager.cpp deleted file mode 100644 index 2d04bcb..0000000 --- a/part/undo/kateundomanager.cpp +++ /dev/null @@ -1,395 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ -#include "kateundomanager.h" - -#include - -#include "katedocument.h" -#include "kateundo.h" - -KateUndoManager::KateUndoManager (KateDocument *doc) - : QObject (doc) - , m_document (doc) - , m_undoComplexMerge (false) - , m_isActive (true) - , m_editCurrentUndo (0) - , lastUndoGroupWhenSaved(0) - , lastRedoGroupWhenSaved(0) - , docWasSavedWhenUndoWasEmpty(true) - , docWasSavedWhenRedoWasEmpty(true) -{ - connect(this, SIGNAL(undoEnd(KTextEditor::Document*)), this, SIGNAL(undoChanged())); - connect(this, SIGNAL(redoEnd(KTextEditor::Document*)), this, SIGNAL(undoChanged())); - - connect(doc, SIGNAL(viewCreated(KTextEditor::Document*, KTextEditor::View*)), SLOT(viewCreated(KTextEditor::Document*, KTextEditor::View*))); -} - -KateUndoManager::~KateUndoManager() -{ - delete m_editCurrentUndo; - - // cleanup the undo/redo items, very important, truee :/ - qDeleteAll(undoItems); - undoItems.clear(); - qDeleteAll(redoItems); - redoItems.clear(); -} - -KTextEditor::Document *KateUndoManager::document() -{ - return m_document; -} - -void KateUndoManager::viewCreated (KTextEditor::Document *, KTextEditor::View *newView) -{ - connect(newView, SIGNAL(cursorPositionChanged(KTextEditor::View*, const KTextEditor::Cursor&)), SLOT(undoCancel())); -} - -void KateUndoManager::editStart() -{ - if (!m_isActive) - return; - - // editStart() and editEnd() must be called in alternating fashion - Q_ASSERT(m_editCurrentUndo == 0); // make sure to enter a clean state - - const KTextEditor::Cursor cursorPosition = activeView() ? activeView()->cursorPosition() : KTextEditor::Cursor::invalid(); - const KTextEditor::Range selectionRange = activeView() ? activeView()->selectionRange() : KTextEditor::Range::invalid(); - - // new current undo item - m_editCurrentUndo = new KateUndoGroup(this, cursorPosition, selectionRange); - - Q_ASSERT(m_editCurrentUndo != 0); // a new undo group must be created by this method -} - -void KateUndoManager::editEnd() -{ - if (!m_isActive) - return; - - // editStart() and editEnd() must be called in alternating fashion - Q_ASSERT(m_editCurrentUndo != 0); // an undo group must have been created by editStart() - - const KTextEditor::Cursor cursorPosition = activeView() ? activeView()->cursorPosition() : KTextEditor::Cursor::invalid(); - const KTextEditor::Range selectionRange = activeView() ? activeView()->selectionRange() : KTextEditor::Range::invalid(); - - m_editCurrentUndo->editEnd(cursorPosition, selectionRange); - - bool changedUndo = false; - - if (m_editCurrentUndo->isEmpty()) { - delete m_editCurrentUndo; - } else if (!undoItems.isEmpty() - && undoItems.last()->merge(m_editCurrentUndo, m_undoComplexMerge)) { - delete m_editCurrentUndo; - } else { - undoItems.append(m_editCurrentUndo); - changedUndo = true; - } - - m_editCurrentUndo = 0L; - - if (changedUndo) - emit undoChanged(); - - Q_ASSERT(m_editCurrentUndo == 0); // must be 0 after calling this method -} - -void KateUndoManager::inputMethodStart() -{ - setActive(false); - m_document->editStart(); -} - -void KateUndoManager::inputMethodEnd() -{ - m_document->editEnd(); - setActive(true); -} - -void KateUndoManager::startUndo() -{ - setActive(false); - m_document->editStart(); -} - -void KateUndoManager::endUndo() -{ - m_document->editEnd(); - setActive(true); -} - -void KateUndoManager::slotTextInserted(int line, int col, const QString &s) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditInsertTextUndo(m_document, line, col, s)); -} - -void KateUndoManager::slotTextRemoved(int line, int col, const QString &s) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditRemoveTextUndo(m_document, line, col, s)); -} - -void KateUndoManager::slotMarkLineAutoWrapped(int line, bool autowrapped) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditMarkLineAutoWrappedUndo(m_document, line, autowrapped)); -} - -void KateUndoManager::slotLineWrapped(int line, int col, int pos, bool newLine) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditWrapLineUndo(m_document, line, col, pos, newLine)); -} - -void KateUndoManager::slotLineUnWrapped(int line, int col, int length, bool lineRemoved) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditUnWrapLineUndo(m_document, line, col, length, lineRemoved)); -} - -void KateUndoManager::slotLineInserted(int line, const QString &s) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditInsertLineUndo(m_document, line, s)); -} - -void KateUndoManager::slotLineRemoved(int line, const QString &s) -{ - if (m_editCurrentUndo != 0) // do we care about notifications? - addUndoItem(new KateEditRemoveLineUndo(m_document, line, s)); -} - -void KateUndoManager::undoCancel() -{ - // Don't worry about this when an edit is in progress - if (m_document->isEditRunning()) - return; - - undoSafePoint(); -} - -void KateUndoManager::undoSafePoint() { - KateUndoGroup *undoGroup = m_editCurrentUndo; - - if (undoGroup == 0 && !undoItems.isEmpty()) - undoGroup = undoItems.last(); - - if (undoGroup == 0) - return; - - undoGroup->safePoint(); -} - -void KateUndoManager::addUndoItem(KateUndo *undo) -{ - Q_ASSERT(undo != 0); // don't add null pointers to our history - Q_ASSERT(m_editCurrentUndo != 0); // make sure there is an undo group for our item - - m_editCurrentUndo->addItem(undo); - - // Clear redo buffer - qDeleteAll(redoItems); - redoItems.clear(); -} - -void KateUndoManager::setActive(bool enabled) -{ - Q_ASSERT(m_editCurrentUndo == 0); // must not already be in edit mode - Q_ASSERT(m_isActive != enabled); - - m_isActive = enabled; - - emit isActiveChanged(enabled); -} - -uint KateUndoManager::undoCount () const -{ - return undoItems.count (); -} - -uint KateUndoManager::redoCount () const -{ - return redoItems.count (); -} - -void KateUndoManager::undo() -{ - Q_ASSERT(m_editCurrentUndo == 0); // undo is not supported while we care about notifications (call editEnd() first) - - if (undoItems.count() > 0) - { - emit undoStart(document()); - - undoItems.last()->undo(activeView()); - redoItems.append (undoItems.last()); - undoItems.removeLast (); - updateModified(); - - emit undoEnd(document()); - } -} - -void KateUndoManager::redo() -{ - Q_ASSERT(m_editCurrentUndo == 0); // redo is not supported while we care about notifications (call editEnd() first) - - if (redoItems.count() > 0) - { - emit redoStart(document()); - - redoItems.last()->redo(activeView()); - undoItems.append (redoItems.last()); - redoItems.removeLast (); - updateModified(); - - emit redoEnd(document()); - } -} - -void KateUndoManager::updateModified() -{ - /* - How this works: - - After noticing that there where to many scenarios to take into - consideration when using 'if's to toggle the "Modified" flag - I came up with this baby, flexible and repetitive calls are - minimal. - - A numeric unique pattern is generated by toggling a set of bits, - each bit symbolizes a different state in the Undo Redo structure. - - undoItems.isEmpty() != null BIT 1 - redoItems.isEmpty() != null BIT 2 - docWasSavedWhenUndoWasEmpty == true BIT 3 - docWasSavedWhenRedoWasEmpty == true BIT 4 - lastUndoGroupWhenSavedIsLastUndo BIT 5 - lastUndoGroupWhenSavedIsLastRedo BIT 6 - lastRedoGroupWhenSavedIsLastUndo BIT 7 - lastRedoGroupWhenSavedIsLastRedo BIT 8 - - If you find a new pattern, please add it to the patterns array - */ - - unsigned char currentPattern = 0; - const unsigned char patterns[] = {5,16,21,24,26,88,90,93,133,144,149,154,165}; - const unsigned char patternCount = sizeof(patterns); - KateUndoGroup* undoLast = 0; - KateUndoGroup* redoLast = 0; - - if (undoItems.isEmpty()) - { - currentPattern |= 1; - } - else - { - undoLast = undoItems.last(); - } - - if (redoItems.isEmpty()) - { - currentPattern |= 2; - } - else - { - redoLast = redoItems.last(); - } - - if (docWasSavedWhenUndoWasEmpty) currentPattern |= 4; - if (docWasSavedWhenRedoWasEmpty) currentPattern |= 8; - if (lastUndoGroupWhenSaved == undoLast) currentPattern |= 16; - if (lastUndoGroupWhenSaved == redoLast) currentPattern |= 32; - if (lastRedoGroupWhenSaved == undoLast) currentPattern |= 64; - if (lastRedoGroupWhenSaved == redoLast) currentPattern |= 128; - - // This will print out the pattern information - - kDebug() << "Pattern:" << static_cast(currentPattern); - - for (uint patternIndex = 0; patternIndex < patternCount; ++patternIndex) - { - if ( currentPattern == patterns[patternIndex] ) - { - m_document->setModified( false ); - // (dominik) whenever the doc is not modified, succeeding edits - // should not be merged - undoSafePoint(); - kDebug() << "setting modified to false!"; - break; - } - } -} - -void KateUndoManager::clearUndo() -{ - qDeleteAll(undoItems); - undoItems.clear (); - - lastUndoGroupWhenSaved = 0; - docWasSavedWhenUndoWasEmpty = false; - - emit undoChanged (); -} - -void KateUndoManager::clearRedo() -{ - qDeleteAll(redoItems); - redoItems.clear (); - - lastRedoGroupWhenSaved = 0; - docWasSavedWhenRedoWasEmpty = false; - - emit undoChanged (); -} - -void KateUndoManager::setModified(bool m) { - if ( m == false ) - { - if ( ! undoItems.isEmpty() ) - { - lastUndoGroupWhenSaved = undoItems.last(); - } - - if ( ! redoItems.isEmpty() ) - { - lastRedoGroupWhenSaved = redoItems.last(); - } - - docWasSavedWhenUndoWasEmpty = undoItems.isEmpty(); - docWasSavedWhenRedoWasEmpty = redoItems.isEmpty(); - } -} - -void KateUndoManager::updateConfig () -{ - emit undoChanged (); -} - -void KateUndoManager::setAllowComplexMerge(bool allow) -{ - m_undoComplexMerge = allow; -} - -KTextEditor::View* KateUndoManager::activeView() -{ - return m_document->activeView(); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/undo/kateundomanager.h b/part/undo/kateundomanager.h deleted file mode 100644 index 9e60640..0000000 --- a/part/undo/kateundomanager.h +++ /dev/null @@ -1,206 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009-2010 Bernhard Beschow - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATEUNDOMANAGER_H -#define KATEUNDOMANAGER_H - -#include - -#include "katepartprivate_export.h" - -#include - -class KateDocument; -class KateUndo; -class KateUndoGroup; - -namespace KTextEditor { - class Document; - class View; -} - -/** - * KateUndoManager implements a document's history. It is in either of the two states: - * @li the default state, which allows rolling back and forth the history of a document, and - * @li a state in which a new element is being added to the history. - * - * The state of the KateUndomanager can be switched using editStart() and editEnd(). - */ -class KATEPART_TESTS_EXPORT KateUndoManager : public QObject -{ - Q_OBJECT - - public: - /** - * Creates a clean undo history. - * - * @param doc the document the KateUndoManager will belong to - */ - KateUndoManager (KateDocument *doc); - - ~KateUndoManager(); - - KTextEditor::Document *document(); - - /** - * Returns how many undo() actions can be performed. - * - * @return the number of undo groups which can be undone - */ - uint undoCount () const; - - /** - * Returns how many redo() actions can be performed. - * - * @return the number of undo groups which can be redone - */ - uint redoCount () const; - - /** - * Prevent latest KateUndoGroup from being merged with the next one. - */ - void undoSafePoint(); - - /** - * Allows or disallows merging of "complex" undo groups. - * - * When an undo group contains different types of undo items, it is considered - * a "complex" group. - * - * @param allow whether complex merging is allowed - */ - void setAllowComplexMerge(bool allow); - - bool isActive() const { return m_isActive; } - - void setModified( bool m ); - void updateConfig (); - - public Q_SLOTS: - /** - * Undo the latest undo group. - * - * Make sure isDefaultState() is true when calling this method. - */ - void undo (); - - /** - * Redo the latest undo group. - * - * Make sure isDefaultState() is true when calling this method. - */ - void redo (); - - void clearUndo (); - void clearRedo (); - - /** - * Notify KateUndoManager about the beginning of an edit. - */ - void editStart(); - - /** - * Notify KateUndoManager about the end of an edit. - */ - void editEnd(); - - void startUndo(); - void endUndo(); - - void inputMethodStart(); - void inputMethodEnd(); - - /** - * Notify KateUndoManager that text was inserted. - */ - void slotTextInserted(int line, int col, const QString &s); - - /** - * Notify KateUndoManager that text was removed. - */ - void slotTextRemoved(int line, int col, const QString &s); - - /** - * Notify KateUndoManager that a line was marked as autowrapped. - */ - void slotMarkLineAutoWrapped(int line, bool autowrapped); - - /** - * Notify KateUndoManager that a line was wrapped. - */ - void slotLineWrapped(int line, int col, int pos, bool newLine); - - /** - * Notify KateUndoManager that a line was un-wrapped. - */ - void slotLineUnWrapped(int line, int col, int length, bool lineRemoved); - - /** - * Notify KateUndoManager that a line was inserted. - */ - void slotLineInserted(int line, const QString &s); - - /** - * Notify KateUndoManager that a line was removed. - */ - void slotLineRemoved(int line, const QString &s); - - Q_SIGNALS: - void undoChanged (); - void undoStart (KTextEditor::Document*); - void undoEnd (KTextEditor::Document*); - void redoStart (KTextEditor::Document*); - void redoEnd (KTextEditor::Document*); - void isActiveChanged(bool enabled); - - private Q_SLOTS: - /** - * @short Add an undo item to the current undo group. - * - * @param undo undo item to be added, must be non-null - */ - void addUndoItem(KateUndo *undo); - - void setActive(bool active); - - void updateModified(); - - void undoCancel(); - void viewCreated (KTextEditor::Document *, KTextEditor::View *newView); - - private: - KTextEditor::View *activeView(); - - private: - KateDocument *m_document; - bool m_undoComplexMerge; - bool m_isActive; - KateUndoGroup* m_editCurrentUndo; - QList undoItems; - QList redoItems; - // these two variables are for resetting the document to - // non-modified if all changes have been undone... - KateUndoGroup* lastUndoGroupWhenSaved; - KateUndoGroup* lastRedoGroupWhenSaved; - bool docWasSavedWhenUndoWasEmpty; - bool docWasSavedWhenRedoWasEmpty; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateautoindent.cpp b/part/utils/kateautoindent.cpp deleted file mode 100644 index 534780f..0000000 --- a/part/utils/kateautoindent.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2003 Jesse Yurkovich - Copyright (C) 2004 >Anders Lund (KateVarIndent class) - Copyright (C) 2005 Dominik Haumann (basic support for config page) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateautoindent.h" -#include "kateautoindent.moc" - -#include "kateconfig.h" -#include "katehighlight.h" -#include "kateglobal.h" -#include "kateindentscript.h" -#include "katescriptmanager.h" -#include "kateview.h" -#include "kateextendedattribute.h" -#include "katedocument.h" - -#include -#include -#include - -#include - -const QString MODE_NONE = QLatin1String("none"); -const QString MODE_NORMAL = QLatin1String("normal"); - -//BEGIN KateAutoIndent - -QStringList KateAutoIndent::listModes () -{ - QStringList l; - - for (int i = 0; i < modeCount(); ++i) - l << modeDescription(i); - - return l; -} - -int KateAutoIndent::modeCount () -{ - // inbuild modes + scripts - return 2 + KateGlobal::self()->scriptManager()->indentationScriptCount(); -} - - -QString KateAutoIndent::modeName (int mode) -{ - if (mode == 0 || mode >= modeCount ()) - return MODE_NONE; - - if (mode == 1) - return MODE_NORMAL; - - return KateGlobal::self()->scriptManager()->indentationScriptByIndex(mode-2)->indentHeader().baseName(); -} - -QString KateAutoIndent::modeDescription (int mode) -{ - if (mode == 0 || mode >= modeCount ()) - return i18nc ("Autoindent mode", "None"); - - if (mode == 1) - return i18nc ("Autoindent mode", "Normal"); - - return KateGlobal::self()->scriptManager()->indentationScriptByIndex(mode-2)->indentHeader().name(); -} - -QString KateAutoIndent::modeRequiredStyle(int mode) -{ - if (mode == 0 || mode == 1 || mode >= modeCount()) - return QString(); - - return KateGlobal::self()->scriptManager()->indentationScriptByIndex(mode-2)->indentHeader().requiredStyle(); -} - -uint KateAutoIndent::modeNumber (const QString &name) -{ - for (int i = 0; i < modeCount(); ++i) - if (modeName(i) == name) - return i; - - return 0; -} - -KateAutoIndent::KateAutoIndent (KateDocument *_doc) - : QObject(_doc), doc(_doc), m_script (0) -{ - // don't call updateConfig() here, document might is not ready for that.... - - // on script reload, the script pointer is invalid -> force reload - connect(KateGlobal::self()->scriptManager(), SIGNAL(reloaded()), - this, SLOT(reloadScript())); -} - -KateAutoIndent::~KateAutoIndent () -{ -} - -QString KateAutoIndent::tabString (int length, int align) const -{ - QString s; - length = qMin (length, 256); // sanity check for large values of pos - int spaces = qBound(0, align - length, 256); - - if (!useSpaces) - { - s.append (QString (length / tabWidth, '\t')); - length = length % tabWidth; - } - s.append(QString(length + spaces, ' ')); - - return s; -} - -bool KateAutoIndent::doIndent(int line, int indentDepth, int align) -{ - kDebug (13060) << "doIndent: line: " << line << " indentDepth: " << indentDepth << " align: " << align; - - Kate::TextLine textline = doc->plainKateTextLine(line); - - // textline not found, cu - if (!textline) - return false; - - // sanity check - if (indentDepth < 0) - indentDepth = 0; - - const QString oldIndentation = textline->leadingWhitespace(); - - // Preserve existing "tabs then spaces" alignment if and only if: - // - no alignment was passed to doIndent and - // - we aren't using spaces for indentation and - // - we aren't rounding indentation up to the next multiple of the indentation width and - // - we aren't using a combination to tabs and spaces for alignment, or in other words - // the indent width is a multiple of the tab width. - bool preserveAlignment = !useSpaces && keepExtra && indentWidth % tabWidth == 0; - if (align == 0 && preserveAlignment) - { - // Count the number of consecutive spaces at the end of the existing indentation - int i = oldIndentation.size() - 1; - while (i >= 0 && oldIndentation.at(i) == ' ') - --i; - // Use the passed indentDepth as the alignment, and set the indentDepth to - // that value minus the number of spaces found (but don't let it get negative). - align = indentDepth; - indentDepth = qMax(0, align - (oldIndentation.size() - 1 - i)); - } - - QString indentString = tabString(indentDepth, align); - - // remove leading whitespace, then insert the leading indentation - doc->editStart (); - doc->editRemoveText (line, 0, oldIndentation.length()); - doc->editInsertText (line, 0, indentString); - doc->editEnd (); - - return true; -} - -bool KateAutoIndent::doIndentRelative(int line, int change) -{ - kDebug (13060) << "doIndentRelative: line: " << line << " change: " << change; - - Kate::TextLine textline = doc->plainKateTextLine(line); - - // get indent width of current line - int indentDepth = textline->indentDepth (tabWidth); - int extraSpaces = indentDepth % indentWidth; - - // add change - indentDepth += change; - - // if keepExtra is off, snap to a multiple of the indentWidth - if (!keepExtra && extraSpaces > 0) - { - if (change < 0) - indentDepth += indentWidth - extraSpaces; - else - indentDepth -= extraSpaces; - } - - // do indent - return doIndent(line, indentDepth); -} - -void KateAutoIndent::keepIndent ( int line ) -{ - // no line in front, no work... - if (line <= 0) - return; - - Kate::TextLine prevTextLine = doc->plainKateTextLine(line-1); - Kate::TextLine textLine = doc->plainKateTextLine(line); - - // textline not found, cu - if (!prevTextLine || !textLine) - return; - - const QString previousWhitespace = prevTextLine->leadingWhitespace(); - - // remove leading whitespace, then insert the leading indentation - doc->editStart (); - - if (!keepExtra) - { - const QString currentWhitespace = textLine->leadingWhitespace(); - doc->editRemoveText (line, 0, currentWhitespace.length()); - } - - doc->editInsertText (line, 0, previousWhitespace); - doc->editEnd (); -} - -void KateAutoIndent::reloadScript() -{ - // small trick to force reload - m_script = 0; // prevent dangling pointer - QString currentMode = m_mode; - m_mode = QString(); - setMode(currentMode); -} - -void KateAutoIndent::scriptIndent (KateView *view, const KTextEditor::Cursor &position, QChar typedChar) -{ - QPair result = m_script->indent (view, position, typedChar, indentWidth); - int newIndentInChars = result.first; - - // handle negative values special - if (newIndentInChars < -1) - return; - - // reuse indentation of the previous line, just like the "normal" indenter - if (newIndentInChars == -1) - { - // keep indent of previous line - keepIndent (position.line()); - - return; - } - - int align = result.second; - if (align > 0) - kDebug (13060) << "Align: " << align; - - // we got a positive or zero indent to use... - doIndent (position.line(), newIndentInChars, align); -} - -bool KateAutoIndent::isStyleProvided(const KateIndentScript *script, const KateHighlighting *highlight) -{ - QString requiredStyle = script->indentHeader().requiredStyle(); - return (requiredStyle.isEmpty() || requiredStyle == highlight->style()); -} - -void KateAutoIndent::setMode (const QString &name) -{ - // bail out, already set correct mode... - if (m_mode == name) - return; - - // cleanup - m_script = 0; - - // first, catch easy stuff... normal mode and none, easy... - if ( name.isEmpty() || name == MODE_NONE ) - { - m_mode = MODE_NONE; - return; - } - - if ( name == MODE_NORMAL ) - { - m_mode = MODE_NORMAL; - return; - } - - // handle script indenters, if any for this name... - KateIndentScript *script = KateGlobal::self()->scriptManager()->indentationScript(name); - if ( script ) - { - if (isStyleProvided(script, doc->highlight())) - { - m_script = script; - m_mode = name; - - kDebug( 13060 ) << "mode: " << name << "accepted"; - return; - } - else - { - kWarning( 13060 ) << "mode" << name << "requires a different highlight style"; - } - } - else - { - kWarning( 13060 ) << "mode" << name << "does not exist"; - } - - // Fall back to normal - m_mode = MODE_NORMAL; -} - -void KateAutoIndent::checkRequiredStyle() -{ - if (m_script) - { - if (!isStyleProvided(m_script, doc->highlight())) - { - kDebug( 13060 ) << "mode" << m_mode << "requires a different highlight style"; - doc->config()->setIndentationMode(MODE_NORMAL); - } - } -} - -void KateAutoIndent::updateConfig () -{ - KateDocumentConfig *config = doc->config(); - - useSpaces = config->replaceTabsDyn(); - keepExtra = config->keepExtraSpaces(); - tabWidth = config->tabWidth(); - indentWidth = config->indentationWidth(); -} - - -bool KateAutoIndent::changeIndent (const KTextEditor::Range &range, int change) -{ - QList skippedLines; - - // loop over all lines given... - for (int line = range.start().line () < 0 ? 0 : range.start().line (); - line <= qMin (range.end().line (), doc->lines()-1); ++line) - { - // don't indent empty lines - if (doc->line(line).isEmpty()) - { - skippedLines.append (line); - continue; - } - // don't indent the last line when the cursor is on the first column - if (line == range.end().line() && range.end().column() == 0) - { - skippedLines.append (line); - continue; - } - - doIndentRelative(line, change * indentWidth); - } - - if (skippedLines.count() > range.numberOfLines()) - { - // all lines were empty, so indent them nevertheless - foreach (int line, skippedLines) - doIndentRelative(line, change * indentWidth); - } - - return true; -} - -void KateAutoIndent::indent (KateView *view, const KTextEditor::Range &range) -{ - // no script, do nothing... - if (!m_script) - return; - - doc->pushEditState(); - doc->editStart(); - // loop over all lines given... - for (int line = range.start().line () < 0 ? 0 : range.start().line (); - line <= qMin (range.end().line (), doc->lines()-1); ++line) - { - // let the script indent for us... - scriptIndent (view, KTextEditor::Cursor (line, 0), QChar()); - } - doc->editEnd (); - doc->popEditState(); -} - -void KateAutoIndent::userTypedChar (KateView *view, const KTextEditor::Cursor &position, QChar typedChar) -{ - // normal mode - if (m_mode == MODE_NORMAL) - { - // only indent on new line, per default - if (typedChar != '\n') - return; - - // keep indent of previous line - keepIndent (position.line()); - - return; - } - - // no script, do nothing... - if (!m_script) - return; - - // does the script allow this char as trigger? - if (typedChar != '\n' && !m_script->triggerCharacters().contains(typedChar)) - return; - - // let the script indent for us... - scriptIndent (view, position, typedChar); -} -//END KateAutoIndent - -//BEGIN KateViewIndentAction -KateViewIndentationAction::KateViewIndentationAction(KateDocument *_doc, const QString& text, QObject *parent) - : KActionMenu (text, parent), doc(_doc) -{ - connect(menu(),SIGNAL(aboutToShow()),this,SLOT(slotAboutToShow())); - actionGroup = new QActionGroup(menu()); -} - -void KateViewIndentationAction::slotAboutToShow() -{ - QStringList modes = KateAutoIndent::listModes (); - - menu()->clear (); - foreach (QAction *action, actionGroup->actions()) { - actionGroup->removeAction(action); - } - for (int z=0; zaddAction( '&' + KateAutoIndent::modeDescription(z).replace('&', "&&") ); - actionGroup->addAction(action); - action->setCheckable( true ); - action->setData( z ); - - QString requiredStyle = KateAutoIndent::modeRequiredStyle(z); - action->setEnabled(requiredStyle.isEmpty() || requiredStyle == doc->highlight()->style()); - - if ( doc->config()->indentationMode() == KateAutoIndent::modeName (z) ) - action->setChecked( true ); - } - - disconnect( menu(), SIGNAL( triggered( QAction* ) ), this, SLOT( setMode( QAction* ) ) ); - connect( menu(), SIGNAL( triggered( QAction* ) ), this, SLOT( setMode( QAction* ) ) ); -} - -void KateViewIndentationAction::setMode (QAction *action) -{ - // set new mode - doc->config()->setIndentationMode(KateAutoIndent::modeName (action->data().toInt())); -} -//END KateViewIndentationAction - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateautoindent.h b/part/utils/kateautoindent.h deleted file mode 100644 index 0f9d5ea..0000000 --- a/part/utils/kateautoindent.h +++ /dev/null @@ -1,249 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2003 Jesse Yurkovich - Copyright (C) 2004 >Anders Lund (KateVarIndent class) - Copyright (C) 2005 Dominik Haumann (basic support for config page) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_AUTO_INDENT_H__ -#define __KATE_AUTO_INDENT_H__ - -#include "kateconfig.h" - -#include - -#include -#include - -class KateDocument; -class KateIndentScript; -class KateHighlighting; - -/** - * Provides Auto-Indent functionality for katepart. - * This baseclass is a real dummy, does nothing beside remembering the document it belongs too, - * only to have the object around - */ -class KateAutoIndent : public QObject -{ - Q_OBJECT - /* - * Static methods to list indention modes - */ - public: - /** - * List all possible modes by name - * @return list of modes - */ - static QStringList listModes (); - - /** - * Return the mode name given the mode - * @param mode mode index - * @return name for this mode index - */ - static QString modeName (int mode); - - /** - * Return the mode description - * @param mode mode index - * @return mode index - */ - static QString modeDescription (int mode); - - /** - * Return the syntax highlighting style required to use this mode - * @param mode mode index - * @return required style, or empty if the mode doesn't require any style - */ - static QString modeRequiredStyle(int mode); - - /** - * Maps name -> index - * @param name mode name - * @return mode index - */ - static uint modeNumber (const QString &name); - - /** - * count of modes - * @return number of existing modes - */ - static int modeCount (); - - /* - * Construction + Destruction - */ - public: - /** - * Constructor, creates dummy indenter "None" - * \param doc parent document - */ - explicit KateAutoIndent (KateDocument *doc); - - /** - * Destructor - */ - ~KateAutoIndent (); - - /* - * Internal helper for the subclasses and itself - */ - private: - /** - * Produces a string with the proper indentation characters for its length. - * - * @param length The length of the indention in characters. - * @param align Length of alignment, ignored if less of equal to length - * @return A QString representing @p length characters (factoring in tabs and spaces) - */ - QString tabString (int length, int align) const; - - /** - * Set the indent level of the line. - * \param line line to change indent for - * \param change set indentation to given number of spaces - * \param align if align is higher than indentDepth, the difference - * represents a number of spaces to be added after the indent - */ - bool doIndent(int line, int indentDepth, int align = 0); - - /** - * Change the indent of the specified line by the number of levels - * specified by change. Positive values will indent more, negative values - * will indent less. - * \param line line to change indent for - * \param change change the indentation by given number of spaces - */ - bool doIndentRelative(int line, int change); - - /** - * Reuse the indent of the previous line - * \param line line to change indent for - */ - void keepIndent ( int line ); - - /** - * Call the indentation script, this is a helper to be used in userTypedChar and indent - * \param view the view the user work at - * \param position current cursor position, after the inserted char... - * \param typedChar the inserted char, indent will just give the script '\n' - */ - void scriptIndent (KateView *view, const KTextEditor::Cursor &position, QChar typedChar); - - /** - * Return true if the required style for the script is provided by the highlighter. - */ - static bool isStyleProvided(const KateIndentScript *script, const KateHighlighting *highlight); - - public: - /** - * Switch indenter - * Nop if already set to given mode - * Otherwise switch to given indenter or to "None" if no suitable found... - * @param name indention mode wanted - */ - void setMode (const QString &name); - - /** - * Check if the current highlighting mode provides the style required by the - * current indenter. If not, deactivate the indenter by changing to "normal" - * mode. - */ - void checkRequiredStyle(); - - /** - * mode name - */ - const QString &modeName () const { return m_mode; } - - /** - * Update indenter's configuration (indention width, etc.) - * Is called in the updateConfig() of the document and after creation of the indenter... - */ - void updateConfig (); - - /** - * Function to provide the common indent/unindent/clean indent functionality to the document - * This should be generic for all indenters, internally it uses the doIndent function. - * This works equal for all indenters, even for "none" or the scripts - * \param range range of text to change indent for - * \param change level of indents to add or remove, zero will still trigger cleaning of indentation - * and removal of extra spaces, if option set - * \return \e true on success, otherwise \e false - */ - bool changeIndent (const KTextEditor::Range &range, int change); - - /** - * The document requests the indenter to indent the given range of existing text. - * This may happen to indent text pasted or to reindent existing text. - * For "none" and "normal" this is a nop, for the scripts, the expression - * will be asked for indent level for each line - * \param view the view the user work at - * \param range the range of text to indent... - */ - void indent (KateView *view, const KTextEditor::Range &range); - - /** - * The user typed some char, the indenter can react on this - * '\n' will be send as char if the user wraps a line - * \param view the view the user work at - * \param position current cursor position, after the inserted char... - * \param typedChar the inserted char - */ - void userTypedChar (KateView *view, const KTextEditor::Cursor &position, QChar typedChar); - - public Q_SLOTS: - void reloadScript(); - - /* - * needed data - */ - private: - KateDocument *doc; //!< the document the indenter works on - int tabWidth; //!< The number of characters simulated for a tab - int indentWidth; //!< The number of characters used when tabs are replaced by spaces - bool useSpaces; //!< Should we use spaces or tabs to indent - bool keepExtra; //!< Keep indentation that is not on indentation boundaries - QString m_mode; - KateIndentScript *m_script; -}; - -/** - * This action provides a list of available indenters and gets plugged - * into the KateView's KActionCollection. - */ -class KateViewIndentationAction : public KActionMenu -{ - Q_OBJECT - - public: - KateViewIndentationAction(KateDocument *_doc, const QString& text, QObject *parent); - - private: - KateDocument* doc; - QActionGroup *actionGroup; - - public Q_SLOTS: - void slotAboutToShow(); - - private Q_SLOTS: - void setMode (QAction*); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katebookmarks.cpp b/part/utils/katebookmarks.cpp deleted file mode 100644 index 4565d5b..0000000 --- a/part/utils/katebookmarks.cpp +++ /dev/null @@ -1,307 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002, 2003, 2004 Anders Lund - Copyright (C) 2002 John Firebaugh - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katebookmarks.h" -#include "katebookmarks.moc" - -#include "katedocument.h" -#include "kateview.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace KTextEditor{ class Document; } - -/** - Utility: selection sort - sort a QMemArray in ascending order. - max it the largest (zerobased) index to sort. - To sort the entire array: ssort( *array, array.size() -1 ); - This is only efficient if ran only once. -*/ -static void ssort( QVector &a, int max ) -{ - uint tmp, j, maxpos; - for ( uint h = max; h >= 1; h-- ) - { - maxpos = 0; - for ( j = 0; j <= h; j++ ) - maxpos = a[j] > a[maxpos] ? j : maxpos; - tmp = a[maxpos]; - a[maxpos] = a[h]; - a[h] = tmp; - } -} - -// TODO add a insort() or bubble_sort - more efficient for aboutToShow() ? - -KateBookmarks::KateBookmarks( KateView* view, Sorting sort ) - : QObject( view ) - , m_view( view ) - , m_bookmarkClear (0) - , m_sorting( sort ) -{ - setObjectName( "kate bookmarks" ); - connect (view->doc(), SIGNAL( marksChanged( KTextEditor::Document* ) ), this, SLOT( marksChanged() )); - _tries=0; - m_bookmarksMenu = 0L; -} - -KateBookmarks::~KateBookmarks() -{ -} - -void KateBookmarks::createActions( KActionCollection* ac ) -{ - m_bookmarkToggle = new KToggleAction( i18n("Set &Bookmark"), this ); - ac->addAction( "bookmarks_toggle", m_bookmarkToggle ); - m_bookmarkToggle->setIcon( KIcon( "bookmark-new" ) ); - m_bookmarkToggle->setShortcut( Qt::CTRL+Qt::Key_B ); - m_bookmarkToggle->setWhatsThis(i18n("If a line has no bookmark then add one, otherwise remove it.")); - connect( m_bookmarkToggle, SIGNAL( triggered() ), this, SLOT(toggleBookmark()) ); - - m_bookmarkClear = new KAction( i18n("Clear &All Bookmarks"), this ); - ac->addAction("bookmarks_clear", m_bookmarkClear); - m_bookmarkClear->setWhatsThis(i18n("Remove all bookmarks of the current document.")); - connect( m_bookmarkClear, SIGNAL( triggered() ), this, SLOT(clearBookmarks()) ); - - m_goNext = new KAction( i18n("Next Bookmark"), this); - ac->addAction("bookmarks_next", m_goNext); - m_goNext->setIcon( KIcon( "go-down-search" ) ); - m_goNext->setShortcut( Qt::ALT + Qt::Key_PageDown ); - m_goNext->setWhatsThis(i18n("Go to the next bookmark.")); - connect( m_goNext, SIGNAL( triggered() ), this, SLOT(goNext()) ); - - m_goPrevious = new KAction( i18n("Previous Bookmark"), this); - ac->addAction("bookmarks_previous", m_goPrevious); - m_goPrevious->setIcon( KIcon( "go-up-search" ) ); - m_goPrevious->setShortcut( Qt::ALT + Qt::Key_PageUp ); - m_goPrevious->setWhatsThis(i18n("Go to the previous bookmark.")); - connect( m_goPrevious, SIGNAL( triggered() ), this, SLOT(goPrevious()) ); - - KActionMenu *actionMenu = new KActionMenu(i18n("&Bookmarks"), this); - ac->addAction("bookmarks", actionMenu); - m_bookmarksMenu = actionMenu->menu(); - - connect( m_bookmarksMenu, SIGNAL(aboutToShow()), this, SLOT(bookmarkMenuAboutToShow())); - - marksChanged (); - - // Always want the actions with shortcuts plugged into something so their shortcuts can work - m_view->addAction(m_bookmarkToggle); - m_view->addAction(m_bookmarkClear); - m_view->addAction(m_goNext); - m_view->addAction(m_goPrevious); -} - -void KateBookmarks::toggleBookmark () -{ - uint mark = m_view->doc()->mark( m_view->cursorPosition().line() ); - if( mark & KTextEditor::MarkInterface::markType01 ) - m_view->doc()->removeMark( m_view->cursorPosition().line(), - KTextEditor::MarkInterface::markType01 ); - else - m_view->doc()->addMark( m_view->cursorPosition().line(), - KTextEditor::MarkInterface::markType01 ); -} - -void KateBookmarks::clearBookmarks () -{ - QHash m = m_view->doc()->marks(); - for (QHash::const_iterator i = m.constBegin(); i != m.constEnd(); ++i) - m_view->doc()->removeMark( i.value()->line, KTextEditor::MarkInterface::markType01 ); - - // just to be sure ;) - // dominik: the following line can be deleted afaics, as Document::removeMark emits this signal. - marksChanged (); -} - -void KateBookmarks::insertBookmarks( QMenu& menu ) -{ - int line = m_view->cursorPosition().line(); - const QRegExp re("&(?!&)"); - int idx( -1 ); - KTextEditor::Mark *next = 0; - KTextEditor::Mark *prev = 0; - - const QHash &m = m_view->doc()->marks(); - QVector sortArray( m.size() ); - - if ( m.isEmpty() ) - return; - - int i = 0; - QAction* firstNewAction = menu.addSeparator(); - for (QHash::const_iterator it = m.constBegin(); it != m.constEnd(); ++it, ++i) - { - if( it.value()->type & KTextEditor::MarkInterface::markType01 ) - { - QString bText = menu.fontMetrics().elidedText - ( m_view->doc()->line( it.value()->line ), - Qt::ElideRight, - menu.fontMetrics().maxWidth() * 32 ); - bText.replace(re, "&&"); // kill undesired accellerators! - bText.replace('\t', ' '); // kill tabs, as they are interpreted as shortcuts - - QAction *before=0; - if ( m_sorting == Position ) - { - sortArray[i] = it.value()->line; - ssort( sortArray, i ); - - for (int i=0; i < sortArray.size(); ++i) - { - if ((int)sortArray[i] == it.value()->line) - { - idx = i + 3; - if (idx>=menu.actions().size()) before=0; - else before=menu.actions()[idx]; - break; - } - } - } - - if (before) { - QAction *a=new QAction(QString("%1 - \"%2\"").arg( it.value()->line+1 ).arg( bText ),&menu); - menu.insertAction(before,a); - connect(a,SIGNAL(activated()),this,SLOT(gotoLine())); - a->setData(it.value()->line); - if (!firstNewAction) firstNewAction = a; - - } else { - QAction* a = menu.addAction(QString("%1 - \"%2\"").arg( it.value()->line+1 ).arg( bText ), this, SLOT(gotoLine())); - a->setData(it.value()->line); - } - - if ( it.value()->line < line ) - { - if ( ! prev || prev->line < it.value()->line ) - prev = (*it); - } - - else if ( it.value()->line > line ) - { - if ( ! next || next->line > it.value()->line ) - next = it.value(); - } - } - } - - if ( next ) - { - m_goNext->setText( i18n("&Next: %1 - \"%2\"", next->line + 1 , - KStringHandler::rsqueeze( m_view->doc()->line( next->line ), 24 ) ) ); - menu.insertAction(firstNewAction, m_goNext); - firstNewAction = m_goNext; - } - if ( prev ) - { - m_goPrevious->setText( i18n("&Previous: %1 - \"%2\"", prev->line + 1 , - KStringHandler::rsqueeze( m_view->doc()->line( prev->line ), 24 ) ) ); - menu.insertAction(firstNewAction, m_goPrevious); - firstNewAction = m_goPrevious; - } - - if ( next || prev ) - menu.insertSeparator(firstNewAction); -} - -void KateBookmarks::gotoLine() -{ - if (!sender()) return; - gotoLine(((QAction*)(sender()))->data().toInt()); -} - -void KateBookmarks::gotoLine (int line) -{ - m_view->setCursorPosition(KTextEditor::Cursor(line, 0)); -} - -void KateBookmarks::bookmarkMenuAboutToShow() -{ - m_bookmarksMenu->clear(); - m_bookmarkToggle->setChecked( m_view->doc()->mark( m_view->cursorPosition().line() ) - & KTextEditor::MarkInterface::markType01 ); - m_bookmarksMenu->addAction(m_bookmarkToggle); - m_bookmarksMenu->addAction(m_bookmarkClear); - - m_goNext->setText( i18n("Next Bookmark") ); - m_goPrevious->setText( i18n("Previous Bookmark") ); - - insertBookmarks(*m_bookmarksMenu); -} - -void KateBookmarks::goNext() -{ - const QHash &m = m_view->doc()->marks(); - if (m.isEmpty()) - return; - - int line = m_view->cursorPosition().line(); - int found = -1; - - for (QHash::const_iterator it = m.constBegin(); it != m.constEnd(); ++it) - { - if ( (it.value()->line > line) && ((found == -1) || (found > it.value()->line)) ) - found = it.value()->line; - } - - if (found != -1) - gotoLine ( found ); -} - -void KateBookmarks::goPrevious() -{ - const QHash &m = m_view->doc()->marks(); - if (m.isEmpty()) - return; - - int line = m_view->cursorPosition().line(); - int found = -1; - - for (QHash::const_iterator it = m.constBegin(); it != m.constEnd(); ++it) - { - if ((it.value()->line < line) && ((found == -1) || (found < it.value()->line))) - found = it.value()->line; - } - - if (found != -1) - gotoLine ( found ); -} - -void KateBookmarks::marksChanged () -{ - if (m_bookmarkClear) - m_bookmarkClear->setEnabled( !m_view->doc()->marks().isEmpty() ); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katebookmarks.h b/part/utils/katebookmarks.h deleted file mode 100644 index c833190..0000000 --- a/part/utils/katebookmarks.h +++ /dev/null @@ -1,81 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002, 2003 Anders Lund - Copyright (C) 2002 John Firebaugh - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_BOOKMARKS_H__ -#define __KATE_BOOKMARKS_H__ - -#include - -class KateView; - -namespace KTextEditor { class Mark; class View; } - -class KAction; -class KToggleAction; -class KActionCollection; -class QMenu; - -class KateBookmarks : public QObject -{ - Q_OBJECT - - public: - enum Sorting { Position, Creation }; - explicit KateBookmarks( KateView* parent, Sorting sort=Position ); - virtual ~KateBookmarks(); - - void createActions( KActionCollection* ); - - KateBookmarks::Sorting sorting() { return m_sorting; } - void setSorting( Sorting s ) { m_sorting = s; } - - protected: - void insertBookmarks( QMenu& menu); - - private Q_SLOTS: - void toggleBookmark(); - void clearBookmarks(); - - void gotoLine(); - void gotoLine (int line); - - void bookmarkMenuAboutToShow(); - - void goNext(); - void goPrevious(); - - void marksChanged (); - - private: - KateView* m_view; - KToggleAction* m_bookmarkToggle; - KAction* m_bookmarkClear; - KAction* m_goNext; - KAction* m_goPrevious; - - Sorting m_sorting; - QMenu* m_bookmarksMenu; - - uint _tries; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; -// vim: noet ts=2 diff --git a/part/utils/katecmd.cpp b/part/utils/katecmd.cpp deleted file mode 100644 index 136a564..0000000 --- a/part/utils/katecmd.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecmd.h" -#include "kateglobal.h" - -#include - -//BEGIN KateCmd -#define CMD_HIST_LENGTH 256 - -KateCmd::KateCmd () -{ - m_cmdCompletion.addItem("help"); -} - -KateCmd::~KateCmd () -{ -} - -bool KateCmd::registerCommand (KTextEditor::Command *cmd) -{ - QStringList l = cmd->cmds (); - - for (int z=0; z::const_iterator i = m_dict.constBegin(); - while (i != m_dict.constEnd()) { - if (i.value()==cmd) l << i.key(); - ++i; - } - - for ( QStringList::Iterator it1 = l.begin(); it1 != l.end(); ++it1 ) { - m_dict.remove(*it1); - m_cmdCompletion.removeItem(*it1); - //kDebug(13050)<<"Removed command:"<<*it1; - } - - return true; -} - -KTextEditor::Command *KateCmd::queryCommand (const QString &cmd) const -{ - // a command can be named ".*[\w\-]+" with the constrain that it must - // contain at least one letter. - int f = 0; - bool b = false; - for ( ; f < cmd.length(); f++ ) - { - if ( cmd[f].isLetter() ) - b = true; - if ( b && ( ! cmd[f].isLetterOrNumber() && cmd[f] != '-' && cmd[f] != '_' ) ) - break; - } - return m_dict.value(cmd.left(f)); -} - -QList KateCmd::commands() const -{ - return m_dict.values(); -} - -QStringList KateCmd::commandList () const -{ - return m_cmds; -} - -KateCmd *KateCmd::self () -{ - return KateGlobal::self()->cmdManager (); -} - -void KateCmd::appendHistory( const QString &cmd ) -{ - if (!m_history.isEmpty()) //this line should be backported to 3.x - if ( m_history.last() == cmd ) - return; - - if ( m_history.count() == CMD_HIST_LENGTH ) - m_history.removeFirst(); - - m_history.append( cmd ); -} - -const QString KateCmd::fromHistory( int index ) const -{ - if ( index < 0 || index > m_history.count() - 1 ) - return QString(); - return m_history[ index ]; -} - -KCompletion* KateCmd::commandCompletionObject() -{ - return &m_cmdCompletion; -} -//END KateCmd - -//BEGIN KateCmdShellCompletion -/* - A lot of the code in the below class is copied from - kdelibs/kio/kio/kshellcompletion.cpp - Copyright (C) 2000 David Smith - Copyright (C) 2004 Anders Lund -*/ -KateCmdShellCompletion::KateCmdShellCompletion() - : KCompletion() -{ - m_word_break_char = ' '; - m_quote_char1 = '\"'; - m_quote_char2 = '\''; - m_escape_char = '\\'; -} - -QString KateCmdShellCompletion::makeCompletion( const QString &text ) -{ - // Split text at the last unquoted space - // - splitText(text, m_text_start, m_text_compl); - - // Make completion on the last part of text - // - return KCompletion::makeCompletion( m_text_compl ); -} - -void KateCmdShellCompletion::postProcessMatch( QString *match ) const -{ - if ( match->isNull() ) - return; - - match->prepend( m_text_start ); -} - -void KateCmdShellCompletion::postProcessMatches( QStringList *matches ) const -{ - for ( QStringList::Iterator it = matches->begin(); - it != matches->end(); it++ ) - if ( !(*it).isNull() ) - (*it).prepend( m_text_start ); -} - -void KateCmdShellCompletion::postProcessMatches( KCompletionMatches *matches ) const -{ - for ( KCompletionMatches::Iterator it = matches->begin(); - it != matches->end(); it++ ) - if ( !(*it).value().isNull() ) - (*it).value().prepend( m_text_start ); -} - -void KateCmdShellCompletion::splitText(const QString &text, QString &text_start, - QString &text_compl) const -{ - bool in_quote = false; - bool escaped = false; - QChar p_last_quote_char; - int last_unquoted_space = -1; - int end_space_len = 0; - - for (int pos = 0; pos < text.length(); pos++) { - - end_space_len = 0; - - if ( escaped ) { - escaped = false; - } - else if ( in_quote && text[pos] == p_last_quote_char ) { - in_quote = false; - } - else if ( !in_quote && text[pos] == m_quote_char1 ) { - p_last_quote_char = m_quote_char1; - in_quote = true; - } - else if ( !in_quote && text[pos] == m_quote_char2 ) { - p_last_quote_char = m_quote_char2; - in_quote = true; - } - else if ( text[pos] == m_escape_char ) { - escaped = true; - } - else if ( !in_quote && text[pos] == m_word_break_char ) { - - end_space_len = 1; - - while ( pos+1 < text.length() && text[pos+1] == m_word_break_char ) { - end_space_len++; - pos++; - } - - if ( pos+1 == text.length() ) - break; - - last_unquoted_space = pos; - } - } - - text_start = text.left( last_unquoted_space + 1 ); - - // the last part without trailing blanks - text_compl = text.mid( last_unquoted_space + 1 ); -} - -//END KateCmdShellCompletion - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katecmd.h b/part/utils/katecmd.h deleted file mode 100644 index 4fb09f1..0000000 --- a/part/utils/katecmd.h +++ /dev/null @@ -1,107 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_CMD_H -#define _KATE_CMD_H - -#include "katepartprivate_export.h" - -#include - -#include - -#include -#include - -class KATEPART_TESTS_EXPORT KateCmd -{ - public: - KateCmd (); - ~KateCmd (); - - static KateCmd *self (); - - bool registerCommand (KTextEditor::Command *cmd); - bool unregisterCommand (KTextEditor::Command *cmd); - KTextEditor::Command *queryCommand (const QString &cmd) const; - QList commands() const; - QStringList commandList() const; - - QStringList cmds (); - void appendHistory( const QString &cmd ); - const QString fromHistory( int i ) const; - uint historyLength() const { return m_history.count(); } - - KCompletion* commandCompletionObject(); - - private: - QHash m_dict; - QStringList m_cmds; - QStringList m_history; - KCompletion m_cmdCompletion; // shared completion object for all KateCmdLineEdits in each KTE::View -}; - -/** - * A KCompletion object that completes last ?unquoted? word in the string - * passed. Do not mistake "shell" for anything related to quoting, this - * simply mimics shell tab completion by completing the last word in the - * provided text. - */ -class KateCmdShellCompletion : public KCompletion -{ - public: - KateCmdShellCompletion(); - - /** - * Finds completions to the given text. - * The first match is returned and emitted in the signal match(). - * @param text the text to complete - * @return the first match, or QString() if not found - */ - QString makeCompletion(const QString &text); - - protected: - // Called by KCompletion - void postProcessMatch( QString *match ) const; - void postProcessMatches( QStringList *matches ) const; - void postProcessMatches( KCompletionMatches *matches ) const; - - private: - /** - * Split text at the last unquoted space - * - * @param text_start will be set to the text at the left, including the space - * @param text_compl Will be set to the text at the right. This is the text to complete. - */ - void splitText( const QString &text, QString &text_start, QString &text_compl ) const; - - QChar m_word_break_char; - QChar m_quote_char1; - QChar m_quote_char2; - QChar m_escape_char; - - QString m_text_start; - QString m_text_compl; - -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katecmds.cpp b/part/utils/katecmds.cpp deleted file mode 100644 index f92d2a4..0000000 --- a/part/utils/katecmds.cpp +++ /dev/null @@ -1,936 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003-2005 Anders Lund - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Charles Samuels - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katecmds.h" - -#include "katedocument.h" -#include "kateview.h" -#include "kateconfig.h" -#include "kateautoindent.h" -#include "katetextline.h" -#include "katesyntaxmanager.h" -#include "kateglobal.h" -#include "kateviglobal.h" -#include "katerenderer.h" -#include "katecmd.h" - -#include -#include -#include -#include - -#include - -//BEGIN CoreCommands -// this returns wheather the string s could be converted to -// a bool value, one of on|off|1|0|true|false. the argument val is -// set to the extracted value in case of success -static bool getBoolArg( const QString &t, bool *val ) -{ - bool res( false ); - QString s = t.toLower(); - res = (s == "on" || s == "1" || s == "true"); - if ( res ) - { - *val = true; - return true; - } - res = (s == "off" || s == "0" || s == "false"); - if ( res ) - { - *val = false; - return true; - } - return false; -} - -const QStringList &KateCommands::CoreCommands::cmds() -{ - static QStringList l; - - if (l.isEmpty()) - l << "indent" << "unindent" << "cleanindent" - << "comment" << "uncomment" << "goto" << "kill-line" - << "set-tab-width" << "set-replace-tabs" << "set-show-tabs" - << "set-remove-trailing-space" - << "set-indent-width" - << "set-indent-mode" << "set-auto-indent" - << "set-line-numbers" << "set-folding-markers" << "set-icon-border" - << "set-wrap-cursor" - << "set-word-wrap" << "set-word-wrap-column" - << "set-replace-tabs-save" << "set-remove-trailing-space-save" - << "set-highlight" << "set-mode" << "set-show-indent" - << "print"; - - return l; -} - -bool KateCommands::CoreCommands::exec(KTextEditor::View *view, - const QString &_cmd, - QString &errorMsg) -{ - return exec( view, _cmd, errorMsg, KTextEditor::Range::invalid() ); -} - -bool KateCommands::CoreCommands::exec(KTextEditor::View *view, - const QString &_cmd, - QString &errorMsg, - const KTextEditor::Range& range) -{ -#define KCC_ERR(s) { errorMsg=s; return false; } - // cast it hardcore, we know that it is really a kateview :) - KateView *v = (KateView*) view; - - if ( ! v ) - KCC_ERR( i18n("Could not access view") ); - - //create a list of args - QStringList args(_cmd.split( QRegExp("\\s+"), QString::SkipEmptyParts)) ; - QString cmd ( args.takeFirst() ); - - // ALL commands that takes no arguments. - if ( cmd == "indent" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->indent( KTextEditor::Range(line, 0, line, 0), 1 ); - } - v->doc()->editEnd(); - } else { - v->indent(); - } - return true; - } - else if ( cmd == "unindent" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->indent( KTextEditor::Range(line, 0, line, 0), -1 ); - } - v->doc()->editEnd(); - } else { - v->unIndent(); - } - return true; - } - else if ( cmd == "cleanindent" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->indent( KTextEditor::Range(line, 0, line, 0), 0 ); - } - v->doc()->editEnd(); - } else { - v->cleanIndent(); - } - return true; - } - else if ( cmd == "comment" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->comment( v, line, 0, 1 ); - } - v->doc()->editEnd(); - } else { - v->comment(); - } - return true; - } - else if ( cmd == "uncomment" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->comment( v, line, 0, -1 ); - } - v->doc()->editEnd(); - } else { - v->uncomment(); - } - return true; - } - else if ( cmd == "kill-line" ) - { - if ( range.isValid() ) { - v->doc()->editStart(); - for ( int line = range.start().line(); line <= range.end().line(); line++ ) { - v->doc()->removeLine( range.start().line() ); - } - v->doc()->editEnd(); - } else { - v->killLine(); - } - return true; - } - else if ( cmd == "print" ) - { - v->doc()->printDialog(); - return true; - } - - // ALL commands that take a string argument - else if ( cmd == "set-indent-mode" || - cmd == "set-highlight" || - cmd == "set-mode" ) - { - // need at least one item, otherwise args.first() crashes - if ( ! args.count() ) - KCC_ERR( i18n("Missing argument. Usage: %1 ", cmd ) ); - - if ( cmd == "set-indent-mode" ) - { - v->doc()->config()->setIndentationMode( args.first() ); - return true; - } - else if ( cmd == "set-highlight" ) - { - if ( v->doc()->setHighlightingMode( args.first()) ) - { - ((KateDocument*)v->doc())->setDontChangeHlOnSave (); - return true; - } - - KCC_ERR( i18n("No such highlighting '%1'", args.first() ) ); - } - else if ( cmd == "set-mode" ) - { - if ( v->doc()->setMode( args.first()) ) - return true; - - KCC_ERR( i18n("No such mode '%1'", args.first() ) ); - } - } - // ALL commands that takes exactly one integer argument. - else if ( cmd == "set-tab-width" || - cmd == "set-indent-width" || - cmd == "set-word-wrap-column" || - cmd == "goto" ) - { - // find a integer value > 0 - if ( ! args.count() ) - KCC_ERR( i18n("Missing argument. Usage: %1 ", cmd ) ); - bool ok; - int val ( args.first().toInt( &ok, 10 ) ); // use base 10 even if the string starts with '0' - if ( !ok ) - KCC_ERR( i18n("Failed to convert argument '%1' to integer.", - args.first() ) ); - - if ( cmd == "set-tab-width" ) - { - if ( val < 1 ) - KCC_ERR( i18n("Width must be at least 1.") ); - v->doc()->config()->setTabWidth( val ); - } - else if ( cmd == "set-indent-width" ) - { - if ( val < 1 ) - KCC_ERR( i18n("Width must be at least 1.") ); - v->doc()->config()->setIndentationWidth( val ); - } - else if ( cmd == "set-word-wrap-column" ) - { - if ( val < 2 ) - KCC_ERR( i18n("Column must be at least 1.") ); - v->doc()->setWordWrapAt( val ); - } - else if ( cmd == "goto" ) - { - if ( args.first().at(0) == '-' || args.first().at(0) == '+' ) { - // if the number starts with a minus or plus sign, add/subract the number - val = v->cursorPosition().line() + val; - } else { - val--; // convert given line number to the internal representation of line numbers - } - - // constrain cursor to the range [0, number of lines] - if ( val < 0 ) { - val = 0; - } else if ( val > v->doc()->lines()-1 ) { - val = v->doc()->lines()-1; - } - - v->setCursorPosition( KTextEditor::Cursor( val, 0 ) ); - return true; - } - return true; - } - - // ALL commands that takes 1 boolean argument. - else if ( cmd == "set-icon-border" || - cmd == "set-folding-markers" || - cmd == "set-line-numbers" || - cmd == "set-replace-tabs" || - cmd == "set-remove-trailing-space" || - cmd == "set-show-tabs" || - cmd == "set-word-wrap" || - cmd == "set-wrap-cursor" || - cmd == "set-replace-tabs-save" || - cmd == "set-remove-trailing-space-save" || - cmd == "set-show-indent" ) - { - if ( ! args.count() ) - KCC_ERR( i18n("Usage: %1 on|off|1|0|true|false", cmd ) ); - bool enable = false; - KateDocumentConfig * const config = v->doc()->config(); - if ( getBoolArg( args.first(), &enable ) ) - { - if ( cmd == "set-icon-border" ) - v->setIconBorder( enable ); - else if (cmd == "set-folding-markers") - v->setFoldingMarkersOn( enable ); - else if ( cmd == "set-line-numbers" ) - v->setLineNumbersOn( enable ); - else if ( cmd == "set-show-indent" ) - v->renderer()->setShowIndentLines( enable ); - else if ( cmd == "set-replace-tabs" ) - config->setReplaceTabsDyn( enable ); - else if ( cmd == "set-remove-trailing-space" ) - config->setRemoveTrailingDyn( enable ); - else if ( cmd == "set-show-tabs" ) - config->setShowTabs( enable ); - else if ( cmd == "set-show-trailing-spaces" ) - config->setShowSpaces( enable ); - else if ( cmd == "set-word-wrap" ) - v->doc()->setWordWrap( enable ); - else if ( cmd == "set-remove-trailing-space-save" ) - config->setRemoveSpaces( enable ); - else if ( cmd == "set-wrap-cursor" ) - config->setWrapCursor( enable ); - - return true; - } - else - KCC_ERR( i18n("Bad argument '%1'. Usage: %2 on|off|1|0|true|false", - args.first() , cmd ) ); - } - - // unlikely.. - KCC_ERR( i18n("Unknown command '%1'", cmd) ); -} - -bool KateCommands::CoreCommands::supportsRange(const QString &range) -{ - static QStringList l; - - if (l.isEmpty()) - l << "indent" << "unindent" << "cleanindent" - << "comment" << "uncomment" << "kill-line"; - - return l.contains(range); -} - -KCompletion *KateCommands::CoreCommands::completionObject( KTextEditor::View *view, const QString &cmd ) -{ - Q_UNUSED(view) - - if ( cmd == "set-highlight" ) - { - QStringList l; - for ( int i = 0; i < KateHlManager::self()->highlights(); i++ ) - l << KateHlManager::self()->hlName (i); - - KateCmdShellCompletion *co = new KateCmdShellCompletion(); - co->setItems( l ); - co->setIgnoreCase( true ); - return co; - } - return 0L; -} -//END CoreCommands - -// BEGIN ViCommands -const QStringList &KateCommands::ViCommands::cmds() -{ - static QStringList l; - - if (l.isEmpty()) - l << "nnoremap" << "nn"; - - return l; -} - -bool KateCommands::ViCommands::exec(KTextEditor::View *view, - const QString &_cmd, - QString &msg) -{ - return exec( view, _cmd, msg, KTextEditor::Range::invalid() ); -} - -bool KateCommands::ViCommands::exec(KTextEditor::View *view, - const QString &_cmd, - QString &msg, - const KTextEditor::Range& range) -{ - Q_UNUSED(range) - // cast it hardcore, we know that it is really a kateview :) - KateView *v = (KateView*) view; - - if ( !v ) { - msg = i18n("Could not access view"); - return false; - } - - //create a list of args - QStringList args(_cmd.split( QRegExp("\\s+"), QString::SkipEmptyParts)) ; - QString cmd ( args.takeFirst() ); - - // ALL commands that takes no arguments. - if ( cmd == "nnoremap" || cmd == "nn" ) - { - if ( args.count() == 1 ) { - msg = KateGlobal::self()->viInputModeGlobal()->getMapping( NormalMode, args.at( 0 ), true ); - if ( msg.isEmpty() ) { - msg = i18n( "No mapping found for \"%1\"", args.at(0) ); - return false; - } else { - msg = i18n( "\"%1\" is mapped to \"%2\"", args.at( 0 ), msg ); - } - } else if ( args.count() == 2 ) { - KateGlobal::self()->viInputModeGlobal()->addMapping( NormalMode, args.at( 0 ), args.at( 1 ) ); - } else { - msg = i18n("Missing argument(s). Usage: %1 []", cmd ); - return false; - } - - return true; - } - - // should not happen :) - msg = i18n("Unknown command '%1'", cmd); - return false; -} - -bool KateCommands::ViCommands::supportsRange(const QString &range) -{ - Q_UNUSED(range) - return false; // no commands support a range yet -} - -KCompletion *KateCommands::ViCommands::completionObject( KTextEditor::View *view, const QString &cmd ) -{ - Q_UNUSED(view) - - KateView *v = (KateView*) view; - - if ( v && ( cmd == "nn" || cmd == "nnoremap" ) ) - { - QStringList l = KateGlobal::self()->viInputModeGlobal()->getMappings( NormalMode ); - - KateCmdShellCompletion *co = new KateCmdShellCompletion(); - co->setItems( l ); - co->setIgnoreCase( false ); - return co; - } - return 0L; -} -//END ViCommands - -// BEGIN AppCommands -KateCommands::AppCommands::AppCommands() - : KTextEditor::Command() -{ - re_write.setPattern("w?"); - //re_write.setPattern("w(a)?"); - //re_quit.setPattern("(w)?q?(a)?"); - //re_exit.setPattern("x(a)?"); - //re_changeBuffer.setPattern("b(n|p)"); - //re_edit.setPattern("e(dit)?"); - //re_new.setPattern("(v)?new"); -} - -const QStringList& KateCommands::AppCommands::cmds() -{ - static QStringList l; - - if (l.empty()) { - //l << "q" << "qa" << "w" << "wq" << "wa" << "wqa" << "x" << "xa" - //<< "bn" << "bp" << "new" << "vnew" << "e" << "edit" << "enew"; - l << "w"; - } - - return l; -} - -bool KateCommands::AppCommands::exec(KTextEditor::View *view, - const QString &cmd, QString &msg ) -{ - QStringList args(cmd.split( QRegExp("\\s+"), QString::SkipEmptyParts)) ; - QString command( args.takeFirst() ); - - if (re_write.exactMatch(command)) { // w, wa -/* if (!re_write.cap(1).isEmpty()) { // [a]ll - view->document()->saveAll(); - msg = i18n("All documents written to disk"); - } else { // w*/ - // Save file - view->document()->documentSave(); - msg = i18n("Document written to disk"); - //} - } - /*else if (re_quit.exactMatch(command)) { // q qa wq wqa - if (!re_quit.cap(2).isEmpty()) { // a[ll] qa wqa - if (!re_quit.cap(1).isEmpty()) { // [w]rite wqa - view->document()->saveAll(); - } - view->document()->closeAll(); - } else { // q wq - if (!re_quit.cap(1).isEmpty() && view->document()->isModified()) { // [w]rite wq - view->document()->documentSave(); - } - view->document()->closeDocument(); - } - } else if (re_exit.exactMatch(command)) { // x xa - if (!re_exit.cap(1).isEmpty()) { // a[ll] xa - view->document()->saveAll(); - view->document()->closeAll(); - } else { // x - if (view->document()->isModified()) { - view->document()->documentSave(); - } - view->document()->closeDocument(); - } - } - else if (re_changeBuffer.exactMatch(command)) { - if (re_changeBuffer.cap(1) == "n") { // next document - view->document()->switchToNextDocument(); - } - else { // previous document - view->document()->switchToPreviousDocument(); - } - } - else if (re_edit.exactMatch(command)) { - view->document()->documentReload(); - } - else if (re_new.exactMatch(command)) { - if (re_new.cap(1) == "v") { // vertical split - view->document()->splitViewSpaceVert(); - } else { // horizontal split - view->document()->splitViewSpaceHoriz(); - } - view->document()->newDocument(); - } - else if (command == "enew") { - view->document()->newDocument(); - }*/ - return true; -} - -bool KateCommands::AppCommands::help(KTextEditor::View *view, const QString &cmd, QString &msg) -{ - Q_UNUSED(view); - - if (re_write.exactMatch(cmd)) { - msg = "

w/wa — write document(s) to disk

" - "

Usage: w[a]

" - "

Writes the current document(s) to disk. " - "It can be called in two ways:
" - " w — writes the current document to disk
" - " wa — writes all document to disk.

" - "

If no file name is associated with the document, " - "a file dialog will be shown.

"; - return true; - } - /*else if (re_quit.exactMatch(cmd)) { - msg = "

q/qa/wq/wqa — [write and] quit

" - "

Usage: [w]q[a]

" - "

Quits the application. If w is prepended, it also writes" - " the document(s) to disk. This command " - "can be called in several ways:
" - " q — closes the current view..
" - " qa — closes all view, effectively quitting the application.
" - " wq — writes the current document to disk and closes its view.
" - " wqa — writes all document to disk and quits.

" - "

In all cases, if the view being closed is the last view, the application quits. " - "If no file name is associated with the document and it should be written to disk, " - "a file dialog will be shown.

"; - return true; - } - else if (re_exit.exactMatch(cmd)) { - msg = "

x/xa — write and quit

" - "

Usage: x[a]

" - "

Saves document(s) and quits (exits). This command " - "can be called in two ways:
" - " x — closes the current view..
" - " xa — closes all view, effectively quitting the application.

" - "

In all cases, if the view being closed is the last view, the application quits. " - "If no file name is associated with the document and it should be written to disk, " - "a file dialog will be shown.

" - "

Unlike the 'w' commands, this command only writes the doucment if it is modified." - "

"; - return true; - } - else if (re_changeBuffer.exactMatch(cmd)) { - msg = "

bp/bn — switch no previous/next document

" - "

Usage: bp/bn

" - "

Goes to previous or next document (\"buffer\"). The two" - " commands are:
" - " bp — goes to the document before the current one in the document" - " list.
" - " bn — goes to the document after the current one in the document" - " list.
" - "

Both commands wrap around, i.e., if you go past the last document you and up" - " at the first and vice versa.

"; - return true; - } - else if (re_new.exactMatch(cmd)) { - msg = "

[v]new — split view and create new document

" - "

Usage: [v]new

" - "

Splits the current view and opens a new document in the new view." - " This command can be called in two ways:
" - " new — splits the view horizontally and opens a new document.
" - " vnew — splits the view vertically and opens a new document.
" - "

"; - return true; - } - else if (re_edit.exactMatch(cmd)) { - msg = "

e[dit] — reload current document

" - "

Usage: e[dit]

" - "

Starts editing the current document again. This is useful to re-edit" - " the current file, when it has been changed by another program.

"; - return true; - }*/ - - return false; -} -//END AppCommands - -//BEGIN SedReplace -static void replace(QString &s, const QString &needle, const QString &with) -{ - int pos=0; - while (1) - { - pos=s.indexOf(needle, pos); - if (pos==-1) break; - s.replace(pos, needle.length(), with); - pos+=with.length(); - } - -} - -static int backslashString(const QString &haystack, const QString &needle, int index) -{ - int len=haystack.length(); - int searchlen=needle.length(); - bool evenCount=true; - while (indexkateTextLine( line ); - if ( ! ln || ! ln->length() ) return 0; - - // HANDLING "\n"s in PATTERN - // * Create a list of patterns, splitting PATTERN on (unescaped) "\n" - // * insert $s and ^s to match line ends/beginnings - // * When matching patterhs after the first one, replace \N with the captured - // text. - // * If all patterns in the list match sequentiel lines, there is a match, so - // * remove line/start to line + patterns.count()-1/patterns.last.length - // * handle capatures by putting them in one list. - // * the existing insertion is fine, including the line calculation. - - QStringList patterns(find.split( QRegExp("(^\\\\n|(?![^\\\\])\\\\n)"), QString::KeepEmptyParts)); - if ( patterns.count() > 1 ) - { - for ( int i = 0; i < patterns.count(); i++ ) - { - if ( i < patterns.count() - 1 ) - patterns[i].append("$"); - if ( i ) - patterns[i].prepend("^"); - - kDebug(13025)<<"patterns["<string(), startcol)) >= 0 ) - { - const int len = matcher.matchedLength(); - - if ( endcol >= 0 && startcol + len > endcol ) - break; - - matches++; - - - QString rep=repOld; - - // now set the backreferences in the replacement - const QStringList backrefs=matcher.capturedTexts(); - int refnum=1; - - QStringList::ConstIterator i = backrefs.begin(); - ++i; - - for (; i!=backrefs.end(); ++i) - { - // I need to match "\\" or "", but not "\" - QString number=QString::number(refnum); - - int index=0; - while (index!=-1) - { - index=backslashString(rep, number, index); - if (index>=0) - { - rep.replace(index, 2, *i); - index+=(*i).length(); - } - } - - refnum++; - } - - replace(rep, "\\\\", "\\"); - replace(rep, "\\" + delim, delim); - - doc->removeText( KTextEditor::Range (line, startcol, line, startcol + len) ); - doc->insertText( KTextEditor::Cursor (line, startcol), rep ); - - // TODO if replace contains \n, - // change the line number and - // check for text that needs be searched behind the last inserted newline. - int lns = rep.count(QChar::fromLatin1('\n')); - if ( lns > 0 ) - { - line += lns; - - if ( doc->lineLength( line ) > 0 && ( endcol < 0 || endcol >= startcol + len ) ) - { - // if ( endcol >= startcol + len ) - endcol -= (startcol + len); - uint sc = rep.length() - rep.lastIndexOf('\n') - 1; - matches += sedMagic( doc, line, find, repOld, delim, noCase, repeat, sc, endcol ); - } - } - - if (!repeat) break; - startcol+=rep.length(); - - // sanity check -- avoid infinite loops eg with %s,.*,,g ;) - int ll = ln->length(); - if ( ! ll || startcol > ll ) - break; - } - - return matches; -} - -bool KateCommands::SedReplace::exec (KTextEditor::View *view, const QString &cmd, QString &msg) -{ - return exec(view, cmd, msg, KTextEditor::Range::invalid()); -} - -bool KateCommands::SedReplace::exec (class KTextEditor::View *view, const QString &cmd, - QString &msg, const KTextEditor::Range &r) -{ - kDebug(13025)<<"SedReplace::execCmd( "<doc(); - if ( ! doc ) return false; - - doc->editStart(); - - int replacementsDone = 0; - int linesTouched = 0; - int linesAdded = 0; - - if (r.isValid()) { // given range - for (int line = r.start().line(); line <= r.end().line()+linesAdded; line++) { - int temp = replacementsDone; - int r = sedMagic( doc, line, find, replace, d, !noCase, repeat ); - replacementsDone += r; - - // if we replaced the text with n newlines, we have n new lines to look at - if (replace.contains('\n') ) { - linesAdded += r * replace.count('\n'); - } - - if (replacementsDone > temp) { - linesTouched++; - } - } - } else { // current line - int line= view->cursorPosition().line(); - replacementsDone += sedMagic(doc, line, find, replace, d, !noCase, repeat); - if (replacementsDone > 0) { - linesTouched = 1; - } - } - - msg = i18ncp("%2 is the translation of the next message", - "1 replacement done on %2", "%1 replacements done on %2", replacementsDone, - i18ncp("substituted into the previous message", - "1 line", "%1 lines", linesTouched)); - - doc->editEnd(); - - return true; -} - -//END SedReplace - -//BEGIN Character -bool KateCommands::Character::exec (KTextEditor::View *view, const QString &_cmd, QString &) -{ - QString cmd = _cmd; - - // hex, octal, base 9+1 - QRegExp num("^char *(0?x[0-9A-Fa-f]{1,4}|0[0-7]{1,6}|[0-9]{1,5})$"); - if (num.indexIn(cmd)==-1) return false; - - cmd=num.cap(1); - - // identify the base - - unsigned short int number=0; - int base=10; - if (cmd[0]=='x' || cmd.startsWith(QLatin1String("0x"))) - { - cmd.remove(QRegExp("^0?x")); - base=16; - } - else if (cmd[0]=='0') - base=8; - bool ok; - number=cmd.toUShort(&ok, base); - if (!ok || number==0) return false; - if (number<=255) - { - char buf[2]; - buf[0]=(char)number; - buf[1]=0; - - view->document()->insertText(view->cursorPosition(), QString(buf)); - } - else - { // do the unicode thing - QChar c(number); - - view->document()->insertText(view->cursorPosition(), QString(&c, 1)); - } - - return true; -} - -//END Character - -//BEGIN Date -bool KateCommands::Date::exec (KTextEditor::View *view, const QString &cmd, QString &) -{ - if (!cmd.startsWith(QLatin1String("date"))) - return false; - - if (QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5)).length() > 0) - view->document()->insertText(view->cursorPosition(), QDateTime::currentDateTime().toString(cmd.mid(5, cmd.length()-5))); - else - view->document()->insertText(view->cursorPosition(), QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); - - return true; -} - -//END Date - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katecmds.h b/part/utils/katecmds.h deleted file mode 100644 index fc61941..0000000 --- a/part/utils/katecmds.h +++ /dev/null @@ -1,299 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2003-2005 Anders Lund - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Charles Samuels - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef __KATE_CMDS_H__ -#define __KATE_CMDS_H__ - -#include - -#include - -class KateDocument; -class KCompletion; - -/** - * The KateCommands namespace collects subclasses of KTextEditor::Command - * for specific use in kate. - */ -namespace KateCommands -{ - -/** - * This KTextEditor::Command provides access to a lot of the core functionality - * of kate part, settings, utilities, navigation etc. - * it needs to get a kateview pointer, it will cast the kate::view pointer - * hard to kateview - */ -class CoreCommands : public KTextEditor::Command, public KTextEditor::CommandExtension, - public KTextEditor::RangeCommand -{ - public: - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @return success - */ - bool exec( class KTextEditor::View *view, const QString &cmd, QString &errorMsg ); - - /** - * execute command on given range - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @param rangeStart first line in range - * @param rangeEnd last line in range - * @return success - */ - bool exec( class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)); - - bool supportsRange(const QString &range); - - /** This command does not have help. @see KTextEditor::Command::help */ - bool help( class KTextEditor::View *, const QString &, QString & ) {return false;} - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds(); - - /** - * override completionObject from interfaces/document.h . - */ - KCompletion *completionObject( KTextEditor::View *, const QString & ); - - virtual void flagCompletions( QStringList& ) {} - virtual bool wantsToProcessText( const QString & ) { return false; } - virtual void processText( KTextEditor::View *, const QString & ) {} -}; - -/** - * This KTextEditor::Command provides vi 'ex' commands - */ -class ViCommands : public KTextEditor::Command, public KTextEditor::CommandExtension, - public KTextEditor::RangeCommand -{ - public: - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param msg message returned from running the command - * @return success - */ - bool exec( class KTextEditor::View *view, const QString &cmd, QString &msg ); - - /** - * execute command on given range - * @param view view to use for execution - * @param cmd cmd string - * @param msg message returned from running the command - * @param rangeStart first line in range - * @param rangeEnd last line in range - * @return success - */ - bool exec( class KTextEditor::View *view, const QString &cmd, QString &msg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)); - - bool supportsRange(const QString &range); - - /** This command does not have help. @see KTextEditor::Command::help */ - bool help( class KTextEditor::View *, const QString &, QString & ) {return false;} - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds(); - - /** - * override completionObject from interfaces/document.h . - */ - KCompletion *completionObject( KTextEditor::View *, const QString & ); - - virtual void flagCompletions( QStringList& ) {} - virtual bool wantsToProcessText( const QString & ) { return false; } - virtual void processText( KTextEditor::View *, const QString & ) {} -}; - - -/** - * This KTextEditor::Command provides vi commands for the application - */ -class AppCommands : public KTextEditor::Command -{ - public: - AppCommands(); - virtual ~AppCommands() {} - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param msg message returned from running the command - * @return success - */ - bool exec( class KTextEditor::View *view, const QString &cmd, QString &msg ); - - /** Help for AppCommands */ - bool help( class KTextEditor::View *, const QString &, QString & ); - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds(); - - private: - QRegExp re_write; - /*QRegExp re_quit; - QRegExp re_exit; - QRegExp re_changeBuffer; - QRegExp re_edit; - QRegExp re_new;*/ -}; -/** - * Support vim/sed style search and replace - * @author Charles Samuels - **/ -class SedReplace : public KTextEditor::Command, public KTextEditor::RangeCommand -{ - public: - /** - * Execute command. Valid command strings are: - * - s/search/replace/ find @c search, replace it with @c replace - * on this line - * - \%s/search/replace/ do the same to the whole file - * - s/search/replace/i do the search and replace case insensitively - * - $s/search/replace/ do the search are replacement to the - * selection only - * - * @note $s/// is currently unsupported - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @return success - */ - bool exec (class KTextEditor::View *view, const QString &cmd, QString &errorMsg); - - bool exec (class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &r); - - bool supportsRange(const QString &) { return true; } - - /** This command does not have help. @see KTextEditor::Command::help */ - bool help (class KTextEditor::View *, const QString &, QString &) { return false; } - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds () { static QStringList l("s"); if (l.isEmpty()) l << "%s" << "$s"; return l; } - - private: - /** - * Searches one line and does the replacement in the document. - * If @p replace contains any newline characters, the reamaining part of the - * line is searched, and the @p line set to the last line number searched. - * @return the number of replacements performed. - * @param doc a pointer to the document to work on - * @param line the number of the line to search. This may be changed by the - * function, if newlines are inserted. - * @param find A regular expression pattern to use for searching - * @param replace a template for replacement. Backspaced integers are - * replaced with captured texts from the regular expression. - * @param delim the delimiter character from the command. In the replacement - * text backsplashes preceding this character are removed. - * @param nocase parameter for matching the reqular expression. - * @param repeat If false, the search is stopped after the first match. - * @param startcol The position in the line to start the search. - * @param endcol The last column in the line allowed in a match. - * If it is -1, the whole line is used. - */ - static int sedMagic(KateDocument *doc, int &line, - const QString &find, const QString &replace, const QString &delim, - bool noCase, bool repeat, - int startcol=0, int endcol=-1); -}; - -/** - * insert a unicode or ascii character - * base 9+1: 1234 - * hex: 0x1234 or x1234 - * octal: 01231 - * - * prefixed with "char:" - **/ -class Character : public KTextEditor::Command -{ - public: - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @return success - */ - bool exec (class KTextEditor::View *view, const QString &cmd, QString &errorMsg); - - /** This command does not have help. @see KTextEditor::Command::help */ - bool help (class KTextEditor::View *, const QString &, QString &) { return false; } - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds () { static QStringList test("char"); return test; } -}; - -/** - * insert the current date/time in the given format - */ -class Date : public KTextEditor::Command -{ - public: - /** - * execute command - * @param view view to use for execution - * @param cmd cmd string - * @param errorMsg error to return if no success - * @return success - */ - bool exec (class KTextEditor::View *view, const QString &cmd, QString &errorMsg); - - /** This command does not have help. @see KTextEditor::Command::help */ - bool help (class KTextEditor::View *, const QString &, QString &) { return false; } - - /** - * supported commands as prefixes - * @return prefix list - */ - const QStringList &cmds () { static QStringList test("date"); return test; } -}; - - -} // namespace KateCommands -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateconfig.cpp b/part/utils/kateconfig.cpp deleted file mode 100644 index 52f7235..0000000 --- a/part/utils/kateconfig.cpp +++ /dev/null @@ -1,2159 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007, 2008 Matthew Woehlke - Copyright (C) 2003 Christoph Cullmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateconfig.h" - -#include "kateglobal.h" -#include "katerenderer.h" -#include "kateview.h" -#include "katedocument.h" -#include "kateschema.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -//BEGIN KateConfig -KateConfig::KateConfig () - : configSessionNumber (0), configIsRunning (false) -{ -} - -KateConfig::~KateConfig () -{ -} - -void KateConfig::configStart () -{ - configSessionNumber++; - - if (configSessionNumber > 1) - return; - - configIsRunning = true; -} - -void KateConfig::configEnd () -{ - if (configSessionNumber == 0) - return; - - configSessionNumber--; - - if (configSessionNumber > 0) - return; - - configIsRunning = false; - - updateConfig (); -} -//END - -//BEGIN KateDocumentConfig -KateGlobalConfig *KateGlobalConfig::s_global = 0; -KateDocumentConfig *KateDocumentConfig::s_global = 0; -KateViewConfig *KateViewConfig::s_global = 0; -KateRendererConfig *KateRendererConfig::s_global = 0; - -KateGlobalConfig::KateGlobalConfig () -{ - s_global = this; - - // init with defaults from config or really hardcoded ones - KConfigGroup cg( KGlobal::config(), "Kate Part Defaults"); - readConfig (cg); -} - -KateGlobalConfig::~KateGlobalConfig () -{ -} - -void KateGlobalConfig::readConfig (const KConfigGroup &config) -{ - configStart (); - - setProberType ((KEncodingProber::ProberType)config.readEntry("Encoding Prober Type", (int)KEncodingProber::Universal)); - setFallbackEncoding (config.readEntry("Fallback Encoding", "")); - - configEnd (); -} - -void KateGlobalConfig::writeConfig (KConfigGroup &config) -{ - config.writeEntry("Encoding Prober Type", (int)proberType()); - config.writeEntry("Fallback Encoding", fallbackEncoding()); -} - -void KateGlobalConfig::updateConfig () -{ -} - -void KateGlobalConfig::setProberType (KEncodingProber::ProberType proberType) -{ - configStart (); - m_proberType = proberType; - configEnd (); -} - -const QString &KateGlobalConfig::fallbackEncoding () const -{ - return m_fallbackEncoding; -} - -QTextCodec *KateGlobalConfig::fallbackCodec () const -{ - if (m_fallbackEncoding.isEmpty()) - return QTextCodec::codecForName("ISO 8859-15"); - - return KGlobal::charsets()->codecForName (m_fallbackEncoding); -} - -bool KateGlobalConfig::setFallbackEncoding (const QString &encoding) -{ - QTextCodec *codec; - bool found = false; - if (encoding.isEmpty()) - { - codec = s_global->fallbackCodec(); - found = true; - } - else - codec = KGlobal::charsets()->codecForName (encoding, found); - - if (!found || !codec) - return false; - - configStart (); - m_fallbackEncoding = codec->name(); - configEnd (); - return true; -} - -KateDocumentConfig::KateDocumentConfig () - : m_indentationWidth (2), - m_tabWidth (8), - m_tabHandling (tabSmart), - m_configFlags (0), - m_wordWrapAt (80), - m_tabWidthSet (true), - m_indentationWidthSet (true), - m_indentationModeSet (true), - m_wordWrapSet (true), - m_wordWrapAtSet (true), - m_pageUpDownMovesCursorSet (true), - m_keepExtraSpacesSet (false), - m_indentPastedTextSet (false), - m_backspaceIndentsSet (false), - m_smartHomeSet (false), - m_wrapCursorSet (false), - m_autoBracketsSet (false), - m_showTabsSet (false), - m_showSpacesSet (false), - m_replaceTabsDynSet (false), - m_removeTrailingDynSet (false), - m_removeSpacesSet (false), - m_overwiteModeSet (false), - m_tabIndentsSet (false), - m_encodingSet (true), - m_eolSet (true), - m_bomSet (true), - m_allowEolDetectionSet (false), - m_allowSimpleModeSet (false), - m_backupFlagsSet (true), - m_searchDirConfigDepthSet (true), - m_backupPrefixSet (true), - m_backupSuffixSet (true), - m_swapFileNoSyncSet (true), - m_onTheFlySpellCheckSet (true), - m_doc (0) -{ - s_global = this; - - // init with defaults from config or really hardcoded ones - KConfigGroup cg( KGlobal::config(), "Kate Document Defaults"); - readConfig (cg); -} - -KateDocumentConfig::KateDocumentConfig (const KConfigGroup &cg) - : m_indentationWidth (2), - m_tabWidth (8), - m_tabHandling (tabSmart), - m_configFlags (0), - m_wordWrapAt (80), - m_tabWidthSet (true), - m_indentationWidthSet (true), - m_indentationModeSet (true), - m_wordWrapSet (true), - m_wordWrapAtSet (true), - m_pageUpDownMovesCursorSet (true), - m_keepExtraSpacesSet (false), - m_indentPastedTextSet (false), - m_backspaceIndentsSet (false), - m_smartHomeSet (false), - m_wrapCursorSet (false), - m_autoBracketsSet (false), - m_showTabsSet (false), - m_showSpacesSet (false), - m_replaceTabsDynSet (false), - m_removeTrailingDynSet (false), - m_removeSpacesSet (false), - m_overwiteModeSet (false), - m_tabIndentsSet (false), - m_encodingSet (true), - m_eolSet (true), - m_bomSet (true), - m_allowEolDetectionSet (false), - m_allowSimpleModeSet (false), - m_backupFlagsSet (true), - m_searchDirConfigDepthSet (true), - m_backupPrefixSet (true), - m_backupSuffixSet (true), - m_swapFileNoSyncSet (true), - m_onTheFlySpellCheckSet (true), - m_doc (0) -{ - // init with defaults from config or really hardcoded ones - readConfig (cg); -} - -KateDocumentConfig::KateDocumentConfig (KateDocument *doc) - : m_tabHandling (tabSmart), - m_configFlags (0), - m_tabWidthSet (false), - m_indentationWidthSet (false), - m_indentationModeSet (false), - m_wordWrapSet (false), - m_wordWrapAtSet (false), - m_pageUpDownMovesCursorSet (false), - m_keepExtraSpacesSet (false), - m_indentPastedTextSet (false), - m_backspaceIndentsSet (false), - m_smartHomeSet (false), - m_wrapCursorSet (false), - m_autoBracketsSet (false), - m_showTabsSet (false), - m_showSpacesSet (false), - m_replaceTabsDynSet (false), - m_removeTrailingDynSet (false), - m_removeSpacesSet (false), - m_overwiteModeSet (false), - m_tabIndentsSet (false), - m_encodingSet (false), - m_eolSet (false), - m_bomSet (false), - m_allowEolDetectionSet (false), - m_allowSimpleModeSet (false), - m_backupFlagsSet (false), - m_searchDirConfigDepthSet (false), - m_backupPrefixSet (false), - m_backupSuffixSet (false), - m_swapFileNoSyncSet (false), - m_onTheFlySpellCheckSet (false), - m_doc (doc) -{ -} - -KateDocumentConfig::~KateDocumentConfig () -{ -} - -void KateDocumentConfig::readConfig (const KConfigGroup &config) -{ - configStart (); - - setTabWidth (config.readEntry("Tab Width", 8)); - - setIndentationWidth (config.readEntry("Indentation Width", 2)); - - setIndentationMode (config.readEntry("Indentation Mode", "")); - - setTabHandling (config.readEntry("Tab Handling", int(KateDocumentConfig::tabSmart))); - - setWordWrap (config.readEntry("Word Wrap", false)); - setWordWrapAt (config.readEntry("Word Wrap Column", 80)); - setPageUpDownMovesCursor (config.readEntry("PageUp/PageDown Moves Cursor", false)); - - setSmartHome (config.readEntry("Smart Home", true)); - setWrapCursor (config.readEntry("Wrap Cursor", true)); - setShowTabs (config.readEntry("Show Tabs", true)); - setTabIndents (config.readEntry("Indent On Tab", true)); - setKeepExtraSpaces (config.readEntry("Keep Extra Spaces", false)); - setIndentPastedText (config.readEntry("Indent On Text Paste", false)); - setBackspaceIndents (config.readEntry("Indent On Backspace", false)); - setAutoBrackets (config.readEntry("Automatically Insert Closing Brackets", false)); - setShowSpaces (config.readEntry("Show Spaces", false)); - setReplaceTabsDyn (config.readEntry("ReplaceTabsDyn", false)); - setRemoveTrailingDyn (config.readEntry("RemoveTrailingDyn", false)); - setRemoveSpaces (config.readEntry("Remove Spaces", false)); - setOvr (config.readEntry("Overwrite Mode", false)); - - setEncoding (config.readEntry("Encoding", "")); - - setEol (config.readEntry("End of Line", 0)); - setAllowEolDetection (config.readEntry("Allow End of Line Detection", true)); - - setBom (config.readEntry("BOM",false)); - - setAllowSimpleMode (config.readEntry("Allow Simple Mode", true)); - - setBackupFlags (config.readEntry("Backup Config Flags", 1)); - - setSearchDirConfigDepth (config.readEntry("Search Dir Config Depth", 3)); - - setBackupPrefix (config.readEntry("Backup Prefix", QString (""))); - - setBackupSuffix (config.readEntry("Backup Suffix", QString ("~"))); - - setSwapFileNoSync (config.readEntry("No sync", false)); - - setOnTheFlySpellCheck(config.readEntry("On-The-Fly Spellcheck", false)); - - configEnd (); -} - -void KateDocumentConfig::writeConfig (KConfigGroup &config) -{ - config.writeEntry("Tab Width", tabWidth()); - - config.writeEntry("Indentation Width", indentationWidth()); - config.writeEntry("Indentation Mode", indentationMode()); - - config.writeEntry("Tab Handling", tabHandling()); - - config.writeEntry("Word Wrap", wordWrap()); - config.writeEntry("Word Wrap Column", wordWrapAt()); - - config.writeEntry("PageUp/PageDown Moves Cursor", pageUpDownMovesCursor()); - - config.writeEntry("Smart Home", smartHome()); - config.writeEntry("Wrap Cursor", wrapCursor()); - config.writeEntry("Show Tabs", showTabs()); - config.writeEntry("Indent On Tab", tabIndentsEnabled()); - config.writeEntry("Keep Extra Spaces", keepExtraSpaces()); - config.writeEntry("Indent On Text Paste", indentPastedText()); - config.writeEntry("Indent On Backspace", backspaceIndents()); - config.writeEntry("Automatically Insert Closing Brackets", autoBrackets()); - config.writeEntry("Show Spaces", showSpaces()); - config.writeEntry("ReplaceTabsDyn", replaceTabsDyn()); - config.writeEntry("RemoveTrailingDyn", removeTrailingDyn()); - config.writeEntry("Remove Spaces", removeSpaces()); - config.writeEntry("Overwrite Mode", ovr()); - - config.writeEntry("Encoding", encoding()); - - config.writeEntry("End of Line", eol()); - config.writeEntry("Allow End of Line Detection", allowEolDetection()); - - config.writeEntry("BOM",bom()); - - config.writeEntry("Allow Simple Mode", allowSimpleMode()); - - config.writeEntry("Backup Config Flags", backupFlags()); - - config.writeEntry("Search Dir Config Depth", searchDirConfigDepth()); - - config.writeEntry("Backup Prefix", backupPrefix()); - - config.writeEntry("Backup Suffix", backupSuffix()); - - config.writeEntry("No sync", swapFileNoSync()); - - config.writeEntry("On-The-Fly Spellcheck", onTheFlySpellCheck()); -} - -void KateDocumentConfig::updateConfig () -{ - if (m_doc) - { - m_doc->updateConfig (); - return; - } - - if (isGlobal()) - { - for (int z=0; z < KateGlobal::self()->kateDocuments().size(); ++z) - (KateGlobal::self()->kateDocuments())[z]->updateConfig (); - } -} - -int KateDocumentConfig::tabWidth () const -{ - if (m_tabWidthSet || isGlobal()) - return m_tabWidth; - - return s_global->tabWidth(); -} - -void KateDocumentConfig::setTabWidth (int tabWidth) -{ - if (tabWidth < 1) - return; - - configStart (); - - m_tabWidthSet = true; - m_tabWidth = tabWidth; - - configEnd (); -} - -int KateDocumentConfig::indentationWidth () const -{ - if (m_indentationWidthSet || isGlobal()) - return m_indentationWidth; - - return s_global->indentationWidth(); -} - -void KateDocumentConfig::setIndentationWidth (int indentationWidth) -{ - if (indentationWidth < 1) - return; - - configStart (); - - m_indentationWidthSet = true; - m_indentationWidth = indentationWidth; - - configEnd (); -} - -const QString &KateDocumentConfig::indentationMode () const -{ - if (m_indentationModeSet || isGlobal()) - return m_indentationMode; - - return s_global->indentationMode(); -} - -void KateDocumentConfig::setIndentationMode (const QString &indentationMode) -{ - configStart (); - - m_indentationModeSet = true; - m_indentationMode = indentationMode; - - configEnd (); -} - -uint KateDocumentConfig::tabHandling () const -{ - // This setting is purly a user preference, - // hence, there exists only the global setting. - if (isGlobal()) - return m_tabHandling; - - return s_global->tabHandling(); -} - -void KateDocumentConfig::setTabHandling (uint tabHandling) -{ - configStart (); - - m_tabHandling = tabHandling; - - configEnd (); -} - -bool KateDocumentConfig::wordWrap () const -{ - if (m_wordWrapSet || isGlobal()) - return m_wordWrap; - - return s_global->wordWrap(); -} - -void KateDocumentConfig::setWordWrap (bool on) -{ - configStart (); - - m_wordWrapSet = true; - m_wordWrap = on; - - configEnd (); -} - -unsigned int KateDocumentConfig::wordWrapAt () const -{ - if (m_wordWrapAtSet || isGlobal()) - return m_wordWrapAt; - - return s_global->wordWrapAt(); -} - -void KateDocumentConfig::setWordWrapAt (unsigned int col) -{ - if (col < 1) - return; - - configStart (); - - m_wordWrapAtSet = true; - m_wordWrapAt = col; - - configEnd (); -} - -bool KateDocumentConfig::pageUpDownMovesCursor () const -{ - if (m_pageUpDownMovesCursorSet || isGlobal()) - return m_pageUpDownMovesCursor; - - return s_global->pageUpDownMovesCursor(); -} - -void KateDocumentConfig::setPageUpDownMovesCursor (bool on) -{ - configStart (); - - m_pageUpDownMovesCursorSet = true; - m_pageUpDownMovesCursor = on; - - configEnd (); -} - -void KateDocumentConfig::setKeepExtraSpaces(bool on) -{ - configStart (); - - m_keepExtraSpacesSet = true; - m_keepExtraSpaces = on; - - configEnd (); -} - -bool KateDocumentConfig::keepExtraSpaces() const -{ - if (m_keepExtraSpacesSet || isGlobal()) - return m_keepExtraSpaces; - - return s_global->keepExtraSpaces(); -} - -void KateDocumentConfig::setIndentPastedText(bool on) -{ - configStart (); - - m_indentPastedTextSet = true; - m_indentPastedText = on; - - configEnd (); -} - -bool KateDocumentConfig::indentPastedText() const -{ - if (m_indentPastedTextSet || isGlobal()) - return m_indentPastedText; - - return s_global->indentPastedText(); -} - -void KateDocumentConfig::setBackspaceIndents(bool on) -{ - configStart (); - - m_backspaceIndentsSet = true; - m_backspaceIndents = on; - - configEnd (); -} - -bool KateDocumentConfig::backspaceIndents() const -{ - if (m_backspaceIndentsSet || isGlobal()) - return m_backspaceIndents; - - return s_global->backspaceIndents(); -} - -void KateDocumentConfig::setSmartHome(bool on) -{ - configStart (); - - m_smartHomeSet = true; - m_smartHome = on; - - configEnd (); -} - -bool KateDocumentConfig::smartHome() const -{ - if (m_smartHomeSet || isGlobal()) - return m_smartHome; - - return s_global->smartHome(); -} - -void KateDocumentConfig::setWrapCursor(bool on) -{ - configStart (); - - m_wrapCursorSet = true; - m_wrapCursor = on; - - configEnd (); -} - -bool KateDocumentConfig::wrapCursor() const -{ - if (m_wrapCursorSet || isGlobal()) - return m_wrapCursor; - - return s_global->wrapCursor(); -} - -void KateDocumentConfig::setAutoBrackets(bool on) -{ - configStart (); - - m_autoBracketsSet = true; - m_autoBrackets = on; - - configEnd (); -} - -bool KateDocumentConfig::autoBrackets() const -{ - if (m_autoBracketsSet || isGlobal()) - return m_autoBrackets; - - return s_global->autoBrackets(); -} - -void KateDocumentConfig::setShowTabs(bool on) -{ - configStart (); - - m_showTabsSet = true; - m_showTabs = on; - - configEnd (); -} - -bool KateDocumentConfig::showTabs() const -{ - if (m_showTabsSet || isGlobal()) - return m_showTabs; - - return s_global->showTabs(); -} - -void KateDocumentConfig::setShowSpaces(bool on) -{ - configStart (); - - m_showSpacesSet = true; - m_showSpaces = on; - - configEnd (); -} - -bool KateDocumentConfig::showSpaces() const -{ - if (m_showSpacesSet || isGlobal()) - return m_showSpaces; - - return s_global->showSpaces(); -} - -void KateDocumentConfig::setReplaceTabsDyn(bool on) -{ - configStart (); - - m_replaceTabsDynSet = true; - m_replaceTabsDyn = on; - - configEnd (); -} - -bool KateDocumentConfig::replaceTabsDyn() const -{ - if (m_replaceTabsDynSet || isGlobal()) - return m_replaceTabsDyn; - - return s_global->replaceTabsDyn(); -} - -void KateDocumentConfig::setRemoveTrailingDyn(bool on) -{ - configStart (); - - m_removeTrailingDynSet = true; - m_removeTrailingDyn = on; - - configEnd (); -} - -bool KateDocumentConfig::removeTrailingDyn() const -{ - if (m_removeTrailingDynSet || isGlobal()) - return m_removeTrailingDyn; - - return s_global->removeTrailingDyn(); -} - -void KateDocumentConfig::setRemoveSpaces(bool on) -{ - configStart (); - - m_removeSpacesSet = true; - m_removeSpaces = on; - - configEnd (); -} - -bool KateDocumentConfig::removeSpaces() const -{ - if (m_removeSpacesSet || isGlobal()) - return m_removeSpaces; - - return s_global->removeSpaces(); -} - -void KateDocumentConfig::setOvr(bool on) -{ - configStart (); - - m_overwiteModeSet = true; - m_overwiteMode = on; - - configEnd (); -} - -bool KateDocumentConfig::ovr() const -{ - if (m_overwiteModeSet || isGlobal()) - return m_overwiteMode; - - return s_global->ovr(); -} - -void KateDocumentConfig::setTabIndents(bool on) -{ - configStart (); - - m_tabIndentsSet = true; - m_tabIndents = on; - - configEnd (); -} - -bool KateDocumentConfig::tabIndentsEnabled() const -{ - if (m_tabIndentsSet || isGlobal()) - return m_tabIndents; - - return s_global->tabIndentsEnabled(); -} - -const QString &KateDocumentConfig::encoding () const -{ - if (m_encodingSet || isGlobal()) - return m_encoding; - - return s_global->encoding(); -} - -QTextCodec *KateDocumentConfig::codec () const -{ - if (m_encodingSet || isGlobal()) - { - if (m_encoding.isEmpty() && isGlobal()) - return KGlobal::locale()->codecForEncoding(); - else if (m_encoding.isEmpty()) - return s_global->codec (); - else - return KGlobal::charsets()->codecForName (m_encoding); - } - - return s_global->codec (); -} - -bool KateDocumentConfig::setEncoding (const QString &encoding) -{ - QTextCodec *codec; - bool found = false; - if (encoding.isEmpty()) - { - codec = s_global->codec(); - found=true; - } - else - codec = KGlobal::charsets()->codecForName (encoding, found); - - if (!found || !codec) - return false; - - configStart (); - m_encodingSet = true; - m_encoding = codec->name(); - - if (isGlobal()) - KateGlobal::self()->setDefaultEncoding (m_encoding); - - configEnd (); - return true; -} - -bool KateDocumentConfig::isSetEncoding () const -{ - return m_encodingSet; -} - -int KateDocumentConfig::eol () const -{ - if (m_eolSet || isGlobal()) - return m_eol; - - return s_global->eol(); -} - -QString KateDocumentConfig::eolString () -{ - if (eol() == KateDocumentConfig::eolUnix) - return QString ("\n"); - else if (eol() == KateDocumentConfig::eolDos) - return QString ("\r\n"); - else if (eol() == KateDocumentConfig::eolMac) - return QString ("\r"); - - return QString ("\n"); -} - -void KateDocumentConfig::setEol (int mode) -{ - configStart (); - - m_eolSet = true; - m_eol = mode; - - configEnd (); -} - -void KateDocumentConfig::setBom (bool bom) -{ - configStart (); - - m_bomSet = true; - m_bom = bom; - - configEnd (); -} - -bool KateDocumentConfig::bom() const -{ - if (m_bomSet || isGlobal()) - return m_bom; - return s_global->bom(); -} - - -bool KateDocumentConfig::allowEolDetection () const -{ - if (m_allowEolDetectionSet || isGlobal()) - return m_allowEolDetection; - - return s_global->allowEolDetection(); -} - -void KateDocumentConfig::setAllowEolDetection (bool on) -{ - configStart (); - - m_allowEolDetectionSet = true; - m_allowEolDetection = on; - - configEnd (); -} - - -bool KateDocumentConfig::allowSimpleMode () const -{ - if (m_allowSimpleModeSet || isGlobal()) - return m_allowSimpleMode; - - return s_global->allowSimpleMode(); -} - -void KateDocumentConfig::setAllowSimpleMode (bool on) -{ - configStart (); - - m_allowSimpleModeSet = true; - m_allowSimpleMode = on; - - configEnd (); -} - -uint KateDocumentConfig::backupFlags () const -{ - if (m_backupFlagsSet || isGlobal()) - return m_backupFlags; - - return s_global->backupFlags(); -} - -void KateDocumentConfig::setBackupFlags (uint flags) - { - configStart (); - - m_backupFlagsSet = true; - m_backupFlags = flags; - - configEnd (); -} - -const QString &KateDocumentConfig::backupPrefix () const -{ - if (m_backupPrefixSet || isGlobal()) - return m_backupPrefix; - - return s_global->backupPrefix(); -} - -const QString &KateDocumentConfig::backupSuffix () const -{ - if (m_backupSuffixSet || isGlobal()) - return m_backupSuffix; - - return s_global->backupSuffix(); -} - -void KateDocumentConfig::setBackupPrefix (const QString &prefix) -{ - configStart (); - - m_backupPrefixSet = true; - m_backupPrefix = prefix; - - configEnd (); -} - -void KateDocumentConfig::setBackupSuffix (const QString &suffix) -{ - configStart (); - - m_backupSuffixSet = true; - m_backupSuffix = suffix; - - configEnd (); -} - -bool KateDocumentConfig::swapFileNoSync() const -{ - if (m_swapFileNoSyncSet || isGlobal()) - return m_swapFileNoSync; - - return s_global->swapFileNoSync(); -} - -void KateDocumentConfig::setSwapFileNoSync(bool on) -{ - configStart(); - - m_swapFileNoSyncSet = true; - m_swapFileNoSync = on; - - configEnd(); -} - -int KateDocumentConfig::searchDirConfigDepth () const -{ - if (m_searchDirConfigDepthSet || isGlobal()) - return m_searchDirConfigDepth; - - return s_global->searchDirConfigDepth (); -} - -void KateDocumentConfig::setSearchDirConfigDepth (int depth) -{ - configStart (); - - m_searchDirConfigDepthSet = true; - m_searchDirConfigDepth = depth; - - configEnd (); -} - -bool KateDocumentConfig::onTheFlySpellCheck() const -{ - if(isGlobal()) { - // WARNING: this is slightly hackish, but it's currently the only way to - // do it, see also the KTextEdit class - KConfigGroup configGroup(KGlobal::config(), "Spelling"); - return configGroup.readEntry("checkerEnabledByDefault", false); - } - if (m_onTheFlySpellCheckSet) { - return m_onTheFlySpellCheck; - } - - return s_global->onTheFlySpellCheck(); -} - -void KateDocumentConfig::setOnTheFlySpellCheck(bool on) -{ - configStart (); - - m_onTheFlySpellCheckSet = true; - m_onTheFlySpellCheck = on; - - configEnd (); -} - - - - -//END - -//BEGIN KateViewConfig -KateViewConfig::KateViewConfig () - : - m_dynWordWrapSet (true), - m_dynWordWrapIndicatorsSet (true), - m_dynWordWrapAlignIndentSet (true), - m_lineNumbersSet (true), - m_scrollBarMarksSet (true), - m_iconBarSet (true), - m_foldingBarSet (true), - m_bookmarkSortSet (true), - m_autoCenterLinesSet (true), - m_searchFlagsSet (true), - m_defaultMarkTypeSet (true), - m_persistentSelectionSet (true), - m_viInputModeSet (true), - m_viInputModeStealKeysSet (true), - m_automaticCompletionInvocationSet (true), - m_wordCompletionSet (true), - m_wordCompletionMinimalWordLengthSet (true), - m_smartCopyCutSet (true), - m_scrollPastEndSet (true), - m_allowMarkMenu (true), - m_view (0) -{ - s_global = this; - - // init with defaults from config or really hardcoded ones - KConfigGroup config( KGlobal::config(), "Kate View Defaults"); - readConfig (config); -} - -KateViewConfig::KateViewConfig (KateView *view) - : - m_searchFlags (PowerModePlainText), - m_maxHistorySize (100), - m_dynWordWrapSet (false), - m_dynWordWrapIndicatorsSet (false), - m_dynWordWrapAlignIndentSet (false), - m_lineNumbersSet (false), - m_scrollBarMarksSet (false), - m_iconBarSet (false), - m_foldingBarSet (false), - m_bookmarkSortSet (false), - m_autoCenterLinesSet (false), - m_searchFlagsSet (false), - m_defaultMarkTypeSet (false), - m_persistentSelectionSet (false), - m_viInputModeSet (false), - m_viInputModeStealKeysSet (false), - m_automaticCompletionInvocationSet (false), - m_wordCompletionSet (false), - m_wordCompletionMinimalWordLengthSet (false), - m_smartCopyCutSet (false), - m_scrollPastEndSet (false), - m_allowMarkMenu (true), - m_view (view) -{ -} - -KateViewConfig::~KateViewConfig () -{ -} - - -// TODO Extract more keys to constants for maintainability -static const char * const KEY_SEARCH_REPLACE_FLAGS = "Search/Replace Flags"; -static const char * const KEY_PATTERN_HISTORY = "Search Pattern History"; -static const char * const KEY_REPLACEMENT_HISTORY = "Replacement Text History"; - - -void KateViewConfig::readConfig ( const KConfigGroup &config) -{ - configStart (); - - // default off again, until this is usable for large size documents - setDynWordWrap (config.readEntry( "Dynamic Word Wrap", false )); - setDynWordWrapIndicators (config.readEntry( "Dynamic Word Wrap Indicators", 1 )); - setDynWordWrapAlignIndent (config.readEntry( "Dynamic Word Wrap Align Indent", 80 )); - - setLineNumbers (config.readEntry( "Line Numbers", false)); - - setScrollBarMarks (config.readEntry( "Scroll Bar Marks", false)); - - setIconBar (config.readEntry( "Icon Bar", false )); - - setFoldingBar (config.readEntry( "Folding Bar", true)); - - setBookmarkSort (config.readEntry( "Bookmark Menu Sorting", 0 )); - - setAutoCenterLines (config.readEntry( "Auto Center Lines", 0 )); - - setSearchFlags(config.readEntry(KEY_SEARCH_REPLACE_FLAGS, - IncFromCursor|PowerMatchCase|PowerModePlainText)); - - m_maxHistorySize = config.readEntry("Maximum Search History Size", 100); - - setDefaultMarkType (config.readEntry( "Default Mark Type", int(KTextEditor::MarkInterface::markType01) )); - setAllowMarkMenu (config.readEntry( "Allow Mark Menu", true )); - - setPersistentSelection (config.readEntry( "Persistent Selection", false )); - - setViInputMode (config.readEntry( "Vi Input Mode", false)); - setViInputModeStealKeys (config.readEntry( "Vi Input Mode Steal Keys", false)); - setViInputModeHideStatusBar (config.readEntry( "Vi Input Mode Hide Status Bar", false)); - - setAutomaticCompletionInvocation (config.readEntry( "Auto Completion", true )); - setWordCompletion (config.readEntry( "Word Completion", true )); - setWordCompletionMinimalWordLength (config.readEntry( "Word Completion Minimal Word Length", 3 )); - setSmartCopyCut (config.readEntry( "Smart Copy Cut", false )); - setScrollPastEnd (config.readEntry( "Scroll Past End", false )); - - if (isGlobal()) { - // Read search pattern history - QStringList patternHistory = config.readEntry(KEY_PATTERN_HISTORY, QStringList()); - m_patternHistoryModel.setStringList(patternHistory); - - // Read replacement text history - QStringList replacementHistory = config.readEntry(KEY_REPLACEMENT_HISTORY, QStringList()); - m_replacementHistoryModel.setStringList(replacementHistory); - } - - configEnd (); -} - -void KateViewConfig::writeConfig (KConfigGroup &config) -{ - config.writeEntry( "Dynamic Word Wrap", dynWordWrap() ); - config.writeEntry( "Dynamic Word Wrap Indicators", dynWordWrapIndicators() ); - config.writeEntry( "Dynamic Word Wrap Align Indent", dynWordWrapAlignIndent() ); - - config.writeEntry( "Line Numbers", lineNumbers() ); - - config.writeEntry( "Scroll Bar Marks", scrollBarMarks() ); - - config.writeEntry( "Icon Bar", iconBar() ); - - config.writeEntry( "Folding Bar", foldingBar() ); - - config.writeEntry( "Bookmark Menu Sorting", bookmarkSort() ); - - config.writeEntry( "Auto Center Lines", autoCenterLines() ); - - config.writeEntry(KEY_SEARCH_REPLACE_FLAGS, int(searchFlags())); - - config.writeEntry("Maximum Search History Size", m_maxHistorySize); - - config.writeEntry("Default Mark Type", defaultMarkType()); - - config.writeEntry("Allow Mark Menu", allowMarkMenu()); - - config.writeEntry("Persistent Selection", persistentSelection()); - - config.writeEntry( "Auto Completion", automaticCompletionInvocation()); - config.writeEntry( "Word Completion", wordCompletion()); - config.writeEntry( "Word Completion Minimal Word Length", wordCompletionMinimalWordLength()); - - config.writeEntry( "Smart Copy Cut", smartCopyCut() ); - config.writeEntry( "Scroll Past End" , scrollPastEnd() ); - - config.writeEntry( "Vi Input Mode", viInputMode()); - - config.writeEntry( "Vi Input Mode Steal Keys", viInputModeStealKeys()); - - config.writeEntry( "Vi Input Mode Hide Status Bar", viInputModeHideStatusBar()); - - - if (isGlobal()) { - // Write search pattern history - config.writeEntry(KEY_PATTERN_HISTORY, m_patternHistoryModel.stringList()); - - // Write replacement text history - config.writeEntry(KEY_REPLACEMENT_HISTORY, m_replacementHistoryModel.stringList()); - } -} - -void KateViewConfig::updateConfig () -{ - if (m_view) - { - m_view->updateConfig (); - return; - } - - if (isGlobal()) - { - for (int z=0; z < KateGlobal::self()->views().size(); ++z) - (KateGlobal::self()->views())[z]->updateConfig (); - } -} - -bool KateViewConfig::dynWordWrap () const -{ - if (m_dynWordWrapSet || isGlobal()) - return m_dynWordWrap; - - return s_global->dynWordWrap(); -} - -void KateViewConfig::setDynWordWrap (bool wrap) -{ - configStart (); - - m_dynWordWrapSet = true; - m_dynWordWrap = wrap; - - configEnd (); -} - -int KateViewConfig::dynWordWrapIndicators () const -{ - if (m_dynWordWrapIndicatorsSet || isGlobal()) - return m_dynWordWrapIndicators; - - return s_global->dynWordWrapIndicators(); -} - -void KateViewConfig::setDynWordWrapIndicators (int mode) -{ - configStart (); - - m_dynWordWrapIndicatorsSet = true; - m_dynWordWrapIndicators = qBound(0, mode, 80); - - configEnd (); -} - -int KateViewConfig::dynWordWrapAlignIndent () const -{ - if (m_dynWordWrapAlignIndentSet || isGlobal()) - return m_dynWordWrapAlignIndent; - - return s_global->dynWordWrapAlignIndent(); -} - -void KateViewConfig::setDynWordWrapAlignIndent (int indent) -{ - configStart (); - - m_dynWordWrapAlignIndentSet = true; - m_dynWordWrapAlignIndent = indent; - - configEnd (); -} - -bool KateViewConfig::lineNumbers () const -{ - if (m_lineNumbersSet || isGlobal()) - return m_lineNumbers; - - return s_global->lineNumbers(); -} - -void KateViewConfig::setLineNumbers (bool on) -{ - configStart (); - - m_lineNumbersSet = true; - m_lineNumbers = on; - - configEnd (); -} - -bool KateViewConfig::scrollBarMarks () const -{ - if (m_scrollBarMarksSet || isGlobal()) - return m_scrollBarMarks; - - return s_global->scrollBarMarks(); -} - -void KateViewConfig::setScrollBarMarks (bool on) -{ - configStart (); - - m_scrollBarMarksSet = true; - m_scrollBarMarks = on; - - configEnd (); -} - -bool KateViewConfig::iconBar () const -{ - if (m_iconBarSet || isGlobal()) - return m_iconBar; - - return s_global->iconBar(); -} - -void KateViewConfig::setIconBar (bool on) -{ - configStart (); - - m_iconBarSet = true; - m_iconBar = on; - - configEnd (); -} - -bool KateViewConfig::foldingBar () const -{ - if (m_foldingBarSet || isGlobal()) - return m_foldingBar; - - return s_global->foldingBar(); -} - -void KateViewConfig::setFoldingBar (bool on) -{ - configStart (); - - m_foldingBarSet = true; - m_foldingBar = on; - - configEnd (); -} - -int KateViewConfig::bookmarkSort () const -{ - if (m_bookmarkSortSet || isGlobal()) - return m_bookmarkSort; - - return s_global->bookmarkSort(); -} - -void KateViewConfig::setBookmarkSort (int mode) -{ - configStart (); - - m_bookmarkSortSet = true; - m_bookmarkSort = mode; - - configEnd (); -} - -int KateViewConfig::autoCenterLines () const -{ - if (m_autoCenterLinesSet || isGlobal()) - return m_autoCenterLines; - - return s_global->autoCenterLines(); -} - -void KateViewConfig::setAutoCenterLines (int lines) -{ - if (lines < 0) - return; - - configStart (); - - m_autoCenterLinesSet = true; - m_autoCenterLines = lines; - - configEnd (); -} - -long KateViewConfig::searchFlags () const -{ - if (m_searchFlagsSet || isGlobal()) - return m_searchFlags; - - return s_global->searchFlags(); -} - -void KateViewConfig::setSearchFlags (long flags) - { - configStart (); - - m_searchFlagsSet = true; - m_searchFlags = flags; - - configEnd (); -} - -QStringListModel *KateViewConfig::patternHistoryModel() -{ - // always return global history - if (isGlobal()) - return &m_patternHistoryModel; - - return s_global->patternHistoryModel(); -} - -int KateViewConfig::maxHistorySize() const -{ - return m_maxHistorySize; -} - -QStringListModel *KateViewConfig::replacementHistoryModel() -{ - // always return global history - if (isGlobal()) - return &m_replacementHistoryModel; - - return s_global->replacementHistoryModel(); -} - -uint KateViewConfig::defaultMarkType () const -{ - if (m_defaultMarkTypeSet || isGlobal()) - return m_defaultMarkType; - - return s_global->defaultMarkType(); -} - -void KateViewConfig::setDefaultMarkType (uint type) -{ - configStart (); - - m_defaultMarkTypeSet = true; - m_defaultMarkType = type; - - configEnd (); -} - -bool KateViewConfig::allowMarkMenu() const -{ - return m_allowMarkMenu; -} - -void KateViewConfig::setAllowMarkMenu (bool allow) -{ - m_allowMarkMenu = allow; -} - -bool KateViewConfig::persistentSelection () const -{ - if (m_persistentSelectionSet || isGlobal()) - return m_persistentSelection; - - return s_global->persistentSelection(); -} - -void KateViewConfig::setPersistentSelection (bool on) -{ - configStart (); - - m_persistentSelectionSet = true; - m_persistentSelection = on; - - configEnd (); -} - -bool KateViewConfig::viInputMode () const -{ - if (m_viInputModeSet || isGlobal()) - return m_viInputMode; - - return s_global->viInputMode(); -} - -void KateViewConfig::setViInputMode (bool on) -{ - configStart (); - - m_viInputModeSet = true; - m_viInputMode = on; - - // update all views and show/hide the status bar - foreach (KateView* view, KateGlobal::self()->views() ) { - if (on && !m_viInputModeHideStatusBar) { - view->showViModeBar(); - } else { - view->hideViModeBar(); - } - } - - // make sure to turn off edits mergin when leaving vi input mode - if (!on && m_view) { - m_view->doc()->setUndoMergeAllEdits(false); - } - - configEnd (); -} - -bool KateViewConfig::viInputModeStealKeys () const -{ - if (m_viInputModeStealKeysSet || isGlobal()) - return m_viInputModeStealKeys; - - return s_global->viInputModeStealKeys(); -} - -void KateViewConfig::setViInputModeStealKeys (bool on) -{ - configStart (); - - m_viInputModeStealKeysSet = true; - m_viInputModeStealKeys = on; - - configEnd (); -} - -bool KateViewConfig::viInputModeHideStatusBar () const -{ - if (m_viInputModeHideStatusBarSet || isGlobal()) - return m_viInputModeHideStatusBar; - - return s_global->viInputModeHideStatusBar(); -} - -void KateViewConfig::setViInputModeHideStatusBar (bool on) -{ - configStart (); - - m_viInputModeHideStatusBarSet = true; - m_viInputModeHideStatusBar = on; - - // update all views and show/hide the status bar - foreach (KateView* view, KateGlobal::self()->views() ) { - if (on && m_viInputMode) { - view->hideViModeBar(); - } else if (viInputMode()) { - view->showViModeBar(); - } - } - - configEnd (); -} - - -bool KateViewConfig::automaticCompletionInvocation () const -{ - if (m_automaticCompletionInvocationSet || isGlobal()) - return m_automaticCompletionInvocation; - - return s_global->automaticCompletionInvocation(); -} - -void KateViewConfig::setAutomaticCompletionInvocation (bool on) -{ - configStart (); - - m_automaticCompletionInvocationSet = true; - m_automaticCompletionInvocation = on; - - configEnd (); -} - -bool KateViewConfig::wordCompletion () const -{ - if (m_wordCompletionSet || isGlobal()) - return m_wordCompletion; - - return s_global->wordCompletion(); -} - -void KateViewConfig::setWordCompletion (bool on) -{ - configStart (); - - m_wordCompletionSet = true; - m_wordCompletion = on; - - configEnd (); -} - -int KateViewConfig::wordCompletionMinimalWordLength () const -{ - if (m_wordCompletionMinimalWordLengthSet || isGlobal()) - return m_wordCompletionMinimalWordLength; - - return s_global->wordCompletionMinimalWordLength(); -} - -void KateViewConfig::setWordCompletionMinimalWordLength (int length) -{ - configStart (); - - m_wordCompletionMinimalWordLengthSet = true; - m_wordCompletionMinimalWordLength = length; - - configEnd (); -} - -bool KateViewConfig::smartCopyCut () const -{ - if (m_smartCopyCutSet || isGlobal()) - return m_smartCopyCut; - - return s_global->smartCopyCut(); -} - -void KateViewConfig::setSmartCopyCut (bool on) -{ - configStart (); - - m_smartCopyCutSet = true; - m_smartCopyCut = on; - - configEnd (); -} - -bool KateViewConfig::scrollPastEnd () const -{ - if (m_scrollPastEndSet || isGlobal()) - return m_scrollPastEnd; - - return s_global->scrollPastEnd(); -} - -void KateViewConfig::setScrollPastEnd (bool on) -{ - configStart (); - - m_scrollPastEndSet = true; - m_scrollPastEnd = on; - - configEnd (); -} - -//END - -//BEGIN KateRendererConfig -KateRendererConfig::KateRendererConfig () - : m_fontMetrics(QFont()), - m_lineMarkerColor (KTextEditor::MarkInterface::reservedMarkersCount()), - m_schemaSet (true), - m_fontSet (true), - m_wordWrapMarkerSet (true), - m_showIndentationLinesSet (true), - m_showWholeBracketExpressionSet (true), - m_backgroundColorSet (true), - m_selectionColorSet (true), - m_highlightedLineColorSet (true), - m_highlightedBracketColorSet (true), - m_wordWrapMarkerColorSet (true), - m_tabMarkerColorSet(true), - m_iconBarColorSet (true), - m_lineNumberColorSet (true), - m_spellingMistakeLineColorSet (true), - m_templateColorsSet(true), - m_lineMarkerColorSet (m_lineMarkerColor.size()), - m_renderer (0) -{ - // init bitarray - m_lineMarkerColorSet.fill (true); - - s_global = this; - - // init with defaults from config or really hardcoded ones - KConfigGroup config(KGlobal::config(), "Kate Renderer Defaults"); - readConfig (config); -} - -KateRendererConfig::KateRendererConfig (KateRenderer *renderer) - : m_fontMetrics(QFont()), - m_lineMarkerColor (KTextEditor::MarkInterface::reservedMarkersCount()), - m_schemaSet (false), - m_fontSet (false), - m_wordWrapMarkerSet (false), - m_showIndentationLinesSet (false), - m_showWholeBracketExpressionSet (false), - m_backgroundColorSet (false), - m_selectionColorSet (false), - m_highlightedLineColorSet (false), - m_highlightedBracketColorSet (false), - m_wordWrapMarkerColorSet (false), - m_tabMarkerColorSet(false), - m_iconBarColorSet (false), - m_lineNumberColorSet (false), - m_spellingMistakeLineColorSet (false), - m_templateColorsSet(false), - m_lineMarkerColorSet (m_lineMarkerColor.size()), - m_renderer (renderer) -{ - // init bitarray - m_lineMarkerColorSet.fill (false); -} - -KateRendererConfig::~KateRendererConfig () -{ -} - -void KateRendererConfig::readConfig (const KConfigGroup &config) -{ - configStart (); - - setSchema (config.readEntry("Schema", KateSchemaManager::normalSchema())); - - setWordWrapMarker (config.readEntry("Word Wrap Marker", false )); - - setShowIndentationLines (config.readEntry( "Show Indentation Lines", false)); - - setShowWholeBracketExpression (config.readEntry( "Show Whole Bracket Expression", false)); - - configEnd (); -} - -void KateRendererConfig::writeConfig (KConfigGroup& config) -{ - config.writeEntry ("Schema", schema()); - - config.writeEntry("Word Wrap Marker", wordWrapMarker() ); - - config.writeEntry("Show Indentation Lines", showIndentationLines()); - - config.writeEntry("Show Whole Bracket Expression", showWholeBracketExpression()); -} - -void KateRendererConfig::updateConfig () -{ - if (m_renderer) - { - m_renderer->updateConfig (); - return; - } - - if (isGlobal()) - { - for (int z=0; z < KateGlobal::self()->views().size(); ++z) - (KateGlobal::self()->views())[z]->renderer()->updateConfig (); - } -} - -const QString &KateRendererConfig::schema () const -{ - if (m_schemaSet || isGlobal()) - return m_schema; - - return s_global->schema(); -} - -void KateRendererConfig::setSchema (const QString &schema) -{ - configStart (); - m_schemaSet = true; - m_schema = schema; - setSchemaInternal( schema ); - configEnd (); -} - -void KateRendererConfig::reloadSchema() -{ - if ( isGlobal() ) - foreach (KateView* view, KateGlobal::self()->views() ) - view->renderer()->config()->reloadSchema(); - - else if ( m_renderer && m_schemaSet ) - setSchemaInternal( m_schema ); -} - -void KateRendererConfig::setSchemaInternal( const QString &schema ) -{ - m_schemaSet = true; - m_schema = schema; - - KConfigGroup config = KateGlobal::self()->schemaManager()->schema(KateGlobal::self()->schemaManager()->number(schema)); - - // NOTE keep in sync with KateSchemaConfigColorTab::schemaChanged - KColorScheme schemeView(QPalette::Active, KColorScheme::View); - KColorScheme schemeWindow(QPalette::Active, KColorScheme::Window); - KColorScheme schemeSelection(QPalette::Active, KColorScheme::Selection); - KColorScheme schemeTooltip(QPalette::Active, KColorScheme::Tooltip); - QColor tmp0( schemeView.background().color() ); - QColor tmp1( schemeSelection.background().color() ); - QColor tmp2( schemeView.background(KColorScheme::AlternateBackground).color() ); - // using KColorUtils::shade wasn't working really well - qreal bgLuma = KColorUtils::luma( tmp0 ); - QColor tmp3( KColorUtils::tint(tmp0, schemeView.decoration(KColorScheme::HoverColor).color()) ); - QColor tmp4( KColorUtils::shade( tmp0, bgLuma > 0.3 ? -0.15 : 0.03 ) ); - QColor tmp5( KColorUtils::shade( tmp0, bgLuma > 0.7 ? -0.35 : 0.3 ) ); - QColor tmp6( schemeWindow.background().color() ); - QColor tmp7( schemeWindow.foreground().color() ); - QColor tmp8( schemeView.foreground(KColorScheme::NegativeText).color() ); - - m_backgroundColor = config.readEntry("Color Background", tmp0); - m_backgroundColorSet = true; - m_selectionColor = config.readEntry("Color Selection", tmp1); - m_selectionColorSet = true; - m_highlightedLineColor = config.readEntry("Color Highlighted Line", tmp2); - m_highlightedLineColorSet = true; - m_highlightedBracketColor = config.readEntry("Color Highlighted Bracket", tmp3); - m_highlightedBracketColorSet = true; - m_wordWrapMarkerColor = config.readEntry("Color Word Wrap Marker", tmp4); - m_wordWrapMarkerColorSet = true; - m_tabMarkerColor = config.readEntry("Color Tab Marker", tmp5); - m_tabMarkerColorSet = true; - m_iconBarColor = config.readEntry("Color Icon Bar", tmp6); - m_iconBarColorSet = true; - m_lineNumberColor = config.readEntry("Color Line Number", tmp7); - m_lineNumberColorSet = true; - m_spellingMistakeLineColor = config.readEntry("Color Spelling Mistake Line", tmp8); - m_spellingMistakeLineColorSet = true; - - // same std colors like in KateDocument::markColor - QColor mark[7]; - mark[0] = Qt::blue; - mark[1] = Qt::red; - mark[2] = Qt::yellow; - mark[3] = Qt::magenta; - mark[4] = Qt::gray; - mark[5] = Qt::green; - mark[6] = Qt::red; - - for (int i = 1; i <= KTextEditor::MarkInterface::reservedMarkersCount(); i++) { - QColor col = config.readEntry(QString("Color MarkType%1").arg(i), mark[i - 1]); - int index = i-1; - m_lineMarkerColorSet[index] = true; - m_lineMarkerColor[index] = col; - } - - QFont f (KGlobalSettings::fixedFont()); - - m_font = config.readEntry("Font", f); - m_fontMetrics = QFontMetrics(m_font); - m_fontSet = true; - - m_templateBackgroundColor=config.readEntry(QString("Color Template Background"), - schemeTooltip.background(KColorScheme::NormalBackground).color()); - - m_templateEditablePlaceholderColor = config.readEntry(QString("Color Template Editable Placeholder"), - schemeTooltip.background(KColorScheme::NeutralBackground).color()); - - m_templateFocusedEditablePlaceholderColor=config.readEntry(QString("Color Template Focused Editable Placeholder"), - schemeTooltip.background(KColorScheme::PositiveBackground).color()); - - m_templateNotEditablePlaceholderColor=config.readEntry(QString("Color Template Not Editable Placeholder"), - schemeTooltip.background(KColorScheme::NegativeBackground).color()); - - m_templateColorsSet=true; -} - -const QFont& KateRendererConfig::font() const -{ - if (m_fontSet || isGlobal()) - return m_font; - - return s_global->font(); -} - -const QFontMetrics& KateRendererConfig::fontMetrics() const -{ - if (m_fontSet || isGlobal()) - return m_fontMetrics; - - return s_global->fontMetrics(); -} - -void KateRendererConfig::setFont(const QFont &font) -{ - configStart (); - - m_fontSet = true; - m_font = font; - m_fontMetrics = QFontMetrics(m_font); - - configEnd (); -} - -bool KateRendererConfig::wordWrapMarker () const -{ - if (m_wordWrapMarkerSet || isGlobal()) - return m_wordWrapMarker; - - return s_global->wordWrapMarker(); -} - -void KateRendererConfig::setWordWrapMarker (bool on) -{ - configStart (); - - m_wordWrapMarkerSet = true; - m_wordWrapMarker = on; - - configEnd (); -} - -const QColor& KateRendererConfig::backgroundColor() const -{ - if (m_backgroundColorSet || isGlobal()) - return m_backgroundColor; - - return s_global->backgroundColor(); -} - -void KateRendererConfig::setBackgroundColor (const QColor &col) -{ - configStart (); - - m_backgroundColorSet = true; - m_backgroundColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::selectionColor() const -{ - if (m_selectionColorSet || isGlobal()) - return m_selectionColor; - - return s_global->selectionColor(); -} - -void KateRendererConfig::setSelectionColor (const QColor &col) -{ - configStart (); - - m_selectionColorSet = true; - m_selectionColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::highlightedLineColor() const -{ - if (m_highlightedLineColorSet || isGlobal()) - return m_highlightedLineColor; - - return s_global->highlightedLineColor(); -} - -void KateRendererConfig::setHighlightedLineColor (const QColor &col) -{ - configStart (); - - m_highlightedLineColorSet = true; - m_highlightedLineColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::lineMarkerColor(KTextEditor::MarkInterface::MarkTypes type) const -{ - int index = 0; - if (type > 0) { while((type >> index++) ^ 1) {} } - index -= 1; - - if ( index < 0 || index >= KTextEditor::MarkInterface::reservedMarkersCount() ) - { - static QColor dummy; - return dummy; - } - - if (m_lineMarkerColorSet[index] || isGlobal()) - return m_lineMarkerColor[index]; - - return s_global->lineMarkerColor( type ); -} - -void KateRendererConfig::setLineMarkerColor (const QColor &col, KTextEditor::MarkInterface::MarkTypes type) -{ - int index = static_cast( log(static_cast(type)) / log(2.0) ); - Q_ASSERT( index >= 0 && index < KTextEditor::MarkInterface::reservedMarkersCount() ); - configStart (); - - m_lineMarkerColorSet[index] = true; - m_lineMarkerColor[index] = col; - - configEnd (); -} - -const QColor& KateRendererConfig::highlightedBracketColor() const -{ - if (m_highlightedBracketColorSet || isGlobal()) - return m_highlightedBracketColor; - - return s_global->highlightedBracketColor(); -} - -void KateRendererConfig::setHighlightedBracketColor (const QColor &col) -{ - configStart (); - - m_highlightedBracketColorSet = true; - m_highlightedBracketColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::wordWrapMarkerColor() const -{ - if (m_wordWrapMarkerColorSet || isGlobal()) - return m_wordWrapMarkerColor; - - return s_global->wordWrapMarkerColor(); -} - -void KateRendererConfig::setWordWrapMarkerColor (const QColor &col) -{ - configStart (); - - m_wordWrapMarkerColorSet = true; - m_wordWrapMarkerColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::tabMarkerColor() const -{ - if (m_tabMarkerColorSet || isGlobal()) - return m_tabMarkerColor; - - return s_global->tabMarkerColor(); -} - -void KateRendererConfig::setTabMarkerColor (const QColor &col) -{ - configStart (); - - m_tabMarkerColorSet = true; - m_tabMarkerColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::iconBarColor() const -{ - if (m_iconBarColorSet || isGlobal()) - return m_iconBarColor; - - return s_global->iconBarColor(); -} - -void KateRendererConfig::setIconBarColor (const QColor &col) -{ - configStart (); - - m_iconBarColorSet = true; - m_iconBarColor = col; - - configEnd (); -} - - -const QColor &KateRendererConfig::templateBackgroundColor() const { - if (m_templateColorsSet || isGlobal()) - return m_templateBackgroundColor; - - return s_global->templateBackgroundColor(); -} -const QColor &KateRendererConfig::templateEditablePlaceholderColor() const { - if (m_templateColorsSet || isGlobal()) - return m_templateEditablePlaceholderColor; - - return s_global->templateEditablePlaceholderColor(); -} -const QColor &KateRendererConfig::templateFocusedEditablePlaceholderColor() const { - if (m_templateColorsSet || isGlobal()) - return m_templateFocusedEditablePlaceholderColor; - - return s_global->templateFocusedEditablePlaceholderColor(); -} -const QColor &KateRendererConfig::templateNotEditablePlaceholderColor() const { - if (m_templateColorsSet || isGlobal()) - return m_templateNotEditablePlaceholderColor; - - return s_global->templateNotEditablePlaceholderColor(); -} - - -const QColor& KateRendererConfig::lineNumberColor() const -{ - if (m_lineNumberColorSet || isGlobal()) - return m_lineNumberColor; - - return s_global->lineNumberColor(); -} - -void KateRendererConfig::setLineNumberColor (const QColor &col) -{ - configStart (); - - m_lineNumberColorSet = true; - m_lineNumberColor = col; - - configEnd (); -} - -const QColor& KateRendererConfig::spellingMistakeLineColor() const -{ - if (m_spellingMistakeLineColorSet || isGlobal()) - return m_spellingMistakeLineColor; - - return s_global->spellingMistakeLineColor(); -} - -void KateRendererConfig::setSpellingMistakeKineColor (const QColor &col) -{ - configStart (); - - m_spellingMistakeLineColorSet = true; - m_spellingMistakeLineColor = col; - - configEnd (); -} - -bool KateRendererConfig::showIndentationLines () const -{ - if (m_showIndentationLinesSet || isGlobal()) - return m_showIndentationLines; - - return s_global->showIndentationLines(); -} - -void KateRendererConfig::setShowIndentationLines (bool on) -{ - configStart (); - - m_showIndentationLinesSet = true; - m_showIndentationLines = on; - - configEnd (); -} - -bool KateRendererConfig::showWholeBracketExpression () const -{ - if (m_showWholeBracketExpressionSet || isGlobal()) - return m_showWholeBracketExpression; - - return s_global->showWholeBracketExpression(); -} - -void KateRendererConfig::setShowWholeBracketExpression (bool on) -{ - configStart (); - - m_showWholeBracketExpressionSet = true; - m_showWholeBracketExpression = on; - - configEnd (); -} - -//END - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateconfig.h b/part/utils/kateconfig.h deleted file mode 100644 index 227fd37..0000000 --- a/part/utils/kateconfig.h +++ /dev/null @@ -1,719 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2003 Christoph Cullmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_CONFIG_H__ -#define __KATE_CONFIG_H__ - -#include "katepartprivate_export.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -class KConfigGroup; -class KateView; -class KateDocument; -class KateRenderer; - -class KConfig; - -class QTextCodec; - - -/** - * Base Class for the Kate Config Classes - */ -class KateConfig -{ - public: - /** - * Default Constructor - */ - KateConfig (); - - /** - * Virtual Destructor - */ - virtual ~KateConfig (); - - public: - /** - * start some config changes - * this method is needed to init some kind of transaction - * for config changes, update will only be done once, at - * configEnd() call - */ - void configStart (); - - /** - * end a config change transaction, update the concerned - * documents/views/renderers - */ - void configEnd (); - - protected: - /** - * do the real update - */ - virtual void updateConfig () = 0; - - private: - /** - * recursion depth - */ - uint configSessionNumber; - - /** - * is a config session running - */ - bool configIsRunning; -}; - -class KATEPART_TESTS_EXPORT KateGlobalConfig : public KateConfig -{ - private: - friend class KateGlobal; - - /** - * only used in KateGlobal for the static global fallback !!! - */ - KateGlobalConfig (); - - /** - * Destructor - */ - ~KateGlobalConfig (); - - public: - static KateGlobalConfig *global () { return s_global; } - - public: - /** - * Read config from object - */ - void readConfig (const KConfigGroup &config); - - /** - * Write config to object - */ - void writeConfig (KConfigGroup &config); - - protected: - void updateConfig (); - - public: - KEncodingProber::ProberType proberType () const - { - return m_proberType; - } - - void setProberType (KEncodingProber::ProberType proberType); - - QTextCodec *fallbackCodec () const; - const QString &fallbackEncoding () const; - bool setFallbackEncoding (const QString &encoding); - - private: - KEncodingProber::ProberType m_proberType; - QString m_fallbackEncoding; - - private: - static KateGlobalConfig *s_global; -}; - -class KATEPART_TESTS_EXPORT KateDocumentConfig : public KateConfig -{ - private: - friend class KateGlobal; - - KateDocumentConfig (); - - public: - KateDocumentConfig (const KConfigGroup &cg); - - /** - * Construct a DocumentConfig - */ - KateDocumentConfig (KateDocument *doc); - - /** - * Cu DocumentConfig - */ - ~KateDocumentConfig (); - - inline static KateDocumentConfig *global () { return s_global; } - - inline bool isGlobal () const { return (this == global()); } - - public: - /** - * Read config from object - */ - void readConfig (const KConfigGroup &config); - - /** - * Write config to object - */ - void writeConfig (KConfigGroup &config); - - protected: - void updateConfig (); - - public: - int tabWidth () const; - void setTabWidth (int tabWidth); - - int indentationWidth () const; - void setIndentationWidth (int indentationWidth); - - const QString &indentationMode () const; - void setIndentationMode (const QString &identationMode); - - enum TabHandling - { - tabInsertsTab = 0, - tabIndents = 1, - tabSmart = 2 //!< indents in leading space, otherwise inserts tab - }; - - uint tabHandling () const; - void setTabHandling (uint tabHandling); - - bool wordWrap () const; - void setWordWrap (bool on); - - unsigned int wordWrapAt () const; - void setWordWrapAt (unsigned int col); - - bool pageUpDownMovesCursor () const; - void setPageUpDownMovesCursor (bool on); - - void setKeepExtraSpaces (bool on); - bool keepExtraSpaces () const; - - void setIndentPastedText (bool on); - bool indentPastedText () const; - - void setBackspaceIndents (bool on); - bool backspaceIndents () const; - - void setSmartHome (bool on); - bool smartHome () const; - - void setWrapCursor (bool on); - bool wrapCursor () const; - - void setAutoBrackets (bool on); - bool autoBrackets () const; - - void setShowTabs (bool on); - bool showTabs() const; - - void setShowSpaces (bool on); - bool showSpaces() const; - - void setReplaceTabsDyn (bool on); - bool replaceTabsDyn() const; - - void setRemoveTrailingDyn (bool on); - bool removeTrailingDyn() const; - - void setRemoveSpaces (bool on); - bool removeSpaces () const; - - void setOvr (bool on); - bool ovr () const; - - void setTabIndents (bool on); - bool tabIndentsEnabled () const; - - QTextCodec *codec () const; - const QString &encoding () const; - bool setEncoding (const QString &encoding); - bool isSetEncoding () const; - - enum Eol - { - eolUnix = 0, - eolDos = 1, - eolMac = 2 - }; - - int eol () const; - QString eolString (); - - void setEol (int mode); - - bool bom () const; - void setBom(bool bom); - - bool allowEolDetection () const; - void setAllowEolDetection (bool on); - - bool allowSimpleMode () const; - void setAllowSimpleMode (bool on); - - enum BackupFlags - { - LocalFiles=1, - RemoteFiles=2 - }; - - uint backupFlags () const; - void setBackupFlags (uint flags); - - const QString &backupPrefix () const; - void setBackupPrefix (const QString &prefix); - - const QString &backupSuffix () const; - void setBackupSuffix (const QString &suffix); - - bool swapFileNoSync() const; - void setSwapFileNoSync(bool on); - - /** - * Should Kate Part search for dir wide config file - * and if, how depth? - * @return search depth (< 0 no search) - */ - int searchDirConfigDepth () const; - - void setSearchDirConfigDepth (int depth); - - bool onTheFlySpellCheck() const; - void setOnTheFlySpellCheck(bool on); - - - private: - QString m_indentationMode; - int m_indentationWidth; - int m_tabWidth; - uint m_tabHandling; - uint m_configFlags; - int m_wordWrapAt; - bool m_wordWrap; - bool m_pageUpDownMovesCursor; - bool m_allowEolDetection; - bool m_allowSimpleMode; - int m_eol; - bool m_bom; - uint m_backupFlags; - int m_searchDirConfigDepth; - QString m_encoding; - QString m_backupPrefix; - QString m_backupSuffix; - bool m_swapFileNoSync; - bool m_onTheFlySpellCheck; - - bool m_tabWidthSet : 1; - bool m_indentationWidthSet : 1; - bool m_indentationModeSet : 1; - bool m_wordWrapSet : 1; - bool m_wordWrapAtSet : 1; - bool m_pageUpDownMovesCursorSet : 1; - - bool m_keepExtraSpacesSet : 1; - bool m_keepExtraSpaces : 1; - bool m_indentPastedTextSet : 1; - bool m_indentPastedText : 1; - bool m_backspaceIndentsSet : 1; - bool m_backspaceIndents : 1; - bool m_smartHomeSet : 1; - bool m_smartHome : 1; - bool m_wrapCursorSet : 1; - bool m_wrapCursor : 1; - bool m_autoBracketsSet : 1; - bool m_autoBrackets : 1; - bool m_showTabsSet : 1; - bool m_showTabs : 1; - bool m_showSpacesSet : 1; - bool m_showSpaces : 1; - bool m_replaceTabsDynSet : 1; - bool m_replaceTabsDyn : 1; - bool m_removeTrailingDynSet : 1; - bool m_removeTrailingDyn : 1; - bool m_removeSpacesSet : 1; - bool m_removeSpaces : 1; - bool m_overwiteModeSet : 1; - bool m_overwiteMode : 1; - bool m_tabIndentsSet : 1; - bool m_tabIndents : 1; - - bool m_encodingSet : 1; - bool m_eolSet : 1; - bool m_bomSet :1; - bool m_allowEolDetectionSet : 1; - bool m_allowSimpleModeSet : 1; - bool m_backupFlagsSet : 1; - bool m_searchDirConfigDepthSet : 1; - bool m_backupPrefixSet : 1; - bool m_backupSuffixSet : 1; - bool m_swapFileNoSyncSet : 1; - bool m_onTheFlySpellCheckSet : 1; - - private: - static KateDocumentConfig *s_global; - KateDocument *m_doc; -}; - -class KATEPART_TESTS_EXPORT KateViewConfig : public KateConfig -{ - private: - friend class KateGlobal; - - /** - * only used in KateGlobal for the static global fallback !!! - */ - KateViewConfig (); - - public: - /** - * Construct a DocumentConfig - */ - explicit KateViewConfig (KateView *view); - - /** - * Cu DocumentConfig - */ - ~KateViewConfig (); - - inline static KateViewConfig *global () { return s_global; } - - inline bool isGlobal () const { return (this == global()); } - - public: - /** - * Read config from object - */ - void readConfig (const KConfigGroup &config); - - /** - * Write config to object - */ - void writeConfig (KConfigGroup &config); - - protected: - void updateConfig (); - - public: - bool dynWordWrap () const; - void setDynWordWrap (bool wrap); - - int dynWordWrapIndicators () const; - void setDynWordWrapIndicators (int mode); - - int dynWordWrapAlignIndent () const; - void setDynWordWrapAlignIndent (int indent); - - bool lineNumbers () const; - void setLineNumbers (bool on); - - bool scrollBarMarks () const; - void setScrollBarMarks (bool on); - - bool iconBar () const; - void setIconBar (bool on); - - bool foldingBar () const; - void setFoldingBar (bool on); - - int bookmarkSort () const; - void setBookmarkSort (int mode); - - int autoCenterLines() const; - void setAutoCenterLines (int lines); - - enum SearchFlags { - IncMatchCase = 1 << 0, - IncHighlightAll = 1 << 1, - IncFromCursor = 1 << 2, - PowerMatchCase = 1 << 3, - PowerHighlightAll = 1 << 4, - PowerFromCursor = 1 << 5, - // PowerSelectionOnly = 1 << 6, Better not save to file // Sebastian - PowerModePlainText = 1 << 7, - PowerModeWholeWords = 1 << 8, - PowerModeEscapeSequences = 1 << 9, - PowerModeRegularExpression = 1 << 10, - PowerUsePlaceholders = 1 << 11 - }; - - long searchFlags () const; - void setSearchFlags (long flags); - - int maxHistorySize() const; - - QStringListModel *patternHistoryModel(); - QStringListModel *replacementHistoryModel(); - - uint defaultMarkType () const; - void setDefaultMarkType (uint type); - - bool allowMarkMenu () const; - void setAllowMarkMenu (bool allow); - - bool persistentSelection () const; - void setPersistentSelection (bool on); - - bool viInputMode () const; - void setViInputMode (bool on); - - bool viInputModeStealKeys () const; - void setViInputModeStealKeys (bool on); - - bool viInputModeHideStatusBar () const; - void setViInputModeHideStatusBar (bool on); - - // Do we still need the enum and related functions below? - enum TextToSearch - { - Nowhere = 0, - SelectionOnly = 1, - SelectionWord = 2, - WordOnly = 3, - WordSelection = 4 - }; - - bool automaticCompletionInvocation () const; - void setAutomaticCompletionInvocation (bool on); - - bool wordCompletion () const; - void setWordCompletion (bool on); - - int wordCompletionMinimalWordLength () const; - void setWordCompletionMinimalWordLength (int length); - - bool smartCopyCut() const; - void setSmartCopyCut(bool on); - - bool scrollPastEnd() const; - void setScrollPastEnd(bool on); - - private: - bool m_dynWordWrap; - int m_dynWordWrapIndicators; - int m_dynWordWrapAlignIndent; - bool m_lineNumbers; - bool m_scrollBarMarks; - bool m_iconBar; - bool m_foldingBar; - int m_bookmarkSort; - int m_autoCenterLines; - long m_searchFlags; - int m_maxHistorySize; - QStringListModel m_patternHistoryModel; - QStringListModel m_replacementHistoryModel; - uint m_defaultMarkType; - bool m_persistentSelection; - bool m_viInputMode; - bool m_viInputModeStealKeys; - bool m_viInputModeHideStatusBar; - bool m_automaticCompletionInvocation; - bool m_wordCompletion; - int m_wordCompletionMinimalWordLength; - bool m_smartCopyCut; - bool m_scrollPastEnd; - - bool m_dynWordWrapSet : 1; - bool m_dynWordWrapIndicatorsSet : 1; - bool m_dynWordWrapAlignIndentSet : 1; - bool m_lineNumbersSet : 1; - bool m_scrollBarMarksSet : 1; - bool m_iconBarSet : 1; - bool m_foldingBarSet : 1; - bool m_bookmarkSortSet : 1; - bool m_autoCenterLinesSet : 1; - bool m_searchFlagsSet : 1; - bool m_defaultMarkTypeSet : 1; - bool m_persistentSelectionSet : 1; - bool m_viInputModeSet : 1; - bool m_viInputModeStealKeysSet : 1; - bool m_viInputModeHideStatusBarSet : 1; - bool m_automaticCompletionInvocationSet : 1; - bool m_wordCompletionSet : 1; - bool m_wordCompletionMinimalWordLengthSet : 1; - bool m_smartCopyCutSet : 1; - bool m_scrollPastEndSet : 1; - bool m_allowMarkMenu : 1; - - private: - static KateViewConfig *s_global; - KateView *m_view; -}; - -class KateRendererConfig : public KateConfig -{ - private: - friend class KateGlobal; - - /** - * only used in KateGlobal for the static global fallback !!! - */ - KateRendererConfig (); - - - public: - /** - * Construct a DocumentConfig - */ - KateRendererConfig (KateRenderer *renderer); - - /** - * Cu DocumentConfig - */ - ~KateRendererConfig (); - - inline static KateRendererConfig *global () { return s_global; } - - inline bool isGlobal () const { return (this == global()); } - - public: - /** - * Read config from object - */ - void readConfig (const KConfigGroup &config); - - /** - * Write config to object - */ - void writeConfig (KConfigGroup &config); - - protected: - void updateConfig (); - - public: - const QString &schema () const; - void setSchema (const QString &schema); - /** - * Reload the schema from the schema manager. - * For the global instance, have all other instances reload. - * Used by the schema config page to apply changes. - */ - void reloadSchema(); - - const QFont& font() const; - const QFontMetrics& fontMetrics() const; - void setFont(const QFont &font); - - bool wordWrapMarker () const; - void setWordWrapMarker (bool on); - - const QColor& backgroundColor() const; - void setBackgroundColor (const QColor &col); - - const QColor& selectionColor() const; - void setSelectionColor (const QColor &col); - - const QColor& highlightedLineColor() const; - void setHighlightedLineColor (const QColor &col); - - const QColor& lineMarkerColor(KTextEditor::MarkInterface::MarkTypes type = KTextEditor::MarkInterface::markType01) const; // markType01 == Bookmark - void setLineMarkerColor (const QColor &col, KTextEditor::MarkInterface::MarkTypes type = KTextEditor::MarkInterface::markType01); - - const QColor& highlightedBracketColor() const; - void setHighlightedBracketColor (const QColor &col); - - const QColor& wordWrapMarkerColor() const; - void setWordWrapMarkerColor (const QColor &col); - - const QColor& tabMarkerColor() const; - void setTabMarkerColor (const QColor &col); - - const QColor& iconBarColor() const; - void setIconBarColor (const QColor &col); - - // the line number color is used for the line numbers on the left bar and - // for vertical separator lines and for code folding lines. - const QColor& lineNumberColor() const; - void setLineNumberColor (const QColor &col); - - const QColor& spellingMistakeLineColor() const; - void setSpellingMistakeKineColor (const QColor &col); - - bool showIndentationLines () const; - void setShowIndentationLines (bool on); - - bool showWholeBracketExpression () const; - void setShowWholeBracketExpression (bool on); - - const QColor &templateBackgroundColor() const; - const QColor &templateEditablePlaceholderColor() const; - const QColor &templateFocusedEditablePlaceholderColor() const; - const QColor &templateNotEditablePlaceholderColor() const; - - - private: - /** - * Read the schema properties from the config file. - */ - void setSchemaInternal(const QString &schema); - - QString m_schema; - QFont m_font; - QFontMetrics m_fontMetrics; - bool m_wordWrapMarker; - bool m_showIndentationLines; - bool m_showWholeBracketExpression; - QColor m_backgroundColor; - QColor m_selectionColor; - QColor m_highlightedLineColor; - QColor m_highlightedBracketColor; - QColor m_wordWrapMarkerColor; - QColor m_tabMarkerColor; - QColor m_iconBarColor; - QColor m_lineNumberColor; - QColor m_spellingMistakeLineColor; - QVector m_lineMarkerColor; - - QColor m_templateBackgroundColor; - QColor m_templateEditablePlaceholderColor; - QColor m_templateFocusedEditablePlaceholderColor; - QColor m_templateNotEditablePlaceholderColor; - - - bool m_schemaSet : 1; - bool m_fontSet : 1; - bool m_wordWrapMarkerSet : 1; - bool m_showIndentationLinesSet : 1; - bool m_showWholeBracketExpressionSet : 1; - bool m_backgroundColorSet : 1; - bool m_selectionColorSet : 1; - bool m_highlightedLineColorSet : 1; - bool m_highlightedBracketColorSet : 1; - bool m_wordWrapMarkerColorSet : 1; - bool m_tabMarkerColorSet : 1; - bool m_iconBarColorSet : 1; - bool m_lineNumberColorSet : 1; - bool m_spellingMistakeLineColorSet : 1; - bool m_templateColorsSet : 1; - QBitArray m_lineMarkerColorSet; - - private: - static KateRendererConfig *s_global; - KateRenderer *m_renderer; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katefactory.cpp b/part/utils/katefactory.cpp deleted file mode 100644 index 832152f..0000000 --- a/part/utils/katefactory.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateglobal.h" -#include "katedocument.h" - -#include - -/** - * wrapper factory to be sure nobody external deletes our kateglobal object - * each instance will just increment the reference counter of our internal - * super private global instance ;) - */ -class KateFactory : public KTextEditor::Factory -{ - public: - /** - * constructor, ref the editor, too keep it alive - * @param parent parent object - * @param name name of factory - */ - KateFactory ( QObject *parent = 0 ) - : KTextEditor::Factory (parent) - { - KateGlobal::incRef (); - } - - /** - * destructor, release editor - */ - virtual ~KateFactory () - { - KateGlobal::decRef (); - } - - KTextEditor::Editor *editor () { return KateGlobal::self(); } - - /** - * reimplemented create object method - * @param parentWidget parent widget - * @param parent QObject parent - * @param args additional arguments - * @return constructed part object - */ - KParts::Part *createPartObject ( QWidget *parentWidget, QObject *parent, const char *_classname, const QStringList & ) - { - QByteArray classname( _classname ); - - // default to the kparts::* behavior of having one single widget() if the user don't requested a pure document - bool bWantSingleView = ( classname != "KTextEditor::Document" ); - - // does user want browserview? - bool bWantBrowserView = ( classname == "Browser/View" ); - - // should we be readonly? - bool bWantReadOnly = (bWantBrowserView || ( classname == "KParts::ReadOnlyPart" )); - - // set simple mode on for read-only part per default - KateGlobal::self ()->setSimpleMode (bWantReadOnly); - - KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, parent); - part->setReadWrite( !bWantReadOnly ); - - return part; - } -}; - -K_EXPORT_PLUGIN( KateFactory ) - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateglobal.cpp b/part/utils/kateglobal.cpp deleted file mode 100644 index ad14e15..0000000 --- a/part/utils/kateglobal.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2009 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateglobal.h" -#include "kateglobal.moc" - -#include "katedocument.h" -#include "kateview.h" -#include "katerenderer.h" -#include "katecmds.h" -#include "katemodemanager.h" -#include "kateschema.h" -#include "kateconfig.h" -#include "katescriptmanager.h" -#include "katecmd.h" -#include "katebuffer.h" -#include "katepartpluginmanager.h" -#include "kateviglobal.h" -#include "katewordcompletion.h" -#include "spellcheck/spellcheck.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -KateGlobal *KateGlobal::s_self = 0; - -int KateGlobal::s_ref = 0; - -QString KateGlobal::katePartVersion() -{ - return QString("3.6"); -} - -KateGlobal::KateGlobal () - : KTextEditor::Editor (0) - , m_aboutData ("katepart", 0, ki18n("Kate Part"), katePartVersion().toLatin1(), - ki18n( "Embeddable editor component" ), KAboutData::License_LGPL_V2, - ki18n( "(c) 2000-2009 The Kate Authors" ), KLocalizedString(), "http://www.kate-editor.org") - , m_componentData (&m_aboutData) -{ - // set s_self - s_self = this; - - // load the kate part translation catalog - KGlobal::locale()->insertCatalog("katepart4"); - - // - // fill about data - // - m_aboutData.setProgramIconName("preferences-plugin"); - m_aboutData.addAuthor (ki18n("Christoph Cullmann"), ki18n("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de"); - m_aboutData.addAuthor (ki18n("Anders Lund"), ki18n("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk"); - m_aboutData.addAuthor (ki18n("Joseph Wenninger"), ki18n("Core Developer"), "jowenn@kde.org","http://stud3.tuwien.ac.at/~e9925371"); - m_aboutData.addAuthor (ki18n("Hamish Rodda"), ki18n("Core Developer"), "rodda@kde.org"); - m_aboutData.addAuthor (ki18n("Dominik Haumann"), ki18n("Core Developer"), "dhaumann@kde.de"); - m_aboutData.addAuthor (ki18n("Erlend Hamberg"), ki18n("Vi Input Mode"), "ehamberg@gmail.com", "http://hamberg.no/erlend"); - m_aboutData.addAuthor (ki18n("Bernhard Beschow"), ki18n("Developer"), "bbeschow@cs.tu-berlin.de", "https://user.cs.tu-berlin.de/~bbeschow"); - m_aboutData.addAuthor (ki18n("Waldo Bastian"), ki18n( "The cool buffersystem" ), "bastian@kde.org" ); - m_aboutData.addAuthor (ki18n("Charles Samuels"), ki18n("The Editing Commands"), "charles@kde.org"); - m_aboutData.addAuthor (ki18n("Matt Newell"), ki18n("Testing, ..."), "newellm@proaxis.com"); - m_aboutData.addAuthor (ki18n("Michael Bartl"), ki18n("Former Core Developer"), "michael.bartl1@chello.at"); - m_aboutData.addAuthor (ki18n("Michael McCallum"), ki18n("Core Developer"), "gholam@xtra.co.nz"); - m_aboutData.addAuthor (ki18n("Jochen Wilhemly"), ki18n( "KWrite Author" ), "digisnap@cs.tu-berlin.de" ); - m_aboutData.addAuthor (ki18n("Michael Koch"), ki18n("KWrite port to KParts"), "koch@kde.org"); - m_aboutData.addAuthor (ki18n("Christian Gebauer"), KLocalizedString(), "gebauer@kde.org" ); - m_aboutData.addAuthor (ki18n("Simon Hausmann"), KLocalizedString(), "hausmann@kde.org" ); - m_aboutData.addAuthor (ki18n("Glen Parker"), ki18n("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com"); - m_aboutData.addAuthor (ki18n("Scott Manson"), ki18n("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net"); - m_aboutData.addAuthor (ki18n("John Firebaugh"), ki18n("Patches and more"), "jfirebaugh@kde.org"); - m_aboutData.addAuthor (ki18n("Andreas Kling"), ki18n("Developer"), "kling@impul.se"); - m_aboutData.addAuthor (ki18n("Mirko Stocker"), ki18n("Various bugfixes"), "me@misto.ch", "http://misto.ch/"); - m_aboutData.addAuthor (ki18n("Matthew Woehlke"), ki18n("Selection, KColorScheme integration"), "mw_triad@users.sourceforge.net"); - m_aboutData.addAuthor (ki18n("Sebastian Pipping"), ki18n("Search bar back- and front-end"), "webmaster@hartwork.org", "http://www.hartwork.org/"); - m_aboutData.addAuthor (ki18n("Michel Ludwig"), ki18n("On-the-fly spell checking"), "michel.ludwig@kdemail.net"); - - m_aboutData.addCredit (ki18n("Matteo Merli"), ki18n("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it"); - m_aboutData.addCredit (ki18n("Rocky Scaletta"), ki18n("Highlighting for VHDL"), "rocky@purdue.edu"); - m_aboutData.addCredit (ki18n("Yury Lebedev"), ki18n("Highlighting for SQL"),""); - m_aboutData.addCredit (ki18n("Chris Ross"), ki18n("Highlighting for Ferite"),""); - m_aboutData.addCredit (ki18n("Nick Roux"), ki18n("Highlighting for ILERPG"),""); - m_aboutData.addCredit (ki18n("Carsten Niehaus"), ki18n("Highlighting for LaTeX"),""); - m_aboutData.addCredit (ki18n("Per Wigren"), ki18n("Highlighting for Makefiles, Python"),""); - m_aboutData.addCredit (ki18n("Jan Fritz"), ki18n("Highlighting for Python"),""); - m_aboutData.addCredit (ki18n("Daniel Naber")); - m_aboutData.addCredit (ki18n("Roland Pabel"), ki18n("Highlighting for Scheme"),""); - m_aboutData.addCredit (ki18n("Cristi Dumitrescu"), ki18n("PHP Keyword/Datatype list"),""); - m_aboutData.addCredit (ki18n("Carsten Pfeiffer"), ki18n("Very nice help"), ""); - m_aboutData.addCredit (ki18n("Bruno Massa"), ki18n("Highlighting for Lua"), "brmassa@gmail.com"); - - m_aboutData.addCredit (ki18n("All people who have contributed and I have forgotten to mention")); - - m_aboutData.setTranslator(ki18nc("NAME OF TRANSLATORS","Your names"), ki18nc("EMAIL OF TRANSLATORS","Your emails")); - - // - // dir watch - // - m_dirWatch = new KDirWatch (); - - // - // command manager - // - m_cmdManager = new KateCmd (); - - // - // hl manager - // - m_hlManager = new KateHlManager (); - - // - // mode man - // - m_modeManager = new KateModeManager (); - - // - // schema man - // - m_schemaManager = new KateSchemaManager (); - - // - // vi input mode global - // - m_viInputModeGlobal = new KateViGlobal (); - - // - // spell check manager - // - m_spellCheckManager = new KateSpellCheckManager (); - - // config objects - m_globalConfig = new KateGlobalConfig (); - m_documentConfig = new KateDocumentConfig (); - m_viewConfig = new KateViewConfig (); - m_rendererConfig = new KateRendererConfig (); - - // create script manager (search scripts) - m_scriptManager = new KateScriptManager (); - - // - // plugin manager - // - m_pluginManager = new KatePartPluginManager (); - - // - // init the cmds - // - m_cmds.push_back (new KateCommands::CoreCommands()); - m_cmds.push_back (new KateCommands::ViCommands()); - m_cmds.push_back (new KateCommands::AppCommands()); - m_cmds.push_back (new KateCommands::SedReplace ()); - m_cmds.push_back (new KateCommands::Character ()); - m_cmds.push_back (new KateCommands::Date ()); - - for ( QList::iterator it = m_cmds.begin(); it != m_cmds.end(); ++it ) - m_cmdManager->registerCommand (*it); - - // global word completion model - m_wordCompletionModel = new KateWordCompletionModel (this); -} - -KateGlobal::~KateGlobal() -{ - delete m_pluginManager; - - delete m_globalConfig; - delete m_documentConfig; - delete m_viewConfig; - delete m_rendererConfig; - - delete m_modeManager; - delete m_schemaManager; - - delete m_dirWatch; - - // you too - qDeleteAll (m_cmds); - - // cu managers - delete m_scriptManager; - delete m_hlManager; - delete m_cmdManager; - - delete m_viInputModeGlobal; - delete m_spellCheckManager; - - // cu model - delete m_wordCompletionModel; - - s_self = 0; -} - -KTextEditor::Document *KateGlobal::createDocument ( QObject *parent ) -{ - KateDocument *doc = new KateDocument (false, false, false, 0, parent); - - emit documentCreated (this, doc); - - return doc; -} - -const QList &KateGlobal::documents () -{ - return m_docs; -} - -//BEGIN KTextEditor::Editor config stuff -void KateGlobal::readConfig(KConfig *config) -{ - if( !config ) - config = KGlobal::config().data(); - - KateGlobalConfig::global()->readConfig (KConfigGroup(config, "Kate Part Defaults")); - - KateDocumentConfig::global()->readConfig (KConfigGroup(config, "Kate Document Defaults")); - - KateViewConfig::global()->readConfig (KConfigGroup(config, "Kate View Defaults")); - - KateRendererConfig::global()->readConfig (KConfigGroup(config, "Kate Renderer Defaults")); - - m_viInputModeGlobal->readConfig( KConfigGroup( config, "Kate Vi Input Mode Settings" ) ); -} - -void KateGlobal::writeConfig(KConfig *config) -{ - if( !config ) - config = KGlobal::config().data(); - - KConfigGroup cgGlobal(config, "Kate Part Defaults"); - KateGlobalConfig::global()->writeConfig (cgGlobal); - - KConfigGroup cg(config, "Kate Document Defaults"); - KateDocumentConfig::global()->writeConfig (cg); - - KConfigGroup cgDefault(config, "Kate View Defaults"); - KateViewConfig::global()->writeConfig (cgDefault); - - KConfigGroup cgRenderer(config, "Kate Renderer Defaults"); - KateRendererConfig::global()->writeConfig (cgRenderer); - - KConfigGroup cgViInputMode(config, "Kate Vi Input Mode Settings"); - m_viInputModeGlobal->writeConfig (cgViInputMode); - - config->sync(); -} -//END KTextEditor::Editor config stuff - -bool KateGlobal::configDialogSupported () const -{ - return true; -} - -void KateGlobal::configDialog(QWidget *parent) -{ - QPointer kd = new KPageDialog(parent); - kd->setCaption( i18n("Configure") ); - kd->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Help ); - kd->setFaceType( KPageDialog::List ); - kd->setHelp( QString(), KGlobal::mainComponent().componentName() ); - - QList editorPages; - - for (int i = 0; i < configPages (); ++i) - { - const QString name = configPageName (i); - - QFrame *page = new QFrame(); - - KPageWidgetItem *item = kd->addPage( page, name ); - item->setHeader( configPageFullName (i) ); - item->setIcon( configPageIcon(i) ); - - QVBoxLayout *topLayout = new QVBoxLayout( page ); - topLayout->setMargin( 0 ); - - KTextEditor::ConfigPage *cp = configPage(i, page); - topLayout->addWidget( cp); - editorPages.append (cp); - } - - if (kd->exec() && kd) - { - KateGlobalConfig::global()->configStart (); - KateDocumentConfig::global()->configStart (); - KateViewConfig::global()->configStart (); - KateRendererConfig::global()->configStart (); - - for (int i=0; i < editorPages.count(); ++i) - { - editorPages.at(i)->apply(); - } - - KateGlobalConfig::global()->configEnd (); - KateDocumentConfig::global()->configEnd (); - KateViewConfig::global()->configEnd (); - KateRendererConfig::global()->configEnd (); - - writeConfig (); - } - - delete kd; -} - -int KateGlobal::configPages () const -{ - return 5; -} - -KTextEditor::ConfigPage *KateGlobal::configPage (int number, QWidget *parent) -{ - switch( number ) - { - case 0: - return new KateViewDefaultsConfig (parent); - - case 1: - return new KateSchemaConfigPage (parent); - - case 2: - return new KateEditConfigTab (parent); - - case 3: - return new KateSaveConfigTab (parent); - - case 4: - return new KatePartPluginConfigPage (parent); - - default: - return 0; - } - - return 0; -} - -QString KateGlobal::configPageName (int number) const -{ - switch( number ) - { - case 0: - return i18n ("Appearance"); - - case 1: - return i18n ("Fonts & Colors"); - - case 2: - return i18n ("Editing"); - - case 3: - return i18n("Open/Save"); - - case 4: - return i18n ("Extensions"); - - default: - return QString (""); - } - - return QString (""); -} - -QString KateGlobal::configPageFullName (int number) const -{ - switch( number ) - { - case 0: - return i18n("Appearance"); - - case 1: - return i18n ("Font & Color Schemas"); - - case 2: - return i18n ("Editing Options"); - - case 3: - return i18n("File Opening & Saving"); - - case 4: - return i18n ("Extensions Manager"); - - default: - return QString (""); - } - - return QString (""); -} - -KIcon KateGlobal::configPageIcon (int number) const -{ - switch( number ) - { - case 0: - return KIcon("preferences-desktop-theme"); - - case 1: - return KIcon("preferences-desktop-color"); - - case 2: - return KIcon("accessories-text-editor"); - - case 3: - return KIcon("document-save"); - - case 4: - return KIcon("preferences-plugin"); - - default: - return KIcon("document-properties"); - } - - return KIcon("document-properties"); -} - -KateGlobal *KateGlobal::self () -{ - if (!s_self) { - new KateGlobal (); - } - - return s_self; -} - -void KateGlobal::registerDocument ( KateDocument *doc ) -{ - KateGlobal::incRef (); - m_documents.append( doc ); - m_docs.append (doc); -} - -void KateGlobal::deregisterDocument ( KateDocument *doc ) -{ - m_docs.removeAll (doc); - m_documents.removeAll( doc ); - KateGlobal::decRef (); -} - -void KateGlobal::registerView ( KateView *view ) -{ - KateGlobal::incRef (); - m_views.append( view ); -} - -void KateGlobal::deregisterView ( KateView *view ) -{ - m_views.removeAll( view ); - KateGlobal::decRef (); -} - -//BEGIN command interface -bool KateGlobal::registerCommand (KTextEditor::Command *cmd) -{return m_cmdManager->registerCommand(cmd);} - -bool KateGlobal::unregisterCommand (KTextEditor::Command *cmd) -{return m_cmdManager->unregisterCommand(cmd);} - -KTextEditor::Command *KateGlobal::queryCommand (const QString &cmd) const -{return m_cmdManager->queryCommand(cmd);} - -QList KateGlobal::commands() const -{return m_cmdManager->commands();} - -QStringList KateGlobal::commandList() const -{return m_cmdManager->commandList();} -//END command interface - - -//BEGIN container interface -QObject * KateGlobal::container() -{return m_container.data();} - -void KateGlobal::setContainer( QObject * container ) -{m_container=container;} -//END container interface - - - -KTextEditor::TemplateScript* KateGlobal::registerTemplateScript (QObject* owner, const QString& script) -{ - return scriptManager()->registerTemplateScript(owner, script); -} - -void KateGlobal::unregisterTemplateScript(KTextEditor::TemplateScript* templateScript) -{ - scriptManager()->unregisterTemplateScript(templateScript); -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateglobal.h b/part/utils/kateglobal.h deleted file mode 100644 index 5bf4e4f..0000000 --- a/part/utils/kateglobal.h +++ /dev/null @@ -1,482 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2009 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef __KATE_GLOBAL_H__ -#define __KATE_GLOBAL_H__ - -#include "katepartprivate_export.h" -#include "katescript.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -class KateCmd; -class KateModeManager; -class KateSchemaManager; -class KateGlobalConfig; -class KateDocumentConfig; -class KateViewConfig; -class KateRendererConfig; -class KateDocument; -class KateRenderer; -class KateView; -class KateScriptManager; -class KDirWatch; -class KateHlManager; -class KatePartPluginManager; -class KateSpellCheckManager; -class KateViGlobal; -class KateWordCompletionModel; - -namespace Kate { - class Command; -} - -/** - * KateGlobal - * One instance of this class is hold alive during - * a kate part session, as long as any factory, document - * or view stay around, here is the place to put things - * which are needed and shared by all this objects ;) - */ -class KATEPART_TESTS_EXPORT KateGlobal : public KTextEditor::Editor, public KTextEditor::CommandInterface, public KTextEditor::ContainerInterface, public KTextEditor::TemplateScriptRegistrar -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::CommandInterface) - Q_INTERFACES(KTextEditor::ContainerInterface) - Q_INTERFACES(KTextEditor::TemplateScriptRegistrar) - - // for setDefaultEncoding - friend class KateDocumentConfig; - - private: - /** - * Default constructor, private, as singleton - */ - KateGlobal (); - - public: - /** - * Destructor - */ - ~KateGlobal (); - - /** - * Create a new document object - * @param parent parent object - * @return created KTextEditor::Document - */ - KTextEditor::Document *createDocument ( QObject *parent ); - - /** - * Returns a list of all documents of this editor. - * @return list of all existing documents - */ - const QList &documents (); - - /** - * General Information about this editor - */ - public: - /** - * return the about data - * @return about data of this editor part - */ - const KAboutData* aboutData() const { return &m_aboutData; } - - /** - * Configuration management - */ - public: - /** - * Read editor configuration from given config object - * @param config config object - */ - void readConfig (KConfig *config = 0); - - /** - * Write editor configuration to given config object - * @param config config object - */ - void writeConfig (KConfig *config = 0); - - /** - * Does this editor support a config dialog - * @return does this editor have a config dialog? - */ - bool configDialogSupported () const; - - /** - * Shows a config dialog for the part, changes will be applied - * to the editor, but not saved anywhere automagically, call - * writeConfig to save them - */ - void configDialog (QWidget *parent); - - /** - * Number of available config pages - * If the editor returns a number < 1, it doesn't support this - * and the embedding app should use the configDialog () instead - * @return number of config pages - */ - int configPages () const; - - /** - * returns config page with the given number, - * config pages from 0 to configPages()-1 are available - * if configPages() > 0 - */ - KTextEditor::ConfigPage *configPage (int number, QWidget *parent); - - QString configPageName (int number) const; - - QString configPageFullName (int number) const; - - KIcon configPageIcon (int number) const; - - /** - * Kate Part Internal stuff ;) - */ - public: - /** - * singleton accessor - * @return instance of the factory - */ - static KateGlobal *self (); - - /** - * increment reference counter - */ - static void incRef () { ++s_ref; } - - /** - * decrement reference counter - */ - static void decRef () { if (s_ref > 0) --s_ref; if (s_ref == 0) { delete s_self; s_self = 0L; } } - - /** - * Returns the current version of Kate Part: KDE X.Y.Z contains Kate Part X-1.Y - * @return version of type x.y, e.g. 3.2 - */ - static QString katePartVersion(); - - /** - * public accessor to the instance - * @return instance - */ - const KComponentData &componentData() { return m_componentData; } - - /** - * register document at the factory - * this allows us to loop over all docs for example on config changes - * @param doc document to register - */ - void registerDocument ( KateDocument *doc ); - - /** - * unregister document at the factory - * @param doc document to register - */ - void deregisterDocument ( KateDocument *doc ); - - /** - * register view at the factory - * this allows us to loop over all views for example on config changes - * @param view view to register - */ - void registerView ( KateView *view ); - - /** - * unregister view at the factory - * @param view view to unregister - */ - void deregisterView ( KateView *view ); - - /** - * return a list of all registered docs - * @return all known documents - */ - QList &kateDocuments () { return m_documents; } - - /** - * return a list of all registered views - * @return all known views - */ - QList &views () { return m_views; } - - /** - * global plugin manager - * @return kate part plugin manager - */ - KatePartPluginManager *pluginManager () { return m_pluginManager; } - - /** - * global dirwatch - * @return dirwatch instance - */ - KDirWatch *dirWatch () { return m_dirWatch; } - - /** - * global mode manager - * used to manage the modes centrally - * @return mode manager - */ - KateModeManager *modeManager () { return m_modeManager; } - - /** - * manager for the katepart schemas - * @return schema manager - */ - KateSchemaManager *schemaManager () { return m_schemaManager; } - - /** - * fallback document config - * @return default config for all documents - */ - KateDocumentConfig *documentConfig () { return m_documentConfig; } - - /** - * fallback view config - * @return default config for all views - */ - KateViewConfig *viewConfig () { return m_viewConfig; } - - /** - * fallback renderer config - * @return default config for all renderers - */ - KateRendererConfig *rendererConfig () { return m_rendererConfig; } - - /** - * Global script collection - */ - KateScriptManager *scriptManager () { return m_scriptManager; } - - /** - * hl manager - * @return hl manager - */ - KateHlManager *hlManager () { return m_hlManager; } - - /** - * command manager - * @return command manager - */ - KateCmd *cmdManager () { return m_cmdManager; } - - /** - * vi input mode global - * @return vi input mode global - */ - KateViGlobal *viInputModeGlobal () { return m_viInputModeGlobal; } - - /** - * spell check manager - * @return spell check manager - */ - KateSpellCheckManager *spellCheckManager () { return m_spellCheckManager; } - - /** - * global instance of the simple word completion mode - * @return global instance of the simple word completion mode - */ - KateWordCompletionModel *wordCompletionModel () { return m_wordCompletionModel; } - - /** - * register given command - * this works global, for all documents - * @param cmd command to register - * @return success - */ - bool registerCommand (KTextEditor::Command *cmd); - - /** - * unregister given command - * this works global, for all documents - * @param cmd command to unregister - * @return success - */ - bool unregisterCommand (KTextEditor::Command *cmd); - - /** - * query for command - * @param cmd name of command to query for - * @return found command or 0 - */ - KTextEditor::Command *queryCommand (const QString &cmd) const; - - /** - * Get a list of all registered commands. - * \return list of all commands - */ - QList commands() const; - - /** - * Get a list of available commandline strings. - * \return commandline strings - */ - QStringList commandList() const; - - - /** - * Get the currently associated Container object - * \return container object - */ - QObject * container(); - - /** - * Set the associated container object - */ - void setContainer( QObject * container ); - - - /** - * TemplateScriptRegistrar interface - */ - - KTextEditor::TemplateScript* registerTemplateScript (QObject* owner, const QString& script); - void unregisterTemplateScript(KTextEditor::TemplateScript* templateScript); - - - private: - /** - * instance of this factory - */ - static KateGlobal *s_self; - - /** - * reference counter - */ - static int s_ref; - - /** - * about data (authors and more) - */ - KAboutData m_aboutData; - - /** - * our kinstance - */ - KComponentData m_componentData; - - /** - * registered docs - */ - QList m_documents; - - /** - * registered views - */ - QList m_views; - - /** - * global dirwatch object - */ - KDirWatch *m_dirWatch; - - /** - * mode manager - */ - KateModeManager *m_modeManager; - - /** - * schema manager - */ - KateSchemaManager *m_schemaManager; - - /** - * at start found plugins - */ - KatePartPluginManager *m_pluginManager; - - /** - * global config - */ - KateGlobalConfig *m_globalConfig; - - /** - * fallback document config - */ - KateDocumentConfig *m_documentConfig; - - /** - * fallback view config - */ - KateViewConfig *m_viewConfig; - - /** - * fallback renderer config - */ - KateRendererConfig *m_rendererConfig; - - /** - * internal commands - */ - QList m_cmds; - - /** - * script manager - */ - KateScriptManager *m_scriptManager; - - /** - * hl manager - */ - KateHlManager *m_hlManager; - - /** - * command manager - */ - KateCmd *m_cmdManager; - - /** - * vi input mode global - */ - KateViGlobal *m_viInputModeGlobal; - - /** - * spell check manager - */ - KateSpellCheckManager *m_spellCheckManager; - - QList m_docs; - - /** - * container interface - */ - QPointer m_container; - - /** - * global instance of the simple word completion mode - */ - KateWordCompletionModel *m_wordCompletionModel; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katepartpluginmanager.cpp b/part/utils/katepartpluginmanager.cpp deleted file mode 100644 index 5365e8e..0000000 --- a/part/utils/katepartpluginmanager.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 2001 Anders Lund - * Copyright (C) 2007 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katepartpluginmanager.h" -#include "katepartpluginmanager.moc" - -#include "kateglobal.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -KatePartPluginInfo::KatePartPluginInfo(KService::Ptr service) - : m_pluginInfo(service) -{ -} - -QString KatePartPluginInfo::saveName() const -{ - QString saveName = m_pluginInfo.pluginName(); - if (saveName.isEmpty()) - saveName = service()->library(); - return saveName; -} - -KatePartPluginManager::KatePartPluginManager() - : QObject(), - m_config(new KConfig("katepartpluginsrc", KConfig::NoGlobals)) -{ - setupPluginList (); - loadConfig (); -} - -KatePartPluginManager::~KatePartPluginManager() -{ - writeConfig(); - // than unload the plugins - unloadAllPlugins (); - delete m_config; - m_config = 0; -} - -KatePartPluginManager *KatePartPluginManager::self() -{ - return KateGlobal::self()->pluginManager (); -} - -void KatePartPluginManager::setupPluginList () -{ - KService::List traderList = KServiceTypeTrader::self()-> - query("KTextEditor/Plugin", - "([X-KDE-Version] >= 4.0) and ([X-KDE-Version] <= " + QString("%1.%2").arg(KDE::versionMajor()).arg(KDE::versionMinor()) + ')'); - - foreach(const KService::Ptr &ptr, traderList) - { - KatePartPluginInfo info(ptr); - - info.load = false; - info.plugin = 0L; - - m_pluginList.push_back (info); - } -} - -void KatePartPluginManager::addDocument(KTextEditor::Document *doc) -{ - //kDebug() << doc; - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->load) { - it->plugin->addDocument(doc); - } - } -} - -void KatePartPluginManager::removeDocument(KTextEditor::Document *doc) -{ - //kDebug() << doc; - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->load) { - it->plugin->removeDocument(doc); - } - } -} - -void KatePartPluginManager::addView(KTextEditor::View *view) -{ - //kDebug() << view; - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->load) { - it->plugin->addView(view); - } - } -} - -void KatePartPluginManager::removeView(KTextEditor::View *view) -{ - //kDebug() << view; - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->load) { - it->plugin->removeView(view); - } - } -} - -void KatePartPluginManager::loadConfig () -{ - // first: unload the plugins - unloadAllPlugins (); - - KConfigGroup cg = KConfigGroup(m_config, "Kate Part Plugins"); - - // disable all plugin if no config... - foreach (const KatePartPluginInfo &plugin, m_pluginList) { - bool enabledByDefault = plugin.isEnabledByDefault(); - plugin.load = cg.readEntry (plugin.saveName(), enabledByDefault); - } - - loadAllPlugins(); -} - -void KatePartPluginManager::writeConfig() -{ - KConfigGroup cg = KConfigGroup( m_config, "Kate Part Plugins" ); - foreach(const KatePartPluginInfo &it, m_pluginList) - { - cg.writeEntry (it.saveName(), it.load); - } -} - -void KatePartPluginManager::loadAllPlugins () -{ - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->load) - { - loadPlugin(*it); - enablePlugin(*it); - } - } -} - -void KatePartPluginManager::unloadAllPlugins () -{ - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if (it->plugin) { - disablePlugin(*it); - unloadPlugin(*it); - } - } -} - -void KatePartPluginManager::loadPlugin (KatePartPluginInfo &item) -{ - if (item.plugin) return; - - // make sure all dependencies are loaded beforehand - QStringList openDependencies = item.dependencies(); - if ( !openDependencies.empty() ) - { - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if ( openDependencies.contains( it->saveName() ) ) - { - loadPlugin( *it ); - openDependencies.removeAll( it->saveName() ); - } - } - Q_ASSERT( openDependencies.empty() ); - } - - item.plugin = item.service()->createInstance(this); - Q_ASSERT(item.plugin); - item.load = (item.plugin != 0); -} - -void KatePartPluginManager::unloadPlugin (KatePartPluginInfo &item) -{ - if ( !item.plugin ) return; - - // make sure dependent plugins are unloaded beforehand - for (KatePartPluginList::iterator it = m_pluginList.begin(); - it != m_pluginList.end(); ++it) - { - if ( !it->plugin ) continue; - - if ( it->dependencies().contains( item.saveName() ) ) - { - unloadPlugin( *it ); - } - } - - delete item.plugin; - item.plugin = 0L; - item.load = false; -} - -void KatePartPluginManager::enablePlugin (KatePartPluginInfo &item) -{ - // plugin around at all? - if (!item.plugin || !item.load) - return; - - // register docs and views - foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) { - if (!doc) - continue; - - foreach (KTextEditor::View *view, doc->views()) { - if (!view) - continue; - - KXMLGUIFactory *viewFactory = view->factory(); - if (viewFactory) - viewFactory->removeClient(view); - - item.plugin->addView(view); - - if (viewFactory) - viewFactory->addClient(view); - } - } -} - -void KatePartPluginManager::disablePlugin (KatePartPluginInfo &item) -{ - // plugin around at all? - if (!item.plugin || !item.load) - return; - - // de-register docs and views - foreach (KTextEditor::Document *doc, KateGlobal::self()->documents()) { - if (!doc) - continue; - - foreach (KTextEditor::View *view, doc->views()) { - if (!view) - continue; - - KXMLGUIFactory *viewFactory = view->factory(); - if (viewFactory) - viewFactory->removeClient(view); - - item.plugin->removeView(view); - - if (viewFactory) - viewFactory->addClient(view); - } - } -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katepartpluginmanager.h b/part/utils/katepartpluginmanager.h deleted file mode 100644 index 5543bb0..0000000 --- a/part/utils/katepartpluginmanager.h +++ /dev/null @@ -1,98 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2001-2010 Christoph Cullmann - * Copyright (C) 2001 Joseph Wenninger - * Copyright (C) 2001 Anders Lund - * Copyright (C) 2007 Dominik Haumann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATEPARTPLUGINMANAGER_H -#define KATEPARTPLUGINMANAGER_H - -#include -#include - -#include -#include - -namespace KTextEditor { - class Plugin; - class Document; - class View; -} - -class KatePartPluginInfo -{ - public: - KatePartPluginInfo(KService::Ptr service); - mutable bool load; - KTextEditor::Plugin *plugin; - QString saveName() const; - KService::Ptr service() const { return m_pluginInfo.service(); } - QStringList dependencies() const { return m_pluginInfo.dependencies(); } - bool isEnabledByDefault() const { return m_pluginInfo.isPluginEnabledByDefault(); } - private: - KPluginInfo m_pluginInfo; - QString m_saveName; -}; - -typedef QList KatePartPluginList; - -class KatePartPluginManager : public QObject -{ - Q_OBJECT - - public: - KatePartPluginManager(); - ~KatePartPluginManager(); - - static KatePartPluginManager *self(); - - void loadConfig (); - void writeConfig (); - - void addDocument(KTextEditor::Document *doc); - void removeDocument(KTextEditor::Document *doc); - - void addView(KTextEditor::View *view); - void removeView(KTextEditor::View *view); - - void loadAllPlugins (); - void unloadAllPlugins (); - - void loadPlugin (KatePartPluginInfo &item); - void unloadPlugin (KatePartPluginInfo &item); - - void enablePlugin (KatePartPluginInfo &item); - void disablePlugin (KatePartPluginInfo &item); - - inline KatePartPluginList & pluginList () - { - return m_pluginList; - } - - private: - void setupPluginList (); - - KConfig *m_config; - KatePartPluginList m_pluginList; -}; - -#endif // KATEPARTPLUGINMANAGER_H - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateprinter.cpp b/part/utils/kateprinter.cpp deleted file mode 100644 index 445a571..0000000 --- a/part/utils/kateprinter.cpp +++ /dev/null @@ -1,1192 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2002-2010 Anders Lund - * - * Rewritten based on code of Copyright (c) 2002 Michael Goffioul - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateprinter.h" - -#include "kateconfig.h" -#include "katedocument.h" -#include "kateglobal.h" -#include "katehighlight.h" -#include "katetextlayout.h" -#include "katerenderer.h" -#include "kateschema.h" -#include "katetextline.h" -#include "kateview.h" - -#include -#include -#include -#include -#include -#include -#include -#include // for loginName -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -//BEGIN KatePrinter -bool KatePrinter::print (KateDocument *doc) -{ - - QPrinter printer; - - // docname is now always there, including the right Untitled name - printer.setDocName(doc->documentName()); - - KatePrintTextSettings *kpts = new KatePrintTextSettings; - KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter; - KatePrintLayout *kpl = new KatePrintLayout; - - QList tabs; - tabs << kpts; - tabs << kphf; - tabs << kpl; - - QWidget *parentWidget=doc->widget(); - - if ( !parentWidget ) - parentWidget=QApplication::activeWindow(); - - QScopedPointer printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget)); - - if ( doc->activeView()->selection() ) - printDialog->addEnabledOption(QAbstractPrintDialog::PrintSelection); - - if ( printDialog->exec() ) - { - KateRenderer renderer(doc, doc->activeKateView()); - renderer.config()->setSchema (kpl->colorScheme()); - renderer.setPrinterFriendly(true); - - QPainter paint( &printer ); - /* - * We work in tree cycles: - * 1) initialize variables and retrieve print settings - * 2) prepare data according to those settings - * 3) draw to the printer - */ - uint pdmWidth = printer.width(); - uint pdmHeight = printer.height(); - int y = 0; - uint xstart = 0; // beginning point for painting lines - uint lineCount = 0; - uint maxWidth = pdmWidth; - int headerWidth = pdmWidth; - int startCol = 0; - int endCol = 0; - bool pageStarted = true; - int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page) - - // Text Settings Page - bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection); - bool useGuide = kpts->printGuide(); - - bool printLineNumbers = kpts->printLineNumbers(); - uint lineNumberWidth( 0 ); - - // Header/Footer Page - QFont headerFont(kphf->font()); // used for header/footer - - bool useHeader = kphf->useHeader(); - QColor headerBgColor(kphf->headerBackground()); - QColor headerFgColor(kphf->headerForeground()); - uint headerHeight( 0 ); // further init only if needed - QStringList headerTagList; // do - bool headerDrawBg = false; // do - - bool useFooter = kphf->useFooter(); - QColor footerBgColor(kphf->footerBackground()); - QColor footerFgColor(kphf->footerForeground()); - uint footerHeight( 0 ); // further init only if needed - QStringList footerTagList; // do - bool footerDrawBg = false; // do - - // Layout Page - renderer.config()->setSchema( kpl->colorScheme() ); - bool useBackground = kpl->useBackground(); - bool useBox = kpl->useBox(); - int boxWidth(kpl->boxWidth()); - QColor boxColor(kpl->boxColor()); - int innerMargin = useBox ? kpl->boxMargin() : 6; - - // Post initialization - int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight); - uint currentPage( 1 ); - uint lastline = doc->lastLine(); // necessary to print selection only - uint firstline( 0 ); - int fontHeight = renderer.fontHeight(); - KTextEditor::Range selectionRange; - - /* - * Now on for preparations... - * during preparations, variable names starting with a "_" means - * those variables are local to the enclosing block. - */ - { - if ( selectionOnly ) - { - // set a line range from the first selected line to the last - selectionRange = doc->activeView()->selectionRange(); - firstline = selectionRange.start().line(); - lastline = selectionRange.end().line(); - lineCount = firstline; - } - - if ( printLineNumbers ) - { - // figure out the horiizontal space required - QString s( QString("%1 ").arg( doc->lines() ) ); - s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers - // FIXME calculate which is actually the widest... - lineNumberWidth = renderer.currentFontMetrics().width( s ); - // a small space between the line numbers and the text - int _adj = renderer.currentFontMetrics().width( "5" ); - // adjust available width and set horizontal start point for data - maxWidth -= (lineNumberWidth + _adj); - xstart += lineNumberWidth + _adj; - } - - if ( useHeader || useFooter ) - { - // Set up a tag map - // This retrieves all tags, ued or not, but - // none of theese operations should be expensive, - // and searcing each tag in the format strings is avoided. - QDateTime dt = QDateTime::currentDateTime(); - QMap tags; - - KUser u (KUser::UseRealUserID); - tags["u"] = u.loginName(); - - tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate); - tags["D"] = KGlobal::locale()->formatDateTime(dt, KLocale::LongDate); - tags["h"] = KGlobal::locale()->formatTime(dt.time(), false); - tags["y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate); - tags["Y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate); - tags["f"] = doc->url().fileName(); - tags["U"] = doc->url().prettyUrl(); - if ( selectionOnly ) - { - QString s( i18n("(Selection of) ") ); - tags["f"].prepend( s ); - tags["U"].prepend( s ); - } - - QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%" - - if (useHeader) - { - headerDrawBg = kphf->useHeaderBackground(); - headerHeight = QFontMetrics( headerFont ).height(); - if ( useBox || headerDrawBg ) - headerHeight += innerMargin * 2; - else - headerHeight += 1 + QFontMetrics( headerFont ).leading(); - - headerTagList = kphf->headerFormat(); - QMutableStringListIterator it(headerTagList); - while ( it.hasNext() ) { - QString tag = it.next(); - int pos = reTags.indexIn( tag ); - QString rep; - while ( pos > -1 ) - { - rep = tags[reTags.cap( 1 )]; - tag.replace( (uint)pos, 2, rep ); - pos += rep.length(); - pos = reTags.indexIn( tag, pos ); - } - it.setValue( tag ); - } - - if (!headerBgColor.isValid()) - headerBgColor = Qt::lightGray; - if (!headerFgColor.isValid()) - headerFgColor = Qt::black; - } - - if (useFooter) - { - footerDrawBg = kphf->useFooterBackground(); - footerHeight = QFontMetrics( headerFont ).height(); - if ( useBox || footerDrawBg ) - footerHeight += 2*innerMargin; - else - footerHeight += 1; // line only - - footerTagList = kphf->footerFormat(); - QMutableStringListIterator it(footerTagList); - while ( it.hasNext() ) { - QString tag = it.next(); - int pos = reTags.indexIn( tag ); - QString rep; - while ( pos > -1 ) - { - rep = tags[reTags.cap( 1 )]; - tag.replace( (uint)pos, 2, rep ); - pos += rep.length(); - pos = reTags.indexIn( tag, pos ); - } - it.setValue( tag ); - } - - if (!footerBgColor.isValid()) - footerBgColor = Qt::lightGray; - if (!footerFgColor.isValid()) - footerFgColor = Qt::black; - // adjust maxheight, so we can know when/where to print footer - maxHeight -= footerHeight; - } - } // if ( useHeader || useFooter ) - - if ( useBackground ) - { - if ( ! useBox ) - { - xstart += innerMargin; - maxWidth -= innerMargin * 2; - } - } - - if ( useBox ) - { - if (!boxColor.isValid()) - boxColor = Qt::black; - if (boxWidth < 1) // shouldn't be pssible no more! - boxWidth = 1; - // set maxwidth to something sensible - maxWidth -= ( ( boxWidth + innerMargin ) * 2 ); - xstart += boxWidth + innerMargin; - // maxheight too.. - maxHeight -= boxWidth; - } - else - boxWidth = 0; - - // now that we know the vertical amount of space needed, - // it is possible to calculate the total number of pages - // if needed, that is if any header/footer tag contains "%P". -#if 0 - if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() ) - { - kDebug(13020)<<"'%P' found! calculating number of pages..."; - uint _pages = 0; - uint _ph = maxHeight; - if ( useHeader ) - _ph -= ( headerHeight + innerMargin ); - if ( useFooter ) - _ph -= innerMargin; - int _lpp = _ph / fontHeight; - uint _lt = 0, _c=0; - - // add space for guide if required -// if ( useGuide ) -// _lt += (guideHeight + (fontHeight /2)) / fontHeight; - long _lw; - for ( uint i = firstline; i < lastline; i++ ) - { - //FIXME: _lw = renderer.textWidth( doc->kateTextLine( i ), -1 ); - _lw = 80 * renderer.spaceWidth(); //FIXME: just a stand-in - while ( _lw >= 0 ) - { - _c++; - _lt++; - if ( (int)_lt == _lpp ) - { - _pages++; - _lt = 0; - } - _lw -= maxWidth; - if ( ! _lw ) _lw--; // skip lines matching exactly! - } - } - if ( _lt ) _pages++; // last page - - // substitute both tag lists - QString re("%P"); - QStringList::Iterator it; - for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it ) - (*it).replace( re, QString( "%1" ).arg( _pages ) ); - for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it ) - (*it).replace( re, QString( "%1" ).arg( _pages ) ); - } -#endif - } // end prepare block - - /* - On to draw something :-) - */ - while ( lineCount <= lastline ) - { - startCol = 0; - endCol = 0; - - if ( y + fontHeight >= maxHeight ) - { - kDebug(13020)<<"Starting new page,"<backgroundColor()); - } - - if ( useBox ) - { - paint.setPen(QPen(boxColor, boxWidth)); - paint.drawRect(0, 0, pdmWidth, pdmHeight); - if (useHeader) - paint.drawLine(0, headerHeight, headerWidth, headerHeight); - else - y += innerMargin; - - if ( useFooter ) // drawline is not trustable, grr. - paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor ); - } - - if ( useGuide && currentPage == 1 ) - { // FIXME - this may span more pages... - // draw a box unless we have boxes, in which case we end with a box line - int _ystart = y; - QString _hlName = doc->highlight()->name(); - - QList _attributes; // list of highlight attributes for the legend - doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes); - - KateAttributeList _defaultAttributes; - KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes ); - - QColor _defaultPen = _defaultAttributes.at(0)->foreground().color(); - paint.setPen(_defaultPen); - paint.setBrush(_defaultPen); - - int _marg = 0; - if ( useBox ) - _marg += (2*boxWidth) + (2*innerMargin); - else - { - if ( useBackground ) - _marg += 2*innerMargin; - _marg += 1; - y += 1 + innerMargin; - } - - // draw a title string - QFont _titleFont = renderer.config()->font(); - _titleFont.setBold(true); - paint.setFont( _titleFont ); - QRect _r; - paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y), - Qt::AlignTop|Qt::AlignHCenter, - i18n("Typographical Conventions for %1", _hlName ), &_r ); - int _w = pdmWidth - (_marg*2) - (innerMargin*2); - int _x = _marg + innerMargin; - y += _r.height() + innerMargin; - paint.drawLine( _x, y, _x + _w, y ); - y += 1 + innerMargin; - - int _widest( 0 ); - foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) - _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest); - - int _guideCols = _w/( _widest + innerMargin ); - - // draw attrib names using their styles - int _cw = _w/_guideCols; - int _i(0); - - _titleFont.setUnderline(true); - QString _currentHlName; - foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) - { - QString _hl = attribute->name().section(':',0,0); - QString _name = attribute->name().section(':',1,1); - if ( _hl != _hlName && _hl != _currentHlName ) { - _currentHlName = _hl; - if ( _i%_guideCols ) - y += fontHeight; - y += innerMargin; - paint.setFont(_titleFont); - paint.setPen(_defaultPen); - paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") ); - y += fontHeight; - _i = 0; - } - - KTextEditor::Attribute _attr = *_defaultAttributes[attribute->defaultStyleIndex()]; - _attr += *attribute; - paint.setPen( _attr.foreground().color() ); - paint.setFont( _attr.font() ); - - if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) { - QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name); - _rect.moveTo(_x + ((_i%_guideCols)*_cw), y); - paint.fillRect(_rect, _attr.background() ); - } - - paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name ); - - _i++; - if ( _i && ! ( _i%_guideCols ) ) - y += fontHeight; - } - - if ( _i%_guideCols ) - y += fontHeight;// last row not full - - // draw a box around the legend - paint.setPen ( _defaultPen ); - if ( useBox ) - paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor ); - else - { - _marg -=1; - paint.setBrush(QBrush()); - paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin ); - } - - y += ( useBox ? boxWidth : 1 ) + (innerMargin*2); - } // useGuide - - paint.translate(xstart,y); - pageStarted = false; - } // pageStarted; move on to contents:) - - if ( printLineNumbers /*&& ! startCol*/ ) // don't repeat! - { - paint.setFont( renderer.config()->font() ); - paint.setPen( renderer.config()->lineNumberColor() ); - paint.drawText( (( useBox || useBackground ) ? innerMargin : 0)-xstart, 0, - lineNumberWidth, fontHeight, - Qt::AlignRight, QString("%1").arg( lineCount + 1 ) ); - } - - // HA! this is where we print [part of] a line ;]] - // FIXME Convert this function + related functionality to a separate KatePrintView - KateLineLayout range(doc); - range.setLine(lineCount); - KateLineLayoutPtr *rangeptr = new KateLineLayoutPtr(&range); - renderer.layoutLine(*rangeptr, (int)maxWidth, false); - - // selectionOnly: clip non-selection parts and adjust painter position if needed - int _xadjust = 0; - if (selectionOnly) { - if (doc->activeView()->blockSelection()) { - int _x = renderer.cursorToX((*rangeptr)->viewLine(0), selectionRange.start()); - int _x1 = renderer.cursorToX((*rangeptr)->viewLine((*rangeptr)->viewLineCount()-1), selectionRange.end()); - _xadjust = _x; - paint.translate(-_xadjust, 0); - paint.setClipRegion(QRegion( _x, 0, _x1 - _x, (*rangeptr)->viewLineCount()*fontHeight)); - } - - else if (lineCount == firstline || lineCount == lastline) { - QRegion region(0, 0, maxWidth, (*rangeptr)->viewLineCount()*fontHeight); - - if ( lineCount == firstline) { - region = region.subtracted(QRegion(0, 0, renderer.cursorToX((*rangeptr)->viewLine(0), selectionRange.start()), fontHeight)); - } - - if (lineCount == lastline) { - int _x = renderer.cursorToX((*rangeptr)->viewLine((*rangeptr)->viewLineCount()-1), selectionRange.end()); - region = region.subtracted(QRegion(_x, 0, maxWidth-_x, fontHeight)); - } - - paint.setClipRegion(region); - } - } - - // If the line is too long (too many 'viewlines') to fit the remaining vertical space, - // clip and adjust the painter position as necessary - int _lines = (*rangeptr)->viewLineCount(); // number of "sublines" to paint. - - if (remainder) { - int _height = (maxHeight-y)/fontHeight; - _height = qMin(_height, remainder); - - paint.translate(0, -(_lines-remainder)*fontHeight+1); - paint.setClipRect(0, (_lines-remainder)*fontHeight+1, maxWidth, _height*fontHeight); //### drop the crosspatch in printerfriendly mode??? - remainder -= _height; - } - else if (fontHeight*_lines > maxHeight-y) { - remainder = _lines - ((maxHeight-y)/fontHeight); - paint.setClipRect(0, 0, maxWidth, (_lines-remainder)*fontHeight+1); //### drop the crosspatch in printerfriendly mode??? - } - - renderer.paintTextLine(paint, *rangeptr, 0, (int)maxWidth); - - paint.setClipping(false); - paint.translate(_xadjust, (fontHeight * _lines)); - - y += fontHeight*_lines; - - if ( ! remainder ) - lineCount++; - } // done lineCount <= lastline - - paint.end(); - return true; - } - return false; -} -//END KatePrinter - -//BEGIN KatePrintTextSettings -KatePrintTextSettings::KatePrintTextSettings( QWidget *parent ) - : QWidget( parent ) -{ - setWindowTitle( i18n("Te&xt Settings") ); - - QVBoxLayout *lo = new QVBoxLayout ( this ); - -// cbSelection = new QCheckBox( i18n("Print &selected text only"), this ); -// lo->addWidget( cbSelection ); - - cbLineNumbers = new QCheckBox( i18n("Print line &numbers"), this ); - lo->addWidget( cbLineNumbers ); - - cbGuide = new QCheckBox( i18n("Print &legend"), this ); - lo->addWidget( cbGuide ); - - lo->addStretch( 1 ); - - // set defaults - nothing to do :-) - - // whatsthis -// cbSelection->setWhatsThis(i18n( -// "

This option is only available if some text is selected in the document.

" -// "

If available and enabled, only the selected text is printed.

") ); - cbLineNumbers->setWhatsThis(i18n( - "

If enabled, line numbers will be printed on the left side of the page(s).

") ); - cbGuide->setWhatsThis(i18n( - "

Print a box displaying typographical conventions for the document type, as " - "defined by the syntax highlighting being used.

") ); - - readSettings(); -} - -KatePrintTextSettings::~KatePrintTextSettings() -{ - writeSettings(); -} - -// bool KatePrintTextSettings::printSelection() -// { -// return cbSelection->isChecked(); -// } - -bool KatePrintTextSettings::printLineNumbers() -{ - return cbLineNumbers->isChecked(); -} - -bool KatePrintTextSettings::printGuide() -{ - return cbGuide->isChecked(); -} - -// void KatePrintTextSettings::enableSelection( bool enable ) -// { -// cbSelection->setEnabled( enable ); -// } - -void KatePrintTextSettings::readSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup( config, "Kate Print Settings" ); - - KConfigGroup textGroup( &printGroup, "Text" ); - bool isLineNumbersChecked = textGroup.readEntry( "LineNumbers", false ); - cbLineNumbers->setChecked( isLineNumbersChecked ); - - bool isLegendChecked = textGroup.readEntry( "Legend", false ); - cbGuide->setChecked( isLegendChecked ); -} - -void KatePrintTextSettings::writeSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup( config, "Kate Print Settings" ); - - KConfigGroup textGroup( &printGroup, "Text" ); - textGroup.writeEntry( "LineNumbers", printLineNumbers() ); - textGroup.writeEntry( "Legend", printGuide() ); - - config->sync(); -} - -//END KatePrintTextSettings - -//BEGIN KatePrintHeaderFooter -KatePrintHeaderFooter::KatePrintHeaderFooter( QWidget *parent ) - : QWidget( parent ) -{ - setWindowTitle( i18n("Hea&der && Footer") ); - - QVBoxLayout *lo = new QVBoxLayout ( this ); - - // enable - QHBoxLayout *lo1 = new QHBoxLayout (); - lo->addLayout( lo1 ); - cbEnableHeader = new QCheckBox( i18n("Pr&int header"), this ); - lo1->addWidget( cbEnableHeader ); - cbEnableFooter = new QCheckBox( i18n("Pri&nt footer"), this ); - lo1->addWidget( cbEnableFooter ); - - // font - QHBoxLayout *lo2 = new QHBoxLayout(); - lo->addLayout( lo2 ); - lo2->addWidget( new QLabel( i18n("Header/footer font:"), this ) ); - lFontPreview = new QLabel( this ); - lFontPreview->setFrameStyle( QFrame::Panel|QFrame::Sunken ); - lo2->addWidget( lFontPreview ); - lo2->setStretchFactor( lFontPreview, 1 ); - QPushButton *btnChooseFont = new QPushButton( i18n("Choo&se Font..."), this ); - lo2->addWidget( btnChooseFont ); - connect( btnChooseFont, SIGNAL(clicked()), this, SLOT(setHFFont()) ); - - // header - gbHeader = new QGroupBox( this ); - gbHeader->setTitle(i18n("Header Properties")); - QGridLayout* grid = new QGridLayout(gbHeader); - lo->addWidget( gbHeader ); - - QLabel *lHeaderFormat = new QLabel( i18n("&Format:"), gbHeader ); - grid->addWidget(lHeaderFormat, 0, 0); - - KHBox *hbHeaderFormat = new KHBox( gbHeader ); - grid->addWidget(hbHeaderFormat, 0, 1); - - leHeaderLeft = new KLineEdit( hbHeaderFormat ); - leHeaderCenter = new KLineEdit( hbHeaderFormat ); - leHeaderRight = new KLineEdit( hbHeaderFormat ); - lHeaderFormat->setBuddy( leHeaderLeft ); - - grid->addWidget(new QLabel( i18n("Colors:"), gbHeader ), 1, 0); - - KHBox *hbHeaderColors = new KHBox( gbHeader ); - grid->addWidget(hbHeaderColors, 1, 1); - - hbHeaderColors->setSpacing( -1 ); - QLabel *lHeaderFgCol = new QLabel( i18n("Foreground:"), hbHeaderColors ); - kcbtnHeaderFg = new KColorButton( hbHeaderColors ); - lHeaderFgCol->setBuddy( kcbtnHeaderFg ); - cbHeaderEnableBgColor = new QCheckBox( i18n("Bac&kground"), hbHeaderColors ); - kcbtnHeaderBg = new KColorButton( hbHeaderColors ); - - gbFooter = new QGroupBox( this ); - gbFooter->setTitle(i18n("Footer Properties")); - grid = new QGridLayout(gbFooter); - lo->addWidget( gbFooter ); - - // footer - QLabel *lFooterFormat = new QLabel( i18n("For&mat:"), gbFooter ); - grid->addWidget(lFooterFormat, 0, 0); - - KHBox *hbFooterFormat = new KHBox( gbFooter ); - grid->addWidget(hbFooterFormat, 0, 1); - - hbFooterFormat->setSpacing( -1 ); - leFooterLeft = new KLineEdit( hbFooterFormat ); - leFooterCenter = new KLineEdit( hbFooterFormat ); - leFooterRight = new KLineEdit( hbFooterFormat ); - lFooterFormat->setBuddy( leFooterLeft ); - - grid->addWidget(new QLabel( i18n("Colors:"), gbFooter ), 1, 0); - - KHBox *hbFooterColors = new KHBox( gbFooter ); - grid->addWidget(hbFooterColors, 1, 1); - - hbFooterColors->setSpacing( -1 ); - QLabel *lFooterBgCol = new QLabel( i18n("Foreground:"), hbFooterColors ); - kcbtnFooterFg = new KColorButton( hbFooterColors ); - lFooterBgCol->setBuddy( kcbtnFooterFg ); - cbFooterEnableBgColor = new QCheckBox( i18n("&Background"), hbFooterColors ); - kcbtnFooterBg = new KColorButton( hbFooterColors ); - - lo->addStretch( 1 ); - - // user friendly - connect( cbEnableHeader, SIGNAL(toggled(bool)), gbHeader, SLOT(setEnabled(bool)) ); - connect( cbEnableFooter, SIGNAL(toggled(bool)), gbFooter, SLOT(setEnabled(bool)) ); - connect( cbHeaderEnableBgColor, SIGNAL(toggled(bool)), kcbtnHeaderBg, SLOT(setEnabled(bool)) ); - connect( cbFooterEnableBgColor, SIGNAL(toggled(bool)), kcbtnFooterBg, SLOT(setEnabled(bool)) ); - - // set defaults - cbEnableHeader->setChecked( true ); - leHeaderLeft->setText( "%y" ); - leHeaderCenter->setText( "%f" ); - leHeaderRight->setText( "%p" ); - kcbtnHeaderFg->setColor( QColor("black") ); - cbHeaderEnableBgColor->setChecked( false ); - kcbtnHeaderBg->setColor( QColor("lightgrey") ); - - cbEnableFooter->setChecked( true ); - leFooterRight->setText( "%U" ); - kcbtnFooterFg->setColor( QColor("black") ); - cbFooterEnableBgColor->setChecked( false ); - kcbtnFooterBg->setColor( QColor("lightgrey") ); - - // whatsthis - QString s = i18n("

Format of the page header. The following tags are supported:

"); - QString s1 = i18n( - "
  • %u: current user name
  • " - "
  • %d: complete date/time in short format
  • " - "
  • %D: complete date/time in long format
  • " - "
  • %h: current time
  • " - "
  • %y: current date in short format
  • " - "
  • %Y: current date in long format
  • " - "
  • %f: file name
  • " - "
  • %U: full URL of the document
  • " - "
  • %p: page number
  • " - "

"); - leHeaderRight->setWhatsThis(s + s1 ); - leHeaderCenter->setWhatsThis(s + s1 ); - leHeaderLeft->setWhatsThis(s + s1 ); - s = i18n("

Format of the page footer. The following tags are supported:

"); - leFooterRight->setWhatsThis(s + s1 ); - leFooterCenter->setWhatsThis(s + s1 ); - leFooterLeft->setWhatsThis(s + s1 ); - - readSettings(); -} - -KatePrintHeaderFooter::~KatePrintHeaderFooter() -{ - writeSettings(); -} - -QFont KatePrintHeaderFooter::font() -{ - return lFontPreview->font(); -} - -bool KatePrintHeaderFooter::useHeader() -{ - return cbEnableHeader->isChecked(); -} - -QStringList KatePrintHeaderFooter::headerFormat() -{ - QStringList l; - l << leHeaderLeft->text() << leHeaderCenter->text() << leHeaderRight->text(); - return l; -} - -QColor KatePrintHeaderFooter::headerForeground() -{ - return kcbtnHeaderFg->color(); -} - -QColor KatePrintHeaderFooter::headerBackground() -{ - return kcbtnHeaderBg->color(); -} - -bool KatePrintHeaderFooter::useHeaderBackground() -{ - return cbHeaderEnableBgColor->isChecked(); -} - -bool KatePrintHeaderFooter::useFooter() -{ - return cbEnableFooter->isChecked(); -} - -QStringList KatePrintHeaderFooter::footerFormat() -{ - QStringList l; - l<< leFooterLeft->text() << leFooterCenter->text() << leFooterRight->text(); - return l; -} - -QColor KatePrintHeaderFooter::footerForeground() -{ - return kcbtnFooterFg->color(); -} - -QColor KatePrintHeaderFooter::footerBackground() -{ - return kcbtnFooterBg->color(); -} - -bool KatePrintHeaderFooter::useFooterBackground() -{ - return cbFooterEnableBgColor->isChecked(); -} - -void KatePrintHeaderFooter::setHFFont() -{ - QFont fnt( lFontPreview->font() ); - // display a font dialog - if ( KFontDialog::getFont( fnt, false, this ) == KFontDialog::Accepted ) - { - // set preview - lFontPreview->setFont( fnt ); - lFontPreview->setText( QString(fnt.family() + ", %1pt").arg( fnt.pointSize() ) ); - } -} - -void KatePrintHeaderFooter::readSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup( config, "Kate Print Settings" ); - - // Header - KConfigGroup headerFooterGroup( &printGroup, "HeaderFooter" ); - bool isHeaderEnabledChecked = headerFooterGroup.readEntry( "HeaderEnabled", true ); - cbEnableHeader->setChecked( isHeaderEnabledChecked ); - - QString headerFormatLeft = headerFooterGroup.readEntry( "HeaderFormatLeft", "%y" ); - leHeaderLeft->setText( headerFormatLeft ); - - QString headerFormatCenter = headerFooterGroup.readEntry( "HeaderFormatCenter", "%f" ); - leHeaderCenter->setText( headerFormatCenter ); - - QString headerFormatRight = headerFooterGroup.readEntry( "HeaderFormatRight", "%p" ); - leHeaderRight->setText( headerFormatRight ); - - QColor headerForeground = headerFooterGroup.readEntry( "HeaderForeground", QColor("black") ); - kcbtnHeaderFg->setColor( headerForeground ); - - bool isHeaderBackgroundChecked = headerFooterGroup.readEntry( "HeaderBackgroundEnabled", false ); - cbHeaderEnableBgColor->setChecked( isHeaderBackgroundChecked ); - - QColor headerBackground = headerFooterGroup.readEntry( "HeaderBackground", QColor("lightgrey") ); - kcbtnHeaderBg->setColor( headerBackground ); - - // Footer - bool isFooterEnabledChecked = headerFooterGroup.readEntry( "FooterEnabled", true ); - cbEnableFooter->setChecked( isFooterEnabledChecked ); - - QString footerFormatLeft = headerFooterGroup.readEntry( "FooterFormatLeft", QString() ); - leFooterLeft->setText( footerFormatLeft ); - - QString footerFormatCenter = headerFooterGroup.readEntry( "FooterFormatCenter", QString() ); - leFooterCenter->setText( footerFormatCenter ); - - QString footerFormatRight = headerFooterGroup.readEntry( "FooterFormatRight", "%U" ); - leFooterRight->setText( footerFormatRight ); - - QColor footerForeground = headerFooterGroup.readEntry( "FooterForeground", QColor("black") ); - kcbtnFooterFg->setColor( footerForeground ); - - bool isFooterBackgroundChecked = headerFooterGroup.readEntry( "FooterBackgroundEnabled", false ); - cbFooterEnableBgColor->setChecked( isFooterBackgroundChecked ); - - QColor footerBackground = headerFooterGroup.readEntry( "FooterBackground", QColor("lightgrey") ); - kcbtnFooterBg->setColor( footerBackground ); - - // Font - QFont headerFooterFont = headerFooterGroup.readEntry( "HeaderFooterFont", QFont() ); - lFontPreview->setFont( headerFooterFont ); - lFontPreview->setText( QString(headerFooterFont.family() + ", %1pt").arg( headerFooterFont.pointSize() ) ); -} - -void KatePrintHeaderFooter::writeSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup( config, "Kate Print Settings" ); - - // Header - KConfigGroup headerFooterGroup( &printGroup, "HeaderFooter" ); - headerFooterGroup.writeEntry( "HeaderEnabled", useHeader() ); - - QStringList format = headerFormat(); - headerFooterGroup.writeEntry( "HeaderFormatLeft", format[0] ); - headerFooterGroup.writeEntry( "HeaderFormatCenter", format[1] ); - headerFooterGroup.writeEntry( "HeaderFormatRight", format[2] ); - headerFooterGroup.writeEntry( "HeaderForeground", headerForeground() ); - headerFooterGroup.writeEntry( "HeaderBackgroundEnabled", useHeaderBackground() ); - headerFooterGroup.writeEntry( "HeaderBackground", headerBackground() ); - - // Footer - headerFooterGroup.writeEntry( "FooterEnabled", useFooter() ); - - format = footerFormat(); - headerFooterGroup.writeEntry( "FooterFormatLeft", format[0] ); - headerFooterGroup.writeEntry( "FooterFormatCenter", format[1] ); - headerFooterGroup.writeEntry( "FooterFormatRight", format[2] ); - headerFooterGroup.writeEntry( "FooterForeground", footerForeground() ); - headerFooterGroup.writeEntry( "FooterBackgroundEnabled", useFooterBackground() ); - headerFooterGroup.writeEntry( "FooterBackground", footerBackground() ); - - // Font - headerFooterGroup.writeEntry( "HeaderFooterFont", font() ); - - config->sync(); -} - -//END KatePrintHeaderFooter - -//BEGIN KatePrintLayout - -KatePrintLayout::KatePrintLayout( QWidget *parent) - : QWidget( parent ) -{ - setWindowTitle( i18n("L&ayout") ); - - QVBoxLayout *lo = new QVBoxLayout ( this ); - - KHBox *hb = new KHBox( this ); - lo->addWidget( hb ); - QLabel *lSchema = new QLabel( i18n("&Schema:"), hb ); - cmbSchema = new KComboBox( hb ); - cmbSchema->setEditable( false ); - lSchema->setBuddy( cmbSchema ); - - cbDrawBackground = new QCheckBox( i18n("Draw bac&kground color"), this ); - lo->addWidget( cbDrawBackground ); - - cbEnableBox = new QCheckBox( i18n("Draw &boxes"), this ); - lo->addWidget( cbEnableBox ); - - gbBoxProps = new QGroupBox( this ); - gbBoxProps->setTitle(i18n("Box Properties")); - QGridLayout* grid = new QGridLayout(gbBoxProps); - lo->addWidget( gbBoxProps ); - - QLabel *lBoxWidth = new QLabel( i18n("W&idth:"), gbBoxProps ); - grid->addWidget(lBoxWidth, 0, 0); - sbBoxWidth = new KIntSpinBox( gbBoxProps ); - sbBoxWidth->setRange( 1, 100 ); - sbBoxWidth->setSingleStep( 1 ); - grid->addWidget(sbBoxWidth, 0, 1); - lBoxWidth->setBuddy( sbBoxWidth ); - - QLabel *lBoxMargin = new QLabel( i18n("&Margin:"), gbBoxProps ); - grid->addWidget(lBoxMargin, 1, 0); - sbBoxMargin = new KIntSpinBox( gbBoxProps ); - sbBoxMargin->setRange( 0, 100 ); - sbBoxMargin->setSingleStep( 1 ); - grid->addWidget(sbBoxMargin, 1, 1); - lBoxMargin->setBuddy( sbBoxMargin ); - - QLabel *lBoxColor = new QLabel( i18n("Co&lor:"), gbBoxProps ); - grid->addWidget(lBoxColor, 2, 0); - kcbtnBoxColor = new KColorButton( gbBoxProps ); - grid->addWidget(kcbtnBoxColor, 2, 1); - lBoxColor->setBuddy( kcbtnBoxColor ); - - connect( cbEnableBox, SIGNAL(toggled(bool)), gbBoxProps, SLOT(setEnabled(bool)) ); - - lo->addStretch( 1 ); - // set defaults: - sbBoxMargin->setValue( 6 ); - gbBoxProps->setEnabled( false ); - cmbSchema->addItems (KateGlobal::self()->schemaManager()->list ()); - cmbSchema->setCurrentIndex( 1 ); - - // whatsthis - cmbSchema->setWhatsThis(i18n( - "Select the color scheme to use for the print." ) ); - cbDrawBackground->setWhatsThis(i18n( - "

If enabled, the background color of the editor will be used.

" - "

This may be useful if your color scheme is designed for a dark background.

") ); - cbEnableBox->setWhatsThis(i18n( - "

If enabled, a box as defined in the properties below will be drawn " - "around the contents of each page. The Header and Footer will be separated " - "from the contents with a line as well.

") ); - sbBoxWidth->setWhatsThis(i18n( - "The width of the box outline" ) ); - sbBoxMargin->setWhatsThis(i18n( - "The margin inside boxes, in pixels") ); - kcbtnBoxColor->setWhatsThis(i18n( - "The line color to use for boxes") ); - - readSettings(); -} - -KatePrintLayout::~KatePrintLayout() -{ - writeSettings(); -} - -QString KatePrintLayout::colorScheme() -{ - return cmbSchema->currentText(); -} - -bool KatePrintLayout::useBackground() -{ - return cbDrawBackground->isChecked(); -} - -bool KatePrintLayout::useBox() -{ - return cbEnableBox->isChecked(); -} - -int KatePrintLayout::boxWidth() -{ - return sbBoxWidth->value(); -} - -int KatePrintLayout::boxMargin() -{ - return sbBoxMargin->value(); -} - -QColor KatePrintLayout::boxColor() -{ - return kcbtnBoxColor->color(); -} - -void KatePrintLayout::readSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup(config, "Kate Print Settings"); - - KConfigGroup layoutGroup(&printGroup, "Layout"); - - QString colorScheme = layoutGroup.readEntry( "ColorScheme", KateGlobal::self()->schemaManager()->name(1) ); - cmbSchema->setCurrentItem( colorScheme ); - - bool isBackgroundChecked = layoutGroup.readEntry( "BackgroundColorEnabled", false ); - cbDrawBackground->setChecked( isBackgroundChecked ); - - bool isBoxChecked = layoutGroup.readEntry( "BoxEnabled", false ); - cbEnableBox->setChecked( isBoxChecked ); - - int boxWidth = layoutGroup.readEntry( "BoxWidth", 1 ); - sbBoxWidth->setValue( boxWidth ); - - int boxMargin = layoutGroup.readEntry( "BoxMargin", 6 ); - sbBoxMargin->setValue( boxMargin ); - - QColor boxColor = layoutGroup.readEntry( "BoxColor", QColor() ); - kcbtnBoxColor->setColor( boxColor ); -} - -void KatePrintLayout::writeSettings() -{ - KSharedConfigPtr config = KGlobal::config(); - KConfigGroup printGroup(config, "Kate Print Settings"); - - KConfigGroup layoutGroup(&printGroup, "Layout"); - layoutGroup.writeEntry( "ColorScheme", colorScheme() ); - layoutGroup.writeEntry( "BackgroundColorEnabled", useBackground() ); - layoutGroup.writeEntry( "BoxEnabled", useBox() ); - layoutGroup.writeEntry( "BoxWidth", boxWidth() ); - layoutGroup.writeEntry( "BoxMargin", boxMargin() ); - layoutGroup.writeEntry( "BoxColor", boxColor() ); - - config->sync(); -} - -//END KatePrintLayout - -#include "kateprinter.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateprinter.h b/part/utils/kateprinter.h deleted file mode 100644 index ad9d475..0000000 --- a/part/utils/kateprinter.h +++ /dev/null @@ -1,160 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2002-2010 Anders Lund - * - * Rewritten based on code of Copyright (c) 2002 Michael Goffioul - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef __KATE_PRINTER_H__ -#define __KATE_PRINTER_H__ - -#include - -class KateDocument; - -class KColorButton; -class QCheckBox; -class QComboBox; -class QGroupBox; -class QLabel; -class KLineEdit; -class KIntSpinBox; -class KComboBox; - -class KatePrinter -{ - public: - static bool print (KateDocument *doc); -}; - -//BEGIN Text settings -/* - Text settings page: - - [ ] Print Selection (enabled if there is a selection in the view) - - Print Line Numbers - () Smart () Yes () No -*/ -class KatePrintTextSettings : public QWidget -{ - Q_OBJECT - public: - explicit KatePrintTextSettings( QWidget *parent=0 ); - ~KatePrintTextSettings(); - -// bool printSelection(); - bool printLineNumbers(); - bool printGuide(); - - /* call if view has a selection, enables the seelction checkbox according to the arg */ -// void enableSelection( bool ); - - private: - void readSettings(); - void writeSettings(); - - QCheckBox /* *cbSelection,*/ *cbLineNumbers, *cbGuide; -}; -//END Text Settings - -//BEGIN Header/Footer -/* - Header & Footer page: - - enable header/footer - - header/footer props - o formats - o colors -*/ - -class KatePrintHeaderFooter : public QWidget -{ - Q_OBJECT - public: - explicit KatePrintHeaderFooter( QWidget *parent=0 ); - ~KatePrintHeaderFooter(); - - QFont font(); - - bool useHeader(); - QStringList headerFormat(); - QColor headerForeground(); - QColor headerBackground(); - bool useHeaderBackground(); - - bool useFooter(); - QStringList footerFormat(); - QColor footerForeground(); - QColor footerBackground(); - bool useFooterBackground(); - - public Q_SLOTS: - void setHFFont(); - - private: - void readSettings(); - void writeSettings(); - - QCheckBox *cbEnableHeader, *cbEnableFooter; - QLabel *lFontPreview; - QGroupBox *gbHeader, *gbFooter; - KLineEdit *leHeaderLeft, *leHeaderCenter, *leHeaderRight; - KColorButton *kcbtnHeaderFg, *kcbtnHeaderBg; - QCheckBox *cbHeaderEnableBgColor; - KLineEdit *leFooterLeft, *leFooterCenter, *leFooterRight; - KColorButton *kcbtnFooterFg, *kcbtnFooterBg; - QCheckBox *cbFooterEnableBgColor; -}; - -//END Header/Footer - -//BEGIN Layout -/* - Layout page: - - Color scheme - - Use Box - - Box properties - o Width - o Margin - o Color -*/ -class KatePrintLayout : public QWidget -{ - Q_OBJECT - public: - explicit KatePrintLayout( QWidget *parent=0 ); - ~KatePrintLayout(); - - QString colorScheme(); - bool useBackground(); - bool useBox(); - int boxWidth(); - int boxMargin(); - QColor boxColor(); - - private: - void readSettings(); - void writeSettings(); - - KComboBox *cmbSchema; - QCheckBox *cbEnableBox, *cbDrawBackground; - QGroupBox *gbBoxProps; - KIntSpinBox *sbBoxWidth, *sbBoxMargin; - KColorButton* kcbtnBoxColor; -}; -//END Layout - -#endif diff --git a/part/utils/kateschema.cpp b/part/utils/kateschema.cpp deleted file mode 100644 index 40a5ba1..0000000 --- a/part/utils/kateschema.cpp +++ /dev/null @@ -1,964 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2007, 2008 Matthew Woehlke - Copyright (C) 2001-2003 Christoph Cullmann - Copyright (C) 2002, 2003 Anders Lund - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN Includes -#include "kateschema.h" -#include "kateschema.moc" - -#include "kateconfig.h" -#include "katedocument.h" -#include "kateglobal.h" -#include "kateview.h" -#include "katerenderer.h" -#include "kateextendedattribute.h" -#include "katestyletreewidget.h" - -#include "ui_schemaconfigcolortab.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -//END - - -//BEGIN KateSchemaManager -QString KateSchemaManager::normalSchema () -{ - return KGlobal::mainComponent().aboutData()->appName () + QString (" - Normal"); -} - -QString KateSchemaManager::printingSchema () -{ - return KGlobal::mainComponent().aboutData()->appName () + QString (" - Printing"); -} - -KateSchemaManager::KateSchemaManager () - : m_config ("kateschemarc", KConfig::NoGlobals) -{ - update (); -} - -KateSchemaManager::~KateSchemaManager () -{ -} - -// -// read the types from config file and update the internal list -// -void KateSchemaManager::update (bool readfromfile) -{ - if (readfromfile) - m_config.reparseConfiguration (); - - m_schemas = m_config.groupList(); - m_schemas.sort (); - - m_schemas.removeAll (printingSchema()); - m_schemas.removeAll (normalSchema()); - m_schemas.prepend (printingSchema()); - m_schemas.prepend (normalSchema()); -} - -// -// get the right group -// special handling of the default schemas ;) -// -KConfigGroup KateSchemaManager::schema (uint number) -{ - if ((number>1) && (number < (uint)m_schemas.count())) - return m_config.group (m_schemas[number]); - else if (number == 1) - return m_config.group (printingSchema()); - else - return m_config.group (normalSchema()); -} - -void KateSchemaManager::addSchema (const QString &t) -{ - m_config.group(t).writeEntry("Color Background", KColorScheme(QPalette::Active, KColorScheme::View).background().color()); - - update (false); -} - -void KateSchemaManager::removeSchema (uint number) -{ - if (number >= (uint)m_schemas.count()) - return; - - if (number < 2) - return; - - m_config.deleteGroup (name (number)); - - update (false); -} - -bool KateSchemaManager::validSchema (uint number) -{ - if (number < (uint)m_schemas.count()) - return true; - - return false; -} - -bool KateSchemaManager::validSchema (const QString &name) -{ - if (name == normalSchema() || name == printingSchema()) - return true; - - for (int i = 0; i < m_schemas.size(); ++i) - if (m_schemas[i] == name) - return true; - - return false; -} - -uint KateSchemaManager::number (const QString &name) -{ - if (name == normalSchema()) - return 0; - - if (name == printingSchema()) - return 1; - - int i; - if ((i = m_schemas.indexOf(name)) > -1) - return i; - - return 0; -} - -QString KateSchemaManager::name (uint number) -{ - if ((number>1) && (number < (uint)m_schemas.count())) - return m_schemas[number]; - else if (number == 1) - return printingSchema(); - - return normalSchema(); -} -//END - -// -// DIALOGS !!! -// - -//BEGIN KateSchemaConfigColorTab -- 'Colors' tab -KateSchemaConfigColorTab::KateSchemaConfigColorTab() - : ui(new Ui::SchemaConfigColorTab()) -{ - m_schema = -1; - - ui->setupUi(this); - - // Markers from kdelibs/interfaces/ktextinterface/markinterface.h - // add the predefined mark types as defined in markinterface.h - ui->combobox->addItem(i18n("Bookmark")); // markType01 - ui->combobox->addItem(i18n("Active Breakpoint")); // markType02 - ui->combobox->addItem(i18n("Reached Breakpoint")); // markType03 - ui->combobox->addItem(i18n("Disabled Breakpoint")); // markType04 - ui->combobox->addItem(i18n("Execution")); // markType05 - ui->combobox->addItem(i18n("Warning")); // markType06 - ui->combobox->addItem(i18n("Error")); // markType07 - ui->combobox->addItem(i18n("Template Background")); - ui->combobox->addItem(i18n("Template Editable Placeholder")); - ui->combobox->addItem(i18n("Template Focused Editable Placeholder")); - ui->combobox->addItem(i18n("Template Not Editable Placeholder")); - ui->combobox->setCurrentIndex(0); - - connect( ui->combobox , SIGNAL( activated( int ) ) , SLOT( slotComboBoxChanged( int ) ) ); - connect( ui->back , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->selected , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->current , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->bracket , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->wwmarker , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->iconborder, SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->tmarker , SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->linenumber, SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); - connect( ui->markers , SIGNAL( changed( const QColor& ) ), SLOT( slotMarkerColorChanged( const QColor& ) ) ); - connect( ui->spellingmistakeline, SIGNAL( changed( const QColor& ) ), SIGNAL( changed() ) ); -} - -KateSchemaConfigColorTab::~KateSchemaConfigColorTab() -{ - delete ui; -} - -void KateSchemaConfigColorTab::schemaChanged ( int newSchema ) -{ - // save curent schema - if ( m_schema > -1 ) - { - m_schemas[ m_schema ].back = ui->back->color(); - m_schemas[ m_schema ].selected = ui->selected->color(); - m_schemas[ m_schema ].current = ui->current->color(); - m_schemas[ m_schema ].bracket = ui->bracket->color(); - m_schemas[ m_schema ].wwmarker = ui->wwmarker->color(); - m_schemas[ m_schema ].iconborder = ui->iconborder->color(); - m_schemas[ m_schema ].tmarker = ui->tmarker->color(); - m_schemas[ m_schema ].linenumber = ui->linenumber->color(); - m_schemas[ m_schema ].spellingmistakeline = ui->spellingmistakeline->color(); - } - - if ( newSchema == m_schema ) return; - - // switch - m_schema = newSchema; - - // first block signals otherwise setColor emits changed - bool blocked = blockSignals(true); - - // If we havent this schema, read in from config file - if ( ! m_schemas.contains( newSchema ) ) - { - // fallback defaults - // NOTE keep in sync with KateRendererConfig::setSchemaInternal - KColorScheme schemeView(QPalette::Active, KColorScheme::View); - KColorScheme schemeWindow(QPalette::Active, KColorScheme::Window); - KColorScheme schemeSelection(QPalette::Active, KColorScheme::Selection); - QColor tmp0( schemeView.background().color() ); - QColor tmp1( schemeSelection.background().color() ); - QColor tmp2( schemeView.background(KColorScheme::AlternateBackground).color() ); - // using KColorUtils::shade wasn't working really well - qreal bgLuma = KColorUtils::luma( tmp0 ); - QColor tmp3( KColorUtils::tint(tmp0, schemeView.decoration(KColorScheme::HoverColor).color()) ); - QColor tmp4( KColorUtils::shade( tmp0, bgLuma > 0.3 ? -0.15 : 0.03 ) ); - QColor tmp5( KColorUtils::shade( tmp0, bgLuma > 0.7 ? -0.35 : 0.3 ) ); - QColor tmp6( schemeWindow.background().color() ); - QColor tmp7( schemeWindow.foreground().color() ); - QColor tmp8( Qt::red ); - - // same std colors like in KateDocument::markColor - QVector mark(KTextEditor::MarkInterface::reservedMarkersCount()); - Q_ASSERT(mark.size() > 6); - mark[0] = Qt::blue; - mark[1] = Qt::red; - mark[2] = Qt::yellow; - mark[3] = Qt::magenta; - mark[4] = Qt::gray; - mark[5] = Qt::green; - mark[6] = Qt::red; - - SchemaColors c; - KConfigGroup config = KateGlobal::self()->schemaManager()->schema(newSchema); - - c.back= config.readEntry("Color Background", tmp0); - c.selected = config.readEntry("Color Selection", tmp1); - c.current = config.readEntry("Color Highlighted Line", tmp2); - c.bracket = config.readEntry("Color Highlighted Bracket", tmp3); - c.wwmarker = config.readEntry("Color Word Wrap Marker", tmp4); - c.tmarker = config.readEntry("Color Tab Marker", tmp5); - c.iconborder = config.readEntry("Color Icon Bar", tmp6); - c.linenumber = config.readEntry("Color Line Number", tmp7); - c.spellingmistakeline = config.readEntry("Color Spelling Mistake Line", tmp8); - - for (int i = 0; i < KTextEditor::MarkInterface::reservedMarkersCount(); i++) - c.markerColors[i] = config.readEntry( QString("Color MarkType%1").arg(i+1), mark[i] ); - - c.templateColors[0] = config.readEntry(QString("Color Template Background"),QColor(0xcc,0xcc,0xcc)); - c.templateColors[1] = config.readEntry(QString("Color Template Editable Placeholder"),QColor(0xcc,0xff,0xcc)); - c.templateColors[2] = config.readEntry(QString("Color Template Focused Editable Placeholder"),QColor(0x66,0xff,0x66)); - c.templateColors[3] = config.readEntry(QString("Color Template Not Editable Placeholder"),QColor(0xff,0xcc,0xcc)); - - m_schemas[ newSchema ] = c; - } - - ui->back->setColor( m_schemas[ newSchema ].back); - ui->selected->setColor( m_schemas [ newSchema ].selected ); - ui->current->setColor( m_schemas [ newSchema ].current ); - ui->bracket->setColor( m_schemas [ newSchema ].bracket ); - ui->wwmarker->setColor( m_schemas [ newSchema ].wwmarker ); - ui->tmarker->setColor( m_schemas [ newSchema ].tmarker ); - ui->iconborder->setColor( m_schemas [ newSchema ].iconborder ); - ui->linenumber->setColor( m_schemas [ newSchema ].linenumber ); - ui->spellingmistakeline->setColor( m_schemas [ newSchema ].spellingmistakeline ); - - // map from 0..reservedMarkersCount()-1 - the same index as in markInterface - for (int i = 0; i < KTextEditor::MarkInterface::reservedMarkersCount(); i++) - { - QPixmap pix(16, 16); - pix.fill( m_schemas [ newSchema ].markerColors[i]); - ui->combobox->setItemIcon(i, QIcon(pix)); - } - for (int i = 0; i < 4; i++) - { - QPixmap pix(16, 16); - pix.fill( m_schemas [ newSchema ].templateColors[i]); - ui->combobox->setItemIcon(i+KTextEditor::MarkInterface::reservedMarkersCount(), QIcon(pix)); - } - - ui->markers->setColor( m_schemas [ newSchema ].markerColors[ ui->combobox->currentIndex() ] ); - - blockSignals(blocked); -} - -void KateSchemaConfigColorTab::apply () -{ - schemaChanged( m_schema ); - QMap::Iterator it; - for ( it = m_schemas.begin(); it != m_schemas.end(); ++it ) - { - kDebug(13030)<<"APPLY scheme = "<schemaManager()->schema( it.key() ); - kDebug(13030)<<"Using config group "<combobox->currentIndex(); - if (index<7) - m_schemas[ m_schema ].markerColors[ index ] = color; - else - m_schemas[m_schema].templateColors[index-7] = color; - QPixmap pix(16, 16); - pix.fill(color); - ui->combobox->setItemIcon(index, QIcon(pix)); - - emit changed(); -} - -void KateSchemaConfigColorTab::slotComboBoxChanged(int index) -{ - // temporarily block signals because setColor emits changed as well - bool blocked = ui->markers->blockSignals(true); - if (index<7) - ui->markers->setColor( m_schemas[m_schema].markerColors[index] ); - else - ui->markers->setColor( m_schemas[m_schema].templateColors[index-7] ); - ui->markers->blockSignals(blocked); -} - -//END KateSchemaConfigColorTab - -//BEGIN FontConfig -- 'Fonts' tab -KateSchemaConfigFontTab::KateSchemaConfigFontTab() -{ - // sizemanagment - QGridLayout *grid = new QGridLayout( this ); - - m_fontchooser = new KFontChooser ( this, KFontChooser::NoDisplayFlags ); - grid->addWidget( m_fontchooser, 0, 0); - - m_schema = -1; -} - -KateSchemaConfigFontTab::~KateSchemaConfigFontTab() -{ -} - -void KateSchemaConfigFontTab::slotFontSelected( const QFont &font ) -{ - if ( m_schema > -1 ) - { - m_fonts[m_schema] = font; - emit changed(); - } -} - -void KateSchemaConfigFontTab::apply() -{ - FontMap::Iterator it; - for ( it = m_fonts.begin(); it != m_fonts.end(); ++it ) - { - KateGlobal::self()->schemaManager()->schema( it.key() ).writeEntry( "Font", it.value() ); - } -} - -void KateSchemaConfigFontTab::schemaChanged( int newSchema ) -{ - if ( m_schema > -1 ) - m_fonts[ m_schema ] = m_fontchooser->font(); - - m_schema = newSchema; - - QFont f (KGlobalSettings::fixedFont()); - - m_fontchooser->disconnect ( this ); - m_fontchooser->setFont ( KateGlobal::self()->schemaManager()->schema( newSchema ).readEntry("Font", f) ); - m_fonts[ newSchema ] = m_fontchooser->font(); - connect (m_fontchooser, SIGNAL (fontSelected( const QFont & )), this, SLOT (slotFontSelected( const QFont & ))); -} -//END FontConfig - -//BEGIN FontColorConfig -- 'Normal Text Styles' tab -KateSchemaConfigFontColorTab::KateSchemaConfigFontColorTab() -{ - // sizemanagment - QGridLayout *grid = new QGridLayout( this ); - - m_defaultStyles = new KateStyleTreeWidget( this ); - m_defaultStyles->setRootIsDecorated(false); - connect(m_defaultStyles, SIGNAL(changed()), this, SIGNAL(changed())); - grid->addWidget( m_defaultStyles, 0, 0); - - m_defaultStyles->setWhatsThis(i18n( - "

This list displays the default styles for the current schema and " - "offers the means to edit them. The style name reflects the current " - "style settings.

" - "

To edit the colors, click the colored squares, or select the color " - "to edit from the popup menu.

You can unset the Background and Selected " - "Background colors from the popup menu when appropriate.

") ); -} - -KateSchemaConfigFontColorTab::~KateSchemaConfigFontColorTab() -{ - qDeleteAll(m_defaultStyleLists); -} - -KateAttributeList *KateSchemaConfigFontColorTab::attributeList (uint schema) -{ - if (!m_defaultStyleLists.contains(schema)) - { - KateAttributeList *list = new KateAttributeList (); - KateHlManager::self()->getDefaults(KateGlobal::self()->schemaManager()->name (schema), *list); - - m_defaultStyleLists.insert (schema, list); - } - - return m_defaultStyleLists[schema]; -} - -void KateSchemaConfigFontColorTab::schemaChanged (uint schema) -{ - m_defaultStyles->clear (); - - KateAttributeList *l = attributeList (schema); - - // set colors - QPalette p ( m_defaultStyles->palette() ); - KColorScheme s ( QPalette::Active, KColorScheme::View ); - QColor _c ( s.background().color() ); - p.setColor( QPalette::Base, - KateGlobal::self()->schemaManager()->schema(schema). - readEntry( "Color Background", _c ) ); - _c = KColorScheme(QPalette::Active, KColorScheme::Selection).background().color(); - p.setColor( QPalette::Highlight, - KateGlobal::self()->schemaManager()->schema(schema). - readEntry( "Color Selection", _c ) ); - _c = l->at(0)->foreground().color(); // not quite as much of an assumption ;) - p.setColor( QPalette::Text, _c ); - m_defaultStyles->viewport()->setPalette( p ); - - for ( uint i = 0; i < KateHlManager::self()->defaultStyles(); i++ ) - { - m_defaultStyles->addItem( KateHlManager::self()->defaultStyleName(i, true), l->at( i ) ); - } -} - -void KateSchemaConfigFontColorTab::reload () -{ - m_defaultStyles->clear (); - qDeleteAll(m_defaultStyleLists); - m_defaultStyleLists.clear (); -} - -void KateSchemaConfigFontColorTab::apply () -{ - QHashIterator it = m_defaultStyleLists; - while (it.hasNext()) { - it.next(); - KateHlManager::self()->setDefaults(KateGlobal::self()->schemaManager()->name (it.key()), *it.value()); - } -} - -//END FontColorConfig - -//BEGIN KateSchemaConfigHighlightTab -- 'Highlighting Text Styles' tab -KateSchemaConfigHighlightTab::KateSchemaConfigHighlightTab(KateSchemaConfigFontColorTab *page) -{ - m_defaults = page; - - m_schema = 0; - m_hl = 0; - - QVBoxLayout *layout = new QVBoxLayout(this); - - // hl chooser - KHBox *hbHl = new KHBox( this ); - layout->addWidget (hbHl); - - hbHl->setSpacing( -1 ); - QLabel *lHl = new QLabel( i18n("H&ighlight:"), hbHl ); - hlCombo = new KComboBox( hbHl ); - hlCombo->setEditable( false ); - lHl->setBuddy( hlCombo ); - connect( hlCombo, SIGNAL(activated(int)), - this, SLOT(hlChanged(int)) ); - - for( int i = 0; i < KateHlManager::self()->highlights(); i++) { - if (KateHlManager::self()->hlSection(i).length() > 0) - hlCombo->addItem(KateHlManager::self()->hlSection(i) + QString ("/") + KateHlManager::self()->hlNameTranslated(i)); - else - hlCombo->addItem(KateHlManager::self()->hlNameTranslated(i)); - } - hlCombo->setCurrentIndex(0); - - // styles listview - m_styles = new KateStyleTreeWidget( this, true ); - connect(m_styles, SIGNAL(changed()), this, SIGNAL(changed())); - layout->addWidget (m_styles, 999); - - // get current highlighting from the host application - int hl = 0; - KTextEditor::MdiContainer *iface = qobject_cast(KateGlobal::self()->container()); - if (iface) { - KateView *kv = qobject_cast(iface->activeView()); - if (kv) { - const QString hlName = kv->doc()->highlight()->name(); - hl = KateHlManager::self()->nameFind(hlName); - } - } - hlCombo->setCurrentIndex ( hl ); - hlChanged ( hl ); - - m_styles->setWhatsThis(i18n( - "

This list displays the contexts of the current syntax highlight mode and " - "offers the means to edit them. The context name reflects the current " - "style settings.

To edit using the keyboard, press " - "<SPACE> and choose a property from the popup menu.

" - "

To edit the colors, click the colored squares, or select the color " - "to edit from the popup menu.

You can unset the Background and Selected " - "Background colors from the context menu when appropriate.

") ); -} - -KateSchemaConfigHighlightTab::~KateSchemaConfigHighlightTab() -{ -} - -void KateSchemaConfigHighlightTab::hlChanged(int z) -{ - m_hl = z; - - schemaChanged (m_schema); -} - -void KateSchemaConfigHighlightTab::schemaChanged (int schema) -{ - m_schema = schema; - - kDebug(13030) << "NEW SCHEMA: " << m_schema << " NEW HL: " << m_hl; - - m_styles->clear (); - - if (!m_hlDict.contains(m_schema)) - { - kDebug(13030) << "NEW SCHEMA, create dict"; - - m_hlDict.insert (schema, QHash >()); - } - - if (!m_hlDict[m_schema].contains(m_hl)) - { - kDebug(13030) << "NEW HL, create list"; - - QList list; - KateHlManager::self()->getHl( m_hl )->getKateExtendedAttributeListCopy(KateGlobal::self()->schemaManager()->name (m_schema), list); - m_hlDict[m_schema].insert (m_hl, list); - } - - KateAttributeList *l = m_defaults->attributeList (schema); - - // Set listview colors - // We do that now, because we can now get the "normal text" color. - // TODO this reads of the KConfig object, which should be changed when - // the color tab is fixed. - QPalette p ( m_styles->palette() ); - KColorScheme s ( QPalette::Active, KColorScheme::View ); - QColor _c ( s.background().color() ); - p.setColor( QPalette::Base, - KateGlobal::self()->schemaManager()->schema(m_schema). - readEntry( "Color Background", _c ) ); - _c = KColorScheme(QPalette::Active, KColorScheme::Selection).background().color(); - p.setColor( QPalette::Highlight, - KateGlobal::self()->schemaManager()->schema(m_schema). - readEntry( "Color Selection", _c ) ); - _c = l->at(0)->foreground().color(); // not quite as much of an assumption ;) - p.setColor( QPalette::Text, _c ); - m_styles->viewport()->setPalette( p ); - - QHash prefixes; - QList::ConstIterator it = m_hlDict[m_schema][m_hl].constBegin(); - while (it != m_hlDict[m_schema][m_hl].constEnd()) - { - const KateExtendedAttribute::Ptr itemData = *it; - Q_ASSERT(itemData); - - kDebug(13030) << "insert items " << itemData->name(); - - // All stylenames have their language mode prefixed, e.g. HTML:Comment - // split them and put them into nice substructures. - int c = itemData->name().indexOf(':'); - if ( c > 0 ) { - QString prefix = itemData->name().left(c); - QString name = itemData->name().mid(c+1); - - QTreeWidgetItem *parent = prefixes[prefix]; - if ( ! parent ) - { - parent = new QTreeWidgetItem( m_styles, QStringList() << prefix ); - m_styles->expandItem(parent); - prefixes.insert( prefix, parent ); - } - m_styles->addItem( parent, name, l->at(itemData->defaultStyleIndex()), itemData ); - } else { - m_styles->addItem( itemData->name(), l->at(itemData->defaultStyleIndex()), itemData ); - } - ++it; - } - - m_styles->resizeColumns(); -} - -void KateSchemaConfigHighlightTab::reload () -{ - m_styles->clear (); - - m_hlDict.clear (); - - hlChanged (0); -} - -void KateSchemaConfigHighlightTab::apply () -{ - QMutableHashIterator > > it = m_hlDict; - while (it.hasNext()) { - it.next(); - QMutableHashIterator > it2 = it.value(); - while (it2.hasNext()) { - it2.next(); - KateHlManager::self()->getHl( it2.key() )->setKateExtendedAttributeList (it.key(), it2.value()); - } - } -} - -//END KateSchemaConfigHighlightTab - -//BEGIN KateSchemaConfigPage -- Main dialog page -KateSchemaConfigPage::KateSchemaConfigPage( QWidget *parent) - : KateConfigPage( parent ), - m_lastSchema (-1) -{ - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setMargin(0); - - KHBox *hbHl = new KHBox( this ); - layout->addWidget(hbHl); - hbHl->setSpacing( -1 ); - QLabel *lHl = new QLabel( i18n("&Schema:"), hbHl ); - schemaCombo = new KComboBox( hbHl ); - schemaCombo->setEditable( false ); - lHl->setBuddy( schemaCombo ); - connect( schemaCombo, SIGNAL(activated(int)), - this, SLOT(schemaChanged(int)) ); - - QPushButton *btnnew = new QPushButton( i18n("&New..."), hbHl ); - connect( btnnew, SIGNAL(clicked()), this, SLOT(newSchema()) ); - - btndel = new QPushButton( i18n("&Delete"), hbHl ); - connect( btndel, SIGNAL(clicked()), this, SLOT(deleteSchema()) ); - - qobject_cast(hbHl->layout())->addStretch(); - - m_tabWidget = new KTabWidget ( this ); - layout->addWidget (m_tabWidget); - - m_colorTab = new KateSchemaConfigColorTab(); - m_tabWidget->addTab (m_colorTab, i18n("Colors")); - connect(m_colorTab, SIGNAL(changed()), SLOT(slotChanged())); - - m_fontTab = new KateSchemaConfigFontTab(); - m_tabWidget->addTab (m_fontTab, i18n("Font")); - connect(m_fontTab, SIGNAL(changed()), SLOT(slotChanged())); - - m_fontColorTab = new KateSchemaConfigFontColorTab(); - m_tabWidget->addTab (m_fontColorTab, i18n("Normal Text Styles")); - connect(m_fontColorTab, SIGNAL(changed()), SLOT(slotChanged())); - - m_highlightTab = new KateSchemaConfigHighlightTab(m_fontColorTab); - m_tabWidget->addTab(m_highlightTab, i18n("Highlighting Text Styles")); - connect(m_highlightTab, SIGNAL(changed()), SLOT(slotChanged())); - - connect (m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT (newCurrentPage(int))); - - hbHl = new KHBox( this ); - layout->addWidget (hbHl); - hbHl->setSpacing( -1 ); - lHl = new QLabel( i18n("&Default schema for %1:", KGlobal::mainComponent().aboutData()->programName ()), hbHl ); - defaultSchemaCombo = new KComboBox( hbHl ); - defaultSchemaCombo->setEditable( false ); - lHl->setBuddy( defaultSchemaCombo ); - - m_defaultSchema = KateGlobal::self()->schemaManager()->number (KateRendererConfig::global()->schema()); - - reload(); - - connect( defaultSchemaCombo, SIGNAL(activated(int)), - this, SLOT(slotChanged()) ); -} - -KateSchemaConfigPage::~KateSchemaConfigPage () -{ - // just reload config from disc - KateGlobal::self()->schemaManager()->update (); -} - -void KateSchemaConfigPage::apply() -{ - m_colorTab->apply(); - m_fontTab->apply(); - m_fontColorTab->apply (); - m_highlightTab->apply (); - - // just sync the config - KateGlobal::self()->schemaManager()->schema (0).sync(); - - KateGlobal::self()->schemaManager()->update (); - - // clear all attributes - for (int i = 0; i < KateHlManager::self()->highlights(); ++i) - KateHlManager::self()->getHl (i)->clearAttributeArrays(); - - // than reload the whole stuff - KateRendererConfig::global()->setSchema (KateGlobal::self()->schemaManager()->name (defaultSchemaCombo->currentIndex())); - KateRendererConfig::global()->reloadSchema(); - - // sync the hl config for real - KateHlManager::self()->getKConfig()->sync (); -} - -void KateSchemaConfigPage::reload() -{ - // just reload the config from disc - KateGlobal::self()->schemaManager()->update (); - - // special for the highlighting stuff - m_fontColorTab->reload (); - - update (); - - defaultSchemaCombo->setCurrentIndex (KateGlobal::self()->schemaManager()->number (KateRendererConfig::global()->schema())); - - // initialize to the schema in the current document, or default schema - schemaCombo->setCurrentIndex( m_defaultSchema ); - schemaChanged( m_defaultSchema ); -} - -void KateSchemaConfigPage::reset() -{ - reload (); -} - -void KateSchemaConfigPage::defaults() -{ - reload (); -} - -void KateSchemaConfigPage::update () -{ - // soft update, no load from disk - KateGlobal::self()->schemaManager()->update (false); - - schemaCombo->clear (); - schemaCombo->addItems (KateGlobal::self()->schemaManager()->list ()); - - defaultSchemaCombo->clear (); - defaultSchemaCombo->addItems (KateGlobal::self()->schemaManager()->list ()); - - schemaCombo->setCurrentIndex (0); - schemaChanged (0); - - schemaCombo->setEnabled (schemaCombo->count() > 0); -} - -void KateSchemaConfigPage::deleteSchema () -{ - int t = schemaCombo->currentIndex (); - - KateGlobal::self()->schemaManager()->removeSchema (t); - - update (); -} - -void KateSchemaConfigPage::newSchema () -{ - QString t = KInputDialog::getText (i18n("Name for New Schema"), i18n ("Name:"), i18n("New Schema"), 0, this); - - KateGlobal::self()->schemaManager()->addSchema (t); - - // soft update, no load from disk - KateGlobal::self()->schemaManager()->update (false); - int i = KateGlobal::self()->schemaManager()->list ().indexOf (t); - - update (); - if (i > -1) - { - schemaCombo->setCurrentIndex (i); - schemaChanged (i); - } -} - -void KateSchemaConfigPage::schemaChanged (int schema) -{ - btndel->setEnabled( schema > 1 ); - - m_colorTab->schemaChanged( schema ); - m_fontTab->schemaChanged( schema ); - m_fontColorTab->schemaChanged (schema); - m_highlightTab->schemaChanged (schema); - - m_lastSchema = schema; -} - -void KateSchemaConfigPage::newCurrentPage (int index) -{ - QWidget *w = m_tabWidget->widget(index); - if (w == m_highlightTab) - m_highlightTab->schemaChanged (m_lastSchema); -} -//END KateSchemaConfigPage - -//BEGIN SCHEMA ACTION -- the 'View->Schema' menu action -void KateViewSchemaAction::init() -{ - m_group=0; - m_view = 0; - last = 0; - - connect(menu(),SIGNAL(aboutToShow()),this,SLOT(slotAboutToShow())); -} - -void KateViewSchemaAction::updateMenu (KateView *view) -{ - m_view = view; -} - -void KateViewSchemaAction::slotAboutToShow() -{ - KateView *view=m_view; - int count = KateGlobal::self()->schemaManager()->list().count(); - - if (!m_group) { - m_group=new QActionGroup(menu()); - m_group->setExclusive(true); - - } - - for (int z=0; zschemaManager()->list().operator[](z); - - if (!names.contains(hlName)) - { - names << hlName; - QAction *a=menu()->addAction ( hlName, this, SLOT(setSchema())); - a->setData(hlName); - a->setCheckable(true); - a->setActionGroup(m_group); - //FIXME EXCLUSIVE - } - } - - if (!view) return; - - QString id=view->renderer()->config()->schema(); - foreach(QAction *a,menu()->actions()) { - a->setChecked(a->data().toString()==id); - - } -//FIXME -#if 0 - popupMenu()->setItemChecked (last, false); - popupMenu()->setItemChecked (view->renderer()->config()->schema()+1, true); - - last = view->renderer()->config()->schema()+1; -#endif -} - -void KateViewSchemaAction::setSchema () { - QAction *action = qobject_cast(sender()); - - if (!action) return; - QString mode=action->data().toString(); - - KateView *view=m_view; - - if (view) - view->renderer()->config()->setSchema (mode); -} -//END SCHEMA ACTION - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/kateschema.h b/part/utils/kateschema.h deleted file mode 100644 index 4d423d8..0000000 --- a/part/utils/kateschema.h +++ /dev/null @@ -1,279 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001-2003 Christoph Cullmann - Copyright (C) 2002, 2003 Anders Lund - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_SCHEMA_H__ -#define __KATE_SCHEMA_H__ - -#include "katehighlight.h" -#include "katedialogs.h" - -#include -#include -#include - -#include -#include - -class KateView; -class KateStyleTreeWidget; - - -class QAction; -class QActionGroup; -class KComboBox; -class KTabWidget; - -namespace Ui { class SchemaConfigColorTab; } - -class KateSchemaManager -{ - public: - KateSchemaManager (); - ~KateSchemaManager (); - - /** - * Schema Config changed, update all renderers - */ - void update (bool readfromfile = true); - - /** - * return kconfig with right group set or set to Normal if not there - */ - KConfigGroup schema (uint number); - - void addSchema (const QString &t); - - void removeSchema (uint number); - - /** - * is this schema valid ? (does it exist ?) - */ - bool validSchema (uint number); - bool validSchema (const QString &name); - - /** - * if not found, defaults to 0 - */ - uint number (const QString &name); - - /** - * group names in the end, no i18n involved - */ - QString name (uint number); - - /** - * Don't modify, list with the names of the schemas (i18n name for the default ones) - */ - const QStringList &list () { return m_schemas; } - - static QString normalSchema (); - static QString printingSchema (); - - private: - KConfig m_config; - QStringList m_schemas; -}; - - -class KateViewSchemaAction : public KActionMenu -{ - Q_OBJECT - - public: - KateViewSchemaAction(const QString& text, QObject *parent) - : KActionMenu(text, parent) { init(); } - - void updateMenu (KateView *view); - - private: - void init(); - - QPointer m_view; - QStringList names; - QActionGroup *m_group; - int last; - - public Q_SLOTS: - void slotAboutToShow(); - - private Q_SLOTS: - void setSchema(); -}; - -// -// DIALOGS -// - -class KateSchemaConfigColorTab : public QWidget -{ - Q_OBJECT - - public: - KateSchemaConfigColorTab(); - ~KateSchemaConfigColorTab(); - - private: - // Class for storing the properties on 1 schema. - class SchemaColors { - public: - QColor back, selected, current, bracket, wwmarker, iconborder, tmarker, linenumber, spellingmistakeline; - QMap markerColors; // stores all markerColors - QMap templateColors; - }; - - // schemaid=data, created when a schema is entered - QMap m_schemas; - // current schema - int m_schema; - - Ui::SchemaConfigColorTab* ui; - - public Q_SLOTS: - void apply(); - void schemaChanged( int newSchema ); - - Q_SIGNALS: - void changed(); - - protected Q_SLOTS: - void slotMarkerColorChanged(const QColor&); - void slotComboBoxChanged(int index); -}; - -typedef QMap FontMap; // ### remove it - -class KateSchemaConfigFontTab : public QWidget -{ - Q_OBJECT - - public: - KateSchemaConfigFontTab(); - ~KateSchemaConfigFontTab(); - - public: - void readConfig (KConfig *config); - - public Q_SLOTS: - void apply(); - void schemaChanged( int newSchema ); - - Q_SIGNALS: - void changed(); - - private: - class KFontChooser *m_fontchooser; - FontMap m_fonts; - int m_schema; - - private Q_SLOTS: - void slotFontSelected( const QFont &font ); -}; - -class KateSchemaConfigFontColorTab : public QWidget -{ - Q_OBJECT - - public: - KateSchemaConfigFontColorTab(); - ~KateSchemaConfigFontColorTab(); - - Q_SIGNALS: - void changed(); - - public: - void schemaChanged (uint schema); - void reload (); - void apply (); - - KateAttributeList *attributeList (uint schema); - - private: - KateStyleTreeWidget* m_defaultStyles; - QHash m_defaultStyleLists; -}; - -class KateSchemaConfigHighlightTab : public QWidget -{ - Q_OBJECT - - public: - explicit KateSchemaConfigHighlightTab(KateSchemaConfigFontColorTab *page = 0); - ~KateSchemaConfigHighlightTab(); - - void schemaChanged (int schema); - void reload (); - void apply (); - - Q_SIGNALS: - void changed(); - - protected Q_SLOTS: - void hlChanged(int z); - - private: - KateSchemaConfigFontColorTab *m_defaults; - - KComboBox *hlCombo; - KateStyleTreeWidget *m_styles; - - int m_schema; - int m_hl; - - QHash > > m_hlDict; -}; - -class KateSchemaConfigPage : public KateConfigPage -{ - Q_OBJECT - - public: - explicit KateSchemaConfigPage ( QWidget *parent); - ~KateSchemaConfigPage (); - - public Q_SLOTS: - void apply(); - void reload(); - void reset(); - void defaults(); - - private Q_SLOTS: - void update (); - void deleteSchema (); - void newSchema (); - void schemaChanged (int schema); - - void newCurrentPage(int); - - private: - int m_lastSchema; - int m_defaultSchema; - - class KTabWidget *m_tabWidget; - class QPushButton *btndel; - class KComboBox *defaultSchemaCombo; - class KComboBox *schemaCombo; - KateSchemaConfigColorTab *m_colorTab; - KateSchemaConfigFontTab *m_fontTab; - KateSchemaConfigFontColorTab *m_fontColorTab; - KateSchemaConfigHighlightTab *m_highlightTab; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/utils/katestyletreewidget.cpp b/part/utils/katestyletreewidget.cpp deleted file mode 100644 index 3702eb5..0000000 --- a/part/utils/katestyletreewidget.cpp +++ /dev/null @@ -1,723 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001-2003 Christoph Cullmann - Copyright (C) 2002, 2003 Anders Lund - Copyright (C) 2005-2006 Hamish Rodda - Copyright (C) 2007 Mirko Stocker - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "katestyletreewidget.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "kateconfig.h" -#include "kateextendedattribute.h" - -//BEGIN KateStyleTreeDelegate -class KateStyleTreeDelegate : public QStyledItemDelegate -{ - public: - KateStyleTreeDelegate(KateStyleTreeWidget* widget); - - virtual void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const; - - private: - QBrush getBrushForColorColumn(const QModelIndex& index, int column) const; - KateStyleTreeWidget* m_widget; -}; -//END - -//BEGIN KateStyleTreeWidgetItem decl -/* - QListViewItem subclass to display/edit a style, bold/italic is check boxes, - normal and selected colors are boxes, which will display a color chooser when - activated. - The context name for the style will be drawn using the editor default font and - the chosen colors. - This widget id designed to handle the default as well as the individual hl style - lists. - This widget is designed to work with the KateStyleTreeWidget class exclusively. - Added by anders, jan 23 2002. -*/ -class KateStyleTreeWidgetItem : public QTreeWidgetItem -{ - public: - KateStyleTreeWidgetItem( QTreeWidgetItem *parent, const QString& styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data = KateExtendedAttribute::Ptr() ); - KateStyleTreeWidgetItem( QTreeWidget *parent, const QString& styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data = KateExtendedAttribute::Ptr() ); - ~KateStyleTreeWidgetItem() {} - - enum columns { - Context = 0, - Bold, - Italic, - Underline, - StrikeOut, - Foreground, - SelectedForeground, - Background, - SelectedBackground, - UseDefaultStyle, - NumColumns - }; - - /* initializes the style from the default and the hldata */ - void initStyle(); - /* updates the hldata's style */ - void updateStyle(); - /* For bool fields, toggles them, for color fields, display a color chooser */ - void changeProperty( int p ); - /** unset a color. - * c is 100 (BGColor) or 101 (SelectedBGColor) for now. - */ - void unsetColor( int c ); - /* style context name */ - QString contextName() const { return text(0); } - /* only true for a hl mode item using it's default style */ - bool defStyle() const; - /* true for default styles */ - bool isDefault() const; - /* whichever style is active (currentStyle for hl mode styles not using - the default style, defaultStyle otherwise) */ - KTextEditor::Attribute::Ptr style() const { return currentStyle; } - - virtual QVariant data( int column, int role ) const; - - KateStyleTreeWidget* treeWidget() const; - - private: - /* private methods to change properties */ - void toggleDefStyle(); - void setColor( int ); - /* helper function to copy the default style into the KateExtendedAttribute, - when a property is changed and we are using default style. */ - - KTextEditor::Attribute::Ptr currentStyle, // the style currently in use (was "is") - defaultStyle; // default style for hl mode contexts and default styles (was "ds") - KateExtendedAttribute::Ptr actualStyle; // itemdata for hl mode contexts (was "st") -}; -//END - - -//BEGIN KateStyleTreeWidget -KateStyleTreeWidget::KateStyleTreeWidget( QWidget *parent, bool showUseDefaults ) - : QTreeWidget( parent ) -{ - setItemDelegate(new KateStyleTreeDelegate(this)); - - QStringList headers; - headers << i18nc("@title:column Meaning of text in editor", "Context") << QString() << QString() << QString() << QString() << i18nc("@title:column Text style", "Normal") << i18nc("@title:column Text style", "Selected") << i18nc("@title:column Text style", "Background") << i18nc("@title:column Text style", "Background Selected"); - if(showUseDefaults) { - headers << i18n("Use Default Style"); - } - - setHeaderLabels(headers); - - headerItem()->setIcon(1, KIcon("format-text-bold")); - headerItem()->setIcon(2, KIcon("format-text-italic")); - headerItem()->setIcon(3, KIcon("format-text-underline")); - headerItem()->setIcon(4, KIcon("format-text-strikethrough")); - - // grap the bg color, selected color and default font - normalcol = KColorScheme(QPalette::Active, KColorScheme::View).foreground().color(); - bgcol = KateRendererConfig::global()->backgroundColor(); - selcol = KateRendererConfig::global()->selectionColor(); - docfont = KateRendererConfig::global()->font(); - - QPalette pal = viewport()->palette(); - pal.setColor(QPalette::Background, bgcol); - viewport()->setPalette( pal ); -} - -QIcon brushIcon(const QColor& color) -{ - QPixmap pm(16,16); - QRect all(0,0,15,15); - { - QPainter p(&pm); - p.fillRect(all, color); - p.setPen(Qt::black); - p.drawRect(all); - } - return QIcon(pm); -} - -bool KateStyleTreeWidget::edit( const QModelIndex & index, EditTrigger trigger, QEvent * event ) -{ - if(index.column() == KateStyleTreeWidgetItem::Context) - return false; - - KateStyleTreeWidgetItem *i = dynamic_cast(itemFromIndex(index)); - if (!i) - return QTreeWidget::edit(index, trigger, event); - - switch (trigger) { - case QAbstractItemView::DoubleClicked: - case QAbstractItemView::SelectedClicked: - case QAbstractItemView::EditKeyPressed: - i->changeProperty(index.column()); - update(index); - update(index.sibling(index.row(), KateStyleTreeWidgetItem::Context)); - return false; - default: - return QTreeWidget::edit(index, trigger, event); - } -} - -void KateStyleTreeWidget::resizeColumns() -{ - for (int i = 0; i < columnCount(); ++i) - resizeColumnToContents(i); -} - -void KateStyleTreeWidget::showEvent( QShowEvent * event ) -{ - QTreeWidget::showEvent(event); - - resizeColumns(); -} - -void KateStyleTreeWidget::contextMenuEvent( QContextMenuEvent * event ) -{ - KateStyleTreeWidgetItem *i = dynamic_cast(itemAt(event->pos())); - if (!i) return; - - KMenu m( this ); - KTextEditor::Attribute::Ptr currentStyle = i->style(); - // the title is used, because the menu obscures the context name when - // displayed on behalf of spacePressed(). - QPainter p; - p.setPen(Qt::black); - - QIcon cl = brushIcon( i->style()->foreground().color() ); - QIcon scl = brushIcon( i->style()->selectedForeground().color() ); - QIcon bgcl = brushIcon( i->style()->hasProperty(QTextFormat::BackgroundBrush) ? i->style()->background().color() : viewport()->palette().base().color() ); - QIcon sbgcl = brushIcon( i->style()->hasProperty(KTextEditor::Attribute::SelectedBackground) ? i->style()->selectedBackground().color() : viewport()->palette().base().color() ); - - m.addTitle( i->contextName() ); - - QAction* a = m.addAction( i18n("&Bold"), this, SLOT(changeProperty()) ); - a->setCheckable(true); - a->setChecked( currentStyle->fontBold() ); - a->setData(KateStyleTreeWidgetItem::Bold); - - a = m.addAction( i18n("&Italic"), this, SLOT(changeProperty()) ); - a->setCheckable(true); - a->setChecked( currentStyle->fontItalic() ); - a->setData(KateStyleTreeWidgetItem::Italic); - - a = m.addAction( i18n("&Underline"), this, SLOT(changeProperty()) ); - a->setCheckable(true); - a->setChecked( currentStyle->fontUnderline() ); - a->setData(KateStyleTreeWidgetItem::Underline); - - a = m.addAction( i18n("S&trikeout"), this, SLOT(changeProperty()) ); - a->setCheckable(true); - a->setChecked( currentStyle->fontStrikeOut() ); - a->setData(KateStyleTreeWidgetItem::StrikeOut); - - m.addSeparator(); - - a = m.addAction( cl, i18n("Normal &Color..."), this, SLOT(changeProperty()) ); - a->setData(KateStyleTreeWidgetItem::Foreground); - - a = m.addAction( scl, i18n("&Selected Color..."), this, SLOT(changeProperty()) ); - a->setData(KateStyleTreeWidgetItem::SelectedForeground); - - a = m.addAction( bgcl, i18n("&Background Color..."), this, SLOT(changeProperty()) ); - a->setData(KateStyleTreeWidgetItem::Background); - - a = m.addAction( sbgcl, i18n("S&elected Background Color..."), this, SLOT(changeProperty()) ); - a->setData(KateStyleTreeWidgetItem::SelectedBackground); - - // Unset [some] colors. I could show one only if that button was clicked, but that - // would disable setting this with the keyboard (how many aren't doing just - // that every day? ;) - // ANY ideas for doing this in a nicer way will be warmly wellcomed. - KTextEditor::Attribute::Ptr style = i->style(); - if ( style->hasProperty( QTextFormat::BackgroundBrush) || style->hasProperty( KTextEditor::Attribute::SelectedBackground ) ) - { - m.addSeparator(); - if ( style->hasProperty( QTextFormat::BackgroundBrush) ) { - a = m.addAction( i18n("Unset Background Color"), this, SLOT(unsetColor()) ); - a->setData(100); - } - if ( style->hasProperty( KTextEditor::Attribute::SelectedBackground ) ) { - a = m.addAction( i18n("Unset Selected Background Color"), this, SLOT(unsetColor()) ); - a->setData(101); - } - } - - if ( ! i->isDefault() && ! i->defStyle() ) { - m.addSeparator(); - a = m.addAction( i18n("Use &Default Style"), this, SLOT(changeProperty()) ); - a->setCheckable(true); - a->setChecked( i->defStyle() ); - a->setData(KateStyleTreeWidgetItem::UseDefaultStyle); - } - m.exec( event->globalPos() ); -} - -void KateStyleTreeWidget::changeProperty() -{ - ((KateStyleTreeWidgetItem*)currentItem())->changeProperty( static_cast(sender())->data().toInt() ); -} - -void KateStyleTreeWidget::unsetColor() -{ - ((KateStyleTreeWidgetItem*)currentItem())->unsetColor( static_cast(sender())->data().toInt() ); -} - -void KateStyleTreeWidget::updateGroupHeadings() -{ - for(int i = 0; i < topLevelItemCount(); i++) { - QTreeWidgetItem* currentTopLevelItem = topLevelItem(i); - QTreeWidgetItem* firstChild = currentTopLevelItem->child(0); - - if(firstChild) { - QColor foregroundColor = firstChild->data(KateStyleTreeWidgetItem::Foreground, Qt::DisplayRole).value(); - QColor backgroundColor = firstChild->data(KateStyleTreeWidgetItem::Background, Qt::DisplayRole).value(); - - currentTopLevelItem->setForeground(KateStyleTreeWidgetItem::Context, foregroundColor); - - if(backgroundColor.isValid()) { - currentTopLevelItem->setBackground(KateStyleTreeWidgetItem::Context, backgroundColor); - } - } - } -} - -void KateStyleTreeWidget::emitChanged( ) -{ - updateGroupHeadings(); - emit changed(); -} - -void KateStyleTreeWidget::addItem( const QString & styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data ) -{ - new KateStyleTreeWidgetItem(this, styleName, defaultstyle, data); -} - -void KateStyleTreeWidget::addItem( QTreeWidgetItem * parent, const QString & styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data ) -{ - new KateStyleTreeWidgetItem(parent, styleName, defaultstyle, data); - updateGroupHeadings(); -} -//END - -//BEGIN KateStyleTreeWidgetItem -static const int BoxSize = 16; -static const int ColorBtnWidth = 32; - -KateStyleTreeDelegate::KateStyleTreeDelegate(KateStyleTreeWidget* widget) - : m_widget(widget) -{ -} - -QBrush KateStyleTreeDelegate::getBrushForColorColumn(const QModelIndex& index, int column) const -{ - QModelIndex colorIndex = index.sibling(index.row(), column); - QVariant displayData = colorIndex.model()->data(colorIndex); - return qVariantValue(displayData); -} - -void KateStyleTreeDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const -{ - static QSet columns; - if (!columns.count()) - columns << KateStyleTreeWidgetItem::Foreground << KateStyleTreeWidgetItem::SelectedForeground << KateStyleTreeWidgetItem::Background << KateStyleTreeWidgetItem::SelectedBackground; - - if(index.column() == KateStyleTreeWidgetItem::Context) { - QStyleOptionViewItem styleContextItem(option); - - QBrush brush = getBrushForColorColumn(index, KateStyleTreeWidgetItem::SelectedBackground); - if(brush != QBrush()) { - styleContextItem.palette.setBrush(QPalette::Highlight, brush); - } else { - styleContextItem.palette.setBrush(QPalette::Highlight, QBrush(KateRendererConfig::global()->selectionColor())); - } - - brush = getBrushForColorColumn(index, KateStyleTreeWidgetItem::SelectedForeground); - if(brush != QBrush()) { - styleContextItem.palette.setBrush(QPalette::HighlightedText, brush); - } - - return QStyledItemDelegate::paint(painter, styleContextItem, index); - } - - if (!columns.contains(index.column())) { - return QStyledItemDelegate::paint(painter, option, index); - } - - QVariant displayData = index.model()->data(index); - if (displayData.type() != QVariant::Brush) - return QStyledItemDelegate::paint(painter, option, index); - - QBrush brush = qVariantValue(displayData); - - QStyleOptionButton opt; - opt.rect = option.rect; - opt.palette = m_widget->palette(); - - bool set = brush != QBrush(); - - if (!set) { - opt.text = i18nc("No text or background color set", "None set"); - brush = Qt::white; - } - - if(index.row() == m_widget->currentIndex().row() && m_widget->currentItem()->isSelected() && m_widget->currentItem()->childCount() == 0) { - painter->fillRect(opt.rect, KColorScheme(QPalette::Active, KColorScheme::Selection).background()); - } - - m_widget->style()->drawControl(QStyle::CE_PushButton, &opt, painter, m_widget); - - if (set) - painter->fillRect(m_widget->style()->subElementRect(QStyle::SE_PushButtonContents, &opt,m_widget), brush); -} - -KateStyleTreeWidgetItem::KateStyleTreeWidgetItem( QTreeWidgetItem *parent, const QString & stylename, - KTextEditor::Attribute::Ptr defaultAttribute, KateExtendedAttribute::Ptr actualAttribute ) - : QTreeWidgetItem( parent ), - currentStyle( 0L ), - defaultStyle( defaultAttribute ), - actualStyle( actualAttribute ) -{ - initStyle(); - setText(0, stylename); -} - -KateStyleTreeWidgetItem::KateStyleTreeWidgetItem( QTreeWidget *parent, const QString & stylename, - KTextEditor::Attribute::Ptr defaultAttribute, KateExtendedAttribute::Ptr actualAttribute ) - : QTreeWidgetItem( parent ), - currentStyle( 0L ), - defaultStyle( defaultAttribute ), - actualStyle( actualAttribute ) -{ - initStyle(); - setText(0, stylename); -} - -void KateStyleTreeWidgetItem::initStyle() -{ - if (!actualStyle) - { - currentStyle = defaultStyle; - } - else - { - currentStyle = new KTextEditor::Attribute (*defaultStyle); - - if (actualStyle->hasAnyProperty()) - *currentStyle += *actualStyle; - } - - setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); -} - -static Qt::CheckState toCheckState(bool b) { - return b ? Qt::Checked : Qt::Unchecked; -} - -QVariant KateStyleTreeWidgetItem::data( int column, int role ) const -{ - if (column == Context) { - switch (role) { - case Qt::ForegroundRole: - if (style()->hasProperty(QTextFormat::ForegroundBrush)) - return style()->foreground().color(); - break; - - case Qt::BackgroundRole: - if (style()->hasProperty(QTextFormat::BackgroundBrush)) - return style()->background().color(); - break; - - case Qt::FontRole: - return style()->font(); - break; - } - } - - if (role == Qt::CheckStateRole) { - switch (column) { - case Bold: - return toCheckState(style()->fontBold()); - case Italic: - return toCheckState(style()->fontItalic()); - case Underline: - return toCheckState(style()->fontUnderline()); - case StrikeOut: - return toCheckState(style()->fontStrikeOut()); - case UseDefaultStyle: - /* can't compare all attributes, currentStyle has always more than defaultStyle (e.g. the item's name), - * so we just compare the important ones:*/ - return toCheckState( - currentStyle->foreground() == defaultStyle->foreground() - && currentStyle->background() == defaultStyle->background() - && currentStyle->selectedForeground() == defaultStyle->selectedForeground() - && currentStyle->selectedBackground() == defaultStyle->selectedBackground() - && currentStyle->fontBold() == defaultStyle->fontBold() - && currentStyle->fontItalic() == defaultStyle->fontItalic() - && currentStyle->fontUnderline() == defaultStyle->fontUnderline() - && currentStyle->fontStrikeOut() == defaultStyle->fontStrikeOut()); - } - } - - if (role == Qt::DisplayRole) { - switch (column) { - case Foreground: - return style()->foreground(); - case SelectedForeground: - return style()->selectedForeground(); - case Background: - return style()->background(); - case SelectedBackground: - return style()->selectedBackground(); - } - } - - return QTreeWidgetItem::data(column, role); -} - -void KateStyleTreeWidgetItem::updateStyle() -{ - // nothing there, not update it, will crash - if (!actualStyle) - return; - - if ( currentStyle->hasProperty(QTextFormat::FontWeight) ) - { - if ( currentStyle->fontWeight() != actualStyle->fontWeight()) - actualStyle->setFontWeight( currentStyle->fontWeight() ); - } - else actualStyle->clearProperty( QTextFormat::FontWeight ); - - if ( currentStyle->hasProperty(QTextFormat::FontItalic) ) - { - if ( currentStyle->fontItalic() != actualStyle->fontItalic()) - actualStyle->setFontItalic( currentStyle->fontItalic() ); - } - else actualStyle->clearProperty( QTextFormat::FontItalic ); - - if ( currentStyle->hasProperty(QTextFormat::FontStrikeOut) ) - { - if ( currentStyle->fontStrikeOut() != actualStyle->fontStrikeOut()) - actualStyle->setFontStrikeOut( currentStyle->fontStrikeOut() ); - } - else actualStyle->clearProperty( QTextFormat::FontStrikeOut ); - - if ( currentStyle->hasProperty(QTextFormat::FontUnderline) ) - { - if ( currentStyle->fontUnderline() != actualStyle->fontUnderline()) - actualStyle->setFontUnderline( currentStyle->fontUnderline() ); - } - else actualStyle->clearProperty( QTextFormat::FontUnderline ); - - if ( currentStyle->hasProperty(KTextEditor::Attribute::Outline) ) - { - if ( currentStyle->outline() != actualStyle->outline()) - actualStyle->setOutline( currentStyle->outline() ); - } - else actualStyle->clearProperty( KTextEditor::Attribute::Outline ); - - if ( currentStyle->hasProperty(QTextFormat::ForegroundBrush) ) - { - if ( currentStyle->foreground() != actualStyle->foreground()) - actualStyle->setForeground( currentStyle->foreground() ); - } - else actualStyle->clearProperty( QTextFormat::ForegroundBrush ); - - if ( currentStyle->hasProperty(KTextEditor::Attribute::SelectedForeground) ) - { - if ( currentStyle->selectedForeground() != actualStyle->selectedForeground()) - actualStyle->setSelectedForeground( currentStyle->selectedForeground() ); - } - else actualStyle->clearProperty( KTextEditor::Attribute::SelectedForeground ); - - if ( currentStyle->hasProperty(QTextFormat::BackgroundBrush) ) - { - if ( currentStyle->background() != actualStyle->background()) - actualStyle->setBackground( currentStyle->background() ); - } - else actualStyle->clearProperty( QTextFormat::BackgroundBrush ); - - if ( currentStyle->hasProperty(KTextEditor::Attribute::SelectedBackground) ) - { - if ( currentStyle->selectedBackground() != actualStyle->selectedBackground()) - actualStyle->setSelectedBackground( currentStyle->selectedBackground() ); - } - else actualStyle->clearProperty( KTextEditor::Attribute::SelectedBackground ); -} - -/* only true for a hl mode item using it's default style */ -bool KateStyleTreeWidgetItem::defStyle() const { return actualStyle && actualStyle->properties() != defaultStyle->properties(); } - -/* true for default styles */ -bool KateStyleTreeWidgetItem::isDefault() const { return actualStyle ? false : true; } - -void KateStyleTreeWidgetItem::changeProperty( int p ) -{ - if ( p == Bold ) - currentStyle->setFontBold( ! currentStyle->fontBold() ); - else if ( p == Italic ) - currentStyle->setFontItalic( ! currentStyle->fontItalic() ); - else if ( p == Underline ) - currentStyle->setFontUnderline( ! currentStyle->fontUnderline() ); - else if ( p == StrikeOut ) - currentStyle->setFontStrikeOut( ! currentStyle->fontStrikeOut() ); - else if ( p == UseDefaultStyle ) - toggleDefStyle(); - else - setColor( p ); - - updateStyle (); - - treeWidget()->emitChanged(); -} - -void KateStyleTreeWidgetItem::toggleDefStyle() -{ - if ( *currentStyle == *defaultStyle ) { - KMessageBox::information( treeWidget(), - i18n("\"Use Default Style\" will be automatically unset when you change any style properties."), - i18n("Kate Styles"), - "Kate hl config use defaults" ); - } - else { - currentStyle = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute( *defaultStyle )); - updateStyle(); - - QModelIndex currentIndex = treeWidget()->currentIndex(); - while(currentIndex.isValid()) { - treeWidget()->update(currentIndex); - currentIndex = currentIndex.sibling(currentIndex.row(), currentIndex.column() - 1); - } - } -} - -void KateStyleTreeWidgetItem::setColor( int column ) -{ - QColor c; // use this - QColor d; // default color - if ( column == Foreground) - { - c = currentStyle->foreground().color(); - d = defaultStyle->foreground().color(); - } - else if ( column == SelectedForeground ) - { - c = currentStyle->selectedForeground().color(); - d = defaultStyle->selectedForeground().color(); - } - else if ( column == Background ) - { - c = currentStyle->background().color(); - d = defaultStyle->background().color(); - } - else if ( column == SelectedBackground ) - { - c = currentStyle->selectedBackground().color(); - d = defaultStyle->selectedBackground().color(); - } - - if ( KColorDialog::getColor( c, d, treeWidget() ) != QDialog::Accepted) return; - - bool def = ! c.isValid(); - - // if set default, and the attrib is set in the default style use it - // else if set default, unset it - // else set the selected color - switch (column) - { - case Foreground: - if ( def ) - { - if ( defaultStyle->hasProperty(QTextFormat::ForegroundBrush) ) - currentStyle->setForeground( defaultStyle->foreground()); - else - currentStyle->clearProperty(QTextFormat::ForegroundBrush); - } - else - currentStyle->setForeground( c ); - break; - case SelectedForeground: - if ( def ) - { - if ( defaultStyle->hasProperty(KTextEditor::Attribute::SelectedForeground) ) - currentStyle->setSelectedForeground( defaultStyle->selectedForeground()); - else - currentStyle->clearProperty(KTextEditor::Attribute::SelectedForeground); - } - else - currentStyle->setSelectedForeground( c ); - break; - case Background: - if ( def ) - { - if ( defaultStyle->hasProperty(QTextFormat::BackgroundBrush) ) - currentStyle->setBackground( defaultStyle->background()); - else - currentStyle->clearProperty(QTextFormat::BackgroundBrush); - } - else - currentStyle->setBackground( c ); - break; - case SelectedBackground: - if ( def ) - { - if ( defaultStyle->hasProperty(KTextEditor::Attribute::SelectedBackground) ) - currentStyle->setSelectedBackground( defaultStyle->selectedBackground()); - else - currentStyle->clearProperty(KTextEditor::Attribute::SelectedBackground); - } - else - currentStyle->setSelectedBackground( c ); - break; - } - - //FIXME - //repaint(); -} - -void KateStyleTreeWidgetItem::unsetColor( int c ) -{ - if ( c == 100 && currentStyle->hasProperty(QTextFormat::BackgroundBrush) ) - currentStyle->clearProperty(QTextFormat::BackgroundBrush); - else if ( c == 101 && currentStyle->hasProperty(KTextEditor::Attribute::SelectedBackground) ) - currentStyle->clearProperty(KTextEditor::Attribute::SelectedBackground); - updateStyle(); - - treeWidget()->emitChanged(); -} - -KateStyleTreeWidget* KateStyleTreeWidgetItem::treeWidget() const -{ - return static_cast(QTreeWidgetItem::treeWidget()); -} -//END - -#include "katestyletreewidget.moc" diff --git a/part/utils/katestyletreewidget.h b/part/utils/katestyletreewidget.h deleted file mode 100644 index ceea0cc..0000000 --- a/part/utils/katestyletreewidget.h +++ /dev/null @@ -1,74 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2001-2003 Christoph Cullmann - Copyright (C) 2002, 2003 Anders Lund - Copyright (C) 2005-2006 Hamish Rodda - Copyright (C) 2007 Mirko Stocker - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef KATESTYLETREEWIDGET_H -#define KATESTYLETREEWIDGET_H - -#include - -#include "kateextendedattribute.h" - -class KateExtendedAttribute; - -/** - * QTreeWidget that automatically adds columns for KateStyleListItems and provides a - * popup menu and a slot to edit a style using the keyboard. - * Added by anders, jan 23 2002. - */ -class KateStyleTreeWidget : public QTreeWidget -{ - Q_OBJECT - - friend class KateStyleListItem; - - public: - explicit KateStyleTreeWidget(QWidget *parent = 0, bool showUseDefaults = false); - - void emitChanged(); - - void setBgCol( const QColor &c ) { bgcol = c; } - void setSelCol( const QColor &c ) { selcol = c; } - void setNormalCol( const QColor &c ) { normalcol = c; } - - void addItem( QTreeWidgetItem *parent, const QString& styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data = KateExtendedAttribute::Ptr() ); - void addItem( const QString& styleName, KTextEditor::Attribute::Ptr defaultstyle, KateExtendedAttribute::Ptr data = KateExtendedAttribute::Ptr() ); - - void resizeColumns(); - - Q_SIGNALS: - void changed(); - - protected: - virtual void contextMenuEvent(QContextMenuEvent* event); - virtual void showEvent(QShowEvent* event); - virtual bool edit(const QModelIndex& index, EditTrigger trigger, QEvent* event); - - private Q_SLOTS: - void changeProperty( ); - void unsetColor( ); - void updateGroupHeadings(); - - private: - QColor bgcol, selcol, normalcol; - QFont docfont; -}; - -#endif diff --git a/part/utils/katetemplatehandler.cpp b/part/utils/katetemplatehandler.cpp deleted file mode 100644 index da8e208..0000000 --- a/part/utils/katetemplatehandler.cpp +++ /dev/null @@ -1,1114 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2004,2010 Joseph Wenninger - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include - -#include -#include - -#include "katetemplatehandler.h" -#include "katedocument.h" -#include "kateview.h" -#include "kateconfig.h" -#include "katerenderer.h" -#include "kateundomanager.h" -#include "kateregexpsearch.h" -#include "kateglobal.h" -#include "script/katetemplatescript.h" -#include "script/katescriptmanager.h" - -using namespace KTextEditor; - -#define ifDebug(x) - -static bool cmp_moving_ranges(const KTextEditor::MovingRange* r1, const KTextEditor::MovingRange* r2) -{ - return r1->start() < r2->start(); -} - -/// just like Range::contains() but returns true when the cursor is at the end of the range -static bool customContains(MovingRange* range, const Cursor& cursor) -{ - return range->start() <= cursor && range->end() >= cursor; -} - -static bool customContains(const KTextEditor::Range &range, const Cursor& cursor) -{ - return range.start() <= cursor && range.end() >= cursor; -} - -/* ####################################### */ - -KateTemplateHandler::KateTemplateHandler(KateView *view, - const Cursor& position, - const QString &templateString, - const QMap &initialValues, - KateUndoManager* undoManager, - KateTemplateScript* templateScript) - : QObject(view) - , m_view(view) - , m_undoManager(undoManager) - , m_wholeTemplateRange(0) - , m_finalCursorPosition(0) - , m_lastCaretPosition(position) - , m_isMirroring(false) - , m_editWithUndo(false) - , m_jumping(false) - , m_templateScript(templateScript) -{ - ifDebug(kDebug() << templateString << initialValues;) - - QMap initial_Values(initialValues); - - if (initial_Values.contains("selection")) { - if (initial_Values["selection"].isEmpty()) { - Q_ASSERT(m_view); - initial_Values[ "selection" ] = m_view->selectionText(); - } - } - - if (m_view && m_view->selection()) { - m_lastCaretPosition = m_view->selectionRange().start(); - m_view->removeSelectionText(); - } - - ifDebug(kDebug() << initial_Values;) - - connect(doc(), SIGNAL(aboutToReload(KTextEditor::Document*)), - this, SLOT(cleanupAndExit())); - - connect(doc(), SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTemplateInserted(KTextEditor::Document*, KTextEditor::Range))); - - ///TODO: maybe use Kate::CutCopyPasteEdit or similar? - doc()->editStart(); - - if (doc()->insertText(m_lastCaretPosition, templateString)) { - Q_ASSERT(m_wholeTemplateRange); - - if (m_view) { - // indent the inserted template properly, this makes it possible - // to share snippets e.g. via GHNS without caring about - // what indent-style to use. - doc()->align(m_view, *m_wholeTemplateRange); - } - } - - ///TODO: maybe support delayed actions, i.e.: - /// - create doc - /// - insert template - /// - create view => ranges are added - /// for now simply "just insert" the code when we have no active view - - handleTemplateString(initial_Values); - m_undoManager->undoSafePoint(); - doc()->editEnd(); - - if (!initialValues.isEmpty() && m_view) { - // only do complex stuff when required - if (!m_templateRanges.isEmpty()) { - foreach(View* view, doc()->views()) { - setupEventHandler(view); - } - - connect(doc(), SIGNAL(viewCreated(KTextEditor::Document*, KTextEditor::View*)), - this, SLOT(slotViewCreated(KTextEditor::Document*, KTextEditor::View*))); - connect(doc(), SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextChanged(KTextEditor::Document*, KTextEditor::Range))); - connect(doc(), SIGNAL(textRemoved(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextChanged(KTextEditor::Document*, KTextEditor::Range))); - - setEditWithUndo(undoManager->isActive()); - - connect(undoManager, SIGNAL(isActiveChanged(bool)), - this, SLOT(setEditWithUndo(bool))); - - } else { - // when no interesting ranges got added, we can terminate directly - jumpToFinalCursorPosition(); - cleanupAndExit(); - } - - } else { - cleanupAndExit(); - } -} - -KateTemplateHandler::~KateTemplateHandler() -{ -} - -void KateTemplateHandler::slotTemplateInserted(Document *document, const Range& range) -{ - Q_ASSERT(document == doc()); - Q_UNUSED(document); - ifDebug(kDebug() << "template range inserted" << range;) - - m_wholeTemplateRange = doc()->newMovingRange(range, KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - - disconnect(doc(), SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTemplateInserted(KTextEditor::Document*, KTextEditor::Range))); -} - -void KateTemplateHandler::cleanupAndExit() -{ - ifDebug(kDebug() << "cleaning up and exiting";) - disconnect(doc(), SIGNAL(viewCreated(KTextEditor::Document*, KTextEditor::View*)), - this, SLOT(slotViewCreated(KTextEditor::Document*, KTextEditor::View*))); - disconnect(doc(), SIGNAL(textInserted(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextChanged(KTextEditor::Document*, KTextEditor::Range))); - disconnect(doc(), SIGNAL(textRemoved(KTextEditor::Document*, KTextEditor::Range)), - this, SLOT(slotTextChanged(KTextEditor::Document*, KTextEditor::Range))); - - if (!m_templateRanges.isEmpty()) { - foreach(MovingRange* range, m_templateRanges) { - // delete all children - foreach(MovingRange* child, m_templateRangesChildren[range]) - delete child; - - delete range; - } - - m_templateRanges.clear(); - m_templateRangesChildren.clear(); - m_templateRangesChildToParent.clear(); - } - - // no children if no ranges around - Q_ASSERT(m_templateRangesChildren.isEmpty()); - Q_ASSERT(m_templateRangesChildToParent.isEmpty()); - - if (!m_spacersMovingRanges.isEmpty()) { - foreach(MovingRange* range, m_spacersMovingRanges) { - doc()->removeText(*range); - delete range; - } - - m_spacersMovingRanges.clear(); - } - - delete m_wholeTemplateRange; - delete m_finalCursorPosition; - delete this; -} - -void KateTemplateHandler::jumpToFinalCursorPosition() -{ - if (m_view && (!m_wholeTemplateRange - || customContains(m_wholeTemplateRange->toRange(), m_view->cursorPosition()))) { - m_view->setSelection(Range::invalid()); - m_view->setCursorPosition(*m_finalCursorPosition); - } -} - -KateDocument *KateTemplateHandler::doc() -{ - return m_view->doc(); -} - -void KateTemplateHandler::setEditWithUndo(const bool &enabled) -{ - m_editWithUndo = enabled; -} - -void KateTemplateHandler::slotViewCreated(Document* document, View* view) -{ - Q_ASSERT(document == doc()); - Q_UNUSED(document) - setupEventHandler(view); -} - -void KateTemplateHandler::setupEventHandler(View* view) -{ - view->focusProxy()->installEventFilter(this); -} - -bool KateTemplateHandler::eventFilter(QObject* object, QEvent* event) -{ - // prevent indenting by eating the keypress event for TAB - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - - if (keyEvent->key() == Qt::Key_Tab || keyEvent->key() == Qt::Key_Backtab) { - if (!m_view->isCompletionActive()) { - return true; - } - } - } - - // actually offer shortcuts for navigation - - if (event->type() == QEvent::ShortcutOverride) { - QKeyEvent *keyEvent = static_cast(event); - - if (keyEvent->key() == Qt::Key_Return && keyEvent->modifiers() & Qt::AltModifier) { - // terminate - jumpToFinalCursorPosition(); - cleanupAndExit(); - keyEvent->accept(); - return true; - - } else if (keyEvent->key() == Qt::Key_Escape) { - if (!m_view || !m_view->selection()) { - // terminate - jumpToFinalCursorPosition(); - cleanupAndExit(); - keyEvent->accept(); - return true; - } - - } else if (keyEvent->key() == Qt::Key_Tab && !m_view->isCompletionActive()) { - if (keyEvent->modifiers() & Qt::Key_Shift) { - jumpToPreviousRange(); - - } else { - jumpToNextRange(); - } - - keyEvent->accept(); - return true; - - } else if (keyEvent->key() == Qt::Key_Backtab && !m_view->isCompletionActive()) { - jumpToPreviousRange(); - keyEvent->accept(); - return true; - } - } - - return QObject::eventFilter(object, event); -} - -void KateTemplateHandler::jumpToPreviousRange() -{ - const Cursor & cursor = m_view->cursorPosition(); - - if (cursor == *m_finalCursorPosition) { - // wrap and jump to last range - setCurrentRange(m_masterRanges.last()); - return; - } - - MovingRange* previousRange = 0; - - foreach(MovingRange* range, m_masterRanges) { - if (range->start() >= cursor) { - continue; - } - - if (!previousRange || range->start() > previousRange->start()) { - previousRange = range; - - if (m_templateRangesChildToParent.value(previousRange)) previousRange = m_templateRangesChildToParent.value(previousRange); - } - } - - if (previousRange) { - setCurrentRange(previousRange); - - } else { - // wrap and jump to final cursor - jumpToFinalCursorPosition(); - } -} - -void KateTemplateHandler::jumpToNextRange() -{ - const Cursor & cursor = m_view->cursorPosition(); - - if (cursor == *m_finalCursorPosition) { - // wrap and jump to first range - setCurrentRange(m_masterRanges.first()); - return; - } - - MovingRange* nextRange = 0; - - foreach(MovingRange* range, m_masterRanges) { - if (range->start() <= cursor) { - continue; - } - - if (!nextRange || range->start() < nextRange->start()) { - nextRange = range; - } - } - - if (nextRange) { - if (m_templateRangesChildToParent.value(nextRange)) nextRange = m_templateRangesChildToParent.value(nextRange); - - setCurrentRange(nextRange); - - } else { - // wrap and jump to final cursor - jumpToFinalCursorPosition(); - } -} - -void KateTemplateHandler::setCurrentRange(MovingRange* range) -{ - if (!m_templateRangesChildren[range].isEmpty()) { - ifDebug(kDebug() << "looking for mirroring range";) - // jump to first mirrored range - bool found = false; - foreach(MovingRange* childRange, m_templateRangesChildren[range]) { - ifDebug(kDebug() << "checking range equality";) - - if (m_masterRanges.contains(childRange)) { - ifDebug(kDebug() << "found master range";) - range = childRange; - found = true; - break; - } - } - - if (!found) { - range = m_templateRangesChildren[range].first(); - } - } - - if (m_view) { - m_jumping = true; - - if (m_uneditedRanges.contains(range)) { - m_view->setSelection(*range); - } - - m_view->setCursorPosition(range->start()); - - m_jumping = false; - } - - m_lastCaretPosition = range->start(); -} - -/** - * Returns an attribute with \p color as background with @p alpha alpha value. - */ -Attribute::Ptr getAttribute(QColor color, int alpha = 230) -{ - Attribute::Ptr attribute(new Attribute()); - color.setAlpha(alpha); - attribute->setBackground(QBrush(color)); - return attribute; -} - -void KateTemplateHandler::handleTemplateString(const QMap< QString, QString >& initialValues) -{ - QString templateString = doc()->text(*m_wholeTemplateRange); - - int line = m_wholeTemplateRange->start().line(); - int column = m_wholeTemplateRange->start().column(); - - // not equal -1 when we found a start position - int startPos = -1; - - bool lastWasBrace = false; - - // each found variable gets it's range(s) added to the list. - // the key is the varname, e.g. the same as in initialValues - // to be able to iterate over them in a FIFO matter, also store - // the keys in a queue. - QQueue keyQueue; - QMultiMap ranges; - QMap mirrorBehaviourBuildHelper; - - - QList spacers; - // valid, if we find an occurrence of ${cursor} - Cursor finalCursorPosition = Cursor::invalid(); - - // parse string for ${VAR} or %{VAR} - // VAR must not contain $ or % - // VAR must not contain newlines - // VAR must be set as key in initialValues - // expression must not be escaped - - for (int i = 0; i < templateString.size(); ++i) { - ifDebug(kDebug() << "checking character:" << templateString[i];) - - if (templateString[i] == '\n') { - lastWasBrace = false; - ++line; - column = 0; - - if (startPos != -1) { - // don't allow variables to span multiple lines - startPos = -1; - } - - } else if ((templateString[i] == '%' || templateString[i] == '$') - && i + 1 < templateString.size() && templateString[i+1] == '{') { - - // check whether this var is escaped - int escapeChars = 0; - - while (i - escapeChars > 0 && templateString[i - escapeChars - 1] == '\\') { - ++escapeChars; - } - - if (escapeChars > 0) { - ifDebug(kDebug() << "found" << escapeChars << "escape chars at " << templateString.mid(i - escapeChars - 10, escapeChars + 10);) - // remove half of the escape chars (i.e. \\ => \) and make sure the - // odd rest is removed as well (i.e. the one that escapes this var) - int toRemove = (escapeChars + 1) / 2; - ifDebug(kDebug() << "will remove" << toRemove << "of those escape chars";) - templateString.remove(i - escapeChars, toRemove); - i -= toRemove; - column -= toRemove; - } - - if (escapeChars % 2 == 0) { - // don't check for startPos == -1 here, overwrite blindly since nested variables are not supported - if (lastWasBrace) { - templateString.insert(i, " "); - spacers.append(Range(line, column, line, column + 1)); - ++i; - ++column; - } - - startPos = i; - } - - lastWasBrace = false; - - // skip '{' - ++i; - column += 2; - - } else if ((startPos != -1) && (templateString[i] == ':')) { // skip init value, handled by KTE - i++; - column++; - int backslash_count = 0; - - for (;i < templateString.size();i++, column++) { - if (templateString[i] == '\n') { - ++line; - column = 0; - - if (startPos != -1) { - // don't allow variables to span multiple lines - startPos = -1; - } - - break; - } - - if (templateString[i] == '}') { - if ((backslash_count % 2) == 0) { - i--; - //column--; - break; - - } else { - backslash_count = 0; - } - - } else if (templateString[i] == '\\') { - backslash_count++; - - } else { // any character teminates a backslash sequence - backslash_count = 0; - } - } - - } else if ((startPos != -1) && (templateString[i] == '/')) { // skip regexp - i++; - column++; - int backslash_count = 0; - int slashcount = 1; - - for (;i < templateString.size();i++, column++) { - if (templateString[i] == '\n') { - ++line; - column = 0; - - if (startPos != -1) { - // don't allow variables to span multiple lines - startPos = -1; - } - - break; - } - - if (templateString[i] == '/') { - if ((backslash_count % 2) == 0) - slashcount++; - - backslash_count = 0; - - } else if (templateString[i] == '\\') { - backslash_count++; - - } else { // any character teminates a backslash sequence - backslash_count = 0; - } - - if (slashcount == 3) { - column++; - break; - } - } - - } else if (templateString[i] == '}' && startPos != -1) { - lastWasBrace = true; - bool force_first = false; - // get key, i.e. contents between ${..} - QString key = templateString.mid(startPos + 2, i - (startPos + 2)); - int keyLength = key.length(); - QString searchReplace; - ifDebug(kDebug() << "key found:" << key;) - bool check_slash = false; - bool check_colon = false; - bool check_backtick = false; - int pos_slash = key.indexOf("/"); - int pos_colon = key.indexOf(":"); - int pos_backtick = key.indexOf("`"); - - if ((pos_slash == -1) && (pos_colon == -1)) { - // do nothing - } else if ((pos_slash != -1) && (pos_colon == -1)) { - check_slash = true; - } else if ((pos_slash == -1) && (pos_colon != -1)) { - check_colon = true; - } else { - if (pos_colon < pos_slash) { - check_colon = true; - } else { - check_slash = true; - } - } - - if (!check_slash && !check_colon && pos_backtick >= 0) { - check_backtick = true; - } - - QString functionName; - - if (check_slash) { - searchReplace = key.mid(pos_slash + 1); - key = key.left(pos_slash); - ifDebug(kDebug() << "search_replace" << searchReplace;) - } else if (check_colon) { - key = key.left(pos_colon); - ifDebug(kDebug() << "real key found:" << key;) - } else if (check_backtick) { - functionName = key.mid(pos_backtick + 1); - functionName = functionName.left(functionName.indexOf("`")); - key = key.left(pos_backtick); - ifDebug(kDebug() << "real key found:" << key << "function:" << functionName;) - } - - if (key.contains("@")) { - key = key.left(key.indexOf("@")); - force_first = true; - } - - ifDebug(kDebug() << "real key found:" << key;) - - if (!initialValues.contains(key)) { - kWarning() << "unknown variable key:" << key; - } else if (key == "cursor") { - finalCursorPosition = Cursor(line, column - keyLength - 2); - // don't insert anything, just remove the placeholder - templateString.remove(startPos, i - startPos + 1); - // correct iterator pos, 3 == $ + { + } - i -= 3 + keyLength; - column -= 2 + keyLength; - startPos = -1; - } else { - MirrorBehaviour behaviour; - - if (!searchReplace.isEmpty()) { - QString search; - bool searchValid = false; - QString replace; - bool replaceValid = false; - QString flags; - //search part; - - while (!searchReplace.isEmpty()) { - ifDebug(kDebug() << "searchReplace=" << searchReplace;) - int regescapes = 0; - int pos = searchReplace.indexOf("/"); - - for (int epos = pos - 1; epos >= 0 && searchReplace.at(epos) == '\\'; epos--) { - regescapes++; - } - - ifDebug(kDebug() << "regescapes=" << regescapes;) - if ((regescapes % 2) == 1) { - search += searchReplace.left(pos + 1); - searchReplace = searchReplace.mid(pos + 1); - ifDebug(kDebug() << "intermediate search string is=" << search;) - } else { - search += searchReplace.left(pos); - searchReplace = searchReplace.mid(pos + 1); - searchValid = true; - ifDebug(kDebug() << "final search string is=" << search;) - ifDebug(kDebug() << "remaining characters in searchReplace" << searchReplace;) - break; - } - } - - //replace part - - if (searchValid) { - int last_slash = searchReplace.lastIndexOf("/"); - - if (last_slash != -1) { - replace = searchReplace.left(last_slash); - replaceValid = true; - flags = searchReplace.mid(last_slash + 1); - } - } - - if (searchValid && replaceValid) { - behaviour = MirrorBehaviour(search, replace, flags); - } - - } else if (!functionName.isEmpty()) { - behaviour = MirrorBehaviour(m_templateScript, functionName, this); - } - - const QString initialVal = behaviour.getMirrorString(initialValues[key]); - - // whether the variable starts with % or $ - QChar c = templateString[startPos]; - - // replace variable with initial value - templateString.replace(startPos, i - startPos + 1, initialVal); - - // correct iterator pos, 3 == % + { + } - i -= 3 + keyLength - initialVal.length(); - - // correct column to point at end of range, taking replacement width diff into account - // 2 == % + { - column -= 2 + keyLength - initialVal.length(); - - // always add ${...} to the editable ranges - // only add %{...} to the editable ranges when it's value equals the key - ifDebug(kDebug() << "char is:" << c << "initial value is:" << initialValues[key] << " after fixup is:" << initialVal;) - if (c == '$' || key == initialValues[key]) { - if (!keyQueue.contains(key)) { - keyQueue.append(key); - } - - // support for multiline initial val, e.g. selection - int endColumn = column - initialVal.length(); - int endLine = line; - for (int j = 0; j < initialVal.length(); ++j) { - if (initialVal.at(j) == '\n') { - endColumn = 0; - ++endLine; - } else { - ++endColumn; - } - } - Range tmp = Range(line, column - initialVal.length(), endLine, endColumn ); - ifDebug(kDebug() << "range is:" << tmp;) - - if (force_first) { - QList range_list = ranges.values(key); - range_list.append(tmp); - ranges.remove(key); - - while (!range_list.isEmpty()) { - ranges.insert(key, range_list.takeLast()); - } - } else { - ranges.insert(key, tmp); - } - - mirrorBehaviourBuildHelper.insert(tmp, behaviour); - } - } - - startPos = -1; - - ifDebug(kDebug() << "i=" << i << " template size=" << templateString.size();) - } else { - ++column; - lastWasBrace = false; - } - } - - if (lastWasBrace && (!finalCursorPosition.isValid())) { - templateString += " "; - spacers.append(Range(line, column, line, column + 1)); - ++column; - } - - doc()->replaceText(*m_wholeTemplateRange, templateString); - - Q_ASSERT(!m_wholeTemplateRange->toRange().isEmpty()); - - if (m_view) { - ///HACK: make sure the view cache is up2date so we can safely set the cursor position - /// else one might hit the Q_ASSERT(false) in KateViewInternal::endPos() - /// the cause is that the view get's ::update()'d, but that does not trigger a - /// paint event right away. - m_view->updateView(true); - } - - if (finalCursorPosition.isValid()) { - m_finalCursorPosition = doc()->newMovingCursor(finalCursorPosition); - } else { - m_finalCursorPosition = doc()->newMovingCursor(Cursor(line, column)); - } - - if (ranges.isEmpty()) { - return; - } - - KateRendererConfig *config = m_view->renderer()->config(); - - // TODO: finetune the attribute alpha values, text ranges behave a bit different there... - - Attribute::Ptr editableAttribute = getAttribute(config->templateEditablePlaceholderColor(), 255); - editableAttribute->setDynamicAttribute( - Attribute::ActivateCaretIn, getAttribute(config->templateFocusedEditablePlaceholderColor(), 255) - ); - - Attribute::Ptr mirroredAttribute = getAttribute(config->templateNotEditablePlaceholderColor(), 255); - - m_wholeTemplateRange->setAttribute(getAttribute(config->templateBackgroundColor(), 200)); - - // create moving ranges ranges for each found variable - // if the variable exists more than once, create "mirrored" ranges - foreach(const QString& key, keyQueue) { - const QList &values = ranges.values(key); - // used as parent for mirrored variables, - // and as only item for not-mirrored variables - MovingRange* parent = doc()->newMovingRange(values.last(), MovingRange::ExpandLeft | MovingRange::ExpandRight); - - if (values.size() > 1) { - // add all "real" ranges as children - for (int i = 0; i < values.size(); ++i) { - MovingRange* range = doc()->newMovingRange(values[i], MovingRange::ExpandLeft | MovingRange::ExpandRight); - - // remember child - parent mapping - m_templateRangesChildren[parent].push_back(range); - m_templateRangesChildToParent[range] = parent; - - // the last item will be our real first range (see multimap docs) - if (i == values.size() - 1) { - range->setAttribute(editableAttribute); - m_uneditedRanges.append(range); - m_masterRanges.append(range); - } else { - range->setAttribute(mirroredAttribute); - m_mirrorBehaviour.insert(range, mirrorBehaviourBuildHelper[values[i]]); - } - } - } else { - // just a single range - parent->setAttribute(editableAttribute); - m_uneditedRanges.append(parent); - m_masterRanges.append(parent); - } - - m_templateRanges.append(parent); - } - - // create spacers, only once create the attribute - Attribute::Ptr attribute(new Attribute()); - attribute->setFont(QFont("fixed", 1)); - attribute->setFontStrikeOut(true); - attribute->setFontOverline(true); - attribute->setFontUnderline(true); - foreach(const Range& spacer, spacers) { - MovingRange *r = doc()->newMovingRange(spacer); - r->setAttribute(attribute); - m_spacersMovingRanges.append(r); - } - - qSort(m_masterRanges.begin(), m_masterRanges.end(), cmp_moving_ranges); - - setCurrentRange(m_templateRanges.first()); - mirrorBehaviourBuildHelper.clear(); - - //OPTIMIZE ME, PERHAPS ONLY DO THE MIRRORING ACTION FOR THE MASTER RANGE IN THE CODE ABOVE - //THIS WOULD REDUCE MIRRORING ACTIONS - - m_initialRemodify = true; - foreach(MovingRange* smr, m_masterRanges) { - slotTextChanged(doc(), Range(*smr)); - } - - m_initialRemodify = false; - -} - -void KateTemplateHandler::slotTextChanged(Document* document, const Range& range) -{ - Q_ASSERT(document == doc()); - - ifDebug(kDebug() << "text changed" << document << range;) - - if (m_isMirroring) { - ifDebug(kDebug() << "mirroring - ignoring edit";) - return; - } - - if (!m_initialRemodify) { - if ((!m_editWithUndo && doc()->isEditRunning()) || range.isEmpty()) { - ifDebug(kDebug() << "slotTextChanged returning prematurely";) - return; - } - } - - if (m_wholeTemplateRange->toRange().isEmpty()) { - ifDebug(kDebug() << "template range got deleted, exiting";) - cleanupAndExit(); - return; - } - - if (range.end() == *m_finalCursorPosition) { - ifDebug(kDebug() << "editing at final cursor position, exiting.";) - cleanupAndExit(); - return; - } - - if (!m_wholeTemplateRange->toRange().contains(range.start())) { - // outside our template or one of our own changes - ifDebug(kDebug() << range << "not contained in" << m_wholeTemplateRange->toRange();) - cleanupAndExit(); - return; - } - - ifDebug(kDebug() << "see if we have to mirror the edit";) - - // Check if @p range is mirrored. - // If we have two adjacent mirrored ranges, think ${first}${second}, - // the second will be mirrored, as that's what the user will see "activated", - // since Kate uses contains() that does a comparison "< end()". - // We use "<= end()" though so we can handle contents that were added at the end of a range. - // TODO: make it possible to select either, the left or right rannge (LOWPRIO) - - // The found child range to act as base for mirroring. - MovingRange* baseRange = 0; - // The left-adjacent range that gets some special treatment (if it exists). - MovingRange* leftAdjacentRange = 0; - - foreach(MovingRange* parent, m_templateRanges) { - if (customContains(parent, range.start())) { - if (m_templateRangesChildren[parent].isEmpty()) { - // simple, not-mirrored range got changed - if (!m_initialRemodify) - m_uneditedRanges.removeOne(parent); - } else { - // handle mirrored ranges - if (baseRange) { - // look for adjacent range (we find the right-handed one here) - ifDebug(kDebug() << "looking for adjacent mirror to" << *baseRange;) - foreach(MovingRange* child, m_templateRangesChildren[parent]) { - if (child->start() == range.start() && child->end() >= range.end()) { - ifDebug(kDebug() << "found adjacent mirror - using as base" << *child;) - leftAdjacentRange = baseRange; - baseRange = child; - break; - } - } - - // adjacent mirror handled, we can finish - break; - } else { - // find mirrored range that got edited - foreach(MovingRange* child, m_templateRangesChildren[parent]) { - if (customContains(child, range.start())) { - baseRange = child; - break; - } - } - - if (baseRange && baseRange->end() != range.end()) { - // finish, don't look for adjacent mirror as we are not at the end of this range - break; - } else if (baseRange && (baseRange->isEmpty() || range == *baseRange)) { - // always add to empty ranges first. else ${foo}${bar} will make foo unusable when - // it gets selected and an edit takes place. - break; - } // else don't finish, look for baseRange or adjacent mirror first - } - } - - } else if (baseRange) { - // no adjacent mirrored range found, we can finish - break; - } - } - - if (baseRange) { - m_uneditedRanges.removeOne(baseRange); - - if (leftAdjacentRange) { - // revert that something got added to the adjacent range - ifDebug(kDebug() << "removing edited range" << range << "from left adjacent range" << *leftAdjacentRange;) - leftAdjacentRange->setRange(Range(leftAdjacentRange->start(), range.start())); - ifDebug(kDebug() << "new range:" << *leftAdjacentRange;) - } - - syncMirroredRanges(baseRange); - - if (range.start() == baseRange->start() && m_view) { - // TODO: update the attribute, since kate doesn't do that automatically - // TODO: fix in kate itself - // TODO: attribute->changed == undefined reference... - } - } else { - ifDebug(kDebug() << "no range found to mirror this edit";) - } -} - -void KateTemplateHandler::syncMirroredRanges(MovingRange* range) -{ - Q_ASSERT(m_templateRanges.contains(m_templateRangesChildToParent[range])); - - m_isMirroring = true; - doc()->editStart(); - - const QString &newText = doc()->text(*range); - ifDebug(kDebug() << "mirroring" << newText << "from" << *range;) - - foreach(MovingRange* sibling, m_templateRangesChildren[m_templateRangesChildToParent[range]]) { - if (sibling != range) { - doc()->replaceText(*sibling, m_mirrorBehaviour[sibling].getMirrorString(newText)); - } - } - - /// TODO: now undo only undos the last char edit, and does not - /// merge those edits as usual - doc()->editEnd(); - m_isMirroring = false; -} - - -KateView* KateTemplateHandler::view() -{ - return qobject_cast(m_view); -} - - -//BEGIN MIRROR BEHAVIOUR -KateTemplateHandler::MirrorBehaviour::MirrorBehaviour() - : m_behaviour(Clone) -{ -} - -KateTemplateHandler::MirrorBehaviour::MirrorBehaviour(const QString ®exp, - const QString &replacement, - const QString& flags) - : m_behaviour(Regexp) - , m_search(regexp) - , m_replace(replacement) -{ - m_global = flags.contains("g"); - m_expr = QRegExp(regexp, flags.contains("i") ? Qt::CaseInsensitive : Qt::CaseSensitive, QRegExp::RegExp2); -} - -KateTemplateHandler::MirrorBehaviour::MirrorBehaviour(KateTemplateScript* templateScript, - const QString& functionName, - KateTemplateHandler* handler) - : m_behaviour(Scripted) - , m_templateScript(templateScript) - , m_functionName(functionName) - , m_handler(handler) -{ -} - -KateTemplateHandler::MirrorBehaviour::~MirrorBehaviour() -{ -} - - -QString KateTemplateHandler::MirrorBehaviour::getMirrorString(const QString &source) -{ - QString ahead; - QString output; - QString finalOutput; - int pos; - int matchCounter = 0; - - switch (m_behaviour) { - - case Clone: - return source; - break; - - case Regexp: { - ifDebug(kDebug() << "regexp " << m_search << " replacement " << m_replace;) - - if (m_global) { - ahead = source; - - while (ahead.length() > 0) { - if ((pos = m_expr.indexIn(ahead)) == -1) { - return finalOutput + ahead; - } - - QStringList results = m_expr.capturedTexts(); - output = KateRegExpSearch::buildReplacement(m_replace, results, ++matchCounter); - - finalOutput = finalOutput + ahead.left(pos) + output; - ahead = ahead.mid(pos + m_expr.matchedLength()); - } - - return finalOutput; - } else { - if ((pos = m_expr.indexIn(source)) == -1) { - return source; - } - - QStringList results = m_expr.capturedTexts(); - output = KateRegExpSearch::buildReplacement(m_replace, results, 1); - return source.left(pos) + output + source.mid(pos + m_expr.matchedLength()); - } - - break; - } - - case Scripted: { - KateTemplateScript *script = KateGlobal::self()->scriptManager()->templateScript(m_templateScript); - - if (script) { - QString result = script->invoke(m_handler->view(), m_functionName, source); - - if (!result.isNull()) { - return result; - } - } - - return source; - } - - default: - return QString(); - } - - return QString(); -} - -//END MIRROR BEHAVOUR - - -#include "katetemplatehandler.moc" - -// kate: indent-mode cstyle; space-indent on; indent-width 2; replace-tabs on; replace-tabs on; replace-tabs on; replace-tabs on; diff --git a/part/utils/katetemplatehandler.h b/part/utils/katetemplatehandler.h deleted file mode 100644 index 1d582de..0000000 --- a/part/utils/katetemplatehandler.h +++ /dev/null @@ -1,290 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2004,2010 Joseph Wenninger - * Copyright (C) 2009 Milian Wolff - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KATE_TEMPLATE_HANDLER_H_ -#define _KATE_TEMPLATE_HANDLER_H_ - -#include -#include -#include -#include -#include -#include -#include - -class KateDocument; - -class KateView; - -class KateUndoManager; - -class KateTemplateScript; - -namespace KTextEditor -{ - -class MovingCursor; - -class MovingRange; -} - -/** - * \brief Inserts a template and offers advanced snippet features, like navigation and mirroring. - * - * For each template inserted a new KateTemplateHandler will be created. - * - * The handler has the following features: - * - * \li It inserts the template string into the document at the requested position. - * \li When the template contains at least one variable, the cursor will be placed - * at the start of the first variable and its range gets selected. - * \li When more than one variable exists,TAB and SHIFT TAB can be used to navigate - * to the next/previous variable. - * \li When a variable occurs more than once in the template, edits to any of the - * occurrences will be mirroed to the other ones. - * \li When ESC is pressed, the template handler closes. - * \li When ALT + RETURN is pressed and a \c %{cursor} variable - * exists in the template,the cursor will be placed there. Else the cursor will - * be placed at the end of the template. - * - * \see KateDocument::insertTemplateTextImplementation(), KTextEditor::TemplateInterface - * - * \author Milian Wolff - */ - -class KateTemplateHandler: public QObject -{ - Q_OBJECT - -public: - /** - * Setup the template handler, insert the template string. - * - * NOTE: The handler deletes itself when required, you do not need to - * keep track of it. - */ - KateTemplateHandler(KateView *view, - const KTextEditor::Cursor& position, - const QString &templateString, - const QMap &initialValues, - KateUndoManager* undoManager, - KateTemplateScript* templateScript); - - /** - * Cancels the template handler and cleans everything up. - */ - virtual ~KateTemplateHandler(); - -protected: - /** - * \brief Provide keyboard interaction for the template handler. - * - * The event filter handles the following shortcuts: - * - * TAB: jump to next editable (i.e. not mirrored) range. - * NOTE: this prevents indenting via TAB. - * SHIFT + TAB: jump to previous editable (i.e. not mirrored) range. - * NOTE: this prevents un-indenting via SHIFT + TAB. - * ESC: terminate template handler (only when no completion is active). - * ALT + RETURN: accept template and jump to the end-cursor. - * if %{cursor} was given in the template, that will be the - * end-cursor. - * else just jump to the end of the inserted text. - */ - virtual bool eventFilter(QObject* object, QEvent* event); - -private: - /** - * Inserts the @p text at @p position and sets an undo point. - */ - void insertText(const KTextEditor::Cursor& position, const QString& text); - - /** - * Parses the inserted & indented template string (in \p m_wholeTemplateRange) - * for variables and replaces their palceholders with their \p initialValues. - * Also create child ranges to \p m_templateRange for editable ranges. When a - * variable occurs more than once, create mirrored ranges. - */ - void handleTemplateString(const QMap &initialValues); - - /** - * Install an event filter on the filter proxy of \p view for - * navigation between the ranges and terminating the KateTemplateHandler. - * - * \see eventFilter() - */ - void setupEventHandler(KTextEditor::View* view); - - /** - * Jumps to the previous editable range. If there is none, wrap and jump to the last range. - * - * \see setCurrentRange(), jumpToNextRange() - */ - void jumpToPreviousRange(); - - /** - * Jumps to the next editable range. If there is none, wrap and jump to the last range. - * - * \see setCurrentRange(), jumpToPreviousRange() - */ - void jumpToNextRange(); - - /** - * Set selection to \p range and move the cursor to it's beginning. - */ - void setCurrentRange(KTextEditor::MovingRange* range); - - /** - * Syncs the contents of all mirrored ranges for a given variable. - * - * \param range The range that acts as base. It's contents will be propagated. - * Mirrored ranges can be found as child of a child of \p m_templateRange - */ - void syncMirroredRanges(KTextEditor::MovingRange* range); - -public: - - class MirrorBehaviour - { - - public: - MirrorBehaviour(); //clone - MirrorBehaviour(const QString ®exp, const QString &replacement, const QString &flags); //regexp - MirrorBehaviour(KateTemplateScript* templateScript, const QString& functionName, KateTemplateHandler* handler); //scripted - ~MirrorBehaviour(); - QString getMirrorString(const QString &source); - - private: - enum Behaviour { - Clone = 0, - Regexp = 1, - Scripted = 2 - }; - Behaviour m_behaviour; - QString m_search; - QString m_replace; - QRegExp m_expr; - bool m_global; - KateTemplateScript* m_templateScript; - QString m_functionName; - KateTemplateHandler *m_handler; - }; - -private: - - QHash m_mirrorBehaviour; - - - /** - * Jumps to the final cursor position. This is either \p m_finalCursorPosition, or - * if that is not set, the end of \p m_templateRange. - */ - void jumpToFinalCursorPosition(); - - KateDocument *doc(); - -private Q_SLOTS: - /** - * Cleans up the template handler and deletes it. - * - * We cannot always do that blindly in the dtor, as it would crash - * when we try to do the cleanup when the dtor is called by the - * parent's dtor, i.e. when a document gets closed. - */ - void cleanupAndExit(); - - /** - * Saves the range of the inserted template. This is required since - * tabs could get expanded on insert. While we are at it, we can - * use it to auto-indent the code after insert. - */ - void slotTemplateInserted(KTextEditor::Document* document, const KTextEditor::Range& range); - /** - * Install event filter on new views. - */ - void slotViewCreated(KTextEditor::Document* document, KTextEditor::View* view); - /** - * When the start of @p oldRange overlaps with one of our mirrored ranges, - * update the contents of the siblings. - * - * @see syncMirroredRanges() - */ - void slotTextChanged(KTextEditor::Document* document, const KTextEditor::Range& oldRange); - - /** - * Keeps track of whether undo tracking is enabled in the document's undo manager. - */ - void setEditWithUndo(const bool &enabled); - -public: - KateView* view(); - -private: - /// The document we operate on. - KateView *m_view; - /// The undo manager associated with our document - KateUndoManager *const m_undoManager; - /// List of ranges with highlighting, marking the inserted variables in the template. - /// Mirrored variables will have a parent range and the real ranges will be the children. - /// Each direct child of the list is added as a Highlighting Range with dynamic attribs. - /// - /// Ordered by first occurrence in the document. - /// - /// NOTE: this design is due to some Kate limiations with overlapping ranges. - /// and using a structure like Parent -> NotMirrored + MirrorParents -> Mirrors - /// leads to overlaps, since mirrors often occur anywhere in the template text. - QList m_templateRanges; - - /// mapping of ranges to there children - QMap > m_templateRangesChildren; - QMap m_templateRangesChildToParent; - - /// A range that occupies the whole range of the inserted template. - /// When the cursor moves outside it, the template handler gets closed. - KTextEditor::MovingRange *m_wholeTemplateRange; - /// Position of the (last) occurrence of ${cursor} in the template string. - KTextEditor::MovingCursor *m_finalCursorPosition; - /// The last caret position during editing. - KTextEditor::Cursor m_lastCaretPosition; - /// MovingRanges that are still in this list have not yet been changed. Hence they'll - /// be selected when they get focused. All others just get the cursor placed at the - /// beginning. - QList m_uneditedRanges; - /// stores the master ranges for mirroring, otherwise just the range, needed for cursor placement - QList m_masterRanges; - /// Set to true when we are currently mirroring, to prevent recursion. - bool m_isMirroring; - /// Whether undo tracking is enabled in the undo manager. - bool m_editWithUndo; - /// Whether we are currently setting the cursor manually. - bool m_jumping; - /// template script pointer for the template script, which might be used by the current template - KateTemplateScript* m_templateScript; - - QList m_spacersMovingRanges; - - bool m_initialRemodify; -}; - - -#endif - -// kate: indent-mode cstyle; space-indent on; indent-width 2; replace-tabs on; replace-tabs on; replace-tabs on; replace-tabs on; diff --git a/part/view/kateview.cpp b/part/view/kateview.cpp deleted file mode 100644 index 98b276b..0000000 --- a/part/view/kateview.cpp +++ /dev/null @@ -1,2912 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2009 Michel Ludwig - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2003 Hamish Rodda - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001-2004 Christoph Cullmann - Copyright (C) 2001-2010 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -//BEGIN includes -#include "kateview.h" -#include "kateview.moc" - -#include "kateviewinternal.h" -#include "kateviewhelpers.h" -#include "katerenderer.h" -#include "katedocument.h" -#include "kateundomanager.h" -#include "katedocumenthelpers.h" -#include "kateglobal.h" -#include "kateviglobal.h" -#include "katehighlight.h" -#include "katehighlightmenu.h" -#include "katedialogs.h" -#include "katetextline.h" -#include "katecodefolding.h" -#include "kateschema.h" -#include "katebookmarks.h" -#include "kateconfig.h" -#include "katemodemenu.h" -#include "kateautoindent.h" -#include "katecompletionwidget.h" -#include "katesearchbar.h" -#include "katevimodebar.h" -#include "katepartpluginmanager.h" -#include "katewordcompletion.h" -#include "katelayoutcache.h" -#include "spellcheck/spellcheck.h" -#include "spellcheck/spellcheckdialog.h" -#include "spellcheck/spellingmenu.h" -#include "katebuffer.h" -#include "script/katescriptmanager.h" -#include "script/katescriptaction.h" -#include "script/katescriptconsole.h" -#include "kateswapfile.h" -#include "katerecoverbar.h" -#include "katebrokenswapfilebar.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -//#define VIEW_RANGE_DEBUG - -//END includes - -void KateView::blockFix(KTextEditor::Range& range) -{ - if (range.start().column() > range.end().column()) - { - int tmp = range.start().column(); - range.start().setColumn(range.end().column()); - range.end().setColumn(tmp); - } -} - -KateView::KateView( KateDocument *doc, QWidget *parent ) - : KTextEditor::View( parent ) - , m_completionWidget(0) - , m_annotationModel(0) - , m_hasWrap( false ) - , m_doc( doc ) - , m_config( new KateViewConfig( this ) ) - , m_renderer( new KateRenderer( doc, this ) ) - , m_viewInternal( new KateViewInternal( this ) ) - , m_spell( new KateSpellCheckDialog( this ) ) - , m_bookmarks( new KateBookmarks( this ) ) - , m_startingUp (true) - , m_updatingDocumentConfig (false) - , m_selection (m_doc->buffer(), KTextEditor::Range::invalid(), Kate::TextRange::ExpandRight, Kate::TextRange::AllowEmpty) - , blockSelect (false) - , m_bottomViewBar (0) - , m_topViewBar (0) - , m_recoverBar(0) - , m_brokenSwapFileBar(0) - , m_cmdLine (0) - , m_console (0) - , m_searchBar (0) - , m_viModeBar (0) - , m_gotoBar (0) - , m_dictionaryBar(NULL) - , m_spellingMenu( new KateSpellingMenu( this ) ) - , m_userContextMenuSet( false ) - , m_delayedUpdateTriggered (false) - , m_lineToUpdateMin (-1) - , m_lineToUpdateMax (-1) -{ - // queued connect to collapse view updates for range changes, INIT THIS EARLY ENOUGH! - connect(this, SIGNAL(delayedUpdateOfView ()), this, SLOT(slotDelayedUpdateOfView ()), Qt::QueuedConnection); - - setComponentData ( KateGlobal::self()->componentData () ); - - // selection if for this view only and will invalidate if becoming empty - m_selection.setView (this); - - // use z depth defined in moving ranges interface - m_selection.setZDepth (-100000.0); - - KateGlobal::self()->registerView( this ); - - KTextEditor::ViewBarContainer *viewBarContainer=qobject_cast( KateGlobal::self()->container() ); - QWidget *bottomBarParent=viewBarContainer?viewBarContainer->getViewBarParent(this,KTextEditor::ViewBarContainer::BottomBar):0; - QWidget *topBarParent=viewBarContainer?viewBarContainer->getViewBarParent(this,KTextEditor::ViewBarContainer::TopBar):0; - - m_bottomViewBar=new KateViewBar (bottomBarParent!=0,KTextEditor::ViewBarContainer::BottomBar,bottomBarParent?bottomBarParent:this,this); - m_topViewBar=new KateViewBar (topBarParent!=0,KTextEditor::ViewBarContainer::TopBar,topBarParent?topBarParent:this,this); - - // ugly workaround: - // Force the layout to be left-to-right even on RTL deskstop, as discussed - // on the mailing list. This will cause the lines and icons panel to be on - // the left, even for Arabic/Hebrew/Farsi/whatever users. - setLayoutDirection ( Qt::LeftToRight ); - - // layouting ;) - m_vBox = new QVBoxLayout (this); - m_vBox->setMargin (0); - m_vBox->setSpacing (0); - - // add top viewbar... - if (topBarParent) - viewBarContainer->addViewBarToLayout(this,m_topViewBar,KTextEditor::ViewBarContainer::TopBar); - else - m_vBox->addWidget(m_topViewBar); - - m_bottomViewBar->installEventFilter(m_viewInternal); - - QHBoxLayout *hbox = new QHBoxLayout (); - m_vBox->addLayout (hbox, 100); - hbox->setMargin (0); - hbox->setSpacing (0); - - QStyleOption option; - option.initFrom(this); - - if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &option, this)) { - QHBoxLayout *extrahbox = new QHBoxLayout (); - QFrame * frame = new QFrame(this); - extrahbox->setMargin (0); - extrahbox->setSpacing (0); - extrahbox->addWidget (m_viewInternal->m_leftBorder); - extrahbox->addWidget (m_viewInternal); - frame->setLayout (extrahbox); - hbox->addWidget (frame); - hbox->addSpacing (style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &option, this)); - frame->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); - } - else { - hbox->addWidget (m_viewInternal->m_leftBorder); - hbox->addWidget (m_viewInternal); - } - hbox->addWidget (m_viewInternal->m_lineScroll); - - if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &option, this)) { - m_vBox->addSpacing (style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &option, this)); - } - - hbox = new QHBoxLayout (); - m_vBox->addLayout (hbox); - hbox->setMargin (0); - hbox->setSpacing (0); - - hbox->addWidget (m_viewInternal->m_columnScroll); - hbox->addWidget (m_viewInternal->m_dummy); - - // add viewbar... - if (bottomBarParent) - viewBarContainer->addViewBarToLayout(this,m_bottomViewBar,KTextEditor::ViewBarContainer::BottomBar); - else - m_vBox->addWidget(m_bottomViewBar); - - // this really is needed :) - m_viewInternal->updateView (); - - doc->addView( this ); - - setFocusProxy( m_viewInternal ); - setFocusPolicy( Qt::StrongFocus ); - - // default ui file with all features - QString uifile = "katepartui.rc"; - - // simple mode - if (doc->simpleMode ()) - uifile = "katepartsimpleui.rc"; - - setXMLFile( uifile ); - - setupConnections(); - setupActions(); - - // auto word completion - new KateWordCompletionView (this, actionCollection ()); - - // enable the plugins of this view - KatePartPluginManager::self()->addView(this); - - // update the enabled state of the undo/redo actions... - slotUpdateUndo(); - - m_startingUp = false; - updateConfig (); - - slotHlChanged(); - KCursor::setAutoHideCursor( m_viewInternal, true ); - - if ( viInputMode() && !config()->viInputModeHideStatusBar() ) { - deactivateEditActions(); - showViModeBar(); - } - - // swap file handling - connect (doc->swapFile(), SIGNAL(swapFileBroken()), this, SLOT(showBrokenSwapFileBar())); - connect (doc->swapFile(), SIGNAL(swapFileFound()), this, SLOT(showRecoverBar())); - connect (doc->swapFile(), SIGNAL(swapFileHandled()), this, SLOT(hideRecoverBar())); - if (doc->swapFile()->shouldRecover()) - showRecoverBar(); - -} - -KateView::~KateView() -{ - // invalidate update signal - m_delayedUpdateTriggered = false; - - KTextEditor::ViewBarContainer *viewBarContainer=qobject_cast( KateGlobal::self()->container() ); - if (viewBarContainer) { - viewBarContainer->deleteViewBarForView(this,KTextEditor::ViewBarContainer::BottomBar); - m_bottomViewBar=0; - viewBarContainer->deleteViewBarForView(this,KTextEditor::ViewBarContainer::TopBar); - m_topViewBar=0; - } - - KatePartPluginManager::self()->removeView(this); - - m_doc->removeView( this ); - - delete m_viewInternal; - - delete m_renderer; - - delete m_config; - - KateGlobal::self()->deregisterView (this); -} - -void KateView::setupConnections() -{ - connect( m_doc, SIGNAL(undoChanged()), - this, SLOT(slotUpdateUndo()) ); - connect( m_doc, SIGNAL(highlightingModeChanged(KTextEditor::Document *)), - this, SLOT(slotHlChanged()) ); - connect( m_doc, SIGNAL(canceled(const QString&)), - this, SLOT(slotSaveCanceled(const QString&)) ); - connect( m_viewInternal, SIGNAL(dropEventPass(QDropEvent*)), - this, SIGNAL(dropEventPass(QDropEvent*)) ); - - connect( m_doc, SIGNAL(annotationModelChanged( KTextEditor::AnnotationModel*, KTextEditor::AnnotationModel* )), - m_viewInternal->m_leftBorder, SLOT(annotationModelChanged( KTextEditor::AnnotationModel*, KTextEditor::AnnotationModel* )) ); - - if ( m_doc->browserView() ) - { - connect( this, SIGNAL(dropEventPass(QDropEvent*)), - this, SLOT(slotDropEventPass(QDropEvent*)) ); - } -} - -void KateView::setupActions() -{ - KActionCollection *ac = actionCollection (); - KAction *a; - - m_toggleWriteLock = 0; - - m_cut = a = ac->addAction(KStandardAction::Cut, this, SLOT(cut())); - a->setWhatsThis(i18n("Cut the selected text and move it to the clipboard")); - - m_paste = a = ac->addAction(KStandardAction::PasteText, this, SLOT(paste())); - a->setWhatsThis(i18n("Paste previously copied or cut clipboard contents")); - - m_copy = a = ac->addAction(KStandardAction::Copy, this, SLOT(copy())); - a->setWhatsThis(i18n( "Use this command to copy the currently selected text to the system clipboard.")); - - if (!m_doc->readOnly()) - { - a = ac->addAction(KStandardAction::Save, m_doc, SLOT(documentSave())); - a->setWhatsThis(i18n("Save the current document")); - - a = m_editUndo = ac->addAction(KStandardAction::Undo, m_doc, SLOT(undo())); - a->setWhatsThis(i18n("Revert the most recent editing actions")); - - a = m_editRedo = ac->addAction(KStandardAction::Redo, m_doc, SLOT(redo())); - a->setWhatsThis(i18n("Revert the most recent undo operation")); - - // Tools > Scripts - KateScriptActionMenu* scriptActionMenu = new KateScriptActionMenu(this, i18n("&Scripts")); - ac->addAction("tools_scripts", scriptActionMenu); - - - a = ac->addAction("tools_apply_wordwrap"); - a->setText(i18n("Apply &Word Wrap")); - a->setWhatsThis(i18n("Use this command to wrap all lines of the current document which are longer than the width of the" - " current view, to fit into this view.

This is a static word wrap, meaning it is not updated" - " when the view is resized.")); - connect(a, SIGNAL(triggered(bool)), SLOT(applyWordWrap())); - - a = ac->addAction("tools_cleanIndent"); - a->setText(i18n("&Clean Indentation")); - a->setWhatsThis(i18n("Use this to clean the indentation of a selected block of text (only tabs/only spaces).

" - "You can configure whether tabs should be honored and used or replaced with spaces, in the configuration dialog.")); - connect(a, SIGNAL(triggered(bool)), SLOT(cleanIndent())); - - a = ac->addAction("tools_align"); - a->setText(i18n("&Align")); - a->setWhatsThis(i18n("Use this to align the current line or block of text to its proper indent level.")); - connect(a, SIGNAL(triggered(bool)), SLOT(align())); - - a = ac->addAction("tools_comment"); - a->setText(i18n("C&omment")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_D)); - a->setWhatsThis(i18n("This command comments out the current line or a selected block of text.

" - "The characters for single/multiple line comments are defined within the language's highlighting.")); - connect(a, SIGNAL(triggered(bool)), SLOT(comment())); - - a = ac->addAction("tools_uncomment"); - a->setText(i18n("Unco&mment")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_D)); - a->setWhatsThis(i18n("This command removes comments from the current line or a selected block of text.

" - "The characters for single/multiple line comments are defined within the language's highlighting.")); - connect(a, SIGNAL(triggered(bool)), SLOT(uncomment())); - - a = ac->addAction("tools_toggle_comment"); - a->setText(i18n("Toggle Comment")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleComment())); - - a = m_toggleWriteLock = new KToggleAction(i18n("&Read Only Mode"), this); - a->setWhatsThis( i18n("Lock/unlock the document for writing") ); - a->setChecked( !m_doc->isReadWrite() ); - connect(a, SIGNAL(triggered(bool)), SLOT( toggleWriteLock() )); - ac->addAction("tools_toggle_write_lock", a); - - a = ac->addAction("tools_uppercase"); - a->setText(i18n("Uppercase")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U)); - a->setWhatsThis( i18n("Convert the selection to uppercase, or the character to the " - "right of the cursor if no text is selected.") ); - connect(a, SIGNAL(triggered(bool)), SLOT(uppercase())); - - a = ac->addAction( "tools_lowercase" ); - a->setText( i18n("Lowercase") ); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_U)); - a->setWhatsThis( i18n("Convert the selection to lowercase, or the character to the " - "right of the cursor if no text is selected.") ); - connect(a, SIGNAL(triggered(bool)), SLOT(lowercase())); - - a = ac->addAction( "tools_capitalize" ); - a->setText( i18n("Capitalize") ); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_U)); - a->setWhatsThis( i18n("Capitalize the selection, or the word under the " - "cursor if no text is selected.") ); - connect(a, SIGNAL(triggered(bool)), SLOT(capitalize())); - - a = ac->addAction( "tools_join_lines" ); - a->setText( i18n("Join Lines") ); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_J)); - connect(a, SIGNAL(triggered(bool)), SLOT( joinLines() )); - - a = ac->addAction( "tools_invoke_code_completion" ); - a->setText( i18n("Invoke Code Completion") ); - a->setWhatsThis(i18n("Manually invoke command completion, usually by using a shortcut bound to this action.")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Space)); - connect(a, SIGNAL(triggered(bool)), SLOT(userInvokedCompletion())); - } - else - { - m_cut->setEnabled (false); - m_paste->setEnabled (false); - m_editUndo = 0; - m_editRedo = 0; - } - - a = ac->addAction( KStandardAction::Print, m_doc, SLOT(print()) ); - a->setWhatsThis(i18n("Print the current document.")); - - a = ac->addAction( "file_reload" ); - a->setIcon(KIcon("view-refresh")); - a->setText(i18n("Reloa&d")); - a->setShortcuts(KStandardShortcut::reload()); - a->setWhatsThis(i18n("Reload the current document from disk.")); - connect(a, SIGNAL(triggered(bool)), SLOT(reloadFile())); - - a = ac->addAction( KStandardAction::SaveAs, m_doc, SLOT(documentSaveAs()) ); - a->setWhatsThis(i18n("Save the current document to disk, with a name of your choice.")); - - a = ac->addAction( KStandardAction::GotoLine, this, SLOT(gotoLine()) ); - a->setWhatsThis(i18n("This command opens a dialog and lets you choose a line that you want the cursor to move to.")); - - a = ac->addAction("set_confdlg"); - a->setText(i18n("&Configure Editor...")); - a->setWhatsThis(i18n("Configure various aspects of this editor.")); - connect(a, SIGNAL(triggered(bool)), SLOT(slotConfigDialog())); - - KateModeMenu *ftm = new KateModeMenu (i18n("&Mode"), this); - ac->addAction("tools_mode", ftm); - ftm->setWhatsThis(i18n("Here you can choose which mode should be used for the current document. This will influence the highlighting and folding being used, for example.")); - ftm->updateMenu (m_doc); - - KateHighlightingMenu *menu = new KateHighlightingMenu (i18n("&Highlighting"), this); - ac->addAction("tools_highlighting", menu); - menu->setWhatsThis(i18n("Here you can choose how the current document should be highlighted.")); - menu->updateMenu (m_doc); - - KateViewSchemaAction *schemaMenu = new KateViewSchemaAction (i18n("&Schema"), this); - ac->addAction("view_schemas", schemaMenu); - schemaMenu->updateMenu (this); - - // indentation menu - KateViewIndentationAction *indentMenu = new KateViewIndentationAction(m_doc, i18n("&Indentation"), this); - ac->addAction("tools_indentation", indentMenu); - - m_selectAll = a= ac->addAction( KStandardAction::SelectAll, this, SLOT(selectAll()) ); - a->setWhatsThis(i18n("Select the entire text of the current document.")); - - m_deSelect = a= ac->addAction( KStandardAction::Deselect, this, SLOT(clearSelection()) ); - a->setWhatsThis(i18n("If you have selected something within the current document, this will no longer be selected.")); - - a = ac->addAction("view_inc_font_sizes"); - a->setIcon(KIcon("zoom-in")); - a->setText(i18n("Enlarge Font")); - a->setWhatsThis(i18n("This increases the display font size.")); - connect(a, SIGNAL(triggered(bool)), m_viewInternal, SLOT(slotIncFontSizes())); - - a = ac->addAction("view_dec_font_sizes"); - a->setIcon(KIcon("zoom-out")); - a->setText(i18n("Shrink Font")); - a->setWhatsThis(i18n("This decreases the display font size.")); - connect(a, SIGNAL(triggered(bool)), m_viewInternal, SLOT(slotDecFontSizes())); - - a = m_toggleBlockSelection = new KToggleAction(i18n("Bl&ock Selection Mode"), this); - ac->addAction("set_verticalSelect", a); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_B)); - a->setWhatsThis(i18n("This command allows switching between the normal (line based) selection mode and the block selection mode.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleBlockSelectionMode())); - - a = m_toggleInsert = new KToggleAction(i18n("Overwr&ite Mode"), this); - ac->addAction("set_insert", a); - a->setShortcut(QKeySequence(Qt::Key_Insert)); - a->setWhatsThis(i18n("Choose whether you want the text you type to be inserted or to overwrite existing text.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleInsert())); - - KToggleAction *toggleAction; - a = m_toggleDynWrap = toggleAction = new KToggleAction(i18n("&Dynamic Word Wrap"), this); - ac->addAction("view_dynamic_word_wrap", a); - a->setShortcut(QKeySequence(Qt::Key_F10)); - a->setWhatsThis(i18n("If this option is checked, the text lines will be wrapped at the view border on the screen.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleDynWordWrap())); - - a = m_setDynWrapIndicators = new KSelectAction(i18n("Dynamic Word Wrap Indicators"), this); - ac->addAction("dynamic_word_wrap_indicators", a); - a->setWhatsThis(i18n("Choose when the Dynamic Word Wrap Indicators should be displayed")); - - connect(m_setDynWrapIndicators, SIGNAL(triggered(int)), this, SLOT(setDynWrapIndicators(int))); - QStringList list2; - list2.append(i18n("&Off")); - list2.append(i18n("Follow &Line Numbers")); - list2.append(i18n("&Always On")); - m_setDynWrapIndicators->setItems(list2); - m_setDynWrapIndicators->setEnabled(m_toggleDynWrap->isChecked()); // only synced on real change, later - - a = toggleAction = m_toggleFoldingMarkers = new KToggleAction(i18n("Show Folding &Markers"), this); - ac->addAction("view_folding_markers", a); - a->setShortcut(QKeySequence(Qt::Key_F9)); - a->setWhatsThis(i18n("You can choose if the codefolding marks should be shown, if codefolding is possible.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleFoldingMarkers())); - - a = m_toggleIconBar = toggleAction = new KToggleAction(i18n("Show &Icon Border"), this); - ac->addAction("view_border", a); - a->setShortcut(QKeySequence(Qt::Key_F6)); - a->setWhatsThis(i18n("Show/hide the icon border.

The icon border shows bookmark symbols, for instance.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleIconBorder())); - - a = toggleAction = m_toggleLineNumbers = new KToggleAction(i18n("Show &Line Numbers"), this); - ac->addAction("view_line_numbers", a); - a->setShortcut(QKeySequence(Qt::Key_F11)); - a->setWhatsThis(i18n("Show/hide the line numbers on the left hand side of the view.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleLineNumbersOn())); - - a = m_toggleScrollBarMarks = toggleAction = new KToggleAction(i18n("Show Scroll&bar Marks"), this); - ac->addAction("view_scrollbar_marks", a); - a->setWhatsThis(i18n("Show/hide the marks on the vertical scrollbar.

The marks show bookmarks, for instance.")); - connect(a, SIGNAL(triggered(bool)), SLOT(toggleScrollBarMarks())); - - a = toggleAction = m_toggleWWMarker = new KToggleAction(i18n("Show Static &Word Wrap Marker"), this); - ac->addAction("view_word_wrap_marker", a); - a->setWhatsThis( i18n( - "Show/hide the Word Wrap Marker, a vertical line drawn at the word " - "wrap column as defined in the editing properties" )); - connect(a, SIGNAL(triggered(bool)), SLOT( toggleWWMarker() )); - - a = m_switchCmdLine = ac->addAction("switch_to_cmd_line"); - a->setText(i18n("Switch to Command Line")); - a->setShortcut(QKeySequence(Qt::Key_F7)); - a->setWhatsThis(i18n("Show/hide the command line on the bottom of the view.")); - connect(a, SIGNAL(triggered(bool)), SLOT(switchToCmdLine())); - - a = m_switchConsole = ac->addAction("switch_to_console"); - a->setText(i18n("Show the JavaScript Console")); - a->setWhatsThis(i18n("Show/hide the JavaScript Console on the bottom of the view.")); - connect(a, SIGNAL(triggered(bool)), SLOT(switchToConsole())); - - a = m_viInputModeAction = new KToggleAction(i18n("&VI Input Mode"), this); - ac->addAction("view_vi_input_mode", a); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::META + Qt::Key_V)); - a->setWhatsThis( i18n("Activate/deactivate VI input mode" )); - connect(a, SIGNAL(triggered(bool)), SLOT( toggleViInputMode() )); - - a = m_setEndOfLine = new KSelectAction(i18n("&End of Line"), this); - ac->addAction("set_eol", a); - a->setWhatsThis(i18n("Choose which line endings should be used, when you save the document")); - QStringList list; - list.append("&UNIX"); - list.append("&Windows/DOS"); - list.append("&Macintosh"); - m_setEndOfLine->setItems(list); - m_setEndOfLine->setCurrentItem (m_doc->config()->eol()); - connect(m_setEndOfLine, SIGNAL(triggered(int)), this, SLOT(setEol(int))); - - a=m_addBom=new KToggleAction(i18n("Add &Byte Order Mark (BOM)"),this); - ac->addAction("add_bom",a); - a->setWhatsThis(i18n("Enable/disable adding of byte order markers for UTF-8/UTF-16 encoded files while saving")); - connect(m_addBom,SIGNAL(triggered(bool)),this,SLOT(setAddBom(bool))); - // encoding menu - KateViewEncodingAction *encodingAction = new KateViewEncodingAction(m_doc, this, i18n("E&ncoding"), this); - ac->addAction("set_encoding", encodingAction); - - a = ac->addAction( KStandardAction::Find, this, SLOT(find()) ); - a->setWhatsThis(i18n("Look up the first occurrence of a piece of text or regular expression.")); - addAction(a); - - a = ac->addAction("edit_find_selected"); - a->setText(i18n("Find Selected")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H)); - a->setWhatsThis(i18n("Finds next occurrence of selected text.")); - connect(a, SIGNAL(triggered(bool)), SLOT(findSelectedForwards())); - - a = ac->addAction("edit_find_selected_backwards"); - a->setText(i18n("Find Selected Backwards")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H)); - a->setWhatsThis(i18n("Finds previous occurrence of selected text.")); - connect(a, SIGNAL(triggered(bool)), SLOT(findSelectedBackwards())); - - a = ac->addAction( KStandardAction::FindNext, this, SLOT(findNext()) ); - a->setWhatsThis(i18n("Look up the next occurrence of the search phrase.")); - addAction(a); - - a = ac->addAction( KStandardAction::FindPrev, "edit_find_prev", this, SLOT(findPrevious()) ); - a->setWhatsThis(i18n("Look up the previous occurrence of the search phrase.")); - addAction(a); - - a = ac->addAction( KStandardAction::Replace, this, SLOT(replace()) ); - a->setWhatsThis(i18n("Look up a piece of text or regular expression and replace the result with some given text.")); - - m_spell->createActions( ac ); - m_toggleOnTheFlySpellCheck = new KToggleAction(i18n("Automatic Spell Checking"), this); - m_toggleOnTheFlySpellCheck->setWhatsThis(i18n("Enable/disable automatic spell checking")); - m_toggleOnTheFlySpellCheck->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_O)); - connect(m_toggleOnTheFlySpellCheck, SIGNAL(triggered(bool)), SLOT(toggleOnTheFlySpellCheck(bool))); - ac->addAction("tools_toggle_automatic_spell_checking", m_toggleOnTheFlySpellCheck); - - a = ac->addAction("tools_change_dictionary"); - a->setText(i18n("Change Dictionary...")); - a->setWhatsThis(i18n("Change the dictionary that is used for spell checking.")); - connect(a, SIGNAL(triggered()), SLOT(changeDictionary())); - - a = ac->addAction("tools_clear_dictionary_ranges"); - a->setText(i18n("Clear Dictionary Ranges")); - a->setVisible(false); - a->setWhatsThis(i18n("Remove all the separate dictionary ranges that were set for spell checking.")); - connect(a, SIGNAL(triggered()), m_doc, SLOT(clearDictionaryRanges())); - connect(m_doc, SIGNAL(dictionaryRangesPresent(bool)), a, SLOT(setVisible(bool))); - - m_spellingMenu->createActions( ac ); - - if (!m_doc->simpleMode ()) - m_bookmarks->createActions( ac ); - - slotSelectionChanged (); - - //Now setup the editing actions before adding the associated - //widget and setting the shortcut context - setupEditActions(); - setupCodeFolding(); - - ac->addAssociatedWidget(m_viewInternal); - - foreach (QAction* action, ac->actions()) - action->setShortcutContext(Qt::WidgetWithChildrenShortcut); - - connect (this, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(slotSelectionChanged())); -} - -void KateView::slotConfigDialog () -{ - KateGlobal::self ()->configDialog (this); -} - -void KateView::setupEditActions() -{ - //If you add an editing action to this - //function make sure to include the line - //m_editActions << a after creating the action - KActionCollection* ac = actionCollection(); - - KAction* a = ac->addAction("word_left"); - a->setText(i18n("Move Word Left")); - a->setShortcuts(KStandardShortcut::backwardWord()); - connect(a, SIGNAL(triggered(bool)), SLOT(wordLeft())); - m_editActions << a; - - a = ac->addAction("select_char_left"); - a->setText(i18n("Select Character Left")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Left)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftCursorLeft())); - m_editActions << a; - - a = ac->addAction("select_word_left"); - a->setText(i18n("Select Word Left")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_Left)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftWordLeft())); - m_editActions << a; - - - a = ac->addAction("word_right"); - a->setText(i18n("Move Word Right")); - a->setShortcuts(KStandardShortcut::forwardWord()); - connect(a, SIGNAL(triggered(bool)), SLOT(wordRight())); - m_editActions << a; - - a = ac->addAction("select_char_right"); - a->setText(i18n("Select Character Right")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Right)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftCursorRight())); - m_editActions << a; - - a = ac->addAction("select_word_right"); - a->setText(i18n("Select Word Right")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_Right)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftWordRight())); - m_editActions << a; - - - a = ac->addAction("beginning_of_line"); - a->setText(i18n("Move to Beginning of Line")); - a->setShortcuts(KStandardShortcut::beginningOfLine()); - connect(a, SIGNAL(triggered(bool)), SLOT(home())); - m_editActions << a; - - a = ac->addAction("beginning_of_document"); - a->setText(i18n("Move to Beginning of Document")); - a->setShortcuts(KStandardShortcut::begin()); - connect(a, SIGNAL(triggered(bool)), SLOT(top())); - m_editActions << a; - - a = ac->addAction("select_beginning_of_line"); - a->setText(i18n("Select to Beginning of Line")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Home)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftHome())); - m_editActions << a; - - a = ac->addAction("select_beginning_of_document"); - a->setText(i18n("Select to Beginning of Document")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_Home)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftTop())); - m_editActions << a; - - - a = ac->addAction("end_of_line"); - a->setText(i18n("Move to End of Line")); - a->setShortcuts(KStandardShortcut::endOfLine()); - connect(a, SIGNAL(triggered(bool)), SLOT(end())); - m_editActions << a; - - a = ac->addAction("end_of_document"); - a->setText(i18n("Move to End of Document")); - a->setShortcuts(KStandardShortcut::end()); - connect(a, SIGNAL(triggered(bool)), SLOT(bottom())); - m_editActions << a; - - a = ac->addAction("select_end_of_line"); - a->setText(i18n("Select to End of Line")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_End)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftEnd())); - m_editActions << a; - - a = ac->addAction("select_end_of_document"); - a->setText(i18n("Select to End of Document")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_End)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftBottom())); - m_editActions << a; - - - a = ac->addAction("select_line_up"); - a->setText(i18n("Select to Previous Line")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Up)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftUp())); - m_editActions << a; - - a = ac->addAction("scroll_line_up"); - a->setText(i18n("Scroll Line Up")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up)); - connect(a, SIGNAL(triggered(bool)), SLOT(scrollUp())); - m_editActions << a; - - - a = ac->addAction("move_line_down"); - a->setText(i18n("Move to Next Line")); - a->setShortcut(QKeySequence(Qt::Key_Down)); - connect(a, SIGNAL(triggered(bool)), SLOT(down())); - m_editActions << a; - - - a = ac->addAction("move_line_up"); - a->setText(i18n("Move to Previous Line")); - a->setShortcut(QKeySequence(Qt::Key_Up)); - connect(a, SIGNAL(triggered(bool)), SLOT(up())); - m_editActions << a; - - - a = ac->addAction("move_cursor_right"); - a->setText(i18n("Move Cursor Right")); - a->setShortcut(QKeySequence(Qt::Key_Right)); - connect(a, SIGNAL(triggered(bool)), SLOT(cursorRight())); - m_editActions << a; - - - a = ac->addAction("move_cusor_left"); - a->setText(i18n("Move Cursor Left")); - a->setShortcut(QKeySequence(Qt::Key_Left)); - connect(a, SIGNAL(triggered(bool)), SLOT(cursorLeft())); - m_editActions << a; - - - a = ac->addAction("select_line_down"); - a->setText(i18n("Select to Next Line")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Down)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftDown())); - m_editActions << a; - - a = ac->addAction("scroll_line_down"); - a->setText(i18n("Scroll Line Down")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down)); - connect(a, SIGNAL(triggered(bool)), SLOT(scrollDown())); - m_editActions << a; - - - a = ac->addAction("scroll_page_up"); - a->setText(i18n("Scroll Page Up")); - a->setShortcuts(KStandardShortcut::prior()); - connect(a, SIGNAL(triggered(bool)), SLOT(pageUp())); - m_editActions << a; - - a = ac->addAction("select_page_up"); - a->setText(i18n("Select Page Up")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_PageUp)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftPageUp())); - m_editActions << a; - - a = ac->addAction("move_top_of_view"); - a->setText(i18n("Move to Top of View")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp)); - connect(a, SIGNAL(triggered(bool)), SLOT(topOfView())); - m_editActions << a; - - a = ac->addAction("select_top_of_view"); - a->setText(i18n("Select to Top of View")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_PageUp)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftTopOfView())); - m_editActions << a; - - - a = ac->addAction("scroll_page_down"); - a->setText(i18n("Scroll Page Down")); - a->setShortcuts(KStandardShortcut::next()); - connect(a, SIGNAL(triggered(bool)), SLOT(pageDown())); - m_editActions << a; - - a = ac->addAction("select_page_down"); - a->setText(i18n("Select Page Down")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_PageDown)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftPageDown())); - m_editActions << a; - - a = ac->addAction("move_bottom_of_view"); - a->setText(i18n("Move to Bottom of View")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown)); - connect(a, SIGNAL(triggered(bool)), SLOT(bottomOfView())); - m_editActions << a; - - a = ac->addAction("select_bottom_of_view"); - a->setText(i18n("Select to Bottom of View")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_PageDown)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftBottomOfView())); - m_editActions << a; - - a = ac->addAction("to_matching_bracket"); - a->setText(i18n("Move to Matching Bracket")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6)); - connect(a, SIGNAL(triggered(bool)), SLOT(toMatchingBracket())); - m_editActions << a; - - a = ac->addAction("select_matching_bracket"); - a->setText(i18n("Select to Matching Bracket")); - a->setShortcut(QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_6)); - connect(a, SIGNAL(triggered(bool)), SLOT(shiftToMatchingBracket())); - m_editActions << a; - - - // anders: shortcuts doing any changes should not be created in browserextension - if ( !m_doc->readOnly() ) - { - a = ac->addAction("transpose_char"); - a->setText(i18n("Transpose Characters")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_T)); - connect(a, SIGNAL(triggered(bool)), SLOT(transpose())); - m_editActions << a; - - a = ac->addAction("delete_line"); - a->setText(i18n("Delete Line")); - a->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K)); - connect(a, SIGNAL(triggered(bool)), SLOT(killLine())); - m_editActions << a; - - a = ac->addAction("delete_word_left"); - a->setText(i18n("Delete Word Left")); - a->setShortcuts(KStandardShortcut::deleteWordBack()); - connect(a, SIGNAL(triggered(bool)), SLOT(deleteWordLeft())); - m_editActions << a; - - a = ac->addAction("delete_word_right"); - a->setText(i18n("Delete Word Right")); - a->setShortcuts(KStandardShortcut::deleteWordForward()); - connect(a, SIGNAL(triggered(bool)), SLOT(deleteWordRight())); - m_editActions << a; - - a = ac->addAction("delete_next_character"); - a->setText(i18n("Delete Next Character")); - a->setShortcut(QKeySequence(Qt::Key_Delete)); - connect(a, SIGNAL(triggered(bool)), SLOT(keyDelete())); - m_editActions << a; - - a = ac->addAction("backspace"); - a->setText(i18n("Backspace")); - QList scuts; - scuts << QKeySequence(Qt::Key_Backspace) - << QKeySequence(Qt::SHIFT + Qt::Key_Backspace); - a->setShortcuts(scuts); - connect(a, SIGNAL(triggered(bool)), SLOT(backspace())); - m_editActions << a; - - a = ac->addAction("insert_tabulator"); - a->setText(i18n("Insert Tab")); - connect(a, SIGNAL(triggered(bool)), SLOT(insertTab())); - m_editActions << a; - - a = ac->addAction("smart_newline"); - a->setText(i18n("Insert Smart Newline")); - a->setWhatsThis(i18n("Insert newline including leading characters of the current line which are not letters or numbers.")); - scuts.clear(); - scuts << QKeySequence(Qt::SHIFT + Qt::Key_Return) - << QKeySequence(Qt::SHIFT + Qt::Key_Enter); - a->setShortcuts(scuts); - connect(a, SIGNAL(triggered(bool)), SLOT(smartNewline())); - m_editActions << a; - - a = ac->addAction("tools_indent"); - a->setIcon(KIcon("format-indent-more")); - a->setText(i18n("&Indent")); - a->setWhatsThis(i18n("Use this to indent a selected block of text.

" - "You can configure whether tabs should be honored and used or replaced with spaces, in the configuration dialog.")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_I)); - connect(a, SIGNAL(triggered(bool)), SLOT(indent())); - - a = ac->addAction("tools_unindent"); - a->setIcon(KIcon("format-indent-less")); - a->setText(i18n("&Unindent")); - a->setWhatsThis(i18n("Use this to unindent a selected block of text.")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_I)); - connect(a, SIGNAL(triggered(bool)), SLOT(unIndent())); - } - - if( hasFocus() ) - slotGotFocus(); - else - slotLostFocus(); -} - -void KateView::setupCodeFolding() -{ - KActionCollection *ac=this->actionCollection(); - - KAction* a = ac->addAction("folding_toplevel"); - a->setText(i18n("Collapse Toplevel")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Minus)); - connect(a, SIGNAL(triggered(bool)), m_doc->foldingTree(), SLOT(collapseToplevelNodes())); - - a = ac->addAction("folding_expandtoplevel"); - a->setText(i18n("Expand Toplevel")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Plus)); - connect(a, SIGNAL(triggered(bool)), SLOT(slotExpandToplevel())); - - a = ac->addAction("folding_collapselocal"); - a->setText(i18n("Collapse One Local Level")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_Minus)); - connect(a, SIGNAL(triggered(bool)), SLOT(slotCollapseLocal())); - - a = ac->addAction("folding_expandlocal"); - a->setText(i18n("Expand One Local Level")); - a->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_Plus)); - connect(a, SIGNAL(triggered(bool)), SLOT(slotExpandLocal())); -} - -void KateView::slotExpandToplevel() -{ - m_doc->foldingTree()->expandToplevelNodes(m_doc->lines()); -} - -void KateView::slotCollapseLocal() -{ - int realLine = m_doc->foldingTree()->collapseOne(cursorPosition().line()); - if (realLine != -1) { - // TODO rodda: fix this to only set line and allow internal view to chose column - // Explicitly call internal because we want this to be registered as an internal call - - // (dh) current solution: use current virtual cursor column and map it to - // the real column of the new cursor line - Kate::TextLine textLine = m_doc->plainKateTextLine(realLine); - if (!textLine) return; - KTextEditor::Cursor cc = KTextEditor::Cursor(realLine, textLine->fromVirtualColumn(virtualCursorColumn(), m_doc->config()->tabWidth())); - setCursorPositionInternal(cc, 1); - } -} - -void KateView::slotExpandLocal() -{ - m_doc->foldingTree()->expandOne(cursorPosition().line(), m_doc->lines()); -} - -QString KateView::viewMode () const -{ - if (!m_doc->isReadWrite()) - return i18n ("R/O"); - - if (viInputMode()) { - // vi mode has different notion of OVR/INS. - // vi mode's status is showin in viModeBar() instead - return QString(); - } - - return isOverwriteMode() ? i18n("OVR") : i18n ("INS"); -} - -void KateView::slotGotFocus() -{ - //kDebug(13020) << "KateView::slotGotFocus"; - - if ( !viInputMode() ) { - activateEditActions(); - } - emit focusIn ( this ); -} - -void KateView::slotLostFocus() -{ - //kDebug(13020) << "KateView::slotLostFocus"; - - if ( !viInputMode() ) { - deactivateEditActions(); - } - - emit focusOut ( this ); -} - -void KateView::setDynWrapIndicators(int mode) -{ - config()->setDynWordWrapIndicators (mode); -} - -bool KateView::isOverwriteMode() const -{ - return m_doc->config()->ovr(); -} - -void KateView::reloadFile() -{ - // bookmarks and cursor positions are temporarily saved by the document - m_doc->documentReload(); -} - -void KateView::slotReadWriteChanged () -{ - if ( m_toggleWriteLock ) - m_toggleWriteLock->setChecked( ! m_doc->isReadWrite() ); - - m_cut->setEnabled (m_doc->isReadWrite() && (selection() || m_config->smartCopyCut())); - m_paste->setEnabled (m_doc->isReadWrite()); - - QStringList l; - - l << "edit_replace" << "set_insert" << "tools_spelling" << "tools_indent" - << "tools_unindent" << "tools_cleanIndent" << "tools_align" << "tools_comment" - << "tools_uncomment" << "tools_toggle_comment" << "tools_uppercase" << "tools_lowercase" - << "tools_capitalize" << "tools_join_lines" << "tools_apply_wordwrap" - << "tools_spelling_from_cursor" - << "tools_spelling_selection"; - - QAction *a = 0; - for (int z = 0; z < l.size(); z++) - if ((a = actionCollection()->action( l[z].toAscii().constData() ))) - a->setEnabled (m_doc->isReadWrite()); - slotUpdateUndo(); -} - -void KateView::slotUpdateUndo() -{ - if (m_doc->readOnly()) - return; - - m_editUndo->setEnabled(m_doc->isReadWrite() && m_doc->undoCount() > 0); - m_editRedo->setEnabled(m_doc->isReadWrite() && m_doc->redoCount() > 0); -} - -void KateView::slotDropEventPass( QDropEvent * ev ) -{ - const KUrl::List lstDragURLs=KUrl::List::fromMimeData(ev->mimeData()); - bool ok = !lstDragURLs.isEmpty(); - - KParts::BrowserExtension * ext = KParts::BrowserExtension::childObject( doc() ); - if ( ok && ext ) - emit ext->openUrlRequest( lstDragURLs.first() ); -} - -void KateView::contextMenuEvent( QContextMenuEvent *ev ) -{ - if ( !m_doc || !m_doc->browserExtension() ) - return; - KParts::OpenUrlArguments args; - args.setMimeType( QLatin1String("text/plain") ); - emit m_doc->browserExtension()->popupMenu( ev->globalPos(), m_doc->url(), S_IFREG, args ); - ev->accept(); -} - -bool KateView::setCursorPositionInternal( const KTextEditor::Cursor& position, uint tabwidth, bool calledExternally ) -{ - Kate::TextLine l = m_doc->kateTextLine( position.line() ); - - if (!l) - return false; - - QString line_str = m_doc->line( position.line() ); - - int x = 0; - int z = 0; - for (; z < line_str.length() && z < position.column(); z++) { - if (line_str[z] == QChar('\t')) x += tabwidth - (x % tabwidth); else x++; - } - - if (blockSelectionMode()) - if (z < position.column()) - x += position.column() - z; - - m_viewInternal->updateCursor( KTextEditor::Cursor(position.line(), x), false, true, calledExternally ); - - return true; -} - -void KateView::toggleInsert() -{ - m_doc->config()->setOvr(!m_doc->config()->ovr()); - m_toggleInsert->setChecked (isOverwriteMode ()); - - emit viewModeChanged(this); - emit viewEditModeChanged(this,viewEditMode()); -} - -void KateView::slotSaveCanceled( const QString& error ) -{ - if ( !error.isEmpty() ) // happens when canceling a job - KMessageBox::error( this, error ); -} - -void KateView::gotoLine() -{ - gotoBar()->updateData(); - bottomViewBar()->showBarWidget(gotoBar()); -} - -void KateView::changeDictionary() -{ - dictionaryBar()->updateData(); - bottomViewBar()->showBarWidget(dictionaryBar()); -} - -void KateView::joinLines() -{ - int first = selectionRange().start().line(); - int last = selectionRange().end().line(); - //int left = m_doc->line( last ).length() - m_doc->selEndCol(); - if ( first == last ) - { - first = cursorPosition().line(); - last = first + 1; - } - m_doc->joinLines( first, last ); -} - -void KateView::readSessionConfig(const KConfigGroup& config) -{ - setCursorPositionInternal(KTextEditor::Cursor(config.readEntry("CursorLine",0), config.readEntry("CursorColumn",0))); - - // save vi registers if there are registers with contents - if ( KateGlobal::self()->viInputModeGlobal()->getRegisters()->size() > 0 ) { - getViInputModeManager()->readSessionConfig( config ); - } -} - -void KateView::writeSessionConfig(KConfigGroup& config) -{ - config.writeEntry("CursorLine",m_viewInternal->m_cursor.line()); - config.writeEntry("CursorColumn",m_viewInternal->m_cursor.column()); - - // save vi registers if there are registers with contents - if ( KateGlobal::self()->viInputModeGlobal()->getRegisters()->size() > 0 ) { - getViInputModeManager()->writeSessionConfig( config ); - } -} - -int KateView::getEol() const -{ - return m_doc->config()->eol(); -} - -void KateView::setEol(int eol) -{ - if (!doc()->isReadWrite()) - return; - - if (m_updatingDocumentConfig) - return; - - m_doc->config()->setEol (eol); -} - -void KateView::setAddBom(bool enabled) -{ - if (!doc()->isReadWrite()) - return; - - if (m_updatingDocumentConfig) - return; - - m_doc->config()->setBom (enabled); - m_doc->bomSetByUser(); -} - -void KateView::setIconBorder( bool enable ) -{ - config()->setIconBar (enable); -} - -void KateView::toggleIconBorder() -{ - config()->setIconBar (!config()->iconBar()); -} - -void KateView::setLineNumbersOn( bool enable ) -{ - config()->setLineNumbers (enable); -} - -void KateView::toggleLineNumbersOn() -{ - config()->setLineNumbers (!config()->lineNumbers()); -} - -void KateView::setScrollBarMarks( bool enable ) -{ - config()->setScrollBarMarks (enable); -} - -void KateView::toggleScrollBarMarks() -{ - config()->setScrollBarMarks (!config()->scrollBarMarks()); -} - -void KateView::toggleDynWordWrap() -{ - config()->setDynWordWrap( !config()->dynWordWrap() ); -} - -void KateView::toggleWWMarker() -{ - m_renderer->config()->setWordWrapMarker (!m_renderer->config()->wordWrapMarker()); -} - -void KateView::setFoldingMarkersOn( bool enable ) -{ - config()->setFoldingBar ( enable ); -} - -void KateView::toggleFoldingMarkers() -{ - config()->setFoldingBar ( !config()->foldingBar() ); -} - -bool KateView::iconBorder() { - return m_viewInternal->m_leftBorder->iconBorderOn(); -} - -bool KateView::lineNumbersOn() { - return m_viewInternal->m_leftBorder->lineNumbersOn(); -} - -bool KateView::scrollBarMarks() { - return m_viewInternal->m_lineScroll->showMarks(); -} - -int KateView::dynWrapIndicators() { - return m_viewInternal->m_leftBorder->dynWrapIndicators(); -} - -bool KateView::foldingMarkersOn() { - return m_viewInternal->m_leftBorder->foldingMarkersOn(); -} - -void KateView::toggleWriteLock() -{ - m_doc->setReadWrite( ! m_doc->isReadWrite() ); -} - -void KateView::enableTextHints(int timeout) -{ - m_viewInternal->enableTextHints(timeout); -} - -void KateView::disableTextHints() -{ - m_viewInternal->disableTextHints(); -} - -bool KateView::viInputMode() const -{ - return m_viewInternal->m_viInputMode; -} - -bool KateView::viInputModeStealKeys() const -{ - return m_viewInternal->m_viInputModeStealKeys; -} - -void KateView::toggleViInputMode() -{ - config()->setViInputMode (!config()->viInputMode()); - - if ( viInputMode() ) { - m_viewInternal->getViInputModeManager()->viEnterNormalMode(); - - if ( !config()->viInputModeHideStatusBar() ) { - showViModeBar(); - } - - deactivateEditActions(); - } else { // disabling the vi input mode - hideViModeBar(); - activateEditActions(); - } - - emit viewModeChanged(this); - emit viewEditModeChanged(this,viewEditMode()); -} - -void KateView::showViModeBar() -{ - if (viInputMode() && !config()->viInputModeHideStatusBar()) { - bottomViewBar()->addPermanentBarWidget(viModeBar()); - updateViModeBarMode(); - } -} - -void KateView::hideViModeBar() -{ - if (bottomViewBar() && m_viModeBar) { - bottomViewBar()->removePermanentBarWidget(viModeBar()); - } -} - -void KateView::updateViModeBarMode() -{ - if (config()->viInputModeHideStatusBar()) - return; - - viModeBar()->updateViMode(getCurrentViMode()); -} - -void KateView::updateViModeBarCmd() -{ - if (config()->viInputModeHideStatusBar()) - return; - - QString cmd = m_viewInternal->getViInputModeManager()->getVerbatimKeys(); - viModeBar()->updatePartialCommand(cmd); -} - -ViMode KateView::getCurrentViMode() const -{ - return m_viewInternal->getCurrentViMode(); -} - -KateViInputModeManager* KateView::getViInputModeManager() -{ - return m_viewInternal->getViInputModeManager(); -} - -void KateView::find() -{ - const bool INIT_HINT_AS_INCREMENTAL = false; - KateSearchBar * const bar = searchBar(INIT_HINT_AS_INCREMENTAL); - bar->enterIncrementalMode(); - bottomViewBar()->showBarWidget(bar); - bar->setFocus(); -} - -void KateView::findSelectedForwards() -{ - KateSearchBar::nextMatchForSelection(this, KateSearchBar::SearchForward); -} - -void KateView::findSelectedBackwards() -{ - KateSearchBar::nextMatchForSelection(this, KateSearchBar::SearchBackward); -} - -void KateView::replace() -{ - const bool INIT_HINT_AS_POWER = true; - KateSearchBar * const bar = searchBar(INIT_HINT_AS_POWER); - bar->enterPowerMode(); - bottomViewBar()->showBarWidget(bar); - bar->setFocus(); -} - -void KateView::findNext() -{ - searchBar()->findNext(); -} - -void KateView::findPrevious() -{ - searchBar()->findPrevious(); -} - -void KateView::slotSelectionChanged () -{ - m_copy->setEnabled (selection() || m_config->smartCopyCut()); - m_deSelect->setEnabled (selection()); - - if (m_doc->readOnly()) - return; - - m_cut->setEnabled (selection() || m_config->smartCopyCut() ); - - m_spell->updateActions (); -} - -void KateView::switchToCmdLine () -{ - // if the user has selected text, insert the selection's range (start line to end line) in the - // command line when opened - if (selectionRange().start().line() != -1 && selectionRange().end().line() != -1) { - cmdLineBar()->setText(QString::number(selectionRange().start().line()+1)+',' - +QString::number(selectionRange().end().line()+1)); - } - bottomViewBar()->showBarWidget(cmdLineBar()); - cmdLineBar()->setFocus (); - hideViModeBar(); -} - -void KateView::switchToConsole () -{ - if (!m_console) { - m_console = new KateScriptConsole (this, bottomViewBar()); - bottomViewBar()->addBarWidget(m_console); - bottomViewBar()->showBarWidget(m_console); - } else { - bottomViewBar()->showBarWidget(m_console); - m_console->setupLayout(); - } - m_console->setFocus (); - hideViModeBar(); -} - -KateRenderer *KateView::renderer () -{ - return m_renderer; -} - -void KateView::updateConfig () -{ - if (m_startingUp) - return; - - // dyn. word wrap & markers - if (m_hasWrap != config()->dynWordWrap()) { - m_viewInternal->prepareForDynWrapChange(); - - m_hasWrap = config()->dynWordWrap(); - - m_viewInternal->dynWrapChanged(); - - m_setDynWrapIndicators->setEnabled(config()->dynWordWrap()); - m_toggleDynWrap->setChecked( config()->dynWordWrap() ); - } - - m_viewInternal->m_leftBorder->setDynWrapIndicators( config()->dynWordWrapIndicators() ); - m_setDynWrapIndicators->setCurrentItem( config()->dynWordWrapIndicators() ); - - // line numbers - m_viewInternal->m_leftBorder->setLineNumbersOn( config()->lineNumbers() ); - m_toggleLineNumbers->setChecked( config()->lineNumbers() ); - - // icon bar - m_viewInternal->m_leftBorder->setIconBorderOn( config()->iconBar() ); - m_toggleIconBar->setChecked( config()->iconBar() ); - - // scrollbar marks - m_viewInternal->m_lineScroll->setShowMarks( config()->scrollBarMarks() ); - m_toggleScrollBarMarks->setChecked( config()->scrollBarMarks() ); - - // misc edit - m_toggleBlockSelection->setChecked( blockSelectionMode() ); - m_toggleInsert->setChecked( isOverwriteMode() ); - - // vi modes - m_viInputModeAction->setChecked( config()->viInputMode() ); - - updateFoldingConfig (); - - // bookmark - m_bookmarks->setSorting( (KateBookmarks::Sorting) config()->bookmarkSort() ); - - m_viewInternal->setAutoCenterLines(config()->autoCenterLines ()); - - // vi input mode - m_viewInternal->m_viInputMode = config()->viInputMode(); - - // whether vi input mode should override actions or not - m_viewInternal->m_viInputModeStealKeys = config()->viInputModeStealKeys(); - - reflectOnTheFlySpellCheckStatus(m_doc->isOnTheFlySpellCheckingEnabled()); - - // register/unregister word completion... - unregisterCompletionModel (KateGlobal::self()->wordCompletionModel()); - if (config()->wordCompletion ()) - registerCompletionModel (KateGlobal::self()->wordCompletionModel()); - - m_cut->setEnabled(m_doc->isReadWrite() && (selection() || m_config->smartCopyCut())); - m_copy->setEnabled(selection() || m_config->smartCopyCut()); - - // now redraw... - m_viewInternal->cache()->clear(); - tagAll (); - updateView (true); - - emit configChanged(); -} - -void KateView::updateDocumentConfig() -{ - if (m_startingUp) - return; - - m_updatingDocumentConfig = true; - - m_setEndOfLine->setCurrentItem (m_doc->config()->eol()); - - m_addBom->setChecked(m_doc->config()->bom()); - - m_updatingDocumentConfig = false; - - // maybe block selection or wrap-cursor mode changed - ensureCursorColumnValid(); - - // first change this - m_renderer->setTabWidth (m_doc->config()->tabWidth()); - m_renderer->setIndentWidth (m_doc->config()->indentationWidth()); - - // now redraw... - m_viewInternal->cache()->clear(); - tagAll (); - updateView (true); -} - -void KateView::updateRendererConfig() -{ - if (m_startingUp) - return; - - m_toggleWWMarker->setChecked( m_renderer->config()->wordWrapMarker() ); - - m_viewInternal->updateBracketMarkAttributes(); - m_viewInternal->updateBracketMarks(); - - // now redraw... - m_viewInternal->cache()->clear(); - tagAll (); - m_viewInternal->updateView (true); - - // update the left border right, for example linenumbers - m_viewInternal->m_leftBorder->updateFont(); - m_viewInternal->m_leftBorder->repaint (); - -// @@ showIndentLines is not cached anymore. -// m_renderer->setShowIndentLines (m_renderer->config()->showIndentationLines()); -} - -void KateView::updateFoldingConfig () -{ - // folding bar - bool doit = config()->foldingBar() && m_doc->highlight() && m_doc->highlight()->allowsFolding(); - m_viewInternal->m_leftBorder->setFoldingMarkersOn(doit); - m_toggleFoldingMarkers->setChecked( doit ); - m_toggleFoldingMarkers->setEnabled( m_doc->highlight() && m_doc->highlight()->allowsFolding() ); - - QStringList l; - - l << "folding_toplevel" << "folding_expandtoplevel" - << "folding_collapselocal" << "folding_expandlocal"; - - QAction *a = 0; - for (int z = 0; z < l.size(); z++) - if ((a = actionCollection()->action( l[z].toAscii().constData() ))) - a->setEnabled (m_doc->highlight() && m_doc->highlight()->allowsFolding()); -} - -void KateView::ensureCursorColumnValid() -{ - KTextEditor::Cursor c = m_viewInternal->getCursor(); - - // make sure the cursor is valid: - // - in block selection mode or if wrap cursor is off, the column is arbitrary - // - otherwise: it's bounded by the line length - if (!blockSelectionMode() && wrapCursor() - && (!c.isValid() || c.column() > m_doc->lineLength(c.line()))) - { - c.setColumn(m_doc->kateTextLine(cursorPosition().line())->length()); - setCursorPosition(c); - } -} - -//BEGIN EDIT STUFF -void KateView::editStart () -{ - m_viewInternal->editStart (); -} - -void KateView::editEnd (int editTagLineStart, int editTagLineEnd, bool tagFrom) -{ - m_viewInternal->editEnd (editTagLineStart, editTagLineEnd, tagFrom); -} - -void KateView::editSetCursor (const KTextEditor::Cursor &cursor) -{ - m_viewInternal->editSetCursor (cursor); -} -//END - -//BEGIN TAG & CLEAR -bool KateView::tagLine (const KTextEditor::Cursor& virtualCursor) -{ - return m_viewInternal->tagLine (virtualCursor); -} - -bool KateView::tagRange(const KTextEditor::Range& range, bool realLines) -{ - return m_viewInternal->tagRange(range, realLines); -} - -bool KateView::tagLines (int start, int end, bool realLines) -{ - return m_viewInternal->tagLines (start, end, realLines); -} - -bool KateView::tagLines (KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors) -{ - return m_viewInternal->tagLines (start, end, realCursors); -} - -void KateView::tagAll () -{ - m_viewInternal->tagAll (); -} - -void KateView::clear () -{ - m_viewInternal->clear (); -} - -void KateView::repaintText (bool paintOnlyDirty) -{ - if (paintOnlyDirty) - m_viewInternal->updateDirty(); - else - m_viewInternal->update(); -} - -void KateView::updateView (bool changed) -{ - //kDebug(13020) << "KateView::updateView"; - - m_viewInternal->updateView (changed); - m_viewInternal->m_leftBorder->update(); -} - -//END - -void KateView::slotHlChanged() -{ - KateHighlighting *hl = m_doc->highlight(); - bool ok ( !hl->getCommentStart(0).isEmpty() || !hl->getCommentSingleLineStart(0).isEmpty() ); - - if (actionCollection()->action("tools_comment")) - actionCollection()->action("tools_comment")->setEnabled( ok ); - - if (actionCollection()->action("tools_uncomment")) - actionCollection()->action("tools_uncomment")->setEnabled( ok ); - - if (actionCollection()->action("tools_toggle_comment")) - actionCollection()->action("tools_toggle_comment")->setEnabled( ok ); - - // show folding bar if "view defaults" says so, otherwise enable/disable only the menu entry - updateFoldingConfig (); -} - -int KateView::virtualCursorColumn() const -{ - int r = m_doc->toVirtualColumn(m_viewInternal->getCursor()); - if ( !( m_doc->config()->wrapCursor() ) && - m_viewInternal->getCursor().column() > m_doc->line( m_viewInternal->getCursor().line() ).length() ) - r += m_viewInternal->getCursor().column() - m_doc->line( m_viewInternal->getCursor().line() ).length(); - - return r; -} - -void KateView::notifyMousePositionChanged(const KTextEditor::Cursor& newPosition) -{ - emit mousePositionChanged(this, newPosition); -} - -//BEGIN KTextEditor::SelectionInterface stuff - -bool KateView::setSelection( const KTextEditor::Range &selection ) -{ - /** - * anything to do? - */ - if (selection == m_selection) - return true; - - /** - * backup old range - */ - KTextEditor::Range oldSelection = m_selection; - - /** - * set new range - */ - m_selection.setRange (selection.isEmpty() ? KTextEditor::Range::invalid() : selection); - - /** - * trigger update of correct area - */ - tagSelection(oldSelection); - repaintText(true); - - /** - * emit holy signal - */ - emit selectionChanged (this); - - /** - * be done - */ - return true; -} - -bool KateView::clearSelection() -{ - return clearSelection (true); -} - -bool KateView::clearSelection(bool redraw, bool finishedChangingSelection) -{ - /** - * no selection, nothing to do... - */ - if( !selection() ) - return false; - - /** - * backup old range - */ - KTextEditor::Range oldSelection = m_selection; - - /** - * invalidate current selection - */ - m_selection.setRange (KTextEditor::Range::invalid()); - - /** - * trigger update of correct area - */ - tagSelection(oldSelection); - if (redraw) - repaintText(true); - - /** - * emit holy signal - */ - if (finishedChangingSelection) - emit selectionChanged (this); - - /** - * be done - */ - return true; -} - -bool KateView::selection() const -{ - if (!wrapCursor()) - return m_selection != KTextEditor::Range::invalid(); - else - return m_selection.toRange().isValid(); -} - -QString KateView::selectionText() const -{ - return m_doc->text(m_selection, blockSelect); -} - -bool KateView::removeSelectedText() -{ - if (!selection()) - return false; - - m_doc->editStart (); - - m_doc->removeText (m_selection, blockSelect); - - // don't redraw the cleared selection - that's done in editEnd(). - clearSelection(false); - - m_doc->editEnd (); - - return true; -} - -bool KateView::selectAll() -{ - setBlockSelectionMode (false); - top(); - shiftBottom(); - return true; -} - -bool KateView::cursorSelected(const KTextEditor::Cursor& cursor) -{ - KTextEditor::Cursor ret = cursor; - if ( (!blockSelect) && (ret.column() < 0) ) - ret.setColumn(0); - - if (blockSelect) - return cursor.line() >= m_selection.start().line() && ret.line() <= m_selection.end().line() - && ret.column() >= m_selection.start().column() && ret.column() <= m_selection.end().column(); - else - return m_selection.toRange().contains(cursor) || m_selection.end() == cursor; -} - -bool KateView::lineSelected (int line) -{ - return !blockSelect && m_selection.toRange().containsLine(line); -} - -bool KateView::lineEndSelected (const KTextEditor::Cursor& lineEndPos) -{ - return (!blockSelect) - && (lineEndPos.line() > m_selection.start().line() || (lineEndPos.line() == m_selection.start().line() && (m_selection.start().column() < lineEndPos.column() || lineEndPos.column() == -1))) - && (lineEndPos.line() < m_selection.end().line() || (lineEndPos.line() == m_selection.end().line() && (lineEndPos.column() <= m_selection.end().column() && lineEndPos.column() != -1))); -} - -bool KateView::lineHasSelected (int line) -{ - return selection() && m_selection.toRange().containsLine(line); -} - -bool KateView::lineIsSelection (int line) -{ - return (line == m_selection.start().line() && line == m_selection.end().line()); -} - -void KateView::tagSelection(const KTextEditor::Range &oldSelection) -{ - if (selection()) { - if (oldSelection.start().line() == -1) { - // We have to tag the whole lot if - // 1) we have a selection, and: - // a) it's new; or - tagLines(m_selection, true); - - } else if (blockSelectionMode() && (oldSelection.start().column() != m_selection.start().column() || oldSelection.end().column() != m_selection.end().column())) { - // b) we're in block selection mode and the columns have changed - tagLines(m_selection, true); - tagLines(oldSelection, true); - - } else { - if (oldSelection.start() != m_selection.start()) { - if (oldSelection.start() < m_selection.start()) - tagLines(oldSelection.start(), m_selection.start(), true); - else - tagLines(m_selection.start(), oldSelection.start(), true); - } - - if (oldSelection.end() != m_selection.end()) { - if (oldSelection.end() < m_selection.end()) - tagLines(oldSelection.end(), m_selection.end(), true); - else - tagLines(m_selection.end(), oldSelection.end(), true); - } - } - - } else { - // No more selection, clean up - tagLines(oldSelection, true); - } -} - -void KateView::selectWord( const KTextEditor::Cursor& cursor ) -{ - int start, end, len; - - Kate::TextLine textLine = m_doc->plainKateTextLine(cursor.line()); - - if (!textLine) - return; - - len = textLine->length(); - start = end = cursor.column(); - while (start > 0 && m_doc->highlight()->isInWord(textLine->at(start - 1), textLine->attribute(start - 1))) start--; - while (end < len && m_doc->highlight()->isInWord(textLine->at(end), textLine->attribute(start - 1))) end++; - if (end <= start) return; - - setSelection (KTextEditor::Range(cursor.line(), start, cursor.line(), end)); -} - -void KateView::selectLine( const KTextEditor::Cursor& cursor ) -{ - int line = cursor.line(); - if ( line+1 >= m_doc->lines() ) - setSelection (KTextEditor::Range(line, 0, line, m_doc->lineLength(line))); - else - setSelection (KTextEditor::Range(line, 0, line+1, 0)); -} - -void KateView::cut() -{ - if (!selection() && !m_config->smartCopyCut()) - return; - - copy(); - if (!selection()) - selectLine(m_viewInternal->m_cursor); - removeSelectedText(); -} - -void KateView::copy() const -{ - QString text = selectionText(); - - if (!selection()) { - if (!m_config->smartCopyCut()) - return; - text = m_doc->line(m_viewInternal->m_cursor.line()) + '\n'; - m_viewInternal->moveEdge(KateViewInternal::left, false); - } - - QApplication::clipboard()->setText(text); -} - -void KateView::applyWordWrap () -{ - if (selection()) - m_doc->wrapText (selectionRange().start().line(), selectionRange().end().line()); - else - m_doc->wrapText (0, m_doc->lastLine()); -} - -//END - -//BEGIN KTextEditor::BlockSelectionInterface stuff - -bool KateView::blockSelectionMode () const -{ - return blockSelect; -} - -bool KateView::setBlockSelectionMode (bool on) -{ - if (on != blockSelect) - { - blockSelect = on; - - KTextEditor::Range oldSelection = m_selection; - - const bool hadSelection = clearSelection(false, false); - - setSelection(oldSelection); - - m_toggleBlockSelection->setChecked( blockSelectionMode() ); - - // when leaving block selection mode, if cursor is at an invalid position or past the end of the - // line, move the cursor to the last column of the current line unless cursor wrapping is off - ensureCursorColumnValid(); - - if (!hadSelection) { - // emit selectionChanged() according to the KTextEditor::View api - // documentation also if there is no selection around. This is needed, - // as e.g. the Kate App status bar uses this signal to update the state - // of the selection mode (block selection, line based selection) - emit selectionChanged(this); - } - } - - return true; -} - -bool KateView::toggleBlockSelectionMode () -{ - m_toggleBlockSelection->setChecked (!blockSelect); - return setBlockSelectionMode (!blockSelect); -} - -bool KateView::wrapCursor () const -{ - return !blockSelectionMode() && (m_doc->config()->wrapCursor()); -} - -//END - - -void KateView::slotTextInserted ( KTextEditor::View *view, const KTextEditor::Cursor &position, const QString &text) -{ - emit textInserted ( view, position, text); -} - -bool KateView::insertTemplateTextImplementation ( const KTextEditor::Cursor& c, - const QString &templateString, - const QMap &initialValues) -{ - return m_doc->insertTemplateTextImplementation(c, templateString, initialValues, 0, this); -} - -bool KateView::insertTemplateTextImplementation ( const KTextEditor::Cursor& c, - const QString &templateString, - const QMap &initialValues, - KTextEditor::TemplateScript* templateScript) -{ -/* if (!scriptToken.isEmpty()) { - KateGlobal::self()->scriptManager()->callTestIt(this,scriptToken); - }*/ - return m_doc->insertTemplateTextImplementation(c, templateString, initialValues, templateScript, this); -} - - -bool KateView::tagLines( KTextEditor::Range range, bool realRange ) -{ - return tagLines(range.start(), range.end(), realRange); -} - -void KateView::deactivateEditActions() -{ - foreach(QAction *action, m_editActions) - action->setEnabled(false); -} - -void KateView::activateEditActions() -{ - foreach(QAction *action, m_editActions) - action->setEnabled(true); -} - -bool KateView::mouseTrackingEnabled( ) const -{ - // FIXME support - return true; -} - -bool KateView::setMouseTrackingEnabled( bool ) -{ - // FIXME support - return true; -} - -bool KateView::isCompletionActive( ) const -{ - return completionWidget()->isCompletionActive(); -} - -KateCompletionWidget* KateView::completionWidget() const -{ - if (!m_completionWidget) - m_completionWidget = new KateCompletionWidget(const_cast(this)); - - return m_completionWidget; -} - -void KateView::startCompletion( const KTextEditor::Range & word, KTextEditor::CodeCompletionModel * model ) -{ - completionWidget()->startCompletion(word, model); -} - -void KateView::abortCompletion( ) -{ - completionWidget()->abortCompletion(); -} - -void KateView::forceCompletion( ) -{ - completionWidget()->execute(); -} - -void KateView::registerCompletionModel(KTextEditor::CodeCompletionModel* model) -{ - completionWidget()->registerCompletionModel(model); -} - -void KateView::unregisterCompletionModel(KTextEditor::CodeCompletionModel* model) -{ - completionWidget()->unregisterCompletionModel(model); -} - -bool KateView::isAutomaticInvocationEnabled() const -{ - return m_config->automaticCompletionInvocation(); -} - -void KateView::setAutomaticInvocationEnabled(bool enabled) -{ - config()->setAutomaticCompletionInvocation(enabled); -} - -void KateView::sendCompletionExecuted(const KTextEditor::Cursor& position, KTextEditor::CodeCompletionModel* model, const QModelIndex& index) -{ - emit completionExecuted(this, position, model, index); -} - -void KateView::sendCompletionAborted() -{ - emit completionAborted(this); -} - -void KateView::paste( ) -{ - m_doc->paste( this ); - emit selectionChanged (this); - m_viewInternal->repaint(); -} - -bool KateView::setCursorPosition( KTextEditor::Cursor position ) -{ - return setCursorPositionInternal( position, 1, true ); -} - -KTextEditor::Cursor KateView::cursorPosition( ) const -{ - return m_viewInternal->getCursor(); -} - -KTextEditor::Cursor KateView::cursorPositionVirtual( ) const -{ - return KTextEditor::Cursor (m_viewInternal->getCursor().line(), virtualCursorColumn()); -} - -QPoint KateView::cursorToCoordinate( const KTextEditor::Cursor & cursor ) const -{ - return m_viewInternal->cursorToCoordinate(cursor); -} - -KTextEditor::Cursor KateView::coordinatesToCursor(const QPoint& coords) const -{ - return m_viewInternal->coordinatesToCursor(coords); -} - -QPoint KateView::cursorPositionCoordinates( ) const -{ - return m_viewInternal->cursorCoordinates(); -} - -bool KateView::setCursorPositionVisual( const KTextEditor::Cursor & position ) -{ - return setCursorPositionInternal( position, m_doc->config()->tabWidth(), true ); -} - -QString KateView::currentTextLine( ) -{ - return m_doc->line( cursorPosition().line() ); -} - -void KateView::indent( ) -{ - KTextEditor::Cursor c(cursorPosition().line(), 0); - KTextEditor::Range r = selection() ? selectionRange() : KTextEditor::Range(c, c); - m_doc->indent( r, 1 ); -} - -void KateView::unIndent( ) -{ - KTextEditor::Cursor c(cursorPosition().line(), 0); - KTextEditor::Range r = selection() ? selectionRange() : KTextEditor::Range(c, c); - m_doc->indent( r, -1 ); -} - -void KateView::cleanIndent( ) -{ - KTextEditor::Cursor c(cursorPosition().line(), 0); - KTextEditor::Range r = selection() ? selectionRange() : KTextEditor::Range(c, c); - m_doc->indent( r, 0 ); -} - -void KateView::align( ) -{ - // no selection: align current line; selection: use selection range - const int line = cursorPosition().line(); - KTextEditor::Range alignRange(KTextEditor::Cursor (line,0), KTextEditor::Cursor (line,0)); - if (selection()) { - alignRange = selectionRange(); - } - - m_doc->align( this, alignRange ); -} - -void KateView::comment( ) -{ - m_selection.setInsertBehaviors(Kate::TextRange::ExpandLeft | Kate::TextRange::ExpandRight); - m_doc->comment( this, cursorPosition().line(), cursorPosition().column(), 1 ); - m_selection.setInsertBehaviors(Kate::TextRange::ExpandRight); -} - -void KateView::uncomment( ) -{ - m_doc->comment( this, cursorPosition().line(), cursorPosition().column(),-1 ); -} - -void KateView::toggleComment( ) -{ - m_selection.setInsertBehaviors(Kate::TextRange::ExpandLeft | Kate::TextRange::ExpandRight); - m_doc->comment( this, cursorPosition().line(), cursorPosition().column(), 0 ); - m_selection.setInsertBehaviors(Kate::TextRange::ExpandRight); -} - -void KateView::uppercase( ) -{ - m_doc->transform( this, m_viewInternal->m_cursor, KateDocument::Uppercase ); -} - -void KateView::killLine( ) -{ - m_doc->removeLine( cursorPosition().line() ); -} - -void KateView::lowercase( ) -{ - m_doc->transform( this, m_viewInternal->m_cursor, KateDocument::Lowercase ); -} - -void KateView::capitalize( ) -{ - m_doc->editStart(); - m_doc->transform( this, m_viewInternal->m_cursor, KateDocument::Lowercase ); - m_doc->transform( this, m_viewInternal->m_cursor, KateDocument::Capitalize ); - m_doc->editEnd(); -} - -void KateView::keyReturn( ) -{ - m_viewInternal->doReturn(); -} - -void KateView::smartNewline( ) -{ - m_viewInternal->doSmartNewline(); -} - -void KateView::backspace( ) -{ - m_viewInternal->doBackspace(); -} - -void KateView::insertTab( ) -{ - m_viewInternal->doTabulator(); -} - -void KateView::deleteWordLeft( ) -{ - m_viewInternal->doDeleteWordLeft(); -} - -void KateView::keyDelete( ) -{ - m_viewInternal->doDelete(); -} - -void KateView::deleteWordRight( ) -{ - m_viewInternal->doDeleteWordRight(); -} - -void KateView::transpose( ) -{ - m_viewInternal->doTranspose(); -} - -void KateView::cursorLeft( ) -{ - m_viewInternal->cursorLeft(); -} - -void KateView::shiftCursorLeft( ) -{ - m_viewInternal->cursorLeft(true); -} - -void KateView::cursorRight( ) -{ - m_viewInternal->cursorRight(); -} - -void KateView::shiftCursorRight( ) -{ - m_viewInternal->cursorRight(true); -} - -void KateView::wordLeft( ) -{ - m_viewInternal->wordLeft(); -} - -void KateView::shiftWordLeft( ) -{ - m_viewInternal->wordLeft(true); -} - -void KateView::wordRight( ) -{ - m_viewInternal->wordRight(); -} - -void KateView::shiftWordRight( ) -{ - m_viewInternal->wordRight(true); -} - -void KateView::home( ) -{ - m_viewInternal->home(); -} - -void KateView::shiftHome( ) -{ - m_viewInternal->home(true); -} - -void KateView::end( ) -{ - m_viewInternal->end(); -} - -void KateView::shiftEnd( ) -{ - m_viewInternal->end(true); -} - -void KateView::up( ) -{ - m_viewInternal->cursorUp(); -} - -void KateView::shiftUp( ) -{ - m_viewInternal->cursorUp(true); -} - -void KateView::down( ) -{ - m_viewInternal->cursorDown(); -} - -void KateView::shiftDown( ) -{ - m_viewInternal->cursorDown(true); -} - -void KateView::scrollUp( ) -{ - m_viewInternal->scrollUp(); -} - -void KateView::scrollDown( ) -{ - m_viewInternal->scrollDown(); -} - -void KateView::topOfView( ) -{ - m_viewInternal->topOfView(); -} - -void KateView::shiftTopOfView( ) -{ - m_viewInternal->topOfView(true); -} - -void KateView::bottomOfView( ) -{ - m_viewInternal->bottomOfView(); -} - -void KateView::shiftBottomOfView( ) -{ - m_viewInternal->bottomOfView(true); -} - -void KateView::pageUp( ) -{ - m_viewInternal->pageUp(); -} - -void KateView::shiftPageUp( ) -{ - m_viewInternal->pageUp(true); -} - -void KateView::pageDown( ) -{ - m_viewInternal->pageDown(); -} - -void KateView::shiftPageDown( ) -{ - m_viewInternal->pageDown(true); -} - -void KateView::top( ) -{ - m_viewInternal->top_home(); -} - -void KateView::shiftTop( ) -{ - m_viewInternal->top_home(true); -} - -void KateView::bottom( ) -{ - m_viewInternal->bottom_end(); -} - -void KateView::shiftBottom( ) -{ - m_viewInternal->bottom_end(true); -} - -void KateView::toMatchingBracket( ) -{ - m_viewInternal->cursorToMatchingBracket(); -} - -void KateView::shiftToMatchingBracket( ) -{ - m_viewInternal->cursorToMatchingBracket(true); -} - -const KTextEditor::Range & KateView::selectionRange( ) const -{ - // update the cache - m_holdSelectionRangeForAPI = m_selection; - - // return cached value, has right type! - return m_holdSelectionRangeForAPI; -} - -KTextEditor::Document * KateView::document( ) const -{ - return m_doc; -} - -void KateView::setContextMenu( QMenu * menu ) -{ - if (m_contextMenu) { - disconnect(m_contextMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowContextMenu())); - disconnect(m_contextMenu, SIGNAL(aboutToHide()), this, SLOT(aboutToHideContextMenu())); - } - m_contextMenu = menu; - m_userContextMenuSet=true; - - if (m_contextMenu) { - connect(m_contextMenu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowContextMenu())); - connect(m_contextMenu, SIGNAL(aboutToHide()), this, SLOT(aboutToHideContextMenu())); - } -} - -QMenu *KateView::contextMenu( ) const -{ - if (m_userContextMenuSet) - return m_contextMenu; - else - { - KXMLGUIClient* client = const_cast(this); - while (client->parentClient()) - client = client->parentClient(); - - //kDebug() << "looking up all menu containers"; - if (client->factory()){ - QList conts = client->factory()->containers("menu"); - foreach (QWidget *w, conts) - { - if (w->objectName() == "ktexteditor_popup") - {//perhaps optimize this block - QMenu* menu=(QMenu*)w; - disconnect(menu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowContextMenu())); - disconnect(menu, SIGNAL(aboutToHide()), this, SLOT(aboutToHideContextMenu())); - connect(menu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowContextMenu())); - connect(menu, SIGNAL(aboutToHide()), this, SLOT(aboutToHideContextMenu())); - return menu; - } - } - } - } - return 0; -} - -QMenu * KateView::defaultContextMenu(QMenu* menu) const -{ - if (!menu) - menu = new KMenu(const_cast(this)); - - menu->addAction(m_editUndo); - menu->addAction(m_editRedo); - menu->addSeparator(); - menu->addAction(m_cut); - menu->addAction(m_copy); - menu->addAction(m_paste); - menu->addSeparator(); - menu->addAction(m_selectAll); - menu->addAction(m_deSelect); - if (QAction *spellingSuggestions = actionCollection()->action("spelling_suggestions")) { - menu->addSeparator(); - menu->addAction(spellingSuggestions); - } - if (QAction* bookmark = actionCollection()->action("bookmarks")) { - menu->addSeparator(); - menu->addAction(bookmark); - } - return menu; -} - -void KateView::aboutToShowContextMenu( ) -{ - QMenu* menu = qobject_cast(sender()); - - if (menu) { - emit contextMenuAboutToShow(this, menu); - } -} - -void KateView::aboutToHideContextMenu( ) -{ - m_spellingMenu->setUseMouseForMisspelledRange(false); -} - -// BEGIN ConfigInterface stff -QStringList KateView::configKeys() const -{ - return QStringList() << "icon-bar" << "line-numbers" << "dynamic-word-wrap" - << "background-color" << "selection-color"; -} - -QVariant KateView::configValue(const QString &key) -{ - if (key == "icon-bar") - return config()->iconBar(); - else if (key == "line-numbers") - return config()->lineNumbers(); - else if (key == "dynamic-word-wrap") - return config()->dynWordWrap(); - else if (key == "background-color") - return renderer()->config()->backgroundColor(); - else if (key == "selection-color") - return renderer()->config()->selectionColor(); - else if (key == "default-mark-type") - return config()->defaultMarkType(); - else if (key == "allow-mark-menu") - return config()->allowMarkMenu(); - - // return invalid variant - return QVariant(); -} - -void KateView::setConfigValue(const QString &key, const QVariant &value) -{ - if ( value.canConvert(QVariant::Color) ) { - if (key == "background-color") - renderer()->config()->setBackgroundColor(value.value()); - else if (key == "selection-color") - renderer()->config()->setSelectionColor(value.value()); - } else if ( value.type() == QVariant::Bool ) { - // Note explicit type check above. If we used canConvert, then - // values of type UInt will be trapped here. - if (key == "icon-bar") - config()->setIconBar(value.toBool()); - else if (key == "line-numbers") - config()->setLineNumbers(value.toBool()); - else if (key == "dynamic-word-wrap") - config()->setDynWordWrap(value.toBool()); - else if (key == "allow-mark-menu") - config()->setAllowMarkMenu(value.toBool()); - } else if ( value.canConvert(QVariant::UInt) ) { - if (key == "default-mark-type") - config()->setDefaultMarkType(value.toUInt()); - } -} - -// END ConfigInterface - -void KateView::userInvokedCompletion() -{ - completionWidget()->userInvokedCompletion(); -} - -KateViewBar *KateView::topViewBar() const -{ - return m_topViewBar; -} - -KateViewBar *KateView::bottomViewBar() const -{ - return m_bottomViewBar; -} - -KateCommandLineBar *KateView::cmdLineBar () -{ - if (!m_cmdLine) { - m_cmdLine = new KateCommandLineBar (this, bottomViewBar()); - bottomViewBar()->addBarWidget(m_cmdLine); - } - - return m_cmdLine; -} - -KateScriptConsole *KateView::consoleBar () -{ - if (!m_console) { - m_console = new KateScriptConsole (this, bottomViewBar()); - bottomViewBar()->addBarWidget(m_console); - } - - return m_console; -} - -KateSearchBar *KateView::searchBar (bool initHintAsPower) -{ - if (!m_searchBar) { - m_searchBar = new KateSearchBar(initHintAsPower, this, KateViewConfig::global()); - bottomViewBar()->addBarWidget(m_searchBar); - } - return m_searchBar; -} - -KateViModeBar *KateView::viModeBar() -{ - if (!m_viModeBar) { - m_viModeBar = new KateViModeBar(this); - } - - return m_viModeBar; -} - -KateGotoBar *KateView::gotoBar () -{ - if (!m_gotoBar) { - m_gotoBar = new KateGotoBar (this); - bottomViewBar()->addBarWidget(m_gotoBar); - } - - return m_gotoBar; -} - -KateDictionaryBar *KateView::dictionaryBar () -{ - if(!m_dictionaryBar) { - m_dictionaryBar = new KateDictionaryBar(this); - bottomViewBar()->addBarWidget(m_dictionaryBar); - } - - return m_dictionaryBar; -} - -void KateView::setAnnotationModel( KTextEditor::AnnotationModel* model ) -{ - KTextEditor::AnnotationModel* oldmodel = m_annotationModel; - m_annotationModel = model; - m_viewInternal->m_leftBorder->annotationModelChanged(oldmodel, m_annotationModel); -} - -KTextEditor::AnnotationModel* KateView::annotationModel() const -{ - return m_annotationModel; -} - -void KateView::setAnnotationBorderVisible( bool visible ) -{ - m_viewInternal->m_leftBorder->setAnnotationBorderOn( visible ); -} - -bool KateView::isAnnotationBorderVisible() const -{ - return m_viewInternal->m_leftBorder->annotationBorderOn(); -} - -KTextEditor::Range KateView::visibleRange() -{ - //ensure that the view is up-to-date, otherwise 'endPos()' might fail! - m_viewInternal->updateView(); - return KTextEditor::Range(m_viewInternal->toRealCursor(m_viewInternal->startPos()), - m_viewInternal->toRealCursor(m_viewInternal->endPos())); -} - -void KateView::toggleOnTheFlySpellCheck(bool b) -{ - m_doc->onTheFlySpellCheckingEnabled(b); -} - -void KateView::reflectOnTheFlySpellCheckStatus(bool enabled) -{ - m_spellingMenu->setVisible(enabled); - m_toggleOnTheFlySpellCheck->setChecked(enabled); -} - -KateSpellingMenu* KateView::spellingMenu() -{ - return m_spellingMenu; -} - -void KateView::notifyAboutRangeChange (int startLine, int endLine, bool rangeWithAttribute) -{ -#ifdef VIEW_RANGE_DEBUG - // output args - kDebug() << "trigger attribute changed from" << startLine << "to" << endLine << "rangeWithAttribute" << rangeWithAttribute; -#endif - - // first call: - if (!m_delayedUpdateTriggered) { - m_delayedUpdateTriggered = true; - m_lineToUpdateMin = -1; - m_lineToUpdateMax = -1; - - // only set initial line range, if range with attribute! - if (rangeWithAttribute) { - m_lineToUpdateMin = startLine; - m_lineToUpdateMax = endLine; - } - - // emit queued signal and be done - emit delayedUpdateOfView (); - return; - } - - // ignore lines if no attribute - if (!rangeWithAttribute) - return; - - // update line range - if (startLine != -1 && (m_lineToUpdateMin == -1 || startLine < m_lineToUpdateMin)) - m_lineToUpdateMin = startLine; - - if (endLine != -1 && endLine > m_lineToUpdateMax) - m_lineToUpdateMax = endLine; -} - -void KateView::slotDelayedUpdateOfView () -{ - if (!m_delayedUpdateTriggered) - return; - -#ifdef VIEW_RANGE_DEBUG - // output args - kDebug() << "delayed attribute changed from" << m_lineToUpdateMin << "to" << m_lineToUpdateMax; -#endif - - // update ranges in - updateRangesIn (KTextEditor::Attribute::ActivateMouseIn); - updateRangesIn (KTextEditor::Attribute::ActivateCaretIn); - - // update view, if valid line range, else only feedback update wanted anyway - if (m_lineToUpdateMin != -1 && m_lineToUpdateMax != -1) { - tagLines (m_lineToUpdateMin, m_lineToUpdateMax, true); - updateView (true); - } - - // reset flags - m_delayedUpdateTriggered = false; - m_lineToUpdateMin = -1; - m_lineToUpdateMax = -1; -} - -void KateView::updateRangesIn (KTextEditor::Attribute::ActivationType activationType) -{ - // new ranges with cursor in, default none - QSet newRangesIn; - - // on which range set we work? - QSet &oldSet = (activationType == KTextEditor::Attribute::ActivateMouseIn) ? m_rangesMouseIn : m_rangesCaretIn; - - // which cursor position to honor? - KTextEditor::Cursor currentCursor = (activationType == KTextEditor::Attribute::ActivateMouseIn) ? m_viewInternal->getMouse() : m_viewInternal->getCursor (); - - // first: validate the remembered ranges - QSet validRanges; - foreach (Kate::TextRange *range, oldSet) - if (m_doc->buffer().rangePointerValid(range)) - validRanges.insert (range); - - // cursor valid? else no new ranges can be found - if (currentCursor.isValid () && currentCursor.line() < m_doc->buffer().lines()) { - // now: get current ranges for the line of cursor with an attribute - QList rangesForCurrentCursor = m_doc->buffer().rangesForLine (currentCursor.line(), this, false); - - // match which ranges really fit the given cursor - foreach (Kate::TextRange *range, rangesForCurrentCursor) { - // range has no dynamic attribute of right type and no feedback object - if ((!range->attribute() || !range->attribute()->dynamicAttribute (activationType)) && !range->feedback()) - continue; - - // range doesn't contain cursor, not interesting - if ((range->start().insertBehavior() == KTextEditor::MovingCursor::StayOnInsert) - ? (currentCursor < range->start().toCursor ()) : (currentCursor <= range->start().toCursor ())) - continue; - - if ((range->end().insertBehavior() == KTextEditor::MovingCursor::StayOnInsert) - ? (range->end().toCursor () <= currentCursor) : (range->end().toCursor () < currentCursor)) - continue; - - // range contains cursor, was it already in old set? - if (validRanges.contains (range)) { - // insert in new, remove from old, be done with it - newRangesIn.insert (range); - validRanges.remove (range); - continue; - } - - // oh, new range, trigger update and insert into new set - newRangesIn.insert (range); - - if (range->attribute() && range->attribute()->dynamicAttribute (activationType)) - notifyAboutRangeChange (range->start().line(), range->end().line(), true); - - // feedback - if (range->feedback ()) { - if (activationType == KTextEditor::Attribute::ActivateMouseIn) - range->feedback ()->mouseEnteredRange (range, this); - else - range->feedback ()->caretEnteredRange (range, this); - } - -#ifdef VIEW_RANGE_DEBUG - // found new range for activation - kDebug() << "activated new range" << range << "by" << activationType; -#endif - } - } - - // now: notify for left ranges! - foreach (Kate::TextRange *range, validRanges) { - // range valid + right dynamic attribute, trigger update - if (range->toRange().isValid() && range->attribute() && range->attribute()->dynamicAttribute (activationType)) - notifyAboutRangeChange (range->start().line(), range->end().line(), true); - - // feedback - if (range->feedback ()) { - if (activationType == KTextEditor::Attribute::ActivateMouseIn) - range->feedback ()->mouseExitedRange (range, this); - else - range->feedback ()->caretExitedRange (range, this); - } - } - - // set new ranges - oldSet = newRangesIn; -} - -void KateView::showRecoverBar() -{ - hideBrokenSwapFileBar(); - - topViewBar()->showBarWidget(recoverBar()); -} - -KateRecoverBar* KateView::recoverBar() -{ - if (!m_recoverBar) { - m_recoverBar = new KateRecoverBar(this); - topViewBar()->addBarWidget(m_recoverBar); - } - return m_recoverBar; -} - -void KateView::hideRecoverBar() -{ - if (m_recoverBar) - { - topViewBar()->removeBarWidget(m_recoverBar); - delete m_recoverBar; - m_recoverBar = 0; - } -} - -void KateView::showBrokenSwapFileBar() -{ - hideRecoverBar(); - - topViewBar()->showBarWidget(brokenSwapFileBar()); -} - -KateBrokenSwapFileBar* KateView::brokenSwapFileBar() -{ - if (!m_brokenSwapFileBar) { - m_brokenSwapFileBar = new KateBrokenSwapFileBar(this); - topViewBar()->addBarWidget(m_brokenSwapFileBar); - } - return m_brokenSwapFileBar; -} - -void KateView::hideBrokenSwapFileBar() -{ - if (m_brokenSwapFileBar) - { - topViewBar()->removeBarWidget(m_brokenSwapFileBar); - delete m_brokenSwapFileBar; - m_brokenSwapFileBar = 0; - } -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/view/kateview.h b/part/view/kateview.h deleted file mode 100644 index 7519cad..0000000 --- a/part/view/kateview.h +++ /dev/null @@ -1,785 +0,0 @@ - /* This file is part of the KDE libraries - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001 Christoph Cullmann - Copyright (C) 2001-2010 Joseph Wenninger - Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef kate_view_h -#define kate_view_h - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -#include "kateviinputmodemanager.h" -#include "katetextrange.h" - -namespace KTextEditor -{ - class AnnotationModel; -} - -class KateDocument; -class KateBookmarks; -class KateCommandLineBar; -class KateViewConfig; -class KateRenderer; -class KateSpellCheckDialog; -class KateCompletionWidget; -class KateViewInternal; -class KateSearchBar; -class KateViModeBar; -class KateViewBar; -class KateGotoBar; -class KateDictionaryBar; -class KateSpellingMenu; -class KateRecoverBar; -class KateBrokenSwapFileBar; -class KateScriptConsole; - -class KToggleAction; -class KAction; -class KRecentFilesAction; -class KSelectAction; - -class QVBoxLayout; - -// -// Kate KTextEditor::View class ;) -// -class KATEPART_TESTS_EXPORT KateView : public KTextEditor::View, - public KTextEditor::TextHintInterface, - public KTextEditor::SessionConfigInterface, - public KTextEditor::TemplateInterface2, - public KTextEditor::CodeCompletionInterface, - public KTextEditor::ConfigInterface, - public KTextEditor::AnnotationViewInterface, - public KTextEditor::CoordinatesToCursorInterface -{ - Q_OBJECT - Q_INTERFACES(KTextEditor::TextHintInterface) - Q_INTERFACES(KTextEditor::SessionConfigInterface) - Q_INTERFACES(KTextEditor::TemplateInterface) - Q_INTERFACES(KTextEditor::TemplateInterface2) - Q_INTERFACES(KTextEditor::ConfigInterface) - Q_INTERFACES(KTextEditor::CodeCompletionInterface) - Q_INTERFACES(KTextEditor::AnnotationViewInterface) - Q_INTERFACES(KTextEditor::CoordinatesToCursorInterface) - - friend class KateViewInternal; - friend class KateIconBorder; - friend class KateViModeBase; - - public: - KateView( KateDocument* doc, QWidget* parent ); - ~KateView (); - - KTextEditor::Document *document () const; - - QString viewMode () const; - - // - // KTextEditor::ClipboardInterface - // - public Q_SLOTS: - // TODO: Factor out of m_viewInternal - void paste(); - void cut(); - void copy() const; - - private Q_SLOTS: - /** - * internal use, apply word wrap - */ - void applyWordWrap (); - - // - // KTextEditor::PopupMenuInterface - // - public: - void setContextMenu( QMenu* menu ); - QMenu* contextMenu() const; - QMenu* defaultContextMenu(QMenu* menu = 0L) const; - - private Q_SLOTS: - void aboutToShowContextMenu(); - void aboutToHideContextMenu(); - - private: - QPointer m_contextMenu; - - // - // KTextEditor::ViewCursorInterface - // - public: - bool setCursorPosition (KTextEditor::Cursor position); - - KTextEditor::Cursor cursorPosition () const; - - KTextEditor::Cursor cursorPositionVirtual () const; - - QPoint cursorToCoordinate(const KTextEditor::Cursor& cursor) const; - - KTextEditor::Cursor coordinatesToCursor(const QPoint& coord) const; - - QPoint cursorPositionCoordinates() const; - - bool setCursorPositionVisual( const KTextEditor::Cursor& position ); - - /** - * Return the virtual cursor column, each tab is expanded into the - * document's tabWidth characters. If word wrap is off, the cursor may be - * behind the line's length. - */ - int virtualCursorColumn() const; - - virtual bool mouseTrackingEnabled() const; - virtual bool setMouseTrackingEnabled(bool enable); - - private: - void notifyMousePositionChanged(const KTextEditor::Cursor& newPosition); - - // Internal - public: - bool setCursorPositionInternal( const KTextEditor::Cursor& position, uint tabwidth = 1, bool calledExternally = false ); - - // - // KTextEditor::ConfigInterface - // - public: - QStringList configKeys() const; - QVariant configValue(const QString &key); - void setConfigValue(const QString &key, const QVariant &value); - - Q_SIGNALS: - void configChanged(); - - // - // KTextEditor::CodeCompletionInterface2 - // - public: - virtual bool isCompletionActive() const; - virtual void startCompletion(const KTextEditor::Range& word, KTextEditor::CodeCompletionModel* model); - virtual void abortCompletion(); - virtual void forceCompletion(); - virtual void registerCompletionModel(KTextEditor::CodeCompletionModel* model); - virtual void unregisterCompletionModel(KTextEditor::CodeCompletionModel* model); - virtual bool isAutomaticInvocationEnabled() const; - virtual void setAutomaticInvocationEnabled(bool enabled = true); - - Q_SIGNALS: - void completionExecuted(KTextEditor::View* view, const KTextEditor::Cursor& position, KTextEditor::CodeCompletionModel* model, const QModelIndex&); - void completionAborted(KTextEditor::View* view); - - public Q_SLOTS: - void userInvokedCompletion(); - - public: - KateCompletionWidget* completionWidget() const; - mutable KateCompletionWidget* m_completionWidget; - void sendCompletionExecuted(const KTextEditor::Cursor& position, KTextEditor::CodeCompletionModel* model, const QModelIndex& index); - void sendCompletionAborted(); - - // - // KTextEditor::TextHintInterface - // - public: - void enableTextHints(int timeout); - void disableTextHints(); - - Q_SIGNALS: - void needTextHint(const KTextEditor::Cursor& position, QString &text); - - public: - bool dynWordWrap() const { return m_hasWrap; } - - // - // KTextEditor::SelectionInterface stuff - // - public Q_SLOTS: - virtual bool setSelection ( const KTextEditor::Range &selection ); - - // unhide method... - bool setSelection (const KTextEditor::Cursor &c, int i, bool b) - { return KTextEditor::View::setSelection (c, i, b); } - - virtual bool removeSelection () { return clearSelection(); } - - virtual bool removeSelectionText () { return removeSelectedText(); } - - virtual bool setBlockSelection (bool on) { return setBlockSelectionMode (on); } - - bool clearSelection (); - bool clearSelection (bool redraw, bool finishedChangingSelection = true); - - bool removeSelectedText (); - - bool selectAll(); - - public: - virtual bool selection() const; - virtual QString selectionText() const; - virtual bool blockSelection() const { return blockSelectionMode(); } - virtual const KTextEditor::Range &selectionRange() const; - - static void blockFix(KTextEditor::Range& range); - - private: - mutable KTextEditor::Range m_holdSelectionRangeForAPI; - - // - // Arbitrary Syntax HL + Action extensions - // - public: - // Action association extension - void deactivateEditActions(); - void activateEditActions(); - - // - // internal helper stuff, for katerenderer and so on - // - public: - // should cursor be wrapped ? take config + blockselection state in account - bool wrapCursor () const; - - // some internal functions to get selection state of a line/col - bool cursorSelected(const KTextEditor::Cursor& cursor); - bool lineSelected (int line); - bool lineEndSelected (const KTextEditor::Cursor& lineEndPos); - bool lineHasSelected (int line); - bool lineIsSelection (int line); - - void ensureCursorColumnValid(); - - void tagSelection (const KTextEditor::Range &oldSelection); - - void selectWord( const KTextEditor::Cursor& cursor ); - void selectLine( const KTextEditor::Cursor& cursor ); - - // - // KTextEditor::BlockSelectionInterface stuff - // - public Q_SLOTS: - bool setBlockSelectionMode (bool on); - bool toggleBlockSelectionMode (); - - public: - bool blockSelectionMode() const; - - - //BEGIN EDIT STUFF - public: - void editStart (); - void editEnd (int editTagLineStart, int editTagLineEnd, bool tagFrom); - - void editSetCursor (const KTextEditor::Cursor &cursor); - //END - - //BEGIN TAG & CLEAR - public: - bool tagLine (const KTextEditor::Cursor& virtualCursor); - - bool tagRange (const KTextEditor::Range& range, bool realLines = false); - bool tagLines (int start, int end, bool realLines = false ); - bool tagLines (KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors = false); - bool tagLines (KTextEditor::Range range, bool realRange = false); - - void tagAll (); - - void clear (); - - void repaintText (bool paintOnlyDirty = false); - - void updateView (bool changed = false); - //END - - // - // KTextEditor::AnnotationView - // - public: - void setAnnotationModel( KTextEditor::AnnotationModel* model ); - KTextEditor::AnnotationModel* annotationModel() const; - void setAnnotationBorderVisible( bool visible); - bool isAnnotationBorderVisible() const; - - Q_SIGNALS: - void annotationContextMenuAboutToShow( KTextEditor::View* view, QMenu* menu, int line ); - void annotationActivated( KTextEditor::View* view, int line ); - void annotationBorderVisibilityChanged( View* view, bool visible ); - - void navigateLeft(); - void navigateRight(); - void navigateUp(); - void navigateDown(); - void navigateAccept(); - void navigateBack(); - - private: - KTextEditor::AnnotationModel* m_annotationModel; - - // - // KTextEditor::View - // - public: - void emitNavigateLeft() { - emit navigateLeft(); - } - void emitNavigateRight() { - emit navigateRight(); - } - void emitNavigateUp() { - emit navigateUp(); - } - void emitNavigateDown() { - emit navigateDown(); - } - void emitNavigateAccept() { - emit navigateAccept(); - } - void emitNavigateBack() { - emit navigateBack(); - } - /** - Return values for "save" related commands. - */ - bool isOverwriteMode() const; - enum KTextEditor::View::EditMode viewEditMode() const {return isOverwriteMode() ? KTextEditor::View::EditOverwrite : KTextEditor::View::EditInsert;} - QString currentTextLine(); - - public Q_SLOTS: - void indent(); - void unIndent(); - void cleanIndent(); - void align(); - void comment(); - void uncomment(); - void toggleComment(); - void killLine(); - - /** - Uppercases selected text, or an alphabetic character next to the cursor. - */ - void uppercase(); - /** - Lowercases selected text, or an alphabetic character next to the cursor. - */ - void lowercase(); - /** - Capitalizes the selection (makes each word start with an uppercase) or - the word under the cursor. - */ - void capitalize(); - /** - Joins lines touched by the selection - */ - void joinLines(); - - // Note - the following functions simply forward to KateViewInternal - void keyReturn(); - void smartNewline(); - void backspace(); - void deleteWordLeft(); - void keyDelete(); - void deleteWordRight(); - void transpose(); - void cursorLeft(); - void shiftCursorLeft(); - void cursorRight(); - void shiftCursorRight(); - void wordLeft(); - void shiftWordLeft(); - void wordRight(); - void shiftWordRight(); - void home(); - void shiftHome(); - void end(); - void shiftEnd(); - void up(); - void shiftUp(); - void down(); - void shiftDown(); - void scrollUp(); - void scrollDown(); - void topOfView(); - void shiftTopOfView(); - void bottomOfView(); - void shiftBottomOfView(); - void pageUp(); - void shiftPageUp(); - void pageDown(); - void shiftPageDown(); - void top(); - void shiftTop(); - void bottom(); - void shiftBottom(); - void toMatchingBracket(); - void shiftToMatchingBracket(); - void insertTab(); - - void gotoLine(); - - // config file / session management functions - public: - void readSessionConfig(const KConfigGroup&); - void writeSessionConfig(KConfigGroup&); - - public Q_SLOTS: - void setEol( int eol ); - void setAddBom( bool enabled); - void find(); - void findSelectedForwards(); - void findSelectedBackwards(); - void replace(); - void findNext(); - void findPrevious(); - - void setFoldingMarkersOn( bool enable ); // Not in KTextEditor::View, but should be - void setIconBorder( bool enable ); - void setLineNumbersOn( bool enable ); - void setScrollBarMarks( bool enable ); - void toggleFoldingMarkers(); - void toggleIconBorder(); - void toggleLineNumbersOn(); - void toggleScrollBarMarks(); - void toggleDynWordWrap (); - void toggleViInputMode (); - void showViModeBar (); - void hideViModeBar (); - void setDynWrapIndicators(int mode); - - public: - int getEol() const; - - public: - KateRenderer *renderer (); - - bool iconBorder(); - bool lineNumbersOn(); - bool scrollBarMarks(); - int dynWrapIndicators(); - bool foldingMarkersOn(); - - private Q_SLOTS: - /** - * used to update actions after selection changed - */ - void slotSelectionChanged (); - - public: - /** - * accessor to katedocument pointer - * @return pointer to document - */ - KateDocument* doc() { return m_doc; } - const KateDocument* doc() const { return m_doc; } - - public Q_SLOTS: - void slotUpdateUndo(); - void toggleInsert(); - void reloadFile(); - void toggleWWMarker(); - void toggleWriteLock(); - void switchToCmdLine (); - void switchToConsole (); - void slotReadWriteChanged (); - - Q_SIGNALS: - void dropEventPass(QDropEvent*); - - public: - void slotTextInserted ( KTextEditor::View *view, const KTextEditor::Cursor &position, const QString &text); - - protected: - void contextMenuEvent( QContextMenuEvent* ); - - private Q_SLOTS: - void slotGotFocus(); - void slotLostFocus(); - void slotDropEventPass( QDropEvent* ev ); - void slotSaveCanceled( const QString& error ); - void slotExpandToplevel(); - void slotCollapseLocal(); - void slotExpandLocal(); - void slotConfigDialog (); - - private: - void setupConnections(); - void setupActions(); - void setupEditActions(); - void setupCodeFolding(); - - QList m_editActions; - KAction* m_editUndo; - KAction* m_editRedo; - KRecentFilesAction* m_fileRecent; - KToggleAction* m_toggleFoldingMarkers; - KToggleAction* m_toggleIconBar; - KToggleAction* m_toggleLineNumbers; - KToggleAction* m_toggleScrollBarMarks; - KToggleAction* m_toggleDynWrap; - KSelectAction* m_setDynWrapIndicators; - KToggleAction* m_toggleWWMarker; - KAction* m_switchCmdLine; - KAction* m_switchConsole; - KToggleAction* m_viInputModeAction; - - KSelectAction* m_setEndOfLine; - KToggleAction* m_addBom; - - QAction *m_cut; - QAction *m_copy; - QAction *m_paste; - QAction *m_selectAll; - QAction *m_deSelect; - - KToggleAction *m_toggleBlockSelection; - KToggleAction *m_toggleInsert; - KToggleAction *m_toggleWriteLock; - - bool m_hasWrap; - - KateDocument *const m_doc; - KateViewConfig *const m_config; - KateRenderer *const m_renderer; - KateViewInternal *const m_viewInternal; - KateSpellCheckDialog *m_spell; - KateBookmarks *const m_bookmarks; - - QVBoxLayout *m_vBox; - - private Q_SLOTS: - void slotHlChanged(); - - /** - * Configuration - */ - public: - inline KateViewConfig *config () { return m_config; } - - void updateConfig (); - - void updateDocumentConfig(); - - void updateRendererConfig(); - - private Q_SLOTS: - void updateFoldingConfig (); - - private: - bool m_startingUp; - bool m_updatingDocumentConfig; - - // stores the current selection - Kate::TextRange m_selection; - - // do we select normal or blockwise ? - bool blockSelect; - - // - // TemplateInterface + TemplateInterface2 - // - public: - virtual bool insertTemplateTextImplementation ( const KTextEditor::Cursor&, const QString &templateString, const QMap &initialValues); - virtual bool insertTemplateTextImplementation ( const KTextEditor::Cursor&, const QString &templateString, const QMap &initialValues, KTextEditor::TemplateScript* templateScript); - /** - * Accessors to the bars... - */ - public: - KateViewBar *topViewBar() const; - KateViewBar *bottomViewBar() const; - KateCommandLineBar *cmdLineBar (); - KateScriptConsole *consoleBar (); - KateDictionaryBar *dictionaryBar(); - - private: - KateSearchBar *searchBar (bool initHintAsPower = false); - bool hasSearchBar () const { return m_searchBar != 0; } - KateViModeBar *viModeBar(); - KateGotoBar *gotoBar (); - KateRecoverBar *recoverBar(); - KateBrokenSwapFileBar *brokenSwapFileBar(); - - /** - * viewbar + its widgets - * they are created on demand... - */ - private: - // created in constructor of the view - KateViewBar *m_bottomViewBar; - KateViewBar *m_topViewBar; - KateRecoverBar *m_recoverBar; - KateBrokenSwapFileBar *m_brokenSwapFileBar; - // created on demand..., only access them through the above accessors.... - KateCommandLineBar *m_cmdLine; - KateScriptConsole *m_console; - KateSearchBar *m_searchBar; - KateViModeBar *m_viModeBar; - KateGotoBar *m_gotoBar; - KateDictionaryBar *m_dictionaryBar; - - // vi Mode - public: - /** - * @return boolean indicating whether vi mode is active or not - */ - bool viInputMode() const; - - /** - * @return the current vi mode - */ - ViMode getCurrentViMode() const; - - /** - * @return a pointer to the KateViInputModeManager belonging to the view - */ - KateViInputModeManager* getViInputModeManager(); - - /** - * @return boolean indicating whether vi mode will override actions or not - */ - bool viInputModeStealKeys() const; - - /** - * Update vi mode statusbar according to the current mode - */ - void updateViModeBarMode(); - - /** - * Update vi mode statusbar with the (partial) vi command being typed - */ - void updateViModeBarCmd(); - - public: - KTextEditor::Range visibleRange(); - - Q_SIGNALS: - void displayRangeChanged(KateView *view); - - protected: - KToggleAction* m_toggleOnTheFlySpellCheck; - KateSpellingMenu *m_spellingMenu; - - protected Q_SLOTS: - void toggleOnTheFlySpellCheck(bool b); - void showRecoverBar(); - void showBrokenSwapFileBar(); - - public Q_SLOTS: - void changeDictionary(); - void reflectOnTheFlySpellCheckStatus(bool enabled); - void hideRecoverBar(); - void hideBrokenSwapFileBar(); - - public: - KateSpellingMenu* spellingMenu(); - private: - bool m_userContextMenuSet; - -public: - /** - * Attribute of a range changed or range with attribute changed in given line range. - * @param startLine start line of change - * @param endLine end line of change - * @param rangeWithAttribute attribute changed or is active, this will perhaps lead to repaints - */ - void notifyAboutRangeChange (int startLine, int endLine, bool rangeWithAttribute); - - private Q_SLOTS: - /** - * Delayed update for view after text ranges changed - */ - void slotDelayedUpdateOfView (); - - Q_SIGNALS: - /** - * Delayed update for view after text ranges changed - */ - void delayedUpdateOfView (); - - public: - /** - * set of ranges which had the mouse inside last time, used for rendering - * @return set of ranges which had the mouse inside last time checked - */ - const QSet *rangesMouseIn () const { return &m_rangesMouseIn; } - - /** - * set of ranges which had the caret inside last time, used for rendering - * @return set of ranges which had the caret inside last time checked - */ - const QSet *rangesCaretIn () const { return &m_rangesCaretIn; } - - /** - * check if ranges changed for mouse in and caret in - * @param activationType type of activation to check - */ - void updateRangesIn (KTextEditor::Attribute::ActivationType activationType); - - // - // helpers for delayed view update after ranges changes - // - private: - /** - * update already inited? - */ - bool m_delayedUpdateTriggered; - - /** - * minimal line to update - */ - int m_lineToUpdateMin; - - /** - * maximal line to update - */ - int m_lineToUpdateMax; - - /** - * set of ranges which had the mouse inside last time - */ - QSet m_rangesMouseIn; - - /** - * set of ranges which had the caret inside last time - */ - QSet m_rangesCaretIn; -}; - -/** - * metatype register - */ -Q_DECLARE_METATYPE(KTextEditor::Cursor) -Q_DECLARE_METATYPE(KTextEditor::Range) - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/view/kateviewaccessible.h b/part/view/kateviewaccessible.h deleted file mode 100644 index 6de6990..0000000 --- a/part/view/kateviewaccessible.h +++ /dev/null @@ -1,320 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2010 Sebastian Sauer - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _KATE_VIEW_ACCESSIBLE_ -#define _KATE_VIEW_ACCESSIBLE_ - -#include "kateviewinternal.h" -#include "katetextcursor.h" - -#include -#include -#include - -/** - * This class implements a QAccessible-interface for a Kate::TextCursor. An - * instance of \a KateViewAccessible will hold an instance of this class to - * provide access to the cursor within a kateview. - * - * To test the cursor positioning using kmagnifier from kdeaccessibility you - * can do for example; - * @code - * export QT_ACCESSIBILITY=1 - * kmag & - * kwrite & - * @endcode - * then press F2 in kmag to switch to the "Follow Focus Mode" and see that - * the view follows the cursor in kwrite. - */ -class KateCursorAccessible : public QAccessibleInterface -{ - public: - - enum { ChildId = 1 }; - - explicit KateCursorAccessible(KateViewInternal *view) - : QAccessibleInterface() - , m_view(view) - { - } - - virtual ~KateCursorAccessible() - { - } - - virtual QString actionText(int action, QAccessible::Text t, int) const - { - if (t == QAccessible::Name) { - switch(action) { - case 0: return i18n("Move To..."); - case 1: return i18n("Move Left"); - case 2: return i18n("Move Right"); - case 3: return i18n("Move Up"); - case 4: return i18n("Move Down"); - default: break; - } - } - return QString(); - } - - virtual bool doAction(int action, int, const QVariantList & params = QVariantList() ) - { - bool ok = true; - KTextEditor::Cursor c = m_view->getCursor(); - switch(action) { - case 0: { - if (params.count() < 2) ok = false; - const int line = ok ? params[0].toInt(&ok) : 0; - const int column = ok ? params[1].toInt(&ok) : 0; - if (ok) c.setPosition(line, column); - } break; - case 1: c.setPosition(c.line(), c.column() - 1); break; - case 2: c.setPosition(c.line(), c.column() + 1); break; - case 3: c.setPosition(c.line() - 1, c.column()); break; - case 4: c.setPosition(c.line() + 1, c.column()); break; - default: ok = false; break; - } - return ok; - } - - virtual int userActionCount(int) const - { - return 5; - } - - virtual int childAt(int, int) const - { - return 0; - } - - virtual int childCount() const - { - return 0; - } - - virtual int indexOfChild(const QAccessibleInterface *) const - { - return 0; - } - - virtual bool isValid() const - { - KTextEditor::Cursor c = m_view->getCursor(); - return c.isValid(); - } - - virtual int navigate(QAccessible::RelationFlag relation, int entry, QAccessibleInterface **target) const - { - Q_UNUSED(relation); - Q_UNUSED(entry); - *target = 0; - return -1; - } - - virtual QObject* object() const - { - return m_view; - } - - virtual QRect rect(int) const - { - // return the exact position of the cursor with no width and height defined, - QPoint p = m_view->view()->cursorPositionCoordinates(); - return QRect(m_view->mapToGlobal(p), QSize(0,0)); - } - - virtual QAccessible::Relation relationTo(int child, const QAccessibleInterface *other, int otherChild) const - { - Q_UNUSED(child); - Q_UNUSED(other); - Q_UNUSED(otherChild); - return QAccessible::Unrelated; - } - - virtual QAccessible::Role role(int) const - { - return QAccessible::Cursor; - } - - virtual void setText(QAccessible::Text, int, const QString &) - { - } - - virtual QAccessible::State state(int) const - { - QAccessible::State s = QAccessible::Focusable | QAccessible::Focused; - return s; - } - - virtual QString text(QAccessible::Text, int) const - { - return QString(); - } - - private: - KateViewInternal *m_view; -}; - -/** - * This class implements a QAccessible-interface for a KateViewInternal. - * - * This is the root class for the kateview. The \a KateCursorAccessible class - * represents the cursor in the kateview and is a child of this class. - */ -class KateViewAccessible : public QAccessibleInterface -{ - public: - explicit KateViewAccessible(KateViewInternal *view) - : QAccessibleInterface() - , m_view(view) - , m_cursor(new KateCursorAccessible(view)) - { - } - - virtual ~KateViewAccessible() - { - } - - virtual QString actionText(int action, QAccessible::Text t, int child) const - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->actionText(action, t, 0); - return QString(); - } - - virtual bool doAction(int action, int child, const QVariantList & params = QVariantList() ) - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->doAction(action, 0, params); - return false; - } - - virtual int userActionCount(int child) const - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->userActionCount(0); - return 0; - } - - virtual int childAt(int x, int y) const - { - Q_UNUSED(x); - Q_UNUSED(y); - return 0; - } - - virtual int childCount() const - { - return 1; - } - - virtual int indexOfChild(const QAccessibleInterface *child) const - { - return dynamic_cast(child) ? KateCursorAccessible::ChildId : 0; - } - - virtual bool isValid() const - { - return true; - } - - virtual int navigate(QAccessible::RelationFlag relation, int entry, QAccessibleInterface **target) const - { - if ((relation == QAccessible::Child || QAccessible::FocusChild) && entry == KateCursorAccessible::ChildId) { - *target = new KateCursorAccessible(m_view); - return KateCursorAccessible::ChildId; - } - *target = 0; - return -1; - } - - virtual QObject* object() const - { - return m_view; - } - - virtual QRect rect(int child) const - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->rect(0); - return QRect(m_view->mapToGlobal(QPoint(0,0)), m_view->size()); - } - - virtual QAccessible::Relation relationTo(int child, const QAccessibleInterface *other, int otherChild) const - { - Q_UNUSED(child); - Q_UNUSED(other); - Q_UNUSED(otherChild); - return QAccessible::Unrelated; - } - - virtual QAccessible::Role role(int child) const - { - if (child == KateCursorAccessible::ChildId) - return QAccessible::Cursor; - return QAccessible::Document; - } - - virtual void setText(QAccessible::Text t, int child, const QString & text) - { - if (t == QAccessible::Value && child == 0 && m_view->view()->document()) - m_view->view()->document()->setText(text); - } - - virtual QAccessible::State state(int child) const - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->state(0); - QAccessible::State s = QAccessible::Focusable | QAccessible::Focused; - return s; - } - - virtual QString text(QAccessible::Text t, int child) const - { - if (child == KateCursorAccessible::ChildId) - return m_cursor->text(t, 0); - QString s; - if (m_view->view()->document()) { - if (t == QAccessible::Name) - s = m_view->view()->document()->documentName(); - if (t == QAccessible::Value) - s = m_view->view()->document()->text(); - } - return s; - } - - private: - KateViewInternal *m_view; - KateCursorAccessible *m_cursor; -}; - -/** - * Factory-function used to create \a KateViewAccessible instances for KateViewInternal - * to make the KateViewInternal accessible. - */ -QAccessibleInterface* accessibleInterfaceFactory(const QString &key, QObject *object) -{ - Q_UNUSED(key) - //if (key == QLatin1String("KateViewInternal")) - if (KateViewInternal *view = qobject_cast(object)) - return new KateViewAccessible(view); - return 0; -} - -#endif diff --git a/part/view/kateviewhelpers.cpp b/part/view/kateviewhelpers.cpp deleted file mode 100644 index 0b8e2d6..0000000 --- a/part/view/kateviewhelpers.cpp +++ /dev/null @@ -1,2013 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2008, 2009 Matthew Woehlke - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001 Anders Lund - Copyright (C) 2001 Christoph Cullmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateviewhelpers.h" - -#include "katecmd.h" -#include -#include -#include -#include -#include "katecodefolding.h" -#include "kateconfig.h" -#include "katedocument.h" -#include "katerenderer.h" -#include "kateview.h" -#include "kateviewinternal.h" -#include "katelayoutcache.h" -#include "katetextlayout.h" -#include "kateglobal.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -//BEGIN KateScrollBar -KateScrollBar::KateScrollBar (Qt::Orientation orientation, KateViewInternal* parent) - : QScrollBar (orientation, parent->m_view) - , m_middleMouseDown (false) - , m_view(parent->m_view) - , m_doc(parent->doc()) - , m_viewInternal(parent) - , m_showMarks(false) -{ - connect(this, SIGNAL(valueChanged(int)), this, SLOT(sliderMaybeMoved(int))); - connect(m_doc, SIGNAL(marksChanged(KTextEditor::Document*)), this, SLOT(marksChanged())); - - styleChange(*style()); -} - -void KateScrollBar::mousePressEvent(QMouseEvent* e) -{ - if (e->button() == Qt::MidButton) - m_middleMouseDown = true; - - QScrollBar::mousePressEvent(e); - - redrawMarks(); -} - -void KateScrollBar::mouseReleaseEvent(QMouseEvent* e) -{ - QScrollBar::mouseReleaseEvent(e); - - m_middleMouseDown = false; - - redrawMarks(); -} - -void KateScrollBar::mouseMoveEvent(QMouseEvent* e) -{ - QScrollBar::mouseMoveEvent(e); - - if (e->buttons() | Qt::LeftButton) - redrawMarks(); -} - -void KateScrollBar::paintEvent(QPaintEvent *e) -{ - QScrollBar::paintEvent(e); - - if (!m_showMarks) - return; - - QPainter painter(this); - - QStyleOptionSlider opt; - opt.init(this); - opt.subControls = QStyle::SC_None; - opt.activeSubControls = QStyle::SC_None; - opt.orientation = orientation(); - opt.minimum = minimum(); - opt.maximum = maximum(); - opt.sliderPosition = sliderPosition(); - opt.sliderValue = value(); - opt.singleStep = singleStep(); - opt.pageStep = pageStep(); - - QRect rect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarSlider, this); - - QHashIterator it = m_lines; - while (it.hasNext()) - { - it.next(); - if (it.key() < rect.top() || it.key() > rect.bottom()) - { - painter.setPen(it.value()); - painter.drawLine(0, it.key(), width(), it.key()); - } - } -} - -void KateScrollBar::resizeEvent(QResizeEvent *e) -{ - QScrollBar::resizeEvent(e); - recomputeMarksPositions(); -} - -void KateScrollBar::styleChange(QStyle &s) -{ - QScrollBar::styleChange(s); - recomputeMarksPositions(); -} - -void KateScrollBar::sliderChange ( SliderChange change ) -{ - // call parents implementation - QScrollBar::sliderChange (change); - - if (change == QAbstractSlider::SliderValueChange) - { - redrawMarks(); - } - else if (change == QAbstractSlider::SliderRangeChange) - { - recomputeMarksPositions(); - } -} - -void KateScrollBar::wheelEvent(QWheelEvent *e) -{ - if (e->modifiers() == Qt::NoModifier) - return QScrollBar::wheelEvent(e); - - QCoreApplication::sendEvent(m_viewInternal, e); -} - -void KateScrollBar::marksChanged() -{ - recomputeMarksPositions(); -} - -void KateScrollBar::redrawMarks() -{ - if (!m_showMarks) - return; - - update(); -} - -void KateScrollBar::recomputeMarksPositions() -{ - m_lines.clear(); - int visibleLines = m_doc->visibleLines(); - - QStyleOptionSlider opt; - initStyleOption(&opt); - - int topMargin = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarSubPage, this).top() + 1; - int realHeight = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarAddPage, this).bottom() - topMargin - 1; - - const QHash &marks = m_doc->marks(); - KateCodeFoldingTree *tree = m_doc->foldingTree(); - - for (QHash::const_iterator i = marks.constBegin(); i != marks.constEnd(); ++i) - { - KTextEditor::Mark *mark = i.value(); - - uint line = mark->line; - - if (tree) - { - KateCodeFoldingNode *node = tree->findNodeForLine(line); - - while (node) - { - if (!node->isVisible()) - line = tree->getStartLine(node); - node = node->getParentNode(); - } - } - - line = m_doc->getVirtualLine(line); - - double d = (double)line / (visibleLines - 1); - m_lines.insert(topMargin + (int)(d * realHeight), - QColor(KateRendererConfig::global()->lineMarkerColor((KTextEditor::MarkInterface::MarkTypes)mark->type))); - } - - // with Qt4 we don't have the luxury of painting outside a paint event - // and a paint event wipes the widget... so just update - update(); -} - -void KateScrollBar::sliderMaybeMoved(int value) -{ - if (m_middleMouseDown) { - // we only need to emit this signal once, as for the following slider - // movements the signal sliderMoved() is already emitted. - // Thus, set m_middleMouseDown to false right away. - m_middleMouseDown = false; - emit sliderMMBMoved(value); - } -} -//END - - -//BEGIN KateCmdLineEditFlagCompletion -/** - * This class provide completion of flags. It shows a short description of - * each flag, and flags are appended. - */ -class KateCmdLineEditFlagCompletion : public KCompletion -{ - public: - KateCmdLineEditFlagCompletion() {;} - - QString makeCompletion( const QString & /*s*/ ) - { - return QString(); - } - -}; -//END KateCmdLineEditFlagCompletion - -//BEGIN KateCmdLineEdit -KateCommandLineBar::KateCommandLineBar (KateView *view, QWidget *parent) - : KateViewBarWidget (true, parent) -{ - QVBoxLayout *topLayout = new QVBoxLayout (); - centralWidget()->setLayout(topLayout); - topLayout->setMargin(0); - m_lineEdit = new KateCmdLineEdit (this, view); - connect(m_lineEdit, SIGNAL(hideRequested()), SIGNAL(hideMe())); - topLayout->addWidget (m_lineEdit); - - setFocusProxy (m_lineEdit); -} - -KateCommandLineBar::~KateCommandLineBar() -{ -} - -// inserts the given string in the command line edit and (if selcted = true) selects it so the user -// can type over it if she wants to -// inserts the given string in the command line edit and selects it so the user can type over it if -// she wants to -void KateCommandLineBar::setText(const QString &text, bool selected) -{ - m_lineEdit->setText(text); - if (selected) { - m_lineEdit->selectAll(); - } -} - -void KateCommandLineBar::execute(const QString &text) -{ - m_lineEdit->slotReturnPressed(text); -} - -KateCmdLineEdit::KateCmdLineEdit (KateCommandLineBar *bar, KateView *view) - : KLineEdit () - , m_view (view) - , m_bar (bar) - , m_msgMode (false) - , m_histpos( 0 ) - , m_cmdend( 0 ) - , m_command( 0L ) -{ - connect (this, SIGNAL(returnPressed(const QString &)), - this, SLOT(slotReturnPressed(const QString &))); - - setCompletionObject(KateCmd::self()->commandCompletionObject()); - setAutoDeleteCompletionObject( false ); - m_cmdRange.setPattern("^([0-9$]+|\\.([+-]\\d+)?)?,([0-9$]+|\\.([+-]\\d+)?)?"); - m_cmdExpr.setPattern("^(\\d+)([+-])(\\d+)$"); - m_gotoLine.setPattern("[+-]?\\d+"); - - m_hideTimer = new QTimer(this); - m_hideTimer->setSingleShot(true); - connect(m_hideTimer, SIGNAL(timeout()), this, SLOT(hideLineEdit())); - - // make sure the timer is stopped when the user switches views. if not, focus will be given to the - // wrong view when KateViewBar::hideCurrentBarWidget() is called after 4 seconds. (the timer is - // used for showing things like "Success" for four seconds after the user has used the kate - // command line) - connect(m_view, SIGNAL(focusOut (KTextEditor::View*)), m_hideTimer, SLOT(stop())); -} - -void KateCmdLineEdit::hideEvent(QHideEvent *e) -{ - Q_UNUSED(e); - m_view->showViModeBar(); -} - - -QString KateCmdLineEdit::helptext( const QPoint & ) const -{ - QString beg = "
Help: "; - QString mid = "
"; - QString end = "
"; - - QString t = text(); - QRegExp re( "\\s*help\\s+(.*)" ); - if ( re.indexIn( t ) > -1 ) - { - QString s; - // get help for command - QString name = re.cap( 1 ); - if ( name == "list" ) - { - return beg + i18n("Available Commands") + mid - + KateCmd::self()->commandList().join(" ") - + i18n("

For help on individual commands, do 'help <command>'

") - + end; - } - else if ( ! name.isEmpty() ) - { - KTextEditor::Command *cmd = KateCmd::self()->queryCommand( name ); - if ( cmd ) - { - if ( cmd->help( m_view, name, s ) ) - return beg + name + mid + s + end; - else - return beg + name + mid + i18n("No help for '%1'", name ) + end; - } - else - return beg + mid + i18n("No such command %1", name) + end; - } - } - - return beg + mid + i18n( - "

This is the Katepart command line.
" - "Syntax: command [ arguments ]
" - "For a list of available commands, enter help list
" - "For help for individual commands, enter help <command>

") - + end; -} - - - -bool KateCmdLineEdit::event(QEvent *e) { - if (e->type() == QEvent::QueryWhatsThis) { - setWhatsThis(helptext(QPoint())); - e->accept(); - return true; - } - return KLineEdit::event(e); -} - -void KateCmdLineEdit::slotReturnPressed ( const QString& text ) -{ - if (text.isEmpty()) return; - // silently ignore leading space characters and colon characters (for vi-heads) - uint n = 0; - const uint textlen=text.length(); - while( (n=textlen) return; - - QString cmd = text.mid( n ); - - // expand '%' to '1,$' ("all lines") if at the start of the line - if ( cmd.at( 0 ) == '%' ) { - cmd.replace( 0, 1, "1,$" ); - } - - KTextEditor::Range range(-1, 0, -1, 0); - - // check if a range was given - if (m_cmdRange.indexIn(cmd) != -1 && m_cmdRange.matchedLength() > 0) { - - cmd.remove( m_cmdRange ); - - QString s = m_cmdRange.capturedTexts().at(1); - QString e = m_cmdRange.capturedTexts().at(3); - - if ( s.isEmpty() ) - s = '.'; - if ( e.isEmpty() ) - e = s; - - // replace '$' with the number of the last line and '.' with the current line - s.replace('$', QString::number( m_view->doc()->lines() ) ); - e.replace('$', QString::number( m_view->doc()->lines() ) ); - s.replace('.', QString::number( m_view->cursorPosition().line()+1 ) ); - e.replace('.', QString::number( m_view->cursorPosition().line()+1 ) ); - - // evaluate expressions (a+b or a-b) if we have any - if (m_cmdExpr.indexIn(s) != -1) { - if (m_cmdExpr.capturedTexts().at(2) == "+") { - s = QString::number(m_cmdExpr.capturedTexts().at(1).toInt() - + m_cmdExpr.capturedTexts().at(3).toInt()); - } else { - s = QString::number(m_cmdExpr.capturedTexts().at(1).toInt() - - m_cmdExpr.capturedTexts().at(3).toInt()); - } - } - if (m_cmdExpr.indexIn(e) != -1) { - if (m_cmdExpr.capturedTexts().at(2) == "+") { - e = QString::number(m_cmdExpr.capturedTexts().at(1).toInt() - + m_cmdExpr.capturedTexts().at(3).toInt()); - } else { - e = QString::number(m_cmdExpr.capturedTexts().at(1).toInt() - - m_cmdExpr.capturedTexts().at(3).toInt()); - } - } - - range.setRange(KTextEditor::Range(s.toInt()-1, 0, e.toInt()-1, 0)); - } - - // special case: if the command is just a number with an optional +/- prefix, rewrite to "goto" - if (m_gotoLine.exactMatch(cmd)) { - cmd.prepend("goto "); - } - - // Built in help: if the command starts with "help", [try to] show some help - if ( cmd.startsWith( QLatin1String("help") ) ) - { - QWhatsThis::showText(mapToGlobal(QPoint(0,0)), helptext( QPoint() ) ); - clear(); - KateCmd::self()->appendHistory( cmd ); - m_histpos = KateCmd::self()->historyLength(); - m_oldText.clear(); - return; - } - - if (cmd.length () > 0) - { - KTextEditor::Command *p = KateCmd::self()->queryCommand (cmd); - KTextEditor::RangeCommand *ce = dynamic_cast(p); - - m_oldText = m_cmdRange.capturedTexts().at(0) + cmd; - m_msgMode = true; - - // we got a range and a valid command, but the command does not inherit the RangeCommand - // extension. bail out. - if ( ( !ce && range.isValid() && p ) || ( range.isValid() && ce && !ce->supportsRange(cmd) ) ) { - setText (i18n ("Error: No range allowed for command \"%1\".", cmd)); - } else { - - if (p) - { - QString msg; - - if ((ce && ce->exec(m_view, cmd, msg, range)) || p->exec (m_view, cmd, msg)) - { - - // append command along with range (will be empty if none given) to history - KateCmd::self()->appendHistory( m_cmdRange.capturedTexts().at(0) + cmd ); - m_histpos = KateCmd::self()->historyLength(); - m_oldText.clear(); - - if (msg.length() > 0) - setText (i18n ("Success: ") + msg); - else - // always hide on success without message - emit hideRequested(); - } - else - { - if (msg.length() > 0) { - if (msg.contains('\n')) { - // multiline error, use widget with more space - QWhatsThis::showText(mapToGlobal(QPoint(0,0)), msg); - } else { - setText(msg); - } - } else - setText (i18n ("Command \"%1\" failed.", cmd)); - KNotification::beep(); - } - } - else - { - setText (i18n ("No such command: \"%1\"", cmd)); - KNotification::beep(); - } - } - } - - // clean up - if (completionObject() != KateCmd::self()->commandCompletionObject()) - { - KCompletion *c = completionObject(); - setCompletionObject(KateCmd::self()->commandCompletionObject()); - delete c; - } - m_command = 0; - m_cmdend = 0; - - // the following commands change the focus themselves - // FIXME: ugly :-( - if (cmd != "bn" && cmd != "bp" && cmd != "new" && cmd != "vnew" && cmd != "enew") { - m_view->setFocus (); - } - - if (isVisible()) { - m_hideTimer->start(4000); - } -} - -void KateCmdLineEdit::hideLineEdit () // unless i have focus ;) -{ - if ( ! hasFocus() ) { - emit hideRequested(); - } -} - -void KateCmdLineEdit::focusInEvent ( QFocusEvent *ev ) -{ - if (m_msgMode) - { - m_msgMode = false; - setText (m_oldText); - selectAll(); - } - - KLineEdit::focusInEvent (ev); -} - -void KateCmdLineEdit::keyPressEvent( QKeyEvent *ev ) -{ - if (ev->key() == Qt::Key_Escape || - (ev->key() == Qt::Key_BracketLeft && ev->modifiers() == Qt::ControlModifier)) - { - m_view->setFocus (); - hideLineEdit(); - clear(); - } - else if ( ev->key() == Qt::Key_Up ) - fromHistory( true ); - else if ( ev->key() == Qt::Key_Down ) - fromHistory( false ); - - uint cursorpos = cursorPosition(); - KLineEdit::keyPressEvent (ev); - - // during typing, let us see if we have a valid command - if ( ! m_cmdend || cursorpos <= m_cmdend ) - { - QChar c; - if ( ! ev->text().isEmpty() ) - c = ev->text()[0]; - - if ( ! m_cmdend && ! c.isNull() ) // we have no command, so lets see if we got one - { - if ( ! c.isLetterOrNumber() && c != '-' && c != '_' ) - { - m_command = KateCmd::self()->queryCommand( text().trimmed() ); - if ( m_command ) - { - //kDebug(13025)<<"keypress in commandline: We have a command! "<queryCommand( text().trimmed() ); - if ( m_command ) - { - //kDebug(13025)<<"keypress in commandline: We have a command! "<commandCompletionObject()) - { - KCompletion *c = completionObject(); - setCompletionObject(KateCmd::self()->commandCompletionObject()); - delete c; - } - - m_cmdend = 0; - } - } - - // if we got a command, check if it wants to do something. - if ( m_command ) - { - //kDebug(13025)<<"Checking for CommandExtension.."; - KTextEditor::CommandExtension *ce = dynamic_cast(m_command); - if ( ce ) - { - KCompletion *cmpl = ce->completionObject( m_view, text().left( m_cmdend ).trimmed() ); - if ( cmpl ) - { - // We need to prepend the current command name + flag string - // when completion is done - //kDebug(13025)<<"keypress in commandline: Setting completion object!"; - - setCompletionObject( cmpl ); - } - } - } - } - else if ( m_command )// check if we should call the commands processText() - { - KTextEditor::CommandExtension *ce = dynamic_cast( m_command ); - if ( ce && ce->wantsToProcessText( text().left( m_cmdend ).trimmed() ) - && ! ( ev->text().isNull() || ev->text().isEmpty() ) ) - ce->processText( m_view, text() ); - } -} - -void KateCmdLineEdit::fromHistory( bool up ) -{ - if ( ! KateCmd::self()->historyLength() ) - return; - - QString s; - - if ( up ) - { - if ( m_histpos > 0 ) - { - m_histpos--; - s = KateCmd::self()->fromHistory( m_histpos ); - } - } - else - { - if ( m_histpos < ( KateCmd::self()->historyLength() - 1 ) ) - { - m_histpos++; - s = KateCmd::self()->fromHistory( m_histpos ); - } - else - { - m_histpos = KateCmd::self()->historyLength(); - setText( m_oldText ); - } - } - if ( ! s.isEmpty() ) - { - // Select the argument part of the command, so that it is easy to overwrite - setText( s ); - static QRegExp reCmd = QRegExp(".*[\\w\\-]+(?:[^a-zA-Z0-9_-]|:\\w+)(.*)"); - if ( reCmd.indexIn( text() ) == 0 ) - setSelection( text().length() - reCmd.cap(1).length(), reCmd.cap(1).length() ); - } -} -//END KateCmdLineEdit - -//BEGIN KateIconBorder -using namespace KTextEditor; - -const int halfIPW = 8; - -KateIconBorder::KateIconBorder ( KateViewInternal* internalView, QWidget *parent ) - : QWidget(parent) - , m_view( internalView->m_view ) - , m_doc( internalView->doc() ) - , m_viewInternal( internalView ) - , m_iconBorderOn( false ) - , m_lineNumbersOn( false ) - , m_foldingMarkersOn( false ) - , m_dynWrapIndicatorsOn( false ) - , m_annotationBorderOn( false ) - , m_dynWrapIndicators( 0 ) - , m_cachedLNWidth( 0 ) - , m_maxCharWidth( 0 ) - , iconPaneWidth (16) - , m_annotationBorderWidth (6) - , m_foldingRange(0) - , m_nextHighlightBlock(-2) - , m_currentBlockLine(-1) -{ - initializeFoldingColors(); - - setAttribute( Qt::WA_StaticContents ); - setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Minimum ); - setMouseTracking(true); - m_doc->setMarkDescription( MarkInterface::markType01, i18n("Bookmark") ); - m_doc->setMarkPixmap( MarkInterface::markType01, KIcon("bookmarks").pixmap(16, 16) ); - - updateFont(); - - m_delayFoldingHlTimer.setSingleShot(true); - m_delayFoldingHlTimer.setInterval(250); - connect(&m_delayFoldingHlTimer, SIGNAL(timeout()), this, SLOT(showBlock())); -} - -void KateIconBorder::initializeFoldingColors() -{ - // Get the schema - KateRendererConfig *config = m_view->renderer()->config(); - // FIXME next 3 lines temporary until this moves to config - const KColorScheme scheme( QPalette::Normal ); - const QColor middle( KColorUtils::tint( config->iconBarColor(), scheme.foreground( KColorScheme::NeutralText ).color(), 0.7 ) ); - const QColor final( KColorUtils::tint( config->iconBarColor(), scheme.foreground( KColorScheme::PositiveText ).color(), 0.7 ) ); - - const QColor start( config->iconBarColor() ); - static const int MIDFOLDINGCOLORS = MAXFOLDINGCOLORS / 2; - static const qreal n = 2.0 / MAXFOLDINGCOLORS; - - int i, j; - for( i = 0; i < MIDFOLDINGCOLORS; i++ ) { - const qreal a = 0.9 * pow(qreal(i) * n, 1.0); - m_foldingColors[i] = KColorUtils::tint( start, middle, a ); - } - for( j = 0; i < MAXFOLDINGCOLORS; i++, j++ ) { - const qreal a = 0.9 * pow(qreal(j) * n, 1.0); - m_foldingColors[i] = KColorUtils::tint( middle, final, a ); - } -} - - -KateIconBorder::~KateIconBorder() -{ - delete m_foldingRange; - m_foldingRange = 0; -} - -void KateIconBorder::setIconBorderOn( bool enable ) -{ - if( enable == m_iconBorderOn ) - return; - - m_iconBorderOn = enable; - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -void KateIconBorder::setAnnotationBorderOn( bool enable ) -{ - if( enable == m_annotationBorderOn ) - return; - - m_annotationBorderOn = enable; - - emit m_view->annotationBorderVisibilityChanged(m_view, enable); - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -void KateIconBorder::removeAnnotationHovering() -{ - // remove hovering if it's still there - if (m_annotationBorderOn && !m_hoveredAnnotationText.isEmpty()) - { - m_hoveredAnnotationText.clear(); - hideAnnotationTooltip(); - QTimer::singleShot( 0, this, SLOT(update()) ); - } -} - -void KateIconBorder::setLineNumbersOn( bool enable ) -{ - if( enable == m_lineNumbersOn ) - return; - - m_lineNumbersOn = enable; - m_dynWrapIndicatorsOn = (m_dynWrapIndicators == 1) ? enable : m_dynWrapIndicators; - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -void KateIconBorder::setDynWrapIndicators( int state ) -{ - if (state == m_dynWrapIndicators ) - return; - - m_dynWrapIndicators = state; - m_dynWrapIndicatorsOn = (state == 1) ? m_lineNumbersOn : state; - - updateGeometry (); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -void KateIconBorder::setFoldingMarkersOn( bool enable ) -{ - if( enable == m_foldingMarkersOn ) - return; - - m_foldingMarkersOn = enable; - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -QSize KateIconBorder::sizeHint() const -{ - int w = 0; - - if (m_iconBorderOn) - w += iconPaneWidth + 1; - - if (m_annotationBorderOn) - { - w += m_annotationBorderWidth + 1; - } - - if (m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn)) { - w += lineNumberWidth() + 1; - } - - if (m_foldingMarkersOn) - w += iconPaneWidth + 1; - - w += 4; - - return QSize( w, 0 ); -} - -// This function (re)calculates the maximum width of any of the digit characters (0 -> 9) -// for graceful handling of variable-width fonts as the linenumber font. -void KateIconBorder::updateFont() -{ - QFontMetrics fm = m_view->renderer()->config()->fontMetrics(); - m_maxCharWidth = 0; - // Loop to determine the widest numeric character in the current font. - // 48 is ascii '0' - for (int i = 48; i < 58; i++) { - int charWidth = fm.width( QChar(i) ); - m_maxCharWidth = qMax(m_maxCharWidth, charWidth); - } - - // the icon pane scales with the font... - iconPaneWidth = fm.height(); - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - -int KateIconBorder::lineNumberWidth() const -{ - int width = m_lineNumbersOn ? ((int)log10((double)(m_view->doc()->lines())) + 1) * m_maxCharWidth + 4 : 0; - - if (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) { - // HACK: 16 == style().scrollBarExtent().width() - width = qMax(16 + 4, width); - - if (m_cachedLNWidth != width || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor()) { - int w = 16;// HACK: 16 == style().scrollBarExtent().width() style().scrollBarExtent().width(); - int h = m_view->renderer()->config()->fontMetrics().height(); - - QSize newSize(w, h); - if ((m_arrow.size() != newSize || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor()) && !newSize.isEmpty()) { - m_arrow = QPixmap(newSize); - - QPainter p(&m_arrow); - p.fillRect( 0, 0, w, h, m_view->renderer()->config()->iconBarColor() ); - - h = m_view->renderer()->config()->fontMetrics().ascent(); - - p.setPen(m_view->renderer()->config()->lineNumberColor()); - - QPainterPath path; - path.moveTo(w/2, h/2); - path.lineTo(w/2, 0); - path.lineTo(w/4, h/4); - path.lineTo(0, 0); - path.lineTo(0, h/2); - path.lineTo(w/2, h-1); - path.lineTo(w*3/4, h-1); - path.lineTo(w-1, h*3/4); - path.lineTo(w*3/4, h/2); - path.lineTo(0, h/2); - p.drawPath(path); - } - } - } - - return width; -} - -QBrush KateIconBorder::foldingColor(KateLineInfo *info,int realLine, bool solid) { - int depth; - if (info != 0) { - depth = info->depth; - } else { - KateLineInfo tmp; - m_doc->lineInfo(&tmp, realLine); - depth = tmp.depth; - } - - QColor result; - if (depth < MAXFOLDINGCOLORS) - result = m_foldingColors[depth]; - else - result = m_foldingColors[MAXFOLDINGCOLORS-1]; - if (!solid) - result.setAlphaF(0.4); - - return QBrush( result ); - -} - -void KateIconBorder::paintEvent(QPaintEvent* e) -{ - paintBorder(e->rect().x(), e->rect().y(), e->rect().width(), e->rect().height()); -} - -static void paintTriangle (QPainter &painter, const QColor &baseColor, int xOffset, int yOffset, int width, int height, bool open) -{ - painter.setRenderHint(QPainter::Antialiasing); - - qreal size = qMin (width, height); - - QColor c; - if ( KColorUtils::luma( baseColor ) > 0.25 ) - c = KColorUtils::darken( baseColor ); - else - c = KColorUtils::shade( baseColor, 0.2 ); - - QPen pen; - pen.setJoinStyle (Qt::RoundJoin); - pen.setColor (c); - pen.setWidthF (1.5); - painter.setPen ( pen ); - - painter.setBrush ( c ); - - // let some border, if possible - size *= 0.6; - - qreal halfSize = size / 2; - qreal halfSizeP = halfSize * 0.6; - QPointF middle (xOffset + (qreal)width / 2, yOffset + (qreal)height / 2); - - if (open) - { - QPointF points[3] = { middle+QPointF(-halfSize, -halfSizeP), middle+QPointF(halfSize, -halfSizeP), middle+QPointF(0, halfSizeP) }; - painter.drawConvexPolygon(points, 3); - } - else - { - QPointF points[3] = { middle+QPointF(-halfSizeP, -halfSize), middle+QPointF(-halfSizeP, halfSize), middle+QPointF(halfSizeP, 0) }; - painter.drawConvexPolygon(points, 3); - } - - painter.setRenderHint(QPainter::Antialiasing, false); -} - -void KateIconBorder::paintBorder (int /*x*/, int y, int /*width*/, int height) -{ - uint h = m_view->renderer()->config()->fontMetrics().height(); - uint startz = (y / h); - uint endz = startz + 1 + (height / h); - uint lineRangesSize = m_viewInternal->cache()->viewCacheLineCount(); - - // center the folding boxes - int m_px = (h - 11) / 2; - if (m_px < 0) - m_px = 0; - - int lnWidth( 0 ); - if ( m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) ) // avoid calculating unless needed ;-) - { - lnWidth = lineNumberWidth(); - if ( lnWidth != m_cachedLNWidth || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor() ) - { - // we went from n0 ->n9 lines or vice verca - // this causes an extra updateGeometry() first time the line numbers - // are displayed, but sizeHint() is supposed to be const so we can't set - // the cached value there. - m_cachedLNWidth = lnWidth; - m_oldBackgroundColor = m_view->renderer()->config()->iconBarColor(); - updateGeometry(); - update (); - return; - } - } - - int w( this->width() ); // sane value/calc only once - - QPainter p ( this ); - p.setRenderHints (QPainter::TextAntialiasing); - p.setFont ( m_view->renderer()->config()->font() ); // for line numbers - - KateLineInfo oldInfo; - if (startz < lineRangesSize) - { - if ((m_viewInternal->cache()->viewLine(startz).line()-1) < 0) - oldInfo.topLevel = true; - else - m_doc->lineInfo(&oldInfo,m_viewInternal->cache()->viewLine(startz).line()-1); - } - - KTextEditor::AnnotationModel *model = m_view->annotationModel() ? - m_view->annotationModel() : m_doc->annotationModel(); - - for (uint z=startz; z <= endz; z++) - { - int y = h * z; - int realLine = -1; - - if (z < lineRangesSize) - realLine = m_viewInternal->cache()->viewLine(z).line(); - - int lnX = 0; - - p.fillRect( 0, y, w-4, h, m_view->renderer()->config()->iconBarColor() ); - p.fillRect( w-4, y, 4, h, m_view->renderer()->config()->backgroundColor() ); - - // icon pane - if( m_iconBorderOn ) - { - p.setPen ( m_view->renderer()->config()->lineNumberColor() ); - p.setBrush ( m_view->renderer()->config()->lineNumberColor() ); - p.drawLine(lnX+iconPaneWidth+1, y, lnX+iconPaneWidth+1, y+h); - - if( (realLine > -1) && (m_viewInternal->cache()->viewLine(z).startCol() == 0) ) - { - uint mrk ( m_doc->mark( realLine ) ); // call only once - - if ( mrk ) - { - for( uint bit = 0; bit < 32; bit++ ) - { - MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes)(1<markPixmap( markType )); - - if (!px_mark.isNull() && h > 0 && iconPaneWidth > 0) - { - if (iconPaneWidth < px_mark.width() || h < (uint)px_mark.height()) - px_mark = px_mark.scaled (iconPaneWidth, h, Qt::KeepAspectRatio); - - // center the mark pixmap - int x_px = (iconPaneWidth - px_mark.width()) / 2; - if (x_px < 0) - x_px = 0; - - int y_px = (h - px_mark.height()) / 2; - if (y_px < 0) - y_px = 0; - - p.drawPixmap( lnX+x_px, y+y_px, px_mark); - } - } - } - } - } - - lnX += iconPaneWidth + 2; - } - - // annotation information - if( m_annotationBorderOn ) - { - // Draw a border line between annotations and the line numbers - p.setPen ( m_view->renderer()->config()->lineNumberColor() ); - p.setBrush ( m_view->renderer()->config()->lineNumberColor() ); - - int borderWidth = m_annotationBorderWidth; - p.drawLine(lnX+borderWidth+1, y, lnX+borderWidth+1, y+h); - - if( (realLine > -1) && model ) - { - // Fetch data from the model - QVariant text = model->data( realLine, Qt::DisplayRole ); - QVariant foreground = model->data( realLine, Qt::ForegroundRole ); - QVariant background = model->data( realLine, Qt::BackgroundRole ); - // Fill the background - if( background.isValid() ) - { - p.fillRect( lnX, y, borderWidth + 1, h, background.value() ); - } - // Set the pen for drawing the foreground - if( foreground.isValid() ) - { - p.setBrush( foreground.value() ); - } - - // Draw a border around all adjacent entries that have the same text as the currently hovered one - if( m_hoveredAnnotationText == text.toString() ) - { - p.drawLine( lnX, y, lnX, y+h ); - p.drawLine( lnX+borderWidth, y, lnX+borderWidth, y+h ); - - QVariant beforeText = model->data( realLine-1, Qt::DisplayRole ); - QVariant afterText = model->data( realLine+1, Qt::DisplayRole ); - if( ((beforeText.isValid() && beforeText.canConvert() - && text.isValid() && text.canConvert() - && beforeText.toString() != text.toString()) || realLine == 0) - && m_viewInternal->cache()->viewLine(z).viewLine() == 0) - { - p.drawLine( lnX+1, y, lnX+borderWidth, y ); - } - - if( ((afterText.isValid() && afterText.canConvert() - && text.isValid() && text.canConvert() - && afterText.toString() != text.toString()) - || realLine == m_view->doc()->lines() - 1) - && m_viewInternal->cache()->viewLine(z).viewLine() == m_viewInternal->cache()->viewLineCount(realLine)-1) - { - p.drawLine( lnX+1, y+h-1, lnX+borderWidth, y+h-1 ); - } - } - if( foreground.isValid() ) - { - QPen pen = p.pen(); - pen.setWidth( 1 ); - p.setPen( pen ); - } - - // Now draw the normal text - if( text.isValid() && text.canConvert() && (m_viewInternal->cache()->viewLine(z).startCol() == 0) ) - { - p.drawText( lnX+3, y, borderWidth-3, h, Qt::AlignLeft|Qt::AlignVCenter, text.toString() ); - } - } - - // adjust current X position and reset the pen and brush - lnX += borderWidth + 2; - } - - // line number - if( m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) ) - { - p.setPen ( m_view->renderer()->config()->lineNumberColor() ); - p.setBrush ( m_view->renderer()->config()->lineNumberColor() ); - - if (realLine > -1) { - if (m_viewInternal->cache()->viewLine(z).startCol() == 0) { - if (m_lineNumbersOn) - p.drawText( lnX, y, lnWidth-4, h, Qt::AlignRight|Qt::AlignVCenter, QString("%1").arg( realLine + 1 ) ); - } else if (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) { - p.drawPixmap(lnX + lnWidth - m_arrow.width() - 2, y, m_arrow); - } - } - - lnX += lnWidth + 2; - } - - // folding markers - if( m_foldingMarkersOn ) - { - if( realLine > -1 ) - { - KateLineInfo info; - m_doc->lineInfo(&info,realLine); - - QBrush brush (foldingColor(&info,realLine,true)); - p.fillRect(lnX, y, iconPaneWidth, h, brush); - - if (!info.topLevel) - { - if (info.startsVisibleBlock && (m_viewInternal->cache()->viewLine(z).startCol() == 0)) - { - paintTriangle (p, brush.color(), lnX, y, iconPaneWidth, h, true); - } - else if (info.startsInVisibleBlock && m_viewInternal->cache()->viewLine(z).startCol() == 0) - { - paintTriangle (p, brush.color(), lnX, y, iconPaneWidth, h, false); - } - else - { - // p.drawLine(lnX+halfIPW,y,lnX+halfIPW,y+h-1); - - // if (info.endsBlock && !m_viewInternal->cache()->viewLine(z).wrap()) - // p.drawLine(lnX+halfIPW,y+h-1,lnX+iconPaneWidth-2,y+h-1); - } - } - - oldInfo = info; - } - - lnX += iconPaneWidth + 2; - } - } -} - -KateIconBorder::BorderArea KateIconBorder::positionToArea( const QPoint& p ) const -{ - int x = 0; - if( m_iconBorderOn ) { - x += iconPaneWidth; - if( p.x() <= x ) - return IconBorder; - } - if( this->m_annotationBorderOn ) { - x += m_annotationBorderWidth; - if( p.x() <= x ) - return AnnotationBorder; - } - if( m_lineNumbersOn || m_dynWrapIndicators ) { - x += lineNumberWidth(); - if( p.x() <= x ) - return LineNumbers; - } - if( m_foldingMarkersOn ) { - x += iconPaneWidth; - if( p.x() <= x ) - return FoldingMarkers; - } - return None; -} - -void KateIconBorder::mousePressEvent( QMouseEvent* e ) -{ - const KateTextLayout& t = m_viewInternal->yToKateTextLayout(e->y()); - if (t.isValid()) { - m_lastClickedLine = t.line(); - if ( positionToArea( e->pos() ) != IconBorder && positionToArea( e->pos() ) != AnnotationBorder ) - { - QMouseEvent forward( QEvent::MouseButtonPress, - QPoint( 0, e->y() ), e->button(), e->buttons(),e->modifiers() ); - m_viewInternal->mousePressEvent( &forward ); - } - return e->accept(); - } - - QWidget::mousePressEvent(e); -} - -void KateIconBorder::showDelayedBlock(int line) -{ - // save the line over which the mouse hovers - // either we start the timer for delay, or we show the block immediately - // if the smart range already exists - m_nextHighlightBlock = line; - if (!m_foldingRange) { - if (!m_delayFoldingHlTimer.isActive()) { - m_delayFoldingHlTimer.start(); - } - } else { - showBlock(); - } -} - -void KateIconBorder::showBlock() -{ - if (m_nextHighlightBlock == m_currentBlockLine) return; - m_currentBlockLine = m_nextHighlightBlock; - - // get the new range, that should be highlighted - KTextEditor::Range newRange = KTextEditor::Range::invalid(); - KateCodeFoldingTree *tree = m_doc->foldingTree(); - if (tree) { - KateCodeFoldingNode *node = tree->findNodeForLine(m_currentBlockLine); - KTextEditor::Cursor beg; - KTextEditor::Cursor end; - if (node != tree->rootNode () && node->getBegin(tree, &beg)) { - if (node->getEnd(tree, &end)) - newRange = KTextEditor::Range(beg, end); - else - newRange = KTextEditor::Range(beg, m_viewInternal->doc()->documentEnd()); - } - KateLineInfo info; - tree->getLineInfo(&info, m_currentBlockLine); - if ((info.startsVisibleBlock)){ - node=tree->findNodeStartingAt(m_currentBlockLine); - if (node) { - if (node != tree->rootNode () && node->getBegin(tree, &beg) && node->getEnd(tree, &end)) { - newRange = KTextEditor::Range(beg, end); - } - } - } - - } - - if (newRange.isValid() && m_foldingRange && *m_foldingRange == newRange) { - // new range equals the old one, nothing to do. - return; - } else { // the ranges differ, delete the old, if it exists - delete m_foldingRange; - m_foldingRange = 0; - } - - if (newRange.isValid()) { - kDebug(13025) << "new folding hl-range:" << newRange; - m_foldingRange = m_doc->newMovingRange(newRange, KTextEditor::MovingRange::ExpandRight); - KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute()); - attr->setBackground(foldingColor(0, m_currentBlockLine, false)); - m_foldingRange->setView (m_view); - // use z depth defined in moving ranges interface - m_foldingRange->setZDepth (-100.0); - m_foldingRange->setAttribute(attr); - } -} - -void KateIconBorder::hideBlock() -{ - if (m_delayFoldingHlTimer.isActive()) { - m_delayFoldingHlTimer.stop(); - } - - m_nextHighlightBlock = -2; - m_currentBlockLine = -1; - delete m_foldingRange; - m_foldingRange = 0; -} - -void KateIconBorder::leaveEvent(QEvent *event) -{ - hideBlock(); - removeAnnotationHovering(); - - QWidget::leaveEvent(event); -} - -void KateIconBorder::mouseMoveEvent( QMouseEvent* e ) -{ - const KateTextLayout& t = m_viewInternal->yToKateTextLayout(e->y()); - if (t.isValid()) { - if ( positionToArea( e->pos() ) == FoldingMarkers) showDelayedBlock(t.line()); - else hideBlock(); - if ( positionToArea( e->pos() ) == AnnotationBorder ) - { - KTextEditor::AnnotationModel *model = m_view->annotationModel() ? - m_view->annotationModel() : m_doc->annotationModel(); - if (model) - { - m_hoveredAnnotationText = model->data( t.line(), Qt::DisplayRole ).toString(); - showAnnotationTooltip( t.line(), e->globalPos() ); - QTimer::singleShot( 0, this, SLOT(update()) ); - } - } - else - { - if( positionToArea( e->pos() ) == IconBorder ) - m_doc->requestMarkTooltip( t.line(), e->globalPos() ); - - m_hoveredAnnotationText.clear(); - hideAnnotationTooltip(); - QTimer::singleShot( 0, this, SLOT(update()) ); - } - if ( positionToArea( e->pos() ) != IconBorder ) - { - QPoint p = m_viewInternal->mapFromGlobal( e->globalPos() ); - QMouseEvent forward( QEvent::MouseMove, p, e->button(), e->buttons(), e->modifiers() ); - m_viewInternal->mouseMoveEvent( &forward ); - } - } - else - { - // remove hovering if it's still there - removeAnnotationHovering(); - } - - QWidget::mouseMoveEvent(e); -} - -void KateIconBorder::mouseReleaseEvent( QMouseEvent* e ) -{ - int cursorOnLine = m_viewInternal->yToKateTextLayout(e->y()).line(); - - if (cursorOnLine == m_lastClickedLine && - cursorOnLine <= m_doc->lastLine() ) - { - BorderArea area = positionToArea( e->pos() ); - if( area == IconBorder) { - if (e->button() == Qt::LeftButton) { - if( !m_doc->handleMarkClick(cursorOnLine) ) { - KateViewConfig *config = m_view->config(); - if( m_doc->editableMarks() & config->defaultMarkType() ) { - if( m_doc->mark( cursorOnLine ) & config->defaultMarkType() ) - m_doc->removeMark( cursorOnLine, config->defaultMarkType() ); - else - m_doc->addMark( cursorOnLine, config->defaultMarkType() ); - } else if (config->allowMarkMenu()) { - showMarkMenu( cursorOnLine, QCursor::pos() ); - } - } - } - else - if (e->button() == Qt::RightButton) { - showMarkMenu( cursorOnLine, QCursor::pos() ); - } - } - - if ( area == FoldingMarkers) { - KateLineInfo info; - m_doc->lineInfo(&info,cursorOnLine); - if ((info.startsVisibleBlock) || (info.startsInVisibleBlock)) { - emit toggleRegionVisibility(cursorOnLine); - } - } - - if ( area == AnnotationBorder ) { - if( e->button() == Qt::LeftButton && KGlobalSettings::singleClick() ) { - emit m_view->annotationActivated( m_view, cursorOnLine ); - } else if ( e->button() == Qt::RightButton ) { - showAnnotationMenu( cursorOnLine, e->globalPos() ); - } - } - } - - QMouseEvent forward( QEvent::MouseButtonRelease, - QPoint( 0, e->y() ), e->button(), e->buttons(),e->modifiers() ); - m_viewInternal->mouseReleaseEvent( &forward ); -} - -void KateIconBorder::mouseDoubleClickEvent( QMouseEvent* e ) -{ - int cursorOnLine = m_viewInternal->yToKateTextLayout(e->y()).line(); - - if (cursorOnLine == m_lastClickedLine && - cursorOnLine <= m_doc->lastLine() ) - { - BorderArea area = positionToArea( e->pos() ); - if( area == AnnotationBorder && !KGlobalSettings::singleClick() ) { - emit m_view->annotationActivated( m_view, cursorOnLine ); - } - } - QMouseEvent forward( QEvent::MouseButtonDblClick, - QPoint( 0, e->y() ), e->button(), e->buttons(),e->modifiers() ); - m_viewInternal->mouseDoubleClickEvent( &forward ); -} - -void KateIconBorder::showMarkMenu( uint line, const QPoint& pos ) -{ - if( !m_view->config()->allowMarkMenu() ) - return; - - if( m_doc->handleMarkContextMenu( line, pos ) ) - return; - - KMenu markMenu; - KMenu selectDefaultMark; - - QVector vec( 33 ); - int i=1; - - for( uint bit = 0; bit < 32; bit++ ) { - MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes)(1<editableMarks() & markType) ) - continue; - - QAction *mA; - QAction *dMA; - if( !m_doc->markDescription( markType ).isEmpty() ) { - mA=markMenu.addAction( m_doc->markDescription( markType )); - dMA=selectDefaultMark.addAction( m_doc->markDescription( markType )); - } else { - mA=markMenu.addAction( i18n("Mark Type %1", bit + 1 )); - dMA=selectDefaultMark.addAction( i18n("Mark Type %1", bit + 1 )); - } - mA->setData(i); - mA->setCheckable(true); - dMA->setData(i+100); - dMA->setCheckable(true); - if( m_doc->mark( line ) & markType ) - mA->setChecked(true ); - - if( markType & KateViewConfig::global()->defaultMarkType() ) - dMA->setChecked(true ); - - vec[i++] = markType; - } - - if( markMenu.actions().count() == 0 ) - return; - - if( markMenu.actions().count() > 1 ) - markMenu.addAction( i18n("Set Default Mark Type" ))->setMenu(&selectDefaultMark); - - QAction *rA = markMenu.exec( pos ); - if( !rA ) - return; - int result=rA->data().toInt(); - if ( result > 100) - { - KateViewConfig::global()->setDefaultMarkType (vec[result-100]); - // flush config, otherwise it isn't necessarily done - KConfigGroup cg(KGlobal::config(), "Kate View Defaults"); - KateViewConfig::global()->writeConfig(cg); - } - else - { - MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes) vec[result]; - if( m_doc->mark( line ) & markType ) { - m_doc->removeMark( line, markType ); - } else { - m_doc->addMark( line, markType ); - } - } -} - -void KateIconBorder::showAnnotationTooltip( int line, const QPoint& pos ) -{ - KTextEditor::AnnotationModel *model = m_view->annotationModel() ? - m_view->annotationModel() : m_doc->annotationModel(); - - if( model ) - { - QVariant data = model->data( line, Qt::ToolTipRole ); - QString tip = data.toString(); - if (!tip.isEmpty()) - QToolTip::showText( pos, data.toString(), this ); - } -} - - -int KateIconBorder::annotationLineWidth( int line ) -{ - KTextEditor::AnnotationModel *model = m_view->annotationModel() ? - m_view->annotationModel() : m_doc->annotationModel(); - - if( model ) - { - QVariant data = model->data( line, Qt::DisplayRole ); - return data.toString().length() * m_maxCharWidth + 8; - } - return 8; -} - -void KateIconBorder::updateAnnotationLine( int line ) -{ - if( annotationLineWidth(line) > m_annotationBorderWidth ) - { - m_annotationBorderWidth = annotationLineWidth(line); - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); - } -} - -void KateIconBorder::showAnnotationMenu( int line, const QPoint& pos) -{ - KMenu menu; - QAction a(i18n("Disable Annotation Bar"), &menu); - menu.addAction(&a); - emit m_view->annotationContextMenuAboutToShow( m_view, &menu, line ); - if (menu.exec(pos) == &a) - m_view->setAnnotationBorderVisible(false); -} - -void KateIconBorder::hideAnnotationTooltip() -{ - QToolTip::hideText(); -} - -void KateIconBorder::updateAnnotationBorderWidth( ) -{ - m_annotationBorderWidth = 6; - KTextEditor::AnnotationModel *model = m_view->annotationModel() ? - m_view->annotationModel() : m_doc->annotationModel(); - - if( model ) { - for( int i = 0; i < m_view->doc()->lines(); i++ ) { - int curwidth = annotationLineWidth( i ); - if( curwidth > m_annotationBorderWidth ) - m_annotationBorderWidth = curwidth; - } - } - - updateGeometry(); - - QTimer::singleShot( 0, this, SLOT(update()) ); -} - - - -void KateIconBorder::annotationModelChanged( KTextEditor::AnnotationModel * oldmodel, KTextEditor::AnnotationModel * newmodel ) -{ - if( oldmodel ) - { - oldmodel->disconnect( this ); - } - if( newmodel ) - { - connect( newmodel, SIGNAL(reset()), this, SLOT(updateAnnotationBorderWidth()) ); - connect( newmodel, SIGNAL(lineChanged( int )), this, SLOT(updateAnnotationLine( int )) ); - } - updateAnnotationBorderWidth(); -} - -//END KateIconBorder - -//BEGIN KateViewEncodingAction -// Acording to http://www.iana.org/assignments/ianacharset-mib -// the default/unknown mib value is 2. -#define MIB_DEFAULT 2 - -class KateViewEncodingAction::Private -{ - public: - Private(KateViewEncodingAction *parent) - : q(parent), - currentSubAction(0) - { - } - - void init(); - - void _k_subActionTriggered(QAction*); - - KateViewEncodingAction *q; - QAction *currentSubAction; -}; - -bool lessThanAction(KSelectAction *a, KSelectAction *b) -{ - return a->text() < b->text(); -} - -void KateViewEncodingAction::Private::init() -{ - QList actions; - - q->setToolBarMode(MenuMode); - - int i; - foreach(const QStringList &encodingsForScript, KGlobal::charsets()->encodingsByScript()) - { - KSelectAction* tmp = new KSelectAction(encodingsForScript.at(0),q); - - for (i=1; iaddAction(encodingsForScript.at(i)); - } - q->connect(tmp,SIGNAL(triggered(QAction*)),q,SLOT(_k_subActionTriggered(QAction*))); - //tmp->setCheckable(true); - actions << tmp; - } - qSort(actions.begin(), actions.end(), lessThanAction); - foreach (KSelectAction *action, actions) - q->addAction(action); -} - -void KateViewEncodingAction::Private::_k_subActionTriggered(QAction *action) -{ - if (currentSubAction==action) - return; - currentSubAction=action; - bool ok = false; - int mib = q->mibForName(action->text(), &ok); - if (ok) - { - emit q->KSelectAction::triggered(action->text()); - emit q->triggered(q->codecForMib(mib)); - } -} - -KateViewEncodingAction::KateViewEncodingAction(KateDocument *_doc, KateView *_view, const QString& text, QObject *parent) -: KSelectAction(text, parent), doc(_doc), view (_view), d(new Private(this)) -{ - d->init(); - - connect(menu(),SIGNAL(aboutToShow()),this,SLOT(slotAboutToShow())); - connect(this,SIGNAL(triggered(const QString&)),this,SLOT(setEncoding(const QString&))); -} - -KateViewEncodingAction::~KateViewEncodingAction() -{ - delete d; -} - -void KateViewEncodingAction::slotAboutToShow() -{ - setCurrentCodec(doc->config()->encoding()); -} - -void KateViewEncodingAction::setEncoding (const QString &e) -{ - doc->setEncoding(e); - - view->reloadFile(); - -} -int KateViewEncodingAction::mibForName(const QString &codecName, bool *ok) const -{ - // FIXME logic is good but code is ugly - - bool success = false; - int mib = MIB_DEFAULT; - KCharsets *charsets = KGlobal::charsets(); - - QTextCodec *codec = charsets->codecForName(codecName, success); - if (!success) - { - // Maybe we got a description name instead - codec = charsets->codecForName(charsets->encodingForName(codecName), success); - } - - if (codec) - mib = codec->mibEnum(); - - if (ok) - *ok = success; - - if (success) - return mib; - - kWarning() << "Invalid codec name: " << codecName; - return MIB_DEFAULT; -} - -QTextCodec *KateViewEncodingAction::codecForMib(int mib) const -{ - if (mib == MIB_DEFAULT) - { - // FIXME offer to change the default codec - return QTextCodec::codecForLocale(); - } - else - return QTextCodec::codecForMib(mib); -} - -QTextCodec *KateViewEncodingAction::currentCodec() const -{ - return codecForMib(currentCodecMib()); -} - -bool KateViewEncodingAction::setCurrentCodec( QTextCodec *codec ) -{ - disconnect(this,SIGNAL(triggered(const QString&)),this,SLOT(setEncoding(const QString&))); - - int i,j; - for (i=0;imenu()) - { - for (j=0;jmenu()->actions().size();++j) - { - if (!j && !actions().at(i)->menu()->actions().at(j)->data().isNull()) - continue; - if (actions().at(i)->menu()->actions().at(j)->isSeparator()) - continue; - - if (codec==KGlobal::charsets()->codecForName(actions().at(i)->menu()->actions().at(j)->text())) - { - d->currentSubAction=actions().at(i)->menu()->actions().at(j); - d->currentSubAction->setChecked(true); - } - else - actions().at(i)->menu()->actions().at(j)->setChecked (false); - } - } - } - - connect(this,SIGNAL(triggered(const QString&)),this,SLOT(setEncoding(const QString&))); - return true; -} - -QString KateViewEncodingAction::currentCodecName() const -{ - return d->currentSubAction->text(); -} - -bool KateViewEncodingAction::setCurrentCodec( const QString &codecName ) -{ - return setCurrentCodec(KGlobal::charsets()->codecForName(codecName)); -} - -int KateViewEncodingAction::currentCodecMib() const -{ - return mibForName(currentCodecName()); -} - -bool KateViewEncodingAction::setCurrentCodec( int mib ) -{ - return setCurrentCodec(codecForMib(mib)); -} -//END KateViewEncodingAction - -//BEGIN KateViewBar related classes - -KateViewBarWidget::KateViewBarWidget (bool addCloseButton, QWidget *parent) - : QWidget (parent) -{ - QHBoxLayout *layout = new QHBoxLayout (this); - - // NOTE: Here be cosmetics. - layout->setMargin(0); - - // hide button - if (addCloseButton) { - QToolButton *hideButton = new QToolButton(this); - hideButton->setAutoRaise(true); - hideButton->setIcon(KIcon("dialog-close")); - connect(hideButton, SIGNAL(clicked()), SIGNAL(hideMe())); - layout->addWidget(hideButton); - layout->setAlignment( hideButton, Qt::AlignLeft|Qt::AlignTop ); - } - - // widget to be used as parent for the real content - m_centralWidget = new QWidget (this); - layout->addWidget(m_centralWidget); - - setLayout(layout); - setFocusProxy(m_centralWidget); -} - - -KateViewBar::KateViewBar (bool external,KTextEditor::ViewBarContainer::Position pos,QWidget *parent, KateView *view) - : QWidget (parent), m_external(external), m_pos(pos),m_view (view), m_permanentBarWidget(0) - -{ - m_layout = new QVBoxLayout(this); - m_stack = new QStackedWidget(this); - m_layout->addWidget(m_stack); - m_layout->setMargin(0); - - m_stack->hide(); - hide (); -} - -void KateViewBar::addBarWidget (KateViewBarWidget *newBarWidget) -{ - if (hasBarWidget(newBarWidget)) { - kDebug(13025) << "this bar widget is already added"; - return; - } - // add new widget, invisible... - newBarWidget->hide(); - m_stack->addWidget (newBarWidget); - connect(newBarWidget, SIGNAL(hideMe()), SLOT(hideCurrentBarWidget())); - - kDebug(13025)<<"add barwidget " << newBarWidget; -} - -void KateViewBar::removeBarWidget (KateViewBarWidget *barWidget) -{ - m_stack->removeWidget(barWidget); -} - -void KateViewBar::addPermanentBarWidget (KateViewBarWidget *barWidget) -{ - // remove old widget from layout (if any) - if (m_permanentBarWidget) { - m_permanentBarWidget->hide(); - m_layout->removeWidget(m_permanentBarWidget); - } - - m_layout->addWidget(barWidget, 0, Qt::AlignBottom); - m_permanentBarWidget = barWidget; - m_permanentBarWidget->show(); - - setViewBarVisible(true); -} - -void KateViewBar::removePermanentBarWidget (KateViewBarWidget *barWidget) -{ - if (m_permanentBarWidget != barWidget) { - kDebug(13025) << "no such permanent widget exists in bar"; - return; - } - - if (!m_permanentBarWidget) - return; - - m_permanentBarWidget->hide(); - m_layout->removeWidget(m_permanentBarWidget); - m_permanentBarWidget = 0; - - if (!m_stack->isVisible()) { - setViewBarVisible(false); - } -} - -bool KateViewBar::hasPermanentWidget (KateViewBarWidget *barWidget ) const -{ - return (m_permanentBarWidget == barWidget); -} - -void KateViewBar::showBarWidget (KateViewBarWidget *barWidget) -{ - Q_ASSERT(barWidget != 0); - - KateViewBarWidget *current=qobject_cast(m_stack->currentWidget()); - current->switched(); - // raise correct widget - m_stack->setCurrentWidget (barWidget); - barWidget->show(); - m_stack->show(); - - // if we have any permanent widget, bar is always visible, - // no need to show it - if (!m_permanentBarWidget) { - setViewBarVisible(true); - } -} - -bool KateViewBar::hasBarWidget(KateViewBarWidget* barWidget) const -{ - return m_stack->indexOf(barWidget) != -1; -} - -void KateViewBar::hideCurrentBarWidget () -{ - KateViewBarWidget *current=qobject_cast(m_stack->currentWidget()); - if (current) { - current->closed(); - } - m_stack->hide(); - - // if we have any permanent widget, bar is always visible, - // no need to hide it - if (!m_permanentBarWidget) { - setViewBarVisible(false); - } - - m_view->setFocus(); - kDebug(13025)<<"hide barwidget"; -} - -void KateViewBar::setViewBarVisible (bool visible) -{ - if (m_external) { - KTextEditor::ViewBarContainer *viewBarContainer=qobject_cast( KateGlobal::self()->container() ); - if (viewBarContainer) { - if (visible) { - viewBarContainer->showViewBarForView(m_view,m_pos); - } else { - viewBarContainer->hideViewBarForView(m_view,m_pos); - } - } - } else { - setVisible (visible); - } -} - -void KateViewBar::keyPressEvent(QKeyEvent* event) -{ - if (event->key() == Qt::Key_Escape) { - hideCurrentBarWidget(); - return; - } - QWidget::keyPressEvent(event); - -} - -void KateViewBar::hideEvent(QHideEvent* event) -{ - Q_UNUSED(event); -// if (!event->spontaneous()) -// m_view->setFocus(); -} - -//END KateViewBar related classes - -#include "kateviewhelpers.moc" - -// kate: space-indent on; indent-width 2; replace-tabs on; - diff --git a/part/view/kateviewhelpers.h b/part/view/kateviewhelpers.h deleted file mode 100644 index 44d7139..0000000 --- a/part/view/kateviewhelpers.h +++ /dev/null @@ -1,413 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 John Firebaugh - Copyright (C) 2001 Anders Lund - Copyright (C) 2001 Christoph Cullmann - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef __KATE_VIEW_HELPERS_H__ -#define __KATE_VIEW_HELPERS_H__ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -class KateDocument; -class KateView; -class KateViewInternal; - -#define MAXFOLDINGCOLORS 16 - -class KateLineInfo; - -namespace KTextEditor { - class Command; - class SmartRange; - class AnnotationModel; - class MovingRange; -} - -class QTimer; -class QVBoxLayout; - -/** - * This class is required because QScrollBar's sliderMoved() signal is - * really supposed to be a sliderDragged() signal... so this way we can capture - * MMB slider moves as well - * - * Also, it adds some useful indicators on the scrollbar. - */ -class KateScrollBar : public QScrollBar -{ - Q_OBJECT - - public: - KateScrollBar(Qt::Orientation orientation, class KateViewInternal *parent); - - inline bool showMarks() { return m_showMarks; } - inline void setShowMarks(bool b) { m_showMarks = b; update(); } - - Q_SIGNALS: - void sliderMMBMoved(int value); - - protected: - virtual void mousePressEvent(QMouseEvent* e); - virtual void mouseReleaseEvent(QMouseEvent* e); - virtual void mouseMoveEvent (QMouseEvent* e); - virtual void paintEvent(QPaintEvent *); - virtual void resizeEvent(QResizeEvent *); - virtual void styleChange(QStyle &oldStyle); - virtual void sliderChange ( SliderChange change ); - virtual void wheelEvent(QWheelEvent *e); - - protected Q_SLOTS: - void sliderMaybeMoved(int value); - void marksChanged(); - - private: - void redrawMarks(); - void recomputeMarksPositions(); - - bool m_middleMouseDown; - - KateView *m_view; - KateDocument *m_doc; - class KateViewInternal *m_viewInternal; - - QHash m_lines; - - bool m_showMarks; -}; - -class KateIconBorder : public QWidget -{ - Q_OBJECT - - public: - KateIconBorder( KateViewInternal* internalView, QWidget *parent ); - virtual ~KateIconBorder(); - // VERY IMPORTANT ;) - virtual QSize sizeHint() const; - - void updateFont(); - int lineNumberWidth() const; - - void setIconBorderOn( bool enable ); - void setLineNumbersOn( bool enable ); - void setAnnotationBorderOn( bool enable ); - void setDynWrapIndicators(int state ); - int dynWrapIndicators() const { return m_dynWrapIndicators; } - bool dynWrapIndicatorsOn() const { return m_dynWrapIndicatorsOn; } - void setFoldingMarkersOn( bool enable ); - void toggleIconBorder() { setIconBorderOn( !iconBorderOn() ); } - void toggleLineNumbers() { setLineNumbersOn( !lineNumbersOn() ); } - void toggleFoldingMarkers() { setFoldingMarkersOn( !foldingMarkersOn() ); } - inline bool iconBorderOn() const { return m_iconBorderOn; } - inline bool lineNumbersOn() const { return m_lineNumbersOn; } - inline bool foldingMarkersOn() const { return m_foldingMarkersOn; } - inline bool annotationBorderOn() const { return m_annotationBorderOn; } - - enum BorderArea { None, LineNumbers, IconBorder, FoldingMarkers, AnnotationBorder }; - BorderArea positionToArea( const QPoint& ) const; - - Q_SIGNALS: - void toggleRegionVisibility( unsigned int ); - public Q_SLOTS: - void updateAnnotationBorderWidth(); - void updateAnnotationLine( int line ); - void annotationModelChanged( KTextEditor::AnnotationModel* oldmodel, KTextEditor::AnnotationModel* newmodel ); - - private: - void paintEvent( QPaintEvent* ); - void paintBorder (int x, int y, int width, int height); - - void mousePressEvent( QMouseEvent* ); - void mouseMoveEvent( QMouseEvent* ); - void mouseReleaseEvent( QMouseEvent* ); - void mouseDoubleClickEvent( QMouseEvent* ); - void leaveEvent(QEvent *event); - - void showMarkMenu( uint line, const QPoint& pos ); - - void showAnnotationTooltip( int line, const QPoint& pos ); - void hideAnnotationTooltip(); - void removeAnnotationHovering(); - void showAnnotationMenu( int line, const QPoint& pos); - int annotationLineWidth( int line ); - - KateView *m_view; - KateDocument *m_doc; - KateViewInternal *m_viewInternal; - - bool m_iconBorderOn:1; - bool m_lineNumbersOn:1; - bool m_foldingMarkersOn:1; - bool m_dynWrapIndicatorsOn:1; - bool m_annotationBorderOn:1; - int m_dynWrapIndicators; - - int m_lastClickedLine; - - int m_cachedLNWidth; - - int m_maxCharWidth; - int iconPaneWidth; - int m_annotationBorderWidth; - - mutable QPixmap m_arrow; - mutable QColor m_oldBackgroundColor; - - - KTextEditor::MovingRange *m_foldingRange; - int m_nextHighlightBlock; - int m_currentBlockLine; - QTimer m_delayFoldingHlTimer; - void showDelayedBlock(int line); - void hideBlock(); - - private Q_SLOTS: - void showBlock(); - - private: - QColor m_foldingColors[MAXFOLDINGCOLORS]; - QBrush foldingColor(KateLineInfo *, int,bool solid); - QString m_hoveredAnnotationText; - - void initializeFoldingColors(); -}; - -class KateViewEncodingAction: public KSelectAction -{ - Q_OBJECT - - Q_PROPERTY(QString codecName READ currentCodecName WRITE setCurrentCodec) - Q_PROPERTY(int codecMib READ currentCodecMib) - - public: - KateViewEncodingAction(KateDocument *_doc, KateView *_view, const QString& text, QObject *parent); - - ~KateViewEncodingAction(); - - int mibForName(const QString &codecName, bool *ok = 0) const; - QTextCodec *codecForMib(int mib) const; - - QTextCodec *currentCodec() const; - bool setCurrentCodec(QTextCodec *codec); - - QString currentCodecName() const; - bool setCurrentCodec(const QString &codecName); - - int currentCodecMib() const; - bool setCurrentCodec(int mib); - - Q_SIGNALS: - /** - * Specific (proper) codec was selected - */ - void triggered(QTextCodec *codec); - - private: - KateDocument* doc; - KateView *view; - class Private; - Private* const d; - Q_PRIVATE_SLOT( d, void _k_subActionTriggered(QAction*) ) - - private Q_SLOTS: - void setEncoding (const QString &e); - void slotAboutToShow(); -}; - -class KateViewBar; - -class KateViewBarWidget : public QWidget -{ - Q_OBJECT - - public: - explicit KateViewBarWidget (bool addCloseButton, QWidget* parent = 0); - - virtual void closed(){}; - virtual void switched(){}; - protected: - /** - * @return widget that should be used to add controls to bar widget - */ - QWidget *centralWidget() { return m_centralWidget; } - - signals: - void hideMe(); - - private: - QWidget *m_centralWidget; -}; - -class KateViewBar : public QWidget -{ - Q_OBJECT - - public: - KateViewBar (bool external, - KTextEditor::ViewBarContainer::Position pos, - QWidget *parent, - KateView *view); - - - /** - * Adds a widget to this viewbar. - * Widget is initially invisible, you should call showBarWidget, to show it. - * Several widgets can be added to the bar, but only one can be visible - */ - void addBarWidget (KateViewBarWidget *newBarWidget); - - /** - * Removes a widget from this viewbar. - * Removing a widget makes sense if it takes a lot of space vertically, - * because we use a QStackedWidget to maintain the same height for all - * widgets in the viewbar. - */ - void removeBarWidget (KateViewBarWidget *barWidget); - - /** - * @return if viewbar has widget @p barWidget - */ - bool hasBarWidget(KateViewBarWidget* barWidget) const; - - /** - * Shows barWidget that was previously added with addBarWidget. - * @see hideCurrentBarWidget - */ - void showBarWidget (KateViewBarWidget *barWidget); - - /** - * Adds widget that will be always shown in the viewbar. - * After adding permanent widget viewbar is immediately shown. - * ViewBar with permanent widget won't hide itself - * until permanent widget is removed. - * OTOH showing/hiding regular barWidgets will work as usual - * (they will be shown above permanent widget) - * - * If permanent widget already exists, new one replaces old one - * Old widget is not deleted, caller can do it if it wishes - */ - void addPermanentBarWidget (KateViewBarWidget *barWidget); - - /** - * Removes permanent bar widget from viewbar. - * If no other viewbar widgets are shown, viewbar gets hidden. - * - * barWidget is not deleted, caller must do it if it wishes - */ - void removePermanentBarWidget (KateViewBarWidget *barWidget); - - /** - * @return if viewbar has permanent widget @p barWidget - */ - bool hasPermanentWidget (KateViewBarWidget *barWidget) const; - - public Q_SLOTS: - /** - * Hides currently shown bar widget - */ - void hideCurrentBarWidget(); - - protected: - virtual void keyPressEvent(QKeyEvent* event); - virtual void hideEvent(QHideEvent* event); - - private: - /** - * Shows or hides whole viewbar - */ - void setViewBarVisible(bool visible); - - bool m_external; - KTextEditor::ViewBarContainer::Position m_pos; - - private: - KateView *m_view; - QStackedWidget *m_stack; - KateViewBarWidget *m_permanentBarWidget; - QVBoxLayout *m_layout; -}; - -class KateCommandLineBar : public KateViewBarWidget -{ - public: - explicit KateCommandLineBar(KateView *view, QWidget *parent = 0); - ~KateCommandLineBar(); - - void setText(const QString &text, bool selected = true); - void execute(const QString &text); - - private: - class KateCmdLineEdit *m_lineEdit; -}; - -class KateCmdLineEdit : public KLineEdit -{ - Q_OBJECT - - public: - KateCmdLineEdit (KateCommandLineBar *bar, KateView *view); - virtual bool event(QEvent *e); - - void hideEvent (QHideEvent *e); - - signals: - void hideRequested(); - - public Q_SLOTS: - void slotReturnPressed ( const QString& cmd ); - - private Q_SLOTS: - void hideLineEdit(); - - protected: - void focusInEvent ( QFocusEvent *ev ); - void keyPressEvent( QKeyEvent *ev ); - - private: - void fromHistory( bool up ); - QString helptext( const QPoint & ) const; - - KateView *m_view; - KateCommandLineBar *m_bar; - bool m_msgMode; - QString m_oldText; - uint m_histpos; ///< position in the history - uint m_cmdend; ///< the point where a command ends in the text, if we have a valid one. - KTextEditor::Command *m_command; ///< For completing flags/args and interactiveness - class KateCmdLnWhatsThis *m_help; - QRegExp m_cmdRange; - QRegExp m_cmdExpr; - QRegExp m_gotoLine; - QTimer *m_hideTimer; -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/view/kateviewinternal.cpp b/part/view/kateviewinternal.cpp deleted file mode 100644 index 3483633..0000000 --- a/part/view/kateviewinternal.cpp +++ /dev/null @@ -1,3517 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002 John Firebaugh - Copyright (C) 2002 Joseph Wenninger - Copyright (C) 2002,2003 Christoph Cullmann - Copyright (C) 2002-2007 Hamish Rodda - Copyright (C) 2003 Anakim Border - Copyright (C) 2007 Mirko Stocker - Copyright (C) 2007 Matthew Woehlke - Copyright (C) 2008 Erlend Hamberg - - Based on: - KWriteView : Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "kateviewinternal.h" -#include "kateviewinternal.moc" - -#include "kateview.h" -#include "katecodefolding.h" -#include "kateviewhelpers.h" -#include "katehighlight.h" -#include "katebuffer.h" -#include "katerenderer.h" -#include "kateconfig.h" -#include "katelayoutcache.h" -#include "katecompletionwidget.h" -#include "kateviinputmodemanager.h" -#include "katevimodebar.h" -#include "katesearchbar.h" -#include "spellcheck/spellingmenu.h" -#include "kateviewaccessible.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -static const bool debugPainting = false; - -KateViewInternal::KateViewInternal(KateView *view) - : QWidget (view) - , editSessionNumber (0) - , editIsRunning (false) - , m_view (view) - , m_cursor(doc()->buffer(), KTextEditor::Cursor(0, 0), Kate::TextCursor::MoveOnInsert) - , m_mouse() - , m_possibleTripleClick (false) - , m_completionItemExpanded (false) - , m_bm(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) - , m_bmStart(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) - , m_bmEnd(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) - , m_dummy (0) - - // stay on cursor will avoid that the view scroll around on press return at beginning - , m_startPos (doc()->buffer(), KTextEditor::Cursor (0, 0), Kate::TextCursor::StayOnInsert) - - , m_visibleLineCount(0) - , m_madeVisible(false) - , m_shiftKeyPressed (false) - , m_autoCenterLines(0) - , m_minLinesVisible(0) - , m_selChangedByUser (false) - , m_selectAnchor (-1, -1) - , m_selectionMode( Default ) - , m_layoutCache(new KateLayoutCache(renderer(), this)) - , m_preserveX(false) - , m_preservedX(0) - , m_updatingView(true) - , m_cachedMaxStartPos(-1, -1) - , m_dragScrollTimer(this) - , m_scrollTimer (this) - , m_cursorTimer (this) - , m_textHintTimer (this) - , m_textHintEnabled(false) - , m_textHintMouseX(-1) - , m_textHintMouseY(-1) - , m_imPreeditRange(0) - , m_smartDirty(false) - , m_viInputMode(false) - , m_viInputModeManager (0) -{ - setMinimumSize (0,0); - setAttribute(Qt::WA_OpaquePaintEvent); - setAttribute(Qt::WA_InputMethodEnabled); - - // invalidate m_selectionCached.start(), or keyb selection is screwed initially - m_selectionCached = KTextEditor::Range::invalid(); - - // bracket markers are only for this view and should not be printed - m_bm->setView (m_view); - m_bmStart->setView (m_view); - m_bmEnd->setView (m_view); - m_bm->setAttributeOnlyForViews (true); - m_bmStart->setAttributeOnlyForViews (true); - m_bmEnd->setAttributeOnlyForViews (true); - - // use z depth defined in moving ranges interface - m_bm->setZDepth (-1000.0); - m_bmStart->setZDepth (-1000.0); - m_bmEnd->setZDepth (-1000.0); - - // update mark attributes - updateBracketMarkAttributes(); - - // - // scrollbar for lines - // - m_lineScroll = new KateScrollBar(Qt::Vertical, this); - m_lineScroll->show(); - m_lineScroll->setTracking (true); - m_lineScroll->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Expanding ); - - // bottom corner box - m_dummy = new QWidget(m_view); - m_dummy->setFixedSize(m_lineScroll->width(), m_lineScroll->width()); - m_dummy->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); - - if (m_view->dynWordWrap()) - m_dummy->hide(); - else - m_dummy->show(); - - cache()->setWrap(m_view->dynWordWrap()); - - // Hijack the line scroller's controls, so we can scroll nicely for word-wrap - connect(m_lineScroll, SIGNAL(actionTriggered(int)), SLOT(scrollAction(int))); - connect(m_lineScroll, SIGNAL(sliderMoved(int)), SLOT(scrollLines(int))); - connect(m_lineScroll, SIGNAL(sliderMMBMoved(int)), SLOT(scrollLines(int))); - connect(m_lineScroll, SIGNAL(valueChanged(int)), SLOT(scrollLines(int))); - - // catch wheel events, completing the hijack - //m_lineScroll->installEventFilter(this); - - // - // scrollbar for columns - // - m_columnScroll = new QScrollBar(Qt::Horizontal,m_view); - - if (m_view->dynWordWrap()) - m_columnScroll->hide(); - else - m_columnScroll->show(); - - m_columnScroll->setTracking(true); - m_startX = 0; - - connect(m_columnScroll, SIGNAL(valueChanged(int)), SLOT(scrollColumns(int))); - - // - // iconborder ;) - // - m_leftBorder = new KateIconBorder( this, m_view ); - m_leftBorder->show (); - - connect( m_leftBorder, SIGNAL(toggleRegionVisibility(unsigned int)), - doc()->foldingTree(), SLOT(toggleRegionVisibility(unsigned int))); - - connect( doc()->foldingTree(), SIGNAL(regionVisibilityChangedAt(unsigned int,bool)), - this, SLOT(slotRegionVisibilityChangedAt(unsigned int,bool))); - connect( doc(), SIGNAL(codeFoldingUpdated()), - this, SLOT(slotCodeFoldingChanged()) ); - - m_displayCursor.setPosition(0, 0); - - setAcceptDrops( true ); - - // event filter - installEventFilter(this); - - // set initial cursor - m_mouseCursor = Qt::IBeamCursor; - setCursor(m_mouseCursor); - - // call mouseMoveEvent also if no mouse button is pressed - setMouseTracking(true); - - m_dragInfo.state = diNone; - - // timers - connect( &m_dragScrollTimer, SIGNAL( timeout() ), - this, SLOT( doDragScroll() ) ); - - connect( &m_scrollTimer, SIGNAL( timeout() ), - this, SLOT( scrollTimeout() ) ); - - connect( &m_cursorTimer, SIGNAL( timeout() ), - this, SLOT( cursorTimeout() ) ); - - connect( &m_textHintTimer, SIGNAL( timeout() ), - this, SLOT( textHintTimeout() ) ); - - // selection changed to set anchor - connect( m_view, SIGNAL( selectionChanged(KTextEditor::View*) ), - this, SLOT( viewSelectionChanged() ) ); - - QAccessible::installFactory(accessibleInterfaceFactory); - - // update is called in KateView, after construction and layout is over - // but before any other kateviewinternal call -} - -KateViewInternal::~KateViewInternal () -{ - QAccessible::removeFactory(accessibleInterfaceFactory); - - // kill preedit ranges - delete m_imPreeditRange; - qDeleteAll (m_imPreeditRangeChildren); - - delete m_viInputModeManager; - - // delete bracket markers - delete m_bm; - delete m_bmStart; - delete m_bmEnd; -} - -void KateViewInternal::prepareForDynWrapChange() -{ - // Which is the current view line? - m_wrapChangeViewLine = cache()->displayViewLine(m_displayCursor, true); -} - -void KateViewInternal::dynWrapChanged() -{ - if (m_view->dynWordWrap()) - { - m_columnScroll->hide(); - m_dummy->hide(); - - } - else - { - // column scrollbar + bottom corner box - m_columnScroll->show(); - m_dummy->show(); - } - - cache()->setWrap(m_view->dynWordWrap()); - updateView(); - - if (m_view->dynWordWrap()) - scrollColumns(0); - - // Determine where the cursor should be to get the cursor on the same view line - if (m_wrapChangeViewLine != -1) { - KTextEditor::Cursor newStart = viewLineOffset(m_displayCursor, -m_wrapChangeViewLine); - makeVisible(newStart, newStart.column(), true); - - } else { - update(); - } -} - -KTextEditor::Cursor KateViewInternal::endPos() const -{ - // Hrm, no lines laid out at all?? - if (!cache()->viewCacheLineCount()) - return KTextEditor::Cursor(); - - for (int i = qMin(linesDisplayed() - 1, cache()->viewCacheLineCount() - 1); i >= 0; i--) { - const KateTextLayout& thisLine = cache()->viewLine(i); - - if (thisLine.line() == -1) continue; - - if (thisLine.virtualLine() >= doc()->numVisLines()) { - // Cache is too out of date - return KTextEditor::Cursor(doc()->numVisLines() - 1, doc()->lineLength(doc()->getRealLine(doc()->numVisLines() - 1))); - } - - return KTextEditor::Cursor(thisLine.virtualLine(), thisLine.wrap() ? thisLine.endCol() - 1 : thisLine.endCol()); - } - - kDebug(13030) << "WARNING: could not find a lineRange at all"; - return KTextEditor::Cursor(-1, -1); -} - -int KateViewInternal::endLine() const -{ - return endPos().line(); -} - -KateTextLayout KateViewInternal::yToKateTextLayout(int y) const -{ - if (y < 0 || y > size().height()) - return KateTextLayout::invalid(); - - int range = y / renderer()->lineHeight(); - - // lineRanges is always bigger than 0, after the initial updateView call - if (range >= 0 && range < cache()->viewCacheLineCount()) - return cache()->viewLine(range); - - return KateTextLayout::invalid(); -} - -int KateViewInternal::lineToY(int viewLine) const -{ - return (viewLine-startLine()) * renderer()->lineHeight(); -} - -void KateViewInternal::slotIncFontSizes() -{ - renderer()->increaseFontSizes(); -} - -void KateViewInternal::slotDecFontSizes() -{ - renderer()->decreaseFontSizes(); -} - -/** - * Line is the real line number to scroll to. - */ -void KateViewInternal::scrollLines ( int line ) -{ - KTextEditor::Cursor newPos(line, 0); - scrollPos(newPos); -} - -// This can scroll less than one true line -void KateViewInternal::scrollViewLines(int offset) -{ - KTextEditor::Cursor c = viewLineOffset(startPos(), offset); - scrollPos(c); - - bool blocked = m_lineScroll->blockSignals(true); - m_lineScroll->setValue(startLine()); - m_lineScroll->blockSignals(blocked); -} - -void KateViewInternal::scrollAction( int action ) -{ - switch (action) { - case QAbstractSlider::SliderSingleStepAdd: - scrollNextLine(); - break; - - case QAbstractSlider::SliderSingleStepSub: - scrollPrevLine(); - break; - - case QAbstractSlider::SliderPageStepAdd: - scrollNextPage(); - break; - - case QAbstractSlider::SliderPageStepSub: - scrollPrevPage(); - break; - - case QAbstractSlider::SliderToMinimum: - top_home(); - break; - - case QAbstractSlider::SliderToMaximum: - bottom_end(); - break; - } -} - -void KateViewInternal::scrollNextPage() -{ - scrollViewLines(qMax( linesDisplayed() - 1, 0 )); -} - -void KateViewInternal::scrollPrevPage() -{ - scrollViewLines(-qMax( linesDisplayed() - 1, 0 )); -} - -void KateViewInternal::scrollPrevLine() -{ - scrollViewLines(-1); -} - -void KateViewInternal::scrollNextLine() -{ - scrollViewLines(1); -} - -KTextEditor::Cursor KateViewInternal::maxStartPos(bool changed) -{ - cache()->setAcceptDirtyLayouts(true); - - if (m_cachedMaxStartPos.line() == -1 || changed) - { - KTextEditor::Cursor end(doc()->numVisLines() - 1, doc()->lineLength(doc()->getRealLine(doc()->numVisLines() - 1))); - - if (m_view->config()->scrollPastEnd()) - m_cachedMaxStartPos = viewLineOffset(end, -m_minLinesVisible); - else - m_cachedMaxStartPos = viewLineOffset(end, -(linesDisplayed() - 1)); - } - - cache()->setAcceptDirtyLayouts(false); - - return m_cachedMaxStartPos; -} - -// c is a virtual cursor -void KateViewInternal::scrollPos(KTextEditor::Cursor& c, bool force, bool calledExternally) -{ - if (!force && ((!m_view->dynWordWrap() && c.line() == startLine()) || c == startPos())) - return; - - if (c.line() < 0) - c.setLine(0); - - KTextEditor::Cursor limit = maxStartPos(); - if (c > limit) { - c = limit; - - // Re-check we're not just scrolling to the same place - if (!force && ((!m_view->dynWordWrap() && c.line() == startLine()) || c == startPos())) - return; - } - - int viewLinesScrolled = 0; - - // only calculate if this is really used and useful, could be wrong here, please recheck - // for larger scrolls this makes 2-4 seconds difference on my xeon with dyn. word wrap on - // try to get it really working ;) - bool viewLinesScrolledUsable = !force - && (c.line() >= startLine() - linesDisplayed() - 1) - && (c.line() <= endLine() + linesDisplayed() + 1); - - if (viewLinesScrolledUsable) { - viewLinesScrolled = cache()->displayViewLine(c); - } - - m_startPos.setPosition(c); - - // set false here but reversed if we return to makeVisible - m_madeVisible = false; - - if (viewLinesScrolledUsable) - { - int lines = linesDisplayed(); - if (doc()->numVisLines() < lines) { - KTextEditor::Cursor end(doc()->numVisLines() - 1, doc()->lineLength(doc()->getRealLine(doc()->numVisLines() - 1))); - lines = qMin(linesDisplayed(), cache()->displayViewLine(end) + 1); - } - - Q_ASSERT(lines >= 0); - - if (!calledExternally && qAbs(viewLinesScrolled) < lines) - { - updateView(false, viewLinesScrolled); - - int scrollHeight = -(viewLinesScrolled * (int)renderer()->lineHeight()); - - scroll(0, scrollHeight); - m_leftBorder->scroll(0, scrollHeight); - - emit m_view->verticalScrollPositionChanged( m_view, c ); - emit m_view->displayRangeChanged(m_view); - return; - } - } - - updateView(); - update(); - m_leftBorder->update(); - emit m_view->verticalScrollPositionChanged( m_view, c ); - emit m_view->displayRangeChanged(m_view); -} - -void KateViewInternal::scrollColumns ( int x ) -{ - if (x == m_startX) - return; - - if (x < 0) - x = 0; - - int dx = m_startX - x; - m_startX = x; - - if (qAbs(dx) < width()) - scroll(dx, 0); - else - update(); - - emit m_view->horizontalScrollPositionChanged( m_view ); - emit m_view->displayRangeChanged(m_view); - - bool blocked = m_columnScroll->blockSignals(true); - m_columnScroll->setValue(m_startX); - m_columnScroll->blockSignals(blocked); -} - -// If changed is true, the lines that have been set dirty have been updated. -void KateViewInternal::updateView(bool changed, int viewLinesScrolled) -{ - doUpdateView(changed, viewLinesScrolled); - - if (changed) - updateDirty(); -} - -void KateViewInternal::doUpdateView(bool changed, int viewLinesScrolled) -{ - if(!isVisible() && !viewLinesScrolled ) - return; //When this view is not visible, don't do anything - - m_updatingView = true; - - bool blocked = m_lineScroll->blockSignals(true); - - if (width() != cache()->viewWidth()) { - cache()->setViewWidth(width()); - changed = true; - } - - /* It was observed that height() could be negative here -- - when the main Kate view has 0 as size (during creation), - and there frame arount KateViewInternal. In which - case we'd set the view cache to 0 (or less!) lines, and - start allocating huge chunks of data, later. */ - int newSize = (qMax (0, height()) / renderer()->lineHeight()) + 1; - cache()->updateViewCache(startPos(), newSize, viewLinesScrolled); - m_visibleLineCount = newSize; - - KTextEditor::Cursor maxStart = maxStartPos(changed); - int maxLineScrollRange = maxStart.line(); - if (m_view->dynWordWrap() && maxStart.column() != 0) - maxLineScrollRange++; - m_lineScroll->setRange(0, maxLineScrollRange); - - m_lineScroll->setValue(startPos().line()); - m_lineScroll->setSingleStep(1); - m_lineScroll->setPageStep(qMax (0, height()) / renderer()->lineHeight()); - m_lineScroll->blockSignals(blocked); - - if (!m_view->dynWordWrap()) - { - int max = maxLen(startLine()) - width(); - if (max < 0) - max = 0; - - // if we lose the ability to scroll horizontally, move view to the far-left - if (max == 0) - { - scrollColumns(0); - } - - blocked = m_columnScroll->blockSignals(true); - - // disable scrollbar - m_columnScroll->setDisabled (max == 0); - - m_columnScroll->setRange(0, max); - - m_columnScroll->setValue(m_startX); - - // Approximate linescroll - m_columnScroll->setSingleStep(renderer()->config()->fontMetrics().width('a')); - m_columnScroll->setPageStep(width()); - - m_columnScroll->blockSignals(blocked); - } - - if (m_smartDirty) - m_smartDirty = false; - - m_updatingView = false; -} - -/** - * this function ensures a certain location is visible on the screen. - * if endCol is -1, ignore making the columns visible. - */ -void KateViewInternal::makeVisible (const KTextEditor::Cursor& c, int endCol, bool force, bool center, bool calledExternally) -{ - //kDebug(13030) << "MakeVisible start " << startPos() << " end " << endPos() << " -> request: " << c;// , new start [" << scroll.line << "," << scroll.col << "] lines " << (linesDisplayed() - 1) << " height " << height(); - // if the line is in a folded region, unfold all the way up - //if ( doc()->foldingTree()->findNodeForLine( c.line )->visible ) - // kDebug(13030)<<"line ("< endPos())) - { - KTextEditor::Cursor scroll = viewLineOffset(c, -int(linesDisplayed()) / 2); - scrollPos(scroll, false, calledExternally); - } - else if ( c > viewLineOffset(startPos(), linesDisplayed() - m_minLinesVisible - 1) ) - { - KTextEditor::Cursor scroll = viewLineOffset(c, -(linesDisplayed() - m_minLinesVisible - 1)); - scrollPos(scroll, false, calledExternally); - } - else if ( c < viewLineOffset(startPos(), m_minLinesVisible) ) - { - KTextEditor::Cursor scroll = viewLineOffset(c, -m_minLinesVisible); - scrollPos(scroll, false, calledExternally); - } - else - { - // Check to see that we're not showing blank lines - KTextEditor::Cursor max = maxStartPos(); - if (startPos() > max) { - scrollPos(max, max.column(), calledExternally); - } - } - - if (!m_view->dynWordWrap() && (endCol != -1 || m_view->wrapCursor())) - { - KTextEditor::Cursor rc = toRealCursor(c); - int sX = renderer()->cursorToX(cache()->textLayout(rc), rc, !m_view->wrapCursor()); - - int sXborder = sX-8; - if (sXborder < 0) - sXborder = 0; - - if (sX < m_startX) - scrollColumns (sXborder); - else if (sX > m_startX + width()) - scrollColumns (sX - width() + 8); - } - - m_madeVisible = !force; - - QAccessible::updateAccessibility( this, KateCursorAccessible::ChildId, QAccessible::Focus ); -} - -void KateViewInternal::slotRegionVisibilityChangedAt(unsigned int,bool clear_cache) -{ - Q_UNUSED(clear_cache) - kDebug(13030); - m_cachedMaxStartPos.setLine(-1); - KTextEditor::Cursor max = maxStartPos(); - if (startPos() > max) - scrollPos(max); - - cache()->clear (); - - m_preserveX = true; - KTextEditor::Cursor newPos = toRealCursor(toVirtualCursor(m_cursor)); - KateTextLayout newLine = cache()->textLayout(newPos); - newPos = renderer()->xToCursor(newLine, m_preservedX, !m_view->wrapCursor()); - updateCursor(newPos, true); - - updateView(); - update(); - m_leftBorder->update(); - emit m_view->displayRangeChanged(m_view); -} - -void KateViewInternal::slotCodeFoldingChanged() -{ - m_leftBorder->update(); -} - -void KateViewInternal::slotRegionBeginEndAddedRemoved(unsigned int) -{ - kDebug(13030); - // FIXME: performance problem - m_leftBorder->update(); -} - -void KateViewInternal::showEvent ( QShowEvent *e ) -{ - updateView (); - - QWidget::showEvent (e); -} - -int KateViewInternal::linesDisplayed() const -{ - int h = height(); - - // catch zero heights, even if should not happen - int fh = qMax (1, renderer()->lineHeight()); - - // default to 1, there is always one line around.... - // too many places calc with linesDisplayed() - 1 - return qMax (1, (h - (h % fh)) / fh); -} - -QPoint KateViewInternal::cursorToCoordinate( const KTextEditor::Cursor & cursor, bool realCursor, bool includeBorder ) const -{ - int viewLine = cache()->displayViewLine(realCursor ? toVirtualCursor(cursor) : cursor, true); - - if (viewLine < 0 || viewLine >= cache()->viewCacheLineCount()) - return QPoint(-1, -1); - - int y = (int)viewLine * renderer()->lineHeight(); - - KateTextLayout layout = cache()->viewLine(viewLine); - int x = 0; - - // only set x value if we have a valid layout (bug #171027) - if (layout.isValid()) - x = (int)layout.lineLayout().cursorToX(cursor.column()); -// else -// kDebug() << "Invalid Layout"; - - if (includeBorder) x += m_leftBorder->width(); - - x -= startX(); - - return QPoint(x, y); -} - -QPoint KateViewInternal::cursorCoordinates(bool includeBorder) const -{ - return cursorToCoordinate(m_displayCursor, false, includeBorder); -} - -KTextEditor::Cursor KateViewInternal::findMatchingBracket() -{ - KTextEditor::Cursor c; - - if (!m_bm->toRange().isValid()) - return KTextEditor::Cursor::invalid(); - - Q_ASSERT(m_bmEnd->toRange().isValid()); - Q_ASSERT(m_bmStart->toRange().isValid()); - - if (m_bmStart->toRange().contains(m_cursor) || m_bmStart->end() == m_cursor.toCursor()) { - c = m_bmEnd->end(); - } else if (m_bmEnd->toRange().contains(m_cursor) || m_bmEnd->end() == m_cursor.toCursor()) { - c = m_bmStart->start(); - } else { - // should never happen: a range exists, but the cursor position is - // neither at the start nor at the end... - return KTextEditor::Cursor::invalid(); - } - - return c; -} - -void KateViewInternal::doReturn() -{ - doc()->newLine( m_view ); - updateView(); -} - -void KateViewInternal::doSmartNewline() -{ - int ln = m_cursor.line(); - Kate::TextLine line = doc()->kateTextLine(ln); - int col = qMin(m_cursor.column(), line->firstChar()); - if (col != -1) { - while (line->length() > col && - !(line->at(col).isLetterOrNumber() || line->at(col) == QLatin1Char('_')) && - col < m_cursor.column()) ++col; - } else { - col = line->length(); // stay indented - } - doc()->editStart(); - doc()->editWrapLine(ln, m_cursor.column()); - doc()->insertText(KTextEditor::Cursor(ln + 1, 0), line->string(0, col)); - doc()->editEnd(); - - updateView(); -} - -void KateViewInternal::doDelete() -{ - doc()->del( m_view, m_cursor ); -} - -void KateViewInternal::doBackspace() -{ - doc()->backspace( m_view, m_cursor ); -} - -void KateViewInternal::doTabulator() -{ - doc()->insertTab( m_view, m_cursor ); -} - -void KateViewInternal::doTranspose() -{ - doc()->transpose( m_cursor ); -} - -void KateViewInternal::doDeleteWordLeft() -{ - doc()->editStart(); - wordLeft( true ); - KTextEditor::Range selection = m_view->selectionRange(); - m_view->removeSelectedText(); - doc()->editEnd(); - tagRange(selection, true); - updateDirty(); -} - -void KateViewInternal::doDeleteWordRight() -{ - doc()->editStart(); - wordRight( true ); - KTextEditor::Range selection = m_view->selectionRange(); - m_view->removeSelectedText(); - doc()->editEnd(); - tagRange(selection, true); - updateDirty(); -} - -class CalculatingCursor : public KTextEditor::Cursor { -public: - // These constructors constrain their arguments to valid positions - // before only the third one did, but that leads to crashs - // see bug 227449 - CalculatingCursor(KateViewInternal* vi) - : KTextEditor::Cursor() - , m_vi(vi) - { - makeValid(); - } - - CalculatingCursor(KateViewInternal* vi, const KTextEditor::Cursor& c) - : KTextEditor::Cursor(c) - , m_vi(vi) - { - makeValid(); - } - - CalculatingCursor(KateViewInternal* vi, int line, int col) - : KTextEditor::Cursor(line, col) - , m_vi(vi) - { - makeValid(); - } - - - virtual CalculatingCursor& operator+=( int n ) = 0; - - virtual CalculatingCursor& operator-=( int n ) = 0; - - CalculatingCursor& operator++() { return operator+=( 1 ); } - - CalculatingCursor& operator--() { return operator-=( 1 ); } - - void makeValid() { - setLine(qBound( 0, line(), int( doc()->lines() - 1 ) ) ); - if (view()->wrapCursor()) - m_column = qBound( 0, column(), doc()->lineLength( line() ) ); - else - m_column = qMax( 0, column() ); - Q_ASSERT( valid() ); - } - - void toEdge( KateViewInternal::Bias bias ) { - if( bias == KateViewInternal::left ) m_column = 0; - else if( bias == KateViewInternal::right ) m_column = doc()->lineLength( line() ); - } - - bool atEdge() const { return atEdge( KateViewInternal::left ) || atEdge( KateViewInternal::right ); } - - bool atEdge( KateViewInternal::Bias bias ) const { - switch( bias ) { - case KateViewInternal::left: return column() == 0; - case KateViewInternal::none: return atEdge(); - case KateViewInternal::right: return column() >= doc()->lineLength( line() ); - default: Q_ASSERT(false); return false; - } - } - -protected: - bool valid() const { - return line() >= 0 && - line() < doc()->lines() && - column() >= 0 && - (!view()->wrapCursor() || column() <= doc()->lineLength( line() )); - } - KateView* view() { return m_vi->m_view; } - const KateView* view() const { return m_vi->m_view; } - KateDocument* doc() { return view()->doc(); } - const KateDocument* doc() const { return view()->doc(); } - KateViewInternal* m_vi; -}; - -class BoundedCursor : public CalculatingCursor { -public: - BoundedCursor(KateViewInternal* vi) - : CalculatingCursor( vi ) {} - BoundedCursor(KateViewInternal* vi, const KTextEditor::Cursor& c ) - : CalculatingCursor( vi, c ) {} - BoundedCursor(KateViewInternal* vi, int line, int col ) - : CalculatingCursor( vi, line, col ) {} - virtual CalculatingCursor& operator+=( int n ) { - KateLineLayoutPtr thisLine = m_vi->cache()->line(line()); - if (!thisLine->isValid()) { - kWarning() << "Did not retrieve valid layout for line " << line(); - return *this; - } - - const bool wrapCursor = view()->wrapCursor(); - int maxColumn = -1; - if (n >= 0) { - for (int i = 0; i < n; i++) { - if (m_column >= thisLine->length()) { - if (wrapCursor) { - break; - - } else if (view()->dynWordWrap()) { - // Don't go past the edge of the screen in dynamic wrapping mode - if (maxColumn == -1) - maxColumn = thisLine->length() + ((m_vi->width() - thisLine->widthOfLastLine()) / m_vi->renderer()->spaceWidth()) - 1; - - if (m_column >= maxColumn) { - m_column = maxColumn; - break; - } - - ++m_column; - - } else { - ++m_column; - } - - } else { - m_column = thisLine->layout()->nextCursorPosition(m_column); - } - } - } else { - for (int i = 0; i > n; i--) { - if (m_column >= thisLine->length()) - --m_column; - else if (m_column == 0) - break; - else - m_column = thisLine->layout()->previousCursorPosition(m_column); - } - } - - Q_ASSERT( valid() ); - return *this; - } - virtual CalculatingCursor& operator-=( int n ) { - return operator+=( -n ); - } -}; - -class WrappingCursor : public CalculatingCursor { -public: - WrappingCursor(KateViewInternal* vi) - : CalculatingCursor( vi) {} - WrappingCursor(KateViewInternal* vi, const KTextEditor::Cursor& c ) - : CalculatingCursor( vi, c ) {} - WrappingCursor(KateViewInternal* vi, int line, int col ) - : CalculatingCursor( vi, line, col ) {} - - virtual CalculatingCursor& operator+=( int n ) { - KateLineLayoutPtr thisLine = m_vi->cache()->line(line()); - if (!thisLine->isValid()) { - kWarning() << "Did not retrieve a valid layout for line " << line(); - return *this; - } - - if (n >= 0) { - for (int i = 0; i < n; i++) { - if (m_column >= thisLine->length()) { - // Have come to the end of a line - if (line() >= doc()->lines() - 1) - // Have come to the end of the document - break; - - // Advance to the beginning of the next line - m_column = 0; - setLine(line() + 1); - - // Retrieve the next text range - thisLine = m_vi->cache()->line(line()); - if (!thisLine->isValid()) { - kWarning() << "Did not retrieve a valid layout for line " << line(); - return *this; - } - - continue; - } - - m_column = thisLine->layout()->nextCursorPosition(m_column); - } - - } else { - for (int i = 0; i > n; i--) { - if (m_column == 0) { - // Have come to the start of the document - if (line() == 0) - break; - - // Start going back to the end of the last line - setLine(line() - 1); - - // Retrieve the next text range - thisLine = m_vi->cache()->line(line()); - if (!thisLine->isValid()) { - kWarning() << "Did not retrieve a valid layout for line " << line(); - return *this; - } - - // Finish going back to the end of the last line - m_column = thisLine->length(); - - continue; - } - - m_column = thisLine->layout()->previousCursorPosition(m_column); - } - } - - Q_ASSERT(valid()); - return *this; - } - virtual CalculatingCursor& operator-=( int n ) { - return operator+=( -n ); - } -}; - -void KateViewInternal::moveChar( KateViewInternal::Bias bias, bool sel ) -{ - KTextEditor::Cursor c; - if ( m_view->wrapCursor() ) { - c = WrappingCursor( this, m_cursor ) += bias; - } else { - c = BoundedCursor( this, m_cursor ) += bias; - } - - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::cursorLeft( bool sel ) -{ - if ( ! m_view->wrapCursor() && m_cursor.column() == 0 ) - return; - - moveChar( KateViewInternal::left, sel ); -} - -void KateViewInternal::cursorRight( bool sel ) -{ - moveChar( KateViewInternal::right, sel ); -} - -void KateViewInternal::wordLeft ( bool sel ) -{ - WrappingCursor c( this, m_cursor ); - - // First we skip backwards all space. - // Then we look up into which category the current position falls: - // 1. a "word" character - // 2. a "non-word" character (except space) - // 3. the beginning of the line - // and skip all preceding characters that fall into this class. - // The code assumes that space is never part of the word character class. - - KateHighlighting* h = doc()->highlight(); - if( !c.atEdge( left ) ) { - - while( !c.atEdge( left ) && doc()->line( c.line() )[ c.column() - 1 ].isSpace() ) - --c; - } - if( c.atEdge( left ) ) - { - --c; - } - else if( h->isInWord( doc()->line( c.line() )[ c.column() - 1 ] ) ) - { - while( !c.atEdge( left ) && h->isInWord( doc()->line( c.line() )[ c.column() - 1 ] ) ) - --c; - } - else - { - while( !c.atEdge( left ) - && !h->isInWord( doc()->line( c.line() )[ c.column() - 1 ] ) - // in order to stay symmetric to wordLeft() - // we must not skip space preceding a non-word sequence - && !doc()->line( c.line() )[ c.column() - 1 ].isSpace() ) - { - --c; - } - } - - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::wordRight( bool sel ) -{ - WrappingCursor c( this, m_cursor ); - - // We look up into which category the current position falls: - // 1. a "word" character - // 2. a "non-word" character (except space) - // 3. the end of the line - // and skip all following characters that fall into this class. - // If the skipped characters are followed by space, we skip that too. - // The code assumes that space is never part of the word character class. - - KateHighlighting* h = doc()->highlight(); - if( c.atEdge( right ) ) - { - ++c; - } - else if( h->isInWord( doc()->line( c.line() )[ c.column() ] ) ) - { - while( !c.atEdge( right ) && h->isInWord( doc()->line( c.line() )[ c.column() ] ) ) - ++c; - } - else - { - while( !c.atEdge( right ) - && !h->isInWord( doc()->line( c.line() )[ c.column() ] ) - // we must not skip space, because if that space is followed - // by more non-word characters, we would skip them, too - && !doc()->line( c.line() )[ c.column() ].isSpace() ) - { - ++c; - } - } - - while( !c.atEdge( right ) && doc()->line( c.line() )[ c.column() ].isSpace() ) - ++c; - - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::moveEdge( KateViewInternal::Bias bias, bool sel ) -{ - BoundedCursor c( this, m_cursor ); - c.toEdge( bias ); - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::home( bool sel ) -{ - if (m_view->dynWordWrap() && currentLayout().startCol()) { - // Allow us to go to the real start if we're already at the start of the view line - if (m_cursor.column() != currentLayout().startCol()) { - KTextEditor::Cursor c = currentLayout().start(); - updateSelection( c, sel ); - updateCursor( c ); - return; - } - } - - if( !doc()->config()->smartHome() ) { - moveEdge( left, sel ); - return; - } - - Kate::TextLine l = doc()->kateTextLine( m_cursor.line() ); - - if (!l) - return; - - KTextEditor::Cursor c = m_cursor; - int lc = l->firstChar(); - - if( lc < 0 || c.column() == lc ) { - c.setColumn(0); - } else { - c.setColumn(lc); - } - - updateSelection( c, sel ); - updateCursor( c, true ); -} - -void KateViewInternal::end( bool sel ) -{ - KateTextLayout layout = currentLayout(); - - if (m_view->dynWordWrap() && layout.wrap()) { - // Allow us to go to the real end if we're already at the end of the view line - if (m_cursor.column() < layout.endCol() - 1) { - KTextEditor::Cursor c(m_cursor.line(), layout.endCol() - 1); - updateSelection( c, sel ); - updateCursor( c ); - return; - } - } - - if( !doc()->config()->smartHome() ) { - moveEdge( right, sel ); - return; - } - - Kate::TextLine l = doc()->kateTextLine( m_cursor.line() ); - - if (!l) - return; - - // "Smart End", as requested in bugs #78258 and #106970 - if (m_cursor.column() == doc()->lineLength(m_cursor.line())) { - KTextEditor::Cursor c = m_cursor; - c.setColumn(l->lastChar() + 1); - updateSelection(c, sel); - updateCursor(c, true); - } else { - moveEdge(right, sel); - } -} - -KateTextLayout KateViewInternal::currentLayout() const -{ - return cache()->textLayout(m_cursor); -} - -KateTextLayout KateViewInternal::previousLayout() const -{ - int currentViewLine = cache()->viewLine(m_cursor); - - if (currentViewLine) - return cache()->textLayout(m_cursor.line(), currentViewLine - 1); - else - return cache()->textLayout(doc()->getRealLine(m_displayCursor.line() - 1), -1); -} - -KateTextLayout KateViewInternal::nextLayout() const -{ - int currentViewLine = cache()->viewLine(m_cursor) + 1; - - if (currentViewLine >= cache()->line(m_cursor.line())->viewLineCount()) { - currentViewLine = 0; - return cache()->textLayout(doc()->getRealLine(m_displayCursor.line() + 1), currentViewLine); - } else { - return cache()->textLayout(m_cursor.line(), currentViewLine); - } -} - -/* - * This returns the cursor which is offset by (offset) view lines. - * This is the main function which is called by code not specifically dealing with word-wrap. - * The opposite conversion (cursor to offset) can be done with cache()->displayViewLine(). - * - * The cursors involved are virtual cursors (ie. equivalent to m_displayCursor) - */ -KTextEditor::Cursor KateViewInternal::viewLineOffset(const KTextEditor::Cursor& virtualCursor, int offset, bool keepX) -{ - if (!m_view->dynWordWrap()) { - KTextEditor::Cursor ret(qMin((int)doc()->visibleLines() - 1, virtualCursor.line() + offset), 0); - - if (ret.line() < 0) - ret.setLine(0); - - if (keepX) { - int realLine = doc()->getRealLine(ret.line()); - KateTextLayout t = cache()->textLayout(realLine, 0); - Q_ASSERT(t.isValid()); - - ret.setColumn(renderer()->xToCursor(t, m_preservedX, !m_view->wrapCursor()).column()); - } - - return ret; - } - - KTextEditor::Cursor realCursor = virtualCursor; - realCursor.setLine(doc()->getRealLine(virtualCursor.line())); - - int cursorViewLine = cache()->viewLine(realCursor); - - int currentOffset = 0; - int virtualLine = 0; - - bool forwards = (offset > 0) ? true : false; - - if (forwards) { - currentOffset = cache()->lastViewLine(realCursor.line()) - cursorViewLine; - if (offset <= currentOffset) { - // the answer is on the same line - KateTextLayout thisLine = cache()->textLayout(realCursor.line(), cursorViewLine + offset); - Q_ASSERT(thisLine.virtualLine() == virtualCursor.line()); - return KTextEditor::Cursor(virtualCursor.line(), thisLine.startCol()); - } - - virtualLine = virtualCursor.line() + 1; - - } else { - offset = -offset; - currentOffset = cursorViewLine; - if (offset <= currentOffset) { - // the answer is on the same line - KateTextLayout thisLine = cache()->textLayout(realCursor.line(), cursorViewLine - offset); - Q_ASSERT(thisLine.virtualLine() == virtualCursor.line()); - return KTextEditor::Cursor(virtualCursor.line(), thisLine.startCol()); - } - - virtualLine = virtualCursor.line() - 1; - } - - currentOffset++; - - while (virtualLine >= 0 && virtualLine < (int)doc()->visibleLines()) - { - int realLine = doc()->getRealLine(virtualLine); - KateLineLayoutPtr thisLine = cache()->line(realLine, virtualLine); - if (!thisLine) - break; - - for (int i = 0; i < thisLine->viewLineCount(); ++i) { - if (offset == currentOffset) { - KateTextLayout thisViewLine = thisLine->viewLine(i); - - if (!forwards) { - // We actually want it the other way around - int requiredViewLine = cache()->lastViewLine(realLine) - thisViewLine.viewLine(); - if (requiredViewLine != thisViewLine.viewLine()) { - thisViewLine = thisLine->viewLine(requiredViewLine); - } - } - - KTextEditor::Cursor ret(virtualLine, thisViewLine.startCol()); - - // keep column position - if (keepX) { - KTextEditor::Cursor realCursor = toRealCursor(virtualCursor); - KateTextLayout t = cache()->textLayout(realCursor); - // renderer()->cursorToX(t, realCursor, !m_view->wrapCursor()); - - realCursor = renderer()->xToCursor(thisViewLine, m_preservedX, !m_view->wrapCursor()); - ret.setColumn(realCursor.column()); - } - - return ret; - } - - currentOffset++; - } - - if (forwards) - virtualLine++; - else - virtualLine--; - } - - // Looks like we were asked for something a bit exotic. - // Return the max/min valid position. - if (forwards) - return KTextEditor::Cursor(doc()->visibleLines() - 1, doc()->lineLength(doc()->getRealLine (doc()->visibleLines() - 1))); - else - return KTextEditor::Cursor(0, 0); -} - -int KateViewInternal::lineMaxCursorX(const KateTextLayout& range) -{ - if (!m_view->wrapCursor() && !range.wrap()) - return INT_MAX; - - int maxX = range.endX(); - - if (maxX && range.wrap()) { - QChar lastCharInLine = doc()->kateTextLine(range.line())->at(range.endCol() - 1); - maxX -= renderer()->config()->fontMetrics().width(lastCharInLine); - } - - return maxX; -} - -int KateViewInternal::lineMaxCol(const KateTextLayout& range) -{ - int maxCol = range.endCol(); - - if (maxCol && range.wrap()) - maxCol--; - - return maxCol; -} - -void KateViewInternal::cursorUp(bool sel) -{ - if(!sel && m_view->completionWidget()->isCompletionActive()) { - m_view->completionWidget()->cursorUp(); - return; - } - - if (m_displayCursor.line() == 0 && (!m_view->dynWordWrap() || cache()->viewLine(m_cursor) == 0)) - return; - - m_preserveX = true; - - KateTextLayout thisLine = currentLayout(); - // This is not the first line because that is already simplified out above - KateTextLayout pRange = previousLayout(); - - // Ensure we're in the right spot - Q_ASSERT(m_cursor.line() == thisLine.line()); - Q_ASSERT(m_cursor.column() >= thisLine.startCol()); - Q_ASSERT(!thisLine.wrap() || m_cursor.column() < thisLine.endCol()); - - KTextEditor::Cursor c = renderer()->xToCursor(pRange, m_preservedX, !m_view->wrapCursor()); - - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::cursorDown(bool sel) -{ - if(!sel && m_view->completionWidget()->isCompletionActive()) { - m_view->completionWidget()->cursorDown(); - return; - } - - if ((m_displayCursor.line() >= doc()->numVisLines() - 1) && (!m_view->dynWordWrap() || cache()->viewLine(m_cursor) == cache()->lastViewLine(m_cursor.line()))) - return; - - m_preserveX = true; - - KateTextLayout thisLine = currentLayout(); - // This is not the last line because that is already simplified out above - KateTextLayout nRange = nextLayout(); - - // Ensure we're in the right spot - Q_ASSERT((m_cursor.line() == thisLine.line()) && - (m_cursor.column() >= thisLine.startCol()) && - (!thisLine.wrap() || m_cursor.column() < thisLine.endCol())); - - KTextEditor::Cursor c = renderer()->xToCursor(nRange, m_preservedX, !m_view->wrapCursor()); - - updateSelection(c, sel); - updateCursor(c); -} - -void KateViewInternal::cursorToMatchingBracket( bool sel ) -{ - KTextEditor::Cursor c = findMatchingBracket(); - - if (c.isValid()) { - updateSelection( c, sel ); - updateCursor( c ); - } -} - -void KateViewInternal::topOfView( bool sel ) -{ - KTextEditor::Cursor c = viewLineOffset(startPos(), m_minLinesVisible); - updateSelection( toRealCursor(c), sel ); - updateCursor( toRealCursor(c) ); -} - -void KateViewInternal::bottomOfView( bool sel ) -{ - KTextEditor::Cursor c = viewLineOffset(endPos(), -m_minLinesVisible); - updateSelection( toRealCursor(c), sel ); - updateCursor( toRealCursor(c) ); -} - -// lines is the offset to scroll by -void KateViewInternal::scrollLines( int lines, bool sel ) -{ - KTextEditor::Cursor c = viewLineOffset(m_displayCursor, lines, true); - - // Fix the virtual cursor -> real cursor - c.setLine(doc()->getRealLine(c.line())); - - updateSelection( c, sel ); - updateCursor( c ); -} - -// This is a bit misleading... it's asking for the view to be scrolled, not the cursor -void KateViewInternal::scrollUp() -{ - KTextEditor::Cursor newPos = viewLineOffset(startPos(), -1); - scrollPos(newPos); -} - -void KateViewInternal::scrollDown() -{ - KTextEditor::Cursor newPos = viewLineOffset(startPos(), 1); - scrollPos(newPos); -} - -void KateViewInternal::setAutoCenterLines(int viewLines, bool updateView) -{ - m_autoCenterLines = viewLines; - m_minLinesVisible = qMin(int((linesDisplayed() - 1)/2), m_autoCenterLines); - if (updateView) - KateViewInternal::updateView(); -} - -void KateViewInternal::pageUp( bool sel ) -{ - if (m_view->isCompletionActive()) { - m_view->completionWidget()->pageUp(); - return; - } - - // remember the view line and x pos - int viewLine = cache()->displayViewLine(m_displayCursor); - bool atTop = startPos().atStartOfDocument(); - - // Adjust for an auto-centering cursor - int lineadj = m_minLinesVisible; - - int linesToScroll = -qMax( (linesDisplayed() - 1) - lineadj, 0 ); - m_preserveX = true; - - if (!doc()->pageUpDownMovesCursor () && !atTop) { - KTextEditor::Cursor newStartPos = viewLineOffset(startPos(), linesToScroll - 1); - scrollPos(newStartPos); - - // put the cursor back approximately where it was - KTextEditor::Cursor newPos = toRealCursor(viewLineOffset(newStartPos, viewLine, true)); - - KateTextLayout newLine = cache()->textLayout(newPos); - - newPos = renderer()->xToCursor(newLine, m_preservedX, !m_view->wrapCursor()); - - m_preserveX = true; - updateSelection( newPos, sel ); - updateCursor(newPos); - - } else { - scrollLines( linesToScroll, sel ); - } -} - -void KateViewInternal::pageDown( bool sel ) -{ - if (m_view->isCompletionActive()) { - m_view->completionWidget()->pageDown(); - return; - } - - // remember the view line - int viewLine = cache()->displayViewLine(m_displayCursor); - bool atEnd = startPos() >= m_cachedMaxStartPos; - - // Adjust for an auto-centering cursor - int lineadj = m_minLinesVisible; - - int linesToScroll = qMax( (linesDisplayed() - 1) - lineadj, 0 ); - m_preserveX = true; - - if (!doc()->pageUpDownMovesCursor () && !atEnd) { - KTextEditor::Cursor newStartPos = viewLineOffset(startPos(), linesToScroll + 1); - scrollPos(newStartPos); - - // put the cursor back approximately where it was - KTextEditor::Cursor newPos = toRealCursor(viewLineOffset(newStartPos, viewLine, true)); - - KateTextLayout newLine = cache()->textLayout(newPos); - - newPos = renderer()->xToCursor(newLine, m_preservedX, !m_view->wrapCursor()); - - m_preserveX = true; - updateSelection( newPos, sel ); - updateCursor(newPos); - - } else { - scrollLines( linesToScroll, sel ); - } -} - -int KateViewInternal::maxLen(int startLine) -{ - Q_ASSERT(!m_view->dynWordWrap()); - - int displayLines = (m_view->height() / renderer()->lineHeight()) + 1; - - int maxLen = 0; - - for (int z = 0; z < displayLines; z++) { - int virtualLine = startLine + z; - - if (virtualLine < 0 || virtualLine >= (int)doc()->visibleLines()) - break; - - maxLen = qMax(maxLen, cache()->line(doc()->getRealLine(virtualLine))->width()); - } - - return maxLen; -} - -bool KateViewInternal::columnScrollingPossible () -{ - return !m_view->dynWordWrap() && m_columnScroll->isEnabled() && (m_columnScroll->maximum() > 0); -} - -void KateViewInternal::top( bool sel ) -{ - KTextEditor::Cursor newCursor(0, 0); - - newCursor = renderer()->xToCursor(cache()->textLayout(newCursor), m_preservedX, !m_view->wrapCursor()); - - updateSelection( newCursor, sel ); - updateCursor( newCursor ); -} - -void KateViewInternal::bottom( bool sel ) -{ - KTextEditor::Cursor newCursor(doc()->lastLine(), 0); - - newCursor = renderer()->xToCursor(cache()->textLayout(newCursor), m_preservedX, !m_view->wrapCursor()); - - updateSelection( newCursor, sel ); - updateCursor( newCursor ); -} - -void KateViewInternal::top_home( bool sel ) -{ - if (m_view->isCompletionActive()) { - m_view->completionWidget()->top(); - return; - } - - KTextEditor::Cursor c( 0, 0 ); - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::bottom_end( bool sel ) -{ - if (m_view->isCompletionActive()) { - m_view->completionWidget()->bottom(); - return; - } - - KTextEditor::Cursor c( doc()->lastLine(), doc()->lineLength( doc()->lastLine() ) ); - updateSelection( c, sel ); - updateCursor( c ); -} - -void KateViewInternal::updateSelection( const KTextEditor::Cursor& _newCursor, bool keepSel ) -{ - KTextEditor::Cursor newCursor = _newCursor; - if( keepSel ) - { - if ( !m_view->selection() || (m_selectAnchor.line() == -1) - //don't kill the selection if we have a persistent selection and - //the cursor is inside or at the boundaries of the selected area - || (m_view->config()->persistentSelection() - && !(m_view->selectionRange().contains(m_cursor) - || m_view->selectionRange().boundaryAtCursor(m_cursor))) ) - { - m_selectAnchor = m_cursor; - setSelection( KTextEditor::Range(m_cursor, newCursor) ); - } - else - { - bool doSelect = true; - switch (m_selectionMode) - { - case Word: - { - // Restore selStartCached if needed. It gets nuked by - // viewSelectionChanged if we drag the selection into non-existence, - // which can legitimately happen if a shift+DC selection is unable to - // set a "proper" (i.e. non-empty) cached selection, e.g. because the - // start was on something that isn't a word. Word select mode relies - // on the cached selection being set properly, even if it is empty - // (i.e. selStartCached == selEndCached). - if ( !m_selectionCached.isValid() ) - m_selectionCached.start() = m_selectionCached.end(); - - int c; - if ( newCursor > m_selectionCached.start() ) - { - m_selectAnchor = m_selectionCached.start(); - - Kate::TextLine l = doc()->kateTextLine( newCursor.line() ); - - c = newCursor.column(); - if ( c > 0 && doc()->highlight()->isInWord( l->at( c-1 ) ) ) { - for ( ; c < l->length(); c++ ) - if ( !doc()->highlight()->isInWord( l->at( c ) ) ) - break; - } - - newCursor.setColumn( c ); - } - else if ( newCursor < m_selectionCached.start() ) - { - m_selectAnchor = m_selectionCached.end(); - - Kate::TextLine l = doc()->kateTextLine( newCursor.line() ); - - c = newCursor.column(); - if ( c > 0 && c < doc()->lineLength( newCursor.line() ) - && doc()->highlight()->isInWord( l->at( c ) ) - && doc()->highlight()->isInWord( l->at( c-1 ) ) ) { - for ( c -= 2; c >= 0; c-- ) - if ( !doc()->highlight()->isInWord( l->at( c ) ) ) - break; - newCursor.setColumn( c+1 ); - } - } - else - doSelect = false; - - } - break; - case Line: - if ( !m_selectionCached.isValid() ) { - m_selectionCached = KTextEditor::Range(endLine(), 0, endLine(), 0); - } - if ( newCursor.line() > m_selectionCached.start().line() ) - { - if (newCursor.line() + 1 >= doc()->lines() ) - newCursor.setColumn( doc()->line( newCursor.line() ).length() ); - else - newCursor.setPosition( newCursor.line() + 1, 0 ); - // Grow to include the entire line - m_selectAnchor = m_selectionCached.start(); - m_selectAnchor.setColumn( 0 ); - } - else if ( newCursor.line() < m_selectionCached.start().line() ) - { - newCursor.setColumn( 0 ); - // Grow to include entire line - m_selectAnchor = m_selectionCached.end(); - if ( m_selectAnchor.column() > 0 ) - { - if ( m_selectAnchor.line()+1 >= doc()->lines() ) - m_selectAnchor.setColumn( doc()->line( newCursor.line() ).length() ); - else - m_selectAnchor.setPosition( m_selectAnchor.line() + 1, 0 ); - } - } - else // same line, ignore - doSelect = false; - break; - case Mouse: - { - if ( !m_selectionCached.isValid() ) - break; - - if ( newCursor > m_selectionCached.end() ) - m_selectAnchor = m_selectionCached.start(); - else if ( newCursor < m_selectionCached.start() ) - m_selectAnchor = m_selectionCached.end(); - else - doSelect = false; - } - break; - default: /* nothing special to do */; - } - - if ( doSelect ) - setSelection( KTextEditor::Range(m_selectAnchor, newCursor) ); - else if ( m_selectionCached.isValid() ) // we have a cached selection, so we restore that - setSelection( m_selectionCached ); - } - - m_selChangedByUser = true; - } - else if ( !m_view->config()->persistentSelection() ) - { - m_view->clearSelection(); - - m_selectionCached = KTextEditor::Range::invalid(); - } -} - -void KateViewInternal::setSelection( const KTextEditor::Range &range ) -{ - disconnect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(viewSelectionChanged())); - m_view->setSelection(range); - connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(viewSelectionChanged())); -} - -void KateViewInternal::moveCursorToSelectionEdge() -{ - if (!m_view->selection()) - return; - - int tmp = m_minLinesVisible; - m_minLinesVisible = 0; - - if ( m_view->selectionRange().start() < m_selectAnchor ) - updateCursor( m_view->selectionRange().start() ); - else - updateCursor( m_view->selectionRange().end() ); - - m_minLinesVisible = tmp; -} - -void KateViewInternal::updateCursor( const KTextEditor::Cursor& newCursor, bool force, bool center, bool calledExternally ) -{ - if ( !force && (m_cursor.toCursor() == newCursor) ) - { - m_displayCursor = toVirtualCursor(newCursor); - if ( !m_madeVisible && m_view == doc()->activeView() ) - { - // unfold if required - doc()->foldingTree()->ensureVisible( newCursor.line() ); - - makeVisible ( m_displayCursor, m_displayCursor.column(), false, center, calledExternally ); - } - - return; - } - - // unfold if required - doc()->foldingTree()->ensureVisible( newCursor.line() ); - - KTextEditor::Cursor oldDisplayCursor = m_displayCursor; - - m_displayCursor = toVirtualCursor(newCursor); - m_cursor.setPosition( newCursor ); - - if ( m_view == doc()->activeView() ) - makeVisible ( m_displayCursor, m_displayCursor.column(), false, center, calledExternally ); - - updateBracketMarks(); - - // It's efficient enough to just tag them both without checking to see if they're on the same view line -/* kdDebug()<<"oldDisplayCursor:"< 0 ) - m_cursorTimer.start( KApplication::cursorFlashTime() / 2 ); - renderer()->setDrawCaret(true); - } - - // Remember the maximum X position if requested - if (m_preserveX) - m_preserveX = false; - else - m_preservedX = renderer()->cursorToX(cache()->textLayout(m_cursor), m_cursor, !m_view->wrapCursor()); - - //kDebug(13030) << "m_preservedX: " << m_preservedX << " (was "<< oldmaxx << "), m_cursorX: " << m_cursorX; - //kDebug(13030) << "Cursor now located at real " << cursor.line << "," << cursor.col << ", virtual " << m_displayCursor.line << ", " << m_displayCursor.col << "; Top is " << startLine() << ", " << startPos().col; - - cursorMoved(); - - updateDirty(); //paintText(0, 0, width(), height(), true); - - emit m_view->cursorPositionChanged(m_view, m_cursor); -} - -void KateViewInternal::updateBracketMarkAttributes() -{ - KTextEditor::Attribute::Ptr bracketFill = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); - bracketFill->setBackground(m_view->m_renderer->config()->highlightedBracketColor()); - bracketFill->setBackgroundFillWhitespace(false); - if (QFontInfo(renderer()->currentFont()).fixedPitch()) { - // make font bold only for fixed fonts, otherwise text jumps around - bracketFill->setFontBold(); - } - - m_bmStart->setAttribute(bracketFill); - m_bmEnd->setAttribute(bracketFill); - - if (m_view->m_renderer->config()->showWholeBracketExpression()) { - KTextEditor::Attribute::Ptr expressionFill = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); - expressionFill->setBackground(m_view->m_renderer->config()->highlightedBracketColor()); - expressionFill->setBackgroundFillWhitespace(false); - - m_bm->setAttribute(expressionFill); - } else { - m_bm->setAttribute(KTextEditor::Attribute::Ptr(new KTextEditor::Attribute())); - } -} - -void KateViewInternal::updateBracketMarks() -{ - // add some limit to this, this is really endless on big files without limit - int maxLines = 5000; - KTextEditor::Range newRange; - doc()->newBracketMark( m_cursor, newRange, maxLines ); - - // new range valid, then set ranges to it - if (newRange.isValid ()) { - // modify full range - m_bm->setRange (newRange); - - // modify start and end ranges - m_bmStart->setRange (KTextEditor::Range (m_bm->start(), KTextEditor::Cursor (m_bm->start().line(), m_bm->start().column() + 1))); - m_bmEnd->setRange (KTextEditor::Range (m_bm->end(), KTextEditor::Cursor (m_bm->end().line(), m_bm->end().column() + 1))); - return; - } - - // new range was invalid - m_bm->setRange (KTextEditor::Range::invalid()); - m_bmStart->setRange (KTextEditor::Range::invalid()); - m_bmEnd->setRange (KTextEditor::Range::invalid()); -} - -bool KateViewInternal::tagLine(const KTextEditor::Cursor& virtualCursor) -{ - // FIXME may be a more efficient way for this - if ((int)doc()->getRealLine(virtualCursor.line()) > doc()->lastLine()) - return false; - // End FIXME - - int viewLine = cache()->displayViewLine(virtualCursor, true); - if (viewLine >= 0 && viewLine < cache()->viewCacheLineCount()) { - cache()->viewLine(viewLine).setDirty(); - m_leftBorder->update (0, lineToY(viewLine), m_leftBorder->width(), renderer()->lineHeight()); - return true; - } - return false; -} - -bool KateViewInternal::tagLines( int start, int end, bool realLines ) -{ - return tagLines(KTextEditor::Cursor(start, 0), KTextEditor::Cursor(end, -1), realLines); -} - -bool KateViewInternal::tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors) -{ - if (realCursors) - { - cache()->relayoutLines(start.line(), end.line()); - - //kDebug(13030)<<"realLines is true"; - start = toVirtualCursor(start); - end = toVirtualCursor(end); - - } else { - cache()->relayoutLines(toRealCursor(start).line(), toRealCursor(end).line()); - } - - if (end.line() < startLine()) - { - //kDebug(13030)<<"end endLine(), but cache may not be valid when checking, so use a - // less optimal but still adequate approximation (potential overestimation but minimal performance difference) - if (start.line() > startLine() + cache()->viewCacheLineCount()) - { - //kDebug(13030)<<"start> endLine"<updateViewCache(startPos()); - - //kDebug(13030) << "tagLines( [" << start << "], [" << end << "] )"; - - bool ret = false; - - for (int z = 0; z < cache()->viewCacheLineCount(); z++) - { - KateTextLayout& line = cache()->viewLine(z); - if ((line.virtualLine() > start.line() || (line.virtualLine() == start.line() && line.endCol() >= start.column() && start.column() != -1)) && - (line.virtualLine() < end.line() || (line.virtualLine() == end.line() && (line.startCol() <= end.column() || end.column() == -1)))) { - ret = true; - break; - //kDebug(13030) << "Tagged line " << line.line(); - } - } - - if (!m_view->dynWordWrap()) - { - int y = lineToY( start.line() ); - // FIXME is this enough for when multiple lines are deleted - int h = (end.line() - start.line() + 2) * renderer()->lineHeight(); - if (end.line() >= doc()->numVisLines() - 1) - h = height(); - - m_leftBorder->update (0, y, m_leftBorder->width(), h); - } - else - { - // FIXME Do we get enough good info in editRemoveText to optimize this more? - //bool justTagged = false; - for (int z = 0; z < cache()->viewCacheLineCount(); z++) - { - KateTextLayout& line = cache()->viewLine(z); - if (!line.isValid() || - ((line.virtualLine() > start.line() || (line.virtualLine() == start.line() && line.endCol() >= start.column() && start.column() != -1)) && - (line.virtualLine() < end.line() || (line.virtualLine() == end.line() && (line.startCol() <= end.column() || end.column() == -1))))) - { - //justTagged = true; - m_leftBorder->update (0, z * renderer()->lineHeight(), m_leftBorder->width(), m_leftBorder->height()); - break; - } - /*else if (justTagged) - { - justTagged = false; - leftBorder->update (0, z * doc()->viewFont.fontHeight, leftBorder->width(), doc()->viewFont.fontHeight); - break; - }*/ - } - } - - return ret; -} - -bool KateViewInternal::tagRange(const KTextEditor::Range& range, bool realCursors) -{ - return tagLines(range.start(), range.end(), realCursors); -} - -void KateViewInternal::tagAll() -{ - // clear the cache... - cache()->clear (); - - m_leftBorder->updateFont(); - m_leftBorder->update(); -} - -void KateViewInternal::paintCursor() -{ - if (tagLine(m_displayCursor)) - updateDirty(); //paintText (0,0,width(), height(), true); -} - -// Point in content coordinates -void KateViewInternal::placeCursor( const QPoint& p, bool keepSelection, bool updateSelection ) -{ - KateTextLayout thisLine = yToKateTextLayout(p.y()); - KTextEditor::Cursor c; - - if (!thisLine.isValid()) // probably user clicked below the last line -> use the last line - thisLine = cache()->textLayout(doc()->lines() - 1, -1); - - c = renderer()->xToCursor(thisLine, startX() + p.x(), !m_view->wrapCursor()); - - if (c.line () < 0 || c.line() >= doc()->lines()) { - return; - } - - if (updateSelection) - KateViewInternal::updateSelection( c, keepSelection ); - - int tmp = m_minLinesVisible; - m_minLinesVisible = 0; - updateCursor( c ); - m_minLinesVisible = tmp; - - if (updateSelection && keepSelection) - moveCursorToSelectionEdge(); -} - -// Point in content coordinates -bool KateViewInternal::isTargetSelected( const QPoint& p ) -{ - const KateTextLayout& thisLine = yToKateTextLayout(p.y()); - if (!thisLine.isValid()) - return false; - - return m_view->cursorSelected(renderer()->xToCursor(thisLine, startX() + p.x(), !m_view->wrapCursor())); -} - -//BEGIN EVENT HANDLING STUFF - -bool KateViewInternal::eventFilter( QObject *obj, QEvent *e ) -{ - if (obj == m_lineScroll) - { - // the second condition is to make sure a scroll on the vertical bar doesn't cause a horizontal scroll ;) - if (e->type() == QEvent::Wheel && m_lineScroll->minimum() != m_lineScroll->maximum()) - { - wheelEvent((QWheelEvent*)e); - return true; - } - - // continue processing - return QWidget::eventFilter( obj, e ); - } - - switch( e->type() ) - { - case QEvent::ChildAdded: - case QEvent::ChildRemoved: { - QChildEvent* c = static_cast(e); - if (c->added()) { - c->child()->installEventFilter(this); - /*foreach (QWidget* child, c->child()->findChildren()) - child->installEventFilter(this);*/ - - } else if (c->removed()) { - c->child()->removeEventFilter(this); - - /*foreach (QWidget* child, c->child()->findChildren()) - child->removeEventFilter(this);*/ - } - } break; - - case QEvent::ShortcutOverride: - { - QKeyEvent *k = static_cast(e); - - if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) { - if (m_view->isCompletionActive()) { - m_view->abortCompletion(); - k->accept(); - //kDebug() << obj << "shortcut override" << k->key() << "aborting completion"; - return true; - } else if (m_view->bottomViewBar()->isVisible()) { - m_view->bottomViewBar()->hideCurrentBarWidget(); - k->accept(); - //kDebug() << obj << "shortcut override" << k->key() << "closing view bar"; - return true; - } else if (!m_view->config()->persistentSelection() && m_view->selection()) { - m_view->clearSelection(); - k->accept(); - //kDebug() << obj << "shortcut override" << k->key() << "clearing selection"; - return true; - } else if (m_view->hasSearchBar()) { - // hide search&replace highlights - m_view->searchBar()->clearHighlights(); - k->accept(); - return true; - } - } - - // if vi input mode key stealing is on, override kate shortcuts - if (m_view->viInputMode() && m_view->viInputModeStealKeys() && ( m_view->getCurrentViMode() != InsertMode || - ( m_view->getCurrentViMode() == InsertMode && k->modifiers() == Qt::ControlModifier ) ) ) { - k->accept(); - return true; - } - - } break; - - case QEvent::KeyPress: - { - QKeyEvent *k = static_cast(e); - - // Override all other single key shortcuts which do not use a modifier other than Shift - if (obj == this && (!k->modifiers() || k->modifiers() == Qt::ShiftModifier)) { - keyPressEvent( k ); - if (k->isAccepted()) { - //kDebug() << obj << "shortcut override" << k->key() << "using keystroke"; - return true; - } - } - - //kDebug() << obj << "shortcut override" << k->key() << "ignoring"; - } break; - - case QEvent::DragMove: - { - QPoint currentPoint = ((QDragMoveEvent*) e)->pos(); - - QRect doNotScrollRegion( s_scrollMargin, s_scrollMargin, - width() - s_scrollMargin * 2, - height() - s_scrollMargin * 2 ); - - if ( !doNotScrollRegion.contains( currentPoint ) ) - { - startDragScroll(); - // Keep sending move events - ( (QDragMoveEvent*)e )->accept( QRect(0,0,0,0) ); - } - - dragMoveEvent((QDragMoveEvent*)e); - } break; - - case QEvent::DragLeave: - // happens only when pressing ESC while dragging - stopDragScroll(); - break; - - case QEvent::WindowBlocked: - // next focus originates from an internal dialog: - // don't show the modonhd prompt - if (isVisible()) { - doc()->ignoreModifiedOnDiskOnce(); - } - break; - - default: - break; - } - - return QWidget::eventFilter( obj, e ); -} - -void KateViewInternal::keyPressEvent( QKeyEvent* e ) -{ - if( e->key() == Qt::Key_Left && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateLeft(); - e->setAccepted(true); - return; - } - if( e->key() == Qt::Key_Right && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateRight(); - e->setAccepted(true); - return; - } - if( e->key() == Qt::Key_Up && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateUp(); - e->setAccepted(true); - return; - } - if( e->key() == Qt::Key_Down && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateDown(); - e->setAccepted(true); - return; - } - if( e->key() == Qt::Key_Return && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateAccept(); - e->setAccepted(true); - return; - } - if( e->key() == Qt::Key_Backspace && e->modifiers() == Qt::AltModifier ) { - m_view->emitNavigateBack(); - e->setAccepted(true); - return; - } - - if( e->key() == Qt::Key_Alt && m_view->completionWidget()->isCompletionActive() ) { - m_completionItemExpanded = m_view->completionWidget()->toggleExpanded(true); - m_view->completionWidget()->resetHadNavigation(); - m_altDownTime = QTime::currentTime(); - } - - // Note: AND'ing with is a quick hack to fix Key_Enter - const int key = e->key() | (e->modifiers() & Qt::ShiftModifier); - - if (m_view->isCompletionActive()) - { - if( key == Qt::Key_Enter || key == Qt::Key_Return ) { - m_view->completionWidget()->execute(); - e->accept(); - return; - } - } - - if ( m_view->viInputMode() ) { - if ( !m_view->config()->viInputModeHideStatusBar() ) { - m_view->viModeBar()->clearMessage(); // clear [error] message - } - - if ( getViInputModeManager()->getCurrentViMode() == InsertMode - || getViInputModeManager()->getCurrentViMode() == ReplaceMode ) { - if ( getViInputModeManager()->handleKeypress( e ) ) { - return; - } else if ( e->modifiers() != Qt::NoModifier && e->modifiers() != Qt::ShiftModifier ) { - // re-post key events not handled if they have a modifier other than shift - QEvent *copy = new QKeyEvent ( e->type(), e->key(), e->modifiers(), e->text(), - e->isAutoRepeat(), e->count() ); - QCoreApplication::postEvent( parent(), copy ); - } - } else { // !InsertMode - if ( !getViInputModeManager()->handleKeypress( e ) ) { - // we didn't need that keypress, un-steal it :-) - QEvent *copy = new QKeyEvent ( e->type(), e->key(), e->modifiers(), e->text(), - e->isAutoRepeat(), e->count() ); - QCoreApplication::postEvent( parent(), copy ); - } - m_view->updateViModeBarCmd(); - return; - } - } - - if( !doc()->isReadWrite() ) - { - e->ignore(); - return; - } - - if ((key == Qt::Key_Return) || (key == Qt::Key_Enter)) - { - doReturn(); - e->accept(); - return; - } - - if (key == Qt::Key_Backspace || key == Qt::SHIFT + Qt::Key_Backspace) - { - //m_view->backspace(); - e->accept(); - - return; - } - - if (key == Qt::Key_Tab || key == Qt::SHIFT+Qt::Key_Backtab || key == Qt::Key_Backtab) - { - if(m_view->completionWidget()->isCompletionActive()) - { - e->accept(); - m_view->completionWidget()->tab(key != Qt::Key_Tab); - return; - } - - if( key == Qt::Key_Tab ) - { - uint tabHandling = doc()->config()->tabHandling(); - // convert tabSmart into tabInsertsTab or tabIndents: - if (tabHandling == KateDocumentConfig::tabSmart) - { - // multiple lines selected - if (m_view->selection() && !m_view->selectionRange().onSingleLine()) - { - tabHandling = KateDocumentConfig::tabIndents; - } - - // otherwise: take look at cursor position - else - { - // if the cursor is at or before the first non-space character - // or on an empty line, - // Tab indents, otherwise it inserts a tab character. - Kate::TextLine line = doc()->kateTextLine( m_cursor.line() ); - int first = line->firstChar(); - if (first < 0 || m_cursor.column() <= first) - tabHandling = KateDocumentConfig::tabIndents; - else - tabHandling = KateDocumentConfig::tabInsertsTab; - } - } - - if (tabHandling == KateDocumentConfig::tabInsertsTab) - doc()->typeChars( m_view, QString("\t") ); - else - doc()->indent( m_view->selection() ? m_view->selectionRange() : KTextEditor::Range(m_cursor.line(), 0, m_cursor.line(), 0), 1 ); - - e->accept(); - - return; - } - else if (doc()->config()->tabHandling() != KateDocumentConfig::tabInsertsTab) - { - // key == Qt::SHIFT+Qt::Key_Backtab || key == Qt::Key_Backtab - doc()->indent( m_view->selection() ? m_view->selectionRange() : KTextEditor::Range(m_cursor.line(), 0, m_cursor.line(), 0), -1 ); - e->accept(); - - return; - } - } - - if ( !(e->modifiers() & Qt::ControlModifier) && !e->text().isEmpty() && doc()->typeChars ( m_view, e->text() ) ) - { - e->accept(); - - return; - } - - // allow composition of AltGr + (q|2|3) on windows - static const int altGR = Qt::ControlModifier | Qt::AltModifier; - if( (e->modifiers() & altGR) == altGR && !e->text().isEmpty() && doc()->typeChars ( m_view, e->text() ) ) - { - e->accept(); - - return; - } - - e->ignore(); -} - -void KateViewInternal::keyReleaseEvent( QKeyEvent* e ) -{ - if( e->key() == Qt::Key_Alt && m_view->completionWidget()->isCompletionActive() && ((m_completionItemExpanded && (m_view->completionWidget()->hadNavigation() || m_altDownTime.msecsTo(QTime::currentTime()) > 300)) || (!m_completionItemExpanded && !m_view->completionWidget()->hadNavigation())) ) { - - m_view->completionWidget()->toggleExpanded(false, true); - } - - if ((e->modifiers() & Qt::SHIFT) == Qt::SHIFT) - { - m_shiftKeyPressed = true; - } - else - { - if (m_shiftKeyPressed) - { - m_shiftKeyPressed = false; - - if (m_selChangedByUser) - { - if (m_view->selection()) - QApplication::clipboard()->setText(m_view->selectionText (), QClipboard::Selection); - - m_selChangedByUser = false; - } - } - } - - e->ignore(); - return; -} - -void KateViewInternal::contextMenuEvent ( QContextMenuEvent * e ) -{ - // try to show popup menu - - QPoint p = e->pos(); - - if ( doc()->browserView() ) - { - m_view->contextMenuEvent( e ); - return; - } - - if ( e->reason() == QContextMenuEvent::Keyboard ) - { - makeVisible( m_displayCursor, 0 ); - p = cursorCoordinates(false); - p.rx() -= startX(); - } - else if ( ! m_view->selection() || m_view->config()->persistentSelection() ) - placeCursor( e->pos() ); - - // popup is a qguardedptr now - if (m_view->contextMenu()) { - m_view->spellingMenu()->setUseMouseForMisspelledRange((e->reason() == QContextMenuEvent::Mouse)); - m_view->contextMenu()->popup( mapToGlobal( p ) ); - e->accept (); - } -} - -void KateViewInternal::mousePressEvent( QMouseEvent* e ) -{ - switch (e->button()) - { - case Qt::LeftButton: - m_selChangedByUser = false; - - if (m_possibleTripleClick) - { - m_possibleTripleClick = false; - - m_selectionMode = Line; - - if ( e->modifiers() & Qt::ShiftModifier ) - { - updateSelection( m_cursor, true ); - } - else - { - m_view->selectLine( m_cursor ); - if (m_view->selection()) - m_selectAnchor = m_view->selectionRange().start(); - } - - if (m_view->selection()) - QApplication::clipboard()->setText(m_view->selectionText (), QClipboard::Selection); - - // Keep the line at the select anchor selected during further - // mouse selection - if ( m_selectAnchor.line() > m_view->selectionRange().start().line() ) - { - // Preserve the last selected line - if ( m_selectAnchor == m_view->selectionRange().end() && m_selectAnchor.column() == 0 ) - m_selectionCached.start().setPosition( m_selectAnchor.line()-1, 0 ); - else - m_selectionCached.start().setPosition( m_selectAnchor.line(), 0 ); - m_selectionCached.end() = m_view->selectionRange().end(); - } - else - { - // Preserve the first selected line - m_selectionCached.start() = m_view->selectionRange().start(); - if ( m_view->selectionRange().end().line() > m_view->selectionRange().start().line() ) - m_selectionCached.end().setPosition( m_view->selectionRange().start().line()+1, 0 ); - else - m_selectionCached.end() = m_view->selectionRange().end(); - } - - moveCursorToSelectionEdge(); - - m_scrollX = 0; - m_scrollY = 0; - m_scrollTimer.start (50); - - e->accept(); - return; - } - else if ( m_selectionMode == Default ) - { - m_selectionMode = Mouse; - } - - if ( e->modifiers() & Qt::ShiftModifier ) - { - if ( !m_selectAnchor.isValid() ) - m_selectAnchor = m_cursor; - } - else - { - m_selectionCached = KTextEditor::Range::invalid(); - } - - if( !(e->modifiers() & Qt::ShiftModifier) && isTargetSelected( e->pos() ) ) - { - m_dragInfo.state = diPending; - m_dragInfo.start = e->pos(); - } - else - { - m_dragInfo.state = diNone; - - if ( e->modifiers() & Qt::ShiftModifier ) - { - placeCursor( e->pos(), true, false ); - if ( m_selectionCached.start().isValid() ) - { - if ( m_cursor.toCursor() < m_selectionCached.start() ) - m_selectAnchor = m_selectionCached.end(); - else - m_selectAnchor = m_selectionCached.start(); - } - setSelection( KTextEditor::Range( m_selectAnchor, m_cursor ) ); - } - else - { - placeCursor( e->pos() ); - } - - m_scrollX = 0; - m_scrollY = 0; - - m_scrollTimer.start (50); - } - - e->accept (); - break; - - default: - e->ignore (); - break; - } -} - -void KateViewInternal::mouseDoubleClickEvent(QMouseEvent *e) -{ - switch (e->button()) - { - case Qt::LeftButton: - m_selectionMode = Word; - - if ( e->modifiers() & Qt::ShiftModifier ) - { - KTextEditor::Range oldSelection = m_view->selectionRange(); - - // Now select the word under the select anchor - int cs, ce; - Kate::TextLine l = doc()->kateTextLine( m_selectAnchor.line() ); - - ce = m_selectAnchor.column(); - if ( ce > 0 && doc()->highlight()->isInWord( l->at(ce) ) ) { - for (; ce < l->length(); ce++ ) - if ( !doc()->highlight()->isInWord( l->at(ce) ) ) - break; - } - - cs = m_selectAnchor.column() - 1; - if ( cs < doc()->lineLength( m_selectAnchor.line() ) - && doc()->highlight()->isInWord( l->at(cs) ) ) { - for ( cs--; cs >= 0; cs-- ) - if ( !doc()->highlight()->isInWord( l->at(cs) ) ) - break; - } - - // ...and keep it selected - if (cs+1 < ce) - { - m_selectionCached.start().setPosition( m_selectAnchor.line(), cs+1 ); - m_selectionCached.end().setPosition( m_selectAnchor.line(), ce ); - } - else - { - m_selectionCached.start() = m_selectAnchor; - m_selectionCached.end() = m_selectAnchor; - } - // Now word select to the mouse cursor - placeCursor( e->pos(), true ); - } - else - { - // first clear the selection, otherwise we run into bug #106402 - // ...and set the cursor position, for the same reason (otherwise there - // are *other* idiosyncrasies we can't fix without reintroducing said - // bug) - // Parameters: don't redraw, and don't emit selectionChanged signal yet - m_view->clearSelection( false, false ); - placeCursor( e->pos() ); - m_view->selectWord( m_cursor ); - cursorToMatchingBracket(true); - - if (m_view->selection()) - { - m_selectAnchor = m_view->selectionRange().start(); - m_selectionCached = m_view->selectionRange(); - } - else - { - m_selectAnchor = m_cursor; - m_selectionCached = KTextEditor::Range(m_cursor, m_cursor); - } - } - - // Move cursor to end (or beginning) of selected word - if (m_view->selection()) - QApplication::clipboard()->setText( m_view->selectionText(), QClipboard::Selection ); - - moveCursorToSelectionEdge(); - m_possibleTripleClick = true; - QTimer::singleShot ( QApplication::doubleClickInterval(), this, SLOT(tripleClickTimeout()) ); - - m_scrollX = 0; - m_scrollY = 0; - - m_scrollTimer.start (50); - - e->accept (); - break; - - default: - e->ignore (); - break; - } -} - -void KateViewInternal::tripleClickTimeout() -{ - m_possibleTripleClick = false; -} - -void KateViewInternal::mouseReleaseEvent( QMouseEvent* e ) -{ - switch (e->button()) - { - case Qt::LeftButton: - m_selectionMode = Default; -// m_selectionCached.start().setLine( -1 ); - - if (m_selChangedByUser) - { - if (m_view->selection()) { - QApplication::clipboard()->setText(m_view->selectionText (), QClipboard::Selection); - } - moveCursorToSelectionEdge(); - - m_selChangedByUser = false; - } - - if (m_dragInfo.state == diPending) - placeCursor( e->pos(), e->modifiers() & Qt::ShiftModifier ); - else if (m_dragInfo.state == diNone) - m_scrollTimer.stop (); - - m_dragInfo.state = diNone; - - e->accept (); - break; - - case Qt::MidButton: - placeCursor( e->pos() ); - - if( doc()->isReadWrite() ) - { - doc()->paste( m_view, QClipboard::Selection ); - repaint(); - } - - e->accept (); - break; - - default: - e->ignore (); - break; - } -} - -void KateViewInternal::leaveEvent( QEvent* ) -{ - m_textHintTimer.stop(); -} - -KTextEditor::Cursor KateViewInternal::coordinatesToCursor(const QPoint& _coord) const -{ - QPoint coord(_coord); - - KTextEditor::Cursor ret = KTextEditor::Cursor::invalid(); - - coord.setX( coord.x() - m_leftBorder->width() + startX() ); - - const KateTextLayout& thisLine = yToKateTextLayout(coord.y()); - if (thisLine.isValid()) - ret = renderer()->xToCursor(thisLine, coord.x(), !m_view->wrapCursor()); - - return ret; -} - -void KateViewInternal::mouseMoveEvent( QMouseEvent* e ) -{ - // FIXME only do this if needing to track mouse movement - const KateTextLayout& thisLine = yToKateTextLayout(e->y()); - if (thisLine.isValid()) { - KTextEditor::Cursor newPosition = renderer()->xToCursor(thisLine, e->x(), !m_view->wrapCursor()); - if (newPosition != m_mouse) { - m_mouse = newPosition; - mouseMoved(); - } - } else { - if (m_mouse.isValid()) { - m_mouse = KTextEditor::Cursor::invalid(); - mouseMoved(); - } - } - - if( e->buttons() & Qt::LeftButton ) - { - if (m_dragInfo.state == diPending) - { - // we had a mouse down, but haven't confirmed a drag yet - // if the mouse has moved sufficiently, we will confirm - QPoint p( e->pos() - m_dragInfo.start ); - - // we've left the drag square, we can start a real drag operation now - if( p.manhattanLength() > KGlobalSettings::dndEventDelay() ) - doDrag(); - - return; - } - else if (m_dragInfo.state == diDragging) - { - // Don't do anything after a canceled drag until the user lets go of - // the mouse button! - return; - } - - m_mouseX = e->x(); - m_mouseY = e->y(); - - m_scrollX = 0; - m_scrollY = 0; - int d = renderer()->lineHeight(); - - if (m_mouseX < 0) - m_scrollX = -d; - - if (m_mouseX > width()) - m_scrollX = d; - - if (m_mouseY < 0) - { - m_mouseY = 0; - m_scrollY = -d; - } - - if (m_mouseY > height()) - { - m_mouseY = height(); - m_scrollY = d; - } - - placeCursor( QPoint( m_mouseX, m_mouseY ), true ); - - } - else - { - if (isTargetSelected( e->pos() ) ) { - // mouse is over selected text. indicate that the text is draggable by setting - // the arrow cursor as other Qt text editing widgets do - if (m_mouseCursor != Qt::ArrowCursor) { - m_mouseCursor = Qt::ArrowCursor; - setCursor(m_mouseCursor); - } - } else { - // normal text cursor - if (m_mouseCursor != Qt::IBeamCursor) { - m_mouseCursor = Qt::IBeamCursor; - setCursor(m_mouseCursor); - } - } - //We need to check whether the mouse position is actually within the widget, - //because other widgets like the icon border forward their events to this, - //and we will create invalid text hint requests if we don't check - if (m_textHintEnabled && geometry().contains(parentWidget()->mapFromGlobal(e->globalPos()))) - { - m_textHintTimer.start(m_textHintTimeout); - m_textHintMouseX=e->x(); - m_textHintMouseY=e->y(); - } - } -} - -void KateViewInternal::updateDirty( ) -{ - uint h = renderer()->lineHeight(); - - int currentRectStart = -1; - int currentRectEnd = -1; - - QRegion updateRegion; - - { - for (int i = 0; i < cache()->viewCacheLineCount(); ++i) { - if (cache()->viewLine(i).isDirty()) { - if (currentRectStart == -1) { - currentRectStart = h * i; - currentRectEnd = h; - } else { - currentRectEnd += h; - } - - } else if (currentRectStart != -1) { - updateRegion += QRect(0, currentRectStart, width(), currentRectEnd); - currentRectStart = -1; - currentRectEnd = -1; - } - } - } - - - if (currentRectStart != -1) - updateRegion += QRect(0, currentRectStart, width(), currentRectEnd); - - if (!updateRegion.isEmpty()) { - if (debugPainting) kDebug( 13030 ) << k_funcinfo << "Update dirty region " << updateRegion; - update(updateRegion); - } -} - -void KateViewInternal::hideEvent(QHideEvent* e) -{ - Q_UNUSED(e); - if(m_view->isCompletionActive()) - m_view->completionWidget()->abortCompletion(); -} - -void KateViewInternal::paintEvent(QPaintEvent *e) -{ - if (m_smartDirty) - doUpdateView(); - - if (debugPainting) kDebug (13030) << "GOT PAINT EVENT: Region" << e->region(); - - const QRect& unionRect = e->rect(); - - int xStart = startX() + unionRect.x(); - int xEnd = xStart + unionRect.width(); - uint h = renderer()->lineHeight(); - uint startz = (unionRect.y() / h); - uint endz = startz + 1 + (unionRect.height() / h); - uint lineRangesSize = cache()->viewCacheLineCount(); - - QPainter paint(this); - paint.setRenderHints (QPainter::Antialiasing); - - // TODO put in the proper places - renderer()->setCaretStyle(m_view->isOverwriteMode() ? KateRenderer::Block : KateRenderer::Line); - renderer()->setShowTabs(doc()->config()->showTabs()); - renderer()->setShowTrailingSpaces(doc()->config()->showSpaces()); - - int sy = startz * h; - paint.translate(unionRect.x(), startz * h); - - for (uint z=startz; z <= endz; z++) - { - if ( (z >= lineRangesSize) || (cache()->viewLine(z).line() == -1) ) - { - if (!(z >= lineRangesSize)) - cache()->viewLine(z).setDirty(false); - - paint.fillRect( 0, 0, unionRect.width(), h, renderer()->config()->backgroundColor() ); - } - else - { - //kDebug( 13030 )<<"KateViewInternal::paintEvent(QPaintEvent *e):cache()->viewLine"<viewLine(z); - - /* If viewLine() returns non-zero, then a document line was split - in several visual lines, and we're trying to paint visual line - that is not the first. In that case, this line was already - painted previously, since KateRenderer::paintTextLine paints - all visual lines. - Except if we're at the start of the region that needs to - be painted -- when no previous calls to paintTextLine were made. - */ - if (!thisLine.viewLine() || z == startz) { - // Don't bother if we're not in the requested update region - if (!e->region().contains(QRect(unionRect.x(), startz * h, unionRect.width(), h))) - continue; - - //kDebug (13030) << "paint text: line: " << thisLine.line() << " viewLine " << thisLine.viewLine() << " x: " << unionRect.x() << " y: " << sy - // << " width: " << xEnd-xStart << " height: " << h << endl; - - if (thisLine.viewLine()) - paint.translate(QPoint(0, h * - thisLine.viewLine())); - - // The paintTextLine function should be well behaved, but if not, this clipping may be needed - //paint.setClipRect(QRect(xStart, 0, xEnd - xStart, h * (thisLine.kateLineLayout()->viewLineCount()))); - - KTextEditor::Cursor pos = m_cursor; - renderer()->paintTextLine(paint, thisLine.kateLineLayout(), xStart, xEnd, &pos); - - //paint.setClipping(false); - - if (thisLine.viewLine()) - paint.translate(0, h * thisLine.viewLine()); - - thisLine.setDirty(false); - } - } - - paint.translate(0, h); - sy += h; - } -} - -void KateViewInternal::resizeEvent(QResizeEvent* e) -{ - bool expandedHorizontally = width() > e->oldSize().width(); - bool expandedVertically = height() > e->oldSize().height(); - bool heightChanged = height() != e->oldSize().height(); - - m_madeVisible = false; - - if (heightChanged) { - setAutoCenterLines(m_autoCenterLines, false); - m_cachedMaxStartPos.setPosition(-1, -1); - } - - if (m_view->dynWordWrap()) { - bool dirtied = false; - - for (int i = 0; i < cache()->viewCacheLineCount(); i++) { - // find the first dirty line - // the word wrap updateView algorithm is forced to check all lines after a dirty one - KateTextLayout viewLine = cache()->viewLine(i); - - if (viewLine.wrap() || viewLine.isRightToLeft() || viewLine.width() > width()) { - dirtied = true; - viewLine.setDirty(); - break; - } - } - - if (dirtied || heightChanged) { - updateView(true); - m_leftBorder->update(); - } - - if (width() < e->oldSize().width()) { - if (!m_view->wrapCursor()) { - // May have to restrain cursor to new smaller width... - if (m_cursor.column() > doc()->lineLength(m_cursor.line())) { - KateTextLayout thisLine = currentLayout(); - - KTextEditor::Cursor newCursor(m_cursor.line(), thisLine.endCol() + ((width() - thisLine.xOffset() - thisLine.width()) / renderer()->spaceWidth()) - 1); - updateCursor(newCursor); - } - } - } - - } else { - updateView(); - - if (expandedHorizontally && startX() > 0) - scrollColumns(startX() - (width() - e->oldSize().width())); - } - - if (expandedVertically) { - KTextEditor::Cursor max = maxStartPos(); - if (startPos() > max) - scrollPos(max); - } - emit m_view->displayRangeChanged(m_view); -} - -void KateViewInternal::scrollTimeout () -{ - if (m_scrollX || m_scrollY) - { - scrollLines (startPos().line() + (m_scrollY / (int) renderer()->lineHeight())); - placeCursor( QPoint( m_mouseX, m_mouseY ), true ); - } -} - -void KateViewInternal::cursorTimeout () -{ - if (!debugPainting && !m_view->viInputMode()) { - renderer()->setDrawCaret(!renderer()->drawCaret()); - paintCursor(); - } -} - -void KateViewInternal::textHintTimeout () -{ - m_textHintTimer.stop (); - - KateTextLayout thisLine = yToKateTextLayout(m_textHintMouseY); - - if (!thisLine.isValid()) return; - - if (m_textHintMouseX> (lineMaxCursorX(thisLine) - thisLine.startX())) return; - - KTextEditor::Cursor c = renderer()->xToCursor(cache()->textLayout(thisLine.start()), startX() + m_textHintMouseX, !m_view->wrapCursor()); - - QString tmp; - - emit m_view->needTextHint(c, tmp); - - if (!tmp.isEmpty()) kDebug(13030)<<"Hint text: "< 0) - m_cursorTimer.start ( KApplication::cursorFlashTime() / 2 ); - - paintCursor(); - - doc()->setActiveView( m_view ); - - // this will handle focus stuff in kateview - m_view->slotGotFocus (); -} - -void KateViewInternal::focusOutEvent (QFocusEvent *) -{ - //if (m_view->isCompletionActive()) - //m_view->abortCompletion(); - - m_cursorTimer.stop(); - m_view->renderer()->setDrawCaret(true); - paintCursor(); - - m_textHintTimer.stop(); - - m_view->slotLostFocus (); -} - -void KateViewInternal::doDrag() -{ - m_dragInfo.state = diDragging; - m_dragInfo.dragObject = new QDrag(this); - QMimeData *mimeData=new QMimeData(); - mimeData->setText(m_view->selectionText()); - m_dragInfo.dragObject->setMimeData(mimeData); - m_dragInfo.dragObject->start(Qt::MoveAction); -} - -void KateViewInternal::dragEnterEvent( QDragEnterEvent* event ) -{ - if (event->source()==this) event->setDropAction(Qt::MoveAction); - event->setAccepted( (event->mimeData()->hasText() && doc()->isReadWrite()) || - KUrl::List::canDecode(event->mimeData()) ); -} - -void KateViewInternal::fixDropEvent(QDropEvent* event) { - if (event->source()!=this) event->setDropAction(Qt::CopyAction); - else { - Qt::DropAction action=Qt::MoveAction; -#ifdef Q_WS_MAC - if(event->keyboardModifiers() & Qt::AltModifier) - action = Qt::CopyAction; -#else - if (event->keyboardModifiers() & Qt::ControlModifier) - action = Qt::CopyAction; -#endif - event->setDropAction(action); - } -} - -void KateViewInternal::dragMoveEvent( QDragMoveEvent* event ) -{ - // track the cursor to the current drop location - placeCursor( event->pos(), true, false ); - - // important: accept action to switch between copy and move mode - // without this, the text will always be copied. - fixDropEvent(event); -} - -void KateViewInternal::dropEvent( QDropEvent* event ) -{ - if ( KUrl::List::canDecode(event->mimeData()) ) { - - emit dropEventPass(event); - - } else if ( event->mimeData()->hasText() && doc()->isReadWrite() ) { - - QString text=event->mimeData()->text(); - - // is the source our own document? - bool priv = false; - if (KateViewInternal* vi = qobject_cast(event->source())) - priv = doc()->ownedView( vi->m_view ); - - // dropped on a text selection area? - bool selected = m_view->cursorSelected(m_cursor); - - fixDropEvent(event); - - if( priv && selected && event->dropAction() != Qt::CopyAction ) { - // this is a drag that we started and dropped on our selection - // ignore this case - return; - } - - // fix the cursor position before editStart(), so that it is correctly - // stored for the undo action - KTextEditor::Cursor targetCursor(m_cursor); // backup current cursor - int selectionWidth = m_view->selectionRange().columnWidth(); // for block selection - int selectionHeight = m_view->selectionRange().numberOfLines(); // for block selection - - if ( event->dropAction() != Qt::CopyAction ) { - editSetCursor(m_view->selectionRange().end()); - } else { - m_view->clearSelection(); - } - - // use one transaction - doc()->editStart (); - - // on move: remove selected text; on copy: duplicate text - doc()->insertText(targetCursor, text, m_view->blockSelection()); - - Kate::TextCursor startCursor(doc()->buffer(), targetCursor, KTextEditor::MovingCursor::MoveOnInsert); - - if ( event->dropAction() != Qt::CopyAction ) - m_view->removeSelectedText(); - - Kate::TextCursor endCursor1(doc()->buffer(), startCursor, KTextEditor::MovingCursor::MoveOnInsert); - - if ( !m_view->blockSelection() ) { - endCursor1.move(text.length()); - } else { - endCursor1.setColumn(startCursor.column()+selectionWidth); - endCursor1.setLine(startCursor.line()+selectionHeight); - } - - KTextEditor::Cursor endCursor(endCursor1); - kDebug( 13030 )<editEnd (); - - event->acceptProposedAction(); - updateView(); - } - - // finally finish drag and drop mode - m_dragInfo.state = diNone; - // important, because the eventFilter`s DragLeave does not occur - stopDragScroll(); -} -//END EVENT HANDLING STUFF - -void KateViewInternal::clear() -{ - m_startPos.setPosition (0, 0); - m_displayCursor = KTextEditor::Cursor(0, 0); - m_cursor.setPosition(0, 0); - updateView(true); -} - -void KateViewInternal::wheelEvent(QWheelEvent* e) -{ - if (m_lineScroll->minimum() != m_lineScroll->maximum() && e->orientation() != Qt::Horizontal) { - // React to this as a vertical event - if ( ( e->modifiers() & Qt::ControlModifier ) || ( e->modifiers() & Qt::ShiftModifier ) ) { - if (e->delta() > 0) - scrollPrevPage(); - else - scrollNextPage(); - } else { - QApplication::sendEvent(m_lineScroll, e); - } - - } else if (columnScrollingPossible()) { - QWheelEvent copy = *e; - QApplication::sendEvent(m_columnScroll, ©); - - } else { - e->ignore(); - } -} - -void KateViewInternal::startDragScroll() -{ - if ( !m_dragScrollTimer.isActive() ) { - m_dragScrollTimer.start( s_scrollTime ); - } -} - -void KateViewInternal::stopDragScroll() -{ - m_dragScrollTimer.stop(); - updateView(); -} - -void KateViewInternal::doDragScroll() -{ - QPoint p = this->mapFromGlobal( QCursor::pos() ); - - int dx = 0, dy = 0; - if ( p.y() < s_scrollMargin ) { - dy = p.y() - s_scrollMargin; - } else if ( p.y() > height() - s_scrollMargin ) { - dy = s_scrollMargin - (height() - p.y()); - } - - if ( p.x() < s_scrollMargin ) { - dx = p.x() - s_scrollMargin; - } else if ( p.x() > width() - s_scrollMargin ) { - dx = s_scrollMargin - (width() - p.x()); - } - - dy /= 4; - - if (dy) - scrollLines(startPos().line() + dy); - - if (columnScrollingPossible () && dx) - scrollColumns(qMin (m_startX + dx, m_columnScroll->maximum())); - - if (!dy && !dx) - stopDragScroll(); -} - -void KateViewInternal::enableTextHints(int timeout) -{ - m_textHintTimeout=timeout; - m_textHintEnabled=true; - m_textHintTimer.start(timeout); -} - -void KateViewInternal::disableTextHints() -{ - m_textHintEnabled=false; - m_textHintTimer.stop (); -} - -//BEGIN EDIT STUFF -void KateViewInternal::editStart() -{ - editSessionNumber++; - - if (editSessionNumber > 1) - return; - - editIsRunning = true; - editOldCursor = m_cursor; -} - -void KateViewInternal::editEnd(int editTagLineStart, int editTagLineEnd, bool tagFrom) -{ - if (editSessionNumber == 0) - return; - - editSessionNumber--; - - if (editSessionNumber > 0) - return; - - doc()->buffer().ensureHighlighted(endLine()); - - // fix start position, might have moved from column 0 - m_startPos.setPosition (m_startPos.line(), 0); - - if (tagFrom && (editTagLineStart <= int(doc()->getRealLine(startLine())))) - tagAll(); - else - tagLines (editTagLineStart, tagFrom ? qMax(doc()->lastLine() + 1, editTagLineEnd) : editTagLineEnd, true); - - if (editOldCursor == m_cursor.toCursor()) - updateBracketMarks(); - - updateView(true); - - if (editOldCursor != m_cursor.toCursor() || m_view == doc()->activeView()) - { - m_madeVisible = false; - updateCursor ( m_cursor, true ); - } - - editIsRunning = false; -} - -void KateViewInternal::editSetCursor (const KTextEditor::Cursor &_cursor) -{ - if (m_cursor.toCursor() != _cursor) - { - m_cursor.setPosition(_cursor); - } -} -//END - -void KateViewInternal::viewSelectionChanged () -{ - m_selectAnchor = KTextEditor::Cursor::invalid(); - // Do NOT nuke the entire range! The reason is that a shift+DC selection - // might (correctly) set the range to be empty (i.e. start() == end()), and - // subsequent dragging might shrink the selection into non-existence. When - // this happens, we use the cached end to restore the cached start so that - // updateSelection is not confused. See also comments in updateSelection. - m_selectionCached.start() = KTextEditor::Cursor::invalid(); -// updateView(true); -} - -KateLayoutCache* KateViewInternal::cache( ) const -{ - return m_layoutCache; -} - -KTextEditor::Cursor KateViewInternal::toRealCursor( const KTextEditor::Cursor & virtualCursor ) const -{ - return KTextEditor::Cursor(doc()->getRealLine(virtualCursor.line()), virtualCursor.column()); -} - -KTextEditor::Cursor KateViewInternal::toVirtualCursor( const KTextEditor::Cursor & realCursor ) const -{ - return KTextEditor::Cursor(doc()->getVirtualLine(realCursor.line()), realCursor.column()); -} - -KateRenderer * KateViewInternal::renderer( ) const -{ - return m_view->renderer(); -} - -void KateViewInternal::mouseMoved( ) -{ - m_view->notifyMousePositionChanged(m_mouse); - m_view->updateRangesIn (KTextEditor::Attribute::ActivateMouseIn); -} - -void KateViewInternal::cursorMoved( ) -{ - m_view->updateRangesIn (KTextEditor::Attribute::ActivateCaretIn); -} - -bool KateViewInternal::rangeAffectsView(const KTextEditor::Range& range, bool realCursors) const -{ - int startLine = m_startPos.line(); - int endLine = startLine + (int)m_visibleLineCount; - - if ( realCursors ) { - startLine = (int)doc()->getRealLine(startLine); - endLine = (int)doc()->getRealLine(endLine); - } - - return (range.end().line() >= startLine) || (range.start().line() <= endLine); -} - -//BEGIN IM INPUT STUFF -QVariant KateViewInternal::inputMethodQuery ( Qt::InputMethodQuery query ) const -{ - switch (query) { - case Qt::ImMicroFocus: { - // Cursor placement code is changed for Asian input method that - // shows candidate window. This behavior is same as Qt/E 2.3.7 - // which supports Asian input methods. Asian input methods need - // start point of IM selection text to place candidate window as - // adjacent to the selection text. - KTextEditor::Cursor c = m_imPreeditRange ? m_imPreeditRange->start() : m_cursor; - return QRect (cursorToCoordinate(c, true, false), QSize(0, renderer()->lineHeight())); - } - - case Qt::ImFont: - return renderer()->currentFont(); - - case Qt::ImCursorPosition: - return m_imPreeditRange ? m_imPreeditRange->start().column() : 0; - - case Qt::ImSurroundingText: - if (Kate::TextLine l = doc()->kateTextLine(m_cursor.line())) - return l->string(); - else - return QString(); - - case Qt::ImCurrentSelection: - if (m_view->selection()) - return m_view->selectionText(); - else - return QString(); - default: - /* values: ImMaximumTextLength and ImAnchorPosition */ - break; - } - - return QWidget::inputMethodQuery(query); -} - -void KateViewInternal::inputMethodEvent(QInputMethodEvent* e) -{ - if ( doc()->readOnly() ) { - e->ignore(); - return; - } - - //kDebug( 13030 ) << "Event: cursor" << m_cursor << "commit" << e->commitString() << "preedit" << e->preeditString() << "replacement start" << e->replacementStart() << "length" << e->replacementLength(); - - bool createdPreedit = false; - if (!m_imPreeditRange) { - createdPreedit = true; - m_imPreeditRange = doc()->newMovingRange (KTextEditor::Range(m_cursor, m_cursor), KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); - } - - if (!m_imPreeditRange->toRange().isEmpty()) { - doc()->inputMethodStart(); - doc()->removeText(*m_imPreeditRange); - doc()->inputMethodEnd(); - } - - if (!e->commitString().isEmpty() || e->replacementLength()) { - m_view->removeSelectedText(); - - KTextEditor::Range preeditRange = *m_imPreeditRange; - - KTextEditor::Cursor start(m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + e->replacementStart()); - KTextEditor::Cursor removeEnd = start + KTextEditor::Cursor(0, e->replacementLength()); - - doc()->editStart(); - if (start != removeEnd) - doc()->removeText(KTextEditor::Range(start, removeEnd)); - if (!e->commitString().isEmpty()) { - // if the input method event is text that should be inserted, call KateDocument::typeChars() - // with the text. that method will handle the input and take care of overwrite mode, etc. - doc()->typeChars(m_view, e->commitString()); - } - doc()->editEnd(); - - // Revert to the same range as above - m_imPreeditRange->setRange(preeditRange); - } - - if (!e->preeditString().isEmpty()) { - doc()->inputMethodStart(); - doc()->insertText(m_imPreeditRange->start(), e->preeditString()); - doc()->inputMethodEnd(); - // The preedit range gets automatically repositioned - } - - // Finished this input method context? - if (m_imPreeditRange && e->preeditString().isEmpty()) { - // delete the range and reset the pointer - delete m_imPreeditRange; - m_imPreeditRange = 0L; - qDeleteAll (m_imPreeditRangeChildren); - m_imPreeditRangeChildren.clear (); - - if ( KApplication::cursorFlashTime() > 0 ) - renderer()->setDrawCaret(false); - renderer()->setCaretOverrideColor(QColor()); - - e->accept(); - return; - } - - KTextEditor::Cursor newCursor = m_cursor; - bool hideCursor = false; - QColor caretColor; - - if (m_imPreeditRange) { - qDeleteAll (m_imPreeditRangeChildren); - m_imPreeditRangeChildren.clear (); - - int decorationColumn = 0; - foreach (const QInputMethodEvent::Attribute &a, e->attributes()) { - if (a.type == QInputMethodEvent::Cursor) { - newCursor = m_imPreeditRange->start() + KTextEditor::Cursor(0, a.start); - hideCursor = !a.length; - QColor c = qvariant_cast(a.value); - if (c.isValid()) - caretColor = c; - - } else if (a.type == QInputMethodEvent::TextFormat) { - QTextCharFormat f = qvariant_cast(a.value).toCharFormat(); - if (f.isValid() && decorationColumn <= a.start) { - KTextEditor::Range fr(m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + a.start, m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + a.start + a.length); - KTextEditor::MovingRange* formatRange = doc()->newMovingRange (fr); - KTextEditor::Attribute::Ptr attribute(new KTextEditor::Attribute()); - attribute->merge(f); - formatRange->setAttribute(attribute); - decorationColumn = a.start + a.length; - m_imPreeditRangeChildren.push_back (formatRange); - } - } - } - } - - renderer()->setDrawCaret(hideCursor); - renderer()->setCaretOverrideColor(caretColor); - - if (newCursor != m_cursor.toCursor()) - updateCursor(newCursor); - - e->accept(); -} - -//END IM INPUT STUFF - -ViMode KateViewInternal::getCurrentViMode() -{ - return getViInputModeManager()->getCurrentViMode(); -} - -KateViInputModeManager* KateViewInternal::getViInputModeManager() -{ - if (!m_viInputModeManager) { - m_viInputModeManager = new KateViInputModeManager(m_view, this); - } - - return m_viInputModeManager; -} - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/view/kateviewinternal.h b/part/view/kateviewinternal.h deleted file mode 100644 index 1eec39f..0000000 --- a/part/view/kateviewinternal.h +++ /dev/null @@ -1,439 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 2002-2007 Hamish Rodda - Copyright (C) 2002 John Firebaugh - Copyright (C) 2002 Joseph Wenninger - Copyright (C) 2002 Christoph Cullmann - Copyright (C) 2007 Mirko Stocker - - Based on: - KWriteView : Copyright (C) 1999 Jochen Wilhelmy - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _KATE_VIEW_INTERNAL_ -#define _KATE_VIEW_INTERNAL_ - -#include - -#include "katetextcursor.h" -#include "katelinelayout.h" -#include "katetextline.h" -#include "katedocument.h" -#include "kateview.h" - -#include -#include -#include -#include -#include -#include - -namespace KTextEditor { - class MovingRange; -} - -class KateIconBorder; -class KateScrollBar; -class KateTextLayout; - -class KateViInputModeManager; - -class QScrollBar; - -class KateViewInternal : public QWidget -{ - Q_OBJECT - - friend class KateView; - friend class KateIconBorder; - friend class KateScrollBar; - friend class CalculatingCursor; - friend class BoundedCursor; - friend class WrappingCursor; - friend class KateViModeBase; - - public: - enum Bias - { - left = -1, - none = 0, - right = 1 - }; - - public: - KateViewInternal ( KateView *view ); - ~KateViewInternal (); - KateView *view() const { return m_view; } - - //BEGIN EDIT STUFF - public: - void editStart (); - void editEnd (int editTagLineStart, int editTagLineEnd, bool tagFrom); - - void editSetCursor (const KTextEditor::Cursor &cursor); - - private: - uint editSessionNumber; - bool editIsRunning; - KTextEditor::Cursor editOldCursor; - //END - - //BEGIN TAG & CLEAR & UPDATE STUFF - public: - bool tagLine (const KTextEditor::Cursor& virtualCursor); - - bool tagLines (int start, int end, bool realLines = false); - // cursors not const references as they are manipulated within - bool tagLines (KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors = false); - - bool tagRange(const KTextEditor::Range& range, bool realCursors); - - void tagAll (); - - void updateDirty(); - - void clear (); - //END - - private Q_SLOTS: - // Updates the view and requests a redraw. - void updateView (bool changed = false, int viewLinesScrolled = 0); - - private: - // Actually performs the updating, but doesn't call update(). - void doUpdateView(bool changed = false, int viewLinesScrolled = 0); - void makeVisible (const KTextEditor::Cursor& c, int endCol, bool force = false, bool center = false, bool calledExternally = false); - - public: - // Start Position is a virtual cursor - KTextEditor::Cursor startPos() const { return m_startPos; } - int startLine () const { return m_startPos.line(); } - int startX () const { return m_startX; } - - KTextEditor::Cursor endPos () const; - int endLine () const; - - KateTextLayout yToKateTextLayout(int y) const; - - void prepareForDynWrapChange(); - void dynWrapChanged(); - - public Q_SLOTS: - void slotIncFontSizes(); - void slotDecFontSizes(); - - private Q_SLOTS: - void scrollLines(int line); // connected to the sliderMoved of the m_lineScroll - void scrollViewLines(int offset); - void scrollAction(int action); - void scrollNextPage(); - void scrollPrevPage(); - void scrollPrevLine(); - void scrollNextLine(); - void scrollColumns (int x); // connected to the valueChanged of the m_columnScroll - void viewSelectionChanged (); - - public: - void doReturn(); - void doSmartNewline(); - void doDelete(); - void doBackspace(); - void doTabulator(); - void doTranspose(); - void doDeleteWordLeft(); - void doDeleteWordRight(); - - void cursorLeft(bool sel=false); - void cursorRight(bool sel=false); - void wordLeft(bool sel=false); - void wordRight(bool sel=false); - void home(bool sel=false); - void end(bool sel=false); - void cursorUp(bool sel=false); - void cursorDown(bool sel=false); - void cursorToMatchingBracket(bool sel=false); - void scrollUp(); - void scrollDown(); - void topOfView(bool sel=false); - void bottomOfView(bool sel=false); - void pageUp(bool sel=false); - void pageDown(bool sel=false); - void top(bool sel=false); - void bottom(bool sel=false); - void top_home(bool sel=false); - void bottom_end(bool sel=false); - - KTextEditor::Cursor getCursor() const { return m_cursor; } - KTextEditor::Cursor getMouse() const { return m_mouse; } - - QPoint cursorToCoordinate(const KTextEditor::Cursor& cursor, bool realCursor = true, bool includeBorder = true) const; - //Always works on coordinates of the whole widget, eg. offsetted by the border - KTextEditor::Cursor coordinatesToCursor(const QPoint& coord) const; - QPoint cursorCoordinates(bool includeBorder = true) const; - KTextEditor::Cursor findMatchingBracket(); - - // EVENT HANDLING STUFF - IMPORTANT - private: - void fixDropEvent(QDropEvent *event); - protected: - virtual void hideEvent(QHideEvent* e); - virtual void paintEvent(QPaintEvent *e); - virtual bool eventFilter( QObject *obj, QEvent *e ); - virtual void keyPressEvent( QKeyEvent* ); - virtual void keyReleaseEvent( QKeyEvent* ); - virtual void resizeEvent( QResizeEvent* ); - virtual void mousePressEvent( QMouseEvent* ); - virtual void mouseDoubleClickEvent( QMouseEvent* ); - virtual void mouseReleaseEvent( QMouseEvent* ); - virtual void mouseMoveEvent( QMouseEvent* ); - virtual void leaveEvent( QEvent* ); - virtual void dragEnterEvent( QDragEnterEvent* ); - virtual void dragMoveEvent( QDragMoveEvent* ); - virtual void dropEvent( QDropEvent* ); - virtual void showEvent ( QShowEvent *); - virtual void wheelEvent(QWheelEvent* e); - virtual void focusInEvent (QFocusEvent *); - virtual void focusOutEvent (QFocusEvent *); - virtual void inputMethodEvent(QInputMethodEvent* e); - - void contextMenuEvent ( QContextMenuEvent * e ); - - private Q_SLOTS: - void tripleClickTimeout(); - - Q_SIGNALS: - // emitted when KateViewInternal is not handling its own URI drops - void dropEventPass(QDropEvent*); - - private Q_SLOTS: - void slotRegionVisibilityChangedAt(unsigned int,bool clear_cache); - void slotRegionBeginEndAddedRemoved(unsigned int); - void slotCodeFoldingChanged(); - - private: - void moveChar( Bias bias, bool sel ); - void moveEdge( Bias bias, bool sel ); - KTextEditor::Cursor maxStartPos(bool changed = false); - void scrollPos(KTextEditor::Cursor& c, bool force = false, bool calledExternally = false); - void scrollLines( int lines, bool sel ); - - int linesDisplayed() const; - - int lineToY(int viewLine) const; - - void updateSelection( const KTextEditor::Cursor&, bool keepSel ); - void setSelection( const KTextEditor::Range& ); - void moveCursorToSelectionEdge(); - //The smart-lock should not be locked when this is called - void updateCursor( const KTextEditor::Cursor& newCursor, bool force = false, bool center = false, bool calledExternally = false ); - void updateBracketMarks(); - - void paintCursor(); - - void placeCursor( const QPoint& p, bool keepSelection = false, bool updateSelection = true ); - bool isTargetSelected( const QPoint& p ); - //Returns whether the given range affects the area currently visible in the view - bool rangeAffectsView(const KTextEditor::Range& range, bool realCursors) const; - - void doDrag(); - - KateRenderer* renderer() const; - - KateView *m_view; - class KateIconBorder *m_leftBorder; - - int m_mouseX; - int m_mouseY; - int m_scrollX; - int m_scrollY; - - Qt::CursorShape m_mouseCursor; - - Kate::TextCursor m_cursor; - KTextEditor::Cursor m_mouse; - KTextEditor::Cursor m_displayCursor; - - bool m_possibleTripleClick; - - //Whether the current completion-item was expanded while the last press of ALT - bool m_completionItemExpanded; - QTime m_altDownTime; - - // Bracket mark and corresponding decorative ranges - KTextEditor::MovingRange *m_bm, *m_bmStart, *m_bmEnd; - void updateBracketMarkAttributes(); - - enum DragState { diNone, diPending, diDragging }; - - struct _dragInfo { - DragState state; - QPoint start; - QDrag* dragObject; - } m_dragInfo; - - uint m_iconBorderHeight; - - // - // line scrollbar + first visible (virtual) line in the current view - // - KateScrollBar *m_lineScroll; - QWidget* m_dummy; - - // These are now cursors to account for word-wrap. - // Start Position is a virtual cursor - Kate::TextCursor m_startPos; - //Count of lines that are visible behind m_startPos. - //This does not respect dynamic word wrap, so take it as an approximation. - uint m_visibleLineCount; - - // This is set to false on resize or scroll (other than that called by makeVisible), - // so that makeVisible is again called when a key is pressed and the cursor is in the same spot - bool m_madeVisible; - bool m_shiftKeyPressed; - - // How many lines to should be kept visible above/below the cursor when possible - void setAutoCenterLines(int viewLines, bool updateView = true); - int m_autoCenterLines; - int m_minLinesVisible; - - // - // column scrollbar + x position - // - QScrollBar *m_columnScroll; - int m_startX; - - // has selection changed while your mouse or shift key is pressed - bool m_selChangedByUser; - KTextEditor::Cursor m_selectAnchor; - - enum SelectionMode { Default=0, Mouse, Word, Line }; ///< for drag selection. - uint m_selectionMode; - // when drag selecting after double/triple click, keep the initial selected - // word/line independent of direction. - // They get set in the event of a double click, and is used with mouse move + leftbutton - KTextEditor::Range m_selectionCached; - - // maximal length of textlines visible from given startLine - int maxLen(int startLine); - - // are we allowed to scroll columns? - bool columnScrollingPossible (); - - // returns the maximum X value / col value a cursor can take for a specific line range - int lineMaxCursorX(const KateTextLayout& line); - int lineMaxCol(const KateTextLayout& line); - - class KateLayoutCache* cache() const; - KateLayoutCache* m_layoutCache; - - // convenience methods - KateTextLayout currentLayout() const; - KateTextLayout previousLayout() const; - KateTextLayout nextLayout() const; - - // find the cursor offset by (offset) view lines from a cursor. - // when keepX is true, the column position will be calculated based on the x - // position of the specified cursor. - KTextEditor::Cursor viewLineOffset(const KTextEditor::Cursor& virtualCursor, int offset, bool keepX = false); - - KTextEditor::Cursor toRealCursor(const KTextEditor::Cursor& virtualCursor) const; - KTextEditor::Cursor toVirtualCursor(const KTextEditor::Cursor& realCursor) const; - - // These variable holds the most recent maximum real & visible column number - bool m_preserveX; - int m_preservedX; - - bool m_updatingView; - int m_wrapChangeViewLine; - KTextEditor::Cursor m_cachedMaxStartPos; - - private Q_SLOTS: - void doDragScroll(); - void startDragScroll(); - void stopDragScroll(); - - private: - // Timers - QTimer m_dragScrollTimer; - QTimer m_scrollTimer; - QTimer m_cursorTimer; - QTimer m_textHintTimer; - - static const int s_scrollTime = 30; - static const int s_scrollMargin = 16; - - private Q_SLOTS: - void scrollTimeout (); - void cursorTimeout (); - void textHintTimeout (); - - //TextHint - public: - void enableTextHints(int timeout); - void disableTextHints(); - - private: - bool m_textHintEnabled; - int m_textHintTimeout; - int m_textHintMouseX; - int m_textHintMouseY; - - /** - * IM input stuff - */ - public: - virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const; - - private: - KTextEditor::MovingRange *m_imPreeditRange; - QList m_imPreeditRangeChildren; - - private: - void mouseMoved(); - void cursorMoved(); - - private: - bool m_smartDirty; - - private: - inline KateDocument *doc() { return m_view->doc(); } - inline KateDocument *doc() const { return m_view->doc(); } - - // vi Mode - private: - bool m_viInputMode; - bool m_viInputModeStealKeys; - - /** - * returns the current vi mode - */ - ViMode getCurrentViMode(); - - /** - * an instance of KateViInputModeManager. used for interacting with the vi input mode when - * enabled - */ - KateViInputModeManager* m_viInputModeManager; - - /** - * @return a pointer to a KateViInputModeManager - */ - KateViInputModeManager* getViInputModeManager(); -}; - -#endif - -// kate: space-indent on; indent-width 2; replace-tabs on; diff --git a/part/vimode/katevicommand.cpp b/part/vimode/katevicommand.cpp deleted file mode 100644 index 490fbcd..0000000 --- a/part/vimode/katevicommand.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevicommand.h" - -KateViCommand::KateViCommand( KateViNormalMode *parent, QString pattern, - bool( KateViNormalMode::*commandMethod)(), unsigned int flags ) -{ - m_parent = parent; - m_pattern = KateViKeyParser::getInstance()->encodeKeySequence( pattern ); - m_flags = flags; - m_ptr2commandMethod = commandMethod; -} - -KateViCommand::~KateViCommand() -{ -} - -bool KateViCommand::execute() const -{ - return ( m_parent->*m_ptr2commandMethod)(); -} - -bool KateViCommand::matches( const QString &pattern ) const -{ - if ( !( m_flags & REGEX_PATTERN ) ) - return m_pattern.startsWith( pattern ); - else { - QRegExp re( m_pattern ); - re.exactMatch( pattern ); - return ( re.matchedLength() == pattern.length() ); - } -} - -bool KateViCommand::matchesExact( const QString &pattern ) const -{ - if ( !( m_flags & REGEX_PATTERN ) ) - return ( m_pattern == pattern ); - else { - QRegExp re( m_pattern ); - return re.exactMatch( pattern ); - } -} diff --git a/part/vimode/katevicommand.h b/part/vimode/katevicommand.h deleted file mode 100644 index 52b9287..0000000 --- a/part/vimode/katevicommand.h +++ /dev/null @@ -1,59 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevinormalmode.h" -#include "katevikeyparser.h" - -#ifndef KATE_VI_COMMAND_H -#define KATE_VI_COMMAND_H - -class KateViNormalMode; - -enum KateViCommandFlags { - REGEX_PATTERN = 0x1, // the pattern is a regex - NEEDS_MOTION = 0x2, // the command needs a motion before it can be executed - SHOULD_NOT_RESET = 0x4, // the command should not cause the current mode to be left - IS_CHANGE = 0x8 // the command changes the buffer -}; - -class KateViCommand { - public: - KateViCommand( KateViNormalMode *parent, QString pattern, - bool ( KateViNormalMode::*pt2Func)(), unsigned int flags = 0 ); - ~KateViCommand(); - - bool matches( const QString &pattern ) const; - bool matchesExact( const QString &pattern ) const; - bool execute() const; - const QString pattern() const { return m_pattern; } - bool isRegexPattern() const { return m_flags & REGEX_PATTERN; } - bool needsMotion() const { return m_flags & NEEDS_MOTION; } - bool shouldReset() const { return !( m_flags & SHOULD_NOT_RESET ); } - bool isChange() const { return m_flags & IS_CHANGE; } - - protected: - KateViNormalMode *m_parent; - QString m_pattern; - unsigned int m_flags; - bool ( KateViNormalMode::*m_ptr2commandMethod)(); - KateViKeyParser *m_keyParser; -}; - -#endif diff --git a/part/vimode/kateviglobal.cpp b/part/vimode/kateviglobal.cpp deleted file mode 100644 index 85afc41..0000000 --- a/part/vimode/kateviglobal.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2009 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateviglobal.h" -#include "katevikeyparser.h" - -#include "kconfiggroup.h" -#include "kdebug.h" -#include -#include - -KateViGlobal::KateViGlobal() -{ - m_numberedRegisters = new QList; - m_registers = new QMap; -} - -KateViGlobal::~KateViGlobal() -{ - delete m_numberedRegisters; - delete m_registers; -} - -void KateViGlobal::writeConfig( KConfigGroup &config ) const -{ - config.writeEntry( "Normal Mode Mapping Keys", getMappings( NormalMode, true ) ); - QStringList l; - foreach( const QString &s, getMappings( NormalMode ) ) { - l << KateViKeyParser::getInstance()->decodeKeySequence( getMapping( NormalMode, s ) ); - } - config.writeEntry( "Normal Mode Mappings", l ); -} - -void KateViGlobal::readConfig( const KConfigGroup &config ) -{ - QStringList keys = config.readEntry( "Normal Mode Mapping Keys", QStringList() ); - QStringList mappings = config.readEntry( "Normal Mode Mappings", QStringList() ); - - // sanity check - if ( keys.length() == mappings.length() ) { - for ( int i = 0; i < keys.length(); i++ ) { - addMapping( NormalMode, keys.at( i ), mappings.at( i ) ); - kDebug( 13070 ) << "Mapping " << keys.at( i ) << " -> " << mappings.at( i ); - } - } else { - kDebug( 13070 ) << "Error when reading mappings from config: number of keys != number of values"; - } -} - -QString KateViGlobal::getRegisterContent( const QChar ® ) const -{ - QString regContent; - QChar _reg = ( reg != '"' ? reg : m_defaultRegister ); - - if ( _reg >= '1' && _reg <= '9' ) { // numbered register - int index = QString( _reg ).toInt()-1; - if ( m_numberedRegisters->size() > index) { - regContent = m_numberedRegisters->at( index ); - } - } else if ( _reg == '+' ) { // system clipboard register - regContent = QApplication::clipboard()->text( QClipboard::Clipboard ); - } else if ( _reg == '*' ) { // system selection register - regContent = QApplication::clipboard()->text( QClipboard::Selection ); - } else { // regular, named register - if ( m_registers->contains( _reg ) ) { - regContent = m_registers->value( _reg ); - } - } - - return regContent; -} - -void KateViGlobal::addToNumberedRegister( const QString &text ) -{ - if ( m_numberedRegisters->size() == 9 ) { - m_numberedRegisters->removeLast(); - } - - // register 0 is used for the last yank command, so insert at position 1 - m_numberedRegisters->prepend( text ); - - kDebug( 13070 ) << "Register 1-9:"; - for ( int i = 0; i < m_numberedRegisters->size(); i++ ) { - kDebug( 13070 ) << "\t Register " << i+1 << ": " << m_numberedRegisters->at( i ); - } -} - -void KateViGlobal::fillRegister( const QChar ®, const QString &text ) -{ - // the specified register is the "black hole register", don't do anything - if ( reg == '_' ) { - return; - } - - if ( reg >= '1' && reg <= '9' ) { // "kill ring" registers - addToNumberedRegister( text ); - } else if ( reg == '+' ) { // system clipboard register - QApplication::clipboard()->setText( text, QClipboard::Clipboard ); - } else if ( reg == '*' ) { // system selection register - QApplication::clipboard()->setText( text, QClipboard::Selection ); - } else { - m_registers->insert( reg, text ); - } - - kDebug( 13070 ) << "Register " << reg << " set to " << getRegisterContent( reg ); - - if ( reg == '0' || reg == '1' || reg == '-' ) { - m_defaultRegister = reg; - kDebug( 13070 ) << "Register " << '"' << " set to point to \"" << reg; - } -} - -void KateViGlobal::addMapping( ViMode mode, const QString &from, const QString &to ) -{ - if ( !from.isEmpty() ) { - switch ( mode ) { - case NormalMode: - m_normalModeMappings[ KateViKeyParser::getInstance()->encodeKeySequence( from ) ] - = KateViKeyParser::getInstance()->encodeKeySequence( to ); - break; - default: - kDebug( 13070 ) << "Mapping not supported for given mode"; - } - } -} - -const QString KateViGlobal::getMapping( ViMode mode, const QString &from, bool decode ) const -{ - QString ret; - switch ( mode ) { - case NormalMode: - ret = m_normalModeMappings.value( from ); - break; - default: - kDebug( 13070 ) << "Mapping not supported for given mode"; - } - - if ( decode ) { - return KateViKeyParser::getInstance()->decodeKeySequence( ret ); - } - return ret; -} - -const QStringList KateViGlobal::getMappings( ViMode mode, bool decode ) const -{ - QStringList l; - QHash::const_iterator i; - switch (mode ) { - case NormalMode: - for (i = m_normalModeMappings.constBegin(); i != m_normalModeMappings.constEnd(); ++i) { - if ( decode ) { - l << KateViKeyParser::getInstance()->decodeKeySequence( i.key() ); - } else { - l << i.key(); - } - } - break; - default: - kDebug( 13070 ) << "Mapping not supported for given mode"; - } - - return l; -} - -void KateViGlobal::clearMappings( ViMode mode ) -{ - switch (mode ) { - case NormalMode: - m_normalModeMappings.clear(); - break; - default: - kDebug( 13070 ) << "Mapping not supported for given mode"; - } -} diff --git a/part/vimode/kateviglobal.h b/part/vimode/kateviglobal.h deleted file mode 100644 index 7cfac4c..0000000 --- a/part/vimode/kateviglobal.h +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_GLOBAL_H_INCLUDED -#define KATE_VI_GLOBAL_H_INCLUDED - -#include -#include -#include -#include -#include -#include "kateviinputmodemanager.h" - -class KConfigGroup; - -class KateViGlobal -{ -public: - KateViGlobal(); - ~KateViGlobal(); - - void writeConfig( KConfigGroup &config ) const; - void readConfig( const KConfigGroup &config ); - QString getRegisterContent( const QChar ® ) const; - void addToNumberedRegister( const QString &text ); - void fillRegister( const QChar ®, const QString &text); - const QMap* getRegisters() { return m_registers; } - - void clearMappings( ViMode mode ); - void addMapping( ViMode mode, const QString &from, const QString &to ); - const QString getMapping( ViMode mode, const QString &from, bool decode = false ) const; - const QStringList getMappings( ViMode mode, bool decode = false ) const; - -private: - // registers - QList *m_numberedRegisters; - QMap *m_registers; - QChar m_defaultRegister; - QString m_registerTemp; - - // mappings - QHash m_normalModeMappings; -}; - -#endif diff --git a/part/vimode/kateviinputmodemanager.cpp b/part/vimode/kateviinputmodemanager.cpp deleted file mode 100644 index f7fc6cc..0000000 --- a/part/vimode/kateviinputmodemanager.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 - 2009 Erlend Hamberg - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateviinputmodemanager.h" - -#include -#include -#include - -#include -#include - -#include "kateconfig.h" -#include "kateglobal.h" -#include "kateviglobal.h" -#include "katevinormalmode.h" -#include "kateviinsertmode.h" -#include "katevivisualmode.h" -#include "katevireplacemode.h" -#include "katevikeyparser.h" - -KateViInputModeManager::KateViInputModeManager(KateView* view, KateViewInternal* viewInternal) -{ - m_viNormalMode = new KateViNormalMode(this, view, viewInternal); - m_viInsertMode = new KateViInsertMode(this, view, viewInternal); - m_viVisualMode = new KateViVisualMode(this, view, viewInternal); - m_viReplaceMode = new KateViReplaceMode(this, view, viewInternal); - - m_currentViMode = NormalMode; - - m_view = view; - m_viewInternal = viewInternal; - - m_runningMacro = false; - - m_lastSearchBackwards = false; -} - -KateViInputModeManager::~KateViInputModeManager() -{ - delete m_viNormalMode; - delete m_viInsertMode; - delete m_viVisualMode; - delete m_viReplaceMode; -} - -bool KateViInputModeManager::handleKeypress(const QKeyEvent *e) -{ - bool res; - - // record key press so that it can be repeated - if (!isRunningMacro()) { - QKeyEvent copy( e->type(), e->key(), e->modifiers(), e->text() ); - appendKeyEventToLog( copy ); - } - - // FIXME: I think we're making things difficult for ourselves here. Maybe some - // more thought needs to go into the inheritance hierarchy. - switch(m_currentViMode) { - case NormalMode: - res = m_viNormalMode->handleKeypress(e); - break; - case InsertMode: - res = m_viInsertMode->handleKeypress(e); - break; - case VisualMode: - case VisualLineMode: - case VisualBlockMode: - res = m_viVisualMode->handleKeypress(e); - break; - case ReplaceMode: - res = m_viReplaceMode->handleKeypress(e); - break; - default: - kDebug( 13070 ) << "WARNING: Unhandled keypress"; - res = false; - } - - return res; -} - -void KateViInputModeManager::feedKeyPresses(const QString &keyPresses) const -{ - int key; - Qt::KeyboardModifiers mods; - QString text; - - kDebug( 13070 ) << "Repeating change"; - foreach(const QChar &c, keyPresses) { - QString decoded = KateViKeyParser::getInstance()->decodeKeySequence(QString(c)); - key = -1; - mods = Qt::NoModifier; - text.clear(); - - kDebug( 13070 ) << "\t" << decoded; - - if (decoded.length() > 1 ) { // special key - - // remove the angle brackets - decoded.remove(0, 1); - decoded.remove(decoded.indexOf(">"), 1); - kDebug( 13070 ) << "\t Special key:" << decoded; - - // check if one or more modifier keys where used - if (decoded.indexOf("s-") != -1 || decoded.indexOf("c-") != -1 - || decoded.indexOf("m-") != -1 || decoded.indexOf("m-") != -1) { - - int s = decoded.indexOf("s-"); - if (s != -1) { - mods |= Qt::ShiftModifier; - decoded.remove(s, 2); - } - - int c = decoded.indexOf("c-"); - if (c != -1) { - mods |= Qt::ControlModifier; - decoded.remove(c, 2); - } - - int a = decoded.indexOf("a-"); - if (a != -1) { - mods |= Qt::AltModifier; - decoded.remove(a, 2); - } - - int m = decoded.indexOf("m-"); - if (m != -1) { - mods |= Qt::MetaModifier; - decoded.remove(m, 2); - } - - if (decoded.length() > 1 ) { - key = KateViKeyParser::getInstance()->vi2qt(decoded); - } else { - key = int(decoded.at(0).toUpper().toAscii()); - text = decoded.at(0); - kDebug( 13070 ) << "###########" << key; - kDebug( 13070 ) << "###########" << Qt::Key_W; - } - } else { // no modifiers - key = KateViKeyParser::getInstance()->vi2qt(decoded); - } - } else { - key = decoded.at(0).unicode(); - text = decoded.at(0); - } - - QKeyEvent k(QEvent::KeyPress, key, mods, text); - - QCoreApplication::sendEvent(m_viewInternal, &k); - } -} - -void KateViInputModeManager::appendKeyEventToLog(const QKeyEvent &e) -{ - if ( e.key() != Qt::Key_Shift && e.key() != Qt::Key_Control - && e.key() != Qt::Key_Meta && e.key() != Qt::Key_Alt ) { - m_keyEventsLog.append(e); - } -} - -void KateViInputModeManager::storeChangeCommand() -{ - m_lastChange.clear(); - - for (int i = 0; i < m_keyEventsLog.size(); i++) { - int keyCode = m_keyEventsLog.at(i).key(); - QString text = m_keyEventsLog.at(i).text(); - int mods = m_keyEventsLog.at(i).modifiers(); - QChar key; - - if ( text.length() > 0 ) { - key = text.at(0); - } - - if ( text.isEmpty() || ( text.length() ==1 && text.at(0) < 0x20 ) - || ( mods != Qt::NoModifier && mods != Qt::ShiftModifier ) ) { - QString keyPress; - - keyPress.append( '<' ); - keyPress.append( ( mods & Qt::ShiftModifier ) ? "s-" : "" ); - keyPress.append( ( mods & Qt::ControlModifier ) ? "c-" : "" ); - keyPress.append( ( mods & Qt::AltModifier ) ? "a-" : "" ); - keyPress.append( ( mods & Qt::MetaModifier ) ? "m-" : "" ); - keyPress.append( keyCode <= 0xFF ? QChar( keyCode ) : KateViKeyParser::getInstance()->qt2vi( keyCode ) ); - keyPress.append( '>' ); - - key = KateViKeyParser::getInstance()->encodeKeySequence( keyPress ).at( 0 ); - } - - m_lastChange.append(key); - } -} - -void KateViInputModeManager::repeatLastChange() -{ - m_runningMacro = true; - feedKeyPresses(m_lastChange); - m_runningMacro = false; -} - -void KateViInputModeManager::changeViMode(ViMode newMode) -{ - m_currentViMode = newMode; -} - -ViMode KateViInputModeManager::getCurrentViMode() const -{ - return m_currentViMode; -} - -void KateViInputModeManager::viEnterNormalMode() -{ - bool moveCursorLeft = (m_currentViMode == InsertMode || m_currentViMode == ReplaceMode) - && m_viewInternal->getCursor().column() > 0; - - changeViMode(NormalMode); - - if ( moveCursorLeft ) { - m_viewInternal->cursorLeft(); - } - m_viewInternal->repaint (); -} - -void KateViInputModeManager::viEnterInsertMode() -{ - changeViMode(InsertMode); - m_viewInternal->repaint (); -} - -void KateViInputModeManager::viEnterVisualMode( ViMode mode ) -{ - changeViMode( mode ); - - m_viewInternal->repaint (); - getViVisualMode()->setVisualModeType( mode ); - getViVisualMode()->init(); -} - -void KateViInputModeManager::viEnterReplaceMode() -{ - changeViMode(ReplaceMode); - m_viewInternal->repaint (); -} - - -KateViNormalMode* KateViInputModeManager::getViNormalMode() -{ - return m_viNormalMode; -} - -KateViInsertMode* KateViInputModeManager::getViInsertMode() -{ - return m_viInsertMode; -} - -KateViVisualMode* KateViInputModeManager::getViVisualMode() -{ - return m_viVisualMode; -} - -KateViReplaceMode* KateViInputModeManager::getViReplaceMode() -{ - return m_viReplaceMode; -} - -const QString KateViInputModeManager::getVerbatimKeys() const -{ - QString cmd; - - switch (getCurrentViMode()) { - case NormalMode: - cmd = m_viNormalMode->getVerbatimKeys(); - break; - case InsertMode: - case ReplaceMode: - // ... - break; - case VisualMode: - case VisualLineMode: - case VisualBlockMode: - cmd = m_viVisualMode->getVerbatimKeys(); - break; - } - - return cmd; -} - -void KateViInputModeManager::readSessionConfig( const KConfigGroup& config ) -{ - QStringList names = config.readEntry( "ViRegisterNames", QStringList() ); - QStringList contents = config.readEntry( "ViRegisterContents", QStringList() ); - - // sanity check - if ( names.size() == contents.size() ) { - for ( int i = 0; i < names.size(); i++ ) { - KateGlobal::self()->viInputModeGlobal()->fillRegister( names.at( i ).at( 0 ), contents.at( i ) ); - } - } -} - -void KateViInputModeManager::writeSessionConfig( KConfigGroup& config ) -{ - const QMap* regs = KateGlobal::self()->viInputModeGlobal()->getRegisters(); - QStringList names, contents; - QMap::const_iterator i; - for (i = regs->constBegin(); i != regs->constEnd(); ++i) { - if ( i.value().length() <= 1000 ) { - names << i.key(); - contents << i.value(); - } else { - kDebug( 13070 ) << "Did not save contents of register " << i.key() << ": contents too long (" - << i.value().length() << " characters)"; - } - } - - config.writeEntry( "ViRegisterNames", names ); - config.writeEntry( "ViRegisterContents", contents ); -} diff --git a/part/vimode/kateviinputmodemanager.h b/part/vimode/kateviinputmodemanager.h deleted file mode 100644 index 99cc01d..0000000 --- a/part/vimode/kateviinputmodemanager.h +++ /dev/null @@ -1,206 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_INPUT_MODE_MANAGER_INCLUDED -#define KATE_VI_INPUT_MODE_MANAGER_INCLUDED - -#include -#include - -class KConfigGroup; -class KateView; -class KateViewInternal; -class KateViNormalMode; -class KateViInsertMode; -class KateViVisualMode; -class KateViReplaceMode; -class KateViKeyParser; -class QString; - -/** - * The four vi modes supported by Kate's vi input mode - */ -enum ViMode { - NormalMode, - InsertMode, - VisualMode, - VisualLineMode, - VisualBlockMode, - ReplaceMode -}; - -class KateViInputModeManager -{ -public: - KateViInputModeManager(KateView* view, KateViewInternal* viewInternal); - ~KateViInputModeManager(); - - /** - * feed key the given key press to the command parser - * @return true if keypress was is [part of a] command, false otherwise - */ - bool handleKeypress(const QKeyEvent *e); - - /** - * feed key the given list of key presses to the key handling code, one by one - */ - void feedKeyPresses(const QString &keyPresses) const; - - /** - * @return The current vi mode - */ - ViMode getCurrentViMode() const; - - const QString getVerbatimKeys() const; - - /** - * changes the current vi mode to the given mode - */ - void changeViMode(ViMode newMode); - - /** - * set normal mode to be the active vi mode and perform the needed setup work - */ - void viEnterNormalMode(); - - /** - * set insert mode to be the active vi mode and perform the needed setup work - */ - void viEnterInsertMode(); - - /** - * set visual mode to be the active vi mode and make the needed setup work - */ - void viEnterVisualMode( ViMode visualMode = VisualMode ); - - /** - * set replace mode to be the active vi mode and make the needed setup work - */ - void viEnterReplaceMode(); - - /** - * @return the KateViNormalMode instance - */ - KateViNormalMode* getViNormalMode(); - - /** - * @return the KateViInsertMode instance - */ - KateViInsertMode* getViInsertMode(); - - /** - * @return the KateViVisualMode instance - */ - KateViVisualMode* getViVisualMode(); - - /** - * @return the KateViReplaceMode instance - */ - KateViReplaceMode* getViReplaceMode(); - - /** - * @return true if running a macro - */ - bool isRunningMacro() const { return m_runningMacro; } - - /** - * append a QKeyEvent to the key event log - */ - void appendKeyEventToLog(const QKeyEvent &e); - - /** - * clear the key event log - */ - void clearLog() { m_keyEventsLog.clear(); } - - /** - * copy the contents of the key events log to m_lastChange so that it can be repeated - */ - void storeChangeCommand(); - - /** - * repeat last change by feeding the contents of m_lastChange to feedKeys() - */ - void repeatLastChange(); - - /** - * get the last search term used - */ - const QString getLastSearchPattern() const { return m_lastSearchPattern; } - - /** - * record a search term so that it will be used with 'n' and 'N' - */ - void setLastSearchPattern( const QString &p ) { m_lastSearchPattern = p; } - - /** - * get search direction of last search. (true if backwards, false if forwards) - */ - bool lastSearchBackwards() const { return m_lastSearchBackwards; } - - /** - * set search direction of last search. (true if backwards, false if forwards) - */ - void setLastSearchBackwards( bool b ) { m_lastSearchBackwards = b; } - - // session stuff - void readSessionConfig( const KConfigGroup& config ); - void writeSessionConfig( KConfigGroup& config ); - -private: - KateViNormalMode* m_viNormalMode; - KateViInsertMode* m_viInsertMode; - KateViVisualMode* m_viVisualMode; - KateViReplaceMode* m_viReplaceMode; - - ViMode m_currentViMode; - - KateView *m_view; - KateViewInternal *m_viewInternal; - KateViKeyParser *m_keyParser; - - /** - * set to true when running a macro (including using the '.' command) - */ - bool m_runningMacro; - - /** - * a continually updated list of the key events that was part of the last change. - * updated until it is copied to m_lastChange when change is completed. - */ - QList m_keyEventsLog; - - /** - * a list of the key events that was part of the last change. - */ - QString m_lastChange; - - /** - * the last pattern searched for - */ - QString m_lastSearchPattern; - - /** - * keeps track of whether the last search was done backwards or not. - */ - bool m_lastSearchBackwards; -}; - -#endif diff --git a/part/vimode/kateviinsertmode.cpp b/part/vimode/kateviinsertmode.cpp deleted file mode 100644 index 8a9cc21..0000000 --- a/part/vimode/kateviinsertmode.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kateviinsertmode.h" -#include "kateviinputmodemanager.h" -#include "kateview.h" -#include "kateviewinternal.h" -#include "kateconfig.h" -#include "katecompletionwidget.h" - -using KTextEditor::Cursor; - -KateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager, - KateView * view, KateViewInternal * viewInternal ) : KateViModeBase() -{ - m_view = view; - m_viewInternal = viewInternal; - m_viInputModeManager = viInputModeManager; -} - -KateViInsertMode::~KateViInsertMode() -{ -} - - -bool KateViInsertMode::commandInsertFromAbove() -{ - Cursor c( m_view->cursorPosition() ); - - if ( c.line() <= 0 ) { - return false; - } - - QString line = doc()->line( c.line()-1 ); - int tabWidth = doc()->config()->tabWidth(); - QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth ); - - if ( ch == QChar::Null ) { - return false; - } - - return doc()->insertText( c, ch ); -} - -bool KateViInsertMode::commandInsertFromBelow() -{ - Cursor c( m_view->cursorPosition() ); - - if ( c.line() >= doc()->lines()-1 ) { - return false; - } - - QString line = doc()->line( c.line()+1 ); - int tabWidth = doc()->config()->tabWidth(); - QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth ); - - if ( ch == QChar::Null ) { - return false; - } - - return doc()->insertText( c, ch ); -} - -bool KateViInsertMode::commandDeleteWord() -{ - Cursor c1( m_view->cursorPosition() ); - Cursor c2; - - c2 = findPrevWordStart( c1.line(), c1.column() ); - - if ( c2.line() != c1.line() ) { - if ( c1.column() == 0 ) { - c2.setColumn( doc()->line( c2.line() ).length() ); - } else { - c2.setColumn( 0 ); - c2.setLine( c2.line()+1 ); - } - } - - KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion ); - - return deleteRange( r, false, false ); -} - -bool KateViInsertMode::commandIndent() -{ - //return getViNormalMode()->commandIndentLine(); - return false; -} - -bool KateViInsertMode::commandUnindent() -{ - //return getViNormalMode()->commandUnindentLine(); - return false; -} - -bool KateViInsertMode::commandToFirstCharacterInFile() -{ - Cursor c; - - c.setLine( 0 ); - c.setColumn( 0 ); - - updateCursor( c ); - - return true; -} - -bool KateViInsertMode::commandToLastCharacterInFile() -{ - Cursor c; - - int lines = doc()->lines()-1; - c.setLine( lines ); - c.setColumn( doc()->line( lines ).length() ); - - updateCursor( c ); - - return true; -} - -bool KateViInsertMode::commandMoveOneWordLeft() -{ - Cursor c( m_view->cursorPosition() ); - c = findPrevWordStart( c.line(), c.column() ); - - updateCursor( c ); - return true; -} - -bool KateViInsertMode::commandMoveOneWordRight() -{ - Cursor c( m_view->cursorPosition() ); - c = findNextWordStart( c.line(), c.column() ); - - updateCursor( c ); - return true; -} - -bool KateViInsertMode::commandCompleteNext() -{ - if(m_view->completionWidget()->isCompletionActive()) { - m_view->completionWidget()->cursorDown(); - } else { - m_view->userInvokedCompletion(); - } - return true; -} - -bool KateViInsertMode::commandCompletePrevious() -{ - if(m_view->completionWidget()->isCompletionActive()) { - m_view->completionWidget()->cursorUp(); - } else { - m_view->userInvokedCompletion(); - m_view->completionWidget()->bottom(); - } - return true; -} - -/** - * checks if the key is a valid command - * @return true if a command was completed and executed, false otherwise - */ -bool KateViInsertMode::handleKeypress( const QKeyEvent *e ) -{ - // backspace should work even if the shift key is down - if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) { - m_view->backspace(); - return true; - } - - if ( e->modifiers() == Qt::NoModifier ) { - switch ( e->key() ) { - case Qt::Key_Escape: - startNormalMode(); - return true; - break; - case Qt::Key_Left: - m_view->cursorLeft(); - return true; - case Qt::Key_Right: - m_view->cursorRight(); - return true; - case Qt::Key_Up: - m_view->up(); - return true; - case Qt::Key_Down: - m_view->down(); - return true; - case Qt::Key_Delete: - m_view->keyDelete(); - return true; - case Qt::Key_Home: - m_view->home(); - return true; - case Qt::Key_End: - m_view->end(); - return true; - case Qt::Key_PageUp: - m_view->pageUp(); - return true; - case Qt::Key_PageDown: - m_view->pageDown(); - return true; - default: - return false; - break; - } - } else if ( e->modifiers() == Qt::ControlModifier ) { - switch( e->key() ) { - case Qt::Key_BracketLeft: - case Qt::Key_3: - case Qt::Key_C: - startNormalMode(); - return true; - break; - case Qt::Key_D: - commandUnindent(); - return true; - break; - case Qt::Key_E: - commandInsertFromBelow(); - return true; - break; - case Qt::Key_N: - commandCompleteNext(); - return true; - break; - case Qt::Key_P: - commandCompletePrevious(); - return true; - break; - case Qt::Key_T: - commandIndent(); - return true; - break; - case Qt::Key_W: - commandDeleteWord(); - return true; - break; - case Qt::Key_Y: - commandInsertFromAbove(); - return true; - break; - case Qt::Key_Home: - commandToFirstCharacterInFile(); - return true; - break; - case Qt::Key_End: - commandToLastCharacterInFile(); - return true; - break; - case Qt::Key_Left: - commandMoveOneWordLeft(); - return true; - break; - case Qt::Key_Right: - commandMoveOneWordRight(); - return true; - break; - default: - return false; - } - } - - return false; -} diff --git a/part/vimode/kateviinsertmode.h b/part/vimode/kateviinsertmode.h deleted file mode 100644 index 3c4f996..0000000 --- a/part/vimode/kateviinsertmode.h +++ /dev/null @@ -1,66 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_INSERT_MODE_INCLUDED -#define KATE_VI_INSERT_MODE_INCLUDED - -#include -#include "katevimodebase.h" - -class KateViMotion; -class KateView; -class KateViewInternal; - -/** - * Commands for the vi insert mode - */ - -class KateViInsertMode : public KateViModeBase -{ - public: - KateViInsertMode( KateViInputModeManager *viInputModeManager, KateView * view, KateViewInternal * viewInternal ); - ~KateViInsertMode(); - - bool handleKeypress( const QKeyEvent *e ); - - bool commandInsertFromAbove(); - bool commandInsertFromBelow(); - - bool commandDeleteWord(); - - bool commandIndent(); - bool commandUnindent(); - - bool commandToFirstCharacterInFile(); - bool commandToLastCharacterInFile(); - - bool commandMoveOneWordLeft(); - bool commandMoveOneWordRight(); - - bool commandCompleteNext(); - bool commandCompletePrevious(); - - // mappings not supported in insert mode yet - void addMapping( const QString &from, const QString &to ) { Q_UNUSED(from) Q_UNUSED(to) } - const QString getMapping( const QString &from ) const { Q_UNUSED(from) return QString(); } - const QStringList getMappings() const { return QStringList(); } -}; - -#endif diff --git a/part/vimode/katevikeyparser.cpp b/part/vimode/katevikeyparser.cpp deleted file mode 100644 index 59a7553..0000000 --- a/part/vimode/katevikeyparser.cpp +++ /dev/null @@ -1,788 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * Copyright (C) 2008 Evgeniy Ivanov - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevikeyparser.h" -#include - -KateViKeyParser* KateViKeyParser::m_instance = NULL; - -KateViKeyParser::KateViKeyParser() -{ - m_qt2katevi = new QHash; - m_katevi2qt = new QHash; - m_nameToKeyCode = new QHash; - m_keyCodeToName = new QHash; - - initKeyTables(); -} - -KateViKeyParser* KateViKeyParser::getInstance() -{ - if ( m_instance == NULL ) { - m_instance = new KateViKeyParser(); - } - - return m_instance; -} - -void KateViKeyParser::initKeyTables() -{ - m_qt2katevi->insert( Qt::Key_Escape, QString( "esc" ) ); - m_qt2katevi->insert( Qt::Key_Tab, QString( "tab" ) ); - m_qt2katevi->insert( Qt::Key_Backtab, QString( "backtab" ) ); - m_qt2katevi->insert( Qt::Key_Backspace, QString( "backspace" ) ); - m_qt2katevi->insert( Qt::Key_Return, QString( "return" ) ); - m_qt2katevi->insert( Qt::Key_Enter, QString( "enter" ) ); - m_qt2katevi->insert( Qt::Key_Insert, QString( "insert" ) ); - m_qt2katevi->insert( Qt::Key_Delete, QString( "delete" ) ); - m_qt2katevi->insert( Qt::Key_Pause, QString( "pause" ) ); - m_qt2katevi->insert( Qt::Key_Print, QString( "print" ) ); - m_qt2katevi->insert( Qt::Key_SysReq, QString( "sysreq" ) ); - m_qt2katevi->insert( Qt::Key_Clear, QString( "clear" ) ); - m_qt2katevi->insert( Qt::Key_Home, QString( "home" ) ); - m_qt2katevi->insert( Qt::Key_End, QString( "end" ) ); - m_qt2katevi->insert( Qt::Key_Left, QString( "left" ) ); - m_qt2katevi->insert( Qt::Key_Up, QString( "up" ) ); - m_qt2katevi->insert( Qt::Key_Right, QString( "right" ) ); - m_qt2katevi->insert( Qt::Key_Down, QString( "down" ) ); - m_qt2katevi->insert( Qt::Key_PageUp, QString( "pageup" ) ); - m_qt2katevi->insert( Qt::Key_PageDown, QString( "pagedown" ) ); - m_qt2katevi->insert( Qt::Key_Shift, QString( "shift" ) ); - m_qt2katevi->insert( Qt::Key_Control, QString( "control" ) ); - m_qt2katevi->insert( Qt::Key_Meta, QString( "meta" ) ); - m_qt2katevi->insert( Qt::Key_Alt, QString( "alt" ) ); - m_qt2katevi->insert( Qt::Key_AltGr, QString( "altgr" ) ); - m_qt2katevi->insert( Qt::Key_CapsLock, QString( "capslock" ) ); - m_qt2katevi->insert( Qt::Key_NumLock, QString( "numlock" ) ); - m_qt2katevi->insert( Qt::Key_ScrollLock, QString( "scrolllock" ) ); - m_qt2katevi->insert( Qt::Key_F1, QString( "f1" ) ); - m_qt2katevi->insert( Qt::Key_F2, QString( "f2" ) ); - m_qt2katevi->insert( Qt::Key_F3, QString( "f3" ) ); - m_qt2katevi->insert( Qt::Key_F4, QString( "f4" ) ); - m_qt2katevi->insert( Qt::Key_F5, QString( "f5" ) ); - m_qt2katevi->insert( Qt::Key_F6, QString( "f6" ) ); - m_qt2katevi->insert( Qt::Key_F7, QString( "f7" ) ); - m_qt2katevi->insert( Qt::Key_F8, QString( "f8" ) ); - m_qt2katevi->insert( Qt::Key_F9, QString( "f9" ) ); - m_qt2katevi->insert( Qt::Key_F10, QString( "f10" ) ); - m_qt2katevi->insert( Qt::Key_F11, QString( "f11" ) ); - m_qt2katevi->insert( Qt::Key_F12, QString( "f12" ) ); - m_qt2katevi->insert( Qt::Key_F13, QString( "f13" ) ); - m_qt2katevi->insert( Qt::Key_F14, QString( "f14" ) ); - m_qt2katevi->insert( Qt::Key_F15, QString( "f15" ) ); - m_qt2katevi->insert( Qt::Key_F16, QString( "f16" ) ); - m_qt2katevi->insert( Qt::Key_F17, QString( "f17" ) ); - m_qt2katevi->insert( Qt::Key_F18, QString( "f18" ) ); - m_qt2katevi->insert( Qt::Key_F19, QString( "f19" ) ); - m_qt2katevi->insert( Qt::Key_F20, QString( "f20" ) ); - m_qt2katevi->insert( Qt::Key_F21, QString( "f21" ) ); - m_qt2katevi->insert( Qt::Key_F22, QString( "f22" ) ); - m_qt2katevi->insert( Qt::Key_F23, QString( "f23" ) ); - m_qt2katevi->insert( Qt::Key_F24, QString( "f24" ) ); - m_qt2katevi->insert( Qt::Key_F25, QString( "f25" ) ); - m_qt2katevi->insert( Qt::Key_F26, QString( "f26" ) ); - m_qt2katevi->insert( Qt::Key_F27, QString( "f27" ) ); - m_qt2katevi->insert( Qt::Key_F28, QString( "f28" ) ); - m_qt2katevi->insert( Qt::Key_F29, QString( "f29" ) ); - m_qt2katevi->insert( Qt::Key_F30, QString( "f30" ) ); - m_qt2katevi->insert( Qt::Key_F31, QString( "f31" ) ); - m_qt2katevi->insert( Qt::Key_F32, QString( "f32" ) ); - m_qt2katevi->insert( Qt::Key_F33, QString( "f33" ) ); - m_qt2katevi->insert( Qt::Key_F34, QString( "f34" ) ); - m_qt2katevi->insert( Qt::Key_F35, QString( "f35" ) ); - m_qt2katevi->insert( Qt::Key_Super_L, QString( "super_l" ) ); - m_qt2katevi->insert( Qt::Key_Super_R, QString( "super_r" ) ); - m_qt2katevi->insert( Qt::Key_Menu, QString( "menu" ) ); - m_qt2katevi->insert( Qt::Key_Hyper_L, QString( "hyper_l" ) ); - m_qt2katevi->insert( Qt::Key_Hyper_R, QString( "hyper_r" ) ); - m_qt2katevi->insert( Qt::Key_Help, QString( "help" ) ); - m_qt2katevi->insert( Qt::Key_Direction_L, QString( "direction_l" ) ); - m_qt2katevi->insert( Qt::Key_Direction_R, QString( "direction_r" ) ); - m_qt2katevi->insert( Qt::Key_Multi_key, QString( "multi_key" ) ); - m_qt2katevi->insert( Qt::Key_Codeinput, QString( "codeinput" ) ); - m_qt2katevi->insert( Qt::Key_SingleCandidate, QString( "singlecandidate" ) ); - m_qt2katevi->insert( Qt::Key_MultipleCandidate, QString( "multiplecandidate" ) ); - m_qt2katevi->insert( Qt::Key_PreviousCandidate, QString( "previouscandidate" ) ); - m_qt2katevi->insert( Qt::Key_Mode_switch, QString( "mode_switch" ) ); - m_qt2katevi->insert( Qt::Key_Kanji, QString( "kanji" ) ); - m_qt2katevi->insert( Qt::Key_Muhenkan, QString( "muhenkan" ) ); - m_qt2katevi->insert( Qt::Key_Henkan, QString( "henkan" ) ); - m_qt2katevi->insert( Qt::Key_Romaji, QString( "romaji" ) ); - m_qt2katevi->insert( Qt::Key_Hiragana, QString( "hiragana" ) ); - m_qt2katevi->insert( Qt::Key_Katakana, QString( "katakana" ) ); - m_qt2katevi->insert( Qt::Key_Hiragana_Katakana, QString( "hiragana_katakana" ) ); - m_qt2katevi->insert( Qt::Key_Zenkaku, QString( "zenkaku" ) ); - m_qt2katevi->insert( Qt::Key_Hankaku, QString( "hankaku" ) ); - m_qt2katevi->insert( Qt::Key_Zenkaku_Hankaku, QString( "zenkaku_hankaku" ) ); - m_qt2katevi->insert( Qt::Key_Touroku, QString( "touroku" ) ); - m_qt2katevi->insert( Qt::Key_Massyo, QString( "massyo" ) ); - m_qt2katevi->insert( Qt::Key_Kana_Lock, QString( "kana_lock" ) ); - m_qt2katevi->insert( Qt::Key_Kana_Shift, QString( "kana_shift" ) ); - m_qt2katevi->insert( Qt::Key_Eisu_Shift, QString( "eisu_shift" ) ); - m_qt2katevi->insert( Qt::Key_Eisu_toggle, QString( "eisu_toggle" ) ); - m_qt2katevi->insert( Qt::Key_Hangul, QString( "hangul" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Start, QString( "hangul_start" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_End, QString( "hangul_end" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Hanja, QString( "hangul_hanja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Jamo, QString( "hangul_jamo" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Romaja, QString( "hangul_romaja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Jeonja, QString( "hangul_jeonja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Banja, QString( "hangul_banja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_PreHanja, QString( "hangul_prehanja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_PostHanja, QString( "hangul_posthanja" ) ); - m_qt2katevi->insert( Qt::Key_Hangul_Special, QString( "hangul_special" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Grave, QString( "dead_grave" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Acute, QString( "dead_acute" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Circumflex, QString( "dead_circumflex" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Tilde, QString( "dead_tilde" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Macron, QString( "dead_macron" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Breve, QString( "dead_breve" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Abovedot, QString( "dead_abovedot" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Diaeresis, QString( "dead_diaeresis" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Abovering, QString( "dead_abovering" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Doubleacute, QString( "dead_doubleacute" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Caron, QString( "dead_caron" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Cedilla, QString( "dead_cedilla" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Ogonek, QString( "dead_ogonek" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Iota, QString( "dead_iota" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Voiced_Sound, QString( "dead_voiced_sound" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Semivoiced_Sound, QString( "dead_semivoiced_sound" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Belowdot, QString( "dead_belowdot" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Hook, QString( "dead_hook" ) ); - m_qt2katevi->insert( Qt::Key_Dead_Horn, QString( "dead_horn" ) ); - m_qt2katevi->insert( Qt::Key_Back, QString( "back" ) ); - m_qt2katevi->insert( Qt::Key_Forward, QString( "forward" ) ); - m_qt2katevi->insert( Qt::Key_Stop, QString( "stop" ) ); - m_qt2katevi->insert( Qt::Key_Refresh, QString( "refresh" ) ); - m_qt2katevi->insert( Qt::Key_VolumeDown, QString( "volumedown" ) ); - m_qt2katevi->insert( Qt::Key_VolumeMute, QString( "volumemute" ) ); - m_qt2katevi->insert( Qt::Key_VolumeUp, QString( "volumeup" ) ); - m_qt2katevi->insert( Qt::Key_BassBoost, QString( "bassboost" ) ); - m_qt2katevi->insert( Qt::Key_BassUp, QString( "bassup" ) ); - m_qt2katevi->insert( Qt::Key_BassDown, QString( "bassdown" ) ); - m_qt2katevi->insert( Qt::Key_TrebleUp, QString( "trebleup" ) ); - m_qt2katevi->insert( Qt::Key_TrebleDown, QString( "trebledown" ) ); - m_qt2katevi->insert( Qt::Key_MediaPlay, QString( "mediaplay" ) ); - m_qt2katevi->insert( Qt::Key_MediaStop, QString( "mediastop" ) ); - m_qt2katevi->insert( Qt::Key_MediaPrevious, QString( "mediaprevious" ) ); - m_qt2katevi->insert( Qt::Key_MediaNext, QString( "medianext" ) ); - m_qt2katevi->insert( Qt::Key_MediaRecord, QString( "mediarecord" ) ); - m_qt2katevi->insert( Qt::Key_HomePage, QString( "homepage" ) ); - m_qt2katevi->insert( Qt::Key_Favorites, QString( "favorites" ) ); - m_qt2katevi->insert( Qt::Key_Search, QString( "search" ) ); - m_qt2katevi->insert( Qt::Key_Standby, QString( "standby" ) ); - m_qt2katevi->insert( Qt::Key_OpenUrl, QString( "openurl" ) ); - m_qt2katevi->insert( Qt::Key_LaunchMail, QString( "launchmail" ) ); - m_qt2katevi->insert( Qt::Key_LaunchMedia, QString( "launchmedia" ) ); - m_qt2katevi->insert( Qt::Key_Launch0, QString( "launch0" ) ); - m_qt2katevi->insert( Qt::Key_Launch1, QString( "launch1" ) ); - m_qt2katevi->insert( Qt::Key_Launch2, QString( "launch2" ) ); - m_qt2katevi->insert( Qt::Key_Launch3, QString( "launch3" ) ); - m_qt2katevi->insert( Qt::Key_Launch4, QString( "launch4" ) ); - m_qt2katevi->insert( Qt::Key_Launch5, QString( "launch5" ) ); - m_qt2katevi->insert( Qt::Key_Launch6, QString( "launch6" ) ); - m_qt2katevi->insert( Qt::Key_Launch7, QString( "launch7" ) ); - m_qt2katevi->insert( Qt::Key_Launch8, QString( "launch8" ) ); - m_qt2katevi->insert( Qt::Key_Launch9, QString( "launch9" ) ); - m_qt2katevi->insert( Qt::Key_LaunchA, QString( "launcha" ) ); - m_qt2katevi->insert( Qt::Key_LaunchB, QString( "launchb" ) ); - m_qt2katevi->insert( Qt::Key_LaunchC, QString( "launchc" ) ); - m_qt2katevi->insert( Qt::Key_LaunchD, QString( "launchd" ) ); - m_qt2katevi->insert( Qt::Key_LaunchE, QString( "launche" ) ); - m_qt2katevi->insert( Qt::Key_LaunchF, QString( "launchf" ) ); - m_qt2katevi->insert( Qt::Key_MediaLast, QString( "medialast" ) ); - m_qt2katevi->insert( Qt::Key_unknown, QString( "unknown" ) ); - m_qt2katevi->insert( Qt::Key_Call, QString( "call" ) ); - m_qt2katevi->insert( Qt::Key_Context1, QString( "context1" ) ); - m_qt2katevi->insert( Qt::Key_Context2, QString( "context2" ) ); - m_qt2katevi->insert( Qt::Key_Context3, QString( "context3" ) ); - m_qt2katevi->insert( Qt::Key_Context4, QString( "context4" ) ); - m_qt2katevi->insert( Qt::Key_Flip, QString( "flip" ) ); - m_qt2katevi->insert( Qt::Key_Hangup, QString( "hangup" ) ); - m_qt2katevi->insert( Qt::Key_No, QString( "no" ) ); - m_qt2katevi->insert( Qt::Key_Select, QString( "select" ) ); - m_qt2katevi->insert( Qt::Key_Yes, QString( "yes" ) ); - m_qt2katevi->insert( Qt::Key_Execute, QString( "execute" ) ); - m_qt2katevi->insert( Qt::Key_Printer, QString( "printer" ) ); - m_qt2katevi->insert( Qt::Key_Play, QString( "play" ) ); - m_qt2katevi->insert( Qt::Key_Sleep, QString( "sleep" ) ); - m_qt2katevi->insert( Qt::Key_Zoom, QString( "zoom" ) ); - m_qt2katevi->insert( Qt::Key_Cancel, QString( "cancel" ) ); - - for (QHash::const_iterator i = m_qt2katevi->constBegin(); - i != m_qt2katevi->constEnd(); ++i) { - m_katevi2qt->insert( i.value(), i.key() ); - } - - m_nameToKeyCode->insert( QString( "invalid" ), -1 ); - m_nameToKeyCode->insert( QString( "esc" ), 1 ); - m_nameToKeyCode->insert( QString( "tab" ), 2 ); - m_nameToKeyCode->insert( QString( "backtab" ), 3 ); - m_nameToKeyCode->insert( QString( "backspace" ), 4 ); - m_nameToKeyCode->insert( QString( "return" ), 5 ); - m_nameToKeyCode->insert( QString( "enter" ), 6 ); - m_nameToKeyCode->insert( QString( "insert" ), 7 ); - m_nameToKeyCode->insert( QString( "delete" ), 8 ); - m_nameToKeyCode->insert( QString( "pause" ), 9 ); - m_nameToKeyCode->insert( QString( "print" ), 10 ); - m_nameToKeyCode->insert( QString( "sysreq" ), 11 ); - m_nameToKeyCode->insert( QString( "clear" ), 12 ); - m_nameToKeyCode->insert( QString( "home" ), 13 ); - m_nameToKeyCode->insert( QString( "end" ), 14 ); - m_nameToKeyCode->insert( QString( "left" ), 15 ); - m_nameToKeyCode->insert( QString( "up" ), 16 ); - m_nameToKeyCode->insert( QString( "right" ), 17 ); - m_nameToKeyCode->insert( QString( "down" ), 18 ); - m_nameToKeyCode->insert( QString( "pageup" ), 19 ); - m_nameToKeyCode->insert( QString( "pagedown" ), 20 ); - m_nameToKeyCode->insert( QString( "shift" ), 21 ); - m_nameToKeyCode->insert( QString( "control" ), 22 ); - m_nameToKeyCode->insert( QString( "meta" ), 23 ); - m_nameToKeyCode->insert( QString( "alt" ), 24 ); - m_nameToKeyCode->insert( QString( "altgr" ), 25 ); - m_nameToKeyCode->insert( QString( "capslock" ), 26 ); - m_nameToKeyCode->insert( QString( "numlock" ), 27 ); - m_nameToKeyCode->insert( QString( "scrolllock" ), 28 ); - m_nameToKeyCode->insert( QString( "f1" ), 29 ); - m_nameToKeyCode->insert( QString( "f2" ), 30 ); - m_nameToKeyCode->insert( QString( "f3" ), 31 ); - m_nameToKeyCode->insert( QString( "f4" ), 32 ); - m_nameToKeyCode->insert( QString( "f5" ), 33 ); - m_nameToKeyCode->insert( QString( "f6" ), 34 ); - m_nameToKeyCode->insert( QString( "f7" ), 35 ); - m_nameToKeyCode->insert( QString( "f8" ), 36 ); - m_nameToKeyCode->insert( QString( "f9" ), 37 ); - m_nameToKeyCode->insert( QString( "f10" ), 38 ); - m_nameToKeyCode->insert( QString( "f11" ), 39 ); - m_nameToKeyCode->insert( QString( "f12" ), 40 ); - m_nameToKeyCode->insert( QString( "f13" ), 41 ); - m_nameToKeyCode->insert( QString( "f14" ), 42 ); - m_nameToKeyCode->insert( QString( "f15" ), 43 ); - m_nameToKeyCode->insert( QString( "f16" ), 44 ); - m_nameToKeyCode->insert( QString( "f17" ), 45 ); - m_nameToKeyCode->insert( QString( "f18" ), 46 ); - m_nameToKeyCode->insert( QString( "f19" ), 47 ); - m_nameToKeyCode->insert( QString( "f20" ), 48 ); - m_nameToKeyCode->insert( QString( "f21" ), 49 ); - m_nameToKeyCode->insert( QString( "f22" ), 50 ); - m_nameToKeyCode->insert( QString( "f23" ), 51 ); - m_nameToKeyCode->insert( QString( "f24" ), 52 ); - m_nameToKeyCode->insert( QString( "f25" ), 53 ); - m_nameToKeyCode->insert( QString( "f26" ), 54 ); - m_nameToKeyCode->insert( QString( "f27" ), 55 ); - m_nameToKeyCode->insert( QString( "f28" ), 56 ); - m_nameToKeyCode->insert( QString( "f29" ), 57 ); - m_nameToKeyCode->insert( QString( "f30" ), 58 ); - m_nameToKeyCode->insert( QString( "f31" ), 59 ); - m_nameToKeyCode->insert( QString( "f32" ), 60 ); - m_nameToKeyCode->insert( QString( "f33" ), 61 ); - m_nameToKeyCode->insert( QString( "f34" ), 62 ); - m_nameToKeyCode->insert( QString( "f35" ), 63 ); - m_nameToKeyCode->insert( QString( "super_l" ), 64 ); - m_nameToKeyCode->insert( QString( "super_r" ), 65 ); - m_nameToKeyCode->insert( QString( "menu" ), 66 ); - m_nameToKeyCode->insert( QString( "hyper_l" ), 67 ); - m_nameToKeyCode->insert( QString( "hyper_r" ), 68 ); - m_nameToKeyCode->insert( QString( "help" ), 69 ); - m_nameToKeyCode->insert( QString( "direction_l" ), 70 ); - m_nameToKeyCode->insert( QString( "direction_r" ), 71 ); - m_nameToKeyCode->insert( QString( "multi_key" ), 172 ); - m_nameToKeyCode->insert( QString( "codeinput" ), 173 ); - m_nameToKeyCode->insert( QString( "singlecandidate" ), 174 ); - m_nameToKeyCode->insert( QString( "multiplecandidate" ), 175 ); - m_nameToKeyCode->insert( QString( "previouscandidate" ), 176 ); - m_nameToKeyCode->insert( QString( "mode_switch" ), 177 ); - m_nameToKeyCode->insert( QString( "kanji" ), 178 ); - m_nameToKeyCode->insert( QString( "muhenkan" ), 179 ); - m_nameToKeyCode->insert( QString( "henkan" ), 180 ); - m_nameToKeyCode->insert( QString( "romaji" ), 181 ); - m_nameToKeyCode->insert( QString( "hiragana" ), 182 ); - m_nameToKeyCode->insert( QString( "katakana" ), 183 ); - m_nameToKeyCode->insert( QString( "hiragana_katakana" ), 184 ); - m_nameToKeyCode->insert( QString( "zenkaku" ), 185 ); - m_nameToKeyCode->insert( QString( "hankaku" ), 186 ); - m_nameToKeyCode->insert( QString( "zenkaku_hankaku" ), 187 ); - m_nameToKeyCode->insert( QString( "touroku" ), 188 ); - m_nameToKeyCode->insert( QString( "massyo" ), 189 ); - m_nameToKeyCode->insert( QString( "kana_lock" ), 190 ); - m_nameToKeyCode->insert( QString( "kana_shift" ), 191 ); - m_nameToKeyCode->insert( QString( "eisu_shift" ), 192 ); - m_nameToKeyCode->insert( QString( "eisu_toggle" ), 193 ); - m_nameToKeyCode->insert( QString( "hangul" ), 194 ); - m_nameToKeyCode->insert( QString( "hangul_start" ), 195 ); - m_nameToKeyCode->insert( QString( "hangul_end" ), 196 ); - m_nameToKeyCode->insert( QString( "hangul_hanja" ), 197 ); - m_nameToKeyCode->insert( QString( "hangul_jamo" ), 198 ); - m_nameToKeyCode->insert( QString( "hangul_romaja" ), 199 ); - m_nameToKeyCode->insert( QString( "hangul_jeonja" ), 200 ); - m_nameToKeyCode->insert( QString( "hangul_banja" ), 201 ); - m_nameToKeyCode->insert( QString( "hangul_prehanja" ), 202 ); - m_nameToKeyCode->insert( QString( "hangul_posthanja" ), 203 ); - m_nameToKeyCode->insert( QString( "hangul_special" ), 204 ); - m_nameToKeyCode->insert( QString( "dead_grave" ), 205 ); - m_nameToKeyCode->insert( QString( "dead_acute" ), 206 ); - m_nameToKeyCode->insert( QString( "dead_circumflex" ), 207 ); - m_nameToKeyCode->insert( QString( "dead_tilde" ), 208 ); - m_nameToKeyCode->insert( QString( "dead_macron" ), 209 ); - m_nameToKeyCode->insert( QString( "dead_breve" ), 210 ); - m_nameToKeyCode->insert( QString( "dead_abovedot" ), 211 ); - m_nameToKeyCode->insert( QString( "dead_diaeresis" ), 212 ); - m_nameToKeyCode->insert( QString( "dead_abovering" ), 213 ); - m_nameToKeyCode->insert( QString( "dead_doubleacute" ), 214 ); - m_nameToKeyCode->insert( QString( "dead_caron" ), 215 ); - m_nameToKeyCode->insert( QString( "dead_cedilla" ), 216 ); - m_nameToKeyCode->insert( QString( "dead_ogonek" ), 217 ); - m_nameToKeyCode->insert( QString( "dead_iota" ), 218 ); - m_nameToKeyCode->insert( QString( "dead_voiced_sound" ), 219 ); - m_nameToKeyCode->insert( QString( "dead_semivoiced_sound" ), 220 ); - m_nameToKeyCode->insert( QString( "dead_belowdot" ), 221 ); - m_nameToKeyCode->insert( QString( "dead_hook" ), 222 ); - m_nameToKeyCode->insert( QString( "dead_horn" ), 223 ); - m_nameToKeyCode->insert( QString( "back" ), 224 ); - m_nameToKeyCode->insert( QString( "forward" ), 225 ); - m_nameToKeyCode->insert( QString( "stop" ), 226 ); - m_nameToKeyCode->insert( QString( "refresh" ), 227 ); - m_nameToKeyCode->insert( QString( "volumedown" ), 228 ); - m_nameToKeyCode->insert( QString( "volumemute" ), 229 ); - m_nameToKeyCode->insert( QString( "volumeup" ), 230 ); - m_nameToKeyCode->insert( QString( "bassboost" ), 231 ); - m_nameToKeyCode->insert( QString( "bassup" ), 232 ); - m_nameToKeyCode->insert( QString( "bassdown" ), 233 ); - m_nameToKeyCode->insert( QString( "trebleup" ), 234 ); - m_nameToKeyCode->insert( QString( "trebledown" ), 235 ); - m_nameToKeyCode->insert( QString( "mediaplay" ), 236 ); - m_nameToKeyCode->insert( QString( "mediastop" ), 237 ); - m_nameToKeyCode->insert( QString( "mediaprevious" ), 238 ); - m_nameToKeyCode->insert( QString( "medianext" ), 239 ); - m_nameToKeyCode->insert( QString( "mediarecord" ), 240 ); - m_nameToKeyCode->insert( QString( "homepage" ), 241 ); - m_nameToKeyCode->insert( QString( "favorites" ), 242 ); - m_nameToKeyCode->insert( QString( "search" ), 243 ); - m_nameToKeyCode->insert( QString( "standby" ), 244 ); - m_nameToKeyCode->insert( QString( "openurl" ), 245 ); - m_nameToKeyCode->insert( QString( "launchmail" ), 246 ); - m_nameToKeyCode->insert( QString( "launchmedia" ), 247 ); - m_nameToKeyCode->insert( QString( "launch0" ), 248 ); - m_nameToKeyCode->insert( QString( "launch1" ), 249 ); - m_nameToKeyCode->insert( QString( "launch2" ), 250 ); - m_nameToKeyCode->insert( QString( "launch3" ), 251 ); - m_nameToKeyCode->insert( QString( "launch4" ), 252 ); - m_nameToKeyCode->insert( QString( "launch5" ), 253 ); - m_nameToKeyCode->insert( QString( "launch6" ), 254 ); - m_nameToKeyCode->insert( QString( "launch7" ), 255 ); - m_nameToKeyCode->insert( QString( "launch8" ), 256 ); - m_nameToKeyCode->insert( QString( "launch9" ), 257 ); - m_nameToKeyCode->insert( QString( "launcha" ), 258 ); - m_nameToKeyCode->insert( QString( "launchb" ), 259 ); - m_nameToKeyCode->insert( QString( "launchc" ), 260 ); - m_nameToKeyCode->insert( QString( "launchd" ), 261 ); - m_nameToKeyCode->insert( QString( "launche" ), 262 ); - m_nameToKeyCode->insert( QString( "launchf" ), 263 ); - m_nameToKeyCode->insert( QString( "medialast" ), 264 ); - m_nameToKeyCode->insert( QString( "unknown" ), 265 ); - m_nameToKeyCode->insert( QString( "call" ), 266 ); - m_nameToKeyCode->insert( QString( "context1" ), 267 ); - m_nameToKeyCode->insert( QString( "context2" ), 268 ); - m_nameToKeyCode->insert( QString( "context3" ), 269 ); - m_nameToKeyCode->insert( QString( "context4" ), 270 ); - m_nameToKeyCode->insert( QString( "flip" ), 271 ); - m_nameToKeyCode->insert( QString( "hangup" ), 272 ); - m_nameToKeyCode->insert( QString( "no" ), 273 ); - m_nameToKeyCode->insert( QString( "select" ), 274 ); - m_nameToKeyCode->insert( QString( "yes" ), 275 ); - m_nameToKeyCode->insert( QString( "execute" ), 276 ); - m_nameToKeyCode->insert( QString( "printer" ), 277 ); - m_nameToKeyCode->insert( QString( "play" ), 278 ); - m_nameToKeyCode->insert( QString( "sleep" ), 279 ); - m_nameToKeyCode->insert( QString( "zoom" ), 280 ); - m_nameToKeyCode->insert( QString( "cancel" ), 281 ); - - m_nameToKeyCode->insert( QString( "a" ), 282 ); - m_nameToKeyCode->insert( QString( "b" ), 283 ); - m_nameToKeyCode->insert( QString( "c" ), 284 ); - m_nameToKeyCode->insert( QString( "d" ), 285 ); - m_nameToKeyCode->insert( QString( "e" ), 286 ); - m_nameToKeyCode->insert( QString( "f" ), 287 ); - m_nameToKeyCode->insert( QString( "d" ), 288 ); - m_nameToKeyCode->insert( QString( "h" ), 289 ); - m_nameToKeyCode->insert( QString( "i" ), 290 ); - m_nameToKeyCode->insert( QString( "j" ), 291 ); - m_nameToKeyCode->insert( QString( "k" ), 292 ); - m_nameToKeyCode->insert( QString( "l" ), 293 ); - m_nameToKeyCode->insert( QString( "m" ), 294 ); - m_nameToKeyCode->insert( QString( "n" ), 295 ); - m_nameToKeyCode->insert( QString( "o" ), 296 ); - m_nameToKeyCode->insert( QString( "p" ), 297 ); - m_nameToKeyCode->insert( QString( "q" ), 298 ); - m_nameToKeyCode->insert( QString( "r" ), 299 ); - m_nameToKeyCode->insert( QString( "s" ), 300 ); - m_nameToKeyCode->insert( QString( "t" ), 301 ); - m_nameToKeyCode->insert( QString( "u" ), 302 ); - m_nameToKeyCode->insert( QString( "v" ), 303 ); - m_nameToKeyCode->insert( QString( "w" ), 304 ); - m_nameToKeyCode->insert( QString( "x" ), 305 ); - m_nameToKeyCode->insert( QString( "y" ), 306 ); - m_nameToKeyCode->insert( QString( "z" ), 307 ); - m_nameToKeyCode->insert( QString( "`" ), 308 ); - m_nameToKeyCode->insert( QString( "!" ), 309 ); - m_nameToKeyCode->insert( QString( "\"" ), 310 ); - m_nameToKeyCode->insert( QString( "$" ), 311 ); - m_nameToKeyCode->insert( QString( "%" ), 312 ); - m_nameToKeyCode->insert( QString( "^" ), 313 ); - m_nameToKeyCode->insert( QString( "&" ), 314 ); - m_nameToKeyCode->insert( QString( "*" ), 315 ); - m_nameToKeyCode->insert( QString( "(" ), 316 ); - m_nameToKeyCode->insert( QString( ")" ), 317 ); - m_nameToKeyCode->insert( QString( "-" ), 318 ); - m_nameToKeyCode->insert( QString( "_" ), 319 ); - m_nameToKeyCode->insert( QString( "=" ), 320 ); - m_nameToKeyCode->insert( QString( "+" ), 321 ); - m_nameToKeyCode->insert( QString( "[" ), 322 ); - m_nameToKeyCode->insert( QString( "]" ), 323 ); - m_nameToKeyCode->insert( QString( "{" ), 324 ); - m_nameToKeyCode->insert( QString( "}" ), 325 ); - m_nameToKeyCode->insert( QString( ":" ), 326 ); - m_nameToKeyCode->insert( QString( ";" ), 327 ); - m_nameToKeyCode->insert( QString( "@" ), 328 ); - m_nameToKeyCode->insert( QString( "'" ), 329 ); - m_nameToKeyCode->insert( QString( "#" ), 330 ); - m_nameToKeyCode->insert( QString( "~" ), 331 ); - m_nameToKeyCode->insert( QString( "\\" ), 332 ); - m_nameToKeyCode->insert( QString( "|" ), 333 ); - m_nameToKeyCode->insert( QString( "," ), 334 ); - m_nameToKeyCode->insert( QString( "." ), 335 ); - //m_nameToKeyCode->insert( QString( ">" ), 336 ); - m_nameToKeyCode->insert( QString( "/" ), 337 ); - m_nameToKeyCode->insert( QString( "?" ), 338 ); - m_nameToKeyCode->insert( QString( " " ), 339 ); - //m_nameToKeyCode->insert( QString( "<" ), 341 ); - - for (QHash::const_iterator i = m_nameToKeyCode->constBegin(); - i != m_nameToKeyCode->constEnd(); ++i) { - m_keyCodeToName->insert( i.value(), i.key() ); - } -} - -QString KateViKeyParser::qt2vi( int key ) const -{ - return ( m_qt2katevi->contains( key ) ? m_qt2katevi->value( key ) : "invalid" ); -} - -int KateViKeyParser::vi2qt( const QString &keypress ) const -{ - return ( m_katevi2qt->contains( keypress ) ? m_katevi2qt->value( keypress ) : -1 ); -} - - -const QString KateViKeyParser::encodeKeySequence( const QString &keys ) const -{ - QString encodedSequence; - unsigned int keyCodeTemp = 0; - int startOfBlock = -1; - - bool insideTag = false; - QChar c; - for ( int i = 0; i < keys.length(); i++ ) { - c = keys.at( i ); - if ( insideTag ) { - if ( c == '>' ) { - QString temp; - temp.setNum( 0xE000+keyCodeTemp, 16); - QChar code(0xE000+keyCodeTemp ); - encodedSequence.append( code ); - keyCodeTemp = 0; - insideTag = false; - continue; - } - else { - // contains modifiers - if ( keys.mid( i ).indexOf( '-' ) != -1 && keys.mid( i ).indexOf( '-' ) < keys.mid( i ).indexOf( '>' ) ) { - QStringList tokens = keys.mid( i, keys.mid( i ).indexOf( '>' ) ).toLower().split( '-' ); - - foreach ( const QString& str, tokens ) { - if ( str == "s" && ( keyCodeTemp & 0x01 ) != 0x1 ) - keyCodeTemp += 0x1; - else if ( str == "c" && ( keyCodeTemp & 0x02 ) != 0x2 ) - keyCodeTemp += 0x2; - else if ( str == "a" && ( keyCodeTemp & 0x04 ) != 0x4 ) - keyCodeTemp += 0x4; - else if ( str == "m" && ( keyCodeTemp & 0x08 ) != 0x8 ) - keyCodeTemp += 0x8; - else { - if ( m_nameToKeyCode->contains( str ) || ( str.length() == 1 && str.at( 0 ).isLetterOrNumber() ) ) { - if ( m_nameToKeyCode->contains( str ) ) { - keyCodeTemp += m_nameToKeyCode->value( str ) * 0x10; - } else { - keyCodeTemp += str.at( 0 ).unicode() * 0x10; - } - } else { - int endOfBlock = keys.indexOf( '>' ); - if ( endOfBlock -= -1 ) { - endOfBlock = keys.length()-1; - } - encodedSequence.clear(); - encodedSequence.append( m_nameToKeyCode->value( "invalid" ) ); - break; - } - } - } - } - else { - QString str = keys.mid( i, keys.indexOf( '>', i )-i ).toLower(); - if ( keys.indexOf( '>', i ) != -1 && ( m_nameToKeyCode->contains( str ) || ( str.length() == 1 && str.at( 0 ).isLetterOrNumber() ) ) ) { - if ( m_nameToKeyCode->contains( str ) ) { - keyCodeTemp += m_nameToKeyCode->value( str ) * 0x10; - } else { - keyCodeTemp += str.at( 0 ).unicode() * 0x10; - } - } else { - int endOfBlock = keys.indexOf( '>' ); - if ( endOfBlock -= -1 ) { - endOfBlock = keys.length()-1; - } - encodedSequence.clear(); - keyCodeTemp = m_nameToKeyCode->value( "invalid" ) * 0x10; - } - - } - i += keys.mid( i, keys.mid( i ).indexOf( '>' ) ).length()-1; - } - } - else { - if ( c == '<' ) { - // if there's no closing '>', or if there is an opening '<' before the next '>', interpret as a literal '<' - QString rest = keys.mid( i ); - if ( rest.indexOf( '>', 1 ) == -1 || ( rest.indexOf( '<', 1 ) < rest.indexOf( '>', 1 ) && rest.indexOf( '<', 1 ) != -1 ) ) { - encodedSequence.append( c ); - continue; - } - startOfBlock = i; - insideTag = true; - continue; - } else { - encodedSequence.append( c ); - } - } - } - - return encodedSequence; -} - -const QString KateViKeyParser::decodeKeySequence( const QString &keys ) const -{ - QString ret; - - for ( int i = 0; i < keys.length(); i++ ) { - QChar c = keys.at( i ); - int keycode = c.unicode(); - - if ( ( keycode & 0xE000 ) != 0xE000 ) { - ret.append( c ); - } else { - ret.append( '<' ); - - if ( ( keycode & 0x1 ) == 0x1 ) { - ret.append( QLatin1String( "s-") ); - //keycode -= 0x1; - } - if ( ( keycode & 0x2 ) == 0x2 ) { - ret.append( QLatin1String( "c-") ); - //keycode -= 0x2; - } - if ( ( keycode & 0x4 ) == 0x4 ) { - ret.append( QLatin1String( "a-") ); - //keycode -= 0x4; - } - if ( ( keycode & 0x8 ) == 0x8 ) { - ret.append( QLatin1String( "m-") ); - //keycode -= 0x8; - } - - if ( ( keycode & 0xE000 ) == 0xE000 ) { - ret.append( m_keyCodeToName->value( ( keycode-0xE000 )/0x10 ) ); - } else { - ret.append( QChar( keycode ) ); - } - ret.append( '>' ); - } - } - - return ret; -} - -char KateViKeyParser::scanCodeToChar(quint32 code, Qt::KeyboardModifiers modifiers, bool isLetter) const -{ - //Do not forget to ignore letters with shift. Should work with punctuation and special characters ($, ^) only. - //any punctuation (without shift) that has different signs in different layouts should be added to the second switch. - if ((modifiers & Qt::ShiftModifier) && !isLetter) - { - switch(code) - { - case 10: - return '!'; - case 11: - return '@'; - case 12: - return '#'; - case 13: - return '$'; - case 14: - return '%'; - case 15: - return '^'; - case 16: - return '&'; - case 17: - return '*'; - case 18: - return '('; - case 19: - return ')'; - default: - return '0'; - } - } - switch(code) - { - case 24: - return 'q'; - case 25: - return 'w'; - case 26: - return 'e'; - case 27: - return 'r'; - case 28: - return 't'; - case 29: - return 'y'; - case 30: - return 'u'; - case 31: - return 'i'; - case 32: - return 'o'; - case 33: - return 'p'; - case 34: - return '['; - case 35: - return ']'; - case 38: - return 'a'; - case 39: - return 's'; - case 40: - return 'd'; - case 41: - return 'f'; - case 42: - return 'g'; - case 43: - return 'h'; - case 44: - return 'j'; - case 45: - return 'k'; - case 46: - return 'l'; - case 47: - return ';'; - case 48: - return '\''; - case 49: - return '`'; - case 52: - return 'z'; - case 53: - return 'x'; - case 54: - return 'c'; - case 55: - return 'v'; - case 56: - return 'b'; - case 57: - return 'n'; - case 58: - return 'm'; - case 59: - return ','; - case 60: - return '.'; - case 61: - return '/'; - default: - return 0; - } - return 0; -} - -const QChar KateViKeyParser::KeyEventToQChar(int keyCode, const QString &text, - Qt::KeyboardModifiers mods, quint32 nativeScanCode) const -{ - QChar key; - - if ( !text.isEmpty() ) { - key = text.at(0); - } - - if ( text.isEmpty() || ( text.length() == 1 && text.at(0) < 0x20 ) - || ( mods != Qt::NoModifier && mods != Qt::ShiftModifier ) ) { - QString keyPress; - - keyPress.append( '<' ); - keyPress.append( ( mods & Qt::ShiftModifier ) ? "s-" : "" ); - keyPress.append( ( mods & Qt::ControlModifier ) ? "c-" : "" ); - keyPress.append( ( mods & Qt::AltModifier ) ? "a-" : "" ); - keyPress.append( ( mods & Qt::MetaModifier ) ? "m-" : "" ); - keyPress.append( keyCode <= 0xFF ? QChar( keyCode ) : qt2vi( keyCode ) ); - keyPress.append( '>' ); - - key = encodeKeySequence( keyPress ).at( 0 ); - } else { - //maybe we have a non-latin letter, try to convert to latin charachter - //note that non-latin letter in Latin layout can be a punctuation character (also some punctuation differs too) - QChar tempChar(text.at(0)); - //don't touch latin keys - if ((keyCode < Qt::Key_A || keyCode > Qt::Key_Z) && tempChar.isLetter()) { - char ch = scanCodeToChar(nativeScanCode, mods, tempChar.isLetter()); - if (ch != 0) { - key = QChar(ch); - if (key.isLetter()) { - if (tempChar.isUpper()) { - key = QChar(ch).toUpper(); - } else { - key = QChar(ch).toLower(); //scanCodeToChar returns lower, but we don't want to depend on it - } - } - } - else { - key = tempChar; - } - } - else { - key = tempChar; - } - } - - return key; -} diff --git a/part/vimode/katevikeyparser.h b/part/vimode/katevikeyparser.h deleted file mode 100644 index 6f0489c..0000000 --- a/part/vimode/katevikeyparser.h +++ /dev/null @@ -1,60 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * Copyright (C) 2008 Evgeniy Ivanov - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_KEYPARSER_H_INCLUDED -#define KATE_VI_KEYPARSER_H_INCLUDED - -#include -#include -#include - -/** - * for encoding keypresses w/ modifiers into an internal QChar representation and back again to a - * descriptive text string - */ - -class KateViKeyParser -{ -private: - KateViKeyParser(); - -public: - static KateViKeyParser* getInstance(); - - const QString encodeKeySequence( const QString &keys ) const; - const QString decodeKeySequence( const QString &keys ) const; - QString qt2vi( int key ) const; - int vi2qt( const QString &keypress ) const; - char scanCodeToChar(quint32 code, Qt::KeyboardModifiers modifiers, bool isLetter) const; - const QChar KeyEventToQChar(int keyCode, const QString &text, Qt::KeyboardModifiers mods, quint32 nativeScanCode) const; - -private: - void initKeyTables(); - - QHash *m_qt2katevi; - QHash *m_katevi2qt; - QHash *m_nameToKeyCode; - QHash *m_keyCodeToName; - - static KateViKeyParser *m_instance; -}; - -#endif diff --git a/part/vimode/katevimodebar.cpp b/part/vimode/katevimodebar.cpp deleted file mode 100644 index 6455de6..0000000 --- a/part/vimode/katevimodebar.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Dmitry Suzdalev - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevimodebar.h" -#include "kateviinputmodemanager.h" -#include "katevinormalmode.h" -#include "katevivisualmode.h" -#include "kateviinsertmode.h" - -#include -#include -#include -#include - -#include "klocale.h" - -KateViModeBar::KateViModeBar(QWidget* parent) -: KateViewBarWidget(false, parent), - m_labelStatus(new QLabel(this)), - m_labelMessage(new QLabel(this)), - m_labelCommand(new QLabel(this)), - m_timer(0) -{ - QHBoxLayout *lay = qobject_cast(layout()); - lay->addWidget(m_labelStatus); - lay->addSpacing(30); - lay->addWidget(m_labelMessage); - lay->addStretch(1); - lay->addWidget(m_labelCommand); - lay->addSpacing(30); - - // otherwise the command will look 'jumpy' as new symbols are added to it - // 50 pix should be enough i think - m_labelCommand->setFixedWidth(50); - - m_labelStatus->setTextFormat(Qt::PlainText); - m_labelCommand->setTextFormat(Qt::PlainText); -} - -KateViModeBar::~KateViModeBar() -{ - delete m_timer; -} - -void KateViModeBar::updateViMode(ViMode mode) -{ - m_labelStatus->setText(modeToString(mode)); -} - -void KateViModeBar::updatePartialCommand(const QString &cmd) -{ - m_labelCommand->setText(cmd); -} - -void KateViModeBar::setForegroundColor(KColorScheme::ForegroundRole role) -{ - QPalette p = m_labelMessage->palette(); - KColorScheme::adjustForeground(p, role, QPalette::WindowText, KColorScheme::Window); - m_labelMessage->setPalette(p); -} - -void KateViModeBar::showMessage(const QString &msg) -{ - if ( m_timer ) { - m_timer->stop(); - } - setForegroundColor(KColorScheme::NormalText); - m_labelMessage->setText(msg); -} - -void KateViModeBar::showErrorMessage(const QString &msg) -{ - if ( m_timer ) { - m_timer->stop(); - } - setForegroundColor(KColorScheme::NegativeText); - m_labelMessage->setText(Qt::escape(msg)); -} - -void KateViModeBar::clearMessage() -{ - // don't clear the message right away, wait two seconds so the user will see the message even if - // she presses a key right after getting the error message - if ( !m_labelMessage->text().isEmpty() ) { - if (!m_timer) { - m_timer = new QTimer(this); - connect(m_timer, SIGNAL(timeout()), this, SLOT(_clearMessage())); - m_timer->setSingleShot(true); - m_timer->setInterval(2000); - } - - m_timer->start(); - } -} - -void KateViModeBar::_clearMessage() -{ - setForegroundColor(KColorScheme::NormalText); - m_labelMessage->clear(); -} - -QString KateViModeBar::modeToString(ViMode mode) const -{ - QString modeStr; - switch (mode) { - case InsertMode: - modeStr = i18n("VI: INSERT MODE"); - break; - case NormalMode: - modeStr = i18n("VI: NORMAL MODE"); - break; - case VisualMode: - modeStr = i18n("VI: VISUAL"); - break; - case VisualBlockMode: - modeStr = i18n("VI: VISUAL BLOCK"); - break; - case VisualLineMode: - modeStr = i18n("VI: VISUAL LINE"); - break; - case ReplaceMode: - modeStr = i18n("VI: REPLACE"); - break; - } - - return modeStr; -} diff --git a/part/vimode/katevimodebar.h b/part/vimode/katevimodebar.h deleted file mode 100644 index 4b4ac04..0000000 --- a/part/vimode/katevimodebar.h +++ /dev/null @@ -1,63 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Dmitry Suzdalev - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_MODE_BAR_H -#define KATE_VI_MODE_BAR_H - -#include "kateviewhelpers.h" -#include "kateview.h" -#include "kcolorscheme.h" - -class QLabel; -class QTimer; -class KateViNormalMode; -class KateViInsertMode; -class KateViVisualMode; - -class KateViModeBar : public KateViewBarWidget -{ - Q_OBJECT -public: - explicit KateViModeBar(QWidget* parent = 0); - ~KateViModeBar(); - - void updateViMode(ViMode mode); - void updatePartialCommand(const QString &cmd); - void showMessage(const QString &msg); - void showErrorMessage(const QString &msg); - void clearMessage(); - void setForegroundColor(KColorScheme::ForegroundRole role); - -private Q_SLOTS: - void _clearMessage(); - -private: - // move to some common place? seems it may be useful for others. - QString modeToString(ViMode mode) const; - -private: - QLabel* m_labelStatus; - QLabel* m_labelMessage; - QLabel* m_labelCommand; - QTimer* m_timer; -}; - -#endif diff --git a/part/vimode/katevimodebase.cpp b/part/vimode/katevimodebase.cpp deleted file mode 100644 index 2c057bc..0000000 --- a/part/vimode/katevimodebase.cpp +++ /dev/null @@ -1,905 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 - 2009 Erlend Hamberg - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevimodebase.h" -#include "katevirange.h" -#include "kateglobal.h" -#include "kateviglobal.h" -#include "katevivisualmode.h" -#include "katevinormalmode.h" -#include "katevireplacemode.h" -#include "kateviinputmodemanager.h" - -#include -#include -#include "kateconfig.h" -#include "katedocument.h" -#include "kateviewinternal.h" -#include "katevimodebar.h" - -using KTextEditor::Cursor; -using KTextEditor::Range; - -// TODO: the "previous word/WORD [end]" methods should be optimized. now they're being called in a -// loop and all calculations done up to finding a match are trown away when called with a count > 1 -// because they will simply be called again from the last found position. -// They should take the count as a parameter and collect the positions in a QList, then return -// element (count - 1) - -//////////////////////////////////////////////////////////////////////////////// -// HELPER METHODS -//////////////////////////////////////////////////////////////////////////////// - -bool KateViModeBase::deleteRange( KateViRange &r, bool linewise, bool addToRegister) -{ - r.normalize(); - bool res = false; - QString removedText = getRange( r, linewise ); - - if ( linewise ) { - doc()->editStart(); - for ( int i = 0; i < r.endLine-r.startLine+1; i++ ) { - res = doc()->removeLine( r.startLine ); - } - doc()->editEnd(); - } else { - res = doc()->removeText( Range( r.startLine, r.startColumn, r.endLine, r.endColumn) ); - } - - if ( addToRegister ) { - if ( r.startLine == r.endLine ) { - fillRegister( getChosenRegister( '-' ), removedText ); - } else { - fillRegister( getChosenRegister( '0' ), removedText ); - } - } - - return res; -} - -const QString KateViModeBase::getRange( KateViRange &r, bool linewise) const -{ - r.normalize(); - QString s; - - if ( linewise ) { - r.startColumn = 0; - r.endColumn = getLine( r.endLine ).length(); - } - - if ( r.motionType == ViMotion::InclusiveMotion ) { - r.endColumn++; - } - - Range range( r.startLine, r.startColumn, r.endLine, r.endColumn); - - if ( linewise ) { - s = doc()->textLines( range ).join( QChar( '\n' ) ); - s.append( QChar( '\n' ) ); - } else { - s = doc()->text( range ); - } - - return s; -} - -const QString KateViModeBase::getLine( int lineNumber ) const -{ - QString line; - - if ( lineNumber == -1 ) { - Cursor cursor ( m_view->cursorPosition() ); - line = m_view->currentTextLine(); - } else { - line = doc()->line( lineNumber ); - } - - return line; -} - -const QChar KateViModeBase::getCharUnderCursor() const -{ - Cursor c( m_view->cursorPosition() ); - - QString line = getLine( c.line() ); - - if ( line.length() == 0 && c.column() >= line.length() ) { - return QChar::Null; - } - - return line.at( c.column() ); -} - -const QString KateViModeBase::getWordUnderCursor() const -{ - Cursor c( m_view->cursorPosition() ); - Cursor c1 = findPrevWordStart( c.line(), c.column()+1, true ); - Cursor c2 = findWordEnd( c1.line(), c1.column()-1, true ); - c2.setColumn( c2.column()+1 ); - - return doc()->text( Range( c1, c2 ) ); -} - -KateViRange KateViModeBase::findPattern( const QString &pattern, bool backwards, int count ) const -{ - kDebug( 13070 ) << "searching for pattern \"" << pattern << "\", backwards = " << backwards - << ", count = " << count; - if ( pattern.isEmpty() ) { - return KateViRange(); - } - - Cursor c( m_view->cursorPosition() ); - - KTextEditor::Search::SearchOptions flags = KTextEditor::Search::Regex; - - if ( backwards ) { - flags |= KTextEditor::Search::Backwards; - } - - for ( int i = count; i > 0; i-- ) { - // prepare two ranges, one from start → cursor and one from cursor → end - Range r1 = Range( Cursor( 0,0 ), c ); - - // we want to search from current position + one - if ( c.column() < doc()->lineLength( c.line() ) ) { - c.setColumn( c.column()+1 ); - } else if ( c.line() < doc()->lines() ) { - c.setColumn( 0 ); - c.setLine( c.line()+1 ); - } - - Range r2 = Range( c, doc()->documentEnd() ); - - //kDebug( 13070 ) << "r1: " << r1; - //kDebug( 13070 ) << "r2: " << r2; - - //// see if we can find the term before the end of the document (opposite if backwards) - //kDebug( 13070 ) << "searching for " << pattern << " in " << (backwards ? "r1" : "r2") << " backwards = " << backwards; - Range result = doc()->searchText( backwards ? r1 : r2, pattern, flags ).first(); - //kDebug( 13070 ) << "result: " << result; - - if ( result.isValid() ) { - c = result.start(); - } else { - - // no hits, continue from the top - result = doc()->searchText( backwards ? r2 : r1, pattern, flags ).first(); - - c = result.start(); - } - } - - return KateViRange( c.line(), c.column(), ViMotion::ExclusiveMotion ); -} - -Cursor KateViModeBase::findNextWordStart( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - // the start of word pattern need to take m_extraWordCharacters into account if defined - QString startOfWordPattern("\\b(\\w"); - if ( m_extraWordCharacters.length() > 0 ) { - startOfWordPattern.append( QLatin1String( "|[" )+m_extraWordCharacters+']' ); - } - startOfWordPattern.append( ')' ); - - QRegExp startOfWord( startOfWordPattern ); // start of a word - QRegExp nonSpaceAfterSpace( "\\s\\S" ); // non-space right after space - QRegExp nonWordAfterWord( "\\b(?!\\s)\\W" ); // word-boundary followed by a non-word which is not a space - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = startOfWord.indexIn( line, c + 1 ); - int c2 = nonSpaceAfterSpace.indexIn( line, c ); - int c3 = nonWordAfterWord.indexIn( line, c + 1 ); - - if ( c1 == -1 && c2 == -1 && c3 == -1 ) { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l >= doc()->lines()-1 ) { - c = line.length()-1; - return Cursor( l, c ); - } else { - c = 0; - l++; - - line = getLine( l ); - - if ( line.length() == 0 || !line.at( c ).isSpace() ) { - found = true; - } - - continue; - } - } - - c2++; // the second regexp will match one character *before* the character we want to go to - - if ( c1 <= 0 ) - c1 = line.length()-1; - if ( c2 <= 0 ) - c2 = line.length()-1; - if ( c3 <= 0 ) - c3 = line.length()-1; - - c = qMin( c1, qMin( c2, c3 ) ); - - found = true; - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findNextWORDStart( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - Cursor cursor ( m_view->cursorPosition() ); - QString line = getLine(); - KateViRange r( cursor.line(), cursor.column(), ViMotion::ExclusiveMotion ); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - QRegExp startOfWORD("\\s\\S"); - - while ( !found ) { - c = startOfWORD.indexIn( line, c+1 ); - - if ( c == -1 ) { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l >= doc()->lines()-1 ) { - c = line.length()-1; - break; - } else { - c = 0; - l++; - - line = getLine( l ); - - if ( line.length() == 0 || !line.at( c ).isSpace() ) { - found = true; - } - - continue; - } - } else { - c++; - found = true; - } - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findPrevWordEnd( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - QString endOfWordPattern = "\\S\\s|\\S$|\\w\\W|\\S\\b|^$"; - - if ( m_extraWordCharacters.length() > 0 ) { - endOfWordPattern.append( "|["+m_extraWordCharacters+"][^" +m_extraWordCharacters+']' ); - } - - QRegExp endOfWord( endOfWordPattern ); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = endOfWord.lastIndexIn( line, c-1 ); - - if ( c1 != -1 && c-1 != -1 ) { - found = true; - c = c1; - } else { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l > 0 ) { - line = getLine( --l ); - c = line.length(); - - continue; - } else { - c = 0; - return Cursor( l, c ); - } - } - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findPrevWORDEnd( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - QRegExp endOfWORDPattern( "\\S\\s|\\S$|^$" ); - - QRegExp endOfWORD( endOfWORDPattern ); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = endOfWORD.lastIndexIn( line, c-1 ); - - if ( c1 != -1 && c-1 != -1 ) { - found = true; - c = c1; - } else { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l > 0 ) { - line = getLine( --l ); - c = line.length(); - - continue; - } else { - c = 0; - return Cursor( l, c ); - } - } - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findPrevWordStart( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - // the start of word pattern need to take m_extraWordCharacters into account if defined - QString startOfWordPattern("\\b(\\w"); - if ( m_extraWordCharacters.length() > 0 ) { - startOfWordPattern.append( QLatin1String( "|[" )+m_extraWordCharacters+']' ); - } - startOfWordPattern.append( ')' ); - - QRegExp startOfWord( startOfWordPattern ); // start of a word - QRegExp nonSpaceAfterSpace( "\\s\\S" ); // non-space right after space - QRegExp nonWordAfterWord( "\\b(?!\\s)\\W" ); // word-boundary followed by a non-word which is not a space - QRegExp startOfLine( "^\\S" ); // non-space at start of line - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = startOfWord.lastIndexIn( line, -line.length()+c-1 ); - int c2 = nonSpaceAfterSpace.lastIndexIn( line, -line.length()+c-2 ); - int c3 = nonWordAfterWord.lastIndexIn( line, -line.length()+c-1 ); - int c4 = startOfLine.lastIndexIn( line, -line.length()+c-1 ); - - if ( c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1 ) { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l <= 0 ) { - return Cursor( 0, 0 ); - } else { - line = getLine( --l ); - c = line.length(); - - if ( line.length() == 0 ) { - c = 0; - found = true; - } - - continue; - } - } - - c2++; // the second regexp will match one character *before* the character we want to go to - - if ( c1 <= 0 ) - c1 = 0; - if ( c2 <= 0 ) - c2 = 0; - if ( c3 <= 0 ) - c3 = 0; - if ( c4 <= 0 ) - c4 = 0; - - c = qMax( c1, qMax( c2, qMax( c3, c4 ) ) ); - - found = true; - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findPrevWORDStart( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - QRegExp startOfWORD("\\s\\S"); - QRegExp startOfLineWORD("^\\S"); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = startOfWORD.lastIndexIn( line, -line.length()+c-2 ); - int c2 = startOfLineWORD.lastIndexIn( line, -line.length()+c-1 ); - - if ( c1 == -1 && c2 == -1 ) { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l <= 0 ) { - return Cursor( 0, 0 ); - } else { - line = getLine( --l ); - c = line.length(); - - if ( line.length() == 0 ) { - c = 0; - found = true; - } - - continue; - } - } - - c1++; // the startOfWORD pattern matches one character before the word - - c = qMax( c1, c2 ); - - if ( c <= 0 ) - c = 0; - - found = true; - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findWordEnd( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - QString endOfWordPattern = "\\S\\s|\\S$|\\w\\W|\\S\\b"; - - if ( m_extraWordCharacters.length() > 0 ) { - endOfWordPattern.append( "|["+m_extraWordCharacters+"][^" +m_extraWordCharacters+']' ); - } - - QRegExp endOfWORD( endOfWordPattern ); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = endOfWORD.indexIn( line, c+1 ); - - if ( c1 != -1 ) { - found = true; - c = c1; - } else { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l >= doc()->lines()-1 ) { - c = line.length()-1; - return Cursor( l, c ); - } else { - c = -1; - line = getLine( ++l ); - - continue; - } - } - } - - return Cursor( l, c ); -} - -Cursor KateViModeBase::findWORDEnd( int fromLine, int fromColumn, bool onlyCurrentLine ) const -{ - QString line = getLine( fromLine ); - - QRegExp endOfWORD( "\\S\\s|\\S$" ); - - int l = fromLine; - int c = fromColumn; - - bool found = false; - - while ( !found ) { - int c1 = endOfWORD.indexIn( line, c+1 ); - - if ( c1 != -1 ) { - found = true; - c = c1; - } else { - if ( onlyCurrentLine ) { - return Cursor( l, c ); - } else if ( l >= doc()->lines()-1 ) { - c = line.length()-1; - return Cursor( l, c ); - } else { - c = -1; - line = getLine( ++l ); - - continue; - } - } - } - - return Cursor( l, c ); -} - -// FIXME: i" won't work if the cursor is on one of the chars -KateViRange KateViModeBase::findSurrounding( const QChar &c1, const QChar &c2, bool inner ) const -{ - Cursor cursor( m_view->cursorPosition() ); - QString line = getLine(); - - int col1 = line.lastIndexOf( c1, cursor.column() ); - int col2 = line.indexOf( c2, cursor.column() ); - - KateViRange r( cursor.line(), col1, cursor.line(), col2, ViMotion::InclusiveMotion ); - - if ( col1 == -1 || col2 == -1 || col1 > col2 ) { - r.valid = false; - } - - if ( inner ) { - r.startColumn++; - r.endColumn--; - } - - return r; -} - -KateViRange KateViModeBase::findSurrounding( const QRegExp &c1, const QRegExp &c2, bool inner ) const -{ - Cursor cursor( m_view->cursorPosition() ); - QString line = getLine(); - - int col1 = line.lastIndexOf( c1, cursor.column() ); - int col2 = line.indexOf( c2, cursor.column() ); - - KateViRange r( cursor.line(), col1, cursor.line(), col2, ViMotion::InclusiveMotion ); - - if ( col1 == -1 || col2 == -1 || col1 > col2 ) { - r.valid = false; - } - - if ( inner ) { - r.startColumn++; - r.endColumn--; - } - - return r; -} - -int KateViModeBase::findLineStartingWitchChar( const QChar &c, unsigned int count, bool forward ) const -{ - int line = m_view->cursorPosition().line(); - int lines = doc()->lines(); - unsigned int hits = 0; - - if ( forward ) { - line++; - } else { - line--; - } - - while ( line < lines && line > 0 && hits < count ) { - QString l = getLine( line ); - if ( l.length() > 0 && l.at( 0 ) == c ) { - hits++; - } - if ( hits != count ) { - if ( forward ) { - line++; - } else { - line--; - } - } - } - - if ( hits == getCount() ) { - return line; - } - - return -1; -} - -void KateViModeBase::updateCursor( const Cursor &c ) const -{ - m_viewInternal->updateCursor( c ); -} - -/** - * @return the register given for the command. If no register was given, defaultReg is returned. - */ -QChar KateViModeBase::getChosenRegister( const QChar &defaultReg ) const -{ - QChar reg = ( m_register != QChar::Null ) ? m_register : defaultReg; - - return reg; -} - -QString KateViModeBase::getRegisterContent( const QChar ® ) const -{ - QString r = KateGlobal::self()->viInputModeGlobal()->getRegisterContent( reg ); - - if ( r.isNull() ) { - error( i18n( "Nothing in register %1" ,reg )); - } - - return r; -} - -void KateViModeBase::fillRegister( const QChar ®, const QString &text ) -{ - KateGlobal::self()->viInputModeGlobal()->fillRegister( reg, text ); -} - -KateViRange KateViModeBase::goLineDown() -{ - return goLineUpDown( getCount() ); -} - -KateViRange KateViModeBase::goLineUp() -{ - return goLineUpDown( -getCount() ); -} - -/** - * method for moving up or down one or more lines - * note: the sticky column is always a virtual column - */ -KateViRange KateViModeBase::goLineUpDown( int lines ) -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - int tabstop = doc()->config()->tabWidth(); - - // if in an empty document, just return - if ( lines == 0 ) { - return r; - } - - r.endLine += lines; - - // limit end line to be from line 0 through the last line - if ( r.endLine < 0 ) { - r.endLine = 0; - } else if ( r.endLine > doc()->lines()-1 ) { - r.endLine = doc()->lines()-1; - } - - Kate::TextLine startLine = doc()->plainKateTextLine( c.line() ); - Kate::TextLine endLine = doc()->plainKateTextLine( r.endLine ); - - int endLineLen = doc()->lineLength( r.endLine )-1; - - if ( endLineLen < 0 ) { - endLineLen = 0; - } - - int endLineLenVirt = endLine->toVirtualColumn(endLineLen, tabstop); - int virtColumnStart = startLine->toVirtualColumn(c.column(), tabstop); - - // if sticky column isn't set, set end column and set sticky column to its virtual column - if ( m_stickyColumn == -1 ) { - r.endColumn = endLine->fromVirtualColumn( virtColumnStart, tabstop ); - m_stickyColumn = virtColumnStart; - } else { - // sticky is set - set end column to its value - r.endColumn = endLine->fromVirtualColumn( m_stickyColumn, tabstop ); - } - - // make sure end column won't be after the last column of a line - if ( r.endColumn > endLineLen ) { - r.endColumn = endLineLen; - } - - // if we move to a line shorter than the current column, go to its end - if ( virtColumnStart > endLineLenVirt ) { - r.endColumn = endLineLen; - } - - return r; -} - -bool KateViModeBase::startNormalMode() -{ - // store the key presses for this "insert mode session" so that it can be repeated with the - // '.' command - if (!m_viInputModeManager->isRunningMacro()) { - m_viInputModeManager->storeChangeCommand(); - m_viInputModeManager->clearLog(); - } - - m_viInputModeManager->viEnterNormalMode(); - m_view->doc()->setUndoMergeAllEdits(false); - m_view->updateViModeBarMode(); - - return true; -} - -bool KateViModeBase::startInsertMode() -{ - m_viInputModeManager->viEnterInsertMode(); - m_view->doc()->setUndoMergeAllEdits(true); - m_view->updateViModeBarMode(); - - return true; -} - -bool KateViModeBase::startReplaceMode() -{ - m_view->doc()->setUndoMergeAllEdits(true); - m_viInputModeManager->viEnterReplaceMode(); - m_view->updateViModeBarMode(); - - return true; -} - -bool KateViModeBase::startVisualMode() -{ - if ( m_view->getCurrentViMode() == VisualLineMode ) { - m_viInputModeManager->getViVisualMode()->setVisualLine( false ); - m_viInputModeManager->changeViMode(VisualMode); - } else if (m_view->getCurrentViMode() == VisualBlockMode ) { - m_viInputModeManager->getViVisualMode()->setVisualBlock( false ); - m_viInputModeManager->changeViMode(VisualMode); - } else { - m_viInputModeManager->viEnterVisualMode(); - } - - m_view->updateViModeBarMode(); - - return true; -} - -bool KateViModeBase::startVisualBlockMode() -{ - if ( m_view->getCurrentViMode() == VisualMode ) { - m_viInputModeManager->getViVisualMode()->setVisualBlock( true ); - m_viInputModeManager->changeViMode(VisualBlockMode); - } else { - m_viInputModeManager->viEnterVisualMode( VisualBlockMode ); - } - - m_view->updateViModeBarMode(); - - return true; -} - -bool KateViModeBase::startVisualLineMode() -{ - if ( m_view->getCurrentViMode() == VisualMode ) { - m_viInputModeManager->getViVisualMode()->setVisualLine( true ); - m_viInputModeManager->changeViMode(VisualLineMode); - } else { - m_viInputModeManager->viEnterVisualMode( VisualLineMode ); - } - - m_view->updateViModeBarMode(); - - return true; -} - -void KateViModeBase::error( const QString &errorMsg ) const -{ - m_view->viModeBar()->showErrorMessage(errorMsg); -} - -void KateViModeBase::message( const QString &msg ) const -{ - m_view->viModeBar()->showMessage(msg); -} - -QString KateViModeBase::getVerbatimKeys() const -{ - return m_keysVerbatim; -} - -const QChar KateViModeBase::getCharAtVirtualColumn( QString &line, int virtualColumn, - int tabWidth ) const -{ - int column = 0; - int tempCol = 0; - - // sanity check: if the line is empty, there are no chars - if ( line.length() == 0 ) { - return QChar::Null; - } - - while ( tempCol < virtualColumn ) { - if ( line.at( column ) == '\t' ) { - tempCol += tabWidth - ( tempCol % tabWidth ); - } else { - tempCol++; - } - - if ( tempCol <= virtualColumn ) { - column++; - - if ( column >= line.length() ) { - return QChar::Null; - } - } - } - - if ( line.length() > column ) - return line.at( column ); - - return QChar::Null; -} - -void KateViModeBase::addToNumberUnderCursor( int count ) -{ - Cursor c( m_view->cursorPosition() ); - QString line = getLine(); - - int wordStart = findPrevWordStart( c.line(), c.column()+1, true ).column(); - int wordEnd = findWordEnd( c.line(), c.column()-1, true ).column(); - - QRegExp number( "(0x)([0-9a-fA-F]+)|\\d+" ); - - int start = number.indexIn( line, wordStart ); - if ( start <= wordEnd ) { - // FIXME: ignore leading zeroes - QString nString = number.cap(); - bool ok = false; - int base = number.cap( 1 ).isEmpty() ? 10 : 16; - int n = nString.toInt( &ok, base ); - - kDebug( 13070 ) << "base: " << base; - kDebug( 13070 ) << "n: " << n; - - if ( !ok ) { - // conversion to int failed. give up. - return; - } - - // increase/decrease number - n += count; - - // create the new text string to be inserted. prepend with “0x†if in base 16 - QString newText = (base == 16 ? "0x" : "") + QString::number(n, base); - - // replace the old number string with the new - doc()->editStart(); - doc()->removeText( KTextEditor::Range( c.line(), start , c.line(), start+nString.length() ) ); - doc()->insertText( KTextEditor::Cursor( c.line(), start ), newText ); - doc()->editEnd(); - } -} - diff --git a/part/vimode/katevimodebase.h b/part/vimode/katevimodebase.h deleted file mode 100644 index 57eb989..0000000 --- a/part/vimode/katevimodebase.h +++ /dev/null @@ -1,129 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 - 2009 Erlend Hamberg - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_MODE_BASE_INCLUDED -#define KATE_VI_MODE_BASE_INCLUDED - -#include -#include "kateview.h" -#include "katevirange.h" -#include "kateviewinternal.h" - -#include - -using KTextEditor::Cursor; -using KTextEditor::Range; - -class QKeyEvent; -class QString; -class QRegExp; -class QTimer; -class KateDocument; -class KateViVisualMode; -class KateViNormalMode; -class KateViInputModeManager; - -class KateViModeBase : public QObject -{ - Q_OBJECT - - public: - KateViModeBase() : QObject() {}; - virtual ~KateViModeBase() {}; - - /** - * @return normal mode command accumulated so far - */ - QString getVerbatimKeys() const; - - virtual void addMapping( const QString &from, const QString &to ) = 0; - virtual const QString getMapping( const QString &from ) const = 0; - virtual const QStringList getMappings() const = 0; - - protected: - // helper methods - bool deleteRange( KateViRange &r, bool linewise = true, bool addToRegister = true ); - const QString getRange( KateViRange &r, bool linewise = true ) const; - const QString getLine( int lineNumber = -1 ) const; - const QChar getCharUnderCursor() const; - const QString getWordUnderCursor() const; - KateViRange findPattern( const QString &pattern, bool backwards = false, int count = 1 ) const; - Cursor findNextWordStart( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findNextWORDStart( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findPrevWordStart( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findPrevWORDStart( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findPrevWordEnd( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findPrevWORDEnd( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findWordEnd( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - Cursor findWORDEnd( int fromLine, int fromColumn, bool onlyCurrentLine = false ) const; - KateViRange findSurrounding( const QChar &c1, const QChar &c2, bool inner = false ) const; - KateViRange findSurrounding( const QRegExp &c1, const QRegExp &c2, bool inner = false ) const; - int findLineStartingWitchChar( const QChar &c, unsigned int count, bool forward = true ) const; - void updateCursor( const Cursor &c ) const; - const QChar getCharAtVirtualColumn( QString &line, int virtualColumn, int tabWidht ) const; - - void addToNumberUnderCursor( int count ); - - KateViRange goLineUp(); - KateViRange goLineDown(); - KateViRange goLineUpDown( int lines); - - unsigned int linesDisplayed() { return m_viewInternal->linesDisplayed(); } - void scrollViewLines( int l ) { m_viewInternal->scrollViewLines( l ); } - - unsigned int getCount() const { return ( m_count > 0 ) ? m_count : 1; } - - bool startNormalMode(); - bool startInsertMode(); - bool startVisualMode(); - bool startVisualLineMode(); - bool startVisualBlockMode(); - bool startReplaceMode(); - - void error( const QString &errorMsg ) const; - void message( const QString &msg ) const; - - QChar getChosenRegister( const QChar &defaultReg ) const; - QString getRegisterContent( const QChar ® ) const; - void fillRegister( const QChar ®, const QString &text); - - QChar m_register; - - KateViRange m_commandRange; - unsigned int m_count; - - QString m_extraWordCharacters; - QString m_keysVerbatim; - - int m_stickyColumn; - - inline KateDocument* doc() const { return m_view->doc(); }; - - // key mappings - int m_timeoutlen; // time to wait for the next keypress of a multi-key mapping (default: 1000 ms) - QTimer *m_mappingTimer; - - KateView *m_view; - KateViewInternal *m_viewInternal; - KateViInputModeManager* m_viInputModeManager; -}; - -#endif diff --git a/part/vimode/katevimotion.cpp b/part/vimode/katevimotion.cpp deleted file mode 100644 index 640d472..0000000 --- a/part/vimode/katevimotion.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevimotion.h" - -KateViMotion::KateViMotion( KateViNormalMode *parent, const QString &pattern, - KateViRange (KateViNormalMode::*commandMethod)(), unsigned int flags ) - : KateViCommand( parent, pattern, 0, flags ) -{ - m_ptr2commandMethod = commandMethod; -} - -KateViRange KateViMotion::execute() const -{ - return (m_parent->*m_ptr2commandMethod)(); -} diff --git a/part/vimode/katevimotion.h b/part/vimode/katevimotion.h deleted file mode 100644 index f2c4950..0000000 --- a/part/vimode/katevimotion.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_MOTION_INCLUDED -#define KATE_VI_MOTION_INCLUDED - -#include "katevicommand.h" -#include "katevinormalmode.h" -#include "katevirange.h" - -class KateViNormalMode; - -/** - * combined class for motions and text objects. execute() returns a KateViRange. - * For motions the returned range is only a position (start pos is (-1, -1) to - * indicate this) for text objects a range (startx, starty), (endx, endy) is - * returned - */ - -class KateViMotion : public KateViCommand -{ - public: - KateViMotion( KateViNormalMode *parent, const QString &pattern, - KateViRange (KateViNormalMode::*commandMethod)(), unsigned int flags = 0 ); - KateViRange execute() const; - - protected: - KateViRange (KateViNormalMode::*m_ptr2commandMethod)(); -}; - -#endif diff --git a/part/vimode/katevinormalmode.cpp b/part/vimode/katevinormalmode.cpp deleted file mode 100644 index a8a5c7f..0000000 --- a/part/vimode/katevinormalmode.cpp +++ /dev/null @@ -1,2438 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008-2009 Erlend Hamberg - * Copyright (C) 2008 Evgeniy Ivanov - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevinormalmode.h" -#include "katevivisualmode.h" -#include "kateviinputmodemanager.h" -#include "kateviglobal.h" -#include "kateglobal.h" -#include "katebuffer.h" -#include "kateviewhelpers.h" - -#include -#include -#include - -using KTextEditor::Cursor; -using KTextEditor::Range; - -#define ADDCMD(STR,FUNC, FLGS) m_commands.push_back( \ - new KateViCommand( this, STR, &KateViNormalMode::FUNC, FLGS ) ); - -#define ADDMOTION(STR, FUNC, FLGS) m_motions.push_back( new \ - KateViMotion( this, STR, &KateViNormalMode::FUNC, FLGS ) ); - -KateViNormalMode::KateViNormalMode( KateViInputModeManager *viInputModeManager, KateView * view, - KateViewInternal * viewInternal ) : KateViModeBase() -{ - m_view = view; - m_viewInternal = viewInternal; - m_viInputModeManager = viInputModeManager; - m_stickyColumn = -1; - - // FIXME: make configurable: - m_extraWordCharacters = ""; - m_matchingItems["/*"] = "*/"; - m_matchingItems["*/"] = "-/*"; - - m_matchItemRegex = generateMatchingItemRegex(); - - m_defaultRegister = '"'; - - m_timeoutlen = 1000; // FIXME: make configurable - m_mappingKeyPress = false; // temporarily set to true when an aborted mapping sends key presses - m_mappingTimer = new QTimer( this ); - connect(m_mappingTimer, SIGNAL(timeout()), this, SLOT(mappingTimerTimeOut())); - - initializeCommands(); - resetParser(); // initialise with start configuration -} - -KateViNormalMode::~KateViNormalMode() -{ - // delete the text cursors - qDeleteAll( m_marks ); - - qDeleteAll( m_commands ); - qDeleteAll( m_motions) ; -} - -void KateViNormalMode::mappingTimerTimeOut() -{ - kDebug( 13070 ) << "timeout! key presses: " << m_mappingKeys; - m_mappingKeyPress = true; - m_viInputModeManager->feedKeyPresses( m_mappingKeys ); - m_mappingKeyPress = false; - m_mappingKeys.clear(); -} - -/** - * parses a key stroke to check if it's a valid (part of) a command - * @return true if a command was completed and executed, false otherwise - */ -bool KateViNormalMode::handleKeypress( const QKeyEvent *e ) -{ - int keyCode = e->key(); - QString text = e->text(); - - // ignore modifier keys alone - if ( keyCode == Qt::Key_Shift || keyCode == Qt::Key_Control - || keyCode == Qt::Key_Alt || keyCode == Qt::Key_Meta ) { - return false; - } - - if ( keyCode == Qt::Key_Escape ) { - reset(); - return true; - } - - QChar key = KateViKeyParser::getInstance()->KeyEventToQChar( keyCode, text, e->modifiers(), e->nativeScanCode() ); - - // check for matching mappings - if ( !m_mappingKeyPress && m_matchingCommands.size() == 0 ) { - m_mappingKeys.append( key ); - - foreach ( const QString &str, getMappings() ) { - if ( str.startsWith( m_mappingKeys ) ) { - if ( str == m_mappingKeys ) { - m_viInputModeManager->feedKeyPresses( getMapping( str ) ); - m_mappingTimer->stop(); - return true; - } else { - m_mappingTimer->start( m_timeoutlen ); - m_mappingTimer->setSingleShot( true ); - return true; - } - } - } - m_mappingKeys.clear(); - } else { - // FIXME: - //m_mappingKeyPress = false; // key press ignored wrt mappings, re-set m_mappingKeyPress - } - - m_keysVerbatim.append( KateViKeyParser::getInstance()->decodeKeySequence( key ) ); - - QChar c = QChar::Null; - if ( m_keys.size() > 0 ) { - c = m_keys.at( m_keys.size()-1 ); // last char - } - - if ( ( keyCode >= Qt::Key_0 && keyCode <= Qt::Key_9 && c != '"' ) // key 0-9 - && ( m_countTemp != 0 || keyCode != Qt::Key_0 ) // first digit can't be 0 - && ( c != 'f' && c != 't' && c != 'F' && c != 'T' && c != 'r' ) ) { // "find char" motions - - m_countTemp *= 10; - m_countTemp += keyCode-Qt::Key_0; - - return true; - } else if ( m_countTemp != 0 ) { - m_count = getCount() * m_countTemp; - m_countTemp = 0; - - kDebug( 13070 ) << "count = " << getCount(); - } - - m_keys.append( key ); - - // Special case: "cw" and "cW" work the same as "ce" and "cE" if the cursor is - // on a non-blank. This is because Vim interprets "cw" as change-word, and a - // word does not include the following white space. (:help cw in vim) - if ( ( m_keys == "cw" || m_keys == "cW" ) && !getCharUnderCursor().isSpace() ) { - // Special case of the special case: :-) - // If the cursor is at the end of the current word rewrite to "cl" - Cursor c1( m_view->cursorPosition() ); // current position - Cursor c2 = findWordEnd(c1.line(), c1.column()-1, true); // word end - - if ( c1 == c2 ) { // the cursor is at the end of a word - m_keys = "cl"; - } else { - if ( m_keys.at(1) == 'w' ) { - m_keys = "ce"; - } else { - m_keys = "cE"; - } - } - } - - if ( m_keys[ 0 ] == Qt::Key_QuoteDbl ) { - if ( m_keys.size() < 2 ) { - return true; // waiting for a register - } - else { - QChar r = m_keys[ 1 ].toLower(); - - if ( ( r >= '0' && r <= '9' ) || ( r >= 'a' && r <= 'z' ) || r == '_' || r == '+' || r == '*' ) { - m_register = r; - kDebug( 13070 ) << "Register set to " << r; - m_keys.clear(); - return true; - } - else { - resetParser(); - return true; - } - } - } - - - // if we have any matching commands so far, check which ones still match - if ( m_matchingCommands.size() > 0 ) { - int n = m_matchingCommands.size()-1; - - // remove commands not matching anymore - for ( int i = n; i >= 0; i-- ) { - if ( !m_commands.at( m_matchingCommands.at( i ) )->matches( m_keys ) ) { - //kDebug( 13070 ) << "removing " << m_commands.at( m_matchingCommands.at( i ) )->pattern() << ", size before remove is " << m_matchingCommands.size(); - if ( m_commands.at( m_matchingCommands.at( i ) )->needsMotion() ) { - // "cache" command needing a motion for later - //kDebug( 13070 ) << "m_motionOperatorIndex set to " << m_motionOperatorIndex; - m_motionOperatorIndex = m_matchingCommands.at( i ); - } - m_matchingCommands.remove( i ); - } - } - - // check if any of the matching commands need a motion/text object, if so - // push the current command length to m_awaitingMotionOrTextObject so one - // knows where to split the command between the operator and the motion - for ( int i = 0; i < m_matchingCommands.size(); i++ ) { - if ( m_commands.at( m_matchingCommands.at( i ) )->needsMotion() ) { - m_awaitingMotionOrTextObject.push( m_keys.size() ); - break; - } - } - } else { - // go through all registered commands and put possible matches in m_matchingCommands - for ( int i = 0; i < m_commands.size(); i++ ) { - if ( m_commands.at( i )->matches( m_keys ) ) { - m_matchingCommands.push_back( i ); - if ( m_commands.at( i )->needsMotion() && m_commands.at( i )->pattern().length() == m_keys.size() ) { - m_awaitingMotionOrTextObject.push( m_keys.size() ); - } - } - } - } - - // this indicates where in the command string one should start looking for a motion command - int checkFrom = ( m_awaitingMotionOrTextObject.isEmpty() ? 0 : m_awaitingMotionOrTextObject.top() ); - - //kDebug( 13070 ) << "checkFrom: " << checkFrom; - - // look for matching motion commands from position 'checkFrom' - // FIXME: if checkFrom hasn't changed, only motions whose index is in - // m_matchingMotions shold be checked - if ( checkFrom < m_keys.size() ) { - for ( int i = 0; i < m_motions.size(); i++ ) { - //kDebug( 13070 ) << "\tchecking " << m_keys.mid( checkFrom ) << " against " << m_motions.at( i )->pattern(); - if ( m_motions.at( i )->matches( m_keys.mid( checkFrom ) ) ) { - //kDebug( 13070 ) << m_keys.mid( checkFrom ) << " matches!"; - m_matchingMotions.push_back( i ); - - // if it matches exact, we have found the motion command to execute - if ( m_motions.at( i )->matchesExact( m_keys.mid( checkFrom ) ) ) { - if ( checkFrom == 0 ) { - // no command given before motion, just move the cursor to wherever - // the motion says it should go to - KateViRange r = m_motions.at( i )->execute(); - - // jump over folding regions since we are just moving the cursor - int currLine = m_view->cursorPosition().line(); - int delta = r.endLine - currLine; - int vline = doc()->foldingTree()->getVirtualLine( currLine ); - r.endLine = doc()->foldingTree()->getRealLine( vline+delta ); - if ( r.endLine >= doc()->lines() ) r.endLine = doc()->lines()-1; - - // make sure the position is valid before moving the cursor there - if ( r.valid - && r.endLine >= 0 - && ( r.endLine == 0 || r.endLine <= doc()->lines()-1 ) - && r.endColumn >= 0 - && ( r.endColumn == 0 || r.endColumn < doc()->lineLength( r.endLine ) ) ) { - kDebug( 13070 ) << "No command given, going to position (" - << r.endLine << "," << r.endColumn << ")"; - goToPos( r ); - m_viInputModeManager->clearLog(); - } else { - kDebug( 13070 ) << "Invalid position: (" << r.endLine << "," << r.endColumn << ")"; - } - - resetParser(); - return true; - } else { - // execute the specified command and supply the position returned from - // the motion - - m_commandRange = m_motions.at( i )->execute(); - - // if we didn't get an explicit start position, use the current cursor position - if ( m_commandRange.startLine == -1 ) { - Cursor c( m_view->cursorPosition() ); - m_commandRange.startLine = c.line(); - m_commandRange.startColumn = c.column(); - } - - // Special case: "word motions" should never cross a line boundary when they are the - // input to a command - if ( ( m_keys.right(1) == "w" || m_keys.right(1) == "W" ) - && m_commandRange.endLine > m_commandRange.startLine ) { - m_commandRange = motionToEOL(); - - Cursor c( m_view->cursorPosition() ); - m_commandRange.startLine = c.line(); - m_commandRange.startColumn = c.column(); - } - - if ( m_commandRange.valid ) { - kDebug( 13070 ) << "Run command" << m_commands.at( m_motionOperatorIndex )->pattern() - << "from (" << m_commandRange.startLine << "," << m_commandRange.endLine << ")" - << "to (" << m_commandRange.endLine << "," << m_commandRange.endColumn << ")"; - executeCommand( m_commands.at( m_motionOperatorIndex ) ); - } else { - kDebug( 13070 ) << "Invalid range: " - << "from (" << m_commandRange.startLine << "," << m_commandRange.endLine << ")" - << "to (" << m_commandRange.endLine << "," << m_commandRange.endColumn << ")"; - } - - reset(); - return true; - } - } - } - } - } - - //kDebug( 13070 ) << "'" << m_keys << "' MATCHING COMMANDS: " << m_matchingCommands.size(); - //kDebug( 13070 ) << "'" << m_keys << "' MATCHING MOTIONS: " << m_matchingMotions.size(); - //kDebug( 13070 ) << "'" << m_keys << "' AWAITING MOTION OR TO (INDEX): " << ( m_awaitingMotionOrTextObject.isEmpty() ? 0 : m_awaitingMotionOrTextObject.top() ); - - // if we have only one match, check if it is a perfect match and if so, execute it - // if it's not waiting for a motion or a text object - if ( m_matchingCommands.size() == 1 ) { - if ( m_commands.at( m_matchingCommands.at( 0 ) )->matchesExact( m_keys ) - && !m_commands.at( m_matchingCommands.at( 0 ) )->needsMotion() ) { - //kDebug( 13070 ) << "Running command at index " << m_matchingCommands.at( 0 ); - - KateViCommand *cmd = m_commands.at( m_matchingCommands.at( 0 ) ); - executeCommand( cmd ); - - // check if reset() should be called. some commands in visual mode should not end visual mode - if ( cmd->shouldReset() ) { - reset(); - } - resetParser(); - - return true; - } - } else if ( m_matchingCommands.size() == 0 && m_matchingMotions.size() == 0 ) { - resetParser(); - return false; - } - - m_matchingMotions.clear(); - return false; -} - -/** - * (re)set to start configuration. This is done when a command is completed - * executed or when a command is aborted - */ -void KateViNormalMode::resetParser() -{ - kDebug( 13070 ) << "***RESET***"; - m_keys.clear(); - m_keysVerbatim.clear(); - m_count = 0; - m_countTemp = 0; - m_register = QChar::Null; - m_findWaitingForChar = false; - m_matchingCommands.clear(); - m_matchingMotions.clear(); - m_awaitingMotionOrTextObject.clear(); - m_motionOperatorIndex = 0; -} - -// reset the command parser -void KateViNormalMode::reset() -{ - resetParser(); - m_commandRange.startLine = -1; - m_commandRange.startColumn = -1; -} - -void KateViNormalMode::goToPos( const KateViRange &r ) -{ - Cursor c; - c.setLine( r.endLine ); - c.setColumn( r.endColumn ); - - if ( r.jump ) { - addCurrentPositionToJumpList(); - } - - if ( c.line() >= doc()->lines() ) { - c.setLine( doc()->lines()-1 ); - } - - updateCursor( c ); -} - -void KateViNormalMode::executeCommand( const KateViCommand* cmd ) -{ - cmd->execute(); - - // if the command was a change, and it didn't enter insert mode, store the key presses so that - // they can be repeated with '.' - if ( m_viInputModeManager->getCurrentViMode() != InsertMode ) { - if ( cmd->isChange() && !m_viInputModeManager->isRunningMacro() ) { - m_viInputModeManager->storeChangeCommand(); - } - - m_viInputModeManager->clearLog(); - } - - // make sure the cursor does not end up after the end of the line - Cursor c( m_view->cursorPosition() ); - if ( m_viInputModeManager->getCurrentViMode() == NormalMode ) { - int lineLength = doc()->lineLength( c.line() ); - - if ( c.column() >= lineLength ) { - if ( lineLength == 0 ) { - c.setColumn( 0 ); - } else { - c.setColumn( lineLength-1 ); - } - } - updateCursor( c ); - } -} - -void KateViNormalMode::addCurrentPositionToJumpList() -{ - Cursor c( m_view->cursorPosition() ); - - // delete old cursor if any - if (KTextEditor::MovingCursor *oldCursor = m_marks.value('\'')) - delete oldCursor; - - // create and remember new one - KTextEditor::MovingCursor *cursor = doc()->newMovingCursor( c ); - m_marks.insert( '\'', cursor ); -} - -//////////////////////////////////////////////////////////////////////////////// -// COMMANDS AND OPERATORS -//////////////////////////////////////////////////////////////////////////////// - -/** - * enter insert mode at the cursor position - */ - -bool KateViNormalMode::commandEnterInsertMode() -{ - m_stickyColumn = -1; - return startInsertMode(); -} - -/** - * enter insert mode after the current character - */ - -bool KateViNormalMode::commandEnterInsertModeAppend() -{ - Cursor c( m_view->cursorPosition() ); - c.setColumn( c.column()+1 ); - - // if empty line, the cursor should start at column 0 - if ( doc()->lineLength( c.line() ) == 0 ) { - c.setColumn( 0 ); - } - - // cursor should never be in a column > number of columns - if ( c.column() > doc()->lineLength( c.line() ) ) { - c.setColumn( doc()->lineLength( c.line() ) ); - } - - updateCursor( c ); - - m_stickyColumn = -1; - return startInsertMode(); -} - -/** - * start insert mode after the last character of the line - */ - -bool KateViNormalMode::commandEnterInsertModeAppendEOL() -{ - Cursor c( m_view->cursorPosition() ); - c.setColumn( doc()->lineLength( c.line() ) ); - updateCursor( c ); - - m_stickyColumn = -1; - return startInsertMode(); -} - -bool KateViNormalMode::commandEnterInsertModeBeforeFirstNonBlankInLine() -{ - Cursor cursor( m_view->cursorPosition() ); - QRegExp nonSpace( "\\S" ); - int c = getLine().indexOf( nonSpace ); - if ( c == -1 ) { - c = 0; - } - cursor.setColumn( c ); - updateCursor( cursor ); - - m_stickyColumn = -1; - return startInsertMode(); -} - -bool KateViNormalMode::commandEnterVisualLineMode() -{ - if ( m_viInputModeManager->getCurrentViMode() == VisualLineMode ) { - reset(); - return true; - } - - return startVisualLineMode(); -} - -bool KateViNormalMode::commandEnterVisualBlockMode() -{ - if ( m_viInputModeManager->getCurrentViMode() == VisualBlockMode ) { - reset(); - return true; - } - - return startVisualBlockMode(); -} - -bool KateViNormalMode::commandEnterVisualMode() -{ - if ( m_viInputModeManager->getCurrentViMode() == VisualMode ) { - reset(); - return true; - } - - return startVisualMode(); -} - -bool KateViNormalMode::commandToOtherEnd() -{ - if ( m_viInputModeManager->getCurrentViMode() == VisualMode - || m_viInputModeManager->getCurrentViMode() == VisualLineMode - || m_viInputModeManager->getCurrentViMode() == VisualBlockMode ) { - m_viInputModeManager->getViVisualMode()->switchStartEnd(); - return true; - } - - return false; -} - -bool KateViNormalMode::commandEnterReplaceMode() -{ - return startReplaceMode(); -} - -bool KateViNormalMode::commandDeleteLine() -{ - Cursor c( m_view->cursorPosition() ); - - KateViRange r; - - r.startLine = c.line(); - r.endLine = c.line()+getCount()-1; - - int column = c.column(); - - bool ret = deleteRange( r, true ); - - c = m_view->cursorPosition(); - if ( column > doc()->lineLength( c.line() )-1 ) { - column = doc()->lineLength( c.line() )-1; - } - if ( column < 0 ) { - column = 0; - } - - if ( c.line() > doc()->lines()-1 ) { - c.setLine( doc()->lines()-1 ); - } - - c.setColumn( column ); - m_stickyColumn = -1; - updateCursor( c ); - - return ret; -} - -bool KateViNormalMode::commandDelete() -{ - bool linewise = m_viInputModeManager->getCurrentViMode() == VisualLineMode - || ( m_commandRange.startLine != m_commandRange.endLine - && m_viInputModeManager->getCurrentViMode() != VisualMode ); - - return deleteRange( m_commandRange, linewise ); -} - -bool KateViNormalMode::commandDeleteToEOL() -{ - Cursor c( m_view->cursorPosition() ); - - m_commandRange.endLine = c.line()+getCount()-1; - m_commandRange.endColumn = doc()->lineLength( m_commandRange.endLine )-1; - - if ( m_viInputModeManager->getCurrentViMode() == NormalMode ) { - m_commandRange.startLine = c.line(); - m_commandRange.startColumn = c.column(); - } - - bool linewise = ( m_viInputModeManager->getCurrentViMode() == VisualMode - || m_viInputModeManager->getCurrentViMode() == VisualLineMode ); - - bool r = deleteRange( m_commandRange, linewise ); - - if ( !linewise ) { - c.setColumn( doc()->lineLength( c.line() )-1 ); - } else { - c.setLine( m_commandRange.startLine-1 ); - c.setColumn( m_commandRange.startColumn ); - } - - // make sure cursor position is valid after deletion - if ( c.line() < 0 ) { - c.setLine( 0 ); - } - if ( c.column() > doc()->lineLength( c.line() )-1 ) { - c.setColumn( doc()->lineLength( c.line() )-1 ); - } - if ( c.column() < 0 ) { - c.setColumn( 0 ); - } - - updateCursor( c ); - - return r; -} - -bool KateViNormalMode::commandMakeLowercase() -{ - bool linewise = ( m_commandRange.startLine != m_commandRange.endLine - && m_viInputModeManager->getCurrentViMode() != VisualMode ); - - QString text = getRange( m_commandRange, linewise ); - QString lowerCase = text.toLower(); - - Cursor start( m_commandRange.startLine, m_commandRange.startColumn ); - Cursor end( m_commandRange.endLine, m_commandRange.endColumn ); - Range range( start, end ); - - doc()->replaceText( range, lowerCase ); - - return true; -} - -bool KateViNormalMode::commandMakeLowercaseLine() -{ - Cursor c( m_view->cursorPosition() ); - - m_commandRange.startLine = c.line(); - m_commandRange.endLine = c.line(); - m_commandRange.startColumn = 0; - m_commandRange.endColumn = doc()->lineLength( c.line() )-1; - - return commandMakeLowercase(); -} - -bool KateViNormalMode::commandMakeUppercase() -{ - bool linewise = ( m_commandRange.startLine != m_commandRange.endLine - && m_viInputModeManager->getCurrentViMode() != VisualMode ); - - QString text = getRange( m_commandRange, linewise ); - QString upperCase = text.toUpper(); - - Cursor start( m_commandRange.startLine, m_commandRange.startColumn ); - Cursor end( m_commandRange.endLine, m_commandRange.endColumn ); - Range range( start, end ); - - doc()->replaceText( range, upperCase ); - - return true; -} - -bool KateViNormalMode::commandMakeUppercaseLine() -{ - Cursor c( m_view->cursorPosition() ); - - m_commandRange.startLine = c.line(); - m_commandRange.endLine = c.line(); - m_commandRange.startColumn = 0; - m_commandRange.endColumn = doc()->lineLength( c.line() )-1; - - return commandMakeUppercase(); -} - -bool KateViNormalMode::commandChangeCase() -{ - QString text; - Range range; - Cursor c( m_view->cursorPosition() ); - - // in visual mode, the range is from start position to end position... - if ( m_viInputModeManager->getCurrentViMode() == VisualMode ) { - Cursor c2 = m_viInputModeManager->getViVisualMode()->getStart(); - - if ( c2 > c ) { - c2.setColumn( c2.column()+1 ); - } else { - c.setColumn( c.column()+1 ); - } - - range.setRange( c, c2 ); - // ... in visual line mode, the range is from column 0 on the first line to - // the line length of the last line... - } else if ( m_viInputModeManager->getCurrentViMode() == VisualLineMode ) { - Cursor c2 = m_viInputModeManager->getViVisualMode()->getStart(); - - if ( c2 > c ) { - c2.setColumn( doc()->lineLength( c2.line() ) ); - c.setColumn( 0 ); - } else { - c.setColumn( doc()->lineLength( c.line() ) ); - c2.setColumn( 0 ); - } - - range.setRange( c, c2 ); - // ... and in normal mode the range is from the current position to the - // current position + count - } else { - Cursor c2 = c; - c2.setColumn( c.column()+getCount() ); - - if ( c2.column() > doc()->lineLength( c.line() ) ) { - c2.setColumn( doc()->lineLength( c.line() ) ); - } - - range.setRange( c, c2 ); - } - - // get the text the command should operate on - text = doc()->text ( range ); - - // for every character, switch its case - for ( int i = 0; i < text.length(); i++ ) { - if ( text.at(i).isUpper() ) { - text[i] = text.at(i).toLower(); - } else if ( text.at(i).isLower() ) { - text[i] = text.at(i).toUpper(); - } - } - - // replace the old text with the modified text - doc()->replaceText( range, text ); - - // in normal mode, move the cursor to the right, in visual mode move the - // cursor to the start of the selection - if ( m_viInputModeManager->getCurrentViMode() == NormalMode ) { - updateCursor( range.end() ); - } else { - updateCursor( range.start() ); - } - - return true; -} - -bool KateViNormalMode::commandOpenNewLineUnder() -{ - Cursor c( m_view->cursorPosition() ); - - c.setColumn( doc()->lineLength( c.line() ) ); - updateCursor( c ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - doc()->newLine( m_view ); - } - - m_stickyColumn = -1; - startInsertMode(); - m_viewInternal->repaint (); - - return true; -} - -bool KateViNormalMode::commandOpenNewLineOver() -{ - Cursor c( m_view->cursorPosition() ); - - if ( c.line() == 0 ) { - for (unsigned int i = 0; i < getCount(); i++ ) { - doc()->insertLine( 0, QString() ); - } - c.setColumn( 0 ); - c.setLine( 0 ); - updateCursor( c ); - } else { - c.setLine( c.line()-1 ); - c.setColumn( getLine( c.line() ).length() ); - updateCursor( c ); - for ( unsigned int i = 0; i < getCount(); i++ ) { - doc()->newLine( m_view ); - } - - if ( getCount() > 1 ) { - c = m_view->cursorPosition(); - c.setLine( c.line()-(getCount()-1 ) ); - updateCursor( c ); - } - //c.setLine( c.line()-getCount() ); - } - - m_stickyColumn = -1; - startInsertMode(); - m_viewInternal->repaint (); - - return true; -} - -bool KateViNormalMode::commandJoinLines() -{ - Cursor c( m_view->cursorPosition() ); - - // remember line length so the cursor can be put between the joined lines - int l = doc()->lineLength( c.line() ); - - int n = getCount(); - - // if we were given a range of lines, this information overrides the previous - if ( m_commandRange.startLine != -1 && m_commandRange.endLine != -1 ) { - m_commandRange.normalize(); - c.setLine ( m_commandRange.startLine ); - n = m_commandRange.endLine-m_commandRange.startLine; - } - - // make sure we don't try to join lines past the document end - if ( n > doc()->lines()-1-c.line() ) { - n = doc()->lines()-1-c.line(); - } - - doc()->joinLines( c.line(), c.line()+n ); - - // position cursor between the joined lines - c.setColumn( l ); - updateCursor( c ); - - return true; -} - -bool KateViNormalMode::commandChange() -{ - Cursor c( m_view->cursorPosition() ); - - bool linewise = ( m_commandRange.startLine != m_commandRange.endLine - && m_viInputModeManager->getCurrentViMode() != VisualMode ); - - doc()->editStart(); - commandDelete(); - - // if we deleted several lines, insert an empty line and put the cursor there - if ( linewise ) { - doc()->insertLine( m_commandRange.startLine, QString() ); - c.setLine( m_commandRange.startLine ); - c.setColumn(0); - } - doc()->editEnd(); - - if ( linewise ) { - updateCursor( c ); - } - - commandEnterInsertMode(); - - // correct indentation level - if ( linewise ) { - m_view->align(); - } - - return true; -} - -bool KateViNormalMode::commandChangeToEOL() -{ - commandDeleteToEOL(); - commandEnterInsertModeAppend(); - - return true; -} - -bool KateViNormalMode::commandChangeLine() -{ - Cursor c( m_view->cursorPosition() ); - c.setColumn( 0 ); - updateCursor( c ); - - doc()->editStart(); - - // if count >= 2 start by deleting the whole lines - if ( getCount() >= 2 ) { - KateViRange r( c.line(), 0, c.line()+getCount()-2, 0, ViMotion::InclusiveMotion ); - deleteRange( r ); - } - - // ... then delete the _contents_ of the last line, but keep the line - KateViRange r( c.line(), c.column(), c.line(), doc()->lineLength( c.line() )-1, - ViMotion::InclusiveMotion ); - deleteRange( r, false, true ); - doc()->editEnd(); - - // ... then enter insert mode - commandEnterInsertModeAppend(); - - // correct indentation level - m_view->align(); - - return true; -} - -bool KateViNormalMode::commandSubstituteChar() -{ - if ( commandDeleteChar() ) { - return commandEnterInsertMode(); - } - - return false; -} - -bool KateViNormalMode::commandSubstituteLine() -{ - return commandChangeLine(); -} - -bool KateViNormalMode::commandYank() -{ - Cursor c( m_view->cursorPosition() ); - - bool r = false; - QString yankedText; - - bool linewise = m_viInputModeManager->getCurrentViMode() == VisualLineMode - || ( m_commandRange.startLine != m_commandRange.endLine - && m_viInputModeManager->getCurrentViMode() != VisualMode ); - - yankedText = getRange( m_commandRange, linewise ); - - fillRegister( getChosenRegister( '0' ), yankedText ); - - return r; -} - -bool KateViNormalMode::commandYankLine() -{ - Cursor c( m_view->cursorPosition() ); - QString lines; - int linenum = c.line(); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - lines.append( getLine( linenum + i ) + '\n' ); - } - fillRegister( getChosenRegister( '0' ), lines ); - - return true; -} - -bool KateViNormalMode::commandYankToEOL() -{ - Cursor c( m_view->cursorPosition() ); - - bool r = false; - QString yankedText; - - m_commandRange.endLine = c.line()+getCount()-1; - m_commandRange.endColumn = doc()->lineLength( m_commandRange.endLine )-1; - - bool linewise = ( m_viInputModeManager->getCurrentViMode() == VisualMode - || m_viInputModeManager->getCurrentViMode() == VisualLineMode ); - - if ( m_viInputModeManager->getCurrentViMode() == NormalMode ) { - m_commandRange.startLine = c.line(); - m_commandRange.startColumn = c.column(); - } - - yankedText = getRange( m_commandRange, linewise ); - - fillRegister( getChosenRegister( '0' ), yankedText ); - - return r; -} - -// insert the text in the given register at the cursor position -// the cursor should end up at the beginning of what was pasted -bool KateViNormalMode::commandPaste() -{ - Cursor c( m_view->cursorPosition() ); - Cursor cAfter = c; - QChar reg = getChosenRegister( m_defaultRegister ); - - QString textToInsert = getRegisterContent( reg ); - - if ( textToInsert.isNull() ) { - error(i18n("Nothing in register %1", reg )); - return false; - } - - if ( getCount() > 1 ) { - textToInsert = textToInsert.repeated( getCount() ); - } - - if ( textToInsert.endsWith('\n') ) { // line(s) - textToInsert.chop( 1 ); // remove the last \n - c.setColumn( doc()->lineLength( c.line() ) ); // paste after the current line and ... - textToInsert.prepend( QChar( '\n' ) ); // ... prepend a \n, so the text starts on a new line - - cAfter.setLine( cAfter.line()+1 ); - cAfter.setColumn( 0 ); - } else { - if ( getLine( c.line() ).length() > 0 ) { - c.setColumn( c.column()+1 ); - } - - cAfter = c; - } - - doc()->insertText( c, textToInsert ); - - updateCursor( cAfter ); - - return true; -} - -// insert the text in the given register before the cursor position -// the cursor should end up at the beginning of what was pasted -bool KateViNormalMode::commandPasteBefore() -{ - Cursor c( m_view->cursorPosition() ); - Cursor cAfter = c; - QChar reg = getChosenRegister( m_defaultRegister ); - - QString textToInsert = getRegisterContent( reg ); - - if ( getCount() > 1 ) { - textToInsert = textToInsert.repeated( getCount() ); - } - - if ( textToInsert.endsWith('\n') ) { // lines - c.setColumn( 0 ); - cAfter.setColumn( 0 ); - } - - doc()->insertText( c, textToInsert ); - - updateCursor( cAfter ); - - return true; -} - -bool KateViNormalMode::commandDeleteChar() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), c.line(), c.column()+getCount(), ViMotion::ExclusiveMotion ); - - if ( m_commandRange.startLine != -1 && m_commandRange.startColumn != -1 ) { - r = m_commandRange; - } else { - if ( r.endColumn > doc()->lineLength( r.startLine ) ) { - r.endColumn = doc()->lineLength( r.startLine ); - } - } - - // should only delete entire lines if in visual line mode - bool linewise = m_viInputModeManager->getCurrentViMode() == VisualLineMode; - - return deleteRange( r, linewise ); -} - -bool KateViNormalMode::commandDeleteCharBackward() -{ - Cursor c( m_view->cursorPosition() ); - - KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion ); - - if ( m_commandRange.startLine != -1 && m_commandRange.startColumn != -1 ) { - r = m_commandRange; - } else { - if ( r.startColumn < 0 ) { - r.startColumn = 0; - } - } - - // should only delete entire lines if in visual line mode - bool linewise = m_viInputModeManager->getCurrentViMode() == VisualLineMode; - - return deleteRange( r, linewise ); -} - -bool KateViNormalMode::commandReplaceCharacter() -{ - Cursor c1( m_view->cursorPosition() ); - Cursor c2( m_view->cursorPosition() ); - - c2.setColumn( c2.column()+1 ); - - bool r = doc()->replaceText( Range( c1, c2 ), m_keys.right( 1 ) ); - - updateCursor( c1 ); - - return r; -} - -bool KateViNormalMode::commandSwitchToCmdLine() -{ - Cursor c( m_view->cursorPosition() ); - - m_view->switchToCmdLine(); - - // if a count is given, the range [current line] to [current line] + count should be prepended - // to the command line - if ( getCount() != 1 ) { - m_view->cmdLineBar()->setText( ".,.+" +QString::number( getCount()-1 ), false); - } - - return true; -} - -bool KateViNormalMode::commandSearch() -{ - m_view->find(); - return true; -} - -bool KateViNormalMode::commandUndo() -{ - doc()->undo(); - return true; -} - -bool KateViNormalMode::commandRedo() -{ - doc()->redo(); - return true; -} - -bool KateViNormalMode::commandSetMark() -{ - Cursor c( m_view->cursorPosition() ); - - // delete old cursor if any - if (KTextEditor::MovingCursor *oldCursor = m_marks.value(m_keys.at( m_keys.size()-1 ))) - delete oldCursor; - - // create and remember new one - KTextEditor::MovingCursor *cursor = doc()->newMovingCursor( c ); - m_marks.insert( m_keys.at( m_keys.size()-1 ), cursor ); - - kDebug( 13070 ) << "set mark at (" << c.line() << "," << c.column() << ")"; - - return true; -} - -bool KateViNormalMode::commandIndentLine() -{ - Cursor c( m_view->cursorPosition() ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - doc()->indent( KTextEditor::Range( c.line()+i, 0, c.line()+i, 0), 1 ); - } - - return true; -} - -bool KateViNormalMode::commandUnindentLine() -{ - Cursor c( m_view->cursorPosition() ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - doc()->indent( KTextEditor::Range( c.line()+i, 0, c.line()+i, 0), -1 ); - } - - return true; -} - -bool KateViNormalMode::commandIndentLines() -{ - Cursor c( m_view->cursorPosition() ); - - m_commandRange.normalize(); - - int line1 = m_commandRange.startLine; - int line2 = m_commandRange.endLine; - int col = getLine( line2 ).length(); - - doc()->editStart(); - doc()->indent( KTextEditor::Range( line1, 0, line2, col ), 1 ); - doc()->editEnd(); - - return true; -} - -bool KateViNormalMode::commandUnindentLines() -{ - Cursor c( m_view->cursorPosition() ); - - m_commandRange.normalize(); - - int line1 = m_commandRange.startLine; - int line2 = m_commandRange.endLine; - - doc()->editStart(); - doc()->indent( KTextEditor::Range( line1, 0, line2, 0), -1 ); - doc()->editEnd(); - - return true; -} - -bool KateViNormalMode::commandScrollPageDown() -{ - m_view->pageDown(); - - return true; -} - -bool KateViNormalMode::commandScrollPageUp() -{ - m_view->pageUp(); - - return true; -} - -bool KateViNormalMode::commandCentreViewOnCursor() -{ - Cursor c( m_view->cursorPosition() ); - int linesToScroll = (m_viewInternal->endLine()-linesDisplayed()/2)-c.line(); - - scrollViewLines( -linesToScroll ); - - return true; -} - -bool KateViNormalMode::commandAbort() -{ - reset(); - return true; -} - -bool KateViNormalMode::commandPrintCharacterCode() -{ - QChar ch = getCharUnderCursor(); - - if ( ch == QChar::Null ) { - message( QString( "NUL" ) ); - } else { - - int code = ch.unicode(); - - QString dec = QString::number( code ); - QString hex = QString::number( code, 16 ); - QString oct = QString::number( code, 8 ); - if ( oct.length() < 3 ) { oct.prepend( '0' ); } - if ( code > 0x80 && code < 0x1000 ) { hex.prepend( ( code < 0x100 ? "00" : "0" ) ); } - message( i18n("'%1' %2, Hex %3, Octal %4", ch, dec, hex, oct ) ); - } - - return true; -} - -bool KateViNormalMode::commandRepeatLastChange() -{ - resetParser(); - doc()->editStart(); - m_viInputModeManager->repeatLastChange(); - doc()->editEnd(); - - return true; -} - -bool KateViNormalMode::commandAlignLine() -{ - const int line = m_view->cursorPosition().line(); - Range alignRange( Cursor(line, 0), Cursor(line, 0) ); - - doc()->align( m_view, alignRange ); - - return true; -} - -bool KateViNormalMode::commandAlignLines() -{ - Cursor c( m_view->cursorPosition() ); - m_commandRange.normalize(); - - Cursor start(m_commandRange.startLine, 0); - Cursor end(m_commandRange.endLine, 0); - - doc()->align( m_view, Range( start, end ) ); - - return true; -} - -bool KateViNormalMode::commandAddToNumber() -{ - addToNumberUnderCursor( getCount() ); - - return true; -} - -bool KateViNormalMode::commandSubtractFromNumber() -{ - addToNumberUnderCursor( -getCount() ); - - return true; -} - -//////////////////////////////////////////////////////////////////////////////// -// MOTIONS -//////////////////////////////////////////////////////////////////////////////// - -KateViRange KateViNormalMode::motionDown() -{ - return goLineDown(); -} - - -KateViRange KateViNormalMode::motionUp() -{ - return goLineUp(); -} - -KateViRange KateViNormalMode::motionLeft() -{ - Cursor cursor ( m_view->cursorPosition() ); - m_stickyColumn = -1; - KateViRange r( cursor.line(), cursor.column(), ViMotion::ExclusiveMotion ); - r.endColumn -= getCount(); - - return r; -} - -KateViRange KateViNormalMode::motionRight() -{ - Cursor cursor ( m_view->cursorPosition() ); - m_stickyColumn = -1; - KateViRange r( cursor.line(), cursor.column(), ViMotion::ExclusiveMotion ); - r.endColumn += getCount(); - - return r; -} - -KateViRange KateViNormalMode::motionPageDown() -{ - Cursor c( m_view->cursorPosition() ); - int linesToScroll = linesDisplayed(); - - KateViRange r( c.line()+linesToScroll, c.column(), ViMotion::InclusiveMotion ); - - if ( r.endLine >= doc()->lines() ) { - r.endLine = doc()->lines()-1; - } - - return r; -} - -KateViRange KateViNormalMode::motionPageUp() -{ - Cursor c( m_view->cursorPosition() ); - int linesToScroll = linesDisplayed(); - - KateViRange r( c.line()-linesToScroll, c.column(), ViMotion::InclusiveMotion ); - - if ( r.endLine < 0 ) { - r.endLine = 0; - } - - return r; -} - -KateViRange KateViNormalMode::motionDownToFirstNonBlank() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r = goLineDown(); - - r.endColumn = getLine( r.endLine ).indexOf( QRegExp( "\\S" ) ); - - if ( r.endColumn < 0 ) { - r.endColumn = 0; - } - - return r; -} - -KateViRange KateViNormalMode::motionUpToFirstNonBlank() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r = goLineUp(); - - r.endColumn = getLine( r.endLine ).indexOf( QRegExp( "\\S" ) ); - - if ( r.endColumn < 0 ) { - r.endColumn = 0; - } - - return r; -} - -KateViRange KateViNormalMode::motionWordForward() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::ExclusiveMotion ); - - m_stickyColumn = -1; - - // Special case: If we're already on the very last character in the document, the motion should be - // inclusive so the last character gets included - if ( c.line() == doc()->lines()-1 && c.column() == doc()->lineLength( c.line() )-1 ) { - r.motionType = ViMotion::InclusiveMotion; - } else { - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findNextWordStart( c.line(), c.column() ); - - // stop when at the last char in the document - if ( c.line() == doc()->lines()-1 && c.column() == doc()->lineLength( c.line() )-1 ) { - // if we still haven't "used up the count", make the motion inclusive, so that the last char - // is included - if ( i < getCount() ) { - r.motionType = ViMotion::InclusiveMotion; - } - break; - } - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionWordBackward() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::ExclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findPrevWordStart( c.line(), c.column() ); - - // stop when at the first char in the document - if ( c.line() == 0 && c.column() == 0 ) { - break; - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionWORDForward() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::ExclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findNextWORDStart( c.line(), c.column() ); - - // stop when at the last char in the document - if ( c.line() == doc()->lines()-1 && c.column() == doc()->lineLength( c.line() )-1 ) { - break; - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionWORDBackward() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::ExclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findPrevWORDStart( c.line(), c.column() ); - - // stop when at the first char in the document - if ( c.line() == 0 && c.column() == 0 ) { - break; - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToEndOfWord() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findWordEnd( c.line(), c.column() ); - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToEndOfWORD() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findWORDEnd( c.line(), c.column() ); - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToEndOfPrevWord() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findPrevWordEnd( c.line(), c.column() ); - - // stop when at the first char in the document - if ( c.line() == 0 && c.column() == 0 ) { - break; - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToEndOfPrevWORD() -{ - Cursor c( m_view->cursorPosition() ); - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - - m_stickyColumn = -1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c = findPrevWORDEnd( c.line(), c.column() ); - - // stop when at the first char in the document - if ( c.line() == 0 && c.column() == 0 ) { - break; - } - } - - r.endColumn = c.column(); - r.endLine = c.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToEOL() -{ - Cursor c( m_view->cursorPosition() ); - - // set sticky column to a rediculously high value so that the cursor will stick to EOL, - // but only if it's a regular motion - if ( m_keys.size() == 1 ) { - m_stickyColumn = 100000; - } - - unsigned int line = c.line() + ( getCount() - 1 ); - KateViRange r( line, doc()->lineLength(line )-1, ViMotion::InclusiveMotion ); - - return r; -} - -KateViRange KateViNormalMode::motionToColumn0() -{ - m_stickyColumn = -1; - Cursor cursor ( m_view->cursorPosition() ); - KateViRange r( cursor.line(), 0, ViMotion::ExclusiveMotion ); - - return r; -} - -KateViRange KateViNormalMode::motionToFirstCharacterOfLine() -{ - m_stickyColumn = -1; - - Cursor cursor ( m_view->cursorPosition() ); - QRegExp nonSpace( "\\S" ); - int c = getLine().indexOf( nonSpace ); - - KateViRange r( cursor.line(), c, ViMotion::ExclusiveMotion ); - - return r; -} - -KateViRange KateViNormalMode::motionFindChar() -{ - m_lastTFcommand = m_keys; - Cursor cursor ( m_view->cursorPosition() ); - QString line = getLine(); - - m_stickyColumn = -1; - - int matchColumn = cursor.column(); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - matchColumn = line.indexOf( m_keys.right( 1 ), matchColumn+1 ); - if ( matchColumn == -1 ) - break; - } - - KateViRange r; - - r.startColumn = cursor.column(); - r.startLine = cursor.line(); - r.endColumn = matchColumn; - r.endLine = cursor.line(); - - return r; -} - -KateViRange KateViNormalMode::motionFindCharBackward() -{ - m_lastTFcommand = m_keys; - Cursor cursor ( m_view->cursorPosition() ); - QString line = getLine(); - - m_stickyColumn = -1; - - int matchColumn = -1; - - unsigned int hits = 0; - int i = cursor.column()-1; - - while ( hits != getCount() && i >= 0 ) { - if ( line.at( i ) == m_keys.at( m_keys.size()-1 ) ) - hits++; - - if ( hits == getCount() ) - matchColumn = i; - - i--; - } - - KateViRange r; - - r.endColumn = matchColumn; - r.endLine = cursor.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToChar() -{ - m_lastTFcommand = m_keys; - Cursor cursor ( m_view->cursorPosition() ); - QString line = getLine(); - - m_stickyColumn = -1; - - int matchColumn = cursor.column()+1; - - for ( unsigned int i = 0; i < getCount(); i++ ) { - matchColumn = line.indexOf( m_keys.right( 1 ), matchColumn ); - if ( matchColumn == -1 ) - break; - } - - KateViRange r; - - r.endColumn = matchColumn-1; - r.endLine = cursor.line(); - - return r; -} - -KateViRange KateViNormalMode::motionToCharBackward() -{ - m_lastTFcommand = m_keys; - Cursor cursor ( m_view->cursorPosition() ); - QString line = getLine(); - - m_stickyColumn = -1; - - int matchColumn = -1; - - unsigned int hits = 0; - int i = cursor.column()-1; - - while ( hits != getCount() && i >= 0 ) { - if ( line.at( i ) == m_keys.at( m_keys.size()-1 ) ) - hits++; - - if ( hits == getCount() ) - matchColumn = i; - - i--; - } - - KateViRange r; - - r.endColumn = matchColumn+1; - r.endLine = cursor.line(); - - return r; -} - -KateViRange KateViNormalMode::motionRepeatlastTF() -{ - if ( !m_lastTFcommand.isEmpty() ) { - m_keys = m_lastTFcommand; - if ( m_keys.at( 0 ) == 'f' ) { - return motionFindChar(); - } - else if ( m_keys.at( 0 ) == 'F' ) { - return motionFindCharBackward(); - } - else if ( m_keys.at( 0 ) == 't' ) { - return motionToChar(); - } - else if ( m_keys.at( 0 ) == 'T' ) { - return motionToCharBackward(); - } - } - - // there was no previous t/f command - - KateViRange r; - r.valid = false; - - return r; -} - -KateViRange KateViNormalMode::motionRepeatlastTFBackward() -{ - if ( !m_lastTFcommand.isEmpty() ) { - m_keys = m_lastTFcommand; - if ( m_keys.at( 0 ) == 'f' ) { - return motionFindCharBackward(); - } - else if ( m_keys.at( 0 ) == 'F' ) { - return motionFindChar(); - } - else if ( m_keys.at( 0 ) == 't' ) { - return motionToCharBackward(); - } - else if ( m_keys.at( 0 ) == 'T' ) { - return motionToChar(); - } - } - - // there was no previous t/f command - - KateViRange r; - r.valid = false; - - return r; -} - -// FIXME: should honour the provided count -KateViRange KateViNormalMode::motionFindPrev() -{ - QString pattern = m_viInputModeManager->getLastSearchPattern(); - bool backwards = m_viInputModeManager->lastSearchBackwards(); - - return findPattern( pattern, !backwards, getCount() ); -} - -KateViRange KateViNormalMode::motionFindNext() -{ - QString pattern = m_viInputModeManager->getLastSearchPattern(); - bool backwards = m_viInputModeManager->lastSearchBackwards(); - - return findPattern( pattern, backwards, getCount() ); -} - - -KateViRange KateViNormalMode::motionToLineFirst() -{ - KateViRange r( getCount()-1, 0, ViMotion::InclusiveMotion ); - m_stickyColumn = -1; - - if ( r.endLine > doc()->lines() - 1 ) { - r.endLine = doc()->lines() - 1; - } - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToLineLast() -{ - KateViRange r( doc()->lines()-1, 0, ViMotion::InclusiveMotion ); - m_stickyColumn = -1; - - // don't use getCount() here, no count and a count of 1 is different here... - if ( m_count != 0 ) { - r.endLine = m_count-1; - } - - if ( r.endLine > doc()->lines() - 1 ) { - r.endLine = doc()->lines() - 1; - } - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToScreenColumn() -{ - m_stickyColumn = -1; - - Cursor c( m_view->cursorPosition() ); - - int column = getCount()-1; - - if ( doc()->lineLength( c.line() )-1 < (int)getCount()-1 ) { - column = doc()->lineLength( c.line() )-1; - } - - return KateViRange( c.line(), column, ViMotion::ExclusiveMotion ); -} - -KateViRange KateViNormalMode::motionToMark() -{ - KateViRange r; - - m_stickyColumn = -1; - - QChar reg = m_keys.at( m_keys.size()-1 ); - - // ` and ' is the same register (position before jump) - if ( reg == '`' ) { - reg = '\''; - } - - if ( m_marks.contains( reg ) ) { - KTextEditor::MovingCursor *cursor = m_marks.value( reg ); - r.endLine = cursor->line(); - r.endColumn = cursor->column(); - } else { - error(i18n("Mark not set: %1",m_keys.right( 1 ) )); - r.valid = false; - } - - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToMarkLine() -{ - KateViRange r = motionToMark(); - r.endColumn = 0; // FIXME: should be first non-blank on line - - m_stickyColumn = -1; - - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToMatchingItem() -{ - KateViRange r; - Cursor c( m_view->cursorPosition() ); - int lines = doc()->lines(); - QString l = getLine(); - int n1 = l.indexOf( m_matchItemRegex, c.column() ); - int n2; - - m_stickyColumn = -1; - - if ( n1 == -1 ) { - r.valid = false; - return r; - } else { - n2 = l.indexOf( QRegExp( "\\b|\\s|$" ), n1 ); - } - - // text item we want to find a matching item for - QString item = l.mid( n1, n2-n1 ); - - // use kate's built-in matching bracket finder for brackets - if ( QString("{}()[]").indexOf( item ) != -1 ) { - - // move the cursor to the first bracket - c.setColumn( n1+1 ); - updateCursor( c ); - - // find the matching one - c = m_viewInternal->findMatchingBracket(); - - if ( c > m_view->cursorPosition() ) { - c.setColumn( c.column()-1 ); - } - } else { - int toFind = 1; - //int n2 = l.indexOf( QRegExp( "\\s|$" ), n1 ); - - //QString item = l.mid( n1, n2-n1 ); - QString matchingItem = m_matchingItems[ item ]; - - int line = c.line(); - int column = n2-item.length(); - bool reverse = false; - - if ( matchingItem.left( 1 ) == "-" ) { - matchingItem.remove( 0, 1 ); // remove the '-' - reverse = true; - } - - // make sure we don't hit the text item we start the search from - if ( column == 0 && reverse ) { - column -= item.length(); - } - - int itemIdx; - int matchItemIdx; - - while ( toFind > 0 ) { - if ( !reverse ) { - itemIdx = l.indexOf( item, column ); - matchItemIdx = l.indexOf( matchingItem, column ); - - if ( itemIdx != -1 && ( matchItemIdx == -1 || itemIdx < matchItemIdx ) ) { - toFind++; - } - } else { - itemIdx = l.lastIndexOf( item, column-1 ); - matchItemIdx = l.lastIndexOf( matchingItem, column-1 ); - - if ( itemIdx != -1 && ( matchItemIdx == -1 || itemIdx > matchItemIdx ) ) { - toFind++; - } - } - - if ( matchItemIdx != -1 || itemIdx != -1 ) { - if ( !reverse ) { - column = qMin( (unsigned int)itemIdx, (unsigned int)matchItemIdx ); - } else { - column = qMax( itemIdx, matchItemIdx ); - } - } - - if ( matchItemIdx != -1 ) { // match on current line - if ( matchItemIdx == column ) { - toFind--; - c.setLine( line ); - c.setColumn( column ); - } - } else { // no match, advance one line if possible - ( reverse) ? line-- : line++; - column = 0; - - if ( ( !reverse && line >= lines ) || ( reverse && line < 0 ) ) { - r.valid = false; - break; - } else { - l = getLine( line ); - } - } - } - } - - r.endLine = c.line(); - r.endColumn = c.column(); - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToNextBraceBlockStart() -{ - KateViRange r; - - m_stickyColumn = -1; - - int line = findLineStartingWitchChar( '{', getCount() ); - - if ( line == -1 ) { - r.valid = false; - return r; - } - - r.endLine = line; - r.endColumn = 0; - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToPreviousBraceBlockStart() -{ - KateViRange r; - - m_stickyColumn = -1; - - int line = findLineStartingWitchChar( '{', getCount(), false ); - - if ( line == -1 ) { - r.valid = false; - return r; - } - - r.endLine = line; - r.endColumn = 0; - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToNextBraceBlockEnd() -{ - KateViRange r; - - m_stickyColumn = -1; - - int line = findLineStartingWitchChar( '}', getCount() ); - - if ( line == -1 ) { - r.valid = false; - return r; - } - - r.endLine = line; - r.endColumn = 0; - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToPreviousBraceBlockEnd() -{ - KateViRange r; - - m_stickyColumn = -1; - - int line = findLineStartingWitchChar( '{', getCount(), false ); - - if ( line == -1 ) { - r.valid = false; - return r; - } - - r.endLine = line; - r.endColumn = 0; - r.jump = true; - - return r; -} - -KateViRange KateViNormalMode::motionToNextOccurrence() -{ - QString word = getWordUnderCursor(); - word.prepend("\\b").append("\\b"); - - m_viInputModeManager->setLastSearchPattern( word ); - m_viInputModeManager->setLastSearchBackwards( false ); - - return findPattern( word ); -} - -KateViRange KateViNormalMode::motionToPrevOccurrence() -{ - QString word = getWordUnderCursor(); - word.prepend("\\b").append("\\b"); - - m_viInputModeManager->setLastSearchPattern( word ); - m_viInputModeManager->setLastSearchBackwards( true ); - - return findPattern( word, true ); -} - - -//////////////////////////////////////////////////////////////////////////////// -// TEXT OBJECTS -//////////////////////////////////////////////////////////////////////////////// - -KateViRange KateViNormalMode::textObjectAWord() -{ - Cursor c( m_view->cursorPosition() ); - - Cursor c1 = findPrevWordStart( c.line(), c.column()+1, true ); - Cursor c2( c ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c2 = findNextWordStart( c2.line(), c2.column(), true ); - } - - c2.setColumn( c2.column()-1 ); // don't include the first char of the following word - KateViRange r( c.line(), c.column(), ViMotion::InclusiveMotion ); - - // sanity check - if ( c1.line() != c2.line() || c1.column() > c2.column() ) { - r.valid = false; - } else { - r.startLine = c1.line(); - r.endLine = c2.line(); - r.startColumn = c1.column(); - r.endColumn = c2.column(); - } - - return r; -} - -KateViRange KateViNormalMode::textObjectInnerWord() -{ - Cursor c( m_view->cursorPosition() ); - - Cursor c1 = findPrevWordStart( c.line(), c.column()+1, true ); - // need to start search in column-1 because it might be a one-character word - Cursor c2( c.line(), c.column()-1 ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c2 = findWordEnd( c2.line(), c2.column(), true ); - } - - KateViRange r; - - // sanity check - if ( c1.line() != c2.line() || c1.column() > c2.column() ) { - r.valid = false; - } else { - r.startLine = c1.line(); - r.endLine = c2.line(); - r.startColumn = c1.column(); - r.endColumn = c2.column(); - } - - return r; -} - -KateViRange KateViNormalMode::textObjectAWORD() -{ - Cursor c( m_view->cursorPosition() ); - - Cursor c1 = findPrevWORDStart( c.line(), c.column()+1, true ); - Cursor c2( c ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c2 = findNextWORDStart( c2.line(), c2.column(), true ); - } - - KateViRange r( c.line(), c.column(), ViMotion::ExclusiveMotion ); - - // sanity check - if ( c1.line() != c2.line() || c1.column() > c2.column() ) { - r.valid = false; - } else { - r.startLine = c1.line(); - r.endLine = c2.line(); - r.startColumn = c1.column(); - r.endColumn = c2.column(); - } - - return r; -} - -KateViRange KateViNormalMode::textObjectInnerWORD() -{ - Cursor c( m_view->cursorPosition() ); - - Cursor c1 = findPrevWORDStart( c.line(), c.column()+1, true ); - Cursor c2( c ); - - for ( unsigned int i = 0; i < getCount(); i++ ) { - c2 = findWORDEnd( c2.line(), c2.column(), true ); - } - - KateViRange r; - - // sanity check - if ( c1.line() != c2.line() || c1.column() > c2.column() ) { - r.valid = false; - } else { - r.startLine = c1.line(); - r.endLine = c2.line(); - r.startColumn = c1.column(); - r.endColumn = c2.column(); - } - - return r; -} - -KateViRange KateViNormalMode::textObjectAQuoteDouble() -{ - return findSurrounding( '"', '"', false ); -} - -KateViRange KateViNormalMode::textObjectInnerQuoteDouble() -{ - return findSurrounding( '"', '"', true ); -} - -KateViRange KateViNormalMode::textObjectAQuoteSingle() -{ - return findSurrounding( '\'', '\'', false ); -} - -KateViRange KateViNormalMode::textObjectInnerQuoteSingle() -{ - return findSurrounding( '\'', '\'', true ); -} - -KateViRange KateViNormalMode::textObjectAParen() -{ - return findSurrounding( '(', ')', false ); -} - -KateViRange KateViNormalMode::textObjectInnerParen() -{ - return findSurrounding( '(', ')', true ); -} - -KateViRange KateViNormalMode::textObjectABracket() -{ - return findSurrounding( '[', ']', false ); -} - -KateViRange KateViNormalMode::textObjectInnerBracket() -{ - return findSurrounding( '[', ']', true ); -} - -KateViRange KateViNormalMode::textObjectAComma() -{ - KateViRange r = findSurrounding( ',', ',', false ); - - if ( !r.valid ) { - r = findSurrounding( QRegExp(","), QRegExp("[\\])}]"), false ); - } - - if ( !r.valid ) { - r = findSurrounding( QRegExp("[\\[({]"), QRegExp(","), false ); - } - - return r; -} - -KateViRange KateViNormalMode::textObjectInnerComma() -{ - KateViRange r = findSurrounding( ',', ',', true ); - - if ( !r.valid ) { - r = findSurrounding( QRegExp(","), QRegExp("[\\])}]"), true ); - } - - if ( !r.valid ) { - r = findSurrounding( QRegExp("[\\[({]"), QRegExp(","), true ); - } - - return r; -} - -// add commands -// when adding commands here, remember to add them to visual mode too (if applicable) -void KateViNormalMode::initializeCommands() -{ - ADDCMD("a", commandEnterInsertModeAppend, IS_CHANGE ); - ADDCMD("A", commandEnterInsertModeAppendEOL, IS_CHANGE ); - ADDCMD("i", commandEnterInsertMode, IS_CHANGE ); - ADDCMD("I", commandEnterInsertModeBeforeFirstNonBlankInLine, IS_CHANGE ); - ADDCMD("v", commandEnterVisualMode, 0 ); - ADDCMD("V", commandEnterVisualLineMode, 0 ); -//ADDCMD("", commandEnterVisualBlockMode, 0 ); - ADDCMD("o", commandOpenNewLineUnder, IS_CHANGE ); - ADDCMD("O", commandOpenNewLineOver, IS_CHANGE ); - ADDCMD("J", commandJoinLines, IS_CHANGE ); - ADDCMD("c", commandChange, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("C", commandChangeToEOL, IS_CHANGE ); - ADDCMD("cc", commandChangeLine, IS_CHANGE ); - ADDCMD("s", commandSubstituteChar, IS_CHANGE ); - ADDCMD("S", commandSubstituteLine, IS_CHANGE ); - ADDCMD("dd", commandDeleteLine, IS_CHANGE ); - ADDCMD("d", commandDelete, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("D", commandDeleteToEOL, IS_CHANGE ); - ADDCMD("x", commandDeleteChar, IS_CHANGE ); - ADDCMD("X", commandDeleteCharBackward, IS_CHANGE ); - ADDCMD("gu", commandMakeLowercase, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("guu", commandMakeLowercaseLine, IS_CHANGE ); - ADDCMD("gU", commandMakeUppercase, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("gUU", commandMakeUppercaseLine, IS_CHANGE ); - ADDCMD("y", commandYank, NEEDS_MOTION ); - ADDCMD("yy", commandYankLine, 0 ); - ADDCMD("Y", commandYankToEOL, 0 ); - ADDCMD("p", commandPaste, IS_CHANGE ); - ADDCMD("P", commandPasteBefore, IS_CHANGE ); - ADDCMD("r.", commandReplaceCharacter, IS_CHANGE | REGEX_PATTERN ); - ADDCMD("R", commandEnterReplaceMode, IS_CHANGE ); - ADDCMD(":", commandSwitchToCmdLine, 0 ); - ADDCMD("/", commandSearch, 0 ); - ADDCMD("u", commandUndo, 0); - ADDCMD("", commandRedo, 0 ); - ADDCMD("U", commandRedo, 0 ); - ADDCMD("m.", commandSetMark, REGEX_PATTERN ); - ADDCMD(">>", commandIndentLine, IS_CHANGE ); - ADDCMD("<<", commandUnindentLine, IS_CHANGE ); - ADDCMD(">", commandIndentLines, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("<", commandUnindentLines, IS_CHANGE | NEEDS_MOTION ); - ADDCMD("", commandScrollPageDown, 0 ); - ADDCMD("", commandScrollPageDown, 0 ); - ADDCMD("", commandScrollPageUp, 0 ); - ADDCMD("", commandScrollPageUp, 0 ); - ADDCMD("zz", commandCentreViewOnCursor, 0 ); - ADDCMD("ga", commandPrintCharacterCode, SHOULD_NOT_RESET ); - ADDCMD(".", commandRepeatLastChange, 0 ); - ADDCMD("==", commandAlignLine, IS_CHANGE ); - ADDCMD("=", commandAlignLines, IS_CHANGE | NEEDS_MOTION); - ADDCMD("~", commandChangeCase, IS_CHANGE ); - ADDCMD("", commandAddToNumber, IS_CHANGE ); - ADDCMD("", commandSubtractFromNumber, IS_CHANGE ); - - // regular motions - ADDMOTION("h", motionLeft, 0 ); - ADDMOTION("", motionLeft, 0 ); - ADDMOTION("", motionLeft, 0 ); - ADDMOTION("j", motionDown, 0 ); - ADDMOTION("", motionDown, 0 ); - ADDMOTION("", motionDownToFirstNonBlank, 0 ); - ADDMOTION("k", motionUp, 0 ); - ADDMOTION("", motionUp, 0 ); - ADDMOTION("-", motionUpToFirstNonBlank, 0 ); - ADDMOTION("l", motionRight, 0 ); - ADDMOTION("", motionRight, 0 ); - ADDMOTION(" ", motionRight, 0 ); - ADDMOTION("$", motionToEOL, 0 ); - ADDMOTION("", motionToEOL, 0 ); - ADDMOTION("0", motionToColumn0, 0 ); - ADDMOTION("", motionToColumn0, 0 ); - ADDMOTION("^", motionToFirstCharacterOfLine, 0 ); - ADDMOTION("f.", motionFindChar, REGEX_PATTERN ); - ADDMOTION("F.", motionFindCharBackward, REGEX_PATTERN ); - ADDMOTION("t.", motionToChar, REGEX_PATTERN ); - ADDMOTION("T.", motionToCharBackward, REGEX_PATTERN ); - ADDMOTION(";", motionRepeatlastTF, 0 ); - ADDMOTION(",", motionRepeatlastTFBackward, 0 ); - ADDMOTION("n", motionFindNext, 0 ); - ADDMOTION("N", motionFindPrev, 0 ); - ADDMOTION("gg", motionToLineFirst, 0 ); - ADDMOTION("G", motionToLineLast, 0 ); - ADDMOTION("w", motionWordForward, 0 ); - ADDMOTION("W", motionWORDForward, 0 ); - ADDMOTION("b", motionWordBackward, 0 ); - ADDMOTION("B", motionWORDBackward, 0 ); - ADDMOTION("e", motionToEndOfWord, 0 ); - ADDMOTION("E", motionToEndOfWORD, 0 ); - ADDMOTION("ge", motionToEndOfPrevWord, 0 ); - ADDMOTION("gE", motionToEndOfPrevWORD, 0 ); - ADDMOTION("|", motionToScreenColumn, 0 ); - ADDMOTION("%", motionToMatchingItem, 0 ); - ADDMOTION("`[a-zA-Z]", motionToMark, REGEX_PATTERN ); - ADDMOTION("'[a-zA-Z]", motionToMarkLine, REGEX_PATTERN ); - ADDMOTION("[[", motionToPreviousBraceBlockStart, 0 ); - ADDMOTION("]]", motionToNextBraceBlockStart, 0 ); - ADDMOTION("[]", motionToPreviousBraceBlockEnd, 0 ); - ADDMOTION("][", motionToNextBraceBlockEnd, 0 ); - ADDMOTION("*", motionToNextOccurrence, 0 ); - ADDMOTION("#", motionToPrevOccurrence, 0 ); - - // text objects - ADDMOTION("iw", textObjectInnerWord, 0 ); - ADDMOTION("aw", textObjectAWord, 0 ); - ADDMOTION("i\"", textObjectInnerQuoteDouble, 0 ); - ADDMOTION("a\"", textObjectAQuoteDouble, 0 ); - ADDMOTION("i'", textObjectInnerQuoteSingle, 0 ); - ADDMOTION("a'", textObjectAQuoteSingle, 0 ); - ADDMOTION("i[()]", textObjectInnerParen, REGEX_PATTERN ); - ADDMOTION("a[()]", textObjectAParen, REGEX_PATTERN ); - ADDMOTION("i[\\[\\]]", textObjectInnerBracket, REGEX_PATTERN ); - ADDMOTION("a[\\[\\]]", textObjectABracket, REGEX_PATTERN ); - ADDMOTION("i,", textObjectInnerComma, 0 ); - ADDMOTION("a,", textObjectAComma, 0 ); -} - -QRegExp KateViNormalMode::generateMatchingItemRegex() -{ - QString pattern("\\[|\\]|\\{|\\}|\\(|\\)|"); - QList keys = m_matchingItems.keys(); - - for ( int i = 0; i < keys.size(); i++ ) { - QString s = m_matchingItems[ keys[ i ] ]; - s = s.replace( QRegExp( "^-" ), QChar() ); - s = s.replace( QRegExp( "\\*" ), "\\*" ); - s = s.replace( QRegExp( "\\+" ), "\\+" ); - s = s.replace( QRegExp( "\\[" ), "\\[" ); - s = s.replace( QRegExp( "\\]" ), "\\]" ); - s = s.replace( QRegExp( "\\(" ), "\\(" ); - s = s.replace( QRegExp( "\\)" ), "\\)" ); - s = s.replace( QRegExp( "\\{" ), "\\{" ); - s = s.replace( QRegExp( "\\}" ), "\\}" ); - - pattern.append( s ); - - if ( i != keys.size()-1 ) { - pattern.append( '|' ); - } - } - - return QRegExp( pattern ); -} - -void KateViNormalMode::addMapping( const QString &from, const QString &to ) -{ - KateGlobal::self()->viInputModeGlobal()->addMapping( NormalMode, from, to ); -} - -const QString KateViNormalMode::getMapping( const QString &from ) const -{ - return KateGlobal::self()->viInputModeGlobal()->getMapping( NormalMode, from ); -} - -const QStringList KateViNormalMode::getMappings() const -{ - return KateGlobal::self()->viInputModeGlobal()->getMappings( NormalMode ); -} - diff --git a/part/vimode/katevinormalmode.h b/part/vimode/katevinormalmode.h deleted file mode 100644 index 75cfaf2..0000000 --- a/part/vimode/katevinormalmode.h +++ /dev/null @@ -1,259 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 - 2009 Erlend Hamberg - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_NORMAL_MODE_INCLUDED -#define KATE_VI_NORMAL_MODE_INCLUDED - -#include "kateview.h" -#include "kateviewinternal.h" -#include "katevicommand.h" -#include "katevimotion.h" -#include "katevirange.h" -#include "katevimodebase.h" - -#include -#include -#include -#include -#include -#include -#include "katevikeyparser.h" - -class KateViMotion; -class KateViInputModeManager; - -namespace KTextEditor { - class MovingCursor; -} - -/** - * Commands for the vi normal mode - */ -class KateViNormalMode : public KateViModeBase -{ - Q_OBJECT - - public slots: - void mappingTimerTimeOut(); - - public: - KateViNormalMode( KateViInputModeManager *viInputModeManager, KateView * view, KateViewInternal * viewInternal ); - virtual ~KateViNormalMode(); - - bool handleKeypress( const QKeyEvent *e ); - - bool commandEnterInsertMode(); - bool commandEnterInsertModeAppend(); - bool commandEnterInsertModeAppendEOL(); - bool commandEnterInsertModeBeforeFirstNonBlankInLine(); - - bool commandEnterVisualMode(); - bool commandEnterVisualLineMode(); - bool commandEnterVisualBlockMode(); - bool commandToOtherEnd(); - - bool commandEnterReplaceMode(); - - bool commandDelete(); - bool commandDeleteToEOL(); - bool commandDeleteLine(); - - bool commandMakeLowercase(); - bool commandMakeLowercaseLine(); - bool commandMakeUppercase(); - bool commandMakeUppercaseLine(); - bool commandChangeCase(); - - bool commandOpenNewLineUnder(); - bool commandOpenNewLineOver(); - - bool commandJoinLines(); - - bool commandChange(); - bool commandChangeLine(); - bool commandChangeToEOL(); - bool commandSubstituteChar(); - bool commandSubstituteLine(); - - bool commandYank(); - bool commandYankLine(); - bool commandYankToEOL(); - - bool commandPaste(); - bool commandPasteBefore(); - - bool commandDeleteChar(); - bool commandDeleteCharBackward(); - - bool commandReplaceCharacter(); - - bool commandSwitchToCmdLine(); - bool commandSearch(); - bool commandUndo(); - bool commandRedo(); - - bool commandSetMark(); - - bool commandIndentLine(); - bool commandUnindentLine(); - bool commandIndentLines(); - bool commandUnindentLines(); - - bool commandScrollPageDown(); - bool commandScrollPageUp(); - bool commandCentreViewOnCursor(); - - bool commandAbort(); - - bool commandPrintCharacterCode(); - - bool commandRepeatLastChange(); - - bool commandAlignLine(); - bool commandAlignLines(); - - bool commandAddToNumber(); - bool commandSubtractFromNumber(); - - // MOTIONS - - KateViRange motionLeft(); - KateViRange motionRight(); - KateViRange motionDown(); - KateViRange motionUp(); - - KateViRange motionPageDown(); - KateViRange motionPageUp(); - - KateViRange motionUpToFirstNonBlank(); - KateViRange motionDownToFirstNonBlank(); - - KateViRange motionWordForward(); - KateViRange motionWordBackward(); - KateViRange motionWORDForward(); - KateViRange motionWORDBackward(); - - KateViRange motionToEndOfWord(); - KateViRange motionToEndOfWORD(); - KateViRange motionToEndOfPrevWord(); - KateViRange motionToEndOfPrevWORD(); - - KateViRange motionFindChar(); - KateViRange motionFindCharBackward(); - KateViRange motionToChar(); - KateViRange motionToCharBackward(); - KateViRange motionRepeatlastTF(); - KateViRange motionRepeatlastTFBackward(); - KateViRange motionFindNext(); - KateViRange motionFindPrev(); - - - KateViRange motionToEOL(); - KateViRange motionToColumn0(); - KateViRange motionToFirstCharacterOfLine(); - - KateViRange motionToLineFirst(); - KateViRange motionToLineLast(); - - KateViRange motionToScreenColumn(); - - KateViRange motionToMark(); - KateViRange motionToMarkLine(); - - KateViRange motionToMatchingItem(); - - KateViRange motionToPreviousBraceBlockStart(); - KateViRange motionToNextBraceBlockStart(); - KateViRange motionToPreviousBraceBlockEnd(); - KateViRange motionToNextBraceBlockEnd(); - - KateViRange motionToNextOccurrence(); - KateViRange motionToPrevOccurrence(); - - // TEXT OBJECTS - - KateViRange textObjectAWord(); - KateViRange textObjectInnerWord(); - KateViRange textObjectAWORD(); - KateViRange textObjectInnerWORD(); - - KateViRange textObjectAQuoteDouble(); - KateViRange textObjectInnerQuoteDouble(); - - KateViRange textObjectAQuoteSingle(); - KateViRange textObjectInnerQuoteSingle(); - - KateViRange textObjectAParen(); - KateViRange textObjectInnerParen(); - - KateViRange textObjectABracket(); - KateViRange textObjectInnerBracket(); - - KateViRange textObjectAComma(); - KateViRange textObjectInnerComma(); - - void addCurrentPositionToJumpList(); - - void addMapping( const QString &from, const QString &to ); - const QString getMapping( const QString &from ) const; - const QStringList getMappings() const; - - protected: - void resetParser(); - virtual void reset(); - void initializeCommands(); - QRegExp generateMatchingItemRegex(); - virtual void goToPos( const KateViRange &r ); - void executeCommand( const KateViCommand* cmd ); - - QString m_keys; - unsigned int m_countTemp; - bool m_findWaitingForChar; - - QVector m_commands; - QVector m_motions; - QVector m_matchingCommands; - QVector m_matchingMotions; - QStack m_awaitingMotionOrTextObject; - - int m_motionOperatorIndex; - - QString m_lastTFcommand; // holds the last t/T/f/F command so that it can be repeated with ;/, - - // registers - QChar m_defaultRegister; - QString m_registerTemp; - - // marks - QMap m_marks; - - // item matching ('%' motion) - QHash m_matchingItems; - QRegExp m_matchItemRegex; - - // mappings - bool m_mappingKeyPress; - QString m_mappingKeys; - - KateViKeyParser *m_keyParser; -}; - -#endif diff --git a/part/vimode/katevirange.cpp b/part/vimode/katevirange.cpp deleted file mode 100644 index 433346c..0000000 --- a/part/vimode/katevirange.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevirange.h" - - KateViRange::KateViRange( int slin, int scol, int elin, int ecol, ViMotion::MotionType inc ) - : startLine( slin ), startColumn( scol ), endLine( elin ), endColumn( ecol ), motionType( inc ) -{ - valid = true; - jump = false; -} - -// for motions which only return a position, in constrast to "text objects" -// which returns a range - KateViRange::KateViRange( int elin, int ecol, ViMotion::MotionType inc ) - : endLine( elin ), endColumn( ecol ), motionType( inc ) -{ - startLine = -1; - startColumn = -1; - valid = true; - jump = false; -} - -KateViRange::KateViRange() -{ - startLine = -1; - startColumn = -1; - endLine = -1; - endColumn = -1; - valid = true; - jump = false; - motionType = ViMotion::InclusiveMotion; -} - -void KateViRange::normalize() -{ - if ( startLine > endLine || ( startLine == endLine && startColumn > endColumn ) ) { - int tempC, tempL; - tempL = startLine; - tempC = startColumn; - - startLine = endLine; - startColumn = endColumn; - endLine = tempL; - endColumn = tempC; - } -} diff --git a/part/vimode/katevirange.h b/part/vimode/katevirange.h deleted file mode 100644 index 4ee70ff..0000000 --- a/part/vimode/katevirange.h +++ /dev/null @@ -1,47 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_RANGE_INCLUDED -#define KATE_VI_RANGE_INCLUDED - -namespace ViMotion { - enum MotionType { - ExclusiveMotion, InclusiveMotion - }; -} - -class KateViRange -{ - public: - KateViRange( int slin, int scol, int elin, int ecol, ViMotion::MotionType mt ); - KateViRange( int elin, int ecol, ViMotion::MotionType inc ); - KateViRange(); - - void normalize(); - bool isInclusive() const { return motionType == ViMotion::InclusiveMotion; }; - - int startLine, startColumn; - int endLine, endColumn; - ViMotion::MotionType motionType; - bool valid; - bool jump; -}; - -#endif diff --git a/part/vimode/katevireplacemode.cpp b/part/vimode/katevireplacemode.cpp deleted file mode 100644 index dbfcd9e..0000000 --- a/part/vimode/katevireplacemode.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevireplacemode.h" -#include "kateviinputmodemanager.h" -#include "kateview.h" -#include "kateviewinternal.h" -#include "kateconfig.h" - -KateViReplaceMode::KateViReplaceMode( KateViInputModeManager *viInputModeManager, - KateView * view, KateViewInternal * viewInternal ) : KateViModeBase() -{ - m_view = view; - m_viewInternal = viewInternal; - m_viInputModeManager = viInputModeManager; -} - -KateViReplaceMode::~KateViReplaceMode() -{ -} - -bool KateViReplaceMode::commandInsertFromLine( int offset ) -{ - KTextEditor::Cursor c( m_view->cursorPosition() ); - KTextEditor::Cursor c2( c.line(), c.column()+1 ); - - if ( c.line()+offset > doc()->lines() || c.line()+offset < 0 ) { - return false; - } - - QString line = doc()->line( c.line()+offset ); - int tabWidth = doc()->config()->tabWidth(); - QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth ); - QChar removed = doc()->line( c.line() ).at( c.column() ); - - if ( ch == QChar::Null ) { - return false; - } - - if ( doc()->replaceText( KTextEditor::Range( c, c2 ), ch ) ) { - overwrittenChar( removed ); - return true; - } - - return false; -} - -bool KateViReplaceMode::commandMoveOneWordLeft() -{ - KTextEditor::Cursor c( m_view->cursorPosition() ); - c = findPrevWordStart( c.line(), c.column() ); - - updateCursor( c ); - return true; -} - -bool KateViReplaceMode::commandMoveOneWordRight() -{ - KTextEditor::Cursor c( m_view->cursorPosition() ); - c = findNextWordStart( c.line(), c.column() ); - - updateCursor( c ); - return true; -} - -/** - * checks if the key is a valid command - * @return true if a command was completed and executed, false otherwise - */ -bool KateViReplaceMode::handleKeypress( const QKeyEvent *e ) -{ - // backspace should work even if the shift key is down - if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) { - backspace(); - return true; - } - - KTextEditor::Cursor c( m_view->cursorPosition() ); - - if ( e->modifiers() == Qt::NoModifier ) { - switch ( e->key() ) { - case Qt::Key_Escape: - m_overwritten.clear(); - startNormalMode(); - return true; - break; - case Qt::Key_Left: - m_overwritten.clear(); - m_view->cursorLeft(); - return true; - case Qt::Key_Right: - m_overwritten.clear(); - m_view->cursorRight(); - return true; - case Qt::Key_Home: - m_overwritten.clear(); - m_view->home(); - return true; - case Qt::Key_End: - m_overwritten.clear(); - m_view->end(); - return true; - default: - return false; - break; - } - } else if ( e->modifiers() == Qt::ControlModifier ) { - switch( e->key() ) { - case Qt::Key_BracketLeft: - case Qt::Key_C: - startNormalMode(); - return true; - break; - case Qt::Key_E: - commandInsertFromLine( 1 ); - return true; - break; - case Qt::Key_Y: - commandInsertFromLine( -1 ); - return true; - break; - case Qt::Key_Left: - m_overwritten.clear(); - commandMoveOneWordLeft(); - return true; - break; - case Qt::Key_Right: - m_overwritten.clear(); - commandMoveOneWordRight(); - return true; - break; - default: - return false; - } - } - - return false; -} - -void KateViReplaceMode::backspace() -{ - KTextEditor::Cursor c1( m_view->cursorPosition() ); - KTextEditor::Cursor c2( c1.line(), c1.column()-1 ); - - if ( c1.column() > 0 ) { - if ( !m_overwritten.isEmpty() ) { - doc()->removeText(KTextEditor::Range(c1.line(), c1.column()-1, c1.line(), c1.column())); - doc()->insertText(c2 , m_overwritten.right( 1 ) ); - m_overwritten.remove( m_overwritten.length()-1, 1); - } - updateCursor( c2 ); - } -} diff --git a/part/vimode/katevireplacemode.h b/part/vimode/katevireplacemode.h deleted file mode 100644 index 6dc97c1..0000000 --- a/part/vimode/katevireplacemode.h +++ /dev/null @@ -1,60 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_REPLACE_MODE_INCLUDED -#define KATE_VI_REPLACE_MODE_INCLUDED - -#include -#include "katevimodebase.h" - -class KateViMotion; -class KateView; -class KateViewInternal; - -/** - * Commands for the vi replace mode - */ - -class KateViReplaceMode : public KateViModeBase -{ - public: - KateViReplaceMode( KateViInputModeManager *viInputModeManager, KateView * view, KateViewInternal * viewInternal ); - ~KateViReplaceMode(); - - bool handleKeypress( const QKeyEvent *e ); - - bool commandInsertFromLine( int offset ); - - bool commandMoveOneWordLeft(); - bool commandMoveOneWordRight(); - - void overwrittenChar( const QChar &s ) { m_overwritten += s; } - void backspace(); - - // mappings aren't supported in replace mode - void addMapping( const QString &from, const QString &to ) { Q_UNUSED(from) Q_UNUSED(to) } - const QString getMapping( const QString &from ) const { Q_UNUSED(from) return QString(); } - const QStringList getMappings() const { return QStringList(); } - - private: - QString m_overwritten; -}; - -#endif diff --git a/part/vimode/katevivisualmode.cpp b/part/vimode/katevivisualmode.cpp deleted file mode 100644 index 03306aa..0000000 --- a/part/vimode/katevivisualmode.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 Erlend Hamberg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "katevivisualmode.h" -#include "katevirange.h" - -using KTextEditor::Cursor; -using KTextEditor::Range; - -#define ADDCMD(STR,FUNC, FLGS) m_commands.push_back( \ - new KateViCommand( this, STR, &KateViNormalMode::FUNC, FLGS ) ); - -#define ADDMOTION(STR, FUNC, FLGS) m_motions.push_back( new \ - KateViMotion( this, STR, &KateViNormalMode::FUNC, FLGS ) ); - -KateViVisualMode::KateViVisualMode( KateViInputModeManager* viInputModeManager, KateView *view, KateViewInternal *viewInternal ) - : KateViNormalMode( viInputModeManager, view, viewInternal ) -{ - m_start.setPosition( -1, -1 ); - m_previous.setPosition( -1, -1 ); - - m_mode = VisualMode; - - initializeCommands(); -} - -KateViVisualMode::~KateViVisualMode() -{ -} - -void KateViVisualMode::updateDirty( bool entireView ) const -{ - Cursor c = m_view->cursorPosition(); - - if ( entireView ) { - m_view->tagLines(0, m_view->doc()->lastLine() ); - } else { - // tag lines that might have changed their highlighting as dirty - if ( c.line() >= m_start.line() ) { // selection in the "normal" direction - if ( c.line() > m_previous.line() ) { - m_view->tagLines(m_start.line(), c.line()); - } else { - m_view->tagLines(m_start.line(), m_previous.line()); - } - } else { // selection in the "opposite" direction, i.e., upward or to the left - if ( c.line() < m_previous.line() ) { - m_view->tagLines(c.line(), m_start.line()); - } else { - m_view->tagLines(m_previous.line(), m_start.line()); - } - } - } - m_view->updateView( true ); -} - -void KateViVisualMode::goToPos( const KateViRange &r ) -{ - Cursor c = m_view->cursorPosition(); - m_previous = c; - - if ( r.startLine != -1 && r.startColumn != -1 && c == m_start ) { - m_start.setLine( r.startLine ); - m_start.setColumn( r.startColumn ); - c.setLine( r.endLine ); - c.setColumn( r.endColumn ); - } else if ( r.startLine != -1 && r.startColumn != -1 && c < m_start ) { - c.setLine( r.startLine ); - c.setColumn( r.startColumn ); - } else { - c.setLine( r.endLine ); - c.setColumn( r.endColumn ); - } - - if ( c.line() >= doc()->lines() ) { - c.setLine( doc()->lines()-1 ); - } - - updateCursor( c ); - - m_commandRange.startLine = m_start.line(); - m_commandRange.startColumn = m_start.column(); - m_commandRange.endLine = r.endLine; - m_commandRange.endColumn = r.endColumn; - - updateDirty(); -} - -void KateViVisualMode::reset() -{ - m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 - - m_mode = VisualMode; - - // only switch to normal mode if still in visual mode. commands like c, s, ... - // can have switched to insert mode - if ( m_viInputModeManager->getCurrentViMode() == VisualMode - || m_viInputModeManager->getCurrentViMode() == VisualLineMode - || m_viInputModeManager->getCurrentViMode() == VisualBlockMode ) { - startNormalMode(); - } - - // TODO: set register < and > (see :help '< in vim) - - m_start.setPosition( -1, -1 ); - m_previous.setPosition( -1, -1 ); - - // remove highlighting - updateDirty( true ); -} - -void KateViVisualMode::init() -{ - m_start = m_view->cursorPosition(); - updateDirty(); - - m_awaitingMotionOrTextObject.push_back( 0 ); // search for text objects/motion from char 0 - - m_commandRange.startLine = m_commandRange.endLine = m_start.line(); - m_commandRange.startColumn = m_commandRange.endColumn = m_start.column(); -} - -void KateViVisualMode::setVisualLine( bool l ) -{ - if ( l ) { - m_mode = VisualLineMode; - } else { - m_mode = VisualMode; - } - updateDirty( true ); -} - -void KateViVisualMode::setVisualBlock( bool l ) -{ - if ( l ) { - m_mode = VisualBlockMode; - } else { - m_mode = VisualMode; - } - updateDirty( true ); -} - -void KateViVisualMode::setVisualModeType( ViMode mode ) -{ - Q_ASSERT( mode == VisualMode || mode == VisualLineMode || mode == VisualBlockMode ); - m_mode = mode; -} - -void KateViVisualMode::switchStartEnd() -{ - Cursor c = m_start; - m_start = m_view->cursorPosition(); - - updateCursor( c ); - - m_stickyColumn = -1; - - updateDirty(); -} - -Range KateViVisualMode::getVisualRange() const -{ - Cursor c = m_view->cursorPosition(); - - int startLine = qMin( c.line(), m_start.line() ); - int endLine = qMax( c.line(), m_start.line() ); - int startCol; - int endCol; - - if ( m_mode == VisualBlockMode ) { - startCol = qMin( c.column(), m_start.column() ); - endCol = qMax( c.column(), m_start.column() ); - } else if ( m_mode == VisualLineMode ) { - startCol = 0; - endCol = m_view->doc()->lineLength( endLine ); - } else { - if ( c.line() == endLine ) { - startCol = m_start.column(); - endCol = c.column(); - } else { - startCol = c.column(); - endCol = m_start.column(); - } - } - - return Range( startLine, startCol, endLine, endCol ); -} - -void KateViVisualMode::initializeCommands() -{ - // Remove the commands put in here by KateViNormalMode - qDeleteAll(m_commands); - m_commands.clear(); - - // Remove the motions put in here by KateViNormalMode - qDeleteAll(m_motions); - m_motions.clear(); - - ADDCMD("J", commandJoinLines, IS_CHANGE ); - ADDCMD("c", commandChange, IS_CHANGE ); - ADDCMD("s", commandChange, IS_CHANGE ); - ADDCMD("C", commandChangeToEOL, IS_CHANGE ); - ADDCMD("d", commandDelete, IS_CHANGE ); - ADDCMD("D", commandDeleteToEOL, IS_CHANGE ); - ADDCMD("x", commandDeleteChar, IS_CHANGE ); - ADDCMD("X", commandDeleteCharBackward, IS_CHANGE ); - ADDCMD("gu", commandMakeLowercase, IS_CHANGE ); - ADDCMD("u", commandMakeLowercase, IS_CHANGE ); - ADDCMD("gU", commandMakeUppercase, IS_CHANGE ); - ADDCMD("U", commandMakeUppercase, IS_CHANGE ); - ADDCMD("y", commandYank, 0 ); - ADDCMD("Y", commandYankToEOL, 0 ); - ADDCMD("p", commandPaste, IS_CHANGE ); - ADDCMD("P", commandPasteBefore, IS_CHANGE ); - ADDCMD("r.", commandReplaceCharacter, IS_CHANGE | REGEX_PATTERN ); - ADDCMD(":", commandSwitchToCmdLine, 0 ); - ADDCMD("/", commandSearch, 0 ); - ADDCMD("m.", commandSetMark, REGEX_PATTERN ); - ADDCMD(">", commandIndentLines, 0 ); - ADDCMD("<", commandUnindentLines, 0 ); - ADDCMD("", commandAbort, 0 ); - ADDCMD("", commandAbort, 0 ); - ADDCMD("ga", commandPrintCharacterCode, SHOULD_NOT_RESET ); - ADDCMD("v", commandEnterVisualMode, SHOULD_NOT_RESET ); - ADDCMD("V", commandEnterVisualLineMode, SHOULD_NOT_RESET ); - ADDCMD("o", commandToOtherEnd, SHOULD_NOT_RESET ); - ADDCMD("=", commandAlignLines, SHOULD_NOT_RESET ); - ADDCMD("~", commandChangeCase, IS_CHANGE ); - - // regular motions - ADDMOTION("h", motionLeft, 0 ); - ADDMOTION("", motionLeft, 0 ); - ADDMOTION("", motionLeft, 0 ); - ADDMOTION("j", motionDown, 0 ); - ADDMOTION("", motionDown, 0 ); - ADDMOTION("k", motionUp, 0 ); - ADDMOTION("", motionUp, 0 ); - ADDMOTION("l", motionRight, 0 ); - ADDMOTION("", motionRight, 0 ); - ADDMOTION(" ", motionRight, 0 ); - ADDMOTION("$", motionToEOL, 0 ); - ADDMOTION("", motionToEOL, 0 ); - ADDMOTION("0", motionToColumn0, 0 ); - ADDMOTION("", motionToColumn0, 0 ); - ADDMOTION("^", motionToFirstCharacterOfLine, 0 ); - ADDMOTION("f.", motionFindChar, REGEX_PATTERN ); - ADDMOTION("F.", motionFindCharBackward, REGEX_PATTERN ); - ADDMOTION("t.", motionToChar, REGEX_PATTERN ); - ADDMOTION("T.", motionToCharBackward, REGEX_PATTERN ); - ADDMOTION(";", motionRepeatlastTF, 0 ); - ADDMOTION(",", motionRepeatlastTFBackward, 0 ); - ADDMOTION("n", motionFindNext, 0 ); - ADDMOTION("N", motionFindPrev, 0 ); - ADDMOTION("gg", motionToLineFirst, 0 ); - ADDMOTION("G", motionToLineLast, 0 ); - ADDMOTION("w", motionWordForward, 0 ); - ADDMOTION("W", motionWORDForward, 0 ); - ADDMOTION("b", motionWordBackward, 0 ); - ADDMOTION("B", motionWORDBackward, 0 ); - ADDMOTION("e", motionToEndOfWord, 0 ); - ADDMOTION("E", motionToEndOfWORD, 0 ); - ADDMOTION("ge", motionToEndOfPrevWord, 0 ); - ADDMOTION("gE", motionToEndOfPrevWORD, 0 ); - ADDMOTION("|", motionToScreenColumn, 0 ); - ADDMOTION("%", motionToMatchingItem, 0 ); - ADDMOTION("`.", motionToMark, REGEX_PATTERN ); - ADDMOTION("'.", motionToMarkLine, REGEX_PATTERN ); - ADDMOTION("[[", motionToPreviousBraceBlockStart, 0 ); - ADDMOTION("]]", motionToNextBraceBlockStart, 0 ); - ADDMOTION("[]", motionToPreviousBraceBlockEnd, 0 ); - ADDMOTION("][", motionToNextBraceBlockEnd, 0 ); - ADDMOTION("", motionPageDown, 0 ); - ADDMOTION("", motionPageDown, 0 ); - ADDMOTION("", motionPageUp, 0 ); - ADDMOTION("", motionPageUp, 0 ); - - // text objects - ADDMOTION("iw", textObjectInnerWord, 0 ); - ADDMOTION("aw", textObjectAWord, 0 ); - ADDMOTION("i\"", textObjectInnerQuoteDouble, 0 ); - ADDMOTION("a\"", textObjectAQuoteDouble, 0 ); - ADDMOTION("i'", textObjectInnerQuoteSingle, 0 ); - ADDMOTION("a'", textObjectAQuoteSingle, 0 ); - ADDMOTION("i[()]", textObjectInnerParen, REGEX_PATTERN ); - ADDMOTION("a[()]", textObjectAParen, REGEX_PATTERN ); - ADDMOTION("i[\\[\\]]", textObjectInnerBracket, REGEX_PATTERN ); - ADDMOTION("a[\\[\\]]", textObjectABracket, REGEX_PATTERN ); - ADDMOTION("i,", textObjectInnerComma, 0 ); - ADDMOTION("a,", textObjectAComma, 0 ); -} diff --git a/part/vimode/katevivisualmode.h b/part/vimode/katevivisualmode.h deleted file mode 100644 index fd36d0c..0000000 --- a/part/vimode/katevivisualmode.h +++ /dev/null @@ -1,57 +0,0 @@ -/* This file is part of the KDE libraries and the Kate part. - * - * Copyright (C) 2008 - 2009 Erlend Hamberg - * Copyright (C) 2009 Paul Gideon Dann - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KATE_VI_VISUAL_MODE_INCLUDED -#define KATE_VI_VISUAL_MODE_INCLUDED - -#include -#include "katevinormalmode.h" - -class KateViRange; -class KateViInputModeManager; - -class KateViVisualMode : public KateViNormalMode { - public: - KateViVisualMode( KateViInputModeManager *viInputModeManager, KateView *view, KateViewInternal *viewInternal ); - ~KateViVisualMode(); - - void init(); - - void setVisualLine( bool l ); - void setVisualBlock( bool l ); - bool isVisualLine() const { return m_mode == VisualLineMode; } - bool isVisualBlock() const { return m_mode == VisualBlockMode; } - void switchStartEnd(); - void setVisualModeType( ViMode mode ); - KTextEditor::Cursor getStart() const { return m_start; } - KTextEditor::Range getVisualRange() const; - - private: - void initializeCommands(); - void updateDirty( bool entireView = false ) const; - void goToPos( const KateViRange &r ); - void reset(); - ViMode m_mode; - KTextEditor::Cursor m_start; - KTextEditor::Cursor m_previous; // previous position, used when deciding which lines to redraw -}; - -#endif diff --git a/qutepart/syntax/CMakeLists.txt b/qutepart/syntax/CMakeLists.txt deleted file mode 100644 index 61cd895..0000000 --- a/qutepart/syntax/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -########### install files ############### - -add_custom_target(GeneratePhpXmlFiles ALL DEPENDS - ${CMAKE_CURRENT_BINARY_DIR}/css-php.xml - ${CMAKE_CURRENT_BINARY_DIR}/html-php.xml - ${CMAKE_CURRENT_BINARY_DIR}/javascript-php.xml ) - - -macro(GENERATE_PHP_XML targetFile srcFile) - add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${targetFile} - COMMAND ${PERL_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/generate-php.pl < ${CMAKE_CURRENT_SOURCE_DIR}/${srcFile} > ${CMAKE_CURRENT_BINARY_DIR}/${targetFile} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${srcFile} ) -endmacro(GENERATE_PHP_XML) - -generate_php_xml(javascript-php.xml javascript.xml) -generate_php_xml(css-php.xml css.xml) -generate_php_xml(html-php.xml html.xml) - -file(GLOB HIGHLIGHTERS "${CMAKE_CURRENT_SOURCE_DIR}/*.xml") - -install( FILES language.dtd syntax.template ${HIGHLIGHTERS} - ${CMAKE_CURRENT_BINARY_DIR}/html-php.xml ${CMAKE_CURRENT_BINARY_DIR}/css-php.xml ${CMAKE_CURRENT_BINARY_DIR}/javascript-php.xml - DESTINATION ${DATA_INSTALL_DIR}/katepart/syntax) diff --git a/qutepart/syntax/__init__.py b/qutepart/syntax/__init__.py new file mode 100644 index 0000000..52c7e6f --- /dev/null +++ b/qutepart/syntax/__init__.py @@ -0,0 +1,2 @@ +"""Source file parser and highlighter +""" diff --git a/qutepart/syntax/abap.xml b/qutepart/syntax/abap.xml deleted file mode 100644 index 40e24ad..0000000 --- a/qutepart/syntax/abap.xml +++ /dev/null @@ -1,285 +0,0 @@ - - - - - - - - ADD - ADJACENT - ALL - AND - APPEND - APPENDING - AS - ASCENDING - AT - BEGIN - BETWEEN - BINARY - BLOCK - BY - CASE - CENTERED - CHAIN - CHANGING - CHECK - CHECKBOX - CLEAR - COL_BACKGROUND - COL_HEADING - COL_NORMAL - COL_TOTAL - COLOR - COMMENT - COMMIT - COMPARING - COMPUTE - CONCATENATE - CONDENSE - CONSTANTS - CONTINUE - CONTROLS - COUNTRY - DATA - DECIMALS - DEFAULT - DELETE - DELETING - DESCENDING - DESCRIBE - DO - DUPLICATES - EDIT - ELSE - ELSEIF - END - ENDCASE - ENDCHAIN - ENDDO - ENDIF - ENDLOOP - ENDMODULE - ENDSELECT - ENDWHILE - ENTRIES - EQ - EXCEPTIONS - EXCLUDING - EXIT - EXIT-COMMAND - EXPORT - EXPORTING - FIELD - FIRST - FOR - FORMAT - FRAME - FREE - FROM - GE - GROUP - GT - HEADER - HEADING - HIDE - HOTSPOT - ID - IF - IMPORT - IMPORTING - IN - INDEX - INITIAL - INNER - INPUT - INSERT - INTENSIFIED - INTERVALS - INTO - IS - JOIN - KEY - LE - LEAVE - LEFT - LEFT-JUSTIFIED - LIKE - LINE - LINE-COUNT - LINES - LINES - LINE-SIZE - LIST-PROCESSING - LOOP - LT - MASK - MEMORY - MESSAGE - MESSAGE-ID - MOD - MODIFY - MODULE - MOVE - MOVE-CORRESPONDING - NE - NEW-LINE - NEW-PAGE - NO - NO-EXTENSION - NO-GAP - NO-SCROLLING - NOT - NO-ZERO - NUMBER - OBLIGATORY - OCCURS - OF - OFF - ON - OR - OTHERS - OUTPUT - PAGE - PARAMETER - PARAMETERS - PERFORM - PF-STATUS - POS_HIGH - POS_LOW - POSITION - PROGRAM - RADIOBUTTON - RANGES - READ - REFRESH - REPORT - RESERVE - RESET - RIGHT - RIGHT-JUSTIFIED - ROLLBACK - ROWS - SCREEN - SCREEN-GROUP1 - SCREEN-GROUP2 - SCREEN-GROUP3 - SCREEN-GROUP4 - SCREEN-GROUP5 - SCREEN-INPUT - SCREEN-INTENSIFIED - SEARCH - SELECT - SELECTION - SELECTION-SCREEN - SELECT-OPTIONS - SEPARATED - SET - SHIFT - SINGLE - SKIP - SORT - SPACE - SPLIT - STANDARD - STARTING - STOP - STRLEN - STRUCTURE - SUBTRACT - SY-CUCOL - SY-DATUM - SY-DYNNR - SY-LINSZ - SY-LOOPC - SY-LSIND - SY-MSGID - SY-MSGTY - SY-MSGV1 - SY-MSGV2 - SY-MSGV3 - SY-MSGV4 - SY-PAGNO - SY-REPID - SY-STEPL - SY-SUBRC - SY-TABIX - SY-TCODE - SY-TMAXL - SY-UCOMM - SY-ULINE - SY-UNAME - SY-UZEIT - SY-VLINE - TABLE - TABLES - TABLEVIEW - TIMES - TITLE - TITLEBAR - TO - TRAILING - TRANSPORTING - TYPE - TYPE-POOLS - TYPES - ULINE - UP - UPDATE - USING - VALUE - WHEN - WHERE - WHILE - WITH - WORK - WRITE - AFTER - BEFORE - CALL - DURING - ENDFORM - END-OF-SELECTION - FORM - FUNCTION - INCLUDE - LINE-SELECTION - PROCESS - START-OF-SELECTION - TOP-OF-PAGE - TRANSACTION - USER-COMMAND - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/abc.xml b/qutepart/syntax/abc.xml deleted file mode 100644 index 8d5ff16..0000000 --- a/qutepart/syntax/abc.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/actionscript.xml b/qutepart/syntax/actionscript.xml deleted file mode 100644 index cea2639..0000000 --- a/qutepart/syntax/actionscript.xml +++ /dev/null @@ -1,334 +0,0 @@ - - - - - - - _accProps - _focusrect - _global - _highquality - _level - _parent - _quality - _root - _soundbuftime - maxscroll - scroll - this - - - - asfunction - call - chr - clearInterval - duplicateMovieClip - escape - eval - fscommand - getProperty - getTimer - getURL - getVersion - gotoAndPlay - gotoAndStop - ifFrameLoaded - int - isFinite - isNaN - length - loadMovie - loadMovieNum - loadVariables - loadVariablesNum - mbchr - mblength - mbord - mbsubstring - nextFrame - nextScene - on - onClipEvent - ord - parseFloat - parseInt - play - prevFrame - prevScene - print - printAsBitmap - printAsBitmapNum - printNum - random - removeMovieClip - setInterval - setProperty - showRedrawRegions - startDrag - stop - stopAllSounds - stopDrag - substring - targetPath - tellTarget - toggleHighQuality - trace - typeof - unescape - unloadMovie - unloadMovieNum - updateAfterEvent - - - - Accessibility - Accordion - Alert - Binding - Button - Camera - CellRenderer - CheckBox - Collection - Color - ComboBox - ComponentMixins - ContextMenu - ContextMenuItem - CustomActions - CustomFormatter - CustomValidator - DataGrid - DataHolder - DataProvider - DataSet - DataType - Date - DateChooser - DateField - Delta - DeltaItem - DeltaPacket - DepthManager - EndPoint - Error - FaultEvent - FocusManager - Form - Function - Iterator - Key - Label - List - LoadVars - Loader - LocalConnection - Log - Math - Media - Menu - MenuBar - Microphone - Mouse - MovieClip - MovieClipLoader - NetConnection - NetStream - Number - NumericStepper - PendingCall - PopUpManager - PrintJob - ProgressBar - RDBMSResolver - RadioButton - RelayResponder - SOAPCall - Screen - ScrollPane - Selection - SharedObject - Slide - Sound - Stage - StyleManager - System - TextArea - TextField - TextFormat - TextInput - TextSnapshot - TransferObject - Tree - TreeDataProvider - TypedValue - UIComponent - UIEventDispatcher - UIObject - Video - WebService - WebServiceConnector - Window - XML - XMLConnector - XUpdateResolver - - - - add - and - break - case - catch - class - continue - default - delete - do - dynamic - else - eq - extends - finally - for - function - ge - get - gt - if - implements - import - in - instanceof - interface - intrinsic - le - lt - ne - new - not - or - private - public - return - set - static - switch - throw - try - var - void - while - with - - - - false - Infinity - -Infinity - NaN - newline - null - true - undefined - - - - Array - Boolean - Number - Object - String - Void - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qutepart/syntax/ada.xml b/qutepart/syntax/ada.xml deleted file mode 100644 index 9bc6b76..0000000 --- a/qutepart/syntax/ada.xml +++ /dev/null @@ -1,196 +0,0 @@ - - - - - - abort - abs - abstract - accept - access - aliased - all - and - array - at - begin - body - constant - declare - delay - delta - digits - do - else - elsif - end - entry - exception - exit - for - function - generic - goto - in - interface - is - limited - mod - new - not - null - of - or - others - out - overriding - package - pragma - private - procedure - protected - raise - range - rem - record - renames - requeue - return - reverse - separate - subtype - tagged - task - terminate - then - type - until - use - when - while - with - xor - - - all_calls_remote - assert - assertion_policy - asynchronous - atomic - atomic_components - attach_handler - controlled - convention - detect_blocking - discard_names - elaborate - elaborate_all - elaborate_body - export - import - inline - inspection_point - interrupt_handler - interrupt_priority - linker_options - list - locking_policy - no_return - normalize_scalars - optimize - pack - page - partition_elaboration_policy - preelaborable_initialization - preelaborate - priority - priority_specific_dispatching - profile - pure - queuing_policy - relative_deadline - remote_call_interface - remote_types - restrictions - reviewable - shared_passive - storage_size - suppress - task_dispatching_policy - unchecked_union - unsuppress - volatile - volatile_components - - - boolean - char - float - integer - long_float - long_integer - long_long_float - long_long_integer - short_float - short_integer - string - wide_string - wide_char - wide_wide_char - wide_wide_string - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/ahdl.xml b/qutepart/syntax/ahdl.xml deleted file mode 100644 index cf0ab46..0000000 --- a/qutepart/syntax/ahdl.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - assert - bidir - bits - buried - case - clique - connected_pins - constant - defaults - define - design - device - else - elsif - for - function - generate - gnd - help_id - in - include - input - is - machine - node - of - options - others - output - parameters - returns - states - subdesign - then - title - to - tri_state_node - variable - vcc - when - with - - - carry - cascade - dffe - dff - exp - global - jkffe - jkff - latch - lcell - mcell - memory - opendrn - soft - srffe - srff - tffe - tff - tri - wire - x - - - not - and - nand - or - nor - xor - xnor - mod - div - log2 - used - ceil - floor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/alert.xml b/qutepart/syntax/alert.xml deleted file mode 100644 index f18d94d..0000000 --- a/qutepart/syntax/alert.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - diff --git a/qutepart/syntax/alert_indent.xml b/qutepart/syntax/alert_indent.xml deleted file mode 100644 index dcd96b6..0000000 --- a/qutepart/syntax/alert_indent.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - diff --git a/qutepart/syntax/ample.xml b/qutepart/syntax/ample.xml deleted file mode 100644 index d5298f1..0000000 --- a/qutepart/syntax/ample.xml +++ /dev/null @@ -1,3813 +0,0 @@ - - - - - - - break - builtin - case - continue - do - else - extern - local - for - function - if - return - switch - while - - - void - undefined - $abort_enable - $dofile_arg1 - $dofile_arg2 - $dofile_arg3 - $dofile_arg4 - $dofile_arg5 - $dofile_arg6 - $dofile_arg7 - $dofile_arg8 - $dofile_arg9 - $dofile_arg10 - $dofile_arg11 - $dofile_arg12 - $dofile_arg13 - $dofile_arg14 - $dofile_arg15 - $dofile_arg16 - $dofile_arg17 - $dofile_arg18 - $dofile_arg19 - $dofile_arg20 - $dofile_arg_count - $dofile_result - false - off - on - pi - $stderr - $stdin - $stdout - true - two_pi - - - - - - abs - acos - $add_complex - $add_status_args - asin - atan - atan2 - $bad_status - ceil - $clear_file_error - $close_file - $complex_imaginary - $complex_real - $conjugate_complex - $constrain_value - cos - cosh - cot - $create_complex - $create_string_registry - $create_vector - csc - $current_user - $cvt_exist_file - $cvt_read_variable - $cvt_type - $cvt_write_variable - $date - deg - $divide_complex - $dofile - $e - $eof - exp - $expand_rest - $f - $file_error - $file_exist - $file_pos - $file_status - floor - $flush_file - $format - $free_stream_id - $function_help - $function_ref_help - $function_signature - $g - $generate_rand - $get_ample_status - $get_app_name - $get_app_ver - $get_env - $i - $integer_divide - length - $list_overwritten_functions - $load_library - log - log10 - $lower_string - $magnitude_complex - $multiply_complex - $n - $number_string - $open_file - $ord_to_string - $phase_complex - $pop_ample_status - pow - $qsort - rad - $raise_status - $read_file - $reads_file - $real_time - $register_alias - $register_args - $register_command - $resolve_mgc_path - $round - $round_prec - $s - sec - $seek_file - $set_function_status - $set_rand - $set_status - $set_thousands - $set_transcript_mode - sin - sinh - sqrt - $sscanf - $strcat - $strftime - $string_locate - $string_status - $string_to_ord - $subtract_complex - $suspend - $sys_time - $system - tan - tanh - $time - $traceback - $truncate - $type - $undefine_id - $upper_string - $vector_count_range - $vector_element_divide - $vector_element_multiply - $vector_find - $vector_histogram - $vector_integrate - $vector_max - $vector_min - $vector_search - $vector_slope - $vector_sum - $vendor_cpu - $where_is - $write_file - $writeln_file - $writes_file - - - $acquire_license - $activate_net - $activate_net_by_handle - $activate_net_by_name - $activate_port - $activate_port_by_handle - $activate_port_by_name - $add_cell - $add_contacts - $add_device - $add_fp_shape - $add_group_property - $add_metal - $add_multiple_text - $add_net_members_to_ports - $add_overflow - $add_overflow_by_handle - $add_panel - $add_path - $add_path_device - $add_point_device - $add_property - $add_property_group_members - $add_property_group_selections - $add_property_text - $add_route - $add_row - $add_rows_by_area - $add_ruler - $add_shape - $add_shape_device - $add_text - $add_text_on_ports - $add_to_library - $add_to_net - $add_to_port - $add_via - $align - $apply_print_vector_attributes - $attach_library - $autofloorplan - $autoplace_blocks - $autoplace_corner_cells - $autoplace_group - $autoplace_pins - $autoplace_ports - $autoplace_power_vias - $autoplace_standard_cells - $autoroute_all - $autoroute_nets - $autoroute_overflow - $backannotate_net_parameters - $build_hotplot_setup - $build_lib - $build_ports - $build_ports_shapes - $build_ports_text_location - $build_power_strap_shapes - $build_power_straps - $build_read_gdsii_optfile - $change_array - $change_aspect - $change_cursor_status - $change_device - $change_from_object_template - $change_group_property - $change_layer - $change_net - $change_object_attributes - $change_object_template - $change_overflow - $change_overflow_by_handle - $change_path - $change_port - $change_property - $change_property_group_members - $change_property_group_selections - $change_property_text - $change_row - $change_text - $change_via_type - $change_window - $checkpoint_cell - $checkpoint_cell_by_name - $check_drc - $check_fn - $check_instances - $check_overflows - $check_polygons - $check_power_pins - $check_preconditions - $check_shorts_all - $check_shorts_selected - $clear_clipboard - $close_layout_library - $close_logic - $close_selection - $close_session - $close_window - $compact - $compose_groups - $compose_layer_geometries - $compose_layer_selections - $connect_instance - $convert_dracula - $copy - $copy_edit_hotkey_settings - $copy_relative - $copy_to_clipboard - $copy_to_fp_layer - $copy_to_layer - $create_cell - $create_def_from_layout_view - $create_layout_library - $create_layout_view - $create_layout_view_from_def - $create_layout_view_from_lef - $create_layout_view_from_verilog - $create_lef_from_layout_library - $create_lef_from_layout_view - $create_library - $create_process - $create_toolbar - $create_via_cell - $create_viewpoint - $cut - $cut_stretch - $deactivate - $define_hotkey - $define_layer_alias - $define_layer_name - $define_layer_set - $define_max_gate_width - $define_mos_site_type - $define_must_connect - $define_net_pair - $define_net_shield - $define_route_transform - $delete - $delete_area - $delete_connectivity - $delete_drc_all - $delete_drc_area - $delete_drc_check - $delete_drc_current - $delete_drc_point - $delete_drc_scan - $delete_from_library - $delete_group_property - $delete_lvs_results - $delete_panel - $delete_property - $delete_property_group_members - $delete_property_group_selections - $delete_routing - $delete_ruler - $delete_rulers_all - $detach_library - $display_channels - $does_cell_exist - $edit_library - $edit_process - $edit_process_override - $enable_edit_layout_library - $export_drc_check - $extract_cell_connectivity - $extract_direct_distributed_parameters - $extract_direct_lumped_parameters - $extract_mask_distributed_parameters - $extract_mask_lumped_parameters - $fillet - $fillet_area - $filter_group - $fit_fp_shape - $flatten - $flatten_hierarchy - $flip - $flip_in_place - $flip_on_axis - $form_ic_action_buttons_gadget - $form_ic_color_paint_chip_gadget - $form_ic_display_gadget - $form_ic_layer_palette_gadget - $form_ic_patterns_list_box_gadget - $form_single_check_box_gadget - $fracture - $freeze_window - $get_absolute_points - $get_acap_info - $get_active_ic_window - $get_active_net - $get_active_port - $get_arc - $get_area - $get_area_estimate - $get_array_value - $get_auto_checkpoint - $get_basepoint - $get_bottom_orient_set - $get_boundary - $get_cap_extent - $get_cap_neg_pin - $get_cap_pos_pin - $get_cell_boundary - $get_cell_configuration - $get_cell_equivalents - $get_cell_info - $get_cell_list_dts - $get_cell_path - $get_cell_refs - $get_cell_xrefs - $get_circle - $get_closed_polygon - $get_closest_object_location - $get_closest_object_points - $get_compact_add_blkgs - $get_compact_jog_power - $get_compose_layer_geometries - $get_compose_layer_selections - $get_connectivity_layers - $get_containment - $get_context_contrast - $get_context_from_world - $get_crosshair_target_radius - $get_crosshair_target_style - $get_def_bus_bit_characters - $get_def_bus_bit_characters - $get_def_divider_character - $get_def_divider_character - $get_def_non_orthogonal - $set_def_non_orthogonal - $get_design_layers - $get_design_path - $get_design_refs - $get_dev_info - $get_dev_layer - $get_dev_rule - $get_device_alias - $get_device_iobj - $get_device_name - $get_drc_check_current_count - $get_drc_check_original_count - $get_drc_check_polygon_count - $get_drc_check_scan_count - $get_drc_current_result_check_name - $get_drc_current_result_number - $get_drc_current_result_points - $get_drc_current_result_type - $get_drc_default_layer_directory_name - $get_drc_default_summary_report_file_name - $get_drc_results_database_check_count - $get_drc_results_database_check_names - $get_drc_results_database_nonempty_check_names - $get_drc_results_database_result_count - $get_drc_results_database_scan_check_names - $get_drc_results_database_scan_result_count - $get_endangered_nets - $get_externals_info - $get_fp_compute_num_rows - $get_fp_compute_route_area_ratio - $get_fp_extend_row - $get_fractured_rectangles - $get_gadget_value - $get_graphic_preempt_list - $get_group_members - $get_group_names - $get_group_property_names - $get_highlight_count - $get_hotkey_settings - $get_ic_cell_windows - $get_ic_location - $get_ic_window_names - $get_instance_extent - $get_instance_fp_extent - $get_instance_version - $get_internal_row_layout - $get_internal_row_sequence - $get_layer_info - $get_layer_minimum_spacing - $get_layer_minimum_width - $get_layer_names - $get_layer_number - $get_layer_palette_height - $get_layers - $get_layout_counterpart - $get_layout_window - $get_lef_bus_bit_characters - $get_lef_bus_bit_characters - $get_lef_divider_character - $get_lef_divider_character - $get_lef_non_orthogonal - $set_lef_non_orthogonal - $get_lef_overlap_boundary - $set_lef_overlap_boundary - $get_left_orient_set - $get_library_cells - $get_licenses - $get_loaded_logic - $get_logic_counterpart - $get_mark - $get_mask_device_count - $get_mask_discrepancy_count - $get_mask_net_count - $get_mos_gate_pin - $get_mos_sd_extent - $get_mos_sd_pin - $get_nearest_edge - $get_net_members - $get_new_object_handles - $get_object_extent - $get_object_info - $get_outdated_cells - $get_outline - $get_panel_extent - $get_panel_names - $get_parameter_default - $get_peek_protected - $get_perimeter - $get_pid - $get_pin_members - $get_pins - $get_points - $get_port_members - $get_process - $get_process_override - $get_property_handles - $get_property_names - $get_property_value - $get_report_obj_types - $get_report_options - $get_res_extent - $get_res_neg_pin - $get_res_pos_pin - $get_reserved - $get_right_orient_set - $get_rotation_point - $get_router_add_blkgs - $get_router_align_cells - $get_router_align_mode - $get_router_block_feed_percent - $get_router_block_stub_mode - $get_router_cell_feed_percent - $get_router_channel_ocr - $get_router_connect_blk_pwr - $get_router_constrain_power - $get_router_create_power_grid - $get_router_limit_area - $get_router_overflow_mode - $get_router_pre_route - $get_router_preserve_power_width - $get_router_probe_extent_margin - $get_router_x_margin - $get_router_y_margin - $get_row_members - $get_rule_file_check_count - $get_rule_file_check_names - $get_rule_file_select_check_count - $get_rule_file_select_check_names - $get_select_area - $get_select_cell - $get_select_count - $get_select_extent - $get_select_set - $get_selectable_layers - $get_selected_edges - $get_short_segment - $get_snapped_points - $get_status_line_info - $get_top_orient_set - $get_traced_properties_numeric - $get_traced_properties_string - $get_visible_layers - $get_window_cell - $get_window_info - $get_world_from_context - $get_world_from_screen - $group - $group_by_name - $group_by_property - $group_on_selected - $group_text - $hide_layer_palette - $hide_status_line - $hide_system_toolbar - $hide_toolbar - $hide_tooltips - $highlight_all - $highlight_all_discrepancies - $highlight_all_incorrect - $highlight_all_unmatched - $highlight_by_location - $highlight_by_name - $highlight_by_property - $highlight_current_discrepancy - $highlight_discrepancy - $highlight_first_discrepancy - $highlight_group - $highlight_hierarchical_net - $highlight_next_discrepancy - $highlight_on_selected - $highlight_previous_discrepancy - $highlight_protected - $hotplot - $hotplot_invoke - $insert_posts - $iroute - $is_cell_outdated - $is_cell_reserved - $is_cell_salvage_pending - $is_edge_selected - $is_history_active - $is_layer_palette_visible - $is_library_reserved - $is_licensed - $is_process_reserved - $is_select_set_closed - $is_status_line_visible - $is_toolbar_visible - $link_floorplan_shape - $list_drc_all - $list_drc_check - $list_drc_selected - $load_design_hierarchy - $load_hotkey_settings - $load_logic - $load_mask_results - $load_process - $load_rules - $loc - $lvs_direct - $lvs_mask - $make_array - $make_cell - $make_font - $make_keypad_panels - $make_net - $make_port - $mark_instances_as_ignored - $measure_distance - $merge - $mgc_scope_name_pre_init - $minimize_levels - $minimize_vias - $modify_centerline - $move - $move_acap - $move_cursor_down - $move_cursor_left - $move_cursor_right - $move_cursor_up - $move_in_row - $move_on_row - $move_relative - $msg_cell_route_hierarchy_mode - $notch - $notch_special - $open_cell - $open_cell_map - $open_clipboard - $open_context_cell - $open_group_window - $open_hierarchy_window - $open_layout_library - $open_layout_view - $open_logic - $open_logic_by_name - $open_mask_logic - $open_selected_cell - $partition_hierarchy - $paste - $peek - $peek_area - $place - $place_on_row - $place_schematic_instances - $place_schematic_ports - $polygon_to_path - $print_cell - $prompt_for_ic_line - $prompt_for_ic_location - $prompt_for_ic_polygon - $prompt_for_ic_polyline - $prompt_for_ic_rectangle - $prompt_for_ic_route - $protect - $protect_group - $protect_nets - $read_def - $read_gdsii - $read_lef - $read_spice - $read_verilog - $read_xml - $redo - $redraw - $redraw_area - $regenerate_device - $release_license - $reload_cell - $reload_cell_by_name - $remove_contacts_by_area - $remove_contacts_by_m2 - $remove_contacts_by_via - $remove_from_net - $remove_from_port - $remove_metal_by_area - $reopen_selection - $repeat_fn - $repeat_objects - $replace_cell - $replace_toolbar - $report_active_context - $report_all_mask_devices - $report_all_mask_nets - $report_capacitor_type - $report_cell - $report_cell_list_dts - $report_current_direct_net - $report_current_discrepancy - $report_current_mask_device - $report_current_mask_discrepancy - $report_current_mask_net - $report_design_layers - $report_design_tree - $report_design_xref - $report_direct_thresholds - $report_drc_all - $report_drc_area - $report_drc_check - $report_drc_current - $report_drc_point - $report_drc_scan - $report_eco_results - $report_gb_type - $report_group - $report_group_names - $report_hotkey_settings - $report_layer_attributes - $report_layer_sets - $report_library - $report_licenses - $report_logic - $report_lvs_results - $report_mask_results - $report_mask_thresholds - $report_mos_type - $report_net_parameters - $report_nets - $report_outdated_cells - $report_panels - $report_paired_nets - $report_peek_protected - $report_place_route - $report_ports - $report_process - $report_property_names - $report_reserved - $report_resistor_type - $report_row_capacity - $report_scoring - $report_selected - $report_shown_mask_devices - $report_shown_mask_discrepancies - $report_shown_mask_nets - $report_text_file - $report_via_type - $report_windows - $reselect - $reserve_cell - $reserve_cell_by_name - $reserve_library - $reserve_process - $reset_basepoint - $reset_licensing - $resize - $restore_defaults - $restore_drc_results - $restructure_nets - $resync_cell - $resync_cell_by_name - $resync_library - $resync_viewpoint - $rotate - $route_point_to_point - $rule_file_loaded - $run_eco - $salvage_cell - $salvage_reference - $save_cell - $save_cell_as - $save_cell_by_name - $save_drc_results - $save_layout_library - $save_library - $save_process - $save_process_by_name - $save_setup - $scale_cells - $scale_context - $scan_drc_all - $scan_drc_check - $sdl_cleanup - $sdl_create_cell - $select_all - $select_area - $select_area_polygon - $select_by_name - $select_by_property - $select_drc_all - $select_drc_check - $select_edge - $select_fixed_routes - $select_folds - $select_group - $select_highlighted - $select_ignored_instances - $select_on_selected - $select_one - $select_range - $select_text - $select_unplaced_schematic_instances - $select_unplaced_schematic_ports - $send_to_prompt - $set_active_port_style - $get_active_port_style - $set_active_ruler_layer - $get_active_ruler_layer - $set_add_route_alignment - $get_add_route_alignment - $set_add_route_checking - $get_add_route_checking - $set_add_route_padding - $get_add_route_padding - $set_angle_mode - $set_angle_mode_enforcement - $get_angle_mode_enforcement - $set_anneal_cooling_factor - $get_anneal_cooling_factor - $set_arc_segments - $get_arc_segments - $set_array_display_style - $get_array_display_style - $set_auto_focus_active_window - $get_auto_focus_active_window - $set_auto_outline_mode - $get_auto_outline_mode - $set_auto_restructure - $get_auto_restructure - $set_autonotch - $get_autonotch - $set_autoselect - $get_autoselect - $set_basepoint - $set_cell_configuration - $set_cell_logical_name - $set_cell_origin - $set_cell_process - $set_cell_route_hierarchy_mode - $set_cell_type - $set_check_drc_message_mode - $set_circle_input_style - $get_circle_input_style - $set_click_distance - $get_click_distance - $set_compact_center_wires - $get_compact_center_wires - $set_compact_corner_spacing - $get_compact_corner_spacing - $set_compact_cost_factor - $get_compact_cost_factor - $set_compact_ext_cells - $get_compact_ext_cells - $set_compact_ext_rows - $get_compact_ext_rows - $set_compact_jogs - $get_compact_jogs - $set_compact_offset_vias - $get_compact_offset_vias - $set_compact_path_mini - $get_compact_path_mini - $set_compact_route_levels - $get_compact_route_levels - $set_compact_suppress_output - $get_compact_suppress_output - $set_compact_to - $get_compact_to - $set_compact_wires_mode - $get_compact_wires_mode - $set_contact_count - $set_context - $set_context_up - $set_copy_ports_on_copy - $get_copy_ports_on_copy - $set_cross_probe - $get_cross_probe - $set_cross_probe_mode - $set_crosshair_style - $get_crosshair_style - $set_crosshair_target - $set_crosshair_target_radius - $set_cull - $set_def_bus_bit_characters - $set_def_divider_character - $set_def_non_orthogonal - $set_direct_thresholds - $set_display_window_title - $get_display_window_title - $set_drag_complexity - $get_drag_complexity - $set_drag_ruler_mode - $get_drag_ruler_mode - $set_drc_check - $set_drc_first - $set_drc_fit_factor - $set_drc_jump - $set_drc_last - $set_drc_next - $set_drc_previous - $set_drc_result - $set_drc_skip - $set_duplicate_ports_policy - $set_dynamic_drc - $get_dynamic_drc - $set_dynamic_drc_complexity - $get_dynamic_drc_complexity - $set_dynamic_hotkey_mode - $get_dynamic_hotkey_mode - $set_dynamic_loading - $get_dynamic_loading - $set_dynamic_message_mode - $get_dynamic_message_mode - $set_dynamic_pre_locations - $set_error_handling - $get_error_handling - $set_fill_display - $get_fill_display - $set_filled_layers - $get_filled_layers - $set_first_direct_net - $set_first_mask_device - $set_first_mask_discrepancy - $set_first_mask_net - $set_fp_bottom_gap - $get_fp_bottom_gap - $set_fp_left_gap - $get_fp_left_gap - $set_fp_lower_aspect - $get_fp_lower_aspect - $set_fp_max_height - $get_fp_max_height - $set_fp_max_width - $get_fp_max_width - $set_fp_num_rows - $get_fp_num_rows - $set_fp_right_gap - $get_fp_right_gap - $set_fp_route_area_ratio - $get_fp_route_area_ratio - $set_fp_top_gap - $get_fp_top_gap - $set_fp_upper_aspect - $get_fp_upper_aspect - $set_fractured_route - $get_fractured_route - $set_gadget_value - $set_gate_size - $set_gds_allanglefracture - $get_gds_allanglefracture - $set_gds_anglemode - $get_gds_anglemode - $set_gds_auto_identify_vias - $get_gds_auto_identify_vias - $set_gds_cellnamecase - $get_gds_cellnamecase - $set_gds_cellnamelength - $get_gds_cellnamelength - $set_gds_cellnamemap - $get_gds_cellnamemap - $set_gds_fixpolygons - $get_gds_fixpolygons - $set_gds_layerfilter - $get_gds_layerfilter - $set_gds_layermap - $get_gds_layermap - $set_gds_library - $get_gds_library - $set_gds_lockcells - $get_gds_lockcells - $set_gds_logfile - $get_gds_logfile - $set_gds_process - $get_gds_process - $set_gds_properties - $get_gds_properties - $set_gds_read_scale - $get_gds_read_scale - $set_gds_replace - $get_gds_replace - $set_gds_save_cells - $get_gds_save_cells - $set_gds_skipunmapped - $get_gds_skipunmapped - $set_gds_textheightmap - $get_gds_textheightmap - $set_gds_transcript - $get_gds_transcript - $set_graphic_interrupt - $get_graphic_interrupt - $set_gravity_distance - $get_gravity_distance - $set_grid - $set_guideline_net_size - $get_guideline_net_size - $set_guideline_width_limit - $get_guideline_width_limit - $set_hocr - $get_hocr - $set_hotkey_mode - $get_hotkey_mode - $set_ic_array_columns - $get_ic_array_columns - $set_ic_array_rows - $get_ic_array_rows - $set_ic_aspect - $get_ic_aspect - $set_ic_cell_flip - $get_ic_cell_flip - $set_ic_cell_orientation - $get_ic_cell_orientation - $set_ic_cell_rotation - $get_ic_cell_rotation - $set_ic_cell_scale - $get_ic_cell_scale - $set_ic_layer - $get_ic_layer - $set_ic_path_end_style - $get_ic_path_end_style - $set_ic_path_old_style - $get_ic_path_old_style - $set_ic_path_padding - $get_ic_path_padding - $set_ic_path_style - $get_ic_path_style - $set_ic_path_width - $get_ic_path_width - $set_ic_property_owner - $get_ic_property_owner - $set_ic_property_replace - $get_ic_property_replace - $set_ic_property_text_height - $get_ic_property_text_height - $set_ic_property_text_horz_just - $get_ic_property_text_horz_just - $set_ic_property_text_orientation - $get_ic_property_text_orientation - $set_ic_property_text_vert_just - $get_ic_property_text_vert_just - $set_ic_row_auto_resize - $get_ic_row_auto_resize - $set_ic_row_justification - $get_ic_row_justification - $set_ic_row_site - $get_ic_row_site - $set_ic_row_slideable - $get_ic_row_slideable - $set_instance_extent_display - $get_instance_extent_display - $set_instance_name_display - $get_instance_name_display - $set_instance_origin_display - $get_instance_origin_display - $set_instance_route_hierarchy_mode - $set_iobj_points - $set_iroute_accept_at_current_loc - $set_iroute_auto_shield - $set_iroute_checking - $set_iroute_push_mode - $set_iroute_route_transforms - $set_iroute_select_with_active_layer - $set_iroute_show_alignment - $set_iroute_show_ortho_path - $set_iroute_via_generator_is_default - $set_iroute_width_change - $set_join_on_move - $get_join_on_move - $set_layer_appearance - $set_layer_palette_height - $get_layer_palette_height - $set_layer_path_width - $set_lef_bus_bit_characters - $get_lef_bus_bit_characters - $set_lef_divider_character - $get_lef_divider_character - $set_lef_non_orthogonal - $get_lef_non_orthogonal - $set_lef_overlap_boundary - $get_lef_overlap_boundary - $set_library_cell_type - $set_library_site_types - $set_location_mode - $get_location_mode - $set_logic_source - $set_logical_correspondence - $set_lvs_all_capacitor_pins_swappable - $get_lvs_all_capacitor_pins_swappable - $set_lvs_component_subtype_property - $get_lvs_component_subtype_property - $set_lvs_component_type_properties - $get_lvs_component_type_properties - $set_lvs_default_direct_source_subname - $get_lvs_default_direct_source_subname - $set_lvs_default_mask_source_subname - $get_lvs_default_mask_source_subname - $set_lvs_default_report_name - $get_lvs_default_report_name - $set_lvs_filter_unused_bipolar_transistors - $get_lvs_filter_unused_bipolar_transistors - $set_lvs_filter_unused_mos_transistors - $get_lvs_filter_unused_mos_transistors - $set_lvs_ground_names - $get_lvs_ground_names - $set_lvs_ignore_ports - $get_lvs_ignore_ports - $set_lvs_pin_name_properties - $get_lvs_pin_name_properties - $set_lvs_power_names - $get_lvs_power_names - $set_lvs_recognize_gates - $get_lvs_recognize_gates - $set_lvs_recognize_only_simple_gates - $get_lvs_recognize_only_simple_gates - $set_lvs_reduce_parallel_bipolar_transistors - $get_lvs_reduce_parallel_bipolar_transistors - $set_lvs_reduce_parallel_capacitors - $get_lvs_reduce_parallel_capacitors - $set_lvs_reduce_parallel_diodes - $get_lvs_reduce_parallel_diodes - $set_lvs_reduce_parallel_mos_transistors - $get_lvs_reduce_parallel_mos_transistors - $set_lvs_reduce_parallel_resistors - $get_lvs_reduce_parallel_resistors - $set_lvs_reduce_series_capacitors - $get_lvs_reduce_series_capacitors - $set_lvs_reduce_series_resistors - $get_lvs_reduce_series_resistors - $set_lvs_reduce_split_gates - $get_lvs_reduce_split_gates - $set_lvs_report_list_limit - $get_lvs_report_list_limit - $set_lvs_write_instance_cross_reference - $get_lvs_write_instance_cross_reference - $set_lvs_write_net_cross_reference - $get_lvs_write_net_cross_reference - $set_mark - $set_mask_auto_view - $set_mask_default_database_name - $get_mask_default_database_name - $set_mask_thresholds - $get_mask_thresholds - $set_max_auto_display - $get_max_auto_display - $set_modify_distance - $get_modify_distance - $set_mos_cell_type - $get_mos_cell_type - $set_mos_share - $get_mos_share - $set_net_priority - $set_new_window_cull - $get_new_window_cull - $set_new_window_grid - $get_new_window_grid - $set_next_direct_net - $set_next_mask_device - $set_next_mask_discrepancy - $set_next_mask_net - $set_packed_vias - $set_padding_grid - $set_path_display_style - $get_path_display_style - $set_peek_on_view - $get_peek_on_view - $set_peek_protect - $set_pex_backannotation_distributed - $get_pex_backannotation_distributed - $set_pex_backannotation_lumped - $get_pex_backannotation_lumped - $set_pex_capacitance_scale - $get_pex_capacitance_scale - $set_pex_coupled_distributed - $get_pex_coupled_distributed - $set_pex_delay - $get_pex_delay - $set_pex_exclude_distributed - $get_pex_exclude_distributed - $set_pex_include_distributed - $get_pex_include_distributed - $set_pex_netlist_distributed - $get_pex_netlist_distributed - $set_pex_netlist_lumped - $get_pex_netlist_lumped - $set_pex_netlist_simple - $get_pex_netlist_simple - $set_pex_options_lumped - $get_pex_options_lumped - $set_pex_report_distributed - $get_pex_report_distributed - $set_pex_report_lumped - $get_pex_report_lumped - $set_pin_shape_editing - $set_placement_select_mode - $get_placement_select_mode - $set_point_select_mode - $get_point_select_mode - $set_point_select_reset_basepoint - $get_point_select_reset_basepoint - $set_port_pin_name_display - $get_port_pin_name_display - $set_preferred_overflow_layers - $get_preferred_overflow_layers - $set_previous_direct_net - $set_previous_mask_device - $set_previous_mask_discrepancy - $set_previous_mask_net - $set_print_appearance - $set_print_array_style - $get_print_array_style - $set_print_cull - $get_print_cull - $set_print_grid - $get_print_grid - $set_print_layers - $get_print_layers - $set_print_levels - $get_print_levels - $set_print_peeked_only - $get_print_peeked_only - $set_process_override - $set_push_count_limit - $set_query_on_merge - $get_query_on_merge - $set_query_on_placement - $get_query_on_placement - $set_redraw_controls - $get_redraw_controls - $set_redraw_level - $get_redraw_level - $set_redraw_precision - $get_redraw_precision - $set_redraw_queue_control - $get_redraw_queue_control - $set_report_target - $get_report_target - $set_restrict_visible - $get_restrict_visible - $set_resync_on_peek - $get_resync_on_peek - $set_route_center_wires - $get_route_center_wires - $set_route_hierarchy_mode - $set_route_net_order - $get_route_net_order - $set_route_objects - $get_route_objects - $set_route_one_pass - $get_route_one_pass - $set_route_overflow_order - $get_route_overflow_order - $set_route_pack_wires - $get_route_pack_wires - $set_route_protection - $set_route_same_net_checking - $get_route_same_net_checking - $set_route_stub_direction - $get_route_stub_direction - $set_route_trim_nets - $get_route_trim_nets - $set_route_via_rotation - $get_route_via_rotation - $set_router_channel_size_variation - $get_router_channel_size_variation - $set_router_cleanup - $get_router_cleanup - $set_router_compound_path - $get_router_compound_path - $set_router_conn_order - $get_router_conn_order - $set_router_do_net_rules_check - $get_router_do_net_rules_check - $set_router_feed_bias - $get_router_feed_bias - $set_router_h_grid_size - $get_router_h_grid_size - $set_router_improve_global_val - $get_router_improve_global_val - $set_router_initial_global_val - $get_router_initial_global_val - $set_router_max_bends - $get_router_max_bends - $set_router_max_iters - $get_router_max_iters - $set_router_max_vias - $get_router_max_vias - $set_router_minimized_layers - $get_router_minimized_layers - $set_router_mode_type - $get_router_mode_type - $set_router_num_extra_tracks - $get_router_num_extra_tracks - $set_router_oper_mode_type - $get_router_oper_mode_type - $set_router_primary_layer_used - $get_router_primary_layer_used - $set_router_probe_layers - $get_router_probe_layers - $set_router_restricted_layers - $get_router_restricted_layers - $set_router_step_size - $get_router_step_size - $set_router_use_gridded_mode - $get_router_use_gridded_mode - $set_router_v_grid_size - $get_router_v_grid_size - $set_router_view_probes - $get_router_view_probes - $set_router_wrong_direction - $get_router_wrong_direction - $set_ruler_angle_mode - $get_ruler_angle_mode - $set_ruler_select_state - $get_ruler_select_state - $set_ruler_text_height - $get_ruler_text_height - $set_sd_hv_contact - $set_sdl_filter - $get_sdl_filter - $set_sdl_preserve_orientation - $get_sdl_preserve_orientation - $set_sdl_quiet - $get_sdl_quiet - $set_search_path - $get_search_path - $set_select_via_pin - $get_select_via_pin - $set_selectable_area - $get_selectable_area - $set_selectable_layers - $set_selectable_types - $get_selectable_types - $set_site_type - $set_snap_basepoint_to_grid - $get_snap_basepoint_to_grid - $set_target_mode - $get_target_mode - $set_text_cull_basis - $get_text_cull_basis - $set_text_display - $get_text_display - $set_text_origin_display - $get_text_origin_display - $set_timer - $set_toolbar_alignment - $get_toolbar_alignment - $set_toolbar_keep_items_visible - $get_toolbar_keep_items_visible - $set_undo_level - $get_undo_level - $set_undo_object_limit - $get_undo_object_limit - $set_unselect_empty - $get_unselect_empty - $set_update_connected - $get_update_connected - $set_verilog_array_delimiters - $get_verilog_array_delimiters - $set_verilog_supply0 - $get_verilog_supply0 - $set_verilog_supply1 - $get_verilog_supply1 - $set_view_controls - $get_view_controls - $set_visible_layers - $set_working_directory - $get_working_directory - $set_xml_group_protection - $get_xml_group_protection - $set_xml_logfile - $get_xml_logfile - $set_xml_other_protection - $get_xml_other_protection - $set_xml_read_cell_path_style - $get_xml_read_cell_path_style - $set_xml_replace - $get_xml_replace - $set_xml_style - $get_xml_style - $set_xml_write_cell_path_style - $get_xml_write_cell_path_style - $setup_auto_checkpoint - $setup_ic - $setup_ic_dynamics - $setup_new_windows - $setup_print - $setup_redraw_controls - $setup_reports - $setup_rulers - $get_active_ruler_bgd_color - $get_active_ruler_color - $get_active_ruler_font - $setup_sdl - $setup_select_filter - $setup_session - $setup_status_line - $show_all_mask_devices - $show_all_mask_discrepancies - $show_all_mask_nets - $show_aspect - $show_contact_gaps - $show_context - $show_current_mask_device - $show_current_mask_discrepancy - $show_current_mask_net - $show_drc_all - $show_drc_area - $show_drc_check - $show_drc_current - $show_drc_scan - $show_group - $show_guidelines - $show_layer_palette - $show_mask_device_id - $show_mask_device_name - $show_mask_device_point - $show_mask_discrepancy - $show_mask_net_id - $show_mask_net_name - $show_mask_net_point - $show_panel - $show_status_line - $show_system_toolbar - $show_toolbar - $show_tooltips - $show_unplaced_instances - $slice - $slice_array - $slice_with_polygon - $slide_route - $snap_to_grid - $snap_to_row - $startup - $stretch - $stretch_relative - $swap_logically_equivalent_nets - $toolbar_context_glyph_item - $toolbar_glyph_item - $tooltips_visible - $trace_property_numeric - $trace_property_string - $trim_invalid_nets - $trim_nets - $trim_nets_options - $undefine_layer_alias - $undefine_layer_name - $undefine_layer_set - $undefine_must_connect - $undefine_net_pairs - $undelete_drc - $undo - $unfreeze_window - $ungroup - $unhighlight_all - $unhighlight_group - $unhighlight_hierarchical_net - $unlink_floorplan_shape - $unload_closed_cells - $unload_mask_results - $unload_viewpoint - $unmake_port - $unmark_all_ignored - $unmark_instances_as_ignored - $unpeek - $unpeek_area - $unplace - $unprotect_all - $unprotect_group - $unprotect_nets - $unreserve_cell - $unreserve_cell_by_name - $unreserve_library - $unreserve_process - $unselect_all - $unselect_all_edges - $unselect_area - $unselect_area_polygon - $unselect_by_name - $unselect_by_property - $unselect_drc - $unselect_edge - $unselect_group - $unselect_range - $unset_cell_process - $unset_logic_source - $unset_process_override - $unshow_all_mask_devices - $unshow_all_mask_discrepancies - $unshow_all_mask_nets - $unshow_all_mask_results - $unshow_current_mask_device - $unshow_current_mask_discrepancy - $unshow_current_mask_net - $unshow_drc - $unshow_guidelines - $untrace_all_properties - $update_cell - $update_cell_by_name - $update_gadget - $update_group_window - $update_hier_window - $update_layout_view - $update_layout_config_view - $update_library - $view_all - $view_all_mask_devices - $view_all_mask_discrepancies - $view_all_mask_nets - $view_area - $view_centered - $view_context - $view_current_mask_device - $view_current_mask_discrepancy - $view_current_mask_net - $view_drc - $view_highlighted - $view_next - $view_panel - $view_previous - $view_selected - $write_calibre - $write_def - $write_design_lef - $write_direct_cnet - $write_direct_netlist - $write_gdsii - $write_hierarchical_netlist - $write_lef - $write_mask_cnet - $write_mask_netlist - $write_source_cnet - $write_xml - $zoom_in - $zoom_out - $zoom_to_grid - - - $$add_arc - $add_border - $add_bus - $add_circle - $add_dot - $add_fb_def - $add_fb_inst - $add_fb_pins - $add_frame - $add_ic_viewpoint_type - $add_instance - $add_line - $add_net - $add_panel - $add_parameters - $add_pin - $add_polygon - $add_polyline - $add_property - $add_property_to_handle - $add_rectangle - $add_selected_instance - $add_settings_block - $add_sheet_border - $add_text - $add_wire - $align - $allow_resizable_instances - $apply_edits - $auto_sequence_text - $begin_edit_symbol - $change_color - $change_compiled_pin_name - $change_group_visibility - $change_instance_resize_factor - $change_line_style - $change_line_width - $change_net_style - $change_net_width - $change_polygon_fill - $change_property_color - $change_property_font - $change_property_height - $change_property_justification - $change_property_name - $change_property_offset - $change_property_orientation - $change_property_stability_switch - $change_property_type - $change_property_value - $change_property_visibility - $change_property_visibility_switch - $change_text_font - $change_text_height - $change_text_justification - $change_text_value - $change_variant_display - $$check - $check_and_save - $clear_unattached_annotations - $close_design_configuration - $close_selection - $close_window - $comp_name - $connect - $connect_area - $construct_frame - $convert_fb_inst_to_def - $convert_to_comment - $convert_to_new_technology - $copy - $copy_edit_hotkey_settings - $copy_multiple - $copy_to_array - $create_design_configuration - $create_design_sheet - $create_entity - $create_fb_inst_from_def - $create_implicit_pins - $create_pin_list - $create_sheet - $create_symbol - $create_variant_viewpoint - $da_ic_crossprobe - $da_ic_crossprobe_diff - $define_hotkey - $delete - $delete_ba_property - $delete_interfaces - $delete_multiple_ba_properties - $delete_panel - $delete_parameter - $delete_property - $delete_property_owner - $delete_sheet - $delete_template_name - $direct_to_active_window - $disconnect - $disconnect_area - $disconnect_ba - $display_next_sheet - $display_prev_sheet - $display_spec_sheet - $does_selection_exist - $$dump_sim_values - $end_edit_symbol - $$exit_sim_mode - $expand_template_name - $export_spice - $export_verilog - $export_vhdl - $filter_property_check - $flip - $freeze_window - $generate_symbol - $get_active_symbol - $get_active_symbol_history - $get_apply_edits_needed - $get_attached_objects - $get_attributes - $get_auto_update_inst_handles - $get_basepoint - $get_body_text_restriction - $get_bundle_members - $get_check_schematic_status - $get_check_status - $get_comment_graphics_attributes - $get_comment_handles - $get_comment_text_attributes - $get_comment_text_restriction - $get_comment_visibility - $get_default_interface_name - $get_design_sheets - $get_diagram_location - $get_edit_mode - $get_evaluations - $get_fb_line_style_by_handle - $get_frame_attributes - $get_frame_handles - $get_grid - $get_hotkey_settings - $get_in_design_context - $get_instance_attributes - $get_instance_handles - $get_instance_models - $get_instance_pathname - $get_instance_resize_factor - $get_item_type - $get_model_path - $get_net_attributes - $get_net_handles - $get_next_active_symbol - $get_object_property_attributes - $get_objects - $get_objects_in_area - $get_origin - $get_owned_property_names - $get_parameter - $get_pathname - $get_pin_attributes - $get_pin_handles - $get_pin_names - $get_prop_text_restriction - $get_property - $get_property_attributes - $get_property_handles - $get_property_names - $get_property_owners - $get_schematic_sheets - $get_search_path - $get_select_count - $get_select_count_type - $get_select_design_paths - $get_select_extent - $get_select_handles - $get_select_handles_type - $get_select_identical - $get_select_text_exists - $get_select_text_handle - $get_select_text_name - $get_select_text_origin - $get_select_text_value - $get_sheet_design_pathname - $get_sheet_extent - $get_sheetname_viewed - $$get_sim_value - $$get_sim_version - $get_simulation_mode - $get_source_edit_allowed - $get_symbol_name - $get_text_information - $get_type_present - $get_vertex_attributes - $get_vertex_handles - $get_view_area - $get_viewpoint - $get_window_names - $get_window_sheet_list - $group - $hide_active_symbol_window - $hide_annotations - $hide_comment - $hide_context_window - $hide_panel_border - $hide_status_line - $hide_system_toolbar - $hide_toolbar - $highlight_by_handle - $highlight_by_name - $highlight_property_owner - $$hotplot_submit - $import_verilog - $insert_template - $is_active_symbol_window_visible - $is_context_window_visible - $is_handle_valid - $is_selection_open - $is_status_line_visible - $is_system_toolbar_visible - $is_toolbar_visible - $load_hotkey_settings - $make_fb - $make_polygon - $make_polyline - $make_symbol - $mark_property_attributes - $mark_property_value - $measure_distance - $merge_annotations - $modify_frame - $move - $move_cursor_incrementally - $$move_settings_block - $name_instances - $name_instances_auto - $open_design_configuration - $open_design_sheet - $open_down - $open_schematic - $open_sheet - $open_source_code - $open_symbol - $open_top - $open_up - $pivot - $place_active_symbol - $pop_to_front - $print_all_schematics - $print_design_sheets - $protect - $protect_area - $push_to_back - $recalculate_properties - $reconnect_annotations - $redo - $remove_comment_status - $reopen_selection - $replace - $replace_with_alternate_symbol - $report_broken_annotations - $$report_check - $report_default_property_settings - $report_groups - $report_hotkey_settings - $report_interfaces - $report_interfaces_selected - $report_object - $$report_object_name - $report_panels - $report_parameter - $report_unattached_annotations - $reselect - $reset_instance_colors - $resize_fb - $revalidate_models - $rotate - $route - $save_setup - $save_sheet - $save_sheet_as - $save_symbol - $save_symbol_as - $save_variant_viewpoint - $scale - $scroll_down_by_unit - $scroll_down_by_window - $scroll_hz - $scroll_left_by_unit - $scroll_left_by_window - $scroll_right_by_unit - $scroll_right_by_window - $scroll_up_by_unit - $scroll_up_by_window - $scroll_vt - $select_all - $select_area - $select_branches - $select_by_design_path - $select_by_handle - $select_by_name - $select_by_property - $select_by_property_type - $select_fb - $select_group - $select_instances - $select_nets - $select_pins - $select_property_owner - $select_template_name - $select_text - $select_vertices - $sequence_text - $set_active_symbol - $set_active_symbol_history - $set_basepoint - $set_color - $set_color_config - $set_compiler_options - $set_default_parts_menu - $set_edit_mode - $set_evaluations - $set_grid - $set_hotkey_mode - $set_next_active_symbol - $set_origin - $set_out_of_view_warn - $set_parameter - $set_previous_active_symbol - $set_property_owner - $set_property_type - $set_search_path - $set_sel_name_display - $$set_sim_value - $set_simulation_mode - $set_template_directory - $set_toolbar_alignment - $set_userrule_error - $set_userrule_warning - $set_variant_properties - $set_viewpoint - $$settings_block_visible - $setup_annotated_property_text - $setup_check_schematic - $setup_check_schematic_sheet - $$setup_check_sheet - $setup_check_symbol - $setup_color - $setup_comment - $setup_default_viewpoint - $setup_display - $setup_function_block - $setup_grid - $setup_hspice_alter - $setup_net - $setup_object_template - $setup_page - $setup_property_display - $setup_property_text - $setup_report - $setup_ripper - $setup_selection - $setup_select_filter - $setup_sim_config - $setup_sim_model_editor - $setup_symbol_body - $setup_text_restriction - $setup_unselect_filter - $show_active_symbol_window - $show_annotations - $show_comment - $show_context_window - $show_panel_border - $show_registration - $show_status_line - $show_system_toolbar - $show_toolbar - $sim_add_dspf - $sim_add_sdf - $sim_choose_library - $sim_copy_configuration_as - $sim_delete_converter - $sim_edit_commands - $sim_edit_measurements - $sim_edit_sdf - $sim_export_spice - $sim_get_adms_ini_file - $sim_hide_dcop - $sim_insert_converter_default - $sim_insert_converter_inst - $sim_insert_converter_net - $sim_insert_converter_pin - $sim_invoke - $sim_invoke_mr - $sim_invoke_ms - $$sim_merge_annotations - $sim_open_language - $sim_open_lang_model - $sim_process_extracted_netlist - $sim_restore_setup_from - $sim_run - $sim_save_selected - $sim_save_setup_as - $sim_set_additional_commands - $sim_set_include_paths - $sim_set_initial_condition - $sim_set_temperature - $sim_setup_analysis - $sim_setup_analysis_ac - $sim_setup_analysis_dc - $sim_setup_analysis_dcop - $sim_setup_analysis_mc - $sim_setup_analysis_mod_steadystate - $sim_setup_analysis_noise - $sim_setup_analysis_noisetran - $sim_setup_analysis_steadystate - $sim_setup_analysis_steadystateac - $sim_setup_analysis_steadystatenoise - $sim_setup_analysis_steadystateoscil - $sim_setup_analysis_tran - $sim_setup_netlister - $sim_setup_sim_environ - $$sim_setup_simulator_viewer - $$sim_setup_simulator_viewer_advance - $sim_simulate - $sim_view_measurements - $sim_view_output_file - $sim_write_commands - $sim_write_setup_file - $slice - $snap_to_grid - $sort_handles - $sort_handles_by_property - $stretch - $string_to_literal - $symb_name - $undo - $unfreeze_window - $ungroup - $unhighlight_by_handle - $unhighlight_by_name - $unhighlight_property_owner - $unmake_fb - $unprotect - $unprotect_area - $unselect_all - $unselect_area - $unselect_by_design_path - $unselect_by_handle - $unselect_by_property - $unselect_by_property_type - $unselect_fb - $unselect_property_owner - $unselect_vertices - $update - $update_all - $update_all_schematics - $update_border - $update_from_interface - $$update_settings_blocks - $update_title_block - $view_all - $view_area - $view_centered - $view_panel - $view_selected - $vpt_needs_save - $was_saved - $zoom_in - $zoom_out - $get_auto_name_net - $get_auto_place_instance_name - $get_check_busshorts - $get_check_functionblocks - $get_check_schematicbusshorts - $get_check_schematicnetio - $get_fb_def_color - $get_fb_def_line_style - $get_fb_inst_color - $get_fb_inst_line_style - $get_fb_int_change_popup - $get_fb_passthru - $get_fb_popupwin - $set_annotation_color - $set_annotation_visibility - $set_auto_name_net - $set_auto_place_instance_name - $set_auto_update_mode - $set_autoripper - $set_autoroute - $set_autoselect - $set_bus_width - $set_check_annotations - $set_check_busshorts - $set_check_closedots - $set_check_dangle - $set_check_expression - $set_check_filemode - $set_check_filename - $set_check_frame - $set_check_functionblocks - $set_check_initprops - $set_check_instance - $set_check_net - $set_check_notdots - $set_check_overlap - $set_check_owner - $set_check_parameter - $set_check_pins - $set_check_schematicbusshorts - $set_check_schematicinstance - $set_check_schematicinterface - $set_check_schematicnet - $set_check_schematicnetio - $set_check_schematicspecial - $set_check_schematicuserrule - $set_check_special - $set_check_symbolbody - $set_check_symbolinterface - $set_check_symbolpin - $set_check_symbolspecial - $set_check_symboluserrule - $set_check_transcript - $set_check_userrule - $set_check_window - $set_close_dot - $set_closeness_criteria - $set_dot_size - $set_dot_style - $set_dynamic_cursor - $set_dynamic_rounding_precision - $set_environment_dofile_pathname - $set_fb_def_color - $set_fb_def_line_style - $set_fb_inst_color - $set_fb_inst_line_style - $set_fb_int_change_popup - $set_fb_passthru - $set_fb_popupwin - $set_hidden_symbol_prop_display - $set_implicit_ripper - $set_line_style - $set_line_width - $set_modify_multiple_prop_filter - $set_net_style - $set_net_width - $set_new_annotation_visibility - $set_orthogonal - $set_orthogonal_angle - $set_pin_spacing - $set_polygon_fill - $set_property_font - $set_property_height - $set_property_hjustification - $set_property_orientation - $set_property_stability_switch - $set_property_transparency - $set_property_visibility - $set_property_visibility_switch - $set_property_vjustification - $set_report_filemode - $set_report_filename - $set_report_transcript - $set_report_window - $set_ripper_dot - $set_ripper_mode - $set_ripper_query - $set_ripper_symbol_pathname - $set_schem_check_mode - $set_schematicuserrules_file - $set_segment_select_mode - $set_select_aperture - $set_select_comment - $set_select_exterior - $set_select_frame - $set_select_instance - $set_select_net - $set_select_pin - $set_select_property - $set_select_segment - $set_select_symbolbody - $set_select_symbolpin - $set_select_text - $set_select_vertex - $set_selection_color - $set_selection_model - $set_snap - $set_symboluserrules_file - $set_text_font - $set_text_height - $set_text_hjustification - $set_text_orientation - $set_text_transparency - $set_text_vjustification - $set_undo_level - $set_unselect_comment - $set_unselect_exterior - $set_unselect_frame - $set_unselect_instance - $set_unselect_net - $set_unselect_pin - $set_unselect_property - $set_unselect_segment - $set_unselect_symbolbody - $set_unselect_symbolpin - $set_unselect_text - $set_unselect_vertex - $set_userrules_file - $set_user_units - - - $add_menu_item - $ask_color - $ask_frame_name - $ask_integer - $ask_number - $ask_pathname - $ask_pattern - $ask_save_edits - $ask_scope_builtin_name - $ask_scope_callable_name - $ask_scope_form_name - $ask_scope_frame_name - $ask_scope_function_name - $ask_scope_keydef_name - $ask_scope_menu_name - $ask_scope_stroke_name - $ask_string - $ask_yes_no - $ask_yes_no_cancel - $bell - $bottom_y - $c_ask_string - $change_location_map_entry - $change_workspace - $cleanup_icons - $cleanup_windows - $clear_message - $clear_saved_prompt - $close_application_windows - $close_physical_transcript - $close_session - $close_window - $collapse_dockable - $compile_userware - $create_form - $create_menu - $create_notepad - $create_prompt - $create_toolbar - $define_color - $define_userware - $delete_menu_item - $delete_stroke - $disable_interrupt - $disable_softkey_update - $dock_dockable - $dockable_collapsed - $dockable_docked - $dockable_permission - $dockable_pinned - $dockable_visible - $dockables_all_hidden - $dockables_all_shown - $dockables_locked - $double_click_distance - $edit_source - $enable_help - $enable_interrupt - $enable_ref_help - $enable_softkey_update - $eval - $execute - $execute_dynamic - $execute_last_menu - $execute_promptbar - $execute_ref - $execute_stroke - $expand_command - $float_dockable - $forget - $forget_all_promptbars - $forget_promptbar - $form_action - $form_action_buttons_gadget - $form_actual_value - $form_argument - $form_argument_gadget - $form_argument_integer_entry_gadget - $form_argument_number_entry_gadget - $form_argument_string_entry_gadget - $form_argument_value - $form_button - $form_check_boxes_gadget - $form_choice_buttons_gadget - $form_choice_stepper_gadget - $form_click_button_gadget - $form_color_paint_chip_gadget - $form_colors_list_box_gadget - $form_column - $form_display_only - $form_display_text_gadget - $form_dynamic_list_box_gadget - $form_entry_box_gadget - $form_execute_buttons - $form_gadget_value - $form_horiz_dynamic_list_box_gadget - $form_horiz_list_box_gadget - $form_item - $form_label - $form_left_justified_column - $form_list_box_gadget - $form_mouse_tracking - $form_named_argument - $form_named_argument_gadget - $form_navigator_entry - $form_navigator_gadget - $form_number_entry_box_gadget - $form_patterns_list_box_gadget - $form_prompt_text_gadget - $form_push_button_gadget - $form_radio_buttons_gadget - $form_repeat - $form_right_justified_column - $form_row - $form_scope_list_box_gadget - $form_set_no_enter - $form_single_check_box_gadget - $form_string_entry_box_gadget - $form_switch - $form_target_action - $form_target_button - $form_text_entry_box_gadget - $form_variable - $form_variable_gadget - $frame_maximized - $frame_window - $get_action_bar_bgd_color - $get_action_bar_fgd_color - $get_active_color - $get_active_window - $get_additional_workspaces - $get_app_name_and_version - $get_app_name_no_version - $get_auto_pop - $get_auto_refresh - $get_auto_resize_palette - $get_autosave - $get_base_window - $get_bgd_color - $get_border_width - $get_current_profile - $get_cursor_colors - $get_cursor_shape - $get_default_method - $get_default_notepad_font - $get_double_click_interval - $get_expanded_pathname - $get_fgd_color - $get_focus_follows_mouse - $get_focus_follows_mouse_delay - $get_font_nominal_width - $get_form_gadget_value - $get_frame_collapsed - $get_graphic_device - $get_keyboard_type - $get_last_window - $get_message_lines - $get_message_popup - $get_message_reply - $get_message_transcript - $get_notepad_document_status - $get_open_windows - $get_palette_menu_visible - $get_pattern - $get_prompt_fonts - $get_server_switch - $get_sidetab_color - $get_tabbed_workspace_trim_right - $get_text_cursor_blink - $get_transcript_output - $get_window_border_width - $get_window_frame_extent - $get_window_frame_width - $get_workspace - $graphic_x - $graphic_y - $grow_window - $help - $help_context - $help_enabled - $hide_all_dockables - $hide_command_shell - $hide_dockable - $hide_menu_bar - $hide_message_area - $hide_palette - $hide_palette_scrolls - $hide_scrolls - $hide_softkey_labels - $hide_softkeys - $hide_transcript - $hide_window_title - $identify_interrupt - $insert_menu_item - $key_ - $left_x - $load_profile - $load_userware - $location - $lock_dockables - $mark - $maximize_window - $menu_bar_item - $menu_bar_visible - $menu_context_item - $menu_name - $menu_parent_name - $menu_registered_item - $menu_separator_item - $menu_special_text_item - $menu_text_item - $menu_title_item - $message - $message_area_visible - $minimize_window - $move_cursor - $move_dockable - $move_dockable_into - $move_palette - $move_window - $next_field - $next_field_promptbar - $next_icon - $next_window - $open_notepad - $open_physical_transcript - $open_text_report - $option_form_promptbar - $palette_visible - $pause - $pin_dockable - $pop_window - $pop_window_to_top - $popup_command_line - $popup_last_menu - $popup_menu - $popup_menu_at_cursor - $popup_menu_bar - $popup_window_menu - $prev_field - $prev_field_promptbar - $prompt - $prompt_arg - $prompt_display - $prompt_dynamic - $prompt_for_location - $prompt_for_polylocation - $prompt_for_polyrectangle - $prompt_for_rectangle - $prompt_options - $read_cpu_timer - $read_cpu_timer_total - $read_map - $read_timer - $read_timer_total - $redirect_to_active_window - $ref_help - $ref_help_enabled - $refresh - $relative_location - $remove_profile - $replace_palette - $replay_physical_transcript - $report_color - $report_key - $report_stroke - $reposition_window - $reset - $reset_defaults - $reset_timer - $resize_palette - $restore_default_profile - $result - $resume - $right_x - $save_profile - $save_profile_as - $screen_x - $screen_y - $scroll_down_by_unit - $scroll_down_by_window - $scroll_hz - $scroll_left_by_unit - $scroll_left_by_window - $scroll_right_by_unit - $scroll_right_by_window - $scroll_to_bottom - $scroll_to_left - $scroll_to_right - $scroll_to_top - $scroll_up_by_unit - $scroll_up_by_window - $scroll_vt - $scrolls_visible - $select - $select_active_window - $send_ipc - $session_window_active - $set_action_bar_bgd_color - $set_action_bar_fgd_color - $set_active_color - $set_active_window - $set_additional_workspaces - $set_auto_pop - $set_auto_refresh - $set_auto_resize_palette - $set_autosave - $set_base_window - $set_bgd_color - $set_border_width - $set_cmd_line_font - $set_cursor_colors - $set_cursor_shape - $set_default_method - $set_default_notepad_font - $set_default_position - $set_double_click_distance - $set_double_click_interval - $set_fgd_color - $set_focus_follows_mouse - $set_focus_follows_mouse_delay - $set_form_gadget_value - $set_form_position - $set_frame_width - $set_graphic_device - $set_invert_text_color_on_highlight - $set_ipc_port - $set_ipc_wakeup_interval - $set_left_justify_palette_text - $set_list_gadget_double_click_action - $set_menu_rollover_color - $set_message_font_resize - $set_message_lines - $set_message_popup - $set_message_reply - $set_message_transcript - $set_palette_width - $set_pattern - $set_prompt_fonts - $set_sidetab_color - $set_softkey_bgd_color - $set_softkey_fgd_color - $set_softkey_font - $set_tabbed_workspace_trim_right - $set_text_cursor_blink - $set_transcript_output - $set_window_border_width - $set_window_frame_width - $set_working_directory - setup_registered_commands - $show_all_dockables - $show_command_shell - $show_dockable - $show_location_map - $show_menu_bar - $show_message_area - $show_palette - $show_palette_scrolls - $show_parent_palette - $show_scrolls - $show_softkey_labels - $show_softkeys - $show_sub_palette - $show_toolbar_icons - $show_toolbar_text - $show_top_palette - $show_transcript - $show_window_title - $show_workspace_tab - $softkey_bgd_color - $softkey_fgd_color - $softkey_font - $softkeys_visible - $source - $start_stroke - $start_stroke_location - $start_timer - $stop - $stop_stroke - $stop_stroke_location - $stop_timer - $stroke_extent - $stroke_identity - $stroke_ - $target_name - $title_visible - $toolbar_action_selector_item - $toolbar_add_item - $toolbar_associative_item - $toolbar_combo_box_item - $toolbar_insert_item - $toolbar_label_item - $toolbar_n_state_item - $toolbar_registered_item - $toolbar_remove_item - $toolbar_separator_item - $toolbar_text_field_item - $toolbar_text_icon_item - $top_y - $transcript_visible - $ui_message_ask_yes_no - $ui_message_fail - $update_menu_bar - $update_palette - $update_softkey_labels - $update_toolbars - $use_animations - $user_init - $user_pre_init - $user_window_init - $using_animations - $version - $wait - $window_class_name - $window_extent - $window_init - $window_interior_extent - $window_scope_name - $window_visible - $writeln - - - $add_back_annotation - $add_multiple_properties - $add_parameter - $add_primitive - $add_property - $add_substitute - $add_visible_property - $change_model - $change_property - $check_design - $clear_global_parameter - $close_design_viewpoint - $connect_back_annotation - $delete_invalid_entries - $delete_parameter - $delete_primitive - $delete_property - $delete_substitute - $delete_visible_property - $disconnect_back_annotation - $erc_check - $export_back_annotation - $export_design_configuration - $filter_property_check - $get_viewpoint_name - $import_back_annotation - $is_ba_readonly - $is_function_defined - $latch_using_label - $latch_version - $maintain_back_annotation_window - $open_back_annotation - $open_design_configuration - $open_design_viewpoint - $preset_global_parameter - $reload_model - $report_select_counts - $report_viewpoint_references - $save_design_viewpoint - $select_back_annotation - $select_design_configuration - $select_parameter - $select_primitive - $select_substitute - $select_visible_property - $unlatch_version - $unselect_back_annotation - $unselect_design_configuration - $unselect_parameter - $unselect_primitive - $unselect_substitute - $unselect_visible_property - $update_latched_version - - - - $add_bundle - $add_bundle_members - $classify_all_genlib - $classify_symbol - $close_window - $delete_bundle - $delete_bundle_members - $delete_parameter - $generate - $get_bundle - $get_bundle_list - $get_bundle_members - $get_components - $get_instances - $get_nets - $get_parameter - $get_partition_setup - $get_property_list - $get_property_setup - $get_schematics - $get_sheets - $get_symbols - $get_symbol_classification - $get_symbol_setup - $open_component_from_model - $open_component_from_tfnf - $open_design_from_viewpoint - $report_bundle_members - $report_design_info - $report_property_setup - $report_setup - $report_status_bundles - $report_symbol_classifications - $save - $save_as - $set_parameter - $set_symbol_transcript - $setup_partition - $setup_placement - $setup_property - $setup_symbol_generation - $view_all - $view_sheet - $view_symbol - $zoom_in - $zoom_out - $set_balance - $set_bundle_mode - $set_bus_partition - $set_cluster - $set_cluster_spacing - $set_connector_spacing - $set_ground_placement - $set_instance_spacing - $set_iterate - $set_lrflow - $set_net_name_prefix - $set_net_spacing - $set_partition_by_name - $set_partition_by_property - $set_partition_density - $set_partition_mode - $set_partition_sheet_count - $set_partition_sheet_size - $set_placement_technique - $set_power_placement - - - - $add_bus - $add_comment_flag - $add_group - $add_synonym - $clear_name - $clear_selection_filter - $close_all_windows - $close_selection - $delete_bus - $delete_comment_flag - $delete_group - $delete_synonym - $end_object_selection - $end_object_unselection - $freeze_window - $get_all_instance_properties - $get_all_net_properties - $get_all_pin_properties - $get_all_types - $get_average_connected_pin - $get_average_primitive_instance - $get_average_selected - $get_best_case - $get_bottom_visible - $get_bundle_names - $get_bus_parts - $get_bus_width - $get_buses - $get_comment_flags - $get_component_path - $get_connected - $get_connected_instance - $get_connected_net - $get_connected_net_name - $get_connected_pin - $get_contained - $get_default_monitor_flag_font - $get_default_monitor_flag_height - $get_effective_context - $get_equivalent_nets - $get_full_pathname - $get_groups - $get_highlighted - $get_instance_property - $get_instance_viewed - $get_last_created_window - $get_maximum_connected_pin - $get_maximum_primitive_instance - $get_maximum_selected - $get_minimum_connected_pin - $get_minimum_primitive_instance - $get_minimum_selected - $get_monitor_flag_font - $get_monitor_flag_height - $get_naming_context - $get_nearest_instance - $get_nearest_net - $get_nearest_pin - $get_nearest_property_and_owner - $get_nearest_vertex - $get_net_property - $get_pin_property - $get_protected - $get_select_count - $get_selected - $get_selected_types - $get_selection_filter - $get_sheetname_viewed - $get_source_type - $get_sum_connected_pin - $get_sum_primitive_instance - $get_sum_selected - $get_synonyms - $get_top_visible - $get_total_width_of - $get_triplet_mode - $get_typical - $get_undo_depth - $get_view_window_names - $get_window_names - $get_window_titles - $get_window_type - $get_worst_case - $goto_highlight - $highlight_instance - $highlight_net - $highlight_pin - $instance_annotated_property - $instance_exists - $instance_has_annotations - $instance_source_property - $invalidate_window - $is_window_valid - $net_annotated_property - $net_exists - $net_has_annotations - $net_source_property - $open_down - $open_selected - $open_sheet - $open_up - $pin_annotated_property - $pin_exists - $pin_has_annotations - $pin_source_property - $primitive_instance - $primitive_net - $primitive_pin - $protect - $redirect_to_all_windows - $redo - $reopen_selection - $report_buses - $report_groups - $report_highlighted - $report_interfaces - $report_naming_context - $report_objects - $report_parts_list - $report_protected - $report_synonyms - $report_wire_list - $reselect - $select_by_name - $select_by_property - $select_connected - $select_contained - $select_group - $select_messages - $select_statement - $select_whole_window - $selection_closed - $selection_filter_active - $send_to_active_window - $set_auto_locate - $set_default_method - $set_default_monitor_flag_font - $set_default_monitor_flag_height - $set_effective_context - $set_monitor_flag_font - $set_monitor_flag_height - $set_naming_context - $set_selection_filter - $set_triplet_mode - $set_undo_depth - $setup_icon - $setup_icon_font - $setup_name - $setup_window_location - $undo - $unfreeze_window - $unhighlight_all - $unhighlight_instance - $unhighlight_net - $unhighlight_pin - $unprotect - $unselect_all - $unselect_by_name - $unselect_by_property - $unselect_except_by_property - $unselect_except_group - $unselect_group - $unselect_statement - $unselect_whole_window - $update_window - $write_report - - - __da_hdl_arch_name - __da_hdl_entity_name - __da_hdl_lib_name - __da_hdl_libraries - __da_hdl_packages - __da_hdl_port_init - __da_hdl_port_mode - __da_hdl_port_type - __da_hdl_signal_type - __da_suppress_units - Addr_width - Afall, Bfall, Qfall, Qbfall, Tfall, Tbfall - Area - Arise, Brise, Qrise, Qbrise, Trise, Tbrise - Asim_coupling - Asim_param - Asim_pinorder - Asim_model - Asim_model Property in Element Statements - Asim_model_keyword - Attribute_file_required - Basic_container - Block_dir - Brd_loc - Bres_value - Buildmode - Bundle_cover_thickness - Bundle_diameter - Bundle_height - Bundle_length - Bundle_min_bend_radius - Bundle_type - Bundle_width - Cap_coupled - Cap_drive - Cap_drive1 - Cap_drive2 - Cap_net - Cap_nets_coupled - Cap_pin - Class - Cntm_bdry_model - Comp - $Compaction-group - Component_type - $Con-edge - $Con-obj - Conn_order - Conn_type - Contention - Convect_h - Convect_rank - Corr_formula - Corr_formula_rad - Cover_thickness - Cpl_cap_net - Creating_tool - Current_drive - Current_load - Data_width - DCinit - Ddms_versioned_object - Decay - Dec_cap - Default_plot_typ - Default_tool - Diff_pair - Dme_config_ignore_type - Dme_config_include_container - Do_not_jog - dont_delete - dont_shrink - Drive - Dtime - Dual_footprint - Elec_class - Element - Emissivity - Except_assy - Fall - Fall_adj - Fall_slope - Fileset_def - First_addr - Fpin_no_sci - Frexp - From_location_map - From_path - From_version - Func - $G - $Gg - Gate_class - Gate_id - Gatemode - Gdsii_cell - Gdsii_datatype - Gdsii_error - Gdsii_no_output - Gdsii_plex - Gdsii_property_# - Gdsii_text - Requirements for DRACULA II - Gdsii_textinfo - Geom - Global - Globalin - Globalinout - Global_net_cap - Globalout - Group_abut - Group_name - Group_place - Group_prio - Group_seed - Icap_net - Ignore_net - Iih - Iil - Init - Initial_Condition - Ink_id - Input_data - Inst - Instpar - Instpartol - Ioh - Ioh1, Ioh2 - Iol - Iol1, Iol2 - Iozh - Iozl - Junction_max_t - Key_file - Kfall - Krise - Large_icon - Laser - Lms_cat - Lms_component_path - Lms_geometries - Lms_index - Lms_symbols - Load - M - Mass_density - Master_pin - Match_group - Matched_net_length - Mating_connector - Max_addr - Max_cap_pin - Max_stub - Max_wire_length - Mfg - Mgc_cat - Mgc_comps - Mgc_component_path - Mgc_geoms - Mgc_index - Mgc_lib - Mgc_map_path - Mgc_models - Mgc_prop_file_index - Mgc_prop_file_path - Mgc_refine_level - Mgc_symbols - Min_node - Min_stub - Min_wire_length - Model - Modelfile - Modeltype - Ms_* - Multi_assay - Must_jog - My_net - N - Net - Net_comp - Net_comp_count - Net_comp_place - Netdelay - Spike Model Data - Example - Net_length - Net_order - Net_prio - Net_prio_protected - Net_tp_min_clearance - Net_tp_req - Net_type - Nmos_bulk_node - Node - Nodeset - Nofault - Note - Npn_sub_node - Num_blocks - Omit_wire_list - Part_no - Pcb_group - Pcb_ignore - Pcb_inst - Pcb_net - Pcb_pin - Pcb_pin_loc - Pcb_pin_pad - Phy_comp - Phy_pin - Pin - Pin_driver - Pin_gauge - Pin_group - Pin_no - Pin_order - Pin_swap - Pin_tp_req - Pins - Pins_out - Pins_spare - Pintech - Pintype - Pintype_override - Place - Placement_net_cap - Placement_region - Pmos_bulk_node - Pnp_sub_node - $Pn_ext - Portdir - Porttype - Pow_del_max - Pow_del_typ - Pow_derating - Pow_den - Pow_max - Pow_max_symb - Pow_min - Pow_typ - Pow_typ_symb - Power_nets - Power_pins - Power_route_style - Pwr - Prio - Process_var - R - Radiate_h - Rc_feedthrough - Ref - Ref_group - Refloc - Rel_preplacement - Release_comments - Release_date - Release_date_string - Released_by - Released_location_map - Released_to_path - Res_net - Res_path - Res_source - Restrict - R_hat_len - R_hat_width - Rise - Rise_adj - Rise_slope - R_len - R_min_dim - Rn_sub_node - Route_set - Rp_sub_node - R_shape - R_width - Rule - S_des - Seed - Shape - Shared - Side_pref - Size - Small_icon - Source - Source_edit_allowed - Spec_heat - Spicepar - Ss_num - Stub_dir - Substrate - Surface - Surface_area - Swapping - Swap_set - Syn_donttouch - Syn_dontuse - Syn_libname - Target_net_cap - Tech - Tegas5_lib - Temp - Terminator - Therm_cond - Therm_jc - Therm_r - _tid - Timefile - Toler - Tool_reference - Tphz, Tplz, Tpzh, Tpzl - Trace_shielding - Transmode - Trim - Undriven - Value - Variant - Version_depth - Vhdl_type - Vih - Vil - Voh - Voh1, Voh2 - Vol - Vol1, Vol2 - Voltage - Vtype - Wire_auto_calc_length - Zif_model - Zycad_type - - - - $$add_configuration_entry - $add_configuration_entry - $$add_container - $add_container - $$add_directory - $add_directory - $add_link - $add_object_property - $$add_reference - $add_reference - $add_reference_property - $add_toolbox - $$add_type - $add_versions - $browse_for_object - $$build_configuration - $build_configuration - $$change_configuration_references - $change_configuration_references - $$change_design_object_references - $change_design_object_references - $change_link_text - $change_location_map_entry - $$change_object_name - $change_object_name - $change_object_property - $$change_object_references - $change_object_references - $change_password - $change_protection - $change_reference_property - $change_reference_state - $change_version_depth - $check_references - $check_registries - $$clear_entry_filter - $$clear_global_status - $$clear_monitor - $$close_configuration - $close_hierarchy - $$close_versioned_object - $close_window - $$convert_configuration_references - $convert_configuration_references - $$convert_object_references - $convert_object_references - $$copy_configuration - $copy_configuration - $$copy_design_object - $copy_design_object - $$copy_object - $copy_object - $copy_version - $$create_configuration - $create_dm_category - $create_dm_cell - $create_dm_ext_lib - $create_dm_library - $create_dm_project - $create_dm_tech_category - $create_dm_tech_lib - $create_tech_config_object - $$create_versioned_object - $$delete_configuration - $delete_configuration - $delete_design_object - $delete_excess_versions - $$delete_object - $delete_object - $$delete_object_property - $delete_object_property - $$delete_reference - $delete_reference - $$delete_reference_handle - $$delete_reference_property - $delete_reference_property - $$delete_reference_property_handle - $$delete_version - $delete_version - $$delete_version_property - $descend_hierarchy_one_level - $descend_hierarchy_specify_level - $$duplicate_object - $edit_file - $empty_trash - $explore_contents - $explore_parent - $explore_reference_parent - $explore_references - $export_configuration_entries - $export_library - $export_location_map - $find_external_deps - $find_references - $$fix_relative_path - $$freeze_configuration - $freeze_configuration - $$freeze_version - $freeze_version - $get_area_selected_objects - $$get_children - $$get_configuration_entries - $$get_configuration_path - $$get_container_contents - $$get_date_last_modified - $get_default_tool - $$get_entry_version - $$get_fileset_members - $$get_hard_name - $$get_location_map - $$get_monitor_error_count - $$get_monitor_flag - $$get_monitor_verbosity - $$get_monitor_warning_count - $get_navigator_directory - $get_navigator_directory_hard - $get_next_tool_env - $$get_object_current_version - $$get_object_parent_path - $$get_object_path_filter - $get_object_pathname - $$get_object_properties - $$get_object_property_filter - $$get_object_property_value - $$get_object_protection - $$get_object_references - $$get_object_type - $get_object_type - $$get_object_type_filter - $get_object_version - $$get_object_versions - $$get_parent_entry - $$get_primaries - $$get_reference_properties - $$get_reference_properties_handle - $$get_reference_property_filter - $$get_reference_traversal - $$get_secondaries - $$get_soft_name - $$get_status_code - $$get_status_code_stack - $$get_status_messages - $get_subinvoke_mode - $$get_target_path - $get_technology - $get_toolbox_search_path - $get_tool_pathname - $get_tool_script - $get_tool_type - $$get_type_properties - $$get_type_property_value - $$get_version_depth - $$get_version_properties - $$get_working_directory - $goto_directory - $$handle_map_error - $$has_object_property - $$has_reference_property - $$has_reference_property_handle - $hide_secondary_entries - $hide_monitor - $import_classic_data - $import_custom_view - $import_design_kit - $import_ext_lib - $import_icstudio_library - $import_icstudio_project - $include_external_library - $invoke_bgd_tool - $invoke_tool - $$is_build_consistent - $$is_build_valid - $$is_configuration_edited - $$is_configuration_frozen - $$is_configuration_locked - $$is_container - $$is_directory - $$is_entry_container - $$is_entry_fixed - $$is_entry_primary - $$is_entry_retargetable - $$is_object_released - $$is_object_versioned - $$is_read_protected - $$is_relative_path - $$is_type_versioned - $$is_writable - $$is_write_protected - $list_references - $load_registry - $$lock_configuration - $lock_configuration - $$lock_object - $login_admin - $logged_in - $logout_admin - $maintain_hierarchy - $$monitor_global_status - $$move_design_object - $move_design_object - $$move_object - $move_object - $$object_complete - $$object_exists - $$open_configuration - $open_configuration_window - $$open_hierarchy - $open_navigator - $open_object - $open_read_only_editor - $open_session_monitor - $$open_tool - $open_tool - $open_tools_window - $open_trash_window - $open_types_window - $$open_versioned_object - $$prune_design_hierarchy - $$read_map - $read_map - $refresh_all - $$release_configuration - $release_configuration - $$release_object - $release_object - $$remove_configuration_entry - $remove_configuration_entry - $remove_external_library - $remove_toolbox - $report_configuration_info - $$report_configuration_references - $report_configuration_references - $report_entry_info - $$report_entry_verification - $report_entry_verification - $$report_global_status - $report_object_info - $report_reference_info - $report_tool_info - $report_type_info - $report_version_info - $$resolve_path - $$revert_version - $revert_version - $$salvage_object - $salvage_object - $$save_configuration - $save_configuration - $$save_configuration_as - $save_configuration_as - $$save_object - $save_toolbox_search_path - $search - $search_again - $select_all - $select_by_name - $select_by_library - $select_by_type - $select_config_entry - $select_object - $select_reference - $select_tool - $select_toolbox - $select_trash_object - $select_version - $set_build_rules - $$set_location_map_entry - $$set_monitor_flag - $$set_monitor_verbosity - $set_next_tool_env - $$set_object_path_filter - $$set_object_property - $$set_object_property_filter - $$set_object_type_filter - $set_project_refresh_heartbeat - $$set_protection - $$set_protection_numeric - $$set_reference_property - $$set_reference_property_filter - $$set_reference_property_handle - $$set_reference_traversal - $set_subinvoke_mode - $$set_target_path - $set_target_path - $set_technology - $set_toolbox_search_path - $$set_version_depth - $$set_version_property - $$set_working_directory - $set_working_directory - $setup_filter_active - $setup_filter_all - $setup_default_editor - $setup_iconic_window_layout - $setup_invoke_tool - $$setup_monitor - $setup_monitor - $setup_session_defaults - $setup_startup_windows - $show_all_files - $show_compiled_libs - $show_component_hierarchy - $show_custom_views - $show_directories - $show_ext_libs - $show_language_views - $show_layout_views - $$show_location_map - $show_location_map - $show_logic_views - $show_references - $show_monitor - $show_tech_libs - $show_versions - $trash_object - $$unfreeze_configuration - $unfreeze_configuration - $$unfreeze_version - $unfreeze_version - $$unlock_configuration - $unlock_configuration - $$unlock_object - $unselect_all - $unselect_by_name - $unselect_by_type - $unselect_config_entry - $unselect_object - $unselect_reference - $unselect_tool - $unselect_toolbox - $unselect_trash_object - $unselect_version - $unset_next_tool_env - $untrash_object - $$update_type - $update_window - $validate_technology - $view_by_icon - $view_by_name - $view_containment_hierarchy - $view_primary_hierarchy - $view_secondary_entries - $view_toolboxes - $view_tools - $write_default_startup_file - $$writeln_monitor - - - $get_current_obj_hier_path - $get_current_obj_inst_list - $idw_dh_setup_display - $idw_report_hier - $idw_open_hierarchy_window - $inst_area_extend_selection - $inst_area_select_all_items - $inst_area_select_item - $inst_area_show_instances - $inst_area_unselect_all_items - $make_obj_current - $open_new_comp_hierarchy - $open_new_hierarchy - $select_obj - $show_instance - $show_n_levels - $set_font - $setup_comp_hierarchy_display - $setup_hierarchy_selection - $write_default_startup_file - $add_components - $add_labels_to_models - $collapse_object - $delete_labels_from_models - $delete_part_interfaces - $expand_object - $forget_components_edits - $hide_body_props - $hide_labels - $hide_model - $hide_pin_properties - $hide_pins - $register_models - $remove_components - $rename_part_interface - $report_body_prop_info - $report_component_info - $report_model_entry_info - $report_models_for_each_label - $report_model_info - $report_models_with_all_labels - $report_pin_info - $save_components_edits - $select_model_object - $select_object - $set_bgd_color - $set_bgd_color_title_items - $set_bgd_color_titles - $set_constraints - $set_default_part_interface - $set_fgd_color - $set_fgd_color_title_items - $set_fgd_color_titles - $set_font - $set_part_interface_font - $show_body_props - $show_labels - $show_model - $show_pins - $show_pin_properties - $unselect_model_object - $unselect_object - $validate_models - - - quick_help - ref_help - - - - optional - default - - - - - name - callable - enum - integer - location - name - number - pathname - polylocation - polyrectangle - real - rectangle - status - string - vector - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/ansic89.xml b/qutepart/syntax/ansic89.xml deleted file mode 100644 index bcd3170..0000000 --- a/qutepart/syntax/ansic89.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - break - case - continue - default - do - else - enum - extern - for - goto - if - return - sizeof - struct - switch - typedef - union - while - - - auto - char - const - double - float - int - long - register - short - signed - static - unsigned - void - volatile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/ansys.xml b/qutepart/syntax/ansys.xml deleted file mode 100644 index 465703b..0000000 --- a/qutepart/syntax/ansys.xml +++ /dev/null @@ -1,2064 +0,0 @@ - - - - - - /BATCH - /CONFIG - /CWD - /EOF - /EXIT - /FILNAME - HELP - /INPUT - KEYW - MEMM - /MENU - /MSTART - /NERR - /OUTPUT - /STATUS - /SYP - /SYS - /UI - /UIS - /AUX2 - /AUX3 - /AUX12 - /AUX15 - FINISH - /OPT - /POST1 - /POST26 - /PREP7 - /QUIT - /RUNST - /SOLU - /ASSIGN - /CLOG - /COPY - /DELETE - /FDELE - /FTYPE - LGWRITE - *LIST - /RENAME - /COM - /GO - /GOLIST - /GOPR - /NOLIST - /NOPR - - - /CLEAR - RESUME - SAVE - /SMBC - STAT - /STITLE - /TITLE - UNDO - /UNITS - ALLSEL - ASLL - ASEL - ASLV - DOFSEL - ESEL - ESLA - ESLL - ESLN - ESLV - KSEL - KSLL - KSLN - LSEL - LSLA - LSLK - NSEL - NSLA - NSLE - NSLK - NSLL - NSLV - PARTSEL - VSEL - VSLA - CM - CMDELE - CMEDIT - CMGRP - CMLIST - CMMOD - CMPLOT - CMSEL - KWPAVE - KWPLAN - LWPLAN - NWPAVE - NWPLAN - WPAVE - WPCSYS - WPLANE - WPOFFS - WPROTA - WPSTYL - CLOCAL - CS - CSCIR - CSDELE - CSKP - CSLIST - CSWPLA - CSYS - LOCAL - FITEM - FLST - - - /CMAP - /COLOR - /DEVICE - DSYS - /DV3D - /ERASE - ERASE - /GCMD - /GCOLUMN - /GFILE - GPLOT - /GRAPHICS - /GRESUME - /GSAVE - /GTYPE - HPGL - /IMAGE - IMMED - JPEG - /MREP - /NOERASE - /PCOPY - PNGR - PSCR - /PSTATUS - /REPLOT - /RESET - /SEG - /SHOW - TIFF - /WINDOW - /ANGLE - /AUTO - /DIST - /FOCUS - /USER - /VCONE - /VIEW - /VUP - /XFRM - /ZOOM - /DSCALE - /ICLWID - /ICSCALE - /RATIO - /SHRINK - /SSCALE - /TXTRE - /VSCALE - /CPLANE - /CTYPE - /EDGE - /ESHAPE - /FACET - /GLINE - /GMARKER - GMFACE - /LIGHT - /NORMAL - /SHADE - /TRLCY - /TYPE - /CFORMAT - /CLABEL - /CONTOUR - /CVAL - /GFORMAT - /HBC - /NUMBER - /PBC - /PBF - PGSELE - /PICE - /PLOPTS - /PNUM - /PSF - /PSYMB - /TRIAD - /UDOC - /AXLAB - /GRID - /GROPT - /GRTYP - /GTHK - /XRANGE - /YRANGE - /AN3D - /ANNOT - /ANUM - /LARC - /LINE - /LSPEC - /LSYMBOL - /PCIRCLE - /PMORE - /POLYGON - /PSPEC - /PWEDGE - /TLABEL - /TSPEC - - - GET - *ABBR - ABBRES - ABBSAV - *AFUN - *ASK - *CFCLOS - *CFOPEN - *CFWRITE - *CREATE - *CYCLE - *DEL - /DFLAB - *DIM - /DIRECTORY - *DO - *DOWHILE - *ELSE - *ELSEIF - *END - *ENDDO - *ENDIF - *EXIT - *GET - *GO - *IF - /INQUIRE - /MAIL - *MFOURI - *MFUN - *MOPER - *MSG - *MWRITE - PARRES - PARSAV - /PMACRO - /PSEARCH - *REPEAT - *RETURN - *SET - *SREAD - *STATUS - *TAXIS - /TEE - *TOPER - *TREAD - /UCMD - *ULIB - *USE - *VABS - *VCOL - *VCUM - *VEDIT - *VFACT - *VFILL - *VFUN - *VGET - *VITRP - *VLEN - *VMASK - *VOPER - *VPLOT - *VPUT - *VREAD - *VSCFUN - *VSTAT - *VWRITE - /WAIT - - - AFLIST - CDREAD - CDWRITE - CDOPT - CECHECK - CHECK - CNCHECK - FC - FCCHECK - FCDELE - FCLIST - IGESOUT - NOOFFSET - NUMCMP - NUMMRG - NUMOFF - NUMSTR - DOF - ET - ETCONTROL - ETDELE - ETLIST - KEYOPT - NSVR - R - RDELE - RLIST - RMODIF - RMORE - SETFGAP - EMUNIT - *EVAL - *MOONEY - MP - MPAMOD - MPCHG - MPCOPY - MPDATA - MPDELE - MPDRES - /MPLIB - MPLIST - MPPLOT - MPREAD - MPTEMP - MPTGEN - MPTRES - MPWRITE - TBFT - UIMP - TB - TBCOPY - TBDATA - TBDELE - TBFIELD - TBLIST - TBMODIF - TBPLOT - TBPT - TBTEMP - BLC4 - BLC5 - BLOCK - CON4 - CONE - CYL4 - CYL5 - CYLIND - PCIRC - POLY - PRI2 - PRISM - PTXY - RECTNG - RPOLY - RPR4 - RPRISM - SPH4 - SPH5 - SPHERE - TORUS - GSUM - K - KBETW - KCENTER - KDELE - KDIST - KFILL - KGEN - KL - KLIST - KMODIF - KMOVE - KNODE - KPLOT - KPSCALE - KSCALE - KSUM - KSYMM - KTRAN - SOURCE - HPTCREATE - HPTDELETE - BSPLIN - CIRCLE - GSUM - L - L2ANG - L2TAN - LANG - LARC - LAREA - LCOMB - LDELE - LDIV - LDRAG - LEXTND - LFILLT - LGEN - LLIST - LPLOT - LREVERSE - LROTAT - LSSCALE - LSTR - LSUM - LSYMM - LTAN - LTRAN - SPLINE - SSLN - A - AATT - ADELE - ADGL - ADRAG - AFILLT - AGEN - AL - ALIST - ANORM - AOFFST - APLOT - AREVERSE - AROTAT - ARSCALE - ARSYM - ASKIN - ASUB - ASUM - ATRAN - GSUM - SPLOT - EXTOPT - GSUM - V - VA - VDELE - VDGL - VDRAG - VEXT - VGEN - VLIST - VLSCALE - VOFFST - VPLOT - VROTAT - VSUM - VSYMM - VTRAN - AADD - AGLUE - AINA - AINP - AINV - AOVLAP - APTN - ASBA - ASBL - ASBV - ASBW - BOPTN - BTOL - LCSL - LGLUE - LINA - LINL - LINP - LINV - LOVLAP - LPTN - LSBA - LSBL - LSBV - LSBW - VADD - VGLUE - VINP - VINV - VOVLAP - VPTN - VSBA - VSBV - VSBW - ACCAT - ACLEAR - AESIZE - AMAP - AMESH - AREFINE - CHKMSH - CLRMSHLN - CPCYC - DESIZE - EORIENT - EREFINE - ESIZE - ESYS - FVMESH - GSGDATA - IMESH - KATTA - KCLEAR - KESIZE - KMESH - KREFINE - KSCON - LATT - LCCAT - LCLEAR - LESIZE - LMESH - LREFINE - MAT - MCHECK - MODMSH - MOPT - MSHAPE - MSHCOPY - MSHKEY - MSHMID - MSHPATTERN - NREFINE - PSMESH - REAL - RTHICK - SHPP - SMRTSIZE - TCHG - TIMP - TYPE - VATT - VCLEAR - VIMP - VMESH - VEORIENT - VSWEEP - CENTER - FILL - MOVE - N - NANG - NDELE - NDIST - NGEN - NKPT - NLIST - NMODIF - NPLOT - NREAD - NROTAT - NRRANG - NSCALE - NSMOOTH - NSYM - NWRITE - QUAD - SOURCE - TRANSFER - AFSURF - E - EDELE - EGEN - EINTF - ELIST - EMID - EMODIF - EMORE - EMTGEN - EN - ENDRELEASE - ENGEN - ENORM - ENSYM - EORIENT - EPLOT - EREAD - ERRANG - ESURF - ESYM - ESYS - EWRITE - LAYLIST - LAYPLOT - LFSURF - MAT - NDSURF - REAL - SHSD - SWADD - SWDEL - SWGEN - SWLIST - TSHAP - TYPE - UPGEOM - SE - SEDLIST - SELISTL - SESYMM - SETRAN - BELLOW - BEND - BRANCH - FLANGE - MITER - PCORRO - PDRAG - PFLUID - PGAP - PINSUL - POPT - PPRES - PSPEC - PSPRNG - PTEMP - PUNIT - REDUCE - RUN - TEE - VALVE - DIG - DMOVE - DSET - DSURF - CP - CPDELE - CPINTF - CPLGEN - CPLIST - CPNGEN - CPSGEN - CE - CECYC - CEDELE - CEINTF - CELIST - CERIG - CESGEN - RBE3 - NOORDER - WAVES - WERASE - WFRONT - WMID - WMORE - WSORT - WSTART - FLDATA - FLDATA1 - FLDATA2 - FLDATA3 - FLDATA4 - FLDATA4A - FLDATA5 - FLDATA6 - FLDATA7 - FLDATA8 - FLDATA9 - FLDATA10 - FLDATA11 - FLDATA12 - FLDATA13 - FLDATA14 - FLDATA15 - FLDATA16 - FLDATA17 - FLDATA18 - FLDATA19 - FLDATA20 - FLDATA20A - FLDATA20B - FLDATA21 - FLDATA22 - FLDATA23 - FLDATA24 - FLDATA24A - FLDATA24B - FLDATA24C - FLDATA24D - FLDATA24E - FLDATA24F - FLDATA24G - FLDATA24H - FLDATA40 - FLDATA25 - FLDATA26 - FLDATA34 - FLDATA27 - FLDATA28 - FLDATA29 - FLDATA30 - FLDATA31 - FLDATA32 - FLDATA33 - FLDATA35 - FLDATA36 - FLDATA37 - FLDATA38 - FLDATA39 - ICVFRC - PLVFRC - MSADV - MSCAP - MSDATA - MSMASS - MSMETH - MSMIR - MSNOMF - MSPROP - MSQUAD - MSRELAX - MSSOLU - MSSPEC - MSTERM - MSVARY - /CYCEXPAND - CYCLIC - CYCOPT - EMSYM - HFEREFINE - PERBC2D - PHYSICS - RACE - AREAS - BOOL - CEQN - COUPLE - DIGIT - ELEM - ETYPE - FATIGUE - FEBODY - FECONS - FEFOR - FESURF - FLOTRAN - GEOMETRY - KEYPTS - LINE - MATER - MESHING - NODES - PIPE - PMETH - PRIM - RCON - REORDER - SELM - TBLE - VOLUMES - EDASMP - EDBOUND - EDBX - EDCGEN - EDCLIST - EDCMORE - EDCNSTR - EDCONTACT - EDCRB - EDCURVE - EDDBL - EDDC - EDIPART - EDLCS - EDMP - EDNB - EDNDTSD - EDNROT - EDPART - EDPC - EDSP - EDWELD - ALPFILL - ARCOLLAPSE - ARDETACH - ARFILL - ARMERGE - ARSPLIT - GAPFINISH - GAPLIST - GAPMERGE - GAPOPT - GAPPLOT - LNCOLLAPSE - LNDETACH - LNFILL - LNMERGE - LNSPLIT - SARPLOT - SLPPLOT - SLSPLOT - VCVFILL - BSAX - BSM1 - BSM2 - BSMD - BSS1 - BSS2 - BSTE - BSTQ - PRSSOL - SDELETE - SECDATA - SECJOINT - /SECLIB - SECLOCK - SECNUM - SECOFFSET - SECPLOT - SECREAD - SECSTOP - SECTYPE - SECWRITE - SLIST - SSBT - SSMT - SSPA - SSPB - SSPD - SSPE - SSPM - MORPH - DAMORPH - DEMORPH - DVMORPH - TZAMESH - TZDELE - TZEGEN - PMLOPT - PMLSIZE - FSAN - FSCO - FSDT - FSIN - FSIT - FSOR - FSOU - FSRE - FSSTAT - FSTI - FSTR - - - ABEXTRACT - ADAMS - ADAPT - ANTYPE - BCSOPTION - CECHECK - CHECK - CMATRIX - CMSOPT - CNCHECK - CUTCONTROL - CYCOPT - DMPEXT - DSPROC - DSOPT - EMATWRITE - EQSLV - ERESX - ESCHECK - ESSOLV - EXPASS - FSRS - FSSOLV - GAUGE - GMATRIX - HFEIGOPT - HFPA - HFPCSWP - HFSCAT - HFSWEEP - LMATRIX - LUMPM - MONITOR - MSAVE - OPNCONTROL - PRECISION - PSCONTROL - PSOLVE - RATE - RSTOFF - SEEXP - SEGEN - SEOPT - SOLCONTROL - /SOLU - SOLVE - SPSCAN - SPSWP - STAOPT - TOFFST - PCONV - PEXCLUDE - PINCLUDE - /PMETH - PMOPTS - PPRANGE - ARCLENA - ARCTRM - BUCOPT - CNVTOL - CRPLIM - /GST - LNSRCH - MXPAND - NCNV - NEQIT - NLDIAG - NLDPOST - NLGEOM - NLHIST - NROPT - PRED - PSTRES - SSTIF - SUBOPT - ALPHAD - BETAD - DMPRAT - HARFRQ - HREXP - HROPT - HROUT - LVSCALE - MDAMP - MDPLOT - MODOPT - MXPAND - RIGID - SUBOPT - TIMINT - TINTP - TRNOPT - ADDAM - COVAL - CQC - DSUM - FREQ - GRP - NRLSUM - PFACT - PSDCOM - PSDFRQ - PSDGRAPH - PSDSPL - PSDUNIT - PSDVAL - PSDWAV - QDVAL - ROCK - SED - SPOPT - SRSS - SV - SVTYP - VDDAM - AUTOTS - CECMOD - DELTIM - EXPSOL - HMAGSOLV - KBC - KUSE - MAGOPT - MAGSOLV - MODE - NSUBST - NUMEXP - TIME - TREF - TSRES - UPCOORD - USRCAL - WRFULL - DA - DADELE - DALIST - DK - DKDELE - DKLIST - DL - DLDELE - DLLIST - DTRAN - FK - FKDELE - FKLIST - FTRAN - SFA - SFADELE - SFALIST - SFL - SFLDELE - SFLLIST - SFTRAN - BFA - BFADELE - BFALIST - BFK - BFKDELE - BFKLIST - BFL - BFLDELE - BFLLIST - BFTRAN - BFV - BFVDELE - BFVLIST - ACEL - CGLOC - CGOMGA - CMACEL - CMDOMEGA - CMOMEGA - DCGOMG - DOMEGA - IRLF - OMEGA - BIOT - FMAGBC - HFPORT - IC - ICDELE - ICE - ICEDELE - ICELIST - ICLIST - ISFILE - MPCHG - OUTPR - OUTRES - PGRAPH - PGSAVE - PGWRITE - PLWAVE - RESCONTROL - SBCLIST - SBCTRAN - WSPRINGS - LSCLEAR - LSDELE - LSREAD - LSSOLVE - LSWRITE - M - MDELE - MGEN - MLIST - TOTAL - GP - GPDELE - GPLIST - REZONE - MAPSOLVE - REMESH - AREMESH - EALIVE - EKILL - ESTIF - D - DCUM - DDELE - DJ - DJDELE - DJLIST - DLIST - DSCALE - DSYM - GSBDATA - GSLIST - LDREAD - F - FCUM - FDELE - FJ - FJDELE - FJLIST - FLIST - FSCALE - SF - SFBEAM - SFCUM - SFDELE - SFE - SFEDELE - SFELIST - SFFUN - SFGRAD - SFLIST - SFSCALE - BF - BFCUM - BFDELE - BFE - BFECUM - BFEDELE - BFELIST - BFESCAL - BFLIST - BFSCALE - BFUNIF - LDREAD - RIMPORT - TUNIF - BIOOPT - DEACT - DYNOPT - GAP - GENOPT - INRTIA - LSOPER - MASTER - NLOPT - OUTOPT - SMBODY - SMCONS - SMFOR - SMSURF - SOLUOPT - SPTOPT - EDADAPT - EDALE - EDBVIS - EDCADAPT - EDCPU - EDCSC - EDCTS - EDDAMP - EDDRELAX - EDDUMP - EDENERGY - EDFPLOT - EDGCALE - EDHGLS - EDHIST - EDHTIME - EDINT - EDIS - EDLOAD - EDOPT - EDOUT - EDPL - EDPVEL - EDRC - EDRD - EDRI - EDRST - EDRUN - EDSHELL - EDSOLV - EDSTART - EDTERM - EDTP - EDVEL - EDWRITE - REXPORT - FLOCHECK - PEMOPTS - HEMIOPT - RADOPT - RDEC - RSURF - RSYMM - SPCNOD - SPCTEMP - STEF - V2DOPT - VFCALC - VFOPT - QSOPT - FSAN - FSCO - FSDT - FSIN - FSIT - FSOR - FSOU - FSRE - FSRS - FSSTAT - FSTI - FSTR - MFANALYSIS - MFBUCKET - MFCALC - MFCLEAR - MFCMMAND - MFCONV - MFDTIME - MFELEM - MFEM - MFEXTER - MFFNAME - MFIMPORT - MFINTER - MFITER - MFLIST - MFMAP - MFORDER - MFOUTPUT - MFRELAX - MFRSTART - MFSURFACE - MFTIME - MFTOL - MFVOLUME - - - APPEND - DETAB - DNSOL - FILE - HRCPLX - PGRSET - /POST1 - RESET - SET - SUBSET - AVPRIN - AVRES - /EFACET - ERNORM - FORCE - INRES - LAYER - RSYS - SHELL - NSORT - NUSORT - PLCONV - PLDISP - PLESOL - PLNSOL - PLVECT - PPLOT - PRCONV - PRESOL - PRJSOL - PRNLD - PRNSOL - PRRFOR - PRRSOL - PRSSOL - PRVECT - SUMTYPE - DESOL - ESORT - ETABLE - EUSORT - PLETAB - PLLS - PLVECT - PRETAB - PRVECT - SABS - SADD - SALLOW - SEXP - SFACT - SFCALC - SMAX - SMIN - SMULT - SSUM - TALLOW - VCROSS - VDOT - /FORMAT - /HEADER - IRLIST - /PAGE - PRERR - PRITER - ANCNTR - ANCUT - ANDATA - ANDSCL - ANCYC - ANDYNA - /ANFILE - ANFLOW - ANHARM - ANIM - ANISOS - ANMODE - ANMRES - ANTIME - TRTIME - PADELE - PAGET - PAPUT - PARESU - PASAVE - PATH - PCALC - PCROSS - PDEF - PDOT - PLPAGM - PLPATH - PLSECT - PMAP - PPATH - PRANGE - PRPATH - PRSECT - PSEL - PVECT - SUCALC - SUCR - SUDEL - SUEVAL - SUGET - SUMAP - SUPL - SUPR - SURESU - SUSAVE - SUSEL - SUVECT - LCABS - LCASE - LCDEF - LCFACT - LCFILE - LCOPER - LCSEL - LCSUM - LCWRITE - LCZERO - RAPPND - CURR2D - EMAGERR - EMF - EMFT - FLUXV - FMAGSUM - FOR2D - IMPD - MMF - PLF2D - POWERH - QFACT - REFLCOEF - SENERGY - SPARM - TORQ2D - TORQC2D - TORQSUM - FE - FELIST - FL - FLLIST - FP - FPLIST - FS - FSDELE - FSLIST - FSNODE - FSPLOT - FSSECT - FTCALC - FTSIZE - FTWRITE - PLTRAC - TRPDEL - TRPLIS - TRPOIN - FLREAD - BFINT - CBDOF - CMSFILE - /CYCEXPAND - CYCPHASE - /EXPAND - EXPAND - FSSPARM - FSUM - HFANG - HFARRAY - HFNEAR - HFPOWER - HFSYM - INTSRF - KCALC - NFORCE - PLCRACK - PLHFFAR - PLSCH - PLSYZ - PRHFFAR - PRSYZ - RMFLVEC - RSPLIT - SPOINT - DATADEF - DEFINE - DISPLAY - LCCALC - POINT - PRINT - SORT - SPEC - FC - FCCHECK - FCDELE - FCLIST - - - ANSOL - DATA - EDREAD - ESOL - FILE - GAPF - GSSOL - JSOL - NSOL - NSTORE - NUMVAR - /POST26 - RESET - RFORCE - /RGB - SOLU - STORE - TIMERANGE - VARDEL - VARNAM - CFACT - FORCE - LAYERP26 - SHELL - TVAR - ABS - ADD - ATAN - CLOG - CONJUG - DERIV - EXP - FILLDATA - IMAGIN - INT1 - LARGE - NLOG - PROD - QUOT - REALVAR - SMALL - SQRT - PLCPLX - PLTIME - PLVAR - SPREAD - XVAR - EXTREM - LINES - NPRINT - PRCPLX - PRTIME - PRVAR - CVAR - PMGTRAN - RESP - RPSD - SMOOTH - VGET - VPUT - DEFINE - OPERATE - PLOTTING - PRINT - - - /AUX2 - DUMP - FILEAUX2 - FORM - HBMAT - - - /AUX3 - COMPRESS - DELETE - FILEAUX3 - LIST - MODIFY - UNDELETE - - - /AUX12 - EMIS - GEOM - MPRINT - SPACE - STEF - VFQUERY - VTYPE - WRITE - - - /AUX15 - IGESIN - IOPTN - - - RALL - RFILSZ - RITER - RMEMRY - RSPEED - RSTAT - RTIMST - /RUNST - RWFRNT - - - /OPT - OPEQN - OPFACT - OPFRST - OPGRAD - OPKEEP - OPLOOP - OPPRNT - OPRAND - OPSUBP - OPSWEEP - OPTYPE - OPUSER - OPVAR - TOCOMP - TODEF - TOFREQ - TOTYPE - TOVAR - OPADD - OPCLR - OPDEL - OPMAKE - OPSEL - OPANL - OPDATA - OPRESU - OPSAVE - OPEXE - TOEXE - TOLOOP - OPLFA - OPLGR - OPLIST - OPLSW - OPRFA - OPRGR - OPRSW - PLVAROPT - PRVAROPT - TOGRAPH - TOLIST - TOPLOT - TOPRINT - TOSTAT - XVAROPT - - - /PDS - PDANL - PDCORR - PDINQR - PDPLOT - PDVAR - PDDOEL - PDDMCS - PDMETH - PDUSER - PDEXE - PDCDF - PDCMAT - PDHIST - PDPINV - PDPROB - PDROPT - PDSCAT - PDSENS - PDSHIS - PDWRITE - PDCLR - PDRESU - PDSAVE - RSFIT - RSPLOT - RSPRNT - RSSIMS - - - /CMAP - /DEVDISP - FILEDISP - HELPDISP - NOCOLOR - /SEG - /SHOWDISP - TRANS - GRPH - TERM - FINISH - PLOT - STAT - - - RMRESUME - RMSAVE - RMNDISP - RMNEVEC - RMALIST - RMANL - RMASTER - RMCAP - RMCLIST - RMMLIST - RMMRANGE - RMMSELECT - RMPORDER - RMRGENERATE - RMROPTIONS - RMRPLOT - RMRSTATUS - RMSMPLE - RMXPORT - DCVSWP - RMLVSCALE - RMUSE - - - ABS - SIGN - EXP - LOG - LOG10 - SQRT - NINT - MOD - RAND - GDIS - SIN - COS - TAN - SINH - COSH - TANH - ASIN - ACOS - ATAN - ATAN2 - VALCHR - CHRVAL - UPCASE - LWCASE - - - LINK1 - PLANE2 - BEAM3 - BEAM4 - SOLID5 - COMBIN7 - LINK8 - INFIN9 - LINK10 - LINK11 - CONTAC12 - PLANE13 - COMBIN14 - PIPE16 - PIPE17 - PIPE18 - PIPE20 - MASS21 - BEAM23 - BEAM24 - PLANE25 - MATRIX27 - SHELL28 - FLUID29 - FLUID30 - LINK31 - LINK32 - LINK33 - LINK34 - PLANE35 - SOURC36 - COMBIN37 - FLUID38 - COMBIN39 - COMBIN40 - SHELL41 - PLANE42 - SHELL43 - BEAM44 - SOLID45 - SOLID46 - INFIN47 - MATRIX50 - SHELL51 - CONTAC52 - PLANE53 - BEAM54 - PLANE55 - HYPER56 - SHELL57 - HYPER58 - PIPE59 - PIPE60 - SHELL61 - SOLID62 - SHELL63 - SOLID64 - SOLID65 - PLANE67 - LINK68 - SOLID69 - SOLID70 - MASS71 - HYPER74 - PLANE75 - PLANE77 - PLANE78 - FLUID79 - FLUID80 - FLUID81 - PLANE82 - PLANE83 - HYPER84 - HYPER86 - SOLID87 - VISCO88 - VISCO89 - SOLID90 - SHELL91 - SOLID92 - SHELL93 - CIRCU94 - SOLID95 - SOLID96 - SOLID97 - SOLID98 - SHELL99 - VISCO106 - VISCO107 - VISCO108 - TRANS109 - INFIN110 - INFIN111 - INTER115 - FLUID116 - SOLID117 - HF118 - HF119 - HF120 - PLANE121 - SOLID122 - SOLID123 - CIRCU124 - CIRCU125 - TRANS126 - SOLID127 - SOLID128 - FLUID129 - FLUID130 - SHELL131 - SHELL132 - FLUID136 - FLUID138 - FLUID139 - FLUID141 - FLUID142 - SHELL143 - ROM144 - PLANE145 - PLANE146 - SOLID147 - SOLID148 - SHELL150 - SURF151 - SURF152 - SURF153 - SURF154 - SHELL157 - HYPER158 - LINK160 - BEAM161 - PLANE162 - SHELL163 - SOLID164 - COMBI165 - MASS166 - LINK167 - SOLID168 - TARGE169 - TARGE170 - CONTA171 - CONTA172 - CONTA173 - CONTA174 - CONTA175 - CONTA178 - PRETS179 - LINK180 - SHELL181 - PLANE182 - PLANE183 - MPC184 - SOLID185 - SOLID186 - SOLID187 - BEAM188 - BEAM189 - SOLSH190 - SOLID191 - INTER192 - INTER193 - INTER194 - INTER195 - MESH200 - FOLLW201 - SHELL208 - SHELL209 - PLANE223 - SOLID226 - SOLID227 - PLANE230 - SOLID231 - SOLID232 - SURF251 - SURF252 - - - EX - EY - EZ - GXY - NUXY - ALPX - ALPY - ALPZ - CTEX - CTEY - CTEZ - THSX - THSY - THSZ - REFT - PRXY - PRYZ - PRXZ - NUXY - NUYZ - NUXZ - GXY - GYZ - GXZ - DAMP - DMPR - MU - DENS - C - ENTH - KXX - KYY - KZZ - HF - EMIS - QRATE - VISC - SONC - RSVX - RSVY - RSVZ - PERX - MURX - MURY - MURZ - MGXX - MGYY - MGZZ - LSST - SBKX - - - UX - UY - UZ - FX - FY - FZ - MX - MY - MZ - HEAT - HBOT - HE2 - HE3 - HTOP - FLOW - AMPS - CHRG - CSGX - CSGY - CSGZ - ROTX - ROTY - ROTZ - WARP - TEMP - TBOT - TE2 - TE3 - TTOP - PRES - VX - VY - VZ - ENKE - ENDS - SP01 - SP02 - SP03 - SP04 - SP05 - SP06 - VOLT - MAG - AX - AYAZ - - - STATIC - BUCKLE - MODAL - HARMIC - TRANS - SUBSTR - SPECTR - - - - - - NX - NY - NZ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/apache.xml b/qutepart/syntax/apache.xml deleted file mode 100644 index db8b2cc..0000000 --- a/qutepart/syntax/apache.xml +++ /dev/null @@ -1,634 +0,0 @@ - - - - - - - - - -AcceptFilter -AccessFileName -Action -AddAlt -AddAltByEncoding -AddAltByType -AddCharset -AddDefaultCharset -AddDescription -AddEncoding -AddHandler -AddIcon -AddIconByEncoding -AddIconByType -AddInputFilter -AddLanguage -AddModuleInfo -AddOutputFilter -AddOutputFilterByType -AddType -Alias -AliasMatch -Allow -Anonymous -AuthBasicProvider -AuthDBMGroupFile -AuthDBMUserFile -AuthDigestDomain -AuthDigestFile -AuthDigestGroupFile -AuthDigestNonceFormat -AuthDigestProvider -AuthGroupFile -AuthLDAPBindDN -AuthLDAPBindPassword -AuthLDAPCharsetConfig -AuthLDAPGroupAttribute -AuthLDAPUrl -AuthName -AuthUserFile -BrowserMatch -BrowserMatchNoCase -BS2000Account -CacheDisable -CacheEnable -CacheFile -CacheGcClean -CacheGcUnused -CacheRoot -CGIMapExtension -CharsetDefault -CharsetOptions -CharsetSourceEnc -CookieDomain -CookieLog -CookieName -CoreDumpDirectory -CustomLog -Dav -DavGenericLockDB -DavLockDB -DBDParams -DBDPrepareSQL -DBDriver -DefaultIcon -DefaultLanguage -DefaultType -DeflateFilterNote -Deny -DirectoryIndex -DocumentRoot -ErrorDocument -ErrorLog -Example -ExpiresByType -ExpiresDefault -ExtFilterDefine -ExtFilterOptions -FilterChain -FilterDeclare -FilterProtocol -FilterProvider -FilterTrace -ForceType -ForensicLog -Group -Header -HeaderName -ImapBase -Include -IndexIgnore -IndexOptions -IndexStyleSheet -ISAPICacheFile -LanguagePriority -LDAPSharedCacheFile -LDAPTrustedCA -LDAPTrustedCAType -LDAPTrustedClientCert -LDAPTrustedGlobalCert -Listen -LoadFile -LoadModule -LockFile -LogFormat -MetaDir -MetaSuffix -MimeMagicFile -MMapFile -NameVirtualHost -NoProxy -NWSSLTrustedCerts -NWSSLUpgradeable -PassEnv -PidFile -ProxyBlock -ProxyDomain -ProxyPass -ProxyPassReverse -ProxyPassReverseCookieDomain -ProxyPassReverseCookiePath -ProxyRemote -ProxyRemoteMatch -ReadmeName -Redirect -RedirectMatch -RedirectPermanent -RedirectTemp -RemoveCharset -RemoveEncoding -RemoveHandler -RemoveInputFilter -RemoveLanguage -RemoveOutputFilter -RemoveType -RequestHeader -Require -RewriteBase -RewriteCond -RewriteLock -RewriteLog -RewriteMap -RewriteRule -ScoreBoardFile -Script -ScriptAlias -ScriptAliasMatch -ScriptLog -ScriptSock -SecureListen -ServerAdmin -ServerAlias -ServerName -ServerPath -ServerRoot -SetEnv -SetEnvIf -SetEnvIfNoCase -SetHandler -SetInputFilter -SetOutputFilter -SSIEndTag -SSIErrorMsg -SSIStartTag -SSITimeFormat -SSIUndefinedEcho -SSLCACertificateFile -SSLCACertificatePath -SSLCADNRequestFile -SSLCADNRequestPath -SSLCARevocationFile -SSLCARevocationPath -SSLCertificateChainFile -SSLCertificateFile -SSLCertificateKeyFile -SSLCipherSuite -SSLCryptoDevice -SSLHonorCiperOrder -SSLPassPhraseDialog -SSLProxyCACertificateFile -SSLProxyCACertificatePath -SSLProxyCARevocationFile -SSLProxyCARevocationPath -SSLProxyCipherSuite -SSLProxyMachineCertificateFile -SSLProxyMachineCertificatePath -SSLProxyProtocol -SSLRandomSeed -SSLRequire -SSLRequireSSL -SSLUserName -SuexecUserGroup -TransferLog -TypesConfig -UnsetEnv -User -UserDir -VirtualDocumentRoot -VirtualDocumentRootIP -VirtualScriptAlias -VirtualScriptAliasIP -Win32DisableAcceptEx - - - -AllowCONNECT -AssignUserID -AuthDigestNonceLifetime -AuthDigestShmemSize -CacheDefaultExpire -CacheDirLength -CacheDirLevels -CacheForceCompletion -CacheGcDaily -CacheGcInterval -CacheGcMemUsage -CacheLastModifiedFactor -CacheMaxExpire -CacheMaxFileSize -CacheMinFileSize -CacheSize -CacheTimeMargin -ChildPerUserID -CookieExpires -DavMinTimeout -DBDExptime -DBDKeep -DBDMax -DBDMin -DBDPersist -DeflateBufferSize -DeflateCompressionLevel -DeflateMemLevel -DeflateWindowSize -IdentityCheckTimeout -ISAPIReadAheadBuffer -KeepAliveTimeout -LDAPCacheEntries -LDAPCacheTTL -LDAPConnectionTimeout -LDAPOpCacheEntries -LDAPOpCacheTTL -LDAPSharedCacheSize -LimitInternalRecursion -LimitRequestBody -LimitRequestFields -LimitRequestFieldsize -LimitRequestLine -LimitXMLRequestBody -ListenBacklog -MaxClients -MaxKeepAliveRequests -MaxMemFree -MaxRequestsPerChild -MaxRequestsPerThread -MaxSpareServers -MaxSpareThreads -MaxThreads -MaxThreadsPerChild -MCacheMaxObjectCount -MCacheMaxObjectSize -MCacheMaxStreamingBuffer -MCacheMinObjectSize -MCacheSize -MinSpareServers -MinSpareThreads -NumServers -ProxyIOBufferSize -ProxyMaxForwards -ProxyReceiveBufferSize -ProxyTimeout -RewriteLogLevel -RLimitCPU -RLimitMEM -RLimitNPROC -ScriptLogBuffer -ScriptLogLength -SendBufferSize -ServerLimit -SSLProxyVerifyDepth -SSLSessionCacheTimeout -SSLVerifyDepth -StartServers -StartThreads -ThreadLimit -ThreadsPerChild -ThreadStackSize -TimeOut - - - -AcceptMutex -AcceptPathInfo -AllowEncodedSlashes -AllowOverride -Anonymous_Authoritative -Anonymous_LogEmail -Anonymous_MustGiveEmail -Anonymous_NoUserID -Anonymous_VerifyEmail -AuthAuthoritative -AuthBasicAuthoritative -AuthBasicProvider -AuthDBMAuthoritative -AuthDBMType -AuthDefaultAuthoritative -AuthDigestAlgorithm -AuthDigestNcCheck -AuthDigestQop -AuthLDAPAuthoritative -AuthLDAPCompareDNOnServer -AuthLDAPDereferenceAliases -AuthLDAPEnabled -AuthLDAPFrontPageHack -AuthLDAPGroupAttributeIsDN -AuthLDAPRemoteUserIsDN -AuthType -AuthzDBMAuthoritative -AuthzDBMType -AuthzDefaultAuthoritative -AuthzGroupFileAuthoritative -AuthzLDAPAuthoritative -AuthzOwnerAuthoritative -AuthzUserAuthoritative -BufferedLogs -CacheExpiryCheck -CacheIgnoreCacheControl -CacheIgnoreHeaders -CacheIgnoreNoLastMod -CacheNegotiatedDocs -CacheStoreNoStore -CacheStorePrivate -CheckSpelling -ContentDigest -CookieStyle -CookieTracking -CoreDumpDirectory -CustomLog -DavDepthInfinity -DirectorySlash -DumpIOInput -DumpIOOutput -EnableExceptionHook -EnableMMAP -EnableSendfile -ExpiresActive -ExtendedStatus -FileETag -ForceLanguagePriority -HostnameLookups -IdentityCheck -ImapDefault -ImapMenu -IndexOrderDefault -ISAPIAppendLogToErrors -ISAPIAppendLogToQuery -ISAPIFakeAsync -ISAPILogNotSupported -KeepAlive -LDAPTrustedMode -LDAPVerifyServerCert -LogLevel -MCacheRemovalAlgorithm -MetaFiles -ModMimeUsePathInfo -MultiviewsMatch -Options -Order -ProtocolEcho -ProxyBadHeader -ProxyErrorOverride -ProxyPreserveHost -ProxyRequests -ProxyVia -RewriteEngine -RewriteOptions -Satisfy -ScriptInterpreterSource -ServerSignature -ServerTokens -SSLEngine -SSLMutex -SSLOptions -SSLProtocol -SSLProxyEngine -SSLProxyVerify -SSLSessionCache -SSLVerifyClient -UseCanonicalName -XBitHack - - - -On -Off -Default -flock -fcntl -posixsem -pthread -sysvsem -All -None -AuthConfig -FileInfo -Indexes -Limit -Options - -ExecCGI -FollowSymLinks -Includes -IncludesNOEXEC -Indexes -MultiViews -SymLinksIfOwnerMatch -StdEnvVars -CompatEnvVars -ExportCertData -FakeBasicAuth -StrictRequire -OptRenegotiate - -SDBM -GDBM -NDBM -DB -MD5 -MD5-sess -auth -auth-int -never -searching -finding -always -Basic -Digest -Connection -Keep-Alive -Proxy-Authenticate -Proxy-Authorization -TE -Trailers -Transfer-Encoding -Upgrade -Netscape -Cookie -Cookie2 -RFC2109 -RFC2965 -INode -MTime -Size -Prefer -Fallback -Double -error -nocontent -map -referer -formatted -semiformatted -unformatted -Ascending -Descending -Name -Date -Size -Description -SSL -TLS -STARTTLS -emerg -alert -crit -error -warn -notice -info -debug -LRU -GDSF -Any -NegotiatedOnly -Filters -Handlers -Deny,Allow -Allow,Deny -Mutual-failure -IsError -Ignore -StartBody -Full -Block -inherit -Registry -Registry-Strict -Script -EMail -Major -Minor -Min -Minimal -Prod -ProductOnly -OS -Full -optional -posixsem -sysvsem -sem -pthread -fcntl: -flock: -file: -yes -no -SSLv2 -SSLv3 -TLSv1 -require -optional_no_ca -nonenotnull -dbm: -shm: -dc: -DNS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asm-avr.xml b/qutepart/syntax/asm-avr.xml deleted file mode 100644 index 49bafba..0000000 --- a/qutepart/syntax/asm-avr.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - adc - add - adiw - and - andi - asr - bclr - bld - brbc - brbs - brcc - brcs - break - breq - brge - brhc - brhs - brid - brie - brlo - brlt - brmi - brne - brpl - brsh - brtc - brts - brvc - brvs - bset - bst - call - cbi - cbr - clc - clh - cli - cln - clr - cls - clt - clv - clz - com - cp - cpc - cpi - cpse - dec - eicall - eijmp - elpm - eor - fmul - fmuls - fmulsu - icall - ijmp - in - inc - jmp - ld - ldd - ldi - lds - lpm - lsl - lsr - mov - movw - mul - muls - mulsu - neg - nop - or - ori - out - pop - push - rcall - ret - reti - rjmp - rol - ror - sbc - sbr - sbrc - sbrs - sec - seh - sbi - sbci - sbic - sbis - sbiw - sei - sen - ser - ses - set - sev - sez - sleep - spm - st - std - sts - sub - subi - swap - tst - wdr - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asm-dsp56k.xml b/qutepart/syntax/asm-dsp56k.xml deleted file mode 100644 index e1640d9..0000000 --- a/qutepart/syntax/asm-dsp56k.xml +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - - - x - x0 - x1 - y - y0 - y1 - a2 - a1 - a0 - a - a10 - ab - b2 - b1 - b0 - b - b10 - ba - - - - r0 - r1 - r2 - r3 - r4 - r5 - r6 - r7 - - - - n0 - n1 - n2 - n3 - n4 - n5 - n6 - n7 - - - - m0 - m1 - m2 - m3 - m4 - m5 - m6 - m7 - - - - la - lc - pc - ssh - ssl - omr - sr - sp - mr - ccr - - - - abs - adc - add - addl - addr - and - andi - asl - asr - bchg - bclr - bset - btst - clr - cmp - cmpm - div - do - enddo - eor - illegal - jcc - jhs - jcs - jls - jec - jeq - jes - jge - jgt - jlc - jle - jls - jlt - jmi - jne - jnr - jpl - jnn - jclr - jmp - jscc - jshs - jscs - jsls - jsec - jseq - jses - jsge - jsgt - jslc - jsle - jsls - jslt - jsmi - jsne - jsnr - jspl - jsnn - jsclr - jset - jsr - jsset - lsl - lsr - lua - mac - macr - move - movec - movem - movep - mpy - mpyr - neg - nop - norm - not - or - ori - rep - reset - rnd - rol - ror - rti - rts - sbc - stop - sub - subl - subr - swi - tcc - ths - tcs - tls - tec - teq - tes - tge - tgt - tlc - tle - tls - tlt - tmi - tne - tnr - tpl - snn - tfr - tst - wait - - - - endif - endc - else - ifne - if - ifeq - ifle - iflt - ifge - ifgt - include - incbin - printval - pass1val - pass2val - fail - endm - end - org - ds - dsm - list - nolist - macro - dc - equ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asm-m68k.xml b/qutepart/syntax/asm-m68k.xml deleted file mode 100644 index f7611c8..0000000 --- a/qutepart/syntax/asm-m68k.xml +++ /dev/null @@ -1,651 +0,0 @@ - - - - - - - - d0 - d1 - d2 - d3 - d4 - d5 - d6 - d7 - - - - a0 - a1 - a2 - a3 - a4 - a5 - a6 - a7 - sp - - - - ccr - sr - pc - zpc - ssp - usp - msp - isp - dfc - cacr - caar - vbr - crp - srp - urp - tc - tt0 - tt1 - mmusr - itt0 - itt1 - dtt0 - dtt1 - buscr - pcr - ic - - bc - - - - fp0 - fp1 - fp2 - fp3 - fp4 - fp5 - fp6 - fp7 - fpcr> - fpsr - fpiar - - - - abcd - adda - addi - add - addq - addx - andi - and - asl - asr - bcc - bchg - bclr - bcs - beq - bfchg - bfclr - bfexts - bfextu - bfffo - bfins - bfset - bftst - bge - bgt - bhi - bhs - bkpt - ble - blo - bls - blt - bmi - bne - bpl - bra - bset - bsr - btst - bvc - bvs - callm - cas2 - cas - chk2 - chk - cinva - cinvl - cinvp - clr - cmp2 - cmpa - cmpi - cmp - cmpm - cpusha - cpushl - cpushp - dbcc - dbcs - dbeq - dbf - dbge - dbgt - dbhi - dbhs - dble - dblo - dbls - dblt - dbmi - dbne - dbpl - dbra - dbt - dbvc - dbvc - divs - divsl - divu - divul - eori - eor - exg - extb - ext - illegal - jmp - jsr - lea - link - lpstop - lsl - lsr - move16 - movea - movec - move - movem - movep - moveq - moves - muls - mulu - nbcd - neg - negx - nop - not - ori - or - pack - pea - pflusha - pflushan - pflush - pflushn - ploadr - ploadw - plpa - pmovefd - pmove - ptestr - ptestw - reset - rol - ror - roxl - roxr - rtd - rte - rtm - rtr - rts - sbcd - scc - scs - seq - sf - sge - sgt - shi - shs - sle - slo - sls - slt - smi - sne - spl - st - stop - suba - subi - sub - subq - subx - svc - svc - swap - tas - trapcc - trapcs - trapeq - trapf - trapge - trapgt - traphi - traphs - trap - traple - traplo - trapls - traplt - trapmi - trapne - trappl - trapt - trapvc - trapvc - trapv - tst - unlk - unpk - - - - fabs - facos - fadd - fasin - fatanh - fatan - fbeq - fbf - fbge - fbgle - fbgl - fbgt - fble - fblt - fbne - fbnge - fbngle - fbngl - fbngt - fbnle - fbnlt - fboge - fbogl - fbogt - fbole - fbolt - fbor - fbseq - fbsf - fbsne - fbst - fbt - fbueq - fbuge - fbugt - fbule - fbult - fbun - fcmp - fcosh - fcos - fdabs - fdadd - fdbeq - fdbf - fdbge - fdbgle - fdbgl - fdbgt - fdble - fdblt - fdbne - fdbnge - fdbngle - fdbngl - fdbngt - fdbnle - fdbnlt - fdboge - fdbogl - fdbogt - fdbole - fdbolt - fdbor - fdbseq - fdbsf - fdbsne - fdbst - fdbt - fdbueq - fdbuge - fdbugt - fdbule - fdbult - fdbun - fddiv - fdiv - fdmove - fdmul - fdneg - fdsqrt - fdsub - fetox - fetoxm1 - fgetexp - fgetman - fint - fintrz - flog10 - flog2 - flogn - flognp1 - fmod - fmovecr - fmove - fmovem - fmul - fneg - fnop - frem - frestore - fsabs - fsadd - fsave - fscale - fsdiv - fseq - fsf - fsge - fsgldiv - fsgle - fsgl - fsglmul - fsgt - fsincos - fsinh - fsin - fsle - fslt - fsmove - fsmul - fsneg - fsne - fsnge - fsngle - fsngl - fsngt - fsnle - fsnlt - fsoge - fsogl - fsogt - fsole - fsolt - fsor - fsqrt - fsseq - fssf - fssne - fssqrt - fsst - fssub - fst - fsub - fsueq - fsuge - fsugt - fsule - fsult - fsun - ftanh - ftan - ftentox - ftrapeq - ftrapf - ftrapge - ftrapgle - ftrapgl - ftrapgt - ftraple - ftraplt - ftrapne - ftrapnge - ftrapngle - ftrapngl - ftrapngt - ftrapnle - ftrapnlt - ftrapoge - ftrapogl - ftrapogt - ftrapole - ftrapolt - ftrapor - ftrapseq - ftrapsf - ftrapsne - ftrapst - ftrapt - ftrapueq - ftrapuge - ftrapugt - ftrapule - ftrapult - ftrapun - ftst - ftwotox - - - - align - blk - bss - clrfo - clrso - cnop - code - cseg - data - dc - dcb - ds - dseg - else - end - endc - endif - endm - endr - equ - even - fo - idnt - if - ifeq - ifne - ifgt - ifge - iflt - ifle - ifd - ifnd - ifc - ifnc - incbin - incdir - include - macro - org - public - rept - rs - rsreset - rsset - section - set - setfo - setso - so - text - ttl - xdef - xref - sdreg - cpu32 - far - fpu - machine - mc68000 - mc68010 - mc68020 - mc68030 - mc68040 - mc68060 - mcf5200 - mcf5206 - mcf5307 - mcf5407 - near - opt - equr - equrl - fequr - fequrl - freg - reg - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asm6502.xml b/qutepart/syntax/asm6502.xml deleted file mode 100644 index 8d3e726..0000000 --- a/qutepart/syntax/asm6502.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asn1.xml b/qutepart/syntax/asn1.xml deleted file mode 100644 index e3cc6f4..0000000 --- a/qutepart/syntax/asn1.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - DEFINITIONS - BEGIN - END - EXPORTS - IMPORTS - FROM - APPLICATION - PRIVATE - UNIVERSAL - DEFAULT - OPTIONAL - FALSE - TRUE - - - BOOLEAN - INTEGER - OCTET STRING - NULL - REAL - ENUMERATED - SEQUENCE - SET - CHOICE - OF - VisibleString - StringStore - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/asterisk.xml b/qutepart/syntax/asterisk.xml deleted file mode 100644 index e76a1e3..0000000 --- a/qutepart/syntax/asterisk.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - AGI - Answer - Dial - Hangup - GoTo - GoToIf - GoToIfTime - NoOp - PlayBack - Read - SayDigits - SayNumber - Set - SetCallerPres - System - Wait - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/bibtex.xml b/qutepart/syntax/bibtex.xml deleted file mode 100644 index e167c27..0000000 --- a/qutepart/syntax/bibtex.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - ]> - - - - @article - @book - @booklet - @conference - @collection - @electronic - @inbook - @incollection - @inproceedings - @manual - @mastersthesis - @misc - @online - @patent - @periodical - @proceedings - @report - @phdthesis - @set - @thesis - @techreport - @unpublished - @www - @person - @company - @place - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/bmethod.xml b/qutepart/syntax/bmethod.xml deleted file mode 100644 index a852390..0000000 --- a/qutepart/syntax/bmethod.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - MACHINE - SETS - CONSTANTS - PROPERTIES - PROMOTES - INCLUDES - USES - SEES - VARIABLES - INVARIANT - INITIALISATION - REFINEMENT - REFINES - CONSTRAINTS - IMPLEMENTATION - IMPORTS - - - OPERATIONS - - - END - - - THEN - WHEN - ELSE - OR - WHERE - INVARIANT - DO - VARIANT - IN - ELSIF - - - PRE - IF - ANY - LET - CHOICE - CASE - SELECT - VAR - WHILE - BEGIN - - - END - - - NAT - NAT1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qutepart/syntax/boo.xml b/qutepart/syntax/boo.xml deleted file mode 100644 index 3043646..0000000 --- a/qutepart/syntax/boo.xml +++ /dev/null @@ -1,314 +0,0 @@ - - - - - - - - import - from - as - namespace - - - - and - assert - in - is - not - or - - - - bool - byte - sbyte - double - decimal - single - short - ushort - int - char - uint - long - ulong - object - duck - string - regex - date - timespan - - - - abstract - virtual - override - static - final - transient - macro - - protected - private - public - internal - partial - - class - struct - interface - enum - callable - of - - def - constructor - destructor - - do - get - set - event - - return - yield - - - - true - false - - - - null - self - super - - - - and - break - cast - continue - elif - else - except - ensure - for - given - goto - if - in - is - isa - not - or - otherwise - pass - raise - try - unless - when - while - ref - - - - assert - __eval__ - __switch__ - enumerate - filter - len - typeof - map - max - min - property - using - getter - required - lock - range - zip - checked - unchecked - rawArrayIndexing - normalArrayIndexing - print - array - matrix - yieldAll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/cParser.c b/qutepart/syntax/cParser.c similarity index 99% rename from qutepart/cParser.c rename to qutepart/syntax/cParser.c index 91bccd8..2ed983c 100644 --- a/qutepart/cParser.c +++ b/qutepart/syntax/cParser.c @@ -96,7 +96,7 @@ static PyTypeObject TYPE_NAME##Type = { \ PyObject_HEAD_INIT(NULL)\ 0,\ - "qutepart.cParser." #TYPE_NAME,\ + "qutepart.syntax.cParser." #TYPE_NAME,\ sizeof(TYPE_NAME),\ 0,\ (destructor)TYPE_NAME##_dealloc,\ diff --git a/qutepart/syntax/cgis.xml b/qutepart/syntax/cgis.xml deleted file mode 100644 index dda121f..0000000 --- a/qutepart/syntax/cgis.xml +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - 1D - 2D - break - continue - do - else - extern - for - forall - foreach - function - if - in - inout - internal - out - reduction - return - struct - typedef - while - - - bool - bool2 - bool3 - bool4 - int - int2 - int3 - int4 - half - half2 - half3 - half4 - float - float2 - float3 - float4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/changelog.xml b/qutepart/syntax/changelog.xml deleted file mode 100644 index aec3392..0000000 --- a/qutepart/syntax/changelog.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/checkdtd b/qutepart/syntax/checkdtd deleted file mode 100755 index 707e229..0000000 --- a/qutepart/syntax/checkdtd +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -xmllint --noout --dtdvalid language.dtd $@ diff --git a/qutepart/syntax/cisco.xml b/qutepart/syntax/cisco.xml deleted file mode 100644 index 47c7888..0000000 --- a/qutepart/syntax/cisco.xml +++ /dev/null @@ -1,312 +0,0 @@ - - - - - - aaa - access-list - address - alias - arp - async-bootp - banner - boot - bridge - buffers - busy-message - call-history-mib - cdp - chat-script - class-map - clock - cns - config-register - controller - crypto - default - default-value - dialer - dialer-list - dnsix-dmdp - dnsix-nat - downward-compatible-config - enable - end - exception - exit - file - frame-relay - help - hostname - interface - ip - isdn - isdn-mib - kerberos - key - line - logging - login-string - map-class - map-list - memory-size - menu - modemcap - multilink - netbios - no - ntp - partition - policy-map - priority-list - privilege - process-max-time - prompt - queue-list - resume-string - rlogin - rmon - route-map - router - rtr - scheduler - service - snmp-server - sntp - stackmaker - state-machine - subscriber-policy - tacacs-server - template - terminal-queue - tftp-server - time-range - username - virtual-profile - virtual-template - vpdn - vpdn-group - x25 - x29 - - - accounting - accounting-list - accounting-threshold - accounting-transits - address-pool - as-path - audit - auth-proxy - authentication - authorization - bgp-community - bootp - cef - classless - community-list - default-gateway - default-network - dhcp - dhcp-server - domain-list - domain-lookup - domain-name - dvmrp - exec-callback - extcommunity-list - finger - flow-aggregation - flow-cache - flow-export - forward-protocol - ftp - gratuitous-arps - host - host-routing - hp-host - http - icmp - inspect - local - mrm - mroute - msdp - multicast - multicast-routing - name-server - nat - new-model - ospf - password - password-encryption - pgm - pim - port-map - prefix-list - radius - rcmd - reflexive-list - route - routing - rsvp - rtcp - sap - sdr - security - source-route - subnet-zero - tacacs - tcp - tcp-small-servers - telnet - tftp - timestamps - udp-small-servers - vrf - wccp - - - accounting - accounting-list - accounting-threshold - accounting-transits - address-pool - as-path - audit - auth-proxy - authentication - authorization - bgp-community - bootp - cef - classless - community-list - default-gateway - default-network - dhcp - dhcp-server - domain-list - domain-lookup - domain-name - dvmrp - exec-callback - extcommunity-list - finger - flow-aggregation - flow-cache - flow-export - forward-protocol - ftp - gratuitous-arps - host - host-routing - hp-host - http - icmp - inspect - local - mrm - mroute - msdp - multicast - multicast-routing - name-server - nat - new-model - ospf - password - password-encryption - pgm - pim - port-map - prefix-list - radius - rcmd - reflexive-list - route - routing - rsvp - rtcp - sap - sdr - security - source-route - subnet-zero - tacacs - tcp - tcp-small-servers - telnet - tftp - timestamps - udp-small-servers - vrf - wccp - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/clipper.xml b/qutepart/syntax/clipper.xml deleted file mode 100644 index 11bba63..0000000 --- a/qutepart/syntax/clipper.xml +++ /dev/null @@ -1,501 +0,0 @@ - - - - - - - - .and. - announce - begin - case - command - define - do - elseif - else - endcase - enddo - endif - error - exit - field - .f. - for - function - ifdef - if - include - init - inndef - local - memvar - next - nil - .not. - .or. - other - parameters - private - procedure - public - request - return - sequence - static - stdout - .t. - traslate - undef - while - xcommand - xtranslate - - - - - accept - all - alternate - append - ascending - average - bell - blank - box - century - clear - close - coclor - color - commit - confirm - console - continue - copy - count - create - cursor - date - decimals - default - deleted - delete - delimiters - descending - device - display - do - eject - epoch - erase - escape - eval - every - exact - extended - file - filter - fixed - form - from - get - gets - go - goto - index - input - intensity - ? - ?? - @ - join - keyboard - key - label - list - locate - margin - memory - menu - message - new - on - order - pack - path - pict - printer - prompt - quit - range - read - recall - record - reindex - relation - release - rename - replace - report - rest - restore - run - save - say - scoreboard - seek - select - set - skip - softseek - sort - structure - sum - tag - to - total - typeahead - type - unique - unlock - update - use - valid - wait - when - with - wrap - zap - - - - - aadd - abs - achoice - aclone - acopy - adel - aeval - afill - ains - alert - alias - alltrim - altd - array - ascan - asize - asort - atail - at - bin2i - bin2l - bin2w - bof - break - browse - cdowchr - chr - cmonth - col - colorselect - ctod - curdir - date - day - dbappend - dbclearall - dbclearfilter - dbclearindex - dbclearrelation - dbcloseall - dbclosearea - dbcommitall - dbcommit - dbcreateindex - dbcreate - dbdelete - dbedit - dbeval - dbfilter - dbf - dbgobottom - dbgoto - dbgotop - dbrecall - dbreindex - dbrelation - dbrlock - dbrlocklist - dbrselect - dbrunlock - dbseek - dbselectarea - dbsetfilter - dbsetindex - dbsetorder - dbsetrelation - dbskip - dbstruct - dbunlockall - dbunlock - dbusearea - deleted - descend - devout - devpos - directory - dispbegin - dispbox - dispcount - dispend - dispout - dispspace - doserror - dow - dtoc - dtos - empty - eof - errorblock - errorinhandler - errorlevel - eval - exp - fclose - fcount - fcreate - ferase - ferror - fieldblock - fieldget - field - fieldname - fieldpos - fieldput - fieldwblock - file - flock - fopen - found - fread - freadstr - frename - fseek - fwrite - getactive - getenv - hardcr - header - i2bin - iif - indexext - indexkey - indexord - inkey - int - isalpha - iscolor - isdigit - islower - isprinter - isupper - l2bin - lastkey - lastrec - left - len - lock - log - lower - ltrim - lupdate - maxcol - max - maxrow - memoedit - memoline - memoread - memory - memotran - memowrit - memvarblock - min - mlcount - mlctopos - mlpos - mod - month - mpostolc - neterr - netname - nextkey - nosnow - ordbagext - ordbagname - ordcreate - orddestroy - ordfor - ordkey - ordlistadd - ordlistclear - ordlistrebuild - ordname - ordnumber - ordsetfocus - os - outerr - outstd - padc - padl - padr - pcol - pcount - proclineprocname - prow - qout - qqout - rat - rddlist - rddname - rddsetdefault - readexit - readinsert - readmodal - readvar - reccount - recno - recsize - replicate - restscreen - right - rlock - round - row - rtrim - savesreen - scroll - seconds - select - setblink - setcancel - setcolor - setcursor - setkey - setmode - setpos - setprc - soundex - space - sqrt - str - strtran - stuff - substr - time - tone - transform - trim - updated - upper - used - val - valtype - version - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/cmake-gen.sh b/qutepart/syntax/cmake-gen.sh deleted file mode 100755 index f9c2fa3..0000000 --- a/qutepart/syntax/cmake-gen.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/bin/env bash -# kate: tab-width 4; indent-mode normal; -# Copyright 2008, 2009 Matthew Woehlke (mw_triad@users.sourceforge.net) - -export LC_ALL=C - -# need cmake -CMAKE="$(type -P cmake)" -[ -x "$CMAKE" ] || exit 1 -echo "found cmake... $CMAKE" - -t=.tmp_cmake$$ - -# Get cmake version -CMAKE_VERSION="$("$CMAKE" --help | sed -n '1p')" - -count() { - wc -l $t.$1 | awk '{print $1}' -} - -# Extract before/after command list -sed -n -e '/ $t.1 -sed -e '/<\/list\s*>/ba' -e 'd' -e ':a' -e 'n;ba' cmake.xml > $t._2 -sed -n -e '/ $t.2 -sed "1,$(wc -l < $t.2)d" $t._2 | sed -e '/<\/list\s*>/ba' -e 'd' -e ':a' -e 'n;ba' > $t._3 -sed -n -e '/ $t.3 -sed "1,$(wc -l < $t.3)d" $t._3 | sed -e '/<\/list\s*>/ba' -e 'd' -e ':a' -e 'n;ba' > $t.4 - -cmake --help-command-list | sed '1d' | sort > $t.commands -echo "$(count commands) commands" - -extract_args() { - sed -e '/'"$1"'(/ba' \ - -e 'd' \ - -e ':a' \ - -e '/)/{s/^.*(\(.*\)).*$/\1/p;d}' \ - -e 'N;s/\n/ /;ba' | \ - sed -e 's/[][]//g' -e 's/|\| \+/\n/g' | \ - sed -n '/^[[:upper:][:digit:]_]\+$/p' >> $t.args -} - -while read COMMAND ; do - "$CMAKE" --help-command $COMMAND | extract_args $COMMAND -done < $t.commands -sort -u $t.args > $t.argsu -echo "$(count args) arguments, $(count argsu) unique" -cmake --help-property-list | sed -e '1d' -e '/[<>]/d' | sort -u > $t.props -echo "$(count props) properties" - -# Generate new .xml -{ - sed '//' $t.1 - echo " " - sed 's!.*! & !' $t.commands - cat $t.2 - echo " " - sed 's!.*! & !' $t.argsu - cat $t.3 - echo " " - sed 's!.*! & !' $t.props - cat $t.4 -} > cmake.xml - -rm -f $t.* -echo "Remember to update the version!" diff --git a/qutepart/syntax/cmake.xml b/qutepart/syntax/cmake.xml deleted file mode 100644 index 9201933..0000000 --- a/qutepart/syntax/cmake.xml +++ /dev/null @@ -1,581 +0,0 @@ - - - - - - - - - - add_custom_command - add_custom_target - add_definitions - add_dependencies - add_executable - add_library - add_subdirectory - add_test - aux_source_directory - break - build_command - build_name - cmake_minimum_required - cmake_policy - configure_file - create_test_sourcelist - define_property - else - elseif - enable_language - enable_testing - endforeach - endfunction - endif - endmacro - endwhile - exec_program - execute_process - export - export_library_dependencies - file - find_file - find_library - find_package - find_path - find_program - fltk_wrap_ui - foreach - function - get_cmake_property - get_directory_property - get_filename_component - get_property - get_source_file_property - get_target_property - get_test_property - if - include - include_directories - include_external_msproject - include_regular_expression - install - install_files - install_programs - install_targets - link_directories - link_libraries - list - load_cache - load_command - macro - make_directory - mark_as_advanced - math - message - option - output_required_files - project - qt_wrap_cpp - qt_wrap_ui - remove - remove_definitions - return - separate_arguments - set - set_directory_properties - set_property - set_source_files_properties - set_target_properties - set_tests_properties - site_name - source_group - string - subdir_depends - subdirs - target_link_libraries - try_compile - try_run - unset - use_mangled_mesa - utility_source - variable_requires - variable_watch - while - write_file - - - - itk_wrap_tcl - vtk_make_instantiator - vtk_wrap_java - vtk_wrap_python - vtk_wrap_tcl - - - - - A - ABSOLUTE - AFTER - ALL - ALPHABET - AND - APPEND - ARCHIVE - ARGS - ASCII - AUTHOR_WARNING - B - BEFORE - BRIEF_DOCS - BUNDLE - CACHE - CLEAR - CMAKE_FIND_ROOT_PATH_BOTH - CMAKE_FLAGS - CODE - COMMAND - COMMAND_NAME - COMMENT - COMPARE - COMPILE_DEFINITIONS - COMPILE_OUTPUT_VARIABLE - COMPILE_RESULT_VAR - COMPONENT - COMPONENTS - CONFIGS - CONFIGURATION - CONFIGURATIONS - CONFIGURE - COPYONLY - COPY_FILE - DEFINED - DEFINITION - DEPENDS - DESTINATION - DIRECTORY - DIRECTORY_PERMISSIONS - DOC - DOWNLOAD - ENV - EQUAL - ERROR_FILE - ERROR_QUIET - ERROR_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE - ESCAPE_QUOTES - EXACT - EXCLUDE - EXCLUDE_FROM_ALL - EXISTS - EXPORT - EXPR - EXT - EXTRA_INCLUDE - FATAL_ERROR - FILE - FILES - FILES_MATCHING - FILE_PERMISSIONS - FIND - FOLLOW_SYMLINKS - FORCE - FRAMEWORK - FULL_DOCS - FUNCTION - GET - GLOB - GLOB_RECURSE - GREATER - GROUP_EXECUTE - GROUP_READ - HEX - HINTS - IMPLICIT_DEPENDS - IMPORTED - IN - INCLUDE_INTERNALS - INHERITED - INPUT_FILE - INSERT - IS_ABSOLUTE - IS_DIRECTORY - IS_NEWER_THAN - IS_SYMLINK - ITEMS - LENGTH - LENGTH_MAXIMUM - LENGTH_MINIMUM - LESS - LIBRARY - LIMIT - LIMIT_COUNT - LIMIT_INPUT - LIMIT_OUTPUT - LINK_INTERFACE_LIBRARIES - LISTS - LOG - MACOSX_BUNDLE - MAIN_DEPENDENCY - MAKE_DIRECTORY - MATCH - MATCHALL - MATCHES - MODULE - NAME - NAMELINK_ONLY - NAMELINK_SKIP - NAMES - NAMESPACE - NAME_WE - NEW - NEWLINE_CONSUME - NOT - NOTEQUAL - NO_CMAKE_BUILDS_PATH - NO_CMAKE_ENVIRONMENT_PATH - NO_CMAKE_FIND_ROOT_PATH - NO_CMAKE_PACKAGE_REGISTRY - NO_CMAKE_PATH - NO_CMAKE_SYSTEM_PATH - NO_DEFAULT_PATH - NO_HEX_CONVERSION - NO_MODULE - NO_POLICY_SCOPE - NO_SOURCE_PERMISSIONS - NO_SYSTEM_ENVIRONMENT_PATH - OFFSET - OLD - ONLY_CMAKE_FIND_ROOT_PATH - OPTIONAL - OR - OUTPUT - OUTPUT_DIRECTORY - OUTPUT_FILE - OUTPUT_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE - OUTPUT_VARIABLE - OWNER_EXECUTE - OWNER_READ - OWNER_WRITE - PACKAGE - PARENT_SCOPE - PATH - PATHS - PATH_SUFFIXES - PATH_TO_MESA - PATTERN - PERMISSIONS - POLICY - POP - POST_BUILD - PREORDER - PRE_BUILD - PRE_LINK - PRIVATE_HEADER - PROGRAM - PROGRAMS - PROGRAM_ARGS - PROJECT_NAME - PROPERTIES - PROPERTY - PUBLIC_HEADER - PUSH - QUIET - RANDOM - RANDOM_SEED - RANGE - READ - READ_WITH_PREFIX - REALPATH - REGEX - REGULAR_EXPRESSION - RELATIVE - RELATIVE_PATH - REMOVE - REMOVE_AT - REMOVE_DUPLICATES - REMOVE_ITEM - REMOVE_RECURSE - RENAME - REPLACE - REQUIRED - REQUIRED_VARIABLE1 - REQUIRED_VARIABLE2 - RESOURCE - RESULT_VAR - RESULT_VARIABLE - RETURN_VALUE - REVERSE - RUNTIME - RUNTIME_DIRECTORY - RUN_OUTPUT_VARIABLE - RUN_RESULT_VAR - SCRIPT - SEND_ERROR - SET - SHARED - SORT - SOURCE - SOURCES - STATIC - STATUS - STREQUAL - STRGREATER - STRINGS - STRIP - STRLESS - SUBSTRING - SYSTEM - TARGET - TARGETS - TEST - TEST_VARIABLE - TIMEOUT - TOLOWER - TOUPPER - TO_CMAKE_PATH - TO_NATIVE_PATH - USE_SOURCE_PERMISSIONS - VALUE - VAR - VAR2 - VARIABLE - VERBATIM - VERSION - VERSION_EQUAL - VERSION_GREATER - VERSION_LESS - WARNING - WIN32 - WORKING_DIRECTORY - WRITE - - - - - GLOBAL - INTERNAL - - - - - ABSTRACT - ADDITIONAL_MAKE_CLEAN_FILES - ADVANCED - ALLOW_DUPLICATE_CUSTOM_TARGETS - ARCHIVE_OUTPUT_DIRECTORY - ARCHIVE_OUTPUT_NAME - ATTACHED_FILES - ATTACHED_FILES_ON_FAIL - BUILD_WITH_INSTALL_RPATH - CACHE_VARIABLES - CLEAN_NO_CUSTOM - COMPILE_DEFINITIONS - COMPILE_FLAGS - COST - DEBUG_CONFIGURATIONS - DEBUG_POSTFIX - DEFINE_SYMBOL - DEFINITIONS - DEPENDS - DISABLED_FEATURES - ENABLED_FEATURES - ENABLED_LANGUAGES - ENABLE_EXPORTS - ENVIRONMENT - EXCLUDE_FROM_ALL - EXTERNAL_OBJECT - EchoString - FAIL_REGULAR_EXPRESSION - FIND_LIBRARY_USE_LIB64_PATHS - FIND_LIBRARY_USE_OPENBSD_VERSIONING - FRAMEWORK - Fortran_MODULE_DIRECTORY - GENERATED - GENERATOR_FILE_NAME - GLOBAL_DEPENDS_DEBUG_MODE - GLOBAL_DEPENDS_NO_CYCLES - HAS_CXX - HEADER_FILE_ONLY - HELPSTRING - IMPLICIT_DEPENDS_INCLUDE_TRANSFORM - IMPORTED - IMPORTED_CONFIGURATIONS - IMPORTED_IMPLIB - IMPORTED_LINK_DEPENDENT_LIBRARIES - IMPORTED_LINK_INTERFACE_LANGUAGES - IMPORTED_LINK_INTERFACE_LIBRARIES - IMPORTED_LINK_INTERFACE_MULTIPLICITY - IMPORTED_LOCATION - IMPORTED_SONAME - IMPORT_PREFIX - IMPORT_SUFFIX - INCLUDE_DIRECTORIES - INCLUDE_REGULAR_EXPRESSION - INSTALL_NAME_DIR - INSTALL_RPATH - INSTALL_RPATH_USE_LINK_PATH - INTERPROCEDURAL_OPTIMIZATION - IN_TRY_COMPILE - KEEP_EXTENSION - LABELS - LANGUAGE - LIBRARY_OUTPUT_DIRECTORY - LIBRARY_OUTPUT_NAME - LINKER_LANGUAGE - LINK_DIRECTORIES - LINK_FLAGS - LINK_INTERFACE_LIBRARIES - LINK_INTERFACE_MULTIPLICITY - LINK_SEARCH_END_STATIC - LISTFILE_STACK - LOCATION - MACOSX_BUNDLE - MACOSX_BUNDLE_INFO_PLIST - MACOSX_FRAMEWORK_INFO_PLIST - MACOSX_PACKAGE_LOCATION - MACROS - MEASUREMENT - MODIFIED - OBJECT_DEPENDS - OBJECT_OUTPUTS - OSX_ARCHITECTURES - OUTPUT_NAME - PACKAGES_FOUND - PACKAGES_NOT_FOUND - PARENT_DIRECTORY - PASS_REGULAR_EXPRESSION - POST_INSTALL_SCRIPT - PREFIX - PRE_INSTALL_SCRIPT - PRIVATE_HEADER - PROCESSORS - PROJECT_LABEL - PUBLIC_HEADER - REPORT_UNDEFINED_PROPERTIES - REQUIRED_FILES - RESOURCE - RULE_LAUNCH_COMPILE - RULE_LAUNCH_CUSTOM - RULE_LAUNCH_LINK - RULE_MESSAGES - RUNTIME_OUTPUT_DIRECTORY - RUNTIME_OUTPUT_NAME - RUN_SERIAL - SKIP_BUILD_RPATH - SOURCES - SOVERSION - STATIC_LIBRARY_FLAGS - STRINGS - SUFFIX - SYMBOLIC - TARGET_ARCHIVES_MAY_BE_SHARED_LIBS - TARGET_SUPPORTS_SHARED_LIBS - TEST_INCLUDE_FILE - TIMEOUT - TYPE - VALUE - VARIABLES - VERSION - VS_KEYWORD - VS_SCC_LOCALPATH - VS_SCC_PROJECTNAME - VS_SCC_PROVIDER - WILL_FAIL - WIN32_EXECUTABLE - WRAP_EXCLUDE - __CMAKE_DELETE_CACHE_CHANGE_VARS_ - - - - - COMMANDS - DEFINITION - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/coldfusion.xml b/qutepart/syntax/coldfusion.xml deleted file mode 100644 index 9e49e4a..0000000 --- a/qutepart/syntax/coldfusion.xml +++ /dev/null @@ -1,732 +0,0 @@ - - - - - - - - - if - else - for - in - while - do - continue - break - with - try - catch - switch - case - new - var - function - return - this - delete - true - false - void - throw - typeof - const - default - - - - - - Anchor - Applet - Area - Array - Boolean - Button - Checkbox - Date - Document - Event - FileUpload - Form - Frame - Function - Hidden - History - Image - Layer - Linke - Location - Math - Navigator - Number - Object - Option - Password - Radio - RegExp - Reset - Screen - Select - String - Submit - Text - Textarea - Window - - - - - - abs - acos - alert - anchor - apply - asin - atan - atan2 - back - blur - call - captureEvents - ceil - charAt - charCodeAt - clearInterval - clearTimeout - click - close - compile - concat - confirm - cos - disableExternalCapture - enableExternalCapture - eval - exec - exp - find - floor - focus - forward - fromCharCode - getDate - getDay - getFullYear - getHours - getMilliseconds - getMinutes - getMonth - getSeconds - getSelection - getTime - getTimezoneOffset - getUTCDate - getUTCDay - getUTCFullYear - getUTCHours - getUTCMilliseconds - getUTCMinutes - getUTCMonth - getUTCSeconds - go - handleEvent - home - indexOf - javaEnabled - join - lastIndexOf - link - load - log - match - max - min - moveAbove - moveBelow - moveBy - moveTo - moveToAbsolute - open - parse - plugins.refresh - pop - pow - preference - print - prompt - push - random - releaseEvents - reload - replace - reset - resizeBy - resizeTo - reverse - round - routeEvent - scrollBy - scrollTo - search - select - setDate - setFullYear - setHours - setInterval - setMilliseconds - setMinutes - setMonth - setSeconds - setTime - setTimeout - setUTCDate - setUTCFullYear - setUTCHours - setUTCMilliseconds - setUTCMinutes - setUTCMonth - setUTCSeconds - shift - sin - slice - sort - splice - split - sqrt - stop - String formatting - submit - substr - substring - taintEnabled - tan - test - toLocaleString - toLowerCase - toSource - toString - toUpperCase - toUTCString - unshift - unwatch - UTC - valueOf - watch - write - writeln - - - - - - break - case - catch - continue - default - do - else - for - function - if - in - return - switch - try - var - while - - - - - - Abs - ACos - ArrayAppend - ArrayAvg - ArrayClear - ArrayDeleteAt - ArrayInsertAt - ArrayIsEmpty - ArrayLen - ArrayMax - ArrayMin - ArrayNew - ArrayPrepend - ArrayResize - ArraySet - ArraySort - ArraySum - ArraySwap - ArrayToList - Asc - ASin - Atn - BitAnd - BitMaskClear - BitMaskRead - BitMaskSet - BitNot - BitOr - BitSHLN - BitSHRN - BitXor - Ceiling - Chr - CJustify - Compare - CompareNoCase - Cos - CreateDate - CreateDateTime - CreateObject - CreateODBCDate - CreateODBCDateTime - CreateODBCTime - CreateTime - CreateTimeSpan - CreateUUID - DateAdd - DateCompare - DateConvert - DateDiff - DateFormat - DatePart - Day - DayOfWeek - DayOfWeekAsString - DayOfYear - DaysInMonth - DaysInYear - DE - DecimalFormat - DecrementValue - Decrypt - DeleteClientVariable - DirectoryExists - DollarFormat - Duplicate - Encrypt - Evaluate - Exp - ExpandPath - FileExists - Find - FindNoCase - FindOneOf - FirstDayOfMonth - Fix - FormatBaseN - GetAuthUser - GetBaseTagData - GetBaseTagList - GetBaseTemplatePath - GetClientVariablesList - GetCurrentTemplatePath - GetDirectoryFromPath - GetException - GetFileFromPath - GetFunctionList - GetHttpRequestData - GetHttpTimeString - GetK2ServerDocCount - GetK2ServerDocCountLimit - GetLocale - GetMetaData - GetMetricData - GetPageContext - GetProfileSections - GetProfileString - GetServiceSettings - GetTempDirectory - GetTempFile - GetTemplatePath - GetTickCount - GetTimeZoneInfo - GetToken - Hash - Hour - HTMLCodeFormat - HTMLEditFormat - IIf - IncrementValue - InputBaseN - Insert - Int - IsArray - IsBinary - IsBoolean - IsCustomFunction - IsDate - IsDebugMode - IsDefined - IsK2ServerABroker - IsK2ServerDocCountExceeded - IsK2ServerOnline - IsLeapYear - IsNumeric - IsNumericDate - IsObject - IsQuery - IsSimpleValue - IsStruct - IsUserInRole - IsWDDX - IsXmlDoc - IsXmlElement - IsXmlRoot - JavaCast - JSStringFormat - LCase - Left - Len - ListAppend - ListChangeDelims - ListContains - ListContainsNoCase - ListDeleteAt - ListFind - ListFindNoCase - ListFirst - ListGetAt - ListInsertAt - ListLast - ListLen - ListPrepend - ListQualify - ListRest - ListSetAt - ListSort - ListToArray - ListValueCount - ListValueCountNoCase - LJustify - Log - Log10 - LSCurrencyFormat - LSDateFormat - LSEuroCurrencyFormat - LSIsCurrency - LSIsDate - LSIsNumeric - LSNumberFormat - LSParseCurrency - LSParseDateTime - LSParseEuroCurrency - LSParseNumber - LSTimeFormat - LTrim - Max - Mid - Min - Minute - Month - MonthAsString - Now - NumberFormat - ParagraphFormat - ParameterExists - ParseDateTime - Pi - PreserveSingleQuotes - Quarter - QueryAddColumn - QueryAddRow - QueryNew - QuerySetCell - QuotedValueList - Rand - Randomize - RandRange - REFind - REFindNoCase - RemoveChars - RepeatString - Replace - ReplaceList - ReplaceNoCase - REReplace - REReplaceNoCase - Reverse - Right - RJustify - Round - RTrim - Second - SetEncoding - SetLocale - SetProfileString - SetVariable - Sgn - Sin - SpanExcluding - SpanIncluding - Sqr - StripCR - StructAppend - StructClear - StructCopy - StructCount - StructDelete - StructFind - StructFindKey - StructFindValue - StructGet - StructInsert - StructIsEmpty - StructKeyArray - StructKeyExists - StructKeyList - StructNew - StructSort - StructUpdate - Tan - TimeFormat - ToBase64 - ToBinary - ToString - Trim - UCase - URLDecode - URLEncodedFormat - URLSessionFormat - Val - ValueList - Week - WriteOutput - XmlChildPos - XmlElemNew - XmlFormat - XmlNew - XmlParse - XmlSearch - XmlTransform - Year - YesNoFormat - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/colortheme.py b/qutepart/syntax/colortheme.py similarity index 100% rename from qutepart/colortheme.py rename to qutepart/syntax/colortheme.py diff --git a/qutepart/syntax/commonlisp.xml b/qutepart/syntax/commonlisp.xml deleted file mode 100644 index 563e560..0000000 --- a/qutepart/syntax/commonlisp.xml +++ /dev/null @@ -1,1200 +0,0 @@ - - - - - - - < - <= - = - > - >= - => - - - / - /= - // - /// - * - ** - *** - + - ++ - +++ - 1- - 1+ - - - defclass - defconstant - defgeneric - define-compiler-macro - define-condition - define-method-combination - define-modify-macro - define-setf-expander - define-setf-method - define-symbol-macro - defmacro - defmethod - defpackage - defparameter - defsetf - deftype - defvar - defun - defstruct - - - abort - abs - access - acons - acos - acosh - add-method - adjoin - adjustable-array-p - adjust-array - allocate-instance - alpha-char-p - alphanumericp - and - append - apply - applyhook - apropos - apropos-list - aref - arithmetic-error - arithmetic-error-operands - arithmetic-error-operation - array - array-dimension - array-dimension-limit - array-dimensions - array-displacement - array-element-type - array-has-fill-pointer-p - array-in-bounds-p - arrayp - array-rank - array-rank-limit - array-row-major-index - array-total-size - array-total-size-limit - ash - asin - asinh - assert - assoc - assoc-if - assoc-if-not - atan - atanh - atom - base-char - base-string - bignum - bit - bit-and - bit-andc1 - bit-andc2 - bit-eqv - bit-ior - bit-nand - bit-nor - bit-not - bit-orc1 - bit-orc2 - bit-vector - bit-vector-p - bit-xor - block - boole - boole-1 - boole-2 - boolean - boole-and - boole-andc1 - boole-andc2 - boole-c1 - boole-c2 - boole-clr - boole-eqv - boole-ior - boole-nand - boole-nor - boole-orc1 - boole-orc2 - boole-set - boole-xor - both-case-p - boundp - break - broadcast-stream - broadcast-stream-streams - built-in-class - butlast - byte - byte-position - byte-size - caaaar - caaadr - caaar - caadar - caaddr - caadr - caar - cadaar - cadadr - cadar - caddar - cadddr - caddr - cadr - call-arguments-limit - call-method - call-next-method - capitalize - car - case - catch - ccase - cdaaar - cdaadr - cdaar - cdadar - cdaddr - cdadr - cdar - cddaar - cddadr - cddar - cdddar - cddddr - cdddr - cddr - cdr - ceiling - cell-error - cell-error-name - cerror - change-class - char - char< - char<= - char= - char> - char>= - char/= - character - characterp - char-bit - char-bits - char-bits-limit - char-code - char-code-limit - char-control-bit - char-downcase - char-equal - char-font - char-font-limit - char-greaterp - char-hyper-bit - char-int - char-lessp - char-meta-bit - char-name - char-not-equal - char-not-greaterp - char-not-lessp - char-super-bit - char-upcase - check-type - cis - class - class-name - class-of - clear-input - clear-output - close - clrhash - code-char - coerce - commonp - compilation-speed - compile - compiled-function - compiled-function-p - compile-file - compile-file-pathname - compiler-let - compiler-macro - compiler-macro-function - complement - complex - complexp - compute-applicable-methods - compute-restarts - concatenate - concatenated-stream - concatenated-stream-streams - cond - condition - conjugate - cons - consp - constantly - constantp - continue - control-error - copy-alist - copy-list - copy-pprint-dispatch - copy-readtable - copy-seq - copy-structure - copy-symbol - copy-tree - cos - cosh - count - count-if - count-if-not - ctypecase - debug - decf - declaim - declaration - declare - decode-float - decode-universal-time - delete - delete-duplicates - delete-file - delete-if - delete-if-not - delete-package - denominator - deposit-field - describe - describe-object - destructuring-bind - digit-char - digit-char-p - directory - directory-namestring - disassemble - division-by-zero - do - do* - do-all-symbols - documentation - do-exeternal-symbols - do-external-symbols - dolist - do-symbols - dotimes - double-float - double-float-epsilon - double-float-negative-epsilon - dpb - dribble - dynamic-extent - ecase - echo-stream - echo-stream-input-stream - echo-stream-output-stream - ed - eighth - elt - encode-universal-time - end-of-file - endp - enough-namestring - ensure-directories-exist - ensure-generic-function - eq - eql - equal - equalp - error - etypecase - eval - evalhook - eval-when - evenp - every - exp - export - expt - extended-char - fboundp - fceiling - fdefinition - ffloor - fifth - file-author - file-error - file-error-pathname - file-length - file-namestring - file-position - file-stream - file-string-length - file-write-date - fill - fill-pointer - find - find-all-symbols - find-class - find-if - find-if-not - find-method - find-package - find-restart - find-symbol - finish-output - first - fixnum - flet - float - float-digits - floating-point-inexact - floating-point-invalid-operation - floating-point-overflow - floating-point-underflow - floatp - float-precision - float-radix - float-sign - floor - fmakunbound - force-output - format - formatter - fourth - fresh-line - fround - ftruncate - ftype - funcall - function - function-keywords - function-lambda-expression - functionp - gbitp - gcd - generic-function - gensym - gentemp - get - get-decoded-time - get-dispatch-macro-character - getf - gethash - get-internal-real-time - get-internal-run-time - get-macro-character - get-output-stream-string - get-properties - get-setf-expansion - get-setf-method - get-universal-time - go - graphic-char-p - handler-bind - handler-case - hash-table - hash-table-count - hash-table-p - hash-table-rehash-size - hash-table-rehash-threshold - hash-table-size - hash-table-test - host-namestring - identity - if - if-exists - ignorable - ignore - ignore-errors - imagpart - import - incf - initialize-instance - inline - in-package - in-package - input-stream-p - inspect - int-char - integer - integer-decode-float - integer-length - integerp - interactive-stream-p - intern - internal-time-units-per-second - intersection - invalid-method-error - invoke-debugger - invoke-restart - invoke-restart-interactively - isqrt - keyword - keywordp - labels - lambda - lambda-list-keywords - lambda-parameters-limit - last - lcm - ldb - ldb-test - ldiff - least-negative-double-float - least-negative-long-float - least-negative-normalized-double-float - least-negative-normalized-long-float - least-negative-normalized-short-float - least-negative-normalized-single-float - least-negative-short-float - least-negative-single-float - least-positive-double-float - least-positive-long-float - least-positive-normalized-double-float - least-positive-normalized-long-float - least-positive-normalized-short-float - least-positive-normalized-single-float - least-positive-short-float - least-positive-single-float - length - let - let* - lisp - lisp-implementation-type - lisp-implementation-version - list - list* - list-all-packages - listen - list-length - listp - load - load-logical-pathname-translations - load-time-value - locally - log - logand - logandc1 - logandc2 - logbitp - logcount - logeqv - logical-pathname - logical-pathname-translations - logior - lognand - lognor - lognot - logorc1 - logorc2 - logtest - logxor - long-float - long-float-epsilon - long-float-negative-epsilon - long-site-name - loop - loop-finish - lower-case-p - machine-instance - machine-type - machine-version - macroexpand - macroexpand-1 - macroexpand-l - macro-function - macrolet - make-array - make-array - make-broadcast-stream - make-char - make-concatenated-stream - make-condition - make-dispatch-macro-character - make-echo-stream - make-hash-table - make-instance - make-instances-obsolete - make-list - make-load-form - make-load-form-saving-slots - make-method - make-package - make-pathname - make-random-state - make-sequence - make-string - make-string-input-stream - make-string-output-stream - make-symbol - make-synonym-stream - make-two-way-stream - makunbound - map - mapc - mapcan - mapcar - mapcon - maphash - map-into - mapl - maplist - mask-field - max - member - member-if - member-if-not - merge - merge-pathname - merge-pathnames - method - method-combination - method-combination-error - method-qualifiers - min - minusp - mismatch - mod - most-negative-double-float - most-negative-fixnum - most-negative-long-float - most-negative-short-float - most-negative-single-float - most-positive-double-float - most-positive-fixnum - most-positive-long-float - most-positive-short-float - most-positive-single-float - muffle-warning - multiple-value-bind - multiple-value-call - multiple-value-list - multiple-value-prog1 - multiple-value-seteq - multiple-value-setq - multiple-values-limit - name-char - namestring - nbutlast - nconc - next-method-p - nil - nintersection - ninth - no-applicable-method - no-next-method - not - notany - notevery - notinline - nreconc - nreverse - nset-difference - nset-exclusive-or - nstring - nstring-capitalize - nstring-downcase - nstring-upcase - nsublis - nsubst - nsubst-if - nsubst-if-not - nsubstitute - nsubstitute-if - nsubstitute-if-not - nth - nthcdr - nth-value - null - number - numberp - numerator - nunion - oddp - open - open-stream-p - optimize - or - otherwise - output-stream-p - package - package-error - package-error-package - package-name - package-nicknames - packagep - package-shadowing-symbols - package-used-by-list - package-use-list - pairlis - parse-error - parse-integer - parse-namestring - pathname - pathname-device - pathname-directory - pathname-host - pathname-match-p - pathname-name - pathnamep - pathname-type - pathname-version - peek-char - phase - pi - plusp - pop - position - position-if - position-if-not - pprint - pprint-dispatch - pprint-exit-if-list-exhausted - pprint-fill - pprint-indent - pprint-linear - pprint-logical-block - pprint-newline - pprint-pop - pprint-tab - pprint-tabular - prin1 - prin1-to-string - princ - princ-to-string - print - print-not-readable - print-not-readable-object - print-object - print-unreadable-object - probe-file - proclaim - prog - prog* - prog1 - prog2 - progn - program-error - progv - provide - psetf - psetq - push - pushnew - putprop - quote - random - random-state - random-state-p - rassoc - rassoc-if - rassoc-if-not - ratio - rational - rationalize - rationalp - read - read-byte - read-char - read-char-no-hang - read-delimited-list - reader-error - read-eval-print - read-from-string - read-line - read-preserving-whitespace - read-sequence - readtable - readtable-case - readtablep - real - realp - realpart - reduce - reinitialize-instance - rem - remf - remhash - remove - remove-duplicates - remove-if - remove-if-not - remove-method - remprop - rename-file - rename-package - replace - require - rest - restart - restart-bind - restart-case - restart-name - return - return-from - revappend - reverse - room - rotatef - round - row-major-aref - rplaca - rplacd - safety - satisfies - sbit - scale-float - schar - search - second - sequence - serious-condition - set - set-char-bit - set-difference - set-dispatch-macro-character - set-exclusive-or - setf - set-macro-character - set-pprint-dispatch - setq - set-syntax-from-char - seventh - shadow - shadowing-import - shared-initialize - shiftf - short-float - short-float-epsilon - short-float-negative-epsilon - short-site-name - signal - signed-byte - signum - simle-condition - simple-array - simple-base-string - simple-bit-vector - simple-bit-vector-p - simple-condition-format-arguments - simple-condition-format-control - simple-error - simple-string - simple-string-p - simple-type-error - simple-vector - simple-vector-p - simple-warning - sin - single-flaot-epsilon - single-float - single-float-epsilon - single-float-negative-epsilon - sinh - sixth - sleep - slot-boundp - slot-exists-p - slot-makunbound - slot-missing - slot-unbound - slot-value - software-type - software-version - some - sort - space - special - special-form-p - special-operator-p - speed - sqrt - stable-sort - standard - standard-char - standard-char-p - standard-class - standard-generic-function - standard-method - standard-object - step - storage-condition - store-value - stream - stream-element-type - stream-error - stream-error-stream - stream-external-format - streamp - streamup - string - string< - string<= - string= - string> - string>= - string/= - string-capitalize - string-char - string-char-p - string-downcase - string-equal - string-greaterp - string-left-trim - string-lessp - string-not-equal - string-not-greaterp - string-not-lessp - stringp - string-right-strim - string-right-trim - string-stream - string-trim - string-upcase - structure - structure-class - structure-object - style-warning - sublim - sublis - subseq - subsetp - subst - subst-if - subst-if-not - substitute - substitute-if - substitute-if-not - subtypep - svref - sxhash - symbol - symbol-function - symbol-macrolet - symbol-name - symbolp - symbol-package - symbol-plist - symbol-value - synonym-stream - synonym-stream-symbol - sys - system - t - tagbody - tailp - tan - tanh - tenth - terpri - the - third - throw - time - trace - translate-logical-pathname - translate-pathname - tree-equal - truename - truncase - truncate - two-way-stream - two-way-stream-input-stream - two-way-stream-output-stream - type - typecase - type-error - type-error-datum - type-error-expected-type - type-of - typep - unbound-slot - unbound-slot-instance - unbound-variable - undefined-function - unexport - unintern - union - unless - unread - unread-char - unsigned-byte - untrace - unuse-package - unwind-protect - update-instance-for-different-class - update-instance-for-redefined-class - upgraded-array-element-type - upgraded-complex-part-type - upper-case-p - use-package - user - user-homedir-pathname - use-value - values - values-list - vector - vectorp - vector-pop - vector-push - vector-push-extend - warn - warning - when - wild-pathname-p - with-accessors - with-compilation-unit - with-condition-restarts - with-hash-table-iterator - with-input-from-string - with-open-file - with-open-stream - with-output-to-string - with-package-iterator - with-simple-restart - with-slots - with-standard-io-syntax - write - write-byte - write-char - write-line - write-sequence - write-string - write-to-string - yes-or-no-p - y-or-n-p - zerop - - - - :abort - :adjustable - :append - :array - :base - :case - :circle - :conc-name - :constructor - :copier - :count - :create - :default - :defaults - :device - :direction - :directory - :displaced-index-offset - :displaced-to - :element-type - :end1 - :end2 - :end - :error - :escape - :external - :from-end - :gensym - :host - :if-does-not-exist:pretty - :if-exists:print - :include:print-function - :index - :inherited - :initial-contents - :initial-element - :initial-offset - :initial-value - :input - :internal:size - :io - :junk-allowed - :key - :length - :level - :named - :name - :new-version - :nicknames - :output-file - :output - :overwrite - :predicate - :preserve-whitespace - :probe - :radix - :read-only - :rehash-size - :rehash-threshold - :rename-and-delete - :rename - :start1 - :start2 - :start - :stream - :supersede - :test - :test-not - :type - :use - :verbose - :version - - - *applyhook* - *break-on-signals* - *break-on-signals* - *break-on-warnings* - *compile-file-pathname* - *compile-file-pathname* - *compile-file-truename* - *compile-file-truename* - *compile-print* - *compile-verbose* - *compile-verbose* - *debugger-hook* - *debug-io* - *default-pathname-defaults* - *error-output* - *evalhook* - *features* - *gensym-counter* - *load-pathname* - *load-print* - *load-truename* - *load-verbose* - *macroexpand-hook* - *modules* - *package* - *print-array* - *print-base* - *print-case* - *print-circle* - *print-escape* - *print-gensym* - *print-length* - *print-level* - *print-lines* - *print-miser-width* - *print-miser-width* - *print-pprint-dispatch* - *print-pprint-dispatch* - *print-pretty* - *print-radix* - *print-readably* - *print-right-margin* - *print-right-margin* - *query-io* - *random-state* - *read-base* - *read-default-float-format* - *read-eval* - *read-suppress* - *readtable* - *standard-input* - *standard-output* - *terminal-io* - *trace-output* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/component-pascal.xml b/qutepart/syntax/component-pascal.xml deleted file mode 100644 index 09e7001..0000000 --- a/qutepart/syntax/component-pascal.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - - - - - - - - - - - BEGIN - BY - CASE - CLOSE - CONST - DO - ELSE - ELSIF - END - FOR - IF - IMPORT - LOOP - MODULE - NEW - OF - OUT - PROCEDURE - REPEAT - THEN - TO - TYPE - UNTIL - VAR - WHILE - WITH - - - ASSERT - EXIT - HALT - RETURN - - - ANYPTR - ANYREC - ARRAY - BOOLEAN - SHORTCHAR - CHAR - BYTE - SHORTINT - INTEGER - LONGINT - POINTER - RECORD - SHORTREAL - REAL - SET - - - ABSTRACT - EMPTY - EXTENSIBLE - LIMITED - - - ABS - ASH - BITS - CAP - CHR - DEC - ENTIER - EXCL - INC - INCL - LEN - LONG - MAX - MIN - ODD - ORD - SHORT - SIZE - - - FALSE - INF - NIL - TRUE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/cs.xml b/qutepart/syntax/cs.xml deleted file mode 100644 index 260434c..0000000 --- a/qutepart/syntax/cs.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - - abstract - as - base - break - case - catch - class - checked - continue - default - delegate - do - else - enum - event - explicit - extern - false - for - foreach - finally - fixed - goto - if - implicit - in - interface - internal - is - lock - namespace - new - null - operator - out - override - params - private - protected - public - readonly - ref - return - sealed - sizeof - stackalloc - static - struct - switch - this - throw - true - try - typeof - unchecked - unsafe - using - virtual - while - #if - #else - #elif - #endif - #define - #undef - #warning - #error - #line - - - bool - byte - char - const - decimal - double - float - int - long - object - uint - ushort - ulong - sbyte - short - string - void - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/cue.xml b/qutepart/syntax/cue.xml deleted file mode 100644 index 6044aae..0000000 --- a/qutepart/syntax/cue.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - CATALOG - CDTEXTFILE - FILE - FLAGS - INDEX - ISRC - PERFORMER - PREGAP - POSTGAP - REM - SONGWRITER - TITLE - TRACK - - - AIFF - WAVE - MP3 - BINARY - MOTOTOLA - - - AUDIO - CDG - CDI - MODE1 - MODE2 - RAW - - - 4CH - DCP - PRE - SCMS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/part/syntax/data/CMakeLists.txt b/qutepart/syntax/data/CMakeLists.txt similarity index 100% rename from part/syntax/data/CMakeLists.txt rename to qutepart/syntax/data/CMakeLists.txt diff --git a/part/syntax/data/abap.xml b/qutepart/syntax/data/abap.xml similarity index 100% rename from part/syntax/data/abap.xml rename to qutepart/syntax/data/abap.xml diff --git a/part/syntax/data/abc.xml b/qutepart/syntax/data/abc.xml similarity index 100% rename from part/syntax/data/abc.xml rename to qutepart/syntax/data/abc.xml diff --git a/part/syntax/data/actionscript.xml b/qutepart/syntax/data/actionscript.xml similarity index 100% rename from part/syntax/data/actionscript.xml rename to qutepart/syntax/data/actionscript.xml diff --git a/part/syntax/data/ada.xml b/qutepart/syntax/data/ada.xml similarity index 100% rename from part/syntax/data/ada.xml rename to qutepart/syntax/data/ada.xml diff --git a/part/syntax/data/ahdl.xml b/qutepart/syntax/data/ahdl.xml similarity index 100% rename from part/syntax/data/ahdl.xml rename to qutepart/syntax/data/ahdl.xml diff --git a/part/syntax/data/alert.xml b/qutepart/syntax/data/alert.xml similarity index 100% rename from part/syntax/data/alert.xml rename to qutepart/syntax/data/alert.xml diff --git a/part/syntax/data/alert_indent.xml b/qutepart/syntax/data/alert_indent.xml similarity index 100% rename from part/syntax/data/alert_indent.xml rename to qutepart/syntax/data/alert_indent.xml diff --git a/part/syntax/data/ample.xml b/qutepart/syntax/data/ample.xml similarity index 100% rename from part/syntax/data/ample.xml rename to qutepart/syntax/data/ample.xml diff --git a/qutepart/syntax/ansforth94.xml b/qutepart/syntax/data/ansforth94.xml similarity index 100% rename from qutepart/syntax/ansforth94.xml rename to qutepart/syntax/data/ansforth94.xml diff --git a/part/syntax/data/ansic89.xml b/qutepart/syntax/data/ansic89.xml similarity index 100% rename from part/syntax/data/ansic89.xml rename to qutepart/syntax/data/ansic89.xml diff --git a/part/syntax/data/ansys.xml b/qutepart/syntax/data/ansys.xml similarity index 100% rename from part/syntax/data/ansys.xml rename to qutepart/syntax/data/ansys.xml diff --git a/part/syntax/data/apache.xml b/qutepart/syntax/data/apache.xml similarity index 100% rename from part/syntax/data/apache.xml rename to qutepart/syntax/data/apache.xml diff --git a/part/syntax/data/asm-avr.xml b/qutepart/syntax/data/asm-avr.xml similarity index 100% rename from part/syntax/data/asm-avr.xml rename to qutepart/syntax/data/asm-avr.xml diff --git a/part/syntax/data/asm-dsp56k.xml b/qutepart/syntax/data/asm-dsp56k.xml similarity index 100% rename from part/syntax/data/asm-dsp56k.xml rename to qutepart/syntax/data/asm-dsp56k.xml diff --git a/part/syntax/data/asm-m68k.xml b/qutepart/syntax/data/asm-m68k.xml similarity index 100% rename from part/syntax/data/asm-m68k.xml rename to qutepart/syntax/data/asm-m68k.xml diff --git a/part/syntax/data/asm6502.xml b/qutepart/syntax/data/asm6502.xml similarity index 100% rename from part/syntax/data/asm6502.xml rename to qutepart/syntax/data/asm6502.xml diff --git a/part/syntax/data/asn1.xml b/qutepart/syntax/data/asn1.xml similarity index 100% rename from part/syntax/data/asn1.xml rename to qutepart/syntax/data/asn1.xml diff --git a/qutepart/syntax/asp.xml b/qutepart/syntax/data/asp.xml similarity index 100% rename from qutepart/syntax/asp.xml rename to qutepart/syntax/data/asp.xml diff --git a/part/syntax/data/asterisk.xml b/qutepart/syntax/data/asterisk.xml similarity index 100% rename from part/syntax/data/asterisk.xml rename to qutepart/syntax/data/asterisk.xml diff --git a/qutepart/syntax/awk.xml b/qutepart/syntax/data/awk.xml similarity index 100% rename from qutepart/syntax/awk.xml rename to qutepart/syntax/data/awk.xml diff --git a/qutepart/syntax/bash.xml b/qutepart/syntax/data/bash.xml similarity index 100% rename from qutepart/syntax/bash.xml rename to qutepart/syntax/data/bash.xml diff --git a/part/syntax/data/bibtex.xml b/qutepart/syntax/data/bibtex.xml similarity index 100% rename from part/syntax/data/bibtex.xml rename to qutepart/syntax/data/bibtex.xml diff --git a/part/syntax/data/bmethod.xml b/qutepart/syntax/data/bmethod.xml similarity index 100% rename from part/syntax/data/bmethod.xml rename to qutepart/syntax/data/bmethod.xml diff --git a/part/syntax/data/boo.xml b/qutepart/syntax/data/boo.xml similarity index 100% rename from part/syntax/data/boo.xml rename to qutepart/syntax/data/boo.xml diff --git a/qutepart/syntax/c.xml b/qutepart/syntax/data/c.xml similarity index 100% rename from qutepart/syntax/c.xml rename to qutepart/syntax/data/c.xml diff --git a/qutepart/syntax/cg.xml b/qutepart/syntax/data/cg.xml similarity index 100% rename from qutepart/syntax/cg.xml rename to qutepart/syntax/data/cg.xml diff --git a/part/syntax/data/cgis.xml b/qutepart/syntax/data/cgis.xml similarity index 100% rename from part/syntax/data/cgis.xml rename to qutepart/syntax/data/cgis.xml diff --git a/part/syntax/data/changelog.xml b/qutepart/syntax/data/changelog.xml similarity index 100% rename from part/syntax/data/changelog.xml rename to qutepart/syntax/data/changelog.xml diff --git a/part/syntax/data/checkdtd b/qutepart/syntax/data/checkdtd similarity index 100% rename from part/syntax/data/checkdtd rename to qutepart/syntax/data/checkdtd diff --git a/part/syntax/data/cisco.xml b/qutepart/syntax/data/cisco.xml similarity index 100% rename from part/syntax/data/cisco.xml rename to qutepart/syntax/data/cisco.xml diff --git a/part/syntax/data/clipper.xml b/qutepart/syntax/data/clipper.xml similarity index 100% rename from part/syntax/data/clipper.xml rename to qutepart/syntax/data/clipper.xml diff --git a/qutepart/syntax/clojure.xml b/qutepart/syntax/data/clojure.xml similarity index 100% rename from qutepart/syntax/clojure.xml rename to qutepart/syntax/data/clojure.xml diff --git a/part/syntax/data/cmake-gen.sh b/qutepart/syntax/data/cmake-gen.sh similarity index 100% rename from part/syntax/data/cmake-gen.sh rename to qutepart/syntax/data/cmake-gen.sh diff --git a/part/syntax/data/cmake.xml b/qutepart/syntax/data/cmake.xml similarity index 100% rename from part/syntax/data/cmake.xml rename to qutepart/syntax/data/cmake.xml diff --git a/qutepart/syntax/coffee.xml b/qutepart/syntax/data/coffee.xml similarity index 100% rename from qutepart/syntax/coffee.xml rename to qutepart/syntax/data/coffee.xml diff --git a/part/syntax/data/coldfusion.xml b/qutepart/syntax/data/coldfusion.xml similarity index 100% rename from part/syntax/data/coldfusion.xml rename to qutepart/syntax/data/coldfusion.xml diff --git a/part/syntax/data/commonlisp.xml b/qutepart/syntax/data/commonlisp.xml similarity index 100% rename from part/syntax/data/commonlisp.xml rename to qutepart/syntax/data/commonlisp.xml diff --git a/part/syntax/data/component-pascal.xml b/qutepart/syntax/data/component-pascal.xml similarity index 100% rename from part/syntax/data/component-pascal.xml rename to qutepart/syntax/data/component-pascal.xml diff --git a/qutepart/syntax/cpp.xml b/qutepart/syntax/data/cpp.xml similarity index 100% rename from qutepart/syntax/cpp.xml rename to qutepart/syntax/data/cpp.xml diff --git a/qutepart/syntax/crk.xml b/qutepart/syntax/data/crk.xml similarity index 100% rename from qutepart/syntax/crk.xml rename to qutepart/syntax/data/crk.xml diff --git a/part/syntax/data/cs.xml b/qutepart/syntax/data/cs.xml similarity index 100% rename from part/syntax/data/cs.xml rename to qutepart/syntax/data/cs.xml diff --git a/qutepart/syntax/css.xml b/qutepart/syntax/data/css.xml similarity index 100% rename from qutepart/syntax/css.xml rename to qutepart/syntax/data/css.xml diff --git a/part/syntax/data/cue.xml b/qutepart/syntax/data/cue.xml similarity index 100% rename from part/syntax/data/cue.xml rename to qutepart/syntax/data/cue.xml diff --git a/qutepart/syntax/d.xml b/qutepart/syntax/data/d.xml similarity index 100% rename from qutepart/syntax/d.xml rename to qutepart/syntax/data/d.xml diff --git a/qutepart/syntax/debianchangelog.xml b/qutepart/syntax/data/debianchangelog.xml similarity index 100% rename from qutepart/syntax/debianchangelog.xml rename to qutepart/syntax/data/debianchangelog.xml diff --git a/qutepart/syntax/debiancontrol.xml b/qutepart/syntax/data/debiancontrol.xml similarity index 100% rename from qutepart/syntax/debiancontrol.xml rename to qutepart/syntax/data/debiancontrol.xml diff --git a/part/syntax/data/desktop.xml b/qutepart/syntax/data/desktop.xml similarity index 100% rename from part/syntax/data/desktop.xml rename to qutepart/syntax/data/desktop.xml diff --git a/part/syntax/data/diff.xml b/qutepart/syntax/data/diff.xml similarity index 100% rename from part/syntax/data/diff.xml rename to qutepart/syntax/data/diff.xml diff --git a/qutepart/syntax/djangotemplate.xml b/qutepart/syntax/data/djangotemplate.xml similarity index 100% rename from qutepart/syntax/djangotemplate.xml rename to qutepart/syntax/data/djangotemplate.xml diff --git a/qutepart/syntax/dosbat.xml b/qutepart/syntax/data/dosbat.xml similarity index 100% rename from qutepart/syntax/dosbat.xml rename to qutepart/syntax/data/dosbat.xml diff --git a/qutepart/syntax/dot.xml b/qutepart/syntax/data/dot.xml similarity index 100% rename from qutepart/syntax/dot.xml rename to qutepart/syntax/data/dot.xml diff --git a/qutepart/syntax/doxygen.xml b/qutepart/syntax/data/doxygen.xml similarity index 100% rename from qutepart/syntax/doxygen.xml rename to qutepart/syntax/data/doxygen.xml diff --git a/part/syntax/data/doxygenlua.xml b/qutepart/syntax/data/doxygenlua.xml similarity index 100% rename from part/syntax/data/doxygenlua.xml rename to qutepart/syntax/data/doxygenlua.xml diff --git a/part/syntax/data/dtd.xml b/qutepart/syntax/data/dtd.xml similarity index 100% rename from part/syntax/data/dtd.xml rename to qutepart/syntax/data/dtd.xml diff --git a/qutepart/syntax/e.xml b/qutepart/syntax/data/e.xml similarity index 100% rename from qutepart/syntax/e.xml rename to qutepart/syntax/data/e.xml diff --git a/part/syntax/data/eiffel.xml b/qutepart/syntax/data/eiffel.xml similarity index 100% rename from part/syntax/data/eiffel.xml rename to qutepart/syntax/data/eiffel.xml diff --git a/part/syntax/data/email.xml b/qutepart/syntax/data/email.xml similarity index 100% rename from part/syntax/data/email.xml rename to qutepart/syntax/data/email.xml diff --git a/part/syntax/data/erlang.xml b/qutepart/syntax/data/erlang.xml similarity index 100% rename from part/syntax/data/erlang.xml rename to qutepart/syntax/data/erlang.xml diff --git a/part/syntax/data/euphoria.xml b/qutepart/syntax/data/euphoria.xml similarity index 100% rename from part/syntax/data/euphoria.xml rename to qutepart/syntax/data/euphoria.xml diff --git a/part/syntax/data/ferite.xml b/qutepart/syntax/data/ferite.xml similarity index 100% rename from part/syntax/data/ferite.xml rename to qutepart/syntax/data/ferite.xml diff --git a/part/syntax/data/fgl-4gl.xml b/qutepart/syntax/data/fgl-4gl.xml similarity index 100% rename from part/syntax/data/fgl-4gl.xml rename to qutepart/syntax/data/fgl-4gl.xml diff --git a/part/syntax/data/fgl-per.xml b/qutepart/syntax/data/fgl-per.xml similarity index 100% rename from part/syntax/data/fgl-per.xml rename to qutepart/syntax/data/fgl-per.xml diff --git a/part/syntax/data/find-trivial-regexpr.sh b/qutepart/syntax/data/find-trivial-regexpr.sh similarity index 100% rename from part/syntax/data/find-trivial-regexpr.sh rename to qutepart/syntax/data/find-trivial-regexpr.sh diff --git a/qutepart/syntax/fortran.xml b/qutepart/syntax/data/fortran.xml similarity index 100% rename from qutepart/syntax/fortran.xml rename to qutepart/syntax/data/fortran.xml diff --git a/part/syntax/data/freebasic.xml b/qutepart/syntax/data/freebasic.xml similarity index 100% rename from part/syntax/data/freebasic.xml rename to qutepart/syntax/data/freebasic.xml diff --git a/qutepart/syntax/fsharp.xml b/qutepart/syntax/data/fsharp.xml similarity index 100% rename from qutepart/syntax/fsharp.xml rename to qutepart/syntax/data/fsharp.xml diff --git a/part/syntax/data/fstab.xml b/qutepart/syntax/data/fstab.xml similarity index 100% rename from part/syntax/data/fstab.xml rename to qutepart/syntax/data/fstab.xml diff --git a/part/syntax/data/gap.xml b/qutepart/syntax/data/gap.xml similarity index 100% rename from part/syntax/data/gap.xml rename to qutepart/syntax/data/gap.xml diff --git a/part/syntax/data/gdb.xml b/qutepart/syntax/data/gdb.xml similarity index 100% rename from part/syntax/data/gdb.xml rename to qutepart/syntax/data/gdb.xml diff --git a/part/syntax/data/gdl.xml b/qutepart/syntax/data/gdl.xml similarity index 100% rename from part/syntax/data/gdl.xml rename to qutepart/syntax/data/gdl.xml diff --git a/part/syntax/data/generate-php.pl b/qutepart/syntax/data/generate-php.pl similarity index 100% rename from part/syntax/data/generate-php.pl rename to qutepart/syntax/data/generate-php.pl diff --git a/part/syntax/data/gettext.xml b/qutepart/syntax/data/gettext.xml similarity index 100% rename from part/syntax/data/gettext.xml rename to qutepart/syntax/data/gettext.xml diff --git a/qutepart/syntax/glosstex.xml b/qutepart/syntax/data/glosstex.xml similarity index 100% rename from qutepart/syntax/glosstex.xml rename to qutepart/syntax/data/glosstex.xml diff --git a/qutepart/syntax/glsl.xml b/qutepart/syntax/data/glsl.xml similarity index 100% rename from qutepart/syntax/glsl.xml rename to qutepart/syntax/data/glsl.xml diff --git a/qutepart/syntax/gnuassembler.xml b/qutepart/syntax/data/gnuassembler.xml similarity index 100% rename from qutepart/syntax/gnuassembler.xml rename to qutepart/syntax/data/gnuassembler.xml diff --git a/qutepart/syntax/go.xml b/qutepart/syntax/data/go.xml similarity index 100% rename from qutepart/syntax/go.xml rename to qutepart/syntax/data/go.xml diff --git a/part/syntax/data/grammar.xml b/qutepart/syntax/data/grammar.xml similarity index 100% rename from part/syntax/data/grammar.xml rename to qutepart/syntax/data/grammar.xml diff --git a/qutepart/syntax/haskell.xml b/qutepart/syntax/data/haskell.xml similarity index 100% rename from qutepart/syntax/haskell.xml rename to qutepart/syntax/data/haskell.xml diff --git a/part/syntax/data/haxe.xml b/qutepart/syntax/data/haxe.xml similarity index 100% rename from part/syntax/data/haxe.xml rename to qutepart/syntax/data/haxe.xml diff --git a/part/syntax/data/html.xml b/qutepart/syntax/data/html.xml similarity index 100% rename from part/syntax/data/html.xml rename to qutepart/syntax/data/html.xml diff --git a/part/syntax/data/idconsole.xml b/qutepart/syntax/data/idconsole.xml similarity index 100% rename from part/syntax/data/idconsole.xml rename to qutepart/syntax/data/idconsole.xml diff --git a/part/syntax/data/idl.xml b/qutepart/syntax/data/idl.xml similarity index 100% rename from part/syntax/data/idl.xml rename to qutepart/syntax/data/idl.xml diff --git a/part/syntax/data/ilerpg.xml b/qutepart/syntax/data/ilerpg.xml similarity index 100% rename from part/syntax/data/ilerpg.xml rename to qutepart/syntax/data/ilerpg.xml diff --git a/part/syntax/data/inform.xml b/qutepart/syntax/data/inform.xml similarity index 100% rename from part/syntax/data/inform.xml rename to qutepart/syntax/data/inform.xml diff --git a/part/syntax/data/ini.xml b/qutepart/syntax/data/ini.xml similarity index 100% rename from part/syntax/data/ini.xml rename to qutepart/syntax/data/ini.xml diff --git a/qutepart/syntax/jam.xml b/qutepart/syntax/data/jam.xml similarity index 100% rename from qutepart/syntax/jam.xml rename to qutepart/syntax/data/jam.xml diff --git a/qutepart/syntax/java.xml b/qutepart/syntax/data/java.xml similarity index 100% rename from qutepart/syntax/java.xml rename to qutepart/syntax/data/java.xml diff --git a/part/syntax/data/javadoc.xml b/qutepart/syntax/data/javadoc.xml similarity index 100% rename from part/syntax/data/javadoc.xml rename to qutepart/syntax/data/javadoc.xml diff --git a/qutepart/syntax/javascript.xml b/qutepart/syntax/data/javascript.xml similarity index 100% rename from qutepart/syntax/javascript.xml rename to qutepart/syntax/data/javascript.xml diff --git a/part/syntax/data/json.xml b/qutepart/syntax/data/json.xml similarity index 100% rename from part/syntax/data/json.xml rename to qutepart/syntax/data/json.xml diff --git a/part/syntax/data/jsp.xml b/qutepart/syntax/data/jsp.xml similarity index 100% rename from part/syntax/data/jsp.xml rename to qutepart/syntax/data/jsp.xml diff --git a/part/syntax/data/kbasic.xml b/qutepart/syntax/data/kbasic.xml similarity index 100% rename from part/syntax/data/kbasic.xml rename to qutepart/syntax/data/kbasic.xml diff --git a/part/syntax/data/language.dtd b/qutepart/syntax/data/language.dtd similarity index 100% rename from part/syntax/data/language.dtd rename to qutepart/syntax/data/language.dtd diff --git a/qutepart/syntax/latex.xml b/qutepart/syntax/data/latex.xml similarity index 100% rename from qutepart/syntax/latex.xml rename to qutepart/syntax/data/latex.xml diff --git a/qutepart/syntax/ld.xml b/qutepart/syntax/data/ld.xml similarity index 100% rename from qutepart/syntax/ld.xml rename to qutepart/syntax/data/ld.xml diff --git a/part/syntax/data/ldif.xml b/qutepart/syntax/data/ldif.xml similarity index 100% rename from part/syntax/data/ldif.xml rename to qutepart/syntax/data/ldif.xml diff --git a/part/syntax/data/lex.xml b/qutepart/syntax/data/lex.xml similarity index 100% rename from part/syntax/data/lex.xml rename to qutepart/syntax/data/lex.xml diff --git a/part/syntax/data/lilypond.xml b/qutepart/syntax/data/lilypond.xml similarity index 100% rename from part/syntax/data/lilypond.xml rename to qutepart/syntax/data/lilypond.xml diff --git a/part/syntax/data/list-keywords-ldif.awk b/qutepart/syntax/data/list-keywords-ldif.awk similarity index 100% rename from part/syntax/data/list-keywords-ldif.awk rename to qutepart/syntax/data/list-keywords-ldif.awk diff --git a/part/syntax/data/list-keywords-ldif.sh b/qutepart/syntax/data/list-keywords-ldif.sh similarity index 100% rename from part/syntax/data/list-keywords-ldif.sh rename to qutepart/syntax/data/list-keywords-ldif.sh diff --git a/qutepart/syntax/literate-haskell.xml b/qutepart/syntax/data/literate-haskell.xml similarity index 100% rename from qutepart/syntax/literate-haskell.xml rename to qutepart/syntax/data/literate-haskell.xml diff --git a/part/syntax/data/logtalk.xml b/qutepart/syntax/data/logtalk.xml similarity index 100% rename from part/syntax/data/logtalk.xml rename to qutepart/syntax/data/logtalk.xml diff --git a/part/syntax/data/lpc.xml b/qutepart/syntax/data/lpc.xml similarity index 100% rename from part/syntax/data/lpc.xml rename to qutepart/syntax/data/lpc.xml diff --git a/part/syntax/data/lsl.xml b/qutepart/syntax/data/lsl.xml similarity index 100% rename from part/syntax/data/lsl.xml rename to qutepart/syntax/data/lsl.xml diff --git a/qutepart/syntax/lua.xml b/qutepart/syntax/data/lua.xml similarity index 100% rename from qutepart/syntax/lua.xml rename to qutepart/syntax/data/lua.xml diff --git a/part/syntax/data/m3u.xml b/qutepart/syntax/data/m3u.xml similarity index 100% rename from part/syntax/data/m3u.xml rename to qutepart/syntax/data/m3u.xml diff --git a/qutepart/syntax/m4.xml b/qutepart/syntax/data/m4.xml similarity index 100% rename from qutepart/syntax/m4.xml rename to qutepart/syntax/data/m4.xml diff --git a/part/syntax/data/mab.xml b/qutepart/syntax/data/mab.xml similarity index 100% rename from part/syntax/data/mab.xml rename to qutepart/syntax/data/mab.xml diff --git a/qutepart/syntax/makefile.xml b/qutepart/syntax/data/makefile.xml similarity index 100% rename from qutepart/syntax/makefile.xml rename to qutepart/syntax/data/makefile.xml diff --git a/part/syntax/data/mandoc.xml b/qutepart/syntax/data/mandoc.xml similarity index 100% rename from part/syntax/data/mandoc.xml rename to qutepart/syntax/data/mandoc.xml diff --git a/qutepart/syntax/mason.xml b/qutepart/syntax/data/mason.xml similarity index 100% rename from qutepart/syntax/mason.xml rename to qutepart/syntax/data/mason.xml diff --git a/part/syntax/data/matlab.xml b/qutepart/syntax/data/matlab.xml similarity index 100% rename from part/syntax/data/matlab.xml rename to qutepart/syntax/data/matlab.xml diff --git a/part/syntax/data/maxima.xml b/qutepart/syntax/data/maxima.xml similarity index 100% rename from part/syntax/data/maxima.xml rename to qutepart/syntax/data/maxima.xml diff --git a/qutepart/syntax/mediawiki.xml b/qutepart/syntax/data/mediawiki.xml similarity index 100% rename from qutepart/syntax/mediawiki.xml rename to qutepart/syntax/data/mediawiki.xml diff --git a/qutepart/syntax/mel.xml b/qutepart/syntax/data/mel.xml similarity index 100% rename from qutepart/syntax/mel.xml rename to qutepart/syntax/data/mel.xml diff --git a/part/syntax/data/mergetagtext.xml b/qutepart/syntax/data/mergetagtext.xml similarity index 100% rename from part/syntax/data/mergetagtext.xml rename to qutepart/syntax/data/mergetagtext.xml diff --git a/qutepart/syntax/metafont.xml b/qutepart/syntax/data/metafont.xml similarity index 100% rename from qutepart/syntax/metafont.xml rename to qutepart/syntax/data/metafont.xml diff --git a/part/syntax/data/mips.xml b/qutepart/syntax/data/mips.xml similarity index 100% rename from part/syntax/data/mips.xml rename to qutepart/syntax/data/mips.xml diff --git a/part/syntax/data/modelica.xml b/qutepart/syntax/data/modelica.xml similarity index 100% rename from part/syntax/data/modelica.xml rename to qutepart/syntax/data/modelica.xml diff --git a/qutepart/syntax/modelines.xml b/qutepart/syntax/data/modelines.xml similarity index 100% rename from qutepart/syntax/modelines.xml rename to qutepart/syntax/data/modelines.xml diff --git a/part/syntax/data/modula-2.xml b/qutepart/syntax/data/modula-2.xml similarity index 100% rename from part/syntax/data/modula-2.xml rename to qutepart/syntax/data/modula-2.xml diff --git a/part/syntax/data/monobasic.xml b/qutepart/syntax/data/monobasic.xml similarity index 100% rename from part/syntax/data/monobasic.xml rename to qutepart/syntax/data/monobasic.xml diff --git a/qutepart/syntax/mup.xml b/qutepart/syntax/data/mup.xml similarity index 100% rename from qutepart/syntax/mup.xml rename to qutepart/syntax/data/mup.xml diff --git a/qutepart/syntax/nasm.xml b/qutepart/syntax/data/nasm.xml similarity index 100% rename from qutepart/syntax/nasm.xml rename to qutepart/syntax/data/nasm.xml diff --git a/part/syntax/data/nemerle.xml b/qutepart/syntax/data/nemerle.xml similarity index 100% rename from part/syntax/data/nemerle.xml rename to qutepart/syntax/data/nemerle.xml diff --git a/part/syntax/data/noweb.xml b/qutepart/syntax/data/noweb.xml similarity index 100% rename from part/syntax/data/noweb.xml rename to qutepart/syntax/data/noweb.xml diff --git a/part/syntax/data/objectivec.xml b/qutepart/syntax/data/objectivec.xml similarity index 100% rename from part/syntax/data/objectivec.xml rename to qutepart/syntax/data/objectivec.xml diff --git a/part/syntax/data/objectivecpp.xml b/qutepart/syntax/data/objectivecpp.xml similarity index 100% rename from part/syntax/data/objectivecpp.xml rename to qutepart/syntax/data/objectivecpp.xml diff --git a/part/syntax/data/ocaml.xml b/qutepart/syntax/data/ocaml.xml similarity index 100% rename from part/syntax/data/ocaml.xml rename to qutepart/syntax/data/ocaml.xml diff --git a/part/syntax/data/octave.xml b/qutepart/syntax/data/octave.xml similarity index 100% rename from part/syntax/data/octave.xml rename to qutepart/syntax/data/octave.xml diff --git a/qutepart/syntax/oors.xml b/qutepart/syntax/data/oors.xml similarity index 100% rename from qutepart/syntax/oors.xml rename to qutepart/syntax/data/oors.xml diff --git a/part/syntax/data/opal.xml b/qutepart/syntax/data/opal.xml similarity index 100% rename from part/syntax/data/opal.xml rename to qutepart/syntax/data/opal.xml diff --git a/part/syntax/data/pango.xml b/qutepart/syntax/data/pango.xml similarity index 100% rename from part/syntax/data/pango.xml rename to qutepart/syntax/data/pango.xml diff --git a/part/syntax/data/pascal.xml b/qutepart/syntax/data/pascal.xml similarity index 100% rename from part/syntax/data/pascal.xml rename to qutepart/syntax/data/pascal.xml diff --git a/qutepart/syntax/perl.xml b/qutepart/syntax/data/perl.xml similarity index 100% rename from qutepart/syntax/perl.xml rename to qutepart/syntax/data/perl.xml diff --git a/part/syntax/data/pgn.xml b/qutepart/syntax/data/pgn.xml similarity index 100% rename from part/syntax/data/pgn.xml rename to qutepart/syntax/data/pgn.xml diff --git a/qutepart/syntax/php.xml b/qutepart/syntax/data/php.xml similarity index 100% rename from qutepart/syntax/php.xml rename to qutepart/syntax/data/php.xml diff --git a/part/syntax/data/picsrc.xml b/qutepart/syntax/data/picsrc.xml similarity index 100% rename from part/syntax/data/picsrc.xml rename to qutepart/syntax/data/picsrc.xml diff --git a/qutepart/syntax/pig.xml b/qutepart/syntax/data/pig.xml similarity index 100% rename from qutepart/syntax/pig.xml rename to qutepart/syntax/data/pig.xml diff --git a/part/syntax/data/pike.xml b/qutepart/syntax/data/pike.xml similarity index 100% rename from part/syntax/data/pike.xml rename to qutepart/syntax/data/pike.xml diff --git a/part/syntax/data/postscript.xml b/qutepart/syntax/data/postscript.xml similarity index 100% rename from part/syntax/data/postscript.xml rename to qutepart/syntax/data/postscript.xml diff --git a/part/syntax/data/povray.xml b/qutepart/syntax/data/povray.xml similarity index 100% rename from part/syntax/data/povray.xml rename to qutepart/syntax/data/povray.xml diff --git a/part/syntax/data/progress.xml b/qutepart/syntax/data/progress.xml similarity index 100% rename from part/syntax/data/progress.xml rename to qutepart/syntax/data/progress.xml diff --git a/qutepart/syntax/prolog.xml b/qutepart/syntax/data/prolog.xml similarity index 100% rename from qutepart/syntax/prolog.xml rename to qutepart/syntax/data/prolog.xml diff --git a/part/syntax/data/purebasic.xml b/qutepart/syntax/data/purebasic.xml similarity index 100% rename from part/syntax/data/purebasic.xml rename to qutepart/syntax/data/purebasic.xml diff --git a/qutepart/syntax/python.xml b/qutepart/syntax/data/python.xml similarity index 100% rename from qutepart/syntax/python.xml rename to qutepart/syntax/data/python.xml diff --git a/qutepart/syntax/qmake.xml b/qutepart/syntax/data/qmake.xml similarity index 100% rename from qutepart/syntax/qmake.xml rename to qutepart/syntax/data/qmake.xml diff --git a/qutepart/syntax/qml.xml b/qutepart/syntax/data/qml.xml similarity index 100% rename from qutepart/syntax/qml.xml rename to qutepart/syntax/data/qml.xml diff --git a/qutepart/syntax/r.xml b/qutepart/syntax/data/r.xml similarity index 100% rename from qutepart/syntax/r.xml rename to qutepart/syntax/data/r.xml diff --git a/part/syntax/data/rapidq.xml b/qutepart/syntax/data/rapidq.xml similarity index 100% rename from part/syntax/data/rapidq.xml rename to qutepart/syntax/data/rapidq.xml diff --git a/qutepart/syntax/relaxng.xml b/qutepart/syntax/data/relaxng.xml similarity index 100% rename from qutepart/syntax/relaxng.xml rename to qutepart/syntax/data/relaxng.xml diff --git a/qutepart/syntax/relaxngcompact.xml b/qutepart/syntax/data/relaxngcompact.xml similarity index 100% rename from qutepart/syntax/relaxngcompact.xml rename to qutepart/syntax/data/relaxngcompact.xml diff --git a/qutepart/syntax/rest.xml b/qutepart/syntax/data/rest.xml similarity index 100% rename from qutepart/syntax/rest.xml rename to qutepart/syntax/data/rest.xml diff --git a/part/syntax/data/rexx.xml b/qutepart/syntax/data/rexx.xml similarity index 100% rename from part/syntax/data/rexx.xml rename to qutepart/syntax/data/rexx.xml diff --git a/part/syntax/data/rhtml.xml b/qutepart/syntax/data/rhtml.xml similarity index 100% rename from part/syntax/data/rhtml.xml rename to qutepart/syntax/data/rhtml.xml diff --git a/part/syntax/data/rib.xml b/qutepart/syntax/data/rib.xml similarity index 100% rename from part/syntax/data/rib.xml rename to qutepart/syntax/data/rib.xml diff --git a/part/syntax/data/roff.xml b/qutepart/syntax/data/roff.xml similarity index 100% rename from part/syntax/data/roff.xml rename to qutepart/syntax/data/roff.xml diff --git a/qutepart/syntax/rpmspec.xml b/qutepart/syntax/data/rpmspec.xml similarity index 100% rename from qutepart/syntax/rpmspec.xml rename to qutepart/syntax/data/rpmspec.xml diff --git a/part/syntax/data/rsiidl.xml b/qutepart/syntax/data/rsiidl.xml similarity index 100% rename from part/syntax/data/rsiidl.xml rename to qutepart/syntax/data/rsiidl.xml diff --git a/qutepart/syntax/ruby.xml b/qutepart/syntax/data/ruby.xml similarity index 100% rename from qutepart/syntax/ruby.xml rename to qutepart/syntax/data/ruby.xml diff --git a/part/syntax/data/sather.xml b/qutepart/syntax/data/sather.xml similarity index 100% rename from part/syntax/data/sather.xml rename to qutepart/syntax/data/sather.xml diff --git a/part/syntax/data/scala.xml b/qutepart/syntax/data/scala.xml similarity index 100% rename from part/syntax/data/scala.xml rename to qutepart/syntax/data/scala.xml diff --git a/part/syntax/data/scheme.xml b/qutepart/syntax/data/scheme.xml similarity index 100% rename from part/syntax/data/scheme.xml rename to qutepart/syntax/data/scheme.xml diff --git a/part/syntax/data/sci.xml b/qutepart/syntax/data/sci.xml similarity index 100% rename from part/syntax/data/sci.xml rename to qutepart/syntax/data/sci.xml diff --git a/qutepart/syntax/scss.xml b/qutepart/syntax/data/scss.xml similarity index 100% rename from qutepart/syntax/scss.xml rename to qutepart/syntax/data/scss.xml diff --git a/qutepart/syntax/sed.xml b/qutepart/syntax/data/sed.xml similarity index 100% rename from qutepart/syntax/sed.xml rename to qutepart/syntax/data/sed.xml diff --git a/part/syntax/data/sgml.xml b/qutepart/syntax/data/sgml.xml similarity index 100% rename from part/syntax/data/sgml.xml rename to qutepart/syntax/data/sgml.xml diff --git a/part/syntax/data/sieve.xml b/qutepart/syntax/data/sieve.xml similarity index 100% rename from part/syntax/data/sieve.xml rename to qutepart/syntax/data/sieve.xml diff --git a/part/syntax/data/sisu.xml b/qutepart/syntax/data/sisu.xml similarity index 100% rename from part/syntax/data/sisu.xml rename to qutepart/syntax/data/sisu.xml diff --git a/part/syntax/data/sml.xml b/qutepart/syntax/data/sml.xml similarity index 100% rename from part/syntax/data/sml.xml rename to qutepart/syntax/data/sml.xml diff --git a/qutepart/syntax/spice.xml b/qutepart/syntax/data/spice.xml similarity index 100% rename from qutepart/syntax/spice.xml rename to qutepart/syntax/data/spice.xml diff --git a/part/syntax/data/sql-mysql.xml b/qutepart/syntax/data/sql-mysql.xml similarity index 100% rename from part/syntax/data/sql-mysql.xml rename to qutepart/syntax/data/sql-mysql.xml diff --git a/part/syntax/data/sql-postgresql.xml b/qutepart/syntax/data/sql-postgresql.xml similarity index 100% rename from part/syntax/data/sql-postgresql.xml rename to qutepart/syntax/data/sql-postgresql.xml diff --git a/part/syntax/data/sql.xml b/qutepart/syntax/data/sql.xml similarity index 100% rename from part/syntax/data/sql.xml rename to qutepart/syntax/data/sql.xml diff --git a/qutepart/syntax/stata.xml b/qutepart/syntax/data/stata.xml similarity index 100% rename from qutepart/syntax/stata.xml rename to qutepart/syntax/data/stata.xml diff --git a/part/syntax/data/syntax.template b/qutepart/syntax/data/syntax.template similarity index 100% rename from part/syntax/data/syntax.template rename to qutepart/syntax/data/syntax.template diff --git a/qutepart/syntax/syntax_db.json b/qutepart/syntax/data/syntax_db.json similarity index 100% rename from qutepart/syntax/syntax_db.json rename to qutepart/syntax/data/syntax_db.json diff --git a/part/syntax/data/systemc.xml b/qutepart/syntax/data/systemc.xml similarity index 100% rename from part/syntax/data/systemc.xml rename to qutepart/syntax/data/systemc.xml diff --git a/qutepart/syntax/systemverilog.xml b/qutepart/syntax/data/systemverilog.xml similarity index 100% rename from qutepart/syntax/systemverilog.xml rename to qutepart/syntax/data/systemverilog.xml diff --git a/qutepart/syntax/tads3.xml b/qutepart/syntax/data/tads3.xml similarity index 100% rename from qutepart/syntax/tads3.xml rename to qutepart/syntax/data/tads3.xml diff --git a/qutepart/syntax/tcl.xml b/qutepart/syntax/data/tcl.xml similarity index 100% rename from qutepart/syntax/tcl.xml rename to qutepart/syntax/data/tcl.xml diff --git a/qutepart/syntax/tcsh.xml b/qutepart/syntax/data/tcsh.xml similarity index 100% rename from qutepart/syntax/tcsh.xml rename to qutepart/syntax/data/tcsh.xml diff --git a/part/syntax/data/texinfo.xml b/qutepart/syntax/data/texinfo.xml similarity index 100% rename from part/syntax/data/texinfo.xml rename to qutepart/syntax/data/texinfo.xml diff --git a/part/syntax/data/tibasic.xml b/qutepart/syntax/data/tibasic.xml similarity index 100% rename from part/syntax/data/tibasic.xml rename to qutepart/syntax/data/tibasic.xml diff --git a/part/syntax/data/txt2tags.xml b/qutepart/syntax/data/txt2tags.xml similarity index 100% rename from part/syntax/data/txt2tags.xml rename to qutepart/syntax/data/txt2tags.xml diff --git a/part/syntax/data/uscript.xml b/qutepart/syntax/data/uscript.xml similarity index 100% rename from part/syntax/data/uscript.xml rename to qutepart/syntax/data/uscript.xml diff --git a/qutepart/syntax/valgrind-suppression.xml b/qutepart/syntax/data/valgrind-suppression.xml similarity index 100% rename from qutepart/syntax/valgrind-suppression.xml rename to qutepart/syntax/data/valgrind-suppression.xml diff --git a/part/syntax/data/velocity.xml b/qutepart/syntax/data/velocity.xml similarity index 100% rename from part/syntax/data/velocity.xml rename to qutepart/syntax/data/velocity.xml diff --git a/qutepart/syntax/vera.xml b/qutepart/syntax/data/vera.xml similarity index 100% rename from qutepart/syntax/vera.xml rename to qutepart/syntax/data/vera.xml diff --git a/qutepart/syntax/verilog.xml b/qutepart/syntax/data/verilog.xml similarity index 100% rename from qutepart/syntax/verilog.xml rename to qutepart/syntax/data/verilog.xml diff --git a/part/syntax/data/vhdl.xml b/qutepart/syntax/data/vhdl.xml similarity index 100% rename from part/syntax/data/vhdl.xml rename to qutepart/syntax/data/vhdl.xml diff --git a/part/syntax/data/vrml.xml b/qutepart/syntax/data/vrml.xml similarity index 100% rename from part/syntax/data/vrml.xml rename to qutepart/syntax/data/vrml.xml diff --git a/part/syntax/data/winehq.xml b/qutepart/syntax/data/winehq.xml similarity index 100% rename from part/syntax/data/winehq.xml rename to qutepart/syntax/data/winehq.xml diff --git a/qutepart/syntax/wml.xml b/qutepart/syntax/data/wml.xml similarity index 100% rename from qutepart/syntax/wml.xml rename to qutepart/syntax/data/wml.xml diff --git a/part/syntax/data/xharbour.xml b/qutepart/syntax/data/xharbour.xml similarity index 100% rename from part/syntax/data/xharbour.xml rename to qutepart/syntax/data/xharbour.xml diff --git a/qutepart/syntax/xml.xml b/qutepart/syntax/data/xml.xml similarity index 100% rename from qutepart/syntax/xml.xml rename to qutepart/syntax/data/xml.xml diff --git a/part/syntax/data/xmldebug.xml b/qutepart/syntax/data/xmldebug.xml similarity index 100% rename from part/syntax/data/xmldebug.xml rename to qutepart/syntax/data/xmldebug.xml diff --git a/part/syntax/data/xorg.xml b/qutepart/syntax/data/xorg.xml similarity index 100% rename from part/syntax/data/xorg.xml rename to qutepart/syntax/data/xorg.xml diff --git a/part/syntax/data/xslt.xml b/qutepart/syntax/data/xslt.xml similarity index 100% rename from part/syntax/data/xslt.xml rename to qutepart/syntax/data/xslt.xml diff --git a/part/syntax/data/xul.xml b/qutepart/syntax/data/xul.xml similarity index 100% rename from part/syntax/data/xul.xml rename to qutepart/syntax/data/xul.xml diff --git a/part/syntax/data/yacas.xml b/qutepart/syntax/data/yacas.xml similarity index 100% rename from part/syntax/data/yacas.xml rename to qutepart/syntax/data/yacas.xml diff --git a/part/syntax/data/yacc.xml b/qutepart/syntax/data/yacc.xml similarity index 100% rename from part/syntax/data/yacc.xml rename to qutepart/syntax/data/yacc.xml diff --git a/part/syntax/data/yaml.xml b/qutepart/syntax/data/yaml.xml similarity index 100% rename from part/syntax/data/yaml.xml rename to qutepart/syntax/data/yaml.xml diff --git a/part/syntax/data/zonnon.xml b/qutepart/syntax/data/zonnon.xml similarity index 100% rename from part/syntax/data/zonnon.xml rename to qutepart/syntax/data/zonnon.xml diff --git a/qutepart/syntax/zsh.xml b/qutepart/syntax/data/zsh.xml similarity index 100% rename from qutepart/syntax/zsh.xml rename to qutepart/syntax/data/zsh.xml diff --git a/qutepart/syntax/desktop.xml b/qutepart/syntax/desktop.xml deleted file mode 100644 index c91e627..0000000 --- a/qutepart/syntax/desktop.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/diff.xml b/qutepart/syntax/diff.xml deleted file mode 100644 index eb63a52..0000000 --- a/qutepart/syntax/diff.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - -]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/doxygenlua.xml b/qutepart/syntax/doxygenlua.xml deleted file mode 100644 index 03fcdc9..0000000 --- a/qutepart/syntax/doxygenlua.xml +++ /dev/null @@ -1,481 +0,0 @@ - - -]> - - - - - - \arg - \attention - \author - \callgraph - \code - \dot - \else - \endcode - \endcond - \enddot - \endhtmlonly - \endif - \endlatexonly - \endlink - \endmanonly - \endverbatim - \endxmlonly - \f[ - \f] - \f$ - \hideinitializer - \htmlonly - \interface - \internal - \invariant - \~ - \@ - \$ - \\ - \# - \latexonly - \li - \manonly - \n - \nosubgrouping - \note - \only - \post - \pre - \remarks - \return - \returns - \sa - \see - \showinitializer - \since - \test - \todo - \verbatim - \warning - \xmlonly - - @arg - @attention - @author - @callgraph - @code - @dot - @else - @endcode - @endcond - @enddot - @endhtmlonly - @endif - @endlatexonly - @endlink - @endmanonly - @endverbatim - @endxmlonly - @f[ - @f] - @f$ - @hideinitializer - @htmlonly - @interface - @internal - @invariant - @~ - @@ - @$ - @\ - @# - @latexonly - @li - @manonly - @n - @nosubgrouping - @note - @only - @post - @pre - @remarks - @return - @returns - @sa - @see - @showinitializer - @since - @test - @todo - @verbatim - @warning - @xmlonly - - - - \addtogroup - \a - \anchor - \b - \c - \class - \cond - \copydoc - \def - \dontinclude - \dotfile - \e - \elseif - \em - \enum - \example - \exception - \exceptions - \file - \htmlinclude - \if - \ifnot - \include - \link - \namespace - \p - \package - \ref - \relatesalso - \relates - \retval - \throw - \throws - \verbinclude - \version - \xrefitem - - @addtogroup - @a - @anchor - @b - @c - @class - @cond - @copydoc - @def - @dontinclude - @dotfile - @e - @elseif - @em - @enum - @example - @exception - @exceptions - @file - @htmlinclude - @if - @ifnot - @include - @link - @namespace - @p - @package - @ref - @relatesalso - @relates - @retval - @throw - @throws - @verbinclude - @version - @xrefitem - - - \param - - @param - - - \image - - @image - - - \defgroup - \page - \paragraph - \section - \struct - \subsection - \subsubsection - \union - \weakgroup - - @defgroup - @page - @paragraph - @section - @struct - @subsection - @subsubsection - @union - @weakgroup - - - \addindex - \brief - \bug - \date - \deprecated - \fn - \ingroup - \line - \mainpage - \name - \overload - \par - \short - \skip - \skipline - \typedef - \until - \var - - @addindex - @brief - @bug - @date - @deprecated - @fn - @ingroup - @line - @mainpage - @name - @overload - @par - @short - @skip - @skipline - @typedef - @until - @var - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/dtd.xml b/qutepart/syntax/dtd.xml deleted file mode 100644 index 17914d1..0000000 --- a/qutepart/syntax/dtd.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - -]> - - - - - EMPTY - ANY - CDATA - ID - IDREF - IDREFS - NMTOKEN - NMTOKENS - ENTITY - ENTITIES - NOTATION - PUBLIC - SYSTEM - NDATA - - - - #PCDATA - #REQUIRED - #IMPLIED - #FIXED - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/eiffel.xml b/qutepart/syntax/eiffel.xml deleted file mode 100644 index 9998fd8..0000000 --- a/qutepart/syntax/eiffel.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - agent - alias - all - and - as - assign - class - convert - create - creation - debug - deferred - do - else - elseif - end - expanded - export - external - feature - from - frozen - if - implies - indexing - infix - inherit - inspect - is - like - local - loop - not - obsolete - old - once - or - prefix - pure - redefine - reference - rename - rescue - retry - separate - then - undefine - - - - Current - False - Precursor - Result - True - TUPLE - - - - check - ensure - require - variant - invariant - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/email.xml b/qutepart/syntax/email.xml deleted file mode 100644 index a3ef294..0000000 --- a/qutepart/syntax/email.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/erlang.xml b/qutepart/syntax/erlang.xml deleted file mode 100644 index cc3ea7c..0000000 --- a/qutepart/syntax/erlang.xml +++ /dev/null @@ -1,250 +0,0 @@ - - - - - - - - - -] -> - - - - - - - after - begin - case - catch - cond - end - fun - if - let - of - query - receive - all_true - some_true - - - - - div - rem - or - xor - bor - bxor - bsl - bsr - and - band - not - bnot - - - - - abs - accept - alarm - apply - atom_to_list - binary_to_list - binary_to_term - check_process_code - concat_binary - date - delete_module - disconnect_node - element - erase - exit - float - float_to_list - garbage_collect - get - get_keys - group_leader - halt - hd - integer_to_list - is_alive - is_atom - is_binary - is_boolean - is_float - is_function - is_integer - is_list - is_number - is_pid - is_port - is_process_alive - is_record - is_reference - is_tuple - length - link - list_to_atom - list_to_binary - list_to_float - list_to_integer - list_to_pid - list_to_tuple - load_module - loaded - localtime - make_ref - module_loaded - node - nodes - now - open_port - pid_to_list - port_close - port_command - port_connect - port_control - ports - pre_loaded - process_flag - process_info - processes - purge_module - put - register - registered - round - self - setelement - size - spawn - spawn_link - spawn_opt - split_binary - statistics - term_to_binary - throw - time - tl - trunc - tuple_to_list - unlink - unregister - whereis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/euphoria.xml b/qutepart/syntax/euphoria.xml deleted file mode 100644 index a1ca199..0000000 --- a/qutepart/syntax/euphoria.xml +++ /dev/null @@ -1,376 +0,0 @@ - - - - - - - - - - abort - allocate - allocate_string - allow_break - and - and_bits - append - arccos - arcsin - arctan - atom_to_float32 - atom_to_float64 - as - begin - bits_to_int - bytes_to_int - c_func - c_proc - call - call_back - call_func - call_proc - check_break - chdir - clear_screen - close - command_line - compare - cos - crash_file - crash_message - current_dir - custom_sort - date - define_c_func - define_c_proc - define_c_var - dir - display_text_image - do - else - elsif - end - equal - exit - find - float32_to_atom - float64_to_atom - floor - flush - for - free - free_console - function - get_bytes - get_key - get_mouse - get_position - get_screen_char - getc - getenv - gets - if - include - int_to_bits - int_to_bytes - length - lock_file - log - lower - machine_func - machine_proc - match - mem_copy - mem_set - mouse_events - mouse_pointer - not - not_bits - of - open - open_dll - or - or_bits - peek - peek4 - peek4s - peek4u - platform - poke - poke4 - position - power - prepend - print - printf - procedure - profile - prompt_number - prompt_string - put_screen_char - puts - rand - read_bitmap - register_block - remainder - repeat - return - reverse - routine_id - save_bitmap - save_text_image - scroll - seek - set_rand - sin - sleep - sort - sprint - sprintf - sqrt - system - system_exec - tan - text_color - then - time - to - trace - type - unlock_file - unregister_block - upper - value - video_config - wait_key - walk_dir - where - while - wildcard_file - wildcard_match - with - without - wrap - xor - xor_bits - ? - - - - atom - constant - global - integer - object - sequence - type - - - - PI - GET_SUCCESS - - - - addto - adjustment - alignment - appendto - append_page - arrow - aspect_frame - button - calendar - cell_renderer_text - cell_renderer_toggle - check - checkbutton - check_menu_item - choice - combo - connect - drawingarea - draw_arc - draw_image - draw_line - draw_polygon - draw_point - draw_rectangle - end_submenu - entry - euget - event_box - flatten - font - frame - get - getImage - getSize - g_list - g_list_to_sequence - deallocate_strings - draw_line - hbox - hbuttonbox - hpaned - hscrollbar - hseparator - hscale - idle_add - image - image_menu_item - init - label - limit - list_store - list_view - list_view_column - main - mark_day - menu - menubar - menu_item - mouse_button - new_gc - new_group - new_menu_group - notebook - option - option_menu - pack - path - pop - progress_bar - push - quit - radio - radiobutton - radio_menu_item - rc_parse - run - separator_menu_item - set - set_submenu - str - scrolled_window - seq_to_str - setfg - setProperty - show - spinbutton - statusbar - table - textbox - timer - togglebutton - toolbar - tooltip - tree_store - tree_view - tree_view_column - vbox - vbuttonbox - vpaned - vscale - vscrollbar - vseparator - when - window - NULL - TRUE - FALSE - color_selection - file_selection - font_selection_dialog - Error - Info - Question - Warn - YesNo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/ferite.xml b/qutepart/syntax/ferite.xml deleted file mode 100644 index 7d15482..0000000 --- a/qutepart/syntax/ferite.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - break - case - continue - else - for - if - do - function - namespace - while - class - new - uses - global - return - self - super - null - iferr - fix - - - number - void - string - array - object - final - static - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/fgl-4gl.xml b/qutepart/syntax/fgl-4gl.xml deleted file mode 100644 index 2acbe8f..0000000 --- a/qutepart/syntax/fgl-4gl.xml +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - at - by - go - if - in - is - no - of - on - or - to - up - - add - ALL - and - ANY - avg - day - end - ESC - for - key - let - log - max - mdy - min - not - put - red - row - run - set - sum - top - - blue - BOLD - call - case - cyan - desc - DROP - else - exit - file - form - FREE - from - goto - help - HIDE - HOLD - HOUR - into - last - left - like - line - load - LOCK - main - menu - MODE - name - NEED - next - null - open - page - PIPE - quit - READ - rows - show - skip - sort - STEP - STOP - TEMP - text - then - thru - true - user - WAIT - when - with - WORK - WRAP - year - - after - alter - ascii - BEGIN - blink - clear - close - count - DEFER - DIRTY - error - every - false - fetch - field - first - flush - green - GROUP - index - input - label - lines - month - order - outer - pause - print - right - share - sleep - space - start - TABLE - today - union - UNITS - using - where - WHILE - white - - ACCEPT - before - border - bottom - column - commit - create - cursor - define - delete - enable - ESCAPE - exists - finish - format - HAVING - header - insert - length - locate - margin - MINUTE - MODIFY - normal - option - output - PAGENO - prompt - record - report - return - revoke - SCREEN - scroll - SECOND - select - spaces - status - UNIQUE - UNLOAD - update - values - window - yellow - - between - clipped - cluster - columns - command - comment - connect - CURRENT - declare - display - execute - foreach - globals - infield - MAGENTA - matches - message - options - prepare - printer - program - reverse - trailer - upshift - waiting - without - - ABSOLUTE - continue - database - defaults - DISTINCT - EXTERNAL - function - INT_FLAG - NOTFOUND - previous - ROLLBACK - whenever - wordwrap - - attribute - committed - construct - delimiter - downshift - exclusive - INTERRUPT - ISOLATION - otherwise - quit_flag - returning - - attributes - CONSTRAINT - initialize - statistics - - fgl_lastkey - formhandler - - fgl_lastkey() - - - - - char - date - array - float - money - serial - DECIMAL - integer - NUMERIC - VARCHAR - DATETIME - FRACTION - INTERVAL - smallint - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/fgl-per.xml b/qutepart/syntax/fgl-per.xml deleted file mode 100644 index 9b3461a..0000000 --- a/qutepart/syntax/fgl-per.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - by - to - - end - not - red - - blue - cyan - keys - like - null - size - type - - black - color - green - input - today - white - - format - record - screen - tables - yellow - - default - display - include - magenta - noentry - picture - reverse - through - UPSHIFT - without - - autonext - comments - COMPRESS - database - formonly - noupdate - required - WORDWRAP - - character - downshift - invisible - underline - - attributes - delimiters - - instructions - - - char - date - array - float - money - serial - DECIMAL - integer - NUMERIC - VARCHAR - DATETIME - FRACTION - INTERVAL - smallint - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/find-trivial-regexpr.sh b/qutepart/syntax/find-trivial-regexpr.sh deleted file mode 100755 index b034f91..0000000 --- a/qutepart/syntax/find-trivial-regexpr.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# Copyright (C) 2008 Sebastian Pipping -grep 'RegExpr' * | grep --color=auto -E 'String=\s*(["'"'"'])'\ -'(\^(\\s[*+]?)?)?'\ -'('\ -'%?'\ -'('\ -'[a-zA-Z"'"'"'#_!§/=:;<>-]'\ -'|\\[\\\]\[()\{\}.$^+*?]'\ -'|[()|]'\ -'|\(\?:'\ -'|&(amp|gt|lt|apos|quot);'\ -')'\ -'|[0-9]'\ -')*%?'\ -'\1' diff --git a/qutepart/syntax/freebasic.xml b/qutepart/syntax/freebasic.xml deleted file mode 100644 index d3bf412..0000000 --- a/qutepart/syntax/freebasic.xml +++ /dev/null @@ -1,609 +0,0 @@ - - - - - - - #DEFINE - #ELSE - #ELSEIF - #ENDIF - #IF - #IFDEF - #IFNDEF - #UNDEF - $DYNAMIC - $INCLIB - $INCLUDE - $STATIC - - - - - Declare - - Open - - For - - For Input - For Output - For Binary - For Random - Close - - To - Step - Next - As - Break - Exit - If - Then - Else - Until - Select - System - Case - Default - EndSelect - Do - Loop - While - Wend - End - Type - DefType - Dim - Global - Function - Sub - Shared - Protected - Static - Declare - - Unsigned - - Data - Restore - Read - - - Goto - Gosub - Return - - DEFBYTE - DEFDBL - DEFINT - DEFLNG - DEFSHORT - DEFSNG - DEFSTR - DEFUBYTE - DEFUINT - DEFUSHORT - - - - - - - - AH - AL - AX - BH - BL - BP - BX - CH - CL - CS - CX - DH - DI - DL - DS - DX - EAX - EBP - EBX - ECX - EDI - EDX - ES - ESI - ESP - FS - GS - SI - SP - SS - - - - Integer - Long - Single - Double - String - Byte PTR - Dword PTR - Qword PTR - Word PTR - - - - AAA - AAD - AAM - AAS - ABS - ACOS - ADC - ADD - ALLOCATE - AND - AND - ARPL - ASC - ASIN - ASM - ATAN2 - ATN - BEEP - BIN$ - BLOAD - BOUND - BREAK - BSAVE - BSF - BSR - BSWAP - BT - BTC - BTR - BTS - BYREF - CALL - CALLOCATE - CALLS - CBW - CBYTE - CDBL - CDQ - CHAIN - CHDIR - CHR$ - CINT - CIRCLE - CLC - CLD - CLEAR - CLI - CLNG - CLOSE - CLTS - CMC - CMP - CMPS - CMPSB - CMPSD - CMPSW - CMPXCHG - COLOR - COMMAND$ - COMMON - CONST - CONTINUE - COS - CSHORT - CSIGN - CSNG - CUNSG - CURDIR$ - CVD - CVI - CVL - CVS - CWD - CWDE - DAA - DAS - DATA - DATE$ - DEALLOCATE - DEC - DIM - DIR$ - DIV - DRAW - END - ENTER - ENUM - ENVIRON - ENVIRON$ - EOF - EQV - ERASE - EXEC - EXEPATH - EXP - FIX - FLIP - FRE - FREEFILE - GET - GETKEY - GETMOUSE - HEX$ - HLT - IDIV - IMP - IMUL - IN - INC - INKEY$ - INP - INPUT - INPUT$ - INS - INSB - INSD - INSTR - INT - INT - INTO - INVD - INVLPG - IRET - IRETD - JA - JAE - JB - JBE - JC - JCXZ - JE - JECXZ - JG - JGE - JL - JLE - JMP - JNA - JNAE - JNB - JNBE - JNC - JNE - JNG - JNGE - JNL - JNLE - JNO - JNP - JNS - JNZ - JO - JP - JPE - JPO - JS - JUMP - JZ - KILL - LAHF - LAR - LBOUND - LCASE$ - LDS - LEA - LEAVE - LEAVED - LEAVEW - LEFT$ - LEN - LES - LET - LFS - LGDT - LGS - LIB - LIDT - LINE - LLDT - LMSW - LOC - LOCK - LOCK - LODS - LODSB - LODSD - LODSW - LOF - LOG - LOOPD - LOOPDE - LOOPDNE - LOOPDNZ - LOOPDZ - LOOPE - LOOPNE - LOOPNZ - LOOPW - LOOPWE - LOOPWNE - LOOPWNZ - LOOPWZ - LOOPZ - LSET - LSL - LSS - LTR - LTRIM$ - MID$ - MKD$ - MKDIR - MKI$ - MKL$ - MKS$ - MOD - MOV - MOVS - MOVSB - MOVSD - MOVSW - MOVSX - MOVZX - MUL - MULTIKEY - NAME - NEG - NOP - NOT - NOTHING - OCT$ - OPTION BASE - OPTION PRIVATE - OR - OUT - OUTS - OUTSB - OUTSD - OUTSW - PAINT - PALETTE - PCOPY - PEEK - PEEKI - PEEKS - PMAP - POINT - POKE - POKEI - POKES - POP - POPA - POPAD - POPF - POPFD - POS - PRESERVE - PRESET - PRINT - PRIVATE - PROCPTR - PSET - PTR - PUBLIC - PUSH - PUSHA - PUSHAD - PUSHF - PUSHFD - PUT - RANDOMIZE - RCL - RCR - REALLOCATE - REDIM - REM - REP - REPE - REPNE - REPNZ - REPZ - RESET - RET - RETURN - RGB - RIGHT$ - RMDIR - RND - ROL - ROR - RSET - RTRIM$ - RUN - SADD - SAHF - SAL - SAR - SBB - SCAS - SCASB - SCASD - SCASW - SCREEN - SCREENCOPY - SCREENINFO - SCREENLOCK - SCREENPTR - SCREENSET - SCREENUNLOCK - SEEK - SETA - SETAE - SETB - SETBE - SETC - SETDATE - SETE - SETENVIRON - SETG - SETGE - SETL - SETLE - SETNA - SETNAE - SETNB - SETNBE - SETNC - SETNE - SETNG - SETNGE - SETNL - SETNLE - SETNO - SETNP - SETNS - SETNZ - SETO - SETP - SETPE - SETPO - SETS - SETZ - SGDT - SGN - SHARED - SHELL - SHL - SHLD - SHR - SHRD - SIDT - SIN - SLDT - SLEEP - SMSW - SPACE$ - SQR - STATIC - STC - STD - STI - STOP - STOS - STOSB - STOSD - STOSW - STR - STR$ - STRING$ - SWAP - TAN - TEST - TIME$ - TIMER - TRIM$ - TYPE - UBOUND - UCASE$ - UNION - UNLOCK - VAL - VARPTR - VERR - VERW - VIEW - WAIT - WINDOWTITLE - WRITE - XADD - XCHG - XLAT - XLATB - XOR - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/fstab.xml b/qutepart/syntax/fstab.xml deleted file mode 100644 index c2e1b21..0000000 --- a/qutepart/syntax/fstab.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - ext2 - ext3 - fat - vfat - reiser - proc - none - sysfs - ntfs - umsdos - swap - minix - iso9660 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/gap.xml b/qutepart/syntax/gap.xml deleted file mode 100644 index 5579e28..0000000 --- a/qutepart/syntax/gap.xml +++ /dev/null @@ -1,7835 +0,0 @@ - - - - - - - - - - - - - break - continue - do - elif - else - - - - - - then - - - - - - and - fail - false - not - or - true - - - - - - in - local - rec - return - - - - mod - - - - AClosVecLib - AClosestVectorCombinationsMatFFEVecFFE - AClosestVectorCombinationsMatFFEVecFFECoords - AClosestVectorDriver - ANFAutomorphism - ANonReesCongruenceOfSemigroup - APolyProd - AbelianGroup - AbelianGroupCons - AbelianInvariants - AbelianInvariantsMultiplier - AbelianInvariantsNormalClosureFpGroup - AbelianInvariantsNormalClosureFpGroupRrs - AbelianInvariantsOfList - AbelianInvariantsSubgroupFpGroup - AbelianInvariantsSubgroupFpGroupMtc - AbelianInvariantsSubgroupFpGroupRrs - AbelianNumberField - AbelianNumberFieldByReducedGaloisStabilizerInfo - AbelianPQuotient - AbelianSubfactorAction - AbsAndIrredModules - AbsInt - AbsolutIrreducibleModules - AbsoluteIrreducibleModules - AbsoluteValue - AbstractWordTietzeWord - AbstractWordTzWord - ActingAlgebra - ActingDomain - Action - ActionAbelianCSPG - ActionHomomorphism - ActionHomomorphismAttr - ActionHomomorphismConstructor - ActionKernelExternalSet - ActionSubspacesElementaryAbelianGroup - ActorOfExternalSet - Add - AddAbelianRelator - AddCoeffs - AddCosetInfoStabChain - AddDictionary - AddEquationsSQ - AddGenerator - AddGenerators - AddGeneratorsExtendSchreierTree - AddGeneratorsGenimagesExtendSchreierTree - AddHashEntry - AddImage - AddImageNC - AddNaturalHomomorphismsPool - AddNormalizingElementPcgs - AddPageNumbersToSix - AddParagraphNumbersGapDocTree - AddRefinement - AddRelator - AddRootParseTree - AddRowVector - AddRule - AddRuleReduced - AddSet - AddToListEntries - AddVectorLTM - AddendumSCTable - AdditiveCoset - AdditiveElementAsMultiplicativeElement - AdditiveElementsAsMultiplicativeElementsFamily - AdditiveGroup - AdditiveGroupByGenerators - AdditiveInverse - AdditiveInverseAttr - AdditiveInverseImmutable - AdditiveInverseMutable - AdditiveInverseOp - AdditiveInverseSM - AdditiveInverseSameMutability - AdditiveMagma - AdditiveMagmaByGenerators - AdditiveMagmaWithInverses - AdditiveMagmaWithInversesByGenerators - AdditiveMagmaWithZero - AdditiveMagmaWithZeroByGenerators - AdditiveNeutralElement - AdditivelyActingDomain - AdjointAssociativeAlgebra - AdjointBasis - AdjointMatrix - AdjointModule - AffineAction - AffineActionByMatrixGroup - AffineActionLayer - AffineOperation - AffineOperationLayer - Agemo - AgemoAbove - AgemoOp - AlgExtElm - AlgExtEmbeddedPol - AlgExtFactSQFree - AlgExtSquareHensel - AlgFacUPrep - Algebra - AlgebraByGenerators - AlgebraByStructureConstants - AlgebraByStructureConstantsArg - AlgebraGeneralMappingByImages - AlgebraHomomorphismByImages - AlgebraHomomorphismByImagesNC - AlgebraWithOne - AlgebraWithOneByGenerators - AlgebraWithOneGeneralMappingByImages - AlgebraWithOneHomomorphismByImages - AlgebraWithOneHomomorphismByImagesNC - AlgebraicElementsFamilies - AlgebraicElementsFamily - AlgebraicExtension - AlgebraicPolynomialModP - AllBlocks - AllGroups - AllIrreducibleMonicPolynomialCoeffsOfDegree - AllIrreducibleMonicPolynomials - AllIrreducibleSolvableGroups - AllLibTomNames - AllModulesSQ - AllMonicPolynomialCoeffsOfDegree - AllPrimitiveGroups - AllSmallGroups - AllTransitiveGroups - AllowableSubgroup - Alpha - AlternatingDegree - AlternatingGroup - AlternatingGroupCons - AlternatingSubgroup - AntiSymmetricParts - Append - AppendCollectedList - AppendTo - ApplicableMethod - ApplicableMethodTypes - Apply - ApplyGeneratorsToPoint - ApplyGeneratorsToPointsList - ApplyRel - ApplySimpleReflection - ApplyToNodesParseTree - ApproxRational - ApproxRootBound - ApproximateRoot - ApproximateSuborbitsStabilizerPermGroup - ArithmeticElementCreator - Arrangements - ArrangementsA - ArrangementsK - AsAlgebra - AsAlgebraWithOne - AsBinaryRelationOnPoints - AsBlockMatrix - AsCharacterMorphismFunction - AsDivisionRing - AsDuplicateFreeList - AsFLMLOR - AsFLMLORWithOne - AsField - AsFreeLeftModule - AsGroup - AsGroupGeneralMappingByImages - AsInducedPcgs - AsLeftIdeal - AsLeftMagmaIdeal - AsLeftModule - AsLeftModuleGeneralMappingByImages - AsLieAlgebra - AsList - AsListOfFreeLeftModule - AsListSorted - AsMagma - AsMagmaIdeal - AsMonoid - AsNearRing - AsPerm - AsPlist - AsPolynomial - AsRightIdeal - AsRightMagmaIdeal - AsRing - AsSSortedList - AsSSortedListList - AsSSortedListNonstored - AsSemigroup - AsSemiring - AsSemiringWithOne - AsSemiringWithOneAndZero - AsSemiringWithZero - AsSet - AsSortedList - AsSubFLMLOR - AsSubFLMLORWithOne - AsSubalgebra - AsSubalgebraWithOne - AsSubgroup - AsSubgroupOfWholeGroupByQuotient - AsSubmagma - AsSubmonoid - AsSubsemigroup - AsSubspace - AsTransformation - AsTransformationNC - AsTwoSidedIdeal - AsVectorSpace - AscendingChain - AscendingChainOp - Assert - AssertionLevel - AssignGeneratorVariables - AssignNiceMonomorphismAutomorphismGroup - AssocBWorLetRepPow - AssocWWorLetRepPow - AssocWord - AssocWordByLetterRep - AssociatedPartition - AssociatedReesMatrixSemigroupOfDClass - AssociatedSemigroup - Associates - AtlasIrrationality - AttributeMethodByNiceMonomorphism - AttributeMethodByNiceMonomorphismCollColl - AttributeMethodByNiceMonomorphismCollElm - AttributeMethodByNiceMonomorphismElmColl - AttributeValueNotSet - AugmentationIdeal - AugmentedCosetTableInWholeGroup - AugmentedCosetTableMtc - AugmentedCosetTableMtcInWholeGroup - AugmentedCosetTableNormalClosure - AugmentedCosetTableNormalClosureInWholeGroup - AugmentedCosetTableRrs - AugmentedCosetTableRrsInWholeGroup - AutoloadPackages - AutomorphismDomain - AutomorphismGroup - AutomorphismGroupAbelianGroup - AutomorphismGroupElAbGroup - AutomorphismGroupFrattFreeGroup - AutomorphismGroupPermGroup - AutomorphismGroupSolvableGroup - AutomorphismRepresentingGroup - AutomorphismsOfTable - AvoidedLayers - BPolyProd - BagStats - BarPartitions - BaseFixedSpace - BaseImage - BaseIntMat - BaseIntersectionIntMats - BaseMat - BaseMatDestructive - BaseOfBasicImageGroup - BaseOfElt - BaseOfGroup - BaseOrthogonalSpaceMat - BasePoint - BasePointOfSchreierTransversal - BaseShortVectors - BaseStabChain - BaseSteinitzVectors - BasicImageEltRepFamily - BasicImageGroup - BasicImageGroupElement - BasicWreathProductOrdering - BasicWreathProductOrderingNC - Basis - BasisForFreeModuleByNiceBasis - BasisNC - BasisNullspaceModN - BasisOfAlgebraModule - BasisOfHomCosetAddMatrixGroup - BasisOfHomCosetAddMatrixGroupFnc - BasisOfMonomialSpace - BasisOfSparseRowSpace - BasisOfWeightRepSpace - BasisVectors - BasisVectorsForMatrixAction - BasisWithReplacedLeftModule - BaumClausenInfo - BaumClausenInfoDebug - BeauzamyBound - BeauzamyBoundGcd - Bell - Bernoulli - BestQuoInt - BestSplittingMatrix - BetaSet - BiAlgebraModule - BiAlgebraModuleByGenerators - BilinearFormMat - BinaryRelationByElements - BinaryRelationByListOfImages - BinaryRelationByListOfImagesNC - BinaryRelationOnPoints - BinaryRelationOnPointsNC - BinaryRelationTransformation - BindGlobal - Binomial - BlistList - BlistStringDecode - BlockMatrix - BlockStabilizer - Blocks - BlocksAttr - BlocksInfo - BlocksOp - BlowUpCocycleSQ - BlowUpIsomorphism - BlownUpMat - BlownUpMatrix - BlownUpModule - BlownUpVector - BombieriNorm - BooleanFamily - BrauerCharacterValue - BrauerTable - BrauerTableOp - BravaisGroup - BravaisSubgroups - BravaisSupergroups - BuildIsomorphismReesMatrixSemigroupWithMap - CIUnivPols - COAffineBlocks - COComplements - COComplementsMain - CONextCentral - CONextCentralizer - CONextCocycles - CONextComplements - CalcDoubleCosets - CalcOrder - CallFuncList - CallFuncTrapError - CanComputeIndex - CanComputeIsSubset - CanComputeSize - CanComputeSizeAnySubgroup - CanEasilyCompareElements - CanEasilyCompareElementsFamily - CanEasilyComputePcgs - CanEasilySortElements - CanEasilySortElementsFamily - CanEasilyTestMembership - CanFindGeneratorOfCyclicGroup - CanFindNilpotentClassTwoElement - CanonicalBasis - CanonicalElt - CanonicalGenerators - CanonicalNiceMonomorphism - CanonicalPcElement - CanonicalPcgs - CanonicalPcgsByGeneratorsWithImages - CanonicalPcgsWrtFamilyPcgs - CanonicalPcgsWrtHomePcgs - CanonicalPcgsWrtSpecialPcgs - CanonicalRelator - CanonicalRepresentativeDeterminatorOfExternalSet - CanonicalRepresentativeOfExternalSet - CanonicalRightCosetElement - CanonicalSubgroupRepresentativePcGroup - CartanMatrix - CartanSubalgebra - Cartesian - CasesCSPG - CategoriesOfObject - CategoryCollections - CategoryFamily - CayleyGraphDualSemigroup - CayleyGraphSemigroup - Cell - CellNoPoint - CellNoPoints - Cells - Center - CenterOfCharacter - CentralCharacter - CentralIdempotentsOfAlgebra - CentralIdempotentsOfSemiring - CentralNormalSeriesByPcgs - CentralProductOfMatrixGroups - CentralRelations - CentralStelClEANSNonsolv - CentralStepClEANS - CentralStepConjugatingElement - CentralStepRatClPGroup - Centralizer - CentralizerInAssociativeGaussianMatrixAlgebra - CentralizerInFiniteDimensionalAlgebra - CentralizerInGLnZ - CentralizerInParent - CentralizerModulo - CentralizerNormalCSPG - CentralizerNormalTransCSPG - CentralizerOp - CentralizerOrder - CentralizerSizeLimitConsiderFunction - CentralizerSolvableGroup - CentralizerTransSymmCSPG - CentralizerWreath - Centre - CentreFromSCTable - CentreOfCharacter - CentrePcGroup - ChaNuPol - ChainHomomorphicImage - ChainStatistics - ChainSubgroup - ChainSubgroupByDirectProduct - ChainSubgroupByHomomorphism - ChainSubgroupByPSubgroupOfAbelian - ChainSubgroupByProjectionFunction - ChainSubgroupBySiftFunction - ChainSubgroupByStabiliser - ChainSubgroupByStabilizer - ChainSubgroupByTrivialSubgroup - ChainSubgroupQuotient - ChangeStabChain - ChangeTypeObj - ChangedBaseGroup - CharTableAlternating - CharTableDoubleCoverAlternating - CharTableDoubleCoverSymmetric - CharTableSymmetric - CharTableWeylB - CharTableWeylD - CharValueDoubleCoverSymmetric - CharValueSymmetric - CharValueWeylB - CharValueWreathSymmetric - Character - CharacterDegreePool - CharacterDegrees - CharacterMorphismGroup - CharacterMorphismOrbits - CharacterNames - CharacterParameters - CharacterString - CharacterTable - CharacterTableDirectProduct - CharacterTableDisplayPrintLegendDefault - CharacterTableDisplayStringEntryDataDefault - CharacterTableDisplayStringEntryDefault - CharacterTableFactorGroup - CharacterTableFromLibrary - CharacterTableHeadOfFactorGroupByFusion - CharacterTableIsoclinic - CharacterTableOfNormalSubgroup - CharacterTableQuaternionic - CharacterTableRegular - CharacterTableWithSortedCharacters - CharacterTableWithSortedClasses - CharacterTableWreathSymmetric - Characteristic - CharacteristicPolynomial - CharacteristicPolynomialMatrixNC - CharsFamily - CheckAndCleanGapDocTree - CheckAuto - CheckCompletionFiles - CheckConsistencyOfDefinitions - CheckCosetTableFpGroup - CheckFixedPoints - CheckForHandlingByNiceBasis - CheckGlobalName - CheckPackageLoading - CheckPermChar - CheckSchreierTreeInternalConsistency - ChevalleyBasis - ChiefNormalSeriesByPcgs - ChiefSeries - ChiefSeriesOfGroup - ChiefSeriesThrough - ChiefSeriesUnderAction - ChineseRem - Chomp - ChooseNextBasePoint - ClassComparison - ClassElementLargeGroup - ClassElementLattice - ClassElementSmallGroup - ClassFunction - ClassFunctionSameType - ClassMultiplicationCoefficient - ClassNames - ClassNamesTom - ClassNumbersElements - ClassOrbit - ClassParameters - ClassPermutation - ClassPositionsOfAgemo - ClassPositionsOfCentre - ClassPositionsOfDerivedSubgroup - ClassPositionsOfDirectProductDecompositions - ClassPositionsOfElementaryAbelianSeries - ClassPositionsOfFittingSubgroup - ClassPositionsOfKernel - ClassPositionsOfLowerCentralSeries - ClassPositionsOfMaximalNormalSubgroups - ClassPositionsOfNormalClosure - ClassPositionsOfNormalSubgroup - ClassPositionsOfNormalSubgroups - ClassPositionsOfSolvableResiduum - ClassPositionsOfSupersolvableResiduum - ClassPositionsOfUpperCentralSeries - ClassRepsPermutedTuples - ClassRoots - ClassStructureCharTable - ClassTypesTom - ClassesSolvableGroup - CleanedTailPcElement - ClearCacheStats - ClearCentralRelations - ClearDefinitionNC - ClearPQuotientStatistics - ClearProfile - CloseMutableBasis - CloseNaturalHomomorphismsPool - CloseStream - ClosedStreamType - ClosureAdditiveGroup - ClosureAdditiveMagmaDefault - ClosureAdditiveMagmaWithInverses - ClosureAlgebra - ClosureDivisionRing - ClosureField - ClosureGroup - ClosureGroupAddElm - ClosureGroupCompare - ClosureGroupDefault - ClosureGroupIntest - ClosureLeftModule - ClosureLeftOperatorRing - ClosureMagmaDefault - ClosureNearAdditiveGroup - ClosureNearAdditiveMagmaWithInverses - ClosureRandomPermGroup - ClosureRing - ClosureSemiring - ClosureSubgroup - ClosureSubgroupNC - CntOp - CoKernel - CoKernelGensIterator - CoKernelGensPermHom - CoKernelOfAdditiveGeneralMapping - CoKernelOfMultiplicativeGeneralMapping - CoSuFp - Coboundaries - CocGroup - Cochain - CochainSpace - CocycleSQ - CocycleToRelVector - Cocycles - CodeGenerators - CodePcGroup - CodePcgs - CoefficientTaylorSeries - Coefficients - CoefficientsAndMagmaElements - CoefficientsFamily - CoefficientsMultiadic - CoefficientsOfLaurentPolynomial - CoefficientsOfUnivariateLaurentPolynomial - CoefficientsOfUnivariatePolynomial - CoefficientsOfUnivariateRationalFunction - CoefficientsOfVector - CoefficientsQadic - CoefficientsRing - CoeffsCyc - CoeffsMod - CollFamRangeEqFamElms - CollFamSourceEqFamElms - CollapsedMat - CollectPolycyclic - CollectUEALatticeElement - CollectWord - CollectWordOrFail - Collected - CollectedPartition - CollectedWordSQ - CollectionsFamily - CollectorSQ - ColorPrompt - ColumnIndexOfReesMatrixSemigroupElement - ColumnIndexOfReesZeroMatrixSemigroupElement - ColumnsOfReesMatrixSemigroup - ColumnsOfReesZeroMatrixSemigroup - Combinations - CombinationsA - CombinationsK - CombinatorialCollector - CombinatorialCollectorByGenerators - CombinatoricSplit - Comm - CommutGenImgs - CommutativeDiagram - CommutatorFactorGroup - CommutatorLength - CommutatorSubgroup - Compacted - CompanionMat - CompareVersionNumbers - CompatibleConjugacyClasses - CompatibleConjugacyClassesDefault - CompatiblePairs - CompileFunc - ComplementIntMat - ComplementSystem - Complementclasses - ComplementclassesEA - ComplementclassesSolvableNC - ComplementclassesSolvableWBG - CompleteChain - CompleteGaloisGroupPElement - CompleteOrdersOfRws - CompleteSchreierTransversal - CompletionBar - ComplexConjugate - ComplexificationQuat - ComponentsOfTuplesFamily - ComposedXMLString - CompositionMapping - CompositionMaps - CompositionOfStraightLinePrograms - CompositionSeries - Compress - ComputeTails - ComputedAgemos - ComputedAscendingChains - ComputedBrauerTables - ComputedClassFusions - ComputedCyclicExtensionsTom - ComputedHallSubgroups - ComputedIndicators - ComputedIsPNilpotents - ComputedIsPSolvableCharacterTables - ComputedIsPSolvables - ComputedOmegas - ComputedPCentralSeriess - ComputedPCores - ComputedPRumps - ComputedPowerMaps - ComputedPrimeBlockss - ComputedSylowComplements - ComputedSylowSubgroups - ConcatSubos - Concatenation - Conductor - ConfluentRws - Congruences - ConjugacyClass - ConjugacyClassSubgroups - ConjugacyClasses - ConjugacyClassesByOrbits - ConjugacyClassesByRandomSearch - ConjugacyClassesFittingFreeGroup - ConjugacyClassesForSmallGroup - ConjugacyClassesMaximalSubgroups - ConjugacyClassesOfNaturalGroup - ConjugacyClassesPerfectSubgroups - ConjugacyClassesSubgroups - ConjugacyClassesSubwreath - ConjugacyClassesTry - ConjugacyClassesViaRadical - ConjugateDominantWeight - ConjugateDominantWeightWithWord - ConjugateGroup - ConjugateMatrixActionToLinearAction - ConjugateMatrixGroupToLinearAction - ConjugateMatrixGroupToLinearGroup - ConjugateStabChain - ConjugateSubgroup - ConjugateSubgroups - ConjugatedModule - Conjugates - ConjugatingElement - ConjugatorAutomorphism - ConjugatorAutomorphismNC - ConjugatorInnerAutomorphism - ConjugatorIsomorphism - ConjugatorOfConjugatorIsomorphism - ConnectGroupAndCharacterTable - ConsiderKernels - ConsiderSmallerPowerMaps - ConsiderStructureConstants - ConsiderTableAutomorphisms - ConstantInBaseRingPol - ConstantTimeAccessList - ConstituentsCompositionMapping - ConstituentsOfCharacter - ConstituentsPolynomial - ContainedCharacters - ContainedDecomposables - ContainedMaps - ContainedPossibleCharacters - ContainedPossibleVirtualCharacters - ContainedSpecialVectors - ContainedTom - ContainingTom - ContinuedFractionApproximationOfRoot - ContinuedFractionExpansionOfRoot - ConvertBasicImageGroupElement - ConvertToCharacterTable - ConvertToCharacterTableNC - ConvertToLibTom - ConvertToLibraryCharacterTableNC - ConvertToMatrixRep - ConvertToMatrixRepNC - ConvertToNormalFormMonomialElement - ConvertToRangeRep - ConvertToSiftGroup - ConvertToStringRep - ConvertToTableOfMarks - ConvertToVectorRep - ConvertToVectorRepNC - ConwayCandidates - ConwayPol - ConwayPolynomial - CopiedAugmentedCosetTable - CopyMappingAttributes - CopyOptionsDefaults - CopyRel - CopyStabChain - Core - CoreInParent - CoreOp - CorestEval - CorrectConjugacyClass - CorrespondingGeneratorsByModuloPcgs - CorrespondingPermutations - CosetLeadersInner - CosetLeadersMatFFE - CosetNumber - CosetRepAsWord - CosetTable - CosetTableBySubgroup - CosetTableDefaultLimit - CosetTableDefaultMaxLimit - CosetTableFpHom - CosetTableFromGensAndRels - CosetTableInWholeGroup - CosetTableNormalClosure - CosetTableNormalClosureInWholeGroup - CosetTableOfFpSemigroup - CosetTableStandard - CoveringTriplesCharacters - CrcFile - CreateAllCycleStructures - CreateCompletionFiles - CreateKnuthBendixRewritingSystem - CreateOrderingByLtFunction - CreateOrderingByLteqFunction - CrystGroupDefaultAction - CurrentAssertionLevel - CycList - Cycle - CycleByPosOp - CycleIndex - CycleIndexOp - CycleLength - CycleLengthOp - CycleLengthPermInt - CycleLengths - CycleLengthsOp - CycleOp - CyclePermInt - CycleStructureClass - CycleStructurePerm - CycleStructuresGroup - Cycles - CyclesOp - CyclicExtensionsTom - CyclicExtensionsTomOp - CyclicGroup - CyclicGroupCons - CyclicTopExtensions - CyclotomicField - CyclotomicPol - CyclotomicPolynomial - Cyclotomics - CyclotomicsFamily - DMYDay - DMYhmsSeconds - DTCommutator - DTConjugate - DTMultiply - DTPower - DTQuotient - DTSolution - DataObj - DataType - DayDMY - DaysInMonth - DaysInYear - DeclareAttribute - DeclareAttributeKernel - DeclareAttributeSuppCT - DeclareAutoPackage - DeclareAutoreadableVariables - DeclareCategory - DeclareCategoryCollections - DeclareCategoryFamily - DeclareCategoryKernel - DeclareComponent - DeclareConstructor - DeclareConstructorKernel - DeclareFilter - DeclareGlobalFunction - DeclareGlobalVariable - DeclareHandlingByNiceBasis - DeclareInfoClass - DeclareOperation - DeclareOperationKernel - DeclarePackage - DeclarePackageAutoDocumentation - DeclarePackageDocumentation - DeclareProperty - DeclarePropertyKernel - DeclarePropertySuppCT - DeclareRepresentation - DeclareRepresentationKernel - DeclareSynonym - DeclareSynonymAttr - DecodeTree - DecodedTreeEntry - DecomposeEltIntoPElts - DecomposeTensorProduct - DecomposedFixedPointVector - DecomposedRationalClass - Decomposition - DecompositionInt - DecompositionMatrix - DecompositionTypes - DecompositionTypesOfGroup - Decreased - DeepThoughtCollector - DeepThoughtCollectorByGenerators - DefaultField - DefaultFieldByGenerators - DefaultFieldOfMatrix - DefaultFieldOfMatrixGroup - DefaultHashLength - DefaultPackageBannerString - DefaultRing - DefaultRingByGenerators - DefaultSparseHashRepType - DefaultSparseHashWithIKRepType - DefaultStabChainOptions - DefectApproximation - DefineNewGenerators - DefiningPcgs - DefiningPolynomial - DefiningQuotientHomomorphism - Degree - DegreeAction - DegreeFFE - DegreeIndeterminate - DegreeNaturalHomomorphismsPool - DegreeOfBinaryRelation - DegreeOfCharacter - DegreeOfLaurentPolynomial - DegreeOfMatrixGroup - DegreeOfTransformation - DegreeOfTransformationSemigroup - DegreeOfUnivariateLaurentPolynomial - DegreeOperation - DegreeOverPrimeField - DeleteImage - Delta - DenominatorCyc - DenominatorOfModuloPcgs - DenominatorOfRationalFunction - DenominatorRat - DenseHashTable - DenseIntKey - DepthOfPcElement - DepthOfUpperTriangularMatrix - DepthSchreierTrees - Derangements - DerangementsK - Derivations - Derivative - DerivedLength - DerivedSeries - DerivedSeriesOfGroup - DerivedSubgroup - DerivedSubgroupTom - DerivedSubgroupsTom - DerivedSubgroupsTomPossible - DerivedSubgroupsTomUnique - DescendingListWithElementRemoved - DescriptionOfNormalizedUEAElement - DescriptionOfRootOfUnity - Determinant - DeterminantIntMat - DeterminantMat - DeterminantMatDestructive - DeterminantMatDivFree - DeterminantOfCharacter - DiagonalMat - DiagonalOfMat - DiagonalSocleAction - DiagonalizeIntMat - DiagonalizeIntMatNormDriven - DiagonalizeMat - DictionariesFamily - DictionaryByList - DictionaryByPosition - DictionaryBySort - DiffCoc - Difference - DifferenceBlist - DifferenceLists - DifferenceOfPcElement - DigitsNumber - DihedralGenerators - DihedralGroup - DihedralGroupCons - Dimension - DimensionOfHighestWeightModule - DimensionOfMatrixGroup - DimensionOfVectors - DimensionsLoewyFactors - DimensionsMat - DirProdTransversal - DirectFactorsOfGroup - DirectProduct - DirectProductDecompositionsLocal - DirectProductInfo - DirectProductOp - DirectSumDecomposition - DirectSumMat - DirectSumOfAlgebraModules - DirectSumOfAlgebras - DirectoriesFamily - DirectoriesLibrary - DirectoriesPackageLibrary - DirectoriesPackagePrograms - DirectoriesSystemPrograms - Directory - DirectoryContents - DirectoryCurrent - DirectoryTemporary - DirectoryType - DisableAttributeValueStoring - Discriminant - Display - DisplayCacheStats - DisplayCompositionSeries - DisplayEggBoxOfDClass - DisplayImfInvariants - DisplayImfReps - DisplayInformationPerfectGroups - DisplayOptions - DisplayOptionsStack - DisplayProfile - DisplayRevision - DisplaySemigroup - DisplayXMLStructure - DistVecClosVecLib - DistanceVecFFE - DistancesDistributionMatFFEVecFFE - DistancesDistributionVecFFEsVecFFE - DivisionRingByGenerators - DivisorsInt - DivisorsIntCache - DixonInit - DixonRecord - DixonRepChi - DixonRepGHchi - DixonSplit - DixontinI - DnLattice - DnLatticeIterative - DoAlgebraicExt - DoCentralSeriesPcgsIfNilpot - DoCheapActionImages - DoCheapOperationImages - DoClosurePrmGp - DoEASLS - DoExponentsConjLayerFampcgs - DoFactorCosetAction - DoGaloisType - DoImmutableMatrix - DoInducedPcgsByPcSequenceNC - DoLogModRho - DoLowIndexSubgroupsFpGroup - DoMulExt - DoNFIM - DoNormalClosurePermGroup - DoNormalizerSA - DoPcgsElementaryAbelianSeries - DoPcgsOrbitOp - DoPrintUnivariateLaurent - DoReadPkg - DoRereadPkg - DoRightTransversalPc - DoShortwordBasepoint - DoSnAnGiantTest - DoSparseActionHomomorphism - DoSparseLinearActionOnFaithfulSubset - DoTest - DoUnivTestRatfun - Domain - DomainByGenerators - DomainForAction - DominantCharacter - DominantWeights - DoubleCentralizerOrbit - DoubleCoset - DoubleCosetRepsAndSizes - DoubleCosets - DoubleCosetsNC - DoubleCosetsPcGroup - DoubleHashArraySize - DoubleHashDictSize - DownEnv - DualGModule - DumpWorkspace - DuplicateFreeList - DxActiveCols - DxCalcAllPowerMaps - DxCalcPrimeClasses - DxDegreeCandidates - DxEigenbase - DxFrobSchurInd - DxGaloisOrbits - DxGeneratePrimeCyclotomic - DxIncludeIrreducibles - DxIsInSpace - DxLiftCharacter - DxLinearCharacters - DxModProduct - DxModularValuePol - DxNiceBasis - DxPreparation - DxRegisterModularChar - DxSplitDegree - EANormalSeriesByPcgs - EAPrimeLayerSQ - ERepAssWorInv - ERepAssWorProd - ERepLettWord - Earns - Edit - EggBoxOfDClass - EichlerTransformation - Eigenspaces - Eigenvalues - EigenvaluesChar - Eigenvectors - ElementByRws - ElementOfFpAlgebra - ElementOfFpGroup - ElementOfFpMonoid - ElementOfFpSemigroup - ElementOfMagmaRing - ElementOrdersPowerMap - ElementProperty - ElementTestFunction - ElementaryAbelianGroup - ElementaryAbelianGroupCons - ElementaryAbelianSeries - ElementaryAbelianSeriesLargeSteps - ElementaryAbelianSubseries - ElementaryDivisorsMat - ElementaryDivisorsMatDestructive - Elements - ElementsFamily - ElementsStabChain - EliminatedWord - EliminationOrdering - ElmDivRingElm - ElmTimesRingElm - ElmWPObj - ElsymsPowersums - Embedding - EmptyBinaryRelation - EmptyMatrix - EmptyRBase - EmptyRowVector - EmptySCTable - EmptyStabChain - EmptyTuplesFamily - EnableAttributeValueStoring - End - EndoMappingByTransformation - EnumerateIndependentAbelianProducts - Enumerator - EnumeratorByBasis - EnumeratorByFunctions - EnumeratorByPcgs - EnumeratorOfAdditiveMagma - EnumeratorOfGroup - EnumeratorOfIdeal - EnumeratorOfMagma - EnumeratorOfMagmaIdeal - EnumeratorOfNormedRowVectors - EnumeratorOfPrimeField - EnumeratorOfRing - EnumeratorOfSemigroupIdeal - EnumeratorOfSubset - EnumeratorOfTrivialAdditiveMagmaWithZero - EnumeratorOfTrivialMagmaWithOne - EnumeratorOfTuples - EnumeratorOfZmodnZ - EnumeratorSorted - EnvelopingAlgebra - EpiPcByModpcgs - EpimorphismNilpotentQuotient - EpimorphismNilpotentQuotientOp - EpimorphismPGroup - EpimorphismQuotientSystem - EpimorphismSchurCover - EqualBoxedObj - EquivalenceClassOfElement - EquivalenceClassOfElementNC - EquivalenceClassRelation - EquivalenceClasses - EquivalenceRelationByPairs - EquivalenceRelationByPairsNC - EquivalenceRelationByPartition - EquivalenceRelationByPartitionNC - EquivalenceRelationByProperty - EquivalenceRelationByRelation - EquivalenceRelationPartition - EquivalenceType - Error - ErrorCount - EspaceBasePoints - EuclideanDegree - EuclideanQuotient - EuclideanRemainder - EulerianFunction - EulerianFunctionByTom - EvalF - EvalFpCoc - EvalStraightLineProgElm - EvalString - EvaluateConsistency - EvaluateOverlapANA - EvaluateOverlapBAN - EvaluateOverlapBNA - EvaluateOverlapCBA - EvaluateRelation - EvaluateRelators - EvectBasePoints - ExactSizeConsiderFunction - ExcludeFromAutoload - ExcludedOrders - Exec - ExecuteProcess - ExpPcElmSortedFun - Exponent - ExponentOfPcElement - ExponentOfPowering - ExponentSumWord - ExponentSums - ExponentSyllable - ExponentsConjugateLayer - ExponentsOfCommutator - ExponentsOfConjugate - ExponentsOfPcElement - ExponentsOfPcElementPermGroup - ExponentsOfRelativePower - ExportToKernelFinished - ExtOrbStabDom - ExtRepByTailVector - ExtRepDenominatorRatFun - ExtRepNumeratorRatFun - ExtRepOfObj - ExtRepPolynomialRatFun - ExtendRepresentation - ExtendSchreierTransversal - ExtendSchreierTransversalShortCube - ExtendSchreierTransversalShortTree - ExtendSeriesPermGroup - ExtendStabChain - ExtendToBasis - ExtendedGroup - ExtendedIntersectionSumPcgs - ExtendedPcgs - ExtendedT - ExtendedVectors - Extension - ExtensionNC - ExtensionOnBlocks - ExtensionRepresentatives - ExtensionSQ - Extensions - ExtensionsOfModule - ExteriorPower - ExteriorPowerOfAlgebraModule - ExternalOrbit - ExternalOrbitOp - ExternalOrbits - ExternalOrbitsStabilizers - ExternalSet - ExternalSetByFilterConstructor - ExternalSetByTypeConstructor - ExternalSubset - ExternalSubsetOp - Extract - ExtraspecialGroup - ExtraspecialGroupCons - FFEFamily - FFPFactors - FFPOrderKnownDividend - FFPPowerModCheck - FFPUpperBoundOrder - FLMLORByGenerators - FLMLORFromFFE - FLMLORWithOne - FLMLORWithOneByGenerators - FMRRemoveZero - FactorCosetAction - FactorCosetOperation - FactorFreeAlgebraByRelators - FactorFreeGroupByRelators - FactorFreeMonoidByRelations - FactorFreeSemigroupByRelations - FactorGroup - FactorGroupFpGroupByRels - FactorGroupNC - FactorGroupNormalSubgroupClasses - FactorGroupTom - FactorSemigroup - FactorSemigroupByClosure - Factorial - Factorization - Factors - FactorsCommonDegreePol - FactorsInt - FactorsOfDirectProduct - FactorsRho - FactorsSquarefree - FaithfulModule - FamElmEqFamRange - FamElmEqFamSource - FamMapFamSourceFamRange - FamRangeEqFamElm - FamRangeNotEqFamElm - FamSourceEqFamElm - FamSourceNotEqFamElm - FamSourceRgtEqFamsLft - FamiliesOfGeneralMappingsAndRanges - FamiliesOfRows - FamilyForOrdering - FamilyForRewritingSystem - FamilyObj - FamilyOfFamilies - FamilyOfTypes - FamilyPcgs - FamilyRange - FamilySource - FamilyType - FastExtSQ - Fibonacci - FibonacciGroup - Field - FieldByGenerators - FieldExtension - FieldOfMatrixGroup - FieldOfMatrixList - FieldOverItselfByGenerators - FileDescriptorOfStream - FileString - Filename - FilterSGMLMarkup - Filtered - FilteredOp - FinIndexCyclicSubgroupGenerator - FindActionKernel - FindBag - FindLayer - FindNewReps - FindNormalCSPG - FindOperationKernel - FindRegularNormalCSPG - FindWindowId - Fingerprint - FingerprintFF - FingerprintLarge - FingerprintMedium - FingerprintPerm - FingerprintSmall - FiniteField - First - FirstOp - FittingSubgroup - FixcellPoint - Fixcells - FixcellsCell - FixedPointSpace - FixpointCellNo - FlagsFamily - FlagsObj - FlagsType - Flat - FlatBlockMat - FlatHashParams - FloatsFamily - FlushCaches - ForAll - ForAllOp - ForAny - ForAnyOp - FormatParagraph - FormattedString - FpAlgebraByGeneralizedCartanMatrix - FpElmComparisonMethod - FpElmEqualityMethod - FpElmKBRWS - FpGroupPcGroupSQ - FpGroupPresentation - FpGrpMonSmgOfFpGrpMonSmgElement - FpLieAlgebraByCartanMatrix - FpLieAlgebraEnumeration - FpMonoidOfElementOfFpMonoid - FpOfModules - FpSemigroupOfElementOfFpSemigroup - FptoSCAMorphismImageElm - FrattiniSubgroup - FrattinifactorId - FrattinifactorSize - FreeAlgebra - FreeAlgebraConstructor - FreeAlgebraOfFpAlgebra - FreeAlgebraWithOne - FreeAssociativeAlgebra - FreeAssociativeAlgebraWithOne - FreeGeneratorsOfFpAlgebra - FreeGeneratorsOfFpGroup - FreeGeneratorsOfFpMonoid - FreeGeneratorsOfFpSemigroup - FreeGeneratorsOfWholeGroup - FreeGroup - FreeGroupOfBasicImageGroup - FreeGroupOfElt - FreeGroupOfFpGroup - FreeLeftModule - FreeLieAlgebra - FreeMagma - FreeMagmaRing - FreeMagmaWithOne - FreeMonoid - FreeMonoidNatHomByGeneratorsNC - FreeMonoidOfFpMonoid - FreeMonoidOfRewritingSystem - FreeSemigroup - FreeSemigroupNatHomByGeneratorsNC - FreeSemigroupOfFpSemigroup - FreeSemigroupOfRewritingSystem - FreeStructureOfRewritingSystem - FrobeniusAutomorphism - FrobeniusAutomorphismI - FrobeniusCharacterValue - FullMatrixAlgebra - FullMatrixAlgebraCentralizer - FullMatrixFLMLOR - FullMatrixLieAlgebra - FullMatrixLieFLMLOR - FullMatrixModule - FullMatrixSpace - FullRowModule - FullRowSpace - FullSparseRowSpace - FullTransformationSemigroup - FunctionAction - FunctionsFamily - FusionCharTableTom - FusionConjugacyClasses - FusionConjugacyClassesOp - FusionRationalClassesPSubgroup - FusionsAllowedByRestrictions - FusionsOfLibTom - FusionsToLibTom - FusionsTom - GAPDocManualLab - GAPInfo - GInverses - GLDegree - GLUnderlyingField - GModuleByMats - GPartitions - GPartitionsEasy - GPartitionsGreatestEQ - GPartitionsGreatestEQHelper - GPartitionsGreatestLE - GPartitionsGreatestLEEasy - GPartitionsNrParts - GPartitionsNrPartsHelper - GQuotients - GaloisConjugates - GaloisCyc - GaloisDiffResolvent - GaloisField - GaloisGroup - GaloisMat - GaloisSetResolvent - GaloisStabilizer - GaloisType - GapInputPcGroup - GapInputSCTable - GasmanLimits - GasmanMessageStatus - GasmanStatistics - GaussianIntegers - GaussianRationals - Gcd - GcdCoeffs - GcdInt - GcdOp - GcdRepresentation - GcdRepresentationOp - Gcdex - GeneralLinearGroup - GeneralLinearGroupCons - GeneralMappingByElements - GeneralMappingsFamily - GeneralOrthogonalGroup - GeneralOrthogonalGroupCons - GeneralStepClEANS - GeneralStepClEANSNonsolv - GeneralUnitaryGroup - GeneralUnitaryGroupCons - GeneralisedEigenspaces - GeneralisedEigenvalues - GeneralizedEigenspaces - GeneralizedEigenvalues - GeneralizedPcgs - GeneratingPairsOfLeftMagmaCongruence - GeneratingPairsOfMagmaCongruence - GeneratingPairsOfRightMagmaCongruence - GeneratingPairsOfSemigroupCongruence - GeneratingSetIsComplete - GeneratorNumberOfQuotient - GeneratorOfCyclicGroup - GeneratorSyllable - GeneratorTranslationAugmentedCosetTable - GeneratorsCenterPGroup - GeneratorsCentrePGroup - GeneratorsListTom - GeneratorsOfAdditiveGroup - GeneratorsOfAdditiveMagma - GeneratorsOfAdditiveMagmaWithInverses - GeneratorsOfAdditiveMagmaWithZero - GeneratorsOfAlgebra - GeneratorsOfAlgebraModule - GeneratorsOfAlgebraWithOne - GeneratorsOfDivisionRing - GeneratorsOfDomain - GeneratorsOfEquivalenceRelationPartition - GeneratorsOfExtASet - GeneratorsOfExtLSet - GeneratorsOfExtRSet - GeneratorsOfExtUSet - GeneratorsOfFLMLOR - GeneratorsOfFLMLORWithOne - GeneratorsOfField - GeneratorsOfGroup - GeneratorsOfIdeal - GeneratorsOfLayer - GeneratorsOfLeftIdeal - GeneratorsOfLeftMagmaIdeal - GeneratorsOfLeftModule - GeneratorsOfLeftOperatorAdditiveGroup - GeneratorsOfLeftOperatorRing - GeneratorsOfLeftOperatorRingWithOne - GeneratorsOfLeftVectorSpace - GeneratorsOfMagma - GeneratorsOfMagmaIdeal - GeneratorsOfMagmaWithInverses - GeneratorsOfMagmaWithOne - GeneratorsOfMonoid - GeneratorsOfNearAdditiveGroup - GeneratorsOfNearAdditiveMagma - GeneratorsOfNearAdditiveMagmaWithInverses - GeneratorsOfNearAdditiveMagmaWithZero - GeneratorsOfPresentation - GeneratorsOfRightIdeal - GeneratorsOfRightMagmaIdeal - GeneratorsOfRightModule - GeneratorsOfRightOperatorAdditiveGroup - GeneratorsOfRing - GeneratorsOfRingForIdeal - GeneratorsOfRingWithOne - GeneratorsOfRws - GeneratorsOfSemigroup - GeneratorsOfSemiring - GeneratorsOfSemiringWithOne - GeneratorsOfSemiringWithOneAndZero - GeneratorsOfSemiringWithZero - GeneratorsOfTwoSidedIdeal - GeneratorsOfVectorSpace - GeneratorsOverIntersection - GeneratorsPrimeResidues - GeneratorsSmallest - GeneratorsSmallestStab - GeneratorsSubgroupsTom - GenericFindActionKernel - GetChars - GetCommutatorNC - GetConjugateNC - GetDefinitionNC - GetETag - GetElement - GetEnt - GetFusionMap - GetHashEntry - GetHashEntryAtLastIndex - GetHashEntryIndex - GetMax - GetNaturalHomomorphismsPool - GetNumRight - GetPols - GetPowerNC - GetSTag - GetWord - GiveNumbersNIndeterminates - GlasbyCover - GlasbyIntersection - GlasbyShift - GlasbyStabilizer - GlobalPartitionOfClasses - Grading - GreensDClassOfElement - GreensDClasses - GreensDRelation - GreensHClassOfElement - GreensHClasses - GreensHRelation - GreensJClassOfElement - GreensJClasses - GreensJRelation - GreensLClassOfElement - GreensLClasses - GreensLRelation - GreensRClassOfElement - GreensRClasses - GreensRRelation - GroebnerBasis - GroebnerBasisNC - Group - GroupByGenerators - GroupByMultiplicationTable - GroupByNiceMonomorphism - GroupByPcgs - GroupByPrimeResidues - GroupByQuotientSystem - GroupByRws - GroupByRwsNC - GroupFromAdditiveGroup - GroupGeneralMappingByImages - GroupHClassOfGreensDClass - GroupHomomorphismByFunction - GroupHomomorphismByImages - GroupHomomorphismByImagesNC - GroupMethodByNiceMonomorphism - GroupMethodByNiceMonomorphismCollColl - GroupMethodByNiceMonomorphismCollElm - GroupMethodByNiceMonomorphismCollOther - GroupOfPcgs - GroupOnSubgroupsOrbit - GroupRing - GroupSeriesMethodByNiceMonomorphism - GroupSeriesMethodByNiceMonomorphismCollColl - GroupSeriesMethodByNiceMonomorphismCollElm - GroupSeriesMethodByNiceMonomorphismCollOther - GroupStabChain - GroupString - GroupToAdditiveGroupHomomorphismByFunction - GroupWithGenerators - HMSMSec - HallSubgroup - HallSubgroupOp - HallSystem - HasANonReesCongruenceOfSemigroup - HasAbelianFactorGroup - HasAbelianInvariants - HasAbelianInvariantsOfList - HasAbsoluteValue - HasActingDomain - HasActionHomomorphismAttr - HasActionKernelExternalSet - HasActorOfExternalSet - HasAdditiveElementAsMultiplicativeElement - HasAdditiveElementsAsMultiplicativeElementsFamily - HasAdditiveInverse - HasAdditiveInverseAttr - HasAdditiveInverseImmutable - HasAdditiveNeutralElement - HasAdditivelyActingDomain - HasAdjointBasis - HasAdjointModule - HasAlgebraicElementsFamilies - HasAllBlocks - HasAlpha - HasAlternatingDegree - HasAlternatingSubgroup - HasAsDuplicateFreeList - HasAsGroup - HasAsGroupGeneralMappingByImages - HasAsLeftModuleGeneralMappingByImages - HasAsList - HasAsMagma - HasAsMonoid - HasAsNearRing - HasAsPolynomial - HasAsRing - HasAsSSortedList - HasAsSemigroup - HasAsSemiring - HasAsSemiringWithOne - HasAsSemiringWithOneAndZero - HasAsSemiringWithZero - HasAsSortedList - HasAsSubgroupOfWholeGroupByQuotient - HasAssociatedReesMatrixSemigroupOfDClass - HasAssociatedSemigroup - HasAugmentationIdeal - HasAugmentedCosetTableMtcInWholeGroup - HasAugmentedCosetTableNormalClosureInWholeGroup - HasAugmentedCosetTableRrsInWholeGroup - HasAutomorphismDomain - HasAutomorphismGroup - HasAutomorphismsOfTable - HasBaseIntMat - HasBaseMat - HasBaseOfBasicImageGroup - HasBaseOfGroup - HasBaseOrthogonalSpaceMat - HasBasis - HasBasisOfHomCosetAddMatrixGroup - HasBasisVectors - HasBaumClausenInfo - HasBilinearFormMat - HasBlocksAttr - HasBlocksInfo - HasBrauerCharacterValue - HasBravaisGroup - HasBravaisSubgroups - HasBravaisSupergroups - HasCanEasilyCompareElements - HasCanEasilySortElements - HasCanFindNilpotentClassTwoElement - HasCanonicalBasis - HasCanonicalElt - HasCanonicalGenerators - HasCanonicalNiceMonomorphism - HasCanonicalPcgs - HasCanonicalPcgsWrtFamilyPcgs - HasCanonicalPcgsWrtHomePcgs - HasCanonicalPcgsWrtSpecialPcgs - HasCanonicalRepresentativeDeterminatorOfExternalSet - HasCanonicalRepresentativeOfExternalSet - HasCartanMatrix - HasCartanSubalgebra - HasCayleyGraphDualSemigroup - HasCayleyGraphSemigroup - HasCenter - HasCentralCharacter - HasCentralIdempotentsOfSemiring - HasCentralNormalSeriesByPcgs - HasCentralizerInGLnZ - HasCentralizerInParent - HasCentre - HasCentreOfCharacter - HasChainHomomorphicImage - HasChainSubgroup - HasChainSubgroupQuotient - HasCharacterDegrees - HasCharacterNames - HasCharacterParameters - HasCharacteristic - HasCharacteristicPolynomial - HasChevalleyBasis - HasChiefNormalSeriesByPcgs - HasChiefSeries - HasClassNames - HasClassNamesTom - HasClassParameters - HasClassPermutation - HasClassPositionsOfCentre - HasClassPositionsOfDerivedSubgroup - HasClassPositionsOfDirectProductDecompositions - HasClassPositionsOfElementaryAbelianSeries - HasClassPositionsOfFittingSubgroup - HasClassPositionsOfKernel - HasClassPositionsOfLowerCentralSeries - HasClassPositionsOfMaximalNormalSubgroups - HasClassPositionsOfNormalSubgroups - HasClassPositionsOfSolvableResiduum - HasClassPositionsOfSupersolvableResiduum - HasClassPositionsOfUpperCentralSeries - HasClassRoots - HasClassTypesTom - HasCoKernelOfAdditiveGeneralMapping - HasCoKernelOfMultiplicativeGeneralMapping - HasCoefficientsAndMagmaElements - HasCoefficientsFamily - HasCoefficientsOfLaurentPolynomial - HasCoefficientsOfUnivariatePolynomial - HasCoefficientsOfUnivariateRationalFunction - HasCoefficientsRing - HasCollectionsFamily - HasColumnIndexOfReesMatrixSemigroupElement - HasColumnIndexOfReesZeroMatrixSemigroupElement - HasColumnsOfReesMatrixSemigroup - HasColumnsOfReesZeroMatrixSemigroup - HasCommutatorFactorGroup - HasCommutatorLength - HasComplementSystem - HasComplexConjugate - HasComponentsOfTuplesFamily - HasCompositionSeries - HasComputedAgemos - HasComputedAscendingChains - HasComputedBrauerTables - HasComputedClassFusions - HasComputedCyclicExtensionsTom - HasComputedHallSubgroups - HasComputedIndicators - HasComputedIsPNilpotents - HasComputedIsPSolvableCharacterTables - HasComputedIsPSolvables - HasComputedOmegas - HasComputedPCentralSeriess - HasComputedPCores - HasComputedPRumps - HasComputedPowerMaps - HasComputedPrimeBlockss - HasComputedSylowComplements - HasComputedSylowSubgroups - HasConductor - HasConfluentRws - HasConjugacyClasses - HasConjugacyClassesMaximalSubgroups - HasConjugacyClassesPerfectSubgroups - HasConjugacyClassesSubgroups - HasConjugates - HasConjugatorInnerAutomorphism - HasConjugatorOfConjugatorIsomorphism - HasConstantTimeAccessList - HasConstituentsOfCharacter - HasConvertBasicImageGroupElement - HasCoreInParent - HasCosetTableFpHom - HasCosetTableInWholeGroup - HasCosetTableNormalClosureInWholeGroup - HasCosetTableOfFpSemigroup - HasCycleStructurePerm - HasCyclicExtensionsTom - HasDecompositionMatrix - HasDecompositionTypesOfGroup - HasDefaultFieldOfMatrix - HasDefaultFieldOfMatrixGroup - HasDefectApproximation - HasDefiningPcgs - HasDefiningPolynomial - HasDegreeAction - HasDegreeOfBinaryRelation - HasDegreeOfCharacter - HasDegreeOfLaurentPolynomial - HasDegreeOfMatrixGroup - HasDegreeOfTransformation - HasDegreeOfTransformationSemigroup - HasDegreeOperation - HasDegreeOverPrimeField - HasDelta - HasDenominatorOfModuloPcgs - HasDenominatorOfRationalFunction - HasDepthOfUpperTriangularMatrix - HasDerivations - HasDerivative - HasDerivedLength - HasDerivedSeriesOfGroup - HasDerivedSubgroup - HasDerivedSubgroupsTomPossible - HasDerivedSubgroupsTomUnique - HasDeterminantMat - HasDeterminantOfCharacter - HasDihedralGenerators - HasDimension - HasDimensionOfMatrixGroup - HasDimensionOfVectors - HasDimensionsLoewyFactors - HasDimensionsMat - HasDirectFactorsOfGroup - HasDirectProductInfo - HasDirectSumDecomposition - HasDisplayOptions - HasDixonRecord - HasEANormalSeriesByPcgs - HasEarns - HasEggBoxOfDClass - HasElementTestFunction - HasElementaryAbelianFactorGroup - HasElementaryAbelianSeries - HasElementaryAbelianSeriesLargeSteps - HasElementaryAbelianSubseries - HasElementsFamily - HasEmptyRowVector - HasEnumerator - HasEnumeratorByBasis - HasEnumeratorSorted - HasEquivalenceClassRelation - HasEquivalenceClasses - HasEquivalenceRelationPartition - HasExponent - HasExponentOfPowering - HasExtRepDenominatorRatFun - HasExtRepNumeratorRatFun - HasExtRepPolynomialRatFun - HasExternalOrbits - HasExternalOrbitsStabilizers - HasExternalSet - HasFactorsOfDirectProduct - HasFaithfulModule - HasFamiliesOfGeneralMappingsAndRanges - HasFamilyForOrdering - HasFamilyForRewritingSystem - HasFamilyPcgs - HasFamilyRange - HasFamilySource - HasFieldOfMatrixGroup - HasFittingSubgroup - HasFpElmComparisonMethod - HasFpElmEqualityMethod - HasFpElmKBRWS - HasFrattiniSubgroup - HasFrattinifactorId - HasFrattinifactorSize - HasFreeAlgebraOfFpAlgebra - HasFreeGeneratorsOfFpAlgebra - HasFreeGeneratorsOfFpGroup - HasFreeGeneratorsOfFpMonoid - HasFreeGeneratorsOfFpSemigroup - HasFreeGroupOfBasicImageGroup - HasFreeGroupOfFpGroup - HasFreeMonoidOfFpMonoid - HasFreeMonoidOfRewritingSystem - HasFreeSemigroupOfFpSemigroup - HasFreeSemigroupOfRewritingSystem - HasFrobeniusAutomorphism - HasFunctionAction - HasFusionConjugacyClassesOp - HasFusionsOfLibTom - HasFusionsToLibTom - HasFusionsTom - HasGLDegree - HasGLUnderlyingField - HasGaloisGroup - HasGaloisMat - HasGaloisStabilizer - HasGaloisType - HasGeneralizedPcgs - HasGeneratingPairsOfLeftMagmaCongruence - HasGeneratingPairsOfMagmaCongruence - HasGeneratingPairsOfRightMagmaCongruence - HasGeneratingSetIsComplete - HasGeneratorOfCyclicGroup - HasGeneratorsOfAdditiveGroup - HasGeneratorsOfAdditiveMagma - HasGeneratorsOfAdditiveMagmaWithInverses - HasGeneratorsOfAdditiveMagmaWithZero - HasGeneratorsOfAlgebra - HasGeneratorsOfAlgebraModule - HasGeneratorsOfAlgebraWithOne - HasGeneratorsOfDivisionRing - HasGeneratorsOfDomain - HasGeneratorsOfEquivalenceRelationPartition - HasGeneratorsOfExtASet - HasGeneratorsOfExtLSet - HasGeneratorsOfExtRSet - HasGeneratorsOfExtUSet - HasGeneratorsOfFLMLOR - HasGeneratorsOfFLMLORWithOne - HasGeneratorsOfField - HasGeneratorsOfGroup - HasGeneratorsOfIdeal - HasGeneratorsOfLeftIdeal - HasGeneratorsOfLeftMagmaIdeal - HasGeneratorsOfLeftModule - HasGeneratorsOfLeftOperatorAdditiveGroup - HasGeneratorsOfLeftOperatorRing - HasGeneratorsOfLeftOperatorRingWithOne - HasGeneratorsOfLeftVectorSpace - HasGeneratorsOfMagma - HasGeneratorsOfMagmaIdeal - HasGeneratorsOfMagmaWithInverses - HasGeneratorsOfMagmaWithOne - HasGeneratorsOfMonoid - HasGeneratorsOfNearAdditiveGroup - HasGeneratorsOfNearAdditiveMagma - HasGeneratorsOfNearAdditiveMagmaWithInverses - HasGeneratorsOfNearAdditiveMagmaWithZero - HasGeneratorsOfRightIdeal - HasGeneratorsOfRightMagmaIdeal - HasGeneratorsOfRightModule - HasGeneratorsOfRightOperatorAdditiveGroup - HasGeneratorsOfRing - HasGeneratorsOfRingWithOne - HasGeneratorsOfRws - HasGeneratorsOfSemigroup - HasGeneratorsOfSemiring - HasGeneratorsOfSemiringWithOne - HasGeneratorsOfSemiringWithOneAndZero - HasGeneratorsOfSemiringWithZero - HasGeneratorsOfTwoSidedIdeal - HasGeneratorsOfVectorSpace - HasGeneratorsSmallest - HasGeneratorsSubgroupsTom - HasGlobalPartitionOfClasses - HasGrading - HasGreensDRelation - HasGreensHRelation - HasGreensJRelation - HasGreensLRelation - HasGreensRRelation - HasGroupByPcgs - HasGroupHClassOfGreensDClass - HasGroupOfPcgs - HasHallSystem - HasHirschLength - HasHomCosetFamily - HasHomFromFreeOfBasicImageGroup - HasHomeEnumerator - HasHomePcgs - HasIBr - HasIdGroup - HasIdempotents - HasIdempotentsTom - HasIdempotentsTomInfo - HasIdentificationOfConjugacyClasses - HasIdentifier - HasIdentity - HasIdentityMapping - HasImageElt - HasImageListOfTransformation - HasImageSetOfTransformation - HasImagesSmallestGenerators - HasImagesSource - HasImfRecord - HasIndependentGeneratorsOfAbelianGroup - HasIndependentGeneratorsOfAbelianMatrixGroup - HasIndeterminateName - HasIndeterminateNumberOfLaurentPolynomial - HasIndeterminateNumberOfUnivariateLaurentPolynomial - HasIndeterminateNumberOfUnivariateRationalFunction - HasIndeterminateOfUnivariateRationalFunction - HasIndeterminatesOfPolynomialRing - HasIndexInParent - HasIndexInWholeGroup - HasIndicesCentralNormalSteps - HasIndicesChiefNormalSteps - HasIndicesEANormalSteps - HasIndicesInvolutaryGenerators - HasIndicesNormalSteps - HasIndicesOfAdjointBasis - HasIndicesPCentralNormalStepsPGroup - HasInducedPcgsWrtFamilyPcgs - HasInducedPcgsWrtHomePcgs - HasInducedPcgsWrtSpecialPcgs - HasInfoText - HasInjectionZeroMagma - HasInnerAutomorphismsAutomorphismGroup - HasInt - HasInternalRepresentative - HasInvariantBilinearForm - HasInvariantConjugateSubgroup - HasInvariantForm - HasInvariantLattice - HasInvariantQuadraticForm - HasInvariantSesquilinearForm - HasInverse - HasInverseAttr - HasInverseClasses - HasInverseGeneralMapping - HasInverseImmutable - HasIrr - HasIrrBaumClausen - HasIrrConlon - HasIrrDixonSchneider - HasIrrFacsPol - HasIrreducibleRepresentations - HasIsAbelian - HasIsAbelianNumberField - HasIsAbelianTom - HasIsAdditiveGroupGeneralMapping - HasIsAdditiveGroupHomomorphism - HasIsAdditiveGroupToGroupGeneralMapping - HasIsAdditiveGroupToGroupHomomorphism - HasIsAdditivelyCommutative - HasIsAlgebraGeneralMapping - HasIsAlgebraHomomorphism - HasIsAlgebraModule - HasIsAlgebraWithOneGeneralMapping - HasIsAlgebraWithOneHomomorphism - HasIsAlternatingGroup - HasIsAnticommutative - HasIsAntisymmetricBinaryRelation - HasIsAssociative - HasIsAutomorphismGroup - HasIsBasicWreathProductOrdering - HasIsBergerCondition - HasIsBijective - HasIsBravaisGroup - HasIsBuiltFromAdditiveMagmaWithInverses - HasIsBuiltFromGroup - HasIsBuiltFromMagma - HasIsBuiltFromMagmaWithInverses - HasIsBuiltFromMagmaWithOne - HasIsBuiltFromMonoid - HasIsBuiltFromSemigroup - HasIsCanonicalBasis - HasIsCanonicalBasisFullMatrixModule - HasIsCanonicalBasisFullRowModule - HasIsCanonicalBasisFullSCAlgebra - HasIsCanonicalNiceMonomorphism - HasIsCanonicalPcgs - HasIsCanonicalPcgsWrtSpecialPcgs - HasIsChainTypeGroup - HasIsCharacter - HasIsCharacteristicMatrixPGroup - HasIsCommutative - HasIsCommutativeFamily - HasIsConfluent - HasIsConjugatorAutomorphism - HasIsConjugatorIsomorphism - HasIsConstantRationalFunction - HasIsConstantTimeAccessGeneralMapping - HasIsCycInt - HasIsCyclic - HasIsCyclicTom - HasIsCyclotomicField - HasIsDihedralGroup - HasIsDistributive - HasIsDivisionRing - HasIsDuplicateFree - HasIsDuplicateFreeList - HasIsElementaryAbelian - HasIsEmpty - HasIsEndoGeneralMapping - HasIsEndoMapping - HasIsEquivalenceRelation - HasIsFFEMatrixGroupOverLargeSpace - HasIsFamilyPcgs - HasIsField - HasIsFieldHomomorphism - HasIsFinite - HasIsFiniteDimensional - HasIsFiniteOrdersPcgs - HasIsFiniteSemigroupGreensRelation - HasIsFinitelyGeneratedGroup - HasIsFrattiniFree - HasIsFreeMonoid - HasIsFreeSemigroup - HasIsFullFpAlgebra - HasIsFullHomModule - HasIsFullMatrixModule - HasIsFullRowModule - HasIsFullSCAlgebra - HasIsFullSubgroupGLorSLRespectingBilinearForm - HasIsFullSubgroupGLorSLRespectingQuadraticForm - HasIsFullSubgroupGLorSLRespectingSesquilinearForm - HasIsFullTransformationSemigroup - HasIsGL - HasIsGeneralLinearGroup - HasIsGeneralizedCartanMatrix - HasIsGeneratorsOfMagmaWithInverses - HasIsGreensClass - HasIsGreensDClass - HasIsGreensDRelation - HasIsGreensHClass - HasIsGreensHRelation - HasIsGreensJClass - HasIsGreensJRelation - HasIsGreensLClass - HasIsGreensLRelation - HasIsGreensRClass - HasIsGreensRRelation - HasIsGreensRelation - HasIsGroupGeneralMapping - HasIsGroupHClass - HasIsGroupHomomorphism - HasIsGroupOfAutomorphisms - HasIsGroupOfAutomorphismsFiniteGroup - HasIsGroupRing - HasIsGroupToAdditiveGroupGeneralMapping - HasIsGroupToAdditiveGroupHomomorphism - HasIsHandledByNiceMonomorphism - HasIsHasseDiagram - HasIsHomCosetOfAdditiveElt - HasIsHomCosetOfFp - HasIsHomCosetOfMatrix - HasIsHomCosetOfPerm - HasIsHomCosetOfTuple - HasIsIdealInParent - HasIsIdempotent - HasIsImpossible - HasIsInducedFromNormalSubgroup - HasIsInducedPcgsWrtSpecialPcgs - HasIsInjective - HasIsInnerAutomorphism - HasIsIntegerMatrixGroup - HasIsIntegralBasis - HasIsIntegralCyclotomic - HasIsIntegralRing - HasIsIrreducibleCharacter - HasIsJacobianRing - HasIsLDistributive - HasIsLatticeOrderBinaryRelation - HasIsLaurentPolynomial - HasIsLeftActedOnByDivisionRing - HasIsLeftAlgebraModule - HasIsLeftIdealInParent - HasIsLeftModuleGeneralMapping - HasIsLeftModuleHomomorphism - HasIsLeftSemigroupCongruence - HasIsLeftSemigroupIdeal - HasIsLieAbelian - HasIsLieAlgebra - HasIsLieNilpotent - HasIsLieSolvable - HasIsLinearlyPrimitive - HasIsMagmaHomomorphism - HasIsMapping - HasIsMatrixModule - HasIsMinimalNonmonomial - HasIsMonoid - HasIsMonomialCharacter - HasIsMonomialCharacterTable - HasIsMonomialGroup - HasIsMonomialMatrix - HasIsMonomialNumber - HasIsNaturalAlternatingGroup - HasIsNaturalGL - HasIsNaturalSL - HasIsNaturalSymmetricGroup - HasIsNearRing - HasIsNearRingWithOne - HasIsNilpQuotientSystem - HasIsNilpotentCharacterTable - HasIsNilpotentGroup - HasIsNilpotentTom - HasIsNonTrivial - HasIsNoncharacteristicMatrixPGroup - HasIsNormalBasis - HasIsNormalForm - HasIsNormalInParent - HasIsNumberField - HasIsNumeratorParentPcgsFamilyPcgs - HasIsOne - HasIsOrderingOnFamilyOfAssocWords - HasIsPGroup - HasIsPQuotientSystem - HasIsPSL - HasIsParentPcgsFamilyPcgs - HasIsPartialOrderBinaryRelation - HasIsPcgsCentralSeries - HasIsPcgsChiefSeries - HasIsPcgsElementaryAbelianSeries - HasIsPcgsPCentralSeriesPGroup - HasIsPerfectCharacterTable - HasIsPerfectGroup - HasIsPerfectTom - HasIsPolycyclicGroup - HasIsPolynomial - HasIsPositionsList - HasIsPreOrderBinaryRelation - HasIsPrimeField - HasIsPrimeOrdersPcgs - HasIsPrimitive - HasIsPrimitiveAffine - HasIsPrimitiveCharacter - HasIsPrimitiveMatrixGroup - HasIsPseudoCanonicalBasisFullHomModule - HasIsQuasiDihedralGroup - HasIsQuasiPrimitive - HasIsQuaternionGroup - HasIsRDistributive - HasIsRationalMatrixGroup - HasIsRectangularTable - HasIsReduced - HasIsReesCongruence - HasIsReesCongruenceSemigroup - HasIsReesMatrixSemigroup - HasIsReesZeroMatrixSemigroup - HasIsReflexiveBinaryRelation - HasIsRegular - HasIsRegularDClass - HasIsRegularSemigroup - HasIsRelativelySM - HasIsRestrictedLieAlgebra - HasIsRightAlgebraModule - HasIsRightIdealInParent - HasIsRightSemigroupCongruence - HasIsRightSemigroupIdeal - HasIsRing - HasIsRingGeneralMapping - HasIsRingHomomorphism - HasIsRingWithOne - HasIsRingWithOneGeneralMapping - HasIsRingWithOneHomomorphism - HasIsRowModule - HasIsSL - HasIsSSortedList - HasIsSemiEchelonized - HasIsSemiRegular - HasIsSemigroup - HasIsSemigroupCongruence - HasIsSemigroupIdeal - HasIsSemiring - HasIsSemiringWithOne - HasIsSemiringWithOneAndZero - HasIsSemiringWithZero - HasIsShortLexOrdering - HasIsSimpleAlgebra - HasIsSimpleCharacterTable - HasIsSimpleGroup - HasIsSimpleSemigroup - HasIsSingleValued - HasIsSkewFieldFamily - HasIsSmallList - HasIsSolvableCharacterTable - HasIsSolvableGroup - HasIsSolvableTom - HasIsSortedList - HasIsSpecialLinearGroup - HasIsSpecialPcgs - HasIsSporadicSimpleCharacterTable - HasIsSporadicSimpleGroup - HasIsStabChainViaChainSubgroup - HasIsSubgroupSL - HasIsSubmonoidFpMonoid - HasIsSubnormallyMonomial - HasIsSubsemigroupFpSemigroup - HasIsSubsemigroupReesMatrixSemigroup - HasIsSubsemigroupReesZeroMatrixSemigroup - HasIsSubsetLocallyFiniteGroup - HasIsSupersolvableCharacterTable - HasIsSupersolvableGroup - HasIsSurjective - HasIsSymmetricBinaryRelation - HasIsSymmetricGroup - HasIsTotal - HasIsTotalOrdering - HasIsTransformationMonoid - HasIsTransformationSemigroup - HasIsTransitive - HasIsTransitiveBinaryRelation - HasIsTranslationInvariantOrdering - HasIsTrivial - HasIsTwoSidedIdealInParent - HasIsUFDFamily - HasIsUniformMatrixGroup - HasIsUnivariatePolynomial - HasIsUnivariateRationalFunction - HasIsVectorSpaceHomomorphism - HasIsVirtualCharacter - HasIsWeightLexOrdering - HasIsWellFoundedOrdering - HasIsWeylGroup - HasIsWholeFamily - HasIsWreathProductOrdering - HasIsZero - HasIsZeroGroup - HasIsZeroMultiplicationRing - HasIsZeroRationalFunction - HasIsZeroSimpleSemigroup - HasIsZeroSquaredRing - HasIsomorphismFpAlgebra - HasIsomorphismFpFLMLOR - HasIsomorphismFpGroup - HasIsomorphismFpMonoid - HasIsomorphismFpSemigroup - HasIsomorphismMatrixAlgebra - HasIsomorphismMatrixFLMLOR - HasIsomorphismPcGroup - HasIsomorphismPermGroup - HasIsomorphismReesMatrixSemigroup - HasIsomorphismRefinedPcGroup - HasIsomorphismSCAlgebra - HasIsomorphismSCFLMLOR - HasIsomorphismSimplifiedFpGroup - HasIsomorphismSpecialPcGroup - HasIsomorphismTransformationSemigroup - HasJenningsLieAlgebra - HasJenningsSeries - HasJordanDecomposition - HasKernelOfAdditiveGeneralMapping - HasKernelOfCharacter - HasKernelOfMultiplicativeGeneralMapping - HasKernelOfTransformation - HasKillingMatrix - HasKnowsHowToDecompose - HasLClassOfHClass - HasLGFirst - HasLGHeads - HasLGLayers - HasLGLength - HasLGTails - HasLGWeights - HasLargestElementGroup - HasLargestMovedPoint - HasLargestMovedPointPerm - HasLatticeGeneratorsInUEA - HasLatticeSubgroups - HasLeadCoeffsIGS - HasLeftActingAlgebra - HasLeftActingDomain - HasLeftActingGroup - HasLeftActingRingOfIdeal - HasLeftDerivations - HasLength - HasLengthsTom - HasLessThanFunction - HasLessThanOrEqualFunction - HasLetterRepWordsLessFunc - HasLevelsOfGenerators - HasLeviMalcevDecomposition - HasLieAlgebraByDomain - HasLieCenter - HasLieCentralizerInParent - HasLieCentre - HasLieDerivedSeries - HasLieDerivedSubalgebra - HasLieFamily - HasLieLowerCentralSeries - HasLieNilRadical - HasLieNormalizerInParent - HasLieObject - HasLieSolvableRadical - HasLieUpperCentralSeries - HasLinearActionBasis - HasLinearCharacters - HasLinesOfStraightLineProgram - HasLongestWeylWordPerm - HasLowerCentralSeriesOfGroup - HasMagmaGeneratorsOfFamily - HasMappingGeneratorsImages - HasMappingOfWhichItIsAsGGMBI - HasMarksTom - HasMatTom - HasMatrixByBlockMatrix - HasMatrixDimension - HasMaximalAbelianQuotient - HasMaximalBlocksAttr - HasMaximalNormalSubgroups - HasMaximalSubgroupClassReps - HasMaximalSubgroups - HasMaximalSubgroupsLattice - HasMaximalSubgroupsTom - HasMinimalBlockDimension - HasMinimalGeneratingSet - HasMinimalNormalSubgroups - HasMinimalStabChain - HasMinimalSupergroupsLattice - HasMinimizedBombieriNorm - HasModuleOfExtension - HasModulusOfZmodnZObj - HasMoebiusTom - HasMolienSeriesInfo - HasMonoidOfRewritingSystem - HasMonomialComparisonFunction - HasMonomialExtrepComparisonFun - HasMovedPoints - HasMultiplicationTable - HasMultiplicativeNeutralElement - HasMultiplicativeZero - HasName - HasNameIsomorphismClass - HasNamesLibTom - HasNamesOfFusionSources - HasNaturalCharacter - HasNaturalHomomorphismByNormalSubgroupNCInParent - HasNaturalHomomorphismsPool - HasNegativeRootVectors - HasNegativeRoots - HasNestingDepthA - HasNestingDepthM - HasNiceAlgebraMonomorphism - HasNiceBasis - HasNiceFreeLeftModule - HasNiceFreeLeftModuleInfo - HasNiceMonomorphism - HasNiceNormalFormByExtRepFunction - HasNiceObject - HasNilpotencyClassOfGroup - HasNilpotentClassTwoElement - HasNonLieNilpotentElement - HasNonNilpotentElement - HasNorm - HasNormalBase - HasNormalClosureInParent - HasNormalMaximalSubgroups - HasNormalSeriesByPcgs - HasNormalSubgroupClassesInfo - HasNormalSubgroups - HasNormalizerInGLnZ - HasNormalizerInGLnZBravaisGroup - HasNormalizerInHomePcgs - HasNormalizerInParent - HasNormalizersTom - HasNormedRowVector - HasNormedRowVectors - HasNormedVectors - HasNotifiedFusionsOfLibTom - HasNotifiedFusionsToLibTom - HasNrConjugacyClasses - HasNrInputsOfStraightLineProgram - HasNrMovedPoints - HasNrMovedPointsPerm - HasNrSubsTom - HasNrSyllables - HasNullAlgebra - HasNullspaceIntMat - HasNullspaceMat - HasNumberGeneratorsOfRws - HasNumberSyllables - HasNumeratorOfModuloPcgs - HasNumeratorOfRationalFunction - HasONanScottType - HasOccuringVariableIndices - HasOmegaAndLowerPCentralSeries - HasOmegaSeries - HasOne - HasOneAttr - HasOneImmutable - HasOneOfPcgs - HasOperatorOfExternalSet - HasOrbitGeneratorsOfGroup - HasOrbitLengths - HasOrbitLengthsDomain - HasOrbitStabilizingParentGroup - HasOrbits - HasOrbitsDomain - HasOrder - HasOrderingOfRewritingSystem - HasOrderingOnGenerators - HasOrderingsFamily - HasOrdersClassRepresentatives - HasOrdersTom - HasOrdinaryCharacterTable - HasOrthogonalSpaceInFullRowSpace - HasPCentralLieAlgebra - HasPCentralNormalSeriesByPcgsPGroup - HasPClassPGroup - HasPSLDegree - HasPSLUnderlyingField - HasParent - HasParentAttr - HasParentPcgs - HasPartialClosureOfCongruence - HasPartialOrderOfHasseDiagram - HasPcGroupWithPcgs - HasPcSeries - HasPcgs - HasPcgsCentralSeries - HasPcgsChiefSeries - HasPcgsElementaryAbelianSeries - HasPcgsPCentralSeriesPGroup - HasPerfectIdentification - HasPerfectResiduum - HasPermutationTom - HasPositiveRootVectors - HasPositiveRoots - HasPositiveRootsAsWeights - HasPowerS - HasPowerSubalgebraSeries - HasPreBasis - HasPreImagesRange - HasPreferredGenerators - HasPrefrattiniSubgroup - HasPresentation - HasPrimaryGeneratorWords - HasPrimeField - HasPrimePGroup - HasPrimePowerComponents - HasPrimitiveElement - HasPrimitiveIdentification - HasPrimitiveRoot - HasProjectiveOrder - HasPseudoRandomSeed - HasPthPowerImages - HasQuasiDihedralGenerators - HasQuaternionGenerators - HasQuotientGroup - HasQuotientGroupHom - HasQuotientSemigroupCongruence - HasQuotientSemigroupHomomorphism - HasQuotientSemigroupPreimage - HasRClassOfHClass - HasRadicalGroup - HasRadicalOfAlgebra - HasRange - HasRankAction - HasRankMat - HasRankOfTransformation - HasRankPGroup - HasRat - HasRationalClasses - HasRationalFunctionsFamily - HasRationalizedMat - HasRealClasses - HasRecNames - HasReducedConfluentRewritingSystem - HasReesCongruenceOfSemigroupIdeal - HasReesZeroMatrixSemigroupElementIsZero - HasRefinedPcGroup - HasRegularActionHomomorphism - HasRelationsOfFpMonoid - HasRelationsOfFpSemigroup - HasRelativeOrders - HasRelatorsOfFpAlgebra - HasRelatorsOfFpGroup - HasRepresentative - HasRepresentativeSmallest - HasRepresentativesContainedRightCosets - HasRepresentativesMinimalBlocksAttr - HasRepresentativesPerfectSubgroups - HasRepresentativesSimpleSubgroups - HasRespectsAddition - HasRespectsAdditiveInverses - HasRespectsInverses - HasRespectsMultiplication - HasRespectsOne - HasRespectsScalarMultiplication - HasRespectsZero - HasRightActingAlgebra - HasRightActingDomain - HasRightActingGroup - HasRightActingRingOfIdeal - HasRightDerivations - HasRightTransversalInParent - HasRootOfDefiningPolynomial - HasRootSystem - HasRowIndexOfReesMatrixSemigroupElement - HasRowIndexOfReesZeroMatrixSemigroupElement - HasRowsOfReesMatrixSemigroup - HasRowsOfReesZeroMatrixSemigroup - HasRules - HasSLDegree - HasSLUnderlyingField - HasSandwichMatrixOfReesMatrixSemigroup - HasSandwichMatrixOfReesZeroMatrixSemigroup - HasSemiEchelonBasis - HasSemiEchelonMat - HasSemiEchelonMatTransformation - HasSemiSimpleType - HasSemidirectFactorsOfGroup - HasSemidirectProductInfo - HasSemigroupOfRewritingSystem - HasSiftFunction - HasSiftGroup - HasSignPerm - HasSimpleSystem - HasSimsNo - HasSize - HasSizesCentralizers - HasSizesConjugacyClasses - HasSmallGeneratingSet - HasSmallestGeneratorPerm - HasSmallestMovedPoint - HasSmallestMovedPointPerm - HasSocle - HasSocleComplement - HasSocleDimensions - HasSocleTypePrimitiveGroup - HasSortingPerm - HasSource - HasSparseCartanMatrix - HasSpecialPcgs - HasSplittingField - HasStabChainImmutable - HasStabChainMutable - HasStabChainOptions - HasStabilizerOfExternalSet - HasStandardGeneratorsInfo - HasStoredExcludedOrders - HasStoredGroebnerBasis - HasStraightLineProgElmType - HasStraightLineProgramsTom - HasString - HasStructureConstantsTable - HasStructureDescription - HasSubdirectProductInfo - HasSubfields - HasSubnormalSeriesInParent - HasSubsTom - HasSubspaces - HasSubspacesAll - HasSuccessors - HasSupersolvableResiduum - HasSurjectiveActionHomomorphismAttr - HasSylowSystem - HasSymmetricDegree - HasSymmetricParentGroup - HasTableOfMarks - HasTestMonomial - HasTestMonomialQuick - HasTestQuasiPrimitive - HasTestRelativelySM - HasTestSubnormallyMonomial - HasTietzeOrigin - HasTrace - HasTranformsOneIntoZero - HasTransformationRepresentation - HasTransformsAdditionIntoMultiplication - HasTransformsAdditiveInversesIntoInverses - HasTransformsInversesIntoAdditiveInverses - HasTransformsMultiplicationIntoAddition - HasTransformsZeroIntoOne - HasTransitiveIdentification - HasTransitivity - HasTransposedMat - HasTransposedMatAttr - HasTransposedMatImmutable - HasTransposedMatrixGroup - HasTransversal - HasTriangulizedNullspaceMat - HasTrivialCharacter - HasTrivialSubFLMLOR - HasTrivialSubadditiveMagmaWithZero - HasTrivialSubalgebra - HasTrivialSubgroup - HasTrivialSubmagmaWithOne - HasTrivialSubmodule - HasTrivialSubmonoid - HasTrivialSubnearAdditiveMagmaWithZero - HasTrivialSubspace - HasTwoClosure - HasTzOptions - HasTzRules - HasUnderlyingCharacterTable - HasUnderlyingCharacteristic - HasUnderlyingCollection - HasUnderlyingElementOfReesMatrixSemigroupElement - HasUnderlyingElementOfReesZeroMatrixSemigroupElement - HasUnderlyingExternalSet - HasUnderlyingFamily - HasUnderlyingField - HasUnderlyingGeneralMapping - HasUnderlyingGroup - HasUnderlyingLeftModule - HasUnderlyingLieAlgebra - HasUnderlyingMagma - HasUnderlyingRelation - HasUnderlyingSemigroupOfReesMatrixSemigroup - HasUnderlyingSemigroupOfReesZeroMatrixSemigroup - HasUnderlyingVectorSpace - HasUnits - HasUniversalEnvelopingAlgebra - HasUpperActingDomain - HasUpperCentralSeriesOfGroup - HasValuesOfClassFunction - HasWeightOfGenerators - HasWeightsTom - HasWeylGroup - HasWreathProductInfo - HasZClassRepsQClass - HasZero - HasZeroAttr - HasZeroCoefficient - HasZeroImmutable - HasZuppos - HashDictAddDictionary - HashFunct - HashKeyBag - HashKeyEnumerator - HashTable - HasnpeGL - HasnpePSL - HasnpeSL - HasseDiagramBinaryRelation - HeadPcElementByNumber - HeadsInfoOfSemiEchelonizedMat - HeadsInfoOfSemiEchelonizedMats - HenselBound - HermiteNormalFormIntegerMat - HermiteNormalFormIntegerMatTransform - HermiteNormalFormIntegerMatTransforms - HeuGcdIntPolsCoeffs - HeuGcdIntPolsExtRep - HeuristicCancelPolynomialsExtRep - HexBlistSetup - HexStringBlist - HexStringBlistEncode - HexStringInt - HideGlobalVariables - HighestWeightModule - HirschLength - Hom - HomCoset - HomCosetFamily - HomCosetWithImage - HomFromFree - HomFromFreeOfBasicImageGroup - HomTransversal - HomeEnumerator - HomePcgs - HomomorphicCanonicalPcgs - HomomorphicInducedPcgs - Homomorphism - HomomorphismFactorSemigroup - HomomorphismFactorSemigroupByClosure - HomomorphismQuotientSemigroup - HomomorphismTransformationSemigroup - HomomorphismsSeries - HumanReadableDefinition - IBr - IMFList - IMFLoad - IMFRec - IdFunc - IdGroup - IdSmallGroup - Ideal - IdealByGenerators - IdealByGeneratorsForLieAlgebra - IdealNC - Idempotents - IdempotentsTom - IdempotentsTomInfo - IdentificationGenericGroup - IdentificationOfConjugacyClasses - IdentificationPermGroup - IdentificationSolvableGroup - Identifier - IdentifierLetters - Identity - IdentityBinaryRelation - IdentityFromSCTable - IdentityMapping - IdentityMat - IdentityTransformation - IdsOfAllGroups - IdsOfAllSmallGroups - Ignore - Image - ImageElm - ImageElmActionHomomorphism - ImageElt - ImageGroup - ImageInWord - ImageKernelBlocksHomomorphism - ImageListOfTransformation - ImageMat - ImageOnAbelianCSPG - ImageSetOfTransformation - ImageSiftedBaseImage - ImageUnderWord - Images - ImagesElm - ImagesListOfBinaryRelation - ImagesRepresentative - ImagesRepresentativeGMBIByElementsList - ImagesSet - ImagesSmallestGenerators - ImagesSource - ImfInvariants - ImfMatrixGroup - ImfNumberQClasses - ImfNumberQQClasses - ImfNumberZClasses - ImfPositionNumber - ImfRecord - ImgElmSLP - ImgElmSLPNonrecursive - ImmediateImplicationsIdentityMapping - ImmediateImplicationsZeroMapping - Immutable - ImmutableBasis - ImmutableMatrix - ImproveActionDegreeByBlocks - ImproveMaps - ImproveOperationDegreeByBlocks - InParentFOA - IncorporateCentralRelations - IncreaseCounter - IndPcgsWrtSpecFromFamOrHome - IndependentGeneratorsAbelianPPermGroup - IndependentGeneratorsOfAbelianGroup - IndependentGeneratorsOfAbelianMatrixGroup - Indeterminate - IndeterminateName - IndeterminateNumberOfLaurentPolynomial - IndeterminateNumberOfUnivariateLaurentPolynomial - IndeterminateNumberOfUnivariateRationalFunction - IndeterminateOfLaurentPolynomial - IndeterminateOfUnivariateRationalFunction - Indeterminateness - IndeterminatenessInfo - IndeterminatesOfPolynomialRing - Index - IndexCosetTab - IndexInParent - IndexInWholeGroup - IndexNC - IndexOp - Indicator - IndicatorOp - IndicesCentralNormalSteps - IndicesChiefNormalSteps - IndicesEANormalSteps - IndicesInvolutaryGenerators - IndicesNormalSteps - IndicesOfAdjointBasis - IndicesPCentralNormalStepsPGroup - IndicesStabChain - Indirected - Induced - InducedActionAutGroup - InducedActionFactor - InducedAutomorphism - InducedClassFunction - InducedClassFunctions - InducedClassFunctionsByFusionMap - InducedCyclic - InducedGModule - InducedLinearAction - InducedModule - InducedModuleByFieldReduction - InducedPcgs - InducedPcgsByGenerators - InducedPcgsByGeneratorsNC - InducedPcgsByGeneratorsWithImages - InducedPcgsByPcSequence - InducedPcgsByPcSequenceAndGenerators - InducedPcgsByPcSequenceNC - InducedPcgsWrtFamilyPcgs - InducedPcgsWrtHomePcgs - InducedPcgsWrtSpecialPcgs - InducedRepFpGroup - InducedRepresentation - InducedRepresentationImagesRepresentative - InduciblePairs - InductionScheme - Inequalities - InertiaSubgroup - InfiniteListOfGenerators - InfiniteListOfNames - Inflated - Info - InfoAction - InfoAlgebra - InfoAttributes - InfoAutGrp - InfoBasicImage - InfoBckt - InfoChain - InfoCharacterTable - InfoClassFamily - InfoClasses - InfoCoh - InfoCompPairs - InfoComplement - InfoConfluence - InfoCoset - InfoData - InfoDebug - InfoDecision - InfoDoPrint - InfoExtReps - InfoFactor - InfoFpGroup - InfoGalois - InfoGlobal - InfoGroebner - InfoGroup - InfoHash - InfoHashTables - InfoHomClass - InfoIdgroup - InfoImf - InfoKnuthBendix - InfoLattice - InfoLevel - InfoMatInt - InfoMatOrb - InfoMatrix - InfoMeatAxe - InfoMethodSelection - InfoMonomial - InfoMorph - InfoNumtheor - InfoOperation - InfoOptions - InfoOverGr - InfoPcGroup - InfoPcNormalizer - InfoPcSubgroup - InfoPerformance - InfoPoly - InfoPrimeInt - InfoQuotientGroup - InfoQuotientSystem - InfoRSS - InfoRandIso - InfoSQ - InfoSchur - InfoSearchTable - InfoSpecPcgs - InfoTeaching - InfoText - InfoTiming - InfoTom - InfoTransversal - InfoTuples - InfoWarning - InfoZLattice - InitAbsAndIrredModules - InitEpimorphismSQ - InitFusion - InitPowerMap - InitialiseCentralRelations - InitializePackagesInfoRecords - InitializeSchreierTree - Injection - InjectionZeroMagma - InnerAutomorphism - InnerAutomorphismNC - InnerAutomorphismsAutomorphismGroup - InnerSubdirectProducts - InputLogTo - InputOutputLocalProcess - InputOutputStreamByPtyDefaultType - InputTextFile - InputTextFileStillOpen - InputTextFileType - InputTextNone - InputTextNoneType - InputTextString - InputTextStringType - InputTextUser - Insert - InsertElmList - InsertTrivialStabilizer - InstallAccessToGenerators - InstallAtExit - InstallAttributeFunction - InstallAttributeMethodByGroupGeneralMappingByImages - InstallCharReadHookFunc - InstallEqMethodForMappingsFromGenerators - InstallFactorMaintenance - InstallFlushableValue - InstallGlobalFunction - InstallHandlingByNiceBasis - InstallHiddenTrueMethod - InstallImmediateMethod - InstallIsomorphismMaintenance - InstallIsomorphismMaintenanceFunction - InstallMethod - InstallMonomialOrdering - InstallOtherMethod - InstallPcgsSeriesFromIndices - InstallSubsetMaintenance - InstallTrueMethod - InstallTrueMethodNewFilter - InstallValue - InstalledPackageVersion - Int - IntFFE - IntFFESymm - IntHexString - IntScalarProducts - IntVecFFE - Integers - IntegralizedMat - IntegratedStraightLineProgram - IntermediateGroup - IntermediateSubgroups - InternalRepresentative - InterpolatedPolynomial - IntersectBlist - IntersectSet - Intersection - IntersectionBlist - IntersectionNormalClosurePermGroup - IntersectionSet - IntersectionSumPcgs - IntersectionsTom - InvariantBilinearForm - InvariantElementaryAbelianSeries - InvariantForm - InvariantLattice - InvariantQuadraticForm - InvariantSesquilinearForm - InvariantSubgroupsElementaryAbelianGroup - InvariantSubspaceOrCyclicGroup - InvariantSubspaceOrUniformCyclicPGroup - Inverse - InverseAsWord - InverseAttr - InverseClasses - InverseGeneralMapping - InverseImmutable - InverseMap - InverseMatMod - InverseMutable - InverseOp - InversePcgs - InverseRepresentative - InverseRepresentativeWord - InverseSLPElm - InverseSM - InverseSameMutability - Irr - IrrBaumClausen - IrrConlon - IrrDixonSchneider - IrrFacsPol - IrredSolGroupList - IrredSolJSGens - IrreducibleDifferences - IrreducibleModules - IrreducibleRepresentations - IrreducibleRepresentationsByBaumClausen - IrreducibleRepresentationsDixon - IrreducibleSolvableGroup - IrreducibleSolvableGroupMS - IsANFAutomorphism - IsANFAutomorphismRep - IsAbelian - IsAbelianNumberField - IsAbelianNumberFieldPolynomialRing - IsAbelianTom - IsActionHomomorphism - IsActionHomomorphismAutomGroup - IsActionHomomorphismByActors - IsActionHomomorphismByBase - IsActionHomomorphismSubset - IsAdditiveCoset - IsAdditiveCosetDefaultRep - IsAdditiveElement - IsAdditiveElementAsMultiplicativeElementRep - IsAdditiveElementCollColl - IsAdditiveElementCollCollColl - IsAdditiveElementCollection - IsAdditiveElementList - IsAdditiveElementTable - IsAdditiveElementWithInverse - IsAdditiveElementWithInverseCollColl - IsAdditiveElementWithInverseCollCollColl - IsAdditiveElementWithInverseCollection - IsAdditiveElementWithInverseList - IsAdditiveElementWithInverseTable - IsAdditiveElementWithZero - IsAdditiveElementWithZeroCollColl - IsAdditiveElementWithZeroCollCollColl - IsAdditiveElementWithZeroCollection - IsAdditiveElementWithZeroList - IsAdditiveElementWithZeroTable - IsAdditiveGroup - IsAdditiveGroupGeneralMapping - IsAdditiveGroupHomomorphism - IsAdditiveGroupToGroupGeneralMapping - IsAdditiveGroupToGroupHomomorphism - IsAdditiveMagma - IsAdditiveMagmaWithInverses - IsAdditiveMagmaWithZero - IsAdditivelyCommutative - IsAdditivelyCommutativeElement - IsAdditivelyCommutativeElementCollColl - IsAdditivelyCommutativeElementCollection - IsAdditivelyCommutativeElementFamily - IsAlgBFRep - IsAlgExtRep - IsAlgebra - IsAlgebraGeneralMapping - IsAlgebraGeneralMappingByImagesDefaultRep - IsAlgebraHomomorphism - IsAlgebraHomomorphismFromFpRep - IsAlgebraModule - IsAlgebraModuleElement - IsAlgebraModuleElementCollection - IsAlgebraModuleElementFamily - IsAlgebraWithOne - IsAlgebraWithOneGeneralMapping - IsAlgebraWithOneHomomorphism - IsAlgebraicElement - IsAlgebraicElementCollColl - IsAlgebraicElementCollCollColl - IsAlgebraicElementCollection - IsAlgebraicElementFamily - IsAlgebraicExtension - IsAlgebraicExtensionDefaultRep - IsAlgebraicExtensionPolynomialRing - IsAlphaChar - IsAlternatingGroup - IsAnticommutative - IsAntisymmetricBinaryRelation - IsAssocWord - IsAssocWordCollection - IsAssocWordFamily - IsAssocWordWithInverse - IsAssocWordWithInverseCollection - IsAssocWordWithInverseFamily - IsAssocWordWithOne - IsAssocWordWithOneCollection - IsAssocWordWithOneFamily - IsAssociated - IsAssociative - IsAssociativeAOpDSum - IsAssociativeAOpESum - IsAssociativeElement - IsAssociativeElementCollColl - IsAssociativeElementCollection - IsAssociativeLOpDProd - IsAssociativeLOpEProd - IsAssociativeROpDProd - IsAssociativeROpEProd - IsAssociativeUOpDProd - IsAssociativeUOpEProd - IsAttributeStoringRep - IsAttributeStoringRepFlags - IsAutomorphismGroup - IsBLetterAssocWordRep - IsBLetterWordsFamily - IsBasicImageEltRep - IsBasicImageEltRepCollection - IsBasicImageGroup - IsBasicWreathLessThanOrEqual - IsBasicWreathProductOrdering - IsBasis - IsBasisByNiceBasis - IsBasisFiniteFieldRep - IsBasisOfAlgebraModuleElementSpace - IsBasisOfMonomialSpaceRep - IsBasisOfSparseRowSpaceRep - IsBasisOfWeightRepElementSpace - IsBasisWithReplacedLeftModuleRep - IsBergerCondition - IsBijective - IsBinaryRelation - IsBinaryRelationDefaultRep - IsBinaryRelationOnPointsRep - IsBlist - IsBlistRep - IsBlockMatrixRep - IsBlocksHomomorphism - IsBlocksOfActionHomomorphism - IsBlowUpIsomorphism - IsBool - IsBound - IsBoundElmWPObj - IsBoundGlobal - IsBracketRep - IsBrauerTable - IsBravaisGroup - IsBuiltFromAdditiveMagmaWithInverses - IsBuiltFromGroup - IsBuiltFromMagma - IsBuiltFromMagmaWithInverses - IsBuiltFromMagmaWithOne - IsBuiltFromMonoid - IsBuiltFromSemigroup - IsCanonicalBasis - IsCanonicalBasisAbelianNumberFieldRep - IsCanonicalBasisAlgebraicExtension - IsCanonicalBasisCyclotomicFieldRep - IsCanonicalBasisFreeMagmaRingRep - IsCanonicalBasisFullMatrixModule - IsCanonicalBasisFullRowModule - IsCanonicalBasisFullSCAlgebra - IsCanonicalBasisGaussianIntegersRep - IsCanonicalBasisIntegersRep - IsCanonicalBasisRationals - IsCanonicalNiceMonomorphism - IsCanonicalPcgs - IsCanonicalPcgsWrtSpecialPcgs - IsCentral - IsCentralFromGenerators - IsChainTypeGroup - IsChar - IsCharCollection - IsCharacter - IsCharacterTable - IsCharacterTableInProgress - IsCharacteristicMatrixPGroup - IsCharacteristicSubgroup - IsCheapConwayPolynomial - IsClassFunction - IsClassFunctionsSpace - IsClassFusionOfNormalSubgroup - IsClosedStream - IsCochain - IsCochainCollection - IsCochainsSpace - IsCocycle - IsCoeffsElms - IsCollCollsElms - IsCollCollsElmsElms - IsCollCollsElmsElmsX - IsCollLieCollsElms - IsCollection - IsCollectionFamily - IsCollsCollsElms - IsCollsCollsElmsX - IsCollsCollsElmsXX - IsCollsElms - IsCollsElmsColls - IsCollsElmsElms - IsCollsElmsElmsElms - IsCollsElmsElmsX - IsCollsElmsX - IsCollsElmsXElms - IsCollsElmsXX - IsCollsXElms - IsCollsXElmsX - IsCombinatorialCollectorRep - IsCommutative - IsCommutativeElement - IsCommutativeElementCollColl - IsCommutativeElementCollection - IsCommutativeFamily - IsCommutativeFromGenerators - IsCompatiblePair - IsComponentObjectRep - IsCompositionMappingRep - IsConfluent - IsCongruenceClass - IsConjugacyClassGroupRep - IsConjugacyClassPermGroupRep - IsConjugacyClassSubgroupsByStabilizerRep - IsConjugacyClassSubgroupsRep - IsConjugate - IsConjugatorAutomorphism - IsConjugatorIsomorphism - IsConsistentPolynomial - IsConstantRationalFunction - IsConstantTimeAccessGeneralMapping - IsConstantTimeAccessList - IsConstituentHomomorphism - IsContainedInSpan - IsCopyable - IsCyc - IsCycInt - IsCyclic - IsCyclicTom - IsCyclotomic - IsCyclotomicCollColl - IsCyclotomicCollCollColl - IsCyclotomicCollection - IsCyclotomicField - IsCyclotomicMatrixGroup - IsDataObjectRep - IsDeepThoughtCollectorRep - IsDefaultGeneralMappingRep - IsDefaultRhsTypeSingleCollector - IsDefaultTupleRep - IsDenseCoeffVectorRep - IsDenseHashRep - IsDenseList - IsDiagonalMat - IsDictionary - IsDictionaryDefaultRep - IsDigitChar - IsDihedralGroup - IsDirectSumElement - IsDirectSumElementCollection - IsDirectSumElementFamily - IsDirectSumElementsSpace - IsDirectory - IsDirectoryPath - IsDirectoryRep - IsDistributive - IsDistributiveLOpDProd - IsDistributiveLOpDSum - IsDistributiveLOpEProd - IsDistributiveLOpESum - IsDistributiveROpDProd - IsDistributiveROpDSum - IsDistributiveROpEProd - IsDistributiveROpESum - IsDistributiveUOpDProd - IsDistributiveUOpDSum - IsDistributiveUOpEProd - IsDistributiveUOpESum - IsDivisionRing - IsDocumentedVariable - IsDomain - IsDoneIterator - IsDoubleCoset - IsDoubleCosetDefaultRep - IsDuplicateFree - IsDuplicateFreeCollection - IsDuplicateFreeList - IsDxLargeGroup - IsElementFinitePolycyclicGroup - IsElementFinitePolycyclicGroupCollection - IsElementOfFpAlgebra - IsElementOfFpAlgebraCollection - IsElementOfFpAlgebraFamily - IsElementOfFpGroup - IsElementOfFpGroupCollection - IsElementOfFpGroupFamily - IsElementOfFpMonoid - IsElementOfFpMonoidCollection - IsElementOfFpMonoidFamily - IsElementOfFpSemigroup - IsElementOfFpSemigroupCollection - IsElementOfFpSemigroupFamily - IsElementOfFreeGroup - IsElementOfFreeGroupFamily - IsElementOfFreeMagmaRing - IsElementOfFreeMagmaRingCollection - IsElementOfFreeMagmaRingFamily - IsElementOfMagmaRingModuloRelations - IsElementOfMagmaRingModuloRelationsCollection - IsElementOfMagmaRingModuloRelationsFamily - IsElementOfMagmaRingModuloSpanOfZeroFamily - IsElementaryAbelian - IsElementsFamilyByRws - IsElmsCoeffs - IsElmsCollColls - IsElmsCollCollsX - IsElmsCollLieColls - IsElmsColls - IsElmsCollsX - IsElmsCollsXX - IsElmsLieColls - IsEmbeddingDirectProductPermGroup - IsEmbeddingImprimitiveWreathProductPermGroup - IsEmbeddingMagmaMagmaRing - IsEmbeddingProductActionWreathProductPermGroup - IsEmbeddingRingMagmaRing - IsEmbeddingWreathProductPermGroup - IsEmpty - IsEmptyRowVectorRep - IsEmptyString - IsEndOfStream - IsEndoGeneralMapping - IsEndoMapping - IsEnumeratorByFunctions - IsEnumeratorByFunctionsRep - IsEnumeratorByPcgsRep - IsEqualSet - IsEquivalenceClass - IsEquivalenceClassDefaultRep - IsEquivalenceRelation - IsEquivalenceRelationDefaultRep - IsEquivalentByFp - IsEuclideanRing - IsEvenInt - IsExecutableFile - IsExistingFile - IsExtAElement - IsExtAElementCollColl - IsExtAElementCollection - IsExtAElementList - IsExtAElementTable - IsExtASet - IsExtLElement - IsExtLElementCollColl - IsExtLElementCollection - IsExtLElementList - IsExtLElementTable - IsExtLSet - IsExtRElement - IsExtRElementCollColl - IsExtRElementCollection - IsExtRElementList - IsExtRElementTable - IsExtRSet - IsExtUSet - IsExtensibleGeneralMapping - IsExtensiblePartialMapping - IsExternalOrbit - IsExternalOrbitByStabilizerRep - IsExternalSet - IsExternalSetByActorsRep - IsExternalSetByOperatorsRep - IsExternalSetByPcgs - IsExternalSetDefaultRep - IsExternalSubset - IsFFE - IsFFECollColl - IsFFECollCollColl - IsFFECollection - IsFFEFamily - IsFFEMatrixGroup - IsFFEMatrixGroupOverLargeSpace - IsFLMLOR - IsFLMLORWithOne - IsFamFamFam - IsFamFamFamX - IsFamFamX - IsFamFamXY - IsFamLieFam - IsFamXFam - IsFamXFamY - IsFamXYFamZ - IsFamily - IsFamilyDefaultRep - IsFamilyElementOfFreeLieAlgebra - IsFamilyOfFamilies - IsFamilyOfTypes - IsFamilyOverFullCoefficientsFamily - IsFamilyPcgs - IsField - IsFieldControlledByGaloisGroup - IsFieldElementsSpace - IsFieldHomomorphism - IsFilter - IsFinite - IsFiniteBasisDefault - IsFiniteDimensional - IsFiniteFieldPolynomialRing - IsFiniteOrderElement - IsFiniteOrderElementCollColl - IsFiniteOrderElementCollection - IsFiniteOrdersPcgs - IsFiniteSemigroupGreensRelation - IsFinitelyGeneratedGroup - IsFixedStabilizer - IsFlatHashTable - IsFlexibleGeneralMapping - IsFlexiblePartialMapping - IsFpAlgebraElementsSpace - IsFpGroup - IsFpMonoid - IsFpSemigroup - IsFptoSCAMorphism - IsFrattiniFree - IsFreeGroup - IsFreeLeftModule - IsFreeMagma - IsFreeMagmaRing - IsFreeMagmaRingWithOne - IsFreeMonoid - IsFreeSemigroup - IsFrobeniusAutomorphism - IsFromFpGroupGeneralMapping - IsFromFpGroupGeneralMappingByImages - IsFromFpGroupHomomorphism - IsFromFpGroupHomomorphismByImages - IsFromFpGroupStdGensGeneralMappingByImages - IsFromFpGroupStdGensHomomorphismByImages - IsFullFpAlgebra - IsFullHomModule - IsFullMatrixModule - IsFullRowModule - IsFullSCAlgebra - IsFullSubgroupGLorSLRespectingBilinearForm - IsFullSubgroupGLorSLRespectingQuadraticForm - IsFullSubgroupGLorSLRespectingSesquilinearForm - IsFullTransformationSemigroup - IsFunction - IsGL - IsGaussInt - IsGaussRat - IsGaussianIntegers - IsGaussianMatrixSpace - IsGaussianRationals - IsGaussianRowSpace - IsGaussianSpace - IsGeneralLinearGroup - IsGeneralMapping - IsGeneralMappingCollection - IsGeneralMappingFamily - IsGeneralPcgs - IsGeneralizedCartanMatrix - IsGeneralizedDomain - IsGeneralizedRowVector - IsGeneratorsOfMagmaWithInverses - IsGenericCharacterTableRep - IsGenericFiniteSpace - IsGreensClass - IsGreensDClass - IsGreensDRelation - IsGreensHClass - IsGreensHRelation - IsGreensJClass - IsGreensJRelation - IsGreensLClass - IsGreensLRelation - IsGreensLessThanOrEqual - IsGreensRClass - IsGreensRRelation - IsGreensRelation - IsGroup - IsGroupGeneralMapping - IsGroupGeneralMappingByAsGroupGeneralMappingByImages - IsGroupGeneralMappingByImages - IsGroupGeneralMappingByPcgs - IsGroupHClass - IsGroupHomomorphism - IsGroupOfAutomorphisms - IsGroupOfAutomorphismsFiniteGroup - IsGroupOfFamily - IsGroupRing - IsGroupToAdditiveGroupGeneralMapping - IsGroupToAdditiveGroupHomomorphism - IsHandledByNiceBasis - IsHandledByNiceMonomorphism - IsHash - IsHashTable - IsHasseDiagram - IsHomCoset - IsHomCosetCollection - IsHomCosetOfAdditiveElt - IsHomCosetOfFp - IsHomCosetOfMatrix - IsHomCosetOfPerm - IsHomCosetOfTuple - IsHomCosetToAdditiveElt - IsHomCosetToAdditiveEltCollection - IsHomCosetToAdditiveEltRep - IsHomCosetToFp - IsHomCosetToFpCollection - IsHomCosetToFpRep - IsHomCosetToMatrix - IsHomCosetToMatrixCollection - IsHomCosetToMatrixRep - IsHomCosetToObjectRep - IsHomCosetToPerm - IsHomCosetToPermCollection - IsHomCosetToPermRep - IsHomCosetToTuple - IsHomCosetToTupleCollection - IsHomCosetToTupleRep - IsHomQuotientGroup - IsHomogeneousList - IsIdeal - IsIdealInParent - IsIdealOp - IsIdempotent - IsIdenticalObj - IsIdenticalObjFamiliesColObjObj - IsIdenticalObjFamiliesColObjObjObj - IsIdenticalObjFamiliesColXXXObj - IsIdenticalObjFamiliesColXXXXXXObj - IsIdenticalObjFamiliesRwsObj - IsIdenticalObjFamiliesRwsObjObj - IsIdenticalObjFamiliesRwsObjXXX - IsIdenticalObjObjObjX - IsIdenticalObjObjXObj - IsImfMatrixGroup - IsImpossible - IsInBasicOrbit - IsInCenter - IsInCentre - IsInChain - IsIncomparableUnder - IsInducedFromNormalSubgroup - IsInducedPcgs - IsInducedPcgsRep - IsInducedPcgsWrtSpecialPcgs - IsInfBitsAssocWord - IsInfBitsFamily - IsInfiniteListOfGeneratorsRep - IsInfiniteListOfNamesRep - IsInfinity - IsInfoClass - IsInfoClassCollection - IsInfoClassListRep - IsInfoSelector - IsInjective - IsInnerAutomorphism - IsInputOutputStream - IsInputOutputStreamByPtyRep - IsInputStream - IsInputTextFileRep - IsInputTextNone - IsInputTextNoneRep - IsInputTextStream - IsInputTextStringRep - IsInt - IsIntegerMatrixGroup - IsIntegers - IsIntegralBasis - IsIntegralCyclotomic - IsIntegralRing - IsInternalRep - IsInternallyConsistent - IsInverseGeneralMappingRep - IsIrreducible - IsIrreducibleCharacter - IsIrreducibleRingElement - IsIterator - IsIteratorByFunctions - IsIteratorByFunctionsRep - IsJacobianElement - IsJacobianElementCollColl - IsJacobianElementCollection - IsJacobianRing - IsKernelPcWord - IsKnuthBendixRewritingSystem - IsKnuthBendixRewritingSystemRep - IsLDistributive - IsLatticeOrderBinaryRelation - IsLatticeSubgroupsRep - IsLaurentPolynomial - IsLaurentPolynomialDefaultRep - IsLaurentPolynomialsFamily - IsLaurentPolynomialsFamilyElement - IsLeftActedOnByDivisionRing - IsLeftActedOnByRing - IsLeftActedOnBySuperset - IsLeftAlgebraModule - IsLeftAlgebraModuleElement - IsLeftAlgebraModuleElementCollection - IsLeftIdeal - IsLeftIdealFromGenerators - IsLeftIdealInParent - IsLeftIdealOp - IsLeftMagmaCongruence - IsLeftMagmaIdeal - IsLeftModule - IsLeftModuleGeneralMapping - IsLeftModuleHomomorphism - IsLeftOperatorAdditiveGroup - IsLeftOperatorRing - IsLeftOperatorRingWithOne - IsLeftSemigroupCongruence - IsLeftSemigroupIdeal - IsLeftVectorSpace - IsLessThanOrEqualUnder - IsLessThanUnder - IsLetterAssocWordRep - IsLetterWordsFamily - IsLexicographicallyLess - IsLibTomRep - IsLibraryCharacterTableRep - IsLieAbelian - IsLieAlgebra - IsLieEmbeddingRep - IsLieFamFam - IsLieMatrix - IsLieNilpotent - IsLieNilpotentElement - IsLieObject - IsLieObjectCollection - IsLieObjectsModule - IsLieSolvable - IsLinearActionHomomorphism - IsLinearGeneralMappingByImagesDefaultRep - IsLinearMapping - IsLinearMappingByMatrixDefaultRep - IsLinearMappingsModule - IsLinearlyIndependent - IsLinearlyPrimitive - IsList - IsListDefault - IsListDictionary - IsListHashTable - IsListLookupDictionary - IsListOrCollection - IsLockedRepresentationVector - IsLookupDictionary - IsLowerAlphaChar - IsLowerTriangularMat - IsMagma - IsMagmaByMultiplicationTableObj - IsMagmaCollsMagmaRingColls - IsMagmaCongruence - IsMagmaHomomorphism - IsMagmaIdeal - IsMagmaRingModuloRelations - IsMagmaRingModuloSpanOfZero - IsMagmaRingObjDefaultRep - IsMagmaRingsMagmas - IsMagmaRingsRings - IsMagmaWithInverses - IsMagmaWithInversesIfNonzero - IsMagmaWithMultiplicativeZeroAdjoinedElementRep - IsMagmaWithOne - IsMagmasMagmaRings - IsMapping - IsMappingByFunctionRep - IsMappingByFunctionWithInverseRep - IsMatchingSublist - IsMatrix - IsMatrixCollection - IsMatrixFLMLOR - IsMatrixGroup - IsMatrixModule - IsMatrixSpace - IsMemberPcSeriesPermGroup - IsMinimalNonmonomial - IsModuloPcgs - IsModuloPcgsFpGroupRep - IsModuloPcgsPermGroupRep - IsModuloPcgsRep - IsModuloTailPcgsByListRep - IsModuloTailPcgsRep - IsModulusRep - IsMonoid - IsMonomial - IsMonomialCharacter - IsMonomialCharacterTable - IsMonomialElement - IsMonomialElementCollection - IsMonomialElementFamily - IsMonomialElementRep - IsMonomialGroup - IsMonomialMatrix - IsMonomialNumber - IsMonomialOrdering - IsMonomialOrderingDefaultRep - IsMultiplicativeElement - IsMultiplicativeElementCollColl - IsMultiplicativeElementCollCollColl - IsMultiplicativeElementCollection - IsMultiplicativeElementList - IsMultiplicativeElementTable - IsMultiplicativeElementWithInverse - IsMultiplicativeElementWithInverseByPolycyclicCollector - IsMultiplicativeElementWithInverseByPolycyclicCollectorCollection - IsMultiplicativeElementWithInverseByRws - IsMultiplicativeElementWithInverseCollColl - IsMultiplicativeElementWithInverseCollCollColl - IsMultiplicativeElementWithInverseCollection - IsMultiplicativeElementWithInverseList - IsMultiplicativeElementWithInverseTable - IsMultiplicativeElementWithOne - IsMultiplicativeElementWithOneCollColl - IsMultiplicativeElementWithOneCollCollColl - IsMultiplicativeElementWithOneCollection - IsMultiplicativeElementWithOneList - IsMultiplicativeElementWithOneTable - IsMultiplicativeElementWithZero - IsMultiplicativeElementWithZeroCollection - IsMultiplicativeGeneralizedRowVector - IsMultiplicativeZero - IsMutable - IsMutableBasis - IsMutableBasisByImmutableBasisRep - IsMutableBasisOfGaussianMatrixSpaceRep - IsMutableBasisOfGaussianRowSpaceRep - IsMutableBasisViaNiceMutableBasisRep - IsMutableBasisViaUnderlyingMutableBasisRep - IsNBitsPcWordRep - IsNameOfNoninstalledTableOfMarks - IsNaturalAlternatingGroup - IsNaturalGL - IsNaturalGLnZ - IsNaturalHomomorphismPcGroupRep - IsNaturalSL - IsNaturalSLnZ - IsNaturalSymmetricGroup - IsNearAdditiveElement - IsNearAdditiveElementCollColl - IsNearAdditiveElementCollCollColl - IsNearAdditiveElementCollection - IsNearAdditiveElementList - IsNearAdditiveElementTable - IsNearAdditiveElementWithInverse - IsNearAdditiveElementWithInverseCollColl - IsNearAdditiveElementWithInverseCollCollColl - IsNearAdditiveElementWithInverseCollection - IsNearAdditiveElementWithInverseList - IsNearAdditiveElementWithInverseTable - IsNearAdditiveElementWithZero - IsNearAdditiveElementWithZeroCollColl - IsNearAdditiveElementWithZeroCollCollColl - IsNearAdditiveElementWithZeroCollection - IsNearAdditiveElementWithZeroList - IsNearAdditiveElementWithZeroTable - IsNearAdditiveGroup - IsNearAdditiveMagma - IsNearAdditiveMagmaWithInverses - IsNearAdditiveMagmaWithZero - IsNearRing - IsNearRingElement - IsNearRingElementCollColl - IsNearRingElementCollCollColl - IsNearRingElementCollection - IsNearRingElementFamily - IsNearRingElementList - IsNearRingElementTable - IsNearRingElementWithInverse - IsNearRingElementWithInverseCollColl - IsNearRingElementWithInverseCollCollColl - IsNearRingElementWithInverseCollection - IsNearRingElementWithInverseList - IsNearRingElementWithInverseTable - IsNearRingElementWithOne - IsNearRingElementWithOneCollColl - IsNearRingElementWithOneCollCollColl - IsNearRingElementWithOneCollection - IsNearRingElementWithOneList - IsNearRingElementWithOneTable - IsNearRingWithOne - IsNearlyCharacterTable - IsNegInt - IsNegRat - IsNiceMonomorphism - IsNilpQuotientSystem - IsNilpotent - IsNilpotentCharacterTable - IsNilpotentElement - IsNilpotentGroup - IsNilpotentTom - IsNoImmediateMethodsObject - IsNonGaussianMatrixSpace - IsNonGaussianRowSpace - IsNonSPGeneralMapping - IsNonSPMappingByFunctionRep - IsNonSPMappingByFunctionWithInverseRep - IsNonTrivial - IsNonassocWord - IsNonassocWordCollection - IsNonassocWordFamily - IsNonassocWordWithOne - IsNonassocWordWithOneCollection - IsNonassocWordWithOneFamily - IsNoncharacteristicMatrixPGroup - IsNonnegativeIntegers - IsNormal - IsNormalBasis - IsNormalForm - IsNormalInParent - IsNormalOp - IsNotElmsColls - IsNotIdenticalObj - IsNullMapMatrix - IsNumberField - IsNumeratorParentForExponentsRep - IsNumeratorParentPcgsFamilyPcgs - IsObjToBePrinted - IsObject - IsOddAdditiveNestingDepthFamily - IsOddAdditiveNestingDepthObject - IsOddInt - IsOne - IsOperation - IsOperationAlgebraHomomorphismDefaultRep - IsOrdering - IsOrderingOnFamilyOfAssocWords - IsOrdinaryMatrix - IsOrdinaryMatrixCollection - IsOrdinaryTable - IsOutputStream - IsOutputTextFileRep - IsOutputTextNone - IsOutputTextNoneRep - IsOutputTextStream - IsOutputTextStringRep - IsPGroup - IsPNilpotent - IsPNilpotentOp - IsPQuotientSystem - IsPSL - IsPSolvable - IsPSolvableCharacterTable - IsPSolvableCharacterTableOp - IsPSolvableOp - IsPackedElementDefaultRep - IsPadicExtensionNumber - IsPadicExtensionNumberFamily - IsPadicNumber - IsPadicNumberCollColl - IsPadicNumberCollection - IsPadicNumberFamily - IsPadicNumberList - IsPadicNumberTable - IsParentPcgsFamilyPcgs - IsPartialOrderBinaryRelation - IsPartition - IsPcGroup - IsPcGroupGeneralMappingByImages - IsPcGroupHomomorphismByImages - IsPcgs - IsPcgsCentralSeries - IsPcgsChiefSeries - IsPcgsDefaultRep - IsPcgsElementaryAbelianSeries - IsPcgsFamily - IsPcgsPCentralSeriesPGroup - IsPcgsPermGroupRep - IsPcgsToPcgsGeneralMappingByImages - IsPcgsToPcgsHomomorphism - IsPerfect - IsPerfectCharacterTable - IsPerfectGroup - IsPerfectLibraryGroup - IsPerfectTom - IsPerm - IsPermCollColl - IsPermCollection - IsPermGroup - IsPermGroupGeneralMappingByImages - IsPermGroupHomomorphismByImages - IsPermOnEnumerator - IsPlistRep - IsPolycyclicCollector - IsPolycyclicGroup - IsPolynomial - IsPolynomialDefaultRep - IsPolynomialFunction - IsPolynomialFunctionCollection - IsPolynomialFunctionsFamily - IsPolynomialFunctionsFamilyElement - IsPolynomialRing - IsPolynomialRingIdeal - IsPosInt - IsPosRat - IsPositionDictionary - IsPositionLookupDictionary - IsPositionalObjectRep - IsPositionsList - IsPositiveIntegers - IsPowerCommutatorCollector - IsPowerConjugateCollector - IsPreOrderBinaryRelation - IsPreimagesByAsGroupGeneralMappingByImages - IsPresentation - IsPresentationDefaultRep - IsPrimGrpIterRep - IsPrime - IsPrimeField - IsPrimeInt - IsPrimeOrdersPcgs - IsPrimePowerInt - IsPrimitive - IsPrimitiveAffine - IsPrimitiveCharacter - IsPrimitiveMatrixGroup - IsPrimitivePolynomial - IsPrimitiveRootMod - IsProbablyPrimeInt - IsProbablyPrimeIntWithFail - IsProjectionDirectProductPermGroup - IsProjectionSubdirectProductPermGroup - IsPseudoCanonicalBasisFullHomModule - IsPurePadicNumber - IsPurePadicNumberFamily - IsQuasiDihedralGroup - IsQuasiPrimitive - IsQuaternion - IsQuaternionCollColl - IsQuaternionCollection - IsQuaternionGroup - IsQuickPositionList - IsQuotientSemigroup - IsQuotientSystem - IsQuotientToAdditiveGroup - IsQuotientToFpGroup - IsQuotientToMatrixGroup - IsQuotientToPermGroup - IsQuotientToTupleGroup - IsRDistributive - IsRange - IsRangeRep - IsRat - IsRationalClassGroupRep - IsRationalClassPermGroupRep - IsRationalFunction - IsRationalFunctionCollection - IsRationalFunctionDefaultRep - IsRationalFunctionOverField - IsRationalFunctionsFamily - IsRationalFunctionsFamilyElement - IsRationalMatrixGroup - IsRationals - IsRationalsPolynomialRing - IsReadOnlyGVar - IsReadOnlyGlobal - IsReadableFile - IsRecord - IsRecordCollColl - IsRecordCollection - IsRectangularTable - IsRectangularTablePlist - IsReduced - IsReducedConfluentRewritingSystem - IsReducedForm - IsReductionOrdering - IsReesCongruence - IsReesCongruenceSemigroup - IsReesMatrixSemigroup - IsReesMatrixSemigroupElement - IsReesMatrixSemigroupElementCollection - IsReesMatrixSemigroupElementRep - IsReesZeroMatrixSemigroup - IsReesZeroMatrixSemigroupElement - IsReesZeroMatrixSemigroupElementCollection - IsReflexiveBinaryRelation - IsRegular - IsRegularDClass - IsRegularSemigroup - IsRegularSemigroupElement - IsRelativeBasisDefaultRep - IsRelativelySM - IsRestrictedLieAlgebra - IsRewritingSystem - IsRightActedOnByDivisionRing - IsRightActedOnByRing - IsRightActedOnBySuperset - IsRightAlgebraModule - IsRightAlgebraModuleElement - IsRightAlgebraModuleElementCollection - IsRightCoset - IsRightCosetDefaultRep - IsRightIdeal - IsRightIdealFromGenerators - IsRightIdealInParent - IsRightIdealOp - IsRightMagmaCongruence - IsRightMagmaIdeal - IsRightModule - IsRightOperatorAdditiveGroup - IsRightSemigroupCongruence - IsRightSemigroupIdeal - IsRightTransversal - IsRightTransversalCollection - IsRightTransversalFpGroupRep - IsRightTransversalPcGroupRep - IsRightTransversalPermGroupRep - IsRightTransversalRep - IsRightTransversalViaCosetsRep - IsRing - IsRingCollsMagmaRingColls - IsRingElement - IsRingElementCollColl - IsRingElementCollCollColl - IsRingElementCollection - IsRingElementFamily - IsRingElementList - IsRingElementTable - IsRingElementWithInverse - IsRingElementWithInverseCollColl - IsRingElementWithInverseCollCollColl - IsRingElementWithInverseCollection - IsRingElementWithInverseList - IsRingElementWithInverseTable - IsRingElementWithOne - IsRingElementWithOneCollColl - IsRingElementWithOneCollCollColl - IsRingElementWithOneCollection - IsRingElementWithOneList - IsRingElementWithOneTable - IsRingGeneralMapping - IsRingHomomorphism - IsRingWithOne - IsRingWithOneGeneralMapping - IsRingWithOneHomomorphism - IsRingsMagmaRings - IsRootSystem - IsRootSystemFromLieAlgebra - IsRowModule - IsRowSpace - IsRowVector - IsSCAlgebraObj - IsSCAlgebraObjCollColl - IsSCAlgebraObjCollCollColl - IsSCAlgebraObjCollection - IsSCAlgebraObjFamily - IsSCAlgebraObjSpace - IsSL - IsSPGeneralMapping - IsSPMappingByFunctionRep - IsSPMappingByFunctionWithInverseRep - IsSSortedList - IsScalar - IsScalarCollColl - IsScalarCollection - IsScalarList - IsScalarTable - IsSearchTable - IsSemiEchelonBasisOfGaussianMatrixSpaceRep - IsSemiEchelonBasisOfGaussianRowSpaceRep - IsSemiEchelonized - IsSemiRegular - IsSemigroup - IsSemigroupCongruence - IsSemigroupIdeal - IsSemiring - IsSemiringWithOne - IsSemiringWithOneAndZero - IsSemiringWithZero - IsSet - IsShortLexLessThanOrEqual - IsShortLexOrdering - IsSimple - IsSimpleAlgebra - IsSimpleCharacterTable - IsSimpleGroup - IsSimpleSemigroup - IsSingleCollectorRep - IsSingleValued - IsSkewFieldFamily - IsSlicedPerm - IsSlicedPermInv - IsSmallIntRep - IsSmallList - IsSolvable - IsSolvableCharacterTable - IsSolvableGroup - IsSolvableTom - IsSortDictionary - IsSortLookupDictionary - IsSortedList - IsSortedPcgsRep - IsSpaceOfElementsOfMagmaRing - IsSpaceOfRationalFunctions - IsSpaceOfUEAElements - IsSparseHashRep - IsSparseRowSpaceElement - IsSparseRowSpaceElementCollection - IsSparseRowSpaceElementFamily - IsSpecialLinearGroup - IsSpecialPcgs - IsSporadicSimple - IsSporadicSimpleCharacterTable - IsSporadicSimpleGroup - IsStabChainViaChainSubgroup - IsStandardGeneratorsOfGroup - IsStandardized - IsStraightLineProgElm - IsStraightLineProgram - IsStream - IsString - IsStringRep - IsSubalgebraFpAlgebra - IsSubgroup - IsSubgroupFgGroup - IsSubgroupFpGroup - IsSubgroupOfWholeGroupByQuotientRep - IsSubgroupSL - IsSubmonoidFpMonoid - IsSubnormal - IsSubnormallyMonomial - IsSubsemigroupFpSemigroup - IsSubsemigroupReesMatrixSemigroup - IsSubsemigroupReesZeroMatrixSemigroup - IsSubset - IsSubsetBlist - IsSubsetInducedNumeratorModuloTailPcgsRep - IsSubsetInducedPcgsRep - IsSubsetLocallyFiniteGroup - IsSubsetSet - IsSubspace - IsSubspacesFullRowSpaceDefaultRep - IsSubspacesVectorSpace - IsSubspacesVectorSpaceDefaultRep - IsSupersolvable - IsSupersolvableCharacterTable - IsSupersolvableGroup - IsSurjective - IsSyllableAssocWordRep - IsSyllableWordsFamily - IsSymmetricBinaryRelation - IsSymmetricGroup - IsSymmetricPowerElement - IsSymmetricPowerElementCollection - IsTable - IsTableOfMarks - IsTableOfMarksWithGens - IsTailInducedPcgsRep - IsTensorElement - IsTensorElementCollection - IsToBeDefinedObj - IsToFpGroupGeneralMappingByImages - IsToFpGroupHomomorphismByImages - IsToPcGroupGeneralMappingByImages - IsToPcGroupHomomorphismByImages - IsToPermGroupGeneralMappingByImages - IsToPermGroupHomomorphismByImages - IsTotal - IsTotalOrdering - IsTransformation - IsTransformationCollection - IsTransformationMonoid - IsTransformationRep - IsTransformationRepOfEndo - IsTransformationSemigroup - IsTransitive - IsTransitiveBinaryRelation - IsTranslationInvariantOrdering - IsTransvByDirProd - IsTransvByDirProdCollection - IsTransvByHomomorphism - IsTransvByHomomorphismCollection - IsTransvBySchreierTree - IsTransvBySchreierTreeCollection - IsTransvBySiftFunct - IsTransvBySiftFunctCollection - IsTransvByTrivSubgrp - IsTransvByTrivSubgrpCollection - IsTrivial - IsTrivialAOpEZero - IsTrivialHomCoset - IsTrivialLOpEOne - IsTrivialLOpEZero - IsTrivialRBase - IsTrivialROpEOne - IsTrivialROpEZero - IsTrivialUOpEOne - IsTrivialUOpEZero - IsTuple - IsTupleCollection - IsTupleFamily - IsTwoSidedIdeal - IsTwoSidedIdealInParent - IsTwoSidedIdealOp - IsType - IsTypeDefaultRep - IsUEALatticeElement - IsUEALatticeElementCollection - IsUEALatticeElementFamily - IsUFDFamily - IsUniformMatrixGroup - IsUniqueFactorizationRing - IsUnit - IsUnivariatePolynomial - IsUnivariatePolynomialRing - IsUnivariatePolynomialsFamily - IsUnivariatePolynomialsFamilyElement - IsUnivariateRationalFunction - IsUnivariateRationalFunctionDefaultRep - IsUnknown - IsUnknownDefaultRep - IsUnsortedPcgsRep - IsUpToDatePolycyclicCollector - IsUpperActedOnByGroup - IsUpperActedOnBySuperset - IsUpperAlphaChar - IsUpperTriangularMat - IsValidIdentifier - IsVector - IsVectorCollColl - IsVectorCollection - IsVectorList - IsVectorSearchTable - IsVectorSearchTableDefaultRep - IsVectorSpace - IsVectorSpaceHomomorphism - IsVectorTable - IsVirtualCharacter - IsWLetterAssocWordRep - IsWLetterWordsFamily - IsWPObj - IsWeakPointerObject - IsWedgeElement - IsWedgeElementCollection - IsWeightLexOrdering - IsWeightRepElement - IsWeightRepElementCollection - IsWeightRepElementFamily - IsWellFoundedOrdering - IsWeylGroup - IsWholeFamily - IsWord - IsWordCollection - IsWordWithInverse - IsWordWithOne - IsWreathProductElement - IsWreathProductElementCollection - IsWreathProductElementDefaultRep - IsWreathProductOrdering - IsWritableFile - IsZDFRE - IsZDFRECollColl - IsZDFRECollection - IsZero - IsZeroCochainRep - IsZeroCyc - IsZeroGroup - IsZeroMultiplicationRing - IsZeroRationalFunction - IsZeroSimpleSemigroup - IsZeroSquaredElement - IsZeroSquaredElementCollColl - IsZeroSquaredElementCollection - IsZeroSquaredRing - IsZmodnZObj - IsZmodnZObjNonprime - IsZmodnZObjNonprimeCollColl - IsZmodnZObjNonprimeCollCollColl - IsZmodnZObjNonprimeCollection - IsZmodnZObjNonprimeFamily - IsZmodpZObj - IsZmodpZObjLarge - IsZmodpZObjSmall - IsolatePoint - IsomorphicSubgroups - IsomorphismAbelianGroups - IsomorphismFpAlgebra - IsomorphismFpFLMLOR - IsomorphismFpGroup - IsomorphismFpGroupByCompositionSeries - IsomorphismFpGroupByGenerators - IsomorphismFpGroupByGeneratorsNC - IsomorphismFpGroupByPcgs - IsomorphismFpGroupBySubnormalSeries - IsomorphismFpMonoid - IsomorphismFpSemigroup - IsomorphismGroups - IsomorphismMatrixAlgebra - IsomorphismMatrixFLMLOR - IsomorphismPcGroup - IsomorphismPermGroup - IsomorphismPermGroupImfGroup - IsomorphismPermGroupOrFailFpGroup - IsomorphismPermGroups - IsomorphismReesMatrixSemigroup - IsomorphismRefinedPcGroup - IsomorphismSCAlgebra - IsomorphismSCFLMLOR - IsomorphismSimplifiedFpGroup - IsomorphismSolvableSmallGroups - IsomorphismSpecialPcGroup - IsomorphismToFullRowSpace - IsomorphismTransformationSemigroup - IsomorphismTypeInfoFiniteSimpleGroup - Iterated - Iterator - IteratorByBasis - IteratorByFunctions - IteratorList - IteratorSorted - IteratorsFamily - Jacobi - JenningsLieAlgebra - JenningsSeries - JoinEquivalenceRelations - JoinMagmaCongruences - JoinSemigroupCongruences - JoinStringsWithSeparator - JordanDecomposition - KBOverlaps - KappaPerp - Kernel - KernelHcommaC - KernelOfAdditiveGeneralMapping - KernelOfCharacter - KernelOfHomQuotientGroup - KernelOfMultiplicativeGeneralMapping - KernelOfTransformation - KernelUnderDualAction - KeyDependentOperation - KillingMatrix - KnownAttributesOfObject - KnownNaturalHomomorphismsPool - KnownPropertiesOfObject - KnownTruePropertiesOfObject - KnowsDictionary - KnowsHowToDecompose - KnuthBendixRewritingSystem - KroneckerProduct - KuKGenerators - LClassOfHClass - LGFirst - LGHeads - LGLayers - LGLength - LGTails - LGWeights - LLLReducedBasis - LLLReducedGramMat - LLLint - LMPSLPSeed - LaTeX - LaTeXObj - LaTeXStringDecompositionMatrix - LaTeXToHTMLString - LabsLims - Lambda - LargeGaloisField - LargestElementGroup - LargestElementStabChain - LargestMovedPoint - LargestMovedPointPerm - LargestMovedPointPerms - LargestUnknown - LastHashIndex - LastReadValue - LastSystemError - LatticeByCyclicExtension - LatticeGeneratorsInUEA - LatticeSubgroups - LatticeSubgroupsByTom - LaurentPolynomialByCoefficients - LaurentPolynomialByExtRep - Lcm - LcmInt - LcmOp - LcmPP - LeadCoeffsIGS - LeadingCoefficient - LeadingCoefficientOfPolynomial - LeadingExponentOfPcElement - LeadingMonomial - LeadingMonomialOfPolynomial - LeadingMonomialPosExtRep - LeadingTermOfPolynomial - LeadingUEALatticeMonomial - LeastBadComplementLayer - LeastBadHallLayer - LeftActingAlgebra - LeftActingDomain - LeftActingGroup - LeftActingRingOfIdeal - LeftAction - LeftAlgebraModule - LeftAlgebraModuleByGenerators - LeftDerivations - LeftIdeal - LeftIdealByGenerators - LeftIdealNC - LeftMagmaCongruence - LeftMagmaCongruenceByGeneratingPairs - LeftMagmaIdeal - LeftMagmaIdealByGenerators - LeftModuleByGenerators - LeftModuleByHomomorphismToMatAlg - LeftModuleGeneralMappingByImages - LeftModuleGeneratorsForIdealFromGenerators - LeftModuleHomomorphismByImages - LeftModuleHomomorphismByImagesNC - LeftModuleHomomorphismByMatrix - LeftNormedComm - LeftQuotient - LeftQuotientPowerPcgsElement - LeftReduceUEALatticeElement - LeftSemigroupCongruenceByGeneratingPairs - LeftSemigroupIdealEnumeratorDataGetElement - LeftShiftRowVector - Legendre - Length - LengthOfDescendingSeries - LengthOfLongestCommonPrefixOfTwoAssocWords - LengthWPObj - LengthsTom - LenstraBase - LessBoxedObj - LessThanFunction - LessThanOrEqualFunction - LetterRepAssocWord - LetterRepWordsLessFunc - LevelsOfGenerators - LeviMalcevDecomposition - LexicographicOrdering - LexicographicOrderingNC - LieAlgebra - LieAlgebraByDomain - LieAlgebraByStructureConstants - LieBracket - LieCenter - LieCentralizer - LieCentralizerInParent - LieCentre - LieCoboundaryOperator - LieDerivedSeries - LieDerivedSubalgebra - LieFamily - LieLowerCentralSeries - LieNilRadical - LieNormalizer - LieNormalizerInParent - LieObject - LieSolvableRadical - LieUpperCentralSeries - LiftAbsAndIrredModules - LiftEpimorphism - LiftEpimorphismSQ - LiftInduciblePair - LiftedInducedPcgs - LiftedPcElement - LineNumberStringPosition - LinearAction - LinearActionBasis - LinearActionLayer - LinearCharacters - LinearCombination - LinearCombinationPcgs - LinearCombinationVecs - LinearGroupParameters - LinearIndependentColumns - LinearOperation - LinearOperationLayer - LinesOfStraightLineProgram - List - ListBlist - ListHashParams - ListN - ListOp - ListPerm - ListSorted - ListStabChain - ListWithIdenticalEntries - ListX - ListXHelp - ListsFamily - LoadAllPackages - LoadDynamicModule - LoadPackage - LoadPackageDocumentation - LoadStaticModule - LoadedModules - LockNaturalHomomorphismsPool - Log - LogFFE - LogInputTo - LogInt - LogMod - LogModRhoIterate - LogModShanks - LogOutputTo - LogTo - LongestWeylWordPerm - LookupDictionary - LowIndexSubgroupsFpGroup - LowerCentralSeries - LowerCentralSeriesOfGroup - LowerTriangularMatrix - LowercaseString - Lucas - MATINTbezout - MATINTmgcdex - MATINTrgcd - MATINTsplit - Magma - MagmaByGenerators - MagmaByMultiplicationTable - MagmaByMultiplicationTableCreator - MagmaCongruenceByGeneratingPairs - MagmaCongruencePartition - MagmaElement - MagmaGeneratorsOfFamily - MagmaHomomorphismByFunctionNC - MagmaIdeal - MagmaIdealByGenerators - MagmaInputString - MagmaIsomorphismByFunctionsNC - MagmaRingModuloSpanOfZero - MagmaWithInverses - MagmaWithInversesByGenerators - MagmaWithInversesByMultiplicationTable - MagmaWithOne - MagmaWithOneByGenerators - MagmaWithOneByMultiplicationTable - MakeCanonical - MakeConfluent - MakeConsequences - MakeConsequencesPres - MakeFormulaVector - MakeGAPDocDoc - MakeHomChain - MakeImagesInfoLinearGeneralMappingByImages - MakeImmutable - MakeKnuthBendixRewritingSystemConfluent - MakeLIBTOMLIST - MakeMagmaWithInversesByFiniteGenerators - MakeMapping - MakeMonomialOrdering - MakePreImagesInfoLinearGeneralMappingByImages - MakePreImagesInfoLinearMappingByMatrix - MakePreImagesInfoOperationAlgebraHomomorphism - MakeReadOnlyGVar - MakeReadOnlyGlobal - MakeReadWriteGVar - MakeReadWriteGlobal - MakeStabChainLong - ManageableQuotientOfAbelianPGroup - ManageableQuotientOfNilpotentGroup - MappedExpression - MappedExpressionForElementOfFreeAssociativeAlgebra - MappedPcElement - MappedVector - MappedWord - MappedWordSyllableAssocWord - MappingByFunction - MappingGeneratorsImages - MappingOfWhichItIsAsGGMBI - MappingPermListList - MarksTom - MatAlgebra - MatAutomorphismsFamily - MatCharsWreathSymmetric - MatClassMultCoeffsCharTable - MatLieAlgebra - MatOrbs - MatOrbsApprox - MatScalarProducts - MatSpace - MatTom - MathieuGroup - MathieuGroupCons - MatricesOfRelator - MatrixAlgebra - MatrixAutomorphisms - MatrixByBlockMatrix - MatrixDimension - MatrixLieAlgebra - MatrixNewBasePoint - MatrixOfAction - MatrixOperationOfCP - MatrixOperationOfCPGroup - MatrixSpace - MatrixSpinCharsSn - MaxHashViewSize - MaxNumeratorCoeffAlgElm - MaximalAbelianQuotient - MaximalBlocks - MaximalBlocksAttr - MaximalBlocksOp - MaximalNormalSubgroups - MaximalSubgroupClassReps - MaximalSubgroupClassesRepsLayer - MaximalSubgroups - MaximalSubgroupsLattice - MaximalSubgroupsSymmAlt - MaximalSubgroupsTom - Maximum - MaximumList - MeetEquivalenceRelations - MeetMagmaCongruences - MeetMaps - MeetPartitionStrat - MeetPartitionStratCell - MeetSemigroupCongruences - MembershipTestKnownBase - MinimalBlockDimension - MinimalElementCosetStabChain - MinimalGeneratingSet - MinimalGensLayer - MinimalNonmonomialGroup - MinimalNormalSubgroups - MinimalPolynomial - MinimalPolynomialMatrixNC - MinimalStabChain - MinimalSupergroupsLattice - MinimalSupergroupsTom - MinimizeExplicitTransversal - MinimizedBombieriNorm - Minimum - MinimumGroupOnSubgroupsOrbit - MinimumList - MinusCharacter - ModGauss - ModifyMinGens - ModifyPcgs - ModularCharacterDegree - ModuleByRestriction - ModuleOfExtension - ModuloPcgs - ModuloPcgsByPcSequence - ModuloPcgsByPcSequenceNC - ModuloTailPcgsByList - ModulusOfZmodnZObj - MoebiusMu - MoebiusTom - MolienSeries - MolienSeriesInfo - MolienSeriesWithGivenDenominator - Monoid - MonoidByGenerators - MonoidByMultiplicationTable - MonoidOfRewritingSystem - MonomialComparisonFunction - MonomialExtGrlexLess - MonomialExtrepComparisonFun - MonomialGrevlexOrdering - MonomialGrlexOrdering - MonomialLexOrdering - MonomialOrderingsFamily - MonomialTotalDegreeLess - MorClassLoop - MorClassOrbs - MorFindGeneratingSystem - MorFroWords - MorMaxFusClasses - MorRatClasses - Morphium - MorrisRecursion - MostFrequentGeneratorFpGroup - MovedPoints - MovedPointsPerms - MulExt - MultCoeffs - MultMatrixPadicNumbersByCoefficientsList - MultRowVector - MultiplicationTable - MultiplicativeElementsWithInversesFamilyByRws - MultiplicativeNeutralElement - MultiplicativeZero - MultiplicativeZeroOp - Multiply - MutableBasis - MutableBasisOfClosureUnderAction - MutableBasisOfIdealInNonassociativeAlgebra - MutableBasisOfNonassociativeAlgebra - MutableBasisOfProductSpace - MutableCopyMat - MutableIdentityMat - MutableNullMat - MutableTransposedMat - MutableTransposedMatDestructive - MyFingerprint - MyIntCoefficients - Naive - Name - NameFunction - NameIsomorphismClass - NameMonth - NameRNam - NameWeekDay - NamesFilter - NamesGVars - NamesLibTom - NamesLocalVariablesFunction - NamesOfComponents - NamesOfFusionSources - NamesSystemGVars - NamesUserGVars - NaturalActedSpace - NaturalCharacter - NaturalHomomorphismByFixedPointSubspace - NaturalHomomorphismByGenerators - NaturalHomomorphismByHomVW - NaturalHomomorphismByIdeal - NaturalHomomorphismByInvariantSubspace - NaturalHomomorphismByNilpotentClassTwoElement - NaturalHomomorphismByNormalSubgroup - NaturalHomomorphismByNormalSubgroupInParent - NaturalHomomorphismByNormalSubgroupNC - NaturalHomomorphismByNormalSubgroupNCInParent - NaturalHomomorphismByNormalSubgroupNCOp - NaturalHomomorphismByNormalSubgroupNCOrig - NaturalHomomorphismByNormalSubgroupOp - NaturalHomomorphismBySubAlgebraModule - NaturalHomomorphismBySubspace - NaturalHomomorphismBySubspaceOntoFullRowSpace - NaturalHomomorphismsPool - NaturalIsomorphismByPcgs - NearAdditiveGroup - NearAdditiveGroupByGenerators - NearAdditiveMagma - NearAdditiveMagmaByGenerators - NearAdditiveMagmaWithInverses - NearAdditiveMagmaWithInversesByGenerators - NearAdditiveMagmaWithZero - NearAdditiveMagmaWithZeroByGenerators - NearlyCharacterTablesFamily - NegativeRootVectors - NegativeRoots - NestingDepthA - NestingDepthM - NewAttribute - NewCategory - NewConstructor - NewDictionary - NewFamily - NewFilter - NewInfoClass - NewOperation - NewProperty - NewRepresentation - NewToBeDefinedObj - NewType - NewmanInfinityCriterion - NextIterator - NextLevelRegularGroups - NextPrimeInt - NextRBasePoint - NextStepCentralizer - NiceAlgebraMonomorphism - NiceBasis - NiceBasisFiltersInfo - NiceBasisNC - NiceFreeLeftModule - NiceFreeLeftModuleForFLMLOR - NiceFreeLeftModuleInfo - NiceMonomorphism - NiceMonomorphismAutomGroup - NiceNormalFormByExtRepFunction - NiceObject - NiceVector - NicomorphismOfFFEMatrixGroup - NicomorphismOfGeneralMatrixGroup - NilpotencyClassOfGroup - NilpotentClassTwoElement - NilpotentQuotientOfFpLieAlgebra - NinKernelCSPG - NonLieNilpotentElement - NonNilpotentElement - NonPerfectCSPG - NonSplitExtensions - NonTrivialRightHandSides - NonassocWord - NonnegIntScalarProducts - NonnegativeIntegers - NorSerPermPcgs - Norm - NormalBase - NormalClosure - NormalClosureByChain - NormalClosureInParent - NormalClosureOp - NormalFormIntMat - NormalIntersection - NormalIntersectionPcgs - NormalMaximalSubgroups - NormalSeriesByPcgs - NormalSubgroupClasses - NormalSubgroupClassesInfo - NormalSubgroups - NormalSubgroupsAbove - NormalSubgroupsCalc - NormalizeNameAndKey - NormalizeWhitespace - NormalizedArgList - NormalizedElementOfMagmaRingModuloRelations - NormalizedNameAndKey - NormalizedWhitespace - Normalizer - NormalizerInGLnZ - NormalizerInGLnZBravaisGroup - NormalizerInHomePcgs - NormalizerInParent - NormalizerOp - NormalizerParentSA - NormalizerStabCSPG - NormalizerTom - NormalizersTom - NormalizingReducedGL - NormedRowVector - NormedRowVectors - NormedVectors - NotifiedFusionsOfLibTom - NotifiedFusionsToLibTom - NrAffinePrimitiveGroups - NrArrangements - NrArrangementsMSetA - NrArrangementsMSetK - NrArrangementsSetA - NrArrangementsSetK - NrArrangementsX - NrBasisVectors - NrBitsInt - NrCombinations - NrCombinationsMSetA - NrCombinationsMSetK - NrCombinationsSetA - NrCombinationsSetK - NrCombinationsX - NrCompatiblePolynomials - NrConjugacyClasses - NrConjugacyClassesGL - NrConjugacyClassesGU - NrConjugacyClassesInSupergroup - NrConjugacyClassesPGL - NrConjugacyClassesPGU - NrConjugacyClassesPSL - NrConjugacyClassesPSU - NrConjugacyClassesSL - NrConjugacyClassesSLIsogeneous - NrConjugacyClassesSU - NrConjugacyClassesSUIsogeneous - NrDerangements - NrDerangementsK - NrInputsOfStraightLineProgram - NrIrreducibleSolvableGroups - NrMovedPoints - NrMovedPointsPerm - NrMovedPointsPerms - NrOrderedPartitions - NrPartitionTuples - NrPartitions - NrPartitionsSet - NrPerfectGroups - NrPerfectLibraryGroups - NrPermutationsList - NrPolyhedralSubgroups - NrPrimitiveGroups - NrRestrictedPartitions - NrRestrictedPartitionsK - NrSmallGroups - NrSolvableAffinePrimitiveGroups - NrSubsTom - NrSyllables - NrTransitiveGroups - NrTuples - NrUnorderedTuples - NthChainSubgroup - NthFundamentalOrbit - NthRoot - NthSchreierTransversalOfChainSubgroup - NthSiftOneLevel - Nucleus - NullAlgebra - NullMapMatrix - NullMat - NullspaceIntMat - NullspaceMat - NullspaceMatDestructive - NullspaceModQ - NumBol - Number - NumberArgumentsFunction - NumberCells - NumberCoset - NumberDigits - NumberFFVector - NumberField - NumberGeneratorsOfRws - NumberIrreducibleSolvableGroups - NumberOfCommutators - NumberOfNewGenerators - NumberOp - NumberPerfectGroups - NumberPerfectLibraryGroups - NumberSmallGroups - NumberSyllables - NumeratorOfModuloPcgs - NumeratorOfRationalFunction - NumeratorRat - OCAddBigMatrices - OCAddCentralizer - OCAddComplement - OCAddGenerators - OCAddGeneratorsGeneral - OCAddGeneratorsPcgs - OCAddMatrices - OCAddRelations - OCAddSumMatrices - OCAddToFunctions - OCConjugatingWord - OCCoprimeComplement - OCEquationMatrix - OCEquationVector - OCNormalRelations - OCOneCoboundaries - OCOneCocycles - OCSmallEquationMatrix - OCSmallEquationVector - OCTestRelations - OCTestRelators - ONanScottType - ObjByExponents - ObjByExtRep - ObjByVector - Objectify - ObjectifyWithAttributes - OccuringVariableIndices - OctaveAlgebra - OddSpinVals - OldGeneratorsOfPresentation - OldKernelHcommaC - OldSubspaceVectorSpaceGroup - Omega - OmegaAndLowerPCentralSeries - OmegaOp - OmegaSeries - OminusEven - OnBreak - OnBreakMessage - OnCharReadHookExcFds - OnCharReadHookExcFuncs - OnCharReadHookExcStreams - OnCharReadHookInFds - OnCharReadHookInFuncs - OnCharReadHookInStreams - OnCharReadHookOutFds - OnCharReadHookOutFuncs - OnCharReadHookOutStreams - OnCocycle - OnIndeterminates - OnLeftAntiOperation - OnLeftInverse - OnLines - OnPairs - OnPoints - OnQuit - OnRelVector - OnRight - OnSets - OnSetsDisjointSets - OnSetsSets - OnSetsTuples - OnSubspacesByCanonicalBasis - OnTuples - OnTuplesSets - OnTuplesTuples - One - OneAttr - OneCoboundaries - OneCocycles - OneFactorBound - OneGroup - OneImmutable - OneIrreducibleSolvableGroup - OneMutable - OneNormalizerfixedBlockSystem - OneOfPcgs - OneOp - OnePrimitiveGroup - OneSM - OneSameMutability - OneSmallGroup - OneTransitiveGroup - OperationAlgebraHomomorphism - OperatorOfExternalSet - OplusEven - OpmOdd - OpmSmall - OptionsStack - Orbit - OrbitByPosOp - OrbitChar - OrbitFusions - OrbitGenerators - OrbitGeneratorsInv - OrbitGeneratorsOfGroup - OrbitLength - OrbitLengthOp - OrbitLengths - OrbitLengthsDomain - OrbitOp - OrbitPerms - OrbitPowerMaps - OrbitRepresentativesCharacters - OrbitShortVectors - OrbitSplit - OrbitStabChain - OrbitStabilizer - OrbitStabilizerAlgorithm - OrbitStabilizerOp - OrbitStabilizingParentGroup - OrbitalPartition - OrbitishFO - OrbitishReq - Orbits - OrbitsByPosOp - OrbitsCharacters - OrbitsDomain - OrbitsPartition - OrbitsPerms - OrbitsishOperation - OrbitsishReq - Order - OrderKnownDividendList - OrderMatLimit - OrderMatTrial - OrderMod - OrderModK - OrderOfRewritingSystem - OrderOfSchurLift - OrderPerm - OrderedPartitions - OrderedPartitionsA - OrderedPartitionsK - OrderingByLessThanFunctionNC - OrderingByLessThanOrEqualFunctionNC - OrderingOfRewritingSystem - OrderingOnGenerators - OrderingsFamily - OrdersClassRepresentatives - OrdersTom - Ordinal - OrdinaryCharacterTable - OrthogonalComponents - OrthogonalEmbeddings - OrthogonalEmbeddingsSpecialDimension - OrthogonalSpaceInFullRowSpace - OrthogonalityDefectEuclideanLattice - OutdatePolycyclicCollector - OutputLogTo - OutputTextFile - OutputTextFileStillOpen - OutputTextFileType - OutputTextNone - OutputTextNoneType - OutputTextString - OutputTextStringType - OutputTextUser - OzeroEven - OzeroOdd - PBIsMinimal - PCentralLieAlgebra - PCentralNormalSeriesByPcgsPGroup - PCentralSeries - PCentralSeriesOp - PClassPGroup - PCore - PCoreOp - PCover - PERFRec - PGroupGeneratorsOfAbelianGroup - PMultiplicator - PQStatistics - PQuotient - PRIMGrp - PRump - PRumpOp - PSLDegree - PSLUnderlyingField - PSp - PackageInfo - PackageVariablesInfo - PadicCoefficients - PadicExpansionByRat - PadicExtensionNumberFamily - PadicNumber - Page - PageDisplay - Pager - Parametrized - Parent - ParentAttr - ParentPcgs - ParityPol - ParseArguments - ParseBibFiles - ParseError - ParseTreeXMLString - PartialClosureOfCongruence - PartialOrderByOrderingFunction - PartialOrderOfHasseDiagram - Partition - PartitionBacktrack - PartitionSortedPoints - PartitionStabilizerPermGroup - PartitionTuples - Partitions - PartitionsA - PartitionsGreatestEQ - PartitionsGreatestLE - PartitionsK - PartitionsRecursively - PartitionsSet - PartitionsSetA - PartitionsSetK - PartitionsTest - PcElementByExponents - PcElementByExponentsNC - PcGroupClassMatrixColumn - PcGroupCode - PcGroupCodeRec - PcGroupFpGroup - PcGroupFpGroupNC - PcGroupWithPcgs - PcSeries - Pcgs - PcgsByIndependentGeneratorsOfAbelianGroup - PcgsByPcSequence - PcgsByPcSequenceCons - PcgsByPcSequenceNC - PcgsCentralSeries - PcgsChiefSeries - PcgsElAbSerFromSpecPcgs - PcgsElementaryAbelianSeries - PcgsHomSoImPow - PcgsMemberPcSeriesPermGroup - PcgsPCentralSeriesPGroup - PcgsStabChainSeries - PcgsSystemLGSeries - PcgsSystemWithComplementSystem - PcgsSystemWithHallSystem - PcgsSystemWithWf - PerfGrpConst - PerfGrpLoad - PerfectCSPG - PerfectCentralProduct - PerfectGroup - PerfectIdentification - PerfectResiduum - PerfectSubdirectProduct - PerfectSubgroupsAlternatingGroup - Perform - PermBounds - PermCandidates - PermCandidatesFaithful - PermCharInfo - PermCharInfoRelative - PermChars - PermCharsTom - PermComb - PermLeftQuoTransformation - PermList - PermListList - PermMatrixGroup - PermNatAnTestDetect - PermNewBasePoint - PermOnEnumerator - Permanent - PermgpContainsAn - PermpcgsPcGroupPcgs - Permut - Permutation - PermutationCharacter - PermutationCycle - PermutationCycleOp - PermutationGModule - PermutationMat - PermutationOp - PermutationToSortCharacters - PermutationToSortClasses - PermutationTom - PermutationsFamily - PermutationsList - PermutationsListK - Permuted - Phi - PlainListCopy - PlainListCopyOp - PointInCellNo - PolycyclicFactorGroup - PolycyclicFactorGroupByRelators - PolycyclicFactorGroupByRelatorsNC - PolycyclicFactorGroupNC - PolynomialByExtRep - PolynomialByExtRepNC - PolynomialCoefficientsOfPolynomial - PolynomialDivisionAlgorithm - PolynomialModP - PolynomialReducedRemainder - PolynomialReduction - PolynomialRing - PopOptions - PosSublOdd - PosVecEnumFF - Position - PositionBound - PositionCanonical - PositionFirstComponent - PositionMatchingDelimiter - PositionNonZero - PositionNot - PositionNthOccurrence - PositionNthTrueBlist - PositionProperty - PositionSet - PositionSorted - PositionStream - PositionSublist - PositionWord - PositionsTrueBlist - PositiveExponentsPresentationFpHom - PositiveIntegers - PositiveRootVectors - PositiveRoots - PositiveRootsAsWeights - PossibleClassFusions - PossibleFusionsCharTableTom - PossiblePowerMaps - PostMakeImmutable - Pover - PowerDecompositions - PowerMap - PowerMapByComposition - PowerMapOfGroup - PowerMapOfGroupWithInvariants - PowerMapOp - PowerMapsAllowedBySymmetrisations - PowerMapsAllowedBySymmetrizations - PowerMod - PowerModCoeffs - PowerModEvalPol - PowerModInt - PowerPartition - PowerPcgsElement - PowerS - PowerSi - PowerSubalgebraSeries - PowerWreath - PowersumsElsyms - PreBasis - PreImage - PreImageElm - PreImageSetStabBlocksHomomorphism - PreImageWord - PreImages - PreImagesElm - PreImagesRange - PreImagesRepresentative - PreImagesRepresentativeOperationAlgebraHomomorphism - PreImagesSet - PreOrbishProcessing - PreferredGenerators - PrefrattiniSubgroup - PreimagesOfTransformation - Presentation - PresentationAugmentedCosetTable - PresentationFpGroup - PresentationNormalClosure - PresentationNormalClosureRrs - PresentationRegularPermutationGroup - PresentationRegularPermutationGroupNC - PresentationSubgroup - PresentationSubgroupMtc - PresentationSubgroupRrs - PresentationViaCosetTable - PresentationsFamily - PrevPrimeInt - PriGroItNext - PrimGrpLoad - PrimaryGeneratorWords - PrimeBlocks - PrimeBlocksOp - PrimeField - PrimeOfPGroup - PrimePGroup - PrimePowerComponent - PrimePowerComponents - PrimePowerPcSequence - PrimePowersInt - PrimeResidues - PrimeResiduesCache - Primes - PrimitiveElement - PrimitiveFacExtRepRatPol - PrimitiveGroup - PrimitiveGroupSims - PrimitiveGroupsIterator - PrimitiveIdentification - PrimitiveIndexIrreducibleSolvableGroup - PrimitivePolynomial - PrimitiveRoot - PrimitiveRootMod - Print - PrintAmbiguity - PrintArray - PrintBibAsBib - PrintBibAsHTML - PrintBibAsText - PrintCharacterTable - PrintCounters - PrintFactorsInt - PrintFormattedString - PrintFormattingStatus - PrintGAPDocElementTemplates - PrintHashWithNames - PrintObj - PrintPadicExpansion - PrintRecIndent - PrintSixFile - PrintTo - ProbabilityShapes - Process - ProcessFixpoint - ProdCoefRatfun - ProdCoeffLaurpol - ProdCoeffUnivfunc - Product - ProductCoeffs - ProductMod - ProductOp - ProductPP - ProductPol - ProductRootsPol - ProductSpace - ProductX - ProductXHelp - ProfileFunctions - ProfileFunctionsInGlobalVariables - ProfileGlobalFunctions - ProfileMethods - ProfileOperations - ProfileOperationsAndMethods - ProfileOperationsAndMethodsOff - ProfileOperationsAndMethodsOn - ProfileOperationsOff - ProfileOperationsOn - ProjectedInducedPcgs - ProjectedPcElement - Projection - ProjectionMap - ProjectionOntoFullRowSpace - ProjectionOntoVectorSubspace - ProjectiveActionHomomorphismMatrixGroup - ProjectiveActionOnFullSpace - ProjectiveCharDeg - ProjectiveGeneralLinearGroup - ProjectiveGeneralLinearGroupCons - ProjectiveGeneralUnitaryGroup - ProjectiveGeneralUnitaryGroupCons - ProjectiveOrder - ProjectiveSpecialLinearGroup - ProjectiveSpecialLinearGroupCons - ProjectiveSpecialUnitaryGroup - ProjectiveSpecialUnitaryGroupCons - ProjectiveSymplecticGroup - ProjectiveSymplecticGroupCons - PropertyMethodByNiceMonomorphism - PropertyMethodByNiceMonomorphismCollColl - PropertyMethodByNiceMonomorphismCollElm - PropertyMethodByNiceMonomorphismElmColl - PseudoRandom - PseudoRandomSeed - PthPowerImage - PthPowerImages - PullBack - PullbackCSPG - PullbackKernelCSPG - PurePadicNumberFamily - PushOptions - Quadratic - QuasiDihedralGenerators - QuaternionAlgebra - QuaternionGenerators - QuickInverseRepresentative - QuoInt - QuotRemLaurpols - QuotRemPolList - QuotSysDefinitionByIndex - QuotSysIndexByDefinition - Quotient - QuotientFromSCTable - QuotientGroup - QuotientGroupByChainHomomorphicImage - QuotientGroupByHomomorphism - QuotientGroupByImages - QuotientGroupByImagesNC - QuotientGroupHom - QuotientMod - QuotientPolynomialsExtRep - QuotientRemainder - QuotientSemigroupCongruence - QuotientSemigroupHomomorphism - QuotientSemigroupPreimage - QuotientSystem - RBaseGroupsBloxPermGroup - RClassOfHClass - RNamObj - RPFactorsModPrime - RPGcdCRT - RPGcdModPrime - RPGcdRepresentationModPrime - RPIFactors - RPIGcd - RPQuotientModPrime - RPSquareHensel - RRefine - RSSDefaultOptions - RadicalGroup - RadicalOfAlgebra - RanImgSrcSurjBloho - RanImgSrcSurjTraho - Random - RandomBinaryRelationOnPoints - RandomByPcs - RandomCommutatorSubproduct - RandomElmAsWord - RandomHashKey - RandomInvertibleMat - RandomIsomorphismTest - RandomList - RandomMat - RandomNormalSubproduct - RandomPcgsSylowSubgroup - RandomPol - RandomPrimitivePolynomial - RandomSchreierSims - RandomSpecialPcgsCoded - RandomSubprod - RandomTransformation - RandomUnimodularMat - Range - Rank - RankAction - RankFilter - RankMat - RankMatDestructive - RankOfTransformation - RankPGroup - RanksOfDescendingSeries - Rat - RatClasPElmArrangeClasses - RatPairString - RationalClass - RationalClasses - RationalClassesInEANS - RationalClassesPElements - RationalClassesPermGroup - RationalClassesSolvableGroup - RationalClassesTry - RationalFunctionByExtRep - RationalFunctionByExtRepWithCancellation - RationalFunctionsFamily - RationalIdentificationPermGroup - RationalizedMat - Rationals - ReObjectify - Read - ReadAll - ReadAllIoStreamByPty - ReadAllLine - ReadAndCheckFunc - ReadAsFunction - ReadByte - ReadGapRoot - ReadGrp - ReadLib - ReadLine - ReadOrComplete - ReadPackage - ReadPkg - ReadPrim - ReadSmall - ReadSmallLib - ReadTest - ReadTom - ReadTrans - RealClasses - RealizableBrauerCharacters - RecFields - RecNames - RecordsFamily - RecurseSchreierTree - RedispatchOnCondition - ReduceCoefficientsOfRws - ReduceCoeffs - ReduceCoeffsMod - ReduceLetterRepWordsRewSys - ReduceRules - ReduceStabChain - ReduceWordUsingRewritingSystem - Reduced - ReducedAdditiveInverse - ReducedByIsomorphisms - ReducedCharacters - ReducedClassFunctions - ReducedComm - ReducedConfluentRewritingSystem - ReducedConfluentRwsFromKbrwsNC - ReducedConjugate - ReducedDifference - ReducedForm - ReducedGaloisStabilizerInfo - ReducedGroebnerBasis - ReducedInverse - ReducedLeftQuotient - ReducedOne - ReducedOrdinary - ReducedPcElement - ReducedPower - ReducedProduct - ReducedQuotient - ReducedRrsWord - ReducedSCTable - ReducedScalarProduct - ReducedSum - ReducedVectorLTM - ReducedZero - Ree - ReeGroup - ReeGroupCons - ReesCongruenceOfSemigroupIdeal - ReesMatrixSemigroup - ReesMatrixSemigroupElement - ReesMatrixSemigroupEnumeratorGetElement - ReesZeroMatrixSemigroup - ReesZeroMatrixSemigroupElement - ReesZeroMatrixSemigroupElementIsZero - ReesZeroMatrixSemigroupEnumeratorGetElement - RefinedChain - RefinedPcGroup - RefinedSymmetrisations - RefinedSymmetrizations - Refinements - ReflectionMat - ReflexiveClosureBinaryRelation - RegisterRBasePoint - RegularActionHomomorphism - RegularModule - RegularModuleByGens - RegularNinKernelCSPG - RelVectorToCocycle - RelationsOfFpMonoid - RelationsOfFpSemigroup - RelativeBasis - RelativeBasisNC - RelativeOrderOfPcElement - RelativeOrders - RelatorFixedMultiplier - RelatorMatrixAbelianizedNormalClosure - RelatorMatrixAbelianizedNormalClosureRrs - RelatorMatrixAbelianizedSubgroup - RelatorMatrixAbelianizedSubgroupMtc - RelatorMatrixAbelianizedSubgroupRrs - RelatorRepresentatives - RelatorsCode - RelatorsOfFpAlgebra - RelatorsOfFpGroup - RelatorsPermGroupHom - RelsSortedByStartGen - RelsViaCosetTable - RemInt - RemoveCharacters - RemoveElmList - RemoveFile - RemoveOuterCoeffs - RemoveRelator - RemoveRootParseTree - RemoveSet - RemoveStabChain - RenumberHighestWeightGenerators - RenumberTree - RenumberedWord - RepOpElmTuplesPermGroup - RepOpSetsPermGroup - RepeatedString - ReplacedString - RepresentationsOfMatrix - RepresentationsOfObject - Representative - RepresentativeAction - RepresentativeActionOp - RepresentativeFromGenerators - RepresentativeLinearOperation - RepresentativeSmallest - RepresentativeTom - RepresentativeTomByGenerators - RepresentativeTomByGeneratorsNC - RepresentativesContainedRightCosets - RepresentativesFusions - RepresentativesMinimalBlocks - RepresentativesMinimalBlocksAttr - RepresentativesMinimalBlocksOp - RepresentativesPerfectSubgroups - RepresentativesPowerMaps - RepresentativesSimpleSubgroups - RepsPerfSimpSub - RequirePackage - Reread - RereadAndCheckFunc - RereadGrp - RereadLib - RereadPackage - RereadPkg - RereadPrim - RereadSmall - RereadTrans - ResetFilterObj - ResetOptionsStack - ResizeFlatHashTable - ResizeListHashTable - RespectsAddition - RespectsAdditiveInverses - RespectsInverses - RespectsMultiplication - RespectsOne - RespectsScalarMultiplication - RespectsZero - RestoreStateRandom - Restricted - RestrictedClassFunction - RestrictedClassFunctions - RestrictedExternalSet - RestrictedMapping - RestrictedNiceMonomorphism - RestrictedPartitions - RestrictedPartitionsA - RestrictedPartitionsK - RestrictedPerm - RestrictedTransformation - ResultOfLineOfStraightLineProgram - ResultOfStraightLineProgram - Resultant - ReturnFail - ReturnFalse - ReturnNextBasePoint - ReturnPopOptions - ReturnTrue - Reversed - ReversedOp - Revision - RewindStream - RewriteAbelianizedSubgroupRelators - RewriteSubgroupRelators - RewriteWord - RightActingAlgebra - RightActingDomain - RightActingGroup - RightActingRingOfIdeal - RightAction - RightAlgebraModule - RightAlgebraModuleByGenerators - RightCoset - RightCosetCanonicalRepresentativeDeterminator - RightCosets - RightCosetsNC - RightDerivations - RightIdeal - RightIdealByGenerators - RightIdealNC - RightMagmaCongruence - RightMagmaCongruenceByGeneratingPairs - RightMagmaIdeal - RightMagmaIdealByGenerators - RightModuleByHomomorphismToMatAlg - RightSemigroupCongruenceByGeneratingPairs - RightSemigroupIdealEnumeratorDataGetElement - RightShiftRowVector - RightTransversal - RightTransversalInParent - RightTransversalOp - RightTransversalPermGroupConstructor - Ring - RingByGenerators - RingElmTimesElm - RingFromFFE - RingWithOne - RingWithOneByGenerators - Root - RootBound - RootInt - RootMod - RootModPrime - RootModPrimePower - RootOfDefiningPolynomial - RootSystem - RootsMod - RootsModPrime - RootsModPrimePower - RootsOfUPol - RootsRepresentativeFFPol - RootsUnityMod - RootsUnityModPrime - RootsUnityModPrimePower - RoundCyc - RoundCycDown - RowEchelonFormLTM - RowIndexOfReesMatrixSemigroupElement - RowIndexOfReesZeroMatrixSemigroupElement - RowSpace - RowsOfReesMatrixSemigroup - RowsOfReesZeroMatrixSemigroup - Rules - RunImmediateMethods - Runtime - Runtimes - SCMinSmaGens - SCRExtend - SCRExtendRecord - SCRMakeStabStrong - SCRNotice - SCRRandomPerm - SCRRandomString - SCRRandomSubproduct - SCRRestoredRecord - SCRSchTree - SCRSift - SCRStrongGenTest - SCTableEntry - SCTableProduct - SLDegree - SLUnderlyingField - SNFofREF - SPolynomial - SSortedList - SSortedListList - STDOut - STGSelFunc - SameBlock - SandwichMatrixOfReesMatrixSemigroup - SandwichMatrixOfReesZeroMatrixSemigroup - SaveWorkspace - ScalarProduct - SchreierTransversal - SchreierTreeDepth - SchreierTreeInternalConsistencyCheck - SchuMu - SchurCover - SchurCoverFP - ScriptFromString - Search - SecHMSM - SecondaryGeneratorWordsAugmentedCosetTable - SecondaryImagesAugmentedCosetTable - SecondsDMYhms - SeekPositionStream - SelectSmallGroups - SelectTransitiveGroups - SemiEchelonBasis - SemiEchelonBasisNC - SemiEchelonMat - SemiEchelonMatDestructive - SemiEchelonMatTransformation - SemiEchelonMatTransformationDestructive - SemiEchelonMats - SemiEchelonMatsDestructive - SemiEchelonMatsNoCo - SemiSimpleType - SemidirectFactorsOfGroup - SemidirectProduct - SemidirectProductInfo - Semigroup - SemigroupByGenerators - SemigroupByMultiplicationTable - SemigroupCongruenceByGeneratingPairs - SemigroupIdealByGenerators - SemigroupIdealEnumeratorDataGetElement - SemigroupOfRewritingSystem - SemigroupTCInitialTableSize - SemigroupToddCoxeterInfo - Semiring - SemiringByGenerators - SemiringWithOne - SemiringWithOneAndZero - SemiringWithOneAndZeroByGenerators - SemiringWithOneByGenerators - SemiringWithZero - SemiringWithZeroByGenerators - SeqsOrbits - Set - SetANonReesCongruenceOfSemigroup - SetAbelianInvariants - SetAbelianInvariantsOfList - SetAbsoluteValue - SetActingDomain - SetActionHomomorphismAttr - SetActionKernelExternalSet - SetActorOfExternalSet - SetActualLibFileName - SetAdditiveElementAsMultiplicativeElement - SetAdditiveElementsAsMultiplicativeElementsFamily - SetAdditiveInverse - SetAdditiveInverseAttr - SetAdditiveInverseImmutable - SetAdditiveNeutralElement - SetAdditivelyActingDomain - SetAdjointBasis - SetAdjointModule - SetAlgebraicElementsFamilies - SetAllBlocks - SetAllInfoLevels - SetAlpha - SetAlternatingDegree - SetAlternatingSubgroup - SetAsDuplicateFreeList - SetAsGroup - SetAsGroupGeneralMappingByImages - SetAsLeftModuleGeneralMappingByImages - SetAsList - SetAsMagma - SetAsMonoid - SetAsNearRing - SetAsPolynomial - SetAsRing - SetAsSSortedList - SetAsSemigroup - SetAsSemiring - SetAsSemiringWithOne - SetAsSemiringWithOneAndZero - SetAsSemiringWithZero - SetAsSortedList - SetAsSubgroupOfWholeGroupByQuotient - SetAssertionLevel - SetAssociatedReesMatrixSemigroupOfDClass - SetAssociatedSemigroup - SetAugmentationIdeal - SetAugmentedCosetTableMtcInWholeGroup - SetAugmentedCosetTableNormalClosureInWholeGroup - SetAugmentedCosetTableRrsInWholeGroup - SetAutomorphismDomain - SetAutomorphismGroup - SetAutomorphismsOfTable - SetBaseIntMat - SetBaseMat - SetBaseOfBasicImageGroup - SetBaseOfGroup - SetBaseOrthogonalSpaceMat - SetBasis - SetBasisOfHomCosetAddMatrixGroup - SetBasisVectors - SetBaumClausenInfo - SetBilinearFormMat - SetBlocksAttr - SetBlocksInfo - SetBrauerCharacterValue - SetBravaisGroup - SetBravaisSubgroups - SetBravaisSupergroups - SetCanEasilyCompareElements - SetCanEasilySortElements - SetCanFindNilpotentClassTwoElement - SetCanonicalBasis - SetCanonicalElt - SetCanonicalGenerators - SetCanonicalNiceMonomorphism - SetCanonicalPcgs - SetCanonicalPcgsWrtFamilyPcgs - SetCanonicalPcgsWrtHomePcgs - SetCanonicalPcgsWrtSpecialPcgs - SetCanonicalRepresentativeDeterminatorOfExternalSet - SetCanonicalRepresentativeOfExternalOrbitByPcgs - SetCanonicalRepresentativeOfExternalSet - SetCartanMatrix - SetCartanSubalgebra - SetCayleyGraphDualSemigroup - SetCayleyGraphSemigroup - SetCenter - SetCentralCharacter - SetCentralIdempotentsOfSemiring - SetCentralNormalSeriesByPcgs - SetCentralizerInGLnZ - SetCentralizerInParent - SetCentre - SetCentreOfCharacter - SetChainSubgroup - SetChainSubgroupQuotient - SetCharacterDegrees - SetCharacterNames - SetCharacterParameters - SetCharacteristic - SetCharacteristicPolynomial - SetChevalleyBasis - SetChiefNormalSeriesByPcgs - SetChiefSeries - SetClassNames - SetClassNamesTom - SetClassParameters - SetClassPermutation - SetClassPositionsOfCentre - SetClassPositionsOfDerivedSubgroup - SetClassPositionsOfDirectProductDecompositions - SetClassPositionsOfElementaryAbelianSeries - SetClassPositionsOfFittingSubgroup - SetClassPositionsOfKernel - SetClassPositionsOfLowerCentralSeries - SetClassPositionsOfMaximalNormalSubgroups - SetClassPositionsOfNormalSubgroups - SetClassPositionsOfSolvableResiduum - SetClassPositionsOfSupersolvableResiduum - SetClassPositionsOfUpperCentralSeries - SetClassRoots - SetClassTypesTom - SetCoKernelOfAdditiveGeneralMapping - SetCoKernelOfMultiplicativeGeneralMapping - SetCoefficientsAndMagmaElements - SetCoefficientsFamily - SetCoefficientsOfLaurentPolynomial - SetCoefficientsOfUnivariatePolynomial - SetCoefficientsOfUnivariateRationalFunction - SetCoefficientsRing - SetCollectionsFamily - SetColumnIndexOfReesMatrixSemigroupElement - SetColumnIndexOfReesZeroMatrixSemigroupElement - SetColumnsOfReesMatrixSemigroup - SetColumnsOfReesZeroMatrixSemigroup - SetCommutator - SetCommutatorANC - SetCommutatorFactorGroup - SetCommutatorLength - SetCommutatorNC - SetComplementSystem - SetComplexConjugate - SetComponentsOfTuplesFamily - SetCompositionSeries - SetComputedAgemos - SetComputedAscendingChains - SetComputedBrauerTables - SetComputedClassFusions - SetComputedCyclicExtensionsTom - SetComputedHallSubgroups - SetComputedIndicators - SetComputedIsPNilpotents - SetComputedIsPSolvableCharacterTables - SetComputedIsPSolvables - SetComputedOmegas - SetComputedPCentralSeriess - SetComputedPCores - SetComputedPRumps - SetComputedPowerMaps - SetComputedPrimeBlockss - SetComputedSylowComplements - SetComputedSylowSubgroups - SetConductor - SetConfluentRws - SetConjugacyClasses - SetConjugacyClassesMaximalSubgroups - SetConjugacyClassesPerfectSubgroups - SetConjugacyClassesSubgroups - SetConjugate - SetConjugateANC - SetConjugateNC - SetConjugates - SetConjugatorInnerAutomorphism - SetConjugatorOfConjugatorIsomorphism - SetConstantTimeAccessList - SetConstituentsOfCharacter - SetConvertBasicImageGroupElement - SetCoreInParent - SetCosetTableFpHom - SetCosetTableInWholeGroup - SetCosetTableNormalClosureInWholeGroup - SetCosetTableOfFpSemigroup - SetCrystGroupDefaultAction - SetCycleStructurePerm - SetCyclicExtensionsTom - SetDataType - SetDecompositionMatrix - SetDecompositionTypesOfGroup - SetDefaultFieldOfMatrix - SetDefaultFieldOfMatrixGroup - SetDefectApproximation - SetDefiningPcgs - SetDefiningPolynomial - SetDefinitionNC - SetDegreeAction - SetDegreeOfBinaryRelation - SetDegreeOfCharacter - SetDegreeOfLaurentPolynomial - SetDegreeOfMatrixGroup - SetDegreeOfTransformation - SetDegreeOfTransformationSemigroup - SetDegreeOperation - SetDegreeOverPrimeField - SetDelta - SetDenominatorOfModuloPcgs - SetDenominatorOfRationalFunction - SetDepthOfUpperTriangularMatrix - SetDerivations - SetDerivative - SetDerivedLength - SetDerivedSeriesOfGroup - SetDerivedSubgroup - SetDerivedSubgroupsTomPossible - SetDerivedSubgroupsTomUnique - SetDeterminantMat - SetDeterminantOfCharacter - SetDihedralGenerators - SetDimension - SetDimensionOfMatrixGroup - SetDimensionOfVectors - SetDimensionsLoewyFactors - SetDimensionsMat - SetDirectFactorsOfGroup - SetDirectProductInfo - SetDirectSumDecomposition - SetDisplayOptions - SetDixonRecord - SetEANormalSeriesByPcgs - SetEarns - SetEggBoxOfDClass - SetElementTestFunction - SetElementaryAbelianSeries - SetElementaryAbelianSeriesLargeSteps - SetElementaryAbelianSubseries - SetElementsFamily - SetElmWPObj - SetEmptyRowVector - SetEntrySCTable - SetEnumerator - SetEnumeratorByBasis - SetEnumeratorSorted - SetEquivalenceClassRelation - SetEquivalenceClasses - SetEquivalenceRelationPartition - SetErrorHandler - SetExponent - SetExponentOfPowering - SetExtRepDenominatorRatFun - SetExtRepNumeratorRatFun - SetExtRepPolynomialRatFun - SetExternalOrbits - SetExternalOrbitsStabilizers - SetExternalSet - SetFactorsOfDirectProduct - SetFaithfulModule - SetFamiliesOfGeneralMappingsAndRanges - SetFamilyForOrdering - SetFamilyForRewritingSystem - SetFamilyPcgs - SetFamilyRange - SetFamilySource - SetFeatureObj - SetFieldOfMatrixGroup - SetFilterObj - SetFittingSubgroup - SetFpElmComparisonMethod - SetFpElmEqualityMethod - SetFpElmKBRWS - SetFrattiniSubgroup - SetFrattinifactorId - SetFrattinifactorSize - SetFreeAlgebraOfFpAlgebra - SetFreeGeneratorsOfFpAlgebra - SetFreeGeneratorsOfFpGroup - SetFreeGeneratorsOfFpMonoid - SetFreeGeneratorsOfFpSemigroup - SetFreeGroupOfBasicImageGroup - SetFreeGroupOfFpGroup - SetFreeMonoidOfFpMonoid - SetFreeMonoidOfRewritingSystem - SetFreeSemigroupOfFpSemigroup - SetFreeSemigroupOfRewritingSystem - SetFrobeniusAutomorphism - SetFunctionAction - SetFusionConjugacyClassesOp - SetFusionsOfLibTom - SetFusionsToLibTom - SetFusionsTom - SetGLDegree - SetGLUnderlyingField - SetGaloisGroup - SetGaloisMat - SetGaloisStabilizer - SetGaloisType - SetGapDocHTMLOptions - SetGapDocLaTeXOptions - SetGapDocTxtOptions - SetGasmanMessageStatus - SetGeneralizedPcgs - SetGeneratingPairsOfLeftMagmaCongruence - SetGeneratingPairsOfMagmaCongruence - SetGeneratingPairsOfRightMagmaCongruence - SetGeneratingSetIsComplete - SetGeneratorOfCyclicGroup - SetGeneratorsOfAdditiveGroup - SetGeneratorsOfAdditiveMagma - SetGeneratorsOfAdditiveMagmaWithInverses - SetGeneratorsOfAdditiveMagmaWithZero - SetGeneratorsOfAlgebra - SetGeneratorsOfAlgebraModule - SetGeneratorsOfAlgebraWithOne - SetGeneratorsOfDivisionRing - SetGeneratorsOfDomain - SetGeneratorsOfEquivalenceRelationPartition - SetGeneratorsOfExtASet - SetGeneratorsOfExtLSet - SetGeneratorsOfExtRSet - SetGeneratorsOfExtUSet - SetGeneratorsOfFLMLOR - SetGeneratorsOfFLMLORWithOne - SetGeneratorsOfField - SetGeneratorsOfGroup - SetGeneratorsOfIdeal - SetGeneratorsOfLeftIdeal - SetGeneratorsOfLeftMagmaIdeal - SetGeneratorsOfLeftModule - SetGeneratorsOfLeftOperatorAdditiveGroup - SetGeneratorsOfLeftOperatorRing - SetGeneratorsOfLeftOperatorRingWithOne - SetGeneratorsOfLeftVectorSpace - SetGeneratorsOfMagma - SetGeneratorsOfMagmaIdeal - SetGeneratorsOfMagmaWithInverses - SetGeneratorsOfMagmaWithOne - SetGeneratorsOfMonoid - SetGeneratorsOfNearAdditiveGroup - SetGeneratorsOfNearAdditiveMagma - SetGeneratorsOfNearAdditiveMagmaWithInverses - SetGeneratorsOfNearAdditiveMagmaWithZero - SetGeneratorsOfRightIdeal - SetGeneratorsOfRightMagmaIdeal - SetGeneratorsOfRightModule - SetGeneratorsOfRightOperatorAdditiveGroup - SetGeneratorsOfRing - SetGeneratorsOfRingWithOne - SetGeneratorsOfRws - SetGeneratorsOfSemigroup - SetGeneratorsOfSemiring - SetGeneratorsOfSemiringWithOne - SetGeneratorsOfSemiringWithOneAndZero - SetGeneratorsOfSemiringWithZero - SetGeneratorsOfTwoSidedIdeal - SetGeneratorsOfVectorSpace - SetGeneratorsSmallest - SetGeneratorsSubgroupsTom - SetGlobalPartitionOfClasses - SetGrading - SetGreensDRelation - SetGreensHRelation - SetGreensJRelation - SetGreensLRelation - SetGreensRRelation - SetGroupByPcgs - SetGroupHClassOfGreensDClass - SetGroupOfPcgs - SetHallSystem - SetHashEntry - SetHashEntryAtLastIndex - SetHelpViewer - SetHirschLength - SetHomCosetFamily - SetHomFromFreeOfBasicImageGroup - SetHomeEnumerator - SetHomePcgs - SetIBr - SetIdGroup - SetIdempotents - SetIdempotentsTom - SetIdempotentsTomInfo - SetIdentificationOfConjugacyClasses - SetIdentifier - SetIdentity - SetIdentityMapping - SetImage - SetImageElt - SetImageListOfTransformation - SetImageSetOfTransformation - SetImagesSmallestGenerators - SetImagesSource - SetImfRecord - SetIndependentGeneratorsOfAbelianGroup - SetIndependentGeneratorsOfAbelianMatrixGroup - SetIndeterminateName - SetIndeterminateNumberOfLaurentPolynomial - SetIndeterminateNumberOfUnivariateLaurentPolynomial - SetIndeterminateNumberOfUnivariateRationalFunction - SetIndeterminateOfUnivariateRationalFunction - SetIndeterminatesOfPolynomialRing - SetIndexInParent - SetIndexInWholeGroup - SetIndicesCentralNormalSteps - SetIndicesChiefNormalSteps - SetIndicesEANormalSteps - SetIndicesInvolutaryGenerators - SetIndicesNormalSteps - SetIndicesOfAdjointBasis - SetIndicesPCentralNormalStepsPGroup - SetInducedPcgs - SetInducedPcgsWrtFamilyPcgs - SetInducedPcgsWrtHomePcgs - SetInducedPcgsWrtSpecialPcgs - SetInfoLevel - SetInfoText - SetInjectionZeroMagma - SetInnerAutomorphismsAutomorphismGroup - SetInt - SetInternalRepresentative - SetInvariantBilinearForm - SetInvariantForm - SetInvariantLattice - SetInvariantQuadraticForm - SetInvariantSesquilinearForm - SetInverse - SetInverseAttr - SetInverseClasses - SetInverseGeneralMapping - SetInverseImmutable - SetIrr - SetIrrBaumClausen - SetIrrConlon - SetIrrDixonSchneider - SetIrrFacsPol - SetIrreducibleRepresentations - SetIsAbelian - SetIsAbelianNumberField - SetIsAbelianTom - SetIsAdditiveGroupGeneralMapping - SetIsAdditiveGroupHomomorphism - SetIsAdditiveGroupToGroupGeneralMapping - SetIsAdditiveGroupToGroupHomomorphism - SetIsAdditivelyCommutative - SetIsAlgebraGeneralMapping - SetIsAlgebraHomomorphism - SetIsAlgebraModule - SetIsAlgebraWithOneGeneralMapping - SetIsAlgebraWithOneHomomorphism - SetIsAlternatingGroup - SetIsAnticommutative - SetIsAntisymmetricBinaryRelation - SetIsAssociative - SetIsAutomorphismGroup - SetIsBasicWreathProductOrdering - SetIsBergerCondition - SetIsBijective - SetIsBravaisGroup - SetIsBuiltFromAdditiveMagmaWithInverses - SetIsBuiltFromGroup - SetIsBuiltFromMagma - SetIsBuiltFromMagmaWithInverses - SetIsBuiltFromMagmaWithOne - SetIsBuiltFromMonoid - SetIsBuiltFromSemigroup - SetIsCanonicalBasis - SetIsCanonicalBasisFullMatrixModule - SetIsCanonicalBasisFullRowModule - SetIsCanonicalBasisFullSCAlgebra - SetIsCanonicalNiceMonomorphism - SetIsCanonicalPcgs - SetIsCanonicalPcgsWrtSpecialPcgs - SetIsChainTypeGroup - SetIsCharacter - SetIsCharacteristicMatrixPGroup - SetIsCommutative - SetIsCommutativeFamily - SetIsConfluent - SetIsConjugatorAutomorphism - SetIsConjugatorIsomorphism - SetIsConstantRationalFunction - SetIsConstantTimeAccessGeneralMapping - SetIsCycInt - SetIsCyclic - SetIsCyclicTom - SetIsCyclicWithSize - SetIsCyclotomicField - SetIsDihedralGroup - SetIsDistributive - SetIsDivisionRing - SetIsDuplicateFree - SetIsDuplicateFreeList - SetIsElementaryAbelian - SetIsEmpty - SetIsEndoGeneralMapping - SetIsEndoMapping - SetIsEquivalenceRelation - SetIsFFEMatrixGroupOverLargeSpace - SetIsFamilyPcgs - SetIsField - SetIsFieldHomomorphism - SetIsFinite - SetIsFiniteDimensional - SetIsFiniteOrdersPcgs - SetIsFiniteSemigroupGreensRelation - SetIsFinitelyGeneratedGroup - SetIsFrattiniFree - SetIsFreeMonoid - SetIsFreeSemigroup - SetIsFullFpAlgebra - SetIsFullHomModule - SetIsFullMatrixModule - SetIsFullRowModule - SetIsFullSCAlgebra - SetIsFullSubgroupGLorSLRespectingBilinearForm - SetIsFullSubgroupGLorSLRespectingQuadraticForm - SetIsFullSubgroupGLorSLRespectingSesquilinearForm - SetIsFullTransformationSemigroup - SetIsGL - SetIsGeneralLinearGroup - SetIsGeneralizedCartanMatrix - SetIsGeneratorsOfMagmaWithInverses - SetIsGreensClass - SetIsGreensDClass - SetIsGreensDRelation - SetIsGreensHClass - SetIsGreensHRelation - SetIsGreensJClass - SetIsGreensJRelation - SetIsGreensLClass - SetIsGreensLRelation - SetIsGreensRClass - SetIsGreensRRelation - SetIsGreensRelation - SetIsGroupGeneralMapping - SetIsGroupHClass - SetIsGroupHomomorphism - SetIsGroupOfAutomorphisms - SetIsGroupOfAutomorphismsFiniteGroup - SetIsGroupRing - SetIsGroupToAdditiveGroupGeneralMapping - SetIsGroupToAdditiveGroupHomomorphism - SetIsHandledByNiceMonomorphism - SetIsHasseDiagram - SetIsHomCosetOfAdditiveElt - SetIsHomCosetOfFp - SetIsHomCosetOfMatrix - SetIsHomCosetOfPerm - SetIsHomCosetOfTuple - SetIsIdealInParent - SetIsIdempotent - SetIsImpossible - SetIsInducedFromNormalSubgroup - SetIsInducedPcgsWrtSpecialPcgs - SetIsInjective - SetIsInnerAutomorphism - SetIsIntegerMatrixGroup - SetIsIntegralBasis - SetIsIntegralCyclotomic - SetIsIntegralRing - SetIsIrreducibleCharacter - SetIsJacobianRing - SetIsLDistributive - SetIsLatticeOrderBinaryRelation - SetIsLaurentPolynomial - SetIsLeftActedOnByDivisionRing - SetIsLeftAlgebraModule - SetIsLeftIdealInParent - SetIsLeftModuleGeneralMapping - SetIsLeftModuleHomomorphism - SetIsLeftSemigroupCongruence - SetIsLeftSemigroupIdeal - SetIsLieAbelian - SetIsLieAlgebra - SetIsLieNilpotent - SetIsLieSolvable - SetIsLinearlyPrimitive - SetIsMagmaHomomorphism - SetIsMapping - SetIsMatrixModule - SetIsMinimalNonmonomial - SetIsMonoid - SetIsMonomialCharacter - SetIsMonomialCharacterTable - SetIsMonomialGroup - SetIsMonomialMatrix - SetIsMonomialNumber - SetIsNaturalAlternatingGroup - SetIsNaturalGL - SetIsNaturalSL - SetIsNaturalSymmetricGroup - SetIsNearRing - SetIsNearRingWithOne - SetIsNilpQuotientSystem - SetIsNilpotentCharacterTable - SetIsNilpotentGroup - SetIsNilpotentTom - SetIsNonTrivial - SetIsNoncharacteristicMatrixPGroup - SetIsNormalBasis - SetIsNormalForm - SetIsNormalInParent - SetIsNumberField - SetIsNumeratorParentPcgsFamilyPcgs - SetIsOne - SetIsOrderingOnFamilyOfAssocWords - SetIsPGroup - SetIsPQuotientSystem - SetIsPSL - SetIsParentPcgsFamilyPcgs - SetIsPartialOrderBinaryRelation - SetIsPcgsCentralSeries - SetIsPcgsChiefSeries - SetIsPcgsElementaryAbelianSeries - SetIsPcgsPCentralSeriesPGroup - SetIsPerfectCharacterTable - SetIsPerfectGroup - SetIsPerfectTom - SetIsPolycyclicGroup - SetIsPolynomial - SetIsPositionsList - SetIsPreOrderBinaryRelation - SetIsPrimeField - SetIsPrimeOrdersPcgs - SetIsPrimitive - SetIsPrimitiveAffine - SetIsPrimitiveCharacter - SetIsPrimitiveMatrixGroup - SetIsPseudoCanonicalBasisFullHomModule - SetIsQuasiDihedralGroup - SetIsQuasiPrimitive - SetIsQuaternionGroup - SetIsRDistributive - SetIsRationalMatrixGroup - SetIsRectangularTable - SetIsReduced - SetIsReesCongruence - SetIsReesCongruenceSemigroup - SetIsReesMatrixSemigroup - SetIsReesZeroMatrixSemigroup - SetIsReflexiveBinaryRelation - SetIsRegular - SetIsRegularDClass - SetIsRegularSemigroup - SetIsRelativelySM - SetIsRestrictedLieAlgebra - SetIsRightAlgebraModule - SetIsRightIdealInParent - SetIsRightSemigroupCongruence - SetIsRightSemigroupIdeal - SetIsRing - SetIsRingGeneralMapping - SetIsRingHomomorphism - SetIsRingWithOne - SetIsRingWithOneGeneralMapping - SetIsRingWithOneHomomorphism - SetIsRowModule - SetIsSL - SetIsSSortedList - SetIsSemiEchelonized - SetIsSemiRegular - SetIsSemigroup - SetIsSemigroupCongruence - SetIsSemigroupIdeal - SetIsSemiring - SetIsSemiringWithOne - SetIsSemiringWithOneAndZero - SetIsSemiringWithZero - SetIsShortLexOrdering - SetIsSimpleAlgebra - SetIsSimpleCharacterTable - SetIsSimpleGroup - SetIsSimpleSemigroup - SetIsSingleValued - SetIsSkewFieldFamily - SetIsSmallList - SetIsSolvableCharacterTable - SetIsSolvableGroup - SetIsSolvableTom - SetIsSortedList - SetIsSpecialLinearGroup - SetIsSpecialPcgs - SetIsSporadicSimpleCharacterTable - SetIsSporadicSimpleGroup - SetIsStabChainViaChainSubgroup - SetIsSubgroupSL - SetIsSubmonoidFpMonoid - SetIsSubnormallyMonomial - SetIsSubsemigroupFpSemigroup - SetIsSubsemigroupReesMatrixSemigroup - SetIsSubsemigroupReesZeroMatrixSemigroup - SetIsSubsetLocallyFiniteGroup - SetIsSupersolvableCharacterTable - SetIsSupersolvableGroup - SetIsSurjective - SetIsSymmetricBinaryRelation - SetIsSymmetricGroup - SetIsTotal - SetIsTotalOrdering - SetIsTransformationMonoid - SetIsTransformationSemigroup - SetIsTransitive - SetIsTransitiveBinaryRelation - SetIsTranslationInvariantOrdering - SetIsTrivial - SetIsTwoSidedIdealInParent - SetIsUFDFamily - SetIsUniformMatrixGroup - SetIsUnivariatePolynomial - SetIsUnivariateRationalFunction - SetIsVectorSpaceHomomorphism - SetIsVirtualCharacter - SetIsWeightLexOrdering - SetIsWellFoundedOrdering - SetIsWeylGroup - SetIsWholeFamily - SetIsWreathProductOrdering - SetIsZero - SetIsZeroGroup - SetIsZeroMultiplicationRing - SetIsZeroRationalFunction - SetIsZeroSimpleSemigroup - SetIsZeroSquaredRing - SetIsomorphismFpAlgebra - SetIsomorphismFpFLMLOR - SetIsomorphismFpGroup - SetIsomorphismFpMonoid - SetIsomorphismFpSemigroup - SetIsomorphismMatrixAlgebra - SetIsomorphismMatrixFLMLOR - SetIsomorphismPcGroup - SetIsomorphismPermGroup - SetIsomorphismReesMatrixSemigroup - SetIsomorphismRefinedPcGroup - SetIsomorphismSCAlgebra - SetIsomorphismSCFLMLOR - SetIsomorphismSimplifiedFpGroup - SetIsomorphismSpecialPcGroup - SetIsomorphismTransformationSemigroup - SetJenningsLieAlgebra - SetJenningsSeries - SetJordanDecomposition - SetKernelOfAdditiveGeneralMapping - SetKernelOfCharacter - SetKernelOfMultiplicativeGeneralMapping - SetKernelOfTransformation - SetKillingMatrix - SetKnowsHowToDecompose - SetLClassOfHClass - SetLGFirst - SetLGHeads - SetLGLayers - SetLGLength - SetLGTails - SetLGWeights - SetLargestElementGroup - SetLargestMovedPoint - SetLargestMovedPointPerm - SetLatticeGeneratorsInUEA - SetLatticeSubgroups - SetLeadCoeffsIGS - SetLeftActingAlgebra - SetLeftActingDomain - SetLeftActingGroup - SetLeftActingRingOfIdeal - SetLeftDerivations - SetLength - SetLengthsTom - SetLessThanFunction - SetLessThanOrEqualFunction - SetLetterRepWordsLessFunc - SetLevelsOfGenerators - SetLeviMalcevDecomposition - SetLieAlgebraByDomain - SetLieCenter - SetLieCentralizerInParent - SetLieCentre - SetLieDerivedSeries - SetLieDerivedSubalgebra - SetLieFamily - SetLieLowerCentralSeries - SetLieNilRadical - SetLieNormalizerInParent - SetLieObject - SetLieSolvableRadical - SetLieUpperCentralSeries - SetLinearActionBasis - SetLinearCharacters - SetLinesOfStraightLineProgram - SetLongestWeylWordPerm - SetLowerCentralSeriesOfGroup - SetMagmaGeneratorsOfFamily - SetMappingGeneratorsImages - SetMappingOfWhichItIsAsGGMBI - SetMarksTom - SetMatTom - SetMatrixByBlockMatrix - SetMatrixDimension - SetMaximalAbelianQuotient - SetMaximalBlocksAttr - SetMaximalNormalSubgroups - SetMaximalSubgroupClassReps - SetMaximalSubgroups - SetMaximalSubgroupsLattice - SetMaximalSubgroupsTom - SetMinimalBlockDimension - SetMinimalGeneratingSet - SetMinimalNormalSubgroups - SetMinimalStabChain - SetMinimalSupergroupsLattice - SetMinimizedBombieriNorm - SetModuleOfExtension - SetModulusOfZmodnZObj - SetMoebiusTom - SetMolienSeriesInfo - SetMonoidOfRewritingSystem - SetMonomialComparisonFunction - SetMonomialExtrepComparisonFun - SetMovedPoints - SetMultipleAttributes - SetMultiplicationTable - SetMultiplicativeNeutralElement - SetMultiplicativeZero - SetName - SetNameIsomorphismClass - SetNamesLibTom - SetNamesOfFusionSources - SetNaturalCharacter - SetNaturalHomomorphismByNormalSubgroupNCInParent - SetNaturalHomomorphismsPool - SetNegativeRootVectors - SetNegativeRoots - SetNestingDepthA - SetNestingDepthM - SetNiceAlgebraMonomorphism - SetNiceBasis - SetNiceFreeLeftModule - SetNiceFreeLeftModuleInfo - SetNiceMonomorphism - SetNiceNormalFormByExtRepFunction - SetNiceObject - SetNilpotencyClassOfGroup - SetNilpotentClassTwoElement - SetNonLieNilpotentElement - SetNonNilpotentElement - SetNorm - SetNormalBase - SetNormalClosureInParent - SetNormalMaximalSubgroups - SetNormalSeriesByPcgs - SetNormalSubgroupClassesInfo - SetNormalSubgroups - SetNormalizerInGLnZ - SetNormalizerInGLnZBravaisGroup - SetNormalizerInHomePcgs - SetNormalizerInParent - SetNormalizersTom - SetNormedRowVector - SetNormedRowVectors - SetNormedVectors - SetNotifiedFusionsOfLibTom - SetNotifiedFusionsToLibTom - SetNrConjugacyClasses - SetNrInputsOfStraightLineProgram - SetNrMovedPoints - SetNrMovedPointsPerm - SetNrSubsTom - SetNrSyllables - SetNullAlgebra - SetNullspaceIntMat - SetNullspaceMat - SetNumberGeneratorsOfRws - SetNumberSyllables - SetNumeratorOfModuloPcgs - SetNumeratorOfRationalFunction - SetONanScottType - SetOccuringVariableIndices - SetOmegaAndLowerPCentralSeries - SetOmegaSeries - SetOne - SetOneAttr - SetOneImmutable - SetOneOfPcgs - SetOperatorOfExternalSet - SetOrbitGeneratorsOfGroup - SetOrbitLengths - SetOrbitLengthsDomain - SetOrbitStabilizingParentGroup - SetOrbits - SetOrbitsDomain - SetOrder - SetOrderingOfRewritingSystem - SetOrderingOnGenerators - SetOrderingsFamily - SetOrdersClassRepresentatives - SetOrdersTom - SetOrdinaryCharacterTable - SetOrthogonalSpaceInFullRowSpace - SetPCentralLieAlgebra - SetPCentralNormalSeriesByPcgsPGroup - SetPClassPGroup - SetPSLDegree - SetPSLUnderlyingField - SetPackageInfo - SetParent - SetParentAttr - SetParentPcgs - SetPartialClosureOfCongruence - SetPartialOrderOfHasseDiagram - SetPcGroupWithPcgs - SetPcSeries - SetPcgs - SetPcgsCentralSeries - SetPcgsChiefSeries - SetPcgsElementaryAbelianSeries - SetPcgsPCentralSeriesPGroup - SetPerfectIdentification - SetPerfectResiduum - SetPermutationTom - SetPositiveRootVectors - SetPositiveRoots - SetPositiveRootsAsWeights - SetPower - SetPowerANC - SetPowerNC - SetPowerS - SetPowerSubalgebraSeries - SetPreBasis - SetPreImagesRange - SetPreferredGenerators - SetPrefrattiniSubgroup - SetPresentation - SetPrimaryGeneratorWords - SetPrimeField - SetPrimePGroup - SetPrimePowerComponents - SetPrimitiveElement - SetPrimitiveIdentification - SetPrimitiveRoot - SetPrintFormattingStatus - SetProjectiveOrder - SetPseudoRandomSeed - SetPthPowerImages - SetQuasiDihedralGenerators - SetQuaternionGenerators - SetQuotientGroup - SetQuotientGroupHom - SetQuotientSemigroupCongruence - SetQuotientSemigroupHomomorphism - SetQuotientSemigroupPreimage - SetRClassOfHClass - SetRadicalGroup - SetRadicalOfAlgebra - SetRange - SetRankAction - SetRankMat - SetRankOfTransformation - SetRankPGroup - SetRat - SetRationalClasses - SetRationalFunctionsFamily - SetRationalizedMat - SetRealClasses - SetRecNames - SetRecursionTrapInterval - SetReducedConfluentRewritingSystem - SetReducedMultiplication - SetReesCongruenceOfSemigroupIdeal - SetReesZeroMatrixSemigroupElementIsZero - SetRefinedPcGroup - SetRegularActionHomomorphism - SetRelationsOfFpMonoid - SetRelationsOfFpSemigroup - SetRelativeOrder - SetRelativeOrderNC - SetRelativeOrders - SetRelatorsOfFpAlgebra - SetRelatorsOfFpGroup - SetRepresentative - SetRepresentativeSmallest - SetRepresentativesContainedRightCosets - SetRepresentativesMinimalBlocksAttr - SetRepresentativesPerfectSubgroups - SetRepresentativesSimpleSubgroups - SetRespectsAddition - SetRespectsAdditiveInverses - SetRespectsInverses - SetRespectsMultiplication - SetRespectsOne - SetRespectsScalarMultiplication - SetRespectsZero - SetRightActingAlgebra - SetRightActingDomain - SetRightActingGroup - SetRightActingRingOfIdeal - SetRightDerivations - SetRightTransversalInParent - SetRootOfDefiningPolynomial - SetRootSystem - SetRowIndexOfReesMatrixSemigroupElement - SetRowIndexOfReesZeroMatrixSemigroupElement - SetRowsOfReesMatrixSemigroup - SetRowsOfReesZeroMatrixSemigroup - SetRules - SetSLDegree - SetSLUnderlyingField - SetSandwichMatrixOfReesMatrixSemigroup - SetSandwichMatrixOfReesZeroMatrixSemigroup - SetSemiEchelonBasis - SetSemiEchelonMat - SetSemiEchelonMatTransformation - SetSemiSimpleType - SetSemidirectFactorsOfGroup - SetSemidirectProductInfo - SetSemigroupOfRewritingSystem - SetSiftFunction - SetSiftGroup - SetSignPerm - SetSimpleSystem - SetSimsNo - SetSize - SetSizesCentralizers - SetSizesConjugacyClasses - SetSmallGeneratingSet - SetSmallestGeneratorPerm - SetSmallestMovedPoint - SetSmallestMovedPointPerm - SetSocle - SetSocleComplement - SetSocleDimensions - SetSocleTypePrimitiveGroup - SetSortingPerm - SetSource - SetSparseCartanMatrix - SetSpecialPcgs - SetSplittingField - SetStabChainImmutable - SetStabChainMutable - SetStabChainOptions - SetStabilizerOfExternalSet - SetStandardGeneratorsInfo - SetStoredExcludedOrders - SetStoredGroebnerBasis - SetStraightLineProgElmType - SetStraightLineProgramsTom - SetString - SetStructureConstantsTable - SetStructureDescription - SetSubdirectProductInfo - SetSubfields - SetSubnormalSeriesInParent - SetSubsTom - SetSubspaces - SetSubspacesAll - SetSuccessors - SetSupersolvableResiduum - SetSurjectiveActionHomomorphismAttr - SetSylowSystem - SetSymmetricDegree - SetSymmetricParentGroup - SetTableOfMarks - SetTestMonomial - SetTestMonomialQuick - SetTestQuasiPrimitive - SetTestRelativelySM - SetTestSubnormallyMonomial - SetTietzeOrigin - SetTrace - SetTranformsOneIntoZero - SetTransformationRepresentation - SetTransformsAdditionIntoMultiplication - SetTransformsAdditiveInversesIntoInverses - SetTransformsInversesIntoAdditiveInverses - SetTransformsMultiplicationIntoAddition - SetTransformsZeroIntoOne - SetTransitiveIdentification - SetTransitivity - SetTransposedMat - SetTransposedMatAttr - SetTransposedMatImmutable - SetTransposedMatrixGroup - SetTransversal - SetTriangulizedNullspaceMat - SetTrivialCharacter - SetTrivialSubFLMLOR - SetTrivialSubadditiveMagmaWithZero - SetTrivialSubalgebra - SetTrivialSubgroup - SetTrivialSubmagmaWithOne - SetTrivialSubmodule - SetTrivialSubmonoid - SetTrivialSubnearAdditiveMagmaWithZero - SetTrivialSubspace - SetTwoClosure - SetTypeObj - SetTzOptions - SetTzRules - SetUnderlyingCharacterTable - SetUnderlyingCharacteristic - SetUnderlyingCollection - SetUnderlyingElementOfReesMatrixSemigroupElement - SetUnderlyingElementOfReesZeroMatrixSemigroupElement - SetUnderlyingExternalSet - SetUnderlyingFamily - SetUnderlyingField - SetUnderlyingGeneralMapping - SetUnderlyingGroup - SetUnderlyingLeftModule - SetUnderlyingLieAlgebra - SetUnderlyingMagma - SetUnderlyingRelation - SetUnderlyingSemigroupOfReesMatrixSemigroup - SetUnderlyingSemigroupOfReesZeroMatrixSemigroup - SetUnderlyingVectorSpace - SetUnits - SetUniversalEnvelopingAlgebra - SetUpperActingDomain - SetUpperCentralSeriesOfGroup - SetValueOption - SetValuesOfClassFunction - SetWeightOfGenerators - SetWeightsTom - SetWeylGroup - SetWreathProductInfo - SetX - SetXHelp - SetZClassRepsQClass - SetZero - SetZeroAttr - SetZeroCoefficient - SetZeroImmutable - SetZuppos - SetnpeGL - SetnpePSL - SetnpeSL - SetsOrbits - Setter - ShallowCopy - ShapeFrequencies - SharedObj - SharedType - ShiftedCoeffs - ShiftedPadicNumber - ShortLexOrdering - ShortLexOrderingNC - ShortestVectors - ShowArgument - ShowArguments - ShowDetails - ShowImpliedFilters - ShowMethods - ShowOtherMethods - ShowPackageVariables - ShrinkCoeffs - ShrinkRowVector - ShrinkableHashTable - ShrinkableSingleValuedHashTable - Sift - SiftAsWord - SiftForStrongGenerator - SiftFunction - SiftGroup - SiftOneLevel - SiftVector - SiftedPcElement - SiftedPermutation - SiftedVector - SiftedVectorForGaussianMatrixSpace - SiftedVectorForGaussianRowSpace - SiftedWord - Sigma - SignInt - SignPartition - SignPerm - SignPermGroup - SimpleLieAlgebra - SimpleLieAlgebraTypeH - SimpleLieAlgebraTypeK - SimpleLieAlgebraTypeS - SimpleLieAlgebraTypeW - SimpleSystem - SimplifiedFpGroup - SimplifyPresentation - SimsName - SimsNo - SimultaneousEigenvalues - SingleCollector - SingleCollectorByGenerators - SingleCollectorByRelators - SingleValuedHashTable - Size - SizeBlist - SizeConsiderFunction - SizeGL - SizeNumbersPerfectGroups - SizeOfChainOfGroup - SizeOfFieldOfDefinition - SizeOfGLdZmodmZ - SizePSL - SizePolynomialUnipotentClassGL - SizeSL - SizeScreen - SizeStabChain - SizeUpperBound - SizesCentralizers - SizesConjugacyClasses - SizesPerfectGroups - Sleep - SmallGeneratingSet - SmallGroup - SmallGroupsInformation - SmallSpaceCutoff - SmallerDegreePermutationRepresentation - SmallestGeneratorPerm - SmallestMovedPoint - SmallestMovedPointPerm - SmallestMovedPointPerms - SmallestPrimeDivisor - SmallestRootInt - SmithNormalFormIntegerMat - SmithNormalFormIntegerMatTransforms - SmithNormalFormSQ - Socle - SocleComplement - SocleDimensions - SocleTypePrimitiveGroup - SolutionIntMat - SolutionMat - SolutionMatDestructive - SolutionMatNoCo - SolutionNullspaceIntMat - SolutionSQ - SolvableNormalClosurePermGroup - SolvableQuotient - SomeVerbalSubgroups - Sort - SortParallel - SortRationalClasses - SortRelsSortedByStartGen - SortedCharacterTable - SortedCharacters - SortedList - SortedSparseActionHomomorphism - SortedSparseActionHomomorphismOp - SortedTom - Sortex - SortingPerm - Source - SourceElt - Sp - SpanOfMatrixGroup - SpanningTree - SparseActionHomomorphism - SparseActionHomomorphismOp - SparseCartanMatrix - SparseHashTable - SparseIntKey - SpecialLinearGroup - SpecialLinearGroupCons - SpecialOrthogonalGroup - SpecialOrthogonalGroupCons - SpecialPcgs - SpecialPcgsFactor - SpecialPcgsSubgroup - SpecialUnitaryGroup - SpecialUnitaryGroupCons - SpecializedExtRepPol - SpinInductionScheme - SpinorNorm - SplitCell - SplitCharacters - SplitExtension - SplitStep - SplitString - SplitStringInternal - SplitTwoSpace - SplitUpSublistsByFpFunc - SplitWordTail - SplittingField - Sqrt - SquareRoots - StabChain - StabChainBaseStrongGenerators - StabChainForcePoint - StabChainImmutable - StabChainMutable - StabChainOp - StabChainOptions - StabChainPermGroupToPermGroupGeneralMappingByImages - StabChainRandomPermGroup - StabChainStrong - StabChainSwap - Stabilizer - StabilizerByMatrixOperation - StabilizerFunc - StabilizerFuncOp - StabilizerOfBlockNC - StabilizerOfExternalSet - StabilizerOp - StabilizerPcgs - StandardAssociate - StandardClassMatrixColumn - StandardGeneratorsFunctions - StandardGeneratorsInfo - StandardGeneratorsOfFullHomModule - StandardGeneratorsOfFullMatrixModule - StandardGeneratorsOfGroup - StandardScalarProduct - StandardizeTable - StandardizeTableC - StarCyc - StateRandom - StatusRandom - StepModGauss - StopNumConsecSiftToOne - StopNumSift - StopSize - StoreAlgExtFam - StoreFactorsPol - StoreFusion - StoreInfoFreeMagma - StoredExcludedOrders - StoredGroebnerBasis - StraightLineProgElm - StraightLineProgElmType - StraightLineProgGens - StraightLineProgram - StraightLineProgramElmRankFilter - StraightLineProgramNC - StraightLineProgramsDefaultType - StraightLineProgramsFamily - StraightLineProgramsTom - StratMeetPartition - StreamsFamily - StretchImportantSLPElement - String - StringDate - StringFamily - StringFile - StringImType - StringOfResultOfLineOfStraightLineProgram - StringOfResultOfStraightLineProgram - StringOfUnivariateRationalPolynomialByCoefficients - StringPP - StringPrint - StringStreamInputTextFile - StringTime - StringToStraightLineProgram - StringUnivariateLaurent - StringView - StripBeginEnd - StripEscapeSequences - StrongGeneratorsStabChain - StrongGens - StronglyConnectedComponents - StructuralCopy - StructureConstantsPadicNumbers - StructureConstantsTable - StructureDescription - SuPeRfail - SubAlgebraModule - SubFLMLOR - SubFLMLORNC - SubFLMLORWithOne - SubFLMLORWithOneNC - SubGModLeadPos - SubSyllables - SubadditiveGroup - SubadditiveGroupNC - SubadditiveMagma - SubadditiveMagmaNC - SubadditiveMagmaWithInverses - SubadditiveMagmaWithInversesNC - SubadditiveMagmaWithZero - SubadditiveMagmaWithZeroNC - Subalgebra - SubalgebraNC - SubalgebraWithOne - SubalgebraWithOneNC - SubdirProdPcGroups - SubdirectDiagonalPerms - SubdirectProduct - SubdirectProductInfo - SubdirectProductOp - SubdirectProducts - Subfield - SubfieldNC - Subfields - SubgpConjSymmgp - Subgroup - SubgroupByPcgs - SubgroupByProperty - SubgroupGeneratorsCosetTable - SubgroupMethodByNiceMonomorphism - SubgroupMethodByNiceMonomorphismCollColl - SubgroupMethodByNiceMonomorphismCollElm - SubgroupMethodByNiceMonomorphismCollOther - SubgroupNC - SubgroupOfWholeGroupByCosetTable - SubgroupOfWholeGroupByQuotientSubgroup - SubgroupProperty - SubgroupShell - SubgroupsMethodByNiceMonomorphism - SubgroupsOrbitsAndNormalizers - SubgroupsSolvableGroup - Submagma - SubmagmaNC - SubmagmaWithInverses - SubmagmaWithInversesNC - SubmagmaWithOne - SubmagmaWithOneNC - Submodule - SubmoduleNC - Submonoid - SubmonoidNC - SubnearAdditiveGroup - SubnearAdditiveGroupNC - SubnearAdditiveMagma - SubnearAdditiveMagmaNC - SubnearAdditiveMagmaWithInverses - SubnearAdditiveMagmaWithInversesNC - SubnearAdditiveMagmaWithZero - SubnearAdditiveMagmaWithZeroNC - SubnormalSeries - SubnormalSeriesInParent - SubnormalSeriesOp - SuboLiBli - SuboSiBli - SuboTruePos - SuboUniteBlist - Suborbits - Subring - SubringNC - SubringWithOne - SubringWithOneNC - SubsTom - Subsemigroup - SubsemigroupNC - Subsemiring - SubsemiringNC - SubsemiringWithOne - SubsemiringWithOneAndZero - SubsemiringWithOneAndZeroNC - SubsemiringWithOneNC - SubsemiringWithZero - SubsemiringWithZeroNC - Subspace - SubspaceNC - SubspaceVectorSpaceGroup - Subspaces - SubspacesAll - SubspacesDim - SubstitutedWord - SubstitutionSublist - SubtractBlist - SubtractBlistOrbitStabChain - SubtractSet - Subtype - Subword - Successors - SuggestUpgrades - Sum - SumCoefPolynomial - SumCoefRatfun - SumCoeffLaurpol - SumCoeffUnivfunc - SumFactorizationFunctionPcgs - SumIntersectionMat - SumOfMBMAndMapping - SumOfMappingAndMBM - SumOfPcElement - SumOp - SumPcgs - SumRootsPol - SumRootsPolComp - SumX - SumXHelp - SummandMolienSeries - SupType - SupersolvableResiduum - SupersolvableResiduumDefault - SupportedCharacterTableInfo - SupportedLibraryTableComponents - SurjectiveActionHomomorphismAttr - SuzukiGroup - SuzukiGroupCons - SyllableRepAssocWord - SyllableWordObjByExtRep - SylowComplement - SylowComplementOp - SylowSubgroup - SylowSubgroupOp - SylowSubgroupPermGroup - SylowSystem - SymAdic - SymmetricClosureBinaryRelation - SymmetricDegree - SymmetricGroup - SymmetricGroupCons - SymmetricParentGroup - SymmetricParts - SymmetricPower - SymmetricPowerOfAlgebraModule - Symmetrisations - Symmetrizations - SymplecticComponents - SymplecticGroup - SymplecticGroupCons - SyzygyCriterion - Sz - TRANSGrp - TRANSProperties - TableAutomorphisms - TableHasIntKeyFun - TableOfMarks - TableOfMarksByLattice - TableOfMarksComponents - TableOfMarksCyclic - TableOfMarksDihedral - TableOfMarksFamily - TableOfMarksFrobenius - TableOfMarksFromLibrary - TailOfPcgsPermGroup - TailsInverses - Tau - TeX - TeXObj - TemporaryGlobalVarName - TensorProduct - TensorProductGModule - TensorProductOfAlgebraModules - TensorWreathProductOfMatrixGroup - Tensored - TestConsistencyMaps - TestHomogeneous - TestInducedFromNormalSubgroup - TestJacobi - TestMonomial - TestMonomialFromLattice - TestMonomialQuick - TestMonomialUseLattice - TestPackageAvailability - TestQuasiPrimitive - TestRelativelySM - TestRelativelySMFun - TestRow - TestSubnormallyMonomial - Tester - TextAttr - TextM - TietzeOrigin - TietzeWordAbstractWord - TmpDirectory - TmpName - ToBeDefinedObjFamily - ToBeDefinedObjType - ToggleEcho - TopExtensionsByAutomorphism - Trace - TraceDefinition - TraceImmediateMethods - TraceMat - TraceMethods - TraceModQF - TracePolynomial - TracedCosetFpGroup - TrailingEntriesLTM - TranformsOneIntoZero - TransArrange - TransCombinat - TransGrpLoad - TransStabCSPG - TransferDiagram - TransferPcgsInfo - TransferedExtensionPol - Transformation - TransformationData - TransformationFamily - TransformationNC - TransformationRelation - TransformationRepresentation - TransformationType - TransformingPermutationFamily - TransformingPermutations - TransformingPermutationsCharacterTables - TransformsAdditionIntoMultiplication - TransformsAdditiveInversesIntoInverses - TransformsInversesIntoAdditiveInverses - TransformsMultiplicationIntoAddition - TransformsZeroIntoOne - TransitiveClosureBinaryRelation - TransitiveGroup - TransitiveIdentification - Transitivity - TranslateString - TranslatorSubalgebra - TransposedMat - TransposedMatAttr - TransposedMatDestructive - TransposedMatImmutable - TransposedMatMutable - TransposedMatOp - TransposedMatrixGroup - TransvByDirProdFamily - TransvByHomomorphismFamily - TransvBySchreierTreeFamily - TransvBySiftFunctFamily - TransvByTrivSubgrpFamily - Transversal - TransversalBySiftFunction - TransversalByTrivial - TransversalElt - TransversalOfChainSubgroup - TreeEntry - TreeRepresentedWord - TrialQuotientRPF - TriangulizeIntegerMat - TriangulizeMat - TriangulizeMonomialElementList - TriangulizeWeightRepElementList - TriangulizedGeneratorsByMatrix - TriangulizedIntegerMat - TriangulizedIntegerMatTransform - TriangulizedIntegerMatTransforms - TriangulizedNullspaceMat - TriangulizedNullspaceMatDestructive - TriangulizedNullspaceMatNT - TrivialCharacter - TrivialGModule - TrivialGroup - TrivialGroupCons - TrivialIterator - TrivialModule - TrivialPartition - TrivialQuotientSubgroup - TrivialSubFLMLOR - TrivialSubadditiveMagmaWithZero - TrivialSubalgebra - TrivialSubgroup - TrivialSubmagmaWithOne - TrivialSubmodule - TrivialSubmonoid - TrivialSubnearAdditiveMagmaWithZero - TrivialSubspace - TryCombinations - TryConwayPolynomialForFrobeniusCharacterValue - TryCosetTableInWholeGroup - TryGcdCancelExtRepPolynomials - TryLayerSQ - TryModuleSQ - TryNextMethod - TryPcgsPermGroup - TrySecondaryImages - Tschirnhausen - Tuple - TupleNC - Tuples - TuplesFamily - TuplesK - TwoClosure - TwoClosurePermGroup - TwoCoboundaries - TwoCoboundariesSQ - TwoCocycles - TwoCocyclesSQ - TwoCohomology - TwoCohomologySQ - TwoSeqPol - TwoSidedIdeal - TwoSidedIdealByGenerators - TwoSidedIdealNC - TwoSquares - TypeObj - TypeOfDefaultGeneralMapping - TypeOfFamilies - TypeOfFamilyOfFamilies - TypeOfFamilyOfTypes - TypeOfTypes - TzCheckRecord - TzEliminate - TzEliminateFromTree - TzEliminateGen - TzEliminateGens - TzFindCyclicJoins - TzGeneratorExponents - TzGo - TzGoGo - TzImagesOldGens - TzInitGeneratorImages - TzMostFrequentPairs - TzNewGenerator - TzOccurrences - TzOccurrencesPairs - TzOptionNames - TzOptions - TzPreImagesNewGens - TzPrint - TzPrintGeneratorImages - TzPrintGenerators - TzPrintLengths - TzPrintOptions - TzPrintPairs - TzPrintPresentation - TzPrintRelators - TzPrintStatus - TzRelator - TzRemoveGenerators - TzRenumberGens - TzReplaceGens - TzRules - TzSearch - TzSearchC - TzSearchEqual - TzSort - TzSortC - TzSubstitute - TzSubstituteCyclicJoins - TzSubstituteGen - TzSubstituteWord - TzTestInitialSetup - TzUpdateGeneratorImages - TzWordAbstractWord - UNIXSelect - UglyVector - UnInstallCharReadHookFunc - UnSetImage - Unbind - UnbindElmWPObj - UnbindGlobal - UnderlyingCharacterTable - UnderlyingCharacteristic - UnderlyingCollection - UnderlyingDomainOfBinaryRelation - UnderlyingElement - UnderlyingElementOfReesMatrixSemigroupElement - UnderlyingElementOfReesZeroMatrixSemigroupElement - UnderlyingExternalSet - UnderlyingFamily - UnderlyingField - UnderlyingGeneralMapping - UnderlyingGroup - UnderlyingLeftModule - UnderlyingLieAlgebra - UnderlyingMagma - UnderlyingRelation - UnderlyingSemigroupOfReesMatrixSemigroup - UnderlyingSemigroupOfReesZeroMatrixSemigroup - UnderlyingVectorSpace - UndoRefinement - UnhideGlobalVariables - Union - UnionBlist - UnionSet - UnipotentSubgroup - Unique - UniteBlist - UniteBlistList - UniteSet - Units - UnivariateLaurentPolynomialByCoefficients - UnivariatePolynomial - UnivariatePolynomialByCoefficients - UnivariatePolynomialRing - UnivariateRationalFunctionByCoefficients - UnivariateRationalFunctionByExtRep - UnivariatenessTestRationalFunction - UniversalEnvelopingAlgebra - Unknown - UnknownsType - UnloadSmallGroupsData - UnlockNaturalHomomorphismsPool - UnmarkTree - UnorderedTuples - UnorderedTuplesK - UnprofileFunctions - UnprofileMethods - UntraceMethods - UpEnv - UpdateMap - UpdatePolycyclicCollector - UpdateWeightInfo - UpperActingDomain - UpperCentralSeries - UpperCentralSeriesOfGroup - UpperSubdiagonal - UseBasis - UseFactorRelation - UseIsomorphismRelation - UseMatrixChainSubgroups - UsePermChainSubgroups - UseStabChainViaChainSubgroup - UseSubsetRelation - UseSubsetRelationNC - VPActionHom - VSTInsertToLeft - VSTNode - ValidatePackageInfo - Valuation - Value - ValueCochain - ValueGlobal - ValueMolienSeries - ValueOption - ValuePol - ValuesOfClassFunction - VectorOfRelator - VectorSearchTable - VectorSpace - VectorSpaceByPcgsOfElementaryAbelianGroup - VerifySGS - VerifyStabilizer - View - ViewFullHomModule - ViewLength - ViewMolienSeries - ViewObj - VirtualCharacter - WallForm - WeakPointerObj - WedgeGModule - WeekDay - WeightLexOrdering - WeightLexOrderingNC - WeightOfGenerators - WeightVecFFE - WeightsTom - WeylGroup - WeylOrbitIterator - Where - WindowCmd - Word - WordAlp - WordsString - WreathElm - WreathProduct - WreathProductImprimitiveAction - WreathProductInfo - WreathProductOfMatrixGroup - WreathProductOrdering - WreathProductProductAction - WriteAll - WriteBibFile - WriteByte - WriteLine - ZClassRepsQClass - ZOp - ZassenhausIntersection - Zero - ZeroAttr - ZeroCoefficient - ZeroCoefficientRatFun - ZeroImmutable - ZeroMapping - ZeroMutable - ZeroOp - ZeroSM - ZeroSameMutability - ZevData - ZevDataValue - ZippedListQuotient - ZippedProduct - ZippedSum - ZmodnZ - ZmodnZObj - ZmodpZ - ZmodpZNC - ZumbroichBase - Zuppos - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/gdb.xml b/qutepart/syntax/gdb.xml deleted file mode 100644 index 85f9383..0000000 --- a/qutepart/syntax/gdb.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qutepart/syntax/gdl.xml b/qutepart/syntax/gdl.xml deleted file mode 100644 index a41af14..0000000 --- a/qutepart/syntax/gdl.xml +++ /dev/null @@ -1,313 +0,0 @@ - - - - - - white - blue - red - green - yellow - magenta - cyan - darkgrey - darkgray - darkblue - darkred - darkgreen - darkyellow - darkmagenta - darkcyan - gold - lightgrey - lightgray - lightblue - lightred - lightgreen - lightyellow - lightmagenta - lightcyan - lilac - turquoise - aquamarine - khaki - purple - yellowgreen - pink - orange - orchid - black - - - box - triangle - circle - ellipse - hexagon - rhomb - rhomboid - trapeze - uptrapeze - trapezoid - uptrapezoid - lparallelogram - rparallelogram - - - unfolded - folded - boxed - clustered - wrapped - exclusive - white - - - normal - tree - forcedir - dfs - minbackward - maxdepth - maxdepthslow - mindepth - mindepthslow - minindegree - minoutdegree - maxindegree - maxoutdegree - maxdegree - mindegree - - - attraction - repulsion - randomfactor - randomimpulse - randomrounds - tempscheme - temptreshold - tempmin - tempmax - - - no - polar - circular - polcircular - orthogonal - - - toptobottom - bottomtotop - lefttoright - righttoleft - top_to_bottom - bottom_to_top - left_to_right - right_to_left - - - solid - continuous - dashed - dotted - double - triple - invisible - - - pfish - cfish - fpfish - fcfish - dpfish - dcfish - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qutepart/syntax/generate-php.pl b/qutepart/syntax/generate-php.pl deleted file mode 100644 index c6bb3a5..0000000 --- a/qutepart/syntax/generate-php.pl +++ /dev/null @@ -1,56 +0,0 @@ -# This perl script read stdin and write on stdout. It shall be an XML language file. -# -# * If the name of the language is 'HTML', then it creates the language 'PHP (HTML)' -# which shall be used for PHP hl. -# -# * If the name of the language is something else (say '*'), it creates the language '*/PHP'. -# This new language is the same as the old one, but is able to detect PHP everywhere. -# -# This script will correctly set extensions & mimetype, and will replace -# by -# -# Generated languages need a language named 'PHP/PHP', which shall take care of PHP hl itself -# and which will be called every time something like -# License: LGPL - -my $file = ""; - -while (<>) -{ - $file .= $_; -} - -$warning = "\n\n\n"; - -$file =~ s/(?=]+name="HTML"/) -{ - $root = 1; -} - -if ($root == 1) -{ - $file =~ s/]+)name="[^"]*"/]+)section="[^"]*"/]+)extensions="[^"]*"/]+)mimetype="[^"]*"/]+)name="([^"]*)"/