commit 32f28094bfa7cc3ce54b862cde7c7e95a2b3e3c4 Author: unknown Date: Mon Oct 19 14:27:31 2015 +0400 Initial release diff --git a/BUGS b/BUGS new file mode 100644 index 0000000..f467a3b --- /dev/null +++ b/BUGS @@ -0,0 +1,35 @@ +###################################################### +# Tcl/Tk project Manager +# Distributed under GNU Public License +# Author: Sergey Kalinin banzaj@lrn.ru +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru +###################################################### + +- Файл проекта, убрать расширение +- Глюки подсветки + +* Изменение размера шрифтов для редактора вступает в силу только после +перезагрузки, что не очень-то удобно. + +* При запуске приходится делать лишнее усилие по открытию root +элемента в TreeView. Сделай это по умолчанию автоматом, плиз. И чтобы +это также работало при команде refresh. + +* Есть refresh для TreeView хорошо бы тогда чтобы он или другая +функция обновляла syntax hightlight, а то когда большие куски +ставляешь кода и он их не рассчвечивает неудобно. + +* При вводе текста если ввести proc, то твой редактор подставит +автоматом скобки. Вообще-то это не очень правильно, к примеру я +ставлю после функции комментарий вида } ;# proc testFunct +И вот тут он вставляет не нужные мне сейчас ковычки. По идеи надо в +balloon окне показать формат этой команды (также для все остальных). +Посмотри как это сделано в VisualBasic версии > 4. А так есть еще +один баг. Если у меня перед командой proc стоят пробелы, то точно +такое же их количество должно стоять и после последней закрывающей +скобкой иначе все форматирование едит и надо править ручками. + +- При установки переменной editor(wrap) значения none на длинных строках при появлениии нижнего скролбара наблюдается глюк пока не объяснимый :( +Скрол бар начинает мерцать (то появиться то исчезнет) + + diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..13f0f3f --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,348 @@ +######################################################### +# Tcl/Tk Project Manager +# Distributed under GNU Public License +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru +######################################################### + +0.3.7 + +18/10/2007 +-Added text encoding support from koi8-r,cpp1251,cp866 to UTF-8 + +20/02/2007 +- Fixed settings dialog +- Fixed saved settings parameter + +27/01/2006 + +- Remove SuperText widget now use native TEXT + +29/12/2005 +- Added RUBY projects support +- Fixed remove project if some files is open in editor +- Add function for added interpritator into new like #!/usr/bin/wish + +0.3.6 + +18/02/2005 +- Fixed correctly file attributes in WIN OS as like a date and time + +01/02/2005 +- Added DOT-file support + +07/12/2004 +- Added PHP projects support + +0.3.5 + +01/11/2004 +- Added Rivet and TclHttpd template files support +- Removed BWidget documentation +- Fixed bug with One Click mouse button on folder in TreeWidget + +25/10/2004 +Fixed bug with PageRise function + +27/09/2004 +- Added "Create New Directory" dialog into main and pop-up menu + +14/09/2004 +- Added image viewer +- Fixed close projman if was not opened projects + +0.3.4 +15/07/2004 +- Fixed closes "About" window with popup menu + +13/04/2004 +- Added O'Caml (ML) support (not stable) +- Fixed settings dialog + +0.3.3 + +04/12/2003 +- Fix perl source code navigation ('sub' keyword) + +22/09/2003 +- Added fortran project support +- Added STDERR output in text widget when project or file compile (running) + +10/07/2003 +- Fix buf with runing TkCVS and other modules + +07/07/2003 +- Added PERL project support +- Added "Control+ PageUp" and "Control+ PageDown" key switching editors tabs +- Added popupmenus for tabs + +0.3.2 +20/12/2002 +- Fixed "Open project" from any directoryes, now files don't copying into default projects dir +- Fixed "Delete project" procedure +- Change work dir in windows - now .projman +- Small change install dialog + +15/12/2002 +- Fixed error with delete file +06/12/2002 +- Fixed error with comments highlight in JAVA-source + +0.3.1 + +20/11/2002 +- Added comand line option in compiler string (for projects) +- Fixed file compile procedure +- Fixed add (create new) file to project procedure. Now file created in any location. + +05/11/2002 +- Fixed error with run project on press F9 key +- Fixed error with different project location +- Fixed "Select All" procedure +- Small bugs fixes in projects.tcl +- Code cleaning +- Fixed Save/Close editing file + +0.3.0 + +28/10/2002 +- Correct main menus and popup-menus ("file" and "projects" menus) + +25/10/2002 +- Fixed settings dialog - now full working :) +- Added JAVA files and project compiling + +14/10/2002 +- Remove editor.conf, now all setting placement in projman.conf need replace old ~/.projman/projman.conf file +- Fixed "Settings dialog" + +16/09/2002 +- Changed TCL highlight procedure + +10/09/2002 +- Added JAVA project support like source code highlightning, project managment, class navigation + +0.2.5 + +02/09/2002 +- New release VisualRegexp added (thanks Laurent Riesterer) + +17/06/2002 +- Bug in Help procedure (
 tag) fixed (by  Alexander Danilov) 
+
+0.2.4
+11/06/2002
+- Fixed copying french documentation files
+- Now interface language setting on $env(LANG) variable (system lacale) and HOMEPATH HOMEDRIVE vars (for windows)
+- Change Procedure Complitition proc
+- Change load modules procedure
+
+05/06/2002
+- Change tcl highlight procedure for braces and options (by Korwin)
+
+03/06/2002
+- Small GUI changes (Tree view, AboutBox)(by  Alexander Danilov)
+- Fixed help files path in install.tcl (by  Alexander Danilov)
+- Added "Close" button into toolbar
+- Change Settins dialog (now self window) - DON'T WORKING developers only
+- Code clean (procedure.tcl)
+- Changes NoteBook title (save/modify file veiew)
+
+0.2.3
+30/05/2002
+- Added icon for XML files
+- Added XML highlightning (used highlight/html.tcl)
+- Added "Select All" command into "Edit" menu
+- Fixed "Overwrite/Insert" procedure
+- Fixed On/Off toolbar
+
+
+21/05/2002
+- Rewrite all TCL and TK docs by Alexander Danilov 
+
+0.2.2
+17/05/2002
+- Fixed calling external modules procedure
+
+0.2.1
+
+14/05/2002
+- Fixed location help files
+    - Added menu support into spec
+    
+    15/04/2002
+    - Changes highlight procedure - now all highlight files puts into /highlight directory and loaded automaticaly and now creation new highlight module so easy...
+    - Added TeX highlightning
+    
+    09/04/2002
+    - Added french localisation and Tcl help by Michel SALVAGNIAC
+    
+    01/04/2002
+    - Added german localisation by Roman Schaller 
+
+0.2.0 (26/03/2002)
+        
+    - Added Close opened file procedure when Delete file
+    - Fix calling Ctags module if ctags package not installed
+    - Added paned windows (for changes Tree size)
+            
+    22/03/2002
+    - Autocomplitition procedure (by Alexander Dederer (aka Korwin))
+    - Added procedure names and parameters complitition
+    - Changed Create New File dialog
+    - Fixed directory setings and created into Windows
+    - Added CTags support (*nix only)
+    - Fixed error with Pop-Up menu
+    - Added Edit pop-up menu into editor window
+    - Small fix with some keys binding
+    - Small fix with quit ProjMan and saved modifing files 
+    
+        
+
+0.1.5 (01/03/2002)
+    - Fix autoindent text procedure
+    - Include updated ducumenation (by Alex Danilov)
+        
+        
+0.1.4 (20/02/2002)
+    - Fix some problem with Close/Open file
+    - Added bracket highlightning and corsor jumping for bracket!!! (by Korwin)
+        
+
+    07/02/2002
+    - Added refresh Tree procedure and ToolBar On/Off procedure
+    - Some changes menu structure
+        
+
+    05/02/2002
+    - Changed GUI for installiation dialog
+    - Added english ProjMan user manual
+        
+    04/02/2002
+    - Changes documentation structure, now documentation split by chapters and languages
+    - Changes Help procedure for working with new directory structure
+    - Include new Tcl documentation by Alexander Danilov
+    - Changes installiation procedure - added select Documentation language for install
+    - Fixed problem with encoding russian documentation in Windows OS
+    - Fixed problem with names like "proc::name" into Help system
+    - Added Tcl/Tk and BWidget english documentation
+        
+0.1.3 (31/01/2002)
+        - Replase SelectDir on standart dialog tk_chooseDirectory
+        - Fixed error into TkDIFF+ with convert date procedure
+        - Added find history in Find dialog, and now used F3 for repeat searching
+        - Fixed hot keys bindings into Find (F3, Enter) and Replace (F4, Enter) dialogs
+        - Fixed changing "File modify" flag after successfully replaceing
+
+0.1.2 (29/01/2002)
+        - Fix error with "Close all" procedure if raised About (Debug, Settings e.t.c.) dialog
+        - Translate TODO on English
+
+        24/01/2002
+        - Added mouse wheel support on Tree widget (by Korwin)
+        - Added "editor.conf" for change editor preferences and source highlightning colors
+
+0.1.1 (23/01/2002)
+        - Fix correct cursor position viewed
+        - Added highlightning comments like ";#" (by Korwin)
+
+        22/01/2002
+        - Added raised notebook tab when click mouse on opened file name
+        - Fix correct windows path to tcl interpritator into Project Setting dialog
+        - Added TkREGEXP module (aka VisualREGEXP) from Laurent Riesterer
+        - Added new diff'ing module TkDIFF+ (with compare dirrectoryes) from Laurent Riesterer
+        - Added TkREGEXP and TkDIFF+ documentation
+
+        19/01/2002
+        - Fix callback links procedure into help system (thanks Dederer)
+    
+0.1.0 (17/01/2002)
+        - Added graphical installiation
+        - Corrected path for work in windows
+        
+        16/01/2002
+        - Fix error with create and select directory into install.tcl
+        - Some Windows bugs fix
+        - Add invoke tkDiff for one or two selected files
+        - Add saved all files before run project
+
+0.0.19 (15/01/2002)
+        - Add "Select Directory" procedure into settings page
+        - Add "Open project" procedure for adding existing project
+        - Add invoke TkCVS for Active project
+        - Fix error with open files with names like "some.file.name"
+        - Code cleaning
+
+        14/01/2001
+        - Add close window procedure into "Settings" and "Project Settings" dialog
+        after pushed "Save" button
+
+0.0.17 (11/01/2002)
+        - Fix error with "New file" in new project procedure
+        - Fix small errors
+
+        10/01/2002
+        - Replaced hotkey "Ctrl-T" with "Ctrl-M". And now "Control-T" reverses the order of the two
+        characters to the right of the insertion cursor.
+        - Fix small bug
+
+        09/01/2002
+        - Added "Interface Language" select procedure into "Settings" dialog
+        - Fix error with close opening and modifing file procedure
+        - Fix read procedure with names "Proc::Name" and "Proc_name"
+        - Fix Insert/Overwrite editor mode
+
+        08/01/2002
+        - Fix error in notebook with mouse button click
+        - Changes mouse click procedure in Tree widget
+
+        07/01/2002
+        - Added "Print file" command
+            - Added "Print Selected text" command
+        - Fix error with "Save Setting" procedure (CheckBox verify)
+        - Fix error with "Find dialog" "Replace dialog", e.t.c. if no files opened
+        - Added "Editor font" option
+
+        04/01/2002
+        - Fixed many small bugs
+        - Fix error with Ctrl+T keys
+        - Fix error with "Save As" procedure
+
+        03/01/2002
+        - Added THANKS file, and view this into About window
+        - Fix problem with execute external browser from About window
+        - Fix create new text file in "Add To Project" dialog
+        - Fix some errors in MakeRPM procedure, but not working yet :(
+        - Fix error with select active project after creating new project
+        - Fix small error with delete project procedure
+        - Fix uncorrect cursor position counter into editor
+        
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..86cf81a
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,341 @@
+
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                          675 Mass Ave, Cambridge, MA 02139, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	Appendix: How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    
+    Copyright (C) 19yy  
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) 19yy name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  , 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
diff --git a/INSTALL b/INSTALL
new file mode 100644
index 0000000..617a7ab
--- /dev/null
+++ b/INSTALL
@@ -0,0 +1,11 @@
+#########################################################
+#                Tcl/Tk Project Manager
+# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru
+#########################################################
+
+1. Install Tcl/Tk, BWidget first
+3. Run install.tcl script for copying files, or use RedHat Package Manager
+3. Type from the command line 'projman' and enjoy
+
+
diff --git a/README b/README
new file mode 100644
index 0000000..f17d5ba
--- /dev/null
+++ b/README
@@ -0,0 +1,48 @@
+######################################################
+#              Tcl/Tk Project Manager                     #
+#              Distributed under GPL                     #
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru  #
+# Home page: http://conero.lrn.ru                     #
+######################################################
+
+ABOUT
+
+Tcl/Tk Project Manager is a full IDE for programming in TCL/Tk.
+It includes a project and file manager, a source editor with
+syntax highlighting and procedure navigation, a context-sensitive
+help system, and much more.
+Working an Unix (Linux tested) and Windows.
+
+INSTALLATION
+
+See INSTALL
+
+REQUIREMENTS
+
+For UNIX-like OS
+Tcl/Tk http://www.scriptics.com
+BWidget http://sourceforge.net/projects/tcllib
+CTags
+tcl-img - for image viewer
+
+For WINDOWS
+ActiveTcl http://tcl.activestate.com
+
+CREDITS
+
+Sergey Kalinin (aka Banzaj) - main project programmer and coordinator
+banzaj@lrn.ru
+http://conero.lrn.ru
+
+Laurent Riesterer - VisualREGEXP and TkDIFF+ parts
+laurent.riesterer@free.fr
+http://laurent.riesterer.free.fr
+
+Alexander Danilov - rewrite all documentation
+daapp@chat.ru
+
+Alexandr Dederer (aka Korwin) - many features and bugs fixed
+dederer-a@mail.ru
+
+
+
diff --git a/THANKS b/THANKS
new file mode 100644
index 0000000..9bd4095
--- /dev/null
+++ b/THANKS
@@ -0,0 +1,10 @@
+Alexander Danilov, daapp@chat.ru (documentation rewrite)
+Laurent Riesterer, laurent.riesterer@free.fr, http://laurent.riesterer.free.fr (VisualRegexp module)
+Alexander Dederer (aka Korwin) dederer-a@mail.ru (many features and bugs fixed)
+Igor Didkovsky, ididkovsky@mail.ru, http://langos.lrn.ru/ (programm tester)
+Oleg S. Gints (pogramm tester)
+Victor Wagner (aka Vitus), http://www.ice.ru/~vitus
+Serg Oskin, http://oskin.msk.ru/
+DataX/FLORIN Inc. http://www.florin.ru (documentation)
+Peter Campbell, http://fastbase.co.nz/edit (ML-editor)
+Alexey Kakunin, http://kakunin.chat.ru/ (TCL Developer Studio)
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..f8ccfd6
--- /dev/null
+++ b/TODO
@@ -0,0 +1,82 @@
+##########################################################
+#                Tcl/Tk project Manager
+#        Distributed under GNU Public License
+# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru
+##########################################################
+
+1. GUI
+
+- one click tree procedure
+- added tcl-console    
+- added readline widget
+- into settings dialog
+-- on/off highligttning
+-- on/off
+- Add color scheme
+- Переключение закладок с помощью Alt+>  Alt+<
+- перед первой фукнцией возможность перейти в начало документа, а после последней на конец 
+документа
+- В статусбаре самый последнее поле (правое) где тест file saved уж 
+больно большое для таких кратких сообщений.
+- Edit Window split
+
+2. An package managers system independed files
+- rpm spec file
+- deb
+
+4. Working with release (distribute)
+- ftp received
+
+5. Working with files
+- open file dialog
+- include internal cvs support
+- search and replacement text into all projects files (ala grep)
+
+6. Working with projects
+-   - making project procedure
+-- compile error out
+- generate installiation script for projects (install.tcl)
+- synchronize version number into all projects file (if needed)
+- added template file with headers
+- documentation projects (LaTeX)
+- added Select license procedure (settings dialog)
+- change project dir (put into .proj file)
+
+
+8. Internal editor
+- files export
+-- ps
+-- html
+- alphabetics ordered procedure list
+- code/encode text files
+- Add Insert curent date procedure
+- search procedure with reguliar expretions
+- Comment/uncomment selected area
+- On/Off wrap function
+
+
+9. Locale (messages)
+- autodetect system locale
+
+10. Help system
+- patching html_lib
+- searchin in help
+- lock mouse and keyboard when help file opened
+
+11. Multiplatform featuring
+- Windows printing
+
+фолдинг
+поддержка frink (автоформаттер)
+нумерация строк
+
+
+
+
+########################################
+
+
+
+
+
diff --git a/baloon.tcl b/baloon.tcl
new file mode 100644
index 0000000..d56bef9
--- /dev/null
+++ b/baloon.tcl
@@ -0,0 +1,87 @@
+#######################################################################
+#                        Baloon help
+#                Author: Alexander Dederer
+# Usage:
+#   Set balloon tips to widget:
+#     balloon $widget set "Hello World"
+#     balloon [button .exit -text "exit" -command exit] set "Hello world"
+#
+#   Clear ballon tips from widget:
+#     balloon $widget clear
+#
+#   Show balloon tips on widget:
+#     balloon $widget show "Hello World"
+#######################################################################
+
+proc balloon { widget action args } {
+    global BALLOON
+    
+    switch -- $action {
+        set {
+            if { $args != {{}} } {
+                balloon $widget clear
+                #bind $widget  "after 1000 [list balloon %W show $args mousepointer %X %Y]"
+                #bind $widget  "catch { destroy %W.balloon }"
+                bind $widget  " balloon $widget show $args "
+                bind $widget  " wm withdraw .bubble "
+            }
+        }
+        show {
+            if ![winfo exists .bubble] {
+                toplevel .bubble -relief flat -background black -bd 1
+                wm withdraw .bubble
+                update
+                array set attrFont [font actual fixed]
+                set attrFont(-size) [expr $attrFont(-size) - 2]
+                eval pack [message .bubble.txt -aspect 5000 -bg lightyellow \
+                -font [array get attrFont] -text [lindex $args 0]]
+                pack .bubble.txt
+                wm transient .bubble .
+                wm overrideredirect .bubble 1
+                bind .bubble  "wm withdraw .bubble"
+            } ;# if
+            
+            if {$args == ""} {  wm withdraw .bubble  }
+            set text [lindex $args 0]
+            
+            set BALLOON $text
+            switch $text {
+                ""        {   wm withdraw .bubble ; update  }
+                "default" {
+                    after 1000 "raise_balloon $widget {$text}"
+                    after 7000 "if { \$BALLOON == {$text} } { wm withdraw .bubble ; update }"
+                }
+            } ;# switch
+        }
+        clear {
+            catch { destroy .balloon }
+            bind $widget  {}
+            bind $widget  {}
+        }
+    } ;# switch action
+} ;# proc balloon
+
+
+proc raise_balloon {widget text} {
+    global BALLOON
+    
+    if { $BALLOON != $text } {   wm withdraw .bubble ; update ; return  }
+    set cur_widget [winfo containing [winfo pointerx .] [winfo pointery .]]
+    if { $cur_widget != $widget } {  return  }
+    
+    raise .bubble
+    .bubble.txt configure -text $text
+    set b_x [expr [winfo pointerx .] - [winfo reqwidth .bubble]/2]
+    set b_y [expr [winfo pointery .] + 15]
+    wm geometry .bubble +$b_x+$b_y
+    wm deiconify .bubble
+    update
+} ;# proc raise_balloon
+
+
+
+
+
+
+
+
diff --git a/completition.tcl b/completition.tcl
new file mode 100644
index 0000000..dafef10
--- /dev/null
+++ b/completition.tcl
@@ -0,0 +1,167 @@
+###########################################################
+#                Tcl/Tk Project Manager                   #
+#                Distrubuted under GPL                    #
+# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru  #
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru       #
+###########################################################
+#                AutoCompletition Procedure               #
+#                    Author Alex DEDERER                  #
+###########################################################
+
+proc auto_completition { widget } {
+    set start_word [$widget get "insert - 1 chars wordstart" insert]
+    set box        [$widget bbox insert]
+    set box_x      [expr [lindex $box 0] + [winfo rootx $widget] ]
+    set box_y      [expr [lindex $box 1] + [winfo rooty $widget] + [lindex $box 3] ] 
+    
+    set cnt 0
+    set pos "1.0"
+    set last_pos ""
+    set pattern "$start_word\\w*"
+    #set pattern ""
+    
+    set list_word($start_word) 1
+    while { ([set start [$widget search -count cnt -regexp -- $pattern $pos end]] != "") } {
+        set word [$widget get $start "$start + $cnt chars"]
+        if { ![string equal $start_word $word] }  { set list_word($word) 1 }
+        set pos [$widget index "$pos + [expr $cnt + 1] chars"]
+        if { [string equal $last_pos $pos] } { break }
+        set last_pos $pos
+    } ;# while
+    
+    bindtags $widget [list CompletitionBind [winfo toplevel $widget] $widget Text sysAfter all]
+    bind CompletitionBind   "bindtags $widget {[list [winfo toplevel $widget] $widget Text sysAfter all]}; catch { destroy .aCompletition }"
+    bind CompletitionBind      { auto_completition_key %W %K %A ; break}
+    eval auto_completition_win $box_x $box_y [array names list_word]
+} ;# proc auto_completition
+
+## PROCEDURE LIST        ##
+## by BanZaj                ##
+proc auto_completition_proc { widget } {
+    global procList activeProject noteBook
+    set nodeEdit [$noteBook raise]
+    if {$nodeEdit == "" || $nodeEdit == "newproj" || $nodeEdit == "about" || $nodeEdit == "debug"} {
+        return
+    }
+    set start_word [$widget get "insert - 1 chars wordstart" insert]
+    set box        [$widget bbox insert]
+    set box_x      [expr [lindex $box 0] + [winfo rootx $widget] ]
+    set box_y      [expr [lindex $box 1] + [winfo rooty $widget] + [lindex $box 3] ] 
+    
+    set cnt 0
+    set pos "1.0"
+    set last_pos ""
+    set pattern "$start_word\\w*"
+    #set list_word($start_word) 1
+    if [info exists procList($activeProject)] {
+        set len [llength $procList($activeProject)]
+    } else {
+        return
+    }
+    set i 0
+    while {$len >=$i} {
+        set line [lindex $procList($activeProject) $i]
+        scan $line "%s" word
+        if [regexp -nocase -all -- {\s\{.*?\}+\s} $line par] {
+            regsub -all (\{|\}) $par " " par
+            set word_ "$word [string trim $par]"
+            if {[string match "$start_word*" $word]} {set list_word($word_) $i}
+        }
+        incr i
+    }    
+    bindtags $widget [list CompletitionBind [winfo toplevel $widget] $widget Text sysAfter all]
+    bind CompletitionBind   "bindtags $widget {[list [winfo toplevel $widget] $widget Text sysAfter all]}; catch { destroy .aCompletition }"
+    bind CompletitionBind      {auto_completition_key %W %K %A ; break}
+    eval auto_completition_win $box_x $box_y [array names list_word]
+} ;# proc auto_completition_proc
+
+
+proc auto_completition_win { x y args} {
+    set win .aCompletition
+    if { [winfo exists $win] }  { destroy $win }
+    toplevel $win
+    wm transient $win .
+    wm overrideredirect $win 1
+    
+    listbox $win.lBox -width 30 -border 2 -yscrollcommand "$win.yscroll set" -border 1
+    scrollbar $win.yscroll -orient vertical -command  "$win.lBox yview" -width 13 -border 1
+    pack $win.lBox -expand true -fill y -side left
+    pack $win.yscroll -side left -expand false -fill y
+    
+    foreach { word } $args {
+        $win.lBox insert end $word
+    } ;# foreach | insert all word 
+    
+    catch { $win.lBox activate 0 ; $win.lBox selection set 0 0 }
+    
+    if { [set height [llength $args]] > 10 } { set height 10 }
+    $win.lBox configure -height $height
+    
+    bind $win       " destroy $win "
+    bind $win.lBox  " destroy $win "
+    
+    wm geom $win +$x+$y
+} ;# auto_completition_win
+
+
+
+proc auto_completition_key { widget K A } {
+    set win .aCompletition
+    set ind [$win.lBox curselection]
+    
+    switch -- $K {
+        Prior   {
+            set up   [expr [$win.lBox index active] - [$win.lBox cget -height]]
+            if { $up < 0 } { set up 0 }
+            $win.lBox activate $up
+            $win.lBox selection clear 0 end
+            $win.lBox selection set $up $up
+        }
+        Next    {
+            set down [expr [$win.lBox index active] + [$win.lBox cget -height]]
+            if { $down >= [$win.lBox index end] }  { set down end }
+            $win.lBox activate $down
+            $win.lBox selection clear 0 end
+            $win.lBox selection set $down $down
+        }
+        Up      {
+            set up   [expr [$win.lBox index active] - 1]
+            if { $up < 0 } { set up 0 }
+            $win.lBox activate $up
+            $win.lBox selection clear 0 end
+            $win.lBox selection set $up $up
+        }
+        Down    {
+            set down [expr [$win.lBox index active] + 1]
+            if { $down >= [$win.lBox index end] }  { set down end }
+            $win.lBox activate $down 
+            $win.lBox selection clear 0 end 
+            $win.lBox selection set $down $down 
+        }
+        Return  {
+            $widget delete "insert - 1 chars wordstart" "insert wordend - 1 chars"
+            $widget insert "insert" [$win.lBox get [$win.lBox curselection]]
+            eval [bind CompletitionBind ]
+        }
+        default {
+            $widget insert "insert" $A
+            eval [bind CompletitionBind ] 
+        }
+    }
+} ;# proc auto_completition_key
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/editor.tcl b/editor.tcl
new file mode 100644
index 0000000..7d7124f
--- /dev/null
+++ b/editor.tcl
@@ -0,0 +1,1161 @@
+###########################################################
+#                Tcl/Tk Project Manager                   #
+#                  all procedure file                     #
+# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru  #
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru       #
+###########################################################
+
+## GETTING OPERATORS FOR COMPLITE PROCEDURE #
+proc GetOp {} {
+    global opList
+    set opList(if) "\{\} \{\n\n\}"
+    set opList(else) "\{\n\n\}"
+    set opList(elseif) "\{\} \{\n\n\}"
+    set opList(for) "\{\} \{\} \{\} \{\n\n\}"
+    set opList(foreach) "\{\n\n\}"
+    set opList(while) "\{\} \{\n\n\}"
+    set opList(switch) "\{\n\n\}"
+    set opList(proc) "\{\} \{\n\n\}"
+    # for Object extention
+    set opList(method) "\{\} \{\n\n\}"
+    set opList(class) "\{\n\n\}"
+}
+## Alexander Dederer (aka Korwin) dederer-a@mail.ru ##
+## SETTING DEFAULT STYLE FOR TEXT WIDGET    ##
+proc SetDefStyle { text args } {
+    global editor(font) editor(fontBold)
+    set a_args(-wrap)     none
+    set a_args(-background)  white
+    set a_args(-font)      {$editor(font)}
+    array set a_args $args
+    
+    foreach { key value } [ array get a_args ] {
+        catch { $text configure $key $value }
+    } ;# foreach
+}
+
+## CURSOR POSITION COUNTERED ##
+proc Position {} {
+    global tree noteBook fontNormal fontBold replace
+    set nodeEdit [$noteBook raise]
+    if {$nodeEdit == "" || $nodeEdit == "newproj" || $nodeEdit == "debug" || $nodeEdit == "about"} {
+        return
+    }
+    set text "$noteBook.f$nodeEdit.text"
+    set pos [$text index insert]
+    set posY [lindex [split $pos "."] 0]
+    set posX [lindex [split $pos "."] 1]
+    set lbl .frmStatus.frmLine.lblLine
+    $lbl configure -text $pos -font $fontBold
+    
+    
+}
+proc ReplaceChar {text} {
+    global replace
+    set pos [$text index insert]
+    set posY [lindex [split $pos "."] 0]
+    set posX [lindex [split $pos "."] 1]
+    if {$replace == 1} {
+        $text delete $posY.$posX $posY.[expr $posX + 1]
+    }
+}
+## OVERWRITE SYMBOL PROCEDURE ##
+proc OverWrite {} {
+    global replace fontNormal
+    if {$replace == 1} {
+        set replace 0
+        .frmStatus.frmOvwrt.lblOvwrt configure -text [::msgcat::mc "Insert"] -font $fontNormal\
+        -foreground black
+    } else {
+        set replace 1
+        .frmStatus.frmOvwrt.lblOvwrt configure -text [::msgcat::mc "Overwrite"] -font $fontNormal\
+        -foreground red
+    }
+}
+## GOTO LINE DIALOG FORM ##
+proc GoToLine {} {
+    global noteBook fileList fontNormal
+    set node [$noteBook raise]
+    if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} {
+        return
+    }
+    set file $fileList($node)
+    set w $noteBook.f$node.goto
+    set text "$noteBook.f$node.text"
+    # destroy the find window if it already exists
+    if {[winfo exists $w]} {
+        destroy $w
+    }
+    # create the new "goto" window
+    toplevel $w
+    wm title $w [::msgcat::mc "Goto line"]
+    wm resizable $w 0 0
+    wm transient $w $noteBook.f$node
+    
+    label $w.text -text [::msgcat::mc "Line number"] -font $fontNormal
+    entry $w.entGoTo -width 6 -validate key -validatecommand "ValidNumber %W %P"
+    pack $w.text $w.entGoTo -side left -anchor nw  -padx 2 -pady 2
+    
+    bind $w.entGoTo  "+GoToLineNumber $text $noteBook.f$node"
+    bind $w.entGoTo  "destroy $w"
+    focus -force $w.entGoTo
+}
+## Check input number ##
+proc ValidNumber {w value} {
+    if [string is integer $value] {
+        return 1
+    } else {
+        bell
+        return 0
+    }
+}
+## GOTO LINE ##
+proc GoToLineNumber {text w} {
+    set lineNumber [$w.goto.entGoTo get]
+    destroy $w.goto
+    catch {
+        $text mark set insert $lineNumber.0
+        $text see insert
+        Position $text .frmStatus.frmLine.lblLine
+    }
+}
+## SEARCH DIALOG FORM ##
+set findHistory ""
+set findString ""
+set replaceString ""
+proc Find {} {
+    global noteBook fileList  findHistory findString fontNormal
+    
+    set node [$noteBook raise]
+    if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} {
+        return
+    }
+    set file $fileList($node)
+    set w $noteBook.f$node.find
+    set text "$noteBook.f$node.text"
+    set findString ""
+    # destroy the find window if it already exists
+    if {[winfo exists $w]} {
+        destroy $w
+    }
+    
+    toplevel $w
+    wm title $w [::msgcat::mc "Find"]
+    wm resizable $w 0 0
+    wm transient $w $noteBook.f$node
+    frame $w.frmCombo -borderwidth 1
+    frame $w.frmBtn -borderwidth 1
+    pack $w.frmCombo $w.frmBtn -side top -fill x
+    
+    #    set combo [entry $w.frmCombo.entFind]
+    set combo [ComboBox $w.frmCombo.txtLocale\
+    -textvariable findString \
+    -selectbackground "#55c4d1" -selectborderwidth 0\
+    -values $findHistory]
+    
+    pack $combo -fill x -padx 2 -pady 2
+    
+    button $w.frmBtn.btnFind -text "[::msgcat::mc "Find"] - F3"\
+    -font $fontNormal -width 12 -relief groove\
+    -command "FindCommand $text $w"
+    button $w.frmBtn.btnCancel -text "[::msgcat::mc "Close"] - Esc"\
+    -relief groove -width 12 -font $fontNormal\
+    -command "destroy $w"
+    pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left
+    
+    bind $w  "FindCommand  $text $w"
+    bind $w  "FindCommand  $text $w"
+    bind $w  "destroy $w"
+    focus -force $combo
+    
+    #    set findIndex [lsearch -exact $findHistory "$findString"]
+    $combo setvalue @0
+}
+
+proc FindCommand {text w} {
+    global findString findHistory
+    #    set findString [$entry get]
+    destroy $w
+    # if null string? do nothing
+    if {$findString == ""} {
+        return
+    }
+    # search "again" (starting from current position)
+    FindNext $text 0
+}
+
+proc FindNext {text {incr 1}} {
+    global findString findHistory
+    set t $text
+    puts $t
+    # append find string into find history list #
+    if {[lsearch -exact $findHistory $findString] == -1} {
+        set findHistory [linsert $findHistory 0 $findString]
+    }
+    
+    set pos [$t index insert]
+    set line [lindex [split $pos "."] 0]
+    set x [lindex [split $pos "."] 1]
+    incr x $incr 
+    
+    set pos [$t search -nocase $findString $line.$x end]
+    
+    # if found then move the insert cursor to that position, otherwise beep
+    if {$pos != ""} {
+        $t mark set insert $pos
+        $t see $pos
+        
+        # highlight the found word
+        set line [lindex [split $pos "."] 0]
+        set x [lindex [split $pos "."] 1]
+        set x [expr {$x + [string length $findString]}]
+        $t tag remove sel 1.0 end
+        $t tag add sel $pos $line.$x
+        focus -force $t
+        return 1
+    } else {
+        bell
+        return 0
+    }
+    Position
+}
+## FIND FUNCTION PROCEDURE ##
+proc FindProc {text findString node} {
+    global noteBook
+    
+    set pos "0.0"
+    $text see $pos
+    set line [lindex [split $pos "."] 0]
+    set x [lindex [split $pos "."] 1]
+    
+    set pos [$text search -nocase $findString $line.$x end]
+    $text mark set insert $pos
+    $text see $pos
+    
+    # highlight the found word
+    set line [lindex [split $pos "."] 0]
+    set x [lindex [split $pos "."] 1]
+    set x [expr {$x + [string length $findString]}]
+    $text tag remove sel 1.0 end
+    $text tag add sel $pos $line.$x
+    focus -force $text
+    Position
+    return 1
+}
+
+#3 REPLACE DIALOG FORM ##
+proc ReplaceDialog {} {
+    global noteBook fontNormal fontBold fileList findString replaceString text
+    set node [$noteBook raise]
+    if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} {
+        return
+    }
+    #set file $fileList($node)
+    set w .replace
+    set text "$noteBook.f$node.text"
+    #    set findString ""
+    # destroy the find window if it already exists
+    if {[winfo exists $w]} {
+        destroy $w
+    }
+    
+    # create the new "find" window
+    toplevel $w
+    wm transient $w $noteBook.f$node
+    wm title $w [::msgcat::mc "Replace"]
+    wm resizable $w 0 0
+
+    set f1 [frame $w.frmFind]
+    set f2 [frame $w.frmReplace]
+    set f3 [frame $w.frmBtn -borderwidth 1]
+    pack $f1 $f2 $f3 -side top -fill x -expand true
+
+    label $f1.lblFind -text [::msgcat::mc "Find"] -font $fontNormal -width 15 -anchor w
+    entry $f1.entFind -width 30
+    pack $f1.lblFind $f1.entFind -side left -padx 2 -pady 2
+    pack $f1.entFind -side left -fill x -expand true  -padx 2 -pady 2
+
+    label $f2.lblReplace -text [::msgcat::mc "Replace with"] -font $fontNormal -width 15 -anchor w
+    entry $f2.entReplace -width 30
+    pack $f2.lblReplace $f2.entReplace -side left -padx 2 -pady 2
+    pack $f2.entReplace -side left -fill x -expand true -padx 2 -pady 2
+
+    button $f3.btnFind -text "[::msgcat::mc "Find"] - Enter" -width 12 -pady 0 -font $fontNormal -relief groove\
+     -command "ReplaceCommand $text $w $f1.entFind $f2.entReplace find"
+    button $f3.btnReplace -text "[::msgcat::mc "Replace"] - F4" -width 12 -pady 0\
+            -font $fontNormal -relief groove\
+            -command {
+                ReplaceCommand $text $w  .replace.frmFind.entFind .replace.frmReplace.entReplace replace
+                focus -force .replace
+            }
+    button $f3.btnReplaceAll -text [::msgcat::mc "Replace all"] -width 12 -pady 0\
+            -font $fontNormal -relief groove\
+            -command "ReplaceCommand $text $w $f1.entFind $f2.entReplace replace_all"
+    button $f3.btnCancel -text "[::msgcat::mc "Cancel"] - Esc" -command "destroy $w"\
+      -width 12 -pady 0 -font $fontNormal -relief groove
+      pack $f3.btnFind $f3.btnReplace $f3.btnReplaceAll $f3.btnCancel\
+            -side left -padx 2 -pady 2 -fill x
+
+    bind $w  "ReplaceCommand $text $w  $f1.entFind $f2.entReplace find"
+    bind $w  "ReplaceCommand $text $w  $f1.entFind $f2.entReplace replace"
+    bind $w  "destroy $w"
+    focus -force $f1.entFind
+
+    if {$findString != ""} {
+        InsertEnt $f1.entFind $findString
+    }
+    if {$replaceString != ""} {
+        InsertEnt $f2.entReplace $replaceString
+    }
+}
+## REPLACE COMMAND ##
+proc ReplaceCommand {text w entFind entReplace command} {
+    global noteBook fontNormal fontBold fileList findString replaceString
+    set node [$noteBook raise]
+    
+    set findString [$entFind get]
+    set replaceString [$entReplace get]
+    
+    switch -- $command {
+        "find" {
+            FindNext $text 1
+            focus -force .replace
+        }
+        "replace" {
+            if {[Replace $text 0]} {
+                FindNext $text 1
+                if {[lindex $fileList($node) 1] == 0} {
+                    set fileList($node) [list [lindex $fileList($node) 0] 1]
+                    LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+                }
+                focus -force .replace
+            }
+        }
+        "replace_all" {
+            set stringsReplace 0
+            if {[Replace $text 0]} {
+                if {[lindex $fileList($node) 1] == 0} {
+                    set fileList($node) [list [lindex $fileList($node) 0] 1]
+                    LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+                }
+                incr stringsReplace
+                while {[Replace $text 1]} {
+                    incr stringsReplace
+                }
+            }
+            tk_messageBox -icon info -title [::msgcat::mc "Replace"]\
+            -parent $text -message\
+            "[::msgcat::mc "Was replacement"] $stringsReplace."
+            destroy $w
+        }
+    }
+}
+## REPLACE ONE WORD PROCEDURE ##
+proc Replace {text incr} {
+    global noteBook fontNormal fontBold fileList findString replaceString
+    
+    if {[FindNext $text $incr]} {
+        set selected [$text tag ranges sel]
+        set start [lindex $selected 0]
+        set end [lindex $selected 1]
+        $text delete $start $end
+        $text insert [$text index insert] $replaceString
+        return 1
+    } else {
+        return 0
+    }
+    #    focus -force .replace
+}
+## FILE OPERATION ##
+proc FileDialog {operation} {
+    global noteBook fontNormal fontBold fileList tree noteBook projDir activeProject imgDir editor
+    set dot "_"
+    set types {
+        {"Tcl files" {.tcl}}
+        {"Tk files" {.tk}}
+        {"Rivet files" {.rvt}}
+        {"TclHttpd Template" {.tml}}
+        {"Sql files" {.sql}}
+        {"Html files" {.html}}
+        {"Text files" {.txt}}
+        {"JAVA files" {.java}}
+        {"PERL files" {.pl}}
+        {"PHP files" {.php}}
+        {"FORTRAN files" {.for}}
+        {"CAML or ML files" {.ml}}
+        {"CAML or ML interface files" {.mli}}
+        {"Ruby files" {.rb}}
+        {"Text files" {} TEXT}
+        {"All files" *}
+    }
+    
+    
+    if {$operation == "open"} {
+        set dir $projDir
+        set fullPath [tk_getOpenFile -initialdir $dir -filetypes \
+        $types -parent $noteBook]
+        regsub -all "." $file "_" node
+        set dir [file dirname $fullPath]
+        set file [file tail $fullPath]
+        set name [file rootname $file]
+        set ext [string range [file extension $file] 1 end]
+        set node "$name$dot$ext"
+        EditFile $node $fullPath
+        return 1
+    } elseif {$operation == "delete"} {
+        set node [$tree selection get]
+        set fullPath [$tree itemcget $node -data]
+        set dir [file dirname $fullPath]
+        set file [file tail $fullPath]
+        set answer [tk_messageBox -message "[::msgcat::mc "Delete file"] \"$file\"?"\
+        -type yesno -icon question -default yes]
+        case $answer {
+            yes {
+                FileDialog close
+                file delete -force "$fullPath"
+                $tree delete $node
+                $tree configure -redraw 1
+                return 0
+            }
+        }
+    } elseif {$operation == "close"} {
+        set node [$noteBook raise]
+        if {$node == "newproj" || $node == "settings" || $node == "about" || $node == "debug"} {
+            $noteBook delete $node
+            set node [$noteBook raise]
+            return
+        } else {
+            if {$node == ""} {return}
+            if {[info exists fileList($node)] == 0} {return}
+            set fullPath [lindex $fileList($node) 0]
+            set dir [file dirname $fullPath]
+            set file [file tail $fullPath]
+            set text "$noteBook.f$node.text"
+        }
+    } elseif {$operation == "close" && [info exists files] == 0} {
+        return
+    }  else {
+        set node [$noteBook raise]
+        puts $node        
+        if {$node == ""} {return}
+        if {[info exists fileList($node)] == 0} {return}
+        set fullPath [lindex $fileList($node) 0]
+        set dir [file dirname $fullPath]
+        set file [file tail $fullPath]
+        set text "$noteBook.f$node.text"
+    }
+    set name [file rootname $file]
+    set ext [string range [file extension $file] 1 end]
+    set treeSubNode "$name$dot$ext"
+    
+    set img [GetImage $file]
+    
+    if {$operation == "open"} {
+        set fullPath [tk_getOpenFile -initialdir $dir -filetypes \
+        $types -parent $noteBook]
+        set file [string range $fullPath [expr [string last "/" $fullPath]+1] end]
+        regsub -all "." $file "_" node
+        $noteBook insert end $node -text "$file"
+        EditFile $node $fullPath
+    } elseif {$operation == "save"} {
+        if {$name == "untitled"} {
+            set file [tk_getSaveFile -initialdir $dir -filetypes \
+            $types -parent $text -initialfile $file \
+            -defaultextension .$ext]
+            set contents [$text get 0.0 end]
+            set fhandle [open "$file" "w"]
+            puts $fhandle $contents nonewline
+            close $fhandle
+            file delete [file join $dir $name.$ext]
+            #$tree delete $treeSubNode
+            unset fileList($node)
+            # change data into tree and notebook
+            set dir [file dirname $file]
+            set file [file tail $file]
+            set name [file rootname $file]
+            set ext [string range [file extension $file] 1 end]
+            $tree itemconfigure $treeSubNode -text $name
+            set treeSubNode "$activeProject$dot$name$dot$ext"
+            
+            #$tree insert end $activeProject $treeSubNode -text "$file" \
+            #-data "[file join $dir $file]" -open 1\
+            #-image [Bitmap::get [file join $imgDir $img.gif]]\
+            #-font $fontNormal
+            set nbNode [$noteBook raise]
+            $noteBook itemconfigure $nbNode -text $file
+            set fileList($nbNode) [list $file 0]
+        } else {
+            set contents [$text get 0.0 end]
+            set fhandle [open [file join $dir $file] "w"]
+            puts $fhandle $contents nonewline
+            close $fhandle
+            EditFlag $node [file join $dir $file] 0
+        }
+    } elseif {$operation == "save_all"} {
+        set i 0
+        set nodeList [$noteBook pages 0 end]
+        set length [llength $nodeList]
+        while {$i < $length} {
+            set nbNode [lindex $nodeList $i]
+            if {[info exists fileList($nbNode)] == 1} {
+                set text "$noteBook.f$nbNode.text"
+                set savedFile [lindex $fileList($nbNode) 0]
+                set contents [$text get 0.0 end]
+                set fhandle [open [file join $dir $savedFile] "w"]
+                puts $fhandle $contents nonewline
+                close $fhandle
+                EditFlag $nbNode [file join $dir $savedFile] 0
+            }
+            incr i
+        }
+    } elseif {$operation == "close"} {
+        # delete file name from fileList array #
+        if {$node == "newproj" || $node == "settings" || $node == "about" || $node == "debug"} {
+            $noteBook delete $node
+            set node [$noteBook raise]
+            return
+        }
+        set editFlag [lindex $fileList($node) 1]
+        set closedFile [file tail [lindex $fileList($node) 0]]
+        if {$editFlag == 1} {
+            set answer [tk_messageBox\
+            -message "$closedFile [::msgcat::mc "File was modifyed. Save?"]"\
+            -type yesnocancel -icon warning\
+            -title [::msgcat::mc "Warning"]]
+            case $answer {
+                yes {
+                    FileDialog save
+                    #                    FileDialog close
+                }
+                no {
+                    set index 0
+                    set nl [$tree nodes $node 0 end]
+                    if {$nl != ""} {
+                        foreach n $nl {
+                            $tree delete $n
+                        }
+                    }
+                    $noteBook delete $node
+                    unset fileList($node)
+                    $noteBook raise [$noteBook page $index]
+                    set node [$noteBook raise]
+                }
+                cancel {
+                    return 0
+                }
+            }
+        } else {
+            set index 0
+            set nl [$tree nodes $node 0 end]
+            if {$nl != ""} {
+                foreach n $nl {
+                    $tree delete $n
+                }
+            }
+            #puts $node
+            $noteBook delete $node
+            unset fileList($node)
+            $noteBook raise [$noteBook page $index]
+            set node [$noteBook raise]
+        }
+        if {$node != ""} {
+            if {$node == "newproj" || $node == "settings" || $node == "about" || $node == "debug"} {
+                $noteBook delete $node
+            } else {
+                focus -force $noteBook.f$node
+            }
+            $tree selection set $node
+        } else {
+            LabelUpdate .frmStatus.frmLine.lblLine ""
+            LabelUpdate .frmStatus.frmFile.lblFile ""
+            LabelUpdate .frmStatus.frmOvwrt.lblOvwrt ""
+            LabelUpdate .frmStatus.frmProgress.lblProgress ""
+        }
+    } elseif {$operation == "close_all"} {
+        set nodeList [$noteBook pages 0 end]
+        $noteBook raise [$noteBook page 0]
+        set nbNode [$noteBook raise]
+        while {$nbNode != ""} {
+            if {$nbNode == "newproj" || $nbNode == "settings" || $nbNode == "about" || $nbNode == "debug"} {
+                $noteBook delete $nbNode
+                $noteBook raise [$noteBook page 0]
+                set nbNode [$noteBook raise]
+            }
+            if {[info exists fileList($nbNode)] == 1} {
+                set editFlag [lindex $fileList($nbNode) 1]
+                if {$editFlag == 1} {
+                    set f [lindex $fileList($nbNode) 0]
+                    set f [file tail $f]
+                    set answer [tk_messageBox\
+                    -message "$f [::msgcat::mc "File was modifyed. Save?"]"\
+                    -type yesnocancel -icon warning\
+                    -title [::msgcat::mc "Warning"]]
+                    case $answer {
+                        yes {
+                            FileDialog save
+                        }
+                        no {}
+                        cancel {return cancel}
+                    }
+                }
+                set nl [$tree nodes $nbNode 0 end]
+                if {$nl != ""} {
+                    foreach n $nl {
+                        $tree delete $n
+                    }
+                }
+                $noteBook delete $nbNode
+                $noteBook raise [$noteBook page 0]
+                unset fileList($nbNode)
+                set nbNode [$noteBook raise]
+            }
+        }
+        LabelUpdate .frmStatus.frmLine.lblLine ""
+        LabelUpdate .frmStatus.frmFile.lblFile ""
+        LabelUpdate .frmStatus.frmOvwrt.lblOvwrt ""
+        
+    } elseif {$operation == "save_as"} {
+        set file [tk_getSaveFile -initialdir $dir -filetypes \
+        $types -parent $text -initialfile $file]
+        if {$file != ""} {
+            set contents [$text get 0.0 end]
+            set fhandle [open $file "w"]
+            puts $fhandle $contents nonewline
+            close $fhandle
+            set dir [file dirname $file]
+            set file [file tail $file]
+            set name [string range $file 0 [expr [string last "." $file]-1]]
+            if {[string last "." $file] == -1} {
+                set ext [string range [file extension $file] 1 end]
+            } else {
+                set ext ""
+            }
+            set treeSubNode "$activeProject$dot$name$dot$ext"
+            $tree insert end $activeProject $treeSubNode -text "$file" \
+            -data "[file join $dir $file]" -open 1\
+            -image [Bitmap::get [file join $imgDir $img.gif]]\
+            -font $fontNormal
+            set nbNode [$noteBook raise]
+            $noteBook itemconfigure $nbNode -text $file
+            set fileList($nbNode) [list $file 0]
+        }
+        return 0
+    }
+}
+## COMPLITE PRODEDURE AND OPERATOR ##
+proc OpComplite {text fileExt node} {
+    global opList autoFormat fileList
+    if {$node == "newproj" || $node == "settings" || $node == "about"} {return}
+    
+    set pos [$text index insert]
+    set line [lindex [split $pos "."] 0]
+    set posNum [lindex [split $pos "."] 1]
+    set string [$text get $line.0 $pos]
+    set first [string wordstart $string [expr $posNum-1]]
+    set op [string range $string $first $posNum]
+    if {[info exists opList($op)] == 1} {
+        if {[string match "*\{" [$text get $pos $line.end]] != 1} {
+            $text insert $pos $opList($op)
+            set x [expr $posNum + 2]
+            $text mark set insert $line.$posNum
+            $text see $line.$posNum
+        } else {
+            return
+        }
+    }
+}
+## OPEN AND CLOSE BRACE HIGHLIGHT ##
+proc BraceHighLight {text} {
+    set pos [$text index insert]
+    set lineNum [lindex [split $pos "."] 0]
+    set posNum [lindex [split $pos "."] 1]
+    set curChar [$text get $lineNum.$posNum $lineNum.[expr $posNum+1]]
+    #    _searchCloseBracket $text \{ \} insert end]
+    
+}
+## NOTEBOOK PAGE SWITCHER ##
+## NOTEBOOK PAGE SWITCHER ##
+proc PageTab {key} {
+    global noteBook tree fileList editor
+    set nb $noteBook
+    set len [llength [$nb pages]]
+    if {$len > 0} {
+        set newIndex [expr [$nb index [$nb raise]] + $key]
+        if {$newIndex < 0} {
+            set newIndex [expr $len - 1]
+        } elseif {$newIndex >= $len} {
+            set newIndex 0
+        }
+        $nb see [lindex [$nb pages] $newIndex]
+        $nb raise [lindex [$nb pages] $newIndex]
+        PageRaise [lindex [$nb pages] $newIndex]
+    }
+}
+
+proc _PageTab {} {
+    global noteBook tree fileList editor
+    set nodeList [$noteBook pages 0 end]
+    set length [llength $nodeList]
+    set node [$noteBook raise]
+    set nodeIndex [$noteBook index $node]
+    if {$nodeIndex == [expr $length-1]} {
+        set nextNode [$noteBook page 0]
+    } else {
+        set nextNode [$noteBook page [expr $nodeIndex + 1]]
+    }
+    $noteBook raise $nextNode
+    
+    if {$nextNode == "newproj" || $nextNode == "settings" || $nextNode == "about" || $nextNode == "debug"} {
+        return
+    } else {
+        $tree selection set $nextNode
+        $tree see $nextNode
+        set item [$tree itemcget $nextNode -data]
+        focus -force $noteBook.f$nextNode.text
+        LabelUpdate .frmStatus.frmHelp.lblHelp "[FileAttr $item]"
+        LabelUpdate .frmStatus.frmFile.lblFile "[file size $item] b."
+        if {[lindex $fileList($nextNode) 1] == 0} {
+            LabelUpdate .frmStatus.frmProgress.lblProgress ""            
+            $noteBook itemconfigure $node -foreground $editor(nbNormal)
+        } else {
+            LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+            $noteBook itemconfigure $node -foreground $editor(nbModify)
+        }
+    }
+}
+## RAISED NOTEBOOK TAB IF CLICK MPOUSE BUTTON ##
+proc PageRaise {node} {
+    global noteBook tree fileList editor nodeEdit
+    #puts $node
+    $noteBook raise $node
+    set nodeEdit [$noteBook raise]
+    #set nodeEdit $node
+    puts $node
+    puts $nodeEdit
+    if {$node == "newproj" || $node == "settings" || $node == "about" || $node == "debug"} {
+        return
+    } else {
+        $tree selection set $node
+        $tree see $node
+        set item [$tree itemcget $node -data]
+        puts $item ;# debug
+        set ext [GetExtention $node]
+        if {$ext == "gif" || $ext == "jpg" || $ext == "png" || $ext == "xpm"  || $ext == "xbm"} {
+            focus -force $noteBook.f$node.f.c
+        } else {
+            focus -force $noteBook.f$node.text
+            Position
+        }
+        
+        LabelUpdate .frmStatus.frmHelp.lblHelp "[FileAttr $item]"
+        LabelUpdate .frmStatus.frmFile.lblFile "[file size $item] b."
+        if {[lindex $fileList($node) 1] == 0} {
+            LabelUpdate .frmStatus.frmProgress.lblProgress ""
+            $noteBook itemconfigure $node -foreground $editor(nbNormal)
+        } else {
+            LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+            $noteBook itemconfigure $node -foreground $editor(nbModify)
+        }
+    }
+}
+
+## TABULAR INSERT (auto indent)##
+proc TabIns {text} {
+    set tabSize 4
+    set indentSize 4
+    set pos [$text index insert]
+    set lineNum [lindex [split $pos "."] 0]
+    set posNum [lindex [split $pos "."] 1]
+    if {$lineNum > 1} {
+        # get current text
+        set curText  [$text get $lineNum.0 "$lineNum.0 lineend"]
+        #get text of prev line
+        set prevLineNum [expr {$lineNum - 1}]
+        set prevText [$text get $prevLineNum.0 "$prevLineNum.0 lineend"]
+        #count first spaces in current line
+        set spaces ""
+        regexp "^| *" $curText spaces
+        #count first spaces in prev line
+        set prevSpaces ""
+        regexp "^( |\t)*" $prevText prevSpaces
+        set len [string length $prevSpaces]
+        set shouldBeSpaces 0
+        for {set i 0} {$i < $len} {incr i} {
+            if {[string index $prevSpaces $i] == "\t"} {
+                incr shouldBeSpaces $tabSize
+            } else  {
+                incr shouldBeSpaces
+            }
+        }
+        #see last symbol in the prev String.
+        set lastSymbol [string index $prevText [expr {[string length $prevText] - 1}]]
+        # is it open brace?
+        if {$lastSymbol == "\{"} {
+            incr shouldBeSpaces $indentSize
+        }
+        set a ""
+        regexp "^| *\}" $curText a
+        if {$a != ""} {
+            # make unindent
+            if {$shouldBeSpaces >= $indentSize} {
+                set shouldBeSpaces [expr {$shouldBeSpaces - $indentSize}]
+            }
+        }
+        set spaceNum [string length $spaces]
+        if {$shouldBeSpaces > $spaceNum} {
+            #insert spaces
+            set deltaSpace [expr {$shouldBeSpaces - $spaceNum}]
+            set incSpaces ""
+            for {set i 0} {$i < $deltaSpace} {incr i} {
+                append incSpaces " "
+            }
+            $text insert $lineNum.0 $incSpaces
+        } elseif {$shouldBeSpaces < $spaceNum} {
+            #delete spaces
+            set deltaSpace [expr {$spaceNum - $shouldBeSpaces}]
+            $text delete $lineNum.0 $lineNum.$deltaSpace
+        }
+    }
+}
+
+proc EditFlag {node file flag} {
+    global fileList editor noteBook
+    if {$flag == 0} {
+        set fileList($node) [list $file 0]
+        LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File saved"]
+        $noteBook itemconfigure $node -foreground $editor(nbNormal)
+    } else {
+        set fileList($node) [list $file end 1]
+        LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+        $noteBook itemconfigure $node -foreground $editor(nbModify)
+    }
+}
+proc TextEncode {encode} {
+    global fileList editor noteBook
+    set node [$noteBook raise]
+    if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} {
+        return
+    }
+    #set file $fileList($node)
+    set w .replace
+    set text "$noteBook.f$node.text"
+    set contents [$text get 0.0 end]
+    #puts "[lindex $files($activeFile) 2] $encode"
+    set contents [encoding convertfrom $encode $contents]
+    #set contents [encoding convertfrom $encode $contents]
+    $text delete 0.0 end
+    $text insert end $contents
+    unset text
+    #SetEncode $encode
+}
+
+## EDITING  FILE ##
+proc EditFile {node fileName} {
+    global projDir workDir imgDir tree noteBook fontNormal fontBold w fileList replace nodeEdit
+    global backUpFileCreate fileExt progress editor braceHighLightBG braceHighLightFG 
+    set nodeEdit $node
+    set replace 0
+    set file [file tail $fileName]
+    set name [file rootname $file]
+    set fileExt [string range [file extension $fileName] 1 end]
+    set parentNode  [$tree parent $node]
+    set project [$tree itemcget $parentNode -data]
+    set w [$noteBook insert end $node -text "$file" -image [Bitmap::get [file join $imgDir [GetImage $fileName].gif]]]
+    # create array with file names #
+    if {[info exists fileList($node)] != 1} {
+        set fileList($node) [list $fileName 0]
+        LabelUpdate .frmStatus.frmProgress.lblProgress ""
+    }
+    
+    
+    if {$fileExt == "gif" || $fileExt == "jpg" || $fileExt == "png"  || $fileExt == "xpm" || $fileExt == "xbm"} {
+        ImageViewer $fileName $w $node
+        #$scrwin setwidget $w.ц⌠
+        $noteBook raise $node
+        return
+    }
+    set scrwin [ScrolledWindow $w.scrwin -bg $editor(bg)]
+     pack $scrwin -fill both -expand true
+    
+    
+    text $w.text\
+    -relief sunken -wrap $editor(wrap) -highlightthickness 0 -undo 1 -font $editor(font)\
+    -selectborderwidth 0 -selectbackground #55c4d1 -width 10 -background $editor(bg) -foreground $editor(fg)
+    
+    pack $w.text -side left -fill both -expand true
+    $scrwin setwidget $w.text
+    
+    if {$backUpFileCreate == "Yes"} {file copy -force $fileName "$fileName~"}
+    
+    $noteBook raise $node
+    set procName ""
+    set file [open "$fileName" r]
+    set lineNumber 1
+    #    Progress start
+    #    LabelUpdate .frmStatus.frmProgress.lblProgress "[::msgcat::mc "Opened file in progress"]"
+    
+    while {[gets $file line]>=0} {
+        # Insert procedure names into tree #
+        regsub -all {\t} $line "        " line
+        $w.text insert end "$line\n"
+        #        set progress $lineNumber
+        set keyWord ""
+        set procName ""                                                         
+        
+        if {$fileExt == "php" || $fileExt == "phtml"} {
+            regexp -nocase -all -- {(function) (.*?)\(} $line match keyWord procName
+            #puts "$keyWord --- $procName"
+            
+        } else {
+            scan $line "%s%s" keyWord procName
+        }
+        # && $procName != ""
+        if {$keyWord == "proc" || $keyWord == "let" || $keyWord == "class" || $keyWord == "sub" || $keyWord == "function" || $keyWord == "fun" } {
+            set dot "_"
+            set openBrace [string first "\{" $line]
+            set closeBrace [expr [string first "\}" $line]-1]
+            set var [string range $line $openBrace end]
+            regsub -all ":" $procName "_" prcNode
+            if {$keyWord == "proc" || $keyWord == "sub" || $keyWord == "function"  || $keyWord == "let"} {
+                set img "proc.gif"
+            } elseif {$keyWord == "class"} {
+                set img "class.gif"
+            }
+            if {[$tree exists $prcNode$dot$lineNumber] !=1} {
+                $tree insert end $node $prcNode$dot$lineNumber -text $procName \
+                -data "prc_$procName"\
+                -image [Bitmap::get [file join $imgDir $img]] -font $fontNormal
+            }
+        }
+        incr lineNumber
+    }
+    close $file
+    $w.text mark set insert 0.0
+    $w.text see insert
+    $w.text tag configure lightBracket -background #000000 -foreground #00feff
+    
+    # key bindings #
+    set text $w.text
+    bind $text  {
+        regexp {^(\s*)} [%W get "insert linestart" end] -> spaceStart
+        %W insert insert "\n$spaceStart"
+        break
+    }
+
+    
+    bind $text  GoToLine
+    bind $text  GoToLine
+    bind $text  Find
+    bind $text  Find
+    bind $text  {FindNext $w.text 1}
+    bind $text  ReplaceDialog
+    bind $text  ReplaceDialog
+    bind $text  {ReplaceCommand $w.text 1}
+    bind $text  {FileDialog save}
+    bind $text  {FileDialog save}
+    bind $text  {FileDialog save_as}
+    bind $text  {FileDialog save_as}
+    bind $text  {FileDialog close}
+    bind $text  {FileDialog close}
+    bind $text  "tk_textCut $w.text;break"
+    bind $text  "tk_textCut $w.text;break"
+    bind $text  "tk_textCopy $w.text;break"
+    bind $text  "tk_textCopy $w.text;break"
+    bind $text  "tk_textPaste $w.text;break"
+    bind $text  "tk_textPaste $w.text;break"
+    bind $text  "auto_completition $text"
+    bind $text  "auto_completition $text"
+    bind $text  "auto_completition_proc $text"
+    bind $text  "auto_completition_proc $text"
+    bind $text  Find
+    bind $text  Find
+    #bind .  PageTab
+    #bind .  PageTab
+    bind $text  {OverWrite}
+    bind $text  {Position}
+    bind $text  {catch [PopupMenuEditor %X %Y]}
+    bind $text  "%W yview scroll -3 units"
+    bind $text  "%W yview scroll  3 units"
+    #bind $text  "%W xview scroll -2 units"
+    #bind $text  "%W xview scroll  2 units"
+    
+    bind $text  {
+        Position
+        set nodeEdit [$noteBook raise]
+        if {$nodeEdit == "" || $nodeEdit == "newproj" || $nodeEdit == "settings" || $nodeEdit == "about" || $nodeEdit == "debug"} {
+        } else {
+            set textEdit "$noteBook.f$nodeEdit.text"
+            set pos [$textEdit index insert]
+            set line [lindex [split $pos "."] 0]
+            set editLine [$textEdit get $line.0 $pos]
+            if {$autoFormat == "Yes"} {
+                if {$fileExt != "for"} {
+                    TabIns $textEdit
+                }
+            }
+            HighLight $fileExt $textEdit $editLine $line $nodeEdit
+        }
+    }
+    bind $text  {
+        if {$nodeEdit == "" || $nodeEdit == "newproj" || $nodeEdit == "settings" || $nodeEdit == "about"  || $nodeEdit == "debug"} {
+        } else {
+            set nodeEdit [$noteBook raise]
+            if {[Key %k] == "true"} {
+                if {[lindex $fileList($nodeEdit) 1] == 0} {
+                    set fileList($nodeEdit) [list [lindex $fileList($nodeEdit) 0] 1]
+                    LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+                    $noteBook itemconfigure $nodeEdit -foreground $editor(nbModify)
+                }
+                ReplaceChar %W
+            };# if
+        };# if
+    };# bind
+    bind $text  {
+        if {$nodeEdit == ""} {return}
+        set textEdit "$noteBook.f$nodeEdit.text"
+        OpComplite $textEdit $fileExt $nodeEdit
+        if {[lindex $fileList($nodeEdit) 1] == 0} {
+            set fileList($nodeEdit) [list [lindex $fileList($nodeEdit) 0] 1]
+            LabelUpdate .frmStatus.frmProgress.lblProgress [::msgcat::mc "File modify"]
+            $noteBook itemconfigure $nodeEdit -foreground  $editor(nbModify)
+        }
+    }
+    # Alexander Dederer (aka Korwin)
+    # bind like VI editor
+    bind $text  {
+        set i -1
+        switch -- [%W get "insert - 1 chars"] {
+            \{ {set i [_searchCloseBracket %W \{ \} insert end]}
+            \[ {set i [_searchCloseBracket %W \[ \] insert end]}
+            (  {set i [_searchCloseBracket %W  (  ) insert end]}
+            \} {set i [_searchOpenBracket  %W \{ \} insert 1.0]}
+            \] {set i [_searchOpenBracket  %W \[ \] insert 1.0]}
+            )  {set i [_searchOpenBracket  %W  (  ) insert 1.0]}
+        } ;# switch
+        if { $i != -1 } {
+            %W mark set insert $i
+            %W see insert
+        }
+    } ;# bind
+    bindtags $text [list [winfo toplevel $text] $text Text sysAfter all]
+    bind sysAfter  {+ set i -1
+            catch {
+            switch -- [%W get "insert - 1 chars"] {
+                \{ {set i [_searchCloseBracket %W \{ \} insert end]}
+                \[ {set i [_searchCloseBracket %W \[ \] insert end]}
+                ( {set i [_searchCloseBracket %W (   ) insert end]}
+                \} {set i [_searchOpenBracket  %W \{ \} insert 1.0]}
+                \] {set i [_searchOpenBracket  %W \[ \] insert 1.0]}
+                ) {set i [_searchOpenBracket  %W  (  ) insert 1.0]}
+            } ;# switch
+            catch { %W tag remove lightBracket 1.0 end }
+            if { $i != -1 } {
+                %W tag add lightBracket "$i - 1 chars" $i
+            };#if
+        };#catch
+    } ;# bind sysAfter
+    
+    bind sysAfter  [bind sysAfter ]
+    focus -force $w.text
+    Position
+    .frmStatus.frmOvwrt.lblOvwrt configure -text [::msgcat::mc "Insert"] -font $fontNormal
+    bind $text  {OverWrite; break}
+    ## READ TEXT FOR HIGHLIGHTNING ##
+    set lineNum 1
+    while {$lineNum <=[expr $lineNumber + 1]} {
+        set line [$w.text get $lineNum.0 $lineNum.end]
+        HighLight $fileExt $w.text $line $lineNum $nodeEdit
+        incr lineNum
+    }
+}
+
+## GET KEYS CODE ##
+proc Key {key} {
+    if {$key >= 10 && $key <= 22} {return "true"}
+    if {$key >= 24 && $key <= 36} {return "true"}
+    if {$key >= 38 && $key <= 50} {return "true"}
+    if {$key >= 51 && $key <= 61 && $key != 58} {return "true"}
+    if {$key >= 79 && $key <= 91} {return "true"}
+    if {$key == 63 || $key == 107 || $key == 108 || $key == 112} {return "true"}
+}
+
+
+# "Alexander Dederer (aka Korwin)
+## Search close bracket in editor widget
+proc _searchCloseBracket { widget o_bracket c_bracket start_pos end_pos } {
+    set o_count 1
+    set c_count 0
+    set found 0
+    set pattern "\[\\$o_bracket\\$c_bracket\]"
+    set pos [$widget search -regexp -- $pattern $start_pos $end_pos]
+    while { ! [string equal $pos {}] } {
+        set char [$widget get $pos]
+        #tk_messageBox -title $pattern -message "char: $char; $pos; o_count=$o_count; c_count=$c_count"
+        if {[string equal $char $o_bracket]} {incr o_count ; set found 1}
+        if {[string equal $char $c_bracket]} {incr c_count ; set found 1}
+        if {($found == 1) && ($o_count == $c_count) } { return [$widget index "$pos + 1 chars"] }
+        set found 0
+        set start_pos "$pos + 1 chars"
+        set pos [$widget search -regexp -- $pattern $start_pos $end_pos]
+    } ;# while search
+    
+    return -1
+} ;# proc _searchCloseBracket
+
+# "Alexander Dederer (aka Korwin)
+## Search open bracket in editor widget
+proc _searchOpenBracket { widget o_bracket c_bracket start_pos end_pos } {
+    set o_count 0
+    set c_count 1
+    set found 0
+    set pattern "\[\\$o_bracket\\$c_bracket\]"
+    set pos [$widget search -backward -regexp -- $pattern "$start_pos - 1 chars" $end_pos]
+    while { ! [string equal $pos {}] } {
+        set char [$widget get $pos]
+        #tk_messageBox -title $pattern -message "char: $char; $pos; o_count=$o_count; c_count=$c_count"
+        if {[string equal $char $o_bracket]} {incr o_count ; set found 1}
+        if {[string equal $char $c_bracket]} {incr c_count ; set found 1}
+        if {($found == 1) && ($o_count == $c_count) } { return [$widget index "$pos + 1 chars"] }
+        set found 0
+        set start_pos "$pos - 0 chars"
+        set pos [$widget search -backward -regexp -- $pattern $start_pos $end_pos]
+    } ;# while search
+    return -1
+} ;# proc _searchOpenBracket
+
+proc SelectAll {text} {
+    global noteBook
+    
+    $text tag remove sel 1.0 end
+    $text tag add sel 1.0 end
+    
+}
+
+#################################### 
+GetOp
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/errors b/errors
new file mode 100644
index 0000000..e69de29
diff --git a/help.tcl b/help.tcl
new file mode 100644
index 0000000..3b6bdc9
--- /dev/null
+++ b/help.tcl
@@ -0,0 +1,362 @@
+##!/usr/bin/wish                                                                 
+
+###########################################################
+#                Tcl/Tk Project Manager                   #
+#                    version 0.0.1                        #
+#                    help module                          #
+# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru  #
+# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru       #
+###########################################################
+
+#package require BWidget                                                         
+#package require msgcat
+
+## GETTING TABLES OF CONTENT ##
+#set homeDir "$env(HOME)/projects/tcl/projman"
+#set docDir "$env(HOME)/projects/tcl/projman/hlp"
+#set imgDir "$env(HOME)/projects/tcl/projman/img"
+#set msgDir "$env(HOME)/projects/tcl/projman/msgs"
+
+#set workDir "$env(HOME)/.projman"
+
+#source $workDir/projman.conf
+source [file join $dataDir html_lib.tcl]
+#source [file join $dataDir htmllib.tcl]
+
+set sourceEncode "koi8-r"
+
+## LOAD MESSAGES FILE? LANGUAGE AND NEDDED FILES ##
+#source $homeDir/html.tcl
+
+#::msgcat::mclocale $locale
+#::msgcat::mcload $msgDir
+proc HlpTreeOneClick {node} {
+    global fontNormal hlpTree wordList hlpNoteBook findString imgDir fontBold fontNormal
+    global lstSearch nodeParent
+    $hlpTree selection set $node
+    set nodeParent [$hlpTree parent $node]
+    set item [$hlpTree itemcget $node -data]
+    set file [string range $item 4 end]
+    #puts "$file" ;#debuf info
+    if {[string range $item 0 2] == "toc"} {
+        #        $hlpTree configure
+    }
+    if {[$hlpTree itemcget $node -open] == 1} {
+        $hlpTree itemconfigure $node -open 0
+    } elseif {[$hlpTree itemcget $node -open] == 0} {
+        $hlpTree itemconfigure $node -open 1
+    }
+    if {[string range $item 0 2] == "doc"} {
+        GetContent $file
+    }
+}
+## GETTING TABLE OF CONTENT ##
+proc GetTOC {} {
+    global docDir hlpTree imgDir fontNormal lstSearch arr sourceEncode
+    if {[catch {cd $docDir}] != 0} {
+        return ""
+    }
+    foreach dir [lsort [glob -nocomplain *]] {
+        if {[file isdirectory $dir] == 1} {
+            foreach file [lsort [glob -nocomplain [file join $dir *toc.html]]] {
+                #puts $file
+                set fileName [file join $file]
+                set tocFile [open $fileName r]
+                fconfigure $tocFile -encoding binary
+                set dot "_"
+                #set nodeParent [string range $fileName 0 [expr [string first "." $fileName]-1]]
+                #puts $fileName
+                set nodeParent [file dirname $fileName]
+                while {[gets $tocFile line]>=0} {
+                    set a ""
+                    set b ""
+                    set line [encoding convertfrom $sourceEncode $line]
+                    if {[regexp -nocase ".+\" $line a]} {
+                        if {[regexp ">.+\<" $line a]} {
+                            set length [string length $a]
+                            set title [string range $a 1 [expr $length-2]]
+                            #puts $nodeParent ;# debug info
+                            $hlpTree insert end root $nodeParent -text "$title" -font $fontNormal \
+                                    -data "toc_$nodeParent" -open 0\
+                                    -image [Bitmap::get [file join $imgDir books.gif]]
+                        }
+                    } elseif {[regexp "\".+\"" $line a]} {
+                        set data [string range $a 1 [expr [string last "\"" $a]-1]]
+                        if {[regexp ">.+\<" $line b]} {
+                            set line [string range $b 1 [expr [string first "<" $b]-1]]
+                            regsub -all {[ :]} $line "_" subNode
+                            #regsub -all ":" $ubNode "_" node
+                            set subNode "$nodeParent$dot$subNode"
+                            if {[info exists arr($subNode)] == 0} {
+                                set arr($subNode) [file join $dir $data]
+                            }
+                            set data [file join $dir $data]
+                            #puts "$subNode" ;# debug info
+                            $hlpTree insert end "$nodeParent" $subNode -text "$line"\
+                            -font $fontNormal -data "doc_$data" -open 0\
+                            -image [Bitmap::get [file join $imgDir file.gif]]
+                            $lstSearch insert end $line
+                        }        
+                    } else {
+                        break
+                    }
+                }
+                
+            } ;# foreach
+        }
+    }
+    $hlpTree configure -redraw 1
+}
+proc SearchWord {word} {
+    global arr nBookTree
+    set word [string tolower [string trim $word]]
+    puts $word
+    $nBookTree raise hlpSearch
+    InsertEnt .help.frmBody.frmCat.nBookTree.fhlpSearch.frmScrhEnt.entSearch $word
+    foreach wrd [array names arr] {
+        set name "[file rootname [file tail $arr($wrd)]]"
+        set file "$arr($wrd)"
+        if {[string match "$word*" [string tolower $name]] == 1} {
+            GetContent $file
+        }
+    }
+}
+## GETTING CONTENT FROM FILES ##
+proc GetContent {file} {
+    global docDir hlpNoteBook fontNormal sourceEncode
+    $hlpNoteBook raise [$hlpNoteBook page 0]
+    set node [$hlpNoteBook raise]
+    if {$node != ""} {
+        $hlpNoteBook delete hlpHTML
+    }
+    set nbTitle ""
+    set html ""
+    set file [open $file r]
+    fconfigure $file -encoding binary
+    while {[gets $file line]>=0} {
+#        if {$line == ""} {
+#            set html "

Файл $file не содержит данных

" +# } + set line [encoding convertfrom $sourceEncode $line] + if {[regexp -nocase ".+\" $line a]} { + if {[regexp ">.+\<" $a a]} { + set length [string length $a] + set nbTitle [string range $a 1 [expr $length-2]] + #puts $nbTitle + #puts $a + } + } + append html $line\n + } + set frmHTML [$hlpNoteBook insert end hlpHTML -text $nbTitle] + set txt [text $frmHTML.txtHTML -yscrollcommand "$frmHTML.yscroll set" \ + -relief sunken -wrap word -highlightthickness 0 -font $fontNormal\ + -selectborderwidth 0 -selectbackground #55c4d1 -width 10] + scrollbar $frmHTML.yscroll -relief sunken -borderwidth {1} -width {10} -takefocus 0\ + -command "$frmHTML.txtHTML yview" + + pack $txt -side left -fill both -expand true + pack $frmHTML.yscroll -side left -fill y + $hlpNoteBook raise hlpHTML + focus -force $txt +# $txt configure -state disabled + HM::init_win $txt + HM::set_link_callback LinkCallback + HM::set_state $txt -size 0 + HM::set_indent $txt 1.2 + HM::parse_html $html "HM::render $txt" +# HM::tag_title .help "Help - $nbTitle" + $txt configure -state disabled + +} +## GOTO URL PROCEDURE ## +proc LinkCallback {w url} { + global docDir nodeParent + set url "[file join $docDir $nodeParent $url]" + if {[catch {open $url r} oHTML]} { + tk_messageBox -title "[::msgcat::mc "Error open URL"]"\ + -message "[::msgcat::mc "Can't found file:"] $url"\ + -icon error -type ok + } else { + GetContent $url + } +} + + +## autor DEDERER ## +proc LinkCallback_ {w url} { + global docDir + set url "[file join $docDir $url]" + if {[catch {open $url r} oHTML]} { + tk_messageBox -title "[::msgcat::mc "Error open URL"]"\ + -message "[::msgcat::mc "Can't founf file: $url"]"\ + -icon error -type ok + } else { + set html [read $oHTML] + $w configure -state normal + HM::reset_win $w + HM::parse_html $html "HM::render $w" + $w configure -state disable + } +# HM::render [winfo toplevel $w] $url +} + +## MAIN HELP WINDOW ## +proc TopLevelHelp {} { + global fontNormal fontBold hlpTree hlpNoteBook nBookTree homeDir docDir lstSearch w frmSrchList + global imgDir + set w .help + set w_exist [winfo exists $w] + if !$w_exist { + toplevel $w + # wm resizable .help 0 0 + wm geometry $w 900x800+0+0 + wm title $w [::msgcat::mc "Help"] + # wm protocol $w WM_DELETE_WINDOW {destroy .msg .help} + #wm geometry . 600x400+0+0 + wm title $w [::msgcat::mc "Help"] + + frame $w.frmMenu -border 1 -relief raised + frame $w.frmTool -border 1 -relief raised + frame $w.frmBody -border 1 -relief raised + frame $w.frmStatus -border 1 -relief sunken + pack $w.frmMenu -side top -padx 1 -fill x + pack $w.frmTool -side top -padx 1 -fill x + pack $w.frmBody -side top -padx 1 -fill both -expand true + pack $w.frmStatus -side top -padx 1 -fill x + + + button $w.frmTool.btnBack -relief groove -font $fontBold -command Back -state disable + button $w.frmTool.btnForward -relief groove -font $fontBold -command Forward -state disable + button $w.frmTool.btnRefresh -relief groove -font $fontBold -command Refresh -state disable + button $w.frmTool.btnPrint -relief groove -font $fontBold -command Print -state disable + image create photo imgBack -format gif -file [file join $imgDir back.gif] + image create photo imgForward -format gif -file [file join $imgDir forward.gif] + image create photo imgRefresh -format gif -file [file join $imgDir refresh.gif] + image create photo imgPrint -format png -file [file join $imgDir printer.png] + $w.frmTool.btnBack configure -image imgBack + $w.frmTool.btnForward configure -image imgForward + $w.frmTool.btnRefresh configure -image imgRefresh + $w.frmTool.btnPrint configure -image imgPrint + pack $w.frmTool.btnBack $w.frmTool.btnForward $w.frmTool.btnRefresh $w.frmTool.btnPrint\ + -side left -fill x + + + set frmCat [frame $w.frmBody.frmCat -border 1 -relief sunken] + pack $frmCat -side left -fill y + set frmWork [frame $w.frmBody.frmWork -border 1 -relief sunken] + pack $frmWork -side left -fill both -expand true + + set nBookTree [NoteBook $frmCat.nBookTree -font $fontNormal] + pack $nBookTree -fill both -expand true -padx 2 -pady 2 + set frmTreeNb [$nBookTree insert end hlpTree -text "[::msgcat::mc "Contents"]"] + set frmSearch [$nBookTree insert end hlpSearch -text "[::msgcat::mc "Search"]"] + $nBookTree raise hlpTree + + set frmScrlX [frame $frmTreeNb.frmScrlX -border 0 -relief sunken] + set frmTree [frame $frmTreeNb.frmTree -border 1 -relief sunken] + set hlpTree [Tree $frmTree.tree \ + -relief sunken -borderwidth 1 -width 20 -highlightthickness 0\ + -redraw 0 -dropenabled 1 -dragenabled 1 -dragevent 3 \ + -yscrollcommand {.help.frmBody.frmCat.nBookTree.fhlpTree.frmTree.scrlY set} \ + -xscrollcommand {.help.frmBody.frmCat.nBookTree.fhlpTree.frmScrlX.scrlX set} \ + -background "#d3d3d3" -selectbackground "#55c4d1" \ + -droptypes { + TREE_NODE {copy {} move {} link {}} + LISTBOX_ITEM {copy {} move {} link {}} + } -opencmd "" -closecmd ""] + + pack $frmTree -side top -fill y -expand true + pack $frmScrlX -side top -fill x + + scrollbar $frmTree.scrlY -command {$hlpTree yview} \ + -borderwidth {1} -width {10} -takefocus 0 + pack $hlpTree $frmTree.scrlY -side left -fill y + + scrollbar $frmScrlX.scrlX -command {$hlpTree xview} \ + -orient horizontal -borderwidth {1} -width {10} -takefocus 0 + pack $frmScrlX.scrlX -fill x -expand true + + set frmSrchList [frame $frmSearch.frmScrhList -border 0 -relief sunken] + set frmSrchEnt [frame $frmSearch.frmScrhEnt -border 0 -relief sunken] + set frmSrchScrollX [frame $frmSearch.frmScrhScrollX -border 0 -relief sunken] + pack $frmSrchEnt -side top -fill x + pack $frmSrchList -side top -fill both -expand true + pack $frmSrchScrollX -side top -fill x + + entry $frmSrchEnt.entSearch + set lstSearch [listbox $frmSrchList.lstSearch -font $fontNormal\ + -yscrollcommand\ + {.help.frmBody.frmCat.nBookTree.fhlpSearch.frmScrhList.scrListY set}\ + -xscrollcommand\ + {.help.frmBody.frmCat.nBookTree.fhlpSearch.frmScrhScrollX.scrListX set}\ + -selectmode single -selectbackground #55c4d1\ + -selectborderwidth 0] + scrollbar $frmSrchList.scrListY -command\ + {$frmSrchList.lstSearch yview} -borderwidth {1} -width {10} -takefocus 0 + + pack $frmSrchEnt.entSearch -side top -fill x -expand true + + pack $frmSrchList.lstSearch -side left -fill both -expand true + pack $frmSrchList.scrListY -side left -fill y + + scrollbar $frmSrchScrollX.scrListX -orient horizontal -command\ + {$frmSrchList.lstSearch xview} -borderwidth {1} -width {10} -takefocus 0 + pack $frmSrchScrollX.scrListX -fill x +# $hlpTree bindText [puts %k] +# $hlpTree bindText [puts %k] +# bind $frmTree {$frmSrchList.lstSearch xview} + # $hlpTree bindText "HlpTreeDoubleClick [$hlpTree selection get]" + # $hlpTree bindImage "HlpTreeDoubleClick [$hlpTree selection get]" + $hlpTree bindText "HlpTreeOneClick [$hlpTree selection get]" + $hlpTree bindImage "HlpTreeOneClick [$hlpTree selection get]" + bind .help "destroy .help" + +# bind $frmSrchEnt.entSearch \ +# {SearchWord [Text .help.frmBody.frmCat.nBookTree.fhlpSearch.frmScrhEnt.entSearch]} + + #bind $w exit + #bind $frmTree {TreeClick [$hlpTree selection get]} + #bind $frmTree {TreeClick [$hlpTree selection get]} + #bind $frmTree {TreeClick [$hlpTree selection get]} + bind $frmTree.tree.c "$hlpTree yview scroll -3 units" + bind $frmTree.tree.c "$hlpTree yview scroll 3 units" + bind $frmTree.tree.c "$hlpTree xview scroll -2 units" + bind $frmTree.tree.c "$hlpTree xview scroll 2 units" + + set hlpNoteBook [NoteBook $frmWork.hlpNoteBook -font $fontNormal] + pack $hlpNoteBook -fill both -expand true -padx 2 -pady 2 + GetTOC + } + +} + +################################################## +#TopLevelHelp +#GetTOC + +#GetContent $docDir/tcl.toc.html + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/highlight/caml.tcl b/highlight/caml.tcl new file mode 100644 index 0000000..8f62e0a --- /dev/null +++ b/highlight/caml.tcl @@ -0,0 +1,219 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" + +proc HighLightML {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure className -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + + set keyWord [info commands] + # for OOP extention + foreach n {let match compile load exception function bol begin end then type done with class method attribute constructor destructor invariant attribute binding new delete extends final finally implements import interface native new private protected public static super this throw synchronized throws transient try volatile void else} {lappend keyWord $n} + set dataType {list abstract boolean byte char double float int long short} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string trim $word]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="let" || [string trim $word]=="extends" || [string trim $word]=="implements"} { + $text tag add className $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + ## COMENTS ## + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices {(^|\t|;| )\(\*} $workLine begin]} { + set p [lindex $begin 0] + $text tag add comments $lineNumber.[expr $p - 0] $lineNumber.end + } elseif {[regexp -indices {(^|\t|;| )\*} $workLine beginIndex]} { + set beginQuote "$lineNumber.[lindex $beginIndex 0]" + set endQuote [$text search -forward -regexp -- {\*\)} $beginQuote end] + if {$endQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 2 chars" + } else { + $text tag add comments $beginQuote end + } + set endQuotePrev [$text search -backward -regexp -- {\*\)} [expr $lineNumber - 1].end 0.0] + if {$endQuotePrev != ""} { + $text tag remove comments "$endQuotePrev + 2 chars" $beginQuote + } + } elseif {[regexp -indices {\*\)} $workLine endIndex]} { + set endQuote "$lineNumber.[lindex $endIndex 1]" + set beginQuote [$text search -backward -regexp -- {\(\*} $endQuote 0.0] + if {$beginQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 1 chars" + } else { + $text tag add comments 0.0 "$endQuote + 1 chars" + } + set beginQuoteNext [$text search -forward -regexp -- {\(\*} $endQuote end] + if {$beginQuoteNext != ""} { + $text tag remove comments "$endQuote + 2 chars" $beginQuoteNext + } + } else { + if {[lindex [split $beginQuote "."] 0] <= $lineNumber && [lindex [split $endQuote "."] 0] >= $lineNumber} { + #$text tag add comments $lineNumber.0 $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + } + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + + + + + diff --git a/highlight/erlang.tcl b/highlight/erlang.tcl new file mode 100644 index 0000000..e233151 --- /dev/null +++ b/highlight/erlang.tcl @@ -0,0 +1,220 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" + +proc HighLightErl {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure className -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + + set keyWord [info commands] + # for OOP extention + foreach n {let match compile load exception function bol begin end then type done with class method attribute constructor destructor invariant attribute binding new delete extends final finally implements import interface native new private protected public static super this throw synchronized throws transient try volatile void else} {lappend keyWord $n} + set dataType {list abstract boolean byte char double float int long short} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string trim $word]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="let" || [string trim $word]=="extends" || [string trim $word]=="implements"} { + $text tag add className $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + ## COMENTS ## + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices {(^|\t|;| )\(\*} $workLine begin]} { + set p [lindex $begin 0] + $text tag add comments $lineNumber.[expr $p - 0] $lineNumber.end + } elseif {[regexp -indices {(^|\t|;| )\*} $workLine beginIndex]} { + set beginQuote "$lineNumber.[lindex $beginIndex 0]" + set endQuote [$text search -forward -regexp -- {\*\)} $beginQuote end] + if {$endQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 2 chars" + } else { + $text tag add comments $beginQuote end + } + set endQuotePrev [$text search -backward -regexp -- {\*\)} [expr $lineNumber - 1].end 0.0] + if {$endQuotePrev != ""} { + $text tag remove comments "$endQuotePrev + 2 chars" $beginQuote + } + } elseif {[regexp -indices {\*\)} $workLine endIndex]} { + set endQuote "$lineNumber.[lindex $endIndex 1]" + set beginQuote [$text search -backward -regexp -- {\(\*} $endQuote 0.0] + if {$beginQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 1 chars" + } else { + $text tag add comments 0.0 "$endQuote + 1 chars" + } + set beginQuoteNext [$text search -forward -regexp -- {\(\*} $endQuote end] + if {$beginQuoteNext != ""} { + $text tag remove comments "$endQuote + 2 chars" $beginQuoteNext + } + } else { + if {[lindex [split $beginQuote "."] 0] <= $lineNumber && [lindex [split $endQuote "."] 0] >= $lineNumber} { + #$text tag add comments $lineNumber.0 $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + } + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + + + + + + diff --git a/highlight/fortran.tcl b/highlight/fortran.tcl new file mode 100644 index 0000000..8042558 --- /dev/null +++ b/highlight/fortran.tcl @@ -0,0 +1,214 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" + +proc HighLightFORTRAN {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure className -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) ;#-background $editor(bg) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + + $text tag configure label -background $color(label) + $text tag configure six -foreground $color(sixFG) -background $color(sixBG) + $text tag configure operator -background $editor(bg) + + set keyWord [info commands] + # for OOP extention + foreach n {program function subroutine entry block data implicit integer real double precision complex\ + logical character dimension common equivalence parameter external intrinsic save data goto assign if then\ + else elseif endif end do while enddo continue stop pause end open close read write print\ + inquire rewind backspace endfile format call return include} {lappend keyWord $n} + #set dataType {list abstract boolean byte char double float int long short} + set dataType "" + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="class" || [string trim $word]=="extends" || [string trim $word]=="implements"} { + $text tag add className $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b] || [regexp "\'.*?\'" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + $text tag remove label $lineNumber.0 $lineNumber.end + $text tag add label $lineNumber.0 $lineNumber.5 + $text tag remove six $lineNumber.0 $lineNumber.5 + $text tag remove six $lineNumber.6 $lineNumber.end + $text tag add six $lineNumber.5 $lineNumber.6 + $text tag remove operator $lineNumber.6 $lineNumber.end + $text tag add operator $lineNumber.7 $lineNumber.71 + $text tag remove comments $lineNumber.72 $lineNumber.end + $text tag add comments $lineNumber.72 $lineNumber.end + ## COMENTS ## + set workLine [$text get $lineNumber.0 $lineNumber.end] + #if {[regexp -indices -nocase {^(c|\*)} $workLine word]} + if {[regexp -indices -nocase {^(c|\*)} $workLine word]} { + set p [lindex $word 1] + #puts "$p $lineNumber -- $workLine" + $text tag remove label $lineNumber.0 $lineNumber.end + $text tag remove operator $lineNumber.0 $lineNumber.end + $text tag add comments $lineNumber.$p $lineNumber.end + $text tag remove six $lineNumber.5 $lineNumber.6 + #puts [$text dump -tag $lineNumber.0 $lineNumber.end] + #$text tag raise comments + #puts [$text tag ranges comments] + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices -nocase {\!} $workLine word]} { + set p [lindex $word 1] + if {([string index $workLine [expr $p + 1]] == "\'") || ([string index $workLine [expr $p + 1]] == "\"")} { + } else { + #$text tag add comments $lineNumber.$p $lineNumber.end + } + } else { + #$text tag remove comments $lineNumber.0 $lineNumber.end + } + + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + diff --git a/highlight/html.tcl b/highlight/html.tcl new file mode 100644 index 0000000..b0384fa --- /dev/null +++ b/highlight/html.tcl @@ -0,0 +1,106 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightHTML {text line lineNumber node} { + global fontNormal editorFontBold tree imgDir fontBold + global editor color + set startIndex 0 + # bind text tags for highlightning # + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) +# incr lineNumber + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete} { + lappend keyWord $n + } + # add comment # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<\!--.+-->" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add coments $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # get keywords + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "( \t\])|>" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add keyWord $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # get variables + set workLine $line + set startPos 0 + while {$workLine != ""} { + if {[regexp "\[a-zA-Z0-9\]+=" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add variable $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # get strings + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".+\"" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + +} + + + + + + diff --git a/highlight/java.tcl b/highlight/java.tcl new file mode 100644 index 0000000..7c4e088 --- /dev/null +++ b/highlight/java.tcl @@ -0,0 +1,215 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" +proc HighLightJAVA {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure className -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete extends final finally implements import interface native new private protected public static super this throw synchronized throws transient try volatile void else} {lappend keyWord $n} + set dataType {list abstract boolean byte char double float int long short} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string trim $word]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.$endPos + } + + if {[string trim $word]=="class" || [string trim $word]=="extends" || [string trim $word]=="implements"} { + $text tag add className $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + ## COMENTS ## + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )//" $workLine begin]} { + set p [lindex $begin 0] + $text tag add comments $lineNumber.[expr $p - 0] $lineNumber.end + } elseif {[regexp -indices {(^|\t|;| )/\*} $workLine beginIndex]} { + set beginQuote "$lineNumber.[lindex $beginIndex 0]" + set endQuote [$text search -forward -regexp -- {\*/} $beginQuote end] + if {$endQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 2 chars" + } else { + $text tag add comments $beginQuote end + } + set endQuotePrev [$text search -backward -regexp -- {\*/} [expr $lineNumber - 1].end 0.0] + if {$endQuotePrev != ""} { + $text tag remove comments "$endQuotePrev + 2 chars" $beginQuote + } + } elseif {[regexp -indices {\*/} $workLine endIndex]} { + set endQuote "$lineNumber.[lindex $endIndex 1]" + set beginQuote [$text search -backward -regexp -- {/\*} $endQuote 0.0] + if {$beginQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 1 chars" + } else { + $text tag add comments 0.0 "$endQuote + 1 chars" + } + set beginQuoteNext [$text search -forward -regexp -- {/\*} $endQuote end] + if {$beginQuoteNext != ""} { + $text tag remove comments "$endQuote + 2 chars" $beginQuoteNext + } + } else { + if {[lindex [split $beginQuote "."] 0] <= $lineNumber && [lindex [split $endQuote "."] 0] >= $lineNumber} { + #$text tag add comments $lineNumber.0 $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + } + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + diff --git a/highlight/perl.tcl b/highlight/perl.tcl new file mode 100644 index 0000000..c464044 --- /dev/null +++ b/highlight/perl.tcl @@ -0,0 +1,204 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" +proc HighLightPERL {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure className -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + + set keyWord [info commands] + # for OOP extention + foreach n {print my use sub printf substr ord class method attribute constructor destructor invariant attribute binding new delete extends final finally implements import interface native new private protected public static super this throw synchronized throws transient try volatile void else } {lappend keyWord $n} + set dataType {list abstract boolean byte char double float int long short} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string trim $word]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="class" || [string trim $word]=="extends" || [string trim $word]=="implements" || [string trim $word]=="use"} { + $text tag add className $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\@\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b] || [regexp "\'.*?\'" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b] || [regexp "(\-\>)" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + ## COMENTS ## + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )#" $workLine word]} { + set p [lindex $word 1] + $text tag add comments $lineNumber.$p $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + diff --git a/highlight/php.tcl b/highlight/php.tcl new file mode 100644 index 0000000..3f04525 --- /dev/null +++ b/highlight/php.tcl @@ -0,0 +1,270 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightPHP {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + # set pos [$text index insert] + # set lineNumber [lindex [split $pos "."] 0] + + set startIndex 0 + # bind text tags for highlightning # + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure rivet -foreground $color(bindKey) -font $editor(fontBold) -foreground "#ff8800" ;#-background "#c6c6c6" + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + # incr lineNumber + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete \ + mcset mc mclocale mcpreferences mcload mcunknown configure match else elseif} { + lappend keyWord $n + } + foreach n {var include_once include function case echo select from where in order by and or} { + lappend keyWord $n + } + set dataType {true false} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string trim $word]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + set workLine $line + while {$workLine != ""} { + if {[regexp {(\{|\[)[a-zA-Z\\_:]+} $workLine word v]} { + set word [string trim $word $v] + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "( \t\])|>" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add keyWord $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # DEDERER + # hightlight [, {, }, ] + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\<\?|\?>} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add rivet $lineNumber.$start $lineNumber.end + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add coments $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # add comment # + + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )//" $workLine begin]} { + set p [lindex $begin 0] + $text tag add comments $lineNumber.[expr $p - 0] $lineNumber.end + } elseif {[regexp -indices {(^|\t|;| )/\*} $workLine beginIndex]} { + set beginQuote "$lineNumber.[lindex $beginIndex 0]" + set endQuote [$text search -forward -regexp -- {\*/} $beginQuote end] + if {$endQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 2 chars" + } else { + $text tag add comments $beginQuote end + } + set endQuotePrev [$text search -backward -regexp -- {\*/} [expr $lineNumber - 1].end 0.0] + if {$endQuotePrev != ""} { + $text tag remove comments "$endQuotePrev + 2 chars" $beginQuote + } + } elseif {[regexp -indices {\*/} $workLine endIndex]} { + set endQuote "$lineNumber.[lindex $endIndex 1]" + set beginQuote [$text search -backward -regexp -- {/\*} $endQuote 0.0] + if {$beginQuote != ""} { + $text tag add comments $beginQuote "$endQuote + 1 chars" + } else { + $text tag add comments 0.0 "$endQuote + 1 chars" + } + set beginQuoteNext [$text search -forward -regexp -- {/\*} $endQuote end] + if {$beginQuoteNext != ""} { + $text tag remove comments "$endQuote + 2 chars" $beginQuoteNext + } + } else { + if {[lindex [split $beginQuote "."] 0] <= $lineNumber && [lindex [split $endQuote "."] 0] >= $lineNumber} { + #$text tag add comments $lineNumber.0 $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + } +} + + + + + diff --git a/highlight/rivet.tcl b/highlight/rivet.tcl new file mode 100644 index 0000000..5f28dec --- /dev/null +++ b/highlight/rivet.tcl @@ -0,0 +1,249 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightRIVET {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + # set pos [$text index insert] + # set lineNumber [lindex [split $pos "."] 0] + + set startIndex 0 + # bind text tags for highlightning # + $text tag configure bold -font $editor(fontBold) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure rivet -foreground $color(bindKey) -font $editor(fontBold) -foreground "#ff8800" ;#-background "#c6c6c6" + # incr lineNumber + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete \ + mcset mc mclocale mcpreferences mcload mcunknown configure match else elseif} { + lappend keyWord $n + } + set dataType {true false} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $sqlOperators [string tolower [string trim $word]]] != -1} { + $text tag add sql $lineNumber.$startPos $lineNumber.[expr $endPos - 1] + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + set workLine $line + while {$workLine != ""} { + if {[regexp {(\{|\[)[a-zA-Z\\_:]+} $workLine word v]} { + set word [string trim $word $v] + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "( \t\])|>" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add keyWord $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b] || [regexp "\'.*?\'" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # add comment # + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )#" $workLine word]} { + set p [lindex $word 1] + $text tag add comments $lineNumber.$p $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + # DEDERER + # hightlight [, {, }, ] + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\<\?|\?>} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add rivet $lineNumber.$start $lineNumber.end + set startPos $end + } else { + break + } + } + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add coments $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + +} + + + + + + + + + + + + + + + + diff --git a/highlight/ruby.tcl b/highlight/ruby.tcl new file mode 100644 index 0000000..4958d0b --- /dev/null +++ b/highlight/ruby.tcl @@ -0,0 +1,189 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +set beginQuote "0.0" +set endQuote "2.0" +set endQuotePrev "0.0" +proc HighLightRUBY {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + global beginQuote endQuote endQuotePrev + set startIndex 0 + + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure sql -font $editor(fontBold) -foreground $color(sql) + + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete extends final finally implements import interface native new private protected public static super this throw synchronized throws transient try volatile void else def end slots require} {lappend keyWord $n} + set dataType {list abstract boolean byte char double float int long short} + set sqlOperators {select from where and or count sum in order cast as by} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + set className "" + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="class"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + puts "$text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]]" + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\@\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + # if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + ## COMENTS ## + # add comment # + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )#" $workLine word]} { + set p [lindex $word 1] + $text tag add comments $lineNumber.$p $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + + # DEDERER + # hightlight [, {, }, ], ( , ) + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|{|}|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bold $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + + + + + diff --git a/highlight/spec.tcl b/highlight/spec.tcl new file mode 100644 index 0000000..8510220 --- /dev/null +++ b/highlight/spec.tcl @@ -0,0 +1,136 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# SPEC highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightSPEC {text line lineNumber node} { + global fontNormal editorFontBold fontBold tree imgDir noteBook + global editor color +# set pos [$text index insert] +# set lineNumber [lindex [split $pos "."] 0] + + set startIndex 0 + # bind text tags for highlightning # +# foreach tag {bold procName comments string number variable} { +# $text tag remove $tag $lineNumber.0 $lineNumber.end +# } + + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) +# $text tag configure bold -font $fontBold +# $text tag configure procName -font $editorFontBold -foreground blue +# $text tag configure keyWord -foreground #0000a8 +# $text tag configure comments -foreground #9b9b9b +# $text tag configure variable -foreground #e50000 +# $text tag configure string -foreground #168400 +# $text tag configure braceHighLight -font $editorFontBold -foreground green -background black +# $text tag configure brace -foreground brown +# $text tag configure percent -foreground #a500c6 + + foreach n {define name version release description prep setup build install post postun clean files defattr changelog doc} { + lappend keyWord $n + } + # add comment # + if {[string range [string trim $line] 0 0] == "#"} { + $text tag add comments $lineNumber.0 $lineNumber.end + return 0 + } + + set a "" + regexp "^( |\t|\%)*(\[a-z\]|\[A-Z\]|\[0-9\]|_|:|~|\\.|/)+" $line a + if {$a != ""} { + # gets name + set b "" + regexp "^( |\t|\%)*" $line b + set nameStart [string length $b] + set nameEnd [string length $a] + set name [string range $a [string length $b] end] + # is it keyword? + if {[lsearch $keyWord $name] != -1} { + incr nameStart $startIndex + incr nameEnd $startIndex + $text tag add keyWord $lineNumber.$nameStart $lineNumber.$nameEnd + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string { } highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\{.*?\}" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { +# if {[regexp "\%.*? " $workLine a b]} + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + #find [ +# set i [string first "\[" $line] +# if {$i != -1} { +# incr i +# set line [string range $line $i end] +# incr i $startIndex +# set l [HighLight $text $line $i $node] +# eval lappend res $l +# } + +# return $res + +} + + + diff --git a/highlight/tcl.tcl b/highlight/tcl.tcl new file mode 100644 index 0000000..aebda82 --- /dev/null +++ b/highlight/tcl.tcl @@ -0,0 +1,227 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightTCL {text line lineNumber node} { + global fontNormal fontBold editorFontBold tree imgDir noteBook + global editor color + # set pos [$text index insert] + # set lineNumber [lindex [split $pos "."] 0] + + set startIndex 0 + # bind text tags for highlightning # + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure braceHighLight -font $editor(fontBold)\ + -foreground $color(braceBG) -background $color(braceFG) + $text tag configure brace -foreground $color(brace) + $text tag configure bracequad -foreground $color(bracequad) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + + # incr lineNumber + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete \ + mcset mc mclocale mcpreferences mcload mcunknown configure match else elseif} { + lappend keyWord $n + } + set dataType {true false} + set a "" + set startPos 0 + set endPos 0 + set length 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "(^|\t| )\[a-zA-Z\\_:\]+" $workLine word]} { + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[lsearch $dataType [string trim $word]] != -1} { + $text tag add bold $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + set workLine $line + while {$workLine != ""} { + if {[regexp {(\{|\[)[a-zA-Z\\_:]+} $workLine word v]} { + set word [string trim $word $v] + set length [string length $word] + set startPos [string first [string trim $word] $line] + set endPos [expr $startPos + $length] + set workLine [string range $workLine $length end] + if {[lsearch $keyWord [string trim $word]] != -1} { + $text tag add keyWord $lineNumber.$startPos $lineNumber.$endPos + } + if {[string trim $word]=="proc"} { + $text tag add procName $lineNumber.[expr $startPos + $length] $lineNumber.[string wordend $line [expr $startPos + $length +2]] + } + set startPos [expr $endPos + 1] + } else { + break + } + } + + # key binding highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "<.*?>" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # variable highlight # + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\\$\[a-zA-Z\\_:\]+" $workLine a]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + if {$a != ""} { + $text tag add variable $lineNumber.$start $lineNumber.$end + } + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # persent % highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\%" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add percent $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\{|\}" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add brace $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + + # add comment # + set workLine [$text get $lineNumber.0 $lineNumber.end] + if {[regexp -indices "(^|\t|;| )#" $workLine word]} { + set p [lindex $word 1] + $text tag add comments $lineNumber.$p $lineNumber.end + } else { + $text tag remove comments $lineNumber.0 $lineNumber.end + } + # DEDERER + # hightlight [, {, }, ] + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\(|\[|\]|\)} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bracequad $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # parameter for command hightlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp -- {\s-\w+(?=\s)} $workLine a b]} { + set start [expr [string first $a $workLine] + 1] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add bindKey $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } +} + + + + + + + + + + + + + + diff --git a/highlight/tex.tcl b/highlight/tex.tcl new file mode 100644 index 0000000..7434781 --- /dev/null +++ b/highlight/tex.tcl @@ -0,0 +1,114 @@ +########################################################### +# Tcl/Tk Project Manager # +# version 0.0.1 # +# TCL highlight file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +proc HighLightTEX {text line lineNumber node} { + global tree color noteBook + global editor + $text tag configure bold -font $editor(fontBold) + $text tag configure procName -font $editor(fontBold) -foreground $color(procName) + $text tag configure param -foreground $color(param) + $text tag configure subParam -foreground $color(subParam) + + $text tag configure keyWord -foreground $color(keyWord) + $text tag configure comments -foreground $color(comments) + $text tag configure variable -foreground $color(var) + $text tag configure string -foreground $color(string) + $text tag configure brace -foreground $color(brace) + $text tag configure percent -foreground $color(percent) + $text tag configure bindKey -foreground $color(bindKey) + $text tag configure lightBracket -background $color(braceBG) -foreground $color(braceFG) + + set startIndex 0 + set keyWord [info commands] + # for OOP extention + foreach n {class method attribute constructor destructor invariant attribute binding new delete} { + lappend keyWord $n + } + set startPos 0 + set workLine $line + regexp -nocase -all -- {(\\)([a-zA-Z])*} string match v1 v2 + while {$workLine != ""} { + if {[regexp -nocase -all {(\\)([a-zA-Z])*} $workLine a b c]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add keyWord $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # string " " highlight + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp "\".*?\"" $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start $startPos + incr end $startPos + $text tag add string $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\{.*?\}} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start [expr $startPos +1] + incr end [expr $startPos - 1] + $text tag add param $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + set startPos 0 + set workLine $line + while {$workLine != ""} { + if {[regexp {\[.*?\]} $workLine a b]} { + set start [string first $a $workLine] + set end $start + incr end [string length $a] + set workLine [string range $workLine $end end] + incr start [expr $startPos + 1] + incr end [expr $startPos - 1] + $text tag add subParam $lineNumber.$start $lineNumber.$end + set startPos $end + } else { + break + } + } + # add comment # + if [regexp -nocase -all -indices -- {%} $line pos] { + set cur [lindex $pos 1] + $text tag add comments $lineNumber.$cur $lineNumber.end + return 0 + } +} + + + + + + + + + + diff --git a/hlp/ab.htm b/hlp/ab.htm new file mode 100644 index 0000000..a1e3b46 --- /dev/null +++ b/hlp/ab.htm @@ -0,0 +1,16 @@ + + + + about + + +

Документация

+

Документация предоставлена компанией +DataX/FLORIN, Inc. +

© Все права защищены 1992-2001. +

Разрешается не коммерческое использование документации как целиком так и отдельных частей с разрешения авторов и с обязательной ссылкой на +DataX/FLORIN, Inc. и на +CONERO lab + + + diff --git a/hlp/en/bwidget/ArrowButton.html b/hlp/en/bwidget/ArrowButton.html new file mode 100644 index 0000000..3969d3d --- /dev/null +++ b/hlp/en/bwidget/ArrowButton.html @@ -0,0 +1,276 @@ + +ArrowButton + +

NAME
+
ArrowButton + - Button widget with an arrow shape. +
+
+
CREATION
+
ArrowButton pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -activebackground
  -activeforeground
  -background or -bg  -borderwidth or -bd
  -disabledforeground
  -foreground or -fg
  -highlightbackground
  -highlightcolor
  -highlightthickness
  -relief
  -repeatdelay
  -repeatinterval
  -takefocus
  -troughcolor
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -armcommand
  -arrowbd
  -arrowrelief
  -clean
  -command
  -dir
  -disarmcommand
  -height
  -helptext
  -helptype
  -helpvar
  -ipadx
  -ipady
  -state
  -type
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName invoke +
+
+


+DESCRIPTION
+

+ +ArrowButton can be of two types following type option: +for button type, it is standard button with an arrow drawn on it; +for arrow type, it is an arrow like scrollbar's arrow. +

+


+WIDGET-SPECIFIC OPTIONS
+
-armcommand
+
+ +Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is pressed +over the ArrowButton. When repeatdelay or repeatinterval option is positive +integer, this command is repeatedly called if mouse pointer is over the button and until +mouse button 1 is released. +
+
+
-arrowbd
+
+ +When ArrowButton type is arrow, specifies the border width of the +arrow. Must be 1 or 2. + +
+
+
-arrowrelief
+
+ +When ArrowButton type is arrow, specifies the relief of the arrow. +Must be raised or sunken. + +
+
+
-clean
+
+ +Specifies a level of quality, between 0 and 2, for the arrow. +If 0, the arrow is drawn with its maximum width and height. +If 1, the base of arrow is arranged to be odd to have same edges. +If 2, the base of arrow is arranged to be odd and the orthogonal to be (base+1)/2 to +have 'straight' diagonal for edges. +
+
+
-command
+
+ +Specifies a Tcl command to associate with the ArrowButton. This command +is typically invoked when mouse button 1 is released over the ArrowButton +window. +
+
+
-dir
+
+ +Specifies the direction of the arrow: top, bottom, left +or right. +
+
+
-disarmcommand
+
+ +Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is released. +This command is called even if pointer is not over the ArrowButton, and always before +the command specified by command option. +It is typically used in conjuntion with armcommand, repeatdelay and +repeatinterval. +
+
+
-height
+
+ +Specifies a desired height for the ArrowButton. The value is in screen units. +
+
+
-helptext
+
+ +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
+
+
-helptype
+
+Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
+
+
-helpvar
+
+Variable to use when helptype option is variable. +See also DynamicHelp. +
+
+
-ipadx
+
+ +Specifies a minimun pad between the ArrowButton border and the right and left side +of the arrow. The value is in screen units. +
+
+
-ipady
+
+ +Specifies a minimun pad between the ArrowButton border and the top and bottom side +of the arrow. The value is in screen units. +
+
+
-state
+
+ +Specifies one of three states for the ArrowButton: normal, active, +or disabled. +
If ArrowButton type is button:
+
In normal state the ArrowButton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the ArrowButton. In active state +the ArrowButton is displayed using the activeforeground and +activebackground options. In disabled state the disabledforeground and +background options determine how the ArrowButton is displayed. +
+
If ArrowButton type is arrow:
+
Only colors of arrow change. The background of ArrowButton is always +displayed using troughcolor option. +In normal state the ArrowButton is displayed using the background option. The active +state is typically used when the pointer is over the ArrowButton. In active state +the ArrowButton is displayed using the activebackground option. In disabled state +the ArrowButton is displayed with a dark stipple. +
+
+Disabled state means that the ArrowButton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +
+
+
-type
+
+ +Determines the type of the ArrowButton: button for standard button look, or +arrow scrollbar's arrow look. +
+
+
-width
+
+ +Specifies a desired width for the ArrowButton. The value is in screen units. +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName invoke +
+ +If ArrowButton state is not disabled, this invoke the commands of the button. +ArrowButton is redisplayed with active color and sunken relief, and +armcommand is called. Then ArrowButton is redisplayed with +normal color and its defined relief, and disarmcommand then command +are called. +

invoke is called when ArrowButton has input focus and user press the space bar. +

+ diff --git a/hlp/en/bwidget/BWidget.html b/hlp/en/bwidget/BWidget.html new file mode 100644 index 0000000..337906b --- /dev/null +++ b/hlp/en/bwidget/BWidget.html @@ -0,0 +1,116 @@ + +BWidget + +
NAME
+
BWidget + - Description text +
+
+
COMMAND
+
BWidget::XLFDfont + cmd + ?arg...? +
+
BWidget::assert + exp + ?msg? +
+
BWidget::clonename + menu +
+
BWidget::focus + option + path +
+
BWidget::get3dcolor + path + bgcolor +
+
BWidget::getname + name +
+
BWidget::grab + option + path +
+
BWidget::lreorder + list + neworder +
+
BWidget::parsetext + text +
+
BWidget::place + path + w + h + ?arg...? +
+
+


+DESCRIPTION
+

+Description text +

+

+COMMAND
+
BWidget::XLFDfont + cmd + ?arg...? +
+Description text +
+
BWidget::assert + exp + ?msg? +
+Description text +
+
BWidget::clonename + menu +
+Description text +
+
BWidget::focus + option + path +
+Description text +
+
BWidget::get3dcolor + path + bgcolor +
+Description text +
+
BWidget::getname + name +
+Description text +
+
BWidget::grab + option + path +
+Description text +
+
BWidget::lreorder + list + neworder +
+Description text +
+
BWidget::parsetext + text +
+Description text +
+
BWidget::place + path + w + h + ?arg...? +
+Description text +
+ diff --git a/hlp/en/bwidget/Button.html b/hlp/en/bwidget/Button.html new file mode 100644 index 0000000..8a2f49b --- /dev/null +++ b/hlp/en/bwidget/Button.html @@ -0,0 +1,273 @@ + +Button + +
NAME
+
Button + - Button widget with enhanced options +
+
+
CREATION
+
Button pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -activebackground
  -activeforeground
  -anchor
  -background or -bg
  -bitmap
  -borderwidth or -bd
  -cursor
  -disabledforeground
  -font
  -foreground or -fg
  -highlightbackground
  -highlightcolor
  -highlightthickness
  -image
  -justify
  -padx
  -pady
  -repeatdelay
  -repeatinterval
  -takefocus
  -text
  -textvariable
  -wraplength
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
  -armcommand
  -command
  -default
  -disarmcommand
  -height
  -helptext
  -helptype
  -helpvar
  -name
  -relief
  -state
  -underline
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName invoke +
+
+


+DESCRIPTION
+

+ +Button widget extends the Tk button with new options. +DynamicHelp options, +a new relief style, callback for arm/disarm, and +repeatdelay/repeatinterval options has been added. +

+


+WIDGET-SPECIFIC OPTIONS
+
-armcommand
+
+ +Specifies a Tcl command to associate with the Button when mouse button 1 is pressed over the +Button. When repeatdelay or repeatinterval option is positive integer, +this command is repeatedly called if mouse pointer is over the Button and until mouse +button 1 is released. +
+
+
-command
+
+ +Specifies a Tcl command to associate with the Button. This command +is typically invoked when mouse button 1 is released over the Button +window. +
+
+
-default
+
+ +Specifies one of three states for the default ring: normal, active, +or disabled. In active state, the button is drawn with the platform specific +appearance for a default button. In normal state, the button is drawn with the platform +specific appearance for a non-default button, leaving enough space to draw the default +button appearance. The normal and active states will result in buttons of the same size. +In disabled state, the button is drawn with the non-default button appearance without +leaving space for the default appearance. The disabled state may result +in a smaller button than the active state. +
+
+
-disarmcommand
+
+ +Specifies a Tcl command to associate with the Button when mouse button 1 is released. +This command is called even if pointer is not over the Button, and always before +the command specified by command option. +It is typically used in conjuntion with armcommand, repeatdelay and +repeatinterval. +
+
+
-height
+
+ +Specifies a desired height for the Button. +If an image or bitmap is being displayed in the Button then the value is in +screen units; +for text it is in lines of text. +If this option isn't specified, the Button's desired height is computed +from the size of the image or bitmap or text being displayed in it. +
+
+
-helptext
+
+ +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
+
+
-helptype
+
+Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
+
+
-helpvar
+
+Variable to use when helptype option is variable. +See also DynamicHelp. +
+
+
-name
+
+ +Specifies a standard name for the button. If the option *nameName is +found in the resources database, then text and underline options +are extracted from its value. + +
+
+
-relief
+
+ +Specifies the 3-D effect desired for the widget. Acceptable values are standard values for +button relief (raised, sunken, flat, ridge, solid, and groove) and link, which specifies that button relief is flat when pointer +is outside the button and raised when pointer is inside. +
+
+
-state
+
+ +Specifies one of three states for the Button: normal, active, +or disabled. In normal state the Button is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the Button. In active state +the Button is displayed using the activeforeground and +activebackground options. Disabled state means that the Button +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledforeground and +background options determine how the Button is displayed. +
+
+
-underline
+
+ +Specifies the integer index of a character to underline in the label of the button. +0 corresponds to the first character of the text displayed, 1 to the next character, +and so on. +
The binding <Alt-char> is automatically set on the toplevel +of the Button to call Button::setfocus. + +
+
+
-width
+
+ +If an image or bitmap is being displayed in the Button then the value is in +screen units; +for text it is in characters. +If this option isn't specified, the Button's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName invoke +
+ +If Button state is not disabled, this invoke the commands of the Button. +Button is redisplayed with active color and sunken relief, and +armcommand is called. Then Button is redisplayed with +normal color and its defined relief, and disarmcommand then command +are called. +

invoke is called when Button has input focus and user press the space bar. +

+ diff --git a/hlp/en/bwidget/ButtonBox.html b/hlp/en/bwidget/ButtonBox.html new file mode 100644 index 0000000..09200e6 --- /dev/null +++ b/hlp/en/bwidget/ButtonBox.html @@ -0,0 +1,220 @@ + +ButtonBox + +
NAME
+
ButtonBox + - Set of buttons with horizontal or vertical layout +
+
+
CREATION
+
ButtonBox pathName ?option value...?
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + +
  -background or -bg  -default
  -homogeneous
  -orient
  -padx
  -pady
  -spacing
+
+
+
WIDGET COMMAND
+
pathName add + ?option value...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName index + index +
+
pathName invoke + index +
+
pathName itemcget + index + option +
+
pathName itemconfigure + index + ?option? ?value option value ...? +
+
pathName setfocus + index +
+
+


+DESCRIPTION
+

+ +ButtonBox layouts Button horizontally or vertically. +Some commands take an index as argument indicating on which +Button it work. This index may be specified in any of the following forms: +

+

+
+number +
+Specifies the Button numerically, where 0 corresponds +to the first added Button, 1 to the next, and so on. +
+end or last +
+Indicates the last item added. +
default +
+Indicates the default Button. +
+ +

+


+WIDGET-SPECIFIC OPTIONS
+
-background
+
+ +Specifies a default background color for all added buttons and for the frame. + +
+
+
-default
+
+ +Specifies the default button of the button box. The value is an integer +referencing the n-th added button, starting from 0. +If this value is -1 (the default), all button wil be drawn with their -default +option set to disabled, and this value can not be changed.
If this value is +not -1, the associated button is drawn with -default option set to active and +the others are drawn with -default option set to normal. The value can be changed +by configure. + +
+
+
-homogeneous (read-only)
+
+ +Specifies wether or not buttons must have the same width for horizontal layout. + +
+
+
-orient (read-only)
+
+ +Specifies the orientation of the button box. If this option is horizontal +(the default), buttons are added from top to bottom. +If this option is vertical, buttons are added from left to right. + +
+
+
-padx
+
+ +Specifies a default value for the -padx option of all added buttons. + +
+
+
-pady
+
+ +Specifies a default value for the -pady option of all added buttons. + +
+
+
-spacing
+
+ +Specifies the default spacing between buttons. This value can be changed before each +call to add. + +
+
+

+WIDGET COMMAND
+
pathName add + ?option value...? +
+ +Add a button to the button box. +

+See Button for description of options. +

+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName index + index +
+ +Return the numerical index corresponding to the item. + +
+
pathName invoke + index +
+ +Invoke the Button given by index. + +
+
pathName itemcget + index + option +
+ +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
+
pathName itemconfigure + index + ?option? ?value option value ...? +
+ +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
+
pathName setfocus + index +
+ +Set the focus to the Button given by index. + +
+ diff --git a/hlp/en/bwidget/ComboBox.html b/hlp/en/bwidget/ComboBox.html new file mode 100644 index 0000000..766c849 --- /dev/null +++ b/hlp/en/bwidget/ComboBox.html @@ -0,0 +1,306 @@ + +ComboBox + +
NAME
+
ComboBox + - ComboBox widget +
+
+
CREATION
+
ComboBox pathName ?option value...?
+
+
+
OPTIONS from ArrowButton
+
+ + + + + + + + +
  -background or -bg  -disabledforeground
  -foreground or -fg  -state
+
+
+
OPTIONS from Entry
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -command  -disabledforeground
  -dragenabled  -dragendcmd
  -dragevent  -draginitcmd
  -dragtype  -dropcmd
  -dropenabled  -dropovercmd
  -droptypes  -editable
  -entrybg (see -background)  -entryfg (see -foreground)
  -exportselection  -font
  -helptext  -helptype
  -helpvar  -highlightbackground
  -highlightcolor  -highlightthickness
  -insertbackground  -insertborderwidth
  -insertofftime  -insertontime
  -insertwidth  -justify
  -selectbackground  -selectborderwidth
  -selectforeground  -show
  -state  -takefocus
  -text  -textvariable
  -width  -xscrollcommand
+
+
+
OPTIONS from LabelFrame
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -disabledforeground  -foreground or -fg
  -helptext  -helptype
  -helpvar  -label (see -text)
  -labelanchor (see -anchor)  -labelfont (see -font)
  -labelheight (see -height)  -labeljustify (see -justify)
  -labelwidth (see -width)  -name
  -padx  -pady
  -relief  -side
  -state  -underline
  -wraplength
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + +
  -height
  -modifycmd
  -postcommand
  -values
+
+
+
WIDGET COMMAND
+
pathName bind + ?arg...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getvalue +
+
pathName setvalue + index +
+
+


+DESCRIPTION
+

+ +ComboBox widget enables the user to select a value among a list given by the values option. +The list of possible values can be popped by pressing the ArrowButton or by clicking in the entry +when editable value of the ComboBox is false.
+If editable value of the ComboBox is true and the entry has the focus, the user can +press the top and bottom arrow keys to modify its value. If the current value exactly match a value in the list, +then the previous (for top arrow key) or then next (for bottom arrow key) value in the list is displayed. +If the current value match the beginning of a value in the list, then this value is displayed. +If the current value doesnt match anything, then the first value is displayed. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-height
+
+ +Specifies the desired height for the window, in lines. If zero or less, then the desired +height for the window is made just large enough to hold all the elements in the listbox. +
+
+
-modifycmd
+
+ +Specifies a Tcl command called when the user modify the value of the ComboBox by selecting it in the listbox or pressing arrow key. +
+
+
-postcommand
+
+ +Specifies a Tcl command called before the listbox of the ComboBox is mapped. +
+
+
-values
+
+ +Specifies the values to display in the listbox of the ComboBox. +
+
+

+WIDGET COMMAND
+
pathName bind + ?arg...? +
+ +Set bindings on the entry widget. + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName getvalue +
+ +Returns the index of the current text of the ComboBox in the list of values, +or -1 if it doesn't match any value. + +
+
pathName setvalue + index +
+ +Set the text of the ComboBox to the value indicated by index in the list of values. +index may be specified in any of the following forms: +

+

+
+last +
+Specifies the last element of the list of values. +
first +
+Specifies the first element of the list of values. +
+next +
+Specifies the element following the current (ie returned by getvalue) in the list +of values. +
previous +
+Specifies the element preceding the current (ie returned by getvalue) in the list +of values. +
+@number +
+Specifies the integer index in the list of values. +
+ +
+

BINDINGS

+ +When Entry of the ComboBox has the input focus, it has the following bindings, in addition +to the default Entry bindings: +
    +
  • Page up set the value of the ComboBox to the first value. +
  • Page down set the value of the ComboBox to the last value. +
  • Arrow up set the value of the ComboBox to the previous value. +
  • Arrow down set the value of the ComboBox to the next value. +
+If the listbox is not mapped and ComboBox is not editable or disabled, +mouse button 1 on the Entry cause the listbox to popup, as if the user press the ArrowButton. + + diff --git a/hlp/en/bwidget/Dialog.html b/hlp/en/bwidget/Dialog.html new file mode 100644 index 0000000..19dfcbe --- /dev/null +++ b/hlp/en/bwidget/Dialog.html @@ -0,0 +1,293 @@ + +Dialog + +
NAME
+
Dialog + - Dialog abstraction with custom buttons +
+
+
CREATION
+
Dialog pathName ?option value...?
+
+
+
OPTIONS from ButtonBox
+
+ + + + + + + + + + +
  -background or -bg  -homogeneous
  -padx  -pady
  -spacing
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + +
  -anchor
  -bitmap
  -cancel
  -default
  -image
  -modal
  -parent
  -separator
  -side
  -title
+
+
+
WIDGET COMMAND
+
pathName add + ?arg...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName draw + ?focus? +
+
pathName enddialog + result +
+
pathName getframe +
+
pathName invoke + index +
+
pathName itemcget + index + option +
+
pathName itemconfigure + index + ?option? ?value option value ...? +
+
pathName setfocus + index +
+
pathName withdraw +
+
+


+DESCRIPTION
+

+ +Dialog widget enables the user to create a dialog box. +Some commands take an index as argument indicating on which +Button it work. This index is the same specified for equivalent ButtonBox command: +

+

+
+number +
+Specifies the Button numerically, where 0 corresponds +to the first added Button, 1 to the next, and so on. +
+end or last +
+Indicates the last item added. +
default +
+Indicates the default Button. +
+ +

+


+WIDGET-SPECIFIC OPTIONS
+
-anchor (read-only)
+
+ +Specifies the anchor point of the ButtonBox. +Must be one of w, e, n, s or c. +If side option is set to top or bottom, +anchor values n, s and c have the same effect. +If side option is set to left or right, +anchor values w, e and c have the same effect. + +
+
+
-bitmap (read-only)
+
+ +Specifies a bitmap to display at the left of the user frame. +image option override bitmap. +
+
+
-cancel
+
+ +Specifies the number of the cancel button of the Dialog. When user press Esc in the Dialog, +this button is invoked. +
+
+
-default
+
+ +Specifies the number of the default button of the Dialog. +When user press Return in the Dialog, this button is invoked. +
+
+
-image (read-only)
+
+ +Specifies an image to display at the left of the user frame. +image option override bitmap. +
+
+
-modal
+
+ +This option must be none, local or global. The value of this option +specifies the grab mode of the dialog and how works Dialog::draw. + +
+
+
-parent
+
+ +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
+
+
-separator (read-only)
+
+ +Specifies wether or not to draw a separator between the user frame and the ButtonBox. + +
+
+
-side (read-only)
+
+ +Specifies where to draw the ButtonBox relative to the user frame. Must be one of +top, left, bottom or right. +
+
+
-title
+
+ +Title of the Dialog toplevel. + +
+
+

+WIDGET COMMAND
+
pathName add + ?arg...? +
+ +Add a button to the button box of the dialog box. Default -command option is +Dialog::enddialog $path index where index is number of button added. +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName draw + ?focus? +
+ +This command draw the Dialog, and set grab to it following modal option. +If modal option is set to none, the command returns immediatly +an empty string. In all other case, the command returns when Dialog::enddialog +is called or when Dialog is destroyed. +The return value is the result argument of Dialog::enddialog or -1 if it is destroyed. +

+By default, the focus is set to the default button referenced by default option, +or to the toplevel of Dialog if no default button has been set. +If focus is present, it must be a pathname, or an index to a button. +Initial focus is set on this pathname or corresponding button. + +

+
pathName enddialog + result +
+ +This command is typically called within a command of a button to make Dialog::draw +return. + +
+
pathName getframe +
+ +Returns the pathname of the user window. +
+
pathName invoke + index +
+ +Invoke the Button given by index. + +
+
pathName itemcget + index + option +
+ +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
+
pathName itemconfigure + index + ?option? ?value option value ...? +
+ +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
+
pathName setfocus + index +
+ +Set the focus to the Button given by index. + +
+
pathName withdraw +
+ +Call this command to hide the dialog box. + +
+ diff --git a/hlp/en/bwidget/DragSite.html b/hlp/en/bwidget/DragSite.html new file mode 100644 index 0000000..bc6f9b4 --- /dev/null +++ b/hlp/en/bwidget/DragSite.html @@ -0,0 +1,139 @@ + +DragSite + +
NAME
+
DragSite + - Commands set for Drag facilities +
+
+
COMMAND
+
DragSite::include + class + type + event +
+
DragSite::register + path + ?option value...? +
+
DragSite::setdrag + path + subpath + initcmd + endcmd + ?force? +
+
+


+DESCRIPTION
+

+ +Commands of this namespace enable user to define a BWidget or a Tk widget as a drag site. + + + +

+

+COMMAND
+
DragSite::include + class + type + event +
+ +This command provides a simple way to include options relatives to a drag site into +BWidget resources definition. +It includes the options needed for register: -dragevent, initialized to +event, -draginitcmd and -dragendcmd, initialized to empty string, +and two new options: + +
-dragenabledSpecifies wether or not drag is active (initialized to 0) +
-dragtypeDefault or alternate dragged data type (initialized to type) +
+ +
+
DragSite::register + path + ?option value...? +
+ +This command is used to declare path as a drag site. Options are: + +

+

-dragendcmd
+
+ +Command called when drag terminates (ie when user release drag icon). +This command is called with the following arguments: +
    +
  • the pathname of the drag source (the widget itself), +
  • the pathname of the drop target, +
  • the operation, +
  • the type of the dragged data, +
  • the dragged data, +
  • result of the drop (result of the call to -dropcmd of the target), +
+If the drop does not occurs, the target and the operation are empty string and the result +is 0. + +
+
+
-dragevent
+
+ +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
+
+
-draginitcmd
+
+ +Command called when drag initiates. When the event of option dragevent occurs on +path, this command is called with the following arguments: +
    +
  • pathname of the drag source (path), +
  • root x-coordinate of pointer, +
  • root y-coordinate of pointer, +
  • a toplevel created to represent dragged data. When returning, if it +has no children, a bitmap is automatically displayed. +
+The command must return a list containing three elements: +
    +
  • the type of the data, +
  • the list of acceptable basic operations (copy, move and link) +
  • and the data. +
+Note that even if copy does not appear in the list of basic operation, +it is considered as an acceptable operation, since copy semantic does not modify +the drag source. + +
+
+
+
DragSite::setdrag + path + subpath + initcmd + endcmd + ?force? +
+ +This command provides a simple way to call register during a BWidget creation or +configuration. +
    +
  • path is the pathname of the BWidget, +
  • subpath is the pathname of the tk widget where drag event occurs, +
  • initcmd BWidget command for drag-init event, +
  • endcmd BWidget command for drag-end event, +
  • force specifies wether or not to call register whenever no option value has +changed (0 by default - for BWidget configuration, use 1 for BWidget creation). +
+setdrag verifies the modification flag of options dragenabled and +dragevent and calls register if needed according to the options values and +initcmd and endcmd arguments. draginitcmd and dragendcmd are not +taken from options of widget because they are considered as user command, called by +BWidget implementation of drag-init and drag-end events. +
+ + diff --git a/hlp/en/bwidget/DropSite.html b/hlp/en/bwidget/DropSite.html new file mode 100644 index 0000000..264f4c9 --- /dev/null +++ b/hlp/en/bwidget/DropSite.html @@ -0,0 +1,258 @@ + +DropSite + +
NAME
+
DropSite + - Commands set for Drop facilities +
+
+
COMMAND
+
DropSite::include + class + types +
+
DropSite::register + path + ?option value...? +
+
DropSite::setcursor + cursor +
+
DropSite::setdrop + path + subpath + dropover + drop + ?force? +
+
DropSite::setoperation + op +
+
+


+DESCRIPTION
+

+ +Commands of this namespace enable user to define a BWidget or a Tk widget as a drop site. +A drop site is composed of the type of object that can be dropped and associated operation, +a command called when drop occurs, and a command when an object is dragged over the widget. +A drop site must have at least one type of acceptable object and a drop command. + +

+

+COMMAND
+
DropSite::include + class + types +
+ +This command provides a simple way to include options relatives to a drop site into +BWidget resources definition. +It includes the options needed for register, -dropovercmd and -dropcmd, +initialized to empty string, and -droptypes, initialized to types, +and one new option: + +
-dropenabledSpecifies wether or not drop is active (initialized to 0) +
+ +
+
DropSite::register + path + ?option value...? +
+ +This command is used to declare path as a drop site. Options are: + +

+

-dropcmd
+
+ +This command is called when user release the drag icon over a valid drop target widget. +It takes the same arguments as -dragovercmd command. Its return values is passed +as a result to the -dragendcmd command of the drag source widget. + +
+
+
-dropovercmd
+
+ +This command can be used to provide a dynamic drag while drag-over events. +While a drag occurs, events <Enter>, <Motion> and <Leave> are catched. +Arguments passed to the command are: +
    +
  • pathname of the drop target (the widget itself), +
  • pathname of the drag source, +
  • event over the drop target: enter, motion or leave, +
  • root x-coordinate of the pointer, +
  • root y-coordinate of the pointer, +
  • operation, +
  • type of the dragged data, +
  • dragged data. +
+Command must the new status of the drag: +
    +
  • 0 if widget refuse this drag. Command will not be recalled on motion/leave event. +
  • 1 if widget accept this drag. Command will not be recalled on motion/leave event. +
  • 2 if widget refuse this drag. Command will be recalled on each motion event to reevaluate. +
  • 3 if widget accept this drag. Command will be recalled on each motion event to reevaluate. + +
+Here is a list of events and associated actions on a DropSite widget. This example +assumes that dragged data type is valid for the drop target. +status is the status of the drag on a DropSite. Its value is: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Event

+

Old status

+

Action

+

New status

+

<Enter>

+

-

+

if DropSite has dropovercmd, call it with enter

+

result of dropovercmd

+

else

+

1

+

<Motion>

+

0 or 1

  +

unchanged

+

2 or 3

+

call dropovercmd with motion

+

result of dropovercmd

+

<Leave>

+

 

+

0 or 1

  +

-

+

2 or 3

+

call dropovercmd with leave

+

-

+

<Drop>

+

0

+

call dragendcmd of drag source

+

-

+

1

+

call dropcmd and call dragendcmd of drag source

+

2

+

call dropovercmd with leave and call dragendcmd of drag source

+

3

+

call dropcmd and call dragendcmd of drag source

+
+ +
+
+
-droptypes
+
+ +Specifies a list {type oplist ?type oplist? ...} of acceptable +types and associated operations for the drop target. +For each type, oplist is a list +{descops mod ?descops mod? ...} describing operations and +modifier keys for these operations. +descops describe an operation. It can be a predefined operations (copy, +move or link) or a new user defined operation, of the form {subop +baseop ?bitmap?}. +subop is the name given to the sub operation, baseop is the name of the +base operation (copy, move or link) and bitmap is a bitmap +to display for the operation. +
If bitmap is empty, the default bitmap of the base operation is used for the +sub operation. +
subop can be a base operation, in order to change the bitmap of a base operation. +In this case, baseop must be empty or equal to subop. +
mod is the modifer key for the operation. It can be: +
    +
  • none to specify that no modifier key is pressed. This modifier can only be used +with a sub operation named default (and vice versa), which has the behaviour of not +display any bitmap operation. For all type, if the modifier none is not given, it is +automatically associated to the default sub operation of a copy base operation. +
  • program to specifies a sub operation accessible only by DropSite::setoperation. +
  • A list combining shift, control and alt, which means their +corresponding key. +
+ +
+
+
+
DropSite::setcursor + cursor +
+ +This command can be used within the script dragovercmd. It is usefull to provide +visual effect about the state of the drag. +
+
DropSite::setdrop + path + subpath + dropover + drop + ?force? +
+ +This command provides a simple way to call register during a BWidget creation or +configuration. +
    +
  • path is the pathname of the BWidget, +
  • subpath is the pathname of the tk widget where drag event occurs, +
  • dropover is a command for drag-over event, +
  • drop is a command for drop event, +
  • force specifies wether or not to call register whenever no option value +has changed (0 by default - for BWidget configuration, use 1 for BWidget creation). +
+setdrop verifies the modification flag of options dropenabled and +droptypes and calls register if needed according to the options values and +dropover and drop arguments. dropovercmd and dropcmd are not +taken from options of widget because they are considered as user command, called by +BWidget implementation of drag-over and drop events. + +
+
DropSite::setoperation + op +
+Description text +
+ diff --git a/hlp/en/bwidget/DynamicHelp.html b/hlp/en/bwidget/DynamicHelp.html new file mode 100644 index 0000000..a0a338a --- /dev/null +++ b/hlp/en/bwidget/DynamicHelp.html @@ -0,0 +1,126 @@ + +DynamicHelp + +
NAME
+
DynamicHelp + - Provide help to Tk widget or BWidget +
+
+
COMMAND
+
DynamicHelp::configure + ?option? ?value option value ...? +
+
DynamicHelp::include + class + type +
+
DynamicHelp::register + path + type + ?arg...? +
+
DynamicHelp::sethelp + path + subpath + ?force? +
+
+


+DESCRIPTION
+

+Description text +

+

+COMMAND
+
DynamicHelp::configure + ?option? ?value option value ...? +
+This command configure the ballon help. +

+

-borderwidth
+
+Width of the black border around the balloon. +
+
+
-delay
+
+Define the delay in millisecond of mouse inactivity before displaying +the balloon. +
+
+
Other standard options are: +
+ + + + + + + + +
  -background or -bg  -font
  -foreground or -fg  -justify
+
+
DynamicHelp::include + class + type +
+Description text +
+
DynamicHelp::register + path + type + ?arg...? +
+Register a help text to the widget path. +type determines the type of the help or the type of the widget. +Depending on type, other options must be provided. +
+ + + + + + +
type options
balloon text
variable varName text
menu varName
menuentry index text
+
If one of the option is missing or is empty, help is removed for this widget. +
For type other than balloon, varName is typically a variable +linked to a label. +
For menu, balloon type help is not available. To declare a help for menu, +you first declare the menu, and then entries of this menu. +
For example: +

+
+ +
+     # create menu
+menu .m -type menubar
+# associate menubar to toplevel BEFORE DynamicHelp::register
+# to make it works with menu clone name
+. configure -menu .m
+.m add cascade -label "File" -menu .m.file
+menu .m.file
+.m.file add command -label "Open..."
+.m.file add command -label "Quit"
+# create label for help, using variable varinfo
+label .l -textvariable varinfo
+# associate all entries of menu .m.file to variable varinfo
+DynamicHelp::register .m.file menu varinfo
+# then declare entries of .m.file
+DynamicHelp::register .m.file menuentry 0 "Detach menu"
+DynamicHelp::register .m.file menuentry 1 "Open a file"
+DynamicHelp::register .m.file menuentry 2 "Exit demo"
+
+
+
Notice that if popup menu is owned by a menubar, you must associate first the menubar +to its toplevel. In this case, when you create a menu popup, its clone window is also +created, and DynamicHelp::register detects the exitence of the clone window and maps +events to it. +
+
DynamicHelp::sethelp + path + subpath + ?force? +
+Description text +
+ diff --git a/hlp/en/bwidget/Entry.html b/hlp/en/bwidget/Entry.html new file mode 100644 index 0000000..585107d --- /dev/null +++ b/hlp/en/bwidget/Entry.html @@ -0,0 +1,340 @@ + +Entry + +
NAME
+
Entry + - Entry widget with state option, dynamic help and drag and drop facilities +
+
+
CREATION
+
Entry pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -disabledforeground
  -exportselection
  -font
  -foreground or -fg
  -highlightbackground
  -highlightcolor
  -highlightthickness
  -insertbackground
  -insertborderwidth
  -insertofftime
  -insertontime
  -insertwidth
  -justify
  -relief
  -selectbackground
  -selectborderwidth
  -selectforeground
  -takefocus
  -text
  -textvariable
  -xscrollcommand
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -command
  -dragenabled
  -dragendcmd
  -dragevent
  -draginitcmd
  -dragtype
  -dropcmd
  -dropenabled
  -dropovercmd
  -droptypes
  -editable
  -helptext
  -helptype
  -helpvar
  -show
  -state
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName invoke +
+
+


+DESCRIPTION
+

+ +The Entry widget extends the default Tk entry. Options have been added to provide +visual effect depending on the state of the Entry, +DynamicHelp options, +and Drag and +Drop. +Entry behaves much like a Label, with text option to set its contents. +
Tk entry command can also be used on Entry widget. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-command
+
+ +Specifies a command when user press <Return> in the Entry. +
+
+
-dragenabled
+
+A boolean specifying if drag is enabled. +
+
+
-dragendcmd
+
+ +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
If dragendcmd is empty, the internal dragend command updates the entry +following the operation (move or copy) and the dragged data +(whole or selected part of the entry). + +
+
+
-dragevent
+
+ +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
+
+
-draginitcmd
+
+ +Specifies a command to be called when dragevent occurs on widget. +draginitcmd must be a command conforming to the description of the +option draginitcmd of DragSite::register. + +
if draginitcmd is empty, the command refuse the drag if entry is empty or if +portion of text is selected and event doesn't occur above the selection. In all other cases, +the command returns: +
    +
  • as the data type, the value of option dragtype or TEXT if empty, +
  • as the operations, {copy move} if state is normal and editable +is true, or {copy} only in other cases, +
  • as the data, the whole content or the selected portion of the entry. +
+ +
+
+
-dragtype
+
+ +Specifies an alternate type of dragged object. + +
+
+
-dropcmd
+
+ +Entry has a command wrapper for drop events. This command stops auto scrolling +and extract current position. +
If dropcmd is not empty, it is called with the following arguments: +
    +
  • the pathname of the Entry, +
  • the pathname of the drag source, +
  • the numeric index in the entry designated by the cursor, +
  • the current operation, +
  • the data type, +
  • the data. +
+and must return a value conforming to dropcmd option described in +DropSite::register. +If dropcmd is empty, the wrapper updates the entry following the type of data: +
+ + + + + + +
COLOR or FGCOLORreconfigure the foreground of the Entry
BGCOLORreconfigure the background of the Entry
TEXT,
or any other tag
reconfigure the Entry to display the associated string.
+and returns 1. + +
+
+
-dropenabled
+
+A boolean specifying if drop is enabled. +
+
+
-dropovercmd
+
+ +Entry has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +
If dropovercmd is empty, the wrapper accepts the drop if editable option is +true and state option is normal. +
If dropovercmd is not empty, it is called with the following arguments: +
    +
  • the pathname of the Entry, +
  • the pathname of the drag source, +
  • the event, +
  • the numeric index in the entry designated by the cursor, +
  • the current operation, +
  • the data type, +
  • the data. +
+and must return a value conforming to dropovercmd option described in +DropSite::register. + +
+
+
-droptypes
+
+ +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +Default accepts FGCOLOR, COLOR, BGCOLOR and TEXT, +all with copy and move operations. + +
+
+
-editable
+
+ +Specifies whether the Entry is editable by the user. Equivalent to the state option +of the Tk entry widget. +
+
+
-helptext
+
+ +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
+
+
-helptype
+
+Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
+
+
-helpvar
+
+Variable to use when helptype option is variable. +See also DynamicHelp. +
+
+
-show
+
+ +If this option is specified, then the true contents of the entry are not displayed in the +window. Instead, each character in the entry's value will be displayed as the first character +in the value of this option, such as ``*''. This is useful, for example, if the entry is to +be used to enter a password. If characters in the entry are selected and copied elsewhere, the +information copied will be what is displayed, not the true contents of the entry. +
+
+
-state
+
+ +Specifies one of two states for the Entry: normal or disabled. +In normal state the text of the Entry is displayed using the foreground option. +In disabled state the text of the Entry is displayed using the disabledforeground +option. If the entry is disabled then the value may not be changed by user input +and no insertion cursor will be displayed, even if the input focus is in the widget. +Disabled state is the same as not editable with visual effect. +
+
+
-width
+
+ +Specifies an integer value indicating the desired width of the entry window, in average-size +characters of the widget's font. If the value is less than or equal to zero, the widget picks +a size just large enough to hold its current text. +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName invoke +
+ +Calls the command specified by the option -command. + +
+ diff --git a/hlp/en/bwidget/Label.html b/hlp/en/bwidget/Label.html new file mode 100644 index 0000000..7eeb67e --- /dev/null +++ b/hlp/en/bwidget/Label.html @@ -0,0 +1,331 @@ + +Label + +
NAME
+
Label + - Label widget with state option, dynamic help and drag and drop facilities +
+
+
CREATION
+
Label pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -anchor
  -background or -bg
  -bitmap
  -borderwidth or -bd
  -cursor
  -disabledforeground
  -font
  -foreground or -fg
  -highlightbackground
  -highlightcolor
  -highlightthickness
  -image
  -justify
  -padx
  -pady
  -relief
  -takefocus
  -text
  -textvariable
  -wraplength
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -dragenabled
  -dragendcmd
  -dragevent
  -draginitcmd
  -dragtype
  -dropcmd
  -dropenabled
  -dropovercmd
  -droptypes
  -focus
  -height
  -helptext
  -helptype
  -helpvar
  -name
  -state
  -underline
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName setfocus +
+
+


+DESCRIPTION
+

+ +The Label widget extends the default Tk label. Options have been added to provide +visual effect depending on the state of the Label, DynamicHelp options, and Drag + and Drop. +

+


+WIDGET-SPECIFIC OPTIONS
+
-dragenabled
+
+A boolean specifying if drag is enabled. +
+
+
-dragendcmd
+
+ +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
+
+
-dragevent
+
+ +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
+
+
-draginitcmd
+
+ +Specifies a command to be called when dragevent occurs on widget. +draginitcmd must be a command conforming to the description of the +option draginitcmd of DragSite::register. + +
If draginitcmd is empty, the internal draginitcmd command is used instead +and returns: +
+
IMAGE {copy} <image name> +if an image is displayed. +
BITMAP {copy} <bitmap name> +if a bitmap is displayed. +
TEXT {copy} <text> +if a text is displayed. +
+Note that if dragtype option is not empty, its value is used instead of those above. + +
+
+
-dragtype
+
+ +Specifies an alternate type of dragged object. + +
+
+
-dropcmd
+
+ +Specifies a command to be called when drop occurs on the widget. +dropcmd must be a command conforming to the description of the +option dropcmd of DropSite::register. + +
If dropcmd is empty, the command updates the label following the type of the data: +
+ + + + + + + + + + +
COLOR or FGCOLORreconfigure the foreground of the Label.
BGCOLORreconfigure the background of the Label.
IMAGEreconfigure the Label to display the associated image.
BITMAPreconfigure the Label to display the associated bitmap. +image option is set to empty.
TEXT,
or any other tag
reconfigure the Label to display the associated string. +image and bitmap options are set to empty.
+and returns 1. + +
+
+
-dropenabled
+
+A boolean specifying if drop is enabled. +
+
+
-dropovercmd
+
+ +Specifies a command to be called when drag icon is over the widget. +dropovercmd must be a command conforming to the description of the +option dropovercmd of DropSite::register. + +
If dropovercmd is empty, Label always accepts the drop if data type is +FGCOLOR, COLOR, BGCOLOR, and accepts all other data type only if +state is normal. + +
+
+
-droptypes
+
+ +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +Default accepts FGCOLOR, COLOR, BGCOLOR, TEXT, BITMAP +and IMAGE, all with copy and move operations. + +
+
+
-focus
+
+ +Specifies a pathname to set the focus on for Label::setfocus command. + +
+
+
-height
+
+ +Specifies a desired height for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units, for text it is in lines of text. +If this option isn't specified, the label's desired height is computed +from the size of the image or bitmap or text being displayed in it. +
+
+
-helptext
+
+ +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
+
+
-helptype
+
+Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
+
+
-helpvar
+
+Variable to use when helptype option is variable. +See also DynamicHelp. +
+
+
-name
+
+ +Specifies a standard name for the label. If the option *nameName is +found in the resource database, then text and underline options +are extracted from its value. + +
+
+
-state
+
+ +Specifies one of two states for the Label: normal or disabled. +In normal state the text of the Label is displayed using the foreground option. +In disabled state the text of the Label is displayed using the disabledforeground option. +
+
+
-underline
+
+ +Specifies the integer index of a character to underline in the label. +0 corresponds to the first character of the text displayed, 1 to the next character, +and so on. +
The binding <Alt-char> is automatically set on the toplevel +of the Label to call Label::setfocus. + +
+
+
-width
+
+ +Specifies a desired width for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units, for text it is in characters. +If this option isn't specified, the label's desired width is computed +from the size of the image or bitmap or text being displayed in it. + +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName setfocus +
+ +Set the focus on the pathname given by -focus option if -state is normal. + +
+ diff --git a/hlp/en/bwidget/LabelEntry.html b/hlp/en/bwidget/LabelEntry.html new file mode 100644 index 0000000..c0858c7 --- /dev/null +++ b/hlp/en/bwidget/LabelEntry.html @@ -0,0 +1,194 @@ + +LabelEntry + +
NAME
+
LabelEntry + - +LabelFrame containing an Entry widget. + +
+
+
CREATION
+
LabelEntry pathName ?option value...?
+
+
+
OPTIONS from Entry
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -borderwidth or -bd  -command
  -disabledforeground  -dragenabled
  -dragendcmd  -dragevent
  -draginitcmd  -dragtype
  -dropcmd  -dropenabled
  -dropovercmd  -droptypes
  -editable  -entrybg (see -background)
  -entryfg (see -foreground)  -exportselection
  -font  -helptext
  -helptype  -helpvar
  -highlightbackground  -highlightcolor
  -highlightthickness  -insertbackground
  -insertborderwidth  -insertofftime
  -insertontime  -insertwidth
  -justify  -relief
  -selectbackground  -selectborderwidth
  -selectforeground  -show
  -state  -takefocus
  -text  -textvariable
  -width  -xscrollcommand
+
+
+
OPTIONS from LabelFrame
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -background or -bg  -disabledforeground
  -foreground or -fg  -helptext
  -helptype  -helpvar
  -label (see -text)  -labelanchor (see -anchor)
  -labelfont (see -font)  -labelheight (see -height)
  -labeljustify (see -justify)  -labelwidth (see -width)
  -name  -padx
  -pady  -side
  -state  -underline
  -wraplength
+
+
+
WIDGET COMMAND
+
pathName bind + ?arg...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
+


+DESCRIPTION
+

+ +LabelEntry is a widget composed of LabelFrame widget +containing an Entry widget. +Tk entry command can also be used on LabelEntry widget. + +

+

+WIDGET COMMAND
+
pathName bind + ?arg...? +
+ +Set bindings on the entry widget. + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+ diff --git a/hlp/en/bwidget/LabelFrame.html b/hlp/en/bwidget/LabelFrame.html new file mode 100644 index 0000000..1e027fd --- /dev/null +++ b/hlp/en/bwidget/LabelFrame.html @@ -0,0 +1,139 @@ + +LabelFrame + +
NAME
+
LabelFrame + - Frame with a Label +
+
+
CREATION
+
LabelFrame pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + +
  -borderwidth or -bd  -relief
+
+
+
OPTIONS from Label
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -anchor  -background or -bg
  -disabledforeground  -focus
  -font  -foreground or -fg
  -height  -helptext
  -helptype  -helpvar
  -justify  -name
  -padx  -pady
  -state  -text
  -underline  -width
  -wraplength
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + +
  -side
+
+
+
WIDGET COMMAND
+
LabelFrame::align + ?arg...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getframe +
+
+


+DESCRIPTION
+

+ +LabelFrame enables user to create a frame with a +Label positionned at any side. +LabelFrame is used by ComboBox +and SpinBox. +

+


+WIDGET-SPECIFIC OPTIONS
+
-side (read-only)
+
+ +Specifies where to position the Label relative to the user frame: top, bottom, left or right. +
+
+

+WIDGET COMMAND
+
LabelFrame::align + ?arg...? +
+ +This command align label of all widget given by args of class LabelFrame +(or "derived") by setting their width to the max one +1 + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName getframe +
+ +Return the frame where the user can create any other widget. +
+ diff --git a/hlp/en/bwidget/ListBox.html b/hlp/en/bwidget/ListBox.html new file mode 100644 index 0000000..39a8790 --- /dev/null +++ b/hlp/en/bwidget/ListBox.html @@ -0,0 +1,608 @@ + +ListBox + +
NAME
+
ListBox + - ListBox widget +
+
+
CREATION
+
ListBox pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -cursor
  -highlightbackground
  -highlightcolor
  -highlightthickness
  -relief
  -selectbackground
  -selectforeground
  -takefocus
  -xscrollcommand
  -yscrollcommand
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -deltax
  -deltay
  -dragenabled
  -dragendcmd
  -dragevent
  -draginitcmd
  -dragtype
  -dropcmd
  -dropenabled
  -dropovercmd
  -dropovermode
  -droptypes
  -height
  -multicolumn
  -padx
  -redraw
  -width
+
+
+
WIDGET COMMAND
+
pathName bindImage + event + script +
+
pathName bindText + event + script +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName delete + ?arg...? +
+
pathName edit + item + text + ?verifycmd? + ?clickres? + ?select? +
+
pathName exists + item +
+
pathName index + item +
+
pathName insert + index + item + ?option value...? +
+
pathName item + first + ?last? +
+
pathName itemcget + item + option +
+
pathName itemconfigure + item + ?option? ?value option value ...? +
+
pathName items + ?first? + ?last? +
+
pathName move + item + index +
+
pathName reorder + neworder +
+
pathName see + item +
+
pathName selection + cmd + ?arg...? +
+
pathName xview + ?arg...? +
+
pathName yview + ?arg...? +
+
+


+DESCRIPTION
+

+ +ListBox widget uses canvas to display a list of items. +Each item is composed of a label with its own font and foreground attributes, and an optional +image or window. Each item is drawn in a single line, whose height is defined by the +deltay option, so they must have at most this height. +A item is uniquely identified by a string given at creation (by the +insert command). The ListBox can have one or more columns, depending on +multicolumn option. The user do not handle columns; the number of columns +is determined following the height of the ListBox in order to see each item vertically. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-deltax
+
+ +Specifies horizontal pad between each columns. + +
+
+
-deltay
+
+ +Specifies vertical size of the items. + +
+
+
-dragenabled
+
+A boolean specifying if drag is enabled. +
+
+
-dragendcmd
+
+ +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
+
+
-dragevent
+
+ +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
+
+
-draginitcmd
+
+ +ListBox has a command wrapper for drag-init events. This command refused the drag +if no item is designated. In other cases: +
If draginitcmd is empty, it returns: +
    +
  • the value of option dragtype or LISTBOX_ITEM if empty as the data type, +
  • {move copy link} as the operations, +
  • the item identifier as the data. +
+If draginitcmd is not empty, it is called with the following arguments: +
    +
  • the pathname of the listbox, +
  • the identifier of the dragged item, +
  • the toplevel created to represent dragged data. +
+and must return a value conforming to draginitcmd option described in +DragSite::register. + +
+
+
-dragtype
+
+ +Specifies an alternate type of dragged object. + +
+
+
-dropcmd
+
+ +ListBox has a command wrapper for drop events. This command stops auto scrolling +and extract item and position. +
If dropcmd is not empty, it is called with the following arguments: +
    +
  • the pathname of the listbox, +
  • the pathname of the drag source, +
  • a list describing where the drop occurs. It can be: +
      +
    • {widget}, +
    • {item item} or +
    • {position index}. +
    +
  • the current operation, +
  • the data type, +
  • the data. +
+ +
+
+
-dropenabled
+
+A boolean specifying if drop is enabled. +
+
+
-dropovercmd
+
+ +LsitBox has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +If dropovercmd is not empty, the command is called with the following aguments: +
    +
  • the pathname of the listbox, +
  • the pathname of the drag source, +
  • a list describing where the drop can occur, whose elements are: +
      +
    • the string widget if dropovertype option contains w, else empty string. +
    • the targeted item if drag icon points an item and dropovertype option contains +i, else empty string. +
    • an index within two items where drag icon points to if dropovertype option +contains p, else empty string. +
    • optionally, the preferred method if drop can occur both inside an item and between two +items. The value is position or item. +
    +
  • the current operation, +
  • the data type, +
  • the data. +
+The command must return a list with two elements: +
    +
  • the drop status, conforming to those described in dropovercmd option of +DropSite::register, +
  • the choosen method: widget, item or position. +
+ +
+
+
-dropovermode
+
+ +Specifies the type of drop-over interaction. Must be a combination of +w, which specifies that drop can occurs everywhere on widget, +p, which specifies that drop can occurs between two items, +and i, which specifies that drop occurs inside items. + +
+
+
-droptypes
+
+ +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +
Default is LISTBOX_ITEM with operations copy and move. + +
+
+
-height
+
+ +Specifies the desired height for the listbox in units of deltay pixels. + +
+
+
-multicolumn
+
+ +Specifies wether or not ListBox layouts items in order to see each one vertically. + +
+
+
-padx
+
+ +Specifies distance between image or window and text of the items. + +
+
+
-redraw
+
+ +Specifies wether or not the listbox should be redrawn when entering idle. +Set it to false if you call update while modifying the listbox. + +
+
+
-width
+
+ +Specifies the desired width for the listbox in units of 8 pixels. + +
+
+

+WIDGET COMMAND
+
pathName bindImage + event + script +
+ +This command associates a command to execute whenever the event +sequence given by event occurs on the image of a item. +The item idenfier on which the event occurs is appended to the command. + +
+
pathName bindText + event + script +
+ +This command associates a command to execute whenever the event +sequence given by event occurs on the label of a item. +The item idenfier on which the event occurs is appended to the command. + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName delete + ?arg...? +
+ +Deletes all items in arg. arg can be a list +of items or a list of list of items. +To delete all items, do $pathName delete [$pathName items]. + +
+
pathName edit + item + text + ?verifycmd? + ?clickres? + ?select? +
+ +Provides a way for the user to edit in place the label of an item. +
The command takes the initial text as argument and does not modify the label of the +edited node, but returns an empty string if edition is canceled, or the typed text +if edition is accepted. +
When editing, the user can cancel by pressing Escape, or accept by pressing Return. +
clickres specifies what to do if the user click outside the editable area. +If clickres is 0 (the default), the edition is canceled. +If clickres is 1, the edition is accepted. +In all other case, the edition continues. +
If edition is accepted and modifycmd is not empty, then it is called with +the new text as argument and must return 1 to accept the new text, 0 to refuse it +and continue edition. +
select specifies wether or not the initial text should be selected. Default is 1. + +
+
pathName exists + item +
+ +Returns 1 if item exists in the listbox, else 0. + +
+
pathName index + item +
+ +Returns the position of item in the list. + +
+
pathName insert + index + item + ?option value...? +
+ +Inserts a new item identified by item in the list at position index. + +

+

-data
+
+ +User data associated to the item. + +
+
+
-fill
+
+ +Specifies the foreground color of the label of the item. + +
+
+
-font
+
+ +Specifies a font for the label of the item. + +
+
+
-image
+
+ +Specifies an image to display at the left of the label of the item. +window option override image. +
+
+
-indent
+
+ +Specifies the amount of extra space in pixels at the left of the item. + +
+
+
-text
+
+ +Specifies the label of the item. + +
+
+
-window
+
+ +Specifies a pathname to display at the left of the label of the item. +window option override image. +
+
+
+
pathName item + first + ?last? +
+ +Its use is deprecated. Use items instead.
+If last is omitted, returns the item at index first in the list, +or an empty string if first refers to a non-existent element. +If last is specified, the command returns a list whose elements are all +of the items between first and last, inclusive. +Both first and last may have any of the standard forms for indices. + +
+
pathName itemcget + item + option +
+ +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
+
pathName itemconfigure + item + ?option? ?value option value ...? +
+ +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
+
pathName items + ?first? + ?last? +
+ +If first and last are omitted, returns the list of all items. +If first is specified and last omitted, returns the item at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the items between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
+
pathName move + item + index +
+ +Moves item at position index in the list. + +
+
pathName reorder + neworder +
+ +Modifies the order of items in the listbox given by neworder. Items that do not +appear in neworder are no moved. + +
+
pathName see + item +
+ +Arrange the scrolling area to make item visible. + +
+
pathName selection + cmd + ?arg...? +
+ +Modifies the list of selected items following cmd: +
+
clear +
remove all items of the selection. +
set +
set the selection to all items in arg +
add +
add all items of arg in the selection +
remove +
remove all items of arg of the selection +
get +
return the current selected items +
+ +
+
pathName xview + ?arg...? +
+ +Standard command to enable horizontal scrolling of pathName. + +
+
pathName yview + ?arg...? +
+ +Standard command to enable vertical scrolling of pathName. + +
+ diff --git a/hlp/en/bwidget/MainFrame.html b/hlp/en/bwidget/MainFrame.html new file mode 100644 index 0000000..b7d6302 --- /dev/null +++ b/hlp/en/bwidget/MainFrame.html @@ -0,0 +1,283 @@ + +MainFrame + +
NAME
+
MainFrame + - Manage toplevel with menu, toolbar and statusbar +
+
+
CREATION
+
MainFrame pathName ?option value...?
+
+
+
OPTIONS from ProgressBar
+
+ + + + + + + + + + +
  -background or -bg  -progressfg (see -foreground)
  -progressmax (see -maximum)  -progresstype (see -type)
  -progressvar (see -variable)
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + +
  -height
  -menu
  -separator
  -textvariable
  -width
+
+
+
WIDGET COMMAND
+
pathName addindicator + ?arg...? +
+
pathName addtoolbar +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getframe +
+
pathName getindicator + index +
+
pathName getmenu + menuid +
+
pathName gettoolbar + index +
+
pathName setmenustate + tag + state +
+
pathName showstatusbar + name +
+
pathName showtoolbar + index + bool +
+
+


+DESCRIPTION
+

+ +MainFrame manage toplevel to have:
+

    +
  • simple menu creation, with automatic accelerator bindings and +DynamicHelp association, +
  • one or more toolbar that user can hide, +
  • a status bar, displaying a user message or a menu description, and optionnaly a +ProgressBar. +
+

+


+WIDGET-SPECIFIC OPTIONS
+
-height
+
+ +Specifies the desired height for the user frame in any of the forms acceptable to +Tk_GetPixels. If this option is less than or equal to zero (the default) then the window +will not request any size at all. +
+
+
-menu (read-only)
+
+ +This option describes the menu. This is a list whose each five elements describe +one cascad menu. It has the following form: +{menuname tags menuId tearoff menuentries...} +where menuentries is a list where each element describe one menu entry, which can be: +
    +
  • for a separator:
    + {separator} +
  • for a command:
    + {command menuname ?tags? ?description? ?accelerator? ?option value? ...} +
  • for a check button:
    + {checkbutton menuname ?tags? ?description? ?accelerator? ?option value? ...} +
  • for a radio button:
    + {radiobutton menuname ?tags? ?description? ?accelerator ?option value? ...} +
  • for a cascad menu:
    + {cascad menuname tags menuId tearoff menuentries} +
+where: +
    +
  • menuname is the name of the menu. If it contains a &, the following character +is automatically converted to the corresponding -underline option of menu add +command. +
  • tags is the tags list for the entry, used for enabling or disabling menu +entries with MainFrame::setmenustate. +
  • menuId is an id for the menu, from which you can get menu pathname with + MainFrame::getmenu. +
  • tearoff specifies if menu has tearoff entry. +
  • description specifies a string for DynamicHelp. +
  • accelerator specifies a key sequence. It is a list of two elements, where the first +is one of Ctrl, Alt or CtrlAlt, and the second as letter or a digit. +An accelerator string is build and corresponding binding set on the toplevel to invoke the +menu entry. +
  • option value specifies additionnal options for the entry (see menu add +command). +
+Each value enclosed by ? are optional and defaulted to empty string, but must be +provided if one or more following options is not empty. +
Example: +
+set descmenu {
+    "&File" {} {} 0 {
+        {command "&New"     {} "Create a new document"     {Ctrl n} -command Menu::new}
+        {command "&Open..." {} "Open an existing document" {Ctrl o} -command Menu::open}
+        {command "&Save"    open "Save the document" {Ctrl s} -command Menu::save}
+        {cascad  "&Export"  {} export 0 {
+            {command "Format &1" open "Export document to format 1" {} -command {Menu::export 1}}
+            {command "Format &2" open "Export document to format 2" {} -command {Menu::export 2}}
+        }}
+        {separator}
+        {cascad "&Recent files" {} recent 0 {}}
+        {separator}
+        {command "E&xit" {} "Exit the application" {} -command Menu::exit}
+    }
+    "&Options" {} {} 0 {
+        {checkbutton "Toolbar" {} "Show/hide toolbar" {} 
+            -variable Menu::_drawtoolbar
+            -command  {$Menu::_mainframe showtoolbar toolbar $Menu::_drawtoolbar}
+        }
+    }
+}
+
+ +
+
+
-separator (read-only)
+
+ +Specifies if separator should be drawn at the top and/or at the bottom of the user window. +Must be one of the values none, top, bottom or both. +It depends on the relief of subwidgets of user window. +
+
+
-textvariable
+
+ +Specifies the textvariable option for the label of the status bar. +DynamicHelp description +of menu entries are mapped to this variable at the creation of the MainFrame. +If this variable is changed by MainFrame::configure, menu description will +not be available. +
You change the text of the label by modifying the value of the variable. +
+
+
-width
+
+ +Specifies the desired width for the user frame in any of the forms acceptable to +Tk_GetPixels. If this option is less than or equal to zero (the default) then the window +will not request any size at all. +
+
+

+WIDGET COMMAND
+
pathName addindicator + ?arg...? +
+ +Add an indicator box at the right of the status bar. Each indicator are added from left +to right. An indicator is a Tk label widget configured with option-value pair +given by ?arg...?. -relief and -borderwidth options are respetively +defaulted to sunken and 1. Returns the pathname of the created label. +
+
pathName addtoolbar +
+ +Add a toolbar to the MainFrame. Returns the pathname of the new window where to place +toolbar items. +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName getframe +
+ +Returns the pathname of the user window. +
+
pathName getindicator + index +
+ +Returns the pathname of the indexth added indicator. +
+
pathName getmenu + menuid +
+ +Returns the pathname of the menu whose id is menuid. +
+
pathName gettoolbar + index +
+ +Returns the pathname of the indexth added toolbar. +
+
pathName setmenustate + tag + state +
+ +Set the -state option value of all the menu entries that have the tag tag +to state. + +
+
pathName showstatusbar + name +
+ +name is one of none, status or progression. +Use none to hide the status bar, status to display the label only, or +progression to display the label and the +ProgressBar. +
+
pathName showtoolbar + index + bool +
+ +Hide if bool is 0, or show if bool is 1 the indexth added toolbar. +To prevent your toplevel from resizing while hiding/showing toolbar, +do [wm geometry $top [wm geometry $top]] when it is managed. +
+ diff --git a/hlp/en/bwidget/MessageDlg.html b/hlp/en/bwidget/MessageDlg.html new file mode 100644 index 0000000..e6f51da --- /dev/null +++ b/hlp/en/bwidget/MessageDlg.html @@ -0,0 +1,208 @@ + +MessageDlg + +
NAME
+
MessageDlg + - Message dialog box +
+
+
CREATION
+
MessageDlg pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + +
  -anchor
  -font
  -foreground or -fg  -padx
  -pady
+
+
+
OPTIONS from Dialog
+
+ + + + + + + + +
  -background or -bg  -cancel
  -default  -parent
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + +
  -aspect
  -buttons
  -icon
  -justify
  -message
  -title
  -type
  -width
+
+


+DESCRIPTION
+

+ +MessageDlg provides a simple way to display a message dialog. +MessageDlg::create creates the message dialog, displays +it and return the index of the pressed button, or -1 if it is destroyed. +When returning, the dialog no longer exists. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-aspect
+
+ +Specifies a non-negative integer value indicating desired +aspect ratio for the text. The aspect ratio is specified as +100*width/height. 100 means the text should +be as wide as it is tall, 200 means the text should +be twice as wide as it is tall, 50 means the text should +be twice as tall as it is wide, and so on. +Used to choose line length for text if width option +isn't specified. +Defaults to 150. + +
+
+
-buttons
+
+ +Specifies a list of buttons to display when type option is user. +If a button has a symbolic name, its associated text will be displayed. + +
+
+
-icon
+
+ +Specifies an icon to display. Must be one of the following: error, info, +question or warning. + +
+
+
-justify
+
+ +Specifies how to justify lines of text. +Must be one of left, center, or right. Defaults +to left. +This option works together with the anchor, aspect, +padx, pady, and width options to provide a variety +of arrangements of the text within the window. +The aspect and width options determine the amount of +screen space needed to display the text. +The anchor, padx, and pady options determine where this +rectangular area is displayed within the widget's window, and the +justify option determines how each line is displayed within that +rectangular region. +For example, suppose anchor is e and justify is +left, and that the message window is much larger than needed +for the text. +The the text will displayed so that the left edges of all the lines +line up and the right edge of the longest line is padx from +the right side of the window; the entire text block will be centered +in the vertical span of the window. + +
+
+
-message
+
+ +Specifies the message to display in this message box. + +
+
+
-title
+
+ +Specifies a string to display as the title of the message box. +If the value is empty (the default), a default title will be set corresponding +to the icon option. +The default associated title is in english, and can be modified to set it in +another language by specifying the resource: +
    *MessageDlg.nameTitle:   value
+or the equivalent tcl command: +
    option add *MessageDlg.nameTitle value
+where name is the name of an icon as defined in the icon option. +
For example, for french language, you can specify for a warning dialog: +
    option add *MessageDlg.warningTitle  "Attention"
+ +
+
+
-type
+
+ +Specifies a set of buttons to be displayed. The following values are possible: +
+

+

+
+abortretryignore +
+Displays three buttons whose symbolic names are abort, +retry and ignore.

+

+ok +
+Displays one button whose symbolic name is ok.

+

+okcancel +
+Displays two buttons whose symbolic names are ok and cancel.

+

+retrycancel +
+Displays two buttons whose symbolic names are retry and cancel.

+

+yesno +
+Displays two buttons whose symbolic names are yes and no.

+

+yesnocancel +
+Displays three buttons whose symbolic names are yes, no +and cancel. +

+

+user +
+Displays buttons of -buttons option.

+

+
+ +
+
+
-width
+
+ +Specifies the length of lines in the window. +If this option has a value greater than zero then the aspect +option is ignored and the width option determines the line +length. +If this option has a value less than or equal to zero, then +the aspect option determines the line length. + +
+
+ diff --git a/hlp/en/bwidget/NoteBook.html b/hlp/en/bwidget/NoteBook.html new file mode 100644 index 0000000..bf40b36 --- /dev/null +++ b/hlp/en/bwidget/NoteBook.html @@ -0,0 +1,343 @@ + +NoteBook + +
NAME
+
NoteBook + - Notebook manager widget +
+
+
CREATION
+
NoteBook pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + +
  -font
+
+
+
OPTIONS from ArrowButton
+
+ + + + + + + + + + + + + + + + +
  -activebackground  -activeforeground
  -background or -bg  -borderwidth or -bd
  -disabledforeground  -foreground or -fg
  -repeatdelay  -repeatinterval
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + +
  -height
  -homogeneous
  -side
  -width
+
+
+
WIDGET COMMAND
+
pathName bindtabs + event + script +
+
pathName cget + option +
+
pathName compute_size +
+
pathName configure + ?option? ?value option value ...? +
+
pathName delete + page + ?destroyframe? +
+
pathName getframe + page +
+
pathName index + page +
+
pathName insert + index + page + ?option value...? +
+
pathName itemcget + page + option +
+
pathName itemconfigure + page + ?option? ?value option value ...? +
+
pathName move + page + index +
+
pathName page + first + ?last? +
+
pathName pages + ?first? + ?last? +
+
pathName raise + ?page? +
+
pathName see + page +
+
+


+DESCRIPTION
+

+ +NoteBook widget manage a set of pages and displays one of them. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-height
+
+ +Specifies the desired height for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call NoteBook::compute_size to make NoteBook larger +enough to contains the largest page. +
+
+
-homogeneous
+
+ +Specifies wether or not the label of the pages must have the same width. + +
+
+
-side (read-only)
+
+ +Specifies the side where to place the label of the pages. Must be one +of top or bottom. +Only top is implemented for the moment. + +
+
+
-width
+
+ +Specifies the desired width for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call NoteBook::compute_size to make NoteBook larger +enough to contains the largest page. +
+
+

+WIDGET COMMAND
+
pathName bindtabs + event + script +
+ +This command associates a command to execute whenever the event +sequence given by event occurs on a tabs. The page idenfier on which +the event occurs is appended to the command. + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName compute_size +
+ +This command can be called to make the NoteBook large enough to contain the largest page. +Note that if all pages use -createcmd, they will have no requested size. + +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName delete + page + ?destroyframe? +
+ +Deletes the page page. If destroyframe is 1 (the default), the frame +associated to page is destroyed. If destroyframe is 0, the frame is not +destroyed and is reused by further call to insert with the same page. + +
+
pathName getframe + page +
+ +Returns the pathname of the page page. + +
+
pathName index + page +
+ +Return the numerical index corresponding to the item. + +
+
pathName insert + index + page + ?option value...? +
+ +Insert a new page idendified by page at position index in the pages list. +index must be numeric or end. The pathname of the new page is returned. + +

+

-createcmd
+
+ +Specifies a command to be called the first time the page is raised. + +
+
+
-image
+
+ +Specifies an image to display for the page at the left of the label + +
+
+
-leavecmd
+
+ +Specifies a command to be called when a page is about to be leaved. +The command must return 0 if the page can not be leaved, or 1 if it can. + +
+
+
-raisecmd
+
+ +Specifies a command to be called each time the page is raised. + +
+
+
-state
+
+ +Specifies the state of the page. Must be normal or disabled. + +
+
+
-text
+
+ +Specifies a label to display for the page. + +
+
+
+
pathName itemcget + page + option +
+ +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
+
pathName itemconfigure + page + ?option? ?value option value ...? +
+ +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
+
pathName move + page + index +
+ +Moves page tab to index index. + +
+
pathName page + first + ?last? +
+ +Its use is deprecated. Use pages instead.
+If last is omitted, returns the page at index first, or an empty string if +first refers to a non-existent element. If last is specified, the command +returns a list whose elements are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
+
pathName pages + ?first? + ?last? +
+ +If first and last are omitted, returns the list of all pages. +If first is specified and last omitted, returns the page at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
+
pathName raise + ?page? +
+ +Raise the page page, or return the raised page if page is omitted. + +
+
pathName see + page +
+ +Scrolls labels to make the label of the page page visible. + +
+ diff --git a/hlp/en/bwidget/PagesManager.html b/hlp/en/bwidget/PagesManager.html new file mode 100644 index 0000000..33e30c4 --- /dev/null +++ b/hlp/en/bwidget/PagesManager.html @@ -0,0 +1,174 @@ + +PagesManager + +
NAME
+
PagesManager + - Pages manager widget +
+
+
CREATION
+
PagesManager pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + +
  -background
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + +
  -height
  -width
+
+
+
WIDGET COMMAND
+
pathName add + page +
+
pathName cget + option +
+
pathName compute_size +
+
pathName configure + ?option? ?value option value ...? +
+
pathName delete + page +
+
pathName getframe + page +
+
pathName page + first + ?last? +
+
pathName pages + ?first? + ?last? +
+
pathName raise + ?page? +
+
+


+DESCRIPTION
+

+ +PagesManager widget manage a set of pages and displays one of them. +PagesManager does not provide any user access method, as NoteBook does, +so it can be done through a listbox, a menu, radiobutton, or whatever. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-height
+
+ +Specifies the desired height for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call PagesManager::compute_size to make PagesManager +larger enough to contains the largest page. +
+
+
-width
+
+ +Specifies the desired width for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call PagesManager::compute_size to make PagesManager +larger enough to contains the largest page. +
+
+

+WIDGET COMMAND
+
pathName add + page +
+ +Add a new page idendified by page. The pathname of the new page +is returned. + +
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName compute_size +
+ +This command can be called to make the PagesManager large enough to contain the largest page. + +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName delete + page +
+ +Deletes the page page. + +
+
pathName getframe + page +
+ +Returns the pathname of the page page. + +
+
pathName page + first + ?last? +
+ +Its use is deprecated. Use pages instead.
+If last is omitted, returns the page at index first, or an empty string if +first refers to a non-existent element. If last is specified, the command +returns a list whose elements are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
+
pathName pages + ?first? + ?last? +
+ +If first and last are omitted, returns the list of all pages. +If first is specified and last omitted, returns the page at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
+
pathName raise + ?page? +
+ +Raise the page page, or return the raised page if page is omitted. + +
+ diff --git a/hlp/en/bwidget/PanedWindow.html b/hlp/en/bwidget/PanedWindow.html new file mode 100644 index 0000000..3db37e4 --- /dev/null +++ b/hlp/en/bwidget/PanedWindow.html @@ -0,0 +1,130 @@ + +PanedWindow + +
NAME
+
PanedWindow + - Tiled layout manager widget +
+
+
CREATION
+
PanedWindow pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + +
  -background or -bg
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + +
  -pad
  -side
  -width
+
+
+
WIDGET COMMAND
+
pathName add + ?option value...? +
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getframe + index +
+
+


+DESCRIPTION
+

+ +PanedWindow is a widget that lays out children in +a vertically or horizontally tiled format. +The user can adjust the size of the panes, with a pane control sash created +between children. +

+


+WIDGET-SPECIFIC OPTIONS
+
-pad (read-only)
+
+ +Specifies additional space between the button of the sash and children. + +
+
+
-side (read-only)
+
+ +Specifies the side of the sash, which implies the layout: top or bottom +(horizontal layout), left or right (vertical layout). +
+
+
-width (read-only)
+
+ +Specifies the width of the button of the sash. + +
+
+

+WIDGET COMMAND
+
pathName add + ?option value...? +
+ +This command add a new pane. The new pane is placed below the previous pane for vertical +layout or at right for horizontal layout. This command returns a frame where user can place +its widget. Valid options are: +

+

-minsize
+
+ +Specifies the minimum size requested for the pane. +See the grid command for more information. +
+
+
-weight
+
+ +Specifies the relative weight for apportioning any extra spaces among panes. +See the grid command for more information. +
+
+
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName getframe + index +
+ +Returns the pathname of the indexth added pane. +
+ diff --git a/hlp/en/bwidget/PasswdDlg.html b/hlp/en/bwidget/PasswdDlg.html new file mode 100644 index 0000000..3511c8e --- /dev/null +++ b/hlp/en/bwidget/PasswdDlg.html @@ -0,0 +1,214 @@ + +PasswdDlg + +
NAME
+
PasswdDlg + - Login/Password dialog box +
+
+
CREATION
+
PasswdDlg pathName ?option value...?
+
+
+
OPTIONS from Dialog
+
+ + + + + + + + + + + + + + + + + + +
  -anchor  -background or -bg
  -homogeneous  -modal
  -padx  -pady
  -parent  -spacing
  -title
+
+
+
OPTIONS from LabelEntry
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -disabledforeground  -entrybg
  -entryfg  -exportselection
  -font  -foreground or -fg
  -helptype  -highlightbackground
  -highlightcolor  -highlightthickness
  -insertbackground  -insertborderwidth
  -insertofftime  -insertontime
  -insertwidth  -labelanchor
  -labelfont  -labelheight
  -labeljustify  -labelwidth
  -loginhelptext (see -helptext)  -loginhelpvar (see -helpvar)
  -loginlabel (see -label)  -logintext (see -text)
  -logintextvariable (see -textvariable)  -loginunderline (see -underline)
  -passwdeditable (see -editable)  -passwdhelptext (see -helptext)
  -passwdhelpvar (see -helpvar)  -passwdlabel (see -label)
  -passwdstate (see -state)  -passwdtext (see -text)
  -passwdtextvariable (see -textvariable)  -passwdunderline (see -underline)
  -relief  -selectbackground
  -selectborderwidth  -selectforeground
  -wraplength
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + +
  -command
  -type
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
+


+DESCRIPTION
+

+ +PasswdDlg provides a simple way to display a login/password dialog. +PasswdDlg::create creates the dialog, displays it, and return the value of login +and password in a list, or an empty list if it is destroyed or user press cancel. +When returning, the dialog no longer exists. +
Additionnal resources can be set to modify other text: +

+    *loginName     Label for login LabelEntry
+    *passwordName  Label for password LabelEntry
+
+ +

+


+WIDGET-SPECIFIC OPTIONS
+
-command
+
+ +Specifies a command to call when user press ok button. + +
+
+
-type
+
+ +Specifies a set of buttons to be displayed. The following values are possible: +
+

+

+
+ok +
+Displays one button whose symbolic name is ok.

+

+okcancel +
+Displays two buttons whose symbolic names are ok and cancel.

+

+ +
+
+ + + +

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
+ +Stephane Lavirotte (Stephane.Lavirotte@sophia.inria.fr) + + diff --git a/hlp/en/bwidget/ProgressBar.html b/hlp/en/bwidget/ProgressBar.html new file mode 100644 index 0000000..142971c --- /dev/null +++ b/hlp/en/bwidget/ProgressBar.html @@ -0,0 +1,136 @@ + +ProgressBar + +
NAME
+
ProgressBar + - Progress indicator widget +
+
+
CREATION
+
ProgressBar pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -foreground or -fg  -orient
  -relief
  -troughcolor
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + +
  -height
  -maximum
  -type
  -variable
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
+


+DESCRIPTION
+

+ +ProgressBar widget indicates the user the progress of a lengthly operation. +It is used by MainFrame +and ProgressDlg. +

+


+WIDGET-SPECIFIC OPTIONS
+
-height
+
+ +Specifies the desired height for the progress indicator. +
+
+
-maximum
+
+ +Specifies the maximum value of the variable. + +
+
+
-type
+
+ +Specifies the type of the ProgressBar. Must be one of normal, incremental or +infinite. +
If type is normal, the progress indicator is drawn proportional +to the variable value and maximum option each time the variable is set. +
If type is incremental, the value of the progress indicator is maintained internally, +and incremented each time the variable is set by its value. The progress indicator is drawn proportional +to the internal value and maximum option. +
If type is infinite, the value of the progress indicator is maintained internally, +and incremented each time the variable is set by its value. The progress indicator grow from left to +right if internal value (modulo maximum) is less than maximum/2, and from right to left if +internal value is greater than maximum/2. +
See -variable option for special case of its value, + +
+
+
-variable
+
+ +Specifies the variable attached to the progress indicator. +Progress indicator is updated when the value of the variable changes. +If the value of the variable is negative, the progress indicator is not +displayed (it is drawn flat with background color +- usefull for ProgressDlg to make it invisible). If its value 0, progress indicator +is reinitialized. + +
+
+
-width
+
+ +Specifies the desired width for the progress indicator. +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+ diff --git a/hlp/en/bwidget/ProgressDlg.html b/hlp/en/bwidget/ProgressDlg.html new file mode 100644 index 0000000..99506e9 --- /dev/null +++ b/hlp/en/bwidget/ProgressDlg.html @@ -0,0 +1,143 @@ + +ProgressDlg + +
NAME
+
ProgressDlg + - Progress indicator dialog box +
+
+
CREATION
+
ProgressDlg pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + +
  -font
  -textvariable
+
+
+
OPTIONS from Dialog
+
+ + + + + + + + +
  -background or -bg  -parent
  -separator  -title
+
+
+
OPTIONS from ProgressBar
+
+ + + + + + + + + + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -foreground or -fg  -maximum
  -relief  -troughcolor
  -type  -variable
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + +
  -command
  -height
  -stop
  -width
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
+


+DESCRIPTION
+

+ +ProgressDlg provides a simple way to display a progress indicator dialog. +ProgressDlg::create creates the dialog, displays it, set a local +grab to it and immediatly return. The dialog is updated by modifying the +value of the variable of options -textvariable and -variable. +You have to destroy the dialog after use. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-command
+
+ +Specifies a command to call when user press stop button. + +
+
+
-height
+
+ +Specifies a desired height for the label in lines of text. + +
+
+
-stop
+
+ +Specifies the text of the button typically used to stop process. If empty, no button will +be drawn. This can be a symbolic name. + +
+
+
-width
+
+ +Specifies a desired width for the label in characters. + +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+ diff --git a/hlp/en/bwidget/ScrollView.html b/hlp/en/bwidget/ScrollView.html new file mode 100644 index 0000000..c94fc1e --- /dev/null +++ b/hlp/en/bwidget/ScrollView.html @@ -0,0 +1,130 @@ + +ScrollView + +
NAME
+
ScrollView + - Display the visible area of a scrolled window +
+
+
CREATION
+
ScrollView pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + + + +
  -background or -bg  -borderwidth or -bd
  -cursor
  -relief
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + +
  -fill
  -foreground or -fg
  -height
  -width
  -window
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
+


+DESCRIPTION
+

+ +ScrollView displays the visible area of a scrolled window within +its scroll region. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-fill
+
+ +Specifies the fill color of the rectangle. + +
+
+
-foreground
+
+ +Specifies the color of the border of the rectangle. + +
+
+
-height
+
+ +Specifies the desired height for the ScrollView. +
+
+
-width
+
+ +Specifies the desired width for the ScrollView. +
+
+
-window
+
+ +Specifies the window to view. This widget must have -xscrollcommand and +-yscrollcommand options, and respond to xview and yview command. +In order to make ScrollView working with other scrollbar, -xscrollcommand and +-yscrollcommand options of the widget must be set before the widget is passed to +the -window option of the ScrollView (for example, if the widget is handled by +a ScrolledWindow, call setwidget before setting -window option). + +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+

BINDINGS

+ +
If mouse button 1 is pressed and dragged over the ScrollView, the top left corner of +the visible area of the scrolled window is moved proportionally to the mouse displacement. +
+
If mouse button 3 is pressed over the ScrollView, the top left corner of the visible +area is proportionally set to this point. +
+ + diff --git a/hlp/en/bwidget/ScrollableFrame.html b/hlp/en/bwidget/ScrollableFrame.html new file mode 100644 index 0000000..afe7f4a --- /dev/null +++ b/hlp/en/bwidget/ScrollableFrame.html @@ -0,0 +1,191 @@ + +ScrollableFrame + +
NAME
+
ScrollableFrame + - Scrollable frame containing widget +
+
+
CREATION
+
ScrollableFrame pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + +
  -background or -bg  -xscrollcommand
  -yscrollcommand
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + + + + + + + + + + + + + +
  -areaheight
  -areawidth
  -constrainedheight
  -constrainedwidth
  -height
  -width
  -xscrollincrement
  -yscrollincrement
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getframe +
+
pathName see + widget + ?vert? + ?horz? +
+
pathName xview + ?arg...? +
+
pathName yview + ?arg...? +
+
+


+DESCRIPTION
+

+ +ScrollableFrame widget containing widget. + +

+


+WIDGET-SPECIFIC OPTIONS
+
-areaheight
+
+ +Specifies the height for the scrollable area. If zero, then the height +of the scrollable area is made just large enough to hold all its children. +
+
+
-areawidth
+
+ +Specifies the width for the scrollable area. If zero, then the width +of the scrollable area window is made just large enough to hold all its children. +
+
+
-constrainedheight
+
+ +Specifies whether or not the scrollable area should have the same height of the +scrolled window. If true, vertical scrollbar is not needed. + +
+
+
-constrainedwidth
+
+ +Specifies whether or not the scrollable area should have the same width of the +scrolled window. If true, horizontal scrollbar is not needed. + +
+
+
-height
+
+ +Specifies the desired height for the window in pixels. + +
+
+
-width
+
+ +Specifies the desired width for the window in pixels. + +
+
+
-xscrollincrement
+
+ +See xscrollincrement option of canvas widget. + +
+
+
-yscrollincrement
+
+ +See yscrollincrement option of canvas widget. + +
+
+

+WIDGET COMMAND
+
pathName cget + option +
+ +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
+
pathName configure + ?option? ?value option value ...? +
+ +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
+
pathName getframe +
+ +Return the pathname of the scrolled frame where widget should be created. + +
+
pathName see + widget + ?vert? + ?horz? +
+ +Arrange scrollable area to make widget visible in the window. +vert and horz specify which part of widget must be preferably +visible, in case where widget is too tall or too large to be entirely visible. +vert must be top (the default) or bottom, +and horz must be left (the default) or right. +If vert or horz is not a valid value, area is not scrolled in this direction. + +
+
pathName xview + ?arg...? +
+ +Standard command to enable horizontal scrolling of pathName. + +
+
pathName yview + ?arg...? +
+ +Standard command to enable vertical scrolling of pathName. + +
+ diff --git a/hlp/en/bwidget/ScrolledWindow.html b/hlp/en/bwidget/ScrolledWindow.html new file mode 100644 index 0000000..7c48ba9 --- /dev/null +++ b/hlp/en/bwidget/ScrolledWindow.html @@ -0,0 +1,115 @@ + +ScrolledWindow + +
NAME
+
ScrolledWindow + - Generic scrolled widget +
+
+
CREATION
+
ScrolledWindow pathName ?option value...?
+
+
+
STANDARD OPTIONS
+
+ + + + + + +
  -background or -bg  -borderwidth or -bd
  -relief
+
+
+
WIDGET-SPECIFIC OPTIONS
+
+ + + + +
  -auto
  -scrollbar
+
+
+
WIDGET COMMAND
+
pathName cget + option +
+
pathName configure + ?option? ?value option value ...? +
+
pathName getframe +
+
pathName setwidget + widget +
+
+


+DESCRIPTION
+

+ +ScrolledWindow enables user to create easily a widget with its scrollbar. +Scrollbars are created by ScrolledWindow and scroll commands are automatically associated to +a scrollable widget with ScrolledWindow::setwidget. +

+


+WIDGET-SPECIFIC OPTIONS
+
-auto
+
+ +Specifies the desired auto managed scrollbar: +
  • none means scrollbar are always drawn +
  • horizontal means horizontal scrollbar is drawn as needed +
  • vertical means vertical scrollbar is drawn as needed +
  • both means horizontal and vertical scrollbars are drawn as needed +
  • horizontal means horizontal scrollbar is drawn as needed +
  • +
    +
    -scrollbar (read-only)
    +
    + +Specifies the desired scrollbar: none, horizontal, vertical +or both. This option is not modifiable with ScrolledWindow::configure. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the pathname of the frame where the scrolled widget should be created. This command +is no longer needed. You can directly create the scrolled widget as the child +of pathName. +
    +
    pathName setwidget + widget +
    + +Associate widget to the the scrollbars. widget is packed +in with option expand to yes and fill to both. +widget must be a scrollable widget, i.e. have the options +xscrollcommand/yscrollcommand and the command xview/yview, +such as canvas or text. +
    + diff --git a/hlp/en/bwidget/SelectColor.html b/hlp/en/bwidget/SelectColor.html new file mode 100644 index 0000000..cf9199d --- /dev/null +++ b/hlp/en/bwidget/SelectColor.html @@ -0,0 +1,152 @@ + +SelectColor + +
    NAME
    +
    SelectColor + - Color selection widget +
    +
    +
    CREATION
    +
    SelectColor pathName ?option value...?
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + +
      -color
      -command
      -height
      -parent
      -title
      -type
      -variable
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    SelectColor::setcolor + index + color +
    +
    +


    +DESCRIPTION
    +

    + +SelectColor provides a simple way to select color. It can be displayed +as a dialog box or as a menubutton. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -color
    +
    + +Specifies the color value of the widget. + +
    +
    +
    -command
    +
    + +When type is menubutton, +specifies a command to call when user select a color. + +
    +
    +
    -height
    +
    + +When type is menubutton, specifies the desired height for the button. + +
    +
    +
    -parent
    +
    + +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
    +
    +
    -title
    +
    + +Title of the Dialog toplevel. + +
    +
    +
    -type (read-only)
    +
    + +Specifies the type of the SelectColor widget. Must be dialog or menubutton. +
    If type option is dialog, SelectColor::create directly creates the +dialog, displays it and return an empty string if cancel button is pressed or if dialog is +destroyed, and the selected color if ok button is pressed. In all cases, dialog is destroyed. +
    If type option is menubutton, SelectColor::create returns the +pathname of the widget created. It is composed of a button from which user can access a menu +displaying predefined colors. + +
    +
    +
    -variable
    +
    + +Specifies a variable to link to the color value of the widget. + +
    +
    +
    -width
    +
    + +When type is menubutton, specifies the desired width for the button. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    SelectColor::setcolor + index + color +
    + +Set the value of user predefined color at index index to color. +index must be between 1 and 5. + +
    + diff --git a/hlp/en/bwidget/SelectFont.html b/hlp/en/bwidget/SelectFont.html new file mode 100644 index 0000000..e2929a6 --- /dev/null +++ b/hlp/en/bwidget/SelectFont.html @@ -0,0 +1,132 @@ + +SelectFont + +
    NAME
    +
    SelectFont + - Font selection widget +
    +
    +
    CREATION
    +
    SelectFont pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -background or -bg  -font
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + +
      -command
      -parent
      -sampletext
      -title
      -type
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    SelectFont::loadfont +
    +
    +


    +DESCRIPTION
    +

    + +SelectFont provides a simple way to choose font. It can be displayed +as a dialog box or as a toolbar. +
    Textual items in Dialog box uses -name options so they +can be translated to any language. Symbolic name used are +ok, cancel, font, size, style, +bold, italic, underline and overstrike. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -command
    +
    + +Specifies a command to call when user select a new font when SelectFont type +option is toolbar. + +
    +
    +
    -parent
    +
    + +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
    +
    +
    -sampletext
    +
    + +Specifies the text displayed in the preview area. + +
    +
    +
    -title
    +
    + +Title of the Dialog toplevel. + +
    +
    +
    -type
    +
    + +Specifies the type of the SelectFont widget. Must be dialog or toolbar. +
    If type option is dialog, SelectFont::create directly creates the +dialog, displays it and return an empty string if cancel button is pressed or if dialog is +destroyed, and the selected font if ok button is pressed. In all cases, dialog is destroyed. +
    If type option is toolbar, SelectFont::create returns the pathname +of the widget created. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    SelectFont::loadfont +
    + +Load the font available in the system. + +
    + diff --git a/hlp/en/bwidget/Separator.html b/hlp/en/bwidget/Separator.html new file mode 100644 index 0000000..c015e0a --- /dev/null +++ b/hlp/en/bwidget/Separator.html @@ -0,0 +1,77 @@ + +Separator + +
    NAME
    +
    Separator + - 3D separator widget +
    +
    +
    CREATION
    +
    Separator pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -background or -bg  -orient
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + +
      -relief
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +Separator is a widget that display an horizontal or vertical 3-D line. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -relief
    +
    + +Specifies the relief of the Separator. Must be groove (the default) or ridge. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    + diff --git a/hlp/en/bwidget/SpinBox.html b/hlp/en/bwidget/SpinBox.html new file mode 100644 index 0000000..2c510dc --- /dev/null +++ b/hlp/en/bwidget/SpinBox.html @@ -0,0 +1,250 @@ + +SpinBox + +
    NAME
    +
    SpinBox + - SpinBox widget +
    +
    +
    CREATION
    +
    SpinBox pathName ?option value...?
    +
    +
    +
    OPTIONS from ArrowButton
    +
    + + + + + + + + + + + + +
      -background or -bg  -disabledforeground
      -foreground or -fg  -repeatdelay
      -repeatinterval  -state
    +
    +
    +
    OPTIONS from Entry
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -command  -disabledforeground
      -dragenabled  -dragendcmd
      -dragevent  -draginitcmd
      -dragtype  -dropcmd
      -dropenabled  -dropovercmd
      -droptypes  -editable
      -entrybg (see -background)  -entryfg (see -foreground)
      -exportselection  -font
      -helptext  -helptype
      -helpvar  -highlightbackground
      -highlightcolor  -highlightthickness
      -insertbackground  -insertborderwidth
      -insertofftime  -insertontime
      -insertwidth  -justify
      -selectbackground  -selectborderwidth
      -selectforeground  -show
      -state  -takefocus
      -text  -textvariable
      -width  -xscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + +
      -modifycmd
      -range
      -values
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getvalue +
    +
    pathName setvalue + index +
    +
    +


    +DESCRIPTION
    +

    + +SpinBox widget enables the user to select a value among a list given by the values +option or a set of values defined by a mininum, a maximum and an increment. +Notice that range option defines a list of values, so getvalue and +setvalue work with both values and range. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -modifycmd
    +
    + +Specifies a Tcl command called when the user modify the value of the SpinBox. +
    +
    +
    -range
    +
    + +Specifies a list of three intergers (or real) describing the minimum, maximum and increment +of the SpinBox. +
    +
    +
    -values
    +
    + +Specifies the values accepted by the SpinBox. This option takes precedence over +range option. +
    +
    +

    +WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    + +Set bindings on the entry widget. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getvalue +
    + +Returns the index of the current text of the SpinBox in the list of values, +or -1 if it doesn't match any value. + +
    +
    pathName setvalue + index +
    + +Set the text of the SpinBox to the value indicated by index in the list of values. +index may be specified in any of the following forms: +

    +

    +
    +last +
    +Specifies the last element of the list of values. +
    first +
    +Specifies the first element of the list of values. +
    +next +
    +Specifies the element following the current (ie returned by getvalue) in the list +of values. +
    previous +
    +Specifies the element preceding the current (ie returned by getvalue) in the list +of values. +
    +@number +
    +Specifies the integer index in the list of values. +
    + +
    +

    BINDINGS

    + +When Entry of the SpinBox has the input focus, it has the following bindings, in addition +to the default Entry bindings: +
      +
    • Page up set the value of the SpinBox to the last value. +
    • Page down set the value of the SpinBox to the first value. +
    • Arrow up set the value of the SpinBox to the next value. +
    • Arrow down set the value of the SpinBox to the previous value. +
    + + diff --git a/hlp/en/bwidget/TitleFrame.html b/hlp/en/bwidget/TitleFrame.html new file mode 100644 index 0000000..c1b8261 --- /dev/null +++ b/hlp/en/bwidget/TitleFrame.html @@ -0,0 +1,107 @@ + +TitleFrame + +
    NAME
    +
    TitleFrame + - Frame with a title +
    +
    +
    CREATION
    +
    TitleFrame pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -font
      -foreground or -fg
      -relief
      -text
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + +
      -baseline
      -ipad
      -side
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    +


    +DESCRIPTION
    +

    + +TitleFrame enables user to create a frame with a title like XmFrame Motif widget. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -baseline
    +
    + +Specifies the vertical alignment of the title: top, center or bottom. +
    +
    +
    -ipad
    +
    + +Specifies a pad between the border of the frame and the user frame. +The value is in screen units. +
    +
    +
    -side
    +
    + +Specifies the horizontal alignment of the title: left, center or right. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the frame where the user can create any other widget. +
    + diff --git a/hlp/en/bwidget/Tree.html b/hlp/en/bwidget/Tree.html new file mode 100644 index 0000000..6d2b3d2 --- /dev/null +++ b/hlp/en/bwidget/Tree.html @@ -0,0 +1,696 @@ + +Tree + +
    NAME
    +
    Tree + - Tree widget +
    +
    +
    CREATION
    +
    Tree pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -cursor
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -relief
      -selectbackground
      -selectforeground
      -takefocus
      -xscrollcommand
      -yscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -closecmd
      -deltax
      -deltay
      -dragenabled
      -dragendcmd
      -dragevent
      -draginitcmd
      -dragtype
      -dropcmd
      -dropenabled
      -dropovercmd
      -dropovermode
      -droptypes
      -height
      -linesfill
      -linestipple
      -opencmd
      -padx
      -redraw
      -showlines
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bindImage + event + script +
    +
    pathName bindText + event + script +
    +
    pathName cget + option +
    +
    pathName closetree + node +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName delete + ?arg...? +
    +
    pathName edit + node + text + ?verifycmd? + ?clickres? + ?select? +
    +
    pathName exists + node +
    +
    pathName index + node +
    +
    pathName insert + index + parent + node + ?option value...? +
    +
    pathName itemcget + node + option +
    +
    pathName itemconfigure + node + ?option? ?value option value ...? +
    +
    pathName move + parent + node + index +
    +
    pathName nodes + node + ?first? + ?last? +
    +
    pathName opentree + node +
    +
    pathName parent + node +
    +
    pathName reorder + node + neworder +
    +
    pathName see + node +
    +
    pathName selection + cmd + ?arg...? +
    +
    pathName visible + node +
    +
    pathName xview + ?arg...? +
    +
    pathName yview + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +Tree widget uses canvas to display a hierarchical list of items (called nodes). +Each node is composed of a label with its own font and foreground attributes, and an optional +image or window. Each node can have a list of subnodes, which can be collapsed or expanded. +Each node is drawn in a single line, whose height is defined by the +deltay option, so they must have at most this height. +A node is uniquely identified by a string given at creation (by the +insert command). The node named root is the root of +the tree and is not drawn. +The tree structure is directly maintained by the widget. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -closecmd
    +
    + +Specifies a command to be called when user close a node. The +closed node is appended to the command. + +
    +
    +
    -deltax
    +
    + +Specifies horizontal indentation between a node and its children. + +
    +
    +
    -deltay
    +
    + +Specifies vertical size of the nodes. + +
    +
    +
    -dragenabled
    +
    +A boolean specifying if drag is enabled. +
    +
    +
    -dragendcmd
    +
    + +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +Tree has a command wrapper for drag-init events. This command refused the drag +if no node is designated. In other cases: +
    If draginitcmd is empty, it returns: +
      +
    • the value of option dragtype or TREE_NODE if empty as the data type, +
    • {copy move link} as the operations, +
    • the node identifier as the data. +
    +If draginitcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the tree, +
    • the identifier of the dragged node, +
    • the toplevel created to represent dragged data. +
    +and must return a value conforming to draginitcmd option described in +DragSite::register. + +
    +
    +
    -dragtype
    +
    + +Specifies an alternate type of dragged object. + +
    +
    +
    -dropcmd
    +
    + +Tree has a command wrapper for drop events. This command stops auto scrolling +and extract node and position. +
    If dropcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the tree, +
    • the pathname of the drag source, +
    • a list describing where the drop occurs. It can be: +
        +
      • {widget}, +
      • {node node} or +
      • {position node index}. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    + + +
    +
    +
    -dropenabled
    +
    +A boolean specifying if drop is enabled. +
    +
    +
    -dropovercmd
    +
    + +Tree has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +If dropovercmd is not empty, the command is called with the following aguments: +
      +
    • the pathname of the tree, +
    • the pathname of the drag source, +
    • a list describing where the drop can occur, whose elements are: +
        +
      • the string widget if dropovertype option contains w, else empty string. +
      • the targeted node if drag icon points a node and dropovertype option contains n, else empty string. +
      • a list containing a node and the position within the children of the node where drag +icon points to if dropovertype option contains p, else empty string. +
      • optionally, the preferred method if drop can occur both inside a node and between two +nodes. The value is position or node. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    +The command must return a list with two elements: +
      +
    • the drop status, conforming to those described in dropovercmd option of +DropSite::register, +
    • the choosen method: widget, node or position. +
    + +
    +
    +
    -dropovermode
    +
    + +Specifies the type of drop-over interaction. Must be a combination of +w, which specifies that drop can occurs everywhere on widget, +p, which specifies that drop can occurs between two nodes, +and n, which specifies that drop occurs inside nodes. + +
    +
    +
    -droptypes
    +
    + +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +
    Default is TREE_NODE with operations copy and move. + +
    +
    +
    -height
    +
    + +Specifies the desired height for the tree in units of deltay pixels. + +
    +
    +
    -linesfill
    +
    + +Specifies a foreground color for the lines between nodes. + +
    +
    +
    -linestipple
    +
    + +Specifies a stipple bitmap for the lines between nodes. + +
    +
    +
    -opencmd
    +
    + +Specifies a command to be called when user open a node. The +opened node is appended to the command. + +
    +
    +
    -padx
    +
    + +Specifies distance between image or window and text of the nodes. + +
    +
    +
    -redraw
    +
    + +Specifies wether or not the tree should be redrawn when entering idle. +Set it to false if you call update while modifying the tree. + +
    +
    +
    -showlines
    +
    + +Specifies whether or not lines should be drawn between nodes. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the tree in units of 8 pixels. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName bindImage + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the image of a node. +The node idenfier on which the event occurs is appended to the command. + +
    +
    pathName bindText + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the label of a node. +The node idenfier on which the event occurs is appended to the command. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName closetree + node +
    + +This command close all the subtree given by node (recurse +through the tree starting at node and set open option to 0) + +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName delete + ?arg...? +
    + +Deletes all nodes (and children of them) in arg. arg can be a list +of nodes or a list of list of nodes. +To delete all the tree, do $pathName delete [$pathName nodes root]. + +
    +
    pathName edit + node + text + ?verifycmd? + ?clickres? + ?select? +
    + +Provides a way for the user to edit in place the label of a node. This is +possible only if node is visible (all its parents are open). +
    The command takes the initial text as argument and does not modify the label of the +edited node, but returns an empty string if edition is canceled, or the typed text +if edition is accepted. +
    When editing, the user can cancel by pressing Escape, or accept by pressing Return. +
    clickres specifies what to do if the user click outside the editable area. +If clickres is 0 (the default), the edition is canceled. +If clickres is 1, the edition is accepted. +In all other case, the edition continues. +
    If edition is accepted and modifycmd is not empty, then it is called with +the new text as argument and must return 1 to accept the new text, 0 to refuse it +and continue edition. +
    select specifies wether or not the initial text should be selected. Default is 1. + +
    +
    pathName exists + node +
    + +Returns whether or not node exists in the tree. + +
    +
    pathName index + node +
    + +Returns the position of node in its parent. + +
    +
    pathName insert + index + parent + node + ?option value...? +
    + +Inserts a new node identified by node in the children list of parent +at position index. + +

    +

    -data
    +
    + +User data associated to the node. + +
    +
    +
    -drawcross
    +
    + +Specifies how the cross used to expand or collapse the children of a node +should be drawn. +Must be one of auto, allways or never. +
    If auto, the cross is drawn only if the node has children. +If allways, the cross is always drawn. +If never, the cross is never drawn. + +
    +
    +
    -fill
    +
    + +Specifies the foreground color of the label of the node. + +
    +
    +
    -font
    +
    + +Specifies a font for the label of the node. + +
    +
    +
    -image
    +
    + +Specifies an image to display at the left of the label of the node. +window option override image. +
    +
    +
    -open
    +
    + +Specifies wether or not the children of the node should be drawn. + +
    +
    +
    -text
    +
    + +Specifies the label of the node. + +
    +
    +
    -window
    +
    + +Specifies a pathname to display at the left of the label of the node. +window option override image. +
    +
    +
    +
    pathName itemcget + node + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + node + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName move + parent + node + index +
    + +Moves node to the children list of parent at position index. +parent can not be a descendant of node. + +
    +
    pathName nodes + node + ?first? + ?last? +
    + +Returns parts of the children of node, following first and last.
    +If first and last are omitted, returns the list of all children. +If first is specified and last omitted, returns the child at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the children between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName opentree + node +
    + +This command open all the subtree given by node (recurse +through the tree starting at node and set open option to 1) + +
    +
    pathName parent + node +
    + +Returns the parent of node. + +
    +
    pathName reorder + node + neworder +
    + +Modifies the order of children of node given by neworder. Children of +node that do not appear in neworder are no moved. + +
    +
    pathName see + node +
    + +Arrange the scrolling area to make node visible. + +
    +
    pathName selection + cmd + ?arg...? +
    + +Modifies the list of selected nodes following cmd: +
    +
    clear +
    remove all nodes of the selection. +
    set +
    set the selection to all nodes in arg +
    add +
    add all nodes of arg in the selection +
    remove +
    remove all nodes of arg of the selection +
    get +
    return the current selected nodes +
    + +
    +
    pathName visible + node +
    + +Returns whether or not node is visible (all its parents are open). + +
    +
    pathName xview + ?arg...? +
    + +Standard command to enable horizontal scrolling of pathName. + +
    +
    pathName yview + ?arg...? +
    + +Standard command to enable vertical scrolling of pathName. + +
    + diff --git a/hlp/en/bwidget/Widget.html b/hlp/en/bwidget/Widget.html new file mode 100644 index 0000000..e6c0340 --- /dev/null +++ b/hlp/en/bwidget/Widget.html @@ -0,0 +1,409 @@ + +Widget + + Under construction ...
    +
    NAME
    +
    Widget + - The Widget base class +
    +
    +
    COMMAND
    +
    Widget::addmap + class + subclass + subpath + options +
    +
    Widget::bwinclude + class + subclass + subpath + ?arg...? +
    +
    Widget::cget + path + option +
    +
    Widget::configure + path + options +
    +
    Widget::declare + class + optlist +
    +
    Widget::destroy + path +
    +
    Widget::focusNext + w +
    +
    Widget::focusOK + w +
    +
    Widget::focusPrev + w +
    +
    Widget::generate-doc + dir + widgetlist +
    +
    Widget::generate-widget-doc + class + iscmd + file +
    +
    Widget::getoption + path + option +
    +
    Widget::hasChanged + path + option + pvalue +
    +
    Widget::init + class + path + options +
    +
    Widget::setoption + path + option + value +
    +
    Widget::subcget + path + subwidget +
    +
    Widget::syncoptions + class + subclass + subpath + options +
    +
    Widget::tkinclude + class + tkwidget + subpath + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +The Widget namespace handle data associated to all BWidget and provide commands +to easily define BWidget. +
    For commands can be used to define a BWidget: +tkinclude, bwinclude, declare, addmap and syncoptions. +Here is the definition of ComboBox widget: +

    +

    + + +
    +namespace eval ComboBox {
    +    # We're using ArrowButton, Entry and LabelFrame
    +    ArrowButton::use
    +    Entry::use
    +    LabelFrame::use
    +
    +    # Include resources of LabelFrame
    +    Widget::bwinclude ComboBox LabelFrame .labf \ 
    +        rename     {-text -label} \ 
    +        remove     {-focus} \ 
    +        prefix     {label -justify -width -anchor -height -font} \ 
    +        initialize {-relief sunken -borderwidth 2}
    +
    +    # Include resources of Entry
    +    Widget::bwinclude ComboBox Entry .e \ 
    +        remove {-relief -bd -borderwidth -bg -fg} \ 
    +        rename {-foreground -entryfg -background -entrybg}
    +
    +    # Declare new resources
    +    Widget::declare ComboBox {
    +        {-height      TkResource 0  0 listbox}
    +        {-values      String     "" 0}
    +        {-modifycmd   String     "" 0}
    +        {-postcommand String     "" 0}
    +    }
    +
    +    # Map resources to subwidget
    +    Widget::addmap ComboBox "" :cmd {-background {}}
    +    Widget::addmap ComboBox ArrowButton .a \ 
    +        {-foreground {} -background {} -disabledforeground {} -state {}}
    +
    +    # Synchronize subwidget options
    +    Widget::syncoptions ComboBox Entry .e {-text {}}
    +    Widget::syncoptions ComboBox LabelFrame .labf {-label -text -underline {}}
    +
    +    proc use {} {}
    +}
    +
    + +

    +

    +COMMAND
    +
    Widget::addmap + class + subclass + subpath + options +
    + +This command map some resources to subwidget. +Mapped resources automatically configure subwidget when widget is configured. +
      +
    • class is the class of the new BWidget +
    • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget) +
    • subpath is the path of the subwidget +
    • options is the list {option realres ...} of options to map to subwidget +
    +
    +
    Widget::bwinclude + class + subclass + subpath + ?arg...? +
    + +This command includes into a new BWidget the resources of another BWidget. +Arguments are: +
      +
    • class class of the new widget +
    • subclass class name of the BWidget to be included +
    • subpath path of the widget to configure when BWidget is configured +
    • options is: +
        +
      • include {option option ...} +
        list of options to include (all if not defined) +
      • remove {option option ...} +
        list of options to remove +
      • rename {option name option name ...} +
        list of options to rename +
      • prefix {prefix option option ...} +
        pefix all option by prefix +
      • initialize {option value option value ...} +
        default value of options +
      • readonly {option value option value ...} +
        new readonly flag +
    +
    +
    Widget::cget + path + option +
    + +Returns the value of option of BWidget path. cget tests the option +existence and takes care of synchronization with subwidget. +Typically called by the BWidget cget command. + +
    +
    Widget::configure + path + options +
    +Description text +
    +
    Widget::declare + class + optlist +
    + +This command declare new resources for a BWidget. +
      +
    • class is class of the new widget +
    • options is the list describing new options. Each new option is a list +{option type value ro ?args?} where: +
        +
      • option is the name of the option +
      • type is the type of the option +
      • value is the default value of the option +
      • ro is the readonly flag of the option +
      • args depends on type +
    +
    +type can be: +
    +
    +
    TkResource
    +
    +value of option denotes a resource of a Tk widget. args must be class or +{class realoption}. class is the creation command of the Tk widget, e.g. +entry. +The second form must be used if option has not the same name in Tk widget, +but realoption. +
    If value is empty, it is initialized to the default value of the Tk widget. +
    + +
    BwResource
    +
    +value of option denotes a resource of a BWidget. args must be class or +{class realoption}. class is the name of the namespace of the BWidget, e.g. +LabelFrame. +The second form must be used if option has not the same name in BWidget, +but realoption. +
    If value is empty, it is initialized to the default value of the BWidget. +
    + +
    Int
    +
    value of option is an integer. +args can be {?min? ?max?} to force it to be in a range. The test is +[expr $option>$min] && [expr $option<$max] so +if args is {0 10}, value must be beetween 0 and 10 exclude, +if args is {=0 =10} , value must be beetween 0 and 10 include. +
    + +
    Boolean
    +
    value of option is a boolean. True values can be 1, true or yes. +False values can be 0, false or no. Widget::cget always return +0 or 1. +
    + +
    Enum
    +
    +value of option is a element of a enumeration. args must be the list +of enumeration, e.g. {top left bottom right}. +
    + +
    Flag
    +
    +value of option is a combination of a set of chars. args must be a +string defining the set. +
    + +
    String
    +
    +
    value of option is any uncontrolled string. +
    + +
    Synonym
    +
    +
    option is a synonym of option args. value has no effect here. +
    + +
    +
    +
    Widget::destroy + path +
    +Description text +
    +
    Widget::focusNext + w +
    +Description text +
    +
    Widget::focusOK + w +
    +Description text +
    +
    Widget::focusPrev + w +
    +Description text +
    +
    Widget::generate-doc + dir + widgetlist +
    +Description text +
    +
    Widget::generate-widget-doc + class + iscmd + file +
    +Description text +
    +
    Widget::getoption + path + option +
    + +Returns the value of option of BWidget path. This command does not test +option existence, does not handle synonym and does not take care of synchronization with +subwidget. + +
    +
    Widget::hasChanged + path + option + pvalue +
    +Description text +
    +
    Widget::init + class + path + options +
    +Description text +
    +
    Widget::setoption + path + option + value +
    + +Set the value of option of BWidget path without option test, subwidget mapping, +synonym handling and does not set the modification flag. + +
    +
    Widget::subcget + path + subwidget +
    + +Returns the list of all option/value of BWidget path that are mapped to subwidget. + +
    +
    Widget::syncoptions + class + subclass + subpath + options +
    + +This command synchronize options value of a subwidget. +Used when an option of a subwidget is modified out of the BWidget configure command. +
      +
    • class is the class of the new BWidget +
    • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget) +
    • subpath is the path of the subwidget +
    • options is the list {option realres ...} of options to synchronize +with subwidget +
    +
    +
    Widget::tkinclude + class + tkwidget + subpath + ?arg...? +
    + +This command includes into a new BWidget the resources of a Tk widget. +Arguments are: +
      +
    • class class of the new widget +
    • tkwidger command name of the Tk widget to be included +
    • subpath path of the widget to configure when BWidget is configured +
    • options is: +
        +
      • include {option option ...} +
        list of options to include (all if not defined) +
      • remove {option option ...} +
        list of options to remove +
      • rename {option name option name ...} +
        list of options to rename +
      • prefix {prefix option option ...} +
        pefix all option by prefix +
      • initialize {option value option value ...} +
        default value of options +
      • readonly {option value option value ...} +
        new readonly flag +
    +
    + diff --git a/hlp/en/bwidget/bw.toc.html b/hlp/en/bwidget/bw.toc.html new file mode 100644 index 0000000..e6ccfdc --- /dev/null +++ b/hlp/en/bwidget/bw.toc.html @@ -0,0 +1,34 @@ +BWidget +Label
    +Entry
    +Button
    +ArrowButton
    +ProgressBar
    +ScrollView
    +Separator
    +MainFrame
    +LabelFrame
    +TitleFrame
    +ScrolledWindow
    +ScrollableFrame
    +PanedWindow
    +ButtonBox
    +PagesManager
    +NoteBook
    +Dialog
    +LabelEntry
    +ComboBox
    +SpinBox
    +Tree
    +ListBox
    +MessageDlg
    +ProgressDlg
    +PasswdDlg
    +SelectFont
    +SelectColor
    +Widget
    +DynamicHelp
    +DragSite
    +DropSite
    +BWidget
    + diff --git a/hlp/en/bwidget/navtree.html b/hlp/en/bwidget/navtree.html new file mode 100644 index 0000000..d6ca56d --- /dev/null +++ b/hlp/en/bwidget/navtree.html @@ -0,0 +1,39 @@ + +Brief description
    +Simple Widgets
    +  Label
    +  Entry
    +  Button
    +  ArrowButton
    +  ProgressBar
    +  ScrollView
    +  Separator
    +Manager Widgets
    +  MainFrame
    +  LabelFrame
    +  TitleFrame
    +  ScrolledWindow
    +  ScrollableFrame
    +  PanedWindow
    +  ButtonBox
    +  PagesManager
    +  NoteBook
    +  Dialog
    +Composite Widgets
    +  LabelEntry
    +  ComboBox
    +  SpinBox
    +  Tree
    +  ListBox
    +  MessageDlg
    +  ProgressDlg
    +  PasswdDlg
    +  SelectFont
    +  SelectColor
    +Commands Classes
    +  Widget
    +  DynamicHelp
    +  DragSite
    +  DropSite
    +  BWidget
    + diff --git a/hlp/en/bwidget/options.htm b/hlp/en/bwidget/options.htm new file mode 100644 index 0000000..0c6f494 --- /dev/null +++ b/hlp/en/bwidget/options.htm @@ -0,0 +1,449 @@ +Tk Built-In Commands - options manual page + +
    +
    NAME +
    options - Standard options supported by widgets
    +
    DESCRIPTION +
    +
    -activebackground, activeBackground, Foreground +
    -activeborderwidth, activeBorderWidth, BorderWidth +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -jump, jump, Jump +
    -justify, justify, Justify +
    -orient, orient, Orient +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -troughcolor, troughColor, Background +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    KEYWORDS +

    +

    NAME

    +options - Standard options supported by widgets +

    DESCRIPTION

    +This manual entry describes the common configuration options supported +by widgets in the Tk toolkit. Every widget does not necessarily support +every option (see the manual entries for individual widgets for a list +of the standard options supported by that widget), but if a widget does +support an option with one of the names listed below, then the option +has exactly the effect described below. +

    +In the descriptions below, ``Command-Line Name'' refers to the +switch used in class commands and configure widget commands to +set this value. For example, if an option's command-line switch is +-foreground and there exists a widget .a.b.c, then the +command +

    .a.b.c  configure  -foreground black
    +may be used to specify the value black for the option in the +the widget .a.b.c. Command-line switches may be abbreviated, +as long as the abbreviation is unambiguous. +``Database Name'' refers to the option's name in the option database (e.g. +in .Xdefaults files). ``Database Class'' refers to the option's class value +in the option database. +
    +
    Command-Line Name: -activebackground +
    Database Name: activeBackground +
    Database Class: Foreground +
    Specifies background color to use when drawing active elements. +An element (a widget or portion of a widget) is active if the +mouse cursor is positioned over the element and pressing a mouse button +will cause some action to occur. +If strict Motif compliance has been requested by setting the +tk_strictMotif variable, this option will normally be +ignored; the normal background color will be used instead. +For some elements on Windows and Macintosh systems, the active color +will only be used while mouse button 1 is pressed over the element. +

    Command-Line Name: -activeborderwidth +
    Database Name: activeBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating +the width of the 3-D border drawn around active elements. See above for +definition of active elements. +The value may have any of the forms acceptable to Tk_GetPixels. +This option is typically only available in widgets displaying more +than one element at a time (e.g. menus but not buttons). +

    Command-Line Name: -activeforeground +
    Database Name: activeForeground +
    Database Class: Background +
    Specifies foreground color to use when drawing active elements. +See above for definition of active elements. +

    Command-Line Name: -anchor +
    Database Name: anchor +
    Database Class: Anchor +
    Specifies how the information in a widget (e.g. text or a bitmap) +is to be displayed in the widget. +Must be one of the values n, ne, e, se, +s, sw, w, nw, or center. +For example, nw means display the information such that its +top-left corner is at the top-left corner of the widget. +

    Command-Line Name: -background or -bg +
    Database Name: background +
    Database Class: Background +
    Specifies the normal background color to use when displaying the +widget. +

    Command-Line Name: -bitmap +
    Database Name: bitmap +
    Database Class: Bitmap +
    Specifies a bitmap to display in the widget, in any of the forms +acceptable to Tk_GetBitmap. +The exact way in which the bitmap is displayed may be affected by +other options such as anchor or justify. +Typically, if this option is specified then it overrides other +options that specify a textual value to display in the widget; +the bitmap option may be reset to an empty string to re-enable +a text display. +In widgets that support both bitmap and image options, +image will usually override bitmap. +

    Command-Line Name: -borderwidth or -bd +
    Database Name: borderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the outside of the widget (if such a +border is being drawn; the relief option typically determines +this). The value may also be used when drawing 3-D effects in the +interior of the widget. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -cursor +
    Database Name: cursor +
    Database Class: Cursor +
    Specifies the mouse cursor to be used for the widget. +The value may have any of the forms acceptable to Tk_GetCursor. +

    Command-Line Name: -disabledforeground +
    Database Name: disabledForeground +
    Database Class: DisabledForeground +
    Specifies foreground color to use when drawing a disabled element. +If the option is specified as an empty string (which is typically the +case on monochrome displays), disabled elements are drawn with the +normal foreground color but they are dimmed by drawing them +with a stippled fill pattern. +

    Command-Line Name: -exportselection +
    Database Name: exportSelection +
    Database Class: ExportSelection +
    Specifies whether or not a selection in the widget should also be +the X selection. +The value may have any of the forms accepted by Tcl_GetBoolean, +such as true, false, 0, 1, yes, or no. +If the selection is exported, then selecting in the widget deselects +the current X selection, selecting outside the widget deselects any +widget selection, and the widget will respond to selection retrieval +requests when it has a selection. The default is usually for widgets +to export selections. +

    Command-Line Name: -font +
    Database Name: font +
    Database Class: Font +
    Specifies the font to use when drawing text inside the widget. +

    Command-Line Name: -foreground or -fg +
    Database Name: foreground +
    Database Class: Foreground +
    Specifies the normal foreground color to use when displaying the widget. +

    Command-Line Name: -highlightbackground +
    Database Name: highlightBackground +
    Database Class: HighlightBackground +
    Specifies the color to display in the traversal highlight region when +the widget does not have the input focus. +

    Command-Line Name: -highlightcolor +
    Database Name: highlightColor +
    Database Class: HighlightColor +
    Specifies the color to use for the traversal highlight rectangle that is +drawn around the widget when it has the input focus. +

    Command-Line Name: -highlightthickness +
    Database Name: highlightThickness +
    Database Class: HighlightThickness +
    Specifies a non-negative value indicating the width of the highlight +rectangle to draw around the outside of the widget when it has the +input focus. +The value may have any of the forms acceptable to Tk_GetPixels. +If the value is zero, no focus highlight is drawn around the widget. +

    Command-Line Name: -image +
    Database Name: image +
    Database Class: Image +
    Specifies an image to display in the widget, which must have been +created with the image create command. +Typically, if the image option is specified then it overrides other +options that specify a bitmap or textual value to display in the widget; +the image option may be reset to an empty string to re-enable +a bitmap or text display. +

    Command-Line Name: -insertbackground +
    Database Name: insertBackground +
    Database Class: Foreground +
    Specifies the color to use as background in the area covered by the +insertion cursor. This color will normally override either the normal +background for the widget (or the selection background if the insertion +cursor happens to fall in the selection). +

    Command-Line Name: -insertborderwidth +
    Database Name: insertBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -insertofftime +
    Database Name: insertOffTime +
    Database Class: OffTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``off'' in each blink cycle. +If this option is zero then the cursor doesn't blink: it is on +all the time. +

    Command-Line Name: -insertontime +
    Database Name: insertOnTime +
    Database Class: OnTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``on'' in each blink cycle. +

    Command-Line Name: -insertwidth +
    Database Name: insertWidth +
    Database Class: InsertWidth +
    Specifies a value indicating the total width of the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +If a border has been specified for the insertion +cursor (using the insertBorderWidth option), the border +will be drawn inside the width specified by the insertWidth +option. +

    Command-Line Name: -jump +
    Database Name: jump +
    Database Class: Jump +
    For widgets with a slider that can be dragged to adjust a value, +such as scrollbars, this option determines when +notifications are made about changes in the value. +The option's value must be a boolean of the form accepted by +Tcl_GetBoolean. +If the value is false, updates are made continuously as the +slider is dragged. +If the value is true, updates are delayed until the mouse button +is released to end the drag; at that point a single notification +is made (the value ``jumps'' rather than changing smoothly). +

    Command-Line Name: -justify +
    Database Name: justify +
    Database Class: Justify +
    When there are multiple lines of text displayed in a widget, this +option determines how the lines line up with each other. +Must be one of left, center, or right. +Left means that the lines' left edges all line up, center +means that the lines' centers are aligned, and right means +that the lines' right edges line up. +

    Command-Line Name: -orient +
    Database Name: orient +
    Database Class: Orient +
    For widgets that can lay themselves out with either a horizontal +or vertical orientation, such as scrollbars, this option specifies +which orientation should be used. Must be either horizontal +or vertical or an abbreviation of one of these. +

    Command-Line Name: -padx +
    Database Name: padX +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the X-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will +add this amount to the width it would normally need (as determined +by the width of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space to the left and/or right of what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -pady +
    Database Name: padY +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the Y-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will add +this amount to the height it would normally need (as determined by +the height of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space above and/or below what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -relief +
    Database Name: relief +
    Database Class: Relief +
    Specifies the 3-D effect desired for the widget. Acceptable +values are raised, sunken, flat, ridge, +solid, and groove. +The value +indicates how the interior of the widget should appear relative +to its exterior; for example, raised means the interior of +the widget should appear to protrude from the screen, relative to +the exterior of the widget. +

    Command-Line Name: -repeatdelay +
    Database Name: repeatDelay +
    Database Class: RepeatDelay +
    Specifies the number of milliseconds a button or key must be held +down before it begins to auto-repeat. Used, for example, on the +up- and down-arrows in scrollbars. +

    Command-Line Name: -repeatinterval +
    Database Name: repeatInterval +
    Database Class: RepeatInterval +
    Used in conjunction with repeatDelay: once auto-repeat +begins, this option determines the number of milliseconds between +auto-repeats. +

    Command-Line Name: -selectbackground +
    Database Name: selectBackground +
    Database Class: Foreground +
    Specifies the background color to use when displaying selected +items. +

    Command-Line Name: -selectborderwidth +
    Database Name: selectBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around selected items. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -selectforeground +
    Database Name: selectForeground +
    Database Class: Background +
    Specifies the foreground color to use when displaying selected +items. +

    Command-Line Name: -setgrid +
    Database Name: setGrid +
    Database Class: SetGrid +
    Specifies a boolean value that determines whether this widget controls the +resizing grid for its top-level window. +This option is typically used in text widgets, where the information +in the widget has a natural size (the size of a character) and it makes +sense for the window's dimensions to be integral numbers of these units. +These natural window sizes form a grid. +If the setGrid option is set to true then the widget will +communicate with the window manager so that when the user interactively +resizes the top-level window that contains the widget, the dimensions of +the window will be displayed to the user in grid units and the window +size will be constrained to integral numbers of grid units. +See the section GRIDDED GEOMETRY MANAGEMENT in the wm manual +entry for more details. +

    Command-Line Name: -takefocus +
    Database Name: takeFocus +
    Database Class: TakeFocus +
    Determines whether the window accepts the focus during keyboard +traversal (e.g., Tab and Shift-Tab). +Before setting the focus to a window, the traversal scripts +consult the value of the takeFocus option. +A value of 0 means that the window should be skipped entirely +during keyboard traversal. +1 means that the window should receive the input +focus as long as it is viewable (it and all of its ancestors are mapped). +An empty value for the option means that the traversal scripts make +the decision about whether or not to focus on the window: the current +algorithm is to skip the window if it is +disabled, if it has no key bindings, or if it is not viewable. +If the value has any other form, then the traversal scripts take +the value, append the name of the window to it (with a separator space), +and evaluate the resulting string as a Tcl script. +The script must return 0, 1, or an empty string: a +0 or 1 value specifies whether the window will receive +the input focus, and an empty string results in the default decision +described above. +Note: this interpretation of the option is defined entirely by +the Tcl scripts that implement traversal: the widget implementations +ignore the option entirely, so you can change its meaning if you +redefine the keyboard traversal scripts. +

    Command-Line Name: -text +
    Database Name: text +
    Database Class: Text +
    Specifies a string to be displayed inside the widget. The way in which +the string is displayed depends on the particular widget and may be +determined by other options, such as anchor or justify. +

    Command-Line Name: -textvariable +
    Database Name: textVariable +
    Database Class: Variable +
    Specifies the name of a variable. The value of the variable is a text +string to be displayed inside the widget; if the variable value changes +then the widget will automatically update itself to reflect the new value. +The way in which the string is displayed in the widget depends on the +particular widget and may be determined by other options, such as +anchor or justify. +

    Command-Line Name: -troughcolor +
    Database Name: troughColor +
    Database Class: Background +
    Specifies the color to use for the rectangular trough areas +in widgets such as scrollbars and scales. +

    Command-Line Name: -underline +
    Database Name: underline +
    Database Class: Underline +
    Specifies the integer index of a character to underline in the widget. +This option is used by the default bindings to implement keyboard +traversal for menu buttons and menu entries. +0 corresponds to the first character of the text displayed in the +widget, 1 to the next character, and so on. +

    Command-Line Name: -wraplength +
    Database Name: wrapLength +
    Database Class: WrapLength +
    For widgets that can perform word-wrapping, this option specifies +the maximum line length. +Lines that would exceed this length are wrapped onto the next line, +so that no line is longer than the specified length. +The value may be specified in any of the standard forms for +screen distances. +If this value is less than or equal to 0 then no wrapping is done: lines +will break only at newline characters in the text. +

    Command-Line Name: -xscrollcommand +
    Database Name: xScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with horizontal +scrollbars. +When the view in the widget's window changes (or +whenever anything else occurs that could change the display in a +scrollbar, such as a change in the total size of the widget's +contents), the widget will +generate a Tcl command by concatenating the scroll command and +two numbers. +Each of the numbers is a fraction between 0 and 1, which indicates +a position in the document. 0 indicates the beginning of the document, +1 indicates the end, .333 indicates a position one third the way through +the document, and so on. +The first fraction indicates the first information in the document +that is visible in the window, and the second fraction indicates +the information just after the last portion that is visible. +The command is +then passed to the Tcl interpreter for execution. Typically the +xScrollCommand option consists of the path name of a scrollbar +widget followed by ``set'', e.g. ``.x.scrollbar set'': this will cause +the scrollbar to be updated whenever the view in the window changes. +If this option is not specified, then no command will be executed. +

    Command-Line Name: -yscrollcommand +
    Database Name: yScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with vertical +scrollbars. This option is treated in the same way as the +xScrollCommand option, except that it is used for vertical +scrollbars and is provided by widgets that support vertical scrolling. +See the description of xScrollCommand for details +on how this option is used. + +
    +

    KEYWORDS

    +class, name, standard option, switch +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/projman/gpl.en b/hlp/en/projman/gpl.en new file mode 100644 index 0000000..e77696a --- /dev/null +++ b/hlp/en/projman/gpl.en @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/hlp/en/projman/pmabout.html b/hlp/en/projman/pmabout.html new file mode 100644 index 0000000..57e6c0b --- /dev/null +++ b/hlp/en/projman/pmabout.html @@ -0,0 +1,15 @@ +About Tcl/Tk Project Manager +

    Tcl/Tk Project Manager

    +

    Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru +
    Home page: http://conero.lrn.ru + +

    Tcl/Tk Project Manager is a full IDE for programming in TCL/Tk. +It includes a project and file manager, a source editor with +syntax highlighting and procedure navigation, a context-sensitive +help system, and much more. Included TkDIFF+ - compare tools and TkREGEXP - a graphical front-end to write/debug regular expression. + +
    Working an Unix (Linux tested) and Windows. + +

    © Copyright CONERO lab, 2002 + + diff --git a/hlp/en/projman/pmbegin.html b/hlp/en/projman/pmbegin.html new file mode 100644 index 0000000..6180865 --- /dev/null +++ b/hlp/en/projman/pmbegin.html @@ -0,0 +1,14 @@ +Begin work +

    Begin work with ProjMan

    +

    CREAT NEW PROJECT +

    Select "New project" for creation new project or "Open project" for opened existing project into "Projects" menu. +

    SET ACTIVE PROJECT +

    All operation with projects into ProjMan implemented only active project. +Click mouse on project name in tree for set active project. +Name of current (active) project You will see into status bar. +

    DELETING PROJECT +

    For deleting project You must select "Delete project" into "Projects" menu. +

    EDITING FILE +

    For editing file click twice on file name into tree. + + diff --git a/hlp/en/projman/pmhelp.html b/hlp/en/projman/pmhelp.html new file mode 100644 index 0000000..195c0ff --- /dev/null +++ b/hlp/en/projman/pmhelp.html @@ -0,0 +1,3 @@ +Help system +

    Help system manual

    +

    Needed translate from russian language! diff --git a/hlp/en/projman/pmkeys.html b/hlp/en/projman/pmkeys.html new file mode 100644 index 0000000..6bff41d --- /dev/null +++ b/hlp/en/projman/pmkeys.html @@ -0,0 +1,34 @@ +Hot keys +

    Hot keys

    + +

    Ctrl + A - Saved file eith different name +

    Ctrl + C - Copy selected text into clipboard. +

    Ctrl + F - Search words into text. +

    Ctrl + G - Goto line with number +

    Ctrl + J - Get procedure list +

    Ctrl + L - Get word list +

    Ctrl + M - Switch editors open tabs +

    Ctrl + N - Create new file +

    Ctrl + O - Opened existing file. +

    Ctrl + Q - Quit from Project Manager. +

    Ctrl + R - Find and replacement words into text. +

    Ctrl + S - Saved current opened file. +

    Ctrl + T - Reverses the order of the two characters to the right of the insertion cursor +

    Ctrl + U - Jump cursor on open/close bracked +

    Ctrl + V - Insert text from clipboard +

    Ctrl + W - Close current opened file. +

    Ctrl + X - Cut selected text into clipboard. +

    Ctrl + Z - Undo last operation +

    Ctrl + / - Selects the entire contents of the widget +

    Ctrl + \\ - Clears any selection in the widget +

    F1 - Execute context-sensitive help system +

    F3 - Repeat search +

    F5 - Make archive. Workined with active project only. +

    F6 - Make RPM +

    F9 - Run current project. + + + + + + diff --git a/hlp/en/projman/pmregexp.html b/hlp/en/projman/pmregexp.html new file mode 100644 index 0000000..12ab354 --- /dev/null +++ b/hlp/en/projman/pmregexp.html @@ -0,0 +1,81 @@ +VisualREGEXP +

    VisualREGEXP

    +

    Copyright (c) 2000-2001 Laurent Riesterer +
    Latest version 2.2

    + +

    ABOUT +

    VisualREGEXP helps you to design, debug or more generally work with regular +expression. As it is often difficult to write the right regexp at the first +try, this tool will show you the effect of your regexp on a sample you can +choose. +

    REQUIREMENTS +

    This program requires Tcl/Tk 8.3.0 or later. +

    HOW TO USE + +

    Launching the program +

    On Unix, use 'chmod +x ...' to make the program executable. You can then +integrate it with your Window Manager or put it into an executable path. +
    On Windows, create a shortcut and invoke the script with 'wish.exe' + +

    Design of regexps +

    To design regexp, just type the expression in the top text widget. +Press the 'Go' button to highlight the matched part of the text in the sample +text widget. + +

    To get a quickref of the regexp syntax use the menu 'View/Show regexp help'. + +

    You can specify some options using the checkboxes (please read Tcl help to +learn the meaning of these options). + +

    Recursive design of regexps + +

    Sometimes you will need more than one step to extract the information you want +from the sample. For example, imagine you want to retrieve information from +an HTML table inside an another HTML table : + + ' + + +
    + + + +
    One 1
    Two 2
    +
    Foo Bar
    + ' + +

    You cannot use one global regexp to extract the two lines "One 1" and "Two 2". +You have to use a first regexp to narrow the processed region. +Type the following regexp ']*?>(.*?)
    ' and press 'Go'. +You see now that the interessing area is shown in blue. Press the Match '1' +button which will extract the blue text (the regexp to use to get this text +is then printed on the console). +Now use '.*?' to get the information you need. + +

    Optimization of regexps + +

    When you need to match a list of words, use the menu +'Insert regexp/Make regexp' to design an optimized version of the word list. + +

    For example, the list 'aa aab ab ad' is optimized into 'a(ab?|b|d)'. + +

    Processing the sample text + +

    Use can use VisualREGEXP to perform modification of a text. +Just use the menu 'Select mode/Use replace'. You can now design a regexp to +match what you want. Then use the replace text widget to enter the substitution +you want to apply (use \0, \1, \2, ... to match the subregexp, use the color +to map the number with the matched sub-expressions). + +

    After the substitution, you can save the new text using the 'File/Save ...' +menu. You can let the program choose the end-of-line format or force them for +a specific environment (Unix, Windows, Mac). + +

    CONTACT + +

    Send your bug reports, suggestions or any feedback to: +

    +

    laurent.riesterer@free.fr
    +http://laurent.riesterer.free.fr +

    + diff --git a/hlp/en/projman/pmtkdiff.html b/hlp/en/projman/pmtkdiff.html new file mode 100644 index 0000000..a80ae7b --- /dev/null +++ b/hlp/en/projman/pmtkdiff.html @@ -0,0 +1,108 @@ +TkDIFF+ +

    TkDIFF+

    + +

    The top row contains the File, Edit, View, Mark, Merge and Help menus. The second row contains the labels which identify the contents of each text window. Below that is a toolbar which contains navigation and merge selection tools. + +

    The left-most text widget displays the contents of FILE1, the most recently checked-in revision, REV or REV1, respectively (as per the startup options described in the "On Command Line" help). The right-most widget displays the contents of FILE2, FILE or REV2, respectively. Clicking the right mouse button over either of these windows will give you a context sensitive menu with actions that will act on the window you clicked over. For example, if you click right over the right hand window and select "Edit", the file displayed on the right hand side will be loaded into a text editor. + +

    At the bottom of the display is a two line window called the "Line Comparison" window. This will show the "current line" from the left and right windows, one on top of the other. The "current line" is defined by the line that has the blinking insertion cursor, which can be set by merely clicking on any line in the display. This window may be hidden if the View menu item Show Line Comparison is deselected. +

    All difference regions (DRs) are highlighted to set them apart from the surrounding text. The current difference region, or CDR, is further set apart so that it can be correlated to its partner in the other text widget (that is, the CDR on the left matches the CDR on the right). + +

    Changing the CDR + +

    The CDR can be changed in a sequential manner by means of the Next and Previous buttons. The First and Last buttons allow you to quickly navigate to the first or last CDR, respectively. For random access to the DRs, use the dropdown listbox in the toolbar or the diff map, described below. + +

    By clicking right over a window and using the popup menu you can select Find Nearest Diff to find the diff record nearest the point where you clicked. + +

    You may also select any highlighted diff region as the current diff region by double-clicking on it. + +

    Operations + +

    1. From the File menu: + +

    The New... button displays a dialog where you may choose two files to compare. Selecting "Ok" from the dialog will diff the two files. The Recompute Diffs button recomputes the differences between the two files whose names appear at the top of the TkDiff window. The Write Report... lets you create a report file that contains the information visible in the windows. Lastly, the Exit button terminates TkDiff. + +

    2. From the Edit menu: + +

    Copy copies the currently selected text to the system clipboard. Find pops up a dialog to let you search either text window for a specified text string. Edit File 1 and Edit File 2 launch an editor on the files displayed in the left- and right-hand panes. Preferences pops up a dialog box from which display (and other) options can be +changed and saved. + +

    3. From the View menu: + +

    Show Line Numbers toggles the display of line numbers in the text widgets. If Synchronize Scrollbars is on, the left and right text widgets are synchronized i.e. scrolling one of the windows scrolls the other. If Auto Center is on, pressing the Next or Prev buttons centers the new CDR automatically. Show Diff Map toggles the display of the diff map (see below) on or off. Show Merge Preview shows or hides the merge preview (see below). Show Line Comparison toggles the display of the "line comparison" window at the bottom of the display. + +

    4. From the Mark menu: + +The Mark Current Diff creates a new toolbar button that will jump to the current diff region. The Clear Current Diff Mark will remove the toolbar mark button associated with the current diff region, if one exists. + +

    5. From the Merge menu: + +The Show Merge Window button pops up a window with the current merged version of the two files. The Write Merge File button will allow you to save the contents of that window to a file. + +

    6. From the Help menu: + +The About TkDiff button displays copyright and author information. The On GUI button generates this window. The On Command Line button displays help on the TkDiff command line options. The On Preferences button displays help on the user-settable preferences. + +

    7. From the toolbar: + +The first tool is a dropdown list of all of the differences in a standard diff-type format. You may use this list to go directly to any diff record. The Next and Previous buttons take you to the "next" and "previous" DR, respectively. The First and Last buttons take you to the "first" and "last" DR. The Center button centers the CDRs in their respective text windows. You can set Auto Center in Preferences to do this automatically for you as you navigate through the diff records. + +

    Keyboard Navigation + +

    When a text widget has the focus, you may use the following shortcut keys: +

    + f First diff + c Center current diff + l Last diff + n Next diff + p Previous diff + 1 Merge Choice 1 + 2 Merge Choice 2 + u Switch back to directories view + +

    The cursor, Home, End, PageUp and PageDown keys work as expected, adjusting the view in whichever text window has the focus. Note that if Synchronize Scrollbars is set in Preferences, both windows will scroll at the same time. + +

    Scrolling + +

    To scroll the text widgets independently, make sure Synchronize Scrollbars in Preferences is off. If it is on, scrolling any text widget scrolls all others. Scrolling does not change the current diff record (CDR). + +

    Diff Marks + +

    You can set "markers" at specific diff regions for easier navigation. To do this, click on the Set Mark button. It will create a new toolbar button that will jump back to this diff region. To clear a diff mark, go to that diff record and click on the Clear Mark button. + +

    Diff Map + +

    The diff map is a map of all the diff regions. It is shown in the middle of the main window if "Diff Map" on the View menu is on. The map is a miniature of the file's diff regions from top to bottom. Each diff region is rendered as a patch of color, Delete as red, Insert as green and Change as blue. In the case of a 3-way merge, overlap regions are marked in yellow. The height of each patch corresponds to the relative size of the diff region. A thumb lets you interact with the map as if it were a scrollbar. +All diff regions are drawn on the map even if too small to be visible. For large files with small diff regions, this may result in patches overwriting each other. + +

    Merging + +

    To merge the two files, go through the difference regions (via "Next", "Prev" or whatever other means you prefer) and select "Left" or "Right" (next to the "Merge Choice:" label) for each. Selecting "Left" means that the the left-most file's version of the difference will be used in creating the final result; choosing "Right" means that the right-most file's difference will be used. Each choice is recorded, and can be changed arbitrarily many times. To commit the final, merged result to disk, choose "Write Merge File..." from the Merge menu. + +

    Merge Preview + +

    To see a preview of the file that would be written by "Write Merge File...", select "Show Merge Window" in the View menu. A separate window is shown containing the preview. It is updated as you change merge choices. It is synchronized with the other text widgets if "Synchronize Scrollbars" is on. + +

    Credits + +

    Thanks to Wayne Throop for beta testing, and for giving valuable suggestions (and code!) along the way. Thanks (and credit) to John Heidemann for his window tags routines, which I shamelessly stole (with permission) out of his great Tk-based Solitaire game, Klondike. Thanks to D. Elson (author of tkCVS) for writing the code that extends the RCS support to include CVS. Thanks to John Brown for writing the code that extends the revision control support to SCCS. + +

    Major thanks to Warren Jones (wjones@tc.fluke.com) and Peter Brandstrom (qraprbm@era-lvk.ericsson.se) for going way above and beyond the call. Warren added support for NT and cleaned up the Unix code as well. Peter, independently, did the same thing and then added the new interface. The end result was the 2.x series... Many, many thanks to you both! + +

    Major thanks also to Bryan Oakley (boakley@vignette.com), who made the GUI even more appealing... Bryan did a ton of work, the result of which was the 3.x series. Dorothy Robinson provided helpful comments and patches for 3.x, too. Thanks, Bryan and Dorothy! + +

    Thanks to Dean Jones (dean@gallant.com) for permission to use his icons in the toolbar. + +

    Thanks to Laurent Riesterer (laurent.riesterer@free.fr) for adding support to display the differences between files in directories. + +

    Many, many thanks also to the many others who have written and provided ideas and encouragement and code since TkDiff was first released! I haven't done much coding since the 1.x series; almost every new feature that has come about since then has been the result of volunteer efforts. Thanks, folks! +

    Author +
    John M. Klassa +

    Comments + +

    Questions and comments should be sent to the TkDiff mailing list at +http://www.accurev.com/free/tkdiff. + +

    To get it, please visit: +
    http://www.gnu.org/gnulist/production/diffutils.html + diff --git a/hlp/en/projman/projman.toc.html b/hlp/en/projman/projman.toc.html new file mode 100644 index 0000000..6f20fc6 --- /dev/null +++ b/hlp/en/projman/projman.toc.html @@ -0,0 +1,12 @@ +Tcl/Tk Project Manager +About
    +Working with projman
    +Help system
    +Working with VisualREGEXP
    +Working with TkDIFF+
    +Hot keys
    +License
    + + + + diff --git a/hlp/en/tcl/Tcl.htm b/hlp/en/tcl/Tcl.htm new file mode 100644 index 0000000..f5ccb2f --- /dev/null +++ b/hlp/en/tcl/Tcl.htm @@ -0,0 +1,194 @@ +Tcl Built-In Commands - Tcl manual page +

    +
    NAME +
    Tcl - Summary of Tcl language syntax.
    +
    DESCRIPTION +
    +
    +
    $name +
    $name(index) +
    ${name} +
    +
    +
    \a +
    \b +
    \f +
    \n +
    \r +
    \t +
    \v +
    \<newline>whiteSpace +
    \\ +
    \ooo +
    \xhh +
    \uhhhh +
    +
    +

    +

    NAME

    +Tcl - Summary of Tcl language syntax. +

    DESCRIPTION

    +The following rules define the syntax and semantics of the Tcl language: +

    +

    +

    [1]
    +A Tcl script is a string containing one or more commands. +Semi-colons and newlines are command separators unless quoted as +described below. +Close brackets are command terminators during command substitution +(see below) unless quoted. +

    [2]
    +A command is evaluated in two steps. +First, the Tcl interpreter breaks the command into words +and performs substitutions as described below. +These substitutions are performed in the same way for all +commands. +The first word is used to locate a command procedure to +carry out the command, then all of the words of the command are +passed to the command procedure. +The command procedure is free to interpret each of its words +in any way it likes, such as an integer, variable name, list, +or Tcl script. +Different commands interpret their words differently. +

    [3]
    +Words of a command are separated by white space (except for +newlines, which are command separators). +

    [4]
    +If the first character of a word is double-quote (``"'') then +the word is terminated by the next double-quote character. +If semi-colons, close brackets, or white space characters +(including newlines) appear between the quotes then they are treated +as ordinary characters and included in the word. +Command substitution, variable substitution, and backslash substitution +are performed on the characters between the quotes as described below. +The double-quotes are not retained as part of the word. +

    [5]
    +If the first character of a word is an open brace (``{'') then +the word is terminated by the matching close brace (``}''). +Braces nest within the word: for each additional open +brace there must be an additional close brace (however, +if an open brace or close brace within the word is +quoted with a backslash then it is not counted in locating the +matching close brace). +No substitutions are performed on the characters between the +braces except for backslash-newline substitutions described +below, nor do semi-colons, newlines, close brackets, +or white space receive any special interpretation. +The word will consist of exactly the characters between the +outer braces, not including the braces themselves. +

    [6]
    +If a word contains an open bracket (``['') then Tcl performs +command substitution. +To do this it invokes the Tcl interpreter recursively to process +the characters following the open bracket as a Tcl script. +The script may contain any number of commands and must be terminated +by a close bracket (``]''). +The result of the script (i.e. the result of its last command) is +substituted into the word in place of the brackets and all of the +characters between them. +There may be any number of command substitutions in a single word. +Command substitution is not performed on words enclosed in braces. +

    [7]
    +If a word contains a dollar-sign (``$'') then Tcl performs variable +substitution: the dollar-sign and the following characters are +replaced in the word by the value of a variable. +Variable substitution may take any of the following forms: +

    +

    +

    $name
    +Name is the name of a scalar variable; the name is terminated +by any character that isn't a letter, digit, or underscore. +

    $name(index)
    +Name gives the name of an array variable and index gives +the name of an element within that array. +Name must contain only letters, digits, and underscores. +Command substitutions, variable substitutions, and backslash +substitutions are performed on the characters of index. +

    ${name}
    +Name is the name of a scalar variable. It may contain any +characters whatsoever except for close braces. +

    There may be any number of variable substitutions in a single word. +Variable substitution is not performed on words enclosed in braces.

    +

    +

    [8]
    +If a backslash (``\'') appears within a word then +backslash substitution occurs. +In all cases but those described below the backslash is dropped and +the following character is treated as an ordinary +character and included in the word. +This allows characters such as double quotes, close brackets, +and dollar signs to be included in words without triggering +special processing. +The following table lists the backslash sequences that are +handled specially, along with the value that replaces each sequence. +

    +

    +

    \a
    +Audible alert (bell) (0x7). +

    \b
    +Backspace (0x8). +

    \f
    +Form feed (0xc). +

    \n
    +Newline (0xa). +

    \r
    +Carriage-return (0xd). +

    \t
    +Tab (0x9). +

    \v
    +Vertical tab (0xb). +

    \<newline>whiteSpace
    +A single space character replaces the backslash, newline, and all spaces +and tabs after the newline. This backslash sequence is unique in that it +is replaced in a separate pre-pass before the command is actually parsed. +This means that it will be replaced even when it occurs between braces, +and the resulting space will be treated as a word separator if it isn't +in braces or quotes. +

    \\
    +Backslash (``\''). +

    \ooo
    +The digits ooo (one, two, or three of them) give an eight-bit octal +value for the Unicode character that will be inserted. The upper bits of the +Unicode character will be 0. +

    \xhh
    +The hexadecimal digits hh give an eight-bit hexadecimal value for the +Unicode character that will be inserted. Any number of hexadecimal digits +may be present; however, all but the last two are ignored (the result is +always a one-byte quantity). The upper bits of the Unicode character will +be 0. +

    \uhhhh
    +The hexadecimal digits hhhh (one, two, three, or four of them) give a +sixteen-bit hexadecimal value for the Unicode character that will be +inserted. +

    Backslash substitution is not performed on words enclosed in braces, +except for backslash-newline as described above.

    +

    +

    [9]
    +If a hash character (``#'') appears at a point where Tcl is +expecting the first character of the first word of a command, +then the hash character and the characters that follow it, up +through the next newline, are treated as a comment and ignored. +The comment character only has significance when it appears +at the beginning of a command. +

    [10]
    +Each character is processed exactly once by the Tcl interpreter +as part of creating the words of a command. +For example, if variable substitution occurs then no further +substitutions are performed on the value of the variable; the +value is inserted into the word verbatim. +If command substitution occurs then the nested command is +processed entirely by the recursive call to the Tcl interpreter; +no substitutions are performed before making the recursive +call and no additional substitutions are performed on the result +of the nested script. +

    [11]
    +Substitutions do not affect the word boundaries of a command. +For example, during variable substitution the entire value of +the variable becomes part of a single word, even if the variable's +value contains spaces. +

    +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/after.htm b/hlp/en/tcl/after.htm new file mode 100644 index 0000000..08551db --- /dev/null +++ b/hlp/en/tcl/after.htm @@ -0,0 +1,114 @@ +Tcl Built-In Commands - after manual page +
    +
    NAME +
    after - Execute a command after a time delay
    +
    SYNOPSIS +
    +
    after ms +
    after ms ?script script script ...? +
    after cancel id +
    after cancel script script script ... +
    after idle ?script script script ...? +
    after info ?id? +
    +
    DESCRIPTION +
    +
    after ms +
    after ms ?script script script ...? +
    after cancel id +
    after cancel script script ... +
    after idle script ?script script ...? +
    after info ?id? +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +after - Execute a command after a time delay +

    SYNOPSIS

    +after ms
    +after ms ?script script script ...?
    +after cancel id
    +after cancel script script script ...
    +after idle ?script script script ...?
    +after info ?id?
    +

    DESCRIPTION

    +This command is used to delay execution of the program or to execute +a command in background sometime in the future. It has several forms, +depending on the first argument to the command: +

    +

    +

    after ms
    +Ms must be an integer giving a time in milliseconds. +The command sleeps for ms milliseconds and then returns. +While the command is sleeping the application does not respond to +events. +

    after ms ?script script script ...?
    +In this form the command returns immediately, but it arranges +for a Tcl command to be executed ms milliseconds later as an +event handler. +The command will be executed exactly once, at the given time. +The delayed command is formed by concatenating all the script +arguments in the same fashion as the concat command. +The command will be executed at global level (outside the context +of any Tcl procedure). +If an error occurs while executing the delayed command then the +bgerror mechanism is used to report the error. +The after command returns an identifier that can be used +to cancel the delayed command using after cancel. +

    after cancel id
    +Cancels the execution of a delayed command that +was previously scheduled. +Id indicates which command should be canceled; it must have +been the return value from a previous after command. +If the command given by id has already been executed then +the after cancel command has no effect. +

    after cancel script script ...
    +This command also cancels the execution of a delayed command. +The script arguments are concatenated together with space +separators (just as in the concat command). +If there is a pending command that matches the string, it is +cancelled and will never be executed; if no such command is +currently pending then the after cancel command has no effect. +

    after idle script ?script script ...?
    +Concatenates the script arguments together with space +separators (just as in the concat command), and arranges +for the resulting script to be evaluated later as an idle callback. +The script will be run exactly once, the next time the event +loop is entered and there are no events to process. +The command returns an identifier that can be used +to cancel the delayed command using after cancel. +If an error occurs while executing the script then the +bgerror mechanism is used to report the error. +

    after info ?id?
    +This command returns information about existing event handlers. +If no id argument is supplied, the command returns +a list of the identifiers for all existing +event handlers created by the after command for this +interpreter. +If id is supplied, it specifies an existing handler; +id must have been the return value from some previous call +to after and it must not have triggered yet or been cancelled. +In this case the command returns a list with two elements. +The first element of the list is the script associated +with id, and the second element is either +idle or timer to indicate what kind of event +handler it is. +

    +

    +The after ms and after idle forms of the command +assume that the application is event driven: the delayed commands +will not be executed unless the application enters the event loop. +In applications that are not normally event-driven, such as +tclsh, the event loop can be entered with the vwait +and update commands. + +

    SEE ALSO

    +bgerror, concat, update, vwait +

    KEYWORDS

    +cancel, delay, idle callback, sleep, time +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/append.htm b/hlp/en/tcl/append.htm new file mode 100644 index 0000000..923cfa5 --- /dev/null +++ b/hlp/en/tcl/append.htm @@ -0,0 +1,24 @@ +Built-In Commands - append manual page +

    NAME

    +append - Append to variable +

    SYNOPSIS

    +append varName ?value value value ...?
    +

    DESCRIPTION

    +Append all of the value arguments to the current value +of variable varName. If varName doesn't exist, +it is given a value equal to the concatenation of all the +value arguments. +This command provides an efficient way to build up long +variables incrementally. +For example, ``append a $b'' is much more efficient than +``set a $a$b'' if $a is long. + +

    SEE ALSO

    +concat, lappend +

    KEYWORDS

    +append, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/array.htm b/hlp/en/tcl/array.htm new file mode 100644 index 0000000..8aa2ecb --- /dev/null +++ b/hlp/en/tcl/array.htm @@ -0,0 +1,128 @@ +Tcl Built-In Commands - array manual page +
    +
    NAME +
    array - Manipulate array variables
    +
    SYNOPSIS +
    +
    array option arrayName ?arg arg ...? +
    +
    DESCRIPTION +
    +
    array anymore arrayName searchId +
    array donesearch arrayName searchId +
    array exists arrayName +
    array get arrayName ?pattern? +
    array names arrayName ?pattern? +
    array nextelement arrayName searchId +
    array set arrayName list +
    array size arrayName +
    array startsearch arrayName +
    array unset arrayName ?pattern? +
    +
    KEYWORDS +

    +

    NAME

    +array - Manipulate array variables +

    SYNOPSIS

    +array option arrayName ?arg arg ...?
    +

    DESCRIPTION

    +This command performs one of several operations on the +variable given by arrayName. +Unless otherwise specified for individual commands below, +arrayName must be the name of an existing array variable. +The option argument determines what action is carried +out by the command. +The legal options (which may be abbreviated) are: +

    +

    +

    array anymore arrayName searchId
    +Returns 1 if there are any more elements left to be processed +in an array search, 0 if all elements have already been +returned. +SearchId indicates which search on arrayName to +check, and must have been the return value from a previous +invocation of array startsearch. +This option is particularly useful if an array has an element +with an empty name, since the return value from +array nextelement won't indicate whether the search +has been completed. +

    array donesearch arrayName searchId
    +This command terminates an array search and destroys all the +state associated with that search. SearchId indicates +which search on arrayName to destroy, and must have +been the return value from a previous invocation of +array startsearch. Returns an empty string. +

    array exists arrayName
    +Returns 1 if arrayName is an array variable, 0 if there +is no variable by that name or if it is a scalar variable. +

    array get arrayName ?pattern?
    +Returns a list containing pairs of elements. The first +element in each pair is the name of an element in arrayName +and the second element of each pair is the value of the +array element. The order of the pairs is undefined. +If pattern is not specified, then all of the elements of the +array are included in the result. +If pattern is specified, then only those elements whose names +match pattern (using the matching rules of +string match) are included. +If arrayName isn't the name of an array variable, or if +the array contains no elements, then an empty list is returned. +

    array names arrayName ?pattern?
    +Returns a list containing the names of all of the elements in +the array that match pattern (using the matching +rules of string match). +If pattern is omitted then the command returns all of +the element names in the array. +If there are no (matching) elements in the array, or if arrayName +isn't the name of an array variable, then an empty string is +returned. +

    array nextelement arrayName searchId
    +Returns the name of the next element in arrayName, or +an empty string if all elements of arrayName have +already been returned in this search. The searchId +argument identifies the search, and must have +been the return value of an array startsearch command. +Warning: if elements are added to or deleted from the array, +then all searches are automatically terminated just as if +array donesearch had been invoked; this will cause +array nextelement operations to fail for those searches. +

    array set arrayName list
    +Sets the values of one or more elements in arrayName. +list must have a form like that returned by array get, +consisting of an even number of elements. +Each odd-numbered element in list is treated as an element +name within arrayName, and the following element in list +is used as a new value for that array element. +If the variable arrayName does not already exist +and list is empty, +arrayName is created with an empty array value. +

    array size arrayName
    +Returns a decimal string giving the number of elements in the +array. +If arrayName isn't the name of an array then 0 is returned. +

    array startsearch arrayName
    +This command initializes an element-by-element search through the +array given by arrayName, such that invocations of the +array nextelement command will return the names of the +individual elements in the array. +When the search has been completed, the array donesearch +command should be invoked. +The return value is a +search identifier that must be used in array nextelement +and array donesearch commands; it allows multiple +searches to be underway simultaneously for the same array. +

    array unset arrayName ?pattern?
    +Unsets all of the elements in the array that match pattern (using the +matching rules of string match). If arrayName isn't the name +of an array variable or there are no matching elements in the array, then +an empty string is returned. If pattern is omitted and is it an +array variable, then the command unsets the entire array. + +

    +

    KEYWORDS

    +array, element names, search +
    +Copyright © 1993-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/bgerror.htm b/hlp/en/tcl/bgerror.htm new file mode 100644 index 0000000..89af49d --- /dev/null +++ b/hlp/en/tcl/bgerror.htm @@ -0,0 +1,68 @@ +Tcl Built-In Commands - bgerror manual page +

    NAME

    +bgerror - Command invoked to process background errors +

    SYNOPSIS

    +bgerror message
    +

    DESCRIPTION

    +The bgerror command doesn't exist as built-in part of Tcl. Instead, +individual applications or users can define a bgerror +command (e.g. as a Tcl procedure) if they wish to handle background +errors. +

    +A background error is one that occurs in an event handler or some +other command that didn't originate with the application. +For example, if an error occurs while executing a command specified +with the after command, then it is a background error. +For a non-background error, the error can simply be returned up +through nested Tcl command evaluations until it reaches the top-level +code in the application; then the application can report the error +in whatever way it wishes. When a background error occurs, the +unwinding ends in the Tcl library and there is no obvious way for Tcl +to report the error. +

    +When Tcl detects a background error, it saves information about the +error and invokes the bgerror command later as an idle event +handler. Before invoking bgerror, Tcl restores the +errorInfo and errorCode variables to their values at the +time the error occurred, then it invokes bgerror with the error +message as its only argument. Tcl assumes that the application has +implemented the bgerror command, and that the command will +report the error in a way that makes sense for the application. Tcl +will ignore any result returned by the bgerror command as long +as no error is generated. +

    +If another Tcl error occurs within the bgerror command (for +example, because no bgerror command has been defined) then Tcl +reports the error itself by writing a message to stderr. +

    +If several background errors accumulate before bgerror is +invoked to process them, bgerror will be invoked once for each +error, in the order they occurred. However, if bgerror returns +with a break exception, then any remaining errors are skipped without +calling bgerror. +

    +Tcl has no default implementation for bgerror. However, in +applications using Tk there is a default bgerror procedure which +posts a dialog box containing the error message and offers the user a +chance to see a stack trace showing where the error occurred. In +addition to allowing the user to view the stack trace, the dialog +provides an additional application configurable button which may be +used, for example, to save the stack trace to a file. By default, +this is the behavior associated with that button. This behavior can +be redefined by setting the option database values +*ErrorDialog.function.text, to specify the caption for the +function button, and *ErrorDialog.function.command, to specify +the command to be run. The text of the stack trace is appended to the +command when it is evaluated. If either of these options is set to +the empty string, then the additional button will not be displayed in +the dialog. + +

    SEE ALSO

    +after, tclvars +

    KEYWORDS

    +background error, reporting +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/binary.htm b/hlp/en/tcl/binary.htm new file mode 100644 index 0000000..d3375fb --- /dev/null +++ b/hlp/en/tcl/binary.htm @@ -0,0 +1,451 @@ +Tcl Built-In Commands - binary manual page +
    +
    NAME +
    binary - Insert and extract fields from binary strings
    +
    SYNOPSIS +
    +
    binary format formatString ?arg arg ...? +
    binary scan string formatString ?varName varName ...? +
    +
    DESCRIPTION +
    BINARY FORMAT +
    +
    a +
    A +
    b +
    B +
    h +
    H +
    c +
    s +
    S +
    i +
    I +
    f +
    d +
    x +
    X +
    @ +
    +
    BINARY SCAN +
    +
    a +
    A +
    b +
    B +
    h +
    H +
    c +
    s +
    S +
    i +
    I +
    f +
    d +
    x +
    X +
    @ +
    +
    PLATFORM ISSUES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +binary - Insert and extract fields from binary strings +

    SYNOPSIS

    +binary format formatString ?arg arg ...?
    +binary scan string formatString ?varName varName ...?
    +

    DESCRIPTION

    +This command provides facilities for manipulating binary data. The +first form, binary format, creates a binary string from normal +Tcl values. For example, given the values 16 and 22, on a 32 bit +architecture, it might produce an 8-byte binary string consisting of +two 4-byte integers, one for each of the numbers. The second form of +the command, binary scan, does the opposite: it extracts data +from a binary string and returns it as ordinary Tcl string values. + +

    BINARY FORMAT

    +The binary format command generates a binary string whose layout +is specified by the formatString and whose contents come from +the additional arguments. The resulting binary value is returned. +

    +The formatString consists of a sequence of zero or more field +specifiers separated by zero or more spaces. Each field specifier is +a single type character followed by an optional numeric count. +Most field specifiers consume one argument to obtain the value to be +formatted. The type character specifies how the value is to be +formatted. The count typically indicates how many items of the +specified type are taken from the value. If present, the count +is a non-negative decimal integer or *, which normally indicates +that all of the items in the value are to be used. If the number of +arguments does not match the number of fields in the format string +that consume arguments, then an error is generated. +

    +Each type-count pair moves an imaginary cursor through the binary +data, storing bytes at the current position and advancing the cursor +to just after the last byte stored. The cursor is initially at +position 0 at the beginning of the data. The type may be any one of +the following characters: +

    +

    +

    a
    +Stores a character string of length count in the output string. +If arg has fewer than count bytes, then additional zero +bytes are used to pad out the field. If arg is longer than the +specified length, the extra characters will be ignored. If +count is *, then all of the bytes in arg will be +formatted. If count is omitted, then one character will be +formatted. For example, +
    binary format a7a*a alpha bravo charlie
    +will return a string equivalent to alpha\000\000bravoc. +

    A
    +This form is the same as a except that spaces are used for +padding instead of nulls. For example, +
    binary format A6A*A alpha bravo charlie
    +will return alpha bravoc. +

    b
    +Stores a string of count binary digits in low-to-high order +within each byte in the output string. Arg must contain a +sequence of 1 and 0 characters. The resulting bytes are +emitted in first to last order with the bits being formatted in +low-to-high order within each byte. If arg has fewer than +count digits, then zeros will be used for the remaining bits. +If arg has more than the specified number of digits, the extra +digits will be ignored. If count is *, then all of the +digits in arg will be formatted. If count is omitted, +then one digit will be formatted. If the number of bits formatted +does not end at a byte boundary, the remaining bits of the last byte +will be zeros. For example, +
    binary format b5b* 11100 111000011010
    +will return a string equivalent to \x07\x87\x05. +

    B
    +This form is the same as b except that the bits are stored in +high-to-low order within each byte. For example, +
    binary format B5B* 11100 111000011010
    +will return a string equivalent to \xe0\xe1\xa0. +

    h
    +Stores a string of count hexadecimal digits in low-to-high +within each byte in the output string. Arg must contain a +sequence of characters in the set ``0123456789abcdefABCDEF''. The +resulting bytes are emitted in first to last order with the hex digits +being formatted in low-to-high order within each byte. If arg +has fewer than count digits, then zeros will be used for the +remaining digits. If arg has more than the specified number of +digits, the extra digits will be ignored. If count is +*, then all of the digits in arg will be formatted. If +count is omitted, then one digit will be formatted. If the +number of digits formatted does not end at a byte boundary, the +remaining bits of the last byte will be zeros. For example, +
    binary format h3h* AB def
    +will return a string equivalent to \xba\x00\xed\x0f. +

    H
    +This form is the same as h except that the digits are stored in +high-to-low order within each byte. For example, +
    binary format H3H* ab DEF
    +will return a string equivalent to \xab\x00\xde\xf0. +

    c
    +Stores one or more 8-bit integer values in the output string. If no +count is specified, then arg must consist of an integer +value; otherwise arg must consist of a list containing at least +count integer elements. The low-order 8 bits of each integer +are stored as a one-byte value at the cursor position. If count +is *, then all of the integers in the list are formatted. If +the number of elements in the list is fewer than count, then an +error is generated. If the number of elements in the list is greater +than count, then the extra elements are ignored. For example, +
    binary format c3cc* {3 -3 128 1} 260 {2 5}
    +will return a string equivalent to +\x03\xfd\x80\x04\x02\x05, whereas +
    binary format c {2 5}
    +will generate an error. +

    s
    +This form is the same as c except that it stores one or more +16-bit integers in little-endian byte order in the output string. The +low-order 16-bits of each integer are stored as a two-byte value at +the cursor position with the least significant byte stored first. For +example, +
    binary format s3 {3 -3 258 1}
    +will return a string equivalent to +\x03\x00\xfd\xff\x02\x01. +

    S
    +This form is the same as s except that it stores one or more +16-bit integers in big-endian byte order in the output string. For +example, +
    binary format S3 {3 -3 258 1}
    +will return a string equivalent to +\x00\x03\xff\xfd\x01\x02. +

    i
    +This form is the same as c except that it stores one or more +32-bit integers in little-endian byte order in the output string. The +low-order 32-bits of each integer are stored as a four-byte value at +the cursor position with the least significant byte stored first. For +example, +
    binary format i3 {3 -3 65536 1}
    +will return a string equivalent to +\x03\x00\x00\x00\xfd\xff\xff\xff\x00\x00\x01\x00 +

    I
    +This form is the same as i except that it stores one or more one +or more 32-bit integers in big-endian byte order in the output string. +For example, +
    binary format I3 {3 -3 65536 1}
    +will return a string equivalent to +\x00\x00\x00\x03\xff\xff\xff\xfd\x00\x01\x00\x00 +

    f
    +This form is the same as c except that it stores one or more one +or more single-precision floating in the machine's native +representation in the output string. This representation is not +portable across architectures, so it should not be used to communicate +floating point numbers across the network. The size of a floating +point number may vary across architectures, so the number of bytes +that are generated may vary. If the value overflows the +machine's native representation, then the value of FLT_MAX +as defined by the system will be used instead. Because Tcl uses +double-precision floating-point numbers internally, there may be some +loss of precision in the conversion to single-precision. For example, +on a Windows system running on an Intel Pentium processor, +
    binary format f2 {1.6 3.4}
    +will return a string equivalent to +\xcd\xcc\xcc\x3f\x9a\x99\x59\x40. +

    d
    +This form is the same as f except that it stores one or more one +or more double-precision floating in the machine's native +representation in the output string. For example, on a +Windows system running on an Intel Pentium processor, +
    binary format d1 {1.6}
    +will return a string equivalent to +\x9a\x99\x99\x99\x99\x99\xf9\x3f. +

    x
    +Stores count null bytes in the output string. If count is +not specified, stores one null byte. If count is *, +generates an error. This type does not consume an argument. For +example, +
    binary format a3xa3x2a3 abc def ghi
    +will return a string equivalent to abc\000def\000\000ghi. +

    X
    +Moves the cursor back count bytes in the output string. If +count is * or is larger than the current cursor position, +then the cursor is positioned at location 0 so that the next byte +stored will be the first byte in the result string. If count is +omitted then the cursor is moved back one byte. This type does not +consume an argument. For example, +
    binary format a3X*a3X2a3 abc def ghi
    +will return dghi. +

    @
    +Moves the cursor to the absolute location in the output string +specified by count. Position 0 refers to the first byte in the +output string. If count refers to a position beyond the last +byte stored so far, then null bytes will be placed in the unitialized +locations and the cursor will be placed at the specified location. If +count is *, then the cursor is moved to the current end of +the output string. If count is omitted, then an error will be +generated. This type does not consume an argument. For example, +
    binary format a5@2a1@*a3@10a1 abcde f ghi j
    +will return abfdeghi\000\000j. +

    +

    BINARY SCAN

    +The binary scan command parses fields from a binary string, +returning the number of conversions performed. String gives the +input to be parsed and formatString indicates how to parse it. +Each varName gives the name of a variable; when a field is +scanned from string the result is assigned to the corresponding +variable. +

    +As with binary format, the formatString consists of a +sequence of zero or more field specifiers separated by zero or more +spaces. Each field specifier is a single type character followed by +an optional numeric count. Most field specifiers consume one +argument to obtain the variable into which the scanned values should +be placed. The type character specifies how the binary data is to be +interpreted. The count typically indicates how many items of +the specified type are taken from the data. If present, the +count is a non-negative decimal integer or *, which +normally indicates that all of the remaining items in the data are to +be used. If there are not enough bytes left after the current cursor +position to satisfy the current field specifier, then the +corresponding variable is left untouched and binary scan returns +immediately with the number of variables that were set. If there are +not enough arguments for all of the fields in the format string that +consume arguments, then an error is generated. +

    +It is important to note that the c, s, and S +(and i and I on 64bit systems) will be scanned into +long data size values. In doing this, values that have their high +bit set (0x80 for chars, 0x8000 for shorts, 0x80000000 for ints), +will be sign extended. Thus the following will occur: +

    set signShort [binary format s1 0x8000]
    +binary scan $signShort s1 val; # val == 0xFFFF8000
    +If you want to produce an unsigned value, then you can mask the return +value to the desired size. For example, to produce an unsigned short +value: +
    set val [expr {$val & 0xFFFF}]; # val == 0x8000
    +

    +Each type-count pair moves an imaginary cursor through the binary data, +reading bytes from the current position. The cursor is initially +at position 0 at the beginning of the data. The type may be any one of +the following characters: +

    +

    +

    a
    +The data is a character string of length count. If count +is *, then all of the remaining bytes in string will be +scanned into the variable. If count is omitted, then one +character will be scanned. For example, +
    binary scan abcde\000fghi a6a10 var1 var2
    +will return 1 with the string equivalent to abcde\000 +stored in var1 and var2 left unmodified. +

    A
    +This form is the same as a, except trailing blanks and nulls are stripped from +the scanned value before it is stored in the variable. For example, +
    binary scan "abc efghi  \000" A* var1
    +will return 1 with abc efghi stored in var1. +

    b
    +The data is turned into a string of count binary digits in +low-to-high order represented as a sequence of ``1'' and ``0'' +characters. The data bytes are scanned in first to last order with +the bits being taken in low-to-high order within each byte. Any extra +bits in the last byte are ignored. If count is *, then +all of the remaining bits in string will be scanned. If +count is omitted, then one bit will be scanned. For example, +
    binary scan \x07\x87\x05 b5b* var1 var2
    +will return 2 with 11100 stored in var1 and +1110000110100000 stored in var2. +

    B
    +This form is the same as b, except the bits are taken in +high-to-low order within each byte. For example, +
    binary scan \x70\x87\x05 B5B* var1 var2
    +will return 2 with 01110 stored in var1 and +1000011100000101 stored in var2. +

    h
    +The data is turned into a string of count hexadecimal digits in +low-to-high order represented as a sequence of characters in the set +``0123456789abcdef''. The data bytes are scanned in first to last +order with the hex digits being taken in low-to-high order within each +byte. Any extra bits in the last byte are ignored. If count +is *, then all of the remaining hex digits in string will be +scanned. If count is omitted, then one hex digit will be +scanned. For example, +
    binary scan \x07\x86\x05 h3h* var1 var2
    +will return 2 with 706 stored in var1 and +50 stored in var2. +

    H
    +This form is the same as h, except the digits are taken in +high-to-low order within each byte. For example, +
    binary scan \x07\x86\x05 H3H* var1 var2
    +will return 2 with 078 stored in var1 and +05 stored in var2. +

    c
    +The data is turned into count 8-bit signed integers and stored +in the corresponding variable as a list. If count is *, +then all of the remaining bytes in string will be scanned. If +count is omitted, then one 8-bit integer will be scanned. For +example, +
    binary scan \x07\x86\x05 c2c* var1 var2
    +will return 2 with 7 -122 stored in var1 and 5 +stored in var2. Note that the integers returned are signed, but +they can be converted to unsigned 8-bit quantities using an expression +like: +
    expr ( $num + 0x100 ) % 0x100
    +

    s
    +The data is interpreted as count 16-bit signed integers +represented in little-endian byte order. The integers are stored in +the corresponding variable as a list. If count is *, then +all of the remaining bytes in string will be scanned. If +count is omitted, then one 16-bit integer will be scanned. For +example, +
    binary scan \x05\x00\x07\x00\xf0\xff s2s* var1 var2
    +will return 2 with 5 7 stored in var1 and -16 +stored in var2. Note that the integers returned are signed, but +they can be converted to unsigned 16-bit quantities using an expression +like: +
    expr ( $num + 0x10000 ) % 0x10000
    +

    S
    +This form is the same as s except that the data is interpreted +as count 16-bit signed integers represented in big-endian byte +order. For example, +
    binary scan \x00\x05\x00\x07\xff\xf0 S2S* var1 var2
    +will return 2 with 5 7 stored in var1 and -16 +stored in var2. +

    i
    +The data is interpreted as count 32-bit signed integers +represented in little-endian byte order. The integers are stored in +the corresponding variable as a list. If count is *, then +all of the remaining bytes in string will be scanned. If +count is omitted, then one 32-bit integer will be scanned. For +example, +
    binary scan \x05\x00\x00\x00\x07\x00\x00\x00\xf0\xff\xff\xff i2i* var1 var2
    +will return 2 with 5 7 stored in var1 and -16 +stored in var2. Note that the integers returned are signed and +cannot be represented by Tcl as unsigned values. +

    I
    +This form is the same as I except that the data is interpreted +as count 32-bit signed integers represented in big-endian byte +order. For example, +
    binary \x00\x00\x00\x05\x00\x00\x00\x07\xff\xff\xff\xf0 I2I* var1 var2
    +will return 2 with 5 7 stored in var1 and -16 +stored in var2. +

    f
    +The data is interpreted as count single-precision floating point +numbers in the machine's native representation. The floating point +numbers are stored in the corresponding variable as a list. If +count is *, then all of the remaining bytes in +string will be scanned. If count is omitted, then one +single-precision floating point number will be scanned. The size of a +floating point number may vary across architectures, so the number of +bytes that are scanned may vary. If the data does not represent a +valid floating point number, the resulting value is undefined and +compiler dependent. For example, on a Windows system running on an +Intel Pentium processor, +
    binary scan \x3f\xcc\xcc\xcd f var1
    +will return 1 with 1.6000000238418579 stored in +var1. +

    d
    +This form is the same as f except that the data is interpreted +as count double-precision floating point numbers in the +machine's native representation. For example, on a Windows system +running on an Intel Pentium processor, +
    binary scan \x9a\x99\x99\x99\x99\x99\xf9\x3f d var1
    +will return 1 with 1.6000000000000001 +stored in var1. +

    x
    +Moves the cursor forward count bytes in string. If +count is * or is larger than the number of bytes after the +current cursor cursor position, then the cursor is positioned after +the last byte in string. If count is omitted, then the +cursor is moved forward one byte. Note that this type does not +consume an argument. For example, +
    binary scan \x01\x02\x03\x04 x2H* var1
    +will return 1 with 0304 stored in var1. +

    X
    +Moves the cursor back count bytes in string. If +count is * or is larger than the current cursor position, +then the cursor is positioned at location 0 so that the next byte +scanned will be the first byte in string. If count +is omitted then the cursor is moved back one byte. Note that this +type does not consume an argument. For example, +
    binary scan \x01\x02\x03\x04 c2XH* var1 var2
    +will return 2 with 1 2 stored in var1 and 020304 +stored in var2. +

    @
    +Moves the cursor to the absolute location in the data string specified +by count. Note that position 0 refers to the first byte in +string. If count refers to a position beyond the end of +string, then the cursor is positioned after the last byte. If +count is omitted, then an error will be generated. For example, +
    binary scan \x01\x02\x03\x04 c2@1H* var1 var2
    +will return 2 with 1 2 stored in var1 and 020304 +stored in var2. +

    +

    PLATFORM ISSUES

    +Sometimes it is desirable to format or scan integer values in the +native byte order for the machine. Refer to the byteOrder +element of the tcl_platform array to decide which type character +to use when formatting or scanning integers. + +

    SEE ALSO

    +format, scan, tclvars +

    KEYWORDS

    +binary, format, scan +
    +Copyright © 1997 by Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/break.htm b/hlp/en/tcl/break.htm new file mode 100644 index 0000000..22d3176 --- /dev/null +++ b/hlp/en/tcl/break.htm @@ -0,0 +1,26 @@ +Built-In Commands - break manual page +

    NAME

    +break - Abort looping command +

    SYNOPSIS

    +break
    +

    DESCRIPTION

    +This command is typically invoked inside the body of a looping command +such as for or foreach or while. +It returns a TCL_BREAK code, which causes a break exception +to occur. +The exception causes the current script to be aborted +out to the innermost containing loop command, which then +aborts its execution and returns normally. +Break exceptions are also handled in a few other situations, such +as the catch command, Tk event bindings, and the outermost +scripts of procedure bodies. + +

    SEE ALSO

    +catch, continue, for, foreach, while +

    KEYWORDS

    +abort, break, loop +
    +Copyright © 1993-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/catch.htm b/hlp/en/tcl/catch.htm new file mode 100644 index 0000000..c37747f --- /dev/null +++ b/hlp/en/tcl/catch.htm @@ -0,0 +1,50 @@ +Tcl Built-In Commands - catch manual page +

    NAME

    +catch - Evaluate script and trap exceptional returns +

    SYNOPSIS

    +catch script ?varName?
    +

    DESCRIPTION

    +The catch command may be used to prevent errors from aborting command +interpretation. Catch calls the Tcl interpreter recursively to +execute script, and always returns without raising an error, +regardless of any errors that might occur while executing script. +

    +If script raises an error, catch will return a non-zero integer +value corresponding to one of the exceptional return codes (see tcl.h +for the definitions of code values). If the varName argument is +given, then the variable it names is set to the error message from +interpreting script. +

    +If script does not raise an error, catch will return 0 +(TCL_OK) and set the variable to the value returned from script. +

    +Note that catch catches all exceptions, including those +generated by break and continue as well as errors. The +only errors that are not caught are syntax errors found when the +script is compiled. This is because the catch command only catches +errors during runtime. When the catch statement is compiled, the +script is compiled as well and any syntax errors will generate a Tcl +error. + +

    EXAMPLES

    +The catch command may be used in an if to branch based on +the success of a script. + +
    if { [catch {open $someFile w} fid] } {
    +    puts stderr "Could not open $someFile for writing\n$fid"
    +    exit 1
    +}
    +The catch command will not catch compiled syntax errors. The +first time proc foo is called, the body will be compiled and a +Tcl error will be generated. + +
    proc foo {} {
    +    catch {expr {1 +- }}
    +}
    +

    KEYWORDS

    +catch, error +
    +Copyright © 1993-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/cd.htm b/hlp/en/tcl/cd.htm new file mode 100644 index 0000000..93dcc4f --- /dev/null +++ b/hlp/en/tcl/cd.htm @@ -0,0 +1,20 @@ +Built-In Commands - cd manual page +

    NAME

    +cd - Change working directory +

    SYNOPSIS

    +cd ?dirName?
    +

    DESCRIPTION

    +Change the current working directory to dirName, or to the +home directory (as specified in the HOME environment variable) if +dirName is not given. +Returns an empty string. + +

    SEE ALSO

    +filename, glob, pwd +

    KEYWORDS

    +working directory +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/clock.htm b/hlp/en/tcl/clock.htm new file mode 100644 index 0000000..287a309 --- /dev/null +++ b/hlp/en/tcl/clock.htm @@ -0,0 +1,251 @@ +Tcl Built-In Commands - clock manual page +
    +
    NAME +
    clock - Obtain and manipulate time
    +
    SYNOPSIS +
    +
    clock option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    .VS 8.3 +
    clock format clockValue ?-format string? ?-gmt boolean? +
    +
    %% +
    %a +
    %A +
    %b +
    %B +
    %c +
    %d +
    %H +
    %I +
    %j +
    %m +
    %M +
    %p +
    %S +
    %U +
    %w +
    %W +
    %x +
    %X +
    %y +
    %Y +
    %Z +
    +
    +
    %D +
    %e +
    %h +
    %n +
    %r +
    %R +
    %t +
    %T +
    +
    clock scan dateString ?-base clockVal? ?-gmt boolean? +
    +
    time +
    date +
    ISO 8601 point-in-time +
    relative time +
    +
    clock seconds +
    +
    KEYWORDS +

    +

    NAME

    +clock - Obtain and manipulate time +

    SYNOPSIS

    +clock option ?arg arg ...?
    +

    DESCRIPTION

    +This command performs one of several operations that may obtain +or manipulate strings or values that represent some notion of +time. The option argument determines what action is carried +out by the command. The legal options (which may be +abbreviated) are: +

    +

    +

    .VS 8.3
    +clock clicks ?-milliseconds? +Return a high-resolution time value as a system-dependent integer +value. The unit of the value is system-dependent but should be the +highest resolution clock available on the system such as a CPU cycle +counter. If -milliseconds is specified, then the value is +guaranteed to be of millisecond granularity. +This value should only be used for the relative measurement +of elapsed time. +

    clock format clockValue ?-format string? ?-gmt boolean?
    +Converts an integer time value, typically returned by +clock seconds, clock scan, or the atime, mtime, +or ctime options of the file command, to human-readable +form. If the -format argument is present the next argument is a +string that describes how the date and time are to be formatted. +Field descriptors consist of a % followed by a field +descriptor character. All other characters are copied into the result. +Valid field descriptors are: +

    +

    +

    %%
    +Insert a %. +

    %a
    +Abbreviated weekday name (Mon, Tue, etc.). +

    %A
    +Full weekday name (Monday, Tuesday, etc.). +

    %b
    +Abbreviated month name (Jan, Feb, etc.). +

    %B
    +Full month name. +

    %c
    +Locale specific date and time. +

    %d
    +Day of month (01 - 31). +

    %H
    +Hour in 24-hour format (00 - 23). +

    %I
    +Hour in 12-hour format (00 - 12). +

    %j
    +Day of year (001 - 366). +

    %m
    +Month number (01 - 12). +

    %M
    +Minute (00 - 59). +

    %p
    +AM/PM indicator. +

    %S
    +Seconds (00 - 59). +

    %U
    +Week of year (00 - 52), Sunday is the first day of the week. +

    %w
    +Weekday number (Sunday = 0). +

    %W
    +Week of year (00 - 52), Monday is the first day of the week. +

    %x
    +Locale specific date format. +

    %X
    +Locale specific time format. +

    %y
    +Year without century (00 - 99). +

    %Y
    +Year with century (e.g. 1990) +

    %Z
    +Time zone name. +

    +

    +

    +In addition, the following field descriptors may be supported on some +systems (e.g. Unix but not Windows): +

    +

    +

    %D
    +Date as %m/%d/%y. +

    %e
    +Day of month (1 - 31), no leading zeros. +

    %h
    +Abbreviated month name. +

    %n
    +Insert a newline. +

    %r
    +Time as %I:%M:%S %p. +

    %R
    +Time as %H:%M. +

    %t
    +Insert a tab. +

    %T
    +Time as %H:%M:%S. +

    +
    +

    +

    +If the -format argument is not specified, the format string +"%a %b %d %H:%M:%S %Z %Y" is used. If the -gmt argument +is present the next argument must be a boolean which if true specifies +that the time will be formatted as Greenwich Mean Time. If false +then the local timezone will be used as defined by the operating +environment. +
    +

    clock scan dateString ?-base clockVal? ?-gmt boolean?
    +Convert dateString to an integer clock value (see clock seconds). +This command can parse and convert virtually any standard date and/or time +string, which can include standard time zone mnemonics. If only a time is +specified, the current date is assumed. If the string does not contain a +time zone mnemonic, the local time zone is assumed, unless the -gmt +argument is true, in which case the clock value is calculated assuming +that the specified time is relative to Greenwich Mean Time. +-gmt, if specified, affects only the computed time value; it does not +impact the interpretation of -base. +

    +If the -base flag is specified, the next argument should contain +an integer clock value. Only the date in this value is used, not the +time. This is useful for determining the time on a specific day or +doing other date-relative conversions. +

    +The dateString consists of zero or more specifications of the +following form: +

    +

    +

    time
    +A time of day, which is of the form: hh?:mm?:ss?? +?meridian? ?zone? or hhmm ?meridian? +?zone?. If no meridian is specified, hh is interpreted on +a 24-hour clock. +

    date
    +A specific month and day with optional year. The +acceptable formats are mm/dd?/yy?, monthname dd +?, yy?, dd monthname ?yy?, day, dd monthname +yy, ?CC?yymmdd, ?CC?yy-mm-dd, dd-monthname-?CC?yy. +The default year is the current year. If the year is less +than 100, we treat the years 00-68 as 2000-2068 and the years 69-99 +as 1969-1999. Not all platforms can represent the years 38-70, so +an error may result if these years are used. +

    ISO 8601 point-in-time
    +An ISO 8601 point-in-time specification, such as CCyymmddThhmmss, where +T is the literal T, CCyymmdd hhmmss, or +CCyymmddThh:mm:ss. +

    relative time
    +A specification relative to the current time. The format is number +unit acceptable units are year, fortnight, month, week, day, +hour, minute (or min), and second (or sec). The +unit can be specified as a singular or plural, as in 3 weeks. +These modifiers may also be specified: +tomorrow, yesterday, today, now, +last, this, next, ago. +

    +

    +

    +The actual date is calculated according to the following steps. +First, any absolute date and/or time is processed and converted. +Using that time as the base, day-of-week specifications are added. +Next, relative specifications are used. If a date or day is +specified, and no absolute or relative time is given, midnight is +used. Finally, a correction is applied so that the correct hour of +the day is produced after allowing for daylight savings time +differences and the correct date is given when going from the end +of a long month to a short month. +

    +Daylight savings time correction is applied only when the relative time +is specified in units of days or more, ie, days, weeks, fortnights, months or +years. This means that when crossing the daylight savings time boundary, +different results will be given for clock scan "1 day" and +clock scan "24 hours": +

    % clock scan "1 day" -base [clock scan 1999-10-31]
    +941443200
    +% clock scan "24 hours" -base [clock scan 1999-10-31]
    +941439600
    +
    +

    clock seconds
    +Return the current date and time as a system-dependent integer value. The +unit of the value is seconds, allowing it to be used for relative time +calculations. The value is usually defined as total elapsed time from +an ``epoch''. You shouldn't assume the value of the epoch. + +

    +

    KEYWORDS

    +clock, date, time +
    +Copyright © 1992-1995 Karl Lehenbauer and Mark Diekhans.
    +Copyright © 1995-1997 Sun Microsystems, Inc.
    +Copyright © 1998-1999 Scriptics Corporation
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/close.htm b/hlp/en/tcl/close.htm new file mode 100644 index 0000000..af60eb0 --- /dev/null +++ b/hlp/en/tcl/close.htm @@ -0,0 +1,47 @@ +Tcl Built-In Commands - close manual page +

    NAME

    +close - Close an open channel. +

    SYNOPSIS

    +close channelId
    +

    DESCRIPTION

    +Closes the channel given by channelId. ChannelId must be a +channel identifier such as the return value from a previous open +or socket command. +All buffered output is flushed to the channel's output device, +any buffered input is discarded, the underlying file or device is closed, +and channelId becomes unavailable for use. +

    +If the channel is blocking, the command does not return until all output +is flushed. +If the channel is nonblocking and there is unflushed output, the +channel remains open and the command +returns immediately; output will be flushed in the background and the +channel will be closed when all the flushing is complete. +

    +If channelId is a blocking channel for a command pipeline then +close waits for the child processes to complete. +

    +If the channel is shared between interpreters, then close +makes channelId unavailable in the invoking interpreter but has no +other effect until all of the sharing interpreters have closed the +channel. +When the last interpreter in which the channel is registered invokes +close, the cleanup actions described above occur. See the +interp command for a description of channel sharing. +

    +Channels are automatically closed when an interpreter is destroyed and +when the process exits. Channels are switched to blocking mode, to ensure +that all output is correctly flushed before the process exits. +

    +The command returns an empty string, and may generate an error if +an error occurs while flushing output. + +

    SEE ALSO

    +file, open, socket, eof +

    KEYWORDS

    +blocking, channel, close, nonblocking +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/concat.htm b/hlp/en/tcl/concat.htm new file mode 100644 index 0000000..88a4322 --- /dev/null +++ b/hlp/en/tcl/concat.htm @@ -0,0 +1,28 @@ +Built-In Commands - concat manual page +

    NAME

    +concat - Join lists together +

    SYNOPSIS

    +concat ?arg arg ...?
    +

    DESCRIPTION

    +This command treats each argument as a list and concatenates them +into a single list. +It also eliminates leading and trailing spaces in the arg's +and adds a single separator space between arg's. +It permits any number of arguments. For example, +the command +
    concat a b {c d e} {f {g h}}
    +will return +
    a b c d e f {g h}
    +as its result. +

    +If no args are supplied, the result is an empty string. + +

    SEE ALSO

    +append, eval +

    KEYWORDS

    +concatenate, join, lists +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/continue.htm b/hlp/en/tcl/continue.htm new file mode 100644 index 0000000..64f1e61 --- /dev/null +++ b/hlp/en/tcl/continue.htm @@ -0,0 +1,26 @@ +Built-In Commands - continue manual page +

    NAME

    +continue - Skip to the next iteration of a loop +

    SYNOPSIS

    +continue
    +

    DESCRIPTION

    +This command is typically invoked inside the body of a looping command +such as for or foreach or while. +It returns a TCL_CONTINUE code, which causes a continue exception +to occur. +The exception causes the current script to be aborted +out to the innermost containing loop command, which then +continues with the next iteration of the loop. +Catch exceptions are also handled in a few other situations, such +as the catch command and the outermost scripts of procedure +bodies. + +

    SEE ALSO

    +break, for, foreach, while +

    KEYWORDS

    +continue, iteration, loop +
    +Copyright © 1993-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/dde.htm b/hlp/en/tcl/dde.htm new file mode 100644 index 0000000..4289cd7 --- /dev/null +++ b/hlp/en/tcl/dde.htm @@ -0,0 +1,146 @@ +Tcl Built-In Commands - dde manual page +
    +
    NAME +
    dde - Execute a Dynamic Data Exchange command
    +
    SYNOPSIS +
    +
    package require dde 1.1 +
    dde servername ?topic? +
    dde ?-async? command service topic ?data? +
    +
    DESCRIPTION +
    +
    -async +
    +
    DDE COMMANDS +
    +
    dde servername ?topic? +
    dde execute service topic data +
    dde poke service topic item data +
    dde request service topic item +
    dde services service topic +
    dde eval topic cmd ?arg arg ...? +
    +
    DDE AND TCL +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +dde - Execute a Dynamic Data Exchange command +

    SYNOPSIS

    +package require dde 1.1
    +dde servername ?topic?
    +dde ?-async?command service topic ?data?
    +

    DESCRIPTION

    +This command allows an application to send Dynamic Data Exchange (DDE) +command when running under Microsoft Windows. Dynamic Data Exchange is +a mechanism where applications can exchange raw data. Each DDE +transaction needs a service name and a topic. Both the +service name and topic are application defined; Tcl uses +the service name TclEval, while the topic name is the name of the +interpreter given by dde servername. Other applications have their +own service names and topics. For instance, Microsoft Excel +has the service name Excel. +

    +The only option to the dde command is: +

    +

    +

    -async
    +Requests asynchronous invocation. This is valid only for the +execute subcommand. Normally, the dde execute subcommand +waits until the command completes, returning appropriate error +messages. When the -async option is used, the command returns +immediately, and no error information is available. +

    +

    DDE COMMANDS

    +The following commands are a subset of the full Dynamic Data Exchange +set of commands. +

    +

    +

    dde servername ?topic?
    +dde servername registers the interpreter as a DDE server with +the service name TclEval and the topic name specified by topic. +If no topic is given, dde servername returns the name +of the current topic or the empty string if it is not registered as a service. +

    dde execute service topic data
    +dde execute takes the data and sends it to the server +indicated by service with the topic indicated by +topic. Typically, service is the name of an application, +and topic is a file to work on. The data field is given +to the remote application. Typically, the application treats the +data field as a script, and the script is run in the +application. The command returns an error if the script did not +run. If the -async flag was used, the command +returns immediately with no error. +

    dde poke service topic item data
    +dde poke passes the data to the server indicated by +service using the topic and item specified. Typically, +service is the name of an application. topic is application +specific but can be a command to the server or the name of a file to work +on. The item is also application specific and is often not used, but +it must always be non-null. The data field is given to the remote +application. +

    dde request service topic item
    +dde request is typically used to get the value of something; the +value of a cell in Microsoft Excel or the text of a selection in +Microsoft Word. service is typically the name of an application, +topic is typically the name of the file, and item is +application-specific. The command returns the value of item as +defined in the application. +

    dde services service topic
    +dde services returns a list of service-topic pairs that +currently exist on the machine. If service and topic are +both null strings ({}), then all service-topic pairs currently +available on the system are returned. If service is null and +topic is not, then all services with the specified topic are +returned. If service is not null and topic is, all topics +for a given service are returned. If both are not null, if that +service-topic pair currently exists, it is returned; otherwise, null +is returned. +

    dde eval topic cmd ?arg arg ...?
    +dde eval evaluates a command and its arguments using the +interpreter specified by topic. The DDE service must be the +TclEval service. This command can be used to replace send on +Windows. +

    +

    DDE AND TCL

    +A Tcl interpreter always has a service name of TclEval. Each +different interpreter of all running Tcl applications must be +given a unique +name specified by dde servername. Each interp is available as a +DDE topic only if the dde servername command was used to set the +name of the topic for each interp. So a dde services TclEval {} +command will return a list of service-topic pairs, where each of the +currently running interps will be a topic. +

    +When Tcl processes a dde execute command, the data for the +execute is run as a script in the interp named by the topic of the +dde execute command. +

    +When Tcl processes a dde request command, it returns the value of the +variable given in the dde command in the context of the interp named by the +dde topic. Tcl reserves the variable $TCLEVAL$EXECUTE$RESULT for +internal use, and dde request commands for that variable will give +unpredictable results. +

    +An external application which wishes to run a script in Tcl should have +that script store its result in a variable, run the dde execute +command, and the run dde request to get the value of the +variable. +

    +When using DDE, be careful to ensure that the event queue is flushed +using either update or vwait. This happens by default +when using wish unless a blocking command is called (such as exec +without adding the & to place the process in the background). +If for any reason the event queue is not flushed, DDE commands may +hang until the event queue is flushed. This can create a deadlock +situation. + +

    SEE ALSO

    +tk, winfo, send +

    KEYWORDS

    +application, dde, name, remote execution +
    +Copyright © 1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/encoding.htm b/hlp/en/tcl/encoding.htm new file mode 100644 index 0000000..19d7938 --- /dev/null +++ b/hlp/en/tcl/encoding.htm @@ -0,0 +1,83 @@ +Tcl Built-In Commands - encoding manual page +
    +
    NAME +
    encoding - Manipulate encodings
    +
    SYNOPSIS +
    +
    encoding option ?arg arg ...? +
    +
    INTRODUCTION +
    DESCRIPTION +
    +
    encoding convertfrom ?encoding? data +
    encoding convertto ?encoding? string +
    encoding names +
    encoding system ?encoding? +
    +
    EXAMPLE +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +encoding - Manipulate encodings +

    SYNOPSIS

    +encoding option ?arg arg ...?
    +

    INTRODUCTION

    +Strings in Tcl are encoded using 16-bit Unicode characters. Different +operating system interfaces or applications may generate strings in +other encodings such as Shift-JIS. The encoding command helps +to bridge the gap between Unicode and these other formats. + +

    DESCRIPTION

    +Performs one of several encoding related operations, depending on +option. The legal options are: +

    +

    +

    encoding convertfrom ?encoding? data
    +Convert data to Unicode from the specified encoding. The +characters in data are treated as binary data where the lower +8-bits of each character is taken as a single byte. The resulting +sequence of bytes is treated as a string in the specified +encoding. If encoding is not specified, the current +system encoding is used. +

    encoding convertto ?encoding? string
    +Convert string from Unicode to the specified encoding. +The result is a sequence of bytes that represents the converted +string. Each byte is stored in the lower 8-bits of a Unicode +character. If encoding is not specified, the current +system encoding is used. +

    encoding names
    +Returns a list containing the names of all of the encodings that are +currently available. +

    encoding system ?encoding?
    +Set the system encoding to encoding. If encoding is +omitted then the command returns the current system encoding. The +system encoding is used whenever Tcl passes strings to system calls. + +

    +

    EXAMPLE

    +It is common practice to write script files using a text editor that +produces output in the euc-jp encoding, which represents the ASCII +characters as singe bytes and Japanese characters as two bytes. This +makes it easy to embed literal strings that correspond to non-ASCII +characters by simply typing the strings in place in the script. +However, because the source command always reads files using the +ISO8859-1 encoding, Tcl will treat each byte in the file as a separate +character that maps to the 00 page in Unicode. The +resulting Tcl strings will not contain the expected Japanese +characters. Instead, they will contain a sequence of Latin-1 +characters that correspond to the bytes of the original string. The +encoding command can be used to convert this string to the +expected Japanese Unicode characters. For example, +
    set s [encoding convertfrom euc-jp "\xA4\xCF"]
    +would return the Unicode string "\u306F", which is the Hiragana +letter HA. + +

    SEE ALSO

    +Tcl_GetEncoding +

    KEYWORDS

    +encoding +
    +Copyright © 1998 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/eof.htm b/hlp/en/tcl/eof.htm new file mode 100644 index 0000000..2be89ad --- /dev/null +++ b/hlp/en/tcl/eof.htm @@ -0,0 +1,19 @@ +Tcl Built-In Commands - eof manual page +

    NAME

    +eof - Check for end of file condition on channel +

    SYNOPSIS

    +eof channelId
    +

    DESCRIPTION

    +Returns 1 if an end of file condition occurred during the most +recent input operation on channelId (such as gets), +0 otherwise. + +

    SEE ALSO

    +file, open, close, fblocked +

    KEYWORDS

    +channel, end of file +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/error.htm b/hlp/en/tcl/error.htm new file mode 100644 index 0000000..55d6872 --- /dev/null +++ b/hlp/en/tcl/error.htm @@ -0,0 +1,48 @@ +Built-In Commands - error manual page +

    NAME

    +error - Generate an error +

    SYNOPSIS

    +error message ?info? ?code?
    +

    DESCRIPTION

    +Returns a TCL_ERROR code, which causes command interpretation to be +unwound. Message is a string that is returned to the application +to indicate what went wrong. +

    +If the info argument is provided and is non-empty, +it is used to initialize the global variable errorInfo. +errorInfo is used to accumulate a stack trace of what +was in progress when an error occurred; as nested commands unwind, +the Tcl interpreter adds information to errorInfo. If the +info argument is present, it is used to initialize +errorInfo and the first increment of unwind information +will not be added by the Tcl interpreter. In other +words, the command containing the error command will not appear +in errorInfo; in its place will be info. +This feature is most useful in conjunction with the catch command: +if a caught error cannot be handled successfully, info can be used +to return a stack trace reflecting the original point of occurrence +of the error: +

    catch {...} errMsg
    +set savedInfo $errorInfo
    +	...
    +error $errMsg $savedInfo
    +

    +If the code argument is present, then its value is stored +in the errorCode global variable. This variable is intended +to hold a machine-readable description of the error in cases where +such information is available; see the tclvars manual +page for information on the proper format for the variable. +If the code argument is not +present, then errorCode is automatically reset to +``NONE'' by the Tcl interpreter as part of processing the +error generated by the command. + +

    SEE ALSO

    +catch, tclvars +

    KEYWORDS

    +error, errorCode, errorInfo +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/eval.htm b/hlp/en/tcl/eval.htm new file mode 100644 index 0000000..1603459 --- /dev/null +++ b/hlp/en/tcl/eval.htm @@ -0,0 +1,22 @@ +Built-In Commands - eval manual page +

    NAME

    +eval - Evaluate a Tcl script +

    SYNOPSIS

    +eval arg ?arg ...?
    +

    DESCRIPTION

    +Eval takes one or more arguments, which together comprise a Tcl +script containing one or more commands. +Eval concatenates all its arguments in the same +fashion as the concat command, passes the concatenated string to the +Tcl interpreter recursively, and returns the result of that +evaluation (or any error generated by it). + +

    KEYWORDS

    +concatenate, evaluate, script +

    SEE ALSO

    +catch, concat, error, subs, tclvars +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/exec.htm b/hlp/en/tcl/exec.htm new file mode 100644 index 0000000..c1daecb --- /dev/null +++ b/hlp/en/tcl/exec.htm @@ -0,0 +1,314 @@ +Tcl Built-In Commands - exec manual page +
    +
    NAME +
    exec - Invoke subprocess(es)
    +
    SYNOPSIS +
    +
    exec ?switches? arg ?arg ...? +
    +
    DESCRIPTION +
    +
    -keepnewline +
    - - +
    +
    +
    | +
    |& +
    < fileName +
    <@ fileId +
    << value +
    > fileName +
    2> fileName +
    >& fileName +
    >> fileName +
    2>> fileName +
    >>& fileName +
    >@ fileId +
    2>@ fileId +
    >&@ fileId +
    +
    PORTABILITY ISSUES +
    +
    Windows (all versions) +
    Windows NT +
    Windows 95 +
    Macintosh +
    Unix +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +exec - Invoke subprocess(es) +

    SYNOPSIS

    +exec ?switches? arg ?arg ...?
    +

    DESCRIPTION

    +This command treats its arguments as the specification +of one or more subprocesses to execute. +The arguments take the form of a standard shell pipeline +where each arg becomes one word of a command, and +each distinct command becomes a subprocess. +

    +If the initial arguments to exec start with - then +they are treated as command-line switches and are not part +of the pipeline specification. The following switches are +currently supported: +

    +

    +

    -keepnewline
    +Retains a trailing newline in the pipeline's output. +Normally a trailing newline will be deleted. +

    - -
    +Marks the end of switches. The argument following this one will +be treated as the first arg even if it starts with a -. +

    +

    +If an arg (or pair of arg's) has one of the forms +described below then it is used by exec to control the +flow of input and output among the subprocess(es). +Such arguments will not be passed to the subprocess(es). In forms +such as ``< fileName'' fileName may either be in a +separate argument from ``<'' or in the same argument with no +intervening space (i.e. ``<fileName''). +

    +

    +

    |
    +Separates distinct commands in the pipeline. The standard output +of the preceding command will be piped into the standard input +of the next command. +

    |&
    +Separates distinct commands in the pipeline. Both standard output +and standard error of the preceding command will be piped into +the standard input of the next command. +This form of redirection overrides forms such as 2> and >&. +

    < fileName
    +The file named by fileName is opened and used as the standard +input for the first command in the pipeline. +

    <@ fileId
    +FileId must be the identifier for an open file, such as the return +value from a previous call to open. +It is used as the standard input for the first command in the pipeline. +FileId must have been opened for reading. +

    << value
    +Value is passed to the first command as its standard input. +

    > fileName
    +Standard output from the last command is redirected to the file named +fileName, overwriting its previous contents. +

    2> fileName
    +Standard error from all commands in the pipeline is redirected to the +file named fileName, overwriting its previous contents. +

    >& fileName
    +Both standard output from the last command and standard error from all +commands are redirected to the file named fileName, overwriting +its previous contents. +

    >> fileName
    +Standard output from the last command is +redirected to the file named fileName, appending to it rather +than overwriting it. +

    2>> fileName
    +Standard error from all commands in the pipeline is +redirected to the file named fileName, appending to it rather +than overwriting it. +

    >>& fileName
    +Both standard output from the last command and standard error from +all commands are redirected to the file named fileName, +appending to it rather than overwriting it. +

    >@ fileId
    +FileId must be the identifier for an open file, such as the return +value from a previous call to open. +Standard output from the last command is redirected to fileId's +file, which must have been opened for writing. +

    2>@ fileId
    +FileId must be the identifier for an open file, such as the return +value from a previous call to open. +Standard error from all commands in the pipeline is +redirected to fileId's file. +The file must have been opened for writing. +

    >&@ fileId
    +FileId must be the identifier for an open file, such as the return +value from a previous call to open. +Both standard output from the last command and standard error from +all commands are redirected to fileId's file. +The file must have been opened for writing. +

    +

    +If standard output has not been redirected then the exec +command returns the standard output from the last command +in the pipeline. +If any of the commands in the pipeline exit abnormally or +are killed or suspended, then exec will return an error +and the error message will include the pipeline's output followed by +error messages describing the abnormal terminations; the +errorCode variable will contain additional information +about the last abnormal termination encountered. +If any of the commands writes to its standard error file and that +standard error isn't redirected, +then exec will return an error; the error message +will include the pipeline's standard output, followed by messages +about abnormal terminations (if any), followed by the standard error +output. +

    +If the last character of the result or error message +is a newline then that character is normally deleted +from the result or error message. +This is consistent with other Tcl return values, which don't +normally end with newlines. +However, if -keepnewline is specified then the trailing +newline is retained. +

    +If standard input isn't redirected with ``<'' or ``<<'' +or ``<@'' then the standard input for the first command in the +pipeline is taken from the application's current standard input. +

    +If the last arg is ``&'' then the pipeline will be +executed in background. +In this case the exec command will return a list whose +elements are the process identifiers for all of the subprocesses +in the pipeline. +The standard output from the last command in the pipeline will +go to the application's standard output if it hasn't been +redirected, and error output from all of +the commands in the pipeline will go to the application's +standard error file unless redirected. +

    +The first word in each command is taken as the command name; +tilde-substitution is performed on it, and if the result contains +no slashes then the directories +in the PATH environment variable are searched for +an executable by the given name. +If the name contains a slash then it must refer to an executable +reachable from the current directory. +No ``glob'' expansion or other shell-like substitutions +are performed on the arguments to commands. + +

    PORTABILITY ISSUES

    +
    +

    Windows (all versions)
    +Reading from or writing to a socket, using the ``@ fileId'' +notation, does not work. When reading from a socket, a 16-bit DOS +application will hang and a 32-bit application will return immediately with +end-of-file. When either type of application writes to a socket, the +information is instead sent to the console, if one is present, or is +discarded. +

    +The Tk console text widget does not provide real standard IO capabilities. +Under Tk, when redirecting from standard input, all applications will see an +immediate end-of-file; information redirected to standard output or standard +error will be discarded. +

    +Either forward or backward slashes are accepted as path separators for +arguments to Tcl commands. When executing an application, the path name +specified for the application may also contain forward or backward slashes +as path separators. Bear in mind, however, that most Windows applications +accept arguments with forward slashes only as option delimiters and +backslashes only in paths. Any arguments to an application that specify a +path name with forward slashes will not automatically be converted to use +the backslash character. If an argument contains forward slashes as the +path separator, it may or may not be recognized as a path name, depending on +the program. +

    +Additionally, when calling a 16-bit DOS or Windows 3.X application, all path +names must use the short, cryptic, path format (e.g., using ``applba~1.def'' +instead of ``applbakery.default''). +

    +Two or more forward or backward slashes in a row in a path refer to a +network path. For example, a simple concatenation of the root directory +c:/ with a subdirectory /windows/system will yield +c://windows/system (two slashes together), which refers to the mount +point called system on the machine called windows (and the +c:/ is ignored), and is not equivalent to c:/windows/system, +which describes a directory on the current computer. The file join +command should be used to concatenate path components. +

    Windows NT
    +When attempting to execute an application, exec first searches for the +name as it was specified. Then, in order, .com, .exe, and .bat +are appended to the end of the specified name and it searches for +the longer name. If a directory name was not specified as part of the +application name, the following directories are automatically searched in +order when attempting to locate the application: +

    +

    +The directory from which the Tcl executable was loaded. +
    +The current directory. +
    +The Windows NT 32-bit system directory. +
    +The Windows NT 16-bit system directory. +
    +The Windows NT home directory. +
    +The directories listed in the path. +
    +

    +In order to execute the shell builtin commands like dir and copy, +the caller must prepend ``cmd.exe /c '' to the desired command. +

    +

    Windows 95
    +When attempting to execute an application, exec first searches for the +name as it was specified. Then, in order, .com, .exe, and .bat +are appended to the end of the specified name and it searches for +the longer name. If a directory name was not specified as part of the +application name, the following directories are automatically searched in +order when attempting to locate the application: +

    +

    +The directory from which the Tcl executable was loaded. +
    +The current directory. +
    +The Windows 95 system directory. +
    +The Windows 95 home directory. +
    +The directories listed in the path. +
    +

    +In order to execute the shell builtin commands like dir and copy, +the caller must prepend ``command.com /c '' to the desired command. +

    +Once a 16-bit DOS application has read standard input from a console and +then quit, all subsequently run 16-bit DOS applications will see the +standard input as already closed. 32-bit applications do not have this +problem and will run correctly, even after a 16-bit DOS application thinks +that standard input is closed. There is no known workaround for this bug +at this time. +

    +Redirection between the NUL: device and a 16-bit application does not +always work. When redirecting from NUL:, some applications may hang, +others will get an infinite stream of ``0x01'' bytes, and some will actually +correctly get an immediate end-of-file; the behavior seems to depend upon +something compiled into the application itself. When redirecting greater than +4K or so to NUL:, some applications will hang. The above problems do not +happen with 32-bit applications. +

    +All DOS 16-bit applications are run synchronously. All standard input from +a pipe to a 16-bit DOS application is collected into a temporary file; the +other end of the pipe must be closed before the 16-bit DOS application +begins executing. All standard output or error from a 16-bit DOS +application to a pipe is collected into temporary files; the application +must terminate before the temporary files are redirected to the next stage +of the pipeline. This is due to a workaround for a Windows 95 bug in the +implementation of pipes, and is how the standard Windows 95 DOS shell +handles pipes itself. +

    +Certain applications, such as command.com, should not be executed +interactively. Applications which directly access the console window, +rather than reading from their standard input and writing to their standard +output may fail, hang Tcl, or even hang the system if their own private +console window is not available to them. +

    Macintosh
    +The exec command is not implemented and does not exist under Macintosh. +

    Unix
    +The exec command is fully functional and works as described. + +

    +

    SEE ALSO

    +error, open +

    KEYWORDS

    +execute, pipeline, redirection, subprocess +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/exit.htm b/hlp/en/tcl/exit.htm new file mode 100644 index 0000000..77cd8b3 --- /dev/null +++ b/hlp/en/tcl/exit.htm @@ -0,0 +1,20 @@ +Built-In Commands - exit manual page +

    NAME

    +exit - End the application +

    SYNOPSIS

    +exit ?returnCode?
    +

    DESCRIPTION

    +Terminate the process, returning returnCode to the +system as the exit status. +If returnCode isn't specified then it defaults +to 0. + +

    SEE ALSO

    +exec, tclvars +

    KEYWORDS

    +exit, process +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/expr.htm b/hlp/en/tcl/expr.htm new file mode 100644 index 0000000..2cfd8d8 --- /dev/null +++ b/hlp/en/tcl/expr.htm @@ -0,0 +1,380 @@ +Tcl Built-In Commands - expr manual page +
    +
    NAME +
    expr - Evaluate an expression
    +
    SYNOPSIS +
    +
    expr arg ?arg arg ...? +
    +
    DESCRIPTION +
    OPERANDS +
    +
    +
    OPERATORS +
    +
    - + ~ ! +
    * / % +
    + - +
    << >> +
    < > <= >= +
    == != +
    & +
    ^ +
    | +
    && +
    || +
    x?y:z +
    +
    MATH FUNCTIONS +
    +
    abs(arg) +
    acos(arg) +
    asin(arg) +
    atan(arg) +
    atan2(x, y) +
    ceil(arg) +
    cos(arg) +
    cosh(arg) +
    double(arg) +
    exp(arg) +
    floor(arg) +
    fmod(x, y) +
    hypot(x, y) +
    int(arg) +
    log(arg) +
    log10(arg) +
    pow(x, y) +
    rand() +
    round(arg) +
    sin(arg) +
    sinh(arg) +
    sqrt(arg) +
    srand(arg) +
    tan(arg) +
    tanh(arg) +
    +
    TYPES, OVERFLOW, AND PRECISION +
    STRING OPERATIONS +
    PERFORMANCE CONSIDERATIONS +
    KEYWORDS +

    +

    NAME

    +expr - Evaluate an expression +

    SYNOPSIS

    +expr arg ?arg arg ...?
    +

    DESCRIPTION

    +Concatenates arg's (adding separator spaces between them), +evaluates the result as a Tcl expression, and returns the value. +The operators permitted in Tcl expressions are a subset of +the operators permitted in C expressions, and they have the +same meaning and precedence as the corresponding C operators. +Expressions almost always yield numeric results +(integer or floating-point values). +For example, the expression +
    expr 8.2 + 6
    +evaluates to 14.2. +Tcl expressions differ from C expressions in the way that +operands are specified. Also, Tcl expressions support +non-numeric operands and string comparisons. +

    OPERANDS

    +A Tcl expression consists of a combination of operands, operators, +and parentheses. +White space may be used between the operands and operators and +parentheses; it is ignored by the expression's instructions. +Where possible, operands are interpreted as integer values. +Integer values may be specified in decimal (the normal case), in octal (if the +first character of the operand is 0), or in hexadecimal (if the first +two characters of the operand are 0x). +If an operand does not have one of the integer formats given +above, then it is treated as a floating-point number if that is +possible. Floating-point numbers may be specified in any of the +ways accepted by an ANSI-compliant C compiler (except that the +f, F, l, and L suffixes will not be permitted in +most installations). For example, all of the +following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. +If no numeric interpretation is possible, then an operand is left +as a string (and only a limited set of operators may be applied to +it). +

    +Operands may be specified in any of the following ways: +

    +

    +

    [1]
    +As an numeric value, either integer or floating-point. +

    [2]
    +As a Tcl variable, using standard $ notation. +The variable's value will be used as the operand. +

    [3]
    +As a string enclosed in double-quotes. +The expression parser will perform backslash, variable, and +command substitutions on the information between the quotes, +and use the resulting value as the operand +

    [4]
    +As a string enclosed in braces. +The characters between the open brace and matching close brace +will be used as the operand without any substitutions. +

    [5]
    +As a Tcl command enclosed in brackets. +The command will be executed and its result will be used as +the operand. +

    [6]
    +As a mathematical function whose arguments have any of the above +forms for operands, such as sin($x). See below for a list of defined +functions. +

    +

    +Where substitutions occur above (e.g. inside quoted strings), they +are performed by the expression's instructions. +However, an additional layer of substitution may already have +been performed by the command parser before the expression +processor was called. +As discussed below, it is usually best to enclose expressions +in braces to prevent the command parser from performing substitutions +on the contents. +

    +For some examples of simple expressions, suppose the variable +a has the value 3 and +the variable b has the value 6. +Then the command on the left side of each of the lines below +will produce the value on the right side of the line: +

    expr 3.1 + $a	6.1
    +expr 2 + "$a.$b"	5.6
    +expr 4*[llength "6 2"]	8
    +expr {{word one} < "word $a"}	0
    +

    OPERATORS

    +The valid operators are listed below, grouped in decreasing order +of precedence: +

    +

    +

    - + ~ !
    +Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operands +may be applied to string operands, and bit-wise NOT may be +applied only to integers. +

    * / %
    +Multiply, divide, remainder. None of these operands may be +applied to string operands, and remainder may be applied only +to integers. +The remainder will always have the same sign as the divisor and +an absolute value smaller than the divisor. +

    + -
    +Add and subtract. Valid for any numeric operands. +

    << >>
    +Left and right shift. Valid for integer operands only. +A right shift always propagates the sign bit. +

    < > <= >=
    +Boolean less, greater, less than or equal, and greater than or equal. +Each operator produces 1 if the condition is true, 0 otherwise. +These operators may be applied to strings as well as numeric operands, +in which case string comparison is used. +

    == !=
    +Boolean equal and not equal. Each operator produces a zero/one result. +Valid for all operand types. +

    &
    +Bit-wise AND. Valid for integer operands only. +

    ^
    +Bit-wise exclusive OR. Valid for integer operands only. +

    |
    +Bit-wise OR. Valid for integer operands only. +

    &&
    +Logical AND. Produces a 1 result if both operands are non-zero, +0 otherwise. +Valid for boolean and numeric (integers or floating-point) operands only. +

    ||
    +Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. +Valid for boolean and numeric (integers or floating-point) operands only. +

    x?y:z
    +If-then-else, as in C. If x +evaluates to non-zero, then the result is the value of y. +Otherwise the result is the value of z. +The x operand must have a numeric value. +

    +

    +See the C manual for more details on the results +produced by each operator. +All of the binary operators group left-to-right within the same +precedence level. For example, the command +

    expr 4*2 < 7
    +returns 0. +

    +The &&, ||, and ?: operators have ``lazy +evaluation'', just as in C, +which means that operands are not evaluated if they are +not needed to determine the outcome. For example, in the command +

    expr {$v ? [a] : [b]}
    +only one of [a] or [b] will actually be evaluated, +depending on the value of $v. Note, however, that this is +only true if the entire expression is enclosed in braces; otherwise +the Tcl parser will evaluate both [a] and [b] before +invoking the expr command. +

    MATH FUNCTIONS

    +Tcl supports the following mathematical functions in expressions: +
    abs	cosh	log	sqrt
    +acos	double	log10	srand
    +asin	exp	pow	tan
    +atan	floor	rand	tanh
    +atan2	fmod	round
    +ceil	hypot	sin
    +cos	int	sinh
    +

    +

    +

    +

    abs(arg)
    +Returns the absolute value of arg. Arg may be either +integer or floating-point, and the result is returned in the same form. +

    acos(arg)
    +Returns the arc cosine of arg, in the range [0,pi] +radians. Arg should be in the range [-1,1]. +

    asin(arg)
    +Returns the arc sine of arg, in the range [-pi/2,pi/2] radians. +Arg should be in the range [-1,1]. +

    atan(arg)
    +Returns the arc tangent of arg, in the range [-pi/2,pi/2] radians. +

    atan2(x, y)
    +Returns the arc tangent of y/x, in the range [-pi,pi] +radians. x and y cannot both be 0. +

    ceil(arg)
    +Returns the smallest integer value not less than arg. +

    cos(arg)
    +Returns the cosine of arg, measured in radians. +

    cosh(arg)
    +Returns the hyperbolic cosine of arg. If the result would cause +an overflow, an error is returned. +

    double(arg)
    +If arg is a floating value, returns arg, otherwise converts +arg to floating and returns the converted value. +

    exp(arg)
    +Returns the exponential of arg, defined as e**arg. If the +result would cause an overflow, an error is returned. +

    floor(arg)
    +Returns the largest integral value not greater than arg. +

    fmod(x, y)
    +Returns the floating-point remainder of the division of x by +y. If y is 0, an error is returned. +

    hypot(x, y)
    +Computes the length of the hypotenuse of a right-angled triangle +(x*x+y*y). +

    int(arg)
    +If arg is an integer value, returns arg, otherwise converts +arg to integer by truncation and returns the converted value. +

    log(arg)
    +Returns the natural logarithm of arg. Arg must be a +positive value. +

    log10(arg)
    +Returns the base 10 logarithm of arg. Arg must be a +positive value. +

    pow(x, y)
    +Computes the value of x raised to the power y. If x +is negative, y must be an integer value. +

    rand()
    +Returns a floating point number from zero to just less than one or, +in mathematical terms, the range [0,1). The seed comes from the +internal clock of the machine or may be set manual with the srand +function. +

    round(arg)
    +If arg is an integer value, returns arg, otherwise converts +arg to integer by rounding and returns the converted value. +

    sin(arg)
    +Returns the sine of arg, measured in radians. +

    sinh(arg)
    +Returns the hyperbolic sine of arg. If the result would cause +an overflow, an error is returned. +

    sqrt(arg)
    +Returns the square root of arg. Arg must be non-negative. +

    srand(arg)
    +The arg, which must be an integer, is used to reset the seed for +the random number generator. Returns the first random number from +that seed. Each interpreter has it's own seed. +

    tan(arg)
    +Returns the tangent of arg, measured in radians. +

    tanh(arg)
    +Returns the hyperbolic tangent of arg. +

    +

    +In addition to these predefined functions, applications may +define additional functions using Tcl_CreateMathFunc(). +

    TYPES, OVERFLOW, AND PRECISION

    +All internal computations involving integers are done with the C type +long, and all internal computations involving floating-point are +done with the C type double. +When converting a string to floating-point, exponent overflow is +detected and results in a Tcl error. +For conversion to integer from string, detection of overflow depends +on the behavior of some routines in the local C library, so it should +be regarded as unreliable. +In any case, integer overflow and underflow are generally not detected +reliably for intermediate results. Floating-point overflow and underflow +are detected to the degree supported by the hardware, which is generally +pretty reliable. +

    +Conversion among internal representations for integer, floating-point, +and string operands is done automatically as needed. +For arithmetic computations, integers are used until some +floating-point number is introduced, after which floating-point is used. +For example, +

    expr 5 / 4
    +returns 1, while +
    expr 5 / 4.0
    +expr 5 / ( [string length "abcd"] + 0.0 )
    +both return 1.25. +Floating-point values are always returned with a ``.'' +or an e so that they will not look like integer values. For +example, +
    expr 20.0/5.0
    +returns 4.0, not 4. + +

    STRING OPERATIONS

    +String values may be used as operands of the comparison operators, +although the expression evaluator tries to do comparisons as integer +or floating-point when it can. +If one of the operands of a comparison is a string and the other +has a numeric value, the numeric operand is converted back to +a string using the C sprintf format specifier +%d for integers and %g for floating-point values. +For example, the commands +
    expr {"0x03" > "2"}
    +expr {"0y" < "0x12"}
    +both return 1. The first comparison is done using integer +comparison, and the second is done using string comparison after +the second operand is converted to the string 18. +Because of Tcl's tendency to treat values as numbers whenever +possible, it isn't generally a good idea to use operators like == +when you really want string comparison and the values of the +operands could be arbitrary; it's better in these cases to use +the string command instead. + +

    PERFORMANCE CONSIDERATIONS

    +Enclose expressions in braces for the best speed and the smallest +storage requirements. +This allows the Tcl bytecode compiler to generate the best code. +

    +As mentioned above, expressions are substituted twice: +once by the Tcl parser and once by the expr command. +For example, the commands +

    set a 3
    +set b {$a + 2}
    +expr $b*4
    +return 11, not a multiple of 4. +This is because the Tcl parser will first substitute $a + 2 for +the variable b, +then the expr command will evaluate the expression $a + 2*4. +

    +Most expressions do not require a second round of substitutions. +Either they are enclosed in braces or, if not, +their variable and command substitutions yield numbers or strings +that don't themselves require substitutions. +However, because a few unbraced expressions +need two rounds of substitutions, +the bytecode compiler must emit +additional instructions to handle this situation. +The most expensive code is required for +unbraced expressions that contain command substitutions. +These expressions must be implemented by generating new code +each time the expression is executed. + +

    KEYWORDS

    +arithmetic, boolean, compare, expression, fuzzy comparison +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-2000 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/fblocked.htm b/hlp/en/tcl/fblocked.htm new file mode 100644 index 0000000..4398a6d --- /dev/null +++ b/hlp/en/tcl/fblocked.htm @@ -0,0 +1,22 @@ +Tcl Built-In Commands - fblocked manual page +

    NAME

    +fblocked - Test whether the last input operation exhausted all available input +

    SYNOPSIS

    +fblocked channelId
    +

    DESCRIPTION

    +The fblocked command returns 1 if the most recent input operation +on channelId returned less information than requested because all +available input was exhausted. +For example, if gets is invoked when there are only three +characters available for input and no end-of-line sequence, gets +returns an empty string and a subsequent call to fblocked will +return 1. +

    +

    SEE ALSO

    +gets, open, read +

    KEYWORDS

    +blocking, nonblocking +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/fconfigure.htm b/hlp/en/tcl/fconfigure.htm new file mode 100644 index 0000000..6ee6997 --- /dev/null +++ b/hlp/en/tcl/fconfigure.htm @@ -0,0 +1,189 @@ +Tcl Built-In Commands - fconfigure manual page +
    +
    NAME +
    fconfigure - Set and get options on a channel
    +
    SYNOPSIS +
    +
    fconfigure channelId +
    fconfigure channelId name +
    fconfigure channelId name value ?name value ...? +
    +
    DESCRIPTION +
    +
    -blocking boolean +
    -buffering newValue +
    -buffersize newSize +
    -encoding name +
    -eofchar char +
    -eofchar {inChar outChar} +
    -translation mode +
    -translation {inMode outMode} +
    +
    auto +
    binary +
    cr +
    crlf +
    lf +
    +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +fconfigure - Set and get options on a channel +

    SYNOPSIS

    +fconfigure channelId
    +fconfigure channelIdname
    +fconfigure channelIdname value ?name value ...?
    +

    DESCRIPTION

    +The fconfigure command sets and retrieves options for channels. +ChannelId identifies the channel for which to set or query an option. +If no name or value arguments are supplied, the command +returns a list containing alternating option names and values for the channel. +If name is supplied but no value then the command returns +the current value of the given option. +If one or more pairs of name and value are supplied, the +command sets each of the named options to the corresponding value; +in this case the return value is an empty string. +

    +The options described below are supported for all channels. In addition, +each channel type may add options that only it supports. See the manual +entry for the command that creates each type of channels for the options +that that specific type of channel supports. For example, see the manual +entry for the socket command for its additional options. +

    +

    +

    -blocking boolean
    +The -blocking option determines whether I/O operations on the +channel can cause the process to block indefinitely. +The value of the option must be a proper boolean value. +Channels are normally in blocking mode; if a channel is placed into +nonblocking mode it will affect the operation of the gets, +read, puts, flush, and close commands; +see the documentation for those commands for details. +For nonblocking mode to work correctly, the application must be +using the Tcl event loop (e.g. by calling Tcl_DoOneEvent or +invoking the vwait command). +

    -buffering newValue
    +If newValue is full then the I/O system will buffer output +until its internal buffer is full or until the flush command is +invoked. If newValue is line, then the I/O system will +automatically flush output for the channel whenever a newline character +is output. If newValue is none, the I/O system will flush +automatically after every output operation. The default is for +-buffering to be set to full except for channels that +connect to terminal-like devices; for these channels the initial setting +is line. Additionally, stdin and stdout are +intially set to line, and stderr is set to none. +

    -buffersize newSize
    +Newvalue must be an integer; its value is used to set the size of +buffers, in bytes, subsequently allocated for this channel to store input +or output. Newvalue must be between ten and one million, allowing +buffers of ten to one million bytes in size. +

    -encoding name
    +This option is used to specify the encoding of the channel, so that the data +can be converted to and from Unicode for use in Tcl. For instance, in +order for Tcl to read characters from a Japanese file in shiftjis +and properly process and display the contents, the encoding would be set +to shiftjis. Thereafter, when reading from the channel, the bytes in +the Japanese file would be converted to Unicode as they are read. +Writing is also supported - as Tcl strings are written to the channel they +will automatically be converted to the specified encoding on output. +

    +If a file contains pure binary data (for instance, a JPEG image), the +encoding for the channel should be configured to be binary. Tcl +will then assign no interpretation to the data in the file and simply read or +write raw bytes. The Tcl binary command can be used to manipulate this +byte-oriented data. +

    The default encoding for newly opened channels is the same platform- and +locale-dependent system encoding used for interfacing with the operating +system. +

    -eofchar char
    +

    -eofchar {inChar outChar}
    +This option supports DOS file systems that use Control-z (\x1a) as an +end of file marker. If char is not an empty string, then this +character signals end-of-file when it is encountered during input. For +output, the end-of-file character is output when the channel is closed. +If char is the empty string, then there is no special end of file +character marker. For read-write channels, a two-element list specifies +the end of file marker for input and output, respectively. As a +convenience, when setting the end-of-file character for a read-write +channel you can specify a single value that will apply to both reading +and writing. When querying the end-of-file character of a read-write +channel, a two-element list will always be returned. The default value +for -eofchar is the empty string in all cases except for files +under Windows. In that case the -eofchar is Control-z (\x1a) for +reading and the empty string for writing. +

    -translation mode
    +

    -translation {inMode outMode}
    +In Tcl scripts the end of a line is always represented using a single +newline character (\n). However, in actual files and devices the end of +a line may be represented differently on different platforms, or even for +different devices on the same platform. For example, under UNIX newlines +are used in files, whereas carriage-return-linefeed sequences are +normally used in network connections. On input (i.e., with gets +and read) the Tcl I/O system automatically translates the external +end-of-line representation into newline characters. Upon output (i.e., +with puts), the I/O system translates newlines to the external +end-of-line representation. The default translation mode, auto, +handles all the common cases automatically, but the -translation +option provides explicit control over the end of line translations. +

    +The value associated with -translation is a single item for +read-only and write-only channels. The value is a two-element list for +read-write channels; the read translation mode is the first element of +the list, and the write translation mode is the second element. As a +convenience, when setting the translation mode for a read-write channel +you can specify a single value that will apply to both reading and +writing. When querying the translation mode of a read-write channel, a +two-element list will always be returned. The following values are +currently supported: +

    +

    +

    auto
    +As the input translation mode, auto treats any of newline +(lf), carriage return (cr), or carriage return followed by a +newline (crlf) as the end of line representation. The end of line +representation can even change from line-to-line, and all cases are +translated to a newline. As the output translation mode, auto +chooses a platform specific representation; for sockets on all platforms +Tcl chooses crlf, for all Unix flavors, it chooses lf, for the +Macintosh platform it chooses cr and for the various flavors of +Windows it chooses crlf. The default setting for +-translation is auto for both input and output. +

    binary
    +No end-of-line translations are performed. This is nearly identical to +lf mode, except that in addition binary mode also sets the +end-of-file character to the empty string (which disables it) and sets the +encoding to binary (which disables encoding filtering). See the +description of -eofchar and -encoding for more information. +

    cr
    +The end of a line in the underlying file or device is represented by a +single carriage return character. As the input translation mode, +cr mode converts carriage returns to newline characters. As the +output translation mode, cr mode translates newline characters to +carriage returns. This mode is typically used on Macintosh platforms. +

    crlf
    +The end of a line in the underlying file or device is represented by a +carriage return character followed by a linefeed character. As the input +translation mode, crlf mode converts carriage-return-linefeed +sequences to newline characters. As the output translation mode, +crlf mode translates newline characters to carriage-return-linefeed +sequences. This mode is typically used on Windows platforms and for +network connections. +

    lf
    +The end of a line in the underlying file or device is represented by a +single newline (linefeed) character. In this mode no translations occur +during either input or output. This mode is typically used on UNIX +platforms. +

    +

    +

    +

    SEE ALSO

    +close, flush, gets, puts, read, socket +

    KEYWORDS

    +blocking, buffering, carriage return, end of line, flushing, linemode, newline, nonblocking, platform, translation, encoding, filter, byte array, binary +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/fcopy.htm b/hlp/en/tcl/fcopy.htm new file mode 100644 index 0000000..123e48d --- /dev/null +++ b/hlp/en/tcl/fcopy.htm @@ -0,0 +1,108 @@ +Tcl Built-In Commands - fcopy manual page +

    NAME

    +fcopy - Copy data from one channel to another. +

    SYNOPSIS

    +fcopy inchanoutchan ?-size size? ?-command callback?
    +

    DESCRIPTION

    +The fcopy command copies data from one I/O channel, inchan to another I/O channel, outchan. +The fcopy command leverages the buffering in the Tcl I/O system to +avoid extra copies and to avoid buffering too much data in +main memory when copying large files to slow destinations like +network sockets. +

    +The fcopy +command transfers data from inchan until end of file +or size bytes have been +transferred. If no -size argument is given, +then the copy goes until end of file. +All the data read from inchan is copied to outchan. +Without the -command option, fcopy blocks until the copy is complete +and returns the number of bytes written to outchan. +

    +The -command argument makes fcopy work in the background. +In this case it returns immediately and the callback is invoked +later when the copy completes. +The callback is called with +one or two additional +arguments that indicates how many bytes were written to outchan. +If an error occurred during the background copy, the second argument is the +error string associated with the error. +With a background copy, +it is not necessary to put inchan or outchan into +non-blocking mode; the fcopy command takes care of that automatically. +However, it is necessary to enter the event loop by using +the vwait command or by using Tk. +

    +You are not allowed to do other I/O operations with +inchan or outchan during a background fcopy. +If either inchan or outchan get closed +while the copy is in progress, the current copy is stopped +and the command callback is not made. +If inchan is closed, +then all data already queued for outchan is written out. +

    +Note that inchan can become readable during a background copy. +You should turn off any fileevent handlers during a background +copy so those handlers do not interfere with the copy. +Any I/O attempted by a fileevent handler will get a "channel busy" error. +

    +Fcopy translates end-of-line sequences in inchan and outchan +according to the -translation option +for these channels. +See the manual entry for fconfigure for details on the +-translation option. +The translations mean that the number of bytes read from inchan +can be different than the number of bytes written to outchan. +Only the number of bytes written to outchan is reported, +either as the return value of a synchronous fcopy or +as the argument to the callback for an asynchronous fcopy. + +

    EXAMPLE

    +This first example shows how the callback gets +passed the number of bytes transferred. +It also uses vwait to put the application into the event loop. +Of course, this simplified example could be done without the command +callback. +
    proc Cleanup {in out bytes {error {}}} {
    +    global total
    +    set total $bytes
    +    close $in
    +    close $out
    +    if {[string length $error] != 0} {
    +	# error occurred during the copy
    +    }
    +}
    +set in [open $file1]
    +set out [socket $server $port]
    +fcopy $in $out -command [list Cleanup $in $out]
    +vwait total
    +

    +The second example copies in chunks and tests for end of file +in the command callback +

    proc CopyMore {in out chunk bytes {error {}}} {
    +    global total done
    +    incr total $bytes
    +    if {([string length $error] != 0) || [eof $in] {
    +	set done $total
    +	close $in
    +	close $out
    +    } else {
    +	fcopy $in $out -command [list CopyMore $in $out $chunk] \
    +	    -size $chunk
    +    }
    +}
    +set in [open $file1]
    +set out [socket $server $port]
    +set chunk 1024
    +set total 0
    +fcopy $in $out -command [list CopyMore $in $out $chunk] -size $chunk
    +vwait done
    +

    SEE ALSO

    +eof, fblocked, fconfigure +

    KEYWORDS

    +blocking, channel, end of line, end of file, nonblocking, read, translation +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/file.htm b/hlp/en/tcl/file.htm new file mode 100644 index 0000000..f2dd988 --- /dev/null +++ b/hlp/en/tcl/file.htm @@ -0,0 +1,307 @@ +Tcl Built-In Commands - file manual page +
    +
    NAME +
    file - Manipulate file names and attributes
    +
    SYNOPSIS +
    +
    file option name ?arg arg ...? +
    +
    DESCRIPTION +
    +
    file atime name ?time? +
    file attributes name +
    file channels ?pattern? +
    file copy ?-force? ?- -? source target +
    file delete ?-force? ?- -? pathname ?pathname ... ? +
    file dirname name +
    file executable name +
    file exists name +
    file extension name +
    file isdirectory name +
    file isfile name +
    file join name ?name ...? +
    file lstat name varName +
    file mkdir dir ?dir ...? +
    file mtime name ?time? +
    file nativename name +
    file owned name +
    file pathtype name +
    file readable name +
    file readlink name +
    file rename ?-force? ?- -? source target +
    file rename ?-force? ?- -? source ?source ...? targetDir +
    file rootname name +
    file size name +
    file split name +
    file stat name varName +
    file tail name +
    file type name +
    file volume +
    file writable name +
    +
    PORTABILITY ISSUES +
    +
    Unix +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +file - Manipulate file names and attributes +

    SYNOPSIS

    +file optionname ?arg arg ...?
    +

    DESCRIPTION

    +This command provides several operations on a file's name or attributes. +Name is the name of a file; if it starts with a tilde, then tilde +substitution is done before executing the command (see the manual entry for +filename for details). Option indicates what to do with the +file name. Any unique abbreviation for option is acceptable. The +valid options are: +

    +

    +

    file atime name ?time?
    +Returns a decimal string giving the time at which file name was last +accessed. If time is specified, it is an access time to set +for the file. The time is measured in the standard POSIX fashion as +seconds from a fixed starting time (often January 1, 1970). If the file +doesn't exist or its access time cannot be queried or set then an error is +generated. On Windows, FAT file systems do not support access time. +

    file attributes name
    +
    +file attributes name ?option? +
    +file attributes name ?option value option value...? +

    +This subcommand returns or sets platform specific values associated +with a file. The first form returns a list of the platform specific +flags and their values. The second form returns the value for the +specific option. The third form sets one or more of the values. The +values are as follows: +

    +On Unix, -group gets or sets the group name for the file. A group id +can be given to the command, but it returns a group name. -owner gets +or sets the user name of the owner of the file. The command returns the +owner name, but the numerical id can be passed when setting the +owner. -permissions sets or retrieves the octal code that chmod(1) +uses. This command does also has limited support for setting using the +symbolic attributes for chmod(1), of the form [ugo]?[[+-=][rwxst],[...]], +where multiple symbolic attributes can be separated by commas (example: +u+s,go-rw add sticky bit for user, remove read and write +permissions for group and other). A simplified ls style string, +of the form rwxrwxrwx (must be 9 characters), is also supported +(example: rwxr-xr-t is equivalent to 01755). +

    +On Windows, -archive gives the value or sets or clears the +archive attribute of the file. -hidden gives the value or sets +or clears the hidden attribute of the file. -longname will +expand each path element to its long version. This attribute cannot be +set. -readonly gives the value or sets or clears the readonly +attribute of the file. -shortname gives a string where every +path element is replaced with its short (8.3) version of the +name. This attribute cannot be set. -system gives or sets or +clears the value of the system attribute of the file. +

    +On Macintosh, -creator gives or sets the Finder creator type of +the file. -hidden gives or sets or clears the hidden attribute +of the file. -readonly gives or sets or clears the readonly +attribute of the file. Note that directories can only be locked if +File Sharing is turned on. -type gives or sets the Finder file +type for the file. +

    +

    file channels ?pattern?
    +If pattern isn't specified, returns a list of names of all +registered open channels in this interpreter. If pattern is +specified, only those names matching pattern are returned. Matching +is determined using the same rules as for string match. +

    file copy ?-force? ?- -? source target
    +
    +file copy ?-force? ?- -? source ?source ...? targetDir +

    +The first form makes a copy of the file or directory source under +the pathname target. If target is an existing directory, +then the second form is used. The second form makes a copy inside +targetDir of each source file listed. If a directory is +specified as a source, then the contents of the directory will be +recursively copied into targetDir. Existing files will not be +overwritten unless the -force option is specified. Trying to +overwrite a non-empty directory, overwrite a directory with a file, or a +file with a directory will all result in errors even if -force was +specified. Arguments are processed in the order specified, halting at the +first error, if any. A - - marks the end of switches; the argument +following the - - will be treated as a source even if it +starts with a -. +
    +

    file delete ?-force? ?- -? pathname ?pathname ... ?
    +Removes the file or directory specified by each pathname argument. +Non-empty directories will be removed only if the -force option is +specified. Trying to delete a non-existant file is not considered an +error. Trying to delete a read-only file will cause the file to be deleted, +even if the -force flags is not specified. Arguments are processed +in the order specified, halting at the first error, if any. A - - +marks the end of switches; the argument following the - - will be +treated as a pathname even if it starts with a -. +

    file dirname name
    +Returns a name comprised of all of the path components in name +excluding the last element. If name is a relative file name and +only contains one path element, then returns ``.'' (or ``:'' +on the Macintosh). If name refers to a root directory, then the +root directory is returned. For example, +
    file dirname c:/
    +returns c:/. +

    +Note that tilde substitution will only be +performed if it is necessary to complete the command. For example, +

    file dirname ~/src/foo.c
    +returns ~/src, whereas +
    file dirname ~
    +returns /home (or something similar). +

    file executable name
    +Returns 1 if file name is executable by the current user, +0 otherwise. +

    file exists name
    +Returns 1 if file name exists and the current user has +search privileges for the directories leading to it, 0 otherwise. +

    file extension name
    +Returns all of the characters in name after and including the last +dot in the last element of name. If there is no dot in the last +element of name then returns the empty string. +

    file isdirectory name
    +Returns 1 if file name is a directory, 0 otherwise. +

    file isfile name
    +Returns 1 if file name is a regular file, 0 otherwise. +

    file join name ?name ...?
    +Takes one or more file names and combines them, using the correct path +separator for the current platform. If a particular name is +relative, then it will be joined to the previous file name argument. +Otherwise, any earlier arguments will be discarded, and joining will +proceed from the current argument. For example, +
    file join a b /foo bar
    +returns /foo/bar. +

    Note that any of the names can contain separators, and that the result +is always canonical for the current platform: / for Unix and +Windows, and : for Macintosh. +

    file lstat name varName
    +Same as stat option (see below) except uses the lstat +kernel call instead of stat. This means that if name +refers to a symbolic link the information returned in varName +is for the link rather than the file it refers to. On systems that +don't support symbolic links this option behaves exactly the same +as the stat option. +

    file mkdir dir ?dir ...?
    +Creates each directory specified. For each pathname dir specified, +this command will create all non-existing parent directories as +well as dir itself. If an existing directory is specified, then +no action is taken and no error is returned. Trying to overwrite an existing +file with a directory will result in an error. Arguments are processed in +the order specified, halting at the first error, if any. +

    file mtime name ?time?
    +Returns a decimal string giving the time at which file name was last +modified. If time is specified, it is a modification time to set for +the file (equivalent to Unix touch). The time is measured in the +standard POSIX fashion as seconds from a fixed starting time (often January +1, 1970). If the file doesn't exist or its modified time cannot be queried +or set then an error is generated. +

    file nativename name
    +Returns the platform-specific name of the file. This is useful if the +filename is needed to pass to a platform-specific call, such as exec +under Windows or AppleScript on the Macintosh. +

    file owned name
    +Returns 1 if file name is owned by the current user, 0 +otherwise. +

    file pathtype name
    +Returns one of absolute, relative, volumerelative. If +name refers to a specific file on a specific volume, the path type +will be absolute. If name refers to a file relative to the +current working directory, then the path type will be relative. If +name refers to a file relative to the current working directory on +a specified volume, or to a specific file on the current working volume, then +the file type is volumerelative. +

    file readable name
    +Returns 1 if file name is readable by the current user, +0 otherwise. +

    file readlink name
    +Returns the value of the symbolic link given by name (i.e. the name +of the file it points to). If name isn't a symbolic link or its +value cannot be read, then an error is returned. On systems that don't +support symbolic links this option is undefined. +

    file rename ?-force? ?- -? source target +
    file rename ?-force? ?- -? source ?source ...? targetDir
    +The first form takes the file or directory specified by pathname +source and renames it to target, moving the file if the +pathname target specifies a name in a different directory. If +target is an existing directory, then the second form is used. The +second form moves each source file or directory into the directory +targetDir. Existing files will not be overwritten unless the +-force option is specified. Trying to overwrite a non-empty +directory, overwrite a directory with a file, or a file with a directory +will all result in errors. Arguments are processed in the order specified, +halting at the first error, if any. A - - marks the end of +switches; the argument following the - - will be treated as a +source even if it starts with a -. +

    file rootname name
    +Returns all of the characters in name up to but not including the +last ``.'' character in the last component of name. If the last +component of name doesn't contain a dot, then returns name. +

    file size name
    +Returns a decimal string giving the size of file name in bytes. If +the file doesn't exist or its size cannot be queried then an error is +generated. +

    file split name
    +Returns a list whose elements are the path components in name. The +first element of the list will have the same path type as name. +All other elements will be relative. Path separators will be discarded +unless they are needed ensure that an element is unambiguously relative. +For example, under Unix +
    file split /foo/~bar/baz
    +returns / foo ./~bar baz to ensure that later commands +that use the third component do not attempt to perform tilde +substitution. +

    file stat name varName
    +Invokes the stat kernel call on name, and uses the variable +given by varName to hold information returned from the kernel call. +VarName is treated as an array variable, and the following elements +of that variable are set: atime, ctime, dev, gid, +ino, mode, mtime, nlink, size, type, +uid. Each element except type is a decimal string with the +value of the corresponding field from the stat return structure; +see the manual entry for stat for details on the meanings of the +values. The type element gives the type of the file in the same +form returned by the command file type. This command returns an +empty string. +

    file tail name
    +Returns all of the characters in name after the last directory +separator. If name contains no separators then returns +name. +

    file type name
    +Returns a string giving the type of file name, which will be one of +file, directory, characterSpecial, blockSpecial, +fifo, link, or socket. +

    file volume
    +Returns the absolute paths to the volumes mounted on the system, as a +proper Tcl list. On the Macintosh, this will be a list of the mounted +drives, both local and network. N.B. if two drives have the same name, +they will both appear on the volume list, but there is currently no way, +from Tcl, to access any but the first of these drives. On UNIX, the +command will always return "/", since all filesystems are locally mounted. +On Windows, it will return a list of the available local drives +(e.g. {a:/ c:/}). +

    file writable name
    +Returns 1 if file name is writable by the current user, +0 otherwise. +

    +

    PORTABILITY ISSUES

    +
    +

    Unix
    +These commands always operate using the real user and group identifiers, +not the effective ones. + +

    +

    SEE ALSO

    +filename +

    KEYWORDS

    +attributes, copy files, delete files, directory, file, move files, name, rename files, stat +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/fileevent.htm b/hlp/en/tcl/fileevent.htm new file mode 100644 index 0000000..7185722 --- /dev/null +++ b/hlp/en/tcl/fileevent.htm @@ -0,0 +1,95 @@ +Tcl Built-In Commands - fileevent manual page +

    NAME

    +fileevent - Execute a script when a channel becomes readable or writable +

    SYNOPSIS

    +fileevent channelId readable ?script?
    +fileevent channelId writable ?script?
    +

    DESCRIPTION

    +This command is used to create file event handlers. A file event +handler is a binding between a channel and a script, such that the script +is evaluated whenever the channel becomes readable or writable. File event +handlers are most commonly used to allow data to be received from another +process on an event-driven basis, so that the receiver can continue to +interact with the user while waiting for the data to arrive. If an +application invokes gets or read on a blocking channel when +there is no input data available, the process will block; until the input +data arrives, it will not be able to service other events, so it will +appear to the user to ``freeze up''. With fileevent, the process can +tell when data is present and only invoke gets or read when +they won't block. +

    +The channelId argument to fileevent refers to an open channel, +such as the return value from a previous open or socket +command. +If the script argument is specified, then fileevent +creates a new event handler: script will be evaluated +whenever the channel becomes readable or writable (depending on the +second argument to fileevent). +In this case fileevent returns an empty string. +The readable and writable event handlers for a file +are independent, and may be created and deleted separately. +However, there may be at most one readable and one writable +handler for a file at a given time in a given interpreter. +If fileevent is called when the specified handler already +exists in the invoking interpreter, the new script replaces the old one. +

    +If the script argument is not specified, fileevent +returns the current script for channelId, or an empty string +if there is none. +If the script argument is specified as an empty string +then the event handler is deleted, so that no script will be invoked. +A file event handler is also deleted automatically whenever +its channel is closed or its interpreter is deleted. +

    +A channel is considered to be readable if there is unread data +available on the underlying device. +A channel is also considered to be readable if there is unread +data in an input buffer, except in the special case where the +most recent attempt to read from the channel was a gets +call that could not find a complete line in the input buffer. +This feature allows a file to be read a line at a time in nonblocking mode +using events. +A channel is also considered to be readable if an end of file or +error condition is present on the underlying file or device. +It is important for script to check for these conditions +and handle them appropriately; for example, if there is no special +check for end of file, an infinite loop may occur where script +reads no data, returns, and is immediately invoked again. +

    +A channel is considered to be writable if at least one byte of data +can be written to the underlying file or device without blocking, +or if an error condition is present on the underlying file or device. +

    +Event-driven I/O works best for channels that have been +placed into nonblocking mode with the fconfigure command. +In blocking mode, a puts command may block if you give it +more data than the underlying file or device can accept, and a +gets or read command will block if you attempt to read +more data than is ready; no events will be processed while the +commands block. +In nonblocking mode puts, read, and gets never block. +See the documentation for the individual commands for information +on how they handle blocking and nonblocking channels. +

    +The script for a file event is executed at global level (outside the +context of any Tcl procedure) in the interpreter in which the +fileevent command was invoked. +If an error occurs while executing the script then the +bgerror mechanism is used to report the error. +In addition, the file event handler is deleted if it ever returns +an error; this is done in order to prevent infinite loops due to +buggy handlers. + +

    CREDITS

    +fileevent is based on the addinput command created +by Mark Diekhans. + +

    SEE ALSO

    +bgerror, fconfigure, gets, puts, read +

    KEYWORDS

    +asynchronous I/O, blocking, channel, event handler, nonblocking, readable, script, writable. +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/filename.htm b/hlp/en/tcl/filename.htm new file mode 100644 index 0000000..a404238 --- /dev/null +++ b/hlp/en/tcl/filename.htm @@ -0,0 +1,209 @@ +Tcl Built-In Commands - filename manual page +
    +
    NAME +
    filename - File name conventions supported by Tcl commands
    +
    INTRODUCTION +
    PATH TYPES +
    PATH SYNTAX +
    +
    mac +
    +
    : +
    MyFile +
    MyDisk:MyFile +
    :MyDir:MyFile +
    ::MyFile +
    :::MyFile +
    /MyDisk/MyFile +
    ../MyFile +
    +
    unix +
    +
    / +
    /etc/passwd +
    . +
    foo +
    foo/bar +
    ../foo +
    +
    windows +
    +
    \\Host\share/file +
    c:foo +
    c:/foo +
    foo\bar +
    \foo +
    +
    +
    TILDE SUBSTITUTION +
    PORTABILITY ISSUES +
    KEYWORDS +
    SEE ALSO +

    +

    NAME

    +filename - File name conventions supported by Tcl commands +

    INTRODUCTION

    +All Tcl commands and C procedures that take file names as arguments +expect the file names to be in one of three forms, depending on the +current platform. On each platform, Tcl supports file names in the +standard forms(s) for that platform. In addition, on all platforms, +Tcl supports a Unix-like syntax intended to provide a convenient way +of constructing simple file names. However, scripts that are intended +to be portable should not assume a particular form for file names. +Instead, portable scripts must use the file split and file +join commands to manipulate file names (see the file manual +entry for more details). + +

    PATH TYPES

    +File names are grouped into three general types based on the starting point +for the path used to specify the file: absolute, relative, and +volume-relative. Absolute names are completely qualified, giving a path to +the file relative to a particular volume and the root directory on that +volume. Relative names are unqualified, giving a path to the file relative +to the current working directory. Volume-relative names are partially +qualified, either giving the path relative to the root directory on the +current volume, or relative to the current directory of the specified +volume. The file pathtype command can be used to determine the +type of a given path. + +

    PATH SYNTAX

    +The rules for native names depend on the value reported in the Tcl +array element tcl_platform(platform): +

    +

    +

    mac
    +On Apple Macintosh systems, Tcl supports two forms of path names. The +normal Mac style names use colons as path separators. Paths may be +relative or absolute, and file names may contain any character other +than colon. A leading colon causes the rest of the path to be +interpreted relative to the current directory. If a path contains a +colon that is not at the beginning, then the path is interpreted as an +absolute path. Sequences of two or more colons anywhere in the path +are used to construct relative paths where :: refers to the +parent of the current directory, ::: refers to the parent of the +parent, and so forth. +

    +In addition to Macintosh style names, Tcl also supports a subset of +Unix-like names. If a path contains no colons, then it is interpreted +like a Unix path. Slash is used as the path separator. The file name + . refers to the current directory, and .. refers to the +parent of the current directory. However, some names like / or +/.. have no mapping, and are interpreted as Macintosh names. In +general, commands that generate file names will return Macintosh style +names, but commands that accept file names will take both Macintosh +and Unix-style names. +

    +The following examples illustrate various forms of path names: +

    +

    +

    :
    +Relative path to the current folder. +

    MyFile
    +Relative path to a file named MyFile in the current folder. +

    MyDisk:MyFile
    +Absolute path to a file named MyFile on the device named MyDisk. +

    :MyDir:MyFile
    +Relative path to a file name MyFile in a folder named +MyDir in the current folder. +

    ::MyFile
    +Relative path to a file named MyFile in the folder above the +current folder. +

    :::MyFile
    +Relative path to a file named MyFile in the folder two levels above the +current folder. +

    /MyDisk/MyFile
    +Absolute path to a file named MyFile on the device named +MyDisk. +

    ../MyFile
    +Relative path to a file named MyFile in the folder above the +current folder. +

    +

    unix
    +On Unix platforms, Tcl uses path names where the components are +separated by slashes. Path names may be relative or absolute, and +file names may contain any character other than slash. The file names + . and .. are special and refer to the current directory +and the parent of the current directory respectively. Multiple +adjacent slash characters are interpreted as a single separator. +The following examples illustrate various forms of path names: +

    +

    +

    /
    +Absolute path to the root directory. +

    /etc/passwd
    +Absolute path to the file named passwd in the directory +etc in the root directory. +

    .
    +Relative path to the current directory. +

    foo
    +Relative path to the file foo in the current directory. +

    foo/bar
    +Relative path to the file bar in the directory foo in the +current directory. +

    ../foo
    +Relative path to the file foo in the directory above the current +directory. +

    +

    windows
    +On Microsoft Windows platforms, Tcl supports both drive-relative and UNC +style names. Both / and \ may be used as directory separators +in either type of name. Drive-relative names consist of an optional drive +specifier followed by an absolute or relative path. UNC paths follow the +general form \\servername\sharename\path\file. In both forms, +the file names . and .. are special and refer to the current +directory and the parent of the current directory respectively. The +following examples illustrate various forms of path names: +

    +

    +

    \\Host\share/file
    +Absolute UNC path to a file called file in the root directory of +the export point share on the host Host. +

    c:foo
    +Volume-relative path to a file foo in the current directory on drive +c. +

    c:/foo
    +Absolute path to a file foo in the root directory of drive +c. +

    foo\bar
    +Relative path to a file bar in the foo directory in the current +directory on the current volume. +

    \foo
    +Volume-relative path to a file foo in the root directory of the current +volume. +

    +

    +

    TILDE SUBSTITUTION

    +In addition to the file name rules described above, Tcl also supports +csh-style tilde substitution. If a file name starts with a +tilde, then the file name will be interpreted as if the first element +is replaced with the location of the home directory for the given +user. If the tilde is followed immediately by a separator, then the +$HOME environment variable is substituted. Otherwise the +characters between the tilde and the next separator are taken as a +user name, which is used to retrieve the user's home directory for +substitution. +

    +The Macintosh and Windows platforms do not support tilde substitution +when a user name follows the tilde. On these platforms, attempts to +use a tilde followed by a user name will generate an error. File +names that have a tilde without a user name will be substituted using +the $HOME environment variable, just like for Unix. + +

    PORTABILITY ISSUES

    +Not all file systems are case sensitive, so scripts should avoid code +that depends on the case of characters in a file name. In addition, +the character sets allowed on different devices may differ, so scripts +should choose file names that do not contain special characters like: +<>:"/\|. The safest approach is to use names consisting of +alphanumeric characters only. Also Windows 3.1 only supports file +names with a root of no more than 8 characters and an extension of no +more than 3 characters. + +

    KEYWORDS

    +current directory, absolute file name, relative file name, volume-relative file name, portability +

    SEE ALSO

    +file, glob +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/flush.htm b/hlp/en/tcl/flush.htm new file mode 100644 index 0000000..f1eb8e2 --- /dev/null +++ b/hlp/en/tcl/flush.htm @@ -0,0 +1,24 @@ +Tcl Built-In Commands - flush manual page +

    NAME

    +flush - Flush buffered output for a channel +

    SYNOPSIS

    +flush channelId
    +

    DESCRIPTION

    +Flushes any output that has been buffered for channelId. +ChannelId must be a channel identifier such as returned by a previous +open or socket command, and it must have been opened for writing. +If the channel is in blocking mode the command does not return until all the +buffered output has been flushed to the channel. If the channel is in +nonblocking mode, the command may return before all buffered output has been +flushed; the remainder will be flushed in the background as fast as the +underlying file or device is able to absorb it. + +

    SEE ALSO

    +file, open, socket +

    KEYWORDS

    +blocking, buffer, channel, flush, nonblocking, output +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/for.htm b/hlp/en/tcl/for.htm new file mode 100644 index 0000000..57a2a67 --- /dev/null +++ b/hlp/en/tcl/for.htm @@ -0,0 +1,49 @@ +Built-In Commands - for manual page +

    NAME

    +for - ``For'' loop +

    SYNOPSIS

    +for start test next body
    +

    DESCRIPTION

    +For is a looping command, similar in structure to the C +for statement. The start, next, and +body arguments must be Tcl command strings, and test +is an expression string. +The for command first invokes the Tcl interpreter to +execute start. Then it repeatedly evaluates test as +an expression; if the result is non-zero it invokes the Tcl +interpreter on body, then invokes the Tcl interpreter on next, +then repeats the loop. The command terminates when test evaluates +to 0. If a continue command is invoked within body then +any remaining commands in the current execution of body are skipped; +processing continues by invoking the Tcl interpreter on next, then +evaluating test, and so on. If a break command is invoked +within body +or next, +then the for command will +return immediately. +The operation of break and continue are similar to the +corresponding statements in C. +For returns an empty string. +

    +Note: test should almost always be enclosed in braces. If not, +variable substitutions will be made before the for +command starts executing, which means that variable changes +made by the loop body will not be considered in the expression. +This is likely to result in an infinite loop. If test is +enclosed in braces, variable substitutions are delayed until the +expression is evaluated (before +each loop iteration), so changes in the variables will be visible. +For an example, try the following script with and without the braces +around $x<10: +

    for {set x 0} {$x<10} {incr x} {
    +	puts "x is $x"
    +}
    +

    SEE ALSO

    +break, continue, foreach, while +

    KEYWORDS

    +for, iteration, looping +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/foreach.htm b/hlp/en/tcl/foreach.htm new file mode 100644 index 0000000..6d77e48 --- /dev/null +++ b/hlp/en/tcl/foreach.htm @@ -0,0 +1,70 @@ +Built-In Commands - foreach manual page +

    NAME

    +foreach - Iterate over all elements in one or more lists +

    SYNOPSIS

    +foreach varname list body
    +foreach varlist1 list1 ?varlist2 list2 ...? body
    +

    DESCRIPTION

    +The foreach command implements a loop where the loop +variable(s) take on values from one or more lists. +In the simplest case there is one loop variable, varname, +and one list, list, that is a list of values to assign to varname. +The body argument is a Tcl script. +For each element of list (in order +from first to last), foreach assigns the contents of the +element to varname as if the lindex command had been used +to extract the element, then calls the Tcl interpreter to execute +body. +

    +In the general case there can be more than one value list +(e.g., list1 and list2), +and each value list can be associated with a list of loop variables +(e.g., varlist1 and varlist2). +During each iteration of the loop +the variables of each varlist are assigned +consecutive values from the corresponding list. +Values in each list are used in order from first to last, +and each value is used exactly once. +The total number of loop iterations is large enough to use +up all the values from all the value lists. +If a value list does not contain enough +elements for each of its loop variables in each iteration, +empty values are used for the missing elements. +

    +The break and continue statements may be +invoked inside body, with the same effect as in the for +command. Foreach returns an empty string. +

    EXAMPLES

    +The following loop uses i and j as loop variables to iterate over +pairs of elements of a single list. +
    set x {}
    +foreach {i j} {a b c d e f} {
    +    lappend x $j $i
    +}
    +# The value of x is "b a d c f e"
    +# There are 3 iterations of the loop.
    +

    +The next loop uses i and j to iterate over two lists in parallel. +

    set x {}
    +foreach i {a b c} j {d e f g} {
    +    lappend x $i $j
    +}
    +# The value of x is "a d b e c f {} g"
    +# There are 4 iterations of the loop.
    +

    +The two forms are combined in the following example. +

    set x {}
    +foreach i {a b c} {j k} {d e f g} {
    +    lappend x $i $j $k
    +}
    +# The value of x is "a d e b f g c {} {}"
    +# There are 3 iterations of the loop.
    +

    SEE ALSO

    +for, while, break, continue +

    KEYWORDS

    +foreach, iteration, list, looping +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/format.htm b/hlp/en/tcl/format.htm new file mode 100644 index 0000000..363d8e8 --- /dev/null +++ b/hlp/en/tcl/format.htm @@ -0,0 +1,230 @@ +Tcl Built-In Commands - format manual page +
    +
    NAME +
    format - Format a string in the style of sprintf
    +
    SYNOPSIS +
    +
    format formatString ?arg arg ...? +
    +
    INTRODUCTION +
    DETAILS ON FORMATTING +
    +
    - +
    + +
    space +
    0 +
    # +
    +
    +
    d +
    u +
    i +
    o +
    x or X +
    c +
    s +
    f +
    e or e +
    g or G +
    % +
    +
    DIFFERENCES FROM ANSI SPRINTF +
    +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +format - Format a string in the style of sprintf +

    SYNOPSIS

    +format formatString ?arg arg ...?
    +

    INTRODUCTION

    +This command generates a formatted string in the same way as the +ANSI C sprintf procedure (it uses sprintf in its +implementation). +FormatString indicates how to format the result, using +% conversion specifiers as in sprintf, and the additional +arguments, if any, provide values to be substituted into the result. +The return value from format is the formatted string. + +

    DETAILS ON FORMATTING

    +The command operates by scanning formatString from left to right. +Each character from the format string is appended to the result +string unless it is a percent sign. +If the character is a % then it is not copied to the result string. +Instead, the characters following the % character are treated as +a conversion specifier. +The conversion specifier controls the conversion of the next successive +arg to a particular format and the result is appended to +the result string in place of the conversion specifier. +If there are multiple conversion specifiers in the format string, +then each one controls the conversion of one additional arg. +The format command must be given enough args to meet the needs +of all of the conversion specifiers in formatString. +

    +Each conversion specifier may contain up to six different parts: +an XPG3 position specifier, +a set of flags, a minimum field width, a precision, a length modifier, +and a conversion character. +Any of these fields may be omitted except for the conversion character. +The fields that are present must appear in the order given above. +The paragraphs below discuss each of these fields in turn. +

    +If the % is followed by a decimal number and a $, as in +``%2$d'', then the value to convert is not taken from the +next sequential argument. +Instead, it is taken from the argument indicated by the number, +where 1 corresponds to the first arg. +If the conversion specifier requires multiple arguments because +of * characters in the specifier then +successive arguments are used, starting with the argument +given by the number. +This follows the XPG3 conventions for positional specifiers. +If there are any positional specifiers in formatString +then all of the specifiers must be positional. +

    +The second portion of a conversion specifier may contain any of the +following flag characters, in any order: +

    +

    +

    -
    +Specifies that the converted argument should be left-justified +in its field (numbers are normally right-justified with leading +spaces if needed). +

    +
    +Specifies that a number should always be printed with a sign, +even if positive. +

    space
    +Specifies that a space should be added to the beginning of the +number if the first character isn't a sign. +

    0
    +Specifies that the number should be padded on the left with +zeroes instead of spaces. +

    #
    +Requests an alternate output form. For o and O +conversions it guarantees that the first digit is always 0. +For x or X conversions, 0x or 0X (respectively) +will be added to the beginning of the result unless it is zero. +For all floating-point conversions (e, E, f, +g, and G) it guarantees that the result always +has a decimal point. +For g and G conversions it specifies that +trailing zeroes should not be removed. +

    +

    +The third portion of a conversion specifier is a number giving a +minimum field width for this conversion. +It is typically used to make columns line up in tabular printouts. +If the converted argument contains fewer characters than the +minimum field width then it will be padded so that it is as wide +as the minimum field width. +Padding normally occurs by adding extra spaces on the left of the +converted argument, but the 0 and - flags +may be used to specify padding with zeroes on the left or with +spaces on the right, respectively. +If the minimum field width is specified as * rather than +a number, then the next argument to the format command +determines the minimum field width; it must be a numeric string. +

    +The fourth portion of a conversion specifier is a precision, +which consists of a period followed by a number. +The number is used in different ways for different conversions. +For e, E, and f conversions it specifies the number +of digits to appear to the right of the decimal point. +For g and G conversions it specifies the total number +of digits to appear, including those on both sides of the decimal +point (however, trailing zeroes after the decimal point will still +be omitted unless the # flag has been specified). +For integer conversions, it specifies a minimum number of digits +to print (leading zeroes will be added if necessary). +For s conversions it specifies the maximum number of characters to be +printed; if the string is longer than this then the trailing characters will be dropped. +If the precision is specified with * rather than a number +then the next argument to the format command determines the precision; +it must be a numeric string. +

    +The fifth part of a conversion specifier is a length modifier, +which must be h or l. +If it is h it specifies that the numeric value should be +truncated to a 16-bit value before converting. +This option is rarely useful. +The l modifier is ignored. +

    +The last thing in a conversion specifier is an alphabetic character +that determines what kind of conversion to perform. +The following conversion characters are currently supported: +

    +

    +

    d
    +Convert integer to signed decimal string. +

    u
    +Convert integer to unsigned decimal string. +

    i
    +Convert integer to signed decimal string; the integer may either be +in decimal, in octal (with a leading 0) or in hexadecimal +(with a leading 0x). +

    o
    +Convert integer to unsigned octal string. +

    x or X
    +Convert integer to unsigned hexadecimal string, using digits +``0123456789abcdef'' for x and ``0123456789ABCDEF'' for X). +

    c
    +Convert integer to the Unicode character it represents. +

    s
    +No conversion; just insert string. +

    f
    +Convert floating-point number to signed decimal string of +the form xx.yyy, where the number of y's is determined by +the precision (default: 6). +If the precision is 0 then no decimal point is output. +

    e or e
    +Convert floating-point number to scientific notation in the +form x.yyyzz, where the number of y's is determined +by the precision (default: 6). +If the precision is 0 then no decimal point is output. +If the E form is used then E is +printed instead of e. +

    g or G
    +If the exponent is less than -4 or greater than or equal to the +precision, then convert floating-point number as for %e or +%E. +Otherwise convert as for %f. +Trailing zeroes and a trailing decimal point are omitted. +

    %
    +No conversion: just insert %. +

    +

    +For the numerical conversions the argument being converted must +be an integer or floating-point string; format converts the argument +to binary and then converts it back to a string according to +the conversion specifier. + +

    DIFFERENCES FROM ANSI SPRINTF

    +The behavior of the format command is the same as the +ANSI C sprintf procedure except for the following +differences: +

    +

    +

    [1]
    +%p and %n specifiers are not currently supported. +

    [2]
    +For %c conversions the argument must be a decimal string, +which will then be converted to the corresponding character value. +

    [3]
    +The l modifier is ignored; integer values are always converted +as if there were no modifier present and real values are always +converted as if the l modifier were present (i.e. type +double is used for the internal representation). +If the h modifier is specified then integer values are truncated +to short before conversion. + +

    +

    SEE ALSO

    +sprintf, string +

    KEYWORDS

    +conversion specifier, format, sprintf, string, substitution +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/gets.htm b/hlp/en/tcl/gets.htm new file mode 100644 index 0000000..be851e9 --- /dev/null +++ b/hlp/en/tcl/gets.htm @@ -0,0 +1,39 @@ +Tcl Built-In Commands - gets manual page +

    NAME

    +gets - Read a line from a channel +

    SYNOPSIS

    +gets channelId ?varName?
    +

    DESCRIPTION

    +This command reads the next line from channelId, returns everything +in the line up to (but not including) the end-of-line character(s), and +discards the end-of-line character(s). +If varName is omitted the line is returned as the result of the +command. +If varName is specified then the line is placed in the variable by +that name and the return value is a count of the number of characters +returned. +

    +If end of file occurs while scanning for an end of +line, the command returns whatever input is available up to the end of file. +If channelId is in nonblocking mode and there is not a full +line of input available, the command returns an empty string and +does not consume any input. +If varName is specified and an empty string is returned in +varName because of end-of-file or because of insufficient +data in nonblocking mode, then the return count is -1. +Note that if varName is not specified then the end-of-file +and no-full-line-available cases can +produce the same results as if there were an input line consisting +only of the end-of-line character(s). +The eof and fblocked commands can be used to distinguish +these three cases. + +

    SEE ALSO

    +file, eof, fblocked +

    KEYWORDS

    +blocking, channel, end of file, end of line, line, nonblocking, read +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/glob.htm b/hlp/en/tcl/glob.htm new file mode 100644 index 0000000..5b7f485 --- /dev/null +++ b/hlp/en/tcl/glob.htm @@ -0,0 +1,164 @@ +Tcl Built-In Commands - glob manual page +
    +
    NAME +
    glob - Return names of files that match patterns
    +
    SYNOPSIS +
    +
    glob ?switches? pattern ?pattern ...? +
    +
    DESCRIPTION +
    +
    -directory directory +
    -join +
    -nocomplain +
    -path pathPrefix +
    -types typeList +
    - - +
    +
    +
    ? +
    * +
    [chars] +
    \x +
    {a,b,...} +
    +
    PORTABILITY ISSUES +
    +
    Windows +
    Macintosh +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +glob - Return names of files that match patterns +

    SYNOPSIS

    +glob ?switches? pattern ?pattern ...?
    +

    DESCRIPTION

    +This command performs file name ``globbing'' in a fashion similar to +the csh shell. It returns a list of the files whose names match any +of the pattern arguments. +

    +If the initial arguments to glob start with - then +they are treated as switches. The following switches are +currently supported: +

    +

    +

    -directory directory
    +Search for files which match the given patterns starting in the given +directory. This allows searching of directories whose name +contains glob-sensitive characters without the need to quote such +characters explicitly. This option may not be used in conjunction with +-path. +

    -join
    +The remaining pattern arguments are treated as a single pattern +obtained by joining the arguments with directory separators. +

    -nocomplain
    +Allows an empty list to be returned without error; without this +switch an error is returned if the result list would be empty. +

    -path pathPrefix
    +Search for files with the given pathPrefix where the rest of the name +matches the given patterns. This allows searching for files with names +similar to a given file even when the names contain glob-sensitive +characters. This option may not be used in conjunction with +-directory. +

    -types typeList
    +Only list files or directories which match typeList, where the items +in the list have two forms. The first form is like the -type option of +the Unix find command: +b (block special file), +c (character special file), +d (directory), +f (plain file), +l (symbolic link), +p (named pipe), +or s (socket), where multiple types may be specified in the list. +Glob will return all files which match at least one of the types given. +

    +The second form specifies types where all the types given must match. +These are r, w, x as file permissions, and +readonly, hidden as special permission cases. On the +Macintosh, MacOS types and creators are also supported, where any item +which is four characters long is assumed to be a MacOS type +(e.g. TEXT). Items which are of the form {macintosh type XXXX} +or {macintosh creator XXXX} will match types or creators +respectively. Unrecognised types, or specifications of multiple MacOS +types/creators will signal an error. +

    +The two forms may be mixed, so -types {d f r w} will find all +regular files OR directories that have both read AND write permissions. +The following are equivalent: +

    glob -type d *
    +glob */
    +except that the first case doesn't return the trailing ``/'' and +is more platform independent. +

    - -
    +Marks the end of switches. The argument following this one will +be treated as a pattern even if it starts with a -. +

    +

    +The pattern arguments may contain any of the following +special characters: +

    +

    +

    ?
    +Matches any single character. +

    *
    +Matches any sequence of zero or more characters. +

    [chars]
    +Matches any single character in chars. If chars +contains a sequence of the form a-b then any +character between a and b (inclusive) will match. +

    \x
    +Matches the character x. +

    {a,b,...}
    +Matches any of the strings a, b, etc. +

    +

    +As with csh, a ``.'' at the beginning of a file's name or just +after a ``/'' must be matched explicitly or with a {} construct. +In addition, all ``/'' characters must be matched explicitly. +

    +If the first character in a pattern is ``~'' then it refers +to the home directory for the user whose name follows the ``~''. +If the ``~'' is followed immediately by ``/'' then the value of +the HOME environment variable is used. +

    +The glob command differs from csh globbing in two ways. +First, it does not sort its result list (use the lsort +command if you want the list sorted). +Second, glob only returns the names of files that actually +exist; in csh no check for existence is made unless a pattern +contains a ?, *, or [] construct. + +

    PORTABILITY ISSUES

    +Unlike other Tcl commands that will accept both network and native +style names (see the filename manual entry for details on how +native and network names are specified), the glob command only +accepts native names. +

    +

    +

    Windows
    +For Windows UNC names, the servername and sharename components of the path +may not contain ?, *, or [] constructs. On Windows NT, if pattern is +of the form ``~username@domain'' it refers to the home +directory of the user whose account information resides on the specified NT +domain server. Otherwise, user account information is obtained from +the local computer. On Windows 95 and 98, glob accepts patterns +like ``.../'' and ``..../'' for successively higher up parent directories. +

    Macintosh
    +When using the options, -dir, -join or -path, glob +assumes the directory separator for the entire pattern is the standard +``:''. When not using these options, glob examines each pattern argument +and uses ``/'' unless the pattern contains a ``:''. + +

    +

    SEE ALSO

    +file +

    KEYWORDS

    +exist, file, glob, pattern +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/global.htm b/hlp/en/tcl/global.htm new file mode 100644 index 0000000..2f752e3 --- /dev/null +++ b/hlp/en/tcl/global.htm @@ -0,0 +1,28 @@ +Built-In Commands - global manual page +

    NAME

    +global - Access global variables +

    SYNOPSIS

    +global varname ?varname ...?
    +

    DESCRIPTION

    +This command is ignored unless a Tcl procedure is being interpreted. +If so then it declares the given varname's to be global variables +rather than local ones. +Global variables are variables in the global namespace. +For the duration of the current procedure +(and only while executing in the current procedure), +any reference to any of the varnames +will refer to the global variable by the same name. +

    +Please note that this is done by creating local variables that are +linked to the global variables, and therefore that these variables +will be listed by info locals like all other local variables. + +

    SEE ALSO

    +namespace, upvar, variable +

    KEYWORDS

    +global, namespace, procedure, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/history.htm b/hlp/en/tcl/history.htm new file mode 100644 index 0000000..00fd169 --- /dev/null +++ b/hlp/en/tcl/history.htm @@ -0,0 +1,114 @@ +Built-In Commands - history manual page +
    +
    NAME +
    history - Manipulate the history list
    +
    SYNOPSIS +
    +
    history ?option? ?arg arg ...? +
    +
    DESCRIPTION +
    +
    +
    +
    history +
    history add command ?exec? +
    history change newValue ?event? +
    history clear +
    history event ?event? +
    history info ?count? +
    history keep ?count? +
    history nextid +
    history redo ?event? +
    +
    HISTORY REVISION +
    KEYWORDS +

    +

    NAME

    +history - Manipulate the history list +

    SYNOPSIS

    +history ?option? ?arg arg ...?
    +

    DESCRIPTION

    +The history command performs one of several operations related to +recently-executed commands recorded in a history list. Each of +these recorded commands is referred to as an ``event''. When +specifying an event to the history command, the following +forms may be used: +

    +

    +

    [1]
    +A number: if positive, it refers to the event with +that number (all events are numbered starting at 1). If the number +is negative, it selects an event relative to the current event +(-1 refers to the previous event, -2 to the one before that, and +so on). Event 0 refers to the current event. +

    [2]
    +A string: selects the most recent event that matches the string. +An event is considered to match the string either if the string is +the same as the first characters of the event, or if the string +matches the event in the sense of the string match command. +

    +

    +The history command can take any of the following forms: +

    +

    +

    history
    +Same +as history info, described below. +

    history add command ?exec?
    +Adds the command argument to the history list as a new event. If +exec is specified (or abbreviated) then the command is also +executed and its result is returned. If exec isn't specified +then an empty string is returned as result. +

    history change newValue ?event?
    +Replaces the value recorded for an event with newValue. Event +specifies the event to replace, and +defaults to the current event (not event -1). This command +is intended for use in commands that implement new forms of history +substitution and wish to replace the current event (which invokes the +substitution) with the command created through substitution. The return +value is an empty string. +

    history clear
    +Erase the history list. The current keep limit is retained. +The history event numbers are reset. +

    history event ?event?
    +Returns the value of the event given by event. Event +defaults to -1. +

    history info ?count?
    +Returns a formatted string (intended for humans to read) giving +the event number and contents for each of the events in the history +list except the current event. If count is specified +then only the most recent count events are returned. +

    history keep ?count?
    +This command may be used to change the size of the history list to +count events. Initially, 20 events are retained in the history +list. If count is not specified, the current keep limit is returned. +

    history nextid
    +Returns the number of the next event to be recorded +in the history list. It is useful for things like printing the +event number in command-line prompts. +

    history redo ?event?
    +Re-executes the command indicated by event and return its result. +Event defaults to -1. This command results in history +revision: see below for details. +

    +

    HISTORY REVISION

    +Pre-8.0 Tcl had a complex history revision mechanism. +The current mechanism is more limited, and the old +history operations substitute and words have been removed. +(As a consolation, the clear operation was added.) +

    +The history option redo results in much simpler ``history revision''. +When this option is invoked then the most recent event +is modified to eliminate the history command and replace it with +the result of the history command. +If you want to redo an event without modifying history, then use +the event operation to retrieve some event, +and the add operation to add it to history and execute it. + +

    KEYWORDS

    +event, history, record +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/http.htm b/hlp/en/tcl/http.htm new file mode 100644 index 0000000..c39e5a7 --- /dev/null +++ b/hlp/en/tcl/http.htm @@ -0,0 +1,522 @@ +Tcl Built-In Commands - Http manual page +
    +
    NAME +
    Http - Client-side implementation of the HTTP/1.0 protocol.
    +
    SYNOPSIS +
    +
    package require http ?2.4? +
    ::http::config ?options? +
    ::http::geturl url ?options? +
    ::http::formatQuery list +
    ::http::reset token +
    ::http::wait token +
    ::http::status token +
    ::http::size token +
    ::http::code token +
    ::http::ncode token +
    ::http::data token +
    ::http::error token +
    ::http::cleanup token +
    ::http::register proto port command +
    ::http::unregister proto +
    +
    DESCRIPTION +
    COMMANDS +
    +
    ::http::config ?options? +
    +
    -accept mimetypes +
    -proxyhost hostname +
    -proxyport number +
    -proxyfilter command +
    -useragent string +
    +
    ::http::geturl url ?options? +
    +
    -binary boolean +
    -blocksize size +
    -channel name +
    -command callback +
    -handler callback +
    -headers keyvaluelist +
    -progress callback +
    -query query +
    -queryblocksize size +
    -querychannel channelID +
    -queryprogress callback +
    -timeout milliseconds +
    -type mime-type +
    -validate boolean +
    +
    ::http::formatQuery key value ?key value ...? +
    ::http::reset token ?why? +
    ::http::wait token +
    ::http::data token +
    ::http::error token +
    ::http::status token +
    ::http::code token +
    ::http::ncode token +
    ::http::size token +
    ::http::cleanup token +
    ::http::register proto port command +
    ::http::unregister proto +
    +
    ERRORS +
    +
    ok +
    eof +
    error +
    +
    STATE ARRAY +
    +
    body +
    charset +
    coding +
    currentsize +
    error +
    http +
    meta +
    +
    Content-Type +
    Content-Length +
    Location +
    +
    posterror +
    status +
    totalsize +
    type +
    url +
    +
    EXAMPLE +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +Http - Client-side implementation of the HTTP/1.0 protocol. +

    SYNOPSIS

    +package require http ?2.4?
    +::http::config ?options?
    +::http::geturl url ?options?
    +::http::formatQuery list
    +::http::reset token
    +::http::wait token
    +::http::status token
    +::http::size token
    +::http::code token
    +::http::ncode token
    +::http::data token
    +::http::error token
    +::http::cleanup token
    +::http::register proto port command
    +::http::unregister proto
    +

    DESCRIPTION

    +The http package provides the client side of the HTTP/1.0 +protocol. The package implements the GET, POST, and HEAD operations +of HTTP/1.0. It allows configuration of a proxy host to get through +firewalls. The package is compatible with the Safesock security +policy, so it can be used by untrusted applets to do URL fetching from +a restricted set of hosts. This package can be extened to support +additional HTTP transport protocols, such as HTTPS, by providing +a custom socket command, via http::register. +

    +The ::http::geturl procedure does a HTTP transaction. +Its options determine whether a GET, POST, or HEAD transaction +is performed. +The return value of ::http::geturl is a token for the transaction. +The value is also the name of an array in the ::http namespace +that contains state information about the transaction. The elements +of this array are described in the STATE ARRAY section. +

    +If the -command option is specified, then +the HTTP operation is done in the background. +::http::geturl returns immediately after generating the +HTTP request and the callback is invoked +when the transaction completes. For this to work, the Tcl event loop +must be active. In Tk applications this is always true. For pure-Tcl +applications, the caller can use ::http::wait after calling +::http::geturl to start the event loop. +

    COMMANDS

    +
    +

    ::http::config ?options?
    +The ::http::config command is used to set and query the name of the +proxy server and port, and the User-Agent name used in the HTTP +requests. If no options are specified, then the current configuration +is returned. If a single argument is specified, then it should be one +of the flags described below. In this case the current value of +that setting is returned. Otherwise, the options should be a set of +flags and values that define the configuration: +

    +

    +

    -accept mimetypes
    +The Accept header of the request. The default is */*, which means that +all types of documents are accepted. Otherwise you can supply a +comma separated list of mime type patterns that you are +willing to receive. For example, "image/gif, image/jpeg, text/*". +

    -proxyhost hostname
    +The name of the proxy host, if any. If this value is the +empty string, the URL host is contacted directly. +

    -proxyport number
    +The proxy port number. +

    -proxyfilter command
    +The command is a callback that is made during +::http::geturl +to determine if a proxy is required for a given host. One argument, a +host name, is added to command when it is invoked. If a proxy +is required, the callback should return a two element list containing +the proxy server and proxy port. Otherwise the filter should return +an empty list. The default filter returns the values of the +-proxyhost and -proxyport settings if they are +non-empty. +

    -useragent string
    +The value of the User-Agent header in the HTTP request. The default +is "Tcl http client package 2.2." +

    +

    ::http::geturl url ?options?
    +The ::http::geturl command is the main procedure in the package. +The -query option causes a POST operation and +the -validate option causes a HEAD operation; +otherwise, a GET operation is performed. The ::http::geturl command +returns a token value that can be used to get +information about the transaction. See the STATE ARRAY and ERRORS section for +details. The ::http::geturl command blocks until the operation +completes, unless the -command option specifies a callback +that is invoked when the HTTP transaction completes. +::http::geturl takes several options: +

    +

    +

    -binary boolean
    +Specifies whether to force interpreting the url data as binary. Normally +this is auto-detected (anything not beginning with a text content +type or whose content encoding is gzip or compress is +considered binary data). +

    -blocksize size
    +The blocksize used when reading the URL. +At most size bytes are read at once. After each block, a call to the +-progress callback is made (if that option is specified). +

    -channel name
    +Copy the URL contents to channel name instead of saving it in +state(body). +

    -command callback
    +Invoke callback after the HTTP transaction completes. +This option causes ::http::geturl to return immediately. +The callback gets an additional argument that is the token returned +from ::http::geturl. This token is the name of an array that is +described in the STATE ARRAY section. Here is a template for the +callback: +
    proc httpCallback {token} {
    +    upvar #0 $token state
    +    # Access state as a Tcl array
    +}
    +

    -handler callback
    +Invoke callback whenever HTTP data is available; if present, nothing +else will be done with the HTTP data. This procedure gets two additional +arguments: the socket for the HTTP data and the token returned from +::http::geturl. The token is the name of a global array that is described +in the STATE ARRAY section. The procedure is expected to return the number +of bytes read from the socket. Here is a template for the callback: +
    proc httpHandlerCallback {socket token} {
    +    upvar #0 $token state
    +    # Access socket, and state as a Tcl array
    +    ...
    +    (example: set data [read $socket 1000];set nbytes [string length $data])
    +    ...
    +    return nbytes
    +}
    +

    -headers keyvaluelist
    +This option is used to add extra headers to the HTTP request. The +keyvaluelist argument must be a list with an even number of +elements that alternate between keys and values. The keys become +header field names. Newlines are stripped from the values so the +header cannot be corrupted. For example, if keyvaluelist is +Pragma no-cache then the following header is included in the +HTTP request: +
    Pragma: no-cache
    +

    -progress callback
    +The callback is made after each transfer of data from the URL. +The callback gets three additional arguments: the token from +::http::geturl, the expected total size of the contents from the +Content-Length meta-data, and the current number of bytes +transferred so far. The expected total size may be unknown, in which +case zero is passed to the callback. Here is a template for the +progress callback: +
    proc httpProgress {token total current} {
    +    upvar #0 $token state
    +}
    +

    -query query
    +This flag causes ::http::geturl to do a POST request that passes the +query to the server. The query must be a x-url-encoding +formatted query. The ::http::formatQuery procedure can be used to +do the formatting. +

    -queryblocksize size
    +The blocksize used when posting query data to the URL. +At most +size +bytes are written at once. After each block, a call to the +-queryprogress +callback is made (if that option is specified). +

    -querychannel channelID
    +This flag causes ::http::geturl to do a POST request that passes the +data contained in channelID to the server. The data contained in channelID must be a x-url-encoding +formatted query unless the -type option below is used. +If a Content-Length header is not specified via the -headers options, +::http::geturl attempts to determine the size of the post data +in order to create that header. If it is +unable to determine the size, it returns an error. +

    -queryprogress callback
    +The callback is made after each transfer of data to the URL +(i.e. POST) and acts exactly like the -progress option (the +callback format is the same). +

    -timeout milliseconds
    +If milliseconds is non-zero, then ::http::geturl sets up a timeout +to occur after the specified number of milliseconds. +A timeout results in a call to ::http::reset and to +the -command callback, if specified. +The return value of ::http::status is timeout +after a timeout has occurred. +

    -type mime-type
    +Use mime-type as the Content-Type value, instead of the +default value (application/x-www-form-urlencoded) during a +POST operation. +

    -validate boolean
    +If boolean is non-zero, then ::http::geturl does an HTTP HEAD +request. This request returns meta information about the URL, but the +contents are not returned. The meta information is available in the +state(meta) variable after the transaction. See the STATE +ARRAY section for details. +

    +

    ::http::formatQuery key value ?key value ...?
    +This procedure does x-url-encoding of query data. It takes an even +number of arguments that are the keys and values of the query. It +encodes the keys and values, and generates one string that has the +proper & and = separators. The result is suitable for the +-query value passed to ::http::geturl. +

    ::http::reset token ?why?
    +This command resets the HTTP transaction identified by token, if +any. This sets the state(status) value to why, which defaults to reset, and then calls the registered -command callback. +

    ::http::wait token
    +This is a convenience procedure that blocks and waits for the +transaction to complete. This only works in trusted code because it +uses vwait. Also, it's not useful for the case where +::http::geturl is called without the -command option +because in this case the ::http::geturl call doesn't return +until the HTTP transaction is complete, and thus there's nothing to +wait for. +

    ::http::data token
    +This is a convenience procedure that returns the body element +(i.e., the URL data) of the state array. +

    ::http::error token
    +This is a convenience procedure that returns the error element +of the state array. +

    ::http::status token
    +This is a convenience procedure that returns the status element of +the state array. +

    ::http::code token
    +This is a convenience procedure that returns the http element of the +state array. +

    ::http::ncode token
    +This is a convenience procedure that returns just the numeric return +code (200, 404, etc.) from the http element of the state array. +

    ::http::size token
    +This is a convenience procedure that returns the currentsize +element of the state array, which represents the number of bytes +received from the URL in the ::http::geturl call. +

    ::http::cleanup token
    +This procedure cleans up the state associated with the connection +identified by token. After this call, the procedures +like ::http::data cannot be used to get information +about the operation. It is strongly recommended that you call +this function after you're done with a given HTTP request. Not doing +so will result in memory not being freed, and if your app calls +::http::geturl enough times, the memory leak could cause a +performance hit...or worse. +

    ::http::register proto port command
    +This procedure allows one to provide custom HTTP transport types +such as HTTPS, by registering a prefix, the default port, and the +command to execute to create the Tcl channel. E.g.: +
    package require http
    +package require tls
    +
    +http::register https 443 ::tls::socket
    +
    +set token [http::geturl https://my.secure.site/]
    +

    ::http::unregister proto
    +This procedure unregisters a protocol handler that was previously +registered via http::register. + +

    +

    ERRORS

    +The http::geturl procedure will raise errors in the following cases: +invalid command line options, +an invalid URL, +a URL on a non-existent host, +or a URL at a bad port on an existing host. +These errors mean that it +cannot even start the network transaction. +It will also raise an error if it gets an I/O error while +writing out the HTTP request header. +For synchronous ::http::geturl calls (where -command is +not specified), it will raise an error if it gets an I/O error while +reading the HTTP reply headers or data. Because ::http::geturl +doesn't return a token in these cases, it does all the required +cleanup and there's no issue of your app having to call +::http::cleanup. +

    +For asynchronous ::http::geturl calls, all of the above error +situations apply, except that if there's any error while +reading the +HTTP reply headers or data, no exception is thrown. This is because +after writing the HTTP headers, ::http::geturl returns, and the +rest of the HTTP transaction occurs in the background. The command +callback can check if any error occurred during the read by calling +::http::status to check the status and if it's error, +calling ::http::error to get the error message. +

    +Alternatively, if the main program flow reaches a point where it needs +to know the result of the asynchronous HTTP request, it can call +::http::wait and then check status and error, just as the +callback does. +

    +In any case, you must still call +http::cleanup to delete the state array when you're done. +

    +There are other possible results of the HTTP transaction +determined by examining the status from http::status. +These are described below. +

    +

    +

    ok
    +If the HTTP transaction completes entirely, then status will be ok. +However, you should still check the http::code value to get +the HTTP status. The http::ncode procedure provides just +the numeric error (e.g., 200, 404 or 500) while the http::code +procedure returns a value like "HTTP 404 File not found". +

    eof
    +If the server closes the socket without replying, then no error +is raised, but the status of the transaction will be eof. +

    error
    +The error message will also be stored in the error status +array element, accessible via ::http::error. +

    +

    +Another error possibility is that http::geturl is unable to +write all the post query data to the server before the server +responds and closes the socket. +The error message is saved in the posterror status array +element and then http::geturl attempts to complete the +transaction. +If it can read the server's response +it will end up with an ok status, otherwise it will have +an eof status. + +

    STATE ARRAY

    +The ::http::geturl procedure returns a token that can be used to +get to the state of the HTTP transaction in the form of a Tcl array. +Use this construct to create an easy-to-use array variable: +
    upvar #0 $token state
    +Once the data associated with the url is no longer needed, the state +array should be unset to free up storage. +The http::cleanup procedure is provided for that purpose. +The following elements of +the array are supported: +

    +

    +

    body
    +The contents of the URL. This will be empty if the -channel +option has been specified. This value is returned by the ::http::data command. +

    charset
    +The value of the charset attribute from the Content-Type meta-data +value. If none was specified, this defaults to the RFC standard +iso8859-1, or the value of $::http::defaultCharset. Incoming +text data will be automatically converted from this charset to utf-8. +

    coding
    +A copy of the Content-Encoding meta-data value. +

    currentsize
    +The current number of bytes fetched from the URL. +This value is returned by the ::http::size command. +

    error
    +If defined, this is the error string seen when the HTTP transaction +was aborted. +

    http
    +The HTTP status reply from the server. This value +is returned by the ::http::code command. The format of this value is: +
    HTTP/1.0 code string
    +The code is a three-digit number defined in the HTTP standard. +A code of 200 is OK. Codes beginning with 4 or 5 indicate errors. +Codes beginning with 3 are redirection errors. In this case the +Location meta-data specifies a new URL that contains the +requested information. +

    meta
    +The HTTP protocol returns meta-data that describes the URL contents. +The meta element of the state array is a list of the keys and +values of the meta-data. This is in a format useful for initializing +an array that just contains the meta-data: +
    array set meta $state(meta)
    +Some of the meta-data keys are listed below, but the HTTP standard defines +more, and servers are free to add their own. +

    +

    +

    Content-Type
    +The type of the URL contents. Examples include text/html, +image/gif, application/postscript and +application/x-tcl. +

    Content-Length
    +The advertised size of the contents. The actual size obtained by +::http::geturl is available as state(size). +

    Location
    +An alternate URL that contains the requested data. +

    +

    posterror
    +The error, if any, that occurred while writing +the post query data to the server. +

    status
    +Either ok, for successful completion, reset for +user-reset, timeout if a timeout occurred before the transaction +could complete, or error for an error condition. During the +transaction this value is the empty string. +

    totalsize
    +A copy of the Content-Length meta-data value. +

    type
    +A copy of the Content-Type meta-data value. +

    url
    +The requested URL. +

    +

    EXAMPLE

    +
    # Copy a URL to a file and print meta-data
    +proc ::http::copy { url file {chunk 4096} } {
    +    set out [open $file w]
    +    set token [geturl $url -channel $out -progress ::http::Progress \
    +	-blocksize $chunk]
    +    close $out
    +    # This ends the line started by http::Progress
    +    puts stderr ""
    +    upvar #0 $token state
    +    set max 0
    +    foreach {name value} $state(meta) {
    +	if {[string length $name] > $max} {
    +	    set max [string length $name]
    +	}
    +	if {[regexp -nocase ^location$ $name]} {
    +	    # Handle URL redirects
    +	    puts stderr "Location:$value"
    +	    return [copy [string trim $value] $file $chunk]
    +	}
    +    }
    +    incr max
    +    foreach {name value} $state(meta) {
    +	puts [format "%-*s %s" $max $name: $value]
    +    }
    +
    +    return $token
    +}
    +proc ::http::Progress {args} {
    +    puts -nonewline stderr . ; flush stderr
    +}
    +

    SEE ALSO

    +safe, socket, safesock +

    KEYWORDS

    +security policy, socket +
    +Copyright © 1995-1997 Sun Microsystems, Inc.
    +Copyright © 1998-2000 by Ajuba Solutions.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/if.htm b/hlp/en/tcl/if.htm new file mode 100644 index 0000000..b0115ac --- /dev/null +++ b/hlp/en/tcl/if.htm @@ -0,0 +1,35 @@ +Built-In Commands - if manual page +

    NAME

    +if - Execute scripts conditionally +

    SYNOPSIS

    +if expr1 ?then? body1 elseif expr2 ?then? body2elseif ... ?else? ?bodyN?
    +

    DESCRIPTION

    +The if command evaluates expr1 as an expression (in the +same way that expr evaluates its argument). The value of the +expression must be a boolean +(a numeric value, where 0 is false and +anything is true, or a string value such as true or yes +for true and false or no for false); +if it is true then body1 is executed by passing it to the +Tcl interpreter. +Otherwise expr2 is evaluated as an expression and if it is true +then body2 is executed, and so on. +If none of the expressions evaluates to true then bodyN is +executed. +The then and else arguments are optional +``noise words'' to make the command easier to read. +There may be any number of elseif clauses, including zero. +BodyN may also be omitted as long as else is omitted too. +The return value from the command is the result of the body script +that was executed, or an empty string +if none of the expressions was non-zero and there was no bodyN. + +

    SEE ALSO

    +expr, for, foreach +

    KEYWORDS

    +boolean, conditional, else, false, if, true +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/incr.htm b/hlp/en/tcl/incr.htm new file mode 100644 index 0000000..3067512 --- /dev/null +++ b/hlp/en/tcl/incr.htm @@ -0,0 +1,23 @@ +Built-In Commands - incr manual page +

    NAME

    +incr - Increment the value of a variable +

    SYNOPSIS

    +incr varName ?increment?
    +

    DESCRIPTION

    +Increments the value stored in the variable whose name is varName. +The value of the variable must be an integer. +If increment is supplied then its value (which must be an +integer) is added to the value of variable varName; otherwise +1 is added to varName. +The new value is stored as a decimal string in variable varName +and also returned as result. + +

    SEE ALSO

    +expr +

    KEYWORDS

    +add, increment, variable, value +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/info.htm b/hlp/en/tcl/info.htm new file mode 100644 index 0000000..a64b4b5 --- /dev/null +++ b/hlp/en/tcl/info.htm @@ -0,0 +1,190 @@ +Tcl Built-In Commands - info manual page +
    +
    NAME +
    info - Return information about the state of the Tcl interpreter
    +
    SYNOPSIS +
    +
    info option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    info args procname +
    info body procname +
    info cmdcount +
    info commands ?pattern? +
    info complete command +
    info default procname arg varname +
    info exists varName +
    info globals ?pattern? +
    info hostname +
    info level ?number? +
    info library +
    info loaded ?interp? +
    info locals ?pattern? +
    info nameofexecutable +
    info patchlevel +
    info procs ?pattern? +
    info script +
    info sharedlibextension +
    info tclversion +
    info vars ?pattern? +
    +
    KEYWORDS +

    +

    NAME

    +info - Return information about the state of the Tcl interpreter +

    SYNOPSIS

    +info option ?arg arg ...?
    +

    DESCRIPTION

    +This command provides information about various internals of the Tcl +interpreter. +The legal option's (which may be abbreviated) are: +

    +

    +

    info args procname
    +Returns a list containing the names of the arguments to procedure +procname, in order. Procname must be the name of a +Tcl command procedure. +

    info body procname
    +Returns the body of procedure procname. Procname must be +the name of a Tcl command procedure. +

    info cmdcount
    +Returns a count of the total number of commands that have been invoked +in this interpreter. +

    info commands ?pattern?
    +If pattern isn't specified, +returns a list of names of all the Tcl commands in the current namespace, +including both the built-in commands written in C and +the command procedures defined using the proc command. +If pattern is specified, +only those names matching pattern are returned. +Matching is determined using the same rules as for string match. +pattern can be a qualified name like Foo::print*. +That is, it may specify a particular namespace +using a sequence of namespace names separated by ::s, +and may have pattern matching special characters +at the end to specify a set of commands in that namespace. +If pattern is a qualified name, +the resulting list of command names has each one qualified with the name +of the specified namespace. +

    info complete command
    +Returns 1 if command is a complete Tcl command in the sense of +having no unclosed quotes, braces, brackets or array element names, +If the command doesn't appear to be complete then 0 is returned. +This command is typically used in line-oriented input environments +to allow users to type in commands that span multiple lines; if the +command isn't complete, the script can delay evaluating it until additional +lines have been typed to complete the command. +

    info default procname arg varname
    +Procname must be the name of a Tcl command procedure and arg +must be the name of an argument to that procedure. If arg +doesn't have a default value then the command returns 0. +Otherwise it returns 1 and places the default value of arg +into variable varname. +

    info exists varName
    +Returns 1 if the variable named varName exists in the +current context (either as a global or local variable) and has been +defined by being given a value, returns 0 otherwise. +

    info globals ?pattern?
    +If pattern isn't specified, returns a list of all the names +of currently-defined global variables. +Global variables are variables in the global namespace. +If pattern is specified, only those names matching pattern +are returned. Matching is determined using the same rules as for +string match. +

    info hostname
    +Returns the name of the computer on which this invocation is being +executed. +

    info level ?number?
    +If number is not specified, this command returns a number +giving the stack level of the invoking procedure, or 0 if the +command is invoked at top-level. If number is specified, +then the result is a list consisting of the name and arguments for the +procedure call at level number on the stack. If number +is positive then it selects a particular stack level (1 refers +to the top-most active procedure, 2 to the procedure it called, and +so on); otherwise it gives a level relative to the current level +(0 refers to the current procedure, -1 to its caller, and so on). +See the uplevel command for more information on what stack +levels mean. +

    info library
    +Returns the name of the library directory in which standard Tcl +scripts are stored. +This is actually the value of the tcl_library +variable and may be changed by setting tcl_library. +See the tclvars manual entry for more information. +

    info loaded ?interp?
    +Returns a list describing all of the packages that have been loaded into +interp with the load command. +Each list element is a sub-list with two elements consisting of the +name of the file from which the package was loaded and the name of +the package. +For statically-loaded packages the file name will be an empty string. +If interp is omitted then information is returned for all packages +loaded in any interpreter in the process. +To get a list of just the packages in the current interpreter, specify +an empty string for the interp argument. +

    info locals ?pattern?
    +If pattern isn't specified, returns a list of all the names +of currently-defined local variables, including arguments to the +current procedure, if any. +Variables defined with the global and upvar commands +will not be returned. +If pattern is specified, only those names matching pattern +are returned. Matching is determined using the same rules as for +string match. +

    info nameofexecutable
    +Returns the full path name of the binary file from which the application +was invoked. If Tcl was unable to identify the file, then an empty +string is returned. +

    info patchlevel
    +Returns the value of the global variable tcl_patchLevel; see +the tclvars manual entry for more information. +

    info procs ?pattern?
    +If pattern isn't specified, returns a list of all the +names of Tcl command procedures in the current namespace. +If pattern is specified, +only those procedure names in the current namespace +matching pattern are returned. +Matching is determined using the same rules as for +string match. +

    info script
    +If a Tcl script file is currently being evaluated (i.e. there is a +call to Tcl_EvalFile active or there is an active invocation +of the source command), then this command returns the name +of the innermost file being processed. Otherwise the command returns an +empty string. +

    info sharedlibextension
    +Returns the extension used on this platform for the names of files +containing shared libraries (for example, .so under Solaris). +If shared libraries aren't supported on this platform then an empty +string is returned. +

    info tclversion
    +Returns the value of the global variable tcl_version; see +the tclvars manual entry for more information. +

    info vars ?pattern?
    +If pattern isn't specified, +returns a list of all the names of currently-visible variables. +This includes locals and currently-visible globals. +If pattern is specified, only those names matching pattern +are returned. Matching is determined using the same rules as for +string match. +pattern can be a qualified name like Foo::option*. +That is, it may specify a particular namespace +using a sequence of namespace names separated by ::s, +and may have pattern matching special characters +at the end to specify a set of variables in that namespace. +If pattern is a qualified name, +the resulting list of variable names +has each matching namespace variable qualified with the name +of its namespace. + +

    +

    KEYWORDS

    +command, information, interpreter, level, namespace, procedure, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/interp.htm b/hlp/en/tcl/interp.htm new file mode 100644 index 0000000..797a170 --- /dev/null +++ b/hlp/en/tcl/interp.htm @@ -0,0 +1,528 @@ +Tcl Built-In Commands - interp manual page +
    +
    NAME +
    interp - Create and manipulate Tcl interpreters
    +
    SYNOPSIS +
    +
    interp option ?arg arg ...? +
    +
    DESCRIPTION +
    THE INTERP COMMAND +
    +
    interp alias srcPath srcCmd +
    interp alias srcPath srcCmd {} +
    interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...? +
    interp aliases ?path? +
    interp create ?-safe? ?- -? ?path? +
    interp delete ?path ...? +
    interp eval path arg ?arg ...? +
    interp exists path +
    interp expose path hiddenName ?exposedCmdName? +
    interp hide path exposedCmdName ?hiddenCmdName? +
    interp hidden path +
    interp invokehidden path ?-global? hiddenCmdName ?arg ...? +
    interp issafe ?path? +
    interp marktrusted path +
    interp share srcPath channelId destPath +
    interp slaves ?path? +
    interp target path alias +
    interp transfer srcPath channelId destPath +
    +
    SLAVE COMMAND +
    +
    slave aliases +
    slave alias srcCmd +
    slave alias srcCmd {} +
    slave alias srcCmd targetCmd ?arg ..? +
    slave eval arg ?arg ..? +
    slave expose hiddenName ?exposedCmdName? +
    slave hide exposedCmdName ?hiddenCmdName? +
    slave hidden +
    slave invokehidden ?-global hiddenName ?arg ..? +
    slave issafe +
    slave marktrusted +
    +
    SAFE INTERPRETERS +
    ALIAS INVOCATION +
    HIDDEN COMMANDS +
    CREDITS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +interp - Create and manipulate Tcl interpreters +

    SYNOPSIS

    +interp option ?arg arg ...?
    +

    DESCRIPTION

    +This command makes it possible to create one or more new Tcl +interpreters that co-exist with the creating interpreter in the +same application. The creating interpreter is called the master +and the new interpreter is called a slave. +A master can create any number of slaves, and each slave can +itself create additional slaves for which it is master, resulting +in a hierarchy of interpreters. +

    +Each interpreter is independent from the others: it has its own name +space for commands, procedures, and global variables. +A master interpreter may create connections between its slaves and +itself using a mechanism called an alias. An alias is +a command in a slave interpreter which, when invoked, causes a +command to be invoked in its master interpreter or in another slave +interpreter. The only other connections between interpreters are +through environment variables (the env variable), which are +normally shared among all interpreters in the application. Note that the +name space for files (such as the names returned by the open command) +is no longer shared between interpreters. Explicit commands are provided to +share files and to transfer references to open files from one interpreter +to another. +

    +The interp command also provides support for safe +interpreters. A safe interpreter is a slave whose functions have +been greatly restricted, so that it is safe to execute untrusted +scripts without fear of them damaging other interpreters or the +application's environment. For example, all IO channel creation +commands and subprocess creation commands are made inaccessible to safe +interpreters. +See SAFE INTERPRETERS below for more information on +what features are present in a safe interpreter. +The dangerous functionality is not removed from the safe interpreter; +instead, it is hidden, so that only trusted interpreters can obtain +access to it. For a detailed explanation of hidden commands, see +HIDDEN COMMANDS, below. +The alias mechanism can be used for protected communication (analogous to a +kernel call) between a slave interpreter and its master. See ALIAS +INVOCATION, below, for more details on how the alias mechanism works. +

    +A qualified interpreter name is a proper Tcl lists containing a subset of its +ancestors in the interpreter hierarchy, terminated by the string naming the +interpreter in its immediate master. Interpreter names are relative to the +interpreter in which they are used. For example, if a is a slave of +the current interpreter and it has a slave a1, which in turn has a +slave a11, the qualified name of a11 in a is the list +a1 a11. +

    +The interp command, described below, accepts qualified interpreter +names as arguments; the interpreter in which the command is being evaluated +can always be referred to as {} (the empty list or string). Note that +it is impossible to refer to a master (ancestor) interpreter by name in a +slave interpreter except through aliases. Also, there is no global name by +which one can refer to the first interpreter created in an application. +Both restrictions are motivated by safety concerns. + +

    THE INTERP COMMAND

    +The interp command is used to create, delete, and manipulate +slave interpreters, and to share or transfer +channels between interpreters. It can have any of several forms, depending +on the option argument: +

    +

    +

    interp alias srcPath srcCmd
    +Returns a Tcl list whose elements are the targetCmd and +args associated with the alias named srcCmd +(all of these are the values specified when the alias was +created; it is possible that the actual source command in the +slave is different from srcCmd if it was renamed). +

    interp alias srcPath srcCmd {}
    +Deletes the alias for srcCmd in the slave interpreter identified by +srcPath. +srcCmd refers to the name under which the alias +was created; if the source command has been renamed, the renamed +command will be deleted. +

    interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...?
    +This command creates an alias between one slave and another (see the +alias slave command below for creating aliases between a slave +and its master). In this command, either of the slave interpreters +may be anywhere in the hierarchy of interpreters under the interpreter +invoking the command. +SrcPath and srcCmd identify the source of the alias. +SrcPath is a Tcl list whose elements select a particular +interpreter. For example, ``a b'' identifies an interpreter +b, which is a slave of interpreter a, which is a slave +of the invoking interpreter. An empty list specifies the interpreter +invoking the command. srcCmd gives the name of a new +command, which will be created in the source interpreter. +TargetPath and targetCmd specify a target interpreter +and command, and the arg arguments, if any, specify additional +arguments to targetCmd which are prepended to any arguments specified +in the invocation of srcCmd. +TargetCmd may be undefined at the time of this call, or it may +already exist; it is not created by this command. +The alias arranges for the given target command to be invoked +in the target interpreter whenever the given source command is +invoked in the source interpreter. See ALIAS INVOCATION below for +more details. +

    interp aliases ?path?
    +This command returns a Tcl list of the names of all the source commands for +aliases defined in the interpreter identified by path. +

    interp create ?-safe? ?- -? ?path?
    +Creates a slave interpreter identified by path and a new command, +called a slave command. The name of the slave command is the last +component of path. The new slave interpreter and the slave command +are created in the interpreter identified by the path obtained by removing +the last component from path. For example, if path is a b +c then a new slave interpreter and slave command named c are +created in the interpreter identified by the path a b. +The slave command may be used to manipulate the new interpreter as +described below. If path is omitted, Tcl creates a unique name of the +form interpx, where x is an integer, and uses it for the +interpreter and the slave command. If the -safe switch is specified +(or if the master interpreter is a safe interpreter), the new slave +interpreter will be created as a safe interpreter with limited +functionality; otherwise the slave will include the full set of Tcl +built-in commands and variables. The - - switch can be used to +mark the end of switches; it may be needed if path is an unusual +value such as -safe. The result of the command is the name of the +new interpreter. The name of a slave interpreter must be unique among all +the slaves for its master; an error occurs if a slave interpreter by the +given name already exists in this master. +

    interp delete ?path ...?
    +Deletes zero or more interpreters given by the optional path +arguments, and for each interpreter, it also deletes its slaves. The +command also deletes the slave command for each interpreter deleted. +For each path argument, if no interpreter by that name +exists, the command raises an error. +

    interp eval path arg ?arg ...?
    +This command concatenates all of the arg arguments in the same +fashion as the concat command, then evaluates the resulting string as +a Tcl script in the slave interpreter identified by path. The result +of this evaluation (including error information such as the errorInfo +and errorCode variables, if an error occurs) is returned to the +invoking interpreter. +

    interp exists path
    +Returns 1 if a slave interpreter by the specified path +exists in this master, 0 otherwise. If path is omitted, the +invoking interpreter is used. +

    interp expose path hiddenName ?exposedCmdName?
    +Makes the hidden command hiddenName exposed, eventually bringing +it back under a new exposedCmdName name (this name is currently +accepted only if it is a valid global name space name without any ::), +in the interpreter +denoted by path. +If an exposed command with the targetted name already exists, this command +fails. +Hidden commands are explained in more detail in HIDDEN COMMANDS, below. +

    interp hide path exposedCmdName ?hiddenCmdName?
    +Makes the exposed command exposedCmdName hidden, renaming +it to the hidden command hiddenCmdName, or keeping the same name if +hiddenCmdName is not given, in the interpreter denoted +by path. +If a hidden command with the targetted name already exists, this command +fails. +Currently both exposedCmdName and hiddenCmdName can +not contain namespace qualifiers, or an error is raised. +Commands to be hidden by interp hide are looked up in the global +namespace even if the current namespace is not the global one. This +prevents slaves from fooling a master interpreter into hiding the wrong +command, by making the current namespace be different from the global one. +Hidden commands are explained in more detail in HIDDEN COMMANDS, below. +

    interp hidden path
    +Returns a list of the names of all hidden commands in the interpreter +identified by path. +

    interp invokehidden path ?-global? hiddenCmdName ?arg ...?
    +Invokes the hidden command hiddenCmdName with the arguments supplied +in the interpreter denoted by path. No substitutions or evaluation +are applied to the arguments. +If the -global flag is present, the hidden command is invoked at the +global level in the target interpreter; otherwise it is invoked at the +current call frame and can access local variables in that and outer call +frames. +Hidden commands are explained in more detail in HIDDEN COMMANDS, below. +

    interp issafe ?path?
    +Returns 1 if the interpreter identified by the specified path +is safe, 0 otherwise. +

    interp marktrusted path
    +Marks the interpreter identified by path as trusted. Does +not expose the hidden commands. This command can only be invoked from a +trusted interpreter. +The command has no effect if the interpreter identified by path is +already trusted. +

    interp share srcPath channelId destPath
    +Causes the IO channel identified by channelId to become shared +between the interpreter identified by srcPath and the interpreter +identified by destPath. Both interpreters have the same permissions +on the IO channel. +Both interpreters must close it to close the underlying IO channel; IO +channels accessible in an interpreter are automatically closed when an +interpreter is destroyed. +

    interp slaves ?path?
    +Returns a Tcl list of the names of all the slave interpreters associated +with the interpreter identified by path. If path is omitted, +the invoking interpreter is used. +

    interp target path alias
    +Returns a Tcl list describing the target interpreter for an alias. The +alias is specified with an interpreter path and source command name, just +as in interp alias above. The name of the target interpreter is +returned as an interpreter path, relative to the invoking interpreter. +If the target interpreter for the alias is the invoking interpreter then an +empty list is returned. If the target interpreter for the alias is not the +invoking interpreter or one of its descendants then an error is generated. +The target command does not have to be defined at the time of this invocation. +

    interp transfer srcPath channelId destPath
    +Causes the IO channel identified by channelId to become available in +the interpreter identified by destPath and unavailable in the +interpreter identified by srcPath. + +

    +

    SLAVE COMMAND

    +For each slave interpreter created with the interp command, a +new Tcl command is created in the master interpreter with the same +name as the new interpreter. This command may be used to invoke +various operations on the interpreter. It has the following +general form: +
    slave command ?arg arg ...?
    +Slave is the name of the interpreter, and command +and the args determine the exact behavior of the command. +The valid forms of this command are: +

    +

    +

    slave aliases
    +Returns a Tcl list whose elements are the names of all the +aliases in slave. The names returned are the srcCmd +values used when the aliases were created (which may not be the same +as the current names of the commands, if they have been +renamed). +

    slave alias srcCmd
    +Returns a Tcl list whose elements are the targetCmd and +args associated with the alias named srcCmd +(all of these are the values specified when the alias was +created; it is possible that the actual source command in the +slave is different from srcCmd if it was renamed). +

    slave alias srcCmd {}
    +Deletes the alias for srcCmd in the slave interpreter. +srcCmd refers to the name under which the alias +was created; if the source command has been renamed, the renamed +command will be deleted. +

    slave alias srcCmd targetCmd ?arg ..?
    +Creates an alias such that whenever srcCmd is invoked +in slave, targetCmd is invoked in the master. +The arg arguments will be passed to targetCmd as additional +arguments, prepended before any arguments passed in the invocation of +srcCmd. +See ALIAS INVOCATION below for details. +

    slave eval arg ?arg ..?
    +This command concatenates all of the arg arguments in +the same fashion as the concat command, then evaluates +the resulting string as a Tcl script in slave. +The result of this evaluation (including error information +such as the errorInfo and errorCode variables, if an +error occurs) is returned to the invoking interpreter. +

    slave expose hiddenName ?exposedCmdName?
    +This command exposes the hidden command hiddenName, eventually bringing +it back under a new exposedCmdName name (this name is currently +accepted only if it is a valid global name space name without any ::), +in slave. +If an exposed command with the targetted name already exists, this command +fails. +For more details on hidden commands, see HIDDEN COMMANDS, below. +

    slave hide exposedCmdName ?hiddenCmdName?
    +This command hides the exposed command exposedCmdName, renaming it to +the hidden command hiddenCmdName, or keeping the same name if the +the argument is not given, in the slave interpreter. +If a hidden command with the targetted name already exists, this command +fails. +Currently both exposedCmdName and hiddenCmdName can +not contain namespace qualifiers, or an error is raised. +Commands to be hidden are looked up in the global +namespace even if the current namespace is not the global one. This +prevents slaves from fooling a master interpreter into hiding the wrong +command, by making the current namespace be different from the global one. +For more details on hidden commands, see HIDDEN COMMANDS, below. +

    slave hidden
    +Returns a list of the names of all hidden commands in slave. +

    slave invokehidden ?-global hiddenName ?arg ..?
    +This command invokes the hidden command hiddenName with the +supplied arguments, in slave. No substitutions or evaluations are +applied to the arguments. +If the -global flag is given, the command is invoked at the global +level in the slave; otherwise it is invoked at the current call frame and +can access local variables in that or outer call frames. +For more details on hidden commands, see HIDDEN +COMMANDS, below. +

    slave issafe
    +Returns 1 if the slave interpreter is safe, 0 otherwise. +

    slave marktrusted
    +Marks the slave interpreter as trusted. Can only be invoked by a +trusted interpreter. This command does not expose any hidden +commands in the slave interpreter. The command has no effect if the slave +is already trusted. + +

    +

    SAFE INTERPRETERS

    +A safe interpreter is one with restricted functionality, so that +is safe to execute an arbitrary script from your worst enemy without +fear of that script damaging the enclosing application or the rest +of your computing environment. In order to make an interpreter +safe, certain commands and variables are removed from the interpreter. +For example, commands to create files on disk are removed, and the +exec command is removed, since it could be used to cause damage +through subprocesses. +Limited access to these facilities can be provided, by creating +aliases to the master interpreter which check their arguments carefully +and provide restricted access to a safe subset of facilities. +For example, file creation might be allowed in a particular subdirectory +and subprocess invocation might be allowed for a carefully selected and +fixed set of programs. +

    +A safe interpreter is created by specifying the -safe switch +to the interp create command. Furthermore, any slave created +by a safe interpreter will also be safe. +

    +A safe interpreter is created with exactly the following set of +built-in commands: +

    after	append	array	binary
    +break	case	catch	clock
    +close	concat	continue	eof
    +error	eval	expr	fblocked
    +fcopy	fileevent	flush	for
    +foreach	format	gets	global
    +history	if	incr	info
    +interp	join	lappend	lindex
    +linsert	list	llength	lrange
    +lreplace	lsearch	lsort	namespace
    +package	pid	proc	puts
    +read	regexp	regsub	rename
    +return	scan	seek	set
    +split	string	subst	switch
    +tell	trace	unset	update
    +uplevel	upvar	variable	vwait
    +while
    +The following commands are hidden by interp create when it +creates a safe interpreter: +
    cd	exec	exit	fconfigure
    +file	glob	load	open
    +pwd	socket	source	vwait
    +These commands can be recreated later as Tcl procedures or aliases, or +re-exposed by interp expose. +

    +In addition, the env variable is not present in a safe interpreter, +so it cannot share environment variables with other interpreters. The +env variable poses a security risk, because users can store +sensitive information in an environment variable. For example, the PGP +manual recommends storing the PGP private key protection password in +the environment variable PGPPASS. Making this variable available +to untrusted code executing in a safe interpreter would incur a +security risk. +

    +If extensions are loaded into a safe interpreter, they may also restrict +their own functionality to eliminate unsafe commands. For a discussion of +management of extensions for safety see the manual entries for +Safe-Tcl and the load Tcl command. + +

    ALIAS INVOCATION

    +The alias mechanism has been carefully designed so that it can +be used safely when an untrusted script is executing +in a safe slave and the target of the alias is a trusted +master. The most important thing in guaranteeing safety is to +ensure that information passed from the slave to the master is +never evaluated or substituted in the master; if this were to +occur, it would enable an evil script in the slave to invoke +arbitrary functions in the master, which would compromise security. +

    +When the source for an alias is invoked in the slave interpreter, the +usual Tcl substitutions are performed when parsing that command. +These substitutions are carried out in the source interpreter just +as they would be for any other command invoked in that interpreter. +The command procedure for the source command takes its arguments +and merges them with the targetCmd and args for the +alias to create a new array of arguments. If the words +of srcCmd were ``srcCmd arg1 arg2 ... argN'', +the new set of words will be +``targetCmd arg arg ... arg arg1 arg2 ... argN'', +where targetCmd and args are the values supplied when the +alias was created. TargetCmd is then used to locate a command +procedure in the target interpreter, and that command procedure +is invoked with the new set of arguments. An error occurs if +there is no command named targetCmd in the target interpreter. +No additional substitutions are performed on the words: the +target command procedure is invoked directly, without +going through the normal Tcl evaluation mechanism. +Substitutions are thus performed on each word exactly once: +targetCmd and args were substituted when parsing the command +that created the alias, and arg1 - argN are substituted when +the alias's source command is parsed in the source interpreter. +

    +When writing the targetCmds for aliases in safe interpreters, +it is very important that the arguments to that command never be +evaluated or substituted, since this would provide an escape +mechanism whereby the slave interpreter could execute arbitrary +code in the master. This in turn would compromise the security +of the system. + +

    HIDDEN COMMANDS

    +Safe interpreters greatly restrict the functionality available to Tcl +programs executing within them. +Allowing the untrusted Tcl program to have direct access to this +functionality is unsafe, because it can be used for a variety of +attacks on the environment. +However, there are times when there is a legitimate need to use the +dangerous functionality in the context of the safe interpreter. For +example, sometimes a program must be sourced into the interpreter. +Another example is Tk, where windows are bound to the hierarchy of windows +for a specific interpreter; some potentially dangerous functions, e.g. +window management, must be performed on these windows within the +interpreter context. +

    +The interp command provides a solution to this problem in the form of +hidden commands. Instead of removing the dangerous commands entirely +from a safe interpreter, these commands are hidden so they become +unavailable to Tcl scripts executing in the interpreter. However, such +hidden commands can be invoked by any trusted ancestor of the safe +interpreter, in the context of the safe interpreter, using interp +invoke. Hidden commands and exposed commands reside in separate name +spaces. It is possible to define a hidden command and an exposed command by +the same name within one interpreter. +

    +Hidden commands in a slave interpreter can be invoked in the body of +procedures called in the master during alias invocation. For example, an +alias for source could be created in a slave interpreter. When it is +invoked in the slave interpreter, a procedure is called in the master +interpreter to check that the operation is allowable (e.g. it asks to +source a file that the slave interpreter is allowed to access). The +procedure then it invokes the hidden source command in the slave +interpreter to actually source in the contents of the file. Note that two +commands named source exist in the slave interpreter: the alias, and +the hidden command. +

    +Because a master interpreter may invoke a hidden command as part of +handling an alias invocation, great care must be taken to avoid evaluating +any arguments passed in through the alias invocation. +Otherwise, malicious slave interpreters could cause a trusted master +interpreter to execute dangerous commands on their behalf. See the section +on ALIAS INVOCATION for a more complete discussion of this topic. +To help avoid this problem, no substitutions or evaluations are +applied to arguments of interp invokehidden. +

    +Safe interpreters are not allowed to invoke hidden commands in themselves +or in their descendants. This prevents safe slaves from gaining access to +hidden functionality in themselves or their descendants. +

    +The set of hidden commands in an interpreter can be manipulated by a trusted +interpreter using interp expose and interp hide. The interp +expose command moves a hidden command to the +set of exposed commands in the interpreter identified by path, +potentially renaming the command in the process. If an exposed command by +the targetted name already exists, the operation fails. Similarly, +interp hide moves an exposed command to the set of hidden commands in +that interpreter. Safe interpreters are not allowed to move commands +between the set of hidden and exposed commands, in either themselves or +their descendants. +

    +Currently, the names of hidden commands cannot contain namespace +qualifiers, and you must first rename a command in a namespace to the +global namespace before you can hide it. +Commands to be hidden by interp hide are looked up in the global +namespace even if the current namespace is not the global one. This +prevents slaves from fooling a master interpreter into hiding the wrong +command, by making the current namespace be different from the global one. +

    CREDITS

    +This mechanism is based on the Safe-Tcl prototype implemented +by Nathaniel Borenstein and Marshall Rose. + +

    SEE ALSO

    +load, safe, Tcl_CreateSlave +

    KEYWORDS

    +alias, master interpreter, safe interpreter, slave interpreter +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/join.htm b/hlp/en/tcl/join.htm new file mode 100644 index 0000000..e85099e --- /dev/null +++ b/hlp/en/tcl/join.htm @@ -0,0 +1,21 @@ +Built-In Commands - join manual page +

    NAME

    +join - Create a string by joining together list elements +

    SYNOPSIS

    +join list ?joinString?
    +

    DESCRIPTION

    +The list argument must be a valid Tcl list. +This command returns the string +formed by joining all of the elements of list together with +joinString separating each adjacent pair of elements. +The joinString argument defaults to a space character. + +

    SEE ALSO

    +list, lappend +

    KEYWORDS

    +element, join, list, separator +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lappend.htm b/hlp/en/tcl/lappend.htm new file mode 100644 index 0000000..53da1b3 --- /dev/null +++ b/hlp/en/tcl/lappend.htm @@ -0,0 +1,27 @@ +Built-In Commands - lappend manual page +

    NAME

    +lappend - Append list elements onto a variable +

    SYNOPSIS

    +lappend varName ?value value value ...?
    +

    DESCRIPTION

    +This command treats the variable given by varName as a list +and appends each of the value arguments to that list as a separate +element, with spaces between elements. +If varName doesn't exist, it is created as a list with elements +given by the value arguments. +Lappend is similar to append except that the values +are appended as list elements rather than raw text. +This command provides a relatively efficient way to build up +large lists. For example, ``lappend a $b'' is much +more efficient than ``set a [concat $a [list $b]]'' when +$a is long. + +

    SEE ALSO

    +list, lindex, linsert, llength, lsort, lrange +

    KEYWORDS

    +append, element, list, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/library.htm b/hlp/en/tcl/library.htm new file mode 100644 index 0000000..f8e62e0 --- /dev/null +++ b/hlp/en/tcl/library.htm @@ -0,0 +1,320 @@ +Tcl Built-In Commands - library manual page +
    +
    NAME +
    auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl procedures
    +
    SYNOPSIS +
    +
    auto_execok cmd +
    auto_import pattern +
    auto_load cmd +
    auto_mkindex dir pattern pattern ... +
    auto_mkindex_old dir pattern pattern ... +
    auto_qualify command namespace +
    auto_reset +
    tcl_findLibrary basename version patch initScript enVarName varName +
    parray arrayName +
    tcl_endOfWord str start +
    tcl_startOfNextWord str start +
    tcl_startOfPreviousWord str start +
    tcl_wordBreakAfter str start +
    tcl_wordBreakBefore str start +
    +
    INTRODUCTION +
    COMMAND PROCEDURES +
    +
    auto_execok cmd +
    auto_import pattern +
    auto_load cmd +
    auto_mkindex dir pattern pattern ... +
    auto_reset +
    auto_qualify command namespace +
    tcl_findLibrary basename version patch initScript enVarName varName +
    parray arrayName +
    tcl_endOfWord str start +
    tcl_startOfNextWord str start +
    tcl_startOfPreviousWord str start +
    tcl_wordBreakAfter str start +
    tcl_wordBreakBefore str start +
    +
    VARIABLES +
    +
    auto_execs +
    auto_index +
    auto_noexec +
    auto_noload +
    auto_path +
    env(TCL_LIBRARY) +
    env(TCLLIBPATH) +
    tcl_nonwordchars +
    tcl_wordchars +
    unknown_pending +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl procedures +

    SYNOPSIS

    +auto_execok cmd
    +auto_import pattern
    +auto_load cmd
    +auto_mkindex dir pattern pattern ...
    +auto_mkindex_old dir pattern pattern ...
    +auto_qualify command namespace
    +auto_reset
    +tcl_findLibrary basename version patch initScript enVarName varName
    +parray arrayName
    +tcl_endOfWord str start
    +tcl_startOfNextWord str start
    +tcl_startOfPreviousWord str start
    +tcl_wordBreakAfter str start
    +tcl_wordBreakBefore str start
    +

    INTRODUCTION

    +Tcl includes a library of Tcl procedures for commonly-needed functions. +The procedures defined in the Tcl library are generic ones suitable +for use by many different applications. +The location of the Tcl library is returned by the info library +command. +In addition to the Tcl library, each application will normally have +its own library of support procedures as well; the location of this +library is normally given by the value of the $app_library +global variable, where app is the name of the application. +For example, the location of the Tk library is kept in the variable +$tk_library. +

    +To access the procedures in the Tcl library, an application should +source the file init.tcl in the library, for example with +the Tcl command +

    source [file join [info library] init.tcl]
    +If the library procedure Tcl_Init is invoked from an application's +Tcl_AppInit procedure, this happens automatically. +The code in init.tcl will define the unknown procedure +and arrange for the other procedures to be loaded on-demand using +the auto-load mechanism defined below. + +

    COMMAND PROCEDURES

    +The following procedures are provided in the Tcl library: +

    +

    +

    auto_execok cmd
    +Determines whether there is an executable file or shell builtin +by the name cmd. If so, it returns a list of arguments to be +passed to exec to execute the executable file or shell builtin +named by cmd. If not, it returns an empty string. This command +examines the directories in the current search path (given by the PATH +environment variable) in its search for an executable file named +cmd. On Windows platforms, the search is expanded with the same +directories and file extensions as used by exec. Auto_exec +remembers information about previous searches in an array named +auto_execs; this avoids the path search in future calls for the +same cmd. The command auto_reset may be used to force +auto_execok to forget its cached information. +

    auto_import pattern
    +Auto_import is invoked during namespace import to see if +the imported commands specified by pattern reside in an +autoloaded library. If so, the commands are loaded so that they will +be available to the interpreter for creating the import links. If the +commands do not reside in an autoloaded library, auto_import +does nothing. The pattern matching is performed according to the +matching rules of namespace import. +

    auto_load cmd
    +This command attempts to load the definition for a Tcl command named +cmd. To do this, it searches an auto-load path, which is +a list of one or more directories. The auto-load path is given by the +global variable $auto_path if it exists. If there is no +$auto_path variable, then the TCLLIBPATH environment variable is +used, if it exists. Otherwise the auto-load path consists of just the +Tcl library directory. Within each directory in the auto-load path +there must be a file tclIndex that describes one or more +commands defined in that directory and a script to evaluate to load +each of the commands. The tclIndex file should be generated +with the auto_mkindex command. If cmd is found in an +index file, then the appropriate script is evaluated to create the +command. The auto_load command returns 1 if cmd was +successfully created. The command returns 0 if there was no index +entry for cmd or if the script didn't actually define cmd +(e.g. because index information is out of date). If an error occurs +while processing the script, then that error is returned. +Auto_load only reads the index information once and saves it in +the array auto_index; future calls to auto_load check for +cmd in the array rather than re-reading the index files. The +cached index information may be deleted with the command +auto_reset. This will force the next auto_load command to +reload the index database from disk. +

    auto_mkindex dir pattern pattern ...
    +Generates an index suitable for use by auto_load. The command +searches dir for all files whose names match any of the +pattern arguments (matching is done with the glob +command), generates an index of all the Tcl command procedures defined +in all the matching files, and stores the index information in a file +named tclIndex in dir. If no pattern is given a pattern of +*.tcl will be assumed. For example, the command +
    auto_mkindex foo *.tcl
    +

    +will read all the .tcl files in subdirectory foo and +generate a new index file foo/tclIndex. +

    +Auto_mkindex parses the Tcl scripts by sourcing them into a +slave interpreter and monitoring the proc and namespace commands that +are executed. Extensions can use the (undocumented) +auto_mkindex_parser package to register other commands that can +contribute to the auto_load index. You will have to read through +auto.tcl to see how this works. +

    Auto_mkindex_old parses the Tcl scripts in a relatively +unsophisticated way: if any line contains the word proc +as its first characters then it is assumed to be a procedure +definition and the next word of the line is taken as the +procedure's name. +Procedure definitions that don't appear in this way (e.g. they +have spaces before the proc) will not be indexed. If your +script contains "dangerous" code, such as global initialization +code or procedure names with special characters like $, +*, [ or ], you are safer using auto_mkindex_old. +

    auto_reset
    +Destroys all the information cached by auto_execok and +auto_load. This information will be re-read from disk the next +time it is needed. Auto_reset also deletes any procedures +listed in the auto-load index, so that fresh copies of them will be +loaded the next time that they're used. +

    auto_qualify command namespace
    +Computes a list of fully qualified names for command. This list +mirrors the path a standard Tcl interpreter follows for command +lookups: first it looks for the command in the current namespace, and +then in the global namespace. Accordingly, if command is +relative and namespace is not ::, the list returned has +two elements: command scoped by namespace, as if it were +a command in the namespace namespace; and command as if it +were a command in the global namespace. Otherwise, if either +command is absolute (it begins with ::), or +namespace is ::, the list contains only command as +if it were a command in the global namespace. +

    +Auto_qualify is used by the auto-loading facilities in Tcl, both +for producing auto-loading indexes such as pkgIndex.tcl, and for +performing the actual auto-loading of functions at runtime. +

    tcl_findLibrary basename version patch initScript enVarName varName
    +This is a standard search procedure for use by extensions during +their initialization. They call this procedure to look for their +script library in several standard directories. +The last component of the name of the library directory is +normally basenameversion +(e.g., tk8.0), but it might be "library" when in the build hierarchies. +The initScript file will be sourced into the interpreter +once it is found. The directory in which this file is found is +stored into the global variable varName. +If this variable is already defined (e.g., by C code during +application initialization) then no searching is done. +Otherwise the search looks in these directories: +the directory named by the environment variable enVarName; +relative to the Tcl library directory; +relative to the executable file in the standard installation +bin or bin/arch directory; +relative to the executable file in the current build tree; +relative to the executable file in a parallel build tree. +

    parray arrayName
    +Prints on standard output the names and values of all the elements +in the array arrayName. +ArrayName must be an array accessible to the caller of parray. +It may be either local or global. +

    tcl_endOfWord str start
    +Returns the index of the first end-of-word location that occurs after +a starting index start in the string str. An end-of-word +location is defined to be the first non-word character following the +first word character after the starting point. Returns -1 if there +are no more end-of-word locations after the starting point. See the +description of tcl_wordchars and tcl_nonwordchars below +for more details on how Tcl determines which characters are word +characters. +

    tcl_startOfNextWord str start
    +Returns the index of the first start-of-word location that occurs +after a starting index start in the string str. A +start-of-word location is defined to be the first word character +following a non-word character. Returns -1 if there are no more +start-of-word locations after the starting point. +

    tcl_startOfPreviousWord str start
    +Returns the index of the first start-of-word location that occurs +before a starting index start in the string str. Returns +-1 if there are no more start-of-word locations before the starting +point. +

    tcl_wordBreakAfter str start
    +Returns the index of the first word boundary after the starting index +start in the string str. Returns -1 if there are no more +boundaries after the starting point in the given string. The index +returned refers to the second character of the pair that comprises a +boundary. +

    tcl_wordBreakBefore str start
    +Returns the index of the first word boundary before the starting index +start in the string str. Returns -1 if there are no more +boundaries before the starting point in the given string. The index +returned refers to the second character of the pair that comprises a +boundary. + +

    +

    VARIABLES

    +The following global variables are defined or used by the procedures in +the Tcl library: +

    +

    +

    auto_execs
    +Used by auto_execok to record information about whether +particular commands exist as executable files. +

    auto_index
    +Used by auto_load to save the index information read from +disk. +

    auto_noexec
    +If set to any value, then unknown will not attempt to auto-exec +any commands. +

    auto_noload
    +If set to any value, then unknown will not attempt to auto-load +any commands. +

    auto_path
    +If set, then it must contain a valid Tcl list giving directories to +search during auto-load operations. +This variable is initialized during startup to contain, in order: +the directories listed in the TCLLIBPATH environment variable, +the directory named by the $tcl_library variable, +the parent directory of $tcl_library, +the directories listed in the $tcl_pkgPath variable. +

    env(TCL_LIBRARY)
    +If set, then it specifies the location of the directory containing +library scripts (the value of this variable will be +assigned to the tcl_library variable and therefore returned by +the command info library). If this variable isn't set then +a default value is used. +

    env(TCLLIBPATH)
    +If set, then it must contain a valid Tcl list giving directories to +search during auto-load operations. Directories must be specified in +Tcl format, using "/" as the path separator, regardless of platform. +This variable is only used when initializing the auto_path variable. +

    tcl_nonwordchars
    +This variable contains a regular expression that is used by routines +like tcl_endOfWord to identify whether a character is part of a +word or not. If the pattern matches a character, the character is +considered to be a non-word character. On Windows platforms, spaces, +tabs, and newlines are considered non-word characters. Under Unix, +everything but numbers, letters and underscores are considered +non-word characters. +

    tcl_wordchars
    +This variable contains a regular expression that is used by routines +like tcl_endOfWord to identify whether a character is part of a +word or not. If the pattern matches a character, the character is +considered to be a word character. On Windows platforms, words are +comprised of any character that is not a space, tab, or newline. Under +Unix, words are comprised of numbers, letters or underscores. +

    unknown_pending
    +Used by unknown to record the command(s) for which it is +searching. +It is used to detect errors where unknown recurses on itself +infinitely. +The variable is unset before unknown returns. + +

    +

    SEE ALSO

    +info, re_syntax +

    KEYWORDS

    +auto-exec, auto-load, library, unknown, word, whitespace +
    +Copyright © 1991-1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lindex.htm b/hlp/en/tcl/lindex.htm new file mode 100644 index 0000000..3af78ba --- /dev/null +++ b/hlp/en/tcl/lindex.htm @@ -0,0 +1,28 @@ +Tcl Built-In Commands - lindex manual page +

    NAME

    +lindex - Retrieve an element from a list +

    SYNOPSIS

    +lindex list index
    +

    DESCRIPTION

    +This command treats list as a Tcl list and returns the +index'th element from it (0 refers to the first element of the list). +In extracting the element, lindex observes the same rules +concerning braces and quotes and backslashes as the Tcl command +interpreter; however, variable +substitution and command substitution do not occur. +If index is negative or greater than or equal to the number +of elements in value, then an empty +string is returned. +If index has the value end, it refers to the last element +in the list, and end-integer refers to the last element in +the list minus the specified integer offset. + +

    SEE ALSO

    +list, lappend, linsert, llength, lsearch, lsort, lrange, lreplace +

    KEYWORDS

    +element, index, list +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/linsert.htm b/hlp/en/tcl/linsert.htm new file mode 100644 index 0000000..cef74ea --- /dev/null +++ b/hlp/en/tcl/linsert.htm @@ -0,0 +1,25 @@ +Tcl Built-In Commands - linsert manual page +

    NAME

    +linsert - Insert elements into a list +

    SYNOPSIS

    +linsert list index element ?element element ...?
    +

    DESCRIPTION

    +This command produces a new list from list by inserting all of the +element arguments just before the indexth element of +list. Each element argument will become a separate element of +the new list. If index is less than or equal to zero, then the new +elements are inserted at the beginning of the list. If index has the +value end, or if it is greater than or equal to the number of +elements in the list, then the new elements are appended to the list. +end-integer refers to the last element in the list minus the +specified integer offset. + +

    SEE ALSO

    +list, lappend, llength +

    KEYWORDS

    +element, insert, list +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/list.htm b/hlp/en/tcl/list.htm new file mode 100644 index 0000000..9f51783 --- /dev/null +++ b/hlp/en/tcl/list.htm @@ -0,0 +1,30 @@ +Built-In Commands - list manual page +

    NAME

    +list - Create a list +

    SYNOPSIS

    +list ?arg arg ...?
    +

    DESCRIPTION

    +This command returns a list comprised of all the args, +or an empty string if no args are specified. +Braces and backslashes get added as necessary, so that the index command +may be used on the result to re-extract the original arguments, and also +so that eval may be used to execute the resulting list, with +arg1 comprising the command's name and the other args comprising +its arguments. List produces slightly different results than +concat: concat removes one level of grouping before forming +the list, while list works directly from the original arguments. +For example, the command +
    list a b {c d e} {f {g h}}
    +will return +
    a b {c d e} {f {g h}}
    +while concat with the same arguments will return +
    a b c d e f {g h}
    +

    SEE ALSO

    +lappend, lindex, linsert, llength, lsearch, lsort, lrange, lreplace +

    KEYWORDS

    +element, list +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/llength.htm b/hlp/en/tcl/llength.htm new file mode 100644 index 0000000..9ae3c7a --- /dev/null +++ b/hlp/en/tcl/llength.htm @@ -0,0 +1,18 @@ +Built-In Commands - llength manual page +

    NAME

    +llength - Count the number of elements in a list +

    SYNOPSIS

    +llength list
    +

    DESCRIPTION

    +Treats list as a list and returns a decimal string giving +the number of elements in it. + +

    SEE ALSO

    +list, lindex, lrange +

    KEYWORDS

    +element, list, length +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/load.htm b/hlp/en/tcl/load.htm new file mode 100644 index 0000000..0dd08da --- /dev/null +++ b/hlp/en/tcl/load.htm @@ -0,0 +1,130 @@ +Tcl Built-In Commands - load manual page +
    +
    NAME +
    load - Load machine code and initialize new commands.
    +
    SYNOPSIS +
    +
    load fileName +
    load fileName packageName +
    load fileName packageName interp +
    +
    DESCRIPTION +
    PORTABILITY ISSUES +
    +
    Windows +
    +
    BUGS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +load - Load machine code and initialize new commands. +

    SYNOPSIS

    +load fileName
    +load fileName packageName
    +load fileName packageName interp
    +

    DESCRIPTION

    +This command loads binary code from a file into the +application's address space and calls an initialization procedure +in the package to incorporate it into an interpreter. fileName +is the name of the file containing the code; its exact form varies +from system to system but on most systems it is a shared library, +such as a .so file under Solaris or a DLL under Windows. +packageName is the name of the package, and is used to +compute the name of an initialization procedure. +interp is the path name of the interpreter into which to load +the package (see the interp manual entry for details); +if interp is omitted, it defaults to the +interpreter in which the load command was invoked. +

    +Once the file has been loaded into the application's address space, +one of two initialization procedures will be invoked in the new code. +Typically the initialization procedure will add new commands to a +Tcl interpreter. +The name of the initialization procedure is determined by +packageName and whether or not the target interpreter +is a safe one. For normal interpreters the name of the initialization +procedure will have the form pkg_Init, where pkg +is the same as packageName except that the first letter is +converted to upper case and all other letters +are converted to lower case. For example, if packageName is +foo or FOo, the initialization procedure's name will +be Foo_Init. +

    +If the target interpreter is a safe interpreter, then the name +of the initialization procedure will be pkg_SafeInit +instead of pkg_Init. +The pkg_SafeInit function should be written carefully, so that it +initializes the safe interpreter only with partial functionality provided +by the package that is safe for use by untrusted code. For more information +on Safe-Tcl, see the safe manual entry. +

    +The initialization procedure must match the following prototype: +

    typedef int Tcl_PackageInitProc(Tcl_Interp *interp);
    +The interp argument identifies the interpreter in which the +package is to be loaded. The initialization procedure must return +TCL_OK or TCL_ERROR to indicate whether or not it completed +successfully; in the event of an error it should set the interpreter's result +to point to an error message. The result of the load command +will be the result returned by the initialization procedure. +

    +The actual loading of a file will only be done once for each fileName +in an application. If a given fileName is loaded into multiple +interpreters, then the first load will load the code and +call the initialization procedure; subsequent loads will +call the initialization procedure without loading the code again. +It is not possible to unload or reload a package. +

    +The load command also supports packages that are statically +linked with the application, if those packages have been registered +by calling the Tcl_StaticPackage procedure. +If fileName is an empty string, then packageName must +be specified. +

    +If packageName is omitted or specified as an empty string, +Tcl tries to guess the name of the package. +This may be done differently on different platforms. +The default guess, which is used on most UNIX platforms, is to +take the last element of fileName, strip off the first +three characters if they are lib, and use any following +alphabetic and underline characters as the module name. +For example, the command load libxyz4.2.so uses the module +name xyz and the command load bin/last.so {} uses the +module name last. +

    +If fileName is an empty string, then packageName must +be specified. +The load command first searches for a statically loaded package +(one that has been registered by calling the Tcl_StaticPackage +procedure) by that name; if one is found, it is used. +Otherwise, the load command searches for a dynamically loaded +package by that name, and uses it if it is found. If several +different files have been loaded with different versions of +the package, Tcl picks the file that was loaded first. + +

    PORTABILITY ISSUES

    +
    +

    Windows
    +When a load fails with "library not found" error, it is also possible +that a dependent library was not found. To see the dependent libraries, +type ``dumpbin -imports <dllname>'' in a DOS console to see what the +library must import. +When loading a DLL in the current directory, Windows will ignore ``./'' as +a path specifier and use a search heuristic to find the DLL instead. +To avoid this, load the DLL with +
    load [file join [pwd] mylib.DLL]
    +

    +

    BUGS

    +If the same file is loaded by different fileNames, it will +be loaded into the process's address space multiple times. The +behavior of this varies from system to system (some systems may +detect the redundant loads, others may not). + +

    SEE ALSO

    +info sharedlibextension, Tcl_StaticPackage, safe +

    KEYWORDS

    +binary code, loading, safe interpreter, shared library +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lrange.htm b/hlp/en/tcl/lrange.htm new file mode 100644 index 0000000..133874e --- /dev/null +++ b/hlp/en/tcl/lrange.htm @@ -0,0 +1,31 @@ +Tcl Built-In Commands - lrange manual page +

    NAME

    +lrange - Return one or more adjacent elements from a list +

    SYNOPSIS

    +lrange list first last
    +

    DESCRIPTION

    +List must be a valid Tcl list. This command will +return a new list consisting of elements +first through last, inclusive. +First or last +may be end (or any abbreviation of it) to refer to the last +element of the list. +If first is less than zero, it is treated as if it were zero. +If last is greater than or equal to the number of elements +in the list, then it is treated as if it were end. +If first is greater than last then an empty string +is returned. +Note: ``lrange list first first'' does not always produce the +same result as ``lindex list first'' (although it often does +for simple fields that aren't enclosed in braces); it does, however, +produce exactly the same results as ``list [lindex list first]'' + +

    SEE ALSO

    +lappend, lindex, linsert, list, llength, lreplace +

    KEYWORDS

    +element, list, range, sublist +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lreplace.htm b/hlp/en/tcl/lreplace.htm new file mode 100644 index 0000000..dbe6f4f --- /dev/null +++ b/hlp/en/tcl/lreplace.htm @@ -0,0 +1,39 @@ +Tcl Built-In Commands - lreplace manual page +

    NAME

    +lreplace - Replace elements in a list with new elements +

    SYNOPSIS

    +lreplace list first last ?element element ...?
    +

    DESCRIPTION

    +lreplace returns a new list formed by replacing one or more elements of +list with the element arguments. +first and last specify the first and last index of the +range of elements to replace. 0 refers to the first element of the +list, and end (or any abbreviation of it) may be used to refer +to the last element of the list. If list is empty, then +first and last are ignored. + +If first is less than zero, it is considered to refer to the +first element of the list. For non-empty lists, the element indicated +by first must exist. + +If last is less than zero but greater than first, then any +specified elements will be prepended to the list. If last is +less than first then no elements are deleted; the new elements +are simply inserted before first. + +The element arguments specify zero or more new arguments to +be added to the list in place of those that were deleted. +Each element argument will become a separate element of +the list. If no element arguments are specified, then the elements +between first and last are simply deleted. If list +is empty, any element arguments are added to the end of the list. + +

    SEE ALSO

    +lappend, lindex, linsert, list, llength, lrange, lsearch, lsort +

    KEYWORDS

    +element, list, replace +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lsearch.htm b/hlp/en/tcl/lsearch.htm new file mode 100644 index 0000000..909ddfa --- /dev/null +++ b/hlp/en/tcl/lsearch.htm @@ -0,0 +1,36 @@ +Tcl Built-In Commands - lsearch manual page +

    NAME

    +lsearch - See if a list contains a particular element +

    SYNOPSIS

    +lsearch ?mode? list pattern
    +

    DESCRIPTION

    +This command searches the elements of list to see if one +of them matches pattern. +If so, the command returns the index of the first matching +element. +If not, the command returns -1. +The mode argument indicates how the elements of the list are to +be matched against pattern and it must have one of the following +values: +

    +

    +

    -exact
    +The list element must contain exactly the same string as pattern. +

    -glob
    +Pattern is a glob-style pattern which is matched against each list +element using the same rules as the string match command. +

    -regexp
    +Pattern is treated as a regular expression and matched against +each list element using the rules described in the re_syntax +reference page. +

    +

    +If mode is omitted then it defaults to -glob. + +

    KEYWORDS

    +list, match, pattern, regular expression, search, string +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/lsort.htm b/hlp/en/tcl/lsort.htm new file mode 100644 index 0000000..2d54e54 --- /dev/null +++ b/hlp/en/tcl/lsort.htm @@ -0,0 +1,160 @@ +Tcl Built-In Commands - lsort manual page +
    +
    NAME +
    lsort - Sort the elements of a list
    +
    SYNOPSIS +
    +
    lsort ?options? list +
    +
    DESCRIPTION +
    +
    -ascii +
    -dictionary +
    -integer +
    -real +
    -command command +
    -increasing +
    -decreasing +
    -index index +
    -unique +
    +
    NOTES +
    EXAMPLES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +lsort - Sort the elements of a list +

    SYNOPSIS

    +lsort ?options? list
    +

    DESCRIPTION

    +This command sorts the elements of list, returning a new +list in sorted order. The implementation of the lsort command +uses the merge-sort algorithm which is a stable sort that has O(n log +n) performance characteristics. +

    +By default ASCII sorting is used with the result returned in +increasing order. However, any of the following options may be +specified before list to control the sorting process (unique +abbreviations are accepted): +

    +

    +

    -ascii
    +Use string comparison with ASCII collation order. This is the default. +

    -dictionary
    +Use dictionary-style comparison. This is the same as -ascii +except (a) case is ignored except as a tie-breaker and (b) if two +strings contain embedded numbers, the numbers compare as integers, +not characters. For example, in -dictionary mode, bigBoy +sorts between bigbang and bigboy, and x10y +sorts between x9y and x11y. +

    -integer
    +Convert list elements to integers and use integer comparison. +

    -real
    +Convert list elements to floating-point values and use floating comparison. +

    -command command
    +Use command as a comparison command. +To compare two elements, evaluate a Tcl script consisting of +command with the two elements appended as additional +arguments. The script should return an integer less than, +equal to, or greater than zero if the first element is to +be considered less than, equal to, or greater than the second, +respectively. +

    -increasing
    +Sort the list in increasing order (``smallest'' items first). +This is the default. +

    -decreasing
    +Sort the list in decreasing order (``largest'' items first). +

    -index index
    +If this option is specified, each of the elements of list must +itself be a proper Tcl sublist. Instead of sorting based on whole +sublists, lsort will extract the index'th element from +each sublist and sort based on the given element. The keyword +end is allowed for the index to sort on the last sublist +element, +and end-index sorts on a sublist element offset from +the end. +For example, +
    lsort -integer -index 1 {{First 24} {Second 18} {Third 30}}
    +returns {Second 18} {First 24} {Third 30}, and +
    lsort -index end-1 {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}}
    +returns {c 4 5 6 d h} {a 1 e i} {b 2 3 f g}. +This option is much more efficient than using -command +to achieve the same effect. +

    -unique
    +If this option is specified, then only the last set of duplicate +elements found in the list will be retained. Note that duplicates are +determined relative to the comparison used in the sort. Thus if +-index 0 is used, {1 a} and {1 b} would be +considered duplicates and only the second element, {1 b}, would +be retained. + +

    +

    NOTES

    +The options to lsort only control what sort of comparison is +used, and do not necessarily constrain what the values themselves +actually are. This distinction is only noticeable when the list to be +sorted has fewer than two elements. +

    +The lsort command is reentrant, meaning it is safe to use as +part of the implementation of a command used in the -command +option. + +

    EXAMPLES

    +Sorting a list using ASCII sorting: +
    % lsort {a10 B2 b1 a1 a2}
    +B2 a1 a10 a2 b1
    +

    +Sorting a list using Dictionary sorting: +

    % lsort -dictionary {a10 B2 b1 a1 a2}
    +a1 a2 a10 b1 B2
    +

    +Sorting lists of integers: +

    % lsort -integer {5 3 1 2 11 4}
    +1 2 3 4 5 11
    +% lsort -integer {1 2 0x5 7 0 4 -1}
    +-1 0 1 2 4 0x5 7
    +

    +Sorting lists of floating-point numbers: +

    % lsort -real {5 3 1 2 11 4}
    +1 2 3 4 5 11
    +% lsort -real {.5 0.07e1 0.4 6e-1}
    +0.4 .5 6e-1 0.07e1
    +

    +Sorting using indices: +

    % # Note the space character before the c
    +% lsort {{a 5} { c 3} {b 4} {e 1} {d 2}}
    +{ c 3} {a 5} {b 4} {d 2} {e 1}
    +% lsort -index 0 {{a 5} { c 3} {b 4} {e 1} {d 2}}
    +{a 5} {b 4} { c 3} {d 2} {e 1}
    +% lsort -index 1 {{a 5} { c 3} {b 4} {e 1} {d 2}}
    +{e 1} {d 2} { c 3} {b 4} {a 5}
    +

    +Stripping duplicate values using sorting: +

    % lsort -unique {a b c a b c a b c}
    +a b c
    +

    +More complex sorting using a comparison function: +

    % proc compare {a b} {
    +    set a0 [lindex $a 0]
    +    set b0 [lindex $b 0]
    +    if {$a0 < $b0} {
    +        return -1
    +    } elseif {$a0 > $b0} {
    +        return 1
    +    }
    +    return [string compare [lindex $a 1] [lindex $b 1]]
    +}
    +% lsort -command compare \
    +        {{3 apple} {0x2 carrot} {1 dingo} {2 banana}}
    +{1 dingo} {2 banana} {0x2 carrot} {3 apple}
    +

    SEE ALSO

    +lappend, lindex, linsert, list, llength, lrange, lreplace, lsearch +

    KEYWORDS

    +element, list, order, sort +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1999 Scriptics Corporation
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/memory.htm b/hlp/en/tcl/memory.htm new file mode 100644 index 0000000..7ce50cc --- /dev/null +++ b/hlp/en/tcl/memory.htm @@ -0,0 +1,89 @@ +Tcl Built-In Commands - memory manual page +
    +
    NAME +
    memory - Control Tcl memory debugging capabilities.
    +
    SYNOPSIS +
    +
    memory option ?arg arg ...? +
    +
    +
    DESCRIPTION +
    +
    memory info +
    memory trace [on|off] +
    memory validate [on|off] +
    memory trace_on_at_malloc count +
    memory break_on_malloc count +
    memory display file +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +memory - Control Tcl memory debugging capabilities. +

    SYNOPSIS

    +memory option ?arg arg ...?
    +
    +

    DESCRIPTION

    +The memory command gives the Tcl developer control of Tcl's memory +debugging capabilities. The memory command has several suboptions, which are +described below. It is only available when Tcl has been compiled with +memory debugging enabled (when TCL_MEM_DEBUG is defined at +compile time). +

    +

    +

    memory info
    +Produces a report containing the total allocations and frees since +Tcl began, the current packets allocated (the current +number of calls to ckalloc not met by a corresponding call +to ckfree), the current bytes allocated, and the maximum number +of packets and bytes allocated. +

    memory trace [on|off]
    +
    +Turns memory tracing on or off. When memory tracing is on, every call +to ckalloc causes a line of trace information to be written to +stderr, consisting of the word ckalloc, followed by the +address returned, the amount of memory allocated, and the C filename +and line number of the code performing the allocation. For example: +
    ckalloc 40e478 98 tclProc.c 1406
    +Calls to ckfree are traced in the same manner. +

    memory validate [on|off]
    +Turns memory validation on or off. When memory validation is enabled, +on every call to ckalloc or ckfree, the guard zones are +checked for every piece of memory currently in existence that was +allocated by ckalloc. This has a large performance impact and +should only be used when overwrite problems are strongly suspected. +The advantage of enabling memory validation is that a guard zone +overwrite can be detected on the first call to ckalloc or +ckfree after the overwrite occurred, rather than when the +specific memory with the overwritten guard zone(s) is freed, which may +occur long after the overwrite occurred. +

    memory trace_on_at_malloc count
    +Enable memory tracing after count ckalloc's have been performed. +For example, if you enter memory trace_on_at_malloc 100, +after the 100th call to ckalloc, memory trace information will begin +being displayed for all allocations and frees. Since there can be a lot +of memory activity before a problem occurs, judicious use of this option +can reduce the slowdown caused by tracing (and the amount of trace information +produced), if you can identify a number of allocations that occur before +the problem sets in. The current number of memory allocations that have +occurred since Tcl started is printed on a guard zone failure. +

    memory break_on_malloc count
    +After the count allocations have been performed, ckalloc's +output a message to this effect and that it is now attempting to enter +the C debugger. Tcl will then issue a SIGINT signal against itself. +If you are running Tcl under a C debugger, it should then enter the debugger +command mode. +

    memory display file
    +Write a list of all currently allocated memory to the specified file. + +

    +

    SEE ALSO

    +ckalloc, ckfree, Tcl_ValidateAllMemory, Tcl_DumpActiveMemory, TCL_MEM_DEBUG +

    KEYWORDS

    +memory, debug +
    +Copyright © 1992-1999 by Karl Lehenbauer and Mark Diekhans
    +Copyright © 2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/msgcat.htm b/hlp/en/tcl/msgcat.htm new file mode 100644 index 0000000..70c89b2 --- /dev/null +++ b/hlp/en/tcl/msgcat.htm @@ -0,0 +1,244 @@ +Tcl Built-In Commands - msgcat manual page +
    +
    NAME +
    msgcat - Tcl message catalog
    +
    SYNOPSIS +
    +
    ::msgcat::mc src-string +
    ::msgcat::mclocale ?newLocale? +
    ::msgcat::mcpreferences +
    ::msgcat::mcload dirname +
    ::msgcat::mcset locale src-string ?translate-string? +
    ::msgcat::mcunknown locale src-string +
    +
    DESCRIPTION +
    COMMANDS +
    +
    ::msgcat::mc src-string ?arg arg ...? +
    +
    +
    ::msgcat::mclocale ?newLocale? +
    ::msgcat::mcpreferences +
    ::msgcat::mcload dirname +
    ::msgcat::mcset locale src-string ?translate-string? +
    ::msgcat::mcunknown locale src-string +
    +
    LOCALE AND SUBLOCALE SPECIFICATION +
    NAMESPACES AND MESSAGE CATALOGS +
    LOCATION AND FORMAT OF MESSAGE FILES +
    +
    +
    RECOMMENDED MESSAGE SETUP FOR PACKAGES +
    +
    +
    POSTITIONAL CODES FOR FORMAT AND SCAN COMMANDS +
    CREDITS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +msgcat - Tcl message catalog +

    SYNOPSIS

    +::msgcat::mc src-string
    +::msgcat::mclocale ?newLocale?
    +::msgcat::mcpreferences
    +::msgcat::mcload dirname
    +::msgcat::mcset locale src-string ?translate-string?
    +::msgcat::mcunknown locale src-string
    +

    DESCRIPTION

    +The msgcat package provides a set of functions +that can be used to manage multi-lingual user interfaces. +Text strings are defined in a ``message catalog'' which +is independent from the application, and +which can be edited or localized without modifying +the application source code. New languages +or locales are provided by adding a new file to +the message catalog. +

    +Use of the message catalog is optional by any application +or package, but is encouraged if the application or package +wishes to be enabled for multi-lingual applications. + +

    COMMANDS

    +
    +

    ::msgcat::mc src-string ?arg arg ...?
    +Returns a translation of src-string according to the +user's current locale. If additional arguments past src-string +are given, the format command is used to substitute the +additional arguments in the translation of src-string. + +::msgcat::mc will search the messages defined +in the current namespace for a translation of src-string; if +none is found, it will search in the parent of the current namespace, +and so on until it reaches the global namespace. If no translation +string exists, ::msgcat::mcunknown is called and the string +returned from ::msgcat::mcunknown is returned. +

    +

    +::msgcat::mc is the main function used to localize an +application. Instead of using an English string directly, an +applicaton can pass the English string through ::msgcat::mc and +use the result. If an application is written for a single language in +this fashion, then it is easy to add support for additional languages +later simply by defining new message catalog entries. +

    +

    +

    ::msgcat::mclocale ?newLocale?
    +This function sets the locale to newLocale. If newLocale +is omitted, the current locale is returned, otherwise the current locale +is set to newLocale. +The initial locale defaults to the locale specified in +the user's environment. See LOCALE AND SUBLOCALE SPECIFICATION +below for a description of the locale string format. +

    ::msgcat::mcpreferences
    +Returns an ordered list of the locales preferred by +the user, based on the user's language specification. +The list is ordered from most specific to least +preference. If the user has specified LANG=en_US_funky, +this procedure would return {en_US_funky en_US en}. +

    ::msgcat::mcload dirname
    +Searches the specified directory for files that match +the language specifications returned by ::msgcat::mcpreferences. +Each file located is sourced. The file extension is ``.msg''. +The number of message files which matched the specification +and were loaded is returned. +

    ::msgcat::mcset locale src-string ?translate-string?
    +Sets the translation for src-string to translate-string +in the specified locale. If translate-string is not +specified, src-string is used for both. The function +returns translate-string. +

    ::msgcat::mcunknown locale src-string
    +This routine is called by ::msgcat::mc in the case when +a translation for src-string is not defined in the +current locale. The default action is to return +src-string. This procedure can be redefined by the +application, for example to log error messages for each unknown +string. The ::msgcat::mcunknown procedure is invoked at the +same stack context as the call to ::msgcat::mc. The return vaue +of ::msgcat::mcunknown is used as the return vaue for the call +to ::msgcat::mc. + +

    +

    LOCALE AND SUBLOCALE SPECIFICATION

    +The locale is specified by a locale string. +The locale string consists of +a language code, an optional country code, and an optional +system-specific code, each separated by ``_''. The country and language +codes are specified in standards ISO-639 and ISO-3166. +For example, the locale ``en'' specifies English and + ``en_US'' specifes U.S. English. +

    +The locale defaults to the value in env(LANG) at the time the +msgcat package is loaded. If env(LANG) is not defined, then the +locale defaults to ``C''. +

    +When a locale is specified by the user, a ``best match'' search is +performed during string translation. For example, if a user specifies +en_UK_Funky, the locales ``en_UK_Funky'', ``en_UK'', and ``en'' are +searched in order until a matching translation string is found. If no +translation string is available, then ::msgcat::unknown is +called. + +

    NAMESPACES AND MESSAGE CATALOGS

    +Strings stored in the message catalog are stored relative +to the namespace from which they were added. This allows +multiple packages to use the same strings without fear +of collisions with other packages. It also allows the +source string to be shorter and less prone to typographical +error. +

    +For example, executing the code +

    mcset en hello "hello from ::"
    +namespace eval foo {mcset en hello "hello from ::foo"}
    +puts [mc hello]
    +namespace eval foo {puts [mc hello]}
    +will print +
    hello from ::
    +hello from ::foo
    +

    +When searching for a translation of a message, the +message catalog will search first the current namespace, +then the parent of the current namespace, and so on until +the global namespace is reached. This allows child namespaces +to "inherit" messages from their parent namespace. +

    +For example, executing the code +

    mcset en m1 ":: message1"
    +mcset en m2 ":: message2"
    +mcset en m3 ":: message3"
    +namespace eval ::foo {
    +    mcset en m2 "::foo message2"
    +    mcset en m3 "::foo message3"
    +}
    +namespace eval ::foo::bar {
    +    mcset en m3 "::foo::bar message3"
    +}
    +puts "[mc m1]; [mc m2]; [mc m3]"
    +namespace eval ::foo {puts "[mc m1]; [mc m2]; [mc m3]"}
    +namespace eval ::foo::bar {puts "[mc m1]; [mc m2]; [mc m3]"}
    +will print +
    :: message1; :: message2; :: message3
    +:: message1; ::foo message2; ::foo message3
    +:: message1; ::foo message2; ::foo::bar message3
    +

    LOCATION AND FORMAT OF MESSAGE FILES

    +Message files can be located in any directory, subject +to the following conditions: +

    +

    +

    [1]
    +All message files for a package are in the same directory. +

    [2]
    +The message file name is a locale specifier followed +by ``.msg''. For example: +
    es.msg    -- spanish
    +en_UK.msg -- UK English
    +

    [3]
    +The file contains a series of calls to mcset, setting the +necessary translation strings for the language. For example: +
    ::msgcat::mcset es "Free Beer!" "Cerveza Gracias!"
    +

    +

    RECOMMENDED MESSAGE SETUP FOR PACKAGES

    +If a package is installed into a subdirectory of the +tcl_pkgPath and loaded via package require, the +following procedure is recommended. +

    +

    +

    [1]
    +During package installation, create a subdirectory +msgs under your package directory. +

    [2]
    +Copy your *.msg files into that directory. +

    [3]
    + Add the following command to your package +initialization script: +
    # load language files, stored in msgs subdirectory
    +::msgcat::mcload [file join [file dirname [info script]] msgs]
    +

    +

    POSTITIONAL CODES FOR FORMAT AND SCAN COMMANDS

    +It is possible that a message string used as an argument +to format might have positionally dependent parameters that +might need to be repositioned. For example, it might be +syntactically desirable to rearrange the sentence structure +while translating. +
    format "We produced %d units in location %s" $num $city
    +format "In location %s we produced %d units" $city $num
    +

    +This can be handled by using the positional +parameters: +

    format "We produced %1\$d units in location %2\$s" $num $city
    +format "In location %2\$s we produced %1\$d units" $num $city
    +

    +Similarly, positional parameters can be used with scan to +extract values from internationalized strings. + +

    CREDITS

    +The message catalog code was developed by Mark Harrison. + +

    SEE ALSO

    +format, scan, namespace, package +

    KEYWORDS

    +internationalization, i18n, localization, l10n, message, text, translation +
    +Copyright © 1998 Mark Harrison.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/namespace.htm b/hlp/en/tcl/namespace.htm new file mode 100644 index 0000000..14a9849 --- /dev/null +++ b/hlp/en/tcl/namespace.htm @@ -0,0 +1,532 @@ +Tcl Built-In Commands - namespace manual page +
    +
    NAME +
    namespace - create and manipulate contexts for commands and variables
    +
    SYNOPSIS +
    +
    namespace ?option? ?arg ...? +
    +
    DESCRIPTION +
    +
    namespace children ?namespace? ?pattern? +
    namespace code script +
    namespace current +
    namespace delete ?namespace namespace ...? +
    namespace eval namespace arg ?arg ...? +
    namespace export ?-clear? ?pattern pattern ...? +
    namespace forget ?pattern pattern ...? +
    namespace import ?-force? ?pattern pattern ...? +
    namespace inscope namespace arg ?arg ...? +
    namespace origin command +
    namespace parent ?namespace? +
    namespace qualifiers string +
    namespace tail string +
    namespace which ?-command? ?-variable? name +
    +
    WHAT IS A NAMESPACE? +
    QUALIFIED NAMES +
    NAME RESOLUTION +
    IMPORTING COMMANDS +
    EXPORTING COMMANDS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +namespace - create and manipulate contexts for commands and variables +

    SYNOPSIS

    +namespace ?option? ?arg ...?
    +

    DESCRIPTION

    +The namespace command lets you create, access, and destroy +separate contexts for commands and variables. +See the section WHAT IS A NAMESPACE? below +for a brief overview of namespaces. +The legal option's are listed below. +Note that you can abbreviate the option's. +

    +

    +

    namespace children ?namespace? ?pattern?
    +Returns a list of all child namespaces that belong to the +namespace namespace. +If namespace is not specified, +then the children are returned for the current namespace. +This command returns fully-qualified names, +which start with ::. +If the optional pattern is given, +then this command returns only the names that match the glob-style pattern. +The actual pattern used is determined as follows: +a pattern that starts with :: is used directly, +otherwise the namespace namespace +(or the fully-qualified name of the current namespace) +is prepended onto the the pattern. +

    namespace code script
    +Captures the current namespace context for later execution +of the script script. +It returns a new script in which script has been wrapped +in a namespace code command. +The new script has two important properties. +First, it can be evaluated in any namespace and will cause +script to be evaluated in the current namespace +(the one where the namespace code command was invoked). +Second, additional arguments can be appended to the resulting script +and they will be passed to script as additional arguments. +For example, suppose the command +set script [namespace code {foo bar}] +is invoked in namespace ::a::b. +Then eval "$script x y" +can be executed in any namespace (assuming the value of +script has been passed in properly) +and will have the same effect as the command +namespace eval ::a::b {foo bar x y}. +This command is needed because +extensions like Tk normally execute callback scripts +in the global namespace. +A scoped command captures a command together with its namespace context +in a way that allows it to be executed properly later. +See the section SCOPED VALUES for some examples +of how this is used to create callback scripts. +

    namespace current
    +Returns the fully-qualified name for the current namespace. +The actual name of the global namespace is ``'' +(i.e., an empty string), +but this command returns :: for the global namespace +as a convenience to programmers. +

    namespace delete ?namespace namespace ...?
    +Each namespace namespace is deleted +and all variables, procedures, and child namespaces +contained in the namespace are deleted. +If a procedure is currently executing inside the namespace, +the namespace will be kept alive until the procedure returns; +however, the namespace is marked to prevent other code from +looking it up by name. +If a namespace doesn't exist, this command returns an error. +If no namespace names are given, this command does nothing. +

    namespace eval namespace arg ?arg ...?
    +Activates a namespace called namespace and evaluates some code +in that context. +If the namespace does not already exist, it is created. +If more than one arg argument is specified, +the arguments are concatenated together with a space between each one +in the same fashion as the eval command, +and the result is evaluated. +
    +

    +If namespace has leading namespace qualifiers +and any leading namespaces do not exist, +they are automatically created. +

    namespace export ?-clear? ?pattern pattern ...?
    +Specifies which commands are exported from a namespace. +The exported commands are those that can be later imported +into another namespace using a namespace import command. +Both commands defined in a namespace and +commands the namespace has previously imported +can be exported by a namespace. +The commands do not have to be defined +at the time the namespace export command is executed. +Each pattern may contain glob-style special characters, +but it may not include any namespace qualifiers. +That is, the pattern can only specify commands +in the current (exporting) namespace. +Each pattern is appended onto the namespace's list of export patterns. +If the -clear flag is given, +the namespace's export pattern list is reset to empty before any +pattern arguments are appended. +If no patterns are given and the -clear flag isn't given, +this command returns the namespace's current export list. +

    namespace forget ?pattern pattern ...?
    +Removes previously imported commands from a namespace. +Each pattern is a qualified name such as +foo::x or a::b::p*. +Qualified names contain ::s and qualify a name +with the name of one or more namespaces. +Each pattern is qualified with the name of an exporting namespace +and may have glob-style special characters in the command name +at the end of the qualified name. +Glob characters may not appear in a namespace name. +This command first finds the matching exported commands. +It then checks whether any of those those commands +were previously imported by the current namespace. +If so, this command deletes the corresponding imported commands. +In effect, this un-does the action of a namespace import command. +

    namespace import ?-force? ?pattern pattern ...?
    +Imports commands into a namespace. +Each pattern is a qualified name like +foo::x or a::p*. +That is, it includes the name of an exporting namespace +and may have glob-style special characters in the command name +at the end of the qualified name. +Glob characters may not appear in a namespace name. +All the commands that match a pattern string +and which are currently exported from their namespace +are added to the current namespace. +This is done by creating a new command in the current namespace +that points to the exported command in its original namespace; +when the new imported command is called, it invokes the exported command. +This command normally returns an error +if an imported command conflicts with an existing command. +However, if the -force option is given, +imported commands will silently replace existing commands. +The namespace import command has snapshot semantics: +that is, only requested commands that are currently defined +in the exporting namespace are imported. +In other words, you can import only the commands that are in a namespace +at the time when the namespace import command is executed. +If another command is defined and exported in this namespace later on, +it will not be imported. +

    namespace inscope namespace arg ?arg ...?
    +Executes a script in the context of a particular namespace. +This command is not expected to be used directly by programmers; +calls to it are generated implicitly when applications +use namespace code commands to create callback scripts +that the applications then register with, e.g., Tk widgets. +The namespace inscope command is much like the namespace eval +command except that it has lappend semantics +and the namespace must already exist. +It treats the first argument as a list, +and appends any arguments after the first +onto the end as proper list elements. +namespace inscope ::foo a x y z +is equivalent to +namespace eval ::foo [concat a [list x y z]] +This lappend semantics is important because many callback scripts +are actually prefixes. +

    namespace origin command
    +Returns the fully-qualified name of the original command +to which the imported command command refers. +When a command is imported into a namespace, +a new command is created in that namespace +that points to the actual command in the exporting namespace. +If a command is imported into a sequence of namespaces +a, b,...,n where each successive namespace +just imports the command from the previous namespace, +this command returns the fully-qualified name of the original command +in the first namespace, a. +If command does not refer to an imported command, +the command's own fully-qualified name is returned. +

    namespace parent ?namespace?
    +Returns the fully-qualified name of the parent namespace +for namespace namespace. +If namespace is not specified, +the fully-qualified name of the current namespace's parent is returned. +

    namespace qualifiers string
    +Returns any leading namespace qualifiers for string. +Qualifiers are namespace names separated by ::s. +For the string ::foo::bar::x, +this command returns ::foo::bar, +and for :: it returns an empty string. +This command is the complement of the namespace tail command. +Note that it does not check whether the +namespace names are, in fact, +the names of currently defined namespaces. +

    namespace tail string
    +Returns the simple name at the end of a qualified string. +Qualifiers are namespace names separated by ::s. +For the string ::foo::bar::x, +this command returns x, +and for :: it returns an empty string. +This command is the complement of the namespace qualifiers command. +It does not check whether the namespace names are, in fact, +the names of currently defined namespaces. +

    namespace which ?-command? ?-variable? name
    +Looks up name as either a command or variable +and returns its fully-qualified name. +For example, if name does not exist in the current namespace +but does exist in the global namespace, +this command returns a fully-qualified name in the global namespace. +If the command or variable does not exist, +this command returns an empty string. If the variable has been +created but not defined, such as with the variable command +or through a trace on the variable, this command will return the +fully-qualified name of the variable. +If no flag is given, name is treated as a command name. +See the section NAME RESOLUTION below for an explanation of +the rules regarding name resolution. + +

    +

    WHAT IS A NAMESPACE?

    +A namespace is a collection of commands and variables. +It encapsulates the commands and variables to ensure that they +won't interfere with the commands and variables of other namespaces. +Tcl has always had one such collection, +which we refer to as the global namespace. +The global namespace holds all global variables and commands. +The namespace eval command lets you create new namespaces. +For example, +
    namespace eval Counter {
    +    namespace export bump
    +    variable num 0
    +
    +    proc bump {} {
    +        variable num
    +        incr num
    +    }
    +}
    +creates a new namespace containing the variable num and +the procedure bump. +The commands and variables in this namespace are separate from +other commands and variables in the same program. +If there is a command named bump in the global namespace, +for example, it will be different from the command bump +in the Counter namespace. +

    +Namespace variables resemble global variables in Tcl. +They exist outside of the procedures in a namespace +but can be accessed in a procedure via the variable command, +as shown in the example above. +

    +Namespaces are dynamic. +You can add and delete commands and variables at any time, +so you can build up the contents of a +namespace over time using a series of namespace eval commands. +For example, the following series of commands has the same effect +as the namespace definition shown above: +

    namespace eval Counter {
    +    variable num 0
    +    proc bump {} {
    +        variable num
    +        return [incr num]
    +    }
    +}
    +namespace eval Counter {
    +    proc test {args} {
    +        return $args
    +    }
    +}
    +namespace eval Counter {
    +    rename test ""
    +}
    +Note that the test procedure is added to the Counter namespace, +and later removed via the rename command. +

    +Namespaces can have other namespaces within them, +so they nest hierarchically. +A nested namespace is encapsulated inside its parent namespace +and can not interfere with other namespaces. + +

    QUALIFIED NAMES

    +Each namespace has a textual name such as +history or ::safe::interp. +Since namespaces may nest, +qualified names are used to refer to +commands, variables, and child namespaces contained inside namespaces. +Qualified names are similar to the hierarchical path names for +Unix files or Tk widgets, +except that :: is used as the separator +instead of / or .. +The topmost or global namespace has the name ``'' (i.e., an empty string), +although :: is a synonym. +As an example, the name ::safe::interp::create +refers to the command create in the namespace interp +that is a child of of namespace ::safe, +which in turn is a child of the global namespace ::. +

    +If you want to access commands and variables from another namespace, +you must use some extra syntax. +Names must be qualified by the namespace that contains them. +From the global namespace, +we might access the Counter procedures like this: +

    Counter::bump 5
    +Counter::Reset
    +We could access the current count like this: +
    puts "count = $Counter::num"
    +When one namespace contains another, you may need more than one +qualifier to reach its elements. +If we had a namespace Foo that contained the namespace Counter, +you could invoke its bump procedure +from the global namespace like this: +
    Foo::Counter::bump 3
    +

    +You can also use qualified names when you create and rename commands. +For example, you could add a procedure to the Foo +namespace like this: +

    proc Foo::Test {args} {return $args}
    +And you could move the same procedure to another namespace like this: +
    rename Foo::Test Bar::Test
    +

    +There are a few remaining points about qualified names +that we should cover. +Namespaces have nonempty names except for the global namespace. +:: is disallowed in simple command, variable, and namespace names +except as a namespace separator. +Extra :s in a qualified name are ignored; +that is, two or more :s are treated as a namespace separator. +A trailing :: in a qualified variable or command name +refers to the variable or command named {}. +However, a trailing :: in a qualified namespace name is ignored. + +

    NAME RESOLUTION

    +In general, all Tcl commands that take variable and command names +support qualified names. +This means you can give qualified names to such commands as +set, proc, rename, and interp alias. +If you provide a fully-qualified name that starts with a ::, +there is no question about what command, variable, or namespace +you mean. +However, if the name does not start with a :: +(i.e., is relative), +Tcl follows a fixed rule for looking it up: +Command and variable names are always resolved +by looking first in the current namespace, +and then in the global namespace. +Namespace names, on the other hand, are always resolved +by looking in only the current namespace. +

    +In the following example, +

    set traceLevel 0
    +namespace eval Debug {
    +    printTrace $traceLevel
    +}
    +Tcl looks for traceLevel in the namespace Debug +and then in the global namespace. +It looks up the command printTrace in the same way. +If a variable or command name is not found in either context, +the name is undefined. +To make this point absolutely clear, consider the following example: +
    set traceLevel 0
    +namespace eval Foo {
    +    variable traceLevel 3
    +
    +    namespace eval Debug {
    +        printTrace $traceLevel
    +    }
    +}
    +Here Tcl looks for traceLevel first in the namespace Foo::Debug. +Since it is not found there, Tcl then looks for it +in the global namespace. +The variable Foo::traceLevel is completely ignored +during the name resolution process. +

    +You can use the namespace which command to clear up any question +about name resolution. +For example, the command: +

    namespace eval Foo::Debug {namespace which -variable traceLevel}
    +returns ::traceLevel. +On the other hand, the command, +
    namespace eval Foo {namespace which -variable traceLevel}
    +returns ::Foo::traceLevel. +

    +As mentioned above, +namespace names are looked up differently +than the names of variables and commands. +Namespace names are always resolved in the current namespace. +This means, for example, +that a namespace eval command that creates a new namespace +always creates a child of the current namespace +unless the new namespace name begins with a ::. +

    +Tcl has no access control to limit what variables, commands, +or namespaces you can reference. +If you provide a qualified name that resolves to an element +by the name resolution rule above, +you can access the element. +

    +You can access a namespace variable +from a procedure in the same namespace +by using the variable command. +Much like the global command, +this creates a local link to the namespace variable. +If necessary, it also creates the variable in the current namespace +and initializes it. +Note that the global command only creates links +to variables in the global namespace. +It is not necessary to use a variable command +if you always refer to the namespace variable using an +appropriate qualified name. + +

    IMPORTING COMMANDS

    +Namespaces are often used to represent libraries. +Some library commands are used so frequently +that it is a nuisance to type their qualified names. +For example, suppose that all of the commands in a package +like BLT are contained in a namespace called Blt. +Then you might access these commands like this: +
    Blt::graph .g -background red
    +Blt::table . .g 0,0
    +If you use the graph and table commands frequently, +you may want to access them without the Blt:: prefix. +You can do this by importing the commands into the current namespace, +like this: +
    namespace import Blt::*
    +This adds all exported commands from the Blt namespace +into the current namespace context, so you can write code like this: +
    graph .g -background red
    +table . .g 0,0
    +The namespace import command only imports commands +from a namespace that that namespace exported +with a namespace export command. +

    +Importing every command from a namespace is generally +a bad idea since you don't know what you will get. +It is better to import just the specific commands you need. +For example, the command +

    namespace import Blt::graph Blt::table
    +imports only the graph and table commands into the +current context. +

    +If you try to import a command that already exists, you will get an +error. This prevents you from importing the same command from two +different packages. But from time to time (perhaps when debugging), +you may want to get around this restriction. You may want to +reissue the namespace import command to pick up new commands +that have appeared in a namespace. In that case, you can use the +-force option, and existing commands will be silently overwritten: +

    namespace import -force Blt::graph Blt::table
    +If for some reason, you want to stop using the imported commands, +you can remove them with an namespace forget command, like this: +
    namespace forget Blt::*
    +This searches the current namespace for any commands imported from Blt. +If it finds any, it removes them. Otherwise, it does nothing. +After this, the Blt commands must be accessed with the Blt:: +prefix. +

    +When you delete a command from the exporting namespace like this: +

    rename Blt::graph ""
    +the command is automatically removed from all namespaces that import it. + +

    EXPORTING COMMANDS

    +You can export commands from a namespace like this: +
    namespace eval Counter {
    +    namespace export bump reset
    +    variable Num 0
    +    variable Max 100
    +
    +    proc bump {{by 1}} {
    +        variable Num
    +        incr Num $by
    +        Check
    +        return $Num
    +    }
    +    proc reset {} {
    +        variable Num
    +        set Num 0
    +    }
    +    proc Check {} {
    +        variable Num
    +        variable Max
    +        if {$Num > $Max} {
    +            error "too high!"
    +        }
    +    }
    +}
    +The procedures bump and reset are exported, +so they are included when you import from the Counter namespace, +like this: +
    namespace import Counter::*
    +However, the Check procedure is not exported, +so it is ignored by the import operation. +

    +The namespace import command only imports commands +that were declared as exported by their namespace. +The namespace export command specifies what commands +may be imported by other namespaces. +If a namespace import command specifies a command +that is not exported, the command is not imported. + +

    SEE ALSO

    +variable +

    KEYWORDS

    +exported, internal, variable +
    +Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
    +Copyright © 1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/open.htm b/hlp/en/tcl/open.htm new file mode 100644 index 0000000..a5ef82b --- /dev/null +++ b/hlp/en/tcl/open.htm @@ -0,0 +1,275 @@ +Tcl Built-In Commands - open manual page +
    +
    NAME +
    open - Open a file-based or command pipeline channel
    +
    SYNOPSIS +
    +
    open fileName +
    open fileName access +
    open fileName access permissions +
    +
    DESCRIPTION +
    +
    r +
    r+ +
    w +
    w+ +
    a +
    a+ +
    +
    +
    RDONLY +
    WRONLY +
    RDWR +
    APPEND +
    CREAT +
    EXCL +
    NOCTTY +
    NONBLOCK +
    TRUNC +
    +
    COMMAND PIPELINES +
    SERIAL COMMUNICATIONS +
    CONFIGURATION OPTIONS +
    +
    -mode baud,parity,data,stop +
    -pollinterval msec +
    -lasterror +
    +
    PORTABILITY ISSUES +
    +
    Windows (all versions) +
    Windows NT +
    Windows 95 +
    Macintosh +
    Unix +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +open - Open a file-based or command pipeline channel +

    SYNOPSIS

    +open fileName
    +open fileName access
    +open fileName access permissions
    +

    DESCRIPTION

    +This command opens a file, serial port, or command pipeline and returns a +channel identifier that may be used in future invocations of commands like +read, puts, and close. +If the first character of fileName is not | then +the command opens a file: +fileName gives the name of the file to open, and it must conform to the +conventions described in the filename manual entry. +

    +The access argument, if present, indicates the way in which the file +(or command pipeline) is to be accessed. +In the first form access may have any of the following values: +

    +

    +

    r
    +Open the file for reading only; the file must already exist. This is the +default value if access is not specified. +

    r+
    +Open the file for both reading and writing; the file must +already exist. +

    w
    +Open the file for writing only. Truncate it if it exists. If it doesn't +exist, create a new file. +

    w+
    +Open the file for reading and writing. Truncate it if it exists. +If it doesn't exist, create a new file. +

    a
    +Open the file for writing only. If the file doesn't exist, +create a new empty file. +Set the initial access position to the end of the file. +

    a+
    +Open the file for reading and writing. If the file doesn't exist, +create a new empty file. +Set the initial access position to the end of the file. +

    +

    +In the second form, access consists of a list of any of the +following flags, all of which have the standard POSIX meanings. +One of the flags must be either RDONLY, WRONLY or RDWR. +

    +

    +

    RDONLY
    +Open the file for reading only. +

    WRONLY
    +Open the file for writing only. +

    RDWR
    +Open the file for both reading and writing. +

    APPEND
    +Set the file pointer to the end of the file prior to each write. +

    CREAT
    +Create the file if it doesn't already exist (without this flag it +is an error for the file not to exist). +

    EXCL
    +If CREAT is also specified, an error is returned if the +file already exists. +

    NOCTTY
    +If the file is a terminal device, this flag prevents the file from +becoming the controlling terminal of the process. +

    NONBLOCK
    +Prevents the process from blocking while opening the file, and +possibly in subsequent I/O operations. The exact behavior of +this flag is system- and device-dependent; its use is discouraged +(it is better to use the fconfigure command to put a file +in nonblocking mode). +For details refer to your system documentation on the open system +call's O_NONBLOCK flag. +

    TRUNC
    +If the file exists it is truncated to zero length. +

    +

    +If a new file is created as part of opening it, permissions +(an integer) is used to set the permissions for the new file in +conjunction with the process's file mode creation mask. +Permissions defaults to 0666. +

    +Note that if you are going to be reading or writing binary data from +the channel created by this command, you should use the +fconfigure command to change the -translation option of +the channel to binary before transferring any binary data. This +is in contrast to the ``b'' character passed as part of the equivalent +of the access parameter to some versions of the C library +fopen() function. +

    COMMAND PIPELINES

    +If the first character of fileName is ``|'' then the +remaining characters of fileName are treated as a list of arguments +that describe a command pipeline to invoke, in the same style as the +arguments for exec. +In this case, the channel identifier returned by open may be used +to write to the command's input pipe or read from its output pipe, +depending on the value of access. +If write-only access is used (e.g. access is w), then +standard output for the pipeline is directed to the current standard +output unless overridden by the command. +If read-only access is used (e.g. access is r), +standard input for the pipeline is taken from the current standard +input unless overridden by the command. +

    SERIAL COMMUNICATIONS

    +If fileName refers to a serial port, then the specified serial port +is opened and initialized in a platform-dependent manner. Acceptable +values for the fileName to use to open a serial port are described in +the PORTABILITY ISSUES section. + +

    CONFIGURATION OPTIONS

    +The fconfigure command can be used to query and set the following +configuration option for open serial ports: +

    +

    +

    -mode baud,parity,data,stop
    +This option is a set of 4 comma-separated values: the baud rate, parity, +number of data bits, and number of stop bits for this serial port. The +baud rate is a simple integer that specifies the connection speed. +Parity is one of the following letters: n, o, e, +m, s; respectively signifying the parity options of ``none'', +``odd'', ``even'', ``mark'', or ``space''. Data is the number of +data bits and should be an integer from 5 to 8, while stop is the +number of stop bits and should be the integer 1 or 2. +

    -pollinterval msec
    +This option, available only on Windows for serial ports, is used to +set the maximum time between polling for fileevents. This affects the +time interval between checking for events throughout the Tcl +interpreter (the smallest value always wins). Use this option only if +you want to poll the serial port more often than 10 msec (the default). +

    -lasterror
    +This option is available only on Windows for serial ports, and is +query only (will only be reported when directly requested). +In case of a serial communication error, read or puts +returns a general Tcl file I/O error. +fconfigure -lasterror can be called to get a list +of error details (e.g. FRAME RXOVER). + +

    +

    PORTABILITY ISSUES

    +

    +

    +

    +

    Windows (all versions)
    +Valid values for fileName to open a serial port are of the form +comX:, where X is a number, generally from 1 to 4. +This notation only works for serial ports from 1 to 9, if the system +happens to have more than four. An attempt to open a serial port that +does not exist or has a number greater than 9 will fail. An alternate +form of opening serial ports is to use the filename \\.\comX, +where X is any number that corresponds to a serial port; please note +that this method is considerably slower on Windows 95 and Windows 98. +

    Windows NT
    +When running Tcl interactively, there may be some strange interactions +between the real console, if one is present, and a command pipeline that uses +standard input or output. If a command pipeline is opened for reading, some +of the lines entered at the console will be sent to the command pipeline and +some will be sent to the Tcl evaluator. If a command pipeline is opened for +writing, keystrokes entered into the console are not visible until the the +pipe is closed. This behavior occurs whether the command pipeline is +executing 16-bit or 32-bit applications. These problems only occur because +both Tcl and the child application are competing for the console at +the same time. If the command pipeline is started from a script, so that Tcl +is not accessing the console, or if the command pipeline does not use +standard input or output, but is redirected from or to a file, then the +above problems do not occur. +

    Windows 95
    +A command pipeline that executes a 16-bit DOS application cannot be opened +for both reading and writing, since 16-bit DOS applications that receive +standard input from a pipe and send standard output to a pipe run +synchronously. Command pipelines that do not execute 16-bit DOS +applications run asynchronously and can be opened for both reading and +writing. +

    +When running Tcl interactively, there may be some strange interactions +between the real console, if one is present, and a command pipeline that uses +standard input or output. If a command pipeline is opened for reading from +a 32-bit application, some of the keystrokes entered at the console will be +sent to the command pipeline and some will be sent to the Tcl evaluator. If +a command pipeline is opened for writing to a 32-bit application, no output +is visible on the console until the the pipe is closed. These problems only +occur because both Tcl and the child application are competing for the +console at the same time. If the command pipeline is started from a script, +so that Tcl is not accessing the console, or if the command pipeline does +not use standard input or output, but is redirected from or to a file, then +the above problems do not occur. +

    +Whether or not Tcl is running interactively, if a command pipeline is opened +for reading from a 16-bit DOS application, the call to open will not +return until end-of-file has been received from the command pipeline's +standard output. If a command pipeline is opened for writing to a 16-bit DOS +application, no data will be sent to the command pipeline's standard output +until the pipe is actually closed. This problem occurs because 16-bit DOS +applications are run synchronously, as described above. +

    Macintosh
    +Opening a serial port is not currently implemented under Macintosh. +

    +Opening a command pipeline is not supported under Macintosh, since +applications do not support the concept of standard input or output. +

    Unix
    +Valid values for fileName to open a serial port are generally of the +form /dev/ttyX, where X is a or b, but the name +of any pseudo-file that maps to a serial port may be used. +

    +When running Tcl interactively, there may be some strange interactions +between the console, if one is present, and a command pipeline that uses +standard input. If a command pipeline is opened for reading, some +of the lines entered at the console will be sent to the command pipeline and +some will be sent to the Tcl evaluator. This problem only occurs because +both Tcl and the child application are competing for the console at the +same time. If the command pipeline is started from a script, so that Tcl is +not accessing the console, or if the command pipeline does not use standard +input, but is redirected from a file, then the above problem does not occur. +

    +

    +See the PORTABILITY ISSUES section of the exec command for additional +information not specific to command pipelines about executing +applications on the various platforms + +

    SEE ALSO

    +file, close, filename, fconfigure, gets, read, puts, exec, fopen +

    KEYWORDS

    +access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/package.htm b/hlp/en/tcl/package.htm new file mode 100644 index 0000000..4d0ce65 --- /dev/null +++ b/hlp/en/tcl/package.htm @@ -0,0 +1,208 @@ +Tcl Built-In Commands - package manual page +
    +
    NAME +
    package - Facilities for package loading and version control
    +
    SYNOPSIS +
    +
    package forget ?package package ...? +
    package ifneeded package version ?script? +
    package names +
    package present ?-exact? package ?version? +
    package provide package ?version? +
    package require ?-exact? package ?version? +
    package unknown ?command? +
    package vcompare version1 version2 +
    package versions package +
    package vsatisfies version1 version2 +
    +
    DESCRIPTION +
    +
    package forget ?package package ...? +
    package ifneeded package version ?script? +
    package names +
    package present ?-exact? package ?version? +
    package provide package ?version? +
    package require ?-exact? package ?version? +
    package unknown ?command? +
    package vcompare version1 version2 +
    package versions package +
    package vsatisfies version1 version2 +
    +
    VERSION NUMBERS +
    PACKAGE INDICES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +package - Facilities for package loading and version control +

    SYNOPSIS

    +package forget ?package package ...?
    +package ifneeded package version ?script?
    +package names
    +package present ?-exact? package ?version?
    +package provide package ?version?
    +package require ?-exact? package ?version?
    +package unknown ?command?
    +package vcompare version1 version2
    +package versions package
    +package vsatisfies version1 version2
    +

    DESCRIPTION

    +This command keeps a simple database of the packages available for +use by the current interpreter and how to load them into the +interpreter. +It supports multiple versions of each package and arranges +for the correct version of a package to be loaded based on what +is needed by the application. +This command also detects and reports version clashes. +Typically, only the package require and package provide +commands are invoked in normal Tcl scripts; the other commands are used +primarily by system scripts that maintain the package database. +

    +The behavior of the package command is determined by its first argument. +The following forms are permitted: +

    +

    +

    package forget ?package package ...?
    +Removes all information about each specified package from this interpreter, +including information provided by both package ifneeded and +package provide. +

    package ifneeded package version ?script?
    +This command typically appears only in system configuration +scripts to set up the package database. +It indicates that a particular version of +a particular package is available if needed, and that the package +can be added to the interpreter by executing script. +The script is saved in a database for use by subsequent +package require commands; typically, script +sets up auto-loading for the commands in the package (or calls +load and/or source directly), then invokes +package provide to indicate that the package is present. +There may be information in the database for several different +versions of a single package. +If the database already contains information for package +and version, the new script replaces the existing +one. +If the script argument is omitted, the current script for +version version of package package is returned, +or an empty string if no package ifneeded command has +been invoked for this package and version. +

    package names
    +Returns a list of the names of all packages in the +interpreter for which a version has been provided (via +package provide) or for which a package ifneeded +script is available. +The order of elements in the list is arbitrary. +

    package present ?-exact? package ?version?
    +This command is equivalent to package require except that it +does not try and load the package if it is not already loaded. +

    package provide package ?version?
    +This command is invoked to indicate that version version +of package package is now present in the interpreter. +It is typically invoked once as part of an ifneeded script, +and again by the package itself when it is finally loaded. +An error occurs if a different version of package has been +provided by a previous package provide command. +If the version argument is omitted, then the command +returns the version number that is currently provided, or an +empty string if no package provide command has been +invoked for package in this interpreter. +

    package require ?-exact? package ?version?
    +This command is typically invoked by Tcl code that wishes to use +a particular version of a particular package. The arguments +indicate which package is wanted, and the command ensures that +a suitable version of the package is loaded into the interpreter. +If the command succeeds, it returns the version number that is +loaded; otherwise it generates an error. +If both the -exact +switch and the version argument are specified then only the +given version is acceptable. If -exact is omitted but +version is specified, then versions later than version +are also acceptable as long as they have the same major version +number as version. +If both -exact and version are omitted then any +version whatsoever is acceptable. +If a version of package has already been provided (by invoking +the package provide command), then its version number must +satisfy the criteria given by -exact and version and +the command returns immediately. +Otherwise, the command searches the database of information provided by +previous package ifneeded commands to see if an acceptable +version of the package is available. +If so, the script for the highest acceptable version number is invoked; +it must do whatever is necessary to load the package, +including calling package provide for the package. +If the package ifneeded database does not contain an acceptable +version of the package and a package unknown command has been +specified for the interpreter then that command is invoked; when +it completes, Tcl checks again to see if the package is now provided +or if there is a package ifneeded script for it. +If all of these steps fail to provide an acceptable version of the +package, then the command returns an error. +

    package unknown ?command?
    +This command supplies a ``last resort'' command to invoke during +package require if no suitable version of a package can be found +in the package ifneeded database. +If the command argument is supplied, it contains the first part +of a command; when the command is invoked during a package require +command, Tcl appends two additional arguments giving the desired package +name and version. +For example, if command is foo bar and later the command +package require test 2.4 is invoked, then Tcl will execute +the command foo bar test 2.4 to load the package. +If no version number is supplied to the package require command, +then the version argument for the invoked command will be an empty string. +If the package unknown command is invoked without a command +argument, then the current package unknown script is returned, +or an empty string if there is none. +If command is specified as an empty string, then the current +package unknown script is removed, if there is one. +

    package vcompare version1 version2
    +Compares the two version numbers given by version1 and version2. +Returns -1 if version1 is an earlier version than version2, +0 if they are equal, and 1 if version1 is later than version2. +

    package versions package
    +Returns a list of all the version numbers of package +for which information has been provided by package ifneeded +commands. +

    package vsatisfies version1 version2
    +Returns 1 if scripts written for version2 will work unchanged +with version1 (i.e. version1 is equal to or greater +than version2 and they both have the same major version +number), 0 otherwise. + +

    +

    VERSION NUMBERS

    +Version numbers consist of one or more decimal numbers separated +by dots, such as 2 or 1.162 or 3.1.13.1. +The first number is called the major version number. +Larger numbers correspond to later versions of a package, with +leftmost numbers having greater significance. +For example, version 2.1 is later than 1.3 and version +3.4.6 is later than 3.3.5. +Missing fields are equivalent to zeroes: version 1.3 is the +same as version 1.3.0 and 1.3.0.0, so it is earlier than 1.3.1 or 1.3.0.2. +A later version number is assumed to be upwards compatible with +an earlier version number as long as both versions have the same +major version number. +For example, Tcl scripts written for version 2.3 of a package should +work unchanged under versions 2.3.2, 2.4, and 2.5.1. +Changes in the major version number signify incompatible changes: +if code is written to use version 2.1 of a package, it is not guaranteed +to work unmodified with either version 1.7.3 or version 3.1. + +

    PACKAGE INDICES

    +The recommended way to use packages in Tcl is to invoke package require +and package provide commands in scripts, and use the procedure +pkg_mkIndex to create package index files. +Once you've done this, packages will be loaded automatically +in response to package require commands. +See the documentation for pkg_mkIndex for details. + +

    SEE ALSO

    +msgcat, packagens, pkgMkIndex +

    KEYWORDS

    +package, version +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/packagens.htm b/hlp/en/tcl/packagens.htm new file mode 100644 index 0000000..d080e82 --- /dev/null +++ b/hlp/en/tcl/packagens.htm @@ -0,0 +1,64 @@ +Tcl Built-In Commands - pkg::create manual page +
    +
    NAME +
    pkg::create - Construct an appropriate package ifneeded +command for a given package specification
    +
    SYNOPSIS +
    +
    ::pkg::create -name packageName -version packageVersion ?-load filespec? ... ?-source filespec? ... +
    +
    DESCRIPTION +
    OPTIONS +
    +
    -name packageName +
    -version packageVersion +
    -load filespec +
    -source filespec +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +pkg::create - Construct an appropriate package ifneeded +command for a given package specification +

    SYNOPSIS

    +::pkg::create -name packageName-version packageVersion ?-load filespec? ... ?-source filespec? ...
    +

    DESCRIPTION

    +::pkg::create is a utility procedure that is part of the standard Tcl +library. It is used to create an appropriate package ifneeded +command for a given package specification. It can be used to construct a +pkgIndex.tcl file for use with the package mechanism. + +

    OPTIONS

    +The parameters supported are: +

    +

    +

    -name packageName
    +This parameter specifies the name of the package. It is required. +

    -version packageVersion
    +This parameter specifies the version of the package. It is required. +

    -load filespec
    +This parameter specifies a binary library that must be loaded with the +load command. filespec is a list with two elements. The +first element is the name of the file to load. The second, optional +element is a list of commands supplied by loading that file. If the +list of procedures is empty or omitted, ::pkg::create will +set up the library for direct loading (see pkg_mkIndex). Any +number of -load parameters may be specified. +

    -source filespec
    +This parameter is similar to the -load parameter, except that it +specifies a Tcl library that must be loaded with the +source command. Any number of -source parameters may be +specified. +

    +

    +At least one -load or -source paramter must be given. + +

    SEE ALSO

    +package +

    KEYWORDS

    +auto-load, index, package, version +
    +Copyright © 1998-2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/pid.htm b/hlp/en/tcl/pid.htm new file mode 100644 index 0000000..3144d2c --- /dev/null +++ b/hlp/en/tcl/pid.htm @@ -0,0 +1,26 @@ +Tcl Built-In Commands - pid manual page +

    NAME

    +pid - Retrieve process id(s) +

    SYNOPSIS

    +pid ?fileId?
    +

    DESCRIPTION

    +If the fileId argument is given then it should normally +refer to a process pipeline created with the open command. +In this case the pid command will return a list whose elements +are the process identifiers of all the processes in the pipeline, +in order. +The list will be empty if fileId refers to an open file +that isn't a process pipeline. +If no fileId argument is given then pid returns the process +identifier of the current process. +All process identifiers are returned as decimal strings. + +

    SEE ALSO

    +exec, open +

    KEYWORDS

    +file, pipeline, process identifier +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/pkgMkIndex.htm b/hlp/en/tcl/pkgMkIndex.htm new file mode 100644 index 0000000..e99b1e4 --- /dev/null +++ b/hlp/en/tcl/pkgMkIndex.htm @@ -0,0 +1,245 @@ +Tcl Built-In Commands - pkg_mkIndex manual page +
    +
    NAME +
    pkg_mkIndex - Build an index for automatic loading of packages
    +
    SYNOPSIS +
    +
    pkg_mkIndex ?-direct? ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...? +
    +
    DESCRIPTION +
    +
    +
    OPTIONS +
    +
    -direct +
    -lazy +
    -load pkgPat +
    -verbose +
    -- +
    +
    PACKAGES AND THE AUTO-LOADER +
    HOW IT WORKS +
    DIRECT LOADING +
    COMPLEX CASES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +pkg_mkIndex - Build an index for automatic loading of packages +

    SYNOPSIS

    +pkg_mkIndex ?-direct? ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...?
    +

    DESCRIPTION

    +Pkg_mkIndex is a utility procedure that is part of the standard +Tcl library. +It is used to create index files that allow packages to be loaded +automatically when package require commands are executed. +To use pkg_mkIndex, follow these steps: +

    +

    +

    [1]
    +Create the package(s). +Each package may consist of one or more Tcl script files or binary files. +Binary files must be suitable for loading with the load command +with a single argument; for example, if the file is test.so it must +be possible to load this file with the command load test.so. +Each script file must contain a package provide command to declare +the package and version number, and each binary file must contain +a call to Tcl_PkgProvide. +

    [2]
    +Create the index by invoking pkg_mkIndex. +The dir argument gives the name of a directory and each +pattern argument is a glob-style pattern that selects +script or binary files in dir. +The default pattern is *.tcl and *.[info sharedlibextension]. +
    +Pkg_mkIndex will create a file pkgIndex.tcl in dir +with package information about all the files given by the pattern +arguments. +It does this by loading each file into a slave +interpreter and seeing what packages +and new commands appear (this is why it is essential to have +package provide commands or Tcl_PkgProvide calls +in the files, as described above). +If you have a package split among scripts and binary files, +or if you have dependencies among files, +you may have to use the -load option +or adjust the order in which pkg_mkIndex processes +the files. See COMPLEX CASES below. + +

    [3]
    +Install the package as a subdirectory of one of the directories given by +the tcl_pkgPath variable. If $tcl_pkgPath contains more +than one directory, machine-dependent packages (e.g., those that +contain binary shared libraries) should normally be installed +under the first directory and machine-independent packages (e.g., +those that contain only Tcl scripts) should be installed under the +second directory. +The subdirectory should include +the package's script and/or binary files as well as the pkgIndex.tcl +file. As long as the package is installed as a subdirectory of a +directory in $tcl_pkgPath it will automatically be found during +package require commands. +
    +If you install the package anywhere else, then you must ensure that +the directory containing the package is in the auto_path global variable +or an immediate subdirectory of one of the directories in auto_path. +Auto_path contains a list of directories that are searched +by both the auto-loader and the package loader; by default it +includes $tcl_pkgPath. +The package loader also checks all of the subdirectories of the +directories in auto_path. +You can add a directory to auto_path explicitly in your +application, or you can add the directory to your TCLLIBPATH +environment variable: if this environment variable is present, +Tcl initializes auto_path from it during application startup. +

    [4]
    +Once the above steps have been taken, all you need to do to use a +package is to invoke package require. +For example, if versions 2.1, 2.3, and 3.1 of package Test +have been indexed by pkg_mkIndex, the command +package require Test will make version 3.1 available +and the command package require -exact Test 2.1 will +make version 2.1 available. +There may be many versions of a package in the various index files +in auto_path, but only one will actually be loaded in a given +interpreter, based on the first call to package require. +Different versions of a package may be loaded in different +interpreters. + +

    +

    OPTIONS

    +The optional switches are: +

    +

    +

    -direct
    +The generated index will implement direct loading of the package +upon package require. This is the default. +

    -lazy
    +The generated index will manage to delay loading the package until the +use of one of the commands provided by the package, instead of loading +it immediately upon package require. +

    -load pkgPat
    +The index process will pre-load any packages that exist in the +current interpreter and match pkgPat into the slave interpreter used to +generate the index. The pattern match uses string match rules. +See COMPLEX CASES below. +

    -verbose
    +Generate output during the indexing process. Output is via +the tclLog procedure, which by default prints to stderr. +

    --
    +End of the flags, in case dir begins with a dash. + +

    +

    PACKAGES AND THE AUTO-LOADER

    +The package management facilities overlap somewhat with the auto-loader, +in that both arrange for files to be loaded on-demand. +However, package management is a higher-level mechanism that uses +the auto-loader for the last step in the loading process. +It is generally better to index a package with pkg_mkIndex +rather than auto_mkindex because the package mechanism provides +version control: several versions of a package can be made available +in the index files, with different applications using different +versions based on package require commands. +In contrast, auto_mkindex does not understand versions so +it can only handle a single version of each package. +It is probably not a good idea to index a given package with both +pkg_mkIndex and auto_mkindex. +If you use pkg_mkIndex to index a package, its commands cannot +be invoked until package require has been used to select a +version; in contrast, packages indexed with auto_mkindex +can be used immediately since there is no version control. + +

    HOW IT WORKS

    +Pkg_mkIndex depends on the package unknown command, +the package ifneeded command, and the auto-loader. +The first time a package require command is invoked, +the package unknown script is invoked. +This is set by Tcl initialization to a script that +evaluates all of the pkgIndex.tcl files in the +auto_path. +The pkgIndex.tcl files contain package ifneeded +commands for each version of each available package; these commands +invoke package provide commands to announce the +availability of the package, and they setup auto-loader +information to load the files of the package. +If the -lazy flag was provided when the pkgIndex.tcl +was generated, +a given file of a given version of a given package isn't +actually loaded until the first time one of its commands +is invoked. +Thus, after invoking package require you may +not see the package's commands in the interpreter, but you will be able +to invoke the commands and they will be auto-loaded. + +

    DIRECT LOADING

    +Some packages, for instance packages which use namespaces and export +commands or those which require special initialization, might select +that their package files be loaded immediately upon package require +instead of delaying the actual loading to the first use of one of the +package's command. This is the default mode when generating the package +index. It can be overridden by specifying the -lazy argument. + +

    COMPLEX CASES

    +Most complex cases of dependencies among scripts +and binary files, and packages being split among scripts and +binary files are handled OK. However, you may have to adjust +the order in which files are processed by pkg_mkIndex. +These issues are described in detail below. +

    +If each script or file contains one package, and packages +are only contained in one file, then things are easy. +You simply specify all files to be indexed in any order +with some glob patterns. +

    +In general, it is OK for scripts to have dependencies on other +packages. +If scripts contain package require commands, these are +stubbed out in the interpreter used to process the scripts, +so these do not cause problems. +If scripts call into other packages in global code, +these calls are handled by a stub unknown command. +However, if scripts make variable references to other package's +variables in global code, these will cause errors. That is +also bad coding style. +

    +If binary files have dependencies on other packages, things +can become tricky because it is not possible to stub out +C-level API's such as Tcl_PkgRequire API +when loading a binary file. +For example, suppose the BLT package requires Tk, and expresses +this with a call to Tcl_PkgRequire in its Blt_Init routine. +To support this, you must run pkg_mkIndex in an interpreter that +has Tk loaded. You can achieve this with the +-load pkgPat option. If you specify this option, +pkg_mkIndex will load any packages listed by +info loaded and that match pkgPat +into the interpreter used to process files. +In most cases this will satisfy the Tcl_PkgRequire calls +made by binary files. +

    +If you are indexing two binary files and one depends on the other, +you should specify the one that has dependencies last. +This way the one without dependencies will get loaded and indexed, +and then the package it provides +will be available when the second file is processed. +You may also need to load the first package into the +temporary interpreter used to create the index by using +the -load flag; +it won't hurt to specify package patterns that are not yet loaded. +

    +If you have a package that is split across scripts and a binary file, +then you should avoid the -load flag. The problem is that +if you load a package before computing the index it masks any +other files that provide part of the same package. +If you must use -load, +then you must specify the scripts first; otherwise the package loaded from +the binary file may mask the package defined by the scripts. + +

    SEE ALSO

    +package +

    KEYWORDS

    +auto-load, index, package, version +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/proc.htm b/hlp/en/tcl/proc.htm new file mode 100644 index 0000000..a379c3e --- /dev/null +++ b/hlp/en/tcl/proc.htm @@ -0,0 +1,66 @@ +Built-In Commands - proc manual page +

    NAME

    +proc - Create a Tcl procedure +

    SYNOPSIS

    +proc name args body
    +

    DESCRIPTION

    +The proc command creates a new Tcl procedure named +name, replacing +any existing command or procedure there may have been by that name. +Whenever the new command is invoked, the contents of body will +be executed by the Tcl interpreter. +Normally, name is unqualified +(does not include the names of any containing namespaces), +and the new procedure is created in the current namespace. +If name includes any namespace qualifiers, +the procedure is created in the specified namespace. +Args specifies the formal arguments to the +procedure. It consists of a list, possibly empty, each of whose +elements specifies +one argument. Each argument specifier is also a list with either +one or two fields. If there is only a single field in the specifier +then it is the name of the argument; if there are two fields, then +the first is the argument name and the second is its default value. +

    +When name is invoked a local variable +will be created for each of the formal arguments to the procedure; its +value will be the value of corresponding argument in the invoking command +or the argument's default value. +Arguments with default values need not be +specified in a procedure invocation. However, there must be enough +actual arguments for all the +formal arguments that don't have defaults, and there must not be any extra +actual arguments. There is one special case to permit procedures with +variable numbers of arguments. If the last formal argument has the name +args, then a call to the procedure may contain more actual arguments +than the procedure has formals. In this case, all of the actual arguments +starting at the one that would be assigned to args are combined into +a list (as if the list command had been used); this combined value +is assigned to the local variable args. +

    +When body is being executed, variable names normally refer to +local variables, which are created automatically when referenced and +deleted when the procedure returns. One local variable is automatically +created for each of the procedure's arguments. +Global variables can only be accessed by invoking +the global command or the upvar command. +Namespace variables can only be accessed by invoking +the variable command or the upvar command. +

    +The proc command returns an empty string. When a procedure is +invoked, the procedure's return value is the value specified in a +return command. If the procedure doesn't execute an explicit +return, then its return value is the value of the last command +executed in the procedure's body. +If an error occurs while executing the procedure +body, then the procedure-as-a-whole will return that same error. + +

    SEE ALSO

    +info, unknown +

    KEYWORDS

    +argument, procedure +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/puts.htm b/hlp/en/tcl/puts.htm new file mode 100644 index 0000000..1f5c466 --- /dev/null +++ b/hlp/en/tcl/puts.htm @@ -0,0 +1,58 @@ +Tcl Built-In Commands - puts manual page +

    NAME

    +puts - Write to a channel +

    SYNOPSIS

    +puts ?-nonewline? ?channelId? string
    +

    DESCRIPTION

    +Writes the characters given by string to the channel given +by channelId. +ChannelId must be a channel identifier such as returned from a +previous invocation of open or socket. It must have been opened +for output. If no channelId is specified then it defaults to +stdout. Puts normally outputs a newline character after +string, but this feature may be suppressed by specifying the +-nonewline switch. +

    +Newline characters in the output are translated by puts to +platform-specific end-of-line sequences according to the current +value of the -translation option for the channel (for example, +on PCs newlines are normally replaced with carriage-return-linefeed +sequences; on Macintoshes newlines are normally replaced with +carriage-returns). +See the fconfigure manual entry for a discussion on ways in +which fconfigure will alter output. +

    +Tcl buffers output internally, so characters written with puts +may not appear immediately on the output file or device; Tcl will +normally delay output until the buffer is full or the channel is +closed. +You can force output to appear immediately with the flush +command. +

    +When the output buffer fills up, the puts command will normally +block until all the buffered data has been accepted for output by the +operating system. +If channelId is in nonblocking mode then the puts command +will not block even if the operating system cannot accept the data. +Instead, Tcl continues to buffer the data and writes it in the +background as fast as the underlying file or device can accept it. +The application must use the Tcl event loop for nonblocking output +to work; otherwise Tcl never finds out that the file or device is +ready for more output data. +It is possible for an arbitrarily large amount of data to be +buffered for a channel in nonblocking mode, which could consume a +large amount of memory. +To avoid wasting memory, nonblocking I/O should normally +be used in an event-driven fashion with the fileevent command +(don't invoke puts unless you have recently been notified +via a file event that the channel is ready for more output data). + +

    SEE ALSO

    +file, fileevent +

    KEYWORDS

    +channel, newline, output, write +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/pwd.htm b/hlp/en/tcl/pwd.htm new file mode 100644 index 0000000..98713a8 --- /dev/null +++ b/hlp/en/tcl/pwd.htm @@ -0,0 +1,17 @@ +Built-In Commands - pwd manual page +

    NAME

    +pwd - Return the current working directory +

    SYNOPSIS

    +pwd
    +

    DESCRIPTION

    +Returns the path name of the current working directory. + +

    SEE ALSO

    +file, cd, glob, filename +

    KEYWORDS

    +working directory +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/re_syntax.htm b/hlp/en/tcl/re_syntax.htm new file mode 100644 index 0000000..1714c8b --- /dev/null +++ b/hlp/en/tcl/re_syntax.htm @@ -0,0 +1,941 @@ +Tcl Built-In Commands - re_syntax manual page +
    +
    NAME +
    re_syntax - Syntax of Tcl regular expressions.
    +
    DESCRIPTION +
    DIFFERENT FLAVORS OF REs +
    REGULAR EXPRESSION SYNTAX +
    +
    * +
    + +
    ? +
    {m} +
    {m,} +
    {m,n} +
    *? +? ?? {m}? {m,}? {m,n}? +
    +
    +
    (re) +
    (?:re) +
    () +
    (?:) +
    [chars] +
    . +
    \k +
    \c +
    { +
    x +
    +
    +
    ^ +
    $ +
    (?=re) +
    (?!re) +
    +
    BRACKET EXPRESSIONS +
    ESCAPES +
    +
    \a +
    \b +
    \B +
    \cX +
    \e +
    \f +
    \n +
    \r +
    \t +
    \uwxyz +
    \Ustuvwxyz +
    \v +
    \xhhh +
    \0 +
    \xy +
    \xyz +
    +
    +
    \d +
    \s +
    \w +
    \D +
    \S +
    \W +
    +
    +
    \A +
    \m +
    \M +
    \y +
    \Y +
    \Z +
    \m +
    \mnn +
    +
    METASYNTAX +
    +
    b +
    c +
    e +
    i +
    m +
    n +
    p +
    q +
    s +
    t +
    w +
    x +
    +
    MATCHING +
    LIMITS AND COMPATIBILITY +
    BASIC REGULAR EXPRESSIONS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +re_syntax - Syntax of Tcl regular expressions. +

    DESCRIPTION

    +A regular expression describes strings of characters. +It's a pattern that matches certain strings and doesn't match others. + +

    DIFFERENT FLAVORS OF REs

    +Regular expressions (``RE''s), as defined by POSIX, come in two +flavors: extended REs (``EREs'') and basic REs (``BREs''). +EREs are roughly those of the traditional egrep, while BREs are +roughly those of the traditional ed. This implementation adds +a third flavor, advanced REs (``AREs''), basically EREs with +some significant extensions. +

    +This manual page primarily describes AREs. BREs mostly exist for +backward compatibility in some old programs; they will be discussed at +the end. POSIX EREs are almost an exact subset of AREs. Features of +AREs that are not present in EREs will be indicated. + +

    REGULAR EXPRESSION SYNTAX

    +Tcl regular expressions are implemented using the package written by +Henry Spencer, based on the 1003.2 spec and some (not quite all) of +the Perl5 extensions (thanks, Henry!). Much of the description of +regular expressions below is copied verbatim from his manual entry. +

    +An ARE is one or more branches, +separated by `|', +matching anything that matches any of the branches. +

    +A branch is zero or more constraints or quantified atoms, +concatenated. +It matches a match for the first, followed by a match for the second, etc; +an empty branch matches the empty string. +

    +A quantified atom is an atom possibly followed +by a single quantifier. +Without a quantifier, it matches a match for the atom. +The quantifiers, +and what a so-quantified atom matches, are: +

    +

    +

    *
    +a sequence of 0 or more matches of the atom +

    +
    +a sequence of 1 or more matches of the atom +

    ?
    +a sequence of 0 or 1 matches of the atom +

    {m}
    +a sequence of exactly m matches of the atom +

    {m,}
    +a sequence of m or more matches of the atom +

    {m,n}
    +a sequence of m through n (inclusive) matches of the atom; +m may not exceed n +

    *? +? ?? {m}? {m,}? {m,n}?
    +non-greedy quantifiers, +which match the same possibilities, +but prefer the smallest number rather than the largest number +of matches (see MATCHING) +

    +

    +The forms using +{ and } +are known as bounds. +The numbers +m and n are unsigned decimal integers +with permissible values from 0 to 255 inclusive. +

    +An atom is one of: +

    +

    +

    (re)
    +(where re is any regular expression) +matches a match for +re, with the match noted for possible reporting +

    (?:re)
    +as previous, +but does no reporting +(a ``non-capturing'' set of parentheses) +

    ()
    +matches an empty string, +noted for possible reporting +

    (?:)
    +matches an empty string, +without reporting +

    [chars]
    +a bracket expression, +matching any one of the chars (see BRACKET EXPRESSIONS for more detail) +

    .
    +matches any single character +

    \k
    +(where k is a non-alphanumeric character) +matches that character taken as an ordinary character, +e.g. \\ matches a backslash character +

    \c
    +where c is alphanumeric +(possibly followed by other characters), +an escape (AREs only), +see ESCAPES below +

    {
    +when followed by a character other than a digit, +matches the left-brace character `{'; +when followed by a digit, it is the beginning of a +bound (see above) +

    x
    +where x is +a single character with no other significance, matches that character. +

    +

    +A constraint matches an empty string when specific conditions +are met. +A constraint may not be followed by a quantifier. +The simple constraints are as follows; some more constraints are +described later, under ESCAPES. +

    +

    +

    ^
    +matches at the beginning of a line +

    $
    +matches at the end of a line +

    (?=re)
    +positive lookahead (AREs only), matches at any point +where a substring matching re begins +

    (?!re)
    +negative lookahead (AREs only), matches at any point +where no substring matching re begins +

    +

    +The lookahead constraints may not contain back references (see later), +and all parentheses within them are considered non-capturing. +

    +An RE may not end with `\'. + +

    BRACKET EXPRESSIONS

    +A bracket expression is a list of characters enclosed in `[ ]'. +It normally matches any single character from the list (but see below). +If the list begins with `^', +it matches any single character +(but see below) not from the rest of the list. +

    +If two characters in the list are separated by `-', +this is shorthand +for the full range of characters between those two (inclusive) in the +collating sequence, +e.g. +[0-9] +in ASCII matches any decimal digit. +Two ranges may not share an +endpoint, so e.g. +a-c-e +is illegal. +Ranges are very collating-sequence-dependent, +and portable programs should avoid relying on them. +

    +To include a literal +] +or +- +in the list, +the simplest method is to +enclose it in +[. and .] +to make it a collating element (see below). +Alternatively, +make it the first character +(following a possible `^'), +or (AREs only) precede it with `\'. +Alternatively, for `-', +make it the last character, +or the second endpoint of a range. +To use a literal +- +as the first endpoint of a range, +make it a collating element +or (AREs only) precede it with `\'. +With the exception of these, some combinations using +[ +(see next +paragraphs), and escapes, +all other special characters lose their +special significance within a bracket expression. +

    +Within a bracket expression, a collating element (a character, +a multi-character sequence that collates as if it were a single character, +or a collating-sequence name for either) +enclosed in +[. and .] +stands for the +sequence of characters of that collating element. +The sequence is a single element of the bracket expression's list. +A bracket expression in a locale that has +multi-character collating elements +can thus match more than one character. +So (insidiously), a bracket expression that starts with ^ +can match multi-character collating elements even if none of them +appear in the bracket expression! +(Note: Tcl currently has no multi-character collating elements. +This information is only for illustration.) +

    +For example, assume the collating sequence includes a ch +multi-character collating element. +Then the RE [[.ch.]]*c (zero or more ch's followed by c) +matches the first five characters of `chchcc'. +Also, the RE [^c]b matches all of `chb' +(because [^c] matches the multi-character ch). +

    +Within a bracket expression, a collating element enclosed in +[= +and +=] +is an equivalence class, standing for the sequences of characters +of all collating elements equivalent to that one, including itself. +(If there are no other equivalent collating elements, +the treatment is as if the enclosing delimiters were `[.' +and `.]'.) +For example, if +o +and +ô +are the members of an equivalence class, +then `[[=o=]]', `[[=ô=]]', +and `[oô]' +are all synonymous. +An equivalence class may not be an endpoint +of a range. +(Note: +Tcl currently implements only the Unicode locale. +It doesn't define any equivalence classes. +The examples above are just illustrations.) +

    +Within a bracket expression, the name of a character class enclosed +in +[: +and +:] +stands for the list of all characters +(not all collating elements!) +belonging to that +class. +Standard character classes are: +

    +

    +alpha A letter. +upper An upper-case letter. +lower A lower-case letter. +digit A decimal digit. +xdigit A hexadecimal digit. +alnum An alphanumeric (letter or digit). +print An alphanumeric (same as alnum). +blank A space or tab character. +space A character producing white space in displayed text. +punct A punctuation character. +graph A character with a visible representation. +cntrl A control character. +
    +

    +A locale may provide others. +(Note that the current Tcl implementation has only one locale: +the Unicode locale.) +A character class may not be used as an endpoint of a range. +

    +There are two special cases of bracket expressions: +the bracket expressions +[[:<:]] +and +[[:>:]] +are constraints, matching empty strings at +the beginning and end of a word respectively. +A word is defined as a sequence of +word characters +that is neither preceded nor followed by +word characters. +A word character is an +alnum +character +or an underscore +(_). +These special bracket expressions are deprecated; +users of AREs should use constraint escapes instead (see below). +

    ESCAPES

    +Escapes (AREs only), which begin with a +\ +followed by an alphanumeric character, +come in several varieties: +character entry, class shorthands, constraint escapes, and back references. +A +\ +followed by an alphanumeric character but not constituting +a valid escape is illegal in AREs. +In EREs, there are no escapes: +outside a bracket expression, +a +\ +followed by an alphanumeric character merely stands for that +character as an ordinary character, +and inside a bracket expression, +\ +is an ordinary character. +(The latter is the one actual incompatibility between EREs and AREs.) +

    +Character-entry escapes (AREs only) exist to make it easier to specify +non-printing and otherwise inconvenient characters in REs: +

    +

    +

    \a
    +alert (bell) character, as in C +

    \b
    +backspace, as in C +

    \B
    +synonym for +\ +to help reduce backslash doubling in some +applications where there are multiple levels of backslash processing +

    \cX
    +(where X is any character) the character whose +low-order 5 bits are the same as those of +X, +and whose other bits are all zero +

    \e
    +the character whose collating-sequence name +is `ESC', +or failing that, the character with octal value 033 +

    \f
    +formfeed, as in C +

    \n
    +newline, as in C +

    \r
    +carriage return, as in C +

    \t
    +horizontal tab, as in C +

    \uwxyz
    +(where +wxyz +is exactly four hexadecimal digits) +the Unicode character +U+wxyz +in the local byte ordering +

    \Ustuvwxyz
    +(where +stuvwxyz +is exactly eight hexadecimal digits) +reserved for a somewhat-hypothetical Unicode extension to 32 bits +

    \v
    +vertical tab, as in C +are all available. +

    \xhhh
    +(where +hhh +is any sequence of hexadecimal digits) +the character whose hexadecimal value is +0xhhh +(a single character no matter how many hexadecimal digits are used). +

    \0
    +the character whose value is +0 +

    \xy
    +(where +xy +is exactly two octal digits, +and is not a +back reference (see below)) +the character whose octal value is +0xy +

    \xyz
    +(where +xyz +is exactly three octal digits, +and is not a +back reference (see below)) +the character whose octal value is +0xyz +

    +

    +Hexadecimal digits are `0'-`9', `a'-`f', +and `A'-`F'. +Octal digits are `0'-`7'. +

    +The character-entry escapes are always taken as ordinary characters. +For example, +\135 +is +] +in ASCII, +but +\135 +does not terminate a bracket expression. +Beware, however, that some applications (e.g., C compilers) interpret +such sequences themselves before the regular-expression package +gets to see them, which may require doubling (quadrupling, etc.) the `\'. +

    +Class-shorthand escapes (AREs only) provide shorthands for certain commonly-used +character classes: +

    +

    +

    \d
    +[[:digit:]] +

    \s
    +[[:space:]] +

    \w
    +[[:alnum:]_] +(note underscore) +

    \D
    +[^[:digit:]] +

    \S
    +[^[:space:]] +

    \W
    +[^[:alnum:]_] +(note underscore) +

    +

    +Within bracket expressions, `\d', `\s', +and `\w' +lose their outer brackets, +and `\D', `\S', +and `\W' +are illegal. +(So, for example, [a-c\d] is equivalent to [a-c[:digit:]]. +Also, [a-c\D], which is equivalent to [a-c^[:digit:]], is illegal.) +

    +A constraint escape (AREs only) is a constraint, +matching the empty string if specific conditions are met, +written as an escape: +

    +

    +

    \A
    +matches only at the beginning of the string +(see MATCHING, below, for how this differs from `^') +

    \m
    +matches only at the beginning of a word +

    \M
    +matches only at the end of a word +

    \y
    +matches only at the beginning or end of a word +

    \Y
    +matches only at a point that is not the beginning or end of a word +

    \Z
    +matches only at the end of the string +(see MATCHING, below, for how this differs from `$') +

    \m
    +(where +m +is a nonzero digit) a back reference, see below +

    \mnn
    +(where +m +is a nonzero digit, and +nn +is some more digits, +and the decimal value +mnn +is not greater than the number of closing capturing parentheses seen so far) +a back reference, see below +

    +

    +A word is defined as in the specification of +[[:<:]] +and +[[:>:]] +above. +Constraint escapes are illegal within bracket expressions. +

    +A back reference (AREs only) matches the same string matched by the parenthesized +subexpression specified by the number, +so that (e.g.) +([bc])\1 +matches +bb +or +cc +but not `bc'. +The subexpression must entirely precede the back reference in the RE. +Subexpressions are numbered in the order of their leading parentheses. +Non-capturing parentheses do not define subexpressions. +

    +There is an inherent historical ambiguity between octal character-entry +escapes and back references, which is resolved by heuristics, +as hinted at above. +A leading zero always indicates an octal escape. +A single non-zero digit, not followed by another digit, +is always taken as a back reference. +A multi-digit sequence not starting with a zero is taken as a back +reference if it comes after a suitable subexpression +(i.e. the number is in the legal range for a back reference), +and otherwise is taken as octal. +

    METASYNTAX

    +In addition to the main syntax described above, there are some special +forms and miscellaneous syntactic facilities available. +

    +Normally the flavor of RE being used is specified by +application-dependent means. +However, this can be overridden by a director. +If an RE of any flavor begins with `***:', +the rest of the RE is an ARE. +If an RE of any flavor begins with `***=', +the rest of the RE is taken to be a literal string, +with all characters considered ordinary characters. +

    +An ARE may begin with embedded options: +a sequence +(?xyz) +(where +xyz +is one or more alphabetic characters) +specifies options affecting the rest of the RE. +These supplement, and can override, +any options specified by the application. +The available option letters are: +

    +

    +

    b
    +rest of RE is a BRE +

    c
    +case-sensitive matching (usual default) +

    e
    +rest of RE is an ERE +

    i
    +case-insensitive matching (see MATCHING, below) +

    m
    +historical synonym for +n +

    n
    +newline-sensitive matching (see MATCHING, below) +

    p
    +partial newline-sensitive matching (see MATCHING, below) +

    q
    +rest of RE is a literal (``quoted'') string, all ordinary characters +

    s
    +non-newline-sensitive matching (usual default) +

    t
    +tight syntax (usual default; see below) +

    w
    +inverse partial newline-sensitive (``weird'') matching (see MATCHING, below) +

    x
    +expanded syntax (see below) +

    +

    +Embedded options take effect at the +) +terminating the sequence. +They are available only at the start of an ARE, +and may not be used later within it. +

    +In addition to the usual (tight) RE syntax, in which all characters are +significant, there is an expanded syntax, +available in all flavors of RE +with the -expanded switch, or in AREs with the embedded x option. +In the expanded syntax, +white-space characters are ignored +and all characters between a +# +and the following newline (or the end of the RE) are ignored, +permitting paragraphing and commenting a complex RE. +There are three exceptions to that basic rule: +

    +

    +a white-space character or `#' preceded by `\' is retained +

    +white space or `#' within a bracket expression is retained +

    +white space and comments are illegal within multi-character symbols +like the ARE `(?:' or the BRE `\(' +

    +

    +Expanded-syntax white-space characters are blank, tab, newline, and +any character that belongs to the space character class. +

    +Finally, in an ARE, +outside bracket expressions, the sequence `(?#ttt)' +(where +ttt +is any text not containing a `)') +is a comment, +completely ignored. +Again, this is not allowed between the characters of +multi-character symbols like `(?:'. +Such comments are more a historical artifact than a useful facility, +and their use is deprecated; +use the expanded syntax instead. +

    +None of these metasyntax extensions is available if the application +(or an initial +***= +director) +has specified that the user's input be treated as a literal string +rather than as an RE. +

    MATCHING

    +In the event that an RE could match more than one substring of a given +string, +the RE matches the one starting earliest in the string. +If the RE could match more than one substring starting at that point, +its choice is determined by its preference: +either the longest substring, or the shortest. +

    +Most atoms, and all constraints, have no preference. +A parenthesized RE has the same preference (possibly none) as the RE. +A quantified atom with quantifier +{m} +or +{m}? +has the same preference (possibly none) as the atom itself. +A quantified atom with other normal quantifiers (including +{m,n} +with +m +equal to +n) +prefers longest match. +A quantified atom with other non-greedy quantifiers (including +{m,n}? +with +m +equal to +n) +prefers shortest match. +A branch has the same preference as the first quantified atom in it +which has a preference. +An RE consisting of two or more branches connected by the +| +operator prefers longest match. +

    +Subject to the constraints imposed by the rules for matching the whole RE, +subexpressions also match the longest or shortest possible substrings, +based on their preferences, +with subexpressions starting earlier in the RE taking priority over +ones starting later. +Note that outer subexpressions thus take priority over +their component subexpressions. +

    +Note that the quantifiers +{1,1} +and +{1,1}? +can be used to force longest and shortest preference, respectively, +on a subexpression or a whole RE. +

    +Match lengths are measured in characters, not collating elements. +An empty string is considered longer than no match at all. +For example, +bb* +matches the three middle characters of `abbbc', +(week|wee)(night|knights) +matches all ten characters of `weeknights', +when +(.*).* +is matched against +abc +the parenthesized subexpression +matches all three characters, and +when +(a*)* +is matched against +bc +both the whole RE and the parenthesized +subexpression match an empty string. +

    +If case-independent matching is specified, +the effect is much as if all case distinctions had vanished from the +alphabet. +When an alphabetic that exists in multiple cases appears as an +ordinary character outside a bracket expression, it is effectively +transformed into a bracket expression containing both cases, +so that +x +becomes `[xX]'. +When it appears inside a bracket expression, all case counterparts +of it are added to the bracket expression, so that +[x] +becomes +[xX] +and +[^x] +becomes `[^xX]'. +

    +If newline-sensitive matching is specified, . +and bracket expressions using +^ +will never match the newline character +(so that matches will never cross newlines unless the RE +explicitly arranges it) +and +^ +and +$ +will match the empty string after and before a newline +respectively, in addition to matching at beginning and end of string +respectively. +ARE +\A +and +\Z +continue to match beginning or end of string only. +

    +If partial newline-sensitive matching is specified, +this affects . +and bracket expressions +as with newline-sensitive matching, but not +^ +and `$'. +

    +If inverse partial newline-sensitive matching is specified, +this affects +^ +and +$ +as with +newline-sensitive matching, +but not . +and bracket expressions. +This isn't very useful but is provided for symmetry. +

    LIMITS AND COMPATIBILITY

    +No particular limit is imposed on the length of REs. +Programs intended to be highly portable should not employ REs longer +than 256 bytes, +as a POSIX-compliant implementation can refuse to accept such REs. +

    +The only feature of AREs that is actually incompatible with +POSIX EREs is that +\ +does not lose its special +significance inside bracket expressions. +All other ARE features use syntax which is illegal or has +undefined or unspecified effects in POSIX EREs; +the +*** +syntax of directors likewise is outside the POSIX +syntax for both BREs and EREs. +

    +Many of the ARE extensions are borrowed from Perl, but some have +been changed to clean them up, and a few Perl extensions are not present. +Incompatibilities of note include `\b', `\B', +the lack of special treatment for a trailing newline, +the addition of complemented bracket expressions to the things +affected by newline-sensitive matching, +the restrictions on parentheses and back references in lookahead constraints, +and the longest/shortest-match (rather than first-match) matching semantics. +

    +The matching rules for REs containing both normal and non-greedy quantifiers +have changed since early beta-test versions of this package. +(The new rules are much simpler and cleaner, +but don't work as hard at guessing the user's real intentions.) +

    +Henry Spencer's original 1986 regexp package, +still in widespread use (e.g., in pre-8.1 releases of Tcl), +implemented an early version of today's EREs. +There are four incompatibilities between regexp's near-EREs +(`RREs' for short) and AREs. +In roughly increasing order of significance: +

    +

    +In AREs, +\ +followed by an alphanumeric character is either an +escape or an error, +while in RREs, it was just another way of writing the +alphanumeric. +This should not be a problem because there was no reason to write +such a sequence in RREs. +

    +{ +followed by a digit in an ARE is the beginning of a bound, +while in RREs, +{ +was always an ordinary character. +Such sequences should be rare, +and will often result in an error because following characters +will not look like a valid bound. +

    +In AREs, +\ +remains a special character within `[ ]', +so a literal +\ +within +[ ] +must be written `\\'. +\\ +also gives a literal +\ +within +[ ] +in RREs, +but only truly paranoid programmers routinely doubled the backslash. +

    +AREs report the longest/shortest match for the RE, +rather than the first found in a specified search order. +This may affect some RREs which were written in the expectation that +the first match would be reported. +(The careful crafting of RREs to optimize the search order for fast +matching is obsolete (AREs examine all possible matches +in parallel, and their performance is largely insensitive to their +complexity) but cases where the search order was exploited to deliberately +find a match which was not the longest/shortest will need rewriting.) +

    +

    BASIC REGULAR EXPRESSIONS

    +BREs differ from EREs in several respects. `|', `+', +and +? +are ordinary characters and there is no equivalent +for their functionality. +The delimiters for bounds are +\{ +and `\}', +with +{ +and +} +by themselves ordinary characters. +The parentheses for nested subexpressions are +\( +and `\)', +with +( +and +) +by themselves ordinary characters. +^ +is an ordinary character except at the beginning of the +RE or the beginning of a parenthesized subexpression, +$ +is an ordinary character except at the end of the +RE or the end of a parenthesized subexpression, +and +* +is an ordinary character if it appears at the beginning of the +RE or the beginning of a parenthesized subexpression +(after a possible leading `^'). +Finally, +single-digit back references are available, +and +\< +and +\> +are synonyms for +[[:<:]] +and +[[:>:]] +respectively; +no other escapes are available. + +

    SEE ALSO

    +RegExp, regexp, regsub, lsearch, switch, text +

    KEYWORDS

    +match, regular expression, string +
    +Copyright © 1998 Sun Microsystems, Inc.
    +Copyright © 1999 Scriptics Corporation
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/read.htm b/hlp/en/tcl/read.htm new file mode 100644 index 0000000..b99663e --- /dev/null +++ b/hlp/en/tcl/read.htm @@ -0,0 +1,44 @@ +Tcl Built-In Commands - read manual page +

    NAME

    +read - Read from a channel +

    SYNOPSIS

    +read ?-nonewline? channelId
    +read channelId numChars
    +

    DESCRIPTION

    +In the first form, the read command reads all of the data from +channelId up to the end of the file. +If the -nonewline switch is specified then the last character +of the file is discarded if it is a newline. +In the second form, the extra argument specifies how many characters to +read. Exactly that many characters will be read and returned, unless +there are fewer than numChars left in the file; in this case +all the remaining characters are returned. If the channel is +configured to use a multi-byte encoding, then the number of characters +read may not be the same as the number of bytes read. +

    +If channelId is in nonblocking mode, the command may not read as +many characters as requested: once all available input has been read, +the command will return the data that is available rather than +blocking for more input. If the channel is configured to use a +multi-byte encoding, then there may actually be some bytes remaining +in the internal buffers that do not form a complete character. These +bytes will not be returned until a complete character is available or +end-of-file is reached. +The -nonewline switch is ignored if the command returns +before reaching the end of the file. +

    +Read translates end-of-line sequences in the input into +newline characters according to the -translation option +for the channel. +See the fconfigure manual entry for a discussion on ways in +which fconfigure will alter input. + +

    SEE ALSO

    +file, eof, fblocked, fconfigure +

    KEYWORDS

    +blocking, channel, end of line, end of file, nonblocking, read, translation, encoding +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/regexp.htm b/hlp/en/tcl/regexp.htm new file mode 100644 index 0000000..e907341 --- /dev/null +++ b/hlp/en/tcl/regexp.htm @@ -0,0 +1,133 @@ +Tcl Built-In Commands - regexp manual page +
    +
    NAME +
    regexp - Match a regular expression against a string
    +
    SYNOPSIS +
    +
    regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...? +
    +
    DESCRIPTION +
    +
    -about +
    -expanded +
    -indices +
    -line +
    -linestop +
    -lineanchor +
    -nocase +
    -all +
    -inline +
    -start index +
    - - +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +regexp - Match a regular expression against a string +

    SYNOPSIS

    +regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
    +

    DESCRIPTION

    +Determines whether the regular expression exp matches part or +all of string and returns 1 if it does, 0 if it doesn't, unless +-inline is specified (see below). +(Regular expression matching is described in the re_syntax +reference page.) +

    +If additional arguments are specified after string then they +are treated as the names of variables in which to return +information about which part(s) of string matched exp. +MatchVar will be set to the range of string that +matched all of exp. The first subMatchVar will contain +the characters in string that matched the leftmost parenthesized +subexpression within exp, the next subMatchVar will +contain the characters that matched the next parenthesized +subexpression to the right in exp, and so on. +

    +If the initial arguments to regexp start with - then +they are treated as switches. The following switches are +currently supported: +

    +

    +

    -about
    +Instead of attempting to match the regular expression, returns a list +containing information about the regular expression. The first +element of the list is a subexpression count. The second element is a +list of property names that describe various attributes of the regular +expression. This switch is primarily intended for debugging purposes. +

    -expanded
    +Enables use of the expanded regular expression syntax where +whitespace and comments are ignored. This is the same as specifying +the (?x) embedded option (see METASYNTAX, below). +

    -indices
    +Changes what is stored in the subMatchVars. +Instead of storing the matching characters from string, +each variable +will contain a list of two decimal strings giving the indices +in string of the first and last characters in the matching +range of characters. +

    -line
    +Enables newline-sensitive matching. By default, newline is a +completely ordinary character with no special meaning. With this +flag, `[^' bracket expressions and `.' never match newline, `^' +matches an empty string after any newline in addition to its normal +function, and `$' matches an empty string before any newline in +addition to its normal function. This flag is equivalent to +specifying both -linestop and -lineanchor, or the +(?n) embedded option (see METASYNTAX, below). +

    -linestop
    +Changes the behavior of `[^' bracket expressions and `.' so that they +stop at newlines. This is the same as specifying the (?p) +embedded option (see METASYNTAX, below). +

    -lineanchor
    +Changes the behavior of `^' and `$' (the ``anchors'') so they match the +beginning and end of a line respectively. This is the same as +specifying the (?w) embedded option (see METASYNTAX, below). +

    -nocase
    +Causes upper-case characters in string to be treated as +lower case during the matching process. +

    -all
    +Causes the regular expression to be matched as many times as possible +in the string, returning the total number of matches found. If this +is specified with match variables, they will continue information for +the last match only. +

    -inline
    +Causes the command to return, as a list, the data that would otherwise +be placed in match variables. When using -inline, +match variables may not be specified. If used with -all, the +list will be concatenated at each iteration, such that a flat list is +always returned. For each match iteration, the command will append the +overall match data, plus one element for each subexpression in the +regular expression. Examples are: +
    regexp -inline -- {\w(\w)} " inlined "
    + => {in n}
    +    regexp -all -inline -- {\w(\w)} " inlined "
    + => {in n li i ne e}
    +

    -start index
    +Specifies a character index offset into the string to start +matching the regular expression at. When using this switch, `^' +will not match the beginning of the line, and \A will still +match the start of the string at index. If -indices +is specified, the indices will be indexed starting from the +absolute beginning of the input string. +index will be constrained to the bounds of the input string. +

    - -
    +Marks the end of switches. The argument following this one will +be treated as exp even if it starts with a -. +

    +

    +If there are more subMatchVar's than parenthesized +subexpressions within exp, or if a particular subexpression +in exp doesn't match the string (e.g. because it was in a +portion of the expression that wasn't matched), then the corresponding +subMatchVar will be set to ``-1 -1'' if -indices +has been specified or to an empty string otherwise. + +

    SEE ALSO

    +re_syntax, regsub +

    KEYWORDS

    +match, regular expression, string +
    +Copyright © 1998 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/registry.htm b/hlp/en/tcl/registry.htm new file mode 100644 index 0000000..e0245e9 --- /dev/null +++ b/hlp/en/tcl/registry.htm @@ -0,0 +1,163 @@ +Tcl Built-In Commands - registry manual page +
    +
    NAME +
    registry - Manipulate the Windows registry
    +
    SYNOPSIS +
    +
    package require registry 1.0 +
    registry option keyName ?arg arg ...? +
    +
    DESCRIPTION +
    +
    registry delete keyName ?valueName? +
    registry get keyName valueName +
    registry keys keyName ?pattern? +
    registry set keyName ?valueName data ?type?? +
    registry type keyName valueName +
    registry values keyName ?pattern? +
    +
    SUPPORTED TYPES +
    +
    binary +
    none +
    sz +
    expand_sz +
    dword +
    dword_big_endian +
    link +
    multi_sz +
    resource_list +
    +
    PORTABILITY ISSUES +
    KEYWORDS +

    +

    NAME

    +registry - Manipulate the Windows registry +

    SYNOPSIS

    +package require registry 1.0
    +registry optionkeyName ?arg arg ...?
    +

    DESCRIPTION

    +The registry package provides a general set of operations for +manipulating the Windows registry. The package implements the +registry Tcl command. This command is only supported on the +Windows platform. Warning: this command should be used with caution +as a corrupted registry can leave your system in an unusable state. +

    +KeyName is the name of a registry key. Registry keys must be +one of the following forms: +

    +\\hostname\rootname\keypath +

    +rootname\keypath +

    +rootname +

    +

    +Hostname specifies the name of any valid Windows +host that exports its registry. The rootname component must be +one of HKEY_LOCAL_MACHINE, HKEY_USERS, +HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, +HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, or +HKEY_DYN_DATA. The keypath can be one or more +registry key names separated by backslash (\) characters. +

    +Option indicates what to do with the registry key name. Any +unique abbreviation for option is acceptable. The valid options +are: +

    +

    +

    registry delete keyName ?valueName?
    +If the optional valueName argument is present, the specified +value under keyName will be deleted from the registry. If the +optional valueName is omitted, the specified key and any subkeys +or values beneath it in the registry heirarchy will be deleted. If +the key could not be deleted then an error is generated. If the key +did not exist, the command has no effect. +

    registry get keyName valueName
    +Returns the data associated with the value valueName under the key +keyName. If either the key or the value does not exist, then an +error is generated. For more details on the format of the returned +data, see SUPPORTED TYPES, below. +

    registry keys keyName ?pattern?
    +If pattern isn't specified, returns a list of names of all the +subkeys of keyName. If pattern is specified, only those +names matching pattern are returned. Matching is determined +using the same rules as for string match. If the +specified keyName does not exist, then an error is generated. +

    registry set keyName ?valueName data ?type??
    +If valueName isn't specified, creates the key keyName if +it doesn't already exist. If valueName is specified, creates +the key keyName and value valueName if necessary. The +contents of valueName are set to data with the type +indicated by type. If type isn't specified, the type +sz is assumed. For more details on the data and type arguments, +see SUPPORTED TYPES below. +

    registry type keyName valueName
    +Returns the type of the value valueName in the key +keyName. For more information on the possible types, see +SUPPORTED TYPES, below. +

    registry values keyName ?pattern?
    +If pattern isn't specified, returns a list of names of all the +values of keyName. If pattern is specified, only those +names matching pattern are returned. Matching is determined +using the same rules as for string match. + +

    +

    SUPPORTED TYPES

    +Each value under a key in the registry contains some data of a +particular type in a type-specific representation. The registry +command converts between this internal representation and one that can +be manipulated by Tcl scripts. In most cases, the data is simply +returned as a Tcl string. The type indicates the intended use for the +data, but does not actually change the representation. For some +types, the registry command returns the data in a different form to +make it easier to manipulate. The following types are recognized by the +registry command: +

    +

    +

    binary
    +The registry value contains arbitrary binary data. The data is represented +exactly in Tcl, including any embedded nulls. +

    none
    +The registry value contains arbitrary binary data with no defined +type. The data is represented exactly in Tcl, including any embedded +nulls. +

    sz
    +The registry value contains a null-terminated string. The data is +represented in Tcl as a string. +

    expand_sz
    +The registry value contains a null-terminated string that contains +unexpanded references to environment variables in the normal Windows +style (for example, "%PATH%"). The data is represented in Tcl as a +string. +

    dword
    +The registry value contains a little-endian 32-bit number. The data is +represented in Tcl as a decimal string. +

    dword_big_endian
    +The registry value contains a big-endian 32-bit number. The data is +represented in Tcl as a decimal string. +

    link
    +The registry value contains a symbolic link. The data is represented +exactly in Tcl, including any embedded nulls. +

    multi_sz
    +The registry value contains an array of null-terminated strings. The +data is represented in Tcl as a list of strings. +

    resource_list
    +The registry value contains a device-driver resource list. The data +is represented exactly in Tcl, including any embedded nulls. +

    +

    +In addition to the symbolically named types listed above, unknown +types are identified using a 32-bit integer that corresponds to the +type code returned by the system interfaces. In this case, the data +is represented exactly in Tcl, including any embedded nulls. + +

    PORTABILITY ISSUES

    +The registry command is only available on Windows. + +

    KEYWORDS

    +registry +
    +Copyright © 1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/regsub.htm b/hlp/en/tcl/regsub.htm new file mode 100644 index 0000000..74d183d --- /dev/null +++ b/hlp/en/tcl/regsub.htm @@ -0,0 +1,115 @@ +Tcl Built-In Commands - regsub manual page +
    +
    NAME +
    regsub - Perform substitutions based on regular expression pattern matching
    +
    SYNOPSIS +
    +
    regsub ?switches? exp string subSpec varName +
    +
    DESCRIPTION +
    +
    -all +
    -expanded +
    -line +
    -linestop +
    -lineanchor +
    -nocase +
    -start index +
    - - +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +regsub - Perform substitutions based on regular expression pattern matching +

    SYNOPSIS

    +regsub ?switches? exp string subSpec varName
    +

    DESCRIPTION

    +This command matches the regular expression exp against +string, +and it copies string to the variable whose name is +given by varName. +(Regular expression matching is described in the re_syntax +reference page.) +If there is a match, then while copying string to varName +the portion of string that +matched exp is replaced with subSpec. +If subSpec contains a ``&'' or ``\0'', then it is replaced +in the substitution with the portion of string that +matched exp. +If subSpec contains a ``\n'', where n is a digit +between 1 and 9, then it is replaced in the substitution with +the portion of string that matched the n-th +parenthesized subexpression of exp. +Additional backslashes may be used in subSpec to prevent special +interpretation of ``&'' or ``\0'' or ``\n'' or +backslash. +The use of backslashes in subSpec tends to interact badly +with the Tcl parser's use of backslashes, so it's generally +safest to enclose subSpec in braces if it includes +backslashes. +

    +If the initial arguments to regexp start with - then +they are treated as switches. The following switches are +currently supported: +

    +

    +

    -all
    +All ranges in string that match exp are found and +substitution is performed for each of these ranges. +Without this switch only the first +matching range is found and substituted. +If -all is specified, then ``&'' and ``\n'' +sequences are handled for each substitution using the information +from the corresponding match. +

    -expanded
    +Enables use of the expanded regular expression syntax where +whitespace and comments are ignored. This is the same as specifying +the (?x) embedded option (see METASYNTAX, below). +

    -line
    +Enables newline-sensitive matching. By default, newline is a +completely ordinary character with no special meaning. With this +flag, `[^' bracket expressions and `.' never match newline, `^' +matches an empty string after any newline in addition to its normal +function, and `$' matches an empty string before any newline in +addition to its normal function. This flag is equivalent to +specifying both -linestop and -lineanchor, or the +(?n) embedded option (see METASYNTAX, below). +

    -linestop
    +Changes the behavior of `[^' bracket expressions and `.' so that they +stop at newlines. This is the same as specifying the (?p) +embedded option (see METASYNTAX, below). +

    -lineanchor
    +Changes the behavior of `^' and `$' (the ``anchors'') so they match the +beginning and end of a line respectively. This is the same as +specifying the (?w) embedded option (see METASYNTAX, below). +

    -nocase
    +Upper-case characters in string will be converted to lower-case +before matching against exp; however, substitutions specified +by subSpec use the original unconverted form of string. +

    -start index
    +Specifies a character index offset into the string to start +matching the regular expression at. When using this switch, `^' +will not match the beginning of the line, and \A will still +match the start of the string at index. +index will be constrained to the bounds of the input string. +

    - -
    +Marks the end of switches. The argument following this one will +be treated as exp even if it starts with a -. +

    +

    +The command returns a count of the number of matching ranges that +were found and replaced. +See the manual entry for regexp for details on the interpretation +of regular expressions. + +

    SEE ALSO

    +regexp, re_syntax +

    KEYWORDS

    +match, pattern, regular expression, substitute +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 2000 Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/rename.htm b/hlp/en/tcl/rename.htm new file mode 100644 index 0000000..812d0ea --- /dev/null +++ b/hlp/en/tcl/rename.htm @@ -0,0 +1,24 @@ +Built-In Commands - rename manual page +

    NAME

    +rename - Rename or delete a command +

    SYNOPSIS

    +rename oldName newName
    +

    DESCRIPTION

    +Rename the command that used to be called oldName so that it +is now called newName. +If newName is an empty string then oldName is deleted. +oldName and newName may include namespace qualifiers +(names of containing namespaces). +If a command is renamed into a different namespace, +future invocations of it will execute in the new namespace. +The rename command returns an empty string as result. + +

    SEE ALSO

    +namespace, proc +

    KEYWORDS

    +command, delete, namespace, rename +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/resource.htm b/hlp/en/tcl/resource.htm new file mode 100644 index 0000000..ec4e7e6 --- /dev/null +++ b/hlp/en/tcl/resource.htm @@ -0,0 +1,169 @@ +Tcl Built-In Commands - resource manual page +
    +
    NAME +
    resource - Manipulate Macintosh resources
    +
    SYNOPSIS +
    +
    resource option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    resource close rsrcRef +
    resource delete ?options? resourceType +
    +
    -id resourceId +
    -name resourceName +
    -file resourceRef +
    +
    resource files ?resourceRef? +
    resource list resourceType ?resourceRef? +
    resource open fileName ?access? +
    resource read resourceType resourceId ?resourceRef? +
    resource types ?resourceRef? +
    resource write ?options? resourceType data +
    +
    -id resourceId +
    -name resourceName +
    -file resourceRef +
    -force +
    +
    +
    RESOURCE TYPES +
    RESOURCE IDS +
    PORTABILITY ISSUES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +resource - Manipulate Macintosh resources +

    SYNOPSIS

    +resource option ?arg arg ...?
    +

    DESCRIPTION

    +The resource command provides some generic operations for +dealing with Macintosh resources. This command is only supported on +the Macintosh platform. Each Macintosh file consists of two +forks: a data fork and a resource fork. You use the +normal open, puts, close, etc. commands to manipulate the data fork. +You must use this command, however, to interact with the resource +fork. Option indicates what resource command to perform. Any +unique abbreviation for option is acceptable. The valid options +are: +

    +

    +

    resource close rsrcRef
    +Closes the given resource reference (obtained from resource +open). Resources from that resource file will no longer be +available. +

    resource delete ?options? resourceType
    +This command will delete the resource specified by options and +type resourceType (see RESOURCE TYPES below). The options +give you several ways to specify the resource to be deleted. +

    +

    +

    -id resourceId
    +If the -id option is given the id resourceId (see RESOURCE +IDS below) is used to specify the resource to be deleted. The id must +be a number - to specify a name use the -name option. +

    -name resourceName
    +If -name is specified, the resource named +resourceName will be deleted. If the -id is also +provided, then there must be a resource with BOTH this name and +this id. If no name is provided, then the id will be used regardless +of the name of the actual resource. +

    -file resourceRef
    +If the -file option is specified then the resource will be +deleted from the file pointed to by resourceRef. Otherwise the +first resource with the given resourceName and or +resourceId which is found on the resource file path will be +deleted. To inspect the file path, use the resource files command. +

    +

    resource files ?resourceRef?
    +If resourceRefis not provided, this command returns a Tcl list +of the resource references for all the currently open resource files. +The list is in the normal Macintosh search order for resources. If +resourceRef is specified, the command will +return the path to the file whose resource fork is represented by that +token. +

    resource list resourceType ?resourceRef?
    +List all of the resources ids of type resourceType (see RESOURCE +TYPES below). If resourceRef is specified then the command will +limit the search to that particular resource file. Otherwise, all +resource files currently opened by the application will be searched. +A Tcl list of either the resource name's or resource id's of the found +resources will be returned. See the RESOURCE IDS section below for +more details about what a resource id is. +

    resource open fileName ?access?
    +Open the resource for the file fileName. Standard file access +permissions may also be specified (see the manual entry for open +for details). A resource reference (resourceRef) is returned +that can be used by the other resource commands. An error can occur +if the file doesn't exist or the file does not have a resource fork. +However, if you open the file with write permissions the file and/or +resource fork will be created instead of generating an error. +

    resource read resourceType resourceId ?resourceRef?
    +Read the entire resource of type resourceType (see RESOURCE +TYPES below) and the name or id of resourceId (see RESOURCE IDS +below) into memory and return the result. If resourceRef is +specified we limit our search to that resource file, otherwise we +search all open resource forks in the application. It is important to +note that most Macintosh resource use a binary format and the data +returned from this command may have embedded NULLs or other non-ASCII +data. +

    resource types ?resourceRef?
    +This command returns a Tcl list of all resource types (see RESOURCE +TYPES below) found in the resource file pointed to by +resourceRef. If resourceRef is not specified it will +return all the resource types found in every resource file currently +opened by the application. +

    resource write ?options? resourceType data
    +This command will write the passed in data as a new resource of +type resourceType (see RESOURCE TYPES below). Several options +are available that describe where and how the resource is stored. +

    +

    +

    -id resourceId
    +If the -id option is given the id resourceId (see RESOURCE +IDS below) is used for the new resource, otherwise a unique id will be +generated that will not conflict with any existing resource. However, +the id must be a number - to specify a name use the -name option. +

    -name resourceName
    +If -name is specified the resource will be named +resourceName, otherwise it will have the empty string as the +name. +

    -file resourceRef
    +If the -file option is specified then the resource will be +written in the file pointed to by resourceRef, otherwise the +most resently open resource will be used. +

    -force
    +If the target resource already exists, then by default Tcl will not +overwrite it, but raise an error instead. Use the -force flag to +force overwriting the extant resource. +

    +

    +

    RESOURCE TYPES

    +Resource types are defined as a four character string that is then +mapped to an underlying id. For example, TEXT refers to the +Macintosh resource type for text. The type STR# is a list of +counted strings. All Macintosh resources must be of some type. See +Macintosh documentation for a more complete list of resource types +that are commonly used. + +

    RESOURCE IDS

    +For this command the notion of a resource id actually refers to two +ideas in Macintosh resources. Every place you can use a resource Id +you can use either the resource name or a resource number. Names are +always searched or returned in preference to numbers. For example, +the resource list command will return names if they exist or +numbers if the name is NULL. + +

    PORTABILITY ISSUES

    +The resource command is only available on Macintosh. + +

    SEE ALSO

    +open +

    KEYWORDS

    +open, resource +
    +Copyright © 1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/return.htm b/hlp/en/tcl/return.htm new file mode 100644 index 0000000..8492d8e --- /dev/null +++ b/hlp/en/tcl/return.htm @@ -0,0 +1,97 @@ +Tcl Built-In Commands - return manual page +
    +
    NAME +
    return - Return from a procedure
    +
    SYNOPSIS +
    +
    return ?-code code? ?-errorinfo info? ?-errorcode code? ?string? +
    +
    DESCRIPTION +
    EXCEPTIONAL RETURNS +
    +
    ok +
    error +
    return +
    break +
    continue +
    value +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +return - Return from a procedure +

    SYNOPSIS

    +return ?-code code? ?-errorinfo info? ?-errorcode code? ?string?
    +

    DESCRIPTION

    +Return immediately from the current procedure +(or top-level command or source command), +with string as the return value. If string is not specified then +an empty string will be returned as result. + +

    EXCEPTIONAL RETURNS

    +In the usual case where the -code option isn't +specified the procedure will return normally (its completion +code will be TCL_OK). +However, the -code option may be used to generate an +exceptional return from the procedure. +Code may have any of the following values: +

    +

    +

    ok
    +Normal return: same as if the option is omitted. +

    error
    +Error return: same as if the error command were used to +terminate the procedure, except for handling of errorInfo +and errorCode variables (see below). +

    return
    +The current procedure will return with a completion code of +TCL_RETURN, so that the procedure that invoked it will return +also. +

    break
    +The current procedure will return with a completion code of +TCL_BREAK, which will terminate the innermost nested loop in +the code that invoked the current procedure. +

    continue
    +The current procedure will return with a completion code of +TCL_CONTINUE, which will terminate the current iteration of +the innermost nested loop in the code that invoked the current +procedure. +

    value
    +Value must be an integer; it will be returned as the +completion code for the current procedure. +

    +

    +The -code option is rarely used. +It is provided so that procedures that implement +new control structures can reflect exceptional conditions back to +their callers. +

    +Two additional options, -errorinfo and -errorcode, +may be used to provide additional information during error +returns. +These options are ignored unless code is error. +

    +The -errorinfo option specifies an initial stack +trace for the errorInfo variable; if it is not specified then +the stack trace left in errorInfo will include the call to +the procedure and higher levels on the stack but it will not include +any information about the context of the error within the procedure. +Typically the info value is supplied from the value left +in errorInfo after a catch command trapped an error within +the procedure. +

    +If the -errorcode option is specified then code provides +a value for the errorCode variable. +If the option is not specified then errorCode will +default to NONE. + +

    SEE ALSO

    +break, continue, error, proc +

    KEYWORDS

    +break, continue, error, procedure, return +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/safe.htm b/hlp/en/tcl/safe.htm new file mode 100644 index 0000000..add4cb9 --- /dev/null +++ b/hlp/en/tcl/safe.htm @@ -0,0 +1,354 @@ +Tcl Tcl Built-In Commands - Safe manual page +
    +
    NAME +
    Safe Base - A mechanism for creating and manipulating safe interpreters.
    +
    SYNOPSIS +
    +
    ::safe::interpCreate ?slave? ?options...? +
    ::safe::interpInit slave ?options...? +
    ::safe::interpConfigure slave ?options...? +
    ::safe::interpDelete slave +
    ::safe::interpAddToAccessPath slave directory +
    ::safe::interpFindInAccessPath slave directory +
    ::safe::setLogCmd ?cmd arg...? +
    +
    OPTIONS +
    DESCRIPTION +
    COMMANDS +
    +
    ::safe::interpCreate ?slave? ?options...? +
    ::safe::interpInit slave ?options...? +
    ::safe::interpConfigure slave ?options...? +
    ::safe::interpDelete slave +
    ::safe::interpFindInAccessPath slave directory +
    ::safe::interpAddToAccessPath slave directory +
    ::safe::setLogCmd ?cmd arg...? +
    +
    OPTIONS +
    +
    -accessPath directoryList +
    -statics boolean +
    -noStatics +
    -nested boolean +
    -nestedLoadOk +
    -deleteHook script +
    +
    ALIASES +
    +
    source fileName +
    load fileName +
    file ?subCmd args...? +
    encoding ?subCmd args...? +
    exit +
    +
    SECURITY +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +Safe Base - A mechanism for creating and manipulating safe interpreters. +

    SYNOPSIS

    +::safe::interpCreate ?slave? ?options...?
    +::safe::interpInitslave ?options...?
    +::safe::interpConfigureslave ?options...?
    +::safe::interpDeleteslave
    +::safe::interpAddToAccessPathslavedirectory
    +::safe::interpFindInAccessPathslavedirectory
    +::safe::setLogCmd ?cmd arg...?
    +

    OPTIONS

    +?-accessPathpathList? +?-staticsboolean? ?-noStatics? +?-nestedboolean? ?-nestedLoadOk? +?-deleteHookscript? +

    DESCRIPTION

    +Safe Tcl is a mechanism for executing untrusted Tcl scripts +safely and for providing mediated access by such scripts to +potentially dangerous functionality. +

    +The Safe Base ensures that untrusted Tcl scripts cannot harm the +hosting application. +The Safe Base prevents integrity and privacy attacks. Untrusted Tcl +scripts are prevented from corrupting the state of the hosting +application or computer. Untrusted scripts are also prevented from +disclosing information stored on the hosting computer or in the +hosting application to any party. +

    +The Safe Base allows a master interpreter to create safe, restricted +interpreters that contain a set of predefined aliases for the source, +load, file, encoding, and exit commands and +are able to use the auto-loading and package mechanisms. +

    +No knowledge of the file system structure is leaked to the +safe interpreter, because it has access only to a virtualized path +containing tokens. When the safe interpreter requests to source a file, it +uses the token in the virtual path as part of the file name to source; the +master interpreter transparently +translates the token into a real directory name and executes the +requested operation (see the section SECURITY below for details). +Different levels of security can be selected by using the optional flags +of the commands described below. +

    +All commands provided in the master interpreter by the Safe Base reside in +the safe namespace: + +

    COMMANDS

    +The following commands are provided in the master interpreter: +

    +

    +

    ::safe::interpCreate ?slave? ?options...?
    +Creates a safe interpreter, installs the aliases described in the section +ALIASES and initializes the auto-loading and package mechanism as +specified by the supplied options. +See the OPTIONS section below for a description of the +optional arguments. +If the slave argument is omitted, a name will be generated. +::safe::interpCreate always returns the interpreter name. +

    ::safe::interpInit slave ?options...?
    +This command is similar to interpCreate except it that does not +create the safe interpreter. slave must have been created by some +other means, like interp create -safe. +

    ::safe::interpConfigure slave ?options...?
    +If no options are given, returns the settings for all options for the +named safe interpreter as a list of options and their current values +for that slave. +If a single additional argument is provided, +it will return a list of 2 elements name and value where +name is the full name of that option and value the current value +for that option and the slave. +If more than two additional arguments are provided, it will reconfigure the +safe interpreter and change each and only the provided options. +See the section on OPTIONS below for options description. +Example of use: +
    # Create a new interp with the same configuration as "$i0" :
    +set i1 [eval safe::interpCreate [safe::interpConfigure $i0]]
    +# Get the current deleteHook
    +set dh [safe::interpConfigure $i0  -del]
    +# Change (only) the statics loading ok attribute of an interp
    +# and its deleteHook (leaving the rest unchanged) :
    +safe::interpConfigure $i0  -delete {foo bar} -statics 0 ;
    +

    ::safe::interpDelete slave
    +Deletes the safe interpreter and cleans up the corresponding +master interpreter data structures. +If a deleteHook script was specified for this interpreter it is +evaluated before the interpreter is deleted, with the name of the +interpreter as an additional argument. +

    ::safe::interpFindInAccessPath slave directory
    +This command finds and returns the token for the real directory +directory in the safe interpreter's current virtual access path. +It generates an error if the directory is not found. +Example of use: +
    $slave eval [list set tk_library [::safe::interpFindInAccessPath $name $tk_library]]
    +

    ::safe::interpAddToAccessPath slave directory
    +This command adds directory to the virtual path maintained for the +safe interpreter in the master, and returns the token that can be used in +the safe interpreter to obtain access to files in that directory. +If the directory is already in the virtual path, it only returns the token +without adding the directory to the virtual path again. +Example of use: +
    $slave eval [list set tk_library [::safe::interpAddToAccessPath $name $tk_library]]
    +

    ::safe::setLogCmd ?cmd arg...?
    +This command installs a script that will be called when interesting +life cycle events occur for a safe interpreter. +When called with no arguments, it returns the currently installed script. +When called with one argument, an empty string, the currently installed +script is removed and logging is turned off. +The script will be invoked with one additional argument, a string +describing the event of interest. +The main purpose is to help in debugging safe interpreters. +Using this facility you can get complete error messages while the safe +interpreter gets only generic error messages. +This prevents a safe interpreter from seeing messages about failures +and other events that might contain sensitive information such as real +directory names. +

    +Example of use: +
    ::safe::setLogCmd puts stderr
    +Below is the output of a sample session in which a safe interpreter +attempted to source a file not found in its virtual access path. +Note that the safe interpreter only received an error message saying that +the file was not found: +
    NOTICE for slave interp10 : Created
    +NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
    +NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
    +ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory
    +
    +

    +

    OPTIONS

    +The following options are common to +::safe::interpCreate, ::safe::interpInit, +and ::safe::interpConfigure. +Any option name can be abbreviated to its minimal +non-ambiguous name. +Option names are not case sensitive. +

    +

    +

    -accessPath directoryList
    +This option sets the list of directories from which the safe interpreter +can source and load files. +If this option is not specified, or if it is given as the +empty list, the safe interpreter will use the same directories as its +master for auto-loading. +See the section SECURITY below for more detail about virtual paths, +tokens and access control. +

    -statics boolean
    +This option specifies if the safe interpreter will be allowed +to load statically linked packages (like load {} Tk). +The default value is true : +safe interpreters are allowed to load statically linked packages. +

    -noStatics
    +This option is a convenience shortcut for -statics false and +thus specifies that the safe interpreter will not be allowed +to load statically linked packages. +

    -nested boolean
    +This option specifies if the safe interpreter will be allowed +to load packages into its own sub-interpreters. +The default value is false : +safe interpreters are not allowed to load packages into +their own sub-interpreters. +

    -nestedLoadOk
    +This option is a convenience shortcut for -nested true and +thus specifies the safe interpreter will be allowed +to load packages into its own sub-interpreters. +

    -deleteHook script
    +When this option is given an non empty script, it will be +evaluated in the master with the name of +the safe interpreter as an additional argument +just before actually deleting the safe interpreter. +Giving an empty value removes any currently installed deletion hook +script for that safe interpreter. +The default value ({}) is not to have any deletion call back. +

    +

    ALIASES

    +The following aliases are provided in a safe interpreter: +

    +

    +

    source fileName
    +The requested file, a Tcl source file, is sourced into the safe interpreter +if it is found. +The source alias can only source files from directories in +the virtual path for the safe interpreter. The source alias requires +the safe interpreter to +use one of the token names in its virtual path to denote the directory in +which the file to be sourced can be found. +See the section on SECURITY for more discussion of restrictions on +valid filenames. +

    load fileName
    +The requested file, a shared object file, is dynamically loaded into the +safe interpreter if it is found. +The filename must contain a token name mentioned in the virtual path for +the safe interpreter for it to be found successfully. +Additionally, the shared object file must contain a safe entry point; see +the manual page for the load command for more details. +

    file ?subCmd args...?
    +The file alias provides access to a safe subset of the subcommands of +the file command; it allows only dirname, join, +extension, root, tail, pathname and split +subcommands. For more details on what these subcommands do see the manual +page for the file command. +

    encoding ?subCmd args...?
    +The enconding alias provides access to a safe subset of the +subcommands of the encoding command; it disallows setting of +the system encoding, but allows all other subcommands including +system to check the current encoding. +

    exit
    +The calling interpreter is deleted and its computation is stopped, but the +Tcl process in which this interpreter exists is not terminated. + +

    +

    SECURITY

    +The Safe Base does not attempt to completely prevent annoyance and +denial of service attacks. These forms of attack prevent the +application or user from temporarily using the computer to perform +useful work, for example by consuming all available CPU time or +all available screen real estate. +These attacks, while aggravating, are deemed to be of lesser importance +in general than integrity and privacy attacks that the Safe Base +is to prevent. +

    +The commands available in a safe interpreter, in addition to +the safe set as defined in interp manual page, are mediated aliases +for source, load, exit, and safe subsets of +file and encoding. The safe interpreter can also auto-load +code and it can request that packages be loaded. +

    +Because some of these commands access the local file system, there is a +potential for information leakage about its directory structure. +To prevent this, commands that take file names as arguments in a safe +interpreter use tokens instead of the real directory names. +These tokens are translated to the real directory name while a request to, +e.g., source a file is mediated by the master interpreter. +This virtual path system is maintained in the master interpreter for each safe +interpreter created by ::safe::interpCreate or initialized by +::safe::interpInit and +the path maps tokens accessible in the safe interpreter into real path +names on the local file system thus preventing safe interpreters +from gaining knowledge about the +structure of the file system of the host on which the interpreter is +executing. +The only valid file names arguments +for the source and load aliases provided to the slave +are path in the form of +[file join token filename] (ie, when using the +native file path formats: token/filename +on Unix, token\filename on Windows, +and token:filename on the Mac), +where token is representing one of the directories +of the accessPath list and filename is +one file in that directory (no sub directories access are allowed). +

    +When a token is used in a safe interpreter in a request to source or +load a file, the token is checked and +translated to a real path name and the file to be +sourced or loaded is located on the file system. +The safe interpreter never gains knowledge of the actual path name under +which the file is stored on the file system. +

    +To further prevent potential information leakage from sensitive files that +are accidentally included in the set of files that can be sourced by a safe +interpreter, the source alias restricts access to files +meeting the following constraints: the file name must +fourteen characters or shorter, must not contain more than one dot ("."), +must end up with the extension .tcl or be called tclIndex. +

    +Each element of the initial access path +list will be assigned a token that will be set in +the slave auto_path and the first element of that list will be set as +the tcl_library for that slave. +

    +If the access path argument is not given or is the empty list, +the default behavior is to let the slave access the same packages +as the master has access to (Or to be more precise: +only packages written in Tcl (which by definition can't be dangerous +as they run in the slave interpreter) and C extensions that +provides a Safe_Init entry point). For that purpose, the master's +auto_path will be used to construct the slave access path. +In order that the slave successfully loads the Tcl library files +(which includes the auto-loading mechanism itself) the tcl_library will be +added or moved to the first position if necessary, in the +slave access path, so the slave +tcl_library will be the same as the master's (its real +path will still be invisible to the slave though). +In order that auto-loading works the same for the slave and +the master in this by default case, the first-level +sub directories of each directory in the master auto_path will +also be added (if not already included) to the slave access path. +You can always specify a more +restrictive path for which sub directories will never be searched by +explicitly specifying your directory list with the -accessPath flag +instead of relying on this default mechanism. +

    +When the accessPath is changed after the first creation or +initialization (ie through interpConfigure -accessPath list), +an auto_reset is automatically evaluated in the safe interpreter +to synchronize its auto_index with the new token list. + +

    SEE ALSO

    +interp, library, load, package, source, unknown +

    KEYWORDS

    +alias, auto-loading, auto_mkindex, load, master interpreter, safe +interpreter, slave interpreter, source +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/scan.htm b/hlp/en/tcl/scan.htm new file mode 100644 index 0000000..8cbe76a --- /dev/null +++ b/hlp/en/tcl/scan.htm @@ -0,0 +1,197 @@ +Tcl Built-In Commands - scan manual page +
    +
    NAME +
    scan - Parse string using conversion specifiers in the style of sscanf
    +
    SYNOPSIS +
    +
    scan string format ?varName varName ...? +
    +
    INTRODUCTION +
    DETAILS ON SCANNING +
    +
    d +
    o +
    x +
    u +
    i +
    c +
    s +
    e or f or g +
    [chars] +
    [^chars] +
    n +
    +
    DIFFERENCES FROM ANSI SSCANF +
    +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +scan - Parse string using conversion specifiers in the style of sscanf +

    SYNOPSIS

    +scan string format ?varName varName ...?
    +

    INTRODUCTION

    +This command parses fields from an input string in the same fashion as the +ANSI C sscanf procedure and returns a count of the number of +conversions performed, or -1 if the end of the input string is reached +before any conversions have been performed. String gives the input +to be parsed and format indicates how to parse it, using % +conversion specifiers as in sscanf. Each varName gives the +name of a variable; when a field is scanned from string the result is +converted back into a string and assigned to the corresponding variable. +If no varName variables are specified, then scan works in an +inline manner, returning the data that would otherwise be stored in the +variables as a list. In the inline case, an empty string is returned when +the end of the input string is reached before any conversions have been +performed. + +

    DETAILS ON SCANNING

    +Scan operates by scanning string and format together. +If the next character in format is a blank or tab then it +matches any number of white space characters in string (including +zero). +Otherwise, if it isn't a % character then it +must match the next character of string. +When a % is encountered in format, it indicates +the start of a conversion specifier. +A conversion specifier contains up to four fields after the %: +a *, which indicates that the converted value is to be discarded +instead of assigned to a variable; a XPG3 position specifier; a number +indicating a maximum field width; and a conversion character. +All of these fields are optional except for the conversion character. +The fields that are present must appear in the order given above. +

    +When scan finds a conversion specifier in format, it +first skips any white-space characters in string (unless the +specifier is [ or c). +Then it converts the next input characters according to the +conversion specifier and stores the result in the variable given +by the next argument to scan. +

    +If the % is followed by a decimal number and a $, as in +``%2$d'', then the variable to use is not taken from the next +sequential argument. Instead, it is taken from the argument indicated +by the number, where 1 corresponds to the first varName. If +there are any positional specifiers in format then all of the +specifiers must be positional. Every varName on the argument +list must correspond to exactly one conversion specifier or an error +is generated, or in the inline case, any position can be specified +at most once and the empty positions will be filled in with empty strings. +

    +The following conversion characters are supported: +

    +

    +

    d
    +The input field must be a decimal integer. +It is read in and the value is stored in the variable as a decimal string. +

    o
    +The input field must be an octal integer. It is read in and the +value is stored in the variable as a decimal string. +If the value exceeds MAX_INT (017777777777 on platforms using 32-bit +integers), it will be truncated to a signed integer. Hence, 037777777777 +will appear as -1 on a 32-bit machine. +

    x
    +The input field must be a hexadecimal integer. It is read in +and the value is stored in the variable as a decimal string. +If the value exceeds MAX_INT (0x7FFFFFFF on platforms using 32-bit +integers), it will be truncated to a signed integer. Hence, 0xFFFFFFFF +will appear as -1 on a 32-bit machine. +

    u
    +The input field must be a decimal integer. The value is stored in the +variable as an unsigned decimal integer string. +

    i
    +The input field must be an integer. The base (i.e. decimal, octal, or +hexadecimal) is determined in the same fashion as described in +expr. The value is stored in the variable as a decimal string. +

    c
    +A single character is read in and its binary value is stored in +the variable as a decimal string. +Initial white space is not skipped in this case, so the input +field may be a white-space character. +This conversion is different from the ANSI standard in that the +input field always consists of a single character and no field +width may be specified. +

    s
    +The input field consists of all the characters up to the next +white-space character; the characters are copied to the variable. +

    e or f or g
    +The input field must be a floating-point number consisting +of an optional sign, a string of decimal digits possibly +containing a decimal point, and an optional exponent consisting +of an e or E followed by an optional sign and a string of +decimal digits. +It is read in and stored in the variable as a floating-point string. +

    [chars]
    +The input field consists of any number of characters in +chars. +The matching string is stored in the variable. +If the first character between the brackets is a ] then +it is treated as part of chars rather than the closing +bracket for the set. +If chars +contains a sequence of the form a-b then any +character between a and b (inclusive) will match. +If the first or last character between the brackets is a -, then +it is treated as part of chars rather than indicating a range. +

    [^chars]
    +The input field consists of any number of characters not in +chars. +The matching string is stored in the variable. +If the character immediately following the ^ is a ] then it is +treated as part of the set rather than the closing bracket for +the set. +If chars +contains a sequence of the form a-b then any +character between a and b (inclusive) will be excluded +from the set. +If the first or last character between the brackets is a -, then +it is treated as part of chars rather than indicating a range. +

    n
    +No input is consumed from the input string. Instead, the total number +of chacters scanned from the input string so far is stored in the variable. +

    +

    +The number of characters read from the input for a conversion is the +largest number that makes sense for that particular conversion (e.g. +as many decimal digits as possible for %d, as +many octal digits as possible for %o, and so on). +The input field for a given conversion terminates either when a +white-space character is encountered or when the maximum field +width has been reached, whichever comes first. +If a * is present in the conversion specifier +then no variable is assigned and the next scan argument is not consumed. + +

    DIFFERENCES FROM ANSI SSCANF

    +The behavior of the scan command is the same as the behavior of +the ANSI C sscanf procedure except for the following differences: +

    +

    +

    [1]
    +%p conversion specifier is not currently supported. +

    [2]
    +For %c conversions a single character value is +converted to a decimal string, which is then assigned to the +corresponding varName; +no field width may be specified for this conversion. +

    [3]
    +The l, h, and L modifiers are ignored; integer +values are always converted as if there were no modifier present +and real values are always converted as if the l modifier +were present (i.e. type double is used for the internal +representation). +

    [4]
    +If the end of the input string is reached before any conversions have been +performed and no variables are given, and empty string is returned. + +

    +

    SEE ALSO

    +format, sscanf +

    KEYWORDS

    +conversion specifier, parse, scan +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 2000 Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/seek.htm b/hlp/en/tcl/seek.htm new file mode 100644 index 0000000..612428a --- /dev/null +++ b/hlp/en/tcl/seek.htm @@ -0,0 +1,51 @@ +Tcl Built-In Commands - seek manual page +

    NAME

    +seek - Change the access position for an open channel +

    SYNOPSIS

    +seek channelId offset ?origin?
    +

    DESCRIPTION

    +Changes the current access position for channelId. +ChannelId must be a channel identifier such as returned from a +previous invocation of open or socket. +The offset and origin +arguments specify the position at which the next read or write will occur +for channelId. Offset must be an integer (which may be +negative) and origin must be one of the following: +

    +

    +

    start
    +The new access position will be offset bytes from the start +of the underlying file or device. +

    current
    +The new access position will be offset bytes from the current +access position; a negative offset moves the access position +backwards in the underlying file or device. +

    end
    +The new access position will be offset bytes from the end of +the file or device. A negative offset places the access position +before the end of file, and a positive offset places the access +position after the end of file. +

    +

    +The origin argument defaults to start. +

    +The command flushes all buffered output for the channel before the command +returns, even if the channel is in nonblocking mode. +It also discards any buffered and unread input. +This command returns an empty string. +An error occurs if this command is applied to channels whose underlying +file or device does not support seeking. +

    +Note that offset values are byte offsets, not character +offsets. Both seek and tell operate in terms of bytes, +not characters, unlike read. + +

    SEE ALSO

    +file, open, close, gets, tell +

    KEYWORDS

    +access position, file, seek +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/set.htm b/hlp/en/tcl/set.htm new file mode 100644 index 0000000..744b91f --- /dev/null +++ b/hlp/en/tcl/set.htm @@ -0,0 +1,40 @@ +Built-In Commands - set manual page +

    NAME

    +set - Read and write variables +

    SYNOPSIS

    +set varName ?value?
    +

    DESCRIPTION

    +Returns the value of variable varName. +If value is specified, then set +the value of varName to value, creating a new variable +if one doesn't already exist, and return its value. +If varName contains an open parenthesis and ends with a +close parenthesis, then it refers to an array element: the characters +before the first open parenthesis are the name of the array, +and the characters between the parentheses are the index within the array. +Otherwise varName refers to a scalar variable. +Normally, varName is unqualified +(does not include the names of any containing namespaces), +and the variable of that name in the current namespace is read or written. +If varName includes namespace qualifiers +(in the array name if it refers to an array element), +the variable in the specified namespace is read or written. +

    +If no procedure is active, +then varName refers to a namespace variable +(global variable if the current namespace is the global namespace). +If a procedure is active, then varName refers to a parameter +or local variable of the procedure unless the global command +was invoked to declare varName to be global, +or unless a variable command +was invoked to declare varName to be a namespace variable. + +

    SEE ALSO

    +expr, proc, trace, unset +

    KEYWORDS

    +read, write, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/socket.htm b/hlp/en/tcl/socket.htm new file mode 100644 index 0000000..a1a1bbe --- /dev/null +++ b/hlp/en/tcl/socket.htm @@ -0,0 +1,147 @@ +Tcl Built-In Commands - socket manual page +
    +
    NAME +
    socket - Open a TCP network connection
    +
    SYNOPSIS +
    +
    socket ?options? host port +
    socket -server command ?options? port +
    +
    DESCRIPTION +
    CLIENT SOCKETS +
    +
    -myaddr addr +
    -myport port +
    -async +
    +
    SERVER SOCKETS +
    +
    -myaddr addr +
    +
    CONFIGURATION OPTIONS +
    +
    -error +
    -sockname +
    -peername +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +socket - Open a TCP network connection +

    SYNOPSIS

    +socket ?options? host port
    +socket-server command ?options? port
    +

    DESCRIPTION

    +This command opens a network socket and returns a channel +identifier that may be used in future invocations of commands like +read, puts and flush. +At present only the TCP network protocol is supported; future +releases may include support for additional protocols. +The socket command may be used to open either the client or +server side of a connection, depending on whether the -server +switch is specified. + +

    CLIENT SOCKETS

    +If the -server option is not specified, then the client side of a +connection is opened and the command returns a channel identifier +that can be used for both reading and writing. +Port and host specify a port +to connect to; there must be a server accepting connections on +this port. Port is an integer port number and host +is either a domain-style name such as www.sunlabs.com or +a numerical IP address such as 127.0.0.1. +Use localhost to refer to the host on which the command is invoked. +

    +The following options may also be present before host +to specify additional information about the connection: +

    +

    +

    -myaddr addr
    +Addr gives the domain-style name or numerical IP address of +the client-side network interface to use for the connection. +This option may be useful if the client machine has multiple network +interfaces. If the option is omitted then the client-side interface +will be chosen by the system software. +

    -myport port
    +Port specifies an integer port number to use for the client's +side of the connection. If this option is omitted, the client's +port number will be chosen at random by the system software. +

    -async
    +The -async option will cause the client socket to be connected +asynchronously. This means that the socket will be created immediately but +may not yet be connected to the server, when the call to socket +returns. When a gets or flush is done on the socket before the +connection attempt succeeds or fails, if the socket is in blocking mode, the +operation will wait until the connection is completed or fails. If the +socket is in nonblocking mode and a gets or flush is done on +the socket before the connection attempt succeeds or fails, the operation +returns immediately and fblocked on the socket returns 1. + +

    +

    SERVER SOCKETS

    +If the -server option is specified then the new socket +will be a server for the port given by port. +Tcl will automatically accept connections to the given port. +For each connection Tcl will create a new channel that may be used to +communicate with the client. Tcl then invokes command +with three additional arguments: the name of the new channel, the +address, in network address notation, of the client's host, and +the client's port number. +

    +The following additional option may also be specified before host: +

    +

    +

    -myaddr addr
    +Addr gives the domain-style name or numerical IP address of +the server-side network interface to use for the connection. +This option may be useful if the server machine has multiple network +interfaces. If the option is omitted then the server socket is bound +to the special address INADDR_ANY so that it can accept connections from +any interface. +

    +

    +Server channels cannot be used for input or output; their sole use is to +accept new client connections. The channels created for each incoming +client connection are opened for input and output. Closing the server +channel shuts down the server so that no new connections will be +accepted; however, existing connections will be unaffected. +

    +Server sockets depend on the Tcl event mechanism to find out when +new connections are opened. If the application doesn't enter the +event loop, for example by invoking the vwait command or +calling the C procedure Tcl_DoOneEvent, then no connections +will be accepted. + +

    CONFIGURATION OPTIONS

    +The fconfigure command can be used to query several readonly +configuration options for socket channels: +

    +

    +

    -error
    +This option gets the current error status of the given socket. This +is useful when you need to determine if an asynchronous connect +operation succeeded. If there was an error, the error message is +returned. If there was no error, an empty string is returned. +

    -sockname
    +This option returns a list of three elements, the address, the host name +and the port number for the socket. If the host name cannot be computed, +the second element is identical to the address, the first element of the +list. +

    -peername
    +This option is not supported by server sockets. For client and accepted +sockets, this option returns a list of three elements; these are the +address, the host name and the port to which the peer socket is connected +or bound. If the host name cannot be computed, the second element of the +list is identical to the address, its first element. +

    +

    +

    SEE ALSO

    +flush, open, read +

    KEYWORDS

    +bind, channel, connection, domain name, host, network address, socket, tcp +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1998-1999 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/source.htm b/hlp/en/tcl/source.htm new file mode 100644 index 0000000..030b5dd --- /dev/null +++ b/hlp/en/tcl/source.htm @@ -0,0 +1,32 @@ +Built-In Commands - source manual page +

    NAME

    +source - Evaluate a file or resource as a Tcl script +

    SYNOPSIS

    +source fileName
    +source-rsrc resourceName ?fileName?
    +source-rsrcid resourceId ?fileName?
    +

    DESCRIPTION

    +This command takes the contents of the specified file or resource +and passes it to the Tcl interpreter as a text script. The return +value from source is the return value of the last command +executed in the script. If an error occurs in evaluating the contents +of the script then the source command will return that error. +If a return command is invoked from within the script then the +remainder of the file will be skipped and the source command +will return normally with the result from the return command. + +The -rsrc and -rsrcid forms of this command are only +available on Macintosh computers. These versions of the command +allow you to source a script from a TEXT resource. You may specify +what TEXT resource to source by either name or id. By default Tcl +searches all open resource files, which include the current +application and any loaded C extensions. Alternatively, you may +specify the fileName where the TEXT resource can be found. + +

    KEYWORDS

    +file, script +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/split.htm b/hlp/en/tcl/split.htm new file mode 100644 index 0000000..ee4e8d5 --- /dev/null +++ b/hlp/en/tcl/split.htm @@ -0,0 +1,32 @@ +Built-In Commands - split manual page +

    NAME

    +split - Split a string into a proper Tcl list +

    SYNOPSIS

    +split string ?splitChars?
    +

    DESCRIPTION

    +Returns a list created by splitting string at each character +that is in the splitChars argument. +Each element of the result list will consist of the +characters from string that lie between instances of the +characters in splitChars. +Empty list elements will be generated if string contains +adjacent characters in splitChars, or if the first or last +character of string is in splitChars. +If splitChars is an empty string then each character of +string becomes a separate element of the result list. +SplitChars defaults to the standard white-space characters. +For example, +
    split "comp.unix.misc" .
    +returns "comp unix misc" and +
    split "Hello world" {}
    +returns "H e l l o { } w o r l d". + +

    SEE ALSO

    +join, list, string +

    KEYWORDS

    +list, split, string +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/string.htm b/hlp/en/tcl/string.htm new file mode 100644 index 0000000..0dea2f8 --- /dev/null +++ b/hlp/en/tcl/string.htm @@ -0,0 +1,338 @@ +Tcl Built-In Commands - string manual page +
    +
    NAME +
    string - Manipulate strings
    +
    SYNOPSIS +
    +
    string option arg ?arg ...? +
    +
    DESCRIPTION +
    +
    string bytelength string +
    string compare ?-nocase? ?-length int? string1 string2 +
    string equal ?-nocase? ?-length int? string1 string2 +
    string first string1 string2 ?startIndex? +
    string index string charIndex +
    +
    integer +
    end +
    end-integer +
    +
    string is class ?-strict? ?-failindex varname? string +
    +
    alnum +
    alpha +
    ascii +
    boolean +
    control +
    digit +
    double +
    false +
    graph +
    integer +
    lower +
    print +
    punct +
    space +
    true +
    upper +
    wordchar +
    xdigit +
    +
    string last string1 string2 ?startIndex? +
    string length string +
    string map ?-nocase? charMap string +
    string match ?-nocase? pattern string +
    +
    * +
    ? +
    [chars] +
    \x +
    +
    string range string first last +
    string repeat string count +
    string replace string first last ?newstring? +
    string tolower string ?first? ?last? +
    string totitle string ?first? ?last? +
    string toupper string ?first? ?last? +
    string trim string ?chars? +
    string trimleft string ?chars? +
    string trimright string ?chars? +
    string wordend string charIndex +
    string wordstart string charIndex +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +string - Manipulate strings +

    SYNOPSIS

    +string option arg ?arg ...?
    +

    DESCRIPTION

    +Performs one of several string operations, depending on option. +The legal options (which may be abbreviated) are: +

    +

    +

    string bytelength string
    +Returns a decimal string giving the number of bytes used to represent +string in memory. Because UTF-8 uses one to three bytes to +represent Unicode characters, the byte length will not be the same as +the character length in general. The cases where a script cares about +the byte length are rare. In almost all cases, you should use the +string length operation. Refer to the Tcl_NumUtfChars +manual entry for more details on the UTF-8 representation. +

    string compare ?-nocase? ?-length int? string1 string2
    +Perform a character-by-character comparison of strings string1 and +string2. Returns +-1, 0, or 1, depending on whether string1 is lexicographically +less than, equal to, or greater than string2. +If -length is specified, then only the first length characters +are used in the comparison. If -length is negative, it is +ignored. If -nocase is specified, then the strings are +compared in a case-insensitive manner. +

    string equal ?-nocase? ?-length int? string1 string2
    +Perform a character-by-character comparison of strings +string1 and string2. Returns 1 if string1 and +string2 are identical, or 0 when not. If -length is +specified, then only the first length characters are used in the +comparison. If -length is negative, it is ignored. If +-nocase is specified, then the strings are compared in a +case-insensitive manner. +

    string first string1 string2 ?startIndex?
    +Search string2 for a sequence of characters that exactly match +the characters in string1. If found, return the index of the +first character in the first such match within string2. If not +found, return -1. +If startIndex is specified (in any of the forms accepted by the +index method), then the search is constrained to start with the +character in string2 specified by the index. For example, +
    string first a 0a23456789abcdef 5
    +will return 10, but +
    string first a 0123456789abcdef 11
    +will return -1. +

    string index string charIndex
    +Returns the charIndex'th character of the string +argument. A charIndex of 0 corresponds to the first +character of the string. +charIndex may be specified as +follows: +

    +

    +

    integer
    +The char specified at this integral index +

    end
    +The last char of the string. +

    end-integer
    +The last char of the string minus the specified integer +offset (e.g. end-1 would refer to the "c" in "abcd"). +

    If charIndex is less than 0 or greater than +or equal to the length of the string then an empty string is +returned.

    +

    +

    string is class ?-strict? ?-failindex varname? string
    +Returns 1 if string is a valid member of the specified character +class, otherwise returns 0. If -strict is specified, then an +empty string returns 0, otherwise and empty string will return 1 on +any class. If -failindex is specified, then if the function +returns 0, the index in the string where the class was no longer valid +will be stored in the variable named varname. The varname +will not be set if the function returns 1. The following character classes +are recognized (the class name can be abbreviated): +

    +

    +

    alnum
    +Any Unicode alphabet or digit character. +

    alpha
    +Any Unicode alphabet character. +

    ascii
    +Any character with a value less than \u0080 (those that +are in the 7-bit ascii range). +

    boolean
    +Any of the forms allowed to Tcl_GetBoolean. +

    control
    +Any Unicode control character. +

    digit
    +Any Unicode digit character. Note that this includes characters +outside of the [0-9] range. +

    double
    +Any of the valid forms for a double in Tcl, with optional surrounding +whitespace. In case of under/overflow in the value, 0 is returned +and the varname will contain -1. +

    false
    +Any of the forms allowed to Tcl_GetBoolean where the value is false. +

    graph
    +Any Unicode printing character, except space. +

    integer
    +Any of the valid forms for an integer in Tcl, with optional surrounding +whitespace. In case of under/overflow in the value, 0 is returned +and the varname will contain -1. +

    lower
    +Any Unicode lower case alphabet character. +

    print
    +Any Unicode printing character, including space. +

    punct
    +Any Unicode punctuation character. +

    space
    +Any Unicode space character. +

    true
    +Any of the forms allowed to Tcl_GetBoolean where the value is true. +

    upper
    +Any upper case alphabet character in the Unicode character set. +

    wordchar
    +Any Unicode word character. That is any alphanumeric character, +and any Unicode connector punctuation characters (e.g. underscore). +

    xdigit
    +Any hexadecimal digit character ([0-9A-Fa-f]). +

    In the case of boolean, true and false, if the +function will return 0, then the varname will always be set to 0, +due to the varied nature of a valid boolean value.

    +

    +

    string last string1 string2 ?startIndex?
    +Search string2 for a sequence of characters that exactly match +the characters in string1. If found, return the index of the +first character in the last such match within string2. If there +is no match, then return -1. +If startIndex is specified (in any of the forms accepted by the +index method), then only the characters in string2 at or before the +specified startIndex will be considered by the search. For example, +
    string last a 0a23456789abcdef 15
    +will return 10, but +
    string last a 0a23456789abcdef 9
    +will return 1. +

    string length string
    +Returns a decimal string giving the number of characters in +string. Note that this is not necessarily the same as the +number of bytes used to store the string. +

    string map ?-nocase? charMap string
    +Replaces characters in string based on the key-value pairs in +charMap. charMap is a list of key value key value ... +as in the form returned by array get. Each instance of a +key in the string will be replaced with its corresponding value. If +-nocase is specified, then matching is done without regard to +case differences. Both key and value may be multiple +characters. Replacement is done in an ordered manner, so the key appearing +first in the list will be checked first, and so on. string is +only iterated over once, so earlier key replacements will have no +affect for later key matches. For example, +
    string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
    +will return the string 01321221. +

    string match ?-nocase? pattern string
    +See if pattern matches string; return 1 if it does, 0 +if it doesn't. +If -nocase is specified, then the pattern attempts to match +against the string in a case insensitive manner. +For the two strings to match, their contents +must be identical except that the following special sequences +may appear in pattern: +

    +

    +

    *
    +Matches any sequence of characters in string, +including a null string. +

    ?
    +Matches any single character in string. +

    [chars]
    +Matches any character in the set given by chars. If a sequence +of the form +x-y appears in chars, then any character +between x and y, inclusive, will match. +When used with -nocase, the end points of the range are converted +to lower case first. Whereas {[A-z]} matches '_' when matching +case-sensitively ('_' falls between the 'Z' and 'a'), with -nocase +this is considered like {[A-Za-z]} (and probably what was meant in the +first place). +

    \x
    +Matches the single character x. This provides a way of +avoiding the special interpretation of the characters +*?[]\ in pattern. +

    +

    string range string first last
    +Returns a range of consecutive characters from string, starting +with the character whose index is first and ending with the +character whose index is last. An index of 0 refers to the +first character of the string. first and last may be +specified as for the index method. +If first is less than zero then it is treated as if it were zero, and +if last is greater than or equal to the length of the string then +it is treated as if it were end. If first is greater than +last then an empty string is returned. +

    string repeat string count
    +Returns string repeated count number of times. +

    string replace string first last ?newstring?
    +Removes a range of consecutive characters from string, starting +with the character whose index is first and ending with the +character whose index is last. An index of 0 refers to the +first character of the string. First and last may be +specified as for the index method. If newstring is +specified, then it is placed in the removed character range. +If first is less than zero then it is treated as if it were zero, and +if last is greater than or equal to the length of the string then +it is treated as if it were end. If first is greater than +last or the length of the initial string, or last is less +than 0, then the initial string is returned untouched. +

    string tolower string ?first? ?last?
    +Returns a value equal to string except that all upper (or title) case +letters have been converted to lower case. If first is specified, it +refers to the first char index in the string to start modifying. If +last is specified, it refers to the char index in the string to stop +at (inclusive). first and last may be +specified as for the index method. +

    string totitle string ?first? ?last?
    +Returns a value equal to string except that the first character +in string is converted to its Unicode title case variant (or upper +case if there is no title case variant) and the rest of the string is +converted to lower case. If first is specified, it +refers to the first char index in the string to start modifying. If +last is specified, it refers to the char index in the string to stop +at (inclusive). first and last may be +specified as for the index method. +

    string toupper string ?first? ?last?
    +Returns a value equal to string except that all lower (or title) case +letters have been converted to upper case. If first is specified, it +refers to the first char index in the string to start modifying. If +last is specified, it refers to the char index in the string to stop +at (inclusive). first and last may be specified as for the +index method. +

    string trim string ?chars?
    +Returns a value equal to string except that any leading +or trailing characters from the set given by chars are +removed. +If chars is not specified then white space is removed +(spaces, tabs, newlines, and carriage returns). +

    string trimleft string ?chars?
    +Returns a value equal to string except that any +leading characters from the set given by chars are +removed. +If chars is not specified then white space is removed +(spaces, tabs, newlines, and carriage returns). +

    string trimright string ?chars?
    +Returns a value equal to string except that any +trailing characters from the set given by chars are +removed. +If chars is not specified then white space is removed +(spaces, tabs, newlines, and carriage returns). +

    string wordend string charIndex
    +Returns the index of the character just after the last one in the word +containing character charIndex of string. charIndex +may be specified as for the index method. A word is +considered to be any contiguous range of alphanumeric (Unicode letters +or decimal digits) or underscore (Unicode connector punctuation) +characters, or any single character other than these. +

    string wordstart string charIndex
    +Returns the index of the first character in the word containing +character charIndex of string. charIndex may be +specified as for the index method. A word is considered to be any +contiguous range of alphanumeric (Unicode letters or decimal digits) +or underscore (Unicode connector punctuation) characters, or any +single character other than these. + +

    +

    SEE ALSO

    +expr, list +

    KEYWORDS

    +case conversion, compare, index, match, pattern, string, word, equal, ctype +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/subst.htm b/hlp/en/tcl/subst.htm new file mode 100644 index 0000000..abe6659 --- /dev/null +++ b/hlp/en/tcl/subst.htm @@ -0,0 +1,38 @@ +Tcl Built-In Commands - subst manual page +

    NAME

    +subst - Perform backslash, command, and variable substitutions +

    SYNOPSIS

    +subst ?-nobackslashes? ?-nocommands? ?-novariables? string
    +

    DESCRIPTION

    +This command performs variable substitutions, command substitutions, +and backslash substitutions on its string argument and +returns the fully-substituted result. +The substitutions are performed in exactly the same way as for +Tcl commands. +As a result, the string argument is actually substituted twice, +once by the Tcl parser in the usual fashion for Tcl commands, and +again by the subst command. +

    +If any of the -nobackslashes, -nocommands, or +-novariables are specified, then the corresponding substitutions +are not performed. +For example, if -nocommands is specified, no command substitution +is performed: open and close brackets are treated as ordinary characters +with no special interpretation. +

    +Note: when it performs its substitutions, subst does not +give any special treatment to double quotes or curly braces. For +example, the script +

    set a 44
    +subst {xyz {$a}}
    +returns ``xyz {44}'', not ``xyz {$a}''. + +

    SEE ALSO

    +eval +

    KEYWORDS

    +backslash substitution, command substitution, variable substitution +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/switch.htm b/hlp/en/tcl/switch.htm new file mode 100644 index 0000000..7edab16 --- /dev/null +++ b/hlp/en/tcl/switch.htm @@ -0,0 +1,116 @@ +Tcl Built-In Commands - switch manual page +
    +
    NAME +
    switch - Evaluate one of several scripts, depending on a given value
    +
    SYNOPSIS +
    +
    switch ?options? string pattern body ?pattern body ...? +
    switch ?options? string {pattern body ?pattern body ...?} +
    +
    DESCRIPTION +
    +
    -exact +
    -glob +
    -regexp +
    - - +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +switch - Evaluate one of several scripts, depending on a given value +

    SYNOPSIS

    +switch ?options? string pattern body ?pattern body ...?
    +switch ?options? string {pattern body ?pattern body ...?}
    +

    DESCRIPTION

    +The switch command matches its string argument against each of +the pattern arguments in order. +As soon as it finds a pattern that matches string it +evaluates the following body argument by passing it recursively +to the Tcl interpreter and returns the result of that evaluation. +If the last pattern argument is default then it matches +anything. +If no pattern argument +matches string and no default is given, then the switch +command returns an empty string. +

    +If the initial arguments to switch start with - then +they are treated as options. The following options are +currently supported: +

    +

    +

    -exact
    +Use exact matching when comparing string to a pattern. This +is the default. +

    -glob
    +When matching string to the patterns, use glob-style matching +(i.e. the same as implemented by the string match command). +

    -regexp
    +When matching string to the patterns, use regular +expression matching +(as described in the re_syntax reference page). +

    - -
    +Marks the end of options. The argument following this one will +be treated as string even if it starts with a -. +

    +

    +Two syntaxes are provided for the pattern and body arguments. +The first uses a separate argument for each of the patterns and commands; +this form is convenient if substitutions are desired on some of the +patterns or commands. +The second form places all of the patterns and commands together into +a single argument; the argument must have proper list structure, with +the elements of the list being the patterns and commands. +The second form makes it easy to construct multi-line switch commands, +since the braces around the whole list make it unnecessary to include a +backslash at the end of each line. +Since the pattern arguments are in braces in the second form, +no command or variable substitutions are performed on them; this makes +the behavior of the second form different than the first form in some +cases. +

    +If a body is specified as ``-'' it means that the body +for the next pattern should also be used as the body for this +pattern (if the next pattern also has a body of ``-'' +then the body after that is used, and so on). +This feature makes it possible to share a single body among +several patterns. +

    +Beware of how you place comments in switch commands. Comments +should only be placed inside the execution body of one of the +patterns, and not intermingled with the patterns. +

    +Below are some examples of switch commands: +

    switch abc a - b {format 1} abc {format 2} default {format 3}
    +will return 2, +
    switch -regexp aaab {
    +	^a.*b$ -
    +	b {format 1}
    +	a* {format 2}
    +	default {format 3}
    +}
    +will return 1, and +
    switch xyz {
    +	a
    +		-
    +	b
    +		{
    +		# Correct Comment Placement
    +		format 1
    +	}
    +	a*
    +		{format 2}
    +	default
    +		{format 3}
    +}
    +will return 3. + +

    SEE ALSO

    +for, if, regexp +

    KEYWORDS

    +switch, match, regular expression +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/tcl.toc.html b/hlp/en/tcl/tcl.toc.html new file mode 100644 index 0000000..1c4e68f --- /dev/null +++ b/hlp/en/tcl/tcl.toc.html @@ -0,0 +1,110 @@ +Tk Commands +Http
    +continue
    +history
    +pid
    +switch
    +Safe Base
    +dde
    +if
    +pkg::create
    +tcl_endOfWord
    +Tcl
    +encoding
    +incr
    +pkg_mkIndex
    +tcl_findLibrary
    +Tcltest
    +eof
    +info
    +proc
    +tcl_startOfNextWord
    +after
    +error
    +interp
    +puts
    +tcl_startOfPreviousWord
    +append
    +eval
    +join
    +pwd
    +tcl_wordBreakAfter
    +array
    +exec
    +lappend
    +re_syntax
    +tcl_wordBreakBefore
    +auto_execok
    +exit
    +lindex
    +read
    +tclvars
    +auto_import
    +expr
    +linsert
    +regexp
    +tell
    +auto_load
    +fblocked
    +list
    +registry
    +time
    +auto_mkindex
    +fconfigure
    +llength
    +regsub
    +trace
    +auto_mkindex_old
    +fcopy
    +load
    +rename
    +unknown
    +auto_qualify
    +file
    +lrange
    +resource
    +unset
    +auto_reset
    +fileevent
    +lreplace
    +return
    +update
    +bgerror
    +filename
    +lsearch
    +scan
    +uplevel
    +binary
    +flush
    +lsort
    +seek
    +upvar
    +break
    +for
    +memory
    +set
    +variable
    +catch
    +foreach
    +msgcat
    +socket
    +vwait
    +cd
    +format
    +namespace
    +source
    +while
    +clock
    +gets
    +open
    +split
    +close
    +glob
    +package
    +string
    +concat
    +global
    +parray
    +subst
    + + diff --git a/hlp/en/tcl/tclsh.htm b/hlp/en/tcl/tclsh.htm new file mode 100644 index 0000000..44f372c --- /dev/null +++ b/hlp/en/tcl/tclsh.htm @@ -0,0 +1,126 @@ +Applications - tclsh manual page +
    +
    NAME +
    tclsh - Simple shell containing Tcl interpreter
    +
    SYNOPSIS +
    +
    tclsh ?fileName arg arg ...? +
    +
    DESCRIPTION +
    SCRIPT FILES +
    VARIABLES +
    +
    argc +
    argv +
    argv0 +
    tcl_interactive +
    +
    PROMPTS +
    KEYWORDS +

    +

    NAME

    +tclsh - Simple shell containing Tcl interpreter +

    SYNOPSIS

    +tclsh ?fileName arg arg ...?
    +

    DESCRIPTION

    +Tclsh is a shell-like application that reads Tcl commands +from its standard input or from a file and evaluates them. +If invoked with no arguments then it runs interactively, reading +Tcl commands from standard input and printing command results and +error messages to standard output. +It runs until the exit command is invoked or until it +reaches end-of-file on its standard input. +If there exists a file .tclshrc (or tclshrc.tcl on +the Windows platforms) in the home directory of +the user, tclsh evaluates the file as a Tcl script +just before reading the first command from standard input. + +

    SCRIPT FILES

    +If tclsh is invoked with arguments then the first argument +is the name of a script file and any additional arguments +are made available to the script as variables (see below). +Instead of reading commands from standard input tclsh will +read Tcl commands from the named file; tclsh will exit +when it reaches the end of the file. +There is no automatic evaluation of .tclshrc in this +case, but the script file can always source it if desired. +

    +If you create a Tcl script in a file whose first line is +

    #!/usr/local/bin/tclsh
    +then you can invoke the script file directly from your shell if +you mark the file as executable. +This assumes that tclsh has been installed in the default +location in /usr/local/bin; if it's installed somewhere else +then you'll have to modify the above line to match. +Many UNIX systems do not allow the #! line to exceed about +30 characters in length, so be sure that the tclsh +executable can be accessed with a short file name. +

    +An even better approach is to start your script files with the +following three lines: +

    #!/bin/sh
    +# the next line restarts using tclsh \
    +exec tclsh "$0" "$@"
    +This approach has three advantages over the approach in the previous +paragraph. First, the location of the tclsh binary doesn't have +to be hard-wired into the script: it can be anywhere in your shell +search path. Second, it gets around the 30-character file name limit +in the previous approach. +Third, this approach will work even if tclsh is +itself a shell script (this is done on some systems in order to +handle multiple architectures or operating systems: the tclsh +script selects one of several binaries to run). The three lines +cause both sh and tclsh to process the script, but the +exec is only executed by sh. +sh processes the script first; it treats the second +line as a comment and executes the third line. +The exec statement cause the shell to stop processing and +instead to start up tclsh to reprocess the entire script. +When tclsh starts up, it treats all three lines as comments, +since the backslash at the end of the second line causes the third +line to be treated as part of the comment on the second line. +

    +You should note that it is also common practise to install tclsh with +its version number as part of the name. This has the advantage of +allowing multiple versions of Tcl to exist on the same system at once, +but also the disadvantage of making it harder to write scripts that +start up uniformly across different versions of Tcl. + +

    VARIABLES

    +Tclsh sets the following Tcl variables: +

    +

    +

    argc
    +Contains a count of the number of arg arguments (0 if none), +not including the name of the script file. +

    argv
    +Contains a Tcl list whose elements are the arg arguments, +in order, or an empty string if there are no arg arguments. +

    argv0
    +Contains fileName if it was specified. +Otherwise, contains the name by which tclsh was invoked. +

    tcl_interactive
    +Contains 1 if tclsh is running interactively (no +fileName was specified and standard input is a terminal-like +device), 0 otherwise. + +

    +

    PROMPTS

    +When tclsh is invoked interactively it normally prompts for each +command with ``% ''. You can change the prompt by setting the +variables tcl_prompt1 and tcl_prompt2. If variable +tcl_prompt1 exists then it must consist of a Tcl script +to output a prompt; instead of outputting a prompt tclsh +will evaluate the script in tcl_prompt1. +The variable tcl_prompt2 is used in a similar way when +a newline is typed but the current command isn't yet complete; +if tcl_prompt2 isn't set then no prompt is output for +incomplete commands. + +

    KEYWORDS

    +argument, interpreter, prompt, script file, shell +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/tcltest.htm b/hlp/en/tcl/tcltest.htm new file mode 100644 index 0000000..d7b16de --- /dev/null +++ b/hlp/en/tcl/tcltest.htm @@ -0,0 +1,776 @@ +Tcl Built-In Commands - Tcltest manual page +
    +
    NAME +
    Tcltest - Test harness support code and utilities
    +
    SYNOPSIS +
    +
    package require tcltest ?1.0? +
    ::tcltest::test name desc ?constraint? script expectedAnswer +
    ::tcltest::cleanupTests ?runningMultipleTests? +
    ::tcltest::getMatchingTestFiles +
    ::tcltest::loadTestedCommands +
    ::tcltest::makeFile contents name +
    ::tcltest::removeFile name +
    ::tcltest::makeDirectory name +
    ::tcltest::removeDirectory name +
    ::tcltest::viewFile name +
    ::tcltest::normalizeMsg msg +
    ::tcltest::bytestring string +
    ::tcltest::saveState +
    ::tcltest::restoreState +
    ::tcltest::threadReap +
    +
    DESCRIPTION +
    COMMANDS +
    +
    ::tcltest::test name desc ?constraints? script expectedAnswer +
    ::tcltest::cleanupTests ?runningMultipleTests? +
    ::tcltest::getMatchingTestFiles +
    ::tcltest::loadTestedCommands +
    ::tcltest::makeFile contents name +
    ::tcltest::removeFile name +
    ::tcltest::makeDirectory name +
    ::tcltest::removeDirectory name +
    ::tcltest::viewFile file +
    ::tcltest::normalizeMsg msg +
    ::tcltest::bytestring string +
    ::tcltest::saveState +
    ::tcltest::threadReap +
    +
    TESTS +
    TCLTEST NAMEPSACE VARIABLES +
    +
    ::tcltest::outputChannel +
    ::tcltest::errorChannel +
    ::tcltest::mainThread +
    ::tcltest::originalEnv +
    ::tcltest::workingDirectory +
    ::tcltest::temporaryDirectory +
    ::tcltest::testsDirectory +
    ::tcltest::tcltest +
    ::tcltest::loadScript +
    +
    TEST CONSTRAINTS +
    +
    unix +
    pc +
    nt +
    95 +
    98 +
    mac +
    unixOrPc +
    macOrPc +
    macOrUnix +
    tempNotPc +
    tempNotMac +
    unixCrash +
    pcCrash +
    macCrash +
    emptyTest +
    knownBug +
    nonPortable +
    userInteraction +
    interactive +
    nonBlockFiles +
    asyncPipeClose +
    unixExecs +
    hasIsoLocale +
    root +
    notRoot +
    eformat +
    stdio +
    +
    RUNNING TEST FILES +
    +
    -help +
    -verbose <level> +
    -match <matchList> +
    -skip <skipList> +
    -file <globPatternList> +
    -notfile <globPatternList> +
    -constraints <list> +
    -limitconstraints <bool> +
    -load <script> +
    -loadfile <scriptfile> +
    -tmpdir <directoryName> +
    -testdir <directoryName> +
    -preservecore <level> +
    +
    0 +
    1 +
    2 +
    +
    -debug <debugLevel> +
    +
    0 +
    1 +
    2 +
    3 +
    +
    -outfile <filename> +
    -errfile <filename> +
    +
    TEST OUTPUT +
    CONTENTS OF A TEST FILE +
    SELECTING TESTS FOR EXECUTION WITHIN A FILE +
    +
    +
    HOW TO CUSTOMIZE THE TEST HARNESS +
    +
    ::tcltest::PrintUsageInfoHook +
    ::tcltest::processCmdLineArgsFlagHook +
    ::tcltest::processCmdLineArgsHook flags +
    ::tcltest::initConstraintsHook +
    ::tcltest::cleanupTestsHook +
    +
    EXAMPLES +
    +
    +
    KEYWORDS +

    +

    NAME

    +Tcltest - Test harness support code and utilities +

    SYNOPSIS

    +package require tcltest ?1.0?
    +::tcltest::test name desc ?constraint? script expectedAnswer
    +::tcltest::cleanupTests ?runningMultipleTests?
    +::tcltest::getMatchingTestFiles
    +::tcltest::loadTestedCommands
    +::tcltest::makeFile contents name
    +::tcltest::removeFile name
    +::tcltest::makeDirectory name
    +::tcltest::removeDirectory name
    +::tcltest::viewFile name
    +::tcltest::normalizeMsg msg
    +::tcltest::bytestring string
    +::tcltest::saveState
    +::tcltest::restoreState
    +::tcltest::threadReap
    +

    DESCRIPTION

    +The tcltest package provides the user with utility tools for +writing and running tests in the Tcl test suite. It can also be used +to create a customized test harness for an extension. +

    +The Tcl test suite consists of multiple .test files, each of which +contains multiple test cases. Each test case consists of a call to +the test command, which specifies the name of test, a short +description, any constraints that apply to the test case, the script +to be run, and expected results. See the sections "Tests," +"Test Constraints," and "Test Files and How to Run Them" +for more details. +

    +It is also possible to add to this test harness to create your own +customized test harness implementation. For more defails, see the +section "How to Customize the Test Harness". +

    +This approach to testing was designed and initially implemented by +Mary Ann May-Pumphrey of Sun Microsystems in the early 1990's. Many +thanks to her for donating her work back to the public Tcl release. +

    COMMANDS

    +
    +

    ::tcltest::test name desc ?constraints? script expectedAnswer
    +The ::tcltest::test command runsscript and compares +its result to expectedAnswer. It prints an error message if the two do +not match. If ::tcltest::verbose contains "p" or "s", it also prints +out a message if the test passed or was skipped. The test will be +skipped if it doesn't match the ::tcltest::match variable, if it +matches an element in ::tcltest::skip, or if one of the elements +of constraint turns out not to be true. The +::tcltest::test command has no defined return values. See the +"Writing a new test" section for more details on this command. +

    ::tcltest::cleanupTests ?runningMultipleTests?
    +This command should be called at the end of a test file. It prints +statistics about the tests run and removes files that were created by +::tcltest::makeDirectory and ::tcltest::makeFile. Names +of files and directories created outside of +::tcltest::makeFile and ::tcltest::makeDirectory and +never deleted are printed to ::tcltest::outputChannel. This command +also restores the original shell environment, as described by the ::env +array. calledFromAll should be specified when +::tcltest::cleanupTests is called from an "all.tcl" file. Tcl files +files are generally used to run multiple tests. For more details on how to +run multiple tests, please see the section "Running test files". +This proc has no defined return value. +

    ::tcltest::getMatchingTestFiles
    +This command is used when you want to run multiple test files. It returns +the list of tests that should be sourced in an 'all.tcl' file. See the +section "Running test files" for more information. +

    ::tcltest::loadTestedCommands
    +This command uses the script specified via the -load or +-loadfile to load the commands checked by the test suite. +Allowed to be empty, as the tested commands could have been compiled +into the interpreter running the test suite. +

    ::tcltest::makeFile contents name
    +Create a file that will be automatically be removed by +::tcltest::cleanupTests at the end of a test file. +This proc has no defined return value. +

    ::tcltest::removeFile name
    +Force the file referenced by name to be removed. This file name +should be relative to ::tcltest::temporaryDirectory. This proc has no +defined return values. +

    ::tcltest::makeDirectory name
    +Create a directory named name that will automatically be removed +by ::tcltest::cleanupTests at the end of a test file. This proc +has no defined return value. +

    ::tcltest::removeDirectory name
    +Force the directory referenced by name to be removed. This proc +has no defined return value. +

    ::tcltest::viewFile file
    +Returns the contents of file. +

    ::tcltest::normalizeMsg msg
    +Remove extra newlines from msg. +

    ::tcltest::bytestring string
    +Construct a string that consists of the requested sequence of bytes, +as opposed to a string of properly formed UTF-8 characters using the +value supplied in string. This allows the tester to create +denormalized or improperly formed strings to pass to C procedures that +are supposed to accept strings with embedded NULL types and confirm +that a string result has a certain pattern of bytes. +

    ::tcltest::saveState
    +::tcltest::restoreState +Save and restore the procedure and global variable names. +A test file might contain calls to ::tcltest::saveState and +::tcltest:restoreState if it creates or deletes global variables +or procs. +

    ::tcltest::threadReap
    +::tcltest::threadReap only works if testthread is +defined, generally by compiling tcltest. If testthread is +defined, ::tcltest::threadReap kills all threads except for the +main thread. It gets the ID of the main thread by calling +testthread names during initialization. This value is stored in +::tcltest::mainThread. ::tcltest::threadReap returns the +number of existing threads at completion. +

    +

    TESTS

    +The test procedure runs a test script and prints an error +message if the script's result does not match the expected result. +The following is the spec for the test command: +
    test <name> <description> ?<constraint>? <script> <expectedAnswer>
    +The <name> argument should follow the pattern: +
    <target>-<majorNum>.<minorNum>
    +For white-box (regression) tests, the target should be the name of the +C function or Tcl procedure being tested. For black-box tests, the +target should be the name of the feature being tested. Related tests +should share a major number. +

    +The <description> argument is a short textual description of the test, +to help humans understand what it tests. The name of a Tcl or C +function being tested should be included for regression tests. If the +test case exists to reproduce a bug, include the bug ID in the +description. +

    +The optional <constraints> argument can be list of one or more +keywords or an expression. If the <constraints> argument consists of +keywords, each of these keywords must be the name of an element in the array +::tcltest::testConstraints. If any of these elements is false or does +not exist, the test is skipped. If the <constraints> argument +consists of an expression, that expression is evaluated. If the +expression evaluates to true, then the test is run. +

    +Add appropriate constraints (e.g., +unixOnly) to any tests that should not always be run. For example, a +test that should only be run on Unix should look like the following: +

    +

    test getAttribute-1.1 {testing file permissions} {unixOnly} {
    +    lindex [file attributes foo.tcl] 5
    +} {00644}
    +

    +An example of a test that contains an expression: +

    +

    test unixNotfy-1.1 {Tcl_DeleteFileHandler} {unixOnly && !testthread} {
    +    catch {vwait x}
    +    set f [open foo w]
    +    fileevent $f writable {set x 1}
    +    vwait x
    +    close $f
    +    list [catch {vwait x} msg] $msg
    +} {1 {can't wait for variable "x":  would wait forever}}
    +

    +See the "Test Constraints" section for a list of built-in +constraints and information on how to add your own constraints. +

    +The <script> argument contains the script to run to carry out the +test. It must return a result that can be checked for correctness. +If your script requires that a file be created on the fly, please use +the ::tcltest::makeFile procedure. If your test requires that a small +file (<50 lines) be checked in, please consider creating the file on +the fly using the ::tcltest::makeFile procedure. Files created by the +::tcltest::makeFile procedure will automatically be removed by the +::tcltest::cleanupTests call at the end of each test file. +

    +The <expectedAnswer> argument will be compared against the result of +evaluating the <script> argument. If they match, the test passes, +otherwise the test fails. +

    TCLTEST NAMEPSACE VARIABLES

    +The following variables are also defined in the tcltest namespace and +can be used by tests: +

    +

    +

    ::tcltest::outputChannel
    +output file ID - defaults to stdout and can be specified using +-outfile on the command line. +Any test that prints test related output should send +that output to ::tcltest::outputChannel rather than letting +that output default to stdout. +

    ::tcltest::errorChannel
    +error file ID - defaults to stderr and can be specified using -errfile +on the command line. +Any test that prints error messages should send +that output to ::tcltest::errorChannel rather than printing +directly to stderr. +

    ::tcltest::mainThread
    +main thread ID - defaults to 1. This is the only thread that is not +killed by ::tcltest::threadReap and is set according to the return +value of testthread names at initialization. +

    ::tcltest::originalEnv
    +copy of the global "env" array at the beginning of the test run. This +array is used to restore the "env" array to its original state when +::tcltest::cleanupTests is called. +

    ::tcltest::workingDirectory
    +the directory in which the test suite was launched. +

    ::tcltest::temporaryDirectory
    +the output directory - defaults to ::tcltest::workingDirectory and can be +specified using -tmpdir on the command line. +

    ::tcltest::testsDirectory
    +where the tests reside - defaults to ::tcltest::workingDirectory +if the script cannot determine where the tests directory is +located. It is possible to change the default by specifying +-testdir on the commandline. This variable should be +explicitly set if tests are being run from an all.tcl file. +

    ::tcltest::tcltest
    +the name of the executable used to invoke the test suite. +

    ::tcltest::loadScript
    +The script executed loadTestedCommands. Specified either by +-load or -loadfile. +

    +

    TEST CONSTRAINTS

    +Constraints are used to determine whether a test should be skipped. +Each constraint is stored as an index in the array +::tcltest::testConstraints. For example, the unixOnly constraint is +defined as the following: +
    set ::tcltest::testConstraints(unixOnly) \
    +    [string equal $tcl_platform(platform) "unix"]
    +If a test is constrained by "unixOnly", then it will only be run if +the value of ::tcltest::testConstraints(unixOnly) is true. Several +constraints are defined in the tcltest package. To add file- or +test-specific constraints, you can set the desired index of the +::tcltest::testsConstraints array in your own test file. +

    +The following is a list of constraints defined in the tcltest package: +

    +

    +

    unix
    +test can only be run on any UNIX platform +

    pc
    +test can only be run on any Windows platform +

    nt
    +test can only be run on any Windows NT platform +

    95
    +test can only be run on any Windows 95 platform +

    98
    +test can only be run on any Windows 98 platform +

    mac
    +test can only be run on any Mac platform +

    unixOrPc
    +test can only be run on a UNIX or PC platform +

    macOrPc
    +test can only be run on a Mac or PC platform +

    macOrUnix
    +test can only be run on a Mac or UNIX platform +

    tempNotPc
    +test can not be run on Windows. This flag is used to temporarily +disable a test. +

    tempNotMac
    +test can not be run on a Mac. This flag is used +to temporarily disable a test. +

    unixCrash
    +test crashes if it's run on UNIX. This flag is used to temporarily +disable a test. +

    pcCrash
    +test crashes if it's run on Windows. This flag is used to temporarily +disable a test. +

    macCrash
    +test crashes if it's run on a Mac. This flag is used to temporarily +disable a test. +

    emptyTest
    +test is empty, and so not worth running, but it remains as a +place-holder for a test to be written in the future. This constraint +always causes tests to be skipped. +

    knownBug
    +test is known to fail and the bug is not yet fixed. This constraint +always causes tests to be skipped unless the user specifies otherwise. +See the "Introduction" section for more details. +

    nonPortable
    +test can only be run in the master Tcl/Tk development environment. +Some tests are inherently non-portable because they depend on things +like word length, file system configuration, window manager, etc. +These tests are only run in the main Tcl development directory where +the configuration is well known. This constraint always causes tests +to be skipped unless the user specifies otherwise. +

    userInteraction
    +test requires interaction from the user. This constraint always +causes tests to be skipped unless the user specifies otherwise. +

    interactive
    +test can only be run in if the interpreter is in interactive mode, +that is the global tcl_interactive variable is set to 1. +

    nonBlockFiles
    +test can only be run if platform supports setting files into +nonblocking mode +

    asyncPipeClose
    +test can only be run if platform supports async flush and async close +on a pipe +

    unixExecs
    +test can only be run if this machine has commands such as 'cat', 'echo', +etc. available. +

    hasIsoLocale
    +test can only be run if can switch to an ISO locale +

    root
    +test can only run if Unix user is root +

    notRoot
    +test can only run if Unix user is not root +

    eformat
    +test can only run if app has a working version of sprintf with respect +to the "e" format of floating-point numbers. +

    stdio
    +test can only be run if the current app can be spawned via a pipe +

    +

    RUNNING TEST FILES

    +Use the following command to run a test file that uses package +tcltest: +
    <shell> <testFile> ?<option> ?<value>?? ...
    +Command line options include (tcltest namespace variables that +correspond to each flag are listed at the end of each flag description +in parenthesis): +

    +

    +

    -help
    +display usage information. +

    -verbose <level>
    +set the level of verbosity to a substring of "bps". See the "Test +output" section for an explanation of this option. (::tcltest::verbose) +

    -match <matchList>
    +only run tests that match one or more of the glob patterns in +<matchList>. (::tcltest::match) +

    -skip <skipList>
    +do not run tests that match one or more of the glob patterns in +<skipList>. (::tcltest::skip) +

    -file <globPatternList>
    +only source test files that match any of the items in +<globPatternList> relative to ::tcltest::testsDirectory. +This option +only makes sense if you are running tests using "all.tcl" as the +<testFile> instead of running single test files directly. +(::tcltest::matchFiles) +

    -notfile <globPatternList>
    +source files except for those that match any of the items in +<globPatternList> relative to ::tcltest::testsDirectory. +This option +only makes sense if you are running tests using "all.tcl" as the +<testFile> instead of running single test files directly. +(::tcltest::skipFiles) +

    -constraints <list>
    +tests with any constraints in <list> will not be skipped. Note that +elements of <list> must exactly match the existing constraints. This +is useful if you want to make sure that tests with a particular +constraint are run (for example, if the tester wants to run all tests +with the knownBug constraint). +(::tcltest::testConstraints(constraintName)) +

    -limitconstraints <bool>
    +If the argument to this flag is 1, the test harness limits test runs +to those tests that match the constraints listed by the -constraints +flag. Use of this flag requires use of the -constraints flag. The +default value for this flag is 0 (false). This is useful if you want +to run only those tests that match the constraints listed using +the -constraints option. A tester might want to do this if he were +interested in running only those tests that are constrained to be +unixOnly and no other tests. +(::tcltest::limitConstraints) +

    -load <script>
    +will use the specified script to load the commands under test +(::tcltest::loadTestedCommands). The default is the empty +script. See -loadfile below too. (::tcltest::loadScript) +

    -loadfile <scriptfile>
    +will use the contents of the named file to load the commands under +test (::tcltest::loadTestedCommands). See -load above too. The default +is the empty script. (::tcltest::loadScript) +

    -tmpdir <directoryName>
    +put any temporary files (created with ::tcltest::makeFile and +::tcltest::makeDirectory) into the named directory. The default +location is ::tcltest::workingDirectory. (::tcltest::temporaryDirectory) +

    -testdir <directoryName>
    +search the test suite to execute in the named directory. The default +location is ::tcltest::workingDirectory. (::tcltest::testsDirectory) +

    -preservecore <level>
    +check for core files. This flag is used to determine how much +checking should be done for core files. The default value for +level is 0. Levels are defined as: +

    +

    +

    0
    +No checking - do not check for core files at the end of each test +command, but do check for them whenever ::tcltest::cleanupTests is +called from an all.tcl file. +

    1
    +Check for core files at the end of each test command and whenever +::tcltest::cleanupTests is called from all.tcl. +

    2
    +Check for core files at the end of all test commands and whenever +::tcltest::cleanupTests is called from all.tcl. Save any core files +produced in ::tcltest::temporaryDirectory. +

    +

    +(::tcltest::preserveCore) +

    -debug <debugLevel>
    +print debug information to stdout. This is used to debug code in the +test harness. The default debug level is 0. Levels are defined as: +

    +

    +

    0
    +Do not display any debug information. +

    1
    +Display information regarding whether a test is skipped because it +doesn't match any of the tests that were specified using -match or +::tcltest::match (userSpecifiedNonMatch) or matches any of the tests +specified by -skip or ::tcltest::skip (userSpecifiedSkip). +

    2
    +Display the flag array parsed by the command line processor, the +contents of the ::env array, and all user-defined variables that exist +in the current namespace as they are used. +

    3
    +Display information regarding what individual procs in the test +harness are doing. +

    +

    +(::tcltest::debug) +

    -outfile <filename>
    +print output generated by the tcltest package to the named file. This +defaults to stdout. Note that debug output always goes to stdout, +regardless of this flag's setting. (::tcltest::outputChannel) +

    -errfile <filename>
    +print errors generated by the tcltest package to the named file. This +defaults to stderr. (::tcltest::errorChannel) +

    +

    +A second way to run tets is to start up a shell, load the +tcltest package, and then source an appropriate test file or use +the test command. To use the options in interactive mode, set +their corresponding tcltest namespace variables after loading the +package. +

    +See "Test Constraints" for all built-in constraint names +that can be used in the ::tcltest::testConstraints array. +See "Tcltest namespace variables" for details on other variables +defined in the tcltest namespace. +

    +A final way to run tests would be to specify which test files to run +within an all.tcl (or otherwise named) file. This is the +approach used by the Tcl test suite. This file loads the tcltest +package, sets the location of +the test directory (::tcltest::testsDirectory), determines which test +files to run, sources each of these files, calls +::tcltest::cleanupTests and then exits. +

    +A more elaborate all.tcl file might do some pre- and +post-processing before sourcing +each .test file, use separate interpreters for each file, or handle +complex directory structures. +For an example of an all.tcl file, +please see the "Examples" section of this document. +

    TEST OUTPUT

    +After all specified test files are run, the number of tests +passed, skipped, and failed is printed to +::tcltest::outputChannel. Aside from this +statistical information, output can be controlled on a per-test basis +by the ::tcltest::verbose variable. +

    +::tcltest::verbose can be set to any substring or permutation +of "bps". In the string "bps", the 'b' stands for a test's "body", +the 'p' stands for "passed" tests, and the 's' stands for "skipped" +tests. The default value of ::tcltest::verbose is "b". If 'b' +is present, then the entire body of the test is printed for each +failed test, otherwise only the test's name, desired output, and +actual output, are printed for each failed test. If 'p' is present, +then a line is printed for each passed test, otherwise no line is +printed for passed tests. If 's' is present, then a line (containing +the consraints that cause the test to be skipped) is printed for each +skipped test, otherwise no line is printed for skipped tests. +

    +You can set ::tcltest::verbose either interactively (after the +tcltest package has been loaded) or by using the command line +argument -verbose, for example: +

    tclsh socket.test -verbose bps
    +

    CONTENTS OF A TEST FILE

    +Test files should begin by loading the tcltest package: +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +Test files should end by cleaning up after themselves and calling +::tcltest::cleanupTests. The ::tcltest::cleanupTests +procedure prints statistics about the number of tests that passed, +skipped, and failed, and removes all files that were created using the +::tcltest::makeFile and ::tcltest::makeDirectory procedures. +
    # Remove files created by these tests
    +# Change to original working directory
    +# Unset global arrays
    +::tcltest::cleanupTests
    +return
    +When naming test files, file names should end with a .test extension. +The names of test files that contain regression (or glass-box) tests +should correspond to the Tcl or C code file that they are testing. +For example, the test file for the C file "tclCmdAH.c" is "cmdAH.test". +Test files that contain black-box tests should match the pattern "*_bb.test". +

    SELECTING TESTS FOR EXECUTION WITHIN A FILE

    +Normally, all the tests in a file are run whenever the file is +sourced. An individual test will be skipped if one of the following +conditions is met: +

    +

    +

    [1]
    +the name of the tests does not match (using glob style matching) +one or more elements in the ::tcltest::match variable +

    [2]
    +the name of the tests matches (using glob style matching) one or +more elements in the ::tcltest::skip variable +

    [3]
    +the constraints argument to the ::tcltest::test call, if +given, contains one or more false elements. +

    +

    +You can set ::tcltest::match and/or ::tcltest::skip +either interactively (after the tcltest package has been +sourced), or by using the command line arguments -match and +-skip, for example: +

    +

    tclsh info.test -match '*-5.* *-7.*' -skip '*-7.1*'
    +

    +Be sure to use the proper quoting convention so that your shell does +not perform the glob substitution on the match or skip patterns you +specify. +

    +Predefined constraints (e.g. knownBug and nonPortable) can be +overridden either interactively (after the tcltest package has been +sourced) by setting the proper +::tcltest::testConstraints(constraint) variable +or by using the -constraints command line option with the name of the +constraint in the argument. The following example shows how to run +tests that are constrained by the knownBug and nonPortable +restrictions: +

    +

    tclsh all.tcl -constraints "knownBug nonPortable"
    +

    +See the "Constraints" package for information about using +built-in constraints and adding new ones. +

    HOW TO CUSTOMIZE THE TEST HARNESS

    +To create your own custom test harness, create a .tcl file that contains your +namespace. Within this file, require package tcltest. Commands +that can be redefined to customize the test harness include: +

    +

    +

    ::tcltest::PrintUsageInfoHook
    +print additional usage information specific to your situation. +

    ::tcltest::processCmdLineArgsFlagHook
    +tell the test harness about additional flags that you want it to understand. +

    ::tcltest::processCmdLineArgsHook flags
    +process the additional flags that you told the harness about in +::tcltest::processCmdLineArgsFlagHook. +

    ::tcltest::initConstraintsHook
    +used to add additional built-in constraints to those already defined +by tcltest. +

    ::tcltest::cleanupTestsHook
    +do additional cleanup +

    +

    +

    +To add new flags to your customized test harness, redefine +::tcltest::processCmdLineArgsAddFlagHook to define additional flags to be +parsed and ::tcltest::processCmdLineArgsHook to actually process them. +For example: +

    proc ::tcltest::processCmdLineArgsAddFlagHook {} {
    +    return [list -flag1 -flag2]
    +}
    +
    +proc ::tcltest::processCmdLineArgsHook {flagArray} {
    +    array set flag $flagArray
    +
    +    if {[info exists flag(-flag1)]} {
    +        # Handle flag1
    +    }
    +
    +    if {[info exists flag(-flag2)]} {
    +        # Handle flag2
    +    }
    +
    +    return
    +}
    +You may also want to add usage information for these flags. This +information would be displayed whenever the user specifies -help. To +define additional usage information, define your own +::tcltest::PrintUsageInfoHook proc. Within this proc, you should +print out additional usage information for any flags that you've +implemented. +

    +To add new built-in +constraints to the test harness, define your own version of +::tcltest::initConstraintsHook. +Within your proc, you can add to the ::tcltest::testConstraints array. +For example: +

    proc ::tcltest::initConstraintsHook {} {
    +    set ::tcltest::testConstraints(win95Or98) \
    +            [expr {$::tcltest::testConstraints(95) || \
    +            $::tcltest::testConstraints(98)}]
    +}
    +

    +Finally, if you want to add additional cleanup code to your harness +you can define your own ::tcltest::cleanupTestsHook. For example: +

    proc ::tcltest::cleanupTestsHook {} {
    +    # Add your cleanup code here
    +}
    +

    EXAMPLES

    +
    +

    [1]
    +A simple test file (foo.test) +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +test foo-1.1 {save 1 in variable name foo} {} {
    +    set foo 1
    +} {1}
    +
    +::tcltest::cleanupTests
    +return
    +

    [2]
    +A simple all.tcl +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +set ::tcltest::testSingleFile false
    +set ::tcltest::testsDirectory [file dir [info script]]
    +
    +foreach file [::tcltest::getMatchingTestFiles] {
    +    if {[catch {source $file} msg]} {
    +        puts stdout $msg
    +    }
    +}
    +
    +::tclttest::cleanupTests 1
    +return
    +

    [3]
    +Running a single test +
    tclsh foo.test
    +

    [4]
    +Running multiple tests +
    tclsh all.tcl -file 'foo*.test' -notfile 'foo2.test'
    +

    +

    KEYWORDS

    +test, test harness, test suite +
    +Copyright © 1990-1994 The Regents of the University of California
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1998-1999 Scriptics Corporation
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/tclvars.htm b/hlp/en/tcl/tclvars.htm new file mode 100644 index 0000000..f224550 --- /dev/null +++ b/hlp/en/tcl/tclvars.htm @@ -0,0 +1,404 @@ +Tcl Built-In Commands - tclvars manual page +
    +
    NAME +
    tclvars - Variables used by Tcl
    +
    DESCRIPTION +
    +
    env +
    +
    LOGIN +
    USER +
    SYS_FOLDER +
    APPLE_M_FOLDER +
    CP_FOLDER +
    DESK_FOLDER +
    EXT_FOLDER +
    PREF_FOLDER +
    PRINT_MON_FOLDER +
    SHARED_TRASH_FOLDER +
    TRASH_FOLDER +
    START_UP_FOLDER +
    HOME +
    +
    errorCode +
    +
    ARITH code msg +
    CHILDKILLED pid sigName msg +
    CHILDSTATUS pid code +
    CHILDSUSP pid sigName msg +
    NONE +
    POSIX errName msg +
    +
    errorInfo +
    tcl_library +
    tcl_patchLevel +
    tcl_pkgPath +
    tcl_platform +
    +
    byteOrder +
    debug +
    machine +
    os +
    osVersion +
    platform +
    threaded +
    user +
    +
    tcl_precision +
    tcl_rcFileName +
    tcl_rcRsrcName +
    tcl_traceCompile +
    tcl_traceExec +
    tcl_wordchars +
    tcl_nonwordchars +
    tcl_version +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +tclvars - Variables used by Tcl +

    DESCRIPTION

    +The following global variables are created and managed automatically +by the Tcl library. Except where noted below, these variables should +normally be treated as read-only by application-specific code and by users. +

    +

    +

    env
    +This variable is maintained by Tcl as an array +whose elements are the environment variables for the process. +Reading an element will return the value of the corresponding +environment variable. +Setting an element of the array will modify the corresponding +environment variable or create a new one if it doesn't already +exist. +Unsetting an element of env will remove the corresponding +environment variable. +Changes to the env array will affect the environment +passed to children by commands like exec. +If the entire env array is unset then Tcl will stop +monitoring env accesses and will not update environment +variables. +

    +Under Windows, the environment variables PATH and COMSPEC in any +capitalization are converted automatically to upper case. For instance, the +PATH variable could be exported by the operating system as ``path'', +``Path'', ``PaTh'', etc., causing otherwise simple Tcl code to have to +support many special cases. All other environment variables inherited by +Tcl are left unmodified. +
    +

    +On the Macintosh, the environment variable is constructed by Tcl as no +global environment variable exists. The environment variables that +are created for Tcl include: +

    +

    +

    LOGIN
    +This holds the Chooser name of the Macintosh. +

    USER
    +This also holds the Chooser name of the Macintosh. +

    SYS_FOLDER
    +The path to the system directory. +

    APPLE_M_FOLDER
    +The path to the Apple Menu directory. +

    CP_FOLDER
    +The path to the control panels directory. +

    DESK_FOLDER
    +The path to the desk top directory. +

    EXT_FOLDER
    +The path to the system extensions directory. +

    PREF_FOLDER
    +The path to the preferences directory. +

    PRINT_MON_FOLDER
    +The path to the print monitor directory. +

    SHARED_TRASH_FOLDER
    +The path to the network trash directory. +

    TRASH_FOLDER
    +The path to the trash directory. +

    START_UP_FOLDER
    +The path to the start up directory. +

    HOME
    +The path to the application's default directory. +

    +

    +You can also create your own environment variables for the Macintosh. +A file named Tcl Environment Variables may be placed in the +preferences folder in the Mac system folder. Each line of this file +should be of the form VAR_NAME=var_data. +

    +The last alternative is to place environment variables in a 'STR#' +resource named Tcl Environment Variables of the application. This +is considered a little more ``Mac like'' than a Unix style Environment +Variable file. Each entry in the 'STR#' resource has the same format +as above. The source code file tclMacEnv.c contains the +implementation of the env mechanisms. This file contains many +#define's that allow customization of the env mechanisms to fit your +applications needs. +

    +

    errorCode
    +After an error has occurred, this variable will be set to hold +additional information about the error in a form that is easy +to process with programs. +errorCode consists of a Tcl list with one or more elements. +The first element of the list identifies a general class of +errors, and determines the format of the rest of the list. +The following formats for errorCode are used by the +Tcl core; individual applications may define additional formats. +

    +

    +

    ARITH code msg
    +This format is used when an arithmetic error occurs (e.g. an attempt +to divide by zero in the expr command). +Code identifies the precise error and msg provides a +human-readable description of the error. Code will be either +DIVZERO (for an attempt to divide by zero), +DOMAIN (if an argument is outside the domain of a function, such as acos(-3)), +IOVERFLOW (for integer overflow), +OVERFLOW (for a floating-point overflow), +or UNKNOWN (if the cause of the error cannot be determined). +

    CHILDKILLED pid sigName msg
    +This format is used when a child process has been killed because of +a signal. The second element of errorCode will be the +process's identifier (in decimal). +The third element will be the symbolic name of the signal that caused +the process to terminate; it will be one of the names from the +include file signal.h, such as SIGPIPE. +The fourth element will be a short human-readable message +describing the signal, such as ``write on pipe with no readers'' +for SIGPIPE. +

    CHILDSTATUS pid code
    +This format is used when a child process has exited with a non-zero +exit status. The second element of errorCode will be the +process's identifier (in decimal) and the third element will be the exit +code returned by the process (also in decimal). +

    CHILDSUSP pid sigName msg
    +This format is used when a child process has been suspended because +of a signal. +The second element of errorCode will be the process's identifier, +in decimal. +The third element will be the symbolic name of the signal that caused +the process to suspend; this will be one of the names from the +include file signal.h, such as SIGTTIN. +The fourth element will be a short human-readable message +describing the signal, such as ``background tty read'' +for SIGTTIN. +

    NONE
    +This format is used for errors where no additional information is +available for an error besides the message returned with the +error. In these cases errorCode will consist of a list +containing a single element whose contents are NONE. +

    POSIX errName msg
    +If the first element of errorCode is POSIX, then +the error occurred during a POSIX kernel call. +The second element of the list will contain the symbolic name +of the error that occurred, such as ENOENT; this will +be one of the values defined in the include file errno.h. +The third element of the list will be a human-readable +message corresponding to errName, such as +``no such file or directory'' for the ENOENT case. +

    To set errorCode, applications should use library +procedures such as Tcl_SetErrorCode and Tcl_PosixError, +or they may invoke the error command. +If one of these methods hasn't been used, then the Tcl +interpreter will reset the variable to NONE after +the next error.

    +

    +

    errorInfo
    +After an error has occurred, this string will contain one or more lines +identifying the Tcl commands and procedures that were being executed +when the most recent error occurred. +Its contents take the form of a stack trace showing the various +nested Tcl commands that had been invoked at the time of the error. +

    tcl_library
    +This variable holds the name of a directory containing the +system library of Tcl scripts, such as those used for auto-loading. +The value of this variable is returned by the info library command. +See the library manual entry for details of the facilities +provided by the Tcl script library. +Normally each application or package will have its own application-specific +script library in addition to the Tcl script library; +each application should set a global variable with a name like +$app_library (where app is the application's name) +to hold the network file name for that application's library directory. +The initial value of tcl_library is set when an interpreter +is created by searching several different directories until one is +found that contains an appropriate Tcl startup script. +If the TCL_LIBRARY environment variable exists, then +the directory it names is checked first. +If TCL_LIBRARY isn't set or doesn't refer to an appropriate +directory, then Tcl checks several other directories based on a +compiled-in default location, the location of the binary containing +the application, and the current working directory. +

    tcl_patchLevel
    +When an interpreter is created Tcl initializes this variable to +hold a string giving the current patch level for Tcl, such as +7.3p2 for Tcl 7.3 with the first two official patches, or +7.4b4 for the fourth beta release of Tcl 7.4. +The value of this variable is returned by the info patchlevel +command. +

    tcl_pkgPath
    +This variable holds a list of directories indicating where packages are +normally installed. It is not used on Windows. It typically contains +either one or two entries; if it contains two entries, the first is +normally a directory for platform-dependent packages (e.g., shared library +binaries) and the second is normally a directory for platform-independent +packages (e.g., script files). Typically a package is installed as a +subdirectory of one of the entries in $tcl_pkgPath. The directories +in $tcl_pkgPath are included by default in the auto_path +variable, so they and their immediate subdirectories are automatically +searched for packages during package require commands. Note: +tcl_pkgPath it not intended to be modified by the application. Its +value is added to auto_path at startup; changes to tcl_pkgPath +are not reflected in auto_path. If you want Tcl to search additional +directories for packages you should add the names of those directories to +auto_path, not tcl_pkgPath. +

    tcl_platform
    +This is an associative array whose elements contain information about +the platform on which the application is running, such as the name of +the operating system, its current release number, and the machine's +instruction set. The elements listed below will always +be defined, but they may have empty strings as values if Tcl couldn't +retrieve any relevant information. In addition, extensions +and applications may add additional values to the array. The +predefined elements are: + + + + + +

    +

    +

    byteOrder
    +The native byte order of this machine: either littleEndian or +bigEndian. +

    debug
    +If this variable exists, then the interpreter +was compiled with debugging symbols enabled. This varible will only +exist on Windows so extension writers can specify which package to load +depending on the C run-time library that is loaded. +

    machine
    +The instruction set executed by this machine, such as +intel, PPC, 68k, or sun4m. On UNIX machines, this +is the value returned by uname -m. +

    os
    +The name of the operating system running on this machine, +such as Windows 95, Windows NT, MacOS, or SunOS. +On UNIX machines, this is the value returned by uname -s. +On Windows 95 and Windows 98, the value returned will be Windows +95 to provide better backwards compatibility to Windows 95; to +distinguish between the two, check the osVersion. +

    osVersion
    +The version number for the operating system running on this machine. +On UNIX machines, this is the value returned by uname -r. On +Windows 95, the version will be 4.0; on Windows 98, the version will +be 4.10. +

    platform
    +Either windows, macintosh, or unix. This identifies the +general operating environment of the machine. +

    threaded
    +If this variable exists, then the interpreter +was compiled with threads enabled. +

    user
    +This identifies the +current user based on the login information available on the platform. +This comes from the USER or LOGNAME environment variable on Unix, +and the value from GetUserName on Windows and Macintosh. +

    +

    tcl_precision
    +This variable controls the number of digits to generate +when converting floating-point values to strings. It defaults +to 12. +17 digits is ``perfect'' for IEEE floating-point in that it allows +double-precision values to be converted to strings and back to +binary with no loss of information. However, using 17 digits prevents +any rounding, which produces longer, less intuitive results. For example, +expr 1.4 returns 1.3999999999999999 with tcl_precision +set to 17, vs. 1.4 if tcl_precision is 12. +

    +All interpreters in a process share a single tcl_precision value: +changing it in one interpreter will affect all other interpreters as +well. However, safe interpreters are not allowed to modify the +variable. +
    +

    tcl_rcFileName
    +This variable is used during initialization to indicate the name of a +user-specific startup file. If it is set by application-specific +initialization, then the Tcl startup code will check for the existence +of this file and source it if it exists. For example, for wish +the variable is set to ~/.wishrc for Unix and ~/wishrc.tcl +for Windows. +

    tcl_rcRsrcName
    +This variable is only used on Macintosh systems. The variable is used +during initialization to indicate the name of a user-specific +TEXT resource located in the application or extension resource +forks. If it is set by application-specific initialization, then the +Tcl startup code will check for the existence of this resource and +source it if it exists. For example, the Macintosh wish +application has the variable is set to tclshrc. +

    tcl_traceCompile
    +The value of this variable can be set to control +how much tracing information +is displayed during bytecode compilation. +By default, tcl_traceCompile is zero and no information is displayed. +Setting tcl_traceCompile to 1 generates a one line summary in stdout +whenever a procedure or top level command is compiled. +Setting it to 2 generates a detailed listing in stdout of the +bytecode instructions emitted during every compilation. +This variable is useful in +tracking down suspected problems with the Tcl compiler. +It is also occasionally useful when converting +existing code to use Tcl8.0. +

    tcl_traceExec
    +The value of this variable can be set to control +how much tracing information +is displayed during bytecode execution. +By default, tcl_traceExec is zero and no information is displayed. +Setting tcl_traceExec to 1 generates a one line trace in stdout +on each call to a Tcl procedure. +Setting it to 2 generates a line of output +whenever any Tcl command is invoked +that contains the name of the command and its arguments. +Setting it to 3 produces a detailed trace showing the result of +executing each bytecode instruction. +Note that when tcl_traceExec is 2 or 3, +commands such as set and incr +that have been entirely replaced by a sequence +of bytecode instructions are not shown. +Setting this variable is useful in +tracking down suspected problems with the bytecode compiler +and interpreter. +It is also occasionally useful when converting +code to use Tcl8.0. +

    tcl_wordchars
    +The value of this variable is a regular expression that can be set to +control what are considered ``word'' characters, for instances like +selecting a word by double-clicking in text in Tk. It is platform +dependent. On Windows, it defaults to \S, meaning anything +but a Unicode space character. Otherwise it defaults to \w, +which is any Unicode word character (number, letter, or underscore). +

    tcl_nonwordchars
    +The value of this variable is a regular expression that can be set to +control what are considered ``non-word'' characters, for instances like +selecting a word by double-clicking in text in Tk. It is platform +dependent. On Windows, it defaults to \s, meaning any Unicode space +character. Otherwise it defaults to \W, which is anything but a +Unicode word character (number, letter, or underscore). +

    tcl_version
    +When an interpreter is created Tcl initializes this variable to +hold the version number for this version of Tcl in the form x.y. +Changes to x represent major changes with probable +incompatibilities and changes to y represent small enhancements and +bug fixes that retain backward compatibility. +The value of this variable is returned by the info tclversion +command. + +

    +

    SEE ALSO

    +eval +

    KEYWORDS

    +arithmetic, bytecode, compiler, error, environment, POSIX, precision, subprocess, variables +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/tell.htm b/hlp/en/tcl/tell.htm new file mode 100644 index 0000000..80ed7fd --- /dev/null +++ b/hlp/en/tcl/tell.htm @@ -0,0 +1,22 @@ +Tcl Built-In Commands - tell manual page +

    NAME

    +tell - Return current access position for an open channel +

    SYNOPSIS

    +tell channelId
    +

    DESCRIPTION

    +Returns an integer string giving the current access position in +channelId. This value returned is a byte offset that can be passed to +seek in order to set the channel to a particular position. Note +that this value is in terms of bytes, not characters like read. +The value returned is -1 for channels that do not support +seeking. + +

    SEE ALSO

    +file, open, close, gets, seek +

    KEYWORDS

    +access position, channel, seeking +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/time.htm b/hlp/en/tcl/time.htm new file mode 100644 index 0000000..88e0af7 --- /dev/null +++ b/hlp/en/tcl/time.htm @@ -0,0 +1,23 @@ +Built-In Commands - time manual page +

    NAME

    +time - Time the execution of a script +

    SYNOPSIS

    +time script ?count?
    +

    DESCRIPTION

    +This command will call the Tcl interpreter count +times to evaluate script (or once if count isn't +specified). It will then return a string of the form +
    503 microseconds per iteration
    +which indicates the average amount of time required per iteration, +in microseconds. +Time is measured in elapsed time, not CPU time. + +

    SEE ALSO

    +clock +

    KEYWORDS

    +script, time +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/trace.htm b/hlp/en/tcl/trace.htm new file mode 100644 index 0000000..503e2d3 --- /dev/null +++ b/hlp/en/tcl/trace.htm @@ -0,0 +1,165 @@ +Built-In Commands - trace manual page +
    +
    NAME +
    trace - Monitor variable accesses
    +
    SYNOPSIS +
    +
    trace option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    trace variable name ops command +
    +
    r +
    w +
    u +
    +
    trace vdelete name ops command +
    trace vinfo name +
    +
    KEYWORDS +

    +

    NAME

    +trace - Monitor variable accesses +

    SYNOPSIS

    +trace option ?arg arg ...?
    +

    DESCRIPTION

    +This command causes Tcl commands to be executed whenever certain operations are +invoked. At present, only variable tracing is implemented. The +legal option's (which may be abbreviated) are: +

    +

    +

    trace variable name ops command
    +Arrange for command to be executed whenever variable name +is accessed in one of the ways given by ops. Name may +refer to a normal variable, an element of an array, or to an array +as a whole (i.e. name may be just the name of an array, with no +parenthesized index). If name refers to a whole array, then +command is invoked whenever any element of the array is +manipulated. If the variable does not exist, it will be created but +will not be given a value, so it will be visible to namespace which +queries, but not to info exists queries. +

    +Ops indicates which operations are of interest, and consists of +one or more of the following letters: +

    +

    +

    r
    +Invoke command whenever the variable is read. +

    w
    +Invoke command whenever the variable is written. +

    u
    +Invoke command whenever the variable is unset. Variables +can be unset explicitly with the unset command, or +implicitly when procedures return (all of their local variables +are unset). Variables are also unset when interpreters are +deleted, but traces will not be invoked because there is no +interpreter in which to execute them. +

    +

    +When the trace triggers, three arguments are appended to +command so that the actual command is as follows: +

    command name1 name2 op
    +Name1 and name2 give the name(s) for the variable +being accessed: if the variable is a scalar then name1 +gives the variable's name and name2 is an empty string; +if the variable is an array element then name1 gives the +name of the array and name2 gives the index into the array; +if an entire array is being deleted and the trace was registered +on the overall array, rather than a single element, then name1 +gives the array name and name2 is an empty string. +Name1 and name2 are not necessarily the same as the +name used in the trace variable command: the upvar +command allows a procedure to reference a variable under a +different name. +Op indicates what operation is being performed on the +variable, and is one of r, w, or u as +defined above. +

    +Command executes in the same context as the code that invoked +the traced operation: if the variable was accessed as part of a +Tcl procedure, then command will have access to the same +local variables as code in the procedure. This context may be +different than the context in which the trace was created. +If command invokes a procedure (which it normally does) then +the procedure will have to use upvar or uplevel if it +wishes to access the traced variable. +Note also that name1 may not necessarily be the same as the name +used to set the trace on the variable; differences can occur if +the access is made through a variable defined with the upvar +command. +

    +For read and write traces, command can modify +the variable to affect the result of the traced operation. +If command modifies the value of a variable during a +read or write trace, then the new value will be returned as the +result of the traced operation. +The return value from command is ignored except that +if it returns an error of any sort then the traced operation +also returns an error with +the same error message returned by the trace command +(this mechanism can be used to implement read-only variables, for +example). +For write traces, command is invoked after the variable's +value has been changed; it can write a new value into the variable +to override the original value specified in the write operation. +To implement read-only variables, command will have to restore +the old value of the variable. +

    +While command is executing during a read or write trace, traces +on the variable are temporarily disabled. +This means that reads and writes invoked by +command will occur directly, without invoking command +(or any other traces) again. +However, if command unsets the variable then unset traces +will be invoked. +

    +When an unset trace is invoked, the variable has already been +deleted: it will appear to be undefined with no traces. +If an unset occurs because of a procedure return, then the +trace will be invoked in the variable context of the procedure +being returned to: the stack frame of the returning procedure +will no longer exist. +Traces are not disabled during unset traces, so if an unset trace +command creates a new trace and accesses the variable, the +trace will be invoked. +Any errors in unset traces are ignored. +

    +If there are multiple traces on a variable they are invoked +in order of creation, most-recent first. +If one trace returns an error, then no further traces are +invoked for the variable. +If an array element has a trace set, and there is also a trace +set on the array as a whole, the trace on the overall array +is invoked before the one on the element. +

    +Once created, the trace remains in effect either until the +trace is removed with the trace vdelete command described +below, until the variable is unset, or until the interpreter +is deleted. +Unsetting an element of array will remove any traces on that +element, but will not remove traces on the overall array. +

    This command returns an empty string. +

    trace vdelete name ops command
    +If there is a trace set on variable name with the +operations and command given by ops and command, +then the trace is removed, so that command will never +again be invoked. +Returns an empty string. +

    trace vinfo name
    +Returns a list containing one element for each trace +currently set on variable name. +Each element of the list is itself a list containing two +elements, which are the ops and command associated +with the trace. +If name doesn't exist or doesn't have any traces set, then +the result of the command will be an empty string. + +

    +

    KEYWORDS

    +read, variable, write, trace, unset +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/unknown.htm b/hlp/en/tcl/unknown.htm new file mode 100644 index 0000000..f550914 --- /dev/null +++ b/hlp/en/tcl/unknown.htm @@ -0,0 +1,67 @@ +Built-In Commands - unknown manual page +

    NAME

    +unknown - Handle attempts to use non-existent commands +

    SYNOPSIS

    +unknown cmdName ?arg arg ...?
    +

    DESCRIPTION

    +This command is invoked by the Tcl interpreter whenever a script +tries to invoke a command that doesn't exist. The implementation +of unknown isn't part of the Tcl core; instead, it is a +library procedure defined by default when Tcl starts up. You +can override the default unknown to change its functionality. +

    +If the Tcl interpreter encounters a command name for which there +is not a defined command, then Tcl checks for the existence of +a command named unknown. +If there is no such command, then the interpreter returns an +error. +If the unknown command exists, then it is invoked with +arguments consisting of the fully-substituted name and arguments +for the original non-existent command. +The unknown command typically does things like searching +through library directories for a command procedure with the name +cmdName, or expanding abbreviated command names to full-length, +or automatically executing unknown commands as sub-processes. +In some cases (such as expanding abbreviations) unknown will +change the original command slightly and then (re-)execute it. +The result of the unknown command is used as the result for +the original non-existent command. +

    +The default implementation of unknown behaves as follows. +It first calls the auto_load library procedure to load the command. +If this succeeds, then it executes the original command with its +original arguments. +If the auto-load fails then unknown calls auto_execok +to see if there is an executable file by the name cmd. +If so, it invokes the Tcl exec command +with cmd and all the args as arguments. +If cmd can't be auto-executed, unknown checks to +see if the command was invoked at top-level and outside of any +script. If so, then unknown takes two additional steps. +First, it sees if cmd has one of the following three forms: +!!, !event, or ^old^new?^?. +If so, then unknown carries out history substitution +in the same way that csh would for these constructs. +Finally, unknown checks to see if cmd is +a unique abbreviation for an existing Tcl command. +If so, it expands the command name and executes the command with +the original arguments. +If none of the above efforts has been able to execute +the command, unknown generates an error return. +If the global variable auto_noload is defined, then the auto-load +step is skipped. +If the global variable auto_noexec is defined then the +auto-exec step is skipped. +Under normal circumstances the return value from unknown +is the return value from the command that was eventually +executed. + +

    SEE ALSO

    +info, proc +

    KEYWORDS

    +error, non-existent command +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/unset.htm b/hlp/en/tcl/unset.htm new file mode 100644 index 0000000..17b8b36 --- /dev/null +++ b/hlp/en/tcl/unset.htm @@ -0,0 +1,24 @@ +Built-In Commands - unset manual page +

    NAME

    +unset - Delete variables +

    SYNOPSIS

    +unset name ?name name ...?
    +

    DESCRIPTION

    +This command removes one or more variables. +Each name is a variable name, specified in any of the +ways acceptable to the set command. +If a name refers to an element of an array then that +element is removed without affecting the rest of the array. +If a name consists of an array name with no parenthesized +index, then the entire array is deleted. +The unset command returns an empty string as result. +An error occurs if any of the variables doesn't exist, and any variables +after the non-existent one are not deleted. + +

    KEYWORDS

    +remove, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/update.htm b/hlp/en/tcl/update.htm new file mode 100644 index 0000000..d7866cc --- /dev/null +++ b/hlp/en/tcl/update.htm @@ -0,0 +1,40 @@ +Tcl Built-In Commands - update manual page +

    NAME

    +update - Process pending events and idle callbacks +

    SYNOPSIS

    +update ?idletasks?
    +

    DESCRIPTION

    +This command is used to bring the application ``up to date'' +by entering the event loop repeatedly until all pending events +(including idle callbacks) have been processed. +

    +If the idletasks keyword is specified as an argument to the +command, then no new events or errors are processed; only idle +callbacks are invoked. +This causes operations that are normally deferred, such as display +updates and window layout calculations, to be performed immediately. +

    +The update idletasks command is useful in scripts where +changes have been made to the application's state and you want those +changes to appear on the display immediately, rather than waiting +for the script to complete. Most display updates are performed as +idle callbacks, so update idletasks will cause them to run. +However, there are some kinds of updates that only happen in +response to events, such as those triggered by window size changes; +these updates will not occur in update idletasks. +

    +The update command with no options is useful in scripts where +you are performing a long-running computation but you still want +the application to respond to events such as user interactions; if +you occasionally call update then user input will be processed +during the next call to update. + +

    SEE ALSO

    +after, bgerror +

    KEYWORDS

    +event, flush, handler, idle, update +
    +Copyright © 1990-1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/uplevel.htm b/hlp/en/tcl/uplevel.htm new file mode 100644 index 0000000..1e0ba6e --- /dev/null +++ b/hlp/en/tcl/uplevel.htm @@ -0,0 +1,65 @@ +Built-In Commands - uplevel manual page +

    NAME

    +uplevel - Execute a script in a different stack frame +

    SYNOPSIS

    +uplevel ?level? arg ?arg ...?
    +

    DESCRIPTION

    +All of the arg arguments are concatenated as if they had +been passed to concat; the result is then evaluated in the +variable context indicated by level. Uplevel returns +the result of that evaluation. +

    +If level is an integer then +it gives a distance (up the procedure calling stack) to move before +executing the command. If level consists of # followed by +a number then the number gives an absolute level number. If level +is omitted then it defaults to 1. Level cannot be +defaulted if the first command argument starts with a digit or #. +

    +For example, suppose that procedure a was invoked +from top-level, and that it called b, and that b called c. +Suppose that c invokes the uplevel command. If level +is 1 or #2 or omitted, then the command will be executed +in the variable context of b. If level is 2 or #1 +then the command will be executed in the variable context of a. +If level is 3 or #0 then the command will be executed +at top-level (only global variables will be visible). +

    +The uplevel command causes the invoking procedure to disappear +from the procedure calling stack while the command is being executed. +In the above example, suppose c invokes the command +

    uplevel 1 {set x 43; d}
    +where d is another Tcl procedure. The set command will +modify the variable x in b's context, and d will execute +at level 3, as if called from b. If it in turn executes +the command +
    uplevel {set x 42}
    +then the set command will modify the same variable x in b's +context: the procedure c does not appear to be on the call stack +when d is executing. The command ``info level'' may +be used to obtain the level of the current procedure. +

    +Uplevel makes it possible to implement new control +constructs as Tcl procedures (for example, uplevel could +be used to implement the while construct as a Tcl procedure). +

    +namespace eval is another way (besides procedure calls) +that the Tcl naming context can change. +It adds a call frame to the stack to represent the namespace context. +This means each namespace eval command +counts as another call level for uplevel and upvar commands. +For example, info level 1 will return a list +describing a command that is either +the outermost procedure call or the outermost namespace eval command. +Also, uplevel #0 evaluates a script +at top-level in the outermost namespace (the global namespace). + +

    SEE ALSO

    +namespace, upvar +

    KEYWORDS

    +context, level, namespace, stack frame, variables +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/upvar.htm b/hlp/en/tcl/upvar.htm new file mode 100644 index 0000000..64f1e88 --- /dev/null +++ b/hlp/en/tcl/upvar.htm @@ -0,0 +1,93 @@ +Built-In Commands - upvar manual page +

    NAME

    +upvar - Create link to variable in a different stack frame +

    SYNOPSIS

    +upvar ?level? otherVar myVar ?otherVar myVar ...?
    +

    DESCRIPTION

    +This command arranges for one or more local variables in the current +procedure to refer to variables in an enclosing procedure call or +to global variables. +Level may have any of the forms permitted for the uplevel +command, and may be omitted if the first letter of the first otherVar +isn't # or a digit (it defaults to 1). +For each otherVar argument, upvar makes the variable +by that name in the procedure frame given by level (or at +global level, if level is #0) accessible +in the current procedure by the name given in the corresponding +myVar argument. +The variable named by otherVar need not exist at the time of the +call; it will be created the first time myVar is referenced, just like +an ordinary variable. There must not exist a variable by the +name myVar at the time upvar is invoked. +MyVar is always treated as the name of a variable, not an +array element. Even if the name looks like an array element, +such as a(b), a regular variable is created. +OtherVar may refer to a scalar variable, an array, +or an array element. +Upvar returns an empty string. +

    +The upvar command simplifies the implementation of call-by-name +procedure calling and also makes it easier to build new control constructs +as Tcl procedures. +For example, consider the following procedure: +

    proc add2 name {
    +	upvar $name x
    +	set x [expr $x+2]
    +}
    +Add2 is invoked with an argument giving the name of a variable, +and it adds two to the value of that variable. +Although add2 could have been implemented using uplevel +instead of upvar, upvar makes it simpler for add2 +to access the variable in the caller's procedure frame. +

    +namespace eval is another way (besides procedure calls) +that the Tcl naming context can change. +It adds a call frame to the stack to represent the namespace context. +This means each namespace eval command +counts as another call level for uplevel and upvar commands. +For example, info level 1 will return a list +describing a command that is either +the outermost procedure call or the outermost namespace eval command. +Also, uplevel #0 evaluates a script +at top-level in the outermost namespace (the global namespace). +

    +If an upvar variable is unset (e.g. x in add2 above), the +unset operation affects the variable it is linked to, not the +upvar variable. There is no way to unset an upvar variable except +by exiting the procedure in which it is defined. However, it is +possible to retarget an upvar variable by executing another upvar +command. + +

    Traces and upvar

    +Upvar interacts with traces in a straightforward but possibly +unexpected manner. If a variable trace is defined on otherVar, that +trace will be triggered by actions involving myVar. However, +the trace procedure will be passed the name of myVar, rather +than the name of otherVar. Thus, the output of the following code +will be localVar rather than originalVar: +
    proc traceproc { name index op } {
    +	puts $name
    +}
    +proc setByUpvar { name value } {
    +	upvar $name localVar
    +	set localVar $value
    +}
    +set originalVar 1
    +trace variable originalVar w traceproc
    +setByUpvar originalVar 2
    +}
    +If otherVar refers to an element of an array, then variable +traces set for the entire array will not be invoked when myVar +is accessed (but traces on the particular element will still be +invoked). In particular, if the array is env, then changes +made to myVar will not be passed to subprocesses correctly. + +

    SEE ALSO

    +global, namespace, uplevel, variable +

    KEYWORDS

    +context, frame, global, level, namespace, procedure, variable +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/variable.htm b/hlp/en/tcl/variable.htm new file mode 100644 index 0000000..a6a0bb7 --- /dev/null +++ b/hlp/en/tcl/variable.htm @@ -0,0 +1,55 @@ +Tcl Built-In Commands - variable manual page +

    NAME

    +variable - create and initialize a namespace variable +

    SYNOPSIS

    +variable ?name value...? name ?value?
    +

    DESCRIPTION

    +This command is normally used within a +namespace eval command to create one or more variables +within a namespace. +Each variable name is initialized with value. +The value for the last variable is optional. +

    +If a variable name does not exist, it is created. +In this case, if value is specified, +it is assigned to the newly created variable. +If no value is specified, the new variable is left undefined. +If the variable already exists, +it is set to value if value is specified +or left unchanged if no value is given. +Normally, name is unqualified +(does not include the names of any containing namespaces), +and the variable is created in the current namespace. +If name includes any namespace qualifiers, +the variable is created in the specified namespace. If the variable +is not defined, it will be visible to the namespace which +command, but not to the info exists command. +

    +If the variable command is executed inside a Tcl procedure, +it creates local variables +linked to the corresponding namespace variables (and therefore these +variables are listed by info locals.) +In this way the variable command resembles the global command, +although the global command +only links to variables in the global namespace. +If any values are given, +they are used to modify the values of the associated namespace variables. +If a namespace variable does not exist, +it is created and optionally initialized. +

    +A name argument cannot reference an element within an array. +Instead, name should reference the entire array, +and the initialization value should be left off. +After the variable has been declared, +elements within the array can be set using ordinary +set or array commands. + +

    SEE ALSO

    +global, namespace, upvar +

    KEYWORDS

    +global, namespace, procedure, variable +
    +Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
    +Copyright © 1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/vwait.htm b/hlp/en/tcl/vwait.htm new file mode 100644 index 0000000..05dfec7 --- /dev/null +++ b/hlp/en/tcl/vwait.htm @@ -0,0 +1,32 @@ +Tcl Built-In Commands - vwait manual page +

    NAME

    +vwait - Process events until a variable is written +

    SYNOPSIS

    +vwaitvarName
    +

    DESCRIPTION

    +This command enters the Tcl event loop to process events, blocking +the application if no events are ready. It continues processing +events until some event handler sets the value of variable +varName. Once varName has been set, the vwait +command will return as soon as the event handler that modified +varName completes. varName must globally scoped +(either with a call to global for the varName, or with +the full namespace path specification). +

    +In some cases the vwait command may not return immediately +after varName is set. This can happen if the event handler +that sets varName does not complete immediately. For example, +if an event handler sets varName and then itself calls +vwait to wait for a different variable, then it may not return +for a long time. During this time the top-level vwait is +blocked waiting for the event handler to complete, so it cannot +return either. + +

    SEE ALSO

    +global +

    KEYWORDS

    +event, variable, wait +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tcl/while.htm b/hlp/en/tcl/while.htm new file mode 100644 index 0000000..3304a8b --- /dev/null +++ b/hlp/en/tcl/while.htm @@ -0,0 +1,44 @@ +Built-In Commands - while manual page +

    NAME

    +while - Execute script repeatedly as long as a condition is met +

    SYNOPSIS

    +while test body
    +

    DESCRIPTION

    +The while command evaluates test as an expression +(in the same way that expr evaluates its argument). +The value of the expression must a proper boolean +value; if it is a true value +then body is executed by passing it to the Tcl interpreter. +Once body has been executed then test is evaluated +again, and the process repeats until eventually test +evaluates to a false boolean value. Continue +commands may be executed inside body to terminate the current +iteration of the loop, and break +commands may be executed inside body to cause immediate +termination of the while command. The while command +always returns an empty string. +

    +Note: test should almost always be enclosed in braces. If not, +variable substitutions will be made before the while +command starts executing, which means that variable changes +made by the loop body will not be considered in the expression. +This is likely to result in an infinite loop. If test is +enclosed in braces, variable substitutions are delayed until the +expression is evaluated (before +each loop iteration), so changes in the variables will be visible. +For an example, try the following script with and without the braces +around $x<10: +

    set x 0
    +while {$x<10} {
    +	puts "x is $x"
    +	incr x
    +}
    +

    SEE ALSO

    +break, continue, for, foreach +

    KEYWORDS

    +boolean value, loop, test, while +
    +Copyright © 1993 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/bell.htm b/hlp/en/tk/bell.htm new file mode 100644 index 0000000..f851c96 --- /dev/null +++ b/hlp/en/tk/bell.htm @@ -0,0 +1,24 @@ +Tk Built-In Commands - bell manual page +

    NAME

    +bell - Ring a display's bell +

    SYNOPSIS

    +bell ?-displayof window?
    +

    DESCRIPTION

    +This command rings the bell on the display for window and +returns an empty string. +If the -displayof option is omitted, the display of the +application's main window is used by default. +The command uses the current bell-related settings for the display, which +may be modified with programs such as xset. +

    +This command also resets the screen saver for the screen. Some +screen savers will ignore this, but others will reset so that the +screen becomes visible again. + +

    KEYWORDS

    +beep, bell, ring +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/bind.htm b/hlp/en/tk/bind.htm new file mode 100644 index 0000000..0f19273 --- /dev/null +++ b/hlp/en/tk/bind.htm @@ -0,0 +1,525 @@ +Tk Built-In Commands - bind manual page +
    +
    NAME +
    bind - Arrange for X events to invoke Tcl scripts
    +
    SYNOPSIS +
    +
    bind tag +
    bind tag sequence +
    bind tag sequence script +
    bind tag sequence +script +
    +
    INTRODUCTION +
    EVENT PATTERNS +
    MODIFIERS +
    EVENT TYPES +
    +
    Activate +
    Deactivate +
    MouseWheel +
    +
    BINDING SCRIPTS AND SUBSTITUTIONS +
    +
    %% +
    %# +
    %a +
    %b +
    %c +
    %d +
    %f +
    %h +
    %k +
    %m +
    %o +
    %p +
    %s +
    %t +
    %w +
    %x +
    %y +
    %A +
    %B +
    %D +
    %E +
    %K +
    %N +
    %R +
    %S +
    %T +
    %W +
    %X +
    %Y +
    +
    MULTIPLE MATCHES +
    MULTI-EVENT SEQUENCES AND IGNORED EVENTS +
    ERRORS +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +bind - Arrange for X events to invoke Tcl scripts +

    SYNOPSIS

    +bind tag
    +bind tag sequence
    +bind tag sequence script
    +bind tag sequence +script
    +

    INTRODUCTION

    +The bind command associates Tcl scripts with X events. +If all three arguments are specified, bind will +arrange for script (a Tcl script) to be evaluated whenever +the event(s) given by sequence occur in the window(s) +identified by tag. +If script is prefixed with a ``+'', then it is appended to +any existing binding for sequence; otherwise script replaces +any existing binding. +If script is an empty string then the current binding for +sequence is destroyed, leaving sequence unbound. +In all of the cases where a script argument is provided, +bind returns an empty string. +

    +If sequence is specified without a script, then the +script currently bound to sequence is returned, or +an empty string is returned if there is no binding for sequence. +If neither sequence nor script is specified, then the +return value is a list whose elements are all the sequences +for which there exist bindings for tag. +

    +The tag argument determines which window(s) the binding applies to. +If tag begins with a dot, as in .a.b.c, then it must +be the path name for a window; otherwise it may be an arbitrary +string. +Each window has an associated list of tags, and a binding applies +to a particular window if its tag is among those specified for +the window. +Although the bindtags command may be used to assign an +arbitrary set of binding tags to a window, the default binding +tags provide the following behavior: +

    +If a tag is the name of an internal window the binding applies +to that window. +

    +If the tag is the name of a toplevel window the binding applies +to the toplevel window and all its internal windows. +

    +If the tag is the name of a class of widgets, such as Button, +the binding applies to all widgets in that class; +

    +If tag has the value all, +the binding applies to all windows in the application. + +

    +

    EVENT PATTERNS

    +The sequence argument specifies a sequence of one or more +event patterns, with optional white space between the patterns. Each +event pattern may +take one of three forms. In the simplest case it is a single +printing ASCII character, such as a or [. The character +may not be a space character or the character <. This form of +pattern matches a KeyPress event for the particular +character. The second form of pattern is longer but more general. +It has the following syntax: +
    <modifier-modifier-type-detail>
    +The entire event pattern is surrounded by angle brackets. +Inside the angle brackets are zero or more modifiers, an event +type, and an extra piece of information (detail) identifying +a particular button or keysym. Any of the fields may be omitted, +as long as at least one of type and detail is present. +The fields must be separated by white space or dashes. +

    +The third form of pattern is used to specify a user-defined, named virtual +event. It has the following syntax: +

    <<name>>
    +The entire virtual event pattern is surrounded by double angle brackets. +Inside the angle brackets is the user-defined name of the virtual event. +Modifiers, such as Shift or Control, may not be combined with a +virtual event to modify it. Bindings on a virtual event may be created +before the virtual event is defined, and if the definition of a virtual +event changes dynamically, all windows bound to that virtual event will +respond immediately to the new definition. +

    MODIFIERS

    +Modifiers consist of any of the following values: +
    Control	Mod2, M2
    +Shift	Mod3, M3	
    +Lock	Mod4, M4
    +Button1, B1	Mod5, M5	
    +Button2, B2	Meta, M
    +Button3, B3	Alt
    +Button4, B4	Double
    +Button5, B5	Triple
    +Mod1, M1	Quadruple
    +Where more than one value is listed, separated by commas, the values +are equivalent. +Most of the modifiers have the obvious X meanings. +For example, Button1 requires that +button 1 be depressed when the event occurs. +For a binding to match a given event, the modifiers in the event +must include all of those specified in the event pattern. +An event may also contain additional modifiers not specified in +the binding. +For example, if button 1 is pressed while the shift and control keys +are down, the pattern <Control-Button-1> will match +the event, but <Mod1-Button-1> will not. +If no modifiers are specified, then any combination of modifiers may +be present in the event. +

    +Meta and M refer to whichever of the +M1 through M5 modifiers is associated with the meta +key(s) on the keyboard (keysyms Meta_R and Meta_L). +If there are no meta keys, or if they are not associated with any +modifiers, then Meta and M will not match any events. +Similarly, the Alt modifier refers to whichever modifier +is associated with the alt key(s) on the keyboard (keysyms +Alt_L and Alt_R). +

    +The Double, Triple and Quadruple modifiers are a +convenience for specifying double mouse clicks and other repeated +events. They cause a particular event pattern to be repeated 2, 3 or 4 +times, and also place a time and space requirement on the sequence: for a +sequence of events to match a Double, Triple or Quadruple +pattern, all of the events must occur close together in time and without +substantial mouse motion in between. For example, <Double-Button-1> +is equivalent to <Button-1><Button-1> with the extra time and space +requirement. + +

    EVENT TYPES

    +The type field may be any of the standard X event types, with a +few extra abbreviations. The type field will also accept a +couple non-standard X event types that were added to better support +the Macintosh and Windows platforms. Below is a list of all the valid +types; where two names appear together, they are synonyms. +
    Activate	Enter	Map
    +ButtonPress, Button	Expose	Motion
    +ButtonRelease	FocusIn	MouseWheel	
    +Circulate	FocusOut	Property
    +Colormap	Gravity	Reparent
    +Configure	KeyPress, Key	Unmap
    +Deactivate	KeyRelease	Visibility
    +Destroy	Leave
    +

    +Most of the above events have the same fields and behaviors as events +in the X Windowing system. You can find more detailed descriptions of +these events in any X window programming book. A couple of the events +are extensions to the X event system to support features unique to the +Macintosh and Windows platforms. We provide a little more detail on +these events here. These include: +

    +

    +

    Activate
    +

    Deactivate
    +These two events are sent to every sub-window of a toplevel when they +change state. In addition to the focus Window, the Macintosh platform +and Windows platforms have a notion of an active window (which often +has but is not required to have the focus). On the Macintosh, widgets +in the active window have a different appearance than widgets in +deactive windows. The Activate event is sent to all the +sub-windows in a toplevel when it changes from being deactive to +active. Likewise, the Deactive event is sent when the window's +state changes from active to deactive. There are no useful percent +substitutions you would make when binding to these events. +

    MouseWheel
    +Some mice on the Windows platform support a mouse wheel which is used +for scrolling documents without using the scrollbars. By rolling the +wheel, the system will generate MouseWheel events that the +application can use to scroll. Like Key events the event is +always routed to the window that currently has focus. When the event +is received you can use the %D substitution to get the +delta field for the event which is a integer value of motion +that the mouse wheel has moved. The smallest value for which the +system will report is defined by the OS. On Windows 95 & 98 machines +this value is at least 120 before it is reported. However, higher +resolution devices may be available in the future. The sign of the +value determines which direction your widget should scroll. Positive +values should scroll up and negative values should scroll down. +

    +

    +The last part of a long event specification is detail. In the +case of a ButtonPress or ButtonRelease event, it is the +number of a button (1-5). If a button number is given, then only an +event on that particular button will match; if no button number is +given, then an event on any button will match. Note: giving a +specific button number is different than specifying a button modifier; +in the first case, it refers to a button being pressed or released, +while in the second it refers to some other button that is already +depressed when the matching event occurs. If a button +number is given then type may be omitted: if will default +to ButtonPress. For example, the specifier <1> +is equivalent to <ButtonPress-1>. +

    +If the event type is KeyPress or KeyRelease, then +detail may be specified in the form of an X keysym. Keysyms +are textual specifications for particular keys on the keyboard; +they include all the alphanumeric ASCII characters (e.g. ``a'' is +the keysym for the ASCII character ``a''), plus descriptions for +non-alphanumeric characters (``comma'' is the keysym for the comma +character), plus descriptions for all the non-ASCII keys on the +keyboard (``Shift_L'' is the keysm for the left shift key, and +``F1'' is the keysym for the F1 function key, if it exists). The +complete list of keysyms is not presented here; it is +available in other X documentation and may vary from system to +system. +If necessary, you can use the %K notation described below +to print out the keysym name for a particular key. +If a keysym detail is given, then the +type field may be omitted; it will default to KeyPress. +For example, <Control-comma> is equivalent to +<Control-KeyPress-comma>. + +

    BINDING SCRIPTS AND SUBSTITUTIONS

    +The script argument to bind is a Tcl script, +which will be executed whenever the given event sequence occurs. +Command will be executed in the same interpreter that the +bind command was executed in, and it will run at global +level (only global variables will be accessible). +If script contains +any % characters, then the script will not be +executed directly. Instead, a new script will be +generated by replacing each %, and the character following +it, with information from the current event. The replacement +depends on the character following the %, as defined in the +list below. Unless otherwise indicated, the +replacement string is the decimal value of the given field from +the current event. +Some of the substitutions are only valid for +certain types of events; if they are used for other types of events +the value substituted is undefined. +

    +

    +

    %%
    +Replaced with a single percent. +

    %#
    +The number of the last client request processed by the server +(the serial field from the event). Valid for all event +types. +

    %a
    +The above field from the event, +formatted as a hexadecimal number. +Valid only for Configure events. +

    %b
    +The number of the button that was pressed or released. Valid only +for ButtonPress and ButtonRelease events. +

    %c
    +The count field from the event. Valid only for Expose events. +

    %d
    +The detail field from the event. The %d is replaced by +a string identifying the detail. For Enter, +Leave, FocusIn, and FocusOut events, +the string will be one of the following: +
    NotifyAncestor	NotifyNonlinearVirtual
    +NotifyDetailNone	NotifyPointer
    +NotifyInferior	NotifyPointerRoot
    +NotifyNonlinear	NotifyVirtual
    +For events other than these, the substituted string is undefined. +

    %f
    +The focus field from the event (0 or 1). Valid only +for Enter and Leave events. +

    %h
    +The height field from the event. Valid for the Configure and +Expose events. +

    %k
    +The keycode field from the event. Valid only for KeyPress +and KeyRelease events. +

    %m
    +The mode field from the event. The substituted string is one of +NotifyNormal, NotifyGrab, NotifyUngrab, or +NotifyWhileGrabbed. Valid only for Enter, +FocusIn, FocusOut, and Leave events. +

    %o
    +The override_redirect field from the event. Valid only for +Map, Reparent, and Configure events. +

    %p
    +The place field from the event, substituted as one of the +strings PlaceOnTop or PlaceOnBottom. Valid only +for Circulate events. +

    %s
    +The state field from the event. For ButtonPress, +ButtonRelease, Enter, KeyPress, KeyRelease, +Leave, and Motion events, a decimal string +is substituted. For Visibility, one of the strings +VisibilityUnobscured, VisibilityPartiallyObscured, +and VisibilityFullyObscured is substituted. +

    %t
    +The time field from the event. Valid only for events that +contain a time field. +

    %w
    +The width field from the event. Valid only for +Configure and Expose events. +

    %x
    +The x field from the event. Valid only for events containing +an x field. +

    %y
    +The y field from the event. Valid only for events containing +a y field. +

    %A
    +Substitutes the ASCII character corresponding to the event, or +the empty string if the event doesn't correspond to an ASCII character +(e.g. the shift key was pressed). XLookupString does all the +work of translating from the event to an ASCII character. +Valid only for KeyPress and KeyRelease events. +

    %B
    +The border_width field from the event. Valid only for +Configure events. +

    %D
    +This reports the delta value of a MouseWheel event. The +delta value represents the rotation units the mouse wheel has +been moved. On Windows 95 & 98 systems the smallest value for the +delta is 120. Future systems may support higher resolution values for +the delta. The sign of the value represents the direction the mouse +wheel was scrolled. +

    %E
    +The send_event field from the event. Valid for all event types. +

    %K
    +The keysym corresponding to the event, substituted as a textual +string. Valid only for KeyPress and KeyRelease events. +

    %N
    +The keysym corresponding to the event, substituted as a decimal +number. Valid only for KeyPress and KeyRelease events. +

    %R
    +The root window identifier from the event. Valid only for +events containing a root field. +

    %S
    +The subwindow window identifier from the event, +formatted as a hexadecimal number. +Valid only for events containing a subwindow field. +

    %T
    +The type field from the event. Valid for all event types. +

    %W
    +The path name of the window to which the event was reported (the +window field from the event). Valid for all event types. +

    %X
    +The x_root field from the event. +If a virtual-root window manager is being used then the substituted +value is the corresponding x-coordinate in the virtual root. +Valid only for +ButtonPress, ButtonRelease, KeyPress, KeyRelease, +and Motion events. +

    %Y
    +The y_root field from the event. +If a virtual-root window manager is being used then the substituted +value is the corresponding y-coordinate in the virtual root. +Valid only for +ButtonPress, ButtonRelease, KeyPress, KeyRelease, +and Motion events. +

    +

    +The replacement string for a %-replacement is formatted as a proper +Tcl list element. +This means that it will be surrounded with braces +if it contains spaces, or special characters such as $ and +{ may be preceded by backslashes. +This guarantees that the string will be passed through the Tcl +parser when the binding script is evaluated. +Most replacements are numbers or well-defined strings such +as Above; for these replacements no special formatting +is ever necessary. +The most common case where reformatting occurs is for the %A +substitution. For example, if script is +

    insert %A
    +and the character typed is an open square bracket, then the script +actually executed will be +
    insert \[
    +This will cause the insert to receive the original replacement +string (open square bracket) as its first argument. +If the extra backslash hadn't been added, Tcl would not have been +able to parse the script correctly. + +

    MULTIPLE MATCHES

    +It is possible for several bindings to match a given X event. +If the bindings are associated with different tag's, +then each of the bindings will be executed, in order. +By default, a binding for the widget will be executed first, followed +by a class binding, a binding for its toplevel, and +an all binding. +The bindtags command may be used to change this order for +a particular window or to associate additional binding tags with +the window. +

    +The continue and break commands may be used inside a +binding script to control the processing of matching scripts. +If continue is invoked, then the current binding script +is terminated but Tk will continue processing binding scripts +associated with other tag's. +If the break command is invoked within a binding script, +then that script terminates and no other scripts will be invoked +for the event. +

    +If more than one binding matches a particular event and they +have the same tag, then the most specific binding +is chosen and its script is evaluated. +The following tests are applied, in order, to determine which of +several matching sequences is more specific: +(a) an event pattern that specifies a specific button or key is more specific +than one that doesn't; +(b) a longer sequence (in terms of number +of events matched) is more specific than a shorter sequence; +(c) if the modifiers specified in one pattern are a subset of the +modifiers in another pattern, then the pattern with more modifiers +is more specific. +(d) a virtual event whose physical pattern matches the sequence is less +specific than the same physical pattern that is not associated with a +virtual event. +(e) given a sequence that matches two or more virtual events, one +of the virtual events will be chosen, but the order is undefined. +

    +If the matching sequences contain more than one event, then tests +(c)-(e) are applied in order from the most recent event to the least recent +event in the sequences. If these tests fail to determine a winner, then the +most recently registered sequence is the winner. +

    +If there are two (or more) virtual events that are both triggered by the +same sequence, and both of those virtual events are bound to the same window +tag, then only one of the virtual events will be triggered, and it will +be picked at random: +

    event add <<Paste>> <Control-y>
    +event add <<Paste>> <Button-2>
    +event add <<Scroll>> <Button-2>
    +bind Entry <<Paste>> {puts Paste}
    +bind Entry <<Scroll>> {puts Scroll}
    +If the user types Control-y, the <<Paste>> binding +will be invoked, but if the user presses button 2 then one of +either the <<Paste>> or the <<Scroll>> bindings will +be invoked, but exactly which one gets invoked is undefined. +

    +If an X event does not match any of the existing bindings, then the +event is ignored. +An unbound event is not considered to be an error. + +

    MULTI-EVENT SEQUENCES AND IGNORED EVENTS

    +When a sequence specified in a bind command contains +more than one event pattern, then its script is executed whenever +the recent events (leading up to and including the current event) +match the given sequence. This means, for example, that if button 1 is +clicked repeatedly the sequence <Double-ButtonPress-1> will match +each button press but the first. +If extraneous events that would prevent a match occur in the middle +of an event sequence then the extraneous events are +ignored unless they are KeyPress or ButtonPress events. +For example, <Double-ButtonPress-1> will match a sequence of +presses of button 1, even though there will be ButtonRelease +events (and possibly Motion events) between the +ButtonPress events. +Furthermore, a KeyPress event may be preceded by any number +of other KeyPress events for modifier keys without the +modifier keys preventing a match. +For example, the event sequence aB will match a press of the +a key, a release of the a key, a press of the Shift +key, and a press of the b key: the press of Shift is +ignored because it is a modifier key. +Finally, if several Motion events occur in a row, only +the last one is used for purposes of matching binding sequences. + +

    ERRORS

    +If an error occurs in executing the script for a binding then the +bgerror mechanism is used to report the error. +The bgerror command will be executed at global level +(outside the context of any Tcl procedure). + +

    SEE ALSO

    +bgerror, keysyms +

    KEYWORDS

    +form, manual +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1998 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/bindtags.htm b/hlp/en/tk/bindtags.htm new file mode 100644 index 0000000..64f6ef1 --- /dev/null +++ b/hlp/en/tk/bindtags.htm @@ -0,0 +1,66 @@ +Tk Built-In Commands - bindtags manual page +

    NAME

    +bindtags - Determine which bindings apply to a window, and order of evaluation +

    SYNOPSIS

    +bindtags window ?tagList?
    +

    DESCRIPTION

    +When a binding is created with the bind command, it is +associated either with a particular window such as .a.b.c, +a class name such as Button, the keyword all, or any +other string. +All of these forms are called binding tags. +Each window contains a list of binding tags that determine how +events are processed for the window. +When an event occurs in a window, it is applied to each of the +window's tags in order: for each tag, the most specific binding +that matches the given tag and event is executed. +See the bind command for more information on the matching +process. +

    +By default, each window has four binding tags consisting of the +name of the window, the window's class name, the name of the window's +nearest toplevel ancestor, and all, in that order. +Toplevel windows have only three tags by default, since the toplevel +name is the same as that of the window. +The bindtags command allows the binding tags for a window to be +read and modified. +

    +If bindtags is invoked with only one argument, then the +current set of binding tags for window is returned as a list. +If the tagList argument is specified to bindtags, +then it must be a proper list; the tags for window are changed +to the elements of the list. +The elements of tagList may be arbitrary strings; however, +any tag starting with a dot is treated as the name of a window; if +no window by that name exists at the time an event is processed, +then the tag is ignored for that event. +The order of the elements in tagList determines the order in +which binding scripts are executed in response to events. +For example, the command +

    bindtags .b {all . Button .b}
    +reverses the order in which binding scripts will be evaluated for +a button named .b so that all bindings are invoked +first, following by bindings for .b's toplevel (``.''), followed by +class bindings, followed by bindings for .b. +If tagList is an empty list then the binding tags for window +are returned to the default state described above. +

    +The bindtags command may be used to introduce arbitrary +additional binding tags for a window, or to remove standard tags. +For example, the command +

    bindtags .b {.b TrickyButton . all}
    +replaces the Button tag for .b with TrickyButton. +This means that the default widget bindings for buttons, which are +associated with the Button tag, will no longer apply to .b, +but any bindings associated with TrickyButton (perhaps some +new button behavior) will apply. + +

    SEE ALSO

    +bind +

    KEYWORDS

    +binding, event, tag +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/bitmap.htm b/hlp/en/tk/bitmap.htm new file mode 100644 index 0000000..22b630a --- /dev/null +++ b/hlp/en/tk/bitmap.htm @@ -0,0 +1,122 @@ +Tk Built-In Commands - bitmap manual page +
    +
    NAME +
    bitmap - Images that display two colors
    +
    SYNOPSIS +
    +
    image create bitmap ?name? ?options? +
    +
    DESCRIPTION +
    CREATING BITMAPS +
    +
    -background color +
    -data string +
    -file name +
    -foreground color +
    -maskdata string +
    -maskfile name +
    +
    IMAGE COMMAND +
    +
    imageName cget option +
    imageName configure ?option? ?value option value ...? +
    +
    KEYWORDS +

    +

    NAME

    +bitmap - Images that display two colors +

    SYNOPSIS

    +image create bitmap ?name? ?options?
    +

    DESCRIPTION

    +A bitmap is an image whose pixels can display either of two colors +or be transparent. +A bitmap image is defined by four things: a background color, +a foreground color, and two bitmaps, called the source +and the mask. +Each of the bitmaps specifies 0/1 values for a rectangular +array of pixels, and the two bitmaps must have the same +dimensions. +For pixels where the mask is zero, the image displays nothing, +producing a transparent effect. +For other pixels, the image displays the foreground color if +the source data is one and the background color if the source +data is zero. + +

    CREATING BITMAPS

    +Like all images, bitmaps are created using the image create +command. +Bitmaps support the following options: +

    +

    +

    -background color
    +Specifies a background color for the image in any of the standard +ways accepted by Tk. If this option is set to an empty string +then the background pixels will be transparent. This effect +is achieved by using the source bitmap as the mask bitmap, ignoring +any -maskdata or -maskfile options. +

    -data string
    +Specifies the contents of the source bitmap as a string. +The string must adhere to X11 bitmap format (e.g., as generated +by the bitmap program). +If both the -data and -file options are specified, +the -data option takes precedence. +

    -file name
    +name gives the name of a file whose contents define the +source bitmap. +The file must adhere to X11 bitmap format (e.g., as generated +by the bitmap program). +

    -foreground color
    +Specifies a foreground color for the image in any of the standard +ways accepted by Tk. +

    -maskdata string
    +Specifies the contents of the mask as a string. +The string must adhere to X11 bitmap format (e.g., as generated +by the bitmap program). +If both the -maskdata and -maskfile options are specified, +the -maskdata option takes precedence. +

    -maskfile name
    +name gives the name of a file whose contents define the +mask. +The file must adhere to X11 bitmap format (e.g., as generated +by the bitmap program). + +

    +

    IMAGE COMMAND

    +When a bitmap image is created, Tk also creates a new command +whose name is the same as the image. +This command may be used to invoke various operations +on the image. +It has the following general form: +
    imageName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for bitmap images: +

    +

    +

    imageName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the +image create bitmap command. +

    imageName configure ?option? ?value option value ...?
    +Query or modify the configuration options for the image. +If no option is specified, returns a list describing all of +the available options for imageName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the +image create bitmap command. + +

    +

    KEYWORDS

    +bitmap, image +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/button.htm b/hlp/en/tk/button.htm new file mode 100644 index 0000000..87ec7b2 --- /dev/null +++ b/hlp/en/tk/button.htm @@ -0,0 +1,244 @@ +Tk Built-In Commands - button manual page +
    +
    NAME +
    button - Create and manipulate button widgets
    +
    SYNOPSIS +
    +
    button pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -command, command, Command +
    -default, default, Default +
    -height, height, Height +
    -state, state, State +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName flash +
    pathName invoke +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +button - Create and manipulate button widgets +

    SYNOPSIS

    +buttonpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -command +
    Database Name: command +
    Database Class: Command +
    Specifies a Tcl command to associate with the button. This command +is typically invoked when mouse button 1 is released over the button +window. +

    Command-Line Name: -default +
    Database Name: default +
    Database Class: Default +
    Specifies one of three states for the default ring: normal, +active, or disabled. In active state, the button is drawn +with the platform specific appearance for a default button. In normal +state, the button is drawn with the platform specific appearance for a +non-default button, leaving enough space to draw the default button +appearance. The normal and active states will result in buttons of +the same size. In disabled state, the button is drawn with the +non-default button appearance without leaving space for the default +appearance. The disabled state may result in a smaller button than +the active state. +ring. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the button. +If an image or bitmap is being displayed in the button then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the button's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the button: normal, active, +or disabled. In normal state the button is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the button. In active state +the button is displayed using the activeForeground and +activeBackground options. Disabled state means that the button +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the button is displayed. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the button. +If an image or bitmap is being displayed in the button then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the button's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    DESCRIPTION

    +The button command creates a new window (given by the +pathName argument) and makes it into a button widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the button such as its colors, font, +text, and initial relief. The button command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A button is a widget that displays a textual string, bitmap or image. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. +It can display itself in either of three different ways, according +to +the state option; +it can be made to appear raised, sunken, or flat; +and it can be made to flash. When a user invokes the +button (by pressing mouse button 1 with the cursor over the +button), then the Tcl command specified in the -command +option is invoked. + +

    WIDGET COMMAND

    +The button command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for button widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the button +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the button +command. +

    pathName flash
    +Flash the button. This is accomplished by redisplaying the button +several times, alternating between active and normal colors. At +the end of the flash the button is left in the same normal/active +state as when the command was invoked. +This command is ignored if the button's state is disabled. +

    pathName invoke
    +Invoke the Tcl command associated with the button, if there is one. +The return value is the return value from the Tcl command, or an +empty string if there is no command associated with the button. +This command is ignored if the button's state is disabled. + +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for buttons that give them +default behavior: +

    +

    +

    [1]
    +A button activates whenever the mouse passes over it and deactivates +whenever the mouse leaves the button. +Under Windows, this binding is only active when mouse button 1 has +been pressed over the button. +

    [2]
    +A button's relief is changed to sunken whenever mouse button 1 is +pressed over the button, and the relief is restored to its original +value when button 1 is later released. +

    [3]
    +If mouse button 1 is pressed over a button and later released over +the button, the button is invoked. However, if the mouse is not +over the button when button 1 is released, then no invocation occurs. +

    [4]
    +When a button has the input focus, the space key causes the button +to be invoked. +

    +

    +If the button's state is disabled then none of the above +actions occur: the button is completely non-responsive. +

    +The behavior of buttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +button, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/canvas.htm b/hlp/en/tk/canvas.htm new file mode 100644 index 0000000..c201016 --- /dev/null +++ b/hlp/en/tk/canvas.htm @@ -0,0 +1,1826 @@ +Tk Built-In Commands - canvas manual page +
    +
    NAME +
    canvas - Create and manipulate canvas widgets
    +
    SYNOPSIS +
    +
    canvas pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -state +
    -takefocus, takeFocus, TakeFocus +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -closeenough, closeEnough, CloseEnough +
    -confine, confine, Confine +
    -height, height, Height +
    -scrollregion, scrollRegion, ScrollRegion +
    -state, state, State +
    -width, width, width +
    -xscrollincrement, xScrollIncrement, ScrollIncrement +
    -yscrollincrement, yScrollIncrement, ScrollIncrement +
    +
    INTRODUCTION +
    DISPLAY LIST +
    ITEM IDS AND TAGS +
    COORDINATES +
    TRANSFORMATIONS +
    INDICES +
    +
    number +
    end +
    insert +
    sel.first +
    sel.last +
    @x,y +
    +
    DASH PATTERNS +
    WIDGET COMMAND +
    +
    pathName addtag tag searchSpec ?arg arg ...? +
    +
    above tagOrId +
    all +
    below tagOrId +
    closest x y ?halo? ?start? +
    enclosed x1 y1 x2 y2 +
    overlapping x1 y1 x2 y2 +
    withtag tagOrId +
    +
    pathName bbox tagOrId ?tagOrId tagOrId ...? +
    pathName bind tagOrId ?sequence? ?command? +
    pathName canvasx screenx ?gridspacing? +
    pathName canvasy screeny ?gridspacing? +
    pathName cget option +
    pathName configure ?option? ?value? ?option value ...? +
    pathName coords tagOrId ?x0 y0 ...? +
    pathName coords tagOrId ?coordList? +
    pathName create type x y ?x y ...? ?option value ...? +
    pathName create type coordList ?option value ...? +
    pathName dchars tagOrId first ?last? +
    pathName delete ?tagOrId tagOrId ...? +
    pathName dtag tagOrId ?tagToDelete? +
    pathName find searchCommand ?arg arg ...? +
    pathName focus ?tagOrId? +
    pathName gettags tagOrId +
    pathName icursor tagOrId index +
    pathName index tagOrId index +
    pathName insert tagOrId beforeThis string +
    pathName itemcget tagOrId option +
    pathName itemconfigure tagOrId ?option? ?value? ?option value ...? +
    pathName lower tagOrId ?belowThis? +
    pathName move tagOrId xAmount yAmount +
    pathName postscript ?option value option value ...? +
    +
    -colormap varName +
    -colormode mode +
    -file fileName +
    -fontmap varName +
    -height size +
    -pageanchor anchor +
    -pageheight size +
    -pagewidth size +
    -pagex position +
    -pagey position +
    -rotate boolean +
    -width size +
    -x position +
    -y position +
    +
    pathName raise tagOrId ?aboveThis? +
    pathName scale tagOrId xOrigin yOrigin xScale yScale +
    pathName scan option args +
    +
    pathName scan mark x y +
    pathName scan dragto x y ?gain?. +
    +
    pathName select option ?tagOrId arg? +
    +
    pathName select adjust tagOrId index +
    pathName select clear +
    pathName select from tagOrId index +
    pathName select item +
    pathName select to tagOrId index +
    +
    pathName type tagOrId +
    pathName xview ?args? +
    +
    pathName xview +
    pathName xview moveto fraction +
    pathName xview scroll number what +
    +
    pathName yview ?args? +
    +
    pathName yview +
    pathName yview moveto fraction +
    pathName yview scroll number what +
    +
    +
    OVERVIEW OF ITEM TYPES +
    COMMON ITEM OPTIONS +
    +
    -dash pattern +
    -activedash pattern +
    -disableddash pattern +
    -dashoffset offset +
    -fill color +
    -activefill color +
    -disabledfill color +
    -outline color +
    -activeoutline color +
    -disabledoutline color +
    -offset offset +
    -outlinestipple bitmap +
    -activeoutlinestipple bitmap +
    -disabledoutlinestipple bitmap +
    -stipple bitmap +
    -activestipple bitmap +
    -disabledstipple bitmap +
    -state state +
    -tags tagList +
    -width outlineWidth +
    -activewidth outlineWidth +
    -disabledwidth outlineWidth +
    +
    ARC ITEMS +
    +
    -extent degrees +
    -start degrees +
    -style type +
    +
    BITMAP ITEMS +
    +
    -anchor anchorPos +
    -background color +
    -activebackground bitmap +
    -disabledbackground bitmap +
    -bitmap bitmap +
    -activebitmap bitmap +
    -disabledbitmap bitmap +
    -foreground color +
    -activeforeground bitmap +
    -disabledforeground bitmap +
    +
    IMAGE ITEMS +
    +
    -anchor anchorPos +
    -image name +
    -activeimage name +
    -disabledimage name +
    +
    LINE ITEMS +
    +
    -arrow where +
    -arrowshape shape +
    -capstyle style +
    -joinstyle style +
    -smooth boolean +
    -splinesteps number +
    +
    OVAL ITEMS +
    POLYGON ITEMS +
    +
    -joinstyle style +
    -smooth boolean +
    -splinesteps number +
    +
    RECTANGLE ITEMS +
    TEXT ITEMS +
    +
    -anchor anchorPos +
    -font fontName +
    -justify how +
    -text string +
    -width lineLength +
    +
    WINDOW ITEMS +
    +
    -anchor anchorPos +
    -height pixels +
    -width pixels +
    -window pathName +
    +
    APPLICATION-DEFINED ITEM TYPES +
    BINDINGS +
    CREDITS +
    KEYWORDS +

    +

    NAME

    +canvas - Create and manipulate canvas widgets +

    SYNOPSIS

    +canvaspathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -state +
    -takefocus, takeFocus, TakeFocus +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -closeenough +
    Database Name: closeEnough +
    Database Class: CloseEnough +
    Specifies a floating-point value indicating how close the mouse cursor +must be to an item before it is considered to be ``inside'' the item. +Defaults to 1.0. +

    Command-Line Name: -confine +
    Database Name: confine +
    Database Class: Confine +
    Specifies a boolean value that indicates whether or not it should be +allowable to set the canvas's view outside the region defined by the +scrollRegion argument. +Defaults to true, which means that the view will +be constrained within the scroll region. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired window height that the canvas widget should request from +its geometry manager. The value may be specified in any +of the forms described in the COORDINATES section below. +

    Command-Line Name: -scrollregion +
    Database Name: scrollRegion +
    Database Class: ScrollRegion +
    Specifies a list with four coordinates describing the left, top, right, and +bottom coordinates of a rectangular region. +This region is used for scrolling purposes and is considered to be +the boundary of the information in the canvas. +Each of the coordinates may be specified +in any of the forms given in the COORDINATES section below. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Modifies the default state of the canvas where state may be set to +one of: normal, disabled, or hidden. Individual canvas +objects all have their own state option which may override the default +state. Many options can take separate specifications such that the +appearance of the item can be different in different situations. The +options that start with active control the appearence when the mouse +pointer is over it, while the option starting with disabled controls +the appearence when the state is disabled. Canvas items which are +disabled will not react to canvas bindings. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: width +
    Specifies a desired window width that the canvas widget should request from +its geometry manager. The value may be specified in any +of the forms described in the COORDINATES section below. +

    Command-Line Name: -xscrollincrement +
    Database Name: xScrollIncrement +
    Database Class: ScrollIncrement +
    Specifies an increment for horizontal scrolling, in any of the usual forms +permitted for screen distances. If the value of this option is greater +than zero, the horizontal view in the window will be constrained so that +the canvas x coordinate at the left edge of the window is always an even +multiple of xScrollIncrement; furthermore, the units for scrolling +(e.g., the change in view when the left and right arrows of a scrollbar +are selected) will also be xScrollIncrement. If the value of +this option is less than or equal to zero, then horizontal scrolling +is unconstrained. +

    Command-Line Name: -yscrollincrement +
    Database Name: yScrollIncrement +
    Database Class: ScrollIncrement +
    Specifies an increment for vertical scrolling, in any of the usual forms +permitted for screen distances. If the value of this option is greater +than zero, the vertical view in the window will be constrained so that +the canvas y coordinate at the top edge of the window is always an even +multiple of yScrollIncrement; furthermore, the units for scrolling +(e.g., the change in view when the top and bottom arrows of a scrollbar +are selected) will also be yScrollIncrement. If the value of +this option is less than or equal to zero, then vertical scrolling +is unconstrained. +
    +

    INTRODUCTION

    +The canvas command creates a new window (given +by the pathName argument) and makes it into a canvas widget. +Additional options, described above, may be specified on the +command line or in the option database +to configure aspects of the canvas such as its colors and 3-D relief. +The canvas command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +Canvas widgets implement structured graphics. +A canvas displays any number of items, which may be things like +rectangles, circles, lines, and text. +Items may be manipulated (e.g. moved or re-colored) and commands may +be associated with items in much the same way that the bind +command allows commands to be bound to widgets. For example, +a particular command may be associated with the <Button-1> event +so that the command is invoked whenever button 1 is pressed with +the mouse cursor over an item. +This means that items in a canvas can have behaviors defined by +the Tcl scripts bound to them. + +

    DISPLAY LIST

    +The items in a canvas are ordered for purposes of display, +with the first item in the display list being displayed +first, followed by the next item in the list, and so on. +Items later in the display list obscure those that are +earlier in the display list and are sometimes referred to +as being ``on top'' of earlier items. +When a new item is created it is placed at the end of the +display list, on top of everything else. +Widget commands may be used to re-arrange the order of the +display list. +

    +Window items are an exception to the above rules. The underlying +window systems require them always to be drawn on top of other items. +In addition, the stacking order of window items +is not affected by any of the canvas widget commands; you must use +the raise and lower Tk commands instead. + +

    ITEM IDS AND TAGS

    +Items in a canvas widget may be named in either of two ways: +by id or by tag. +Each item has a unique identifying number which is assigned to +that item when it is created. The id of an item never changes +and id numbers are never re-used within the lifetime of a +canvas widget. +

    +Each item may also have any number of tags associated +with it. A tag is just a string of characters, and it may +take any form except that of an integer. +For example, ``x123'' is OK but ``123'' isn't. +The same tag may be associated with many different items. +This is commonly done to group items in various interesting +ways; for example, all selected items might be given the +tag ``selected''. +

    +The tag all is implicitly associated with every item +in the canvas; it may be used to invoke operations on +all the items in the canvas. +

    +The tag current is managed automatically by Tk; +it applies to the current item, which is the +topmost item whose drawn area covers the position of +the mouse cursor. +If the mouse is not in the canvas widget or is not over +an item, then no item has the current tag. +

    +When specifying items in canvas widget commands, if the +specifier is an integer then it is assumed to refer to +the single item with that id. +If the specifier is not an integer, then it is assumed to +refer to all of the items in the canvas that have a tag +matching the specifier. +The symbol tagOrId is used below to indicate that +an argument specifies either an id that selects a single +item or a tag that selects zero or more items. +

    +tagOrId may contain a logical expressions of +tags by using operators: '&&', '||', '^' '!', and parenthezised +subexpressions. For example: +

    .c find withtag {(a&&!b)||(!a&&b)}
    +or equivalently: +
    .c find withtag {a^b}
    +will find only those items with either "a" or "b" tags, but not both. +

    +Some widget commands only operate on a single item at a +time; if tagOrId is specified in a way that +names multiple items, then the normal behavior is for +the command to use the first (lowest) of these items in +the display list that is suitable for the command. +Exceptions are noted in the widget command descriptions +below. + +

    COORDINATES

    +All coordinates related to canvases are stored as floating-point +numbers. +Coordinates and distances are specified in screen units, +which are floating-point numbers optionally followed +by one of several letters. +If no letter is supplied then the distance is in pixels. +If the letter is m then the distance is in millimeters on +the screen; if it is c then the distance is in centimeters; +i means inches, and p means printers points (1/72 inch). +Larger y-coordinates refer to points lower on the screen; larger +x-coordinates refer to points farther to the right. +Coordinates can be specified either as an even number of parameters, +or as a single list parameter containing an even number of x and y +coordinate values. + +

    TRANSFORMATIONS

    +Normally the origin of the canvas coordinate system is at the +upper-left corner of the window containing the canvas. +It is possible to adjust the origin of the canvas +coordinate system relative to the origin of the window using the +xview and yview widget commands; this is typically used +for scrolling. +Canvases do not support scaling or rotation of the canvas coordinate +system relative to the window coordinate system. +

    +Individual items may be moved or scaled using widget commands +described below, but they may not be rotated. + +

    INDICES

    +Text items support the notion of an index for identifying +particular positions within the item. +In a similar fashion, line and polygon items support index for +identifying, inserting and deleting subsets of their coordinates. +Indices are used for commands such as inserting or deleting +a range of characters or coordinates, and setting the insertion +cursor position. An index may be specified in any of a number +of ways, and different types of items may support different forms +for specifying indices. +Text items support the following forms for an index; if you +define new types of text-like items, it would be advisable to +support as many of these forms as practical. +Note that it is possible to refer to the character just after +the last one in the text item; this is necessary for such +tasks as inserting new text at the end of the item. +Lines and Polygons don't support the insertion cursor +and the selection. Their indixes are supposed to be even +always, because coordinates always appear in pairs. +

    +

    +

    number
    +A decimal number giving the position of the desired character +within the text item. +0 refers to the first character, 1 to the next character, and +so on. If indexes are odd for lines and polygons, they will be +automatically decremented by one. +A number less than 0 is treated as if it were zero, and a +number greater than the length of the text item is treated +as if it were equal to the length of the text item. For +polygons, numbers less than 0 or greater then the length +of the coordinate list will be adjusted by adding or substracting +the length until the result is between zero and the length, +inclusive. +

    end
    +Refers to the character or coordinate just after the last one +in the item (same as the number of characters or coordinates +in the item). +

    insert
    +Refers to the character just before which the insertion cursor +is drawn in this item. Not valid for lines and polygons. +

    sel.first
    +Refers to the first selected character in the item. +If the selection isn't in this item then this form is illegal. +

    sel.last
    +Refers to the last selected character in the item. +If the selection isn't in this item then this form is illegal. +

    @x,y
    +Refers to the character or coordinate at the point given by x and +y, where x and y are specified in the coordinate +system of the canvas. +If x and y lie outside the coordinates covered by the +text item, then they refer to the first or last character in the +line that is closest to the given point. + +

    +

    DASH PATTERNS

    +Many items support the notion of an dash pattern for outlines. +

    +The first possible syntax is a list of integers. Each element +represents the number of pixels of a line segment. Only the odd +segments are drawn using the "outline" color. The other segments +are drawn transparant. +

    +The second possible syntax is a character list containing only +5 possible characters [.,-_ ]. The space can be used +to enlarge the space between other line elements, and can not +occur as the first position in the string. Some examples: + -dash . = -dash {2 4} + -dash - = -dash {6 4} + -dash -. = -dash {6 4 2 4} + -dash -.. = -dash {6 4 2 4 2 4} + -dash {. } = -dash {2 8} + -dash , = -dash {4 4} +

    +The main difference of this syntax with the previous is that it +it shape-conserving. This means that all values in the dash +list will be multiplied by the line width before display. This +assures that "." will always be displayed as a dot and "-" +always as a dash regardless of the line width. +

    +On systems which support only a limited set of dash patterns, the dash +pattern will be displayed as the closest dash pattern that is available. +For example, on Windows only the first 4 of the above examples are +available. The last 2 examples will be displayed identically to the first +one. + +

    WIDGET COMMAND

    +The canvas command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. +The following widget commands are possible for canvas widgets: +

    +

    +

    pathName addtag tag searchSpec ?arg arg ...?
    +For each item that meets the constraints specified by +searchSpec and the args, add +tag to the list of tags associated with the item if it +isn't already present on that list. +It is possible that no items will satisfy the constraints +given by searchSpec and args, in which case the +command has no effect. +This command returns an empty string as result. +SearchSpec and arg's may take any of the following +forms: +

    +

    +

    above tagOrId
    +Selects the item just after (above) the one given by tagOrId +in the display list. +If tagOrId denotes more than one item, then the last (topmost) +of these items in the display list is used. +

    all
    +Selects all the items in the canvas. +

    below tagOrId
    +Selects the item just before (below) the one given by tagOrId +in the display list. +If tagOrId denotes more than one item, then the first (lowest) +of these items in the display list is used. +

    closest x y ?halo? ?start?
    +Selects the item closest to the point given by x and y. +If more than one item is at the same closest distance (e.g. two +items overlap the point), then the top-most of these items (the +last one in the display list) is used. +If halo is specified, then it must be a non-negative +value. +Any item closer than halo to the point is considered to +overlap it. +The start argument may be used to step circularly through +all the closest items. +If start is specified, it names an item using a tag or id +(if by tag, it selects the first item in the display list with +the given tag). +Instead of selecting the topmost closest item, this form will +select the topmost closest item that is below start in +the display list; if no such item exists, then the selection +behaves as if the start argument had not been specified. +

    enclosed x1 y1 x2 y2
    +Selects all the items completely enclosed within the rectangular +region given by x1, y1, x2, and y2. +X1 must be no greater then x2 and y1 must be +no greater than y2. +

    overlapping x1 y1 x2 y2
    +Selects all the items that overlap or are enclosed within the +rectangular region given by x1, y1, x2, +and y2. +X1 must be no greater then x2 and y1 must be +no greater than y2. +

    withtag tagOrId
    +Selects all the items given by tagOrId. +

    +

    pathName bbox tagOrId ?tagOrId tagOrId ...?
    +Returns a list with four elements giving an approximate bounding box +for all the items named by the tagOrId arguments. +The list has the form ``x1 y1 x2 y2'' such that the drawn +areas of all the named elements are within the region bounded by +x1 on the left, x2 on the right, y1 on the top, +and y2 on the bottom. +The return value may overestimate the actual bounding box by +a few pixels. +If no items match any of the tagOrId arguments or if the +matching items have empty bounding boxes (i.e. they have nothing +to display) +then an empty string is returned. +

    pathName bind tagOrId ?sequence? ?command?
    +This command associates command with all the items given by +tagOrId such that whenever the event sequence given by +sequence occurs for one of the items the command will +be invoked. +This widget command is similar to the bind command except that +it operates on items in a canvas rather than entire widgets. +See the bind manual entry for complete details +on the syntax of sequence and the substitutions performed +on command before invoking it. +If all arguments are specified then a new binding is created, replacing +any existing binding for the same sequence and tagOrId +(if the first character of command is ``+'' then command +augments an existing binding rather than replacing it). +In this case the return value is an empty string. +If command is omitted then the command returns the command +associated with tagOrId and sequence (an error occurs +if there is no such binding). +If both command and sequence are omitted then the command +returns a list of all the sequences for which bindings have been +defined for tagOrId. +

    +The only events for which bindings may be specified are those related to +the mouse and keyboard (such as Enter, Leave, +ButtonPress, Motion, and KeyPress) or virtual events. +The handling of events in canvases uses the current item defined in ITEM +IDS AND TAGS above. Enter and Leave events trigger for an +item when it becomes the current item or ceases to be the current item; +note that these events are different than Enter and Leave +events for windows. Mouse-related events are directed to the current +item, if any. Keyboard-related events are directed to the focus item, if +any (see the focus widget command below for more on this). If a +virtual event is used in a binding, that binding can trigger only if the +virtual event is defined by an underlying mouse-related or +keyboard-related event. +

    +It is possible for multiple bindings to match a particular event. +This could occur, for example, if one binding is associated with the +item's id and another is associated with one of the item's tags. +When this occurs, all of the matching bindings are invoked. +A binding associated with the all tag is invoked first, +followed by one binding for each of the item's tags (in order), +followed by a binding associated with the item's id. +If there are multiple matching bindings for a single tag, +then only the most specific binding is invoked. +A continue command in a binding script terminates that +script, and a break command terminates that script +and skips any remaining scripts for the event, just as for the +bind command. +

    If bindings have been created for a canvas window using the bind +command, then they are invoked in addition to bindings created for +the canvas's items using the bind widget command. +The bindings for items will be invoked before any of the bindings +for the window as a whole. +

    pathName canvasx screenx ?gridspacing?
    +Given a window x-coordinate in the canvas screenx, this command returns +the canvas x-coordinate that is displayed at that location. +If gridspacing is specified, then the canvas coordinate is +rounded to the nearest multiple of gridspacing units. +

    pathName canvasy screeny ?gridspacing?
    +Given a window y-coordinate in the canvas screeny this command returns +the canvas y-coordinate that is displayed at that location. +If gridspacing is specified, then the canvas coordinate is +rounded to the nearest multiple of gridspacing units. +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the canvas +command. +

    pathName configure ?option? ?value? ?option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the canvas +command. +

    pathName coords tagOrId ?x0 y0 ...?
    +

    pathName coords tagOrId ?coordList?
    +Query or modify the coordinates that define an item. +If no coordinates are specified, this command returns a list +whose elements are the coordinates of the item named by +tagOrId. +If coordinates are specified, then they replace the current +coordinates for the named item. +If tagOrId refers to multiple items, then +the first one in the display list is used. +

    pathName create type x y ?x y ...? ?option value ...?
    +

    pathName create type coordList ?option value ...?
    +Create a new item in pathName of type type. +The exact format of the arguments after type depends +on type, but usually they consist of the coordinates for +one or more points, followed by specifications for zero or +more item options. +See the subsections on individual item types below for more +on the syntax of this command. +This command returns the id for the new item. +

    pathName dchars tagOrId first ?last?
    +For each item given by tagOrId, delete the characters, or coordinates, +in the range given by first and last, inclusive. +If some of the items given by tagOrId don't support +indexing operations then they ignore dchars. +Text items interpret first and last as indices to a character, +line and polygon items interpret them indices to a coordinate (an x,y pair). +Indices are described in INDICES above. +If last is omitted, it defaults to first. +This command returns an empty string. +

    pathName delete ?tagOrId tagOrId ...?
    +Delete each of the items given by each tagOrId, and return +an empty string. +

    pathName dtag tagOrId ?tagToDelete?
    +For each of the items given by tagOrId, delete the +tag given by tagToDelete from the list of those +associated with the item. +If an item doesn't have the tag tagToDelete then +the item is unaffected by the command. +If tagToDelete is omitted then it defaults to tagOrId. +This command returns an empty string. +

    pathName find searchCommand ?arg arg ...?
    +This command returns a list consisting of all the items that +meet the constraints specified by searchCommand and +arg's. +SearchCommand and args have any of the forms +accepted by the addtag command. +The items are returned in stacking order, with the lowest item first. +

    pathName focus ?tagOrId?
    +Set the keyboard focus for the canvas widget to the item given by +tagOrId. +If tagOrId refers to several items, then the focus is set +to the first such item in the display list that supports the +insertion cursor. +If tagOrId doesn't refer to any items, or if none of them +support the insertion cursor, then the focus isn't changed. +If tagOrId is an empty +string, then the focus item is reset so that no item has the focus. +If tagOrId is not specified then the command returns the +id for the item that currently has the focus, or an empty string +if no item has the focus. +

    +Once the focus has been set to an item, the item will display +the insertion cursor and all keyboard events will be directed +to that item. +The focus item within a canvas and the focus window on the +screen (set with the focus command) are totally independent: +a given item doesn't actually have the input focus unless (a) +its canvas is the focus window and (b) the item is the focus item +within the canvas. +In most cases it is advisable to follow the focus widget +command with the focus command to set the focus window to +the canvas (if it wasn't there already). +

    pathName gettags tagOrId
    +Return a list whose elements are the tags associated with the +item given by tagOrId. +If tagOrId refers to more than one item, then the tags +are returned from the first such item in the display list. +If tagOrId doesn't refer to any items, or if the item +contains no tags, then an empty string is returned. +

    pathName icursor tagOrId index
    +Set the position of the insertion cursor for the item(s) given by tagOrId +to just before the character whose position is given by index. +If some or all of the items given by tagOrId don't support +an insertion cursor then this command has no effect on them. +See INDICES above for a description of the +legal forms for index. +Note: the insertion cursor is only displayed in an item if +that item currently has the keyboard focus (see the widget +command focus, below), but the cursor position may +be set even when the item doesn't have the focus. +This command returns an empty string. +

    pathName index tagOrId index
    +This command returns a decimal string giving the numerical index +within tagOrId corresponding to index. +Index gives a textual description of the desired position +as described in INDICES above. +Text items interpret index as an index to a character, +line and polygon items interpret it as an index to a coordinate (an x,y pair). +The return value is guaranteed to lie between 0 and the number +of characters, or coordinates, within the item, inclusive. +If tagOrId refers to multiple items, then the index +is processed in the first of these items that supports indexing +operations (in display list order). +

    pathName insert tagOrId beforeThis string
    +For each of the items given by tagOrId, if the item supports +text or coordinate, insertion then string is inserted into the item's +text just before the character, or coordinate, whose index is beforeThis. +Text items interpret beforethis as an index to a character, +line and polygon items interpret it as an index to a coordinate (an x,y pair). +For lines and polygons the string must be a valid coordinate +sequence. +See INDICES above for information about the forms allowed +for beforeThis. +This command returns an empty string. +

    pathName itemcget tagOrId option
    +Returns the current value of the configuration option for the +item given by tagOrId whose name is option. +This command is similar to the cget widget command except that +it applies to a particular item rather than the widget as a whole. +Option may have any of the values accepted by the create +widget command when the item was created. +If tagOrId is a tag that refers to more than one item, +the first (lowest) such item is used. +

    pathName itemconfigure tagOrId ?option? ?value? ?option value ...?
    +This command is similar to the configure widget command except +that it modifies item-specific options for the items given by +tagOrId instead of modifying options for the overall +canvas widget. +If no option is specified, returns a list describing all of +the available options for the first item given by tagOrId +(see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s) in +each of the items given by tagOrId; in +this case the command returns an empty string. +The options and values are the same as those permissible +in the create widget command when the item(s) were created; +see the sections describing individual item types below for details +on the legal options. +

    pathName lower tagOrId ?belowThis?
    +Move all of the items given by tagOrId to a new position +in the display list just before the item given by belowThis. +If tagOrId refers to more than one item then all are moved +but the relative order of the moved items will not be changed. +BelowThis is a tag or id; if it refers to more than one +item then the first (lowest) of these items in the display list is used +as the destination location for the moved items. +Note: this command has no effect on window items. Window items always +obscure other item types, and the stacking order of window items is +determined by the raise and lower commands, not the +raise and lower widget commands for canvases. +This command returns an empty string. +

    pathName move tagOrId xAmount yAmount
    +Move each of the items given by tagOrId in the canvas coordinate +space by adding xAmount to the x-coordinate of each point +associated with the item and yAmount to the y-coordinate of +each point associated with the item. +This command returns an empty string. +

    pathName postscript ?option value option value ...?
    +Generate a Postscript representation for part or all of the canvas. +If the -file option is specified then the Postscript is written +to a file and an empty string is returned; otherwise the Postscript +is returned as the result of the command. +If the interpreter that owns the canvas is marked as safe, the operation +will fail because safe interpreters are not allowed to write files. +If the -channel option is specified, the argument denotes the name +of a channel already opened for writing. The Postscript is written to +that channel, and the channel is left open for further writing at the end +of the operation. +The Postscript is created in Encapsulated Postscript form using +version 3.0 of the Document Structuring Conventions. +Note: by default Postscript is only generated for information that +appears in the canvas's window on the screen. If the canvas is +freshly created it may still have its initial size of 1x1 pixel +so nothing will appear in the Postscript. To get around this problem +either invoke the "update" command to wait for the canvas window +to reach its final size, or else use the -width and -height +options to specify the area of the canvas to print. +The option-value argument pairs provide additional +information to control the generation of Postscript. The following +options are supported: +

    +

    +

    -colormap varName
    +VarName must be the name of an array variable +that specifies a color mapping to use in the Postscript. +Each element of varName must consist of Postscript +code to set a particular color value (e.g. ``1.0 1.0 0.0 setrgbcolor''). +When outputting color information in the Postscript, Tk checks +to see if there is an element of varName with the same +name as the color. +If so, Tk uses the value of the element as the Postscript command +to set the color. +If this option hasn't been specified, or if there isn't an entry +in varName for a given color, then Tk uses the red, green, +and blue intensities from the X color. +

    -colormode mode
    +Specifies how to output color information. Mode must be either +color (for full color output), gray (convert all colors +to their gray-scale equivalents) or mono (convert all colors +to black or white). +

    -file fileName
    +Specifies the name of the file in which to write the Postscript. +If this option isn't specified then the Postscript is returned as the +result of the command instead of being written to a file. +

    -fontmap varName
    +VarName must be the name of an array variable +that specifies a font mapping to use in the Postscript. +Each element of varName must consist of a Tcl list with +two elements, which are the name and point size of a Postscript font. +When outputting Postscript commands for a particular font, Tk +checks to see if varName contains an element with the same +name as the font. +If there is such an element, then the font information contained in +that element is used in the Postscript. +Otherwise Tk attempts to guess what Postscript font to use. +Tk's guesses generally only work for well-known fonts such as +Times and Helvetica and Courier, and only if the X font name does not +omit any dashes up through the point size. +For example, -*-Courier-Bold-R-Normal--*-120-* will work but +*Courier-Bold-R-Normal*120* will not; Tk needs the dashes to +parse the font name). +

    -height size
    +Specifies the height of the area of the canvas to print. +Defaults to the height of the canvas window. +

    -pageanchor anchor
    +Specifies which point of the printed area of the canvas should appear over +the positioning point on the page (which is given by the -pagex +and -pagey options). +For example, -pageanchor n means that the top center of the +area of the canvas being printed (as it appears in the canvas window) +should be over the positioning point. Defaults to center. +

    -pageheight size
    +Specifies that the Postscript should be scaled in both x and y so +that the printed area is size high on the Postscript page. +Size consists of a floating-point number followed by +c for centimeters, i for inches, m for millimeters, +or p or nothing for printer's points (1/72 inch). +Defaults to the height of the printed area on the screen. +If both -pageheight and -pagewidth are specified then +the scale factor from -pagewidth is used (non-uniform scaling +is not implemented). +

    -pagewidth size
    +Specifies that the Postscript should be scaled in both x and y so +that the printed area is size wide on the Postscript page. +Size has the same form as for -pageheight. +Defaults to the width of the printed area on the screen. +If both -pageheight and -pagewidth are specified then +the scale factor from -pagewidth is used (non-uniform scaling +is not implemented). +

    -pagex position
    +Position gives the x-coordinate of the positioning point on +the Postscript page, using any of the forms allowed for -pageheight. +Used in conjunction with the -pagey and -pageanchor options +to determine where the printed area appears on the Postscript page. +Defaults to the center of the page. +

    -pagey position
    +Position gives the y-coordinate of the positioning point on +the Postscript page, using any of the forms allowed for -pageheight. +Used in conjunction with the -pagex and -pageanchor options +to determine where the printed area appears on the Postscript page. +Defaults to the center of the page. +

    -rotate boolean
    +Boolean specifies whether the printed area is to be rotated 90 +degrees. +In non-rotated output the x-axis of the printed area runs along +the short dimension of the page (``portrait'' orientation); +in rotated output the x-axis runs along the long dimension of the +page (``landscape'' orientation). +Defaults to non-rotated. +

    -width size
    +Specifies the width of the area of the canvas to print. +Defaults to the width of the canvas window. +

    -x position
    +Specifies the x-coordinate of the left edge of the area of the +canvas that is to be printed, in canvas coordinates, not window +coordinates. +Defaults to the coordinate of the left edge of the window. +

    -y position
    +Specifies the y-coordinate of the top edge of the area of the +canvas that is to be printed, in canvas coordinates, not window +coordinates. +Defaults to the coordinate of the top edge of the window. +

    +

    pathName raise tagOrId ?aboveThis?
    +Move all of the items given by tagOrId to a new position +in the display list just after the item given by aboveThis. +If tagOrId refers to more than one item then all are moved +but the relative order of the moved items will not be changed. +AboveThis is a tag or id; if it refers to more than one +item then the last (topmost) of these items in the display list is used +as the destination location for the moved items. +Note: this command has no effect on window items. Window items always +obscure other item types, and the stacking order of window items is +determined by the raise and lower commands, not the +raise and lower widget commands for canvases. +This command returns an empty string. +

    pathName scale tagOrId xOrigin yOrigin xScale yScale
    +Rescale all of the items given by tagOrId in canvas coordinate +space. +XOrigin and yOrigin identify the origin for the scaling +operation and xScale and yScale identify the scale +factors for x- and y-coordinates, respectively (a scale factor of +1.0 implies no change to that coordinate). +For each of the points defining each item, the x-coordinate is +adjusted to change the distance from xOrigin by a factor +of xScale. +Similarly, each y-coordinate is adjusted to change the distance +from yOrigin by a factor of yScale. +This command returns an empty string. +

    pathName scan option args
    +This command is used to implement scanning on canvases. It has +two forms, depending on option: +

    +

    +

    pathName scan mark x y
    +Records x and y and the canvas's current view; used +in conjunction with later scan dragto commands. +Typically this command is associated with a mouse button press in +the widget and x and y are the coordinates of the +mouse. It returns an empty string. +

    pathName scan dragto x y ?gain?.
    +This command computes the difference between its x and y +arguments (which are typically mouse coordinates) and the x and +y arguments to the last scan mark command for the widget. +It then adjusts the view by gain times the +difference in coordinates, where gain defaults to 10. +This command is typically associated +with mouse motion events in the widget, to produce the effect of +dragging the canvas at high speed through its window. The return +value is an empty string. +

    +

    pathName select option ?tagOrId arg?
    +Manipulates the selection in one of several ways, depending on +option. +The command may take any of the forms described below. +In all of the descriptions below, tagOrId must refer to +an item that supports indexing and selection; if it refers to +multiple items then the first of +these that supports indexing and the selection is used. +Index gives a textual description of a position +within tagOrId, as described in INDICES above. +

    +

    +

    pathName select adjust tagOrId index
    +Locate the end of the selection in tagOrId nearest +to the character given by index, and adjust that +end of the selection to be at index (i.e. including +but not going beyond index). +The other end of the selection is made the anchor point +for future select to commands. +If the selection isn't currently in tagOrId then +this command behaves the same as the select to widget +command. +Returns an empty string. +

    pathName select clear
    +Clear the selection if it is in this widget. +If the selection isn't in this widget then the command +has no effect. +Returns an empty string. +

    pathName select from tagOrId index
    +Set the selection anchor point for the widget to be just +before the character +given by index in the item given by tagOrId. +This command doesn't change the selection; it just sets +the fixed end of the selection for future select to +commands. +Returns an empty string. +

    pathName select item
    +Returns the id of the selected item, if the selection is in an +item in this canvas. +If the selection is not in this canvas then an empty string +is returned. +

    pathName select to tagOrId index
    +Set the selection to consist of those characters of tagOrId +between the selection anchor point and +index. +The new selection will include the character given by index; +it will include the character given by the anchor point only if +index is greater than or equal to the anchor point. +The anchor point is determined by the most recent select adjust +or select from command for this widget. +If the selection anchor point for the widget isn't currently in +tagOrId, then it is set to the same character given +by index. +Returns an empty string. +

    +

    pathName type tagOrId
    +Returns the type of the item given by tagOrId, such as +rectangle or text. +If tagOrId refers to more than one item, then the type +of the first item in the display list is returned. +If tagOrId doesn't refer to any items at all then +an empty string is returned. +

    pathName xview ?args?
    +This command is used to query and change the horizontal position of the +information displayed in the canvas's window. +It can take any of the following forms: +

    +

    +

    pathName xview
    +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the horizontal span that is visible in the window. +For example, if the first element is .2 and the second element is .6, +20% of the canvas's area (as defined by the -scrollregion option) +is off-screen to the left, the middle 40% is visible +in the window, and 40% of the canvas is off-screen to the right. +These are the same values passed to scrollbars via the -xscrollcommand +option. +

    pathName xview moveto fraction
    +Adjusts the view in the window so that fraction of the +total width of the canvas is off-screen to the left. +Fraction must be a fraction between 0 and 1. +

    pathName xview scroll number what
    +This command shifts the view in the window left or right according to +number and what. +Number must be an integer. +What must be either units or pages or an abbreviation +of one of these. +If what is units, the view adjusts left or right in units +of the xScrollIncrement option, if it is greater than zero, +or in units of one-tenth the window's width otherwise. +If what is pages then the view +adjusts in units of nine-tenths the window's width. +If number is negative then information farther to the left +becomes visible; if it is positive then information farther to the right +becomes visible. +

    +

    pathName yview ?args?
    +This command is used to query and change the vertical position of the +information displayed in the canvas's window. +It can take any of the following forms: +

    +

    +

    pathName yview
    +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the vertical span that is visible in the window. +For example, if the first element is .6 and the second element is 1.0, +the lowest 40% of the canvas's area (as defined by the -scrollregion +option) is visible in the window. +These are the same values passed to scrollbars via the -yscrollcommand +option. +

    pathName yview moveto fraction
    +Adjusts the view in the window so that fraction of the canvas's +area is off-screen to the top. +Fraction is a fraction between 0 and 1. +

    pathName yview scroll number what
    +This command adjusts the view in the window up or down according to +number and what. +Number must be an integer. +What must be either units or pages. +If what is units, the view adjusts up or down in units +of the yScrollIncrement option, if it is greater than zero, +or in units of one-tenth the window's height otherwise. +If what is pages then +the view adjusts in units of nine-tenths the window's height. +If number is negative then higher information becomes +visible; if it is positive then lower information +becomes visible. +

    +

    +

    OVERVIEW OF ITEM TYPES

    +The sections below describe the various types of items supported +by canvas widgets. Each item type is characterized by two things: +first, the form of the create command used to create +instances of the type; and second, a set of configuration options +for items of that type, which may be used in the +create and itemconfigure widget commands. +Most items don't support indexing or selection or the commands +related to them, such as index and insert. +Where items do support these facilities, it is noted explicitly +in the descriptions below. +At present, text, line and polygon items provide this support. +For lines and polygons the indexing facility is used to manipulate +the coordinates of the item. + +

    COMMON ITEM OPTIONS

    +Many items share a common set of options. These options are +explained here, and then referred to be each widget type for brevity. +

    +

    +

    +

    -dash pattern
    +

    -activedash pattern
    +

    -disableddash pattern
    +This option specifies dash patterns for the normal, active +state, and disabled state of an item. +pattern may have any of the forms accepted by Tk_GetDash. +If the dash options are omitted then the default is a solid outline. +See "DASH PATTERNS" for more information. +

    -dashoffset offset
    +The starting offset in pixels into the pattern provided by the +-dash option. -dashoffset is ignored if there is no +-dash pattern. The offset may have any of the forms described +in the COORDINATES section above. +

    -fill color
    +

    -activefill color
    +

    -disabledfill color
    +Specifies the color to be used to fill item's area. +in its normal, active, and disabled states, +Color may have any of the forms accepted by Tk_GetColor. +If color is an empty string (the default), then +then the item will not be filled. +For the line item, it specifies the color of the line drawn. +For the text item, it specifies the foreground color of the text. +

    -outline color
    +

    -activeoutline color
    +

    -disabledoutline color
    +This option specifies the color that should be used to draw the +outline of the item in its normal, active and disabled states. +Color may have any of the forms accepted by Tk_GetColor. +This option defaults to black. If color is specified +as an empty string then no outline is drawn for the item. +

    -offset offset
    +Specifies the offset of stipples. The offset value can be of the form +x,y or side, where side can be n, ne, e, +se, s, sw, w, nw, or center. In the +first case the origin is the origin of the toplevel of the current window. +For the canvas itself and canvas objects the origin is the canvas origin, +but putting # in front of the coordinate pair indicates using the +toplevel origin instead. For canvas objects, the -offset option is +used for stippling as well. For the line and polygon canvas items you can +also specify an index as argument, which connects the stipple origin to one +of the coordinate points of the line/polygon. +

    -outlinestipple bitmap
    +

    -activeoutlinestipple bitmap
    +

    -disabledoutlinestipple bitmap
    +This option specifies stipple patterns that should be used to draw the +outline of the item in its normal, active and disabled states. +Indicates that the outline for the item should be drawn with a stipple pattern; +bitmap specifies the stipple pattern to use, in any of the +forms accepted by Tk_GetBitmap. +If the -outline option hasn't been specified then this option +has no effect. +If bitmap is an empty string (the default), then the outline is drawn +in a solid fashion. +

    -stipple bitmap
    +

    -activestipple bitmap
    +

    -disabledstipple bitmap
    +This option specifies stipple patterns that should be used to fill the +the item in its normal, active and disabled states. +bitmap specifies the stipple pattern to use, in any of the +forms accepted by Tk_GetBitmap. +If the -fill option hasn't been specified then this option +has no effect. +If bitmap is an empty string (the default), then filling is done +in a solid fashion. +For the text item, it affects the actual text. +

    -state state
    +This allows an item to override the canvas widget's global state +option. It takes the same values: +normal, disabled or hidden. +

    -tags tagList
    +Specifies a set of tags to apply to the item. +TagList consists of a list of tag names, which replace any +existing tags for the item. TagList may be an empty list. +

    -width outlineWidth
    +

    -activewidth outlineWidth
    +

    -disabledwidth outlineWidth
    +Specifies the width of the outline to be drawn around +the item's region, in its normal, active and disabled states. +outlineWidth may be in any of the forms described in the COORDINATES +section above. +If the -outline option has been specified as an empty string then +this option has no effect. This option defaults to 1.0. +For arcs, wide outlines will be drawn centered on the edges of the +arc's region. + +

    +

    ARC ITEMS

    +Items of type arc appear on the display as arc-shaped regions. +An arc is a section of an oval delimited by two angles (specified +by the -start and -extent options) and displayed in +one of several ways (specified by the -style option). +Arcs are created with widget commands of the following form: +
    pathName create arc x1 y1 x2 y2 ?option value option value ...?
    +pathName create arc coordList ?option value option value ...?
    +The arguments x1, y1, x2, and y2 or coordList give +the coordinates of two diagonally opposite corners of a +rectangular region enclosing the oval that defines the arc. +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by arcs: +
    -dash
    +-activedash
    +-disableddash
    +-dashoffset
    +-fill
    +-activefill
    +-disabledfill
    +-offset
    +-outline
    +-activeoutline
    +-disabledoutline
    +-outlinestipple
    +-activeoutlinestipple
    +-disabledoutlinestipple
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +-width
    +-activewidth
    +-disabledwidth
    +The following extra options are supported for arcs: +

    +

    +

    -extent degrees
    +Specifies the size of the angular range occupied by the arc. +The arc's range extends for degrees degrees counter-clockwise +from the starting angle given by the -start option. +Degrees may be negative. +If it is greater than 360 or less than -360, then degrees +modulo 360 is used as the extent. +

    -start degrees
    +Specifies the beginning of the angular range occupied by the +arc. +Degrees is given in units of degrees measured counter-clockwise +from the 3-o'clock position; it may be either positive or negative. +

    -style type
    +Specifies how to draw the arc. If type is pieslice +(the default) then the arc's region is defined by a section +of the oval's perimeter plus two line segments, one between the center +of the oval and each end of the perimeter section. +If type is chord then the arc's region is defined +by a section of the oval's perimeter plus a single line segment +connecting the two end points of the perimeter section. +If type is arc then the arc's region consists of +a section of the perimeter alone. +In this last case the -fill option is ignored. + +

    +

    BITMAP ITEMS

    +Items of type bitmap appear on the display as images with +two colors, foreground and background. +Bitmaps are created with widget commands of the following form: +
    pathName create bitmap x y ?option value option value ...?
    +pathName create bitmap coordList ?option value option value ...?
    +The arguments x and y or coordList specify the coordinates of a +point used to position the bitmap on the display (see the -anchor +option below for more information on how bitmaps are displayed). +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by bitmaps: +
    -state
    +-tags
    +The following extra options are supported for bitmaps: +

    +

    +

    -anchor anchorPos
    +AnchorPos tells how to position the bitmap relative to the +positioning point for the item; it may have any of the forms +accepted by Tk_GetAnchor. For example, if anchorPos +is center then the bitmap is centered on the point; if +anchorPos is n then the bitmap will be drawn so that +its top center point is at the positioning point. +This option defaults to center. +

    -background color
    +

    -activebackground bitmap
    +

    -disabledbackground bitmap
    +Specifies the color to use for each of the bitmap's '0' valued pixels +in its normal, active and disabled states. +Color may have any of the forms accepted by Tk_GetColor. +If this option isn't specified, or if it is specified as an empty +string, then nothing is displayed where the bitmap pixels are 0; this +produces a transparent effect. +

    -bitmap bitmap
    +

    -activebitmap bitmap
    +

    -disabledbitmap bitmap
    +Specifies the bitmaps to display in the item in its normal, active and +disabled states. +Bitmap may have any of the forms accepted by Tk_GetBitmap. +

    -foreground color
    +

    -activeforeground bitmap
    +

    -disabledforeground bitmap
    +Specifies the color to use for each of the bitmap's '1' valued pixels +in its normal, active and disabled states. +Color may have any of the forms accepted by Tk_GetColor and +defaults to black. + +

    +

    IMAGE ITEMS

    +Items of type image are used to display images on a +canvas. +Images are created with widget commands of the following form: +
    pathName create image x y ?option value option value ...?
    +pathName create image coordList ?option value option value ...?
    +The arguments x and y or coordList specify the coordinates of a +point used to position the image on the display (see the -anchor +option below for more information). +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by images: +
    -state
    +-tags
    +The following extra options are supported for images: +

    +

    +

    -anchor anchorPos
    +AnchorPos tells how to position the image relative to the +positioning point for the item; it may have any of the forms +accepted by Tk_GetAnchor. For example, if anchorPos +is center then the image is centered on the point; if +anchorPos is n then the image will be drawn so that +its top center point is at the positioning point. +This option defaults to center. +

    -image name
    +

    -activeimage name
    +

    -disabledimage name
    +Specifies the name of the images to display in the item in is normal, +active and disabled states. +This image must have been created previously with the +image create command. + +

    +

    LINE ITEMS

    +Items of type line appear on the display as one or more connected +line segments or curves. +Line items support coordinate indexing operations using the canvas +widget commands: dchars, index, insert. +Lines are created with widget commands of the following form: +
    pathName create line x1 y1... xn yn ?option value option value ...?
    +pathName create line coordList ?option value option value ...?
    +The arguments x1 through yn or coordList give +the coordinates for a series of two or more points that describe +a series of connected line segments. +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by lines: +
    -dash
    +-activedash
    +-disableddash
    +-dashoffset
    +-fill
    +-activefill
    +-disabledfill
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +-width
    +-activewidth
    +-disabledwidth
    +The following extra options are supported for lines: +

    +

    +

    -arrow where
    +Indicates whether or not arrowheads are to be drawn at one or both +ends of the line. +Where must have one of the values none (for no arrowheads), +first (for an arrowhead at the first point of the line), +last (for an arrowhead at the last point of the line), or +both (for arrowheads at both ends). +This option defaults to none. +

    -arrowshape shape
    +This option indicates how to draw arrowheads. +The shape argument must be a list with three elements, each +specifying a distance in any of the forms described in +the COORDINATES section above. +The first element of the list gives the distance along the line +from the neck of the arrowhead to its tip. +The second element gives the distance along the line from the +trailing points of the arrowhead to the tip, and the third +element gives the distance from the outside edge of the line to the +trailing points. +If this option isn't specified then Tk picks a ``reasonable'' shape. +

    -capstyle style
    +Specifies the ways in which caps are to be drawn at the endpoints +of the line. +Style may have any of the forms accepted by Tk_GetCapStyle +(butt, projecting, or round). +If this option isn't specified then it defaults to butt. +Where arrowheads are drawn the cap style is ignored. +

    -joinstyle style
    +Specifies the ways in which joints are to be drawn at the vertices +of the line. +Style may have any of the forms accepted by Tk_GetCapStyle +(bevel, miter, or round). +If this option isn't specified then it defaults to miter. +If the line only contains two points then this option is +irrelevant. +

    -smooth boolean
    +Boolean must have one of the forms accepted by Tk_GetBoolean. +It indicates whether or not the line should be drawn as a curve. +If so, the line is rendered as a set of parabolic splines: one spline +is drawn for the first and second line segments, one for the second +and third, and so on. Straight-line segments can be generated within +a curve by duplicating the end-points of the desired line segment. +

    -splinesteps number
    +Specifies the degree of smoothness desired for curves: each spline +will be approximated with number line segments. This +option is ignored unless the -smooth option is true. + +

    +

    OVAL ITEMS

    +Items of type oval appear as circular or oval regions on +the display. Each oval may have an outline, a fill, or +both. Ovals are created with widget commands of the +following form: +
    pathName create oval x1 y1 x2 y2 ?option value option value ...?
    +pathName create oval coordList ?option value option value ...?
    +The arguments x1, y1, x2, and y2 or coordList give +the coordinates of two diagonally opposite corners of a +rectangular region enclosing the oval. +The oval will include the top and left edges of the rectangle +not the lower or right edges. +If the region is square then the resulting oval is circular; +otherwise it is elongated in shape. +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by ovals: +
    -dash
    +-activedash
    +-disableddash
    +-dashoffset
    +-fill
    +-activefill
    +-disabledfill
    +-offset
    +-outline
    +-activeoutline
    +-disabledoutline
    +-outlinestipple
    +-activeoutlinestipple
    +-disabledoutlinestipple
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +-width
    +-activewidth
    +-disabledwidth
    +

    POLYGON ITEMS

    +Items of type polygon appear as polygonal or curved filled regions +on the display. +Polygon items support coordinate indexing operations using the canvas +widget commands: dchars, index, insert. +Polygons are created with widget commands of the following form: +
    pathName create polygon x1 y1 ... xn yn ?option value option value ...?
    +pathName create polygon coordList ?option value option value ...?
    +The arguments x1 through yn or coordList specify the coordinates for +three or more points that define a polygon. +The first point should not be repeated as the last to +close the shape; Tk will automatically close the periphery between +the first and last points. +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by polygons: +
    -dash
    +-activedash
    +-disableddash
    +-dashoffset
    +-fill
    +-activefill
    +-disabledfill
    +-offset
    +-outline
    +-activeoutline
    +-disabledoutline
    +-outlinestipple
    +-activeoutlinestipple
    +-disabledoutlinestipple
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +-width
    +-activewidth
    +-disabledwidth
    +The following extra options are supported for polygons: +

    +

    +

    -joinstyle style
    +Specifies the ways in which joints are to be drawn at the vertices +of the outline. +Style may have any of the forms accepted by Tk_GetCapStyle +(bevel, miter, or round). +If this option isn't specified then it defaults to miter. +

    -smooth boolean
    +Boolean must have one of the forms accepted by Tk_GetBoolean +It indicates whether or not the polygon should be drawn with a +curved perimeter. +If so, the outline of the polygon becomes a set of parabolic splines, +one spline for the first and second line segments, one for the second +and third, and so on. Straight-line segments can be generated in a +smoothed polygon by duplicating the end-points of the desired line segment. +

    -splinesteps number
    +Specifies the degree of smoothness desired for curves: each spline +will be approximated with number line segments. This +option is ignored unless the -smooth option is true. +

    +

    +Polygon items are different from other items such as rectangles, ovals +and arcs in that interior points are considered to be ``inside'' a +polygon (e.g. for purposes of the find closest and +find overlapping widget commands) even if it is not filled. +For most other item types, an +interior point is considered to be inside the item only if the item +is filled or if it has neither a fill nor an outline. If you would +like an unfilled polygon whose interior points are not considered +to be inside the polygon, use a line item instead. + +

    RECTANGLE ITEMS

    +Items of type rectangle appear as rectangular regions on +the display. Each rectangle may have an outline, a fill, or +both. Rectangles are created with widget commands of the +following form: +
    pathName create rectangle x1 y1 x2 y2 ?option value option value ...?
    +pathName create rectangle coordList ?option value option value ...?
    +The arguments x1, y1, x2, and y2 or coordList give +the coordinates of two diagonally opposite corners of the rectangle +(the rectangle will include its upper and left edges but not +its lower or right edges). +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by rectangles: +
    -dash
    +-activedash
    +-disableddash
    +-dashoffset
    +-fill
    +-activefill
    +-disabledfill
    +-offset
    +-outline
    +-activeoutline
    +-disabledoutline
    +-outlinestipple
    +-activeoutlinestipple
    +-disabledoutlinestipple
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +-width
    +-activewidth
    +-disabledwidth
    +

    TEXT ITEMS

    +A text item displays a string of characters on the screen in one +or more lines. +Text items support indexing and selection, along with the +following text-related canvas widget commands: dchars, +focus, icursor, index, insert, +select. +Text items are created with widget commands of the following +form: +
    pathName create text x y ?option value option value ...?
    +pathName create text coordList ?option value option value ...?
    +The arguments x and y or coordList specify the coordinates of a +point used to position the text on the display (see the options +below for more information on how text is displayed). +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by text items: +
    -fill
    +-activefill
    +-disabledfill
    +-stipple
    +-activestipple
    +-disabledstipple
    +-state
    +-tags
    +The following extra options are supported for text items: +

    +

    +

    -anchor anchorPos
    +AnchorPos tells how to position the text relative to the +positioning point for the text; it may have any of the forms +accepted by Tk_GetAnchor. For example, if anchorPos +is center then the text is centered on the point; if +anchorPos is n then the text will be drawn such that +the top center point of the rectangular region occupied by the +text will be at the positioning point. +This option defaults to center. +

    -font fontName
    +Specifies the font to use for the text item. +FontName may be any string acceptable to Tk_GetFont. +If this option isn't specified, it defaults to a system-dependent +font. +

    -justify how
    +Specifies how to justify the text within its bounding region. +How must be one of the values left, right, +or center. +This option will only matter if the text is displayed as multiple +lines. +If the option is omitted, it defaults to left. +

    -text string
    +String specifies the characters to be displayed in the text item. +Newline characters cause line breaks. +The characters in the item may also be changed with the +insert and delete widget commands. +This option defaults to an empty string. +

    -width lineLength
    +Specifies a maximum line length for the text, in any of the forms +described in the COORDINATES section above. +If this option is zero (the default) the text is broken into +lines only at newline characters. +However, if this option is non-zero then any line that would +be longer than lineLength is broken just before a space +character to make the line shorter than lineLength; the +space character is treated as if it were a newline +character. + +

    +

    WINDOW ITEMS

    +Items of type window cause a particular window to be displayed +at a given position on the canvas. +Window items are created with widget commands of the following form: +
    pathName create window x y ?option value option value ...?
    +pathName create window coordList ?option value option value ...?
    +The arguments x and y or coordList specify the coordinates of a +point used to position the window on the display (see the -anchor +option below for more information on how bitmaps are displayed). +After the coordinates there may be any number of option-value +pairs, each of which sets one of the configuration options +for the item. These same option-value pairs may be +used in itemconfigure widget commands to change the item's +configuration. +
    +The following standard options are supported by window items: +
    -state
    +-tags
    +The following extra options are supported for window items: +

    +

    +

    -anchor anchorPos
    +AnchorPos tells how to position the window relative to the +positioning point for the item; it may have any of the forms +accepted by Tk_GetAnchor. For example, if anchorPos +is center then the window is centered on the point; if +anchorPos is n then the window will be drawn so that +its top center point is at the positioning point. +This option defaults to center. +

    -height pixels
    +Specifies the height to assign to the item's window. +Pixels may have any of the +forms described in the COORDINATES section above. +If this option isn't specified, or if it is specified as an empty +string, then the window is given whatever height it requests internally. +

    -width pixels
    +Specifies the width to assign to the item's window. +Pixels may have any of the +forms described in the COORDINATES section above. +If this option isn't specified, or if it is specified as an empty +string, then the window is given whatever width it requests internally. +

    -window pathName
    +Specifies the window to associate with this item. +The window specified by pathName must either be a child of +the canvas widget or a child of some ancestor of the canvas widget. +PathName may not refer to a top-level window. +

    +

    +Note: due to restrictions in the ways that windows are managed, it is not +possible to draw other graphical items (such as lines and images) on top +of window items. A window item always obscures any graphics that +overlap it, regardless of their order in the display list. + +

    APPLICATION-DEFINED ITEM TYPES

    +It is possible for individual applications to define new item +types for canvas widgets using C code. +See the documentation for Tk_CreateItemType. + +

    BINDINGS

    +In the current implementation, new canvases are not given any +default behavior: you'll have to execute explicit Tcl commands +to give the canvas its behavior. + +

    CREDITS

    +Tk's canvas widget is a blatant ripoff of ideas from Joel Bartlett's +ezd program. Ezd provides structured graphics in a Scheme +environment and preceded canvases by a year or two. Its simple +mechanisms for placing and animating graphical objects inspired the +functions of canvases. + +

    KEYWORDS

    +canvas, widget +
    +Copyright © 1992-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1997-1999 Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/checkbutton.htm b/hlp/en/tk/checkbutton.htm new file mode 100644 index 0000000..561efb7 --- /dev/null +++ b/hlp/en/tk/checkbutton.htm @@ -0,0 +1,319 @@ +Tk Built-In Commands - checkbutton manual page +
    +
    NAME +
    checkbutton - Create and manipulate checkbutton widgets
    +
    SYNOPSIS +
    +
    checkbutton pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -command, command, Command +
    -height, height, Height +
    -indicatoron, indicatorOn, IndicatorOn +
    -offvalue, offValue, Value +
    -onvalue, onValue, Value +
    -selectcolor, selectColor, Background +
    -selectimage, selectImage, SelectImage +
    -state, state, State +
    -variable, variable, Variable +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName deselect +
    pathName flash +
    pathName invoke +
    pathName select +
    pathName toggle +
    +
    BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +checkbutton - Create and manipulate checkbutton widgets +

    SYNOPSIS

    +checkbutton pathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -command +
    Database Name: command +
    Database Class: Command +
    Specifies a Tcl command to associate with the button. This command +is typically invoked when mouse button 1 is released over the button +window. The button's global variable (-variable option) will +be updated before the command is invoked. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the button. +If an image or bitmap is being displayed in the button then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the button's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -indicatoron +
    Database Name: indicatorOn +
    Database Class: IndicatorOn +
    Specifies whether or not the indicator should be drawn. Must be a +proper boolean value. If false, the relief option is +ignored and the widget's relief is always sunken if the widget is +selected and raised otherwise. +

    Command-Line Name: -offvalue +
    Database Name: offValue +
    Database Class: Value +
    Specifies value to store in the button's associated variable whenever +this button is deselected. Defaults to ``0''. +

    Command-Line Name: -onvalue +
    Database Name: onValue +
    Database Class: Value +
    Specifies value to store in the button's associated variable whenever +this button is selected. Defaults to ``1''. +

    Command-Line Name: -selectcolor +
    Database Name: selectColor +
    Database Class: Background +
    Specifies a background color to use when the button is selected. +If indicatorOn is true then the color applies to the indicator. +Under Windows, this color is used as the background for the indicator +regardless of the select state. +If indicatorOn is false, this color is used as the background +for the entire widget, in place of background or activeBackground, +whenever the widget is selected. +If specified as an empty string then no special color is used for +displaying when the widget is selected. +

    Command-Line Name: -selectimage +
    Database Name: selectImage +
    Database Class: SelectImage +
    Specifies an image to display (in place of the image option) +when the checkbutton is selected. +This option is ignored unless the image option has been +specified. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the checkbutton: normal, active, +or disabled. In normal state the checkbutton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the checkbutton. In active state +the checkbutton is displayed using the activeForeground and +activeBackground options. Disabled state means that the checkbutton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the checkbutton is displayed. +

    Command-Line Name: -variable +
    Database Name: variable +
    Database Class: Variable +
    Specifies name of global variable to set to indicate whether +or not this button is selected. Defaults to the name of the +button within its parent (i.e. the last element of the button +window's path name). +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the button. +If an image or bitmap is being displayed in the button then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the button's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    DESCRIPTION

    +The checkbutton command creates a new window (given by the +pathName argument) and makes it into a checkbutton widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the checkbutton such as its colors, font, +text, and initial relief. The checkbutton command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A checkbutton is a widget +that displays a textual string, bitmap or image +and a square called an indicator. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. +A checkbutton has +all of the behavior of a simple button, including the +following: it can display itself in either of three different +ways, according to the state option; +it can be made to appear +raised, sunken, or flat; it can be made to flash; and it invokes +a Tcl command whenever mouse button 1 is clicked over the +checkbutton. +

    +In addition, checkbuttons can be selected. +If a checkbutton is selected then the indicator is normally +drawn with a selected appearance, and +a Tcl variable associated with the checkbutton is set to a particular +value (normally 1). +Under Unix, the indicator is drawn with a sunken relief and a special +color. Under Windows, the indicator is drawn with a check mark inside. +If the checkbutton is not selected, then the indicator is drawn with a +deselected appearance, and the associated variable is +set to a different value (typically 0). +Under Unix, the indicator is drawn with a raised relief and no special +color. Under Windows, the indicator is drawn without a check mark inside. +By default, the name of the variable associated with a checkbutton is the +same as the name used to create the checkbutton. +The variable name, and the ``on'' and ``off'' values stored in it, +may be modified with options on the command line or in the option +database. +Configuration options may also be used to modify the way the +indicator is displayed (or whether it is displayed at all). +By default a checkbutton is configured to select and deselect +itself on alternate button clicks. +In addition, each checkbutton monitors its associated variable and +automatically selects and deselects itself when the variables value +changes to and from the button's ``on'' value. + +

    WIDGET COMMAND

    +The checkbutton command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for checkbutton widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the checkbutton +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the checkbutton +command. +

    pathName deselect
    +Deselects the checkbutton and sets the associated variable to its ``off'' +value. +

    pathName flash
    +Flashes the checkbutton. This is accomplished by redisplaying the checkbutton +several times, alternating between active and normal colors. At +the end of the flash the checkbutton is left in the same normal/active +state as when the command was invoked. +This command is ignored if the checkbutton's state is disabled. +

    pathName invoke
    +Does just what would have happened if the user invoked the checkbutton +with the mouse: toggle the selection state of the button and invoke +the Tcl command associated with the checkbutton, if there is one. +The return value is the return value from the Tcl command, or an +empty string if there is no command associated with the checkbutton. +This command is ignored if the checkbutton's state is disabled. +

    pathName select
    +Selects the checkbutton and sets the associated variable to its ``on'' +value. +

    pathName toggle
    +Toggles the selection state of the button, redisplaying it and +modifying its associated variable to reflect the new state. + +

    +

    BINDINGS

    +Tk automatically creates class bindings for checkbuttons that give them +the following default behavior: +

    +

    +

    [1]
    +On Unix systems, a checkbutton activates whenever the mouse passes +over it and deactivates whenever the mouse leaves the checkbutton. On +Mac and Windows systems, when mouse button 1 is pressed over a +checkbutton, the button activates whenever the mouse pointer is inside +the button, and deactivates whenever the mouse pointer leaves the +button. +

    [2]
    +When mouse button 1 is pressed over a checkbutton, it is invoked (its +selection state toggles and the command associated with the button is +invoked, if there is one). +

    [3]
    +When a checkbutton has the input focus, the space key causes the checkbutton +to be invoked. Under Windows, there are additional key bindings; plus +(+) and equal (=) select the button, and minus (-) deselects the button. +

    +

    +If the checkbutton's state is disabled then none of the above +actions occur: the checkbutton is completely non-responsive. +

    +The behavior of checkbuttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +checkbutton, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/chooseColor.htm b/hlp/en/tk/chooseColor.htm new file mode 100644 index 0000000..1d0292b --- /dev/null +++ b/hlp/en/tk/chooseColor.htm @@ -0,0 +1,36 @@ +Tk Built-In Commands - tk_chooseColor manual page +

    NAME

    +tk_chooseColor - pops up a dialog box for the user to select a color. +

    +

    SYNOPSIS

    +tk_chooseColor ?option value ...?
    +

    DESCRIPTION

    +The procedure tk_chooseColor pops up a dialog box for the +user to select a color. The following option-value pairs are +possible as command line arguments: +

    +

    +

    -initialcolor color
    +Specifies the color to display in the color dialog when it pops +up. color must be in a form acceptable to the Tk_GetColor +function. +

    -parent window
    +Makes window the logical parent of the color dialog. The color +dialog is displayed on top of its parent window. +

    -title titleString
    +Specifies a string to display as the title of the dialog box. If this +option is not specified, then a default title will be displayed. +

    +

    +If the user selects a color, tk_chooseColor will return the +name of the color in a form acceptable to Tk_GetColor. If the +user cancels the operation, both commands will return the empty +string. +

    EXAMPLE

    +
    button .b -fg [tk_chooseColor -initialcolor gray -title "Choose color"]
    +

    KEYWORDS

    +color selection dialog +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/chooseDirectory.htm b/hlp/en/tk/chooseDirectory.htm new file mode 100644 index 0000000..d225e6d --- /dev/null +++ b/hlp/en/tk/chooseDirectory.htm @@ -0,0 +1,58 @@ +Tk Built-In Commands - tk_chooseDirectory manual page +
    +
    NAME +
    tk_chooseDirectory - pops up a dialog box for the user to select a directory.
    +
    SYNOPSIS +
    +
    tk_chooseDirectory ?option value ...? +
    +
    DESCRIPTION +
    +
    -initialdir dirname +
    -parent window +
    -title titleString +
    -mustexist boolean +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +tk_chooseDirectory - pops up a dialog box for the user to select a directory. +

    +

    SYNOPSIS

    +tk_chooseDirectory ?option value ...?
    +

    DESCRIPTION

    +The procedure tk_chooseDirectory pops up a dialog box for the +user to select a directory. The following option-value pairs are +possible as command line arguments: +

    +

    +

    -initialdir dirname
    +Specifies that the directories in directory should be displayed +when the dialog pops up. If this parameter is not specified, then +the directories in the current working directory are displayed. If the +parameter specifies a relative path, the return value will convert the +relative path to an absolute path. This option may not always work on +the Macintosh. This is not a bug. Rather, the General Controls +control panel on the Mac allows the end user to override the +application default directory. +

    -parent window
    +Makes window the logical parent of the dialog. The dialog +is displayed on top of its parent window. +

    -title titleString
    +Specifies a string to display as the title of the dialog box. If this +option is not specified, then a default title will be displayed. +

    -mustexist boolean
    +Specifies whether the user may specify non-existant directories. If +this parameter is true, then the user may only select directories that +already exist. The default value is false. +

    +

    +

    SEE ALSO

    +tk_getOpenFile, tk_getSaveFile +

    KEYWORDS

    +directory selection dialog +
    +Copyright © 1998-2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/clipboard.htm b/hlp/en/tk/clipboard.htm new file mode 100644 index 0000000..6533da2 --- /dev/null +++ b/hlp/en/tk/clipboard.htm @@ -0,0 +1,68 @@ +Tk Built-In Commands - clipboard manual page +

    NAME

    +clipboard - Manipulate Tk clipboard +

    SYNOPSIS

    +clipboard option ?arg arg ...?
    +

    DESCRIPTION

    +This command provides a Tcl interface to the Tk clipboard, +which stores data for later retrieval using the selection mechanism. +In order to copy data into the clipboard, clipboard clear must +be called, followed by a sequence of one or more calls to clipboard +append. To ensure that the clipboard is updated atomically, all +appends should be completed before returning to the event loop. +

    +The first argument to clipboard determines the format of the +rest of the arguments and the behavior of the command. The following +forms are currently supported: +

    +

    +

    +

    clipboard clear ?-displayof window?
    +Claims ownership of the clipboard on window's display and removes +any previous contents. Window defaults to ``.''. Returns an +empty string. +

    clipboard append ?-displayof window? ?-format format? ?-type type? ?- -? data
    +Appends data to the clipboard on window's +display in the form given by type with the representation given +by format and claims ownership of the clipboard on window's +display. +

    +Type specifies the form in which the selection is to be returned +(the desired ``target'' for conversion, in ICCCM terminology), and +should be an atom name such as STRING or FILE_NAME; see the +Inter-Client Communication Conventions Manual for complete details. +Type defaults to STRING. +

    +The format argument specifies the representation that should be +used to transmit the selection to the requester (the second column of +Table 2 of the ICCCM), and defaults to STRING. If format is +STRING, the selection is transmitted as 8-bit ASCII characters. If +format is ATOM, then the data is +divided into fields separated by white space; each field is converted +to its atom value, and the 32-bit atom value is transmitted instead of +the atom name. For any other format, data is divided +into fields separated by white space and each +field is converted to a 32-bit integer; an array of integers is +transmitted to the selection requester. Note that strings passed to +clipboard append are concatenated before conversion, so the +caller must take care to ensure appropriate spacing across string +boundaries. All items appended to the clipboard with the same +type must have the same format. +

    +The format argument is needed only for compatibility with +clipboard requesters that don't use Tk. If the Tk toolkit is being +used to retrieve the CLIPBOARD selection then the value is converted back to +a string at the requesting end, so format is +irrelevant. +

    A - - argument may be specified to mark the end of options: the +next argument will always be used as data. +This feature may be convenient if, for example, data starts +with a -. +

    +

    KEYWORDS

    +clear, format, clipboard, append, selection, type +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/colors.htm b/hlp/en/tk/colors.htm new file mode 100644 index 0000000..27515a5 --- /dev/null +++ b/hlp/en/tk/colors.htm @@ -0,0 +1,765 @@ +Tk Built-In Commands - colors manual page +

    NAME

    +colors - symbolic color names recognized by Tk +

    DESCRIPTION

    +Tk recognizes many symbolic color names (eg, red) when +specifying colors. The symbolic names recognized by Tk and their +8-bit RGB values are: +
    alice blue                 240   248   248
    +AliceBlue                  240   248   248
    +antique white              250   235   235
    +AntiqueWhite               250   235   235
    +AntiqueWhite1              255   239   239
    +AntiqueWhite2              238   223   223
    +AntiqueWhite3              205   192   192
    +AntiqueWhite4              139   131   131
    +aquamarine                 127   255   255
    +aquamarine1                127   255   255
    +aquamarine2                118   238   238
    +aquamarine3                102   205   205
    +aquamarine4                 69   139   139
    +azure                      240   255   255
    +azure1                     240   255   255
    +azure2                     224   238   238
    +azure3                     193   205   205
    +azure4                     131   139   139
    +beige                      245   245   245
    +bisque                     255   228   228
    +bisque1                    255   228   228
    +bisque2                    238   213   213
    +bisque3                    205   183   183
    +bisque4                    139   125   125
    +black                        0     0     0
    +blanched almond            255   235   235
    +BlanchedAlmond             255   235   235
    +blue                         0     0     0
    +blue violet                138    43    43
    +blue1                        0     0     0
    +blue2                        0     0     0
    +blue3                        0     0     0
    +blue4                        0     0     0
    +BlueViolet                 138    43    43
    +brown                      165    42    42
    +brown1                     255    64    64
    +brown2                     238    59    59
    +brown3                     205    51    51
    +brown4                     139    35    35
    +burlywood                  222   184   184
    +burlywood1                 255   211   211
    +burlywood2                 238   197   197
    +burlywood3                 205   170   170
    +burlywood4                 139   115   115
    +cadet blue                  95   158   158
    +CadetBlue                   95   158   158
    +CadetBlue1                 152   245   245
    +CadetBlue2                 142   229   229
    +CadetBlue3                 122   197   197
    +CadetBlue4                  83   134   134
    +chartreuse                 127   255   255
    +chartreuse1                127   255   255
    +chartreuse2                118   238   238
    +chartreuse3                102   205   205
    +chartreuse4                 69   139   139
    +chocolate                  210   105   105
    +chocolate1                 255   127   127
    +chocolate2                 238   118   118
    +chocolate3                 205   102   102
    +chocolate4                 139    69    69
    +coral                      255   127   127
    +coral1                     255   114   114
    +coral2                     238   106   106
    +coral3                     205    91    91
    +coral4                     139    62    62
    +cornflower blue            100   149   149
    +CornflowerBlue             100   149   149
    +cornsilk                   255   248   248
    +cornsilk1                  255   248   248
    +cornsilk2                  238   232   232
    +cornsilk3                  205   200   200
    +cornsilk4                  139   136   136
    +cyan                         0   255   255
    +cyan1                        0   255   255
    +cyan2                        0   238   238
    +cyan3                        0   205   205
    +cyan4                        0   139   139
    +dark blue                    0     0     0
    +dark cyan                    0   139   139
    +dark goldenrod             184   134   134
    +dark gray                  169   169   169
    +dark green                   0   100   100
    +dark grey                  169   169   169
    +dark khaki                 189   183   183
    +dark magenta               139     0     0
    +dark olive green            85   107   107
    +dark orange                255   140   140
    +dark orchid                153    50    50
    +dark red                   139     0     0
    +dark salmon                233   150   150
    +dark sea green             143   188   188
    +dark slate blue             72    61    61
    +dark slate gray             47    79    79
    +dark slate grey             47    79    79
    +dark turquoise               0   206   206
    +dark violet                148     0     0
    +DarkBlue                     0     0     0
    +DarkCyan                     0   139   139
    +DarkGoldenrod              184   134   134
    +DarkGoldenrod1             255   185   185
    +DarkGoldenrod2             238   173   173
    +DarkGoldenrod3             205   149   149
    +DarkGoldenrod4             139   101   101
    +DarkGray                   169   169   169
    +DarkGreen                    0   100   100
    +DarkGrey                   169   169   169
    +DarkKhaki                  189   183   183
    +DarkMagenta                139     0     0
    +DarkOliveGreen              85   107   107
    +DarkOliveGreen1            202   255   255
    +DarkOliveGreen2            188   238   238
    +DarkOliveGreen3            162   205   205
    +DarkOliveGreen4            110   139   139
    +DarkOrange                 255   140   140
    +DarkOrange1                255   127   127
    +DarkOrange2                238   118   118
    +DarkOrange3                205   102   102
    +DarkOrange4                139    69    69
    +DarkOrchid                 153    50    50
    +DarkOrchid1                191    62    62
    +DarkOrchid2                178    58    58
    +DarkOrchid3                154    50    50
    +DarkOrchid4                104    34    34
    +DarkRed                    139     0     0
    +DarkSalmon                 233   150   150
    +DarkSeaGreen               143   188   188
    +DarkSeaGreen1              193   255   255
    +DarkSeaGreen2              180   238   238
    +DarkSeaGreen3              155   205   205
    +DarkSeaGreen4              105   139   139
    +DarkSlateBlue               72    61    61
    +DarkSlateGray               47    79    79
    +DarkSlateGray1             151   255   255
    +DarkSlateGray2             141   238   238
    +DarkSlateGray3             121   205   205
    +DarkSlateGray4              82   139   139
    +DarkSlateGrey               47    79    79
    +DarkTurquoise                0   206   206
    +DarkViolet                 148     0     0
    +deep pink                  255    20    20
    +deep sky blue                0   191   191
    +DeepPink                   255    20    20
    +DeepPink1                  255    20    20
    +DeepPink2                  238    18    18
    +DeepPink3                  205    16    16
    +DeepPink4                  139    10    10
    +DeepSkyBlue                  0   191   191
    +DeepSkyBlue1                 0   191   191
    +DeepSkyBlue2                 0   178   178
    +DeepSkyBlue3                 0   154   154
    +DeepSkyBlue4                 0   104   104
    +dim gray                   105   105   105
    +dim grey                   105   105   105
    +DimGray                    105   105   105
    +DimGrey                    105   105   105
    +dodger blue                 30   144   144
    +DodgerBlue                  30   144   144
    +DodgerBlue1                 30   144   144
    +DodgerBlue2                 28   134   134
    +DodgerBlue3                 24   116   116
    +DodgerBlue4                 16    78    78
    +firebrick                  178    34    34
    +firebrick1                 255    48    48
    +firebrick2                 238    44    44
    +firebrick3                 205    38    38
    +firebrick4                 139    26    26
    +floral white               255   250   250
    +FloralWhite                255   250   250
    +forest green                34   139   139
    +ForestGreen                 34   139   139
    +gainsboro                  220   220   220
    +ghost white                248   248   248
    +GhostWhite                 248   248   248
    +gold                       255   215   215
    +gold1                      255   215   215
    +gold2                      238   201   201
    +gold3                      205   173   173
    +gold4                      139   117   117
    +goldenrod                  218   165   165
    +goldenrod1                 255   193   193
    +goldenrod2                 238   180   180
    +goldenrod3                 205   155   155
    +goldenrod4                 139   105   105
    +gray                       190   190   190
    +gray0                        0     0     0
    +gray1                        3     3     3
    +gray2                        5     5     5
    +gray3                        8     8     8
    +gray4                       10    10    10
    +gray5                       13    13    13
    +gray6                       15    15    15
    +gray7                       18    18    18
    +gray8                       20    20    20
    +gray9                       23    23    23
    +gray10                      26    26    26
    +gray11                      28    28    28
    +gray12                      31    31    31
    +gray13                      33    33    33
    +gray14                      36    36    36
    +gray15                      38    38    38
    +
    gray16                      41    41    41
    +gray17                      43    43    43
    +gray18                      46    46    46
    +gray19                      48    48    48
    +gray20                      51    51    51
    +gray21                      54    54    54
    +gray22                      56    56    56
    +gray23                      59    59    59
    +gray24                      61    61    61
    +gray25                      64    64    64
    +gray26                      66    66    66
    +gray27                      69    69    69
    +gray28                      71    71    71
    +gray29                      74    74    74
    +gray30                      77    77    77
    +gray31                      79    79    79
    +gray32                      82    82    82
    +gray33                      84    84    84
    +gray34                      87    87    87
    +gray35                      89    89    89
    +gray36                      92    92    92
    +gray37                      94    94    94
    +gray38                      97    97    97
    +gray39                      99    99    99
    +gray40                     102   102   102
    +gray41                     105   105   105
    +gray42                     107   107   107
    +gray43                     110   110   110
    +gray44                     112   112   112
    +gray45                     115   115   115
    +gray46                     117   117   117
    +gray47                     120   120   120
    +gray48                     122   122   122
    +gray49                     125   125   125
    +gray50                     127   127   127
    +gray51                     130   130   130
    +gray52                     133   133   133
    +gray53                     135   135   135
    +gray54                     138   138   138
    +gray55                     140   140   140
    +gray56                     143   143   143
    +gray57                     145   145   145
    +gray58                     148   148   148
    +gray59                     150   150   150
    +gray60                     153   153   153
    +gray61                     156   156   156
    +gray62                     158   158   158
    +gray63                     161   161   161
    +gray64                     163   163   163
    +gray65                     166   166   166
    +gray66                     168   168   168
    +gray67                     171   171   171
    +gray68                     173   173   173
    +gray69                     176   176   176
    +gray70                     179   179   179
    +gray71                     181   181   181
    +gray72                     184   184   184
    +gray73                     186   186   186
    +gray74                     189   189   189
    +gray75                     191   191   191
    +gray76                     194   194   194
    +gray77                     196   196   196
    +gray78                     199   199   199
    +gray79                     201   201   201
    +gray80                     204   204   204
    +gray81                     207   207   207
    +gray82                     209   209   209
    +gray83                     212   212   212
    +gray84                     214   214   214
    +gray85                     217   217   217
    +gray86                     219   219   219
    +gray87                     222   222   222
    +gray88                     224   224   224
    +gray89                     227   227   227
    +gray90                     229   229   229
    +gray91                     232   232   232
    +gray92                     235   235   235
    +gray93                     237   237   237
    +gray94                     240   240   240
    +gray95                     242   242   242
    +gray96                     245   245   245
    +gray97                     247   247   247
    +gray98                     250   250   250
    +gray99                     252   252   252
    +gray100                    255   255   255
    +green                        0   255   255
    +green yellow               173   255   255
    +green1                       0   255   255
    +green2                       0   238   238
    +green3                       0   205   205
    +green4                       0   139   139
    +GreenYellow                173   255   255
    +grey                       190   190   190
    +grey0                        0     0     0
    +grey1                        3     3     3
    +grey2                        5     5     5
    +grey3                        8     8     8
    +grey4                       10    10    10
    +grey5                       13    13    13
    +grey6                       15    15    15
    +grey7                       18    18    18
    +grey8                       20    20    20
    +grey9                       23    23    23
    +grey10                      26    26    26
    +grey11                      28    28    28
    +grey12                      31    31    31
    +grey13                      33    33    33
    +grey14                      36    36    36
    +grey15                      38    38    38
    +grey16                      41    41    41
    +grey17                      43    43    43
    +grey18                      46    46    46
    +grey19                      48    48    48
    +grey20                      51    51    51
    +grey21                      54    54    54
    +grey22                      56    56    56
    +grey23                      59    59    59
    +grey24                      61    61    61
    +grey25                      64    64    64
    +grey26                      66    66    66
    +grey27                      69    69    69
    +grey28                      71    71    71
    +grey29                      74    74    74
    +grey30                      77    77    77
    +grey31                      79    79    79
    +grey32                      82    82    82
    +grey33                      84    84    84
    +grey34                      87    87    87
    +grey35                      89    89    89
    +grey36                      92    92    92
    +grey37                      94    94    94
    +grey38                      97    97    97
    +grey39                      99    99    99
    +grey40                     102   102   102
    +grey41                     105   105   105
    +grey42                     107   107   107
    +grey43                     110   110   110
    +grey44                     112   112   112
    +grey45                     115   115   115
    +grey46                     117   117   117
    +grey47                     120   120   120
    +grey48                     122   122   122
    +grey49                     125   125   125
    +grey50                     127   127   127
    +grey51                     130   130   130
    +grey52                     133   133   133
    +grey53                     135   135   135
    +grey54                     138   138   138
    +grey55                     140   140   140
    +grey56                     143   143   143
    +grey57                     145   145   145
    +grey58                     148   148   148
    +grey59                     150   150   150
    +grey60                     153   153   153
    +grey61                     156   156   156
    +grey62                     158   158   158
    +grey63                     161   161   161
    +grey64                     163   163   163
    +grey65                     166   166   166
    +grey66                     168   168   168
    +grey67                     171   171   171
    +grey68                     173   173   173
    +grey69                     176   176   176
    +grey70                     179   179   179
    +grey71                     181   181   181
    +grey72                     184   184   184
    +grey73                     186   186   186
    +grey74                     189   189   189
    +grey75                     191   191   191
    +grey76                     194   194   194
    +grey77                     196   196   196
    +grey78                     199   199   199
    +grey79                     201   201   201
    +grey80                     204   204   204
    +grey81                     207   207   207
    +grey82                     209   209   209
    +grey83                     212   212   212
    +grey84                     214   214   214
    +grey85                     217   217   217
    +grey86                     219   219   219
    +grey87                     222   222   222
    +grey88                     224   224   224
    +grey89                     227   227   227
    +grey90                     229   229   229
    +grey91                     232   232   232
    +grey92                     235   235   235
    +grey93                     237   237   237
    +grey94                     240   240   240
    +grey95                     242   242   242
    +grey96                     245   245   245
    +grey97                     247   247   247
    +grey98                     250   250   250
    +grey99                     252   252   252
    +grey100                    255   255   255
    +honeydew                   240   255   255
    +honeydew1                  240   255   255
    +honeydew2                  224   238   238
    +honeydew3                  193   205   205
    +honeydew4                  131   139   139
    +hot pink                   255   105   105
    +
    HotPink                    255   105   105
    +HotPink1                   255   110   110
    +HotPink2                   238   106   106
    +HotPink3                   205    96    96
    +HotPink4                   139    58    58
    +indian red                 205    92    92
    +IndianRed                  205    92    92
    +IndianRed1                 255   106   106
    +IndianRed2                 238    99    99
    +IndianRed3                 205    85    85
    +IndianRed4                 139    58    58
    +ivory                      255   255   255
    +ivory1                     255   255   255
    +ivory2                     238   238   238
    +ivory3                     205   205   205
    +ivory4                     139   139   139
    +khaki                      240   230   230
    +khaki1                     255   246   246
    +khaki2                     238   230   230
    +khaki3                     205   198   198
    +khaki4                     139   134   134
    +lavender                   230   230   230
    +lavender blush             255   240   240
    +LavenderBlush              255   240   240
    +LavenderBlush1             255   240   240
    +LavenderBlush2             238   224   224
    +LavenderBlush3             205   193   193
    +LavenderBlush4             139   131   131
    +lawn green                 124   252   252
    +LawnGreen                  124   252   252
    +lemon chiffon              255   250   250
    +LemonChiffon               255   250   250
    +LemonChiffon1              255   250   250
    +LemonChiffon2              238   233   233
    +LemonChiffon3              205   201   201
    +LemonChiffon4              139   137   137
    +light blue                 173   216   216
    +light coral                240   128   128
    +light cyan                 224   255   255
    +light goldenrod            238   221   221
    +light goldenrod yellow     250   250   250
    +light gray                 211   211   211
    +light green                144   238   238
    +light grey                 211   211   211
    +light pink                 255   182   182
    +light salmon               255   160   160
    +light sea green             32   178   178
    +light sky blue             135   206   206
    +light slate blue           132   112   112
    +light slate gray           119   136   136
    +light slate grey           119   136   136
    +light steel blue           176   196   196
    +light yellow               255   255   255
    +LightBlue                  173   216   216
    +LightBlue1                 191   239   239
    +LightBlue2                 178   223   223
    +LightBlue3                 154   192   192
    +LightBlue4                 104   131   131
    +LightCoral                 240   128   128
    +LightCyan                  224   255   255
    +LightCyan1                 224   255   255
    +LightCyan2                 209   238   238
    +LightCyan3                 180   205   205
    +LightCyan4                 122   139   139
    +LightGoldenrod             238   221   221
    +LightGoldenrod1            255   236   236
    +LightGoldenrod2            238   220   220
    +LightGoldenrod3            205   190   190
    +LightGoldenrod4            139   129   129
    +LightGoldenrodYellow       250   250   250
    +LightGray                  211   211   211
    +LightGreen                 144   238   238
    +LightGrey                  211   211   211
    +LightPink                  255   182   182
    +LightPink1                 255   174   174
    +LightPink2                 238   162   162
    +LightPink3                 205   140   140
    +LightPink4                 139    95    95
    +LightSalmon                255   160   160
    +LightSalmon1               255   160   160
    +LightSalmon2               238   149   149
    +LightSalmon3               205   129   129
    +LightSalmon4               139    87    87
    +LightSeaGreen               32   178   178
    +LightSkyBlue               135   206   206
    +LightSkyBlue1              176   226   226
    +LightSkyBlue2              164   211   211
    +LightSkyBlue3              141   182   182
    +LightSkyBlue4               96   123   123
    +LightSlateBlue             132   112   112
    +LightSlateGray             119   136   136
    +LightSlateGrey             119   136   136
    +LightSteelBlue             176   196   196
    +LightSteelBlue1            202   225   225
    +LightSteelBlue2            188   210   210
    +LightSteelBlue3            162   181   181
    +LightSteelBlue4            110   123   123
    +LightYellow                255   255   255
    +LightYellow1               255   255   255
    +LightYellow2               238   238   238
    +LightYellow3               205   205   205
    +LightYellow4               139   139   139
    +lime green                  50   205   205
    +LimeGreen                   50   205   205
    +linen                      250   240   240
    +magenta                    255     0     0
    +magenta1                   255     0     0
    +magenta2                   238     0     0
    +magenta3                   205     0     0
    +magenta4                   139     0     0
    +maroon                     176    48    48
    +maroon1                    255    52    52
    +maroon2                    238    48    48
    +maroon3                    205    41    41
    +maroon4                    139    28    28
    +medium aquamarine          102   205   205
    +medium blue                  0     0     0
    +medium orchid              186    85    85
    +medium purple              147   112   112
    +medium sea green            60   179   179
    +medium slate blue          123   104   104
    +medium spring green          0   250   250
    +medium turquoise            72   209   209
    +medium violet red          199    21    21
    +MediumAquamarine           102   205   205
    +MediumBlue                   0     0     0
    +MediumOrchid               186    85    85
    +MediumOrchid1              224   102   102
    +MediumOrchid2              209    95    95
    +MediumOrchid3              180    82    82
    +MediumOrchid4              122    55    55
    +MediumPurple               147   112   112
    +MediumPurple1              171   130   130
    +MediumPurple2              159   121   121
    +MediumPurple3              137   104   104
    +MediumPurple4               93    71    71
    +MediumSeaGreen              60   179   179
    +MediumSlateBlue            123   104   104
    +MediumSpringGreen            0   250   250
    +MediumTurquoise             72   209   209
    +MediumVioletRed            199    21    21
    +midnight blue               25    25    25
    +MidnightBlue                25    25    25
    +mint cream                 245   255   255
    +MintCream                  245   255   255
    +misty rose                 255   228   228
    +MistyRose                  255   228   228
    +MistyRose1                 255   228   228
    +MistyRose2                 238   213   213
    +MistyRose3                 205   183   183
    +MistyRose4                 139   125   125
    +moccasin                   255   228   228
    +navajo white               255   222   222
    +NavajoWhite                255   222   222
    +NavajoWhite1               255   222   222
    +NavajoWhite2               238   207   207
    +NavajoWhite3               205   179   179
    +NavajoWhite4               139   121   121
    +navy                         0     0     0
    +navy blue                    0     0     0
    +NavyBlue                     0     0     0
    +old lace                   253   245   245
    +OldLace                    253   245   245
    +olive drab                 107   142   142
    +OliveDrab                  107   142   142
    +OliveDrab1                 192   255   255
    +OliveDrab2                 179   238   238
    +OliveDrab3                 154   205   205
    +OliveDrab4                 105   139   139
    +orange                     255   165   165
    +orange red                 255    69    69
    +orange1                    255   165   165
    +orange2                    238   154   154
    +orange3                    205   133   133
    +orange4                    139    90    90
    +OrangeRed                  255    69    69
    +OrangeRed1                 255    69    69
    +OrangeRed2                 238    64    64
    +OrangeRed3                 205    55    55
    +OrangeRed4                 139    37    37
    +orchid                     218   112   112
    +orchid1                    255   131   131
    +orchid2                    238   122   122
    +orchid3                    205   105   105
    +orchid4                    139    71    71
    +pale goldenrod             238   232   232
    +pale green                 152   251   251
    +pale turquoise             175   238   238
    +pale violet red            219   112   112
    +PaleGoldenrod              238   232   232
    +PaleGreen                  152   251   251
    +PaleGreen1                 154   255   255
    +PaleGreen2                 144   238   238
    +PaleGreen3                 124   205   205
    +PaleGreen4                  84   139   139
    +PaleTurquoise              175   238   238
    +PaleTurquoise1             187   255   255
    +PaleTurquoise2             174   238   238
    +PaleTurquoise3             150   205   205
    +PaleTurquoise4             102   139   139
    +
    PaleVioletRed              219   112   112
    +PaleVioletRed1             255   130   130
    +PaleVioletRed2             238   121   121
    +PaleVioletRed3             205   104   104
    +PaleVioletRed4             139    71    71
    +papaya whip                255   239   239
    +PapayaWhip                 255   239   239
    +peach puff                 255   218   218
    +PeachPuff                  255   218   218
    +PeachPuff1                 255   218   218
    +PeachPuff2                 238   203   203
    +PeachPuff3                 205   175   175
    +PeachPuff4                 139   119   119
    +peru                       205   133   133
    +pink                       255   192   192
    +pink1                      255   181   181
    +pink2                      238   169   169
    +pink3                      205   145   145
    +pink4                      139    99    99
    +plum                       221   160   160
    +plum1                      255   187   187
    +plum2                      238   174   174
    +plum3                      205   150   150
    +plum4                      139   102   102
    +powder blue                176   224   224
    +PowderBlue                 176   224   224
    +purple                     160    32    32
    +purple1                    155    48    48
    +purple2                    145    44    44
    +purple3                    125    38    38
    +purple4                     85    26    26
    +red                        255     0     0
    +red1                       255     0     0
    +red2                       238     0     0
    +red3                       205     0     0
    +red4                       139     0     0
    +rosy brown                 188   143   143
    +RosyBrown                  188   143   143
    +RosyBrown1                 255   193   193
    +RosyBrown2                 238   180   180
    +RosyBrown3                 205   155   155
    +RosyBrown4                 139   105   105
    +royal blue                  65   105   105
    +RoyalBlue                   65   105   105
    +RoyalBlue1                  72   118   118
    +RoyalBlue2                  67   110   110
    +RoyalBlue3                  58    95    95
    +RoyalBlue4                  39    64    64
    +saddle brown               139    69    69
    +SaddleBrown                139    69    69
    +salmon                     250   128   128
    +salmon1                    255   140   140
    +salmon2                    238   130   130
    +salmon3                    205   112   112
    +salmon4                    139    76    76
    +sandy brown                244   164   164
    +SandyBrown                 244   164   164
    +sea green                   46   139   139
    +SeaGreen                    46   139   139
    +SeaGreen1                   84   255   255
    +SeaGreen2                   78   238   238
    +SeaGreen3                   67   205   205
    +SeaGreen4                   46   139   139
    +seashell                   255   245   245
    +seashell1                  255   245   245
    +seashell2                  238   229   229
    +seashell3                  205   197   197
    +seashell4                  139   134   134
    +sienna                     160    82    82
    +sienna1                    255   130   130
    +sienna2                    238   121   121
    +sienna3                    205   104   104
    +sienna4                    139    71    71
    +sky blue                   135   206   206
    +SkyBlue                    135   206   206
    +SkyBlue1                   135   206   206
    +SkyBlue2                   126   192   192
    +SkyBlue3                   108   166   166
    +SkyBlue4                    74   112   112
    +slate blue                 106    90    90
    +slate gray                 112   128   128
    +slate grey                 112   128   128
    +SlateBlue                  106    90    90
    +SlateBlue1                 131   111   111
    +SlateBlue2                 122   103   103
    +SlateBlue3                 105    89    89
    +SlateBlue4                  71    60    60
    +SlateGray                  112   128   128
    +SlateGray1                 198   226   226
    +SlateGray2                 185   211   211
    +SlateGray3                 159   182   182
    +SlateGray4                 108   123   123
    +SlateGrey                  112   128   128
    +snow                       255   250   250
    +snow1                      255   250   250
    +snow2                      238   233   233
    +snow3                      205   201   201
    +snow4                      139   137   137
    +spring green                 0   255   255
    +SpringGreen                  0   255   255
    +SpringGreen1                 0   255   255
    +SpringGreen2                 0   238   238
    +SpringGreen3                 0   205   205
    +SpringGreen4                 0   139   139
    +steel blue                  70   130   130
    +SteelBlue                   70   130   130
    +SteelBlue1                  99   184   184
    +SteelBlue2                  92   172   172
    +SteelBlue3                  79   148   148
    +SteelBlue4                  54   100   100
    +tan                        210   180   180
    +tan1                       255   165   165
    +tan2                       238   154   154
    +tan3                       205   133   133
    +tan4                       139    90    90
    +thistle                    216   191   191
    +thistle1                   255   225   225
    +thistle2                   238   210   210
    +thistle3                   205   181   181
    +thistle4                   139   123   123
    +tomato                     255    99    99
    +tomato1                    255    99    99
    +tomato2                    238    92    92
    +tomato3                    205    79    79
    +tomato4                    139    54    54
    +turquoise                   64   224   224
    +turquoise1                   0   245   245
    +turquoise2                   0   229   229
    +turquoise3                   0   197   197
    +turquoise4                   0   134   134
    +violet                     238   130   130
    +violet red                 208    32    32
    +VioletRed                  208    32    32
    +VioletRed1                 255    62    62
    +VioletRed2                 238    58    58
    +VioletRed3                 205    50    50
    +VioletRed4                 139    34    34
    +wheat                      245   222   222
    +wheat1                     255   231   231
    +wheat2                     238   216   216
    +wheat3                     205   186   186
    +wheat4                     139   126   126
    +white                      255   255   255
    +white smoke                245   245   245
    +WhiteSmoke                 245   245   245
    +yellow                     255   255   255
    +yellow green               154   205   205
    +yellow1                    255   255   255
    +yellow2                    238   238   238
    +yellow3                    205   205   205
    +yellow4                    139   139   139
    +YellowGreen                154   205   205
    +

    KEYWORDS

    +color, option +
    +Copyright © 1998-2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/cursors.htm b/hlp/en/tk/cursors.htm new file mode 100644 index 0000000..b6e1d6e --- /dev/null +++ b/hlp/en/tk/cursors.htm @@ -0,0 +1,128 @@ +Tk Built-In Commands - cursors manual page +

    NAME

    +cursors - mouse cursors available in Tk +

    DESCRIPTION

    +The -cursor widget option allows a Tk programmer to change the +mouse cursor for a particular widget. The cursor names recognized by +Tk on all platforms are: +
    X_cursor
    +arrow
    +based_arrow_down
    +based_arrow_up
    +boat
    +bogosity
    +bottom_left_corner
    +bottom_right_corner
    +bottom_side
    +bottom_tee
    +box_spiral
    +center_ptr
    +circle
    +clock
    +coffee_mug
    +cross
    +cross_reverse
    +crosshair
    +diamond_cross
    +dot
    +dotbox
    +double_arrow
    +draft_large
    +draft_small
    +draped_box
    +exchange
    +fleur
    +gobbler
    +gumby
    +hand1
    +hand2
    +heart
    +icon
    +iron_cross
    +left_ptr
    +left_side
    +left_tee
    +leftbutton
    +ll_angle
    +lr_angle
    +man
    +middlebutton
    +mouse
    +pencil
    +pirate
    +plus
    +question_arrow
    +right_ptr
    +right_side
    +right_tee
    +rightbutton
    +rtl_logo
    +sailboat
    +sb_down_arrow
    +sb_h_double_arrow
    +sb_left_arrow
    +sb_right_arrow
    +sb_up_arrow
    +sb_v_double_arrow
    +shuttle
    +sizing
    +spider
    +spraycan
    +star
    +target
    +tcross
    +top_left_arrow
    +top_left_corner
    +top_right_corner
    +top_side
    +top_tee
    +trek
    +ul_angle
    +umbrella
    +ur_angle
    +watch
    +xterm
    +

    PORTABILITY ISSUES

    +
    +

    Windows
    +On Windows systems, the following cursors are mapped to native cursors: +
    arrow
    +center_ptr
    +crosshair
    +fleur
    +ibeam
    +icon
    +sb_h_double_arrow
    +sb_v_double_arrow
    +watch
    +xterm
    +And the following additional cursors are available: +
    no
    +starting
    +size
    +size_ne_sw
    +size_ns
    +size_nw_se
    +size_we
    +uparrow
    +wait
    +The no cursor can be specified to eliminate the cursor. +

    Macintosh
    +On Macintosh systems, the following cursors are mapped to native cursors: +
    arrow
    +cross
    +crosshair
    +ibeam
    +plus
    +watch
    +xterm
    +And the following additional cursors are available: +
    text
    +cross-hair
    +

    +

    KEYWORDS

    +cursor, option +
    +Copyright © 1998-2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/destroy.htm b/hlp/en/tk/destroy.htm new file mode 100644 index 0000000..0f45bb6 --- /dev/null +++ b/hlp/en/tk/destroy.htm @@ -0,0 +1,22 @@ +Built-In Commands - destroy manual page +

    NAME

    +destroy - Destroy one or more windows +

    SYNOPSIS

    +destroy ?window window ...?
    +

    DESCRIPTION

    +This command deletes the windows given by the +window arguments, plus all of their descendants. +If a window ``.'' is deleted then the entire application +will be destroyed. +The windows are destroyed in order, and if an error occurs +in destroying a window the command aborts without destroying the +remaining windows. +No error is returned if window does not exist. + +

    KEYWORDS

    +application, destroy, window +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/dialog.htm b/hlp/en/tk/dialog.htm new file mode 100644 index 0000000..90d355d --- /dev/null +++ b/hlp/en/tk/dialog.htm @@ -0,0 +1,70 @@ +Tk Built-In Commands - tk_dialog manual page +
    +
    NAME +
    tk_dialog - Create modal dialog and wait for response
    +
    SYNOPSIS +
    +
    tk_dialog window title text bitmap default string string ... +
    +
    DESCRIPTION +
    +
    window +
    title +
    text +
    bitmap +
    default +
    string +
    +
    KEYWORDS +

    +

    NAME

    +tk_dialog - Create modal dialog and wait for response +

    SYNOPSIS

    +tk_dialog window title text bitmap default string string ...
    +

    DESCRIPTION

    +This procedure is part of the Tk script library. +Its arguments describe a dialog box: +

    +

    +

    window
    +Name of top-level window to use for dialog. Any existing window +by this name is destroyed. +

    title
    +Text to appear in the window manager's title bar for the dialog. +

    text
    +Message to appear in the top portion of the dialog box. +

    bitmap
    +If non-empty, specifies a bitmap to display in the top portion of +the dialog, to the left of the text. +If this is an empty string then no bitmap is displayed in the dialog. +

    default
    +If this is an integer greater than or equal to zero, then it gives +the index of the button that is to be the default button for the dialog +(0 for the leftmost button, and so on). +If less than zero or an empty string then there won't be any default +button. +

    string
    +There will be one button for each of these arguments. +Each string specifies text to display in a button, +in order from left to right. +

    +

    +After creating a dialog box, tk_dialog waits for the user to +select one of the buttons either by clicking on the button with the +mouse or by typing return to invoke the default button (if any). +Then it returns the index of the selected button: 0 for the leftmost +button, 1 for the button next to it, and so on. +If the dialog's window is destroyed before the user selects one +of the buttons, then -1 is returned. +

    +While waiting for the user to respond, tk_dialog sets a local +grab. This prevents the user from interacting with the application +in any way except to invoke the dialog box. + +

    KEYWORDS

    +bitmap, dialog, modal +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/entry.htm b/hlp/en/tk/entry.htm new file mode 100644 index 0000000..ec9a9b1 --- /dev/null +++ b/hlp/en/tk/entry.htm @@ -0,0 +1,623 @@ +Tk Built-In Commands - entry manual page +
    +
    NAME +
    entry - Create and manipulate entry widgets
    +
    SYNOPSIS +
    +
    entry pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -justify, justify, Justify +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -takefocus, takeFocus, TakeFocus +
    -textvariable, textVariable, Variable +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -invalidcommand or -invcmd, invalidCommand, InvalidCommand +
    -show, show, Show +
    -state, state, State +
    -validate, validate, Validate +
    -validatecommand or -vcmd, validateCommand, ValidateCommand +
    -width, width, Width +
    +
    DESCRIPTION +
    VALIDATION +
    +
    none +
    focus +
    focusin +
    focusout +
    key +
    all +
    +
    +
    %d +
    %i +
    %P +
    %s +
    %S +
    %v +
    %V +
    %W +
    +
    WIDGET COMMAND +
    +
    number +
    anchor +
    end +
    insert +
    sel.first +
    sel.last +
    @number +
    +
    +
    pathName bbox index +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName delete first ?last? +
    pathName get +
    pathName icursor index +
    pathName index index +
    pathName insert index string +
    pathName scan option args +
    +
    pathName scan mark x +
    pathName scan dragto x +
    +
    pathName selection option arg +
    +
    pathName selection adjust index +
    pathName selection clear +
    pathName selection from index +
    pathName selection present +
    pathName selection range start end +
    pathName selection to index +
    +
    .VS 8.3 +
    pathName xview args +
    +
    pathName xview +
    pathName xview index +
    pathName xview moveto fraction +
    pathName xview scroll number what +
    +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +entry - Create and manipulate entry widgets +

    SYNOPSIS

    +entrypathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -justify, justify, Justify +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -takefocus, takeFocus, TakeFocus +
    -textvariable, textVariable, Variable +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -invalidcommand or -invcmd +
    Database Name: invalidCommand +
    Database Class: InvalidCommand +
    Specifies a script to eval when validateCommand returns 0. +Setting it to {} disables this feature (the default). The best use +of this option is to set it to bell. See Validation +below for more information. +

    Command-Line Name: -show +
    Database Name: show +
    Database Class: Show +
    If this option is specified, then the true contents of the entry +are not displayed in the window. +Instead, each character in the entry's value will be displayed as +the first character in the value of this option, such as ``*''. +This is useful, for example, if the entry is to be used to enter +a password. +If characters in the entry are selected and copied elsewhere, the +information copied will be what is displayed, not the true contents +of the entry. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of two states for the entry: normal or disabled. +If the entry is disabled then the value may not be changed using widget +commands and no insertion cursor will be displayed, even if the input focus is +in the widget. +

    Command-Line Name: -validate +
    Database Name: validate +
    Database Class: Validate +
    Specifies the mode in which validation should operate: none, +focus, focusin, focusout, key, or all. +It defaults to none. When you want validation, you must explicitly +state which mode you wish to use. See Validation below for more. +

    Command-Line Name: -validatecommand or -vcmd +
    Database Name: validateCommand +
    Database Class: ValidateCommand +
    Specifies a script to eval when you want to validate the input into +the entry widget. Setting it to {} disables this feature (the default). +This command must return a valid tcl boolean value. If it returns 0 (or +the valid tcl boolean equivalent) then it means you reject the new edition +and it will not occur and the invalidCommand will be evaluated if it +is set. If it returns 1, then the new edition occurs. +See Validation below for more information. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies an integer value indicating the desired width of the entry window, +in average-size characters of the widget's font. +If the value is less than or equal to zero, the widget picks a +size just large enough to hold its current text. +
    +

    DESCRIPTION

    +The entry command creates a new window (given by the +pathName argument) and makes it into an entry widget. +Additional options, described above, may be specified on the +command line or in the option database +to configure aspects of the entry such as its colors, font, +and relief. The entry command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +An entry is a widget that displays a one-line text string and +allows that string to be edited using widget commands described below, which +are typically bound to keystrokes and mouse actions. +When first created, an entry's string is empty. +A portion of the entry may be selected as described below. +If an entry is exporting its selection (see the exportSelection +option), then it will observe the standard X11 protocols for handling the +selection; entry selections are available as type STRING. +Entries also observe the standard Tk rules for dealing with the +input focus. When an entry has the input focus it displays an +insertion cursor to indicate where new characters will be +inserted. +

    +Entries are capable of displaying strings that are too long to +fit entirely within the widget's window. In this case, only a +portion of the string will be displayed; commands described below +may be used to change the view in the window. Entries use +the standard xScrollCommand mechanism for interacting with +scrollbars (see the description of the xScrollCommand option +for details). They also support scanning, as described below. + +

    VALIDATION

    +Validation works by setting the validateCommand +option to a script which will be evaluated according to the validate +option as follows: +

    +

    +

    +

    none
    +Default. This means no validation will occur. +

    focus
    +validateCommand will be called when the entry receives or +loses focus. +

    focusin
    +validateCommand will be called when the entry receives focus. +

    focusout
    +validateCommand will be called when the entry loses focus. +

    key
    +validateCommand will be called when the entry is edited. +

    all
    +validateCommand will be called for all above conditions. +

    +

    +It is posible to perform percent substitutions on the validateCommand +and invalidCommand, +just as you would in a bind script. The following substitutions +are recognized: +

    +

    +

    +

    %d
    +Type of action: 1 for insert, 0 for delete, +or -1 for focus, forced or textvariable validation. +

    %i
    +Index of char string to be inserted/deleted, if any, otherwise -1. +

    %P
    +The value of the entry should edition occur. If you are configuring the +entry widget to have a new textvariable, this will be the value of that +textvariable. +

    %s
    +The current value of entry before edition. +

    %S
    +The text string being inserted/deleted, if any, {} otherwise. +

    %v
    +The type of validation currently set. +

    %V
    +The type of validation that triggered the callback +(key, focusin, focusout, forced). +

    %W
    +The name of the entry widget. +

    +

    +In general, the textVariable and validateCommand can be +dangerous to mix. Any problems have been overcome so that using the +validateCommand will not interfere with the traditional behavior of +the entry widget. Using the textVariable for read-only purposes will +never cause problems. The danger comes when you try set the +textVariable to something that the validateCommand would not +accept, which causes validate to become none (the +invalidCommand will not be triggered). The same happens +when an error occurs evaluating the validateCommand. +

    +Primarily, an error will occur when the validateCommand or +invalidCommand encounters an error in its script while evaluating or +validateCommand does not return a valid tcl boolean value. The +validate option will also set itself to none when you edit the +entry widget from within either the validateCommand or the +invalidCommand. Such editions will override the one that was being +validated. If you wish to edit the entry widget (for example set it to {}) +during validation and still have the validate option set, you should +include the command +

    after idle {%W config -validate %v}
    +in the validateCommand or invalidCommand (whichever one you +were editing the entry widget from). It is also recommended to not set an +associated textVariable during validation, as that can cause the +entry widget to become out of sync with the textVariable. + +

    WIDGET COMMAND

    +The entry command creates a new Tcl command whose +name is pathName. This command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. +

    +Many of the widget commands for entries take one or more indices as +arguments. An index specifies a particular character in the entry's +string, in any of the following ways: +

    +

    +

    number
    +Specifies the character as a numerical index, where 0 corresponds +to the first character in the string. +

    anchor
    +Indicates the anchor point for the selection, which is set with the +select from and select adjust widget commands. +

    end
    +Indicates the character just after the last one in the entry's string. +This is equivalent to specifying a numerical index equal to the length +of the entry's string. +

    insert
    +Indicates the character adjacent to and immediately following the +insertion cursor. +

    sel.first
    +Indicates the first character in the selection. It is an error to +use this form if the selection isn't in the entry window. +

    sel.last
    +Indicates the character just after the last one in the selection. +It is an error to use this form if the selection isn't in the +entry window. +

    @number
    +In this form, number is treated as an x-coordinate in the +entry's window; the character spanning that x-coordinate is used. +For example, ``@0'' indicates the left-most character in the +window. +

    +

    +Abbreviations may be used for any of the forms above, e.g. ``e'' +or ``sel.f''. In general, out-of-range indices are automatically +rounded to the nearest legal value. +

    +The following commands are possible for entry widgets: +

    +

    +

    pathName bbox index
    +Returns a list of four numbers describing the bounding box of the +character given by index. +The first two elements of the list give the x and y coordinates of +the upper-left corner of the screen area covered by the character +(in pixels relative to the widget) and the last two elements give +the width and height of the character, in pixels. +The bounding box may refer to a region outside the visible area +of the window. +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the entry +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the entry +command. +

    pathName delete first ?last?
    +Delete one or more elements of the entry. +First is the index of the first character to delete, and +last is the index of the character just after the last +one to delete. +If last isn't specified it defaults to first+1, +i.e. a single character is deleted. +This command returns an empty string. +

    pathName get
    +Returns the entry's string. +

    pathName icursor index
    +Arrange for the insertion cursor to be displayed just before the character +given by index. Returns an empty string. +

    pathName index index
    +Returns the numerical index corresponding to index. +

    pathName insert index string
    +Insert the characters of string just before the character +indicated by index. Returns an empty string. +

    pathName scan option args
    +This command is used to implement scanning on entries. It has +two forms, depending on option: +

    +

    +

    pathName scan mark x
    +Records x and the current view in the entry window; used in +conjunction with later scan dragto commands. Typically this +command is associated with a mouse button press in the widget. It +returns an empty string. +

    pathName scan dragto x
    +This command computes the difference between its x argument +and the x argument to the last scan mark command for +the widget. It then adjusts the view left or right by 10 times the +difference in x-coordinates. This command is typically associated +with mouse motion events in the widget, to produce the effect of +dragging the entry at high speed through the window. The return +value is an empty string. +

    +

    pathName selection option arg
    +This command is used to adjust the selection within an entry. It +has several forms, depending on option: +

    +

    +

    pathName selection adjust index
    +Locate the end of the selection nearest to the character given by +index, and adjust that end of the selection to be at index +(i.e including but not going beyond index). The other +end of the selection is made the anchor point for future +select to commands. If the selection +isn't currently in the entry, then a new selection is created to +include the characters between index and the most recent +selection anchor point, inclusive. +Returns an empty string. +

    pathName selection clear
    +Clear the selection if it is currently in this widget. If the +selection isn't in this widget then the command has no effect. +Returns an empty string. +

    pathName selection from index
    +Set the selection anchor point to just before the character +given by index. Doesn't change the selection. +Returns an empty string. +

    pathName selection present
    +Returns 1 if there is are characters selected in the entry, +0 if nothing is selected. +

    pathName selection range start end
    +Sets the selection to include the characters starting with +the one indexed by start and ending with the one just +before end. +If end refers to the same character as start or an +earlier one, then the entry's selection is cleared. +

    pathName selection to index
    +If index is before the anchor point, set the selection +to the characters from index up to but not including +the anchor point. +If index is the same as the anchor point, do nothing. +If index is after the anchor point, set the selection +to the characters from the anchor point up to but not including +index. +The anchor point is determined by the most recent select from +or select adjust command in this widget. +If the selection isn't in this widget then a new selection is +created using the most recent anchor point specified for the widget. +Returns an empty string. +

    +

    .VS 8.3
    +pathName validate +This command is used to force an evaluation of the validateCommand +independent of the conditions specified by the validate option. +This is done by temporarily setting the validate option to all. +It returns 0 or 1. +

    pathName xview args
    +This command is used to query and change the horizontal position of the +text in the widget's window. It can take any of the following +forms: +

    +

    +

    pathName xview
    +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the horizontal span that is visible in the window. +For example, if the first element is .2 and the second element is .6, +20% of the entry's text is off-screen to the left, the middle 40% is visible +in the window, and 40% of the text is off-screen to the right. +These are the same values passed to scrollbars via the -xscrollcommand +option. +

    pathName xview index
    +Adjusts the view in the window so that the character given by index +is displayed at the left edge of the window. +

    pathName xview moveto fraction
    +Adjusts the view in the window so that the character fraction of the +way through the text appears at the left edge of the window. +Fraction must be a fraction between 0 and 1. +

    pathName xview scroll number what
    +This command shifts the view in the window left or right according to +number and what. +Number must be an integer. +What must be either units or pages or an abbreviation +of one of these. +If what is units, the view adjusts left or right by +number average-width characters on the display; if it is +pages then the view adjusts by number screenfuls. +If number is negative then characters farther to the left +become visible; if it is positive then characters farther to the right +become visible. +

    +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for entries that give them +the following default behavior. +In the descriptions below, ``word'' refers to a contiguous group +of letters, digits, or ``_'' characters, or any single character +other than these. +

    +

    +

    [1]
    +Clicking mouse button 1 positions the insertion cursor +just before the character underneath the mouse cursor, sets the +input focus to this widget, and clears any selection in the widget. +Dragging with mouse button 1 strokes out a selection between +the insertion cursor and the character under the mouse. +

    [2]
    +Double-clicking with mouse button 1 selects the word under the mouse +and positions the insertion cursor at the beginning of the word. +Dragging after a double click will stroke out a selection consisting +of whole words. +

    [3]
    +Triple-clicking with mouse button 1 selects all of the text in the +entry and positions the insertion cursor before the first character. +

    [4]
    +The ends of the selection can be adjusted by dragging with mouse +button 1 while the Shift key is down; this will adjust the end +of the selection that was nearest to the mouse cursor when button +1 was pressed. +If the button is double-clicked before dragging then the selection +will be adjusted in units of whole words. +

    [5]
    +Clicking mouse button 1 with the Control key down will position the +insertion cursor in the entry without affecting the selection. +

    [6]
    +If any normal printing characters are typed in an entry, they are +inserted at the point of the insertion cursor. +

    [7]
    +The view in the entry can be adjusted by dragging with mouse button 2. +If mouse button 2 is clicked without moving the mouse, the selection +is copied into the entry at the position of the mouse cursor. +

    [8]
    +If the mouse is dragged out of the entry on the left or right sides +while button 1 is pressed, the entry will automatically scroll to +make more text visible (if there is more text off-screen on the side +where the mouse left the window). +

    [9]
    +The Left and Right keys move the insertion cursor one character to the +left or right; they also clear any selection in the entry and set +the selection anchor. +If Left or Right is typed with the Shift key down, then the insertion +cursor moves and the selection is extended to include the new character. +Control-Left and Control-Right move the insertion cursor by words, and +Control-Shift-Left and Control-Shift-Right move the insertion cursor +by words and also extend the selection. +Control-b and Control-f behave the same as Left and Right, respectively. +Meta-b and Meta-f behave the same as Control-Left and Control-Right, +respectively. +

    [10]
    +The Home key, or Control-a, will move the insertion cursor to the +beginning of the entry and clear any selection in the entry. +Shift-Home moves the insertion cursor to the beginning of the entry +and also extends the selection to that point. +

    [11]
    +The End key, or Control-e, will move the insertion cursor to the +end of the entry and clear any selection in the entry. +Shift-End moves the cursor to the end and extends the selection +to that point. +

    [12]
    +The Select key and Control-Space set the selection anchor to the position +of the insertion cursor. They don't affect the current selection. +Shift-Select and Control-Shift-Space adjust the selection to the +current position of the insertion cursor, selecting from the anchor +to the insertion cursor if there was not any selection previously. +

    [13]
    +Control-/ selects all the text in the entry. +

    [14]
    +Control-\ clears any selection in the entry. +

    [15]
    +The F16 key (labelled Copy on many Sun workstations) or Meta-w +copies the selection in the widget to the clipboard, if there is a selection. +

    [16]
    +The F20 key (labelled Cut on many Sun workstations) or Control-w +copies the selection in the widget to the clipboard and deletes +the selection. +If there is no selection in the widget then these keys have no effect. +

    [17]
    +The F18 key (labelled Paste on many Sun workstations) or Control-y +inserts the contents of the clipboard at the position of the +insertion cursor. +

    [18]
    +The Delete key deletes the selection, if there is one in the entry. +If there is no selection, it deletes the character to the right of +the insertion cursor. +

    [19]
    +The BackSpace key and Control-h delete the selection, if there is one +in the entry. +If there is no selection, it deletes the character to the left of +the insertion cursor. +

    [20]
    +Control-d deletes the character to the right of the insertion cursor. +

    [21]
    +Meta-d deletes the word to the right of the insertion cursor. +

    [22]
    +Control-k deletes all the characters to the right of the insertion +cursor. +

    [23]
    +Control-t reverses the order of the two characters to the right of +the insertion cursor. +

    +

    +If the entry is disabled using the -state option, then the entry's +view can still be adjusted and text in the entry can still be selected, +but no insertion cursor will be displayed and no text modifications will +take place. +

    +The behavior of entries can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +entry, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1998-2000 Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/event.htm b/hlp/en/tk/event.htm new file mode 100644 index 0000000..05766fe --- /dev/null +++ b/hlp/en/tk/event.htm @@ -0,0 +1,368 @@ +Tk Built-In Commands - event manual page +
    +
    NAME +
    event - Miscellaneous event facilities: define virtual events and generate events
    +
    SYNOPSIS +
    +
    event option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    event add <<virtual>> sequence ?sequence ...? +
    event delete <<virtual>> ?sequence sequence ...? +
    event generate window event ?option value option value ...? +
    event info ?<<virtual>>? +
    +
    EVENT FIELDS +
    +
    -above window +
    -borderwidth size +
    -button number +
    -count number +
    -delta number +
    -detail detail +
    -focus boolean +
    -height size +
    -keycode number +
    -keysym name +
    -mode notify +
    -override boolean +
    -place where +
    -root window +
    -rootx coord +
    -rooty coord +
    -sendevent boolean +
    -serial number +
    -state state +
    -subwindow window +
    -time integer +
    -warp boolean +
    -width size +
    -when when +
    +
    now +
    tail +
    head +
    mark +
    +
    -x coord +
    -y coord +
    +
    VIRTUAL EVENT EXAMPLES +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +event - Miscellaneous event facilities: define virtual events and generate events +

    SYNOPSIS

    +event option ?arg arg ...?
    +

    DESCRIPTION

    +The event command provides several facilities for dealing with +window system events, such as defining virtual events and synthesizing +events. The command has several different forms, determined by the +first argument. The following forms are currently supported: +

    +

    +

    event add <<virtual>> sequence ?sequence ...?
    +Associates the virtual event virtual with the physical +event sequence(s) given by the sequence arguments, so that +the virtual event will trigger whenever any one of the sequences +occurs. +Virtual may be any string value and sequence may have +any of the values allowed for the sequence argument to the +bind command. +If virtual is already defined, the new physical event sequences +add to the existing sequences for the event. +

    event delete <<virtual>> ?sequence sequence ...?
    +Deletes each of the sequences from those associated with +the virtual event given by virtual. +Virtual may be any string value and sequence may have +any of the values allowed for the sequence argument to the +bind command. +Any sequences not currently associated with virtual +are ignored. +If no sequence argument is provided, all physical event sequences +are removed for virtual, so that the virtual event will not +trigger anymore. +

    event generate window event ?option value option value ...?
    +Generates a window event and arranges for it to be processed just as if +it had come from the window system. +Window gives the path name of the window for which the event +will be generated; it may also be an identifier (such as returned by +winfo id) as long as it is for a window in the current application. +Event provides a basic description of +the event, such as <Shift-Button-2> or <<Paste>>. +If Window is empty the whole screen is meant, and coordinates +are relative to the screen. +Event may have any of the forms allowed for the sequence +argument of the bind command except that it must consist +of a single event pattern, not a sequence. +Option-value pairs may be used to specify additional +attributes of the event, such as the x and y mouse position; see +EVENT FIELDS below. If the -when option is not specified, the +event is processed immediately: all of the handlers for the event +will complete before the event generate command returns. +If the -when option is specified then it determines when the +event is processed. Certain events, such as key events, require +that the window has focus to receive the event properly. +

    event info ?<<virtual>>?
    +Returns information about virtual events. +If the <<virtual>> argument is omitted, the return value +is a list of all the virtual events that are currently defined. +If <<virtual>> is specified then the return value is +a list whose elements are the physical event sequences currently +defined for the given virtual event; if the virtual event is +not defined then an empty string is returned. + +

    +

    EVENT FIELDS

    +The following options are supported for the event generate +command. These correspond to the ``%'' expansions +allowed in binding scripts for the bind command. +

    +

    +

    -above window
    +Window specifies the above field for the event, +either as a window path name or as an integer window id. +Valid for Configure events. +Corresponds to the %a substitution for binding scripts. +

    -borderwidth size
    +Size must be a screen distance; it specifies the +border_width field for the event. +Valid for Configure events. +Corresponds to the %B substitution for binding scripts. +

    -button number
    +Number must be an integer; it specifies the detail field +for a ButtonPress or ButtonRelease event, overriding +any button number provided in the base event argument. +Corresponds to the %b substitution for binding scripts. +

    -count number
    +Number must be an integer; it specifies the count field +for the event. Valid for Expose events. +Corresponds to the %c substitution for binding scripts. +

    -delta number
    +Number must be an integer; it specifies the delta field +for the MouseWheel event. The delta refers to the +direction and magnitude the mouse wheel was rotated. Note the value +is not a screen distance but are units of motion in the mouse wheel. +Typically these values are multiples of 120. For example, 120 should +scroll the text widget up 4 lines and -240 would scroll the text +widget down 8 lines. Of course, other widgets may define different +behaviors for mouse wheel motion. This field corresponds to the +%D substitution for binding scripts. +

    -detail detail
    +Detail specifies the detail field for the event +and must be one of the following: +
    NotifyAncestor	NotifyNonlinearVirtual
    +NotifyDetailNone	NotifyPointer
    +NotifyInferior	NotifyPointerRoot
    +NotifyNonlinear	NotifyVirtual
    +Valid for Enter, Leave, FocusIn and +FocusOut events. +Corresponds to the %d substitution for binding scripts. +

    -focus boolean
    +Boolean must be a boolean value; it specifies the focus +field for the event. +Valid for Enter and Leave events. +Corresponds to the %f substitution for binding scripts. +

    -height size
    +Size must be a screen distance; it specifies the height +field for the event. Valid for Configure events. +Corresponds to the %h substitution for binding scripts. +

    -keycode number
    +Number must be an integer; it specifies the keycode +field for the event. +Valid for KeyPress and KeyRelease events. +Corresponds to the %k substitution for binding scripts. +

    -keysym name
    +Name must be the name of a valid keysym, such as g, +space, or Return; its corresponding +keycode value is used as the keycode field for event, overriding +any detail specified in the base event argument. +Valid for KeyPress and KeyRelease events. +Corresponds to the %K substitution for binding scripts. +

    -mode notify
    +Notify specifies the mode field for the event and must be +one of NotifyNormal, NotifyGrab, NotifyUngrab, or +NotifyWhileGrabbed. +Valid for Enter, Leave, FocusIn, and +FocusOut events. +Corresponds to the %m substitution for binding scripts. +

    -override boolean
    +Boolean must be a boolean value; it specifies the +override_redirect field for the event. +Valid for Map, Reparent, and Configure events. +Corresponds to the %o substitution for binding scripts. +

    -place where
    +Where specifies the place field for the event; it must be +either PlaceOnTop or PlaceOnBottom. +Valid for Circulate events. +Corresponds to the %p substitution for binding scripts. +

    -root window
    +Window must be either a window path name or an integer window +identifier; it specifies the root field for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, and Motion +events. +Corresponds to the %R substitution for binding scripts. +

    -rootx coord
    +Coord must be a screen distance; it specifies the x_root +field for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, and Motion +events. Corresponds to the %X substitution for binding scripts. +

    -rooty coord
    +Coord must be a screen distance; it specifies th y_root +field for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, and Motion +events. +Corresponds to the %Y substitution for binding scripts. +

    -sendevent boolean
    +Boolean must be a boolean value; it specifies the send_event +field for the event. Valid for all events. Corresponds to the +%E substitution for binding scripts. +

    -serial number
    +Number must be an integer; it specifies the serial field +for the event. Valid for all events. +Corresponds to the %# substitution for binding scripts. +

    -state state
    +State specifies the state field for the event. +For KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, and Motion events +it must be an integer value. +For Visibility events it must be one of VisibilityUnobscured, +VisibilityPartiallyObscured, or VisibilityFullyObscured. +This option overrides any modifiers such as Meta or Control +specified in the base event. +Corresponds to the %s substitution for binding scripts. +

    -subwindow window
    +Window specifies the subwindow field for the event, either +as a path name for a Tk widget or as an integer window identifier. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, and Motion events. +Similar to %S substitution for binding scripts. +

    -time integer
    +Integer must be an integer value; it specifies the time field +for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Enter, Leave, Motion, +and Property events. +Corresponds to the %t substitution for binding scripts. +

    -warp boolean
    +boolean must be a boolean value; it specifies whether +the screen pointer should be warped as well. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, and Motion events. The pointer will +only warp to a window if it is mapped. +

    -width size
    +Size must be a screen distance; it specifies the width field +for the event. +Valid for Configure events. +Corresponds to the %w substitution for binding scripts. +

    -when when
    +When determines when the event will be processed; it must have one +of the following values: +

    +

    +

    now
    +Process the event immediately, before the command returns. +This also happens if the -when option is omitted. +

    tail
    +Place the event on Tcl's event queue behind any events already +queued for this application. +

    head
    +Place the event at the front of Tcl's event queue, so that it +will be handled before any other events already queued. +

    mark
    +Place the event at the front of Tcl's event queue but behind any +other events already queued with -when mark. +This option is useful when generating a series of events that should +be processed in order but at the front of the queue. +

    +

    -x coord
    +Coord must be a screen distance; it specifies the x field +for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Motion, Enter, Leave, +Expose, Configure, Gravity, and Reparent +events. +Corresponds to the the %x substitution for binding scripts. +If Window is empty the coordinate is relative to the +screen, and this option corresponds to the %X substitution +for binding scripts. +

    -y coord
    +Coord must be a screen distance; it specifies the y +field for the event. +Valid for KeyPress, KeyRelease, ButtonPress, +ButtonRelease, Motion, Enter, Leave, +Expose, Configure, Gravity, and Reparent +events. +Corresponds to the the %y substitution for binding scripts. +If Window is empty the coordinate is relative to the +screen, and this option corresponds to the %Y substitution +for binding scripts. +

    +

    +Any options that are not specified when generating an event are filled +with the value 0, except for serial, which is filled with the +next X event serial number. + +

    VIRTUAL EVENT EXAMPLES

    +In order for a virtual event binding to trigger, two things must +happen. First, the virtual event must be defined with the +event add command. Second, a binding must be created for +the virtual event with the bind command. +Consider the following virtual event definitions: +
    event add <<Paste>> <Control-y>
    +event add <<Paste>> <Button-2>
    +event add <<Save>> <Control-X><Control-S>
    +event add <<Save>> <Shift-F12>
    +In the bind command, a virtual event can be bound like any other +builtin event type as follows: +
    bind Entry <<Paste>> {%W insert [selection get]}
    +The double angle brackets are used to specify that a virtual event is being +bound. If the user types Control-y or presses button 2, or if +a <<Paste>> virtual event is synthesized with event generate, +then the <<Paste>> binding will be invoked. +

    +If a virtual binding has the exact same sequence as a separate +physical binding, then the physical binding will take precedence. +Consider the following example: +

    event add <<Paste>> <Control-y> <Meta-Control-y>
    +bind Entry <Control-y> {puts Control-y}
    +bind Entry <<Paste>> {puts Paste}
    +When the user types Control-y the <Control-y> binding +will be invoked, because a physical event is considered +more specific than a virtual event, all other things being equal. +However, when the user types Meta-Control-y the +<<Paste>> binding will be invoked, because the +Meta modifier in the physical pattern associated with the +virtual binding is more specific than the <Control-y> sequence for +the physical event. +

    +Bindings on a virtual event may be created before the virtual event exists. +Indeed, the virtual event never actually needs to be defined, for instance, +on platforms where the specific virtual event would meaningless or +ungeneratable. +

    +When a definition of a virtual event changes at run time, all windows +will respond immediately to the new definition. +Starting from the preceding example, if the following code is executed: +

    bind <Entry> <Control-y> {}
    +event add <<Paste>> <Key-F6>
    +the behavior will change such in two ways. First, the shadowed +<<Paste>> binding will emerge. +Typing Control-y will no longer invoke the <Control-y> binding, +but instead invoke the virtual event <<Paste>>. Second, +pressing the F6 key will now also invoke the <<Paste>> binding. + +

    SEE ALSO

    +bind +

    KEYWORDS

    +event, binding, define, handle, virtual event +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1998-2000 Ajuba Solutions.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/focus.htm b/hlp/en/tk/focus.htm new file mode 100644 index 0000000..55aed2b --- /dev/null +++ b/hlp/en/tk/focus.htm @@ -0,0 +1,118 @@ +Tk Built-In Commands - focus manual page +
    +
    NAME +
    focus - Manage the input focus
    +
    SYNOPSIS +
    +
    focus +
    focus window +
    focus option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    focus +
    focus window +
    focus -displayof window +
    focus -force window +
    focus -lastfor window +
    +
    QUIRKS +
    KEYWORDS +

    +

    NAME

    +focus - Manage the input focus +

    SYNOPSIS

    +focus
    +focus window
    +focus option ?arg arg ...?
    +

    DESCRIPTION

    +The focus command is used to manage the Tk input focus. +At any given time, one window on each display is designated as +the focus window; any key press or key release events for the +display are sent to that window. +It is normally up to the window manager to redirect the focus among the +top-level windows of a display. For example, some window managers +automatically set the input focus to a top-level window whenever +the mouse enters it; others redirect the input focus only when +the user clicks on a window. +Usually the window manager will set the focus +only to top-level windows, leaving it up to the application to +redirect the focus among the children of the top-level. +

    +Tk remembers one focus window for each top-level (the most recent +descendant of that top-level to receive the focus); when the window +manager gives the focus +to a top-level, Tk automatically redirects it to the remembered +window. Within a top-level Tk uses an explicit focus model +by default. Moving the mouse within a top-level does not normally +change the focus; the focus changes only when a widget +decides explicitly to claim the focus (e.g., because of a button +click), or when the user types a key such as Tab that moves the +focus. +

    +The Tcl procedure tk_focusFollowsMouse may be invoked to +create an implicit focus model: it reconfigures Tk so that +the focus is set to a window whenever the mouse enters it. +The Tcl procedures tk_focusNext and tk_focusPrev +implement a focus order among the windows of a top-level; they +are used in the default bindings for Tab and Shift-Tab, among other +things. +

    +The focus command can take any of the following forms: +

    +

    +

    focus
    +Returns the path name of the focus window on the display containing +the application's main window, or an empty string if no window in +this application has the focus on that display. Note: it is +better to specify the display explicitly using -displayof +(see below) so that the code will work in applications using multiple +displays. +

    focus window
    +If the application currently has the input focus on window's +display, this command resets the input focus for window's display +to window and returns an empty string. +If the application doesn't currently have the input focus on +window's display, window will be remembered as the focus +for its top-level; the next time the focus arrives at the top-level, +Tk will redirect it to window. +If window is an empty string then the command does nothing. +

    focus -displayof window
    +Returns the name of the focus window on the display containing window. +If the focus window for window's display isn't in this +application, the return value is an empty string. +

    focus -force window
    +Sets the focus of window's display to window, even if +the application doesn't currently have the input focus for the display. +This command should be used sparingly, if at all. +In normal usage, an application should not claim the focus for +itself; instead, it should wait for the window manager to give it +the focus. +If window is an empty string then the command does nothing. +

    focus -lastfor window
    +Returns the name of the most recent window to have the input focus +among all the windows in the same top-level as window. +If no window in that top-level has ever had the input focus, or +if the most recent focus window has been deleted, then the name +of the top-level is returned. The return value is the window that +will receive the input focus the next time the window manager gives +the focus to the top-level. + +

    +

    QUIRKS

    +When an internal window receives the input focus, Tk doesn't actually +set the X focus to that window; as far as X is concerned, the focus +will stay on the top-level window containing the window with the focus. +However, Tk generates FocusIn and FocusOut events just as if the X +focus were on the internal window. This approach gets around a +number of problems that would occur if the X focus were actually moved; +the fact that the X focus is on the top-level is invisible unless +you use C code to query the X server directly. + +

    KEYWORDS

    +events, focus, keyboard, top-level, window manager +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/focusNext.htm b/hlp/en/tk/focusNext.htm new file mode 100644 index 0000000..8955e05 --- /dev/null +++ b/hlp/en/tk/focusNext.htm @@ -0,0 +1,48 @@ +Tk Built-In Commands - tk_focusNext manual page +

    NAME

    +tk_focusNext, tk_focusPrev, tk_focusFollowsMouse - Utility procedures for managing the input focus. +

    SYNOPSIS

    +tk_focusNext window
    +tk_focusPrev window
    +tk_focusFollowsMouse
    +

    DESCRIPTION

    +tk_focusNext is a utility procedure used for keyboard traversal. +It returns the ``next'' window after window in focus order. +The focus order is determined by +the stacking order of windows and the structure of the window hierarchy. +Among siblings, the focus order is the same as the stacking order, with the +lowest window being first. +If a window has children, the window is visited first, followed by +its children (recursively), followed by its next sibling. +Top-level windows other than window are skipped, so that +tk_focusNext never returns a window in a different top-level +from window. +

    +After computing the next window, tk_focusNext examines the +window's -takefocus option to see whether it should be skipped. +If so, tk_focusNext continues on to the next window in the focus +order, until it eventually finds a window that will accept the focus +or returns back to window. +

    +tk_focusPrev is similar to tk_focusNext except that it +returns the window just before window in the focus order. +

    +tk_focusFollowsMouse changes the focus model for the application +to an implicit one where the window under the mouse gets the focus. +After this procedure is called, whenever the mouse enters a window +Tk will automatically give it the input focus. +The focus command may be used to move the focus to a window +other than the one under the mouse, but as soon as the mouse moves +into a new window the focus will jump to that window. +Note: at present there is no built-in support for returning the +application to an explicit focus model; to do this you'll have +to write a script that deletes the bindings created by +tk_focusFollowsMouse. + +

    KEYWORDS

    +focus, keyboard traversal, top-level +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/font.htm b/hlp/en/tk/font.htm new file mode 100644 index 0000000..52a1271 --- /dev/null +++ b/hlp/en/tk/font.htm @@ -0,0 +1,276 @@ +Tk Built-In Commands - font manual page +
    +
    NAME +
    font - Create and inspect fonts.
    +
    SYNOPSIS +
    +
    font option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    font actual font ?-displayof window? ?option? +
    font configure fontname ?option? ?value option value ...? +
    font create ?fontname? ?option value ...? +
    font delete fontname ?fontname ...? +
    font families ?-displayof window? +
    font measure font ?-displayof window? text +
    font metrics font ?-displayof window? ?option? +
    font names +
    +
    FONT DESCRIPTION +
    +
    [1] fontname +
    [2] systemfont +
    [3] family ?size? ?style? ?style ...? +
    [4] X-font names (XLFD) +
    [5] option value ?option value ...? +
    +
    FONT METRICS +
    +
    -ascent +
    -descent +
    -linespace +
    -fixed +
    +
    FONT OPTIONS +
    +
    -family name +
    -size size +
    -weight weight +
    -slant slant +
    -underline boolean +
    -overstrike boolean +
    +
    PLATFORM-SPECIFIC ISSUES +
    +
    X Windows: +
    MS Windows: +
    Macintosh: +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +font - Create and inspect fonts. +

    SYNOPSIS

    +font option ?arg arg ...?
    +

    DESCRIPTION

    +The font command provides several facilities for dealing with +fonts, such as defining named fonts and inspecting the actual attributes of +a font. The command has several different forms, determined by the +first argument. The following forms are currently supported: +

    +

    +

    font actual font ?-displayof window? ?option?
    +Returns information about the the actual attributes that are obtained when +font is used on window's display; the actual attributes obtained +may differ from the attributes requested due to platform-dependant +limitations, such as the availability of font families and pointsizes. +font is a font description; see FONT DESCRIPTIONS below. If the +window argument is omitted, it defaults to the main window. If +option is specified, returns the value of that attribute; if it is +omitted, the return value is a list of all the attributes and their values. +See FONT OPTIONS below for a list of the possible attributes. +

    font configure fontname ?option? ?value option value ...?
    +Query or modify the desired attributes for the named font called +fontname. If no option is specified, returns a list describing +all the options and their values for fontname. If a single option +is specified with no value, then returns the current value of that +attribute. If one or more option-value pairs are specified, +then the command modifies the given named font to have the given values; in +this case, all widgets using that font will redisplay themselves using the +new attributes for the font. See FONT OPTIONS below for a list of the +possible attributes. +

    font create ?fontname? ?option value ...?
    +Creates a new named font and returns its name. fontname specifies the +name for the font; if it is omitted, then Tk generates a new name of the +form fontx, where x is an integer. There may be any number +of option-value pairs, which provide the desired attributes for +the new named font. See FONT OPTIONS below for a list of the possible +attributes. +

    font delete fontname ?fontname ...?
    +Delete the specified named fonts. If there are widgets using the named font, +the named font won't actually be deleted until all the instances are +released. Those widgets will continue to display using the last known values +for the named font. If a deleted named font is subsequently recreated with +another call to font create, the widgets will use the new named font +and redisplay themselves using the new attributes of that font. +

    font families ?-displayof window?
    +The return value is a list of the case-insensitive names of all font families +that exist on window's display. If the window argument is +omitted, it defaults to the main window. +

    font measure font ?-displayof window? text
    +Measures the amount of space the string text would use in the given +font when displayed in window. font is a font description; +see FONT DESCRIPTIONS below. If the window argument is omitted, it +defaults to the main window. The return value is the total width in pixels +of text, not including the extra pixels used by highly exagerrated +characters such as cursive ``f''. If the string contains newlines or tabs, +those characters are not expanded or treated specially when measuring the +string. +

    font metrics font ?-displayof window? ?option?
    +Returns information about the metrics (the font-specific data), for +font when it is used on window's display. font is a font +description; see FONT DESCRIPTIONS below. If the window argument is +omitted, it defaults to the main window. If option is specified, +returns the value of that metric; if it is omitted, the return value is a +list of all the metrics and their values. See FONT METRICS below for a list +of the possible metrics. +

    font names
    +The return value is a list of all the named fonts that are currently defined. +

    +

    FONT DESCRIPTION

    +The following formats are accepted as a font description anywhere +font is specified as an argument above; these same forms are also +permitted when specifying the -font option for widgets. +

    +

    +

    [1] fontname
    +The name of a named font, created using the font create command. When +a widget uses a named font, it is guaranteed that this will never cause an +error, as long as the named font exists, no matter what potentially invalid +or meaningless set of attributes the named font has. If the named font +cannot be displayed with exactly the specified attributes, some other close +font will be substituted automatically. +

    [2] systemfont
    +The platform-specific name of a font, interpreted by the graphics server. +This also includes, under X, an XLFD (see [4]) for which a single ``*'' +character was used to elide more than one field in the middle of the +name. See PLATFORM-SPECIFIC issues for a list of the system fonts. +

    [3] family ?size? ?style? ?style ...?
    +A properly formed list whose first element is the desired font +family and whose optional second element is the desired size. +The interpretation of the size attribute follows the same rules +described for -size in FONT OPTIONS below. Any additional optional +arguments following the size are font styles. Possible values +for the style arguments are as follows: +
    normal	bold	roman	italic	
    +underline	overstrike
    +

    [4] X-font names (XLFD)
    +A Unix-centric font name of the form +-foundry-family-weight-slant-setwidth-addstyle-pixel-point-resx-resy-spacing-width-charset-encoding. +The ``*'' character may be used to skip individual fields that the +user does not care about. There must be exactly one ``*'' for each +field skipped, except that a ``*'' at the end of the XLFD skips any +remaining fields; the shortest valid XLFD is simply ``*'', signifying +all fields as defaults. Any fields that were skipped are given default +values. For compatibility, an XLFD always chooses a font of the specified +pixel size (not point size); although this interpretation is not strictly +correct, all existing applications using XLFDs assumed that one ``point'' +was in fact one pixel and would display incorrectly (generally larger) if +the correct size font were actually used. +

    [5] option value ?option value ...?
    +A properly formed list of option-value pairs that specify +the desired attributes of the font, in the same format used when defining +a named font; see FONT OPTIONS below. +

    +

    +When font description font is used, the system attempts to parse the +description according to each of the above five rules, in the order specified. +Cases [1] and [2] must match the name of an existing named font or of a +system font. Cases [3], [4], and [5] are accepted on all +platforms and the closest available font will be used. In some situations +it may not be possible to find any close font (e.g., the font family was +a garbage value); in that case, some system-dependant default font is +chosen. If the font description does not match any of the above patterns, +an error is generated. +

    FONT METRICS

    +The following options are used by the font metrics command to query +font-specific data determined when the font was created. These properties are +for the whole font itself and not for individual characters drawn in that +font. In the following definitions, the ``baseline'' of a font is the +horizontal line where the bottom of most letters line up; certain letters, +such as lower-case ``g'' stick below the baseline. +

    +

    +

    -ascent
    +The amount in pixels that the tallest letter sticks up above the baseline of +the font, plus any extra blank space added by the designer of the font. +

    -descent
    +The largest amount in pixels that any letter sticks down below the baseline +of the font, plus any extra blank space added by the designer of the font. +

    -linespace
    +Returns how far apart vertically in pixels two lines of text using the same +font should be placed so that none of the characters in one line overlap any +of the characters in the other line. This is generally the sum of the ascent +above the baseline line plus the descent below the baseline. +

    -fixed
    +Returns a boolean flag that is ``1'' if this is a fixed-width font, +where each normal character is the the same width as all the other +characters, or is ``0'' if this is a proportionally-spaced font, where +individual characters have different widths. The widths of control +characters, tab characters, and other non-printing characters are not +included when calculating this value. +

    +

    FONT OPTIONS

    +The following options are supported on all platforms, and are used when +constructing a named font or when specifying a font using style [5] as +above: +

    +

    +

    -family name
    +The case-insensitive font family name. Tk guarantees to support the font +families named Courier (a monospaced ``typewriter'' font), Times +(a serifed ``newspaper'' font), and Helvetica (a sans-serif +``European'' font). The most closely matching native font family will +automatically be substituted when one of the above font families is used. +The name may also be the name of a native, platform-specific font +family; in that case it will work as desired on one platform but may not +display correctly on other platforms. If the family is unspecified or +unrecognized, a platform-specific default font will be chosen. +

    -size size
    +The desired size of the font. If the size argument is a positive +number, it is interpreted as a size in points. If size is a negative +number, its absolute value is interpreted as a size in pixels. If a +font cannot be displayed at the specified size, a nearby size will be +chosen. If size is unspecified or zero, a platform-dependent default +size will be chosen. +

    +Sizes should normally be specified in points so the application will remain +the same ruler size on the screen, even when changing screen resolutions or +moving scripts across platforms. However, specifying pixels is useful in +certain circumstances such as when a piece of text must line up with respect +to a fixed-size bitmap. The mapping between points and pixels is set when +the application starts, based on properties of the installed monitor, but it +can be overridden by calling the tk scaling command. +

    -weight weight
    +The nominal thickness of the characters in the font. The value +normal specifies a normal weight font, while bold specifies a +bold font. The closest available weight to the one specified will +be chosen. The default weight is normal. +

    -slant slant
    +The amount the characters in the font are slanted away from the +vertical. Valid values for slant are roman and italic. +A roman font is the normal, upright appearance of a font, while +an italic font is one that is tilted some number of degrees from upright. +The closest available slant to the one specified will be chosen. +The default slant is roman. +

    -underline boolean
    +The value is a boolean flag that specifies whether characters in this +font should be underlined. The default value for underline is false. +

    -overstrike boolean
    +The value is a boolean flag that specifies whether a horizontal line should +be drawn through the middle of characters in this font. The default value +for overstrike is false. + +

    +

    PLATFORM-SPECIFIC ISSUES

    +The following named system fonts are supported: +

    +

    +

    X Windows:
    +All valid X font names, including those listed by xlsfonts(1), are available. +

    MS Windows:
    +
    system	ansi	device
    +systemfixed	ansifixed	oemfixed
    +

    Macintosh:
    +
    system	application
    +

    +

    SEE ALSO

    +options +

    KEYWORDS

    +font +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/frame.htm b/hlp/en/tk/frame.htm new file mode 100644 index 0000000..2924497 --- /dev/null +++ b/hlp/en/tk/frame.htm @@ -0,0 +1,176 @@ +Tk Built-In Commands - frame manual page +
    +
    NAME +
    frame - Create and manipulate frame widgets
    +
    SYNOPSIS +
    +
    frame pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -background, background, Background +
    -class, class, Class +
    -colormap, colormap, Colormap +
    -container, container, Container +
    -height, height, Height +
    -visual, visual, Visual +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    BINDINGS +
    KEYWORDS +

    +

    NAME

    +frame - Create and manipulate frame widgets +

    SYNOPSIS

    +framepathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -background +
    Database Name: background +
    Database Class: Background +
    This option is the same as the standard background option +except that its value may also be specified as an empty string. +In this case, the widget will display no background or border, and +no colors will be consumed from its colormap for its background +and border. +

    Command-Line Name: -class +
    Database Name: class +
    Database Class: Class +
    Specifies a class for the window. +This class will be used when querying the option database for +the window's other options, and it will also be used later for +other purposes such as bindings. +The class option may not be changed with the configure +widget command. +

    Command-Line Name: -colormap +
    Database Name: colormap +
    Database Class: Colormap +
    Specifies a colormap to use for the window. +The value may be either new, in which case a new colormap is +created for the window and its children, or the name of another +window (which must be on the same screen and have the same visual +as pathName), in which case the new window will use the colormap +from the specified window. +If the colormap option is not specified, the new window +uses the same colormap as its parent. +This option may not be changed with the configure +widget command. +

    Command-Line Name: -container +
    Database Name: container +
    Database Class: Container +
    The value must be a boolean. If true, it means that this window will +be used as a container in which some other application will be embedded +(for example, a Tk toplevel can be embedded using the -use option). +The window will support the appropriate window manager protocols for +things like geometry requests. The window should not have any +children of its own in this application. +This option may not be changed with the configure +widget command. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies the desired height for the window in any of the forms +acceptable to Tk_GetPixels. +If this option is less than or equal to zero then the window will +not request any size at all. +

    Command-Line Name: -visual +
    Database Name: visual +
    Database Class: Visual +
    Specifies visual information for the new window in any of the +forms accepted by Tk_GetVisual. +If this option is not specified, the new window will use the same +visual as its parent. +The visual option may not be modified with the configure +widget command. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired width for the window in any of the forms +acceptable to Tk_GetPixels. +If this option is less than or equal to zero then the window will +not request any size at all. +
    +

    DESCRIPTION

    +The frame command creates a new window (given by the +pathName argument) and makes it into a frame widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the frame such as its background color +and relief. The frame command returns the +path name of the new window. +

    +A frame is a simple widget. Its primary purpose is to act as a +spacer or container for complex window layouts. The only features +of a frame are its background color and an optional 3-D border to make the +frame appear raised or sunken. + +

    WIDGET COMMAND

    +The frame command creates a new Tcl command whose +name is the same as the path name of the frame's window. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +PathName is the name of the command, which is the same as +the frame widget's path name. Option and the args +determine the exact behavior of the command. The following +commands are possible for frame widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the frame +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the frame +command. + +

    +

    BINDINGS

    +When a new frame is created, it has no default event bindings: +frames are not intended to be interactive. + +

    KEYWORDS

    +frame, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/getOpenFile.htm b/hlp/en/tk/getOpenFile.htm new file mode 100644 index 0000000..bd158e9 --- /dev/null +++ b/hlp/en/tk/getOpenFile.htm @@ -0,0 +1,158 @@ +Tk Built-In Commands - tk_getOpenFile manual page +
    +
    NAME +
    tk_getOpenFile, tk_getSaveFile - pop up a dialog box for the user to select a file to open or save.
    +
    SYNOPSIS +
    +
    tk_getOpenFile ?option value ...? +
    tk_getSaveFile ?option value ...? +
    +
    DESCRIPTION +
    +
    -defaultextension extension +
    -filetypes filePatternList +
    -initialdir directory +
    -initialfile filename +
    -parent window +
    -title titleString +
    +
    SPECIFYING FILE PATTERNS +
    SPECIFYING EXTENSIONS +
    EXAMPLE +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +tk_getOpenFile, tk_getSaveFile - pop up a dialog box for the user to select a file to open or save. +

    SYNOPSIS

    +tk_getOpenFile ?option value ...?
    +tk_getSaveFile ?option value ...?
    +

    DESCRIPTION

    +The procedures tk_getOpenFile and tk_getSaveFile pop up a +dialog box for the user to select a file to open or save. The +tk_getOpenFile command is usually associated with the Open +command in the File menu. Its purpose is for the user to select an +existing file only. If the user enters an non-existent file, the +dialog box gives the user an error prompt and requires the user to give +an alternative selection. If an application allows the user to create +new files, it should do so by providing a separate New menu command. +

    +The tk_getSaveFile command is usually associated with the Save +as command in the File menu. If the user enters a file that +already exists, the dialog box prompts the user for confirmation +whether the existing file should be overwritten or not. +

    +The following option-value pairs are possible as command line +arguments to these two commands: +

    +

    +

    -defaultextension extension
    +Specifies a string that will be appended to the filename if the user +enters a filename without an extension. The defaut value is the empty +string, which means no extension will be appended to the filename in +any case. This option is ignored on the Macintosh platform, which +does not require extensions to filenames. +

    -filetypes filePatternList
    +If a File types listbox exists in the file dialog on the particular +platform, this option gives the filetypes in this listbox. When +the user choose a filetype in the listbox, only the files of that type +are listed. If this option is unspecified, or if it is set to the +empty list, or if the File types listbox is not supported by the +particular platform then all files are listed regardless of their +types. See the section SPECIFYING FILE PATTERNS below for a +discussion on the contents of filePatternList. +

    -initialdir directory
    +Specifies that the files in directory should be displayed +when the dialog pops up. If this parameter is not specified, then +the files in the current working directory are displayed. If the +parameter specifies a relative path, the return value will convert the +relative path to an absolute path. This option may not always work on +the Macintosh. This is not a bug. Rather, the General Controls +control panel on the Mac allows the end user to override the +application default directory. +

    -initialfile filename
    +Specifies a filename to be displayed in the dialog when it pops up. This +option is ignored on the Macintosh platform. +

    -parent window
    +Makes window the logical parent of the file dialog. The file +dialog is displayed on top of its parent window. +

    -title titleString
    +Specifies a string to display as the title of the dialog box. If this +option is not specified, then a default title is displayed. +

    +

    +If the user selects a file, both tk_getOpenFile and +tk_getSaveFile return the full pathname of this file. If the +user cancels the operation, both commands return the empty string. +

    SPECIFYING FILE PATTERNS

    +The filePatternList value given by the -filetypes option +is a list of file patterns. Each file pattern is a list of the +form +
    typeName {extension ?extension ...?} ?{macType ?macType ...?}?
    +typeName is the name of the file type described by this +file pattern and is the text string that appears in the File types +listbox. extension is a file extension for this file pattern. +macType is a four-character Macintosh file type. The list of +macTypes is optional and may be omitted for applications that do +not need to execute on the Macintosh platform. +

    +Several file patterns may have the same typeName, in which case +they refer to the same file type and share the same entry in the +listbox. When the user selects an entry in the listbox, all the files +that match at least one of the file patterns corresponding +to that entry are listed. Usually, each file pattern corresponds to a +distinct type of file. The use of more than one file patterns for one +type of file is necessary on the Macintosh platform only. +

    +On the Macintosh platform, a file matches a file pattern if its +name matches at least one of the extension(s) AND it +belongs to at least one of the macType(s) of the +file pattern. For example, the C Source Files file pattern in the +sample code matches with files that have a .c extension AND +belong to the macType TEXT. To use the OR rule instead, +you can use two file patterns, one with the extensions only and +the other with the macType only. The GIF Files file type +in the sample code matches files that EITHER have a .gif +extension OR belong to the macType GIFF. +

    +On the Unix and Windows platforms, a file matches a file pattern +if its name matches at at least one of the extension(s) of +the file pattern. The macTypes are ignored. +

    SPECIFYING EXTENSIONS

    +On the Unix and Macintosh platforms, extensions are matched using +glob-style pattern matching. On the Windows platforms, extensions are +matched by the underlying operating system. The types of possible +extensions are: (1) the special extension * matches any +file; (2) the special extension "" matches any files that +do not have an extension (i.e., the filename contains no full stop +character); (3) any character string that does not contain any wild +card characters (* and ?). +

    +Due to the different pattern matching rules on the various platforms, +to ensure portability, wild card characters are not allowed in the +extensions, except as in the special extension *. Extensions +without a full stop character (e.g, ~) are allowed but may not +work on all platforms. + +

    EXAMPLE

    +
    set types {
    +    {{Text Files}       {.txt}        }
    +    {{TCL Scripts}      {.tcl}        }
    +    {{C Source Files}   {.c}      TEXT}
    +    {{GIF Files}        {.gif}        }
    +    {{GIF Files}        {}        GIFF}
    +    {{All Files}        *             }
    +}
    +set filename [tk_getOpenFile -filetypes $types]
    +
    +if {$filename != ""} {
    +    # Open the file ...
    +}
    +

    SEE ALSO

    +tk_chooseDirectory +

    KEYWORDS

    +file selection dialog +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/grab.htm b/hlp/en/tk/grab.htm new file mode 100644 index 0000000..f39afdc --- /dev/null +++ b/hlp/en/tk/grab.htm @@ -0,0 +1,127 @@ +Built-In Commands - grab manual page +
    +
    NAME +
    grab - Confine pointer and keyboard events to a window sub-tree
    +
    SYNOPSIS +
    +
    grab ?-global? window +
    grab option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    grab ?-global? window +
    grab current ?window? +
    grab release window +
    grab set ?-global? window +
    grab status window +
    +
    BUGS +
    KEYWORDS +

    +

    NAME

    +grab - Confine pointer and keyboard events to a window sub-tree +

    SYNOPSIS

    +grab ?-global? window
    +grab option ?arg arg ...?
    +

    DESCRIPTION

    +This command implements simple pointer and keyboard grabs for Tk. +Tk's grabs are different than the grabs +described in the Xlib documentation. +When a grab is set for a particular window, Tk restricts all pointer +events to the grab window and its descendants in Tk's window hierarchy. +Whenever the pointer is within the grab window's subtree, the pointer +will behave exactly the same as if there had been no grab at all +and all events will be reported in the normal fashion. +When the pointer is outside window's tree, button presses and +releases and +mouse motion events are reported to window, and window entry +and window exit events are ignored. +The grab subtree ``owns'' the pointer: +windows outside the grab subtree will be visible on the screen +but they will be insensitive until the grab is released. +The tree of windows underneath the grab window can include top-level +windows, in which case all of those top-level windows +and their descendants will continue to receive mouse events +during the grab. +

    +Two forms of grabs are possible: local and global. +A local grab affects only the grabbing application: events will +be reported to other applications as if the grab had never occurred. +Grabs are local by default. +A global grab locks out all applications on the screen, +so that only the given subtree of the grabbing application will be +sensitive to pointer events (mouse button presses, mouse button releases, +pointer motions, window entries, and window exits). +During global grabs the window manager will not receive pointer +events either. +

    +During local grabs, keyboard events (key presses and key releases) +are delivered as usual: the window +manager controls which application receives keyboard events, and +if they are sent to any window in the grabbing application then they are +redirected to the focus window. +During a global grab Tk grabs the keyboard so that all keyboard events +are always sent to the grabbing application. +The focus command is still used to determine which window in the +application receives the keyboard events. +The keyboard grab is released when the grab is released. +

    +Grabs apply to particular displays. If an application has windows +on multiple displays then it can establish a separate grab on each +display. +The grab on a particular display affects only the windows on +that display. +It is possible for different applications on a single display to have +simultaneous local grabs, but only one application can have a global +grab on a given display at once. +

    +The grab command can take any of the following forms: +

    +

    +

    grab ?-global? window
    +Same as grab set, described below. +

    grab current ?window?
    +If window is specified, returns the name of the current grab +window in this application for window's display, or an empty +string if there is no such window. +If window is omitted, the command returns a list whose elements +are all of the windows grabbed by this application for all displays, +or an empty string if the application has no grabs. +

    grab release window
    +Releases the grab on window if there is one, otherwise does +nothing. Returns an empty string. +

    grab set ?-global? window
    +Sets a grab on window. If -global is specified then the +grab is global, otherwise it is local. +If a grab was already in effect for this application on +window's display then it is automatically released. +If there is already a grab on window and it has the same +global/local form as the requested grab, then the command +does nothing. Returns an empty string. +

    grab status window
    +Returns none if no grab is currently set on window, +local if a local grab is set on window, and +global if a global grab is set. + +

    +

    BUGS

    +It took an incredibly complex and gross implementation to produce +the simple grab effect described above. +Given the current implementation, it isn't safe for applications +to use the Xlib grab facilities at all except through the Tk grab +procedures. +If applications try to manipulate X's grab mechanisms directly, +things will probably break. +

    +If a single process is managing several different Tk applications, +only one of those applications can have a local grab for a given +display at any given time. If the applications are in different +processes, this restriction doesn't exist. + +

    KEYWORDS

    +grab, keyboard events, pointer events, window +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/grid.htm b/hlp/en/tk/grid.htm new file mode 100644 index 0000000..dcd3e0a --- /dev/null +++ b/hlp/en/tk/grid.htm @@ -0,0 +1,343 @@ +Tk Built-In Commands - grid manual page +
    +
    NAME +
    grid - Geometry manager that arranges widgets in a grid
    +
    SYNOPSIS +
    +
    grid option arg ?arg ...? +
    +
    DESCRIPTION +
    +
    grid slave ?slave ...? ?options? +
    grid bbox master ?column row? ?column2 row2? +
    grid columnconfigure master index ?-option value...? +
    grid configure slave ?slave ...? ?options? +
    +
    -column n +
    -columnspan n +
    -in other +
    -ipadx amount +
    -ipady amount +
    -padx amount +
    -pady amount +
    -row n +
    -rowspan n +
    -sticky style +
    +
    grid forget slave ?slave ...? +
    grid info slave +
    grid location master x y +
    grid propagate master ?boolean? +
    grid rowconfigure master index ?-option value...? +
    grid remove slave ?slave ...? +
    grid size master +
    grid slaves master ?-option value? +
    +
    RELATIVE PLACEMENT +
    +
    - +
    x +
    ^ +
    +
    THE GRID ALGORITHM +
    GEOMETRY PROPAGATION +
    RESTRICTIONS ON MASTER WINDOWS +
    STACKING ORDER +
    CREDITS +
    KEYWORDS +

    +

    NAME

    +grid - Geometry manager that arranges widgets in a grid +

    SYNOPSIS

    +grid option arg ?arg ...?
    +

    DESCRIPTION

    +The grid command is used to communicate with the grid +geometry manager that arranges widgets in rows and columns inside +of another window, called the geometry master (or master window). +The grid command can have any of several forms, depending +on the option argument: +

    +

    +

    grid slave ?slave ...? ?options?
    +If the first argument to grid is a window name (any value +starting with ``.''), then the command is processed in the same +way as grid configure. +

    grid bbox master ?column row? ?column2 row2?
    +With no arguments, +the bounding box (in pixels) of the grid is returned. +The return value consists of 4 integers. The first two are the pixel +offset from the master window (x then y) of the top-left corner of the +grid, and the second two integers are the width and height of the grid, +also in pixels. If a single column and row is specified on +the command line, then the bounding box for that cell is returned, where the +top left cell is numbered from zero. If both column and row +arguments are specified, then the bounding box spanning the rows and columns +indicated is returned. +

    grid columnconfigure master index ?-option value...?
    +Query or set the column properties of the index column of the +geometry master, master. +The valid options are -minsize, -weight and -pad. +If one or more options are provided, then index may be given as +a list of column indeces to which the configuration options will operate on. +The -minsize option sets the minimum size, in screen units, +that will be permitted for this column. +The -weight option (an integer value) +sets the relative weight for apportioning +any extra spaces among +columns. +A weight of zero (0) indicates the column will not deviate from its requested +size. A column whose weight is two will grow at twice the rate as a column +of weight one when extra space is allocated to the layout. +The -pad option specifies the number of screen units that will be +added to the largest window contained completely in that column when the +grid geometry manager requests a size from the containing window. +If only an option is specified, with no value, +the current value of that option is returned. +If only the master window and index is specified, all the current settings +are returned in an list of "-option value" pairs. +

    grid configure slave ?slave ...? ?options?
    +The arguments consist of the names of one or more slave windows +followed by pairs of arguments that specify how +to manage the slaves. +The characters -, x and ^, +can be specified instead of a window name to alter the default +location of a slave, as described in the ``RELATIVE PLACEMENT'' +section, below. +The following options are supported: +

    +

    +

    -column n
    +Insert the slave so that it occupies the nth column in the grid. +Column numbers start with 0. If this option is not supplied, then the +slave is arranged just to the right of previous slave specified on this +call to grid, or column "0" if it is the first slave. For each +x that immediately precedes the slave, the column position +is incremented by one. Thus the x represents a blank column +for this row in the grid. +

    -columnspan n
    +Insert the slave so that it occupies n columns in the grid. +The default is one column, unless the window name is followed by a +-, in which case the columnspan is incremented once for each immediately +following -. +

    -in other
    +Insert the slave(s) in the master +window given by other. The default is the first slave's +parent window. +

    -ipadx amount
    +The amount specifies how much horizontal internal padding to +leave on each side of the slave(s). This is space is added +inside the slave(s) border. +The amount must be a valid screen distance, such as 2 or .5c. +It defaults to 0. +

    -ipady amount
    +The amount specifies how much vertical internal padding to +leave on on the top and bottom of the slave(s). +This space is added inside the slave(s) border. +The amount defaults to 0. +

    -padx amount
    +The amount specifies how much horizontal external padding to +leave on each side of the slave(s), in screen units. +The amount defaults to 0. +This space is added outside the slave(s) border. +

    -pady amount
    +The amount specifies how much vertical external padding to +leave on the top and bottom of the slave(s), in screen units. +The amount defaults to 0. +This space is added outside the slave(s) border. +

    -row n
    +Insert the slave so that it occupies the nth row in the grid. +Row numbers start with 0. If this option is not supplied, then the +slave is arranged on the same row as the previous slave specified on this +call to grid, or the first unoccupied row if this is the first slave. +

    -rowspan n
    +Insert the slave so that it occupies n rows in the grid. +The default is one row. If the next grid command contains +^ characters instead of slaves that line up with the columns +of this slave, then the rowspan of this slave is +extended by one. +

    -sticky style
    +If a slave's cell is larger than its requested dimensions, this +option may be used to position (or stretch) the slave within its cell. +Style is a string that contains zero or more of the characters +n, s, e or w. +The string can optionally contains spaces or +commas, but they are ignored. Each letter refers to a side (north, south, +east, or west) that the slave will "stick" to. If both n and s (or +e and w) are specified, the slave will be stretched to fill the entire +height (or width) of its cavity. The sticky option subsumes the +combination of -anchor and -fill that is used by pack. +The default is {}, which causes the slave to be centered in its cavity, +at its requested size. +

    If any of the slaves are already managed by the geometry manager +then any unspecified options for them retain their previous values rather +than receiving default values.

    +

    +

    grid forget slave ?slave ...?
    +Removes each of the slaves from grid for its +master and unmaps their windows. +The slaves will no longer be managed by the grid geometry manager. +The configuration options for that window are forgotten, so that if the +slave is managed once more by the grid geometry manager, the initial +default settings are used. +

    grid info slave
    +Returns a list whose elements are the current configuration state of +the slave given by slave in the same option-value form that +might be specified to grid configure. +The first two elements of the list are ``-in master'' where +master is the slave's master. +

    grid location master x y
    +Given x and y values in screen units relative to the master window, +the column and row number at that x and y location is returned. +For locations that are above or to the left of the grid, -1 is returned. +

    grid propagate master ?boolean?
    +If boolean has a true boolean value such as 1 or on +then propagation is enabled for master, which must be a window +name (see ``GEOMETRY PROPAGATION'' below). +If boolean has a false boolean value then propagation is +disabled for master. +In either of these cases an empty string is returned. +If boolean is omitted then the command returns 0 or +1 to indicate whether propagation is currently enabled +for master. +Propagation is enabled by default. +

    grid rowconfigure master index ?-option value...?
    +Query or set the row properties of the index row of the +geometry master, master. +The valid options are -minsize, -weight and -pad. +If one or more options are provided, then index may be given as +a list of row indeces to which the configuration options will operate on. +The -minsize option sets the minimum size, in screen units, +that will be permitted for this row. +The -weight option (an integer value) +sets the relative weight for apportioning +any extra spaces among +rows. +A weight of zero (0) indicates the row will not deviate from its requested +size. A row whose weight is two will grow at twice the rate as a row +of weight one when extra space is allocated to the layout. +The -pad option specifies the number of screen units that will be +added to the largest window contained completely in that row when the +grid geometry manager requests a size from the containing window. +If only an option is specified, with no value, +the current value of that option is returned. +If only the master window and index is specified, all the current settings +are returned in an list of "-option value" pairs. +

    grid remove slave ?slave ...?
    +Removes each of the slaves from grid for its +master and unmaps their windows. +The slaves will no longer be managed by the grid geometry manager. +However, the configuration options for that window are remembered, +so that if the +slave is managed once more by the grid geometry manager, the previous +values are retained. +

    grid size master
    +Returns the size of the grid (in columns then rows) for master. +The size is determined either by the slave occupying the largest +row or column, or the largest column or row with a minsize, +weight, or pad that is non-zero. +

    grid slaves master ?-option value?
    +If no options are supplied, a list of all of the slaves in master +are returned, most recently manages first. +Option can be either -row or -column which +causes only the slaves in the row (or column) specified by value +to be returned. +

    +

    RELATIVE PLACEMENT

    +The grid command contains a limited set of capabilities that +permit layouts to be created without specifying the row and column +information for each slave. This permits slaves to be rearranged, +added, or removed without the need to explicitly specify row and +column information. +When no column or row information is specified for a slave, +default values are chosen for +column, row, columnspan and rowspan +at the time the slave is managed. The values are chosen +based upon the current layout of the grid, the position of the slave +relative to other slaves in the same grid command, and the presence +of the characters -, ^, and ^ in grid +command where slave names are normally expected. +

    +

    +

    -
    +This increases the columnspan of the slave to the left. Several +-'s in a row will successively increase the columnspan. A - +may not follow a ^ or a x. +

    x
    +This leaves an empty column between the slave on the left and +the slave on the right. +

    ^
    +This extends the rowspan of the slave above the ^'s +in the grid. The number of ^'s in a row must match the number of +columns spanned by the slave above it. +

    +

    THE GRID ALGORITHM

    +The grid geometry manager lays out its slaves in three steps. +In the first step, the minimum size needed to fit all of the slaves +is computed, then (if propagation is turned on), a request is made +of the master window to become that size. +In the second step, the requested size is compared against the actual size +of the master. If the sizes are different, then spaces is added to or taken +away from the layout as needed. +For the final step, each slave is positioned in its row(s) and column(s) +based on the setting of its sticky flag. +

    +To compute the minimum size of a layout, the grid geometry manager +first looks at all slaves whose columnspan and rowspan values are one, +and computes the nominal size of each row or column to be either the +minsize for that row or column, or the sum of the padding +plus the size of the largest slave, whichever is greater. Then the +slaves whose rowspans or columnspans are greater than one are +examined. If a group of rows or columns need to be increased in size +in order to accommodate these slaves, then extra space is added to each +row or column in the group according to its weight. For each +group whose weights are all zero, the additional space is apportioned +equally. +

    +For masters whose size is larger than the requested layout, the additional +space is apportioned according to the row and column weights. If all of +the weights are zero, the layout is centered within its master. +For masters whose size is smaller than the requested layout, space is taken +away from columns and rows according to their weights. However, once a +column or row shrinks to its minsize, its weight is taken to be zero. +If more space needs to be removed from a layout than would be permitted, as +when all the rows or columns are at there minimum sizes, the layout is +clipped on the bottom and right. +

    GEOMETRY PROPAGATION

    +The grid geometry manager normally computes how large a master must be to +just exactly meet the needs of its slaves, and it sets the +requested width and height of the master to these dimensions. +This causes geometry information to propagate up through a +window hierarchy to a top-level window so that the entire +sub-tree sizes itself to fit the needs of the leaf windows. +However, the grid propagate command may be used to +turn off propagation for one or more masters. +If propagation is disabled then grid will not set +the requested width and height of the master window. +This may be useful if, for example, you wish for a master +window to have a fixed size that you specify. + +

    RESTRICTIONS ON MASTER WINDOWS

    +The master for each slave must either be the slave's parent +(the default) or a descendant of the slave's parent. +This restriction is necessary to guarantee that the +slave can be placed over any part of its master that is +visible without danger of the slave being clipped by its parent. +In addition, all slaves in one call to grid must have the same master. +

    STACKING ORDER

    +If the master for a slave is not its parent then you must make sure +that the slave is higher in the stacking order than the master. +Otherwise the master will obscure the slave and it will appear as +if the slave hasn't been managed correctly. +The easiest way to make sure the slave is higher than the master is +to create the master window first: the most recently created window +will be highest in the stacking order. +

    CREDITS

    +The grid command is based on ideas taken from the GridBag +geometry manager written by Doug. Stein, and the blt_table geometry +manager, written by George Howlett. +

    KEYWORDS

    +geometry manager, location, grid, cell, propagation, size, pack +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/image.htm b/hlp/en/tk/image.htm new file mode 100644 index 0000000..d44dd60 --- /dev/null +++ b/hlp/en/tk/image.htm @@ -0,0 +1,104 @@ +Tk Built-In Commands - image manual page +
    +
    NAME +
    image - Create and manipulate images
    +
    SYNOPSIS +
    +
    image option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    image create type ?name? ?option value ...? +
    image delete ?name name ...? +
    image height name +
    image names +
    image type name +
    image types +
    image width name +
    +
    BUILT-IN IMAGE TYPES +
    +
    bitmap +
    photo +
    +
    KEYWORDS +

    +

    NAME

    +image - Create and manipulate images +

    SYNOPSIS

    +imageoption ?arg arg ...?
    +

    DESCRIPTION

    +The image command is used to create, delete, and query images. +It can take several different forms, depending on the +option argument. The legal forms are: +

    +

    +

    image create type ?name? ?option value ...?
    +Creates a new image and returns its name. +type specifies the type of the image, which must be one of +the types currently defined (e.g., bitmap). +name specifies the name for the image; if it is omitted then +Tk picks a name of the form imagex, where x is +an integer. +There may be any number of option-value pairs, +which provide configuration options for the new image. +The legal set of options is defined separately for each image +type; see below for details on the options for built-in image types. +If an image already exists by the given name then it is replaced +with the new image and any instances of that image will redisplay +with the new contents. +It is important to note that the image command will silently overwrite any +procedure that may currently be defined by the given name, so choose the +name wisely. It is recommended to use a separate namespace for image names +(e.g., ::img::logo, ::img::large). +

    image delete ?name name ...?
    +Deletes each of the named images and returns an empty string. +If there are instances of the images displayed in widgets, +the images won't actually be deleted until all of the instances +are released. +However, the association between the instances and the image +manager will be dropped. +Existing instances will retain their sizes but redisplay as +empty areas. +If a deleted image is recreated with another call to image create, +the existing instances will use the new image. +

    image height name
    +Returns a decimal string giving the height of image name +in pixels. +

    image names
    +Returns a list containing the names of all existing images. +

    image type name
    +Returns the type of image name (the value of the type +argument to image create when the image was created). +

    image types
    +Returns a list whose elements are all of the valid image types +(i.e., all of the values that may be supplied for the type +argument to image create). +

    image width name
    +Returns a decimal string giving the width of image name +in pixels. + +

    +

    BUILT-IN IMAGE TYPES

    +The following image types are defined by Tk so they will be available +in any Tk application. +Individual applications or extensions may define additional types. +

    +

    +

    bitmap
    +Each pixel in the image displays a foreground color, a background +color, or nothing. +See the bitmap manual entry for more information. +

    photo
    +Displays a variety of full-color images, using dithering to +approximate colors on displays with limited color capabilities. +See the photo manual entry for more information. + +

    +

    KEYWORDS

    +height, image, types of images, width +
    +Copyright © 1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/keysyms.htm b/hlp/en/tk/keysyms.htm new file mode 100644 index 0000000..bb021f2 --- /dev/null +++ b/hlp/en/tk/keysyms.htm @@ -0,0 +1,909 @@ +Tk Built-In Commands - keysyms manual page +

    NAME

    +keysyms - keysyms recognized by Tk +

    DESCRIPTION

    +Tk recognizes many keysyms when specifying key bindings (eg, +bind . <Key-keysym>). The following list enumerates the +keysyms that will be recognized by Tk. Note that not all keysyms will +be valid on all platforms. For example, on Unix systems, the presence +of a particular keysym is dependant on the configuration of the +keyboard modifier map. This list shows keysyms along with their +decimal and hexidecimal values. +

    +

    space                               32     0x0020
    +exclam                              33     0x0021
    +quotedbl                            34     0x0022
    +numbersign                          35     0x0023
    +dollar                              36     0x0024
    +percent                             37     0x0025
    +ampersand                           38     0x0026
    +quoteright                          39     0x0027
    +parenleft                           40     0x0028
    +parenright                          41     0x0029
    +asterisk                            42     0x002a
    +plus                                43     0x002b
    +comma                               44     0x002c
    +minus                               45     0x002d
    +period                              46     0x002e
    +slash                               47     0x002f
    +0                                   48     0x0030
    +1                                   49     0x0031
    +2                                   50     0x0032
    +3                                   51     0x0033
    +4                                   52     0x0034
    +5                                   53     0x0035
    +6                                   54     0x0036
    +7                                   55     0x0037
    +8                                   56     0x0038
    +9                                   57     0x0039
    +colon                               58     0x003a
    +semicolon                           59     0x003b
    +less                                60     0x003c
    +equal                               61     0x003d
    +greater                             62     0x003e
    +question                            63     0x003f
    +at                                  64     0x0040
    +A                                   65     0x0041
    +B                                   66     0x0042
    +C                                   67     0x0043
    +D                                   68     0x0044
    +E                                   69     0x0045
    +F                                   70     0x0046
    +G                                   71     0x0047
    +H                                   72     0x0048
    +I                                   73     0x0049
    +J                                   74     0x004a
    +K                                   75     0x004b
    +L                                   76     0x004c
    +M                                   77     0x004d
    +N                                   78     0x004e
    +O                                   79     0x004f
    +P                                   80     0x0050
    +Q                                   81     0x0051
    +R                                   82     0x0052
    +S                                   83     0x0053
    +T                                   84     0x0054
    +U                                   85     0x0055
    +V                                   86     0x0056
    +W                                   87     0x0057
    +X                                   88     0x0058
    +Y                                   89     0x0059
    +Z                                   90     0x005a
    +bracketleft                         91     0x005b
    +backslash                           92     0x005c
    +bracketright                        93     0x005d
    +asciicircum                         94     0x005e
    +underscore                          95     0x005f
    +quoteleft                           96     0x0060
    +a                                   97     0x0061
    +b                                   98     0x0062
    +c                                   99     0x0063
    +d                                  100     0x0064
    +e                                  101     0x0065
    +f                                  102     0x0066
    +g                                  103     0x0067
    +h                                  104     0x0068
    +i                                  105     0x0069
    +j                                  106     0x006a
    +k                                  107     0x006b
    +l                                  108     0x006c
    +m                                  109     0x006d
    +n                                  110     0x006e
    +o                                  111     0x006f
    +p                                  112     0x0070
    +q                                  113     0x0071
    +r                                  114     0x0072
    +s                                  115     0x0073
    +t                                  116     0x0074
    +u                                  117     0x0075
    +v                                  118     0x0076
    +w                                  119     0x0077
    +x                                  120     0x0078
    +y                                  121     0x0079
    +z                                  122     0x007a
    +braceleft                          123     0x007b
    +bar                                124     0x007c
    +braceright                         125     0x007d
    +asciitilde                         126     0x007e
    +nobreakspace                       160     0x00a0
    +exclamdown                         161     0x00a1
    +cent                               162     0x00a2
    +sterling                           163     0x00a3
    +currency                           164     0x00a4
    +yen                                165     0x00a5
    +brokenbar                          166     0x00a6
    +section                            167     0x00a7
    +diaeresis                          168     0x00a8
    +copyright                          169     0x00a9
    +ordfeminine                        170     0x00aa
    +guillemotleft                      171     0x00ab
    +notsign                            172     0x00ac
    +hyphen                             173     0x00ad
    +registered                         174     0x00ae
    +macron                             175     0x00af
    +degree                             176     0x00b0
    +plusminus                          177     0x00b1
    +twosuperior                        178     0x00b2
    +threesuperior                      179     0x00b3
    +acute                              180     0x00b4
    +mu                                 181     0x00b5
    +paragraph                          182     0x00b6
    +periodcentered                     183     0x00b7
    +cedilla                            184     0x00b8
    +onesuperior                        185     0x00b9
    +masculine                          186     0x00ba
    +guillemotright                     187     0x00bb
    +onequarter                         188     0x00bc
    +onehalf                            189     0x00bd
    +threequarters                      190     0x00be
    +questiondown                       191     0x00bf
    +Agrave                             192     0x00c0
    +Aacute                             193     0x00c1
    +Acircumflex                        194     0x00c2
    +Atilde                             195     0x00c3
    +Adiaeresis                         196     0x00c4
    +Aring                              197     0x00c5
    +AE                                 198     0x00c6
    +Ccedilla                           199     0x00c7
    +Egrave                             200     0x00c8
    +Eacute                             201     0x00c9
    +Ecircumflex                        202     0x00ca
    +Ediaeresis                         203     0x00cb
    +Igrave                             204     0x00cc
    +Iacute                             205     0x00cd
    +Icircumflex                        206     0x00ce
    +Idiaeresis                         207     0x00cf
    +Eth                                208     0x00d0
    +Ntilde                             209     0x00d1
    +Ograve                             210     0x00d2
    +Oacute                             211     0x00d3
    +Ocircumflex                        212     0x00d4
    +Otilde                             213     0x00d5
    +Odiaeresis                         214     0x00d6
    +multiply                           215     0x00d7
    +Ooblique                           216     0x00d8
    +Ugrave                             217     0x00d9
    +Uacute                             218     0x00da
    +Ucircumflex                        219     0x00db
    +Udiaeresis                         220     0x00dc
    +Yacute                             221     0x00dd
    +Thorn                              222     0x00de
    +ssharp                             223     0x00df
    +agrave                             224     0x00e0
    +aacute                             225     0x00e1
    +acircumflex                        226     0x00e2
    +atilde                             227     0x00e3
    +adiaeresis                         228     0x00e4
    +aring                              229     0x00e5
    +ae                                 230     0x00e6
    +ccedilla                           231     0x00e7
    +egrave                             232     0x00e8
    +eacute                             233     0x00e9
    +ecircumflex                        234     0x00ea
    +ediaeresis                         235     0x00eb
    +igrave                             236     0x00ec
    +iacute                             237     0x00ed
    +icircumflex                        238     0x00ee
    +idiaeresis                         239     0x00ef
    +eth                                240     0x00f0
    +ntilde                             241     0x00f1
    +ograve                             242     0x00f2
    +oacute                             243     0x00f3
    +ocircumflex                        244     0x00f4
    +otilde                             245     0x00f5
    +odiaeresis                         246     0x00f6
    +division                           247     0x00f7
    +oslash                             248     0x00f8
    +ugrave                             249     0x00f9
    +uacute                             250     0x00fa
    +ucircumflex                        251     0x00fb
    +udiaeresis                         252     0x00fc
    +yacute                             253     0x00fd
    +thorn                              254     0x00fe
    +ydiaeresis                         255     0x00ff
    +Aogonek                            417     0x01a1
    +breve                              418     0x01a2
    +Lstroke                            419     0x01a3
    +Lcaron                             421     0x01a5
    +Sacute                             422     0x01a6
    +Scaron                             425     0x01a9
    +Scedilla                           426     0x01aa
    +Tcaron                             427     0x01ab
    +Zacute                             428     0x01ac
    +
    Zcaron                             430     0x01ae
    +Zabovedot                          431     0x01af
    +aogonek                            433     0x01b1
    +ogonek                             434     0x01b2
    +lstroke                            435     0x01b3
    +lcaron                             437     0x01b5
    +sacute                             438     0x01b6
    +caron                              439     0x01b7
    +scaron                             441     0x01b9
    +scedilla                           442     0x01ba
    +tcaron                             443     0x01bb
    +zacute                             444     0x01bc
    +doubleacute                        445     0x01bd
    +zcaron                             446     0x01be
    +zabovedot                          447     0x01bf
    +Racute                             448     0x01c0
    +Abreve                             451     0x01c3
    +Cacute                             454     0x01c6
    +Ccaron                             456     0x01c8
    +Eogonek                            458     0x01ca
    +Ecaron                             460     0x01cc
    +Dcaron                             463     0x01cf
    +Nacute                             465     0x01d1
    +Ncaron                             466     0x01d2
    +Odoubleacute                       469     0x01d5
    +Rcaron                             472     0x01d8
    +Uring                              473     0x01d9
    +Udoubleacute                       475     0x01db
    +Tcedilla                           478     0x01de
    +racute                             480     0x01e0
    +abreve                             483     0x01e3
    +cacute                             486     0x01e6
    +ccaron                             488     0x01e8
    +eogonek                            490     0x01ea
    +ecaron                             492     0x01ec
    +dcaron                             495     0x01ef
    +nacute                             497     0x01f1
    +ncaron                             498     0x01f2
    +odoubleacute                       501     0x01f5
    +rcaron                             504     0x01f8
    +uring                              505     0x01f9
    +udoubleacute                       507     0x01fb
    +tcedilla                           510     0x01fe
    +abovedot                           511     0x01ff
    +Hstroke                            673     0x02a1
    +Hcircumflex                        678     0x02a6
    +Iabovedot                          681     0x02a9
    +Gbreve                             683     0x02ab
    +Jcircumflex                        684     0x02ac
    +hstroke                            689     0x02b1
    +hcircumflex                        694     0x02b6
    +idotless                           697     0x02b9
    +gbreve                             699     0x02bb
    +jcircumflex                        700     0x02bc
    +Cabovedot                          709     0x02c5
    +Ccircumflex                        710     0x02c6
    +Gabovedot                          725     0x02d5
    +Gcircumflex                        728     0x02d8
    +Ubreve                             733     0x02dd
    +Scircumflex                        734     0x02de
    +cabovedot                          741     0x02e5
    +ccircumflex                        742     0x02e6
    +gabovedot                          757     0x02f5
    +gcircumflex                        760     0x02f8
    +ubreve                             765     0x02fd
    +scircumflex                        766     0x02fe
    +kappa                              930     0x03a2
    +Rcedilla                           931     0x03a3
    +Itilde                             933     0x03a5
    +Lcedilla                           934     0x03a6
    +Emacron                            938     0x03aa
    +Gcedilla                           939     0x03ab
    +Tslash                             940     0x03ac
    +rcedilla                           947     0x03b3
    +itilde                             949     0x03b5
    +lcedilla                           950     0x03b6
    +emacron                            954     0x03ba
    +gacute                             955     0x03bb
    +tslash                             956     0x03bc
    +ENG                                957     0x03bd
    +eng                                959     0x03bf
    +Amacron                            960     0x03c0
    +Iogonek                            967     0x03c7
    +Eabovedot                          972     0x03cc
    +Imacron                            975     0x03cf
    +Ncedilla                           977     0x03d1
    +Omacron                            978     0x03d2
    +Kcedilla                           979     0x03d3
    +Uogonek                            985     0x03d9
    +Utilde                             989     0x03dd
    +Umacron                            990     0x03de
    +amacron                            992     0x03e0
    +iogonek                            999     0x03e7
    +eabovedot                         1004     0x03ec
    +imacron                           1007     0x03ef
    +ncedilla                          1009     0x03f1
    +omacron                           1010     0x03f2
    +kcedilla                          1011     0x03f3
    +uogonek                           1017     0x03f9
    +utilde                            1021     0x03fd
    +umacron                           1022     0x03fe
    +overline                          1150     0x047e
    +kana_fullstop                     1185     0x04a1
    +kana_openingbracket               1186     0x04a2
    +kana_closingbracket               1187     0x04a3
    +kana_comma                        1188     0x04a4
    +kana_middledot                    1189     0x04a5
    +kana_WO                           1190     0x04a6
    +kana_a                            1191     0x04a7
    +kana_i                            1192     0x04a8
    +kana_u                            1193     0x04a9
    +kana_e                            1194     0x04aa
    +kana_o                            1195     0x04ab
    +kana_ya                           1196     0x04ac
    +kana_yu                           1197     0x04ad
    +kana_yo                           1198     0x04ae
    +kana_tu                           1199     0x04af
    +prolongedsound                    1200     0x04b0
    +kana_A                            1201     0x04b1
    +kana_I                            1202     0x04b2
    +kana_U                            1203     0x04b3
    +kana_E                            1204     0x04b4
    +kana_O                            1205     0x04b5
    +kana_KA                           1206     0x04b6
    +kana_KI                           1207     0x04b7
    +kana_KU                           1208     0x04b8
    +kana_KE                           1209     0x04b9
    +kana_KO                           1210     0x04ba
    +kana_SA                           1211     0x04bb
    +kana_SHI                          1212     0x04bc
    +kana_SU                           1213     0x04bd
    +kana_SE                           1214     0x04be
    +kana_SO                           1215     0x04bf
    +kana_TA                           1216     0x04c0
    +kana_TI                           1217     0x04c1
    +kana_TU                           1218     0x04c2
    +kana_TE                           1219     0x04c3
    +kana_TO                           1220     0x04c4
    +kana_NA                           1221     0x04c5
    +kana_NI                           1222     0x04c6
    +kana_NU                           1223     0x04c7
    +kana_NE                           1224     0x04c8
    +kana_NO                           1225     0x04c9
    +kana_HA                           1226     0x04ca
    +kana_HI                           1227     0x04cb
    +kana_HU                           1228     0x04cc
    +kana_HE                           1229     0x04cd
    +kana_HO                           1230     0x04ce
    +kana_MA                           1231     0x04cf
    +kana_MI                           1232     0x04d0
    +kana_MU                           1233     0x04d1
    +kana_ME                           1234     0x04d2
    +kana_MO                           1235     0x04d3
    +kana_YA                           1236     0x04d4
    +kana_YU                           1237     0x04d5
    +kana_YO                           1238     0x04d6
    +kana_RA                           1239     0x04d7
    +kana_RI                           1240     0x04d8
    +kana_RU                           1241     0x04d9
    +kana_RE                           1242     0x04da
    +kana_RO                           1243     0x04db
    +kana_WA                           1244     0x04dc
    +kana_N                            1245     0x04dd
    +voicedsound                       1246     0x04de
    +semivoicedsound                   1247     0x04df
    +Arabic_comma                      1452     0x05ac
    +Arabic_semicolon                  1467     0x05bb
    +Arabic_question_mark              1471     0x05bf
    +Arabic_hamza                      1473     0x05c1
    +Arabic_maddaonalef                1474     0x05c2
    +Arabic_hamzaonalef                1475     0x05c3
    +Arabic_hamzaonwaw                 1476     0x05c4
    +Arabic_hamzaunderalef             1477     0x05c5
    +Arabic_hamzaonyeh                 1478     0x05c6
    +Arabic_alef                       1479     0x05c7
    +Arabic_beh                        1480     0x05c8
    +Arabic_tehmarbuta                 1481     0x05c9
    +Arabic_teh                        1482     0x05ca
    +Arabic_theh                       1483     0x05cb
    +Arabic_jeem                       1484     0x05cc
    +Arabic_hah                        1485     0x05cd
    +Arabic_khah                       1486     0x05ce
    +Arabic_dal                        1487     0x05cf
    +Arabic_thal                       1488     0x05d0
    +Arabic_ra                         1489     0x05d1
    +Arabic_zain                       1490     0x05d2
    +Arabic_seen                       1491     0x05d3
    +Arabic_sheen                      1492     0x05d4
    +Arabic_sad                        1493     0x05d5
    +Arabic_dad                        1494     0x05d6
    +Arabic_tah                        1495     0x05d7
    +Arabic_zah                        1496     0x05d8
    +Arabic_ain                        1497     0x05d9
    +Arabic_ghain                      1498     0x05da
    +Arabic_tatweel                    1504     0x05e0
    +Arabic_feh                        1505     0x05e1
    +Arabic_qaf                        1506     0x05e2
    +Arabic_kaf                        1507     0x05e3
    +Arabic_lam                        1508     0x05e4
    +Arabic_meem                       1509     0x05e5
    +
    Arabic_noon                       1510     0x05e6
    +Arabic_heh                        1511     0x05e7
    +Arabic_waw                        1512     0x05e8
    +Arabic_alefmaksura                1513     0x05e9
    +Arabic_yeh                        1514     0x05ea
    +Arabic_fathatan                   1515     0x05eb
    +Arabic_dammatan                   1516     0x05ec
    +Arabic_kasratan                   1517     0x05ed
    +Arabic_fatha                      1518     0x05ee
    +Arabic_damma                      1519     0x05ef
    +Arabic_kasra                      1520     0x05f0
    +Arabic_shadda                     1521     0x05f1
    +Arabic_sukun                      1522     0x05f2
    +Serbian_dje                       1697     0x06a1
    +Macedonia_gje                     1698     0x06a2
    +Cyrillic_io                       1699     0x06a3
    +Ukranian_je                       1700     0x06a4
    +Macedonia_dse                     1701     0x06a5
    +Ukranian_i                        1702     0x06a6
    +Ukranian_yi                       1703     0x06a7
    +Serbian_je                        1704     0x06a8
    +Serbian_lje                       1705     0x06a9
    +Serbian_nje                       1706     0x06aa
    +Serbian_tshe                      1707     0x06ab
    +Macedonia_kje                     1708     0x06ac
    +Byelorussian_shortu               1710     0x06ae
    +Serbian_dze                       1711     0x06af
    +numerosign                        1712     0x06b0
    +Serbian_DJE                       1713     0x06b1
    +Macedonia_GJE                     1714     0x06b2
    +Cyrillic_IO                       1715     0x06b3
    +Ukranian_JE                       1716     0x06b4
    +Macedonia_DSE                     1717     0x06b5
    +Ukranian_I                        1718     0x06b6
    +Ukranian_YI                       1719     0x06b7
    +Serbian_JE                        1720     0x06b8
    +Serbian_LJE                       1721     0x06b9
    +Serbian_NJE                       1722     0x06ba
    +Serbian_TSHE                      1723     0x06bb
    +Macedonia_KJE                     1724     0x06bc
    +Byelorussian_SHORTU               1726     0x06be
    +Serbian_DZE                       1727     0x06bf
    +Cyrillic_yu                       1728     0x06c0
    +Cyrillic_a                        1729     0x06c1
    +Cyrillic_be                       1730     0x06c2
    +Cyrillic_tse                      1731     0x06c3
    +Cyrillic_de                       1732     0x06c4
    +Cyrillic_ie                       1733     0x06c5
    +Cyrillic_ef                       1734     0x06c6
    +Cyrillic_ghe                      1735     0x06c7
    +Cyrillic_ha                       1736     0x06c8
    +Cyrillic_i                        1737     0x06c9
    +Cyrillic_shorti                   1738     0x06ca
    +Cyrillic_ka                       1739     0x06cb
    +Cyrillic_el                       1740     0x06cc
    +Cyrillic_em                       1741     0x06cd
    +Cyrillic_en                       1742     0x06ce
    +Cyrillic_o                        1743     0x06cf
    +Cyrillic_pe                       1744     0x06d0
    +Cyrillic_ya                       1745     0x06d1
    +Cyrillic_er                       1746     0x06d2
    +Cyrillic_es                       1747     0x06d3
    +Cyrillic_te                       1748     0x06d4
    +Cyrillic_u                        1749     0x06d5
    +Cyrillic_zhe                      1750     0x06d6
    +Cyrillic_ve                       1751     0x06d7
    +Cyrillic_softsign                 1752     0x06d8
    +Cyrillic_yeru                     1753     0x06d9
    +Cyrillic_ze                       1754     0x06da
    +Cyrillic_sha                      1755     0x06db
    +Cyrillic_e                        1756     0x06dc
    +Cyrillic_shcha                    1757     0x06dd
    +Cyrillic_che                      1758     0x06de
    +Cyrillic_hardsign                 1759     0x06df
    +Cyrillic_YU                       1760     0x06e0
    +Cyrillic_A                        1761     0x06e1
    +Cyrillic_BE                       1762     0x06e2
    +Cyrillic_TSE                      1763     0x06e3
    +Cyrillic_DE                       1764     0x06e4
    +Cyrillic_IE                       1765     0x06e5
    +Cyrillic_EF                       1766     0x06e6
    +Cyrillic_GHE                      1767     0x06e7
    +Cyrillic_HA                       1768     0x06e8
    +Cyrillic_I                        1769     0x06e9
    +Cyrillic_SHORTI                   1770     0x06ea
    +Cyrillic_KA                       1771     0x06eb
    +Cyrillic_EL                       1772     0x06ec
    +Cyrillic_EM                       1773     0x06ed
    +Cyrillic_EN                       1774     0x06ee
    +Cyrillic_O                        1775     0x06ef
    +Cyrillic_PE                       1776     0x06f0
    +Cyrillic_YA                       1777     0x06f1
    +Cyrillic_ER                       1778     0x06f2
    +Cyrillic_ES                       1779     0x06f3
    +Cyrillic_TE                       1780     0x06f4
    +Cyrillic_U                        1781     0x06f5
    +Cyrillic_ZHE                      1782     0x06f6
    +Cyrillic_VE                       1783     0x06f7
    +Cyrillic_SOFTSIGN                 1784     0x06f8
    +Cyrillic_YERU                     1785     0x06f9
    +Cyrillic_ZE                       1786     0x06fa
    +Cyrillic_SHA                      1787     0x06fb
    +Cyrillic_E                        1788     0x06fc
    +Cyrillic_SHCHA                    1789     0x06fd
    +Cyrillic_CHE                      1790     0x06fe
    +Cyrillic_HARDSIGN                 1791     0x06ff
    +Greek_ALPHAaccent                 1953     0x07a1
    +Greek_EPSILONaccent               1954     0x07a2
    +Greek_ETAaccent                   1955     0x07a3
    +Greek_IOTAaccent                  1956     0x07a4
    +Greek_IOTAdiaeresis               1957     0x07a5
    +Greek_IOTAaccentdiaeresis         1958     0x07a6
    +Greek_OMICRONaccent               1959     0x07a7
    +Greek_UPSILONaccent               1960     0x07a8
    +Greek_UPSILONdieresis             1961     0x07a9
    +Greek_UPSILONaccentdieresis       1962     0x07aa
    +Greek_OMEGAaccent                 1963     0x07ab
    +Greek_alphaaccent                 1969     0x07b1
    +Greek_epsilonaccent               1970     0x07b2
    +Greek_etaaccent                   1971     0x07b3
    +Greek_iotaaccent                  1972     0x07b4
    +Greek_iotadieresis                1973     0x07b5
    +Greek_iotaaccentdieresis          1974     0x07b6
    +Greek_omicronaccent               1975     0x07b7
    +Greek_upsilonaccent               1976     0x07b8
    +Greek_upsilondieresis             1977     0x07b9
    +Greek_upsilonaccentdieresis       1978     0x07ba
    +Greek_omegaaccent                 1979     0x07bb
    +Greek_ALPHA                       1985     0x07c1
    +Greek_BETA                        1986     0x07c2
    +Greek_GAMMA                       1987     0x07c3
    +Greek_DELTA                       1988     0x07c4
    +Greek_EPSILON                     1989     0x07c5
    +Greek_ZETA                        1990     0x07c6
    +Greek_ETA                         1991     0x07c7
    +Greek_THETA                       1992     0x07c8
    +Greek_IOTA                        1993     0x07c9
    +Greek_KAPPA                       1994     0x07ca
    +Greek_LAMBDA                      1995     0x07cb
    +Greek_MU                          1996     0x07cc
    +Greek_NU                          1997     0x07cd
    +Greek_XI                          1998     0x07ce
    +Greek_OMICRON                     1999     0x07cf
    +Greek_PI                          2000     0x07d0
    +Greek_RHO                         2001     0x07d1
    +Greek_SIGMA                       2002     0x07d2
    +Greek_TAU                         2004     0x07d4
    +Greek_UPSILON                     2005     0x07d5
    +Greek_PHI                         2006     0x07d6
    +Greek_CHI                         2007     0x07d7
    +Greek_PSI                         2008     0x07d8
    +Greek_OMEGA                       2009     0x07d9
    +Greek_alpha                       2017     0x07e1
    +Greek_beta                        2018     0x07e2
    +Greek_gamma                       2019     0x07e3
    +Greek_delta                       2020     0x07e4
    +Greek_epsilon                     2021     0x07e5
    +Greek_zeta                        2022     0x07e6
    +Greek_eta                         2023     0x07e7
    +Greek_theta                       2024     0x07e8
    +Greek_iota                        2025     0x07e9
    +Greek_kappa                       2026     0x07ea
    +Greek_lambda                      2027     0x07eb
    +Greek_mu                          2028     0x07ec
    +Greek_nu                          2029     0x07ed
    +Greek_xi                          2030     0x07ee
    +Greek_omicron                     2031     0x07ef
    +Greek_pi                          2032     0x07f0
    +Greek_rho                         2033     0x07f1
    +Greek_sigma                       2034     0x07f2
    +Greek_finalsmallsigma             2035     0x07f3
    +Greek_tau                         2036     0x07f4
    +Greek_upsilon                     2037     0x07f5
    +Greek_phi                         2038     0x07f6
    +Greek_chi                         2039     0x07f7
    +Greek_psi                         2040     0x07f8
    +Greek_omega                       2041     0x07f9
    +leftradical                       2209     0x08a1
    +topleftradical                    2210     0x08a2
    +horizconnector                    2211     0x08a3
    +topintegral                       2212     0x08a4
    +botintegral                       2213     0x08a5
    +vertconnector                     2214     0x08a6
    +topleftsqbracket                  2215     0x08a7
    +botleftsqbracket                  2216     0x08a8
    +toprightsqbracket                 2217     0x08a9
    +botrightsqbracket                 2218     0x08aa
    +topleftparens                     2219     0x08ab
    +botleftparens                     2220     0x08ac
    +toprightparens                    2221     0x08ad
    +botrightparens                    2222     0x08ae
    +leftmiddlecurlybrace              2223     0x08af
    +rightmiddlecurlybrace             2224     0x08b0
    +topleftsummation                  2225     0x08b1
    +botleftsummation                  2226     0x08b2
    +topvertsummationconnector         2227     0x08b3
    +botvertsummationconnector         2228     0x08b4
    +toprightsummation                 2229     0x08b5
    +botrightsummation                 2230     0x08b6
    +rightmiddlesummation              2231     0x08b7
    +
    lessthanequal                     2236     0x08bc
    +notequal                          2237     0x08bd
    +greaterthanequal                  2238     0x08be
    +integral                          2239     0x08bf
    +therefore                         2240     0x08c0
    +variation                         2241     0x08c1
    +infinity                          2242     0x08c2
    +nabla                             2245     0x08c5
    +approximate                       2248     0x08c8
    +similarequal                      2249     0x08c9
    +ifonlyif                          2253     0x08cd
    +implies                           2254     0x08ce
    +identical                         2255     0x08cf
    +radical                           2262     0x08d6
    +includedin                        2266     0x08da
    +includes                          2267     0x08db
    +intersection                      2268     0x08dc
    +union                             2269     0x08dd
    +logicaland                        2270     0x08de
    +logicalor                         2271     0x08df
    +partialderivative                 2287     0x08ef
    +function                          2294     0x08f6
    +leftarrow                         2299     0x08fb
    +uparrow                           2300     0x08fc
    +rightarrow                        2301     0x08fd
    +downarrow                         2302     0x08fe
    +blank                             2527     0x09df
    +soliddiamond                      2528     0x09e0
    +checkerboard                      2529     0x09e1
    +ht                                2530     0x09e2
    +ff                                2531     0x09e3
    +cr                                2532     0x09e4
    +lf                                2533     0x09e5
    +nl                                2536     0x09e8
    +vt                                2537     0x09e9
    +lowrightcorner                    2538     0x09ea
    +uprightcorner                     2539     0x09eb
    +upleftcorner                      2540     0x09ec
    +lowleftcorner                     2541     0x09ed
    +crossinglines                     2542     0x09ee
    +horizlinescan1                    2543     0x09ef
    +horizlinescan3                    2544     0x09f0
    +horizlinescan5                    2545     0x09f1
    +horizlinescan7                    2546     0x09f2
    +horizlinescan9                    2547     0x09f3
    +leftt                             2548     0x09f4
    +rightt                            2549     0x09f5
    +bott                              2550     0x09f6
    +topt                              2551     0x09f7
    +vertbar                           2552     0x09f8
    +emspace                           2721     0x0aa1
    +enspace                           2722     0x0aa2
    +em3space                          2723     0x0aa3
    +em4space                          2724     0x0aa4
    +digitspace                        2725     0x0aa5
    +punctspace                        2726     0x0aa6
    +thinspace                         2727     0x0aa7
    +hairspace                         2728     0x0aa8
    +emdash                            2729     0x0aa9
    +endash                            2730     0x0aaa
    +signifblank                       2732     0x0aac
    +ellipsis                          2734     0x0aae
    +doubbaselinedot                   2735     0x0aaf
    +onethird                          2736     0x0ab0
    +twothirds                         2737     0x0ab1
    +onefifth                          2738     0x0ab2
    +twofifths                         2739     0x0ab3
    +threefifths                       2740     0x0ab4
    +fourfifths                        2741     0x0ab5
    +onesixth                          2742     0x0ab6
    +fivesixths                        2743     0x0ab7
    +careof                            2744     0x0ab8
    +figdash                           2747     0x0abb
    +leftanglebracket                  2748     0x0abc
    +decimalpoint                      2749     0x0abd
    +rightanglebracket                 2750     0x0abe
    +marker                            2751     0x0abf
    +oneeighth                         2755     0x0ac3
    +threeeighths                      2756     0x0ac4
    +fiveeighths                       2757     0x0ac5
    +seveneighths                      2758     0x0ac6
    +trademark                         2761     0x0ac9
    +signaturemark                     2762     0x0aca
    +trademarkincircle                 2763     0x0acb
    +leftopentriangle                  2764     0x0acc
    +rightopentriangle                 2765     0x0acd
    +emopencircle                      2766     0x0ace
    +emopenrectangle                   2767     0x0acf
    +leftsinglequotemark               2768     0x0ad0
    +rightsinglequotemark              2769     0x0ad1
    +leftdoublequotemark               2770     0x0ad2
    +rightdoublequotemark              2771     0x0ad3
    +prescription                      2772     0x0ad4
    +minutes                           2774     0x0ad6
    +seconds                           2775     0x0ad7
    +latincross                        2777     0x0ad9
    +hexagram                          2778     0x0ada
    +filledrectbullet                  2779     0x0adb
    +filledlefttribullet               2780     0x0adc
    +filledrighttribullet              2781     0x0add
    +emfilledcircle                    2782     0x0ade
    +emfilledrect                      2783     0x0adf
    +enopencircbullet                  2784     0x0ae0
    +enopensquarebullet                2785     0x0ae1
    +openrectbullet                    2786     0x0ae2
    +opentribulletup                   2787     0x0ae3
    +opentribulletdown                 2788     0x0ae4
    +openstar                          2789     0x0ae5
    +enfilledcircbullet                2790     0x0ae6
    +enfilledsqbullet                  2791     0x0ae7
    +filledtribulletup                 2792     0x0ae8
    +filledtribulletdown               2793     0x0ae9
    +leftpointer                       2794     0x0aea
    +rightpointer                      2795     0x0aeb
    +club                              2796     0x0aec
    +diamond                           2797     0x0aed
    +heart                             2798     0x0aee
    +maltesecross                      2800     0x0af0
    +dagger                            2801     0x0af1
    +doubledagger                      2802     0x0af2
    +checkmark                         2803     0x0af3
    +ballotcross                       2804     0x0af4
    +musicalsharp                      2805     0x0af5
    +musicalflat                       2806     0x0af6
    +malesymbol                        2807     0x0af7
    +femalesymbol                      2808     0x0af8
    +telephone                         2809     0x0af9
    +telephonerecorder                 2810     0x0afa
    +phonographcopyright               2811     0x0afb
    +caret                             2812     0x0afc
    +singlelowquotemark                2813     0x0afd
    +doublelowquotemark                2814     0x0afe
    +cursor                            2815     0x0aff
    +leftcaret                         2979     0x0ba3
    +rightcaret                        2982     0x0ba6
    +downcaret                         2984     0x0ba8
    +upcaret                           2985     0x0ba9
    +overbar                           3008     0x0bc0
    +downtack                          3010     0x0bc2
    +upshoe                            3011     0x0bc3
    +downstile                         3012     0x0bc4
    +underbar                          3014     0x0bc6
    +jot                               3018     0x0bca
    +quad                              3020     0x0bcc
    +uptack                            3022     0x0bce
    +circle                            3023     0x0bcf
    +upstile                           3027     0x0bd3
    +downshoe                          3030     0x0bd6
    +rightshoe                         3032     0x0bd8
    +leftshoe                          3034     0x0bda
    +lefttack                          3036     0x0bdc
    +righttack                         3068     0x0bfc
    +hebrew_aleph                      3296     0x0ce0
    +hebrew_beth                       3297     0x0ce1
    +hebrew_gimmel                     3298     0x0ce2
    +hebrew_daleth                     3299     0x0ce3
    +hebrew_he                         3300     0x0ce4
    +hebrew_waw                        3301     0x0ce5
    +hebrew_zayin                      3302     0x0ce6
    +hebrew_het                        3303     0x0ce7
    +hebrew_teth                       3304     0x0ce8
    +hebrew_yod                        3305     0x0ce9
    +hebrew_finalkaph                  3306     0x0cea
    +hebrew_kaph                       3307     0x0ceb
    +hebrew_lamed                      3308     0x0cec
    +hebrew_finalmem                   3309     0x0ced
    +hebrew_mem                        3310     0x0cee
    +hebrew_finalnun                   3311     0x0cef
    +hebrew_nun                        3312     0x0cf0
    +hebrew_samekh                     3313     0x0cf1
    +hebrew_ayin                       3314     0x0cf2
    +hebrew_finalpe                    3315     0x0cf3
    +hebrew_pe                         3316     0x0cf4
    +hebrew_finalzadi                  3317     0x0cf5
    +hebrew_zadi                       3318     0x0cf6
    +hebrew_kuf                        3319     0x0cf7
    +hebrew_resh                       3320     0x0cf8
    +hebrew_shin                       3321     0x0cf9
    +hebrew_taf                        3322     0x0cfa
    +BackSpace                        65288     0xff08
    +Tab                              65289     0xff09
    +Linefeed                         65290     0xff0a
    +Clear                            65291     0xff0b
    +Return                           65293     0xff0d
    +Pause                            65299     0xff13
    +Scroll_Lock                      65300     0xff14
    +Sys_Req                          65301     0xff15
    +Escape                           65307     0xff1b
    +Multi_key                        65312     0xff20
    +Kanji                            65313     0xff21
    +Home                             65360     0xff50
    +Left                             65361     0xff51
    +Up                               65362     0xff52
    +Right                            65363     0xff53
    +Down                             65364     0xff54
    +Prior                            65365     0xff55
    +Next                             65366     0xff56
    +End                              65367     0xff57
    +Begin                            65368     0xff58
    +Win_L                            65371     0xff5b
    +Win_R                            65372     0xff5c
    +
    App                              65373     0xff5d
    +Select                           65376     0xff60
    +Print                            65377     0xff61
    +Execute                          65378     0xff62
    +Insert                           65379     0xff63
    +Undo                             65381     0xff65
    +Redo                             65382     0xff66
    +Menu                             65383     0xff67
    +Find                             65384     0xff68
    +Cancel                           65385     0xff69
    +Help                             65386     0xff6a
    +Break                            65387     0xff6b
    +Hebrew_switch                    65406     0xff7e
    +Num_Lock                         65407     0xff7f
    +KP_Space                         65408     0xff80
    +KP_Tab                           65417     0xff89
    +KP_Enter                         65421     0xff8d
    +KP_F1                            65425     0xff91
    +KP_F2                            65426     0xff92
    +KP_F3                            65427     0xff93
    +KP_F4                            65428     0xff94
    +KP_Multiply                      65450     0xffaa
    +KP_Add                           65451     0xffab
    +KP_Separator                     65452     0xffac
    +KP_Subtract                      65453     0xffad
    +KP_Decimal                       65454     0xffae
    +KP_Divide                        65455     0xffaf
    +KP_0                             65456     0xffb0
    +KP_1                             65457     0xffb1
    +KP_2                             65458     0xffb2
    +KP_3                             65459     0xffb3
    +KP_4                             65460     0xffb4
    +KP_5                             65461     0xffb5
    +KP_6                             65462     0xffb6
    +KP_7                             65463     0xffb7
    +KP_8                             65464     0xffb8
    +KP_9                             65465     0xffb9
    +KP_Equal                         65469     0xffbd
    +F1                               65470     0xffbe
    +F2                               65471     0xffbf
    +F3                               65472     0xffc0
    +F4                               65473     0xffc1
    +F5                               65474     0xffc2
    +F6                               65475     0xffc3
    +F7                               65476     0xffc4
    +F8                               65477     0xffc5
    +F9                               65478     0xffc6
    +F10                              65479     0xffc7
    +L1                               65480     0xffc8
    +L2                               65481     0xffc9
    +L3                               65482     0xffca
    +L4                               65483     0xffcb
    +L5                               65484     0xffcc
    +L6                               65485     0xffcd
    +L7                               65486     0xffce
    +L8                               65487     0xffcf
    +L9                               65488     0xffd0
    +L10                              65489     0xffd1
    +R1                               65490     0xffd2
    +R2                               65491     0xffd3
    +R3                               65492     0xffd4
    +R4                               65493     0xffd5
    +R5                               65494     0xffd6
    +R6                               65495     0xffd7
    +R7                               65496     0xffd8
    +R8                               65497     0xffd9
    +R9                               65498     0xffda
    +R10                              65499     0xffdb
    +R11                              65500     0xffdc
    +R12                              65501     0xffdd
    +F33                              65502     0xffde
    +R14                              65503     0xffdf
    +R15                              65504     0xffe0
    +Shift_L                          65505     0xffe1
    +Shift_R                          65506     0xffe2
    +Control_L                        65507     0xffe3
    +Control_R                        65508     0xffe4
    +Caps_Lock                        65509     0xffe5
    +Shift_Lock                       65510     0xffe6
    +Meta_L                           65511     0xffe7
    +Meta_R                           65512     0xffe8
    +Alt_L                            65513     0xffe9
    +Alt_R                            65514     0xffea
    +Super_L                          65515     0xffeb
    +Super_R                          65516     0xffec
    +Hyper_L                          65517     0xffed
    +Hyper_R                          65518     0xffee
    +Delete                           65535     0xffff
    +

    SEE ALSO

    +bind +

    KEYWORDS

    +keysym, bind, binding +
    +Copyright © 1998-2000 by Scriptics Corporation.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/label.htm b/hlp/en/tk/label.htm new file mode 100644 index 0000000..20dba4a --- /dev/null +++ b/hlp/en/tk/label.htm @@ -0,0 +1,143 @@ +Tk Built-In Commands - label manual page +
    +
    NAME +
    label - Create and manipulate label widgets
    +
    SYNOPSIS +
    +
    label pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground -activeforeground -anchor +
    -background -bitmap -borderwidth +
    -cursor -disabledforeground -font +
    -foreground -highlightbackground -highlightcolor +
    -highlightthickness -image -justify +
    -padx -pady -relief +
    -takefocus -text -textvariable +
    -underline -wraplength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -height, height, Height +
    -state, state, State +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    BINDINGS +
    KEYWORDS +

    +

    NAME

    +label - Create and manipulate label widgets +

    SYNOPSIS

    +labelpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground -activeforeground -anchor +
    -background -bitmap -borderwidth +
    -cursor -disabledforeground -font +
    -foreground -highlightbackground -highlightcolor +
    -highlightthickness -image -justify +
    -padx -pady -relief +
    -takefocus -text -textvariable +
    -underline -wraplength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the label's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the label: normal, active, +or disabled. In normal state the button is displayed using the +foreground and background options. In active state +the label is displayed using the activeForeground and +activeBackground options. In the disabled state the +disabledForeground and background options determine how +the button is displayed. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the label's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    DESCRIPTION

    +The label command creates a new window (given by the +pathName argument) and makes it into a label widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the label such as its colors, font, +text, and initial relief. The label command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A label is a widget that displays a textual string, bitmap or image. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. +The label can be manipulated in a few simple ways, such as +changing its relief or text, using the commands described below. + +

    WIDGET COMMAND

    +The label command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for label widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the label +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the label +command. + +

    +

    BINDINGS

    +When a new label is created, it has no default event bindings: +labels are not intended to be interactive. + +

    KEYWORDS

    +label, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/listbox.htm b/hlp/en/tk/listbox.htm new file mode 100644 index 0000000..3fb76c0 --- /dev/null +++ b/hlp/en/tk/listbox.htm @@ -0,0 +1,611 @@ +Tk Built-In Commands - listbox manual page +
    +
    NAME +
    listbox - Create and manipulate listbox widgets
    +
    SYNOPSIS +
    +
    listbox pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -height +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -listvar +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -width +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -height, height, Height +
    -listvar, listVariable, Variable +
    -selectmode, selectMode, SelectMode +
    -width, width, Width +
    +
    DESCRIPTION +
    INDICES +
    +
    number +
    active +
    anchor +
    end +
    @x,y +
    +
    WIDGET COMMAND +
    +
    pathName activate index +
    pathName bbox index +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName curselection +
    pathName delete first ?last? +
    pathName get first ?last? +
    pathName index index +
    pathName insert index ?element element ...? +
    pathName itemcget index option +
    pathName itemconfigure index ?option? ?value? ?option value ...? +
    +
    -background color +
    -foreground color +
    -selectbackground color +
    -selectforeground color +
    +
    pathName nearest y +
    pathName scan option args +
    +
    pathName scan mark x y +
    pathName scan dragto x y. +
    +
    pathName see index +
    pathName selection option arg +
    +
    pathName selection anchor index +
    pathName selection clear first ?last? +
    pathName selection includes index +
    pathName selection set first ?last? +
    +
    pathName size +
    pathName xview args +
    +
    pathName xview +
    pathName xview index +
    pathName xview moveto fraction +
    pathName xview scroll number what +
    +
    pathName yview ?args? +
    +
    pathName yview +
    pathName yview index +
    pathName yview moveto fraction +
    pathName yview scroll number what +
    +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +listbox - Create and manipulate listbox widgets +

    SYNOPSIS

    +listboxpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -height +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -listvar +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -width +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies the desired height for the window, in lines. +If zero or less, then the desired height for the window is made just +large enough to hold all the elements in the listbox. +

    Command-Line Name: -listvar +
    Database Name: listVariable +
    Database Class: Variable +
    Specifies the name of a variable. The value of the variable is a list +to be displayed inside the widget; if the variable value changes +then the widget will automatically update itself to reflect the new value. +Attempts to assign a bad list value to a variable in use as a listvar +will cause an error. Attempts to unset a variable in use as a listvar +will fail but will not generate an error. +

    Command-Line Name: -selectmode +
    Database Name: selectMode +
    Database Class: SelectMode +
    Specifies one of several styles for manipulating the selection. +The value of the option may be arbitrary, but the default bindings +expect it to be either single, browse, multiple, +or extended; the default value is browse. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired width for the window in characters. +If the font doesn't have a uniform width then the width of the +character ``0'' is used in translating from character units to +screen units. +If zero or less, then the desired width for the window is made just +large enough to hold all the elements in the listbox. +
    +

    DESCRIPTION

    +The listbox command creates a new window (given by the +pathName argument) and makes it into a listbox widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the listbox such as its colors, font, +text, and relief. The listbox command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A listbox is a widget that displays a list of strings, one per line. +When first created, a new listbox has no elements. +Elements may be added or deleted using widget commands described +below. In addition, one or more elements may be selected as described +below. +If a listbox is exporting its selection (see exportSelection +option), then it will observe the standard X11 protocols +for handling the selection. +Listbox selections are available as type STRING; +the value of the selection will be the text of the selected elements, with +newlines separating the elements. +

    +It is not necessary for all the elements to be +displayed in the listbox window at once; commands described below +may be used to change the view in the window. Listboxes allow +scrolling in both directions using the standard xScrollCommand +and yScrollCommand options. +They also support scanning, as described below. + +

    INDICES

    +Many of the widget commands for listboxes take one or more indices +as arguments. +An index specifies a particular element of the listbox, in any of +the following ways: +

    +

    +

    number
    +Specifies the element as a numerical index, where 0 corresponds +to the first element in the listbox. +

    active
    +Indicates the element that has the location cursor. This element +will be displayed with an underline when the listbox has the +keyboard focus, and it is specified with the activate +widget command. +

    anchor
    +Indicates the anchor point for the selection, which is set with the +selection anchor widget command. +

    end
    +Indicates the end of the listbox. +For most commands this refers to the last element in the listbox, +but for a few commands such as index and insert +it refers to the element just after the last one. +

    @x,y
    +Indicates the element that covers the point in the listbox window +specified by x and y (in pixel coordinates). If no +element covers that point, then the closest element to that +point is used. +

    +

    +In the widget command descriptions below, arguments named index, +first, and last always contain text indices in one of +the above forms. + +

    WIDGET COMMAND

    +The listbox command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for listbox widgets: +

    +

    +

    pathName activate index
    +Sets the active element to the one indicated by index. +If index is outside the range of elements in the listbox +then the closest element is activated. +The active element is drawn with an underline when the widget +has the input focus, and its index may be retrieved with the +index active. +

    pathName bbox index
    +Returns a list of four numbers describing the bounding box of +the text in the element given by index. +The first two elements of the list give the x and y coordinates +of the upper-left corner of the screen area covered by the text +(specified in pixels relative to the widget) and the last two +elements give the width and height of the area, in pixels. +If no part of the element given by index is visible on the +screen, +or if index refers to a non-existent element, +then the result is an empty string; if the element is +partially visible, the result gives the full area of the element, +including any parts that are not visible. +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the listbox +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the listbox +command. +

    pathName curselection
    +Returns a list containing the numerical indices of +all of the elements in the listbox that are currently selected. +If there are no elements selected in the listbox then an empty +string is returned. +

    pathName delete first ?last?
    +Deletes one or more elements of the listbox. First and last +are indices specifying the first and last elements in the range +to delete. If last isn't specified it defaults to +first, i.e. a single element is deleted. +

    pathName get first ?last?
    +If last is omitted, returns the contents of the listbox +element indicated by first, +or an empty string if first refers to a non-existent element. +If last is specified, the command returns a list whose elements +are all of the listbox elements between first and last, +inclusive. +Both first and last may have any of the standard +forms for indices. +

    pathName index index
    +Returns the integer index value that corresponds to index. +If index is end the return value is a count of the number +of elements in the listbox (not the index of the last element). +

    pathName insert index ?element element ...?
    +Inserts zero or more new elements in the list just before the +element given by index. If index is specified as +end then the new elements are added to the end of the +list. Returns an empty string. +

    pathName itemcget index option
    +Returns the current value of the item configuration option given +by option. Option may have any of the values accepted +by the listbox itemconfigure command. +

    pathName itemconfigure index ?option? ?value? ?option value ...?
    +Query or modify the configuration options of an item in the listbox. +If no option is specified, returns a list describing all of +the available options for the item (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. The following options +are currently supported for items: +

    +

    +

    -background color
    +Color specifies the background color to use when displaying the +item. It may have any of the forms accepted by Tk_GetColor. +

    -foreground color
    +Color specifies the foreground color to use when displaying the +item. It may have any of the forms accepted by Tk_GetColor. +

    -selectbackground color
    +color specifies the background color to use when displaying the +item while it is selected. It may have any of the forms accepted by +Tk_GetColor. +

    -selectforeground color
    +color specifies the foreground color to use when displaying the +item while it is selected. It may have any of the forms accepted by +Tk_GetColor. +

    +

    pathName nearest y
    +Given a y-coordinate within the listbox window, this command returns +the index of the (visible) listbox element nearest to that y-coordinate. +

    pathName scan option args
    +This command is used to implement scanning on listboxes. It has +two forms, depending on option: +

    +

    +

    pathName scan mark x y
    +Records x and y and the current view in the listbox +window; used in conjunction with later scan dragto commands. +Typically this command is associated with a mouse button press in +the widget. It returns an empty string. +

    pathName scan dragto x y.
    +This command computes the difference between its x and y +arguments and the x and y arguments to the last +scan mark command for the widget. +It then adjusts the view by 10 times the +difference in coordinates. This command is typically associated +with mouse motion events in the widget, to produce the effect of +dragging the list at high speed through the window. The return +value is an empty string. +

    +

    pathName see index
    +Adjust the view in the listbox so that the element given by index +is visible. +If the element is already visible then the command has no effect; +if the element is near one edge of the window then the listbox +scrolls to bring the element into view at the edge; otherwise +the listbox scrolls to center the element. +

    pathName selection option arg
    +This command is used to adjust the selection within a listbox. It +has several forms, depending on option: +

    +

    +

    pathName selection anchor index
    +Sets the selection anchor to the element given by index. +If index refers to a non-existent element, then the closest +element is used. +The selection anchor is the end of the selection that is fixed +while dragging out a selection with the mouse. +The index anchor may be used to refer to the anchor +element. +

    pathName selection clear first ?last?
    +If any of the elements between first and last +(inclusive) are selected, they are deselected. +The selection state is not changed for elements outside +this range. +

    pathName selection includes index
    +Returns 1 if the element indicated by index is currently +selected, 0 if it isn't. +

    pathName selection set first ?last?
    +Selects all of the elements in the range between +first and last, inclusive, without affecting +the selection state of elements outside that range. +

    +

    pathName size
    +Returns a decimal string indicating the total number of elements +in the listbox. +

    pathName xview args
    +This command is used to query and change the horizontal position of the +information in the widget's window. It can take any of the following +forms: +

    +

    +

    pathName xview
    +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the horizontal span that is visible in the window. +For example, if the first element is .2 and the second element is .6, +20% of the listbox's text is off-screen to the left, the middle 40% is visible +in the window, and 40% of the text is off-screen to the right. +These are the same values passed to scrollbars via the -xscrollcommand +option. +

    pathName xview index
    +Adjusts the view in the window so that the character position given by +index is displayed at the left edge of the window. +Character positions are defined by the width of the character 0. +

    pathName xview moveto fraction
    +Adjusts the view in the window so that fraction of the +total width of the listbox text is off-screen to the left. +fraction must be a fraction between 0 and 1. +

    pathName xview scroll number what
    +This command shifts the view in the window left or right according to +number and what. +Number must be an integer. +What must be either units or pages or an abbreviation +of one of these. +If what is units, the view adjusts left or right by +number character units (the width of the 0 character) +on the display; if it is pages then the view adjusts by +number screenfuls. +If number is negative then characters farther to the left +become visible; if it is positive then characters farther to the right +become visible. +

    +

    pathName yview ?args?
    +This command is used to query and change the vertical position of the +text in the widget's window. +It can take any of the following forms: +

    +

    +

    pathName yview
    +Returns a list containing two elements, both of which are real fractions +between 0 and 1. +The first element gives the position of the listbox element at the +top of the window, relative to the listbox as a whole (0.5 means +it is halfway through the listbox, for example). +The second element gives the position of the listbox element just after +the last one in the window, relative to the listbox as a whole. +These are the same values passed to scrollbars via the -yscrollcommand +option. +

    pathName yview index
    +Adjusts the view in the window so that the element given by +index is displayed at the top of the window. +

    pathName yview moveto fraction
    +Adjusts the view in the window so that the element given by fraction +appears at the top of the window. +Fraction is a fraction between 0 and 1; 0 indicates the first +element in the listbox, 0.33 indicates the element one-third the +way through the listbox, and so on. +

    pathName yview scroll number what
    +This command adjusts the view in the window up or down according to +number and what. +Number must be an integer. +What must be either units or pages. +If what is units, the view adjusts up or down by +number lines; if it is pages then +the view adjusts by number screenfuls. +If number is negative then earlier elements +become visible; if it is positive then later elements +become visible. +

    +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for listboxes that give them +Motif-like behavior. Much of the behavior of a listbox is determined +by its selectMode option, which selects one of four ways +of dealing with the selection. +

    +If the selection mode is single or browse, at most one +element can be selected in the listbox at once. +In both modes, clicking button 1 on an element selects +it and deselects any other selected item. +In browse mode it is also possible to drag the selection +with button 1. +

    +If the selection mode is multiple or extended, +any number of elements may be selected at once, including discontiguous +ranges. In multiple mode, clicking button 1 on an element +toggles its selection state without affecting any other elements. +In extended mode, pressing button 1 on an element selects +it, deselects everything else, and sets the anchor to the element +under the mouse; dragging the mouse with button 1 +down extends the selection to include all the elements between +the anchor and the element under the mouse, inclusive. +

    +Most people will probably want to use browse mode for +single selections and extended mode for multiple selections; +the other modes appear to be useful only in special situations. +

    +Any time the selection changes in the listbox, the virtual event +<<ListboxSelect>> will be generated. It is easiest to bind +to this event to be made aware of any changes to listbox selection. +

    +In addition to the above behavior, the following additional behavior +is defined by the default bindings: +

    +

    +

    [1]
    +In extended mode, the selected range can be adjusted by pressing +button 1 with the Shift key down: this modifies the selection to +consist of the elements between the anchor and the element under +the mouse, inclusive. +The un-anchored end of this new selection can also be dragged with +the button down. +

    [2]
    +In extended mode, pressing button 1 with the Control key down +starts a toggle operation: the anchor is set to the element under +the mouse, and its selection state is reversed. The selection state +of other elements isn't changed. +If the mouse is dragged with button 1 down, then the selection state +of all elements between the anchor and the element under the mouse +is set to match that of the anchor element; the selection state of +all other elements remains what it was before the toggle operation +began. +

    [3]
    +If the mouse leaves the listbox window with button 1 down, the window +scrolls away from the mouse, making information visible that used +to be off-screen on the side of the mouse. +The scrolling continues until the mouse re-enters the window, the +button is released, or the end of the listbox is reached. +

    [4]
    +Mouse button 2 may be used for scanning. +If it is pressed and dragged over the listbox, the contents of +the listbox drag at high speed in the direction the mouse moves. +

    [5]
    +If the Up or Down key is pressed, the location cursor (active +element) moves up or down one element. +If the selection mode is browse or extended then the +new active element is also selected and all other elements are +deselected. +In extended mode the new active element becomes the +selection anchor. +

    [6]
    +In extended mode, Shift-Up and Shift-Down move the location +cursor (active element) up or down one element and also extend +the selection to that element in a fashion similar to dragging +with mouse button 1. +

    [7]
    +The Left and Right keys scroll the listbox view left and right +by the width of the character 0. +Control-Left and Control-Right scroll the listbox view left and +right by the width of the window. +Control-Prior and Control-Next also scroll left and right by +the width of the window. +

    [8]
    +The Prior and Next keys scroll the listbox view up and down +by one page (the height of the window). +

    [9]
    +The Home and End keys scroll the listbox horizontally to +the left and right edges, respectively. +

    [10]
    +Control-Home sets the location cursor to the the first element in +the listbox, selects that element, and deselects everything else +in the listbox. +

    [11]
    +Control-End sets the location cursor to the the last element in +the listbox, selects that element, and deselects everything else +in the listbox. +

    [12]
    +In extended mode, Control-Shift-Home extends the selection +to the first element in the listbox and Control-Shift-End extends +the selection to the last element. +

    [13]
    +In multiple mode, Control-Shift-Home moves the location cursor +to the first element in the listbox and Control-Shift-End moves +the location cursor to the last element. +

    [14]
    +The space and Select keys make a selection at the location cursor +(active element) just as if mouse button 1 had been pressed over +this element. +

    [15]
    +In extended mode, Control-Shift-space and Shift-Select +extend the selection to the active element just as if button 1 +had been pressed with the Shift key down. +

    [16]
    +In extended mode, the Escape key cancels the most recent +selection and restores all the elements in the selected range +to their previous selection state. +

    [17]
    +Control-slash selects everything in the widget, except in +single and browse modes, in which case it selects +the active element and deselects everything else. +

    [18]
    +Control-backslash deselects everything in the widget, except in +browse mode where it has no effect. +

    [19]
    +The F16 key (labelled Copy on many Sun workstations) or Meta-w +copies the selection in the widget to the clipboard, if there is +a selection. + +

    +

    +The behavior of listboxes can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +listbox, widget +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/loadTk.htm b/hlp/en/tk/loadTk.htm new file mode 100644 index 0000000..3770a9d --- /dev/null +++ b/hlp/en/tk/loadTk.htm @@ -0,0 +1,65 @@ +Tk Tk Built-In Commands - Safe manual page +

    NAME

    +loadTk - Load Tk into a safe interpreter. +

    SYNOPSIS

    +::safe::loadTk slave ?-usewindowId? ?-displaydisplayName?
    +Safe Tk is based on Safe Tcl, which provides a mechanism +that allows restricted and mediated +access to auto-loading and packages for safe interpreters. +Safe Tk adds the ability to configure the interpreter +for safe Tk operations and load Tk into safe +interpreters. + +

    DESCRIPTION

    +The ::safe::loadTk command initializes the required data structures +in the named safe interpreter and then loads Tk into it. +The command returns the name of the safe interpreter. +If -use is specified, the window identified by the specified system +dependent identifier windowId is used to contain the ``.'' +window of the safe interpreter; it can be any valid id, eventually +referencing a window belonging to another application. As a convenience, +if the window you plan to use is a Tk Window of the application you +can use the window name (eg: .x.y) instead of its window Id +([winfo id .x.y]). +When -use is not specified, +a new toplevel window is created for the ``.'' window of +the safe interpreter. On X11 if you want the embedded window +to use another display than the default one, specify it with +-display. +See the SECURITY ISSUES section below for implementation details. + +

    SECURITY ISSUES

    +Please read the safe manual page for Tcl to learn about the basic +security considerations for Safe Tcl. +

    +::safe::loadTk adds the value of tk_library taken from the master +interpreter to the virtual access path of the safe interpreter so that +auto-loading will work in the safe interpreter. +

    +

    +Tk initialization is now safe with respect to not trusting +the slave's state for startup. ::safe::loadTk +registers the slave's name so +when the Tk initialization (Tk_SafeInit) is called +and in turn calls the master's ::safe::InitTk it will +return the desired argv equivalent (-use +windowId, correct -display, etc...). +

    +When -use is not used, the new toplevel created is specially +decorated so the user is always aware that the user interface presented comes +from a potentially unsafe code and can easily delete the corresponding +interpreter. +

    +On X11, conflicting -use and -display are likely +to generate a fatal X error. + +

    SEE ALSO

    +safe, interp, library, load, package, source, unknown +

    KEYWORDS

    +alias, auto-loading, auto_mkindex, load, master interpreter, safe +interpreter, slave interpreter, source +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/lower.htm b/hlp/en/tk/lower.htm new file mode 100644 index 0000000..24df3ea --- /dev/null +++ b/hlp/en/tk/lower.htm @@ -0,0 +1,27 @@ +Tk Built-In Commands - lower manual page +

    NAME

    +lower - Change a window's position in the stacking order +

    SYNOPSIS

    +lower window ?belowThis?
    +

    DESCRIPTION

    +If the belowThis argument is omitted then the command lowers +window so that it is below all of its siblings in the stacking +order (it will be obscured by any siblings that overlap it and +will not obscure any siblings). +If belowThis is specified then it must be the path name of +a window that is either a sibling of window or the descendant +of a sibling of window. +In this case the lower command will insert +window into the stacking order just below belowThis +(or the ancestor of belowThis that is a sibling of window); +this could end up either raising or lowering window. + +

    SEE ALSO

    +raise +

    KEYWORDS

    +lower, obscure, stacking order +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/menu.htm b/hlp/en/tk/menu.htm new file mode 100644 index 0000000..f5b2a67 --- /dev/null +++ b/hlp/en/tk/menu.htm @@ -0,0 +1,798 @@ +Tk Built-In Commands - menu manual page +
    +
    NAME +
    menu - Create and manipulate menu widgets
    +
    SYNOPSIS +
    +
    menu pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeborderwidth, activeBorderWidth, BorderWidth +
    -activeforeground, activeForeground, Background +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -postcommand, postCommand, Command +
    -selectcolor, selectColor, Background +
    -tearoff, tearOff, TearOff +
    -tearoffcommand, tearOffCommand, TearOffCommand +
    -title, title, Title +
    -type, type, Type +
    +
    INTRODUCTION +
    COMMAND ENTRIES +
    SEPARATOR ENTRIES +
    CHECKBUTTON ENTRIES +
    RADIOBUTTON ENTRIES +
    CASCADE ENTRIES +
    TEAR-OFF ENTRIES +
    MENUBARS +
    SPECIAL MENUS IN MENUBARS +
    CLONES +
    WIDGET COMMAND +
    +
    number +
    active +
    end +
    last +
    none +
    @number +
    pattern +
    +
    +
    pathName activate index +
    pathName add type ?option value option value ...? +
    +
    -activebackground value +
    -activeforeground value +
    -accelerator value +
    -background value +
    -bitmap value +
    -columnbreak value +
    -command value +
    -font value +
    -foreground value +
    -hidemargin value +
    -image value +
    -indicatoron value +
    -label value +
    -menu value +
    -offvalue value +
    -onvalue value +
    -selectcolor value +
    -selectimage value +
    -state value +
    -underline value +
    -value value +
    -variable value +
    +
    pathName cget option +
    pathName clone newPathname ?cloneType? +
    pathName configure ?option? ?value option value ...? +
    pathName delete index1 ?index2? +
    pathName entrycget index option +
    pathName entryconfigure index ?options? +
    pathName index index +
    pathName insert index type ?option value option value ...? +
    pathName invoke index +
    pathName post x y +
    pathName postcascade index +
    pathName type index +
    .VS +
    pathName yposition index +
    +
    MENU CONFIGURATIONS +
    +
    Pulldown Menus in Menubar +
    Pulldown Menus in Menu Buttons +
    Popup Menus +
    Option Menus +
    Torn-off Menus +
    +
    DEFAULT BINDINGS +
    +
    +
    BUGS +
    KEYWORDS +

    +

    NAME

    +menu - Create and manipulate menu widgets +

    SYNOPSIS

    +menupathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeborderwidth, activeBorderWidth, BorderWidth +
    -activeforeground, activeForeground, Background +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -postcommand +
    Database Name: postCommand +
    Database Class: Command +
    If this option is specified then it provides a Tcl command to execute +each time the menu is posted. The command is invoked by the post +widget command before posting the menu. Note that in 8.0 on Macintosh +and Windows, all commands in a menu systems are executed before any +are posted. This is due to the limitations in the individual platforms' +menu managers. +

    Command-Line Name: -selectcolor +
    Database Name: selectColor +
    Database Class: Background +
    For menu entries that are check buttons or radio buttons, this option +specifies the color to display in the indicator when the check button +or radio button is selected. +

    Command-Line Name: -tearoff +
    Database Name: tearOff +
    Database Class: TearOff +
    This option must have a proper boolean value, which specifies +whether or not the menu should include a tear-off entry at the +top. If so, it will exist as entry 0 of the menu and the other +entries will number starting at 1. The default +menu bindings arrange for the menu to be torn off when the tear-off +entry is invoked. +

    Command-Line Name: -tearoffcommand +
    Database Name: tearOffCommand +
    Database Class: TearOffCommand +
    If this option has a non-empty value, then it specifies a Tcl command +to invoke whenever the menu is torn off. The actual command will +consist of the value of this option, followed by a space, followed +by the name of the menu window, followed by a space, followed by +the name of the name of the torn off menu window. For example, if +the option's is ``a b'' and menu .x.y is torn off to +create a new menu .x.tearoff1, then the command +``a b .x.y .x.tearoff1'' will be invoked. +

    Command-Line Name: -title +
    Database Name: title +
    Database Class: Title +
    The string will be used to title the window created when this menu is +torn off. If the title is NULL, then the window will have the title +of the menubutton or the text of the cascade item from which this menu +was invoked. +

    Command-Line Name: -type +
    Database Name: type +
    Database Class: Type +
    This option can be one of menubar, tearoff, or +normal, and is set when the menu is created. While the string +returned by the configuration database will change if this option is +changed, this does not affect the menu widget's behavior. This is used +by the cloning mechanism and is not normally set outside of the Tk +library. +
    +

    INTRODUCTION

    +The menu command creates a new top-level window (given +by the pathName argument) and makes it into a menu widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the menu such as its colors and font. +The menu command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A menu is a widget that displays a collection of one-line entries arranged +in one or more columns. There exist several different types of entries, +each with different properties. Entries of different types may be +combined in a single menu. Menu entries are not the same as +entry widgets. In fact, menu entries are not even distinct widgets; +the entire menu is one widget. +

    +Menu entries are displayed with up to three separate fields. +The main field is a label in the form of a text string, +a bitmap, or an image, controlled by the -label, +-bitmap, and -image options for the entry. +If the -accelerator option is specified for an entry then a second +textual field is displayed to the right of the label. The accelerator +typically describes a keystroke sequence that may be typed in the +application to cause the same result as invoking the menu entry. +The third field is an indicator. The indicator is present only for +checkbutton or radiobutton entries. It indicates whether the entry +is selected or not, and is displayed to the left of the entry's +string. +

    +In normal use, an entry becomes active (displays itself differently) +whenever the mouse pointer is over the entry. If a mouse +button is released over the entry then the entry is invoked. +The effect of invocation is different for each type of entry; +these effects are described below in the sections on individual +entries. +

    +Entries may be disabled, which causes their labels +and accelerators to be displayed +with dimmer colors. +The default menu bindings will not allow +a disabled entry to be activated or invoked. +Disabled entries may be re-enabled, at which point it becomes +possible to activate and invoke them again. +

    +Whenever a menu's active entry is changed, a <<MenuSelect>> virtual +event is send to the menu. The active item can then be queried from +the menu, and an action can be taken, such as setting +context-sensitive help text for the entry. + +

    COMMAND ENTRIES

    +The most common kind of menu entry is a command entry, which +behaves much like a button widget. When a command entry is +invoked, a Tcl command is executed. The Tcl +command is specified with the -command option. + +

    SEPARATOR ENTRIES

    +A separator is an entry that is displayed as a horizontal dividing +line. A separator may not be activated or invoked, and it has +no behavior other than its display appearance. + +

    CHECKBUTTON ENTRIES

    +A checkbutton menu entry behaves much like a checkbutton widget. +When it is invoked it toggles back and forth between the selected +and deselected states. When the entry is selected, a particular +value is stored in a particular global variable (as determined by +the -onvalue and -variable options for the entry); when +the entry is deselected another value (determined by the +-offvalue option) is stored in the global variable. +An indicator box is displayed to the left of the label in a checkbutton +entry. If the entry is selected then the indicator's center is displayed +in the color given by the -selectcolor option for the entry; +otherwise the indicator's center is displayed in the background color for +the menu. If a -command option is specified for a checkbutton +entry, then its value is evaluated as a Tcl command each time the entry +is invoked; this happens after toggling the entry's +selected state. + +

    RADIOBUTTON ENTRIES

    +A radiobutton menu entry behaves much like a radiobutton widget. +Radiobutton entries are organized in groups of which only one +entry may be selected at a time. Whenever a particular entry +becomes selected it stores a particular value into a particular +global variable (as determined by the -value and +-variable options for the entry). This action +causes any previously-selected entry in the same group +to deselect itself. +Once an entry has become selected, any change to the entry's +associated variable will cause the entry to deselect itself. +Grouping of radiobutton entries is determined by their +associated variables: if two entries have the same associated +variable then they are in the same group. +An indicator diamond is displayed to the left of the label in each +radiobutton entry. If the entry is selected then the indicator's +center is displayed in the color given by the -selectcolor option +for the entry; +otherwise the indicator's center is displayed in the background color for +the menu. If a -command option is specified for a radiobutton +entry, then its value is evaluated as a Tcl command each time the entry +is invoked; this happens after selecting the entry. + +

    CASCADE ENTRIES

    +A cascade entry is one with an associated menu (determined +by the -menu option). Cascade entries allow the construction +of cascading menus. +The postcascade widget command can be used to post and unpost +the associated menu just next to of the cascade entry. +The associated menu must be a child of the menu containing +the cascade entry (this is needed in order for menu traversal to +work correctly). +

    +A cascade entry posts its associated menu by invoking a +Tcl command of the form +

    menu post x y
    +where menu is the path name of the associated menu, and x +and y are the root-window coordinates of the upper-right +corner of the cascade entry. +On Unix, the lower-level menu is unposted by executing a Tcl command with +the form +
    menu unpost
    +where menu is the name of the associated menu. +On other platforms, the platform's native code takes care of unposting the +menu. +

    +If a -command option is specified for a cascade entry then it is +evaluated as a Tcl command whenever the entry is invoked. This is not +supported on Windows. + +

    TEAR-OFF ENTRIES

    +A tear-off entry appears at the top of the menu if enabled with the +tearOff option. It is not like other menu entries in that +it cannot be created with the add widget command and +cannot be deleted with the delete widget command. +When a tear-off entry is created it appears as a dashed line at +the top of the menu. Under the default bindings, invoking the +tear-off entry causes a torn-off copy to be made of the menu and +all of its submenus. + +

    MENUBARS

    +Any menu can be set as a menubar for a toplevel window (see +toplevel command for syntax). On the Macintosh, whenever the +toplevel is in front, this menu's cascade items will appear in the +menubar across the top of the main monitor. On Windows and Unix, this +menu's items will be displayed in a menubar accross the top of the +window. These menus will behave according to the interface guidelines +of their platforms. For every menu set as a menubar, a clone menu is +made. See the CLONES section for more information. +

    +As noted, menubars may behave differently on different platforms. One +example of this concerns the handling of checkbuttons and radiobuttons +within the menu. While it is permitted to put these menu elements on +menubars, they may not be drawn with indicators on some platforms, due +to system restrictions. + +

    SPECIAL MENUS IN MENUBARS

    +Certain menus in a menubar will be treated specially. On the Macintosh, +access to the special Apple and Help menus is provided. On Windows, +access to the Windows System menu in each window is provided. On X Windows, +a special right-justified help menu is provided. In all cases, these +menus must be created with the command name of the menubar menu concatenated +with the special name. So for a menubar named .menubar, on the Macintosh, +the special menus would be .menubar.apple and .menubar.help; on Windows, +the special menu would be .menubar.system; on X Windows, the help +menu would be .menubar.help. +

    +When Tk sees an Apple menu on the Macintosh, that menu's contents make +up the first items of the Apple menu on the screen whenever the window +containing the menubar is in front. The menu is the +first one that the user sees and has a title which is an Apple logo. +After all of the Tk-defined items, the menu will have a separator, +followed by all of the items in the user's Apple Menu Items folder. +Since the System uses a different menu definition procedure for +the Apple menu than Tk uses for its menus, and the system APIs do +not fully support everything Tk tries to do, the menu item will only +have its text displayed. No font attributes, images, bitmaps, or colors +will be displayed. In addition, a menu with a tearoff item will have +the tearoff item displayed as "(TearOff)". +

    +When Tk see a Help menu on the Macintosh, the menu's contents are +appended to the standard help menu on the right of the user's menubar +whenever the user's menubar is in front. The first items in the menu +are provided by Apple. Similar to the Apple Menu, cusomization in this +menu is limited to what the system provides. +

    +When Tk sees a System menu on Windows, its items are appended to the +system menu that the menubar is attached to. This menu has an icon +representing a spacebar, and can be invoked with the mouse or by typing +Alt+Spacebar. Due to limitations in the Windows API, any font changes, +colors, images, bitmaps, or tearoff images will not appear in the +system menu. +

    +When Tk see a Help menu on X Windows, the menu is moved to be last in +the menubar and is right justified. + +

    CLONES

    +When a menu is set as a menubar for a toplevel window, or when a menu +is torn off, a clone of the menu is made. This clone is a menu widget +in its own right, but it is a child of the original. Changes in the +configuration of the original are reflected in the +clone. Additionally, any cascades that are pointed to are also cloned +so that menu traversal will work right. Clones are destroyed when +either the tearoff or menubar goes away, or when the original menu is +destroyed. + +

    WIDGET COMMAND

    +The menu command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. +

    +Many of the widget commands for a menu take as one argument an +indicator of which entry of the menu to operate on. These +indicators are called indexes and may be specified in +any of the following forms: +

    +

    +

    number
    +Specifies the entry numerically, where 0 corresponds +to the top-most entry of the menu, 1 to the entry below it, and +so on. +

    active
    +Indicates the entry that is currently active. If no entry is +active then this form is equivalent to none. This form may +not be abbreviated. +

    end
    +Indicates the bottommost entry in the menu. If there are no +entries in the menu then this form is equivalent to none. +This form may not be abbreviated. +

    last
    +Same as end. +

    none
    +Indicates ``no entry at all''; this is used most commonly with +the activate option to deactivate all the entries in the +menu. In most cases the specification of none causes +nothing to happen in the widget command. +This form may not be abbreviated. +

    @number
    +In this form, number is treated as a y-coordinate in the +menu's window; the entry closest to that y-coordinate is used. +For example, ``@0'' indicates the top-most entry in the +window. +

    pattern
    +If the index doesn't satisfy one of the above forms then this +form is used. Pattern is pattern-matched against the label of +each entry in the menu, in order from the top down, until a +matching entry is found. The rules of Tcl_StringMatch +are used. +

    +

    +The following widget commands are possible for menu widgets: +

    +

    +

    pathName activate index
    +Change the state of the entry indicated by index to active +and redisplay it using its active colors. +Any previously-active entry is deactivated. If index +is specified as none, or if the specified entry is +disabled, then the menu ends up with no active entry. +Returns an empty string. +

    pathName add type ?option value option value ...?
    +Add a new entry to the bottom of the menu. The new entry's type +is given by type and must be one of cascade, +checkbutton, command, radiobutton, or separator, +or a unique abbreviation of one of the above. If additional arguments +are present, they specify any of the following options: +

    +

    +

    -activebackground value
    +Specifies a background color to use for displaying this entry when it +is active. +If this option is specified as an empty string (the default), then the +activeBackground option for the overall menu is used. +If the tk_strictMotif variable has been set to request strict +Motif compliance, then this option is ignored and the -background +option is used in its place. +This option is not available for separator or tear-off entries. +

    -activeforeground value
    +Specifies a foreground color to use for displaying this entry when it +is active. +If this option is specified as an empty string (the default), then the +activeForeground option for the overall menu is used. +This option is not available for separator or tear-off entries. +

    -accelerator value
    +Specifies a string to display at the right side of the menu entry. +Normally describes an accelerator keystroke sequence that may be +typed to invoke the same function as the menu entry. This option +is not available for separator or tear-off entries. +

    -background value
    +Specifies a background color to use for displaying this entry when it +is in the normal state (neither active nor disabled). +If this option is specified as an empty string (the default), then the +background option for the overall menu is used. +This option is not available for separator or tear-off entries. +

    -bitmap value
    +Specifies a bitmap to display in the menu instead of a textual +label, in any of the forms accepted by Tk_GetBitmap. +This option overrides the -label option but may be reset +to an empty string to enable a textual label to be displayed. +If a -image option has been specified, it overrides +-bitmap. +This option is not available for separator or tear-off entries. +

    -columnbreak value
    +When this option is zero, the appears below the previous entry. When +this option is one, the menu appears at the top of a new column in the +menu. +

    -command value
    +Specifies a Tcl command to execute when the menu entry is invoked. +Not available for separator or tear-off entries. +

    -font value
    +Specifies the font to use when drawing the label or accelerator +string in this entry. +If this option is specified as an empty string (the default) then +the font option for the overall menu is used. +This option is not available for separator or tear-off entries. +

    -foreground value
    +Specifies a foreground color to use for displaying this entry when it +is in the normal state (neither active nor disabled). +If this option is specified as an empty string (the default), then the +foreground option for the overall menu is used. +This option is not available for separator or tear-off entries. +

    -hidemargin value
    +Specifies whether the standard margins should be drawn for this menu +entry. This is useful when creating palette with images in them, i.e., +color palettes, pattern palettes, etc. 1 indicates that the margin for +the entry is hidden; 0 means that the margin is used. +

    -image value
    +Specifies an image to display in the menu instead of a text string +or bitmap +The image must have been created by some previous invocation of +image create. +This option overrides the -label and -bitmap options +but may be reset to an empty string to enable a textual or +bitmap label to be displayed. +This option is not available for separator or tear-off entries. +

    -indicatoron value
    +Available only for checkbutton and radiobutton entries. +Value is a boolean that determines whether or not the +indicator should be displayed. +

    -label value
    +Specifies a string to display as an identifying label in the menu +entry. Not available for separator or tear-off entries. +

    -menu value
    +Available only for cascade entries. Specifies the path name of +the submenu associated with this entry. +The submenu must be a child of the menu. +

    -offvalue value
    +Available only for checkbutton entries. Specifies the value to +store in the entry's associated variable when the entry is +deselected. +

    -onvalue value
    +Available only for checkbutton entries. Specifies the value to +store in the entry's associated variable when the entry is selected. +

    -selectcolor value
    +Available only for checkbutton and radiobutton entries. +Specifies the color to display in the indicator when the entry is +selected. +If the value is an empty string (the default) then the selectColor +option for the menu determines the indicator color. +

    -selectimage value
    +Available only for checkbutton and radiobutton entries. +Specifies an image to display in the entry (in place of +the -image option) when it is selected. +Value is the name of an image, which must have been created +by some previous invocation of image create. +This option is ignored unless the -image option has +been specified. +

    -state value
    +Specifies one of three states for the entry: normal, active, +or disabled. In normal state the entry is displayed using the +foreground option for the menu and the background +option from the entry or the menu. +The active state is typically used when the pointer is over the entry. +In active state the entry is displayed using the activeForeground +option for the menu along with the activebackground option from +the entry. Disabled state means that the entry +should be insensitive: the default bindings will refuse to activate +or invoke the entry. +In this state the entry is displayed according to the +disabledForeground option for the menu and the +background option from the entry. +This option is not available for separator entries. +

    -underline value
    +Specifies the integer index of a character to underline in the entry. +This option is also queried by the default bindings and used to +implement keyboard traversal. +0 corresponds to the first character of the text displayed in the entry, +1 to the next character, and so on. +If a bitmap or image is displayed in the entry then this option is ignored. +This option is not available for separator or tear-off entries. +

    -value value
    +Available only for radiobutton entries. Specifies the value to +store in the entry's associated variable when the entry is selected. +If an empty string is specified, then the -label option +for the entry as the value to store in the variable. +

    -variable value
    +Available only for checkbutton and radiobutton entries. Specifies +the name of a global value to set when the entry is selected. +For checkbutton entries the variable is also set when the entry +is deselected. For radiobutton entries, changing the variable +causes the currently-selected entry to deselect itself. +

    The add widget command returns an empty string.

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the menu +command. +

    pathName clone newPathname ?cloneType?
    +Makes a clone of the current menu named newPathName. This clone +is a menu in its own right, but any changes to the clone are +propogated to the original menu and vice versa. cloneType can be +normal, menubar, or tearoff. Should not normally be +called outside of the Tk library. See the CLONES section for +more information. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the menu +command. +

    pathName delete index1 ?index2?
    +Delete all of the menu entries between index1 and +index2 inclusive. +If index2 is omitted then it defaults to index1. +Attempts to delete a tear-off menu entry are ignored (instead, you +should change the tearOff option to remove the tear-off entry). +

    pathName entrycget index option
    +Returns the current value of a configuration option for +the entry given by index. +Option may have any of the values accepted by the add +widget command. +

    pathName entryconfigure index ?options?
    +This command is similar to the configure command, except that +it applies to the options for an individual entry, whereas configure +applies to the options for the menu as a whole. +Options may have any of the values accepted by the add +widget command. If options are specified, options are modified +as indicated +in the command and the command returns an empty string. +If no options are specified, returns a list describing +the current options for entry index (see Tk_ConfigureInfo for +information on the format of this list). +

    pathName index index
    +Returns the numerical index corresponding to index, or +none if index was specified as none. +

    pathName insert index type ?option value option value ...?
    +Same as the add widget command except that it inserts the new +entry just before the entry given by index, instead of appending +to the end of the menu. The type, option, and value +arguments have the same interpretation as for the add widget +command. It is not possible to insert new menu entries before the +tear-off entry, if the menu has one. +

    pathName invoke index
    +Invoke the action of the menu entry. See the sections on the +individual entries above for details on what happens. If the +menu entry is disabled then nothing happens. If the +entry has a command associated with it then the result of that +command is returned as the result of the invoke widget +command. Otherwise the result is an empty string. Note: invoking +a menu entry does not automatically unpost the menu; the default +bindings normally take care of this before invoking the invoke +widget command. +

    pathName post x y
    +Arrange for the menu to be displayed on the screen at the root-window +coordinates given by x and y. These coordinates are +adjusted if necessary to guarantee that the entire menu is visible on +the screen. This command normally returns an empty string. +If the postCommand option has been specified, then its value is +executed as a Tcl script before posting the menu and the result of +that script is returned as the result of the post widget +command. +If an error returns while executing the command, then the error is +returned without posting the menu. +

    pathName postcascade index
    +Posts the submenu associated with the cascade entry given by +index, and unposts any previously posted submenu. +If index doesn't correspond to a cascade entry, +or if pathName isn't posted, +the command has no effect except to unpost any currently posted +submenu. +

    pathName type index
    +Returns the type of the menu entry given by index. +This is the type argument passed to the add widget +command when the entry was created, such as command +or separator, or tearoff for a tear-off entry. +

    .VS
    +pathName unpost +Unmap the window so that it is no longer displayed. If a +lower-level cascaded menu is posted, unpost that menu. Returns an +empty string. This subcommand does not work on Windows and the +Macintosh, as those platforms have their own way of unposting menus. +

    pathName yposition index
    +Returns a decimal string giving the y-coordinate within the menu +window of the topmost pixel in the entry specified by index. + +

    +

    MENU CONFIGURATIONS

    +The default bindings support four different ways of using menus: +

    +

    +

    Pulldown Menus in Menubar
    +This is the most command case. You create a menu widget that will become the +menu bar. You then add cascade entries to this menu, specifying the +pull down menus you wish to use in your menu bar. You then create all +of the pulldowns. Once you have done this, specify the menu using the +-menu option of the toplevel's widget command. See the +toplevel manual entry for details. +

    Pulldown Menus in Menu Buttons
    +This is the compatable way to do menu bars. You create one menubutton +widget for each top-level menu, and typically you arrange a series of +menubuttons in a row in a menubar window. You also create the top-level menus +and any cascaded submenus, and tie them together with -menu +options in menubuttons and cascade menu entries. The top-level menu must +be a child of the menubutton, and each submenu must be a child of the +menu that refers to it. Once you have done this, the default bindings +will allow users to traverse and invoke the tree of menus via its +menubutton; see the menubutton manual entry for details. +

    Popup Menus
    +Popup menus typically post in response to a mouse button press or +keystroke. You create the popup menus and any cascaded submenus, +then you call the tk_popup procedure at the appropriate time +to post the top-level menu. +

    Option Menus
    +An option menu consists of a menubutton with an associated menu +that allows you to select one of several values. The current value +is displayed in the menubutton and is also stored in a global +variable. Use the tk_optionMenu procedure to create option +menubuttons and their menus. +

    Torn-off Menus
    +You create a torn-off menu by invoking the tear-off entry at +the top of an existing menu. The default bindings will create a new menu +that is a copy of the original menu and leave it permanently +posted as a top-level window. The torn-off menu behaves just +the same as the original menu. + +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for menus that give them +the following default behavior: +

    +

    +

    [1]
    +When the mouse enters a menu, the entry underneath the mouse +cursor activates; as the mouse moves around the menu, the active +entry changes to track the mouse. +

    [2]
    +When the mouse leaves a menu all of the entries in the menu +deactivate, except in the special case where the mouse moves from +a menu to a cascaded submenu. +

    [3]
    +When a button is released over a menu, the active entry (if any) is invoked. +The menu also unposts unless it is a torn-off menu. +

    [4]
    +The Space and Return keys invoke the active entry and +unpost the menu. +

    [5]
    +If any of the entries in a menu have letters underlined with +with -underline option, then pressing one of the underlined +letters (or its upper-case or lower-case equivalent) invokes that +entry and unposts the menu. +

    [6]
    +The Escape key aborts a menu selection in progress without invoking any +entry. It also unposts the menu unless it is a torn-off menu. +

    [7]
    +The Up and Down keys activate the next higher or lower entry +in the menu. When one end of the menu is reached, the active +entry wraps around to the other end. +

    [8]
    +The Left key moves to the next menu to the left. +If the current menu is a cascaded submenu, then the submenu is +unposted and the current menu entry becomes the cascade entry +in the parent. +If the current menu is a top-level menu posted from a +menubutton, then the current menubutton is unposted and the +next menubutton to the left is posted. +Otherwise the key has no effect. +The left-right order of menubuttons is determined by their stacking +order: Tk assumes that the lowest menubutton (which by default +is the first one created) is on the left. +

    [9]
    +The Right key moves to the next menu to the right. +If the current entry is a cascade entry, then the submenu is +posted and the current menu entry becomes the first entry +in the submenu. +Otherwise, if the current menu was posted from a +menubutton, then the current menubutton is unposted and the +next menubutton to the right is posted. +

    +

    +Disabled menu entries are non-responsive: they don't activate and +they ignore mouse button presses and releases. +

    +The behavior of menus can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    BUGS

    +At present it isn't possible to use the +option database to specify values for the options to individual +entries. + +

    KEYWORDS

    +menu, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/menubutton.htm b/hlp/en/tk/menubutton.htm new file mode 100644 index 0000000..8b8175e --- /dev/null +++ b/hlp/en/tk/menubutton.htm @@ -0,0 +1,266 @@ +Tk Built-In Commands - menubutton manual page +
    +
    NAME +
    menubutton - Create and manipulate menubutton widgets
    +
    SYNOPSIS +
    +
    menubutton pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -direction, direction, Height +
    -height, height, Height +
    -indicatoron, indicatorOn, IndicatorOn +
    -menu, menu, MenuName +
    -state, state, State +
    -width, width, Width +
    +
    INTRODUCTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +menubutton - Create and manipulate menubutton widgets +

    SYNOPSIS

    +menubuttonpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -direction +
    Database Name: direction +
    Database Class: Height +
    Specifies where the menu is going to be popup up. above tries to +pop the menu above the menubutton. below tries to pop the menu +below the menubutton. left tries to pop the menu to the left of +the menubutton. right tries to pop the menu to the right of the +menu button. flush pops the menu directly over the menubutton. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the menubutton's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -indicatoron +
    Database Name: indicatorOn +
    Database Class: IndicatorOn +
    The value must be a proper boolean value. If it is true then +a small indicator rectangle will be displayed on the right side +of the menubutton and the default menu bindings will treat this +as an option menubutton. If false then no indicator will be +displayed. +

    Command-Line Name: -menu +
    Database Name: menu +
    Database Class: MenuName +
    Specifies the path name of the menu associated with this menubutton. +The menu must be a child of the menubutton. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the menubutton: normal, active, +or disabled. In normal state the menubutton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the menubutton. In active state +the menubutton is displayed using the activeForeground and +activeBackground options. Disabled state means that the menubutton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the button is displayed. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the menubutton's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    INTRODUCTION

    +The menubutton command creates a new window (given by the +pathName argument) and makes it into a menubutton widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the menubutton such as its colors, font, +text, and initial relief. The menubutton command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A menubutton is a widget that displays a textual string, bitmap, or image +and is associated with a menu widget. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. In normal usage, pressing +mouse button 1 over the menubutton causes the associated menu to +be posted just underneath the menubutton. If the mouse is moved over +the menu before releasing the mouse button, the button release +causes the underlying menu entry to be invoked. When the button +is released, the menu is unposted. +

    +Menubuttons are typically organized into groups called menu bars +that allow scanning: +if the mouse button is pressed over one menubutton (causing it +to post its menu) and the mouse is moved over another menubutton +in the same menu bar without releasing the mouse button, then the +menu of the first menubutton is unposted and the menu of the +new menubutton is posted instead. +

    +There are several interactions between menubuttons and menus; see +the menu manual entry for information on various menu configurations, +such as pulldown menus and option menus. + +

    WIDGET COMMAND

    +The menubutton command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for menubutton widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the menubutton +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the menubutton +command. + +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for menubuttons that give them +the following default behavior: +

    +

    +

    [1]
    +A menubutton activates whenever the mouse passes over it and deactivates +whenever the mouse leaves it. +

    [2]
    +Pressing mouse button 1 over a menubutton posts the menubutton: +its relief changes to raised and its associated menu is posted +under the menubutton. If the mouse is dragged down into the menu +with the button still down, and if the mouse button is then +released over an entry in the menu, the menubutton is unposted +and the menu entry is invoked. +

    [3]
    +If button 1 is pressed over a menubutton and then released over that +menubutton, the menubutton stays posted: you can still move the mouse +over the menu and click button 1 on an entry to invoke it. +Once a menu entry has been invoked, the menubutton unposts itself. +

    [4]
    +If button 1 is pressed over a menubutton and then dragged over some +other menubutton, the original menubutton unposts itself and the +new menubutton posts. +

    [5]
    +If button 1 is pressed over a menubutton and released outside +any menubutton or menu, the menubutton unposts without invoking +any menu entry. +

    [6]
    +When a menubutton is posted, its associated menu claims the input +focus to allow keyboard traversal of the menu and its submenus. +See the menu manual entry for details on these bindings. +

    [7]
    +If the underline option has been specified for a menubutton +then keyboard traversal may be used to post the menubutton: +Alt+x, where x is the underlined character (or its +lower-case or upper-case equivalent), may be typed in any window +under the menubutton's toplevel to post the menubutton. +

    [8]
    +The F10 key may be typed in any window to post the first menubutton +under its toplevel window that isn't disabled. +

    [9]
    +If a menubutton has the input focus, the space and return keys +post the menubutton. +

    +

    +If the menubutton's state is disabled then none of the above +actions occur: the menubutton is completely non-responsive. +

    +The behavior of menubuttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +menubutton, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/message.htm b/hlp/en/tk/message.htm new file mode 100644 index 0000000..10b799b --- /dev/null +++ b/hlp/en/tk/message.htm @@ -0,0 +1,196 @@ +Tk Built-In Commands - message manual page +
    +
    NAME +
    message - Create and manipulate message widgets
    +
    SYNOPSIS +
    +
    message pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -width +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -aspect, aspect, Aspect +
    -justify, justify, Justify +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    DEFAULT BINDINGS +
    BUGS +
    KEYWORDS +

    +

    NAME

    +message - Create and manipulate message widgets +

    SYNOPSIS

    +messagepathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -width +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -aspect +
    Database Name: aspect +
    Database Class: Aspect +
    Specifies a non-negative integer value indicating desired +aspect ratio for the text. The aspect ratio is specified as +100*width/height. 100 means the text should +be as wide as it is tall, 200 means the text should +be twice as wide as it is tall, 50 means the text should +be twice as tall as it is wide, and so on. +Used to choose line length for text if width option +isn't specified. +Defaults to 150. +

    Command-Line Name: -justify +
    Database Name: justify +
    Database Class: Justify +
    Specifies how to justify lines of text. +Must be one of left, center, or right. Defaults +to left. +This option works together with the anchor, aspect, +padX, padY, and width options to provide a variety +of arrangements of the text within the window. +The aspect and width options determine the amount of +screen space needed to display the text. +The anchor, padX, and padY options determine where this +rectangular area is displayed within the widget's window, and the +justify option determines how each line is displayed within that +rectangular region. +For example, suppose anchor is e and justify is +left, and that the message window is much larger than needed +for the text. +The the text will displayed so that the left edges of all the lines +line up and the right edge of the longest line is padX from +the right side of the window; the entire text block will be centered +in the vertical span of the window. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the length of lines in the window. +The value may have any of the forms acceptable to Tk_GetPixels. +If this option has a value greater than zero then the aspect +option is ignored and the width option determines the line +length. +If this option has a value less than or equal to zero, then +the aspect option determines the line length. +
    +

    DESCRIPTION

    +The message command creates a new window (given by the +pathName argument) and makes it into a message widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the message such as its colors, font, +text, and initial relief. The message command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A message is a widget that displays a textual string. A message +widget has three special features. First, it breaks up +its string into lines in order to produce a given aspect ratio +for the window. The line breaks are chosen at word boundaries +wherever possible (if not even a single word would fit on a +line, then the word will be split across lines). Newline characters +in the string will force line breaks; they can be used, for example, +to leave blank lines in the display. +

    +The second feature of a message widget is justification. The text +may be displayed left-justified (each line starts at the left side of +the window), centered on a line-by-line basis, or right-justified +(each line ends at the right side of the window). +

    +The third feature of a message widget is that it handles control +characters and non-printing characters specially. Tab characters +are replaced with enough blank space to line up on the next +8-character boundary. Newlines cause line breaks. Other control +characters (ASCII code less than 0x20) and characters not defined +in the font are displayed as a four-character sequence \xhh where +hh is the two-digit hexadecimal number corresponding to +the character. In the unusual case where the font doesn't contain +all of the characters in ``0123456789abcdef\x'' then control +characters and undefined characters are not displayed at all. + +

    WIDGET COMMAND

    +The message command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for message widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the message +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the message +command. + +

    +

    DEFAULT BINDINGS

    +When a new message is created, it has no default event bindings: +messages are intended for output purposes only. + +

    BUGS

    +Tabs don't work very well with text that is centered or right-justified. +The most common result is that the line is justified wrong. + +

    KEYWORDS

    +message, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/messageBox.htm b/hlp/en/tk/messageBox.htm new file mode 100644 index 0000000..f253b02 --- /dev/null +++ b/hlp/en/tk/messageBox.htm @@ -0,0 +1,95 @@ +Tk Built-In Commands - tk_messageBox manual page +
    +
    NAME +
    tk_messageBox - pops up a message window and waits for user response.
    +
    SYNOPSIS +
    +
    tk_messageBox ?option value ...? +
    +
    DESCRIPTION +
    +
    -default name +
    -icon iconImage +
    -message string +
    -parent window +
    -title titleString +
    -type predefinedType +
    +
    abortretryignore +
    ok +
    okcancel +
    retrycancel +
    yesno +
    yesnocancel +
    +
    +
    EXAMPLE +
    KEYWORDS +

    +

    NAME

    +tk_messageBox - pops up a message window and waits for user response. +

    SYNOPSIS

    +tk_messageBox ?option value ...?
    +

    DESCRIPTION

    +This procedure creates and displays a message window with an +application-specified message, an icon and a set of buttons. Each of +the buttons in the message window is identified by a unique symbolic +name (see the -type options). After the message window is +popped up, tk_messageBox waits for the user to select one of the +buttons. Then it returns the symbolic name of the selected button. + +The following option-value pairs are supported: +

    +

    +

    -default name
    +Name gives the symbolic name of the default button for +this message window ('ok', 'cancel', and so on). See -type +for a list of the symbolic names. If this option is not specified, +the first button in the dialog will be made the default. +

    -icon iconImage
    +Specifies an icon to display. IconImage must be one of the +following: error, info, question or +warning. If this option is not specified, then the info icon will be +displayed. +

    -message string
    +Specifies the message to display in this message box. +

    -parent window
    +Makes window the logical parent of the message box. The message +box is displayed on top of its parent window. +

    -title titleString
    +Specifies a string to display as the title of the message box. The +default value is an empty string. +

    -type predefinedType
    +Arranges for a predefined set of buttons to be displayed. The +following values are possible for predefinedType: +

    +

    +

    abortretryignore
    +Displays three buttons whose symbolic names are abort, +retry and ignore. +

    ok
    +Displays one button whose symbolic name is ok. +

    okcancel
    +Displays two buttons whose symbolic names are ok and cancel. +

    retrycancel
    +Displays two buttons whose symbolic names are retry and cancel. +

    yesno
    +Displays two buttons whose symbolic names are yes and no. +

    yesnocancel
    +Displays three buttons whose symbolic names are yes, no +and cancel. +

    +

    +

    +

    EXAMPLE

    +
    set answer [tk_messageBox -message "Really quit?" -type yesno -icon question]
    +switch -- $answer {
    +    yes exit
    +    no {tk_messageBox -message "I know you like this application!" -type ok}
    +}
    +

    KEYWORDS

    +message box +
    +Copyright © 1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/option.htm b/hlp/en/tk/option.htm new file mode 100644 index 0000000..50984c7 --- /dev/null +++ b/hlp/en/tk/option.htm @@ -0,0 +1,96 @@ +Built-In Commands - option manual page +
    +
    NAME +
    option - Add/retrieve window options to/from the option database
    +
    SYNOPSIS +
    +
    option add pattern value ?priority? +
    option clear +
    option get window name class +
    option readfile fileName ?priority? +
    +
    DESCRIPTION +
    +
    widgetDefault +
    startupFile +
    userDefault +
    interactive +
    +
    KEYWORDS +

    +

    NAME

    +option - Add/retrieve window options to/from the option database +

    SYNOPSIS

    +option add pattern value ?priority?
    +option clear
    +option get window name class
    +option readfile fileName ?priority?
    +

    DESCRIPTION

    +The option command allows you to add entries to the Tk option +database or to retrieve options from the database. The add +form of the command adds a new option to the database. +Pattern contains +the option being specified, and consists of names and/or classes +separated by asterisks or dots, in the usual X format. Value +contains a text string to associate with pattern; this is the +value that will be returned in calls to Tk_GetOption or by +invocations of the option get command. If priority +is specified, it indicates the priority level for this option (see +below for legal values); it defaults to interactive. +This command always returns an empty string. +

    +The option clear command clears the option database. Default +options (from the +RESOURCE_MANAGER property or the .Xdefaults +file) will be reloaded automatically the next time an +option is added to the database or removed from it. This command +always returns an empty string. +

    +The option get command returns the value of the option +specified for window +under name and class. If several entries in the option +database match window, name, and class, then +the command returns whichever was created with highest +priority level. If there are several matching +entries at the same priority level, then it returns whichever entry +was most recently entered into the option database. If there are +no matching entries, then the empty string is returned. +

    +The readfile form of the command reads fileName, +which should have the standard format for an +X resource database such as .Xdefaults, and adds all the +options specified in that file to the option database. If priority +is specified, it indicates the priority level at which to enter the +options; priority defaults to interactive. +

    +The priority arguments to the option command are +normally specified symbolically using one of the following values: +

    +

    +

    widgetDefault
    +Level 20. Used for default values hard-coded into widgets. +

    startupFile
    +Level 40. Used for options specified in application-specific +startup files. +

    userDefault
    +Level 60. Used for options specified in user-specific defaults +files, such as .Xdefaults, resource databases loaded into +the X server, or user-specific startup files. +

    interactive
    +Level 80. Used for options specified interactively after the application +starts running. If priority isn't specified, it defaults to +this level. +

    +

    +Any of the above keywords may be abbreviated. In addition, priorities +may be specified numerically using integers between 0 and 100, +inclusive. The numeric form is probably a bad idea except for new priority +levels other than the ones given above. + +

    KEYWORDS

    +database, option, priority, retrieve +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/optionMenu.htm b/hlp/en/tk/optionMenu.htm new file mode 100644 index 0000000..be8641c --- /dev/null +++ b/hlp/en/tk/optionMenu.htm @@ -0,0 +1,30 @@ +Tk Built-In Commands - tk_optionMenu manual page +

    NAME

    +tk_optionMenu - Create an option menubutton and its menu +

    SYNOPSIS

    +tk_optionMenu w varName value ?value value ...?
    +

    DESCRIPTION

    +This procedure creates an option menubutton whose name is w, +plus an associated menu. +Together they allow the user to select one of the values +given by the value arguments. +The current value will be stored in the global variable whose +name is given by varName and it will also be displayed as the label +in the option menubutton. +The user can click on the menubutton to display a menu containing +all of the values and thereby select a new value. +Once a new value is selected, it will be stored in the variable +and appear in the option menubutton. +The current value can also be changed by setting the variable. +

    +The return value from tk_optionMenu is the name of the menu +associated with w, so that the caller can change its configuration +options or manipulate it in other ways. + +

    KEYWORDS

    +option menu +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/options.htm b/hlp/en/tk/options.htm new file mode 100644 index 0000000..46f993a --- /dev/null +++ b/hlp/en/tk/options.htm @@ -0,0 +1,453 @@ +Tk Built-In Commands - options manual page +
    +
    NAME +
    options - Standard options supported by widgets
    +
    DESCRIPTION +
    +
    -activebackground, activeBackground, Foreground +
    -activeborderwidth, activeBorderWidth, BorderWidth +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -jump, jump, Jump +
    -justify, justify, Justify +
    -orient, orient, Orient +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -troughcolor, troughColor, Background +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    SEE ALSO +
    KEYWORDS +

    +

    NAME

    +options - Standard options supported by widgets +

    DESCRIPTION

    +This manual entry describes the common configuration options supported +by widgets in the Tk toolkit. Every widget does not necessarily support +every option (see the manual entries for individual widgets for a list +of the standard options supported by that widget), but if a widget does +support an option with one of the names listed below, then the option +has exactly the effect described below. +

    +In the descriptions below, ``Command-Line Name'' refers to the +switch used in class commands and configure widget commands to +set this value. For example, if an option's command-line switch is +-foreground and there exists a widget .a.b.c, then the +command +

    .a.b.c  configure  -foreground black
    +may be used to specify the value black for the option in the +the widget .a.b.c. Command-line switches may be abbreviated, +as long as the abbreviation is unambiguous. +``Database Name'' refers to the option's name in the option database (e.g. +in .Xdefaults files). ``Database Class'' refers to the option's class value +in the option database. +
    +
    Command-Line Name: -activebackground +
    Database Name: activeBackground +
    Database Class: Foreground +
    Specifies background color to use when drawing active elements. +An element (a widget or portion of a widget) is active if the +mouse cursor is positioned over the element and pressing a mouse button +will cause some action to occur. +If strict Motif compliance has been requested by setting the +tk_strictMotif variable, this option will normally be +ignored; the normal background color will be used instead. +For some elements on Windows and Macintosh systems, the active color +will only be used while mouse button 1 is pressed over the element. +

    Command-Line Name: -activeborderwidth +
    Database Name: activeBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating +the width of the 3-D border drawn around active elements. See above for +definition of active elements. +The value may have any of the forms acceptable to Tk_GetPixels. +This option is typically only available in widgets displaying more +than one element at a time (e.g. menus but not buttons). +

    Command-Line Name: -activeforeground +
    Database Name: activeForeground +
    Database Class: Background +
    Specifies foreground color to use when drawing active elements. +See above for definition of active elements. +

    Command-Line Name: -anchor +
    Database Name: anchor +
    Database Class: Anchor +
    Specifies how the information in a widget (e.g. text or a bitmap) +is to be displayed in the widget. +Must be one of the values n, ne, e, se, +s, sw, w, nw, or center. +For example, nw means display the information such that its +top-left corner is at the top-left corner of the widget. +

    Command-Line Name: -background or -bg +
    Database Name: background +
    Database Class: Background +
    Specifies the normal background color to use when displaying the +widget. +

    Command-Line Name: -bitmap +
    Database Name: bitmap +
    Database Class: Bitmap +
    Specifies a bitmap to display in the widget, in any of the forms +acceptable to Tk_GetBitmap. +The exact way in which the bitmap is displayed may be affected by +other options such as anchor or justify. +Typically, if this option is specified then it overrides other +options that specify a textual value to display in the widget; +the bitmap option may be reset to an empty string to re-enable +a text display. +In widgets that support both bitmap and image options, +image will usually override bitmap. +

    Command-Line Name: -borderwidth or -bd +
    Database Name: borderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the outside of the widget (if such a +border is being drawn; the relief option typically determines +this). The value may also be used when drawing 3-D effects in the +interior of the widget. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -cursor +
    Database Name: cursor +
    Database Class: Cursor +
    Specifies the mouse cursor to be used for the widget. +The value may have any of the forms acceptable to Tk_GetCursor. +

    Command-Line Name: -disabledforeground +
    Database Name: disabledForeground +
    Database Class: DisabledForeground +
    Specifies foreground color to use when drawing a disabled element. +If the option is specified as an empty string (which is typically the +case on monochrome displays), disabled elements are drawn with the +normal foreground color but they are dimmed by drawing them +with a stippled fill pattern. +

    Command-Line Name: -exportselection +
    Database Name: exportSelection +
    Database Class: ExportSelection +
    Specifies whether or not a selection in the widget should also be +the X selection. +The value may have any of the forms accepted by Tcl_GetBoolean, +such as true, false, 0, 1, yes, or no. +If the selection is exported, then selecting in the widget deselects +the current X selection, selecting outside the widget deselects any +widget selection, and the widget will respond to selection retrieval +requests when it has a selection. The default is usually for widgets +to export selections. +

    Command-Line Name: -font +
    Database Name: font +
    Database Class: Font +
    Specifies the font to use when drawing text inside the widget. +The value may have any of the forms accepted by Tk_GetFont. +

    Command-Line Name: -foreground or -fg +
    Database Name: foreground +
    Database Class: Foreground +
    Specifies the normal foreground color to use when displaying the widget. +

    Command-Line Name: -highlightbackground +
    Database Name: highlightBackground +
    Database Class: HighlightBackground +
    Specifies the color to display in the traversal highlight region when +the widget does not have the input focus. +

    Command-Line Name: -highlightcolor +
    Database Name: highlightColor +
    Database Class: HighlightColor +
    Specifies the color to use for the traversal highlight rectangle that is +drawn around the widget when it has the input focus. +

    Command-Line Name: -highlightthickness +
    Database Name: highlightThickness +
    Database Class: HighlightThickness +
    Specifies a non-negative value indicating the width of the highlight +rectangle to draw around the outside of the widget when it has the +input focus. +The value may have any of the forms acceptable to Tk_GetPixels. +If the value is zero, no focus highlight is drawn around the widget. +

    Command-Line Name: -image +
    Database Name: image +
    Database Class: Image +
    Specifies an image to display in the widget, which must have been +created with the image create command. +Typically, if the image option is specified then it overrides other +options that specify a bitmap or textual value to display in the widget; +the image option may be reset to an empty string to re-enable +a bitmap or text display. +

    Command-Line Name: -insertbackground +
    Database Name: insertBackground +
    Database Class: Foreground +
    Specifies the color to use as background in the area covered by the +insertion cursor. This color will normally override either the normal +background for the widget (or the selection background if the insertion +cursor happens to fall in the selection). +

    Command-Line Name: -insertborderwidth +
    Database Name: insertBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -insertofftime +
    Database Name: insertOffTime +
    Database Class: OffTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``off'' in each blink cycle. +If this option is zero then the cursor doesn't blink: it is on +all the time. +

    Command-Line Name: -insertontime +
    Database Name: insertOnTime +
    Database Class: OnTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``on'' in each blink cycle. +

    Command-Line Name: -insertwidth +
    Database Name: insertWidth +
    Database Class: InsertWidth +
    Specifies a value indicating the total width of the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +If a border has been specified for the insertion +cursor (using the insertBorderWidth option), the border +will be drawn inside the width specified by the insertWidth +option. +

    Command-Line Name: -jump +
    Database Name: jump +
    Database Class: Jump +
    For widgets with a slider that can be dragged to adjust a value, +such as scrollbars, this option determines when +notifications are made about changes in the value. +The option's value must be a boolean of the form accepted by +Tcl_GetBoolean. +If the value is false, updates are made continuously as the +slider is dragged. +If the value is true, updates are delayed until the mouse button +is released to end the drag; at that point a single notification +is made (the value ``jumps'' rather than changing smoothly). +

    Command-Line Name: -justify +
    Database Name: justify +
    Database Class: Justify +
    When there are multiple lines of text displayed in a widget, this +option determines how the lines line up with each other. +Must be one of left, center, or right. +Left means that the lines' left edges all line up, center +means that the lines' centers are aligned, and right means +that the lines' right edges line up. +

    Command-Line Name: -orient +
    Database Name: orient +
    Database Class: Orient +
    For widgets that can lay themselves out with either a horizontal +or vertical orientation, such as scrollbars, this option specifies +which orientation should be used. Must be either horizontal +or vertical or an abbreviation of one of these. +

    Command-Line Name: -padx +
    Database Name: padX +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the X-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will +add this amount to the width it would normally need (as determined +by the width of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space to the left and/or right of what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -pady +
    Database Name: padY +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the Y-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will add +this amount to the height it would normally need (as determined by +the height of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space above and/or below what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -relief +
    Database Name: relief +
    Database Class: Relief +
    Specifies the 3-D effect desired for the widget. Acceptable +values are raised, sunken, flat, ridge, +solid, and groove. +The value +indicates how the interior of the widget should appear relative +to its exterior; for example, raised means the interior of +the widget should appear to protrude from the screen, relative to +the exterior of the widget. +

    Command-Line Name: -repeatdelay +
    Database Name: repeatDelay +
    Database Class: RepeatDelay +
    Specifies the number of milliseconds a button or key must be held +down before it begins to auto-repeat. Used, for example, on the +up- and down-arrows in scrollbars. +

    Command-Line Name: -repeatinterval +
    Database Name: repeatInterval +
    Database Class: RepeatInterval +
    Used in conjunction with repeatDelay: once auto-repeat +begins, this option determines the number of milliseconds between +auto-repeats. +

    Command-Line Name: -selectbackground +
    Database Name: selectBackground +
    Database Class: Foreground +
    Specifies the background color to use when displaying selected +items. +

    Command-Line Name: -selectborderwidth +
    Database Name: selectBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around selected items. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -selectforeground +
    Database Name: selectForeground +
    Database Class: Background +
    Specifies the foreground color to use when displaying selected +items. +

    Command-Line Name: -setgrid +
    Database Name: setGrid +
    Database Class: SetGrid +
    Specifies a boolean value that determines whether this widget controls the +resizing grid for its top-level window. +This option is typically used in text widgets, where the information +in the widget has a natural size (the size of a character) and it makes +sense for the window's dimensions to be integral numbers of these units. +These natural window sizes form a grid. +If the setGrid option is set to true then the widget will +communicate with the window manager so that when the user interactively +resizes the top-level window that contains the widget, the dimensions of +the window will be displayed to the user in grid units and the window +size will be constrained to integral numbers of grid units. +See the section GRIDDED GEOMETRY MANAGEMENT in the wm manual +entry for more details. +

    Command-Line Name: -takefocus +
    Database Name: takeFocus +
    Database Class: TakeFocus +
    Determines whether the window accepts the focus during keyboard +traversal (e.g., Tab and Shift-Tab). +Before setting the focus to a window, the traversal scripts +consult the value of the takeFocus option. +A value of 0 means that the window should be skipped entirely +during keyboard traversal. +1 means that the window should receive the input +focus as long as it is viewable (it and all of its ancestors are mapped). +An empty value for the option means that the traversal scripts make +the decision about whether or not to focus on the window: the current +algorithm is to skip the window if it is +disabled, if it has no key bindings, or if it is not viewable. +If the value has any other form, then the traversal scripts take +the value, append the name of the window to it (with a separator space), +and evaluate the resulting string as a Tcl script. +The script must return 0, 1, or an empty string: a +0 or 1 value specifies whether the window will receive +the input focus, and an empty string results in the default decision +described above. +Note: this interpretation of the option is defined entirely by +the Tcl scripts that implement traversal: the widget implementations +ignore the option entirely, so you can change its meaning if you +redefine the keyboard traversal scripts. +

    Command-Line Name: -text +
    Database Name: text +
    Database Class: Text +
    Specifies a string to be displayed inside the widget. The way in which +the string is displayed depends on the particular widget and may be +determined by other options, such as anchor or justify. +

    Command-Line Name: -textvariable +
    Database Name: textVariable +
    Database Class: Variable +
    Specifies the name of a variable. The value of the variable is a text +string to be displayed inside the widget; if the variable value changes +then the widget will automatically update itself to reflect the new value. +The way in which the string is displayed in the widget depends on the +particular widget and may be determined by other options, such as +anchor or justify. +

    Command-Line Name: -troughcolor +
    Database Name: troughColor +
    Database Class: Background +
    Specifies the color to use for the rectangular trough areas +in widgets such as scrollbars and scales. This option is ignored for +scrollbars on Windows (native widget doesn't recognize this option). +

    Command-Line Name: -underline +
    Database Name: underline +
    Database Class: Underline +
    Specifies the integer index of a character to underline in the widget. +This option is used by the default bindings to implement keyboard +traversal for menu buttons and menu entries. +0 corresponds to the first character of the text displayed in the +widget, 1 to the next character, and so on. +

    Command-Line Name: -wraplength +
    Database Name: wrapLength +
    Database Class: WrapLength +
    For widgets that can perform word-wrapping, this option specifies +the maximum line length. +Lines that would exceed this length are wrapped onto the next line, +so that no line is longer than the specified length. +The value may be specified in any of the standard forms for +screen distances. +If this value is less than or equal to 0 then no wrapping is done: lines +will break only at newline characters in the text. +

    Command-Line Name: -xscrollcommand +
    Database Name: xScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with horizontal +scrollbars. +When the view in the widget's window changes (or +whenever anything else occurs that could change the display in a +scrollbar, such as a change in the total size of the widget's +contents), the widget will +generate a Tcl command by concatenating the scroll command and +two numbers. +Each of the numbers is a fraction between 0 and 1, which indicates +a position in the document. 0 indicates the beginning of the document, +1 indicates the end, .333 indicates a position one third the way through +the document, and so on. +The first fraction indicates the first information in the document +that is visible in the window, and the second fraction indicates +the information just after the last portion that is visible. +The command is +then passed to the Tcl interpreter for execution. Typically the +xScrollCommand option consists of the path name of a scrollbar +widget followed by ``set'', e.g. ``.x.scrollbar set'': this will cause +the scrollbar to be updated whenever the view in the window changes. +If this option is not specified, then no command will be executed. +

    Command-Line Name: -yscrollcommand +
    Database Name: yScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with vertical +scrollbars. This option is treated in the same way as the +xScrollCommand option, except that it is used for vertical +scrollbars and is provided by widgets that support vertical scrolling. +See the description of xScrollCommand for details +on how this option is used. + +
    +

    SEE ALSO

    +colors, cursors, font +

    KEYWORDS

    +class, name, standard option, switch +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/pack.htm b/hlp/en/tk/pack.htm new file mode 100644 index 0000000..e4cba6e --- /dev/null +++ b/hlp/en/tk/pack.htm @@ -0,0 +1,281 @@ +Tk Built-In Commands - pack manual page +
    +
    NAME +
    pack - Geometry manager that packs around edges of cavity
    +
    SYNOPSIS +
    +
    pack option arg ?arg ...? +
    +
    DESCRIPTION +
    +
    pack slave ?slave ...? ?options? +
    pack configure slave ?slave ...? ?options? +
    +
    -after other +
    -anchor anchor +
    -before other +
    -expand boolean +
    -fill style +
    +
    none +
    x +
    y +
    both +
    +
    -in other +
    -ipadx amount +
    -ipady amount +
    -padx amount +
    -pady amount +
    -side side +
    +
    pack forget slave ?slave ...? +
    pack info slave +
    pack propagate master ?boolean? +
    pack slaves master +
    +
    THE PACKER ALGORITHM +
    +
    +
    EXPANSION +
    GEOMETRY PROPAGATION +
    RESTRICTIONS ON MASTER WINDOWS +
    PACKING ORDER +
    KEYWORDS +

    +

    NAME

    +pack - Geometry manager that packs around edges of cavity +

    SYNOPSIS

    +pack option arg ?arg ...?
    +

    DESCRIPTION

    +The pack command is used to communicate with the packer, +a geometry manager that arranges the children of a parent by +packing them in order around the edges of the parent. +The pack command can have any of several forms, depending +on the option argument: +

    +

    +

    pack slave ?slave ...? ?options?
    +If the first argument to pack is a window name (any value +starting with ``.''), then the command is processed in the same +way as pack configure. +

    pack configure slave ?slave ...? ?options?
    +The arguments consist of the names of one or more slave windows +followed by pairs of arguments that specify how +to manage the slaves. +See ``THE PACKER ALGORITHM'' below for details on how the options +are used by the packer. +The following options are supported: +

    +

    +

    -after other
    +Other must the name of another window. +Use its master as the master for the slaves, and insert +the slaves just after other in the packing order. +

    -anchor anchor
    +Anchor must be a valid anchor position such as n +or sw; it specifies where to position each slave in its +parcel. +Defaults to center. +

    -before other
    +Other must the name of another window. +Use its master as the master for the slaves, and insert +the slaves just before other in the packing order. +

    -expand boolean
    +Specifies whether the slaves should be expanded to consume +extra space in their master. +Boolean may have any proper boolean value, such as 1 +or no. +Defaults to 0. +

    -fill style
    +If a slave's parcel is larger than its requested dimensions, this +option may be used to stretch the slave. +Style must have one of the following values: +

    +

    +

    none
    +Give the slave its requested dimensions plus any internal padding +requested with -ipadx or -ipady. This is the default. +

    x
    +Stretch the slave horizontally to fill the entire width of its +parcel (except leave external padding as specified by -padx). +

    y
    +Stretch the slave vertically to fill the entire height of its +parcel (except leave external padding as specified by -pady). +

    both
    +Stretch the slave both horizontally and vertically. +

    +

    -in other
    +Insert the slave(s) at the end of the packing order for the master +window given by other. +

    -ipadx amount
    +Amount specifies how much horizontal internal padding to +leave on each side of the slave(s). +Amount must be a valid screen distance, such as 2 or .5c. +It defaults to 0. +

    -ipady amount
    +Amount specifies how much vertical internal padding to +leave on each side of the slave(s). +Amount defaults to 0. +

    -padx amount
    +Amount specifies how much horizontal external padding to +leave on each side of the slave(s). +Amount defaults to 0. +

    -pady amount
    +Amount specifies how much vertical external padding to +leave on each side of the slave(s). +Amount defaults to 0. +

    -side side
    +Specifies which side of the master the slave(s) will be packed against. +Must be left, right, top, or bottom. +Defaults to top. +

    If no -in, -after or -before option is specified +then each of the slaves will be inserted at the end of the packing list +for its parent unless it is already managed by the packer (in which +case it will be left where it is). +If one of these options is specified then all the slaves will be +inserted at the specified point. +If any of the slaves are already managed by the geometry manager +then any unspecified options for them retain their previous values rather +than receiving default values.

    +

    +

    pack forget slave ?slave ...?
    +Removes each of the slaves from the packing order for its +master and unmaps their windows. +The slaves will no longer be managed by the packer. +

    pack info slave
    +Returns a list whose elements are the current configuration state of +the slave given by slave in the same option-value form that +might be specified to pack configure. +The first two elements of the list are ``-in master'' where +master is the slave's master. +

    pack propagate master ?boolean?
    +If boolean has a true boolean value such as 1 or on +then propagation is enabled for master, which must be a window +name (see ``GEOMETRY PROPAGATION'' below). +If boolean has a false boolean value then propagation is +disabled for master. +In either of these cases an empty string is returned. +If boolean is omitted then the command returns 0 or +1 to indicate whether propagation is currently enabled +for master. +Propagation is enabled by default. +

    pack slaves master
    +Returns a list of all of the slaves in the packing order for master. +The order of the slaves in the list is the same as their order in +the packing order. +If master has no slaves then an empty string is returned. + +

    +

    THE PACKER ALGORITHM

    +For each master the packer maintains an ordered list of slaves +called the packing list. +The -in, -after, and -before configuration +options are used to specify the master for each slave and the slave's +position in the packing list. +If none of these options is given for a slave then the slave +is added to the end of the packing list for its parent. +

    +The packer arranges the slaves for a master by scanning the +packing list in order. +At the time it processes each slave, a rectangular area within +the master is still unallocated. +This area is called the cavity; for the first slave it +is the entire area of the master. +

    +For each slave the packer carries out the following steps: +

    +

    +

    [1]
    +The packer allocates a rectangular parcel for the slave +along the side of the cavity given by the slave's -side option. +If the side is top or bottom then the width of the parcel is +the width of the cavity and its height is the requested height +of the slave plus the -ipady and -pady options. +For the left or right side the height of the parcel is +the height of the cavity and the width is the requested width +of the slave plus the -ipadx and -padx options. +The parcel may be enlarged further because of the -expand +option (see ``EXPANSION'' below) +

    [2]
    +The packer chooses the dimensions of the slave. +The width will normally be the slave's requested width plus +twice its -ipadx option and the height will normally be +the slave's requested height plus twice its -ipady +option. +However, if the -fill option is x or both +then the width of the slave is expanded to fill the width of the parcel, +minus twice the -padx option. +If the -fill option is y or both +then the height of the slave is expanded to fill the width of the parcel, +minus twice the -pady option. +

    [3]
    +The packer positions the slave over its parcel. +If the slave is smaller than the parcel then the -anchor +option determines where in the parcel the slave will be placed. +If -padx or -pady is non-zero, then the given +amount of external padding will always be left between the +slave and the edges of the parcel. +

    +

    +Once a given slave has been packed, the area of its parcel +is subtracted from the cavity, leaving a smaller rectangular +cavity for the next slave. +If a slave doesn't use all of its parcel, the unused space +in the parcel will not be used by subsequent slaves. +If the cavity should become too small to meet the needs of +a slave then the slave will be given whatever space is +left in the cavity. +If the cavity shrinks to zero size, then all remaining slaves +on the packing list will be unmapped from the screen until +the master window becomes large enough to hold them again. + +

    EXPANSION

    +If a master window is so large that there will be extra space +left over after all of its slaves have been packed, then the +extra space is distributed uniformly among all of the slaves +for which the -expand option is set. +Extra horizontal space is distributed among the expandable +slaves whose -side is left or right, +and extra vertical space is distributed among the expandable +slaves whose -side is top or bottom. + +

    GEOMETRY PROPAGATION

    +The packer normally computes how large a master must be to +just exactly meet the needs of its slaves, and it sets the +requested width and height of the master to these dimensions. +This causes geometry information to propagate up through a +window hierarchy to a top-level window so that the entire +sub-tree sizes itself to fit the needs of the leaf windows. +However, the pack propagate command may be used to +turn off propagation for one or more masters. +If propagation is disabled then the packer will not set +the requested width and height of the packer. +This may be useful if, for example, you wish for a master +window to have a fixed size that you specify. + +

    RESTRICTIONS ON MASTER WINDOWS

    +The master for each slave must either be the slave's parent +(the default) or a descendant of the slave's parent. +This restriction is necessary to guarantee that the +slave can be placed over any part of its master that is +visible without danger of the slave being clipped by its parent. + +

    PACKING ORDER

    +If the master for a slave is not its parent then you must make sure +that the slave is higher in the stacking order than the master. +Otherwise the master will obscure the slave and it will appear as +if the slave hasn't been packed correctly. +The easiest way to make sure the slave is higher than the master is +to create the master window first: the most recently created window +will be highest in the stacking order. +Or, you can use the raise and lower commands to change +the stacking order of either the master or the slave. + +

    KEYWORDS

    +geometry manager, location, packer, parcel, propagation, size +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/palette.htm b/hlp/en/tk/palette.htm new file mode 100644 index 0000000..9e38ce2 --- /dev/null +++ b/hlp/en/tk/palette.htm @@ -0,0 +1,58 @@ +Tk Built-In Commands - tk_setPalette manual page +

    NAME

    +tk_setPalette, tk_bisque - Modify the Tk color palette +

    SYNOPSIS

    +tk_setPalette background
    +tk_setPalette name value ?name value ...?
    +tk_bisque
    +

    DESCRIPTION

    +The tk_setPalette procedure changes the color scheme for Tk. +It does this by modifying the colors of existing widgets and by changing +the option database so that future widgets will use the new color scheme. +If tk_setPalette is invoked with a single argument, the +argument is the name of a color to use as the normal background +color; tk_setPalette will compute a complete color palette +from this background color. +Alternatively, the arguments to tk_setPalette may consist of any number +of name-value pairs, where the first argument of the pair +is the name of an option in the Tk option database and the second +argument is the new value to use for that option. The following +database names are currently supported: +
    activeBackground	foreground	selectColor
    +activeForeground	highlightBackground	selectBackground
    +background	highlightColor	selectForeground
    +disabledForeground	insertBackground	troughColor
    +tk_setPalette tries to compute reasonable defaults for any +options that you don't specify. You can specify options other +than the above ones and Tk will change those options on widgets as +well. This feature may be useful if you are using custom widgets with +additional color options. +

    +Once it has computed the new value to use for each of the color options, +tk_setPalette scans the widget hierarchy to modify the options +of all existing widgets. For each widget, it checks to see if any +of the above options is defined for the widget. If so, and if the +option's current value is the default, then the value is changed; if +the option has a value other than the default, tk_setPalette +will not change it. The default for an option is the one provided by +the widget ([lindex [$w configure $option] 3]) unless +tk_setPalette has been run previously, in which case it is the +value specified in the previous invocation of tk_setPalette. +

    +After modifying all the widgets in the application, tk_setPalette +adds options to the option database to change the defaults for +widgets created in the future. The new options are added at +priority widgetDefault, so they will be overridden by options +from the .Xdefaults file or options specified on the command-line +that creates a widget. +

    +The procedure tk_bisque is provided for backward compatibility: +it restores the application's colors to the light brown (``bisque'') +color scheme used in Tk 3.6 and earlier versions. + +

    KEYWORDS

    +bisque, color, palette +
    +Copyright © 1995-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/photo.htm b/hlp/en/tk/photo.htm new file mode 100644 index 0000000..fb95208 --- /dev/null +++ b/hlp/en/tk/photo.htm @@ -0,0 +1,427 @@ +Tk Built-In Commands - photo manual page +
    +
    NAME +
    photo - Full-color images
    +
    SYNOPSIS +
    +
    image create photo ?name? ?options? +
    +
    DESCRIPTION +
    CREATING PHOTOS +
    +
    -data string +
    -format format-name +
    -file name +
    -gamma value +
    -height number +
    -palette palette-spec +
    -width number +
    +
    IMAGE COMMAND +
    +
    imageName blank +
    imageName cget option +
    imageName configure ?option? ?value option value ...? +
    imageName copy sourceImage ?option value(s) ...? +
    +
    -from x1 y1 x2 y2 +
    -to x1 y1 x2 y2 +
    -shrink +
    -zoom x y +
    -subsample x y +
    +
    imageName data ?option value(s) ...? +
    +
    -background color +
    -format format-name +
    -from x1 y1 x2 y2 +
    -grayscale +
    +
    imageName get x y +
    imageName put data ?option value(s) ...? +
    +
    -format format-name +
    -from x1 y1 x2 y2 +
    -shrink +
    -to x y +
    +
    imageName read filename ?option value(s) ...? +
    +
    -format format-name +
    -from x1 y1 x2 y2 +
    -shrink +
    -to x y +
    +
    imageName redither +
    imageName write filename ?option value(s) ...? +
    +
    -background color +
    -format format-name +
    -from x1 y1 x2 y2 +
    -grayscale +
    +
    +
    IMAGE FORMATS +
    COLOR ALLOCATION +
    CREDITS +
    KEYWORDS +

    +

    NAME

    +photo - Full-color images +

    SYNOPSIS

    +image create photo ?name? ?options?
    +

    DESCRIPTION

    +A photo is an image whose pixels can display any color or be +transparent. A photo image is stored internally in full color (32 +bits per pixel), and is displayed using dithering if necessary. Image +data for a photo image can be obtained from a file or a string, or it +can be supplied from +C code through a procedural interface. At present, only GIF and PPM/PGM +formats are supported, but an interface exists to allow additional +image file formats to be added easily. A photo image is transparent +in regions where no image data has been supplied. + +

    CREATING PHOTOS

    +Like all images, photos are created using the image create +command. +Photos support the following options: +

    +

    +

    -data string
    +Specifies the contents of the image as a string. The string can +contain base64 encoded data or binary data. The format of the +string must be one of those for which there is an image file format +handler that will accept string data. If both the -data +and -file options are specified, the -file option takes +precedence. +

    -format format-name
    +Specifies the name of the file format for the data specified with the +-data or -file option. +

    -file name
    +name gives the name of a file that is to be read to supply data +for the photo image. The file format must be one of those for which +there is an image file format handler that can read data. +

    -gamma value
    +Specifies that the colors allocated for displaying this image in a +window should be corrected for a non-linear display with the specified +gamma exponent value. (The intensity produced by most +CRT displays is a power function of the input value, to a good +approximation; gamma is the exponent and is typically around 2). +The value specified must be greater than zero. The default +value is one (no correction). In general, values greater than one +will make the image lighter, and values less than one will make it +darker. +

    -height number
    +Specifies the height of the image, in pixels. This option is useful +primarily in situations where the user wishes to build up the contents +of the image piece by piece. A value of zero (the default) allows the +image to expand or shrink vertically to fit the data stored in it. +

    -palette palette-spec
    +Specifies the resolution of the color cube to be allocated for +displaying this image, and thus the number of colors used from the +colormaps of the windows where it is displayed. The +palette-spec string may be either a single decimal number, +specifying the number of shades of gray to use, or three decimal +numbers separated by slashes (/), specifying the number of shades of +red, green and blue to use, respectively. If the first form (a single +number) is used, the image will be displayed in monochrome (i.e., +grayscale). +

    -width number
    +Specifies the width of the image, in pixels. This option is useful +primarily in situations where the user wishes to build up the contents +of the image piece by piece. A value of zero (the default) allows the +image to expand or shrink horizontally to fit the data stored in it. + +

    +

    IMAGE COMMAND

    +When a photo image is created, Tk also creates a new command +whose name is the same as the image. +This command may be used to invoke various operations +on the image. +It has the following general form: +
    imageName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. +

    +Those options that write data to the image generally expand the size +of the image, if necessary, to accommodate the data written to the +image, unless the user has specified non-zero values for the +-width and/or -height configuration options, in which +case the width and/or height, respectively, of the image will not be +changed. +

    +The following commands are possible for photo images: +

    +

    +

    imageName blank
    +Blank the image; that is, set the entire image to have no data, so it +will be displayed as transparent, and the background of whatever +window it is displayed in will show through. +

    imageName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the +image create photo command. +

    imageName configure ?option? ?value option value ...?
    +Query or modify the configuration options for the image. +If no option is specified, returns a list describing all of +the available options for imageName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the +image create photo command. +

    imageName copy sourceImage ?option value(s) ...?
    +Copies a region from the image called sourceImage (which must +be a photo image) to the image called imageName, possibly with +pixel zooming and/or subsampling. If no options are specified, this +command copies the whole of sourceImage into imageName, +starting at coordinates (0,0) in imageName. The following +options may be specified: +

    +

    +

    -from x1 y1 x2 y2
    +Specifies a rectangular sub-region of the source image to be copied. +(x1,y1) and (x2,y2) specify diagonally opposite corners of +the rectangle. If x2 and y2 are not specified, the +default value is the bottom-right corner of the source image. The +pixels copied will include the left and top edges of the specified +rectangle but not the bottom or right edges. If the -from +option is not given, the default is the whole source image. +

    -to x1 y1 x2 y2
    +Specifies a rectangular sub-region of the destination image to be +affected. (x1,y1) and (x2,y2) specify diagonally opposite +corners of the rectangle. If x2 and y2 are not specified, +the default value is (x1,y1) plus the size of the source +region (after subsampling and zooming, if specified). If x2 and +y2 are specified, the source region will be replicated if +necessary to fill the destination region in a tiled fashion. +

    -shrink
    +Specifies that the size of the destination image should be reduced, if +necessary, so that the region being copied into is at the bottom-right +corner of the image. This option will not affect the width or height +of the image if the user has specified a non-zero value for the +-width or -height configuration option, respectively. +

    -zoom x y
    +Specifies that the source region should be magnified by a factor of +x in the X direction and y in the Y direction. If y +is not given, the default value is the same as x. With this +option, each pixel in the source image will be expanded into a block +of x x y pixels in the destination image, all the same +color. x and y must be greater than 0. +

    -subsample x y
    +Specifies that the source image should be reduced in size by using +only every xth pixel in the X direction and yth pixel in +the Y direction. Negative values will cause the image to be flipped +about the Y or X axes, respectively. If y is not given, the +default value is the same as x. +

    +

    imageName data ?option value(s) ...?
    +Returns image data in the form of a string. The following options +may be specified: +

    +

    +

    -background color
    +If the color is specified, the data will not contain any transparency +information. In all transparent pixels the color will be replaced by +the specified color. +

    -format format-name
    +Specifies the name of the image file format handler to be used. +Specifically, this subcommand searches +for the first handler whose name matches a initial substring of +format-name and which has the capability to read this image data. +If this option is not given, this subcommand uses the first +handler that has the capability to read the image data. +

    -from x1 y1 x2 y2
    +Specifies a rectangular region of imageName to be returned. +If only x1 and y1 are specified, the region +extends from (x1,y1) to the bottom-right corner of +imageName. If all four coordinates are given, they specify +diagonally opposite corners of the rectangular region, including x1,y1 +and excluding x2,y2. The default, if this option is not given, is the +whole image. +

    -grayscale
    +If this options is specified, the data will not contain color +information. All pixel data will be transformed into grayscale. +

    +

    imageName get x y
    +Returns the color of the pixel at coordinates (x,y) in the +image as a list of three integers between 0 and 255, representing the +red, green and blue components respectively. +

    imageName put data ?option value(s) ...?
    +Sets pixels in imageName to the data specified in +data. This command first searches the list of image file +format handlers for a handler that can interpret the data +in data, and then reads the image in filename into +imageName (the destination image). The following options +may be specified: +

    +

    +

    -format format-name
    +Specifies the format of the image data in data. +Specifically, only image file format handlers whose names begin with +format-name will be used while searching for an image data +format handler to read the data. +

    -from x1 y1 x2 y2
    +Specifies a rectangular sub-region of the image file data to be +returned. If only x1 and y1 are specified, the region +extends from (x1,y1) to the bottom-right corner of the image +in the image file. If all four coordinates are specified, they +specify diagonally opposite corners or the region. The default, +if this option is not specified, is the whole of the image. +

    -shrink
    +If this option, the size of imageName will be reduced, if +necessary, so that the region into which the image file data are read +is at the bottom-right corner of the imageName. This option +will not affect the width or height of the image if the user has +specified a non-zero value for the -width or -height +configuration option, respectively. +

    -to x y
    +Specifies the coordinates of the top-left corner of the region of +imageName into which data from filename are to be read. +The default is (0,0). +

    +

    imageName read filename ?option value(s) ...?
    +Reads image data from the file named filename into the image. +This command first searches the list of +image file format handlers for a handler that can interpret the data +in filename, and then reads the image in filename into +imageName (the destination image). The following options may be +specified: +

    +

    +

    -format format-name
    +Specifies the format of the image data in filename. +Specifically, only image file format handlers whose names begin with +format-name will be used while searching for an image data +format handler to read the data. +

    -from x1 y1 x2 y2
    +Specifies a rectangular sub-region of the image file data to be copied +to the destination image. If only x1 and y1 are +specified, the region extends from (x1,y1) to the bottom-right +corner of the image in the image file. If all four coordinates are +specified, they specify diagonally opposite corners or the region. +The default, if this option is not specified, is the whole of the +image in the image file. +

    -shrink
    +If this option, the size of imageName will be reduced, if +necessary, so that the region into which the image file data are read +is at the bottom-right corner of the imageName. This option +will not affect the width or height of the image if the user has +specified a non-zero value for the -width or -height +configuration option, respectively. +

    -to x y
    +Specifies the coordinates of the top-left corner of the region of +imageName into which data from filename are to be read. +The default is (0,0). +

    +

    imageName redither
    +The dithering algorithm used in displaying photo images propagates +quantization errors from one pixel to its neighbors. +If the image data for imageName is supplied in pieces, the +dithered image may not be exactly correct. Normally the difference is +not noticeable, but if it is a problem, this command can be used to +recalculate the dithered image in each window where the image is +displayed. +

    imageName write filename ?option value(s) ...?
    +Writes image data from imageName to a file named filename. +The following options may be specified: +

    +

    +

    -background color
    +If the color is specified, the data will not contain any transparency +information. In all transparent pixels the color will be replaced by +the specified color. +

    -format format-name
    +Specifies the name of the image file format handler to be used to +write the data to the file. Specifically, this subcommand searches +for the first handler whose name matches a initial substring of +format-name and which has the capability to write an image +file. If this option is not given, this subcommand uses the first +handler that has the capability to write an image file. +

    -from x1 y1 x2 y2
    +Specifies a rectangular region of imageName to be written to the +image file. If only x1 and y1 are specified, the region +extends from (x1,y1) to the bottom-right corner of +imageName. If all four coordinates are given, they specify +diagonally opposite corners of the rectangular region. The default, +if this option is not given, is the whole image. +

    -grayscale
    +If this options is specified, the data will not contain color +information. All pixel data will be transformed into grayscale. +

    +

    +

    IMAGE FORMATS

    +The photo image code is structured to allow handlers for additional +image file formats to be added easily. The photo image code maintains +a list of these handlers. Handlers are added to the list by +registering them with a call to Tk_CreatePhotoImageFormat. The +standard Tk distribution comes with handlers for PPM/PGM and GIF formats, +which are automatically registered on initialization. +

    +When reading an image file or processing +string data specified with the -data configuration option, the +photo image code invokes each handler in turn until one is +found that claims to be able to read the data in the file or string. +Usually this will find the correct handler, but if it doesn't, the +user may give a format name with the -format option to specify +which handler to use. In fact the photo image code will try those +handlers whose names begin with the string specified for the +-format option (the comparison is case-insensitive). For +example, if the user specifies -format gif, then a handler +named GIF87 or GIF89 may be invoked, but a handler +named JPEG may not (assuming that such handlers had been +registered). +

    +When writing image data to a file, the processing of the +-format option is slightly different: the string value given +for the -format option must begin with the complete name of the +requested handler, and may contain additional information following +that, which the handler can use, for example, to specify which variant +to use of the formats supported by the handler. + +

    COLOR ALLOCATION

    +When a photo image is displayed in a window, the photo image code +allocates colors to use to display the image and dithers the image, if +necessary, to display a reasonable approximation to the image using +the colors that are available. The colors are allocated as a color +cube, that is, the number of colors allocated is the product of the +number of shades of red, green and blue. +

    +Normally, the number of +colors allocated is chosen based on the depth of the window. For +example, in an 8-bit PseudoColor window, the photo image code will +attempt to allocate seven shades of red, seven shades of green and +four shades of blue, for a total of 198 colors. In a 1-bit StaticGray +(monochrome) window, it will allocate two colors, black and white. In +a 24-bit DirectColor or TrueColor window, it will allocate 256 shades +each of red, green and blue. Fortunately, because of the way that +pixel values can be combined in DirectColor and TrueColor windows, +this only requires 256 colors to be allocated. If not all of the +colors can be allocated, the photo image code reduces the number of +shades of each primary color and tries again. +

    +The user can exercise some control over the number of colors that a +photo image uses with the -palette configuration option. If +this option is used, it specifies the maximum number of shades of +each primary color to try to allocate. It can also be used to force +the image to be displayed in shades of gray, even on a color display, +by giving a single number rather than three numbers separated by +slashes. + +

    CREDITS

    +The photo image type was designed and implemented by Paul Mackerras, +based on his earlier photo widget and some suggestions from +John Ousterhout. + +

    KEYWORDS

    +photo, image, color +
    +Copyright © 1994 The Australian National University
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/place.htm b/hlp/en/tk/place.htm new file mode 100644 index 0000000..079a556 --- /dev/null +++ b/hlp/en/tk/place.htm @@ -0,0 +1,240 @@ +Built-In Commands - place manual page +
    +
    NAME +
    place - Geometry manager for fixed or rubber-sheet placement
    +
    SYNOPSIS +
    +
    place window option value ?option value ...? +
    place configure window option value ?option value ...? +
    place forget window +
    place info window +
    place slaves window +
    +
    DESCRIPTION +
    +
    -in master +
    -x location +
    -relx location +
    -y location +
    -rely location +
    -anchor where +
    -width size +
    -relwidth size +
    -height size +
    -relheight size +
    -bordermode mode +
    +
    FINE POINTS +
    KEYWORDS +

    +

    NAME

    +place - Geometry manager for fixed or rubber-sheet placement +

    SYNOPSIS

    +place window option value ?option value ...?
    +place configure window option value ?option value ...?
    +place forget window
    +place info window
    +place slaves window
    +

    DESCRIPTION

    +The placer is a geometry manager for Tk. +It provides simple fixed placement of windows, where you specify +the exact size and location of one window, called the slave, +within another window, called the master. +The placer also provides rubber-sheet placement, where you specify the +size and location of the slave in terms of the dimensions of +the master, so that the slave changes size and location +in response to changes in the size of the master. +Lastly, the placer allows you to mix these styles of placement so +that, for example, the slave has a fixed width and height but is +centered inside the master. +

    +If the first argument to the place command is a window path +name or configure then the command arranges for the placer +to manage the geometry of a slave whose path name is window. +The remaining arguments consist of one or more option-value +pairs that specify the way in which window's +geometry is managed. +If the placer is already managing window, then the +option-value pairs modify the configuration for window. +In this form the place command returns an empty string as result. +The following option-value pairs are supported: +

    +

    +

    -in master
    +Master specifes the path name of the window relative +to which window is to be placed. +Master must either be window's parent or a descendant +of window's parent. +In addition, master and window must both be descendants +of the same top-level window. +These restrictions are necessary to guarantee +that window is visible whenever master is visible. +If this option isn't specified then the master defaults to +window's parent. +

    -x location
    +Location specifies the x-coordinate within the master window +of the anchor point for window. +The location is specified in screen units (i.e. any of the forms +accepted by Tk_GetPixels) and need not lie within the bounds +of the master window. +

    -relx location
    +Location specifies the x-coordinate within the master window +of the anchor point for window. +In this case the location is specified in a relative fashion +as a floating-point number: 0.0 corresponds to the left edge +of the master and 1.0 corresponds to the right edge of the master. +Location need not be in the range 0.0-1.0. +If both -x and -relx are specified for a slave +then their values are summed. For example, -relx 0.5 -x -2 +positions the left edge of the slave 2 pixels to the left of the +center of its master. +

    -y location
    +Location specifies the y-coordinate within the master window +of the anchor point for window. +The location is specified in screen units (i.e. any of the forms +accepted by Tk_GetPixels) and need not lie within the bounds +of the master window. +

    -rely location
    +Location specifies the y-coordinate within the master window +of the anchor point for window. +In this case the value is specified in a relative fashion +as a floating-point number: 0.0 corresponds to the top edge +of the master and 1.0 corresponds to the bottom edge of the master. +Location need not be in the range 0.0-1.0. +If both -y and -rely are specified for a slave +then their values are summed. For example, -rely 0.5 -x 3 +positions the top edge of the slave 3 pixels below the +center of its master. +

    -anchor where
    +Where specifies which point of window is to be positioned +at the (x,y) location selected by the -x, -y, +-relx, and -rely options. +The anchor point is in terms of the outer area of window +including its border, if any. +Thus if where is se then the lower-right corner of +window's border will appear at the given (x,y) location +in the master. +The anchor position defaults to nw. +

    -width size
    +Size specifies the width for window in screen units +(i.e. any of the forms accepted by Tk_GetPixels). +The width will be the outer width of window including its +border, if any. +If size is an empty string, or if no -width +or -relwidth option is specified, then the width requested +internally by the window will be used. +

    -relwidth size
    +Size specifies the width for window. +In this case the width is specified as a floating-point number +relative to the width of the master: 0.5 means window will +be half as wide as the master, 1.0 means window will have +the same width as the master, and so on. +If both -width and -relwidth are specified for a slave, +their values are summed. For example, -relwidth 1.0 -width 5 +makes the slave 5 pixels wider than the master. +

    -height size
    +Size specifies the height for window in screen units +(i.e. any of the forms accepted by Tk_GetPixels). +The height will be the outer dimension of window including its +border, if any. +If size is an empty string, or if no -height or +-relheight option is specified, then the height requested +internally by the window will be used. +

    -relheight size
    +Size specifies the height for window. +In this case the height is specified as a floating-point number +relative to the height of the master: 0.5 means window will +be half as high as the master, 1.0 means window will have +the same height as the master, and so on. +If both -height and -relheight are specified for a slave, +their values are summed. For example, -relheight 1.0 -height -2 +makes the slave 2 pixels shorter than the master. +

    -bordermode mode
    +Mode determines the degree to which borders within the +master are used in determining the placement of the slave. +The default and most common value is inside. +In this case the placer considers the area of the master to +be the innermost area of the master, inside any border: +an option of -x 0 corresponds to an x-coordinate just +inside the border and an option of -relwidth 1.0 +means window will fill the area inside the master's +border. +If mode is outside then the placer considers +the area of the master to include its border; +this mode is typically used when placing window +outside its master, as with the options -x 0 -y 0 -anchor ne. +Lastly, mode may be specified as ignore, in which +case borders are ignored: the area of the master is considered +to be its official X area, which includes any internal border but +no external border. A bordermode of ignore is probably +not very useful. +

    +

    +If the same value is specified separately with +two different options, such as -x and -relx, then +the most recent option is used and the older one is ignored. +

    +The place slaves command returns a list of all the slave +windows for which window is the master. +If there are no slaves for window then an empty string is +returned. +

    +The place forget command causes the placer to stop managing +the geometry of window. As a side effect of this command +window will be unmapped so that it doesn't appear on the +screen. +If window isn't currently managed by the placer then the +command has no effect. +Place forget returns an empty string as result. +

    +The place info command returns a list giving the current +configuration of window. +The list consists of option-value pairs in exactly the +same form as might be specified to the place configure +command. +If the configuration of a window has been retrieved with +place info, that configuration can be restored later by +first using place forget to erase any existing information +for the window and then invoking place configure with +the saved information. + +

    FINE POINTS

    +It is not necessary for the master window to be the parent +of the slave window. +This feature is useful in at least two situations. +First, for complex window layouts it means you can create a +hierarchy of subwindows whose only purpose +is to assist in the layout of the parent. +The ``real children'' of the parent (i.e. the windows that +are significant for the application's user interface) can be +children of the parent yet be placed inside the windows +of the geometry-management hierarchy. +This means that the path names of the ``real children'' +don't reflect the geometry-management hierarchy and users +can specify options for the real children +without being aware of the structure of the geometry-management +hierarchy. +

    +A second reason for having a master different than the slave's +parent is to tie two siblings together. +For example, the placer can be used to force a window always to +be positioned centered just below one of its +siblings by specifying the configuration +

    -in sibling -relx 0.5 -rely 1.0 -anchor n -bordermode outside
    +Whenever the sibling is repositioned in the future, the slave +will be repositioned as well. +

    +Unlike many other geometry managers (such as the packer) +the placer does not make any attempt to manipulate the geometry of +the master windows or the parents of slave windows (i.e. it doesn't +set their requested sizes). +To control the sizes of these windows, make them windows like +frames and canvases that provide configuration options for this purpose. + +

    KEYWORDS

    +geometry manager, height, location, master, place, rubber sheet, slave, width +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/popup.htm b/hlp/en/tk/popup.htm new file mode 100644 index 0000000..3040424 --- /dev/null +++ b/hlp/en/tk/popup.htm @@ -0,0 +1,23 @@ +Tk Built-In Commands - tk_popup manual page +

    NAME

    +tk_popup - Post a popup menu +

    SYNOPSIS

    +tk_popup menu x y ?entry?
    +

    DESCRIPTION

    +This procedure posts a menu at a given position on the screen and +configures Tk so that the menu and its cascaded children can be +traversed with the mouse or the keyboard. +Menu is the name of a menu widget and x and y +are the root coordinates at which to display the menu. +If entry is omitted or an empty string, the +menu's upper left corner is positioned at the given point. +Otherwise entry gives the index of an entry in menu and +the menu will be positioned so that the entry is positioned over +the given point. + +

    KEYWORDS

    +menu, popup +
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/radiobutton.htm b/hlp/en/tk/radiobutton.htm new file mode 100644 index 0000000..d8f34d5 --- /dev/null +++ b/hlp/en/tk/radiobutton.htm @@ -0,0 +1,311 @@ +Tk Built-In Commands - radiobutton manual page +
    +
    NAME +
    radiobutton - Create and manipulate radiobutton widgets
    +
    SYNOPSIS +
    +
    radiobutton pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -command, command, Command +
    -height, height, Height +
    -indicatoron, indicatorOn, IndicatorOn +
    -selectcolor, selectColor, Background +
    -selectimage, selectImage, SelectImage +
    -state, state, State +
    -value, value, Value +
    -variable, variable, Variable +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName deselect +
    pathName flash +
    pathName invoke +
    pathName select +
    +
    BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +radiobutton - Create and manipulate radiobutton widgets +

    SYNOPSIS

    +radiobuttonpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -command +
    Database Name: command +
    Database Class: Command +
    Specifies a Tcl command to associate with the button. This command +is typically invoked when mouse button 1 is released over the button +window. The button's global variable (-variable option) will +be updated before the command is invoked. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the button. +If an image or bitmap is being displayed in the button then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the button's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -indicatoron +
    Database Name: indicatorOn +
    Database Class: IndicatorOn +
    Specifies whether or not the indicator should be drawn. Must be a +proper boolean value. If false, the relief option is +ignored and the widget's relief is always sunken if the widget is +selected and raised otherwise. +

    Command-Line Name: -selectcolor +
    Database Name: selectColor +
    Database Class: Background +
    Specifies a background color to use when the button is selected. +If indicatorOn is true then the color applies to the indicator. +Under Windows, this color is used as the background for the indicator +regardless of the select state. +If indicatorOn is false, this color is used as the background +for the entire widget, in place of background or activeBackground, +whenever the widget is selected. +If specified as an empty string then no special color is used for +displaying when the widget is selected. +

    Command-Line Name: -selectimage +
    Database Name: selectImage +
    Database Class: SelectImage +
    Specifies an image to display (in place of the image option) +when the radiobutton is selected. +This option is ignored unless the image option has been +specified. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the radiobutton: normal, active, +or disabled. In normal state the radiobutton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the radiobutton. In active state +the radiobutton is displayed using the activeForeground and +activeBackground options. Disabled state means that the radiobutton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the radiobutton is displayed. +

    Command-Line Name: -value +
    Database Name: value +
    Database Class: Value +
    Specifies value to store in the button's associated variable whenever +this button is selected. +

    Command-Line Name: -variable +
    Database Name: variable +
    Database Class: Variable +
    Specifies name of global variable to set whenever this button is +selected. Changes in this variable also cause the button to select +or deselect itself. +Defaults to the value selectedButton. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the button. +If an image or bitmap is being displayed in the button, the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the button's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    DESCRIPTION

    +The radiobutton command creates a new window (given by the +pathName argument) and makes it into a radiobutton widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the radiobutton such as its colors, font, +text, and initial relief. The radiobutton command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A radiobutton is a widget that displays a textual string, bitmap or image +and a diamond or circle called an indicator. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. A radiobutton has +all of the behavior of a simple button: it can display itself in either +of three different ways, according to the state option; +it can be made to appear +raised, sunken, or flat; it can be made to flash; and it invokes +a Tcl command whenever mouse button 1 is clicked over the +check button. +

    +In addition, radiobuttons can be selected. +If a radiobutton is selected, the indicator is normally +drawn with a selected appearance, and +a Tcl variable associated with the radiobutton is set to a particular +value (normally 1). +Under Unix, the indicator is drawn with a sunken relief and a special +color. Under Windows, the indicator is drawn with a round mark inside. +If the radiobutton is not selected, then the indicator is drawn with a +deselected appearance, and the associated variable is +set to a different value (typically 0). +Under Unix, the indicator is drawn with a raised relief and no special +color. Under Windows, the indicator is drawn without a round mark inside. +Typically, several radiobuttons share a single variable and the +value of the variable indicates which radiobutton is to be selected. +When a radiobutton is selected it sets the value of the variable to +indicate that fact; each radiobutton also monitors the value of +the variable and automatically selects and deselects itself when the +variable's value changes. +By default the variable selectedButton +is used; its contents give the name of the button that is +selected, or the empty string if no button associated with that +variable is selected. +The name of the variable for a radiobutton, +plus the variable to be stored into it, may be modified with options +on the command line or in the option database. +Configuration options may also be used to modify the way the +indicator is displayed (or whether it is displayed at all). +By default a radiobutton is configured to select itself on button clicks. + +

    WIDGET COMMAND

    +The radiobutton command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for radiobutton widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the radiobutton +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the radiobutton +command. +

    pathName deselect
    +Deselects the radiobutton and sets the associated variable to an +empty string. +If this radiobutton was not currently selected, the command has +no effect. +

    pathName flash
    +Flashes the radiobutton. This is accomplished by redisplaying the radiobutton +several times, alternating between active and normal colors. At +the end of the flash the radiobutton is left in the same normal/active +state as when the command was invoked. +This command is ignored if the radiobutton's state is disabled. +

    pathName invoke
    +Does just what would have happened if the user invoked the radiobutton +with the mouse: selects the button and invokes +its associated Tcl command, if there is one. +The return value is the return value from the Tcl command, or an +empty string if there is no command associated with the radiobutton. +This command is ignored if the radiobutton's state is disabled. +

    pathName select
    +Selects the radiobutton and sets the associated variable to the +value corresponding to this widget. + +

    +

    BINDINGS

    +Tk automatically creates class bindings for radiobuttons that give them +the following default behavior: +

    +

    +

    [1]
    +On Unix systems, a radiobutton activates whenever the mouse passes +over it and deactivates whenever the mouse leaves the radiobutton. On +Mac and Windows systems, when mouse button 1 is pressed over a +radiobutton, the button activates whenever the mouse pointer is inside +the button, and deactivates whenever the mouse pointer leaves the +button. +

    [2]
    +When mouse button 1 is pressed over a radiobutton it is invoked (it +becomes selected and the command associated with the button is +invoked, if there is one). +

    [3]
    +When a radiobutton has the input focus, the space key causes the radiobutton +to be invoked. +

    +

    +If the radiobutton's state is disabled then none of the above +actions occur: the radiobutton is completely non-responsive. +

    +The behavior of radiobuttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +radiobutton, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/raise.htm b/hlp/en/tk/raise.htm new file mode 100644 index 0000000..8902ebb --- /dev/null +++ b/hlp/en/tk/raise.htm @@ -0,0 +1,27 @@ +Tk Built-In Commands - raise manual page +

    NAME

    +raise - Change a window's position in the stacking order +

    SYNOPSIS

    +raise window ?aboveThis?
    +

    DESCRIPTION

    +If the aboveThis argument is omitted then the command raises +window so that it is above all of its siblings in the stacking +order (it will not be obscured by any siblings and will obscure +any siblings that overlap it). +If aboveThis is specified then it must be the path name of +a window that is either a sibling of window or the descendant +of a sibling of window. +In this case the raise command will insert +window into the stacking order just above aboveThis +(or the ancestor of aboveThis that is a sibling of window); +this could end up either raising or lowering window. + +

    SEE ALSO

    +lower +

    KEYWORDS

    +obscure, raise, stacking order +
    +Copyright © 1990 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/scale.htm b/hlp/en/tk/scale.htm new file mode 100644 index 0000000..ce97c19 --- /dev/null +++ b/hlp/en/tk/scale.htm @@ -0,0 +1,334 @@ +Tk Built-In Commands - scale manual page +
    +
    NAME +
    scale - Create and manipulate scale widgets
    +
    SYNOPSIS +
    +
    scale pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -orient, orient, Orient +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -takefocus, takeFocus, TakeFocus +
    -troughcolor, troughColor, Background +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -bigincrement, bigIncrement, BigIncrement +
    -command, command, Command +
    -digits, digits, Digits +
    -from, from, From +
    -label, label, Label +
    -length, length, Length +
    -resolution, resolution, Resolution +
    -showvalue, showValue, ShowValue +
    -sliderlength, sliderLength, SliderLength +
    -sliderrelief, sliderRelief, SliderRelief +
    -state, state, State +
    -tickinterval, tickInterval, TickInterval +
    -to, to, To +
    -variable, variable, Variable +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName coords ?value? +
    pathName get ?x y? +
    pathName identify x y +
    pathName set value +
    +
    BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +scale - Create and manipulate scale widgets +

    SYNOPSIS

    +scalepathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -orient, orient, Orient +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -takefocus, takeFocus, TakeFocus +
    -troughcolor, troughColor, Background +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -bigincrement +
    Database Name: bigIncrement +
    Database Class: BigIncrement +
    Some interactions with the scale cause its value to change by +``large'' increments; this option specifies the size of the +large increments. If specified as 0, the large increments default +to 1/10 the range of the scale. +

    Command-Line Name: -command +
    Database Name: command +
    Database Class: Command +
    Specifies the prefix of a Tcl command to invoke whenever the scale's +value is changed via a widget command. +The actual command consists +of this option followed by a space and a real number indicating the +new value of the scale. +

    Command-Line Name: -digits +
    Database Name: digits +
    Database Class: Digits +
    An integer specifying how many significant digits should be retained +when converting the value of the scale to a string. +If the number is less than or equal to zero, then the scale picks +the smallest value that guarantees that every possible slider +position prints as a different string. +

    Command-Line Name: -from +
    Database Name: from +
    Database Class: From +
    A real value corresponding to the left or top end of the scale. +

    Command-Line Name: -label +
    Database Name: label +
    Database Class: Label +
    A string to display as a label for the scale. For +vertical scales the label is displayed just to the right of the +top end of the scale. For horizontal scales the label is displayed +just above the left end of the scale. If the option is specified +as an empty string, no label is displayed. +

    Command-Line Name: -length +
    Database Name: length +
    Database Class: Length +
    Specifies the desired long dimension of the scale in screen units +(i.e. any of the forms acceptable to Tk_GetPixels). +For vertical scales this is the scale's height; for horizontal scales +it is the scale's width. +

    Command-Line Name: -resolution +
    Database Name: resolution +
    Database Class: Resolution +
    A real value specifying the resolution for the scale. +If this value is greater than zero then the scale's value will always be +rounded to an even multiple of this value, as will tick marks and +the endpoints of the scale. If the value is less than zero then no +rounding occurs. Defaults to 1 (i.e., the value will be integral). +

    Command-Line Name: -showvalue +
    Database Name: showValue +
    Database Class: ShowValue +
    Specifies a boolean value indicating whether or not the current +value of the scale is to be displayed. +

    Command-Line Name: -sliderlength +
    Database Name: sliderLength +
    Database Class: SliderLength +
    Specfies the size of the slider, measured in screen units along the slider's +long dimension. The value may be specified in any of the forms acceptable +to Tk_GetPixels. +

    Command-Line Name: -sliderrelief +
    Database Name: sliderRelief +
    Database Class: SliderRelief +
    Specifies the relief to use when drawing the slider, such as raised +or sunken. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the scale: normal, +active, or disabled. +If the scale is disabled then the value may not be changed and the scale +won't activate. +If the scale is active, the slider is displayed using the color +specified by the activeBackground option. +

    Command-Line Name: -tickinterval +
    Database Name: tickInterval +
    Database Class: TickInterval +
    Must be a real value. +Determines the spacing between numerical +tick marks displayed below or to the left of the slider. +If 0, no tick marks will be displayed. +

    Command-Line Name: -to +
    Database Name: to +
    Database Class: To +
    Specifies a real value corresponding +to the right or bottom end of the scale. +This value may be either less than or greater than the from option. +

    Command-Line Name: -variable +
    Database Name: variable +
    Database Class: Variable +
    Specifies the name of a global variable to link to the scale. Whenever the +value of the variable changes, the scale will update to reflect this +value. +Whenever the scale is manipulated interactively, the variable +will be modified to reflect the scale's new value. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired narrow dimension of the trough in screen units +(i.e. any of the forms acceptable to Tk_GetPixels). +For vertical scales this is the trough's width; for horizontal scales +this is the trough's height. +
    +

    DESCRIPTION

    +The scale command creates a new window (given by the +pathName argument) and makes it into a scale widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the scale such as its colors, orientation, +and relief. The scale command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A scale is a widget that displays a rectangular trough and a +small slider. The trough corresponds to a range +of real values (determined by the from, to, and +resolution options), +and the position of the slider selects a particular real value. +The slider's position (and hence the scale's value) may be adjusted +with the mouse or keyboard as described in the BINDINGS +section below. Whenever the scale's value is changed, a Tcl +command is invoked (using the command option) to notify +other interested widgets of the change. +In addition, the value +of the scale can be linked to a Tcl variable (using the variable +option), so that changes in either are reflected in the other. +

    +Three annotations may be displayed in a scale widget: a label +appearing at the top right of the widget (top left for horizontal +scales), a number displayed just to the left of the slider +(just above the slider for horizontal scales), and a collection +of numerical tick marks just to the left of the current value +(just below the trough for horizontal scales). Each of these three +annotations may be enabled or disabled using the +configuration options. + +

    WIDGET COMMAND

    +The scale command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for scale widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the scale +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the scale +command. +

    pathName coords ?value?
    +Returns a list whose elements are the x and y coordinates of +the point along the centerline of the trough that corresponds +to value. +If value is omitted then the scale's current value is used. +

    pathName get ?x y?
    +If x and y are omitted, returns the current value +of the scale. If x and y are specified, they give +pixel coordinates within the widget; the command returns +the scale value corresponding to the given pixel. +Only one of x or y is used: for horizontal scales +y is ignored, and for vertical scales x is ignored. +

    pathName identify x y
    +Returns a string indicating what part of the scale lies under +the coordinates given by x and y. +A return value of slider means that the point is over +the slider; trough1 means that the point is over the +portion of the slider above or to the left of the slider; +and trough2 means that the point is over the portion +of the slider below or to the right of the slider. +If the point isn't over one of these elements, an empty string +is returned. +

    pathName set value
    +This command is invoked to change the current value of the scale, +and hence the position at which the slider is displayed. Value +gives the new value for the scale. +The command has no effect if the scale is disabled. + +

    +

    BINDINGS

    +Tk automatically creates class bindings for scales that give them +the following default behavior. +Where the behavior is different for vertical and horizontal scales, +the horizontal behavior is described in parentheses. +

    +

    +

    [1]
    +If button 1 is pressed in the trough, the scale's value will +be incremented or decremented by the value of the resolution +option so that the slider moves in the direction of the cursor. +If the button is held down, the action auto-repeats. +

    [2]
    +If button 1 is pressed over the slider, the slider can be dragged +with the mouse. +

    [3]
    +If button 1 is pressed in the trough with the Control key down, +the slider moves all the way to the end of its range, in the +direction towards the mouse cursor. +

    [4]
    +If button 2 is pressed, the scale's value is set to the mouse +position. If the mouse is dragged with button 2 down, the scale's +value changes with the drag. +

    [5]
    +The Up and Left keys move the slider up (left) by the value +of the resolution option. +

    [6]
    +The Down and Right keys move the slider down (right) by the value +of the resolution option. +

    [7]
    +Control-Up and Control-Left move the slider up (left) by the +value of the bigIncrement option. +

    [8]
    +Control-Down and Control-Right move the slider down (right) by the +value of the bigIncrement option. +

    [9]
    +Home moves the slider to the top (left) end of its range. +

    [10]
    +End moves the slider to the bottom (right) end of its range. +

    +

    +If the scale is disabled using the state option then +none of the above bindings have any effect. +

    +The behavior of scales can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +scale, slider, trough, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/scrollbar.htm b/hlp/en/tk/scrollbar.htm new file mode 100644 index 0000000..4013d77 --- /dev/null +++ b/hlp/en/tk/scrollbar.htm @@ -0,0 +1,414 @@ +Tk Built-In Commands - scrollbar manual page +
    +
    NAME +
    scrollbar - Create and manipulate scrollbar widgets
    +
    SYNOPSIS +
    +
    scrollbar pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -jump, jump, Jump +
    -orient, orient, Orient +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -takefocus, takeFocus, TakeFocus +
    -troughcolor, troughColor, Background +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -activerelief, activeRelief, ActiveRelief +
    -command, command, Command +
    -elementborderwidth, elementBorderWidth, BorderWidth +
    -width, width, Width +
    +
    DESCRIPTION +
    ELEMENTS +
    +
    arrow1 +
    trough1 +
    slider +
    trough2 +
    arrow2 +
    +
    WIDGET COMMAND +
    +
    pathName activate ?element? +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    pathName delta deltaX deltaY +
    pathName fraction x y +
    pathName get +
    pathName identify x y +
    pathName set first last +
    +
    SCROLLING COMMANDS +
    +
    prefix moveto fraction +
    prefix scroll number units +
    prefix scroll number pages +
    +
    OLD COMMAND SYNTAX +
    +
    pathName set totalUnits windowUnits firstUnit lastUnit +
    +
    +
    prefix unit +
    +
    BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +scrollbar - Create and manipulate scrollbar widgets +

    SYNOPSIS

    +scrollbarpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -jump, jump, Jump +
    -orient, orient, Orient +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -takefocus, takeFocus, TakeFocus +
    -troughcolor, troughColor, Background +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -activerelief +
    Database Name: activeRelief +
    Database Class: ActiveRelief +
    Specifies the relief to use when displaying the element that is +active, if any. +Elements other than the active element are always displayed with +a raised relief. +

    Command-Line Name: -command +
    Database Name: command +
    Database Class: Command +
    Specifies the prefix of a Tcl command to invoke to change the view +in the widget associated with the scrollbar. When a user requests +a view change by manipulating the scrollbar, a Tcl command is +invoked. The actual command consists of this option followed by +additional information as described later. This option almost always has +a value such as .t xview or .t yview, consisting of the +name of a widget and either xview (if the scrollbar is for +horizontal scrolling) or yview (for vertical scrolling). +All scrollable widgets have xview and yview commands +that take exactly the additional arguments appended by the scrollbar +as described in SCROLLING COMMANDS below. +

    Command-Line Name: -elementborderwidth +
    Database Name: elementBorderWidth +
    Database Class: BorderWidth +
    Specifies the width of borders drawn around the internal elements +of the scrollbar (the two arrows and the slider). The value may +have any of the forms acceptable to Tk_GetPixels. +If this value is less than zero, the value of the borderWidth +option is used in its place. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired narrow dimension of the scrollbar window, +not including 3-D border, if any. For vertical +scrollbars this will be the width and for horizontal scrollbars +this will be the height. +The value may have any of the forms acceptable to Tk_GetPixels. +
    +

    DESCRIPTION

    +The scrollbar command creates a new window (given by the +pathName argument) and makes it into a scrollbar widget. +Additional options, described above, may be specified on the command +line or in the option database to configure aspects of the scrollbar +such as its colors, orientation, and relief. +The scrollbar command returns its pathName argument. +At the time this command is invoked, there must not exist a window +named pathName, but pathName's parent must exist. +

    +A scrollbar is a widget that displays two arrows, one at each end of +the scrollbar, and a slider in the middle portion of the +scrollbar. +It provides information about what is visible in an associated window +that displays an document of some sort (such as a file being edited or +a drawing). +The position and size of the slider indicate which portion of the +document is visible in the associated window. For example, if the +slider in a vertical scrollbar covers the top third of the area +between the two arrows, it means that the associated window displays +the top third of its document. +

    +Scrollbars can be used to adjust the view in the associated window +by clicking or dragging with the mouse. See the BINDINGS section +below for details. + +

    ELEMENTS

    +A scrollbar displays five elements, which are referred to in the +widget commands for the scrollbar: +

    +

    +

    arrow1
    +The top or left arrow in the scrollbar. +

    trough1
    +The region between the slider and arrow1. +

    slider
    +The rectangle that indicates what is visible in the associated widget. +

    trough2
    +The region between the slider and arrow2. +

    arrow2
    +The bottom or right arrow in the scrollbar. + +

    +

    WIDGET COMMAND

    +The scrollbar command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for scrollbar widgets: +

    +

    +

    pathName activate ?element?
    +Marks the element indicated by element as active, which +causes it to be displayed as specified by the activeBackground +and activeRelief options. +The only element values understood by this command are arrow1, +slider, or arrow2. +If any other value is specified then no element of the scrollbar +will be active. +If element is not specified, the command returns +the name of the element that is currently active, or an empty string +if no element is active. +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the scrollbar +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the scrollbar +command. +

    pathName delta deltaX deltaY
    +Returns a real number indicating the fractional change in +the scrollbar setting that corresponds to a given change +in slider position. For example, if the scrollbar is horizontal, +the result indicates how much the scrollbar setting must change +to move the slider deltaX pixels to the right (deltaY is +ignored in this case). +If the scrollbar is vertical, the result indicates how much the +scrollbar setting must change to move the slider deltaY pixels +down. The arguments and the result may be zero or negative. +

    pathName fraction x y
    +Returns a real number between 0 and 1 indicating where the point +given by x and y lies in the trough area of the scrollbar. +The value 0 corresponds to the top or left of the trough, the +value 1 corresponds to the bottom or right, 0.5 corresponds to +the middle, and so on. +X and y must be pixel coordinates relative to the scrollbar +widget. +If x and y refer to a point outside the trough, the closest +point in the trough is used. +

    pathName get
    +Returns the scrollbar settings in the form of a list whose +elements are the arguments to the most recent set widget command. +

    pathName identify x y
    +Returns the name of the element under the point given by x and +y (such as arrow1), or an empty string if the point does +not lie in any element of the scrollbar. +X and y must be pixel coordinates relative to the scrollbar +widget. +

    pathName set first last
    +This command is invoked by the scrollbar's associated widget to +tell the scrollbar about the current view in the widget. +The command takes two arguments, each of which is a real fraction +between 0 and 1. +The fractions describe the range of the document that is visible in +the associated widget. +For example, if first is 0.2 and last is 0.4, it means +that the first part of the document visible in the window is 20% +of the way through the document, and the last visible part is 40% +of the way through. + +

    +

    SCROLLING COMMANDS

    +When the user interacts with the scrollbar, for example by dragging +the slider, the scrollbar notifies the associated widget that it +must change its view. +The scrollbar makes the notification by evaluating a Tcl command +generated from the scrollbar's -command option. +The command may take any of the following forms. +In each case, prefix is the contents of the +-command option, which usually has a form like .t yview +

    +

    +

    prefix moveto fraction
    +Fraction is a real number between 0 and 1. +The widget should adjust its view so that the point given +by fraction appears at the beginning of the widget. +If fraction is 0 it refers to the beginning of the +document. 1.0 refers to the end of the document, 0.333 +refers to a point one-third of the way through the document, +and so on. +

    prefix scroll number units
    +The widget should adjust its view by number units. +The units are defined in whatever way makes sense for the widget, +such as characters or lines in a text widget. +Number is either 1, which means one unit should scroll off +the top or left of the window, or -1, which means that one unit +should scroll off the bottom or right of the window. +

    prefix scroll number pages
    +The widget should adjust its view by number pages. +It is up to the widget to define the meaning of a page; typically +it is slightly less than what fits in the window, so that there +is a slight overlap between the old and new views. +Number is either 1, which means the next page should +become visible, or -1, which means that the previous page should +become visible. + +

    +

    OLD COMMAND SYNTAX

    +In versions of Tk before 4.0, the set and get widget +commands used a different form. +This form is still supported for backward compatibility, but it +is deprecated. +In the old command syntax, the set widget command has the +following form: +

    +

    +

    pathName set totalUnits windowUnits firstUnit lastUnit
    +In this form the arguments are all integers. +TotalUnits gives the total size of the object being displayed in the +associated widget. The meaning of one unit depends on the associated +widget; for example, in a text editor widget units might +correspond to lines of +text. WindowUnits indicates the total number of units that +can fit in the associated window at one time. FirstUnit +and lastUnit give the indices of the first and last units +currently visible in the associated window (zero corresponds to the +first unit of the object). +

    +

    +Under the old syntax the get widget command returns a list +of four integers, consisting of the totalUnits, windowUnits, +firstUnit, and lastUnit values from the last set +widget command. +

    +The commands generated by scrollbars also have a different form +when the old syntax is being used: +

    +

    +

    prefix unit
    +Unit is an integer that indicates what should appear at +the top or left of the associated widget's window. +It has the same meaning as the firstUnit and lastUnit +arguments to the set widget command. +

    +

    +The most recent set widget command determines whether or not +to use the old syntax. +If it is given two real arguments then the new syntax will be +used in the future, and if it is given four integer arguments then +the old syntax will be used. + +

    BINDINGS

    +Tk automatically creates class bindings for scrollbars that give them +the following default behavior. +If the behavior is different for vertical and horizontal scrollbars, +the horizontal behavior is described in parentheses. + +

    +

    +

    [1]
    +Pressing button 1 over arrow1 causes the view in the +associated widget to shift up (left) by one unit so that the +document appears to move down (right) one unit. +If the button is held down, the action auto-repeats. +

    [2]
    +Pressing button 1 over trough1 causes the view in the +associated widget to shift up (left) by one screenful so that the +document appears to move down (right) one screenful. +If the button is held down, the action auto-repeats. +

    [3]
    +Pressing button 1 over the slider and dragging causes the view +to drag with the slider. +If the jump option is true, then the view doesn't drag along +with the slider; it changes only when the mouse button is released. +

    [4]
    +Pressing button 1 over trough2 causes the view in the +associated widget to shift down (right) by one screenful so that the +document appears to move up (left) one screenful. +If the button is held down, the action auto-repeats. +

    [5]
    +Pressing button 1 over arrow2 causes the view in the +associated widget to shift down (right) by one unit so that the +document appears to move up (left) one unit. +If the button is held down, the action auto-repeats. +

    [6]
    +If button 2 is pressed over the trough or the slider, it sets +the view to correspond to the mouse position; dragging the +mouse with button 2 down causes the view to drag with the mouse. +If button 2 is pressed over one of the arrows, it causes the +same behavior as pressing button 1. +

    [7]
    +If button 1 is pressed with the Control key down, then if the +mouse is over arrow1 or trough1 the view changes +to the very top (left) of the document; if the mouse is over +arrow2 or trough2 the view changes +to the very bottom (right) of the document; if the mouse is +anywhere else then the button press has no effect. +

    [8]
    +In vertical scrollbars the Up and Down keys have the same behavior +as mouse clicks over arrow1 and arrow2, respectively. +In horizontal scrollbars these keys have no effect. +

    [9]
    +In vertical scrollbars Control-Up and Control-Down have the same +behavior as mouse clicks over trough1 and trough2, respectively. +In horizontal scrollbars these keys have no effect. +

    [10]
    +In horizontal scrollbars the Up and Down keys have the same behavior +as mouse clicks over arrow1 and arrow2, respectively. +In vertical scrollbars these keys have no effect. +

    [11]
    +In horizontal scrollbars Control-Up and Control-Down have the same +behavior as mouse clicks over trough1 and trough2, respectively. +In vertical scrollbars these keys have no effect. +

    [12]
    +The Prior and Next keys have the same behavior +as mouse clicks over trough1 and trough2, respectively. +

    [13]
    +The Home key adjusts the view to the top (left edge) of the document. +

    [14]
    +The End key adjusts the view to the bottom (right edge) of the document. + +

    +

    KEYWORDS

    +scrollbar, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/selection.htm b/hlp/en/tk/selection.htm new file mode 100644 index 0000000..3373c13 --- /dev/null +++ b/hlp/en/tk/selection.htm @@ -0,0 +1,130 @@ +Tk Built-In Commands - selection manual page +
    +
    NAME +
    selection - Manipulate the X selection
    +
    SYNOPSIS +
    +
    selection option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    selection clear ?-displayof window? ?-selection selection? +
    selection get ?-displayof window? ?-selection selection? ?-type type? +
    selection handle ?-selection selection? ?-type type? ?-format format? window command +
    selection own ?-displayof window? ?-selection selection? +
    selection own ?-command command? ?-selection selection? window +
    +
    KEYWORDS +

    +

    NAME

    +selection - Manipulate the X selection +

    SYNOPSIS

    +selection option ?arg arg ...?
    +

    DESCRIPTION

    +This command provides a Tcl interface to the X selection mechanism and +implements the full selection functionality described in the +X Inter-Client Communication Conventions Manual (ICCCM). +

    +The first argument to selection determines the format of the +rest of the arguments and the behavior of the command. The following +forms are currently supported: +

    +

    +

    +

    selection clear ?-displayof window? ?-selection selection?
    +If selection exists anywhere on window's display, clear it +so that no window owns the selection anymore. Selection +specifies the X selection that should be cleared, and should be an +atom name such as PRIMARY or CLIPBOARD; see the Inter-Client +Communication Conventions Manual for complete details. +Selection defaults to PRIMARY and window defaults to ``.''. +Returns an empty string. +

    selection get ?-displayof window? ?-selection selection? ?-type type?
    +Retrieves the value of selection from window's display and +returns it as a result. Selection defaults to PRIMARY and +window defaults to ``.''. +Type specifies the form in which the selection is to be returned +(the desired ``target'' for conversion, in ICCCM terminology), and +should be an atom name such as STRING or FILE_NAME; see the +Inter-Client Communication Conventions Manual for complete details. +Type defaults to STRING. The selection owner may choose to +return the selection in any of several different representation +formats, such as STRING, ATOM, INTEGER, etc. (this format is different +than the selection type; see the ICCCM for all the confusing details). +If the selection is returned in a non-string format, such as INTEGER +or ATOM, the selection command converts it to string format as a +collection of fields separated by spaces: atoms are converted to their +textual names, and anything else is converted to hexadecimal integers. +

    selection handle ?-selection selection? ?-type type? ?-format format? window command
    +Creates a handler for selection requests, such that command will +be executed whenever selection is owned by window and +someone attempts to retrieve it in the form given by type +(e.g. type is specified in the selection get command). +Selection defaults to PRIMARY, type defaults to STRING, and +format defaults to STRING. If command is an empty string +then any existing handler for window, type, and +selection is removed. +

    +When selection is requested, window is the selection owner, +and type is the requested type, command will be executed +as a Tcl command with two additional numbers appended to it +(with space separators). +The two additional numbers +are offset and maxChars: offset specifies a starting +character position in the selection and maxChars gives the maximum +number of characters to retrieve. The command should return a value consisting +of at most maxChars of the selection, starting at position +offset. For very large selections (larger than maxChars) +the selection will be retrieved using several invocations of command +with increasing offset values. If command returns a string +whose length is less than maxChars, the return value is assumed to +include all of the remainder of the selection; if the length of +command's result is equal to maxChars then +command will be invoked again, until it eventually +returns a result shorter than maxChars. The value of maxChars +will always be relatively large (thousands of characters). +

    +If command returns an error then the selection retrieval is rejected +just as if the selection didn't exist at all. +

    +The format argument specifies the representation that should be +used to transmit the selection to the requester (the second column of +Table 2 of the ICCCM), and defaults to STRING. If format is +STRING, the selection is transmitted as 8-bit ASCII characters (i.e. +just in the form returned by command). If format is +ATOM, then the return value from command is divided into fields +separated by white space; each field is converted to its atom value, +and the 32-bit atom value is transmitted instead of the atom name. +For any other format, the return value from command is +divided into fields separated by white space and each field is +converted to a 32-bit integer; an array of integers is transmitted +to the selection requester. +

    The format argument is needed only for compatibility with +selection requesters that don't use Tk. If Tk is being +used to retrieve the selection then the value is converted back to +a string at the requesting end, so format is +irrelevant. +

    selection own ?-displayof window? ?-selection selection?
    +

    selection own ?-command command? ?-selection selection? window
    +The first form of selection own returns the path name of the +window in this application that owns selection on the display +containing window, or an empty string if no window in this +application owns the selection. Selection defaults to PRIMARY and +window defaults to ``.''. +

    +

    +The second form of selection own causes window to become +the new owner of selection on window's display, returning +an empty string as result. The existing owner, if any, is notified +that it has lost the selection. +If command is specified, it is a Tcl script to execute when +some other window claims ownership of the selection away from +window. Selection defaults to PRIMARY. + +

    KEYWORDS

    +clear, format, handler, ICCCM, own, selection, target, type +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/send.htm b/hlp/en/tk/send.htm new file mode 100644 index 0000000..51da636 --- /dev/null +++ b/hlp/en/tk/send.htm @@ -0,0 +1,98 @@ +Tk Built-In Commands - send manual page +
    +
    NAME +
    send - Execute a command in a different application
    +
    SYNOPSIS +
    +
    send ?options? app cmd ?arg arg ...? +
    +
    DESCRIPTION +
    +
    -async +
    -displayof pathName +
    - - +
    +
    APPLICATION NAMES +
    DISABLING SENDS +
    SECURITY +
    KEYWORDS +

    +

    NAME

    +send - Execute a command in a different application +

    SYNOPSIS

    +send ?options? app cmd ?arg arg ...?
    +

    DESCRIPTION

    +This command arranges for cmd (and args) to be executed in the +application named by app. It returns the result or +error from that command execution. +App may be the name of any application whose main window is +on the display containing the sender's main window; it need not +be within the same process. +If no arg arguments are present, then the command to be executed is +contained entirely within the cmd argument. If one or +more args are present, they are concatenated to form the +command to be executed, just as for the eval command. +

    +If the initial arguments of the command begin with ``-'' +they are treated as options. The following options are +currently defined: +

    +

    +

    -async
    +Requests asynchronous invocation. In this case the send +command will complete immediately without waiting for cmd +to complete in the target application; no result will be available +and errors in the sent command will be ignored. +If the target application is in the same process as the sending +application then the -async option is ignored. +

    -displayof pathName
    +Specifies that the target application's main window is on the display +of the window given by pathName, instead of the display containing +the application's main window. +

    - -
    +Serves no purpose except to terminate the list of options. This +option is needed only if app could contain a leading ``-'' +character. + +

    +

    APPLICATION NAMES

    +The name of an application is set initially from the name of the +program or script that created the application. +You can query and change the name of an application with the +tk appname command. + +

    DISABLING SENDS

    +If the send command is removed from an application (e.g. +with the command rename send {}) then the application +will not respond to incoming send requests anymore, nor will it +be able to issue outgoing requests. +Communication can be reenabled by invoking the tk appname +command. + +

    SECURITY

    +The send command is potentially a serious security loophole. On Unix, +any application that can connect to your X server can send +scripts to your applications. +These incoming scripts can use Tcl to read and +write your files and invoke subprocesses under your name. +Host-based access control such as that provided by xhost +is particularly insecure, since it allows anyone with an account +on particular hosts to connect to your server, and if disabled it +allows anyone anywhere to connect to your server. +In order to provide at least a small amount of +security, Tk checks the access control being used by the server +and rejects incoming sends unless (a) xhost-style access control +is enabled (i.e. only certain hosts can establish connections) and (b) the +list of enabled hosts is empty. +This means that applications cannot connect to your server unless +they use some other form of authorization +such as that provide by xauth. +Under Windows, send is currently disabled. Most of the +functionality is provided by the dde command instead. +

    KEYWORDS

    +application, dde, name, remote execution, security, send +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/text.htm b/hlp/en/tk/text.htm new file mode 100644 index 0000000..6902825 --- /dev/null +++ b/hlp/en/tk/text.htm @@ -0,0 +1,1768 @@ +Tk Built-In Commands - text manual page +
    +
    NAME +
    text - Create and manipulate text widgets
    +
    SYNOPSIS +
    +
    text pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -height, height, Height +
    -spacing1, spacing1, Spacing1 +
    -spacing2, spacing2, Spacing2 +
    -spacing3, spacing3, Spacing3 +
    -state, state, State +
    -tabs, tabs, Tabs +
    -width, width, Width +
    -wrap, wrap, Wrap +
    +
    DESCRIPTION +
    INDICES +
    +
    line.char +
    @x,y +
    end +
    mark +
    tag.first +
    tag.last +
    pathName +
    .VS +
    +
    +
    + count chars +
    - count chars +
    + count lines +
    - count lines +
    linestart +
    lineend +
    wordstart +
    wordend +
    +
    TAGS +
    +
    -background color +
    -bgstipple bitmap +
    -borderwidth pixels +
    -elide boolean +
    -fgstipple bitmap +
    -font fontName +
    -foreground color +
    -justify justify +
    -lmargin1 pixels +
    -lmargin2 pixels +
    -offset pixels +
    -overstrike boolean +
    -relief relief +
    -rmargin pixels +
    -spacing1 pixels +
    -spacing2 pixels +
    -spacing3 pixels +
    -tabs tabList +
    -underline boolean +
    -wrap mode +
    +
    MARKS +
    EMBEDDED WINDOWS +
    +
    -align where +
    -create script +
    -padx pixels +
    -pady pixels +
    -stretch boolean +
    -window pathName +
    +
    EMBEDDED IMAGES +
    +
    -align where +
    -image image +
    -name ImageName +
    -padx pixels +
    -pady pixels +
    +
    THE SELECTION +
    +
    +
    THE INSERTION CURSOR +
    WIDGET COMMAND +
    +
    pathName bbox index +
    pathName cget option +
    pathName compare index1 op index2 +
    pathName configure ?option? ?value option value ...? +
    pathName debug ?boolean? +
    pathName delete index1 ?index2? +
    pathName dlineinfo index +
    pathName dump ?switches? index1 ?index2? +
    +
    +
    -all +
    -command command +
    -image +
    -mark +
    -tag +
    -text +
    -window +
    +
    +
    pathName get index1 ?index2? +
    pathName image option ?arg arg ...? +
    +
    pathName image cget index option +
    pathName image configure index ?option value ...? +
    pathName image create index ?option value ...? +
    pathName image names +
    +
    pathName index index +
    pathName insert index chars ?tagList chars tagList ...? +
    pathName mark option ?arg arg ...? +
    +
    pathName mark gravity markName ?direction? +
    pathName mark names +
    pathName mark next index +
    pathName mark previous index +
    pathName mark set markName index +
    pathName mark unset markName ?markName markName ...? +
    +
    pathName scan option args +
    +
    pathName scan mark x y +
    pathName scan dragto x y +
    +
    pathName search ?switches? pattern index ?stopIndex? +
    +
    -forwards +
    -backwards +
    -exact +
    -regexp +
    -nocase +
    -count varName +
    -elide +
    - - +
    +
    pathName see index +
    pathName tag option ?arg arg ...? +
    +
    pathName tag add tagName index1 ?index2 index1 index2 ...? +
    pathName tag bind tagName ?sequence? ?script? +
    pathName tag cget tagName option +
    pathName tag configure tagName ?option? ?value? ?option value ...? +
    pathName tag delete tagName ?tagName ...? +
    pathName tag lower tagName ?belowThis? +
    pathName tag names ?index? +
    pathName tag nextrange tagName index1 ?index2? +
    pathName tag prevrange tagName index1 ?index2? +
    pathName tag raise tagName ?aboveThis? +
    pathName tag ranges tagName +
    pathName tag remove tagName index1 ?index2 index1 index2 ...? +
    +
    pathName window option ?arg arg ...? +
    +
    pathName window cget index option +
    pathName window configure index ?option value ...? +
    pathName window create index ?option value ...? +
    pathName window names +
    +
    pathName xview option args +
    +
    pathName xview +
    pathName xview moveto fraction +
    pathName xview scroll number what +
    +
    pathName yview ?args? +
    +
    pathName yview +
    pathName yview moveto fraction +
    pathName yview scroll number what +
    pathName yview ?-pickplace? index +
    +
    +
    pathName yview number +
    +
    +
    BINDINGS +
    +
    +
    PERFORMANCE ISSUES +
    KEYWORDS +

    +

    NAME

    +text - Create and manipulate text widgets +

    SYNOPSIS

    +textpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -background or -bg, background, Background +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies the desired height for the window, in units of characters +in the font given by the -font option. +Must be at least one. +

    Command-Line Name: -spacing1 +
    Database Name: spacing1 +
    Database Class: Spacing1 +
    Requests additional space above each text line in the widget, +using any of the standard forms for screen distances. +If a line wraps, this option only applies to the first line +on the display. +This option may be overriden with -spacing1 options in +tags. +

    Command-Line Name: -spacing2 +
    Database Name: spacing2 +
    Database Class: Spacing2 +
    For lines that wrap (so that they cover more than one line on the +display) this option specifies additional space to provide between +the display lines that represent a single line of text. +The value may have any of the standard forms for screen distances. +This option may be overriden with -spacing2 options in +tags. +

    Command-Line Name: -spacing3 +
    Database Name: spacing3 +
    Database Class: Spacing3 +
    Requests additional space below each text line in the widget, +using any of the standard forms for screen distances. +If a line wraps, this option only applies to the last line +on the display. +This option may be overriden with -spacing3 options in +tags. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of two states for the text: normal or disabled. +If the text is disabled then characters may not be inserted or deleted +and no insertion cursor will be displayed, even if the input focus is +in the widget. +

    Command-Line Name: -tabs +
    Database Name: tabs +
    Database Class: Tabs +
    Specifies a set of tab stops for the window. The option's value consists +of a list of screen distances giving the positions of the tab stops. Each +position may optionally be followed in the next list element +by one of the keywords left, right, center, +or numeric, which specifies how to justify +text relative to the tab stop. Left is the default; it causes +the text following the tab character to be positioned with its left edge +at the tab position. Right means that the right edge of the text +following the tab character is positioned at the tab position, and +center means that the text is centered at the tab position. +Numeric means that the decimal point in the text is positioned +at the tab position; if there is no decimal point then the least +significant digit of the number is positioned just to the left of the +tab position; if there is no number in the text then the text is +right-justified at the tab position. +For example, -tabs {2c left 4c 6c center} creates three +tab stops at two-centimeter intervals; the first two use left +justification and the third uses center justification. +If the list of tab stops does not have enough elements to cover all +of the tabs in a text line, then Tk extrapolates new tab stops using +the spacing and alignment from the last tab stop in the list. +The value of the tabs option may be overridden by -tabs +options in tags. +If no -tabs option is specified, or if it is specified as +an empty list, then Tk uses default tabs spaced every eight +(average size) characters. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired width for the window in units of characters +in the font given by the -font option. +If the font doesn't have a uniform width then the width of the +character ``0'' is used in translating from character units to +screen units. +

    Command-Line Name: -wrap +
    Database Name: wrap +
    Database Class: Wrap +
    Specifies how to handle lines in the text that are too long to be +displayed in a single line of the text's window. +The value must be none or char or word. +A wrap mode of none means that each line of text appears as +exactly one line on the screen; extra characters that don't fit +on the screen are not displayed. +In the other modes each line of text will be broken up into several +screen lines if necessary to keep all the characters visible. +In char mode a screen line break may occur after any character; +in word mode a line break will only be made at word boundaries. +
    +

    DESCRIPTION

    +The text command creates a new window (given by the +pathName argument) and makes it into a text widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the text such as its default background color +and relief. The text command returns the +path name of the new window. +

    +A text widget displays one or more lines of text and allows that +text to be edited. +Text widgets support four different kinds of annotations on the +text, called tags, marks, embedded windows or embedded images. +Tags allow different portions of the text +to be displayed with different fonts and colors. +In addition, Tcl commands can be associated with tags so +that scripts are invoked when particular actions such as keystrokes +and mouse button presses occur in particular ranges of the text. +See TAGS below for more details. +

    +The second form of annotation consists of marks, which are floating +markers in the text. +Marks are used to keep track of various interesting positions in the +text as it is edited. +See MARKS below for more details. +

    +The third form of annotation allows arbitrary windows to be +embedded in a text widget. +See EMBEDDED WINDOWS below for more details. +

    +The fourth form of annotation allows Tk images to be embedded in a text +widget. +See EMBEDDED IMAGES below for more details. + +

    INDICES

    +Many of the widget commands for texts take one or more indices +as arguments. +An index is a string used to indicate a particular place within +a text, such as a place to insert characters or one endpoint of a +range of characters to delete. +Indices have the syntax +
    base modifier modifier modifier ...
    +Where base gives a starting point and the modifiers +adjust the index from the starting point (e.g. move forward or +backward one character). Every index must contain a base, +but the modifiers are optional. +

    +The base for an index must have one of the following forms: +

    +

    +

    line.char
    +Indicates char'th character on line line. +Lines are numbered from 1 for consistency with other UNIX programs +that use this numbering scheme. +Within a line, characters are numbered from 0. +If char is end then it refers to the newline character +that ends the line. +

    @x,y
    +Indicates the character that covers the pixel whose x and y coordinates +within the text's window are x and y. +

    end
    +Indicates the end of the text (the character just after the last +newline). +

    mark
    +Indicates the character just after the mark whose name is mark. +

    tag.first
    +Indicates the first character in the text that has been tagged with +tag. +This form generates an error if no characters are currently tagged +with tag. +

    tag.last
    +Indicates the character just after the last one in the text that has +been tagged with tag. +This form generates an error if no characters are currently tagged +with tag. +

    pathName
    +Indicates the position of the embedded window whose name is +pathName. +This form generates an error if there is no embedded window +by the given name. +

    .VS
    +imageName +Indicates the position of the embedded image whose name is +imageName. +This form generates an error if there is no embedded image +by the given name. +

    +

    +If the base could match more than one of the above forms, such +as a mark and imageName both having the same value, then +the form earlier in the above list takes precedence. +If modifiers follow the base index, each one of them must have one +of the forms listed below. Keywords such as chars and wordend +may be abbreviated as long as the abbreviation is unambiguous. +

    +

    +

    + count chars
    +Adjust the index forward by count characters, moving to later +lines in the text if necessary. If there are fewer than count +characters in the text after the current index, then set the index +to the last character in the text. +Spaces on either side of count are optional. +

    - count chars
    +Adjust the index backward by count characters, moving to earlier +lines in the text if necessary. If there are fewer than count +characters in the text before the current index, then set the index +to the first character in the text. +Spaces on either side of count are optional. +

    + count lines
    +Adjust the index forward by count lines, retaining the same +character position within the line. If there are fewer than count +lines after the line containing the current index, then set the index +to refer to the same character position on the last line of the text. +Then, if the line is not long enough to contain a character at the indicated +character position, adjust the character position to refer to the last +character of the line (the newline). +Spaces on either side of count are optional. +

    - count lines
    +Adjust the index backward by count lines, retaining the same +character position within the line. If there are fewer than count +lines before the line containing the current index, then set the index +to refer to the same character position on the first line of the text. +Then, if the line is not long enough to contain a character at the indicated +character position, adjust the character position to refer to the last +character of the line (the newline). +Spaces on either side of count are optional. +

    linestart
    +Adjust the index to refer to the first character on the line. +

    lineend
    +Adjust the index to refer to the last character on the line (the newline). +

    wordstart
    +Adjust the index to refer to the first character of the word containing +the current index. A word consists of any number of adjacent characters +that are letters, digits, or underscores, or a single character that +is not one of these. +

    wordend
    +Adjust the index to refer to the character just after the last one of the +word containing the current index. If the current index refers to the last +character of the text then it is not modified. +

    +

    +If more than one modifier is present then they are applied in +left-to-right order. For example, the index ``end - 1 chars'' +refers to the next-to-last character in the text and +``insert wordstart - 1 c'' refers to the character just before +the first one in the word containing the insertion cursor. + +

    TAGS

    +The first form of annotation in text widgets is a tag. +A tag is a textual string that is associated with some of the characters +in a text. +Tags may contain arbitrary characters, but it is probably best to +avoid using the the characters `` '' (space), +, or -: +these characters have special meaning in indices, so tags containing +them can't be used as indices. +There may be any number of tags associated with characters in a +text. +Each tag may refer to a single character, a range of characters, or +several ranges of characters. +An individual character may have any number of tags associated with it. +

    +A priority order is defined among tags, and this order is used in +implementing some of the tag-related functions described below. +When a tag is defined (by associating it with characters or setting +its display options or binding commands to it), it is given +a priority higher than any existing tag. +The priority order of tags may be redefined using the +``pathName tag raise'' and ``pathName tag lower'' +widget commands. +

    +Tags serve three purposes in text widgets. +First, they control the way information is displayed on the screen. +By default, characters are displayed as determined by the +background, font, and foreground options for the +text widget. +However, display options may be associated with individual tags +using the ``pathName tag configure'' widget command. +If a character has been tagged, then the display options associated +with the tag override the default display style. +The following options are currently supported for tags: +

    +

    +

    -background color
    +Color specifies the background color to use for characters +associated with the tag. +It may have any of the forms accepted by Tk_GetColor. +

    -bgstipple bitmap
    +Bitmap specifies a bitmap that is used as a stipple pattern +for the background. +It may have any of the forms accepted by Tk_GetBitmap. +If bitmap hasn't been specified, or if it is specified +as an empty string, then a solid fill will be used for the +background. +

    -borderwidth pixels
    +Pixels specifies the width of a 3-D border to draw around +the background. +It may have any of the forms accepted by Tk_GetPixels. +This option is used in conjunction with the -relief +option to give a 3-D appearance to the background for characters; +it is ignored unless the -background option +has been set for the tag. +

    -elide boolean
    +Elide specifies whether the data should be elided. +Elided data is not displayed and takes no space on screen, but further +on behaves just as normal data. +

    -fgstipple bitmap
    +Bitmap specifies a bitmap that is used as a stipple pattern +when drawing text and other foreground information such as +underlines. +It may have any of the forms accepted by Tk_GetBitmap. +If bitmap hasn't been specified, or if it is specified +as an empty string, then a solid fill will be used. +

    -font fontName
    +FontName is the name of a font to use for drawing characters. +It may have any of the forms accepted by Tk_GetFont. +

    -foreground color
    +Color specifies the color to use when drawing text and other +foreground information such as underlines. +It may have any of the forms accepted by Tk_GetColor. +

    -justify justify
    +If the first character of a display line has a tag for which this +option has been specified, then justify determines how to +justify the line. +It must be one of left, right, or center. +If a line wraps, then the justification for each line on the +display is determined by the first character of that display line. +

    -lmargin1 pixels
    +If the first character of a text line has a tag for which this +option has been specified, then pixels specifies how +much the line should be indented from the left edge of the +window. +Pixels may have any of the standard forms for screen +distances. +If a line of text wraps, this option only applies to the +first line on the display; the -lmargin2 option controls +the indentation for subsequent lines. +

    -lmargin2 pixels
    +If the first character of a display line has a tag for which this +option has been specified, and if the display line is not the +first for its text line (i.e., the text line has wrapped), then +pixels specifies how much the line should be indented from +the left edge of the window. +Pixels may have any of the standard forms for screen +distances. +This option is only used when wrapping is enabled, and it only +applies to the second and later display lines for a text line. +

    -offset pixels
    +Pixels specifies an amount by which the text's baseline +should be offset vertically from the baseline of the overall +line, in pixels. +For example, a positive offset can be used for superscripts +and a negative offset can be used for subscripts. +Pixels may have any of the standard forms for screen +distances. +

    -overstrike boolean
    +Specifies whether or not to draw a horizontal rule through +the middle of characters. +Boolean may have any of the forms accepted by Tk_GetBoolean. +

    -relief relief
    +Relief specifies the 3-D relief to use for drawing backgrounds, +in any of the forms accepted by Tk_GetRelief. +This option is used in conjunction with the -borderwidth +option to give a 3-D appearance to the background for characters; +it is ignored unless the -background option +has been set for the tag. +

    -rmargin pixels
    +If the first character of a display line has a tag for which this +option has been specified, then pixels specifies how wide +a margin to leave between the end of the line and the right +edge of the window. +Pixels may have any of the standard forms for screen +distances. +This option is only used when wrapping is enabled. +If a text line wraps, the right margin for each line on the +display is determined by the first character of that display +line. +

    -spacing1 pixels
    +Pixels specifies how much additional space should be +left above each text line, using any of the standard forms for +screen distances. +If a line wraps, this option only applies to the first +line on the display. +

    -spacing2 pixels
    +For lines that wrap, this option specifies how much additional +space to leave between the display lines for a single text line. +Pixels may have any of the standard forms for screen +distances. +

    -spacing3 pixels
    +Pixels specifies how much additional space should be +left below each text line, using any of the standard forms for +screen distances. +If a line wraps, this option only applies to the last +line on the display. +

    -tabs tabList
    +TabList specifies a set of tab stops in the same form +as for the -tabs option for the text widget. This +option only applies to a display line if it applies to the +first character on that display line. +If this option is specified as an empty string, it cancels +the option, leaving it unspecified for the tag (the default). +If the option is specified as a non-empty string that is +an empty list, such as -tags { }, then it requests +default 8-character tabs as described for the tags +widget option. +

    -underline boolean
    +Boolean specifies whether or not to draw an underline underneath +characters. +It may have any of the forms accepted by Tk_GetBoolean. +

    -wrap mode
    +Mode specifies how to handle lines that are wider than the +text's window. +It has the same legal values as the -wrap option +for the text widget: none, char, or word. +If this tag option is specified, it overrides the -wrap option +for the text widget. +

    +

    +If a character has several tags associated with it, and if their +display options conflict, then the options of the highest priority +tag are used. +If a particular display option hasn't been specified for a +particular tag, or if it is specified as an empty string, then +that option will never be used; the next-highest-priority +tag's option will used instead. +If no tag specifies a particular display option, then the default +style for the widget will be used. +

    +The second purpose for tags is event bindings. +You can associate bindings with a tag in much the same way you can +associate bindings with a widget class: whenever particular X +events occur on characters with the given tag, a given +Tcl command will be executed. +Tag bindings can be used to give behaviors to ranges of characters; +among other things, this allows hypertext-like +features to be implemented. +For details, see the description of the tag bind widget +command below. +

    +The third use for tags is in managing the selection. +See THE SELECTION below. + +

    MARKS

    +The second form of annotation in text widgets is a mark. +Marks are used for remembering particular places in a text. +They are something like tags, in that they have names and +they refer to places in the file, but a mark isn't associated +with particular characters. +Instead, a mark is associated with the gap between two characters. +Only a single position may be associated with a mark at any given +time. +If the characters around a mark are deleted the mark will still +remain; it will just have new neighbor characters. +In contrast, if the characters containing a tag are deleted then +the tag will no longer have an association with characters in +the file. +Marks may be manipulated with the ``pathName mark'' widget +command, and their current locations may be determined by using the +mark name as an index in widget commands. +

    +Each mark also has a gravity, which is either left or +right. +The gravity for a mark specifies what happens to the mark when +text is inserted at the point of the mark. +If a mark has left gravity, then the mark is treated as if it +were attached to the character on its left, so the mark will +remain to the left of any text inserted at the mark position. +If the mark has right gravity, new text inserted at the mark +position will appear to the left of the mark (so that the mark +remains rightmost). The gravity for a mark defaults to right. +

    +The name space for marks is different from that for tags: the +same name may be used for both a mark and a tag, but they will refer +to different things. +

    +Two marks have special significance. +First, the mark insert is associated with the insertion cursor, +as described under THE INSERTION CURSOR below. +Second, the mark current is associated with the character +closest to the mouse and is adjusted automatically to track the +mouse position and any changes to the text in the widget (one +exception: current is not updated in response to mouse +motions if a mouse button is down; the update will be deferred +until all mouse buttons have been released). +Neither of these special marks may be deleted. + +

    EMBEDDED WINDOWS

    +The third form of annotation in text widgets is an embedded window. +Each embedded window annotation causes a window to be displayed +at a particular point in the text. +There may be any number of embedded windows in a text widget, +and any widget may be used as an embedded window (subject to the +usual rules for geometry management, which require the text window +to be the parent of the embedded window or a descendant of its +parent). +The embedded window's position on the screen will be updated as the +text is modified or scrolled, and it will be mapped and unmapped as +it moves into and out of the visible area of the text widget. +Each embedded window occupies one character's worth of index space +in the text widget, and it may be referred to either by the name +of its embedded window or by its position in the widget's +index space. +If the range of text containing the embedded window is deleted then +the window is destroyed. +

    +When an embedded window is added to a text widget with the +window create widget command, several configuration +options may be associated with it. +These options may be modified later with the window configure +widget command. +The following options are currently supported: +

    +

    +

    -align where
    +If the window is not as tall as the line in which it is displayed, +this option determines where the window is displayed in the line. +Where must have one of the values top (align the top of the window +with the top of the line), center (center the window +within the range of the line), bottom (align the bottom of the +window with the bottom of the line's area), +or baseline (align the bottom of the window with the baseline +of the line). +

    -create script
    +Specifies a Tcl script that may be evaluated to create the window +for the annotation. +If no -window option has been specified for the annotation +this script will be evaluated when the annotation is about to +be displayed on the screen. +Script must create a window for the annotation and return +the name of that window as its result. +If the annotation's window should ever be deleted, script +will be evaluated again the next time the annotation is displayed. +

    -padx pixels
    +Pixels specifies the amount of extra space to leave on +each side of the embedded window. +It may have any of the usual forms defined for a screen distance. +

    -pady pixels
    +Pixels specifies the amount of extra space to leave on +the top and on the bottom of the embedded window. +It may have any of the usual forms defined for a screen distance. +

    -stretch boolean
    +If the requested height of the embedded window is less than the +height of the line in which it is displayed, this option can be +used to specify whether the window should be stretched vertically +to fill its line. +If the -pady option has been specified as well, then the +requested padding will be retained even if the window is +stretched. +

    -window pathName
    +Specifies the name of a window to display in the annotation. + +

    +

    EMBEDDED IMAGES

    +The final form of annotation in text widgets is an embedded image. +Each embedded image annotation causes an image to be displayed +at a particular point in the text. +There may be any number of embedded images in a text widget, +and a particular image may be embedded in multiple places in the same +text widget. +The embedded image's position on the screen will be updated as the +text is modified or scrolled. +Each embedded image occupies one character's worth of index space +in the text widget, and it may be referred to either by +its position in the widget's index space, or the name it is assigned +when the image is inserted into the text widget widh image create. +If the range of text containing the embedded image is deleted then +that copy of the image is removed from the screen. +

    +When an embedded image is added to a text widget with the image +create widget command, a name unique to this instance of the image +is returned. This name may then be used to refer to this image +instance. The name is taken to be the value of the -name option +(described below). If the -name option is not provided, the +-image name is used instead. If the imageName is already +in use in the text widget, then #nn is added to the end of the +imageName, where nn is an arbitrary integer. This insures +the imageName is unique. +Once this name is assigned to this instance of the image, it does not +change, even though the -image or -name values can be changed +with image configure. +

    +When an embedded image is added to a text widget with the +image create widget command, several configuration +options may be associated with it. +These options may be modified later with the image configure +widget command. +The following options are currently supported: +

    +

    +

    -align where
    +If the image is not as tall as the line in which it is displayed, +this option determines where the image is displayed in the line. +Where must have one of the values top (align the top of the image +with the top of the line), center (center the image +within the range of the line), bottom (align the bottom of the +image with the bottom of the line's area), +or baseline (align the bottom of the image with the baseline +of the line). +

    -image image
    +Specifies the name of the Tk image to display in the annotation. +If image is not a valid Tk image, then an error is returned. +

    -name ImageName
    +Specifies the name by which this image instance may be referenced in +the text widget. If ImageName is not supplied, then the +name of the Tk image is used instead. +If the imageName is already in use, #nn is appended to +the end of the name as described above. +

    -padx pixels
    +Pixels specifies the amount of extra space to leave on +each side of the embedded image. +It may have any of the usual forms defined for a screen distance. +

    -pady pixels
    +Pixels specifies the amount of extra space to leave on +the top and on the bottom of the embedded image. +It may have any of the usual forms defined for a screen distance. + +

    +

    THE SELECTION

    +Selection support is implemented via tags. +If the exportSelection option for the text widget is true +then the sel tag will be associated with the selection: +

    +

    +

    [1]
    +Whenever characters are tagged with sel the text widget +will claim ownership of the selection. +

    [2]
    +Attempts to retrieve the +selection will be serviced by the text widget, returning all the +characters with the sel tag. +

    [3]
    +If the selection is claimed away by another application or by another +window within this application, then the sel tag will be removed +from all characters in the text. +

    +

    +The sel tag is automatically defined when a text widget is +created, and it may not be deleted with the ``pathName tag delete'' +widget command. Furthermore, the selectBackground, +selectBorderWidth, and selectForeground options for +the text widget are tied to the -background, +-borderwidth, and -foreground options for the sel +tag: changes in either will automatically be reflected in the +other. + +

    THE INSERTION CURSOR

    +The mark named insert has special significance in text widgets. +It is defined automatically when a text widget is created and it +may not be unset with the ``pathName mark unset'' widget +command. +The insert mark represents the position of the insertion +cursor, and the insertion cursor will automatically be drawn at +this point whenever the text widget has the input focus. + +

    WIDGET COMMAND

    +The text command creates a new Tcl command whose +name is the same as the path name of the text's window. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +PathName is the name of the command, which is the same as +the text widget's path name. Option and the args +determine the exact behavior of the command. The following +commands are possible for text widgets: +

    +

    +

    pathName bbox index
    +Returns a list of four elements describing the screen area +of the character given by index. +The first two elements of the list give the x and y coordinates +of the upper-left corner of the area occupied by the +character, and the last two elements give the width and height +of the area. +If the character is only partially visible on the screen, then +the return value reflects just the visible part. +If the character is not visible on the screen then the return +value is an empty list. +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the text +command. +

    pathName compare index1 op index2
    +Compares the indices given by index1 and index2 according +to the relational operator given by op, and returns 1 if +the relationship is satisfied and 0 if it isn't. +Op must be one of the operators <, <=, ==, >=, >, or !=. +If op is == then 1 is returned if the two indices refer to +the same character, if op is < then 1 is returned if index1 +refers to an earlier character in the text than index2, and +so on. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the text +command. +

    pathName debug ?boolean?
    +If boolean is specified, then it must have one of the true or +false values accepted by Tcl_GetBoolean. +If the value is a true one then internal consistency checks will be +turned on in the B-tree code associated with text widgets. +If boolean has a false value then the debugging checks will +be turned off. +In either case the command returns an empty string. +If boolean is not specified then the command returns on +or off to indicate whether or not debugging is turned on. +There is a single debugging switch shared by all text widgets: turning +debugging on or off in any widget turns it on or off for all widgets. +For widgets with large amounts of text, the consistency checks may +cause a noticeable slow-down. +

    pathName delete index1 ?index2?
    +Delete a range of characters from the text. +If both index1 and index2 are specified, then delete +all the characters starting with the one given by index1 +and stopping just before index2 (i.e. the character at +index2 is not deleted). +If index2 doesn't specify a position later in the text +than index1 then no characters are deleted. +If index2 isn't specified then the single character at +index1 is deleted. +It is not allowable to delete characters in a way that would leave +the text without a newline as the last character. +The command returns an empty string. +

    pathName dlineinfo index
    +Returns a list with five elements describing the area occupied +by the display line containing index. +The first two elements of the list give the x and y coordinates +of the upper-left corner of the area occupied by the +line, the third and fourth elements give the width and height +of the area, and the fifth element gives the position of the baseline +for the line, measured down from the top of the area. +All of this information is measured in pixels. +If the current wrap mode is none and the line extends beyond +the boundaries of the window, +the area returned reflects the entire area of the line, including the +portions that are out of the window. +If the line is shorter than the full width of the window then the +area returned reflects just the portion of the line that is occupied +by characters and embedded windows. +If the display line containing index is not visible on +the screen then the return value is an empty list. +

    pathName dump ?switches? index1 ?index2?
    +Return the contents of the text widget from index1 up to, +but not including index2, +including the text and +information about marks, tags, and embedded windows. +If index2 is not specified, then it defaults to +one character past index1. The information is returned +in the following format: +

    +

    +

    +key1 value1 index1 key2 value2 index2 ... +

    +The possible key values are text, mark, +tagon, tagoff, and window. The corresponding +value is the text, mark name, tag name, or window name. +The index information is the index of the +start of the text, the mark, the tag transition, or the window. +One or more of the following switches (or abbreviations thereof) +may be specified to control the dump: +

    +

    +

    -all
    +Return information about all elements: text, marks, tags, images and windows. +This is the default. +

    -command command
    +Instead of returning the information as the result of the dump operation, +invoke the command on each element of the text widget within the range. +The command has three arguments appended to it before it is evaluated: +the key, value, and index. +

    -image
    +Include information about images in the dump results. +

    -mark
    +Include information about marks in the dump results. +

    -tag
    +Include information about tag transitions in the dump results. Tag +information is returned as tagon and tagoff elements that +indicate the begin and end of each range of each tag, respectively. +

    -text
    +Include information about text in the dump results. The value is the +text up to the next element or the end of range indicated by index2. +A text element does not span newlines. A multi-line block of text that +contains no marks or tag transitions will still be dumped as a set +of text seqments that each end with a newline. The newline is part +of the value. +

    -window
    +Include information about embedded windows in the dump results. +The value of a window is its Tk pathname, unless the window +has not been created yet. (It must have a create script.) +In this case an empty string is returned, and you must query the +window by its index position to get more information. +

    +
    +

    +

    +

    pathName get index1 ?index2?
    +Return a range of characters from the text. +The return value will be all the characters in the text starting +with the one whose index is index1 and ending just before +the one whose index is index2 (the character at index2 +will not be returned). +If index2 is omitted then the single character at index1 +is returned. +If there are no characters in the specified range (e.g. index1 +is past the end of the file or index2 is less than or equal +to index1) then an empty string is returned. +If the specified range contains embedded windows, no information +about them is included in the returned string. +

    pathName image option ?arg arg ...?
    +This command is used to manipulate embedded images. +The behavior of the command depends on the option argument +that follows the tag argument. +The following forms of the command are currently supported: +

    +

    +

    pathName image cget index option
    +Returns the value of a configuration option for an embedded image. +Index identifies the embedded image, and option +specifies a particular configuration option, which must be one of +the ones listed in the section EMBEDDED IMAGES. +

    pathName image configure index ?option value ...?
    +Query or modify the configuration options for an embedded image. +If no option is specified, returns a list describing all of +the available options for the embedded image at index +(see Tk_ConfigureInfo for information on the format of this list). +If option is specified with no value, then the command +returns a list describing the one named option (this list will be +identical to the corresponding sublist of the value returned if no +option is specified). +If one or more option-value pairs are specified, then the command +modifies the given option(s) to have the given value(s); in +this case the command returns an empty string. +See EMBEDDED IMAGES for information on the options that +are supported. +

    pathName image create index ?option value ...?
    +This command creates a new image annotation, which will appear +in the text at the position given by index. +Any number of option-value pairs may be specified to +configure the annotation. +Returns a unique identifier that may be used as an index to refer to +this image. +See EMBEDDED IMAGES for information on the options that +are supported, and a description of the identifier returned. +

    pathName image names
    +Returns a list whose elements are the names of all image instances currently +embedded in window. +

    +

    pathName index index
    +Returns the position corresponding to index in the form +line.char where line is the line number and char +is the character number. +Index may have any of the forms described under INDICES above. +

    pathName insert index chars ?tagList chars tagList ...?
    +Inserts all of the chars arguments just before the character at +index. +If index refers to the end of the text (the character after +the last newline) then the new text is inserted just before the +last newline instead. +If there is a single chars argument and no tagList, then +the new text will receive any tags that are present on both the +character before and the character after the insertion point; if a tag +is present on only one of these characters then it will not be +applied to the new text. +If tagList is specified then it consists of a list of +tag names; the new characters will receive all of the tags in +this list and no others, regardless of the tags present around +the insertion point. +If multiple chars-tagList argument pairs are present, +they produce the same effect as if a separate insert widget +command had been issued for each pair, in order. +The last tagList argument may be omitted. +

    pathName mark option ?arg arg ...?
    +This command is used to manipulate marks. The exact behavior of +the command depends on the option argument that follows +the mark argument. The following forms of the command +are currently supported: +

    +

    +

    pathName mark gravity markName ?direction?
    +If direction is not specified, returns left or right +to indicate which of its adjacent characters markName is attached +to. +If direction is specified, it must be left or right; +the gravity of markName is set to the given value. +

    pathName mark names
    +Returns a list whose elements are the names of all the marks that +are currently set. +

    pathName mark next index
    +Returns the name of the next mark at or after index. +If index is specified in numerical form, then the search for +the next mark begins at that index. +If index is the name of a mark, then the search for +the next mark begins immediately after that mark. +This can still return a mark at the same position if +there are multiple marks at the same index. +These semantics mean that the mark next operation can be used to +step through all the marks in a text widget in the same order +as the mark information returned by the dump operation. +If a mark has been set to the special end index, +then it appears to be after end with respect to the mark next operation. +An empty string is returned if there are no marks after index. +

    pathName mark previous index
    +Returns the name of the mark at or before index. +If index is specified in numerical form, then the search for +the previous mark begins with the character just before that index. +If index is the name of a mark, then the search for +the next mark begins immediately before that mark. +This can still return a mark at the same position if +there are multiple marks at the same index. +These semantics mean that the mark previous operation can be used to +step through all the marks in a text widget in the reverse order +as the mark information returned by the dump operation. +An empty string is returned if there are no marks before index. +

    pathName mark set markName index
    +Sets the mark named markName to a position just before the +character at index. +If markName already exists, it is moved from its old position; +if it doesn't exist, a new mark is created. +This command returns an empty string. +

    pathName mark unset markName ?markName markName ...?
    +Remove the mark corresponding to each of the markName arguments. +The removed marks will not be usable in indices and will not be +returned by future calls to ``pathName mark names''. +This command returns an empty string. +

    +

    pathName scan option args
    +This command is used to implement scanning on texts. It has +two forms, depending on option: +

    +

    +

    pathName scan mark x y
    +Records x and y and the current view in the text window, +for use in conjunction with later scan dragto commands. +Typically this command is associated with a mouse button press in +the widget. It returns an empty string. +

    pathName scan dragto x y
    +This command computes the difference between its x and y +arguments and the x and y arguments to the last +scan mark command for the widget. +It then adjusts the view by 10 times the difference in coordinates. +This command is typically associated +with mouse motion events in the widget, to produce the effect of +dragging the text at high speed through the window. The return +value is an empty string. +

    +

    pathName search ?switches? pattern index ?stopIndex?
    +Searches the text in pathName starting at index for a range +of characters that matches pattern. +If a match is found, the index of the first character in the match is +returned as result; otherwise an empty string is returned. +One or more of the following switches (or abbreviations thereof) +may be specified to control the search: +

    +

    +

    -forwards
    +The search will proceed forward through the text, finding the first +matching range starting at or after the position given by index. +This is the default. +

    -backwards
    +The search will proceed backward through the text, finding the +matching range closest to index whose first character +is before index. +

    -exact
    +Use exact matching: the characters in the matching range must be +identical to those in pattern. +This is the default. +

    -regexp
    +Treat pattern as a regular expression and match it against +the text using the rules for regular expressions (see the regexp +command for details). +

    -nocase
    +Ignore case differences between the pattern and the text. +

    -count varName
    +The argument following -count gives the name of a variable; +if a match is found, the number of index positions between beginning and +end of the matching range will be stored in the variable. If there are no +embedded images or windows in the matching range, this is equivalent to the +number of characters matched. In either case, the range matchIdx to +matchIdx + $count chars will return the entire matched text. +

    -elide
    +Find elidden (hidden) text as well. By default only displayed text is +searched. +

    - -
    +This switch has no effect except to terminate the list of switches: +the next argument will be treated as pattern even if it starts +with -. +

    The matching range must be entirely within a single line of text. +For regular expression matching the newlines are removed from the ends +of the lines before matching: use the $ feature in regular +expressions to match the end of a line. +For exact matching the newlines are retained. +If stopIndex is specified, the search stops at that index: +for forward searches, no match at or after stopIndex will +be considered; for backward searches, no match earlier in the +text than stopIndex will be considered. +If stopIndex is omitted, the entire text will be searched: +when the beginning or end of the text is reached, the search +continues at the other end until the starting location is reached +again; if stopIndex is specified, no wrap-around will occur.

    +

    +

    pathName see index
    +Adjusts the view in the window so that the character given by index +is completely visible. +If index is already visible then the command does nothing. +If index is a short distance out of view, the command +adjusts the view just enough to make index visible at the +edge of the window. +If index is far out of view, then the command centers +index in the window. +

    pathName tag option ?arg arg ...?
    +This command is used to manipulate tags. The exact behavior of the +command depends on the option argument that follows the +tag argument. The following forms of the command are currently +supported: +

    +

    +

    pathName tag add tagName index1 ?index2 index1 index2 ...?
    +Associate the tag tagName with all of the characters starting +with index1 and ending just before +index2 (the character at index2 isn't tagged). +A single command may contain any number of index1-index2 +pairs. +If the last index2 is omitted then the single character at +index1 is tagged. +If there are no characters in the specified range (e.g. index1 +is past the end of the file or index2 is less than or equal +to index1) then the command has no effect. +

    pathName tag bind tagName ?sequence? ?script?
    +This command associates script with the tag given by +tagName. +Whenever the event sequence given by sequence occurs for a +character that has been tagged with tagName, +the script will be invoked. +This widget command is similar to the bind command except that +it operates on characters in a text rather than entire widgets. +See the bind manual entry for complete details +on the syntax of sequence and the substitutions performed +on script before invoking it. +If all arguments are specified then a new binding is created, replacing +any existing binding for the same sequence and tagName +(if the first character of script is ``+'' then script +augments an existing binding rather than replacing it). +In this case the return value is an empty string. +If script is omitted then the command returns the script +associated with tagName and sequence (an error occurs +if there is no such binding). +If both script and sequence are omitted then the command +returns a list of all the sequences for which bindings have been +defined for tagName. +

    +The only events for which bindings may be specified are those related +to the mouse and keyboard (such as Enter, Leave, +ButtonPress, Motion, and KeyPress) or virtual events. +Event bindings for a text widget use the current mark described +under MARKS above. An Enter event triggers for a tag when the tag +first becomes present on the current character, and a Leave event +triggers for a tag when it ceases to be present on the current character. +Enter and Leave events can happen either because the +current mark moved or because the character at that position +changed. Note that these events are different than Enter and +Leave events for windows. Mouse and keyboard events are directed +to the current character. If a virtual event is used in a binding, that +binding can trigger only if the virtual event is defined by an underlying +mouse-related or keyboard-related event. +

    +It is possible for the current character to have multiple tags, +and for each of them to have a binding for a particular event +sequence. +When this occurs, one binding is invoked for each tag, in order +from lowest-priority to highest priority. +If there are multiple matching bindings for a single tag, then +the most specific binding is chosen (see the manual entry for +the bind command for details). +continue and break commands within binding scripts +are processed in the same way as for bindings created with +the bind command. +

    If bindings are created for the widget as a whole using the +bind command, then those bindings will supplement the +tag bindings. +The tag bindings will be invoked first, followed by bindings +for the window as a whole. +

    pathName tag cget tagName option
    +This command returns the current value of the option named option +associated with the tag given by tagName. +Option may have any of the values accepted by the tag configure +widget command. +

    pathName tag configure tagName ?option? ?value? ?option value ...?
    +This command is similar to the configure widget command except +that it modifies options associated with the tag given by tagName +instead of modifying options for the overall text widget. +If no option is specified, the command returns a list describing +all of the available options for tagName (see Tk_ConfigureInfo +for information on the format of this list). +If option is specified with no value, then the command returns +a list describing the one named option (this list will be identical to +the corresponding sublist of the value returned if no option +is specified). +If one or more option-value pairs are specified, then the command +modifies the given option(s) to have the given value(s) in tagName; +in this case the command returns an empty string. +See TAGS above for details on the options available for tags. +

    pathName tag delete tagName ?tagName ...?
    +Deletes all tag information for each of the tagName +arguments. +The command removes the tags from all characters in the file +and also deletes any other information associated with the tags, +such as bindings and display information. +The command returns an empty string. +

    pathName tag lower tagName ?belowThis?
    +Changes the priority of tag tagName so that it is just lower +in priority than the tag whose name is belowThis. +If belowThis is omitted, then tagName's priority +is changed to make it lowest priority of all tags. +

    pathName tag names ?index?
    +Returns a list whose elements are the names of all the tags that +are active at the character position given by index. +If index is omitted, then the return value will describe +all of the tags that exist for the text (this includes all tags +that have been named in a ``pathName tag'' widget +command but haven't been deleted by a ``pathName tag delete'' +widget command, even if no characters are currently marked with +the tag). +The list will be sorted in order from lowest priority to highest +priority. +

    pathName tag nextrange tagName index1 ?index2?
    +This command searches the text for a range of characters tagged +with tagName where the first character of the range is +no earlier than the character at index1 and no later than +the character just before index2 (a range starting at +index2 will not be considered). +If several matching ranges exist, the first one is chosen. +The command's return value is a list containing +two elements, which are the index of the first character of the +range and the index of the character just after the last one in +the range. +If no matching range is found then the return value is an +empty string. +If index2 is not given then it defaults to the end of the text. +

    pathName tag prevrange tagName index1 ?index2?
    +This command searches the text for a range of characters tagged +with tagName where the first character of the range is +before the character at index1 and no earlier than +the character at index2 (a range starting at +index2 will be considered). +If several matching ranges exist, the one closest to index1 is chosen. +The command's return value is a list containing +two elements, which are the index of the first character of the +range and the index of the character just after the last one in +the range. +If no matching range is found then the return value is an +empty string. +If index2 is not given then it defaults to the beginning of the text. +

    pathName tag raise tagName ?aboveThis?
    +Changes the priority of tag tagName so that it is just higher +in priority than the tag whose name is aboveThis. +If aboveThis is omitted, then tagName's priority +is changed to make it highest priority of all tags. +

    pathName tag ranges tagName
    +Returns a list describing all of the ranges of text that have been +tagged with tagName. +The first two elements of the list describe the first tagged range +in the text, the next two elements describe the second range, and +so on. +The first element of each pair contains the index of the first +character of the range, and the second element of the pair contains +the index of the character just after the last one in the +range. +If there are no characters tagged with tag then an +empty string is returned. +

    pathName tag remove tagName index1 ?index2 index1 index2 ...?
    +Remove the tag tagName from all of the characters starting +at index1 and ending just before +index2 (the character at index2 isn't affected). +A single command may contain any number of index1-index2 +pairs. +If the last index2 is omitted then the single character at +index1 is tagged. +If there are no characters in the specified range (e.g. index1 +is past the end of the file or index2 is less than or equal +to index1) then the command has no effect. +This command returns an empty string. +

    +

    pathName window option ?arg arg ...?
    +This command is used to manipulate embedded windows. +The behavior of the command depends on the option argument +that follows the tag argument. +The following forms of the command are currently supported: +

    +

    +

    pathName window cget index option
    +Returns the value of a configuration option for an embedded window. +Index identifies the embedded window, and option +specifies a particular configuration option, which must be one of +the ones listed in the section EMBEDDED WINDOWS. +

    pathName window configure index ?option value ...?
    +Query or modify the configuration options for an embedded window. +If no option is specified, returns a list describing all of +the available options for the embedded window at index +(see Tk_ConfigureInfo for information on the format of this list). +If option is specified with no value, then the command +returns a list describing the one named option (this list will be +identical to the corresponding sublist of the value returned if no +option is specified). +If one or more option-value pairs are specified, then the command +modifies the given option(s) to have the given value(s); in +this case the command returns an empty string. +See EMBEDDED WINDOWS for information on the options that +are supported. +

    pathName window create index ?option value ...?
    +This command creates a new window annotation, which will appear +in the text at the position given by index. +Any number of option-value pairs may be specified to +configure the annotation. +See EMBEDDED WINDOWS for information on the options that +are supported. +Returns an empty string. +

    pathName window names
    +Returns a list whose elements are the names of all windows currently +embedded in window. +

    +

    pathName xview option args
    +This command is used to query and change the horizontal position of the +text in the widget's window. It can take any of the following +forms: +

    +

    +

    pathName xview
    +Returns a list containing two elements. +Each element is a real fraction between 0 and 1; together they describe +the portion of the document's horizontal span that is visible in +the window. +For example, if the first element is .2 and the second element is .6, +20% of the text is off-screen to the left, the middle 40% is visible +in the window, and 40% of the text is off-screen to the right. +The fractions refer only to the lines that are actually visible in the +window: if the lines in the window are all very short, so that they +are entirely visible, the returned fractions will be 0 and 1, +even if there are other lines in the text that are +much wider than the window. +These are the same values passed to scrollbars via the -xscrollcommand +option. +

    pathName xview moveto fraction
    +Adjusts the view in the window so that fraction of the horizontal +span of the text is off-screen to the left. +Fraction is a fraction between 0 and 1. +

    pathName xview scroll number what
    +This command shifts the view in the window left or right according to +number and what. +Number must be an integer. +What must be either units or pages or an abbreviation +of one of these. +If what is units, the view adjusts left or right by +number average-width characters on the display; if it is +pages then the view adjusts by number screenfuls. +If number is negative then characters farther to the left +become visible; if it is positive then characters farther to the right +become visible. +

    +

    pathName yview ?args?
    +This command is used to query and change the vertical position of the +text in the widget's window. +It can take any of the following forms: +

    +

    +

    pathName yview
    +Returns a list containing two elements, both of which are real fractions +between 0 and 1. +The first element gives the position of the first character in the +top line in the window, relative to the text as a whole (0.5 means +it is halfway through the text, for example). +The second element gives the position of the character just after +the last one in the bottom line of the window, +relative to the text as a whole. +These are the same values passed to scrollbars via the -yscrollcommand +option. +

    pathName yview moveto fraction
    +Adjusts the view in the window so that the character given by fraction +appears on the top line of the window. +Fraction is a fraction between 0 and 1; 0 indicates the first +character in the text, 0.33 indicates the character one-third the +way through the text, and so on. +

    pathName yview scroll number what
    +This command adjust the view in the window up or down according to +number and what. +Number must be an integer. +What must be either units or pages. +If what is units, the view adjusts up or down by +number lines on the display; if it is pages then +the view adjusts by number screenfuls. +If number is negative then earlier positions in the text +become visible; if it is positive then later positions in the text +become visible. +

    pathName yview ?-pickplace? index
    +Changes the view in the widget's window to make index visible. +If the -pickplace option isn't specified then index will +appear at the top of the window. +If -pickplace is specified then the widget chooses where +index appears in the window: +

    +

    +

    [1]
    +If index is already visible somewhere in the window then the +command does nothing. +

    [2]
    +If index is only a few lines off-screen above the window then +it will be positioned at the top of the window. +

    [3]
    +If index is only a few lines off-screen below the window then +it will be positioned at the bottom of the window. +

    [4]
    +Otherwise, index will be centered in the window. +

    The -pickplace option has been obsoleted by the see widget +command (see handles both x- and y-motion to make a location +visible, whereas -pickplace only handles motion in y).

    +

    +

    pathName yview number
    +This command makes the first character on the line after +the one given by number visible at the top of the window. +Number must be an integer. +This command used to be used for scrolling, but now it is obsolete. +

    +

    +

    BINDINGS

    +Tk automatically creates class bindings for texts that give them +the following default behavior. +In the descriptions below, ``word'' is dependent on the value of +the tcl_wordchars variable. See tclvars(n). +

    +

    +

    [1]
    +Clicking mouse button 1 positions the insertion cursor +just before the character underneath the mouse cursor, sets the +input focus to this widget, and clears any selection in the widget. +Dragging with mouse button 1 strokes out a selection between +the insertion cursor and the character under the mouse. +

    [2]
    +Double-clicking with mouse button 1 selects the word under the mouse +and positions the insertion cursor at the beginning of the word. +Dragging after a double click will stroke out a selection consisting +of whole words. +

    [3]
    +Triple-clicking with mouse button 1 selects the line under the mouse +and positions the insertion cursor at the beginning of the line. +Dragging after a triple click will stroke out a selection consisting +of whole lines. +

    [4]
    +The ends of the selection can be adjusted by dragging with mouse +button 1 while the Shift key is down; this will adjust the end +of the selection that was nearest to the mouse cursor when button +1 was pressed. +If the button is double-clicked before dragging then the selection +will be adjusted in units of whole words; if it is triple-clicked +then the selection will be adjusted in units of whole lines. +

    [5]
    +Clicking mouse button 1 with the Control key down will reposition the +insertion cursor without affecting the selection. +

    [6]
    +If any normal printing characters are typed, they are +inserted at the point of the insertion cursor. +

    [7]
    +The view in the widget can be adjusted by dragging with mouse button 2. +If mouse button 2 is clicked without moving the mouse, the selection +is copied into the text at the position of the mouse cursor. +The Insert key also inserts the selection, but at the position of +the insertion cursor. +

    [8]
    +If the mouse is dragged out of the widget +while button 1 is pressed, the entry will automatically scroll to +make more text visible (if there is more text off-screen on the side +where the mouse left the window). +

    [9]
    +The Left and Right keys move the insertion cursor one character to the +left or right; they also clear any selection in the text. +If Left or Right is typed with the Shift key down, then the insertion +cursor moves and the selection is extended to include the new character. +Control-Left and Control-Right move the insertion cursor by words, and +Control-Shift-Left and Control-Shift-Right move the insertion cursor +by words and also extend the selection. +Control-b and Control-f behave the same as Left and Right, respectively. +Meta-b and Meta-f behave the same as Control-Left and Control-Right, +respectively. +

    [10]
    +The Up and Down keys move the insertion cursor one line up or +down and clear any selection in the text. +If Up or Right is typed with the Shift key down, then the insertion +cursor moves and the selection is extended to include the new character. +Control-Up and Control-Down move the insertion cursor by paragraphs (groups +of lines separated by blank lines), and +Control-Shift-Up and Control-Shift-Down move the insertion cursor +by paragraphs and also extend the selection. +Control-p and Control-n behave the same as Up and Down, respectively. +

    [11]
    +The Next and Prior keys move the insertion cursor forward or backwards +by one screenful and clear any selection in the text. +If the Shift key is held down while Next or Prior is typed, then +the selection is extended to include the new character. +Control-v moves the view down one screenful without moving the +insertion cursor or adjusting the selection. +

    [12]
    +Control-Next and Control-Prior scroll the view right or left by one page +without moving the insertion cursor or affecting the selection. +

    [13]
    +Home and Control-a move the insertion cursor to the +beginning of its line and clear any selection in the widget. +Shift-Home moves the insertion cursor to the beginning of the line +and also extends the selection to that point. +

    [14]
    +End and Control-e move the insertion cursor to the +end of the line and clear any selection in the widget. +Shift-End moves the cursor to the end of the line and extends the selection +to that point. +

    [15]
    +Control-Home and Meta-< move the insertion cursor to the beginning of +the text and clear any selection in the widget. +Control-Shift-Home moves the insertion cursor to the beginning of the text +and also extends the selection to that point. +

    [16]
    +Control-End and Meta-> move the insertion cursor to the end of the +text and clear any selection in the widget. +Control-Shift-End moves the cursor to the end of the text and extends +the selection to that point. +

    [17]
    +The Select key and Control-Space set the selection anchor to the position +of the insertion cursor. They don't affect the current selection. +Shift-Select and Control-Shift-Space adjust the selection to the +current position of the insertion cursor, selecting from the anchor +to the insertion cursor if there was not any selection previously. +

    [18]
    +Control-/ selects the entire contents of the widget. +

    [19]
    +Control-\ clears any selection in the widget. +

    [20]
    +The F16 key (labelled Copy on many Sun workstations) or Meta-w +copies the selection in the widget to the clipboard, if there is a selection. +

    [21]
    +The F20 key (labelled Cut on many Sun workstations) or Control-w +copies the selection in the widget to the clipboard and deletes +the selection. +If there is no selection in the widget then these keys have no effect. +

    [22]
    +The F18 key (labelled Paste on many Sun workstations) or Control-y +inserts the contents of the clipboard at the position of the +insertion cursor. +

    [23]
    +The Delete key deletes the selection, if there is one in the widget. +If there is no selection, it deletes the character to the right of +the insertion cursor. +

    [24]
    +Backspace and Control-h delete the selection, if there is one +in the widget. +If there is no selection, they delete the character to the left of +the insertion cursor. +

    [25]
    +Control-d deletes the character to the right of the insertion cursor. +

    [26]
    +Meta-d deletes the word to the right of the insertion cursor. +

    [27]
    +Control-k deletes from the insertion cursor to the end of its line; +if the insertion cursor is already at the end of a line, then +Control-k deletes the newline character. +

    [28]
    +Control-o opens a new line by inserting a newline character in +front of the insertion cursor without moving the insertion cursor. +

    [29]
    +Meta-backspace and Meta-Delete delete the word to the left of the +insertion cursor. +

    [30]
    +Control-x deletes whatever is selected in the text widget. +

    [31]
    +Control-t reverses the order of the two characters to the right of +the insertion cursor. +

    +

    +If the widget is disabled using the -state option, then its +view can still be adjusted and text can still be selected, +but no insertion cursor will be displayed and no text modifications will +take place. +

    +The behavior of texts can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    PERFORMANCE ISSUES

    +Text widgets should run efficiently under a variety +of conditions. The text widget uses about 2-3 bytes of +main memory for each byte of text, so texts containing a megabyte +or more should be practical on most workstations. +Text is represented internally with a modified B-tree structure +that makes operations relatively efficient even with large texts. +Tags are included in the B-tree structure in a way that allows +tags to span large ranges or have many disjoint smaller ranges +without loss of efficiency. +Marks are also implemented in a way that allows large numbers of +marks. +In most cases it is fine to have large numbers of unique tags, +or a tag that has many distinct ranges. +

    +One performance problem can arise if you have hundreds or thousands +of different tags that all have the following characteristics: +the first and last ranges of each tag are near the beginning and +end of the text, respectively, +or a single tag range covers most of the text widget. +The cost of adding and deleting tags like this is proportional +to the number of other tags with the same properties. +In contrast, there is no problem with having thousands of distinct +tags if their overall ranges are localized and spread uniformly throughout +the text. +

    +Very long text lines can be expensive, +especially if they have many marks and tags within them. +

    +The display line with the insert cursor is redrawn each time the +cursor blinks, which causes a steady stream of graphics traffic. +Set the insertOffTime attribute to 0 avoid this. +

    KEYWORDS

    +text, widget +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/tk.htm b/hlp/en/tk/tk.htm new file mode 100644 index 0000000..9b1c5fd --- /dev/null +++ b/hlp/en/tk/tk.htm @@ -0,0 +1,66 @@ +Tk Built-In Commands - tk manual page +

    NAME

    +tk - Manipulate Tk internal state +

    SYNOPSIS

    +tkoption ?arg arg ...?
    +

    DESCRIPTION

    +The tk command provides access to miscellaneous +elements of Tk's internal state. +Most of the information manipulated by this command pertains to the +application as a whole, or to a screen or display, rather than to a +particular window. +The command can take any of a number of different forms +depending on the option argument. The legal forms are: +

    +

    +

    tk appname ?newName?
    +If newName isn't specified, this command returns the name +of the application (the name that may be used in send +commands to communicate with the application). +If newName is specified, then the name of the application +is changed to newName. +If the given name is already in use, then a suffix of the form +`` #2'' or `` #3'' is appended in order to make the name unique. +The command's result is the name actually chosen. +newName should not start with a capital letter. +This will interfere with option processing, since names starting with +capitals are assumed to be classes; as a result, Tk may not +be able to find some options for the application. +If sends have been disabled by deleting the send command, +this command will reenable them and recreate the send +command. +

    tk scaling ?-displayof window? ?number?
    +Sets and queries the current scaling factor used by Tk to convert between +physical units (for example, points, inches, or millimeters) and pixels. The +number argument is a floating point number that specifies the number of +pixels per point on window's display. If the window argument is +omitted, it defaults to the main window. If the number argument is +omitted, the current value of the scaling factor is returned. +

    +A ``point'' is a unit of measurement equal to 1/72 inch. A scaling factor +of 1.0 corresponds to 1 pixel per point, which is equivalent to a standard +72 dpi monitor. A scaling factor of 1.25 would mean 1.25 pixels per point, +which is the setting for a 90 dpi monitor; setting the scaling factor to +1.25 on a 72 dpi monitor would cause everything in the application to be +displayed 1.25 times as large as normal. The initial value for the scaling +factor is set when the application starts, based on properties of the +installed monitor, but it can be changed at any time. Measurements made +after the scaling factor is changed will use the new scaling factor, but it +is undefined whether existing widgets will resize themselves dynamically to +accomodate the new scaling factor. +

    tk useinputmethods ?-displayof window? ?boolean?
    +Sets and queries the state of whether Tk should use XIM (X Input Methods) +for filtering events. The resulting state is returned. XIM is used in +some locales (ie: Japanese, Korean), to handle special input devices. This +feature is only significant on X. If XIM support is not available, this +will always return 0. If the window argument is omitted, it defaults +to the main window. If the boolean argument is omitted, the current +state is returned. This is turned on by default for the main display. +

    +

    KEYWORDS

    +application name, send +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/tk.toc.html b/hlp/en/tk/tk.toc.html new file mode 100644 index 0000000..67d600a --- /dev/null +++ b/hlp/en/tk/tk.toc.html @@ -0,0 +1,61 @@ +Tcl Commands +bell
    +destroy
    +label
    +photo
    +bind
    +entry
    +listbox
    +place
    +tk_popup
    +bindtags
    +event
    +loadTk
    +radiobutton
    +bitmap
    +focus
    +lower
    +raise
    +tk_dialog
    +tkerror
    +button
    +font
    +menu
    +scale
    +tkvars
    +canvas
    +frame
    +menubutton
    +scrollbar
    +tkwait
    +checkbutton
    +grab
    +message
    +selection
    +toplevel
    +clipboard
    +grid
    +option
    +send
    +winfo
    +colors
    +image
    +options
    +text
    +tk_bisque
    +tk_chooseColor
    +tk_chooseDirectory
    +tk_focusPrev
    +tk_focusFollowsMouse
    +tk_focusNext
    +tk_getOpenFile
    +tk_getSaveFile
    +tk_optionMenu
    +tk_setPalette
    +wm
    +cursors
    +keysyms
    +pack
    +tk
    +tk_messageBox
    + diff --git a/hlp/en/tk/tkerror.htm b/hlp/en/tk/tkerror.htm new file mode 100644 index 0000000..fd00c5a --- /dev/null +++ b/hlp/en/tk/tkerror.htm @@ -0,0 +1,28 @@ +Tk Built-In Commands - tkerror manual page +

    NAME

    +tkerror - Command invoked to process background errors +

    SYNOPSIS

    +tkerror message
    +

    DESCRIPTION

    +Note: as of Tk 4.1 the tkerror command has been renamed to +bgerror because the event loop (which is what usually invokes +it) is now part of Tcl. For backward compatibility +the bgerror provided by the current Tk version still +tries to call tkerror if there is one (or an auto loadable one), +so old script defining that error handler should still work, but you +should anyhow modify your scripts to use bgerror instead +of tkerror because that support for the old name might vanish +in the near future. If that call fails, bgerror +posts a dialog showing the error and offering to see the stack trace +to the user. If you want your own error management you should +directly override bgerror instead of tkerror. +Documentation for bgerror is available as part of Tcl's +documentation. + +

    KEYWORDS

    +background error, reporting +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/tkvars.htm b/hlp/en/tk/tkvars.htm new file mode 100644 index 0000000..75396ca --- /dev/null +++ b/hlp/en/tk/tkvars.htm @@ -0,0 +1,60 @@ +Tk Built-In Commands - tkvars manual page +

    NAME

    +tkvars - Variables used or set by Tk +

    DESCRIPTION

    +The following Tcl variables are either set or used by Tk at various times +in its execution: +

    +

    +

    tk_library
    +This variable holds the file name for a directory containing a library +of Tcl scripts related to Tk. These scripts include an initialization +file that is normally processed whenever a Tk application starts up, +plus other files containing procedures that implement default behaviors +for widgets. +The initial value of tcl_library is set when Tk is added to +an interpreter; this is done by searching several different directories +until one is found that contains an appropriate Tk startup script. +If the TK_LIBRARY environment variable exists, then +the directory it names is checked first. +If TK_LIBRARY isn't set or doesn't refer to an appropriate +directory, then Tk checks several other directories based on a +compiled-in default location, the location of the Tcl library directory, +the location of the binary containing the application, and the current +working directory. +The variable can be modified by an application to switch to a different +library. +

    tk_patchLevel
    +Contains a decimal integer giving the current patch level for Tk. +The patch level is incremented for each new release or patch, and +it uniquely identifies an official version of Tk. +

    tkPriv
    +This variable is an array containing several pieces of information +that are private to Tk. The elements of tkPriv are used by +Tk library procedures and default bindings. +They should not be accessed by any code outside Tk. +

    tk_strictMotif
    +This variable is set to zero by default. +If an application sets it to one, then Tk attempts to adhere as +closely as possible to Motif look-and-feel standards. +For example, active elements such as buttons and scrollbar +sliders will not change color when the pointer passes over them. +

    tk_version
    +Tk sets this variable in the interpreter for each application. +The variable holds the current version number of the Tk +library in the form major.minor. Major and +minor are integers. The major version number increases in +any Tk release that includes changes that are not backward compatible +(i.e. whenever existing Tk applications and scripts may have to change to +work with the new release). The minor version number increases with +each new release of Tk, except that it resets to zero whenever the +major version number changes. + +

    +

    KEYWORDS

    +variables, version +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/tkwait.htm b/hlp/en/tk/tkwait.htm new file mode 100644 index 0000000..b5bddce --- /dev/null +++ b/hlp/en/tk/tkwait.htm @@ -0,0 +1,39 @@ +Built-In Commands - tkwait manual page +

    NAME

    +tkwait - Wait for variable to change or window to be destroyed +

    SYNOPSIS

    +tkwait variable name
    +tkwait visibility name
    +tkwait window name
    +

    DESCRIPTION

    +The tkwait command waits for one of several things to happen, +then it returns without taking any other actions. +The return value is always an empty string. +If the first argument is variable (or any abbreviation of +it) then the second argument is the name of a global variable and the +command waits for that variable to be modified. +If the first argument is visibility (or any abbreviation +of it) then the second argument is the name of a window and the +tkwait command waits for a change in its +visibility state (as indicated by the arrival of a VisibilityNotify +event). This form is typically used to wait for a newly-created +window to appear on the screen before taking some action. +If the first argument is window (or any abbreviation +of it) then the second argument is the name of a window and the +tkwait command waits for that window to be destroyed. +This form is typically used to wait for a user to finish interacting +with a dialog box before using the result of that interaction. +

    +While the tkwait command is waiting it processes events in +the normal fashion, so the application will continue to respond +to user interactions. +If an event handler invokes tkwait again, the nested call +to tkwait must complete before the outer call can complete. + +

    KEYWORDS

    +variable, visibility, wait, window +
    +Copyright © 1992 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/toplevel.htm b/hlp/en/tk/toplevel.htm new file mode 100644 index 0000000..5089789 --- /dev/null +++ b/hlp/en/tk/toplevel.htm @@ -0,0 +1,211 @@ +Tk Built-In Commands - toplevel manual page +
    +
    NAME +
    toplevel - Create and manipulate toplevel widgets
    +
    SYNOPSIS +
    +
    toplevel pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -background, background, Background +
    -class, class, Class +
    -colormap, colormap, Colormap +
    -container, container, Container +
    -height, height, Height +
    -menu, menu, Menu +
    -screen, , +
    -use, use, Use +
    -visual, visual, Visual +
    -width, width, Width +
    +
    DESCRIPTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    BINDINGS +
    KEYWORDS +

    +

    NAME

    +toplevel - Create and manipulate toplevel widgets +

    SYNOPSIS

    +toplevelpathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -background +
    Database Name: background +
    Database Class: Background +
    This option is the same as the standard background option +except that its value may also be specified as an empty string. +In this case, the widget will display no background or border, and +no colors will be consumed from its colormap for its background +and border. +

    Command-Line Name: -class +
    Database Name: class +
    Database Class: Class +
    Specifies a class for the window. +This class will be used when querying the option database for +the window's other options, and it will also be used later for +other purposes such as bindings. +The class option may not be changed with the configure +widget command. +

    Command-Line Name: -colormap +
    Database Name: colormap +
    Database Class: Colormap +
    Specifies a colormap to use for the window. +The value may be either new, in which case a new colormap is +created for the window and its children, or the name of another +window (which must be on the same screen and have the same visual +as pathName), in which case the new window will use the colormap +from the specified window. +If the colormap option is not specified, the new window +uses the default colormap of its screen. +This option may not be changed with the configure +widget command. +

    Command-Line Name: -container +
    Database Name: container +
    Database Class: Container +
    The value must be a boolean. If true, it means that this window will +be used as a container in which some other application will be embedded +(for example, a Tk toplevel can be embedded using the -use option). +The window will support the appropriate window manager protocols for +things like geometry requests. The window should not have any +children of its own in this application. +This option may not be changed with the configure +widget command. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies the desired height for the window in any of the forms +acceptable to Tk_GetPixels. +If this option is less than or equal to zero then the window will +not request any size at all. +

    Command-Line Name: -menu +
    Database Name: menu +
    Database Class: Menu +
    Specifies a menu widget to be used as a menubar. On the Macintosh, the +menubar will be displayed accross the top of the main monitor. On +Microsoft Windows and all UNIX platforms, the menu will appear accross +the toplevel window as part of the window dressing maintained by the +window manager. +

    Command-Line Name: -screen +
    Database Name: +
    Database Class: +
    Specifies the screen on which to place the new window. +Any valid screen name may be used, even one associated with a +different display. +Defaults to the same screen as its parent. +This option is special in that it may not be specified via the option +database, and it may not be modified with the configure +widget command. +

    Command-Line Name: -use +
    Database Name: use +
    Database Class: Use +
    This option is used for embedding. If the value isn't an empty string, +it must be the the window identifier of a container window, specified as +a hexadecimal string like the ones returned by the winfo id +command. The toplevel widget will be created as a child of the given +container instead of the root window for the screen. If the container +window is in a Tk application, it must be a frame or toplevel widget for +which the -container option was specified. +This option may not be changed with the configure +widget command. +

    Command-Line Name: -visual +
    Database Name: visual +
    Database Class: Visual +
    Specifies visual information for the new window in any of the +forms accepted by Tk_GetVisual. +If this option is not specified, the new window will use the default +visual for its screen. +The visual option may not be modified with the configure +widget command. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies the desired width for the window in any of the forms +acceptable to Tk_GetPixels. +If this option is less than or equal to zero then the window will +not request any size at all. +
    +

    DESCRIPTION

    +The toplevel command creates a new toplevel widget (given +by the pathName argument). Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the toplevel such as its background color +and relief. The toplevel command returns the +path name of the new window. +

    +A toplevel is similar to a frame except that it is created as a +top-level window: its X parent is the root window of a screen +rather than the logical parent from its path name. The primary +purpose of a toplevel is to serve as a container for dialog boxes +and other collections of widgets. The only visible features +of a toplevel are its background color and an optional 3-D border +to make the toplevel appear raised or sunken. + +

    WIDGET COMMAND

    +The toplevel command creates a new Tcl command whose +name is the same as the path name of the toplevel's window. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +PathName is the name of the command, which is the same as +the toplevel widget's path name. Option and the args +determine the exact behavior of the command. The following +commands are possible for toplevel widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the toplevel +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the toplevel +command. + +

    +

    BINDINGS

    +When a new toplevel is created, it has no default event bindings: +toplevels are not intended to be interactive. + +

    KEYWORDS

    +toplevel, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/winfo.htm b/hlp/en/tk/winfo.htm new file mode 100644 index 0000000..a43cb91 --- /dev/null +++ b/hlp/en/tk/winfo.htm @@ -0,0 +1,332 @@ +Tk Built-In Commands - winfo manual page +
    +
    NAME +
    winfo - Return window-related information
    +
    SYNOPSIS +
    +
    winfo option ?arg arg ...? +
    +
    DESCRIPTION +
    +
    winfo atom ?-displayof window? name +
    winfo atomname ?-displayof window? id +
    winfo cells window +
    winfo children window +
    winfo class window +
    winfo colormapfull window +
    winfo containing ?-displayof window? rootX rootY +
    winfo depth window +
    winfo exists window +
    winfo fpixels window number +
    winfo geometry window +
    winfo height window +
    winfo id window +
    winfo interps ?-displayof window? +
    winfo ismapped window +
    winfo manager window +
    winfo name window +
    winfo parent window +
    winfo pathname ?-displayof window? id +
    winfo pixels window number +
    winfo pointerx window +
    winfo pointerxy window +
    winfo pointery window +
    winfo reqheight window +
    winfo reqwidth window +
    winfo rgb window color +
    winfo rootx window +
    winfo rooty window +
    winfo screen window +
    winfo screencells window +
    winfo screendepth window +
    winfo screenheight window +
    winfo screenmmheight window +
    winfo screenmmwidth window +
    winfo screenvisual window +
    winfo screenwidth window +
    winfo server window +
    winfo toplevel window +
    winfo viewable window +
    winfo visual window +
    winfo visualid window +
    winfo visualsavailable window ?includeids? +
    winfo vrootheight window +
    winfo vrootwidth window +
    winfo vrootx window +
    winfo vrooty window +
    winfo width window +
    winfo x window +
    winfo y window +
    +
    KEYWORDS +

    +

    NAME

    +winfo - Return window-related information +

    SYNOPSIS

    +winfooption ?arg arg ...?
    +

    DESCRIPTION

    +The winfo command is used to retrieve information about windows +managed by Tk. It can take any of a number of different forms, +depending on the option argument. The legal forms are: +

    +

    +

    winfo atom ?-displayof window? name
    +Returns a decimal string giving the integer identifier for the +atom whose name is name. If no atom exists with the name +name then a new one is created. +If the -displayof option is given then the atom is looked +up on the display of window; otherwise it is looked up on +the display of the application's main window. +

    winfo atomname ?-displayof window? id
    +Returns the textual name for the atom whose integer identifier is +id. +If the -displayof option is given then the identifier is looked +up on the display of window; otherwise it is looked up on +the display of the application's main window. +This command is the inverse of the winfo atom command. +It generates an error if no such atom exists. +

    winfo cells window
    +Returns a decimal string giving the number of cells in the +color map for window. +

    winfo children window
    +Returns a list containing the path names of all the children +of window. The list is in stacking order, with the lowest +window first. Top-level windows are returned as children +of their logical parents. +

    winfo class window
    +Returns the class name for window. +

    winfo colormapfull window
    +Returns 1 if the colormap for window is known to be full, 0 +otherwise. The colormap for a window is ``known'' to be full if the last +attempt to allocate a new color on that window failed and this +application hasn't freed any colors in the colormap since the +failed allocation. +

    winfo containing ?-displayof window? rootX rootY
    +Returns the path name for the window containing the point given +by rootX and rootY. +RootX and rootY are specified in screen units (i.e. +any form acceptable to Tk_GetPixels) in the coordinate +system of the root window (if a virtual-root window manager is in +use then the coordinate system of the virtual root window is used). +If the -displayof option is given then the coordinates refer +to the screen containing window; otherwise they refer to the +screen of the application's main window. +If no window in this application contains the point then an empty +string is returned. +In selecting the containing window, children are given higher priority +than parents and among siblings the highest one in the stacking order is +chosen. +

    winfo depth window
    +Returns a decimal string giving the depth of window (number +of bits per pixel). +

    winfo exists window
    +Returns 1 if there exists a window named window, 0 if no such +window exists. +

    winfo fpixels window number
    +Returns a floating-point value giving the number of pixels +in window corresponding to the distance given by number. +Number may be specified in any of the forms acceptable +to Tk_GetScreenMM, such as ``2.0c'' or ``1i''. +The return value may be fractional; for an integer value, use +winfo pixels. +

    winfo geometry window
    +Returns the geometry for window, in the form +widthxheight+x+y. All dimensions are +in pixels. +

    winfo height window
    +Returns a decimal string giving window's height in pixels. +When a window is first created its height will be 1 pixel; the +height will eventually be changed by a geometry manager to fulfill +the window's needs. +If you need the true height immediately after creating a widget, +invoke update to force the geometry manager to arrange it, +or use winfo reqheight to get the window's requested height +instead of its actual height. +

    winfo id window
    +Returns a hexadecimal string giving a low-level platform-specific +identifier for window. On Unix platforms, this is the X +window identifier. Under Windows, this is the Windows +HWND. On the Macintosh the value has no meaning outside Tk. +

    winfo interps ?-displayof window?
    +Returns a list whose members are the names of all Tcl interpreters +(e.g. all Tk-based applications) currently registered for a particular display. +If the -displayof option is given then the return value refers +to the display of window; otherwise it refers to +the display of the application's main window. +

    winfo ismapped window
    +Returns 1 if window is currently mapped, 0 otherwise. +

    winfo manager window
    +Returns the name of the geometry manager currently +responsible for window, or an empty string if window +isn't managed by any geometry manager. +The name is usually the name of the Tcl command for the geometry +manager, such as pack or place. +If the geometry manager is a widget, such as canvases or text, the +name is the widget's class command, such as canvas. +

    winfo name window
    +Returns window's name (i.e. its name within its parent, as opposed +to its full path name). +The command winfo name . will return the name of the application. +

    winfo parent window
    +Returns the path name of window's parent, or an empty string +if window is the main window of the application. +

    winfo pathname ?-displayof window? id
    +Returns the path name of the window whose X identifier is id. +Id must be a decimal, hexadecimal, or octal integer and must +correspond to a window in the invoking application. +If the -displayof option is given then the identifier is looked +up on the display of window; otherwise it is looked up on +the display of the application's main window. +

    winfo pixels window number
    +Returns the number of pixels in window corresponding +to the distance given by number. +Number may be specified in any of the forms acceptable +to Tk_GetPixels, such as ``2.0c'' or ``1i''. +The result is rounded to the nearest integer value; for a +fractional result, use winfo fpixels. +

    winfo pointerx window
    +If the mouse pointer is on the same screen as window, returns the +pointer's x coordinate, measured in pixels in the screen's root window. +If a virtual root window is in use on the screen, the position is +measured in the virtual root. +If the mouse pointer isn't on the same screen as window then +-1 is returned. +

    winfo pointerxy window
    +If the mouse pointer is on the same screen as window, returns a list +with two elements, which are the pointer's x and y coordinates measured +in pixels in the screen's root window. +If a virtual root window is in use on the screen, the position +is computed in the virtual root. +If the mouse pointer isn't on the same screen as window then +both of the returned coordinates are -1. +

    winfo pointery window
    +If the mouse pointer is on the same screen as window, returns the +pointer's y coordinate, measured in pixels in the screen's root window. +If a virtual root window is in use on the screen, the position +is computed in the virtual root. +If the mouse pointer isn't on the same screen as window then +-1 is returned. +

    winfo reqheight window
    +Returns a decimal string giving window's requested height, +in pixels. This is the value used by window's geometry +manager to compute its geometry. +

    winfo reqwidth window
    +Returns a decimal string giving window's requested width, +in pixels. This is the value used by window's geometry +manager to compute its geometry. +

    winfo rgb window color
    +Returns a list containing three decimal values, which are the +red, green, and blue intensities that correspond to color in +the window given by window. Color +may be specified in any of the forms acceptable for a color +option. +

    winfo rootx window
    +Returns a decimal string giving the x-coordinate, in the root +window of the screen, of the +upper-left corner of window's border (or window if it +has no border). +

    winfo rooty window
    +Returns a decimal string giving the y-coordinate, in the root +window of the screen, of the +upper-left corner of window's border (or window if it +has no border). +

    winfo screen window
    +Returns the name of the screen associated with window, in +the form displayName.screenIndex. +

    winfo screencells window
    +Returns a decimal string giving the number of cells in the default +color map for window's screen. +

    winfo screendepth window
    +Returns a decimal string giving the depth of the root window +of window's screen (number of bits per pixel). +

    winfo screenheight window
    +Returns a decimal string giving the height of window's screen, +in pixels. +

    winfo screenmmheight window
    +Returns a decimal string giving the height of window's screen, +in millimeters. +

    winfo screenmmwidth window
    +Returns a decimal string giving the width of window's screen, +in millimeters. +

    winfo screenvisual window
    +Returns one of the following strings to indicate the default visual +class for window's screen: directcolor, grayscale, +pseudocolor, staticcolor, staticgray, or +truecolor. +

    winfo screenwidth window
    +Returns a decimal string giving the width of window's screen, +in pixels. +

    winfo server window
    +Returns a string containing information about the server for +window's display. The exact format of this string may vary +from platform to platform. For X servers the string +has the form ``XmajorRminor vendor vendorVersion'' +where major and minor are the version and revision +numbers provided by the server (e.g., X11R5), vendor +is the name of the vendor for the server, and vendorRelease +is an integer release number provided by the server. +

    winfo toplevel window
    +Returns the path name of the top-level window containing window. +

    winfo viewable window
    +Returns 1 if window and all of its ancestors up through the +nearest toplevel window are mapped. Returns 0 if any of these +windows are not mapped. +

    winfo visual window
    +Returns one of the following strings to indicate the visual +class for window: directcolor, grayscale, +pseudocolor, staticcolor, staticgray, or +truecolor. +

    winfo visualid window
    +Returns the X identifier for the visual for window. +

    winfo visualsavailable window ?includeids?
    +Returns a list whose elements describe the visuals available for +window's screen. +Each element consists of a visual class followed by an integer depth. +The class has the same form as returned by winfo visual. +The depth gives the number of bits per pixel in the visual. +In addition, if the includeids argument is provided, then the +depth is followed by the X identifier for the visual. +

    winfo vrootheight window
    +Returns the height of the virtual root window associated with window +if there is one; otherwise returns the height of window's screen. +

    winfo vrootwidth window
    +Returns the width of the virtual root window associated with window +if there is one; otherwise returns the width of window's screen. +

    winfo vrootx window
    +Returns the x-offset of the virtual root window associated with window, +relative to the root window of its screen. +This is normally either zero or negative. +Returns 0 if there is no virtual root window for window. +

    winfo vrooty window
    +Returns the y-offset of the virtual root window associated with window, +relative to the root window of its screen. +This is normally either zero or negative. +Returns 0 if there is no virtual root window for window. +

    winfo width window
    +Returns a decimal string giving window's width in pixels. +When a window is first created its width will be 1 pixel; the +width will eventually be changed by a geometry manager to fulfill +the window's needs. +If you need the true width immediately after creating a widget, +invoke update to force the geometry manager to arrange it, +or use winfo reqwidth to get the window's requested width +instead of its actual width. +

    winfo x window
    +Returns a decimal string giving the x-coordinate, in window's +parent, of the +upper-left corner of window's border (or window if it +has no border). +

    winfo y window
    +Returns a decimal string giving the y-coordinate, in window's +parent, of the +upper-left corner of window's border (or window if it +has no border). + +

    +

    KEYWORDS

    +atom, children, class, geometry, height, identifier, information, interpreters, mapped, parent, path name, screen, virtual root, width, window +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/wish.htm b/hlp/en/tk/wish.htm new file mode 100644 index 0000000..03fafa6 --- /dev/null +++ b/hlp/en/tk/wish.htm @@ -0,0 +1,198 @@ +Tk Applications - wish manual page +
    +
    NAME +
    wish - Simple windowing shell
    +
    SYNOPSIS +
    +
    wish ?fileName arg arg ...? +
    +
    OPTIONS +
    +
    -colormap new +
    -display display +
    -geometry geometry +
    -name name +
    -sync +
    -use id +
    -visual visual +
    - - +
    +
    DESCRIPTION +
    OPTIONS +
    APPLICATION NAME AND CLASS +
    VARIABLES +
    +
    argc +
    argv +
    argv0 +
    geometry +
    tcl_interactive +
    +
    SCRIPT FILES +
    PROMPTS +
    KEYWORDS +

    +

    NAME

    +wish - Simple windowing shell +

    SYNOPSIS

    +wish ?fileName arg arg ...?
    +

    OPTIONS

    +
    +

    -colormap new
    +Specifies that the window should have a new private colormap instead of +using the default colormap for the screen. +

    -display display
    +Display (and screen) on which to display window. +

    -geometry geometry
    +Initial geometry to use for window. If this option is specified, its +value is stored in the geometry global variable of the application's +Tcl interpreter. +

    -name name
    +Use name as the title to be displayed in the window, and +as the name of the interpreter for send commands. +

    -sync
    +Execute all X server commands synchronously, so that errors +are reported immediately. This will result in much slower +execution, but it is useful for debugging. +

    -use id
    +Specifies that the main window for the application is to be embedded in +the window whose identifier is id, instead of being created as an +independent toplevel window. Id must be specified in the same +way as the value for the -use option for toplevel widgets (i.e. +it has a form like that returned by the winfo id command). +

    -visual visual
    +Specifies the visual to use for the window. +Visual may have any of the forms supported by the Tk_GetVisual +procedure. +

    - -
    +Pass all remaining arguments through to the script's argv +variable without interpreting them. +This provides a mechanism for passing arguments such as -name +to a script instead of having wish interpret them. +

    +

    DESCRIPTION

    +Wish is a simple program consisting of the Tcl command +language, the Tk toolkit, and a main program that reads commands +from standard input or from a file. +It creates a main window and then processes Tcl commands. +If wish is invoked with no arguments, or with a first argument +that starts with ``-'', then it reads Tcl commands interactively from +standard input. +It will continue processing commands until all windows have been +deleted or until end-of-file is reached on standard input. +If there exists a file .wishrc in the home directory of +the user, wish evaluates the file as a Tcl script +just before reading the first command from standard input. +

    +If wish is invoked with an initial fileName argument, then +fileName is treated as the name of a script file. +Wish will evaluate the script in fileName (which +presumably creates a user interface), then it will respond to events +until all windows have been deleted. +Commands will not be read from standard input. +There is no automatic evaluation of .wishrc in this +case, but the script file can always source it if desired. + +

    OPTIONS

    +Wish automatically processes all of the command-line options +described in the OPTIONS summary above. +Any other command-line arguments besides these are passed through +to the application using the argc and argv variables +described later. + +

    APPLICATION NAME AND CLASS

    +The name of the application, which is used for purposes such as +send commands, is taken from the -name option, +if it is specified; otherwise it is taken from fileName, +if it is specified, or from the command name by which +wish was invoked. In the last two cases, if the name contains a ``/'' +character, then only the characters after the last slash are used +as the application name. +

    +The class of the application, which is used for purposes such as +specifying options with a RESOURCE_MANAGER property or .Xdefaults +file, is the same as its name except that the first letter is +capitalized. + +

    VARIABLES

    +Wish sets the following Tcl variables: +

    +

    +

    argc
    +Contains a count of the number of arg arguments (0 if none), +not including the options described above. +

    argv
    +Contains a Tcl list whose elements are the arg arguments +that follow a - - option or don't match any of the +options described in OPTIONS above, in order, or an empty string +if there are no such arguments. +

    argv0
    +Contains fileName if it was specified. +Otherwise, contains the name by which wish was invoked. +

    geometry
    +If the -geometry option is specified, wish copies its +value into this variable. If the variable still exists after +fileName has been evaluated, wish uses the value of +the variable in a wm geometry command to set the main +window's geometry. +

    tcl_interactive
    +Contains 1 if wish is reading commands interactively (fileName +was not specified and standard input is a terminal-like +device), 0 otherwise. + +

    +

    SCRIPT FILES

    +If you create a Tcl script in a file whose first line is +
    #!/usr/local/bin/wish
    +then you can invoke the script file directly from your shell if +you mark it as executable. +This assumes that wish has been installed in the default +location in /usr/local/bin; if it's installed somewhere else +then you'll have to modify the above line to match. +Many UNIX systems do not allow the #! line to exceed about +30 characters in length, so be sure that the wish executable +can be accessed with a short file name. +

    +An even better approach is to start your script files with the +following three lines: +

    #!/bin/sh
    +# the next line restarts using wish \
    +exec wish "$0" "$@"
    +This approach has three advantages over the approach in the previous +paragraph. First, the location of the wish binary doesn't have +to be hard-wired into the script: it can be anywhere in your shell +search path. Second, it gets around the 30-character file name limit +in the previous approach. +Third, this approach will work even if wish is +itself a shell script (this is done on some systems in order to +handle multiple architectures or operating systems: the wish +script selects one of several binaries to run). The three lines +cause both sh and wish to process the script, but the +exec is only executed by sh. +sh processes the script first; it treats the second +line as a comment and executes the third line. +The exec statement cause the shell to stop processing and +instead to start up wish to reprocess the entire script. +When wish starts up, it treats all three lines as comments, +since the backslash at the end of the second line causes the third +line to be treated as part of the comment on the second line. + +

    PROMPTS

    +When wish is invoked interactively it normally prompts for each +command with ``% ''. You can change the prompt by setting the +variables tcl_prompt1 and tcl_prompt2. If variable +tcl_prompt1 exists then it must consist of a Tcl script +to output a prompt; instead of outputting a prompt wish +will evaluate the script in tcl_prompt1. +The variable tcl_prompt2 is used in a similar way when +a newline is typed but the current command isn't yet complete; +if tcl_prompt2 isn't set then no prompt is output for +incomplete commands. + +

    KEYWORDS

    +shell, toolkit +
    +Copyright © 1991-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/en/tk/wm.htm b/hlp/en/tk/wm.htm new file mode 100644 index 0000000..0d2f89d --- /dev/null +++ b/hlp/en/tk/wm.htm @@ -0,0 +1,519 @@ +Tk Built-In Commands - wm manual page +
    +
    NAME +
    wm - Communicate with window manager
    +
    SYNOPSIS +
    +
    wm option window ?args? +
    +
    DESCRIPTION +
    +
    wm aspect window ?minNumer minDenom maxNumer maxDenom? +
    wm client window ?name? +
    wm colormapwindows window ?windowList? +
    wm command window ?value? +
    wm deiconify window +
    wm focusmodel window ?active|passive? +
    wm frame window +
    wm geometry window ?newGeometry? +
    wm grid window ?baseWidth baseHeight widthInc heightInc? +
    wm group window ?pathName? +
    wm iconbitmap window ?bitmap? +
    wm iconify window +
    wm iconmask window ?bitmap? +
    wm iconname window ?newName? +
    wm iconposition window ?x y? +
    wm iconwindow window ?pathName? +
    wm maxsize window ?width height? +
    wm minsize window ?width height? +
    wm overrideredirect window ?boolean? +
    wm positionfrom window ?who? +
    wm protocol window ?name? ?command? +
    wm resizable window ?width height? +
    wm sizefrom window ?who? +
    wm state window ?newstate? +
    wm title window ?string? +
    wm transient window ?master? +
    wm withdraw window +
    +
    GEOMETRY MANAGEMENT +
    GRIDDED GEOMETRY MANAGEMENT +
    BUGS +
    KEYWORDS +

    +

    NAME

    +wm - Communicate with window manager +

    SYNOPSIS

    +wmoption window ?args?
    +

    DESCRIPTION

    +The wm command is used to interact with window managers in +order to control such things as the title for a window, its geometry, +or the increments in terms of which it may be resized. The wm +command can take any of a number of different forms, depending on +the option argument. All of the forms expect at least one +additional argument, window, which must be the path name of a +top-level window. +

    +The legal forms for the wm command are: +

    +

    +

    wm aspect window ?minNumer minDenom maxNumer maxDenom?
    +If minNumer, minDenom, maxNumer, and maxDenom +are all specified, then they will be passed to the window manager +and the window manager should use them to enforce a range of +acceptable aspect ratios for window. The aspect ratio of +window (width/length) will be constrained to lie +between minNumer/minDenom and maxNumer/maxDenom. +If minNumer etc. are all specified as empty strings, then +any existing aspect ratio restrictions are removed. +If minNumer etc. are specified, then the command returns an +empty string. Otherwise, it returns +a Tcl list containing four elements, which are the current values +of minNumer, minDenom, maxNumer, and maxDenom +(if no aspect restrictions are in effect, then an empty string is +returned). +

    wm client window ?name?
    +If name is specified, this command stores name (which +should be the name of +the host on which the application is executing) in window's +WM_CLIENT_MACHINE property for use by the window manager or +session manager. +The command returns an empty string in this case. +If name isn't specified, the command returns the last name +set in a wm client command for window. +If name is specified as an empty string, the command deletes the +WM_CLIENT_MACHINE property from window. +

    wm colormapwindows window ?windowList?
    +This command is used to manipulate the WM_COLORMAP_WINDOWS +property, which provides information to the window managers about +windows that have private colormaps. +If windowList isn't specified, the command returns a list +whose elements are the names of the windows in the WM_COLORMAP_WINDOWS +property. +If windowList is specified, it consists of a list of window +path names; the command overwrites the WM_COLORMAP_WINDOWS +property with the given windows and returns an empty string. +The WM_COLORMAP_WINDOWS property should normally contain a +list of the internal windows within window whose colormaps differ +from their parents. +The order of the windows in the property indicates a priority order: +the window manager will attempt to install as many colormaps as possible +from the head of this list when window gets the colormap focus. +If window is not included among the windows in windowList, +Tk implicitly adds it at the end of the WM_COLORMAP_WINDOWS +property, so that its colormap is lowest in priority. +If wm colormapwindows is not invoked, Tk will automatically set +the property for each top-level window to all the internal windows +whose colormaps differ from their parents, followed by the top-level +itself; the order of the internal windows is undefined. +See the ICCCM documentation for more information on the +WM_COLORMAP_WINDOWS property. +

    wm command window ?value?
    +If value is specified, this command stores value in window's +WM_COMMAND property for use by the window manager or +session manager and returns an empty string. +Value must have proper list structure; the elements should +contain the words of the command used to invoke the application. +If value isn't specified then the command returns the last value +set in a wm command command for window. +If value is specified as an empty string, the command +deletes the WM_COMMAND property from window. +

    wm deiconify window
    +Arrange for window to be displayed in normal (non-iconified) form. +This is done by mapping the window. If the window has never been +mapped then this command will not map the window, but it will ensure +that when the window is first mapped it will be displayed +in de-iconified form. On Windows, a deiconified window will also be +raised and be given the focus (made the active window). +Returns an empty string. +

    wm focusmodel window ?active|passive?
    +If active or passive is supplied as an optional argument +to the command, then it specifies the focus model for window. +In this case the command returns an empty string. If no additional +argument is supplied, then the command returns the current focus +model for window. +An active focus model means that window will claim the +input focus for itself or its descendants, even at times when +the focus is currently in some other application. Passive means that +window will never claim the focus for itself: the window manager +should give the focus to window at appropriate times. However, +once the focus has been given to window or one of its descendants, +the application may re-assign the focus among window's descendants. +The focus model defaults to passive, and Tk's focus command +assumes a passive model of focusing. +

    wm frame window
    +If window has been reparented by the window manager into a +decorative frame, the command returns the platform specific window +identifier for the outermost frame that contains window (the +window whose parent is the root or virtual root). If window +hasn't been reparented by the window manager then the command returns +the platform specific window identifier for window. +

    wm geometry window ?newGeometry?
    +If newGeometry is specified, then the geometry of window +is changed and an empty string is returned. Otherwise the current +geometry for window is returned (this is the most recent +geometry specified either by manual resizing or +in a wm geometry command). NewGeometry has +the form =widthxheight±x±y, where +any of =, widthxheight, or ±x±y +may be omitted. Width and height are positive integers +specifying the desired dimensions of window. If window +is gridded (see GRIDDED GEOMETRY MANAGEMENT below) then the dimensions +are specified in grid units; otherwise they are specified in pixel +units. X and y specify the desired location of +window on the screen, in pixels. +If x is preceded by +, it specifies +the number of pixels between the left edge of the screen and the left +edge of window's border; if preceded by - then +x specifies the number of pixels +between the right edge of the screen and the right edge of window's +border. If y is preceded by + then it specifies the +number of pixels between the top of the screen and the top +of window's border; if y is preceded by - then +it specifies the number of pixels between the bottom of window's +border and the bottom of the screen. +If newGeometry is specified as an empty string then any +existing user-specified geometry for window is cancelled, and +the window will revert to the size requested internally by its +widgets. +

    wm grid window ?baseWidth baseHeight widthInc heightInc?
    +This command indicates that window is to be managed as a +gridded window. +It also specifies the relationship between grid units and pixel units. +BaseWidth and baseHeight specify the number of grid +units corresponding to the pixel dimensions requested internally +by window using Tk_GeometryRequest. WidthInc +and heightInc specify the number of pixels in each horizontal +and vertical grid unit. +These four values determine a range of acceptable sizes for +window, corresponding to grid-based widths and heights +that are non-negative integers. +Tk will pass this information to the window manager; during +manual resizing, the window manager will restrict the window's size +to one of these acceptable sizes. +Furthermore, during manual resizing the window manager will display +the window's current size in terms of grid units rather than pixels. +If baseWidth etc. are all specified as empty strings, then +window will no longer be managed as a gridded window. If +baseWidth etc. are specified then the return value is an +empty string. +Otherwise the return value is a Tcl list containing +four elements corresponding to the current baseWidth, +baseHeight, widthInc, and heightInc; if +window is not currently gridded, then an empty string +is returned. +Note: this command should not be needed very often, since the +Tk_SetGrid library procedure and the setGrid option +provide easier access to the same functionality. +

    wm group window ?pathName?
    +If pathName is specified, it gives the path name for the leader of +a group of related windows. The window manager may use this information, +for example, to unmap all of the windows in a group when the group's +leader is iconified. PathName may be specified as an empty string to +remove window from any group association. If pathName is +specified then the command returns an empty string; otherwise it +returns the path name of window's current group leader, or an empty +string if window isn't part of any group. +

    wm iconbitmap window ?bitmap?
    +If bitmap is specified, then it names a bitmap in the standard +forms accepted by Tk (see the Tk_GetBitmap manual entry for details). +This bitmap is passed to the window manager to be displayed in +window's icon, and the command returns an empty string. If +an empty string is specified for bitmap, then any current icon +bitmap is cancelled for window. +If bitmap is specified then the command returns an empty string. +Otherwise it returns the name of +the current icon bitmap associated with window, or an empty +string if window has no icon bitmap. On the Windows operating +system, an additional flag is supported: +wm iconbitmap window ?-default? ?image?. +If the -default +flag is given, the icon is applied to all toplevel windows (existing +and future) to which no other specific icon has yet been applied. +In addition to bitmap image types, any file which contains a valid +Windows icon is also accepted (usually .ico or .icr files). Tcl will +first test if the files contains an icon, and if that fails, test for +a bitmap. +

    wm iconify window
    +Arrange for window to be iconified. It window hasn't +yet been mapped for the first time, this command will arrange for +it to appear in the iconified state when it is eventually mapped. +

    wm iconmask window ?bitmap?
    +If bitmap is specified, then it names a bitmap in the standard +forms accepted by Tk (see the Tk_GetBitmap manual entry for details). +This bitmap is passed to the window manager to be used as a mask +in conjunction with the iconbitmap option: where the mask +has zeroes no icon will be displayed; where it has ones, the bits +from the icon bitmap will be displayed. If +an empty string is specified for bitmap then any current icon +mask is cancelled for window (this is equivalent to specifying +a bitmap of all ones). If bitmap is specified +then the command returns an empty string. Otherwise it +returns the name of the current icon mask associated with +window, or an empty string if no mask is in effect. +

    wm iconname window ?newName?
    +If newName is specified, then it is passed to the window +manager; the window manager should display newName inside +the icon associated with window. In this case an empty +string is returned as result. If newName isn't specified +then the command returns the current icon name for window, +or an empty string if no icon name has been specified (in this +case the window manager will normally display the window's title, +as specified with the wm title command). +

    wm iconposition window ?x y?
    +If x and y are specified, they are passed to the window +manager as a hint about where to position the icon for window. +In this case an empty string is returned. If x and y are +specified as empty strings then any existing icon position hint is cancelled. +If neither x nor y is specified, then the command returns +a Tcl list containing two values, which are the current icon position +hints (if no hints are in effect then an empty string is returned). +

    wm iconwindow window ?pathName?
    +If pathName is specified, it is the path name for a window to +use as icon for window: when window is iconified then +pathName will be mapped to serve as icon, and when window +is de-iconified then pathName will be unmapped again. If +pathName is specified as an empty string then any existing +icon window association for window will be cancelled. If +the pathName argument is specified then an empty string is +returned. Otherwise the command returns the path name of the +current icon window for window, or an empty string if there +is no icon window currently specified for window. +Button press events are disabled for window as long as it is +an icon window; this is needed in order to allow window managers +to ``own'' those events. +Note: not all window managers support the notion of an icon window. +

    wm maxsize window ?width height?
    +If width and height are specified, they give +the maximum permissible dimensions for window. +For gridded windows the dimensions are specified in +grid units; otherwise they are specified in pixel units. +The window manager will restrict the window's dimensions to be +less than or equal to width and height. +If width and height are +specified, then the command returns an empty string. Otherwise +it returns a Tcl list with two elements, which are the +maximum width and height currently in effect. +The maximum size defaults to the size of the screen. +If resizing has been disabled with the wm resizable command, +then this command has no effect. +See the sections on geometry management below for more information. +

    wm minsize window ?width height?
    +If width and height are specified, they give the +minimum permissible dimensions for window. +For gridded windows the dimensions are specified in +grid units; otherwise they are specified in pixel units. +The window manager will restrict the window's dimensions to be +greater than or equal to width and height. +If width and height are +specified, then the command returns an empty string. Otherwise +it returns a Tcl list with two elements, which are the +minimum width and height currently in effect. +The minimum size defaults to one pixel in each dimension. +If resizing has been disabled with the wm resizable command, +then this command has no effect. +See the sections on geometry management below for more information. +

    wm overrideredirect window ?boolean?
    +If boolean is specified, it must have a proper boolean form and +the override-redirect flag for window is set to that value. +If boolean is not specified then 1 or 0 is +returned to indicate whether or not the override-redirect flag +is currently set for window. +Setting the override-redirect flag for a window causes +it to be ignored by the window manager; among other things, this means +that the window will not be reparented from the root window into a +decorative frame and the user will not be able to manipulate the +window using the normal window manager mechanisms. +

    wm positionfrom window ?who?
    +If who is specified, it must be either program or +user, or an abbreviation of one of these two. It indicates +whether window's current position was requested by the +program or by the user. Many window managers ignore program-requested +initial positions and ask the user to manually position the window; if +user is specified then the window manager should position the +window at the given place without asking the user for assistance. +If who is specified as an empty string, then the current position +source is cancelled. +If who is specified, then the command returns an empty string. +Otherwise it returns user or program to indicate the +source of the window's current position, or an empty string if +no source has been specified yet. Most window managers interpret +``no source'' as equivalent to program. +Tk will automatically set the position source to user +when a wm geometry command is invoked, unless the source has +been set explicitly to program. +

    wm protocol window ?name? ?command?
    +This command is used to manage window manager protocols such as +WM_DELETE_WINDOW. +Name is the name of an atom corresponding to a window manager +protocol, such as WM_DELETE_WINDOW or WM_SAVE_YOURSELF +or WM_TAKE_FOCUS. +If both name and command are specified, then command +is associated with the protocol specified by name. +Name will be added to window's WM_PROTOCOLS +property to tell the window manager that the application has a +protocol handler for name, and command will +be invoked in the future whenever the window manager sends a +message to the client for that protocol. +In this case the command returns an empty string. +If name is specified but command isn't, then the current +command for name is returned, or an empty string if there +is no handler defined for name. +If command is specified as an empty string then the current +handler for name is deleted and it is removed from the +WM_PROTOCOLS property on window; an empty string is +returned. +Lastly, if neither name nor command is specified, the +command returns a list of all the protocols for which handlers +are currently defined for window. +

    +Tk always defines a protocol handler for WM_DELETE_WINDOW, even if +you haven't asked for one with wm protocol. +If a WM_DELETE_WINDOW message arrives when you haven't defined +a handler, then Tk handles the message by destroying the window for +which it was received. +

    wm resizable window ?width height?
    +This command controls whether or not the user may interactively +resize a top-level window. If width and height are +specified, they are boolean values that determine whether the +width and height of window may be modified by the user. +In this case the command returns an empty string. +If width and height are omitted then the command +returns a list with two 0/1 elements that indicate whether the +width and height of window are currently resizable. +By default, windows are resizable in both dimensions. +If resizing is disabled, then the window's size will be the size +from the most recent interactive resize or wm geometry +command. If there has been no such operation then +the window's natural size will be used. +

    wm sizefrom window ?who?
    +If who is specified, it must be either program or +user, or an abbreviation of one of these two. It indicates +whether window's current size was requested by the +program or by the user. Some window managers ignore program-requested +sizes and ask the user to manually size the window; if +user is specified then the window manager should give the +window its specified size without asking the user for assistance. +If who is specified as an empty string, then the current size +source is cancelled. +If who is specified, then the command returns an empty string. +Otherwise it returns user or window to indicate the +source of the window's current size, or an empty string if +no source has been specified yet. Most window managers interpret +``no source'' as equivalent to program. +

    wm state window ?newstate?
    +If newstate is specified, the window will be set to the new state, +otherwise it returns the current state of window: either +normal, iconic, withdrawn, icon, or (Windows only) +zoomed. The difference between iconic and icon is that +iconic refers to a window that has been iconified (e.g., with the +wm iconify command) while icon refers to a window whose only +purpose is to serve as the icon for some other window (via the wm +iconwindow command). The icon state cannot be set. +

    wm title window ?string?
    +If string is specified, then it will be passed to the window +manager for use as the title for window (the window manager +should display this string in window's title bar). In this +case the command returns an empty string. If string isn't +specified then the command returns the current title for the +window. The title for a window defaults to its name. +

    wm transient window ?master?
    +If master is specified, then the window manager is informed +that window is a transient window (e.g. pull-down menu) working +on behalf of master (where master is the +path name for a top-level window). Some window managers will use +this information to manage window specially. If master +is specified as an empty string then window is marked as not +being a transient window any more. If master is specified, +then the command returns an empty string. Otherwise the command +returns the path name of window's current master, or an +empty string if window isn't currently a transient window. +

    wm withdraw window
    +Arranges for window to be withdrawn from the screen. This +causes the window to be unmapped and forgotten about by the window +manager. If the window +has never been mapped, then this command +causes the window to be mapped in the withdrawn state. Not all +window managers appear to know how to handle windows that are +mapped in the withdrawn state. +Note: it sometimes seems to be necessary to withdraw a +window and then re-map it (e.g. with wm deiconify) to get some +window managers to pay attention to changes in window attributes +such as group. + +

    +

    GEOMETRY MANAGEMENT

    +By default a top-level window appears on the screen in its +natural size, which is the one determined internally by its +widgets and geometry managers. +If the natural size of a top-level window changes, then the window's size +changes to match. +A top-level window can be given a size other than its natural size in two ways. +First, the user can resize the window manually using the facilities +of the window manager, such as resize handles. +Second, the application can request a particular size for a +top-level window using the wm geometry command. +These two cases are handled identically by Tk; in either case, +the requested size overrides the natural size. +You can return the window to its natural by invoking wm geometry +with an empty geometry string. +

    +Normally a top-level window can have any size from one pixel in each +dimension up to the size of its screen. +However, you can use the wm minsize and wm maxsize commands +to limit the range of allowable sizes. +The range set by wm minsize and wm maxsize applies to +all forms of resizing, including the window's natural size as +well as manual resizes and the wm geometry command. +You can also use the command wm resizable to completely +disable interactive resizing in one or both dimensions. + +

    GRIDDED GEOMETRY MANAGEMENT

    +Gridded geometry management occurs when one of the widgets of an +application supports a range of useful sizes. +This occurs, for example, in a text editor where the scrollbars, +menus, and other adornments are fixed in size but the edit widget +can support any number of lines of text or characters per line. +In this case, it is usually desirable to let the user specify the +number of lines or characters-per-line, either with the +wm geometry command or by interactively resizing the window. +In the case of text, and in other interesting cases also, only +discrete sizes of the window make sense, such as integral numbers +of lines and characters-per-line; arbitrary pixel sizes are not useful. +

    +Gridded geometry management provides support for this kind of +application. +Tk (and the window manager) assume that there is a grid of some +sort within the application and that the application should be +resized in terms of grid units rather than pixels. +Gridded geometry management is typically invoked by turning on +the setGrid option for a widget; it can also be invoked +with the wm grid command or by calling Tk_SetGrid. +In each of these approaches the particular widget (or sometimes +code in the application as a whole) specifies the relationship between +integral grid sizes for the window and pixel sizes. +To return to non-gridded geometry management, invoke +wm grid with empty argument strings. +

    +When gridded geometry management is enabled then all the dimensions specified +in wm minsize, wm maxsize, and wm geometry commands +are treated as grid units rather than pixel units. +Interactive resizing is also carried out in even numbers of grid units +rather than pixels. + +

    BUGS

    +Most existing window managers appear to have bugs that affect the +operation of the wm command. For example, some changes won't +take effect if the window is already active: the window will have +to be withdrawn and de-iconified in order to make the change happen. +

    +On the Windows operating system wm iconbitmap has no effect when +passed a bitmap: only icon files currently work properly. + +

    KEYWORDS

    +aspect ratio, deiconify, focus model, geometry, grid, group, icon, iconify, increments, position, size, title, top-level window, units, window manager +
    +Copyright © 1991-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/fr/tcl/SafeBase.htm b/hlp/fr/tcl/SafeBase.htm new file mode 100644 index 0000000..1778ac7 --- /dev/null +++ b/hlp/fr/tcl/SafeBase.htm @@ -0,0 +1,130 @@ + + + + +

    Safe Tcl      Commandes Internes Tcl

    +
    +
    NOM

    +
    Safe Base - MИcanisme pour la crИation et la manipulation d'interprИteurs sШr. +

    +
    SYNTAXE

    +
    ::safe::interpCreate ?slave? ?options...?
    +::safe::interpInit slave ?options...?
    +::safe::interpConfigure slave ?options...?
    +::safe::interpDelete slave
    +::safe::interpAddToAccessPath slave directory
    +::safe::interpFindInAccessPath slave directory
    +::safe::setLogCmd ?cmd arg...? +

    +
    OPTIONS

    +
    ?-accessPath pathList? ?-statics boolean? ?-noStatics? ?-nested boolean? ?-nestedLoadOk? ?-deleteHook script? +

    +
    DESCRIPTION

    +
    Safe Tcl est un mИcanisme pour exИcuter des scripts Tcl Иtrangers sans risque et pour fournir un accХs Ю de tels scripts potentiellement dangereux.
    +
    Safe Base s'assure que des scripts Tcl Иtrangers ne peuvent nuire Ю l'application hТte. Safe Base prИvient les attaques d'intИgritИ et de sИcuritИ. Les scripts Иtrangers sont empЙchИs de corrompre l'Иtat de l'application ou de l'ordinateur hТte. Ces scripts sont Иgalement empЙchИs de rИvИler l'information stockИe sur l'ordinateur principal ou dans l'application hТte Ю n'importe quel espion.
    +
    Safe Base permet Ю un interprХteur maНtre de crИer des interprХteurs sИcurisИs et restreints qui contiennent un ensemble d'alias prИdИfinis pour les commandes source, load, file, encoding, et exit et peuvent employer des mИcanismes d'auto-chargement et de paquet.
    +
    Aucune connaissance de la structure de systХme de fichiers n'est nИcessaire Ю l'interprХteur sШr, parce qu'il accХde seulement Ю un chemin virtuel contenant des repХres. Quand l'interprХteur sШr demande le source d'un fichier, il emploie les repХres dans le chemin  virtuel en tant qu'ИlИment du nom du fichier; l'interprХteur maНtre d'une maniХre transparente traduit les repХres en vrais noms de rИpertoires et exИcute l'opИration demandИe (voir la section SECURITE ci-dessous pour les dИtails). DiffИrents niveaux de sИcuritИ peuvent Йtre choisis en employant les flags optionnels des commandes dИcrites ci-dessous.
    +
    Toutes les commandes fournies dans l'interprХteur maНtre par la commande Safe Base rИsident dans le namespace safe:
    +
    +
    COMMANDES

    +
    Les commandes suivantes sont fournies dans le maНtre interprИteur: +
    +
    ::safe::interpCreate ?slave? ?options...? +
    CrИe un interprХteur sШr, installe les alias dИcrits dans la section ALIAS et initialise le mИcanisme d'auto-chargement et de paquet comme indiquИ par les options fournies. Voir la section OPTIONS ci-dessous pour un description de l optionnel arguments. ci-dessous pour une description des  arguments facultatifs. Si l'argument slave est omis, un nom sera gИnИrИ.. ::safe::interpCreate renvoie toujours le nom d'interprХteur. +
    +

    ::safe::interpInit slave ?options...? +
    Cette commande est identique Ю interpCreate exceptИ qu'elle ne crИe pas l'interprХteur sШr. slave doit avoir ИtИ crИИ par d'autres moyens, comme interp create-safe. +
    +

    ::safe::interpConfigure slave ?options...? +
    Si aucunes options ne sont donnИes, renvoie les paramХtres pour toutes les options de l'interprХteur sШr comme liste d'options et leurs valeurs courantes pour slave. Si un argument additionnel est fourni, renvoie une liste de 2 ИlИments name et valuename est le nom complet de cette option et value la valeur courante pour cette option et slave. Si plus de deux arguments additionnels sont fournis, il modifiera l'interprХteur sШr et changera chacunes et seulement les option fournies. Voir la section OPTIONS ci-dessous pour la description d'options. Exemple d'utilisation: +
            # CrИe un nouvel interp avec la mЙme configuration que "$i0" : +
            set i1 [eval safe::interpCreate [safe::interpConfigure $i0]] +
           # Obtient le deleteHook courant
    +
            set dh [safe::interpConfigure $i0  -del] +
           # Change (seulement) l'attribut de chargement statics ok d'un interp +
           # et son deleteHook (laissant le reste inchangИ) :
    +        safe::interpConfigure $i0  -delete {foo bar} -statics 0 ;
    +
    +

    ::safe::interpDelete slave +
    Efface l'interprХteur sШr et nettoie les structures de donnИes  principales correspondantes d'interprХteur. Si un script deleteHook a ИtИ spИcifiИ pour cet interprИteur, il est ИvaluИ avant l'interprИteur que soit effacИ, avec le nom de l'interprИteur comme argument additionnel. +
    +

    ::safe::interpFindInAccessPath slave directory +
    Cette commande trouve et renvoie le jeton pour le vrai rИpertoire directory de l'accХs au chemin virtuel courant de l'interprХteur sШr. Elle gИnХre une erreur si le rИpertoire n'est pas trouvИ. Exemple d'utilisation: +
           $slave eval [list set tk_library [::safe::interpFindInAccessPath $ name $tk_library]] +
    +

    ::safe::interpAddToAccessPath slave directory +
    Cette commande ajoute directory au chemin virtuel maintenu pour  l'interprХteur sШr dans le maНtre, et retourne un jeton qui peut Йtre utilisИ dans l'interprИteur sШr pour obtenir accХs aux fichiers dans ce rИpertoire. Si le rИpertoire est dИjЮ dans le chemin virtuel, elle renvoie seulement le jeton sans ajouter le rИpertoire au chemin virtuel de nouveau. Exemple d'utilisation: +
           $slave eval [list set tk_library [::safe::interpAddToAccessPath $nom $ tk_library]] +
    +

    ::safe::setLogCmd ?cmd arg...? +
    Cette commande installe un script qui sera appelИ quand les  ИvИnements intИressants du cycle de vie se produisent pour un  interprХteur sШr. Une fois appelИe sans arguments, elle renvoie le script actuellement installИ. Si appelИe avec un  argument, une chaНne vide, le script actuellement installИ est  enlevИ et la journalisation est arrЙtИe. Le script sera appelИ avec un argument supplИmentaire, une chaНne dИcrivant l'ИvХnement intИressant. Le but principal est d'aider le debugging des interprИteur sШrs. En utilisant ce service vous pouvez obtenir des message d'erreurs complets pendant que l'interprИteur sШr reГoit seulement des messages d'erreurs gИnИriques. Ceci empЙche l'interprИteur sШr de voir des messages au sujet des Иchecs et d'autres ИvИnements qui pourraient contenir une information sensible telle que de vrais noms de rИpertoire. +
    Exemple d'utilisation: +
    ::safe::setLogCmd puts stderr +
    +
    +

    +
    Ci-dessous vous trouverez la sortie d'une session exemple dans laquelle un interprИteur sШr a essayИ de " sourcer " un fichier non trouvИ dans son chemin d'accХs virtuel. Notez que l'interprИteur sШr a seulement reГu un message d'erreur disant que le fichier n'a pas ИtИ trouvИ:
    +
    NOTICE for slave interp10 : Created
    +NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
    +NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
    +ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory
    + +
    +
    OPTIONS

    +
    Les options suivantes sont communes Ю ::safe::interpCreate, ::safe::interpInit, et ::safe::interpConfigure. N'importe quel nom d'option peut Йtre abrИgИ Ю son nom non-ambigu minimal. Les noms d'option ne sont ne sont pas sensibles Ю la casse. +
    +
    -accessPath directoryList
    Cette option place la liste de rИpertoires desquels l'interprИteur sШr peut source et load des fichiers. Si cette option n'est pas spИcifiИe, ou si elle est donnИe comme liste vide, l'interprИteur sШr emploiera les mЙme rИpertoires que son maНtre pour auto-chargement. Voir la section SECURITE ci-dessous pour plus de dИtail au sujet des chemins virtuels, des jetons et du contrТle d'accХs. +
    +

    -statics boolean +
    Cette option indique si l'interprИteur sШr sera autorisИ Ю charger les packages statiquement liИs (comme load {} Tk). La valeur par dИfaut est true : les interprИteur sШrs sont autorisИ Ю charger les packages statiquement liИs. +
    +

    -noStatics +
    Cette option est un raccourci de convenance pour -statics false et indique ainsi que l'interprИteur sШr ne sera pas autorisИ Ю charger les packages statiquement liИs. +
    +

    -nested boolean +
    Cette option spИcifie si l'interprИteur sШr sera autorisИ Ю charger des packages dans ses propre sous-interprИteurs. La valeur par dИfaut est false: les interprИteur sШrs ne sont pas autorisИ Ю charger de packages dans leurs propres interprХteurs secondaires. +
    +

    -nestedLoadOk +
    Cette option est un raccourci de convenance pour -nested true et indique ainsi que l'interprИteur sШr sera autorisИ Ю charger des packages dans ses propres interprХteurs secondaires. +
    +

    -deleteHook script +
    Quand Ю cette option est donnИ un script non vide, elle est ИvaluИe dans le maНtre avec le nom de l'interprХteur sШr comme argument additionnel juste avant supprimer rИellement l'interprХteur sШr. Donner une valeur vide enlХve n'importe quel script d'effacement actuellement installИ pour cet interprИteur sШr. La valeur par dИfaut ({}) n'est n'avoir aucun appel de suppression. +
    +
    +

    +
    ALIAS

    +
    Les alias suivants sont fournis dans un interprИteur sШr: +
    +
    source fileName +
    Le fichier requis, un fichier source Tcl, est "sourcИ" dans interprИteur sШr s'il est trouvИ. L'alias source peut seulement " sourcer " les fichier des rИpertoires qui se trouvent dans le chemin virtuel pour l'interprИteur sШr. L'alias source exige de l'interprИteur sШr qu'il utilise un des noms de jeton dans son chemin virtuel pour dИsigner le rИpertoire dans lequel le fichier a "sourcer" peut Йtre trouvИ. Voir la section sur la SECURITE pour une discussion plus approfondie des restrictions sur les noms de fichiers valides. +
    +

    load fileName +
    Le fichier requis, un fichier objet partagИ, est chargИ dynamiquement dans l'interprИteur sШr s'il est trouvИ. Le nom de fichier doit contenir le nom d'un jeton mentionnИ dans le chemin virtuel de l'interprИteur sШr pour Йtre trouvИ avec succХs. De plus, le fichier objet partagИ doit contenir un point d'entrИe sШr; voyez la page de manueluel de la commande load pour plus de dИtails. +
    +

    file ?subCmd args...? +
    L'alias file donne accХs Ю un sous ensemble sШr des sous-commandes de  file; il permet seulement les sous-commandes dirname, join, extension, root, tail, pathname et split. Pour plus de dИtails sur ces sous-commandes voyez la page de manueluel pour la commande file. +
    +

    encoding ?subCmd args...? +
    L'alias encoding donne accХs Ю un sous ensemble sШr des sous-commandes de encoding il interdit de fixer l'encodage systХme, mais permet tout autre sous-commandes incluant system Ю vИrifier l'encodage courant. +
    +

    exit +
    L'interprХteur appelant est supprimИ et son traitement est arrЙtИ, mais le processus Tcl dans lequel cet interprХteur existe n'est pas terminИ.
    +
    +
    +
    +
    SECURITE

    +
    La Safe Base n'essaye pas d'empЙcher complХtement les attaques d'ennui et de deni de service. Ces formes d'attaque empЙchent temporairement l'application ou l'utilisateur d'utiliser l'ordinateur pour effectuer des tБches utiles, par exemple en consommant tout le temps CPU ou tout l'affichage disponible. Ces attaques, quoique graves, sont considИrИes comme moins importantes en gИnИral que les attaques d'intИgritИ et d'intimitИ que la Safe Base doit empЙcher.
    +
    Les commandes disponibles dans un interprИteur sШr, en plus de  l'ensemble sШr comme dИfini en page de manueluel d' interp, sont des alias de source, load, exit, et des sous-ensembles sШrs de file et encoding. L'interprИteur sШr peut aussi auto-charger du code et il peut demander que des packages soient chargИs..
    +
    Puisque certaines de ces commandes accХdent au systХme de fichiers local, il y a un danger potentiel de fuites d'information au sujet de la structure des rИpertoires. Pour empЙcher ceci, les commandes qui prennent des noms de fichier comme aguments dans un interprИteur sШr utilisent des jetons au lieu des noms rИels de rИpertoires. Ces jetons sont traduits en nom rИel de rИpertoire pendant qu'une requЙte pour, ex., sourcer un fichier est traitИe par le maНtre interprИteur. Ce systХme de chemin virtuel est maintenu dans l'interprХteur principal pour chaque interprХteur sШr crИИ par ::safe::interpCreate ou initialisИ par ::safe::interpInit et le chemin pointe des jetons accessibles dans l'interprИteur sШr vers les noms de chemin rИels sur le systХme de fichier local empЙchant de ce fait les interprХteurs sШrs de connaНtre la structure du systХme de fichiers de la machine sur lequel l'interprХteur s'exИcute. Les seuls arguments valides de noms de fichier pour les alias source et load fournis Ю l'esclave sont des chemin sous la forme de [file jointokenfilename] (ie, en utilisant les formats natifs de chemin: token/filename sous Unix, token\filename sous Windows, et token:filename sur Mac), oЫ token reprИsente un des rИpertoires de la liste accessPath et filename est un fichier dans ce rИpertoire (on ne permet aucun accХs aux sous-rИpertoires).
    +
    Quand un jeton est utilisИ par un interprИteur sШr dans un requЙte pour " sourcer " ou charger un fichier, le jeton est vИrifiИ et traduit en un nom rИel de chemin et le fichier a "sourcer" ou chargИ est localisИ sur le systХme de fichier. L'interprИteur sШr n'a jamais connaissance du nom de chemin actuel sous lequel le fichier est stockИ sur le systХme de fichier.
    +
    Pour empЙcher une fuite d'information potentielle Ю partir de fichiers sensibles accidentellement inclus dans l'ensemble de fichiers qui peut Йtre "sourcИ" par un interprИteur sШr, l'alias source restreint l'accХs aux fichiers respectant les contraintes suivantes: le nom de chemin ne doit pas avoir plus de quatorze caractХres, ne doit pas contenir plus d'un point ("."), doit finir avec l'extension .tcl ou Йtre appelИ tclIndex.
    +
    Chaque ИlИment de la liste initiale de chemin d'accХs sera assignИ Ю un jeton qui sera placИe dans l'auto_path de l'esclave et le premier ИlИment de cette liste sera fixИ en tant que tcl_library pour cet esclave.
    +
    Si l'argument de chemin d'accХs n'est pas donnИ ou est une liste vide, le comportement par dИfaut est de laisser l'esclave acceder aux mЙmes packages que le maНtre (ou pour Йtre plus prИcis: seulement les packages Иcrits en Tcl (ne peuvent pas Йtre dangereux tant qu'ils fonctionnent dans l'interprИteur esclave) et les extensions C qui fournissent un point d'entrИe Safe_Init). Dans ce but, l'auto_path du maНtre sera employИ pour construire le chemin d'accХs de l'esclave. Pour que l'esclave charge avec succХs la bibliothХque Tcl (qui inclut le mИcanisme d'auto-chargement) la tcl_library sera ajoutИe ou dИplacИe Ю la premiХre position si nИcessaire, dans le chemin d'accХs de l'esclave, ainsi la tcl_library esclave sera la mЙme que celle du maНtre (son vrai chemin sera cependant toujours invisible Ю l'esclave). Pour que l'auto-chargement fonctionne de mЙme pour l'esclave et le maНtre dans ce cas par dИfaut, les sous rИpertoires de premier-niveau de chaque rИpertoire dans l'auto_path du maНtre sera aussi ajoutИ (si aucun n'est dИjЮ inclus) au chemin d'accХs de l'esclave. Vous pouvez toujours indiquer un chemin plus restrictif pour lequel les sous rИpertoires ne seront jamais recherchИs explicitement en spИcifiant votre liste de rИpertoires avec le flag -accessPath au lieu de compter sur ce mИcanisme par dИfaut.
    +
    Quand le accessPath est changИ aprХs la premiХre crИation ou l'initialisation (c.a.d au travers de interpConfigure -accessPathlist), un auto_reset est automatiquement ИvaluИ dans l'interprИteur sШr pour synchroniser son auto_index avec la nouvelle liste de jetons
    +

    +
    VOIR EGALEMENT

    +
    interp(n), library(n), load(n), package(n), source(n), unknown(n)

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/Tcl.htm b/hlp/fr/tcl/Tcl.htm new file mode 100644 index 0000000..ea88f19 --- /dev/null +++ b/hlp/fr/tcl/Tcl.htm @@ -0,0 +1,47 @@ + + + + +

    Tcl      Commandes Internes Tcl

    +
    +
    NOM

    +
    Tcl - Sommaire de la syntaxe du langage Tcl.

    +
    DESCRIPTION

    +
    Les rХgles suivantes definissent la syntaxe et la sИmantique du langage Tcl: +
    +
    [1]
    Un script Tcl est une chaНne contenant une ou plusieurs commandes. Les point-virgules et les sauts de lignes sont des sИparateurs de commandes sauf placИs entre guillemets comme dИcrit ci-dessous. Les crochets fermants sont des terminateurs de commande pendant la substitution de commande (voir ci-dessous) sauf placИs entre guillemets. +
    +

    [2]
    Une commande est ИvaluИe en deux Иtapes. D'abord, l'interprИteur Tcl divise la commande en mots et effectue les substitutions comme dИcrit ci-dessous. Ces substitutions sont effectuИes de la mЙme faГon pour toutes les commandes. Le premier mot est utilisИ pour localiser une commande Ю exИcuter, ensuite tous les mots de la commande sont transmis Ю la fonction de la commande. La fonction de la commande est libre d'interprИter chacun des mots Ю sa guise, tel un entier, un nom de variable, une liste, ou un script Tcl. DiffИrentes commandes interprХtent leurs mots diffИremment.
    +

    [3]
    Les mots d'une commande sont sИparИs par un espace (exceptИ les saut de lignes, qui sont des sИparateurs de commandes).
    +

    [4]
    Si le premier caractХre d'un mot est un guillemet double(") alors le mot est terminИ par le guillemet double suivant. Si des points-virgules, crochets fermants, ou un espace (incluant les sauts de lignes) apparaissent entre les guillemets alors ils sont traitИs comme des caractХres ordinaires et inclus dans le mot. Les substitution de commandes, substitution de variable , et la substitution backslash sont effectuИes sur les caractХres entre les guillemets comme dИcrit ci-dessous. Le double-guillemets ne sont pas retenus comme partie du mot.
    +

    [5]
    Si le premier caractХre d'un mot est une accolade ouvrante ({) alors le mot est terminИ par l'accolade fermante correspondante (}). Si les accolades sont imbriquИes dans le mot: pour chaque accolade ouverte supplИmentaire il doit y avoir une accolade fermante supplИmentaire (nИanmoins, si une accolade ouvrante ou fermante dans le mot est prИcИdИe avec un antislash alors il n'est pas nИcessaire de lui faire correspondre une accolade fermante). Aucune substitution n'est effectuИe sur les caractХres entre les accolades exceptИ pour les substitutions backslash-newline dИcrites ci-dessous, et les points-virgules, saut de lignes, crochets fermants, ou l'espace ne font l'objet d'une quelconque interprИtation spИciale. Le mot consistera en exactement les caractХres entre les accolades externes, non inclues les accolades elles-mЙme.
    +

    [6]
    Si un mot contient un crochet ouvert ("[") alors Tcl effectue une substitution de commande. Pour ceci il appelle l'interprИteur Tcl rИcursivement pour traiter les caractХres suivants le crochet ouvert comme un script Tcl. Le script peut contiennent n'importe quel nombre de commandes et doit Йtre terminИ par un crochet fermИ ("]"). Le rИsultat du script (i.e. le rИsultat de sa derniХre commande) est substituИ en un mot Ю la place des crochets et de tous les caractХres entre eux. Il peut y avoir quelconque nombre de substitution de commandess dans un seul mot. La substitution de commandes n'est pas effectuИe sur les mots entourИs d'accolades.
    +

    [7]
    Si un mot contient un signe dollar ("$") alors Tcl effectue une substitution de variable:  le signe dollar et les caractХres suivants sont remplacИs dans le mot par les valeur d'une variable. La substitution de variable peut prendre quelconque des formes suivantes:
    +
    $name
    Name est le nom d'une variable scalaire; le nom est terminИ par tout caractХre qui n'est pas une lettre, un chiffre, ou un underscore.
    +
    $name(index)
    Name donne le nom d'une variable tableau et index donne le nom d'un ИlИment Ю l'intИrieur du tableau. Name doit contenir seulement des lettres, chiffres, et underscores. La substitution de commandes, substitution de variables, et substitutions backslash sont effectuИes sur les caractХres de index.
    +
    ${name}
    Name est le nom d'une variable scalaire. Il peut contenir tous les caractХres exceptИs des accolades fermantes.
    +
    +Il peut y avoir n'importe quel nombre de substitution de variables dans un seul mot. La substitution de variables n'est pas effectuИe sur les mots entourИs d'accolades.
    +

    [8]
    Si un antislash ("\") apparail Ю l'intИrieur un mot alors une substitution backslash se produit. Dans tout les cas sauf ceux dИcrit ci-dessous le backslash est omis et le caractХre suivant est traitИ comme un caractХre ordinaire et inclus dans le mot. Ceci permet aux caractХres tels que les double guillemets, crochets fermants, et signes dollar d'Йtre inclus dans les mots sans dИclencher de traitement spИcial. La table suivante liste les sequences backslash qui sont gИrИes spИcialement, avec la valeur qui remplace chaque sИquence.
    +
    \a
    Bip (bell) (0x7).
    +
    \b
    Retour arriХre (0x8).
    +
    \f
    Saut de page (0xc).
    +
    \n
    Saut de ligne (0xa).
    +
    \r
    Retour chariot (0xd).
    +
    \t
    Tabulation (0x9).
    +
    \v
    Tabulation verticale (0xb).
    +
    \<newline>whiteSpace
    Un espace remplace les backslash, newline, et tout les espaces et tabulationss aprХs le saut de ligne. Cette sИquence backslash est unique dans le sens ou elle est remplacИe dans un pre-traitement sИparИ avant que la commande soit analysИe. Ceci signifie qu'elle sera remplacИe mЙme quand elle se produit entre accolades, et l'espace rИsultant sera traitИ comme un separateur de mot s'il n'est pas entre accolades ou guillemets.
    +
    \\
    Backslash ("\").
    +
    \ooo
    Les chiffres ooo (un, deux, ou les trois ) donnent la valeur octale sur huit bits du caractХre Unicode qui sera insИrИ. Les bits forts du caractХre Unicode seront Ю 0.
    +
    \xhh
    Les chiffres hexadИcimaux hh donnent la valeur hexadИcimale sur huit bits du caractХre Unicode qui sera insИrИ. N'importe quel nombre de chiffres hexadИcimaux peuvent Йtre prИsents; nИanmoins, tout sauf les deux derniers sont ignorИs (le rИsultat est toujours une quantitИ sur un octet). Les bits forts du caractХre Unicode seront Ю 0.
    +
    \uhhhh
    Les chiffres hexadИcimaux hhhh (un, deux, trois, ou les quatre) donnent la valeur hexadИcimale sur seize bit du caractХre Unicode qui sera insИrИ.
    +
    +La substitution backslash n'est pas effectuИe sur les mots entourИs d'accolades, exceptИ pour backslash-newline comme dИcrit plus haut. +
    +

    [9]
    Si un caractХre diХse ("#") apparait Ю un point oЫ Tcl attend le premier caractХre du premier mot d'une commande, alors le caractХre diХse et les caractХres qui suivent, jusqu'au saut de ligne suivant, sont considИrИs comme des commentaires et ignorИs. Le caractХre commentaire a seulement une signification quand il apparait au dИbut d'une commande.
    +

    [10]
    Chaque caractХre est traitИ exactement une fois par l'interprИteur Tcl comme partie de la crИation des mots d'une commande. Par exemple, si une substitution de variable se produit alors aucune substitution suivante n'est effectuИe sur la valeur de la variable; la valeur est insИrИe dans le mot texto. Si une substitution de commandes se produit alors la commande imbriquИe est traitИe entiХrement par l'appel recursif de l'interprИteur Tcl; aucune substitution n'est effectuИe avant l'appel recursif et aucune substitution supplИmentaire n'est effectuИe dans le rИsultat du script imbriquИ.
    +

    [11]
    Les substitutions n'affectent pas les limites des mots d'une commande. Par exemple, pendant une substitution de variable la valeur totale de la variable devient une partie d'un simple mot, mЙme si la valeur de la variable contient des espaces.
    +
    +
    +
    DerniХre rИvision: 8.1
    + diff --git a/hlp/fr/tcl/Tcltest.htm b/hlp/fr/tcl/Tcltest.htm new file mode 100644 index 0000000..f9b8b3b --- /dev/null +++ b/hlp/fr/tcl/Tcltest.htm @@ -0,0 +1,309 @@ + + + + +

    Tcltest      Commandes internes Tcl

    +
    +
    NOM

    +
    Tcltest -  Support du systХme de test et utilitaires
    +

    +
    SYNTAXE

    +
    package require tcltest ?1.0?
    +::tcltest::test name desc ?constraint? script expectedAnswer
    +::tcltest::cleanupTests ?runningMultipleTests?
    +::tcltest::getMatchingTestFiles
    +::tcltest::loadTestedCommands
    +::tcltest::makeFile contents name
    +::tcltest::removeFile name
    +::tcltest::makeDirectory name
    +::tcltest::removeDirectory name
    +::tcltest::viewFile name
    +::tcltest::normalizeMsg msg
    +::tcltest::bytestring string
    +::tcltest::saveState
    +::tcltest::restoreState
    +::tcltest::threadReap
    +

    +
    DESCRIPTION

    +
    Le package tcltest fournit Ю l'utilisateur des utilitaires pour Иcrire et faire fonctionner des tests dans le systХme de test Tcl. Il peut Иgalement Йtre utilisИ pour crИer un systХme de test personnalisИ pour une extension.
    +
    Le systХme de test Tcl comporte de multiples fichiers .test, chacun d'entre eux comprenant plusieurs cas de test. Chaque test comporte un appel Ю la commande test, qui indique le nom du test, une description brХve, les contraintes qui s'appliquent au cas testИ, le script Ю exИcuter, et les rИsultats attendus. Voir les sections "Tests", "Contraintes de test", et " Faire fonctionner les fichiers de test " pour plus d'informations. +
    Il est Иgalement possible d'enrichir ce systХme de test pour mettre en place votre propre systХme de test sur mesure. Pour plus d'information, voir la section "Personnaliser le systХme de test". +
    Cette approche pour tester a ИtИ conГue et initialement mise en place par Mary Ann May-Pumphrey de Sun Microsystems au dИbut des annИes 1990. Nous lui adressons de sincХres remerciements pour avoir fait don de son travail au profit de la version publique de Tcl.
    +
    COMMANDES
    +
    +
    +
    ::tcltest::test name desc ?constraints? script expectedAnswer
    La commande ::tcltest::test lance script et compare son rИsultat Ю expectedAnswer. Elle imprime un message d'erreur si les deux ne correspondent pas. Si::tcltest::verbose contient "p" ou "s", elle imprime aussi un message si le test rИussit (p: passed) ou a ИtИ omis (s: skipped). Le test sera omis s'il ne correspond pas Ю la variable ::tcltest::match, s'il correspond Ю l'un des ИlИments de ::tcltest::skip, ou si l'un des ИlИments de constraints s'avХre ne pas Йtre vrai. La commande ::tcltest::test n'a pas de valeur de retour dИfinie. Voir la section "Ecrire un nouveau test" pour plus d'informations sur cette commande.
    +
    ::tcltest::cleanupTests ?runningMultipleTests?
    Cette commande doit normalement Йtre appelИe Ю la fin d'un fichier de test. Elle imprime des statistiques au sujet des tests ИxИcutИs et supprime les fichiers crИИs par ::tcltest::makeDirectory et ::tcltest::makeFile. Les noms des fichiers et rИpertoires crИИs en dehors de ::tcltest::makeFile et ::tcltest::makeDirectory, et qui n'ont jamais ИtИ dИtruits, sont affichИs dans ::tcltest::outputChannel. Cette commande restaure Иgalement l'environnement d'ИxИcution initial, tel que dИcrit par le tableau ::env.calledFromAll doit normalement Йtre indiquИ quand ::tcltest::cleanupTests est appelИ depuis un fichier "all.tcl". Des fichiers Tcl sont gИnИralement utilisИs pour exИcuter des tests multiples. Pour plus d'information sur comment exИcuter des tests multiples, voir la section "ExИcuter des fichiers de test". Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::getMatchingTestFiles
    Cette commande est utilisИe quand vous voulez exИcuter plusieurs fichiers de test. Elle retourne la liste des tests qui doivent Йtre sourcИs dans un fichier "all.tcl". Voir la section "ExИcuter des fichiers de test" pour plus d'informations.
    +
    ::tcltest::loadTestedCommands
    Cette commande utilise le script indiquИ par l'option -load ou -loadfile pour charger les commandes testИes par le systХme de test. AutorisИe Ю Йtre vide, dans le cas oЫ; les commandes testИes sont accumulИes dans  l'interprИteur qui ИxИcute le systХme de test.
    +
    ::tcltest::makeFile contents name
    CrИe un fichier qui sera automatiquement supprimИ par ::tcltest::cleanupTests Ю la fin du fichier de test. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::removeFile name
    Force la suppression du fichier rИfИrencИ par name. Ce nom de fichier doit Йtre indiquИ en rИfИrence au ::tcltest::temporaryDirectory. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::makeDirectory name
    CrИe un rИpertoire name, qui sera automatiquement supprimИ par ::tcltest::cleanupTests Ю la fin du fichier de test. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::removeDirectory name
    Force la suppression du fichier rИfИrencИ par name. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::viewFile file
    Renvoie le contenu de file.
    +
    ::tcltest::normalizeMsg msg
    Retire les fins de lignes superflues de msg.
    +
    ::tcltest::bytestring string
    Construit une chaНne qui se compose de la suite des octets demandИs, et non la chaНne formИe de caractХres UTF-8 corrects, Ю partir de la valeur de string. Cela permet au testeur de crИer des chaНnes dИnormalisИes ou impropement formИes, pour les passer Ю des procИdures C qui sont supposИes accepter des chaНnes comprenant des NULL, et confirmer que le rИsultat sous forme de chaНne correspond bien Ю la suite d'octets prИvue.
    +
    ::tcltest::saveState
    et ::tcltest::restoreState sauvent et restaurent les procИdures et les variables globales. Un fichier de test peut contenir des appels Ю ::tcltest::saveState et ::tcltest:restoreState s'il crИe des variables globales ou des procИdures.
    +
    ::tcltest::threadReap
    ::tcltest::threadReap fonctionne seulement si testthread est dИfini, gИnИralement en compilant tcltest. Si testthread est dИfini, ::tcltest::threadReap tue tous les threads Ю l'exception du thread principal. Il rИcupХre l'ID du thread principal en appelant testthread names pendant l'initialisation. Cette valeur est stockИe dans ::tcltest::mainThread::tcltest::threadReap retourne le nombre de threads existants en tout. (?)
    +
    +

    +
    TESTS

    +
    La procИdure test ИxИcute un script de test est affiche un message d'erreur si le rИsultat du script ne correspond pas au rИsultat attendu. Voici la spИcification de la commande test :
    +
      +
    test <name> <description> ?<constraint>? <script> <expectedAnswer>
    +
    +
      +
    L'argument <name> doit obИir au motif:
    +
          <target>-<majorNum>.<minorNum>
    +
      +
    Pour les tests "en boНte blanche" (tests de rИgression), la cible <target > doit Йtre le nom de la fonction C ou de la procИdure Tcl  qui est testИe. Pour les tests "en boНte noire", la cible  <target> doit Йtre le nom de la fonctionnalitИ testИe.  Des tests apparentИs doivent avoir le mЙme numИro majeur <majorNum>.
    +
      +
    L'argument <description> est une courte description textuelle du test, pour aider les personnes Ю comprendre ce qui est testИ. Le nom de la fonction Tcl ou C devrait y Йtre inclus pour les tests de rИgression. Si le cas de test est dИfini pour reproduire un bug, inclure l'identifiant (bugID) dans la description.
    +
      +
    L'argument optionnel <constraints> peut Йtre une liste d'un ou plusieurs mots-clИs ou une expression. Si l'argument <constraints> se compose de mots-clИs, chacun d'entre eux doit Йtre le nom d'un ИlИment du tableau ::tcltest::testConstraints.  Si l'un de ces ИlИments est faux ou n'existe pas, le test est sautИ. Si l'argument <constraints> est une expression, cette expression sera ИvaluИe: si le rИsultat est vrai, alors le test sera ИxИcutИ.
    +
      +
    Ajoutez des contraintes appropriИes (par exemple, unixOnly) pour les tests qui ne doivent pas toujours Йtre ИxИcutИs. Par exemple, un test qui ne doit Йtre effectuИ que sur Unix devrait ressembler Ю:
    +
    test getAttribute-1.1 {testing file permissions} {unixOnly} {
    +    lindex [file attributes foo.tcl] 5
    +} {00644}
    +
    Exemple de test contenant une expression:
    +
    test unixNotfy-1.1 {Tcl_DeleteFileHandler} {unixOnly && !testthread} {
    +    catch {vwait x}
    +    set f [open foo w]
    +    fileevent $f writable {set x 1}
    +    vwait x
    +    close $f
    +    list [catch {vwait x} msg] $msg
    +} {1 {ne peut pas attendre la variable "x":  attendrait indИfiniment }}
    +
    +
    Voir la section "Contraintes de Test" pour la liste des contraintes prИdИfinies et pour savoir comment ajouter vos propres contraintes.
    +
      +
    L'argument <script> contient le script a exИcuter pour effectuer le test. Il doit retourner un rИsultat dont la validitИ peut Йtre vИrifiИe. Si votre script demande qu'un fichier soit crИИ Ю la volИe, utilisez svp la procИdure ::tcltest::makeFile. Si votre test demande qu'un petit fichier (moins de 50 lignes) soit contrôlИ en lecture, svp pensez Ю crИer le fichier Ю la volИe en utilisant la procИdure ::tcltest::makeFile. Les fichiers crИИs par la procИdure ::tcltest::makeFile seront automatiquement supprimИs par la procИdure ::tcltest::cleanupTests appelИe Ю la fin de chaque fichier de test.
    +
      +
    L'argument <expectedAnswer> sera comparИ au rИsultat de l'Иvaluation de l'argument <script>. S'ils correspondent, le test passe, sinon il Иchoue.
    +
    +
    LES VARIABLES DU NAMESPACE TCLTEST

    +
    Les variables suivantes sont dИfinies dans le namespace tcltest et peuvent Йtre utilisИes par des tests: +
    +
    ::tcltest::outputChannel
    outputfileID - par dИfaut stdout, peut Йtre prИcisИ en indiquant -outfile sur la ligne de commande. Tout test qui imprime des rИsultats devrait envoyer cette sortie Ю ::tcltest::outputChannel plutôt que de sortir par dИfaut sur stdout.
    +

    ::tcltest::errorChannel
    errorfileID - par dИfaut stderr, peut Йtre prИcisИ en indiquant -errfile sur la ligne de commande. Tout test qui imprime des messages d'erreur devrait le faire vers ::tcltest::errorChannel plutôt que directement dans stderr.
    +

    ::tcltest::mainThread
    main thread ID - 1 par dИfaut. Ce sera le seul thread qui ne sera pas tuИ par ::tcltest::threadReap et qui sera assignИ conformИment Ю la valeur de retour de testthread names Ю l'initialisation.
    +

    ::tcltest::originalEnv
    copie du tableau global "env" au dИbut de l'ИxИcution du test. Ce tableau est utilisИ pour restaurer le tableau "env" Ю sa valeur initiale quand ::tcltest::cleanupTests  est appelИe.
    +

    ::tcltest::workingDirectory
    le rИpertoire dans lequel le systХme de test a ИtИ lancИ.
    +

    ::tcltest::temporaryDirectory
    le rИpertoire de sortie - par dИfaut ::tcltest::workingDirectory , peut Йtre prИcisИ en indiquant   -tmpdir en ligne de commande.
    +

    ::tcltest::testsDirectory
    lЮ oЫ; se trouvent les tests - par dИfaut  ::tcltest::workingDirectory , si le script ne peut pas dИterminer oЫ; le rИpertoire de tests se trouve. Il est possible de changer cette valeur par dИfaut en prИcisant -testdir en ligne de commande. Cette variable devrait toujours Йtre prИcisИe explicitement si les tests sont ИxИcutИs depuis un fichier all.tcl.
    +

    ::tcltest::tcltest
    le nom de l'ИxИcutable utilisИ pour appeler le systХme de test.
    +

    ::tcltest::loadScript
    Le script ИxИcutИ en tant que loadTestCommands. PrИcisИ par -load ou -loadfile.
    +
    +
    +
    +
    CONTRAINTES DE TEST
    +
    +
    Les contraintes sont utilisИes pour dИterminer si un test doit Йtre ignorИ.  Chaque contrainte est stockИe comme un indice du tableau ::tcltest::testConstraints. Par exemple, la contrainte unixOnly est dИfinie de la faГon suivante:
    +
    set ::tcltest::testConstraints(unixOnly) \
    +    [string equal $tcl_platform(platform) "unix"]
    +
    +
    Si un test est contraint par "unixOnly", il ne s'exИcutera que si la valeur de ::tcltest::testConstraints(unixOnly) est vraie. Plusieurs contraintes sont dИfinies dans le package tcltest.  Pour ajouter des contraintes spИcifiques Ю un fichier ou Ю un test, vous pouvez crИer l'index correspondant du tableau ::tcltest::testsConstraints dans votre propre fichier de test.
    +
      +
    Voici la liste des contraintes dИfinies dans le package tcltest : +
    +
    unix
    le test ne peut s'exИcuter que sur les plateformes UNIX
    +
    pc
    le test ne peut s'exИcuter que sur les plateformes Windows
    +
    nt
    le test ne peut s'exИcuter que sur les plateformes Windows NT
    +
    95
    le test ne peut s'exИcuter que sur les plateformes Windows 95
    +
    98
    le test ne peut s'exИcuter que sur les plateformes Windows 98
    +
    mac
    le test ne peut s'exИcuter que sur les plateformes Mac
    +
    unixOrPc
    le test ne peut s'exИcuter que sur les plateformes UNIX ou PC
    +
    macOrPC
    le test ne peut s'exИcuter que sur les plateformes Mac ou PC
    +
    macOrUnix
    le test ne peut s'exИcuter que sur les plateformes Mac ou Unix
    +
    tempNotPc
    le test ne peut Йtre ИxИcutИ sur Windows. C'est un flag pour dИsactiver temporairement un test.
    +
    tempNotMac
    le test ne peut Йtre ИxИcutИ sur un Mac. C'est un flag pour dИsactiver temporairement un test.
    +
    unixCrash
    le test se plante s'il est ИxИcutИ sur UNIX. C'est un flag pour dИsactiver temporairement un test.
    +
    pcCrash
    le test se plante s'il est ИxИcutИ sur PC. C'est un flag pour dИsactiver temporairement un test.
    +
    macCrash
    le test se plante s'il est ИxИcutИ sur Mac. C'est un flag pour dИsactiver temporairement un test.
    +
    emptyTest
    le test est vide, et donc ne vaut pas la peine d'Йtre ИxИcutИ, mais il reste afin d'Йtre Иcrit dans le futur. Cette contrainte provoque l'omission systИmatique du test.
    +
    knownBug
    le test est connu pour se planter, et le bug n'est pas encore corrigИ. Cette contrainte provoque l'omission du test., sauf si l'utilisateur demande le contraire. Voir la section "Introduction" pour plus d'informations.
    +
    nonPortable
    ce test ne peut Йtre effectuИ que dans l'environnement de dИveloppement Tcl/Tk maНtre. Certains tests sont par nature non portables, parce qu'ils dИpendent de choses telles que la longueur de mot du processeur, la configuration du systХme de fichiers, le gestionnaire de fenЙtres, etc. Ces tests sont seulement ИxИcutИs dans l'environnement de dИveloppement Tcl principal, oЫ; la configuration est bien connue. Cette contrainte provoque l'omission du test, sauf si l'utilisateur demande le contraire.
    +
    userInteraction
    ce test demande une interaction avec l'utilisateur. Cette contrainte provoque l'omission du test, sauf si l'utilisateur demande le contraire.
    +
    interactive
    ce test ne peut Йtre effectuИ qu'en mode interactif, c'est Ю dire si la variable globale tcl_interactive est positionnИe Ю 1.
    +
    nonBlockFiles
    ce test ne peut s'exИcuter que si la plateforme supporte de mettre les fichiers en mode non-bloquИ.
    +
    asyncPipeClose
    ce test ne peut s'exИcuter que si la plateforme supporte "async flush" et "async close" sur un pipe.
    +
    unixExecs
    le test ne peut s'exИcuter que si la machine dispose des commandes telles que 'cat', 'echo', etc.
    +
    hasIsoLocale
    le test ne peut s'exИcuter que s'il peut passer dans une locale ISO.
    +
    root
    le test ne peut s'exИcuter que si l'utilisateur Unix est root
    +
    notRoot
    le test ne peut s'exИcuter que si l'utilisateur Unix n'est pas root
    +
    eformat
    le test ne peut s'exИcuter que si l'application a une version fonctionnelle de sprintf respectant le format "e" des nombres flottants.
    +
    stdio
    le test ne peut s'exИcuter que si l'application courante peut fonctionner au travers d'un pipe
    +
    +

    +
    FAIRE FONCTIONNER LES FICHIERS DE TEST

    +
    Utiliser la commande suivante pour exИcuter un fichier de test qui utilise le package tcltest:
    +
    <shell> <testFile> ?<option> ?<value>?? ...
    +
    Les options de ligne de commande sont les suivantes (les variables du namespace tcltest qui correspondent Ю chacune des options sont indiquИes entre parenthХses Ю la fin de la description) : +
    +
    -help
    affiche le mode d'utilisation
    +
    -verbose <level>
    +dИfinit le niveau de verbositИ comme une sous-chaНne de "bps". Voir la section "Informations issus des tests" pour une explication de cette option.  (::tcltest::verbose)
    +
    -match <matchList>
    +effectue seulement les tests qui correspondent aux motifs de "glob" dИfinis dans <matchList>.  (::tcltest::match)
    +
    -skip <skipList>
    +n'effectue pas les tests qui correspondent Ю un ou plusieurs motifs de "glob" dИfinis dans <skipList>.  (::tcltest::skip)
    +
    -file <globPatternList>
    +source seulement les fichiers de test dont les noms rИpondent Ю l'un des motifs de  <globPatternList> dИfinis par rapport au rИpertoire::tcltest::testsDirectory. Cette option n'a de sens qui si vous effectuez des tests utilisant "all.tcl" en tant que <testFile> au lieu d'effectuer directement des fichiers unitaires de test. (::tcltest::matchFiles)
    +
    -notfile <globPatternList>
    +source tous les fichiers sauf ceux dont les noms rИpondent Ю l'un des motifs de <globPatternList> dИfinis par rapport au rИpertoire::tcltest::testsDirectory.   Cette option n'a de sens qui si vous effectuez des tests utilisant "all.tcl" en tant que <testFile> au lieu d'effectuer directement des fichiers unitaires de test. (::tcltest::skipFiles)
    +
    -constraints <list>
    +les tests contenant une contrainte parmi la liste <list> ne seront pas sautИs. Notez que les ИlИments de <list> doivent correspondrent exactement aux contraintes existantes. Ceci est utile si vous voulez avoir la certitude que les tests ayant une contrainte particuliХre sont effectuИs (par exemple, si le testeur souhaite que tous les tests contenant la contrainte knownBug soient effectuИs). (::tcltest::testConstraints(constraintName))
    +
    -limitconstraints <bool>
    Si l'argument de cette option est 1, les tests effectuИs seront ceux qui respectent les contraintes dИfinies par l'option -constraints. La valeur par dИfaut de cet indicateur est 0 (false). Ceci est utile si vous voulez exИcuter seulement les tests qui rИpondent aux contraintes listИes par l'option -constraints. Un testeur peut vouloir cela par exemple pour n'effectuer que les tests contraints par unixOnly et aucun autre. (::tcltest::limitConstraints)
    +
    -load <script>
    utilisera le script indiquИ pour charger les commandes Ю tester (::tcltest::loadTestedCommands). La valeur par dИfaut est un script vide. Voir Иgalement -loadfile ci-dessous. (::tcltest::loadScript)
    +
    -loadfile <scriptfile>
    utilisera le contenu du fichier indiquИ pour charger les commandes Ю tester (::tcltest::loadTestedCommands).Voir Иgalement -load ci-dessus. La valeur par dИfaut est un script vide. (::tcltest::loadScript)
    +
    -tmpdir <directoryName>
    mettra tous les fichiers temporaires (crИИs avec ::tcltest::makeFile et ::tcltest::makeDirectory) dans le rИpertoire indiquИ.  L'emplacement par dИfaut est ::tcltest::workingDirectory.  (::tcltest::temporaryDirectory)
    +
    -testdir <directoryName>
    cherche les tests Ю exИcuter dans le rИpertoire indiquИ. L'emplacement par dИfaut est ::tcltest::workingDirectory. (::tcltest::testsDirectory)
    +
    -preservecore <level>
    contrôle pour les fichiers core.  Cette option dИtermine quel niveau de contrôle sera effectuИ pour les fichiers "core". La valeur par dИfaut pour <level> est 0. Les niveaux <level> sont dИfinis comme suit :
    +
    0
    Pas de contrôle - ne pas contrôler les fichiers core Ю la fin de chaque test, mais les contrôler Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl.
    +
    1
    VИrifier l'existence de fichiers core Ю la fin de chaque commande de test et Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl.
    +
    2
    VИrifier l'existence de fichiers core Ю la fin de chaque commande de test et Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl. Sauvegarder tout fichier core produit dans ::tcltest::temporaryDirectory. (::tcltest::preserveCore)
    +
    +
    +
    -debug <debugLevel>
    afficher l'information de debug dans stdout. Ceci est utilisИ pour dИbugger le code du systХme de test. Le niveau de debug par dИfaut est 0. Les niveaux sont dИfinis ainsi:
    +
    0
    Ne pas afficher les informations de debug.
    +
    1
    Afficher l'information indiquant si un test est sautИ parce qu'il ne rИpond Ю aucune des conditions indiquИes dans -match ou ::tcltest::match (userSpecifiedNonMatch), ou parce qu'il rИpond Ю une quelconque des conditions indiquИes par -skip ou ::tcltest::skip ((userSpecifiedSkip).
    +
    2
    Affiche le tableau des options interprИtИ par le processeur de ligne de commande, le contenu du tableau ::env, et toutes les variables utilisateur dИfinies dans le namespace courant, quand elles sont utilisИes.
    +
    3
    Affiche l'information concernant ce que font les procИdures individuelles de le systХme de test.(::tcltest::debug)
    +
    +
    +
    -outfile <filename>
    envoie la sortie gИnИrИe par le package tcltest vers le fichier indiquИ. La valeur par dИfaut est stdout. Notez que la sortie de debug va systИmatiquement dans stdout, quelque soit la valeur de cette option. (::tcltest::outputChannel)
    +
    -errfile <filename>
    envoie les erreurs gИnИrИes par le package tcltest vers le fichier indiquИ. La valeur par dИfaut est stderr. (::tcltest::errorChannel)
    +
    +
    +
    Une seconde faГon d'exИcuter les tests est de dИmarrer un shell, de charger le package tcltest, puis de sourcer un fichier de test appropriИ ou d'utiliser la commande test. Pour utiliser les options en mode interactif, alimenter la variable qui leur correspond dans le namespace tcltest aprХs avoir chargИ le package.
    +
    Voir la section "Contraintes de Test" pour toutes les contraintes prИ-construites qui peuvent Йtre utilisИes dans le tableau ::tcltest::testConstraints. Voir la section "Les variables du namespace Tcltest" pour des informations sur les autres variables dИfinies dans le namespace tcltest.
    +
    Une derniХre faГon d'exИcuter les tests est d'indiquer les fichiers de test Ю exИcuter Ю l'intИrieur d'un fichier all.tcl (qui peut Йtre nommИ diffИremment). C'est l'approche utilisИe par le systХme de test de Tcl. Ce fichier charge le package tcltest, dИfinit l'emplacement du rИpertoire de test (::tcltest::testsDirectory), dИtermine quels fichiers de test exИcuter, source chacun de ces fichiers, appelle ::tcltest::cleanupTests et finit de s'exИcuter.
    +
    Un fichier all.tcl plus ИlaborИ peut faire du prИ- et du post-processing avant de sourcer chaque fichier .test, utiliser des interprИteurs diffИrents pour chaque fichier, ou manipuler des structures de rИpertoires complexes. Pour un exemple de fichier all.tcl, voir la section "Exemples" de ce document.
    +
    RESULTATS DES TESTS

    +
    AprХs que tous les fichiers de test indiquИs aient ИtИ ИxИcutИs, le nombre de tests rИussis, sautИs ou ИchouИs est envoyИ dans::tcltest::outputChannel.  A côtИ de cette information statistique, la sortie peut Йtre pilotИe pour chaque test par la variable ::tcltest::verbose.
    +
      +
    ::tcltest::verbose peut avoir pour valeur n'importe quelle sous-chaНne ou permutation de "bps".   Dans la chaНne "bps", le 'b' se rИfХre au corps (body) du test, le 'p' se rИfХre aux tests rИussis  (passed) et le 's' signifiИ tests sautИs (skipped). La valeur par dИfaut de ::tcltest::verbose est "b". Si 'b' est prИsent, alors le corps entier du test est imprimИ pour chaque test ИchouИ;  sinon seulement le nom du test, la sortie souhaitИe et la sortie obtenue sont imprimИs pour chaque test ИchouИ. Si 'p' est prИsent, alors une ligne est imprimИe pour chaque test rИussi, sinon aucune ligne n'est imprimИe pour les tests rИussis. Si 's' est prИsent, alors une ligne (contenant les contraintes qui ont  fait que le test a ИtИ sautИ) est imprimИe pour chaque test sautИ, sinon aucune ligne n'est imprimИe dans ce cas.
    +
    Vous pouvez positionner ::tcltest::verbose, soit interactivement (une fois que le package tcltest a ИtИ chargИ) ou en utilisant l'argument de ligne de commande -verbose, par exemple:
    +
          tclsh socket.test -verbose bps
    +
    +
    CONTENUS D'UN FICHIER DE TEST
    +
    +
    Les fichiers de test doivent commencer par charger le package tcltest:
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +
    Les fichiers de tests doivent se terminer par l'appel de la fonction de nettoyage ::tcltest::cleanupTests. La procИdure ::tcltest::cleanupTests affiche des statistiques au sujet du nombre de tests rИussis, sautИs ou ИchouИs,  et supprime tous les fichiers crИИs au moyen des procИdures ::tcltest::makeFile et ::tcltest::makeDirectory.
    +
      +
    # Supprime les fichiers crИИs par ces tests
    +
    # Retour au rИpertoire de travail initial
    +# Supprime les tableaux globaux
    +::tcltest::cleanupTests
    +return
    +
    +
    Les fichiers de tests doivent se finir par une extension .test. Les noms des fichiers de tests qui contiennent des tests de rИgression (dits de boНte transparente) doivent Йtre nommИs d'aprХs les fichiers de code Tcl ou C qu'ils testent. Par exemple, le fichier de test du programme C "tclCmdAH.c" doit Йtre "cmdAH.test". Les fichiers qui contiennent des tests "boНte noire" (black-box tests) devraient se conformer au motif "*_bb.test".
    +

    +
    SELECTIONNER DES TESTS A EXECUTER DANS UN FICHIER

    +
    Normalement, quand un fichier est sourcИ, tous les tests qu'il contient sont ИxИcutИs. Individuellement, un test sera sautИ si l'une des conditions suivantes est vraie: +
    +
    [1]
    le nom du test ne correspond pas (en utilisant la correspondance de type "glob") Ю un ou plusieurs ИlИments de la variable ::tcltest::match.
    +
    [2]
    le nom du test correspond (en utilisant la correspondance de type "glob") Ю un ou plusieurs ИlИments de la variable ::tcltest::skip.
    +
    [3]
    l'argument constraints de l'appel Ю ::tcltest::call, s'il existe, contient une ou plusieurs valeurs fausses.
    +
    +
    +
    Vous pouvez dИfinir ::tcltest::match et/ou ::tcltest::skip, soit interactivement (aprХs que le package tcltest a ИtИ sourcИ), ou en utilisant les arguments de ligne de commande -match et -skip, par exemple :  
    +
    tclsh info.test -match '*-5.* *-7.*' -skip '*-7.1*'
    +
    Soyez sûr de bien placer les quotes, de faГon que votre shell ne fasse pas les substitutions de type glob sur les motifs que vous indiquez  (que ce soit bien l'interprИteur tcl qui fasse ces substitutions). 
    +
    Les contraintes prИdИfinies (par exemple knownBug et nonPortable) peuvent Йtre changИes soit interactivement (aprХs que le package tcltest a ИtИ sourcИ), en dИfinissant la variable ::tcltest::testConstraints(constraint), ou en utilisant l'option de ligne de commande -constraints avec le nom de la contrainte comme argument. L'exemple suivant montre comment faire fonctionner des tests contraints par les restrictsions knownBug et nonPortable:
    +
                 tclsh all.tcl -constraints "knownBug nonPortable"
    +
    Voir la section "Contraintes de Test" pour plus d' information sur l'utilisation des contraintes prИdИfinies et l'ajout de nouvelles contraintes.
    +
    +
    PERSONNALISER LE SYSTEME DE TEST
    +
    +
    Pour crИer votre propre systХme de test, crИer un fichier .tcl qui contient votre namespace. Dans ce fichier, appeller le package tcltest (package require tcltest). Les commandes qui peuvent Йtre redИfinies pour personnaliser le systХme de test sont: +
    +
    ::tcltest::PrintUsageInfoHook
    afficher de l'information complИmentaire, spИcifique Ю votre situation.
    +
    ::tcltest::processCmdLineArgsFlagHook
    avertir le systХme au sujet d'options additionnelles que vous voulez qu'il comprenne.
    +
    ::tcltest::processCmdLineArgsHook flags
    traiter les options additionnelles que vous avez communiquИes au systХme de test au travers de ::tcltest::processCmdLineArgsFlagHook.
    +
    ::tcltest::initConstraintsHook
    ajouter des contraintes additionnelles aux contraintes prИdИfinies par tcltest.
    +
    ::tcltest::cleanupTestsHook
    faire du nettoyage additionnel
    +
    +
    +
    Pour ajouter de nouvelles options Ю votre systХme de test personnalisИ, redИfinissez ::tcltest::processCmdLineArgsAddFlagHook pour la liste des options additionnelles Ю interprИter, et ::tcltest::processCmdLineArgsHook pour les traiter effectivement . Par exemple:
    +
    proc ::tcltest::processCmdLineArgsAddFlagHook {} {
    +    return [list -flag1 -flag2]
    +}
    +
    +proc ::tcltest::processCmdLineArgsHook {flagArray} {
    +    array set flag $flagArray
    +
    +    if {[info exists flag(-flag1)]} {
    +        # Handle flag1
    +    }
    +
    +    if {[info exists flag(-flag2)]} {
    +        # Handle flag2
    +    }
    +
    +    return
    +}
    +
    +
      +
    Vous pouvez aussi vouloir ajouter un mode d'emploi pour ces options.  Ce mode d'emploi s'affichera quand l'utilisateur indiquera -help. Pour dИfinir le mode d'emploi additionnel, dИfinissez votre propre procИdure ::tcltest::PrintUsageInfoHook. A l'intИrieur de cette procИdure, vous afficherez le mode d'emploi complИmentaire pour chacune des options que vous avez ajoutИes.
    +
      +
    Pour ajouter de nouvelles contraintes prИdИfinies au systХme de test, dИfinissez votre propre version de ::tcltest::initConstraintsHook.  A l'intИrieur de cette procИdure, vous pouvez complИter le tableau ::tcltest::testConstraints. Par exemple:
    +
    proc ::tcltest::initConstraintsHook {} {
    +    set ::tcltest::testConstraints(win95Or98) \
    +            [expr {$::tcltest::testConstraints(95) || \
    +            $::tcltest::testConstraints(98)}]
    +}
    +
    +
    Enfin, si vous voulez ajouter du code de nettoyage complИmentaire, vous pouvez dИfinir votre propre ::tcltest::cleanupTestsHook.  Par exemple:
    +
    proc ::tcltest::cleanupTestsHook {} {
    +    # Add your cleanup code here
    +}
    +
    +
    EXEMPLES
    +
      +
    [1]      Un fichier de test simple (foo.test)
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +test foo-1.1 {enregistrer 1 dans la variable foo} {} {
    +    set foo 1
    +} {1}
    +
    +::tcltest::cleanupTests
    +return
    +
    +
    [2]      Un fichier all.tcl simple
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +set ::tcltest::testSingleFile false
    +set ::tcltest::testsDirectory [file dir [info script]]
    +
    +foreach file [::tcltest::getMatchingTestFiles] {
    +    if {[catch {source $file} msg]} {
    +        puts stdout $msg
    +    }
    +}
    +
    +::tclttest::cleanupTests 1
    +return
    +
    +
    [3]      ExИcuter un test simple
    +
    tclsh foo.test
    +
    +
    [4]      ExИcuter des tests multiples
    +
    tclsh all.tcl -file 'foo*.test' -notfile 'foo2.test'
    +
    +
      +
    DerniХre rИvision: 8.2
    + diff --git a/hlp/fr/tcl/after.htm b/hlp/fr/tcl/after.htm new file mode 100644 index 0000000..b20575f --- /dev/null +++ b/hlp/fr/tcl/after.htm @@ -0,0 +1,53 @@ + + + + +

    after      Commandes Internes Tcl

    +
    + + +
    NOM

    +
    after - Execute une commande aprХs un certain dИlai +

    +
    SYNTAXE

    +
    after ms
    +after ms ?script script script ...?
    +after cancel id
    +after cancel script script script ...
    +after idle ?script script script ...?
    +after info ?id? +

    +
    DESCRIPTION

    +
    Cette commande est utilisИe pour retarder l'exИcution d'un programme ou exИcuter une commande en arriХre-plan aprХs un certain dИlai +. Elle a plusieurs formes, dИpendantes du premier argument de la commande:
    +
    +
    +
    after ms
    +
    Ms doit Йtre un entier donnant une durИe en millisecondes. La commande dort pendant ms millisecondes et ensuite retourne. Tant que la commande dort l'application ne rИpond pas aux ИvХnements. +
    +

    +after ms ?script script script ...?
    Sous cette forme la commande retourne immИdiatement, mais elle prИpare une commande Tcl Ю Йtre exИcutИe ms millisecondes plus tard comme un gestionnaire d'ИvХnement. La commande sera exИcutИe exactement une fois, Ю l'instant donnИ. La commande retardИe est formИe par concatИnation de tout les arguments de script de la mЙme faГon que par la commande concat. La commande sera exИcutИe au niveau global (en dehors du contexte de toute fonction Tcl). Si une erreur se produit pendant l'exИcution de la commande retardИe alors le mИcanisme bgerror est utilisИ pour rapporter l'erreur. La commande after renvoie un identificateur qui peut Йtre utilisИ pour annuler la commande retardИe en utilisant after cancel. +
    +

    +after cancel id
    Annule l'exИcution d'une commande retardИe qui a ИtИ prИcedemment programmИe. Id indique quelle commande sera annulИe; il doit avoir ИtИ la valeur de retour d'une prИcИdente commande after. Si la commande dИsignИe par id a dИjЮ ИtИ exИcutИe alors la commande after cancel n'a pas d'effet. +
    +

    +after cancel script script ...
    +
    Cette commande annule aussi l'exИcution d'une commande retardИe. Les arguments script sont concatИnИs sИparИs par des espaces (comme dans la commande concat). S'il y a une commande en attente qui correspond Ю la chaНne, elle est annulИe et ne sera jamais exИcutИe; si aucune commande n'est en attente alors la commande after cancel n'a pas d'effet. +
    +

    +after idle script ?script script ...?
    +
    ConcatХne les arguments script avec des sИparateurs espace (comme dans la commande concat), et prИpare le script rИsultant Ю Йtre ИvaluИ plus tard comme un callback inactif . Le script sera lancИ exactement une fois, Ю l'instant de rentrer dans la boucle d'ИvХnement et qu'il n'y a pas d'ИvХnements Ю traiter. La commande renvoie un identificateur qui peut Йtre utilisИ pour annuler la commande retardИe en utilisant after cancel. Si une erreur se produit pendant l'exИcution du script alors le mИcanisme bgerror est utilisИ pour rapporter l'erreur. +
    +

    +after info ?id?
    Cette commande renvoie l'information au sujet des gestionnaires d'ИvХnement existants. Si aucun argument id est fourni, la commande renvoie une liste d'identificateurs de tous les gestionnaires d'ИvХnements existants crИИs par la commande after pour cet interprИteur. Si id est fourni, il spИcifie un gestionnaire existant; id doit avoir ИtИ la valeur de retour d'un prИcedent appel de after et il ne doit pas avoir ИtИ dИjЮ dИclenchИ ou ИtИ annulИ. Dans ce cas la commande renvoie une liste de deux ИlИments. Le premier ИlИment de la liste est le script associИ Ю id, et le second ИlИment est soit idle soit timer pour indiquer de quelle sorte de gestionnaire d'ИvХnement il s'agit.
    +
    +
    +
    Les formes after ms et after idle de la commande supposent que l'application est pilotИe par ИvХnement: les commandes retardИes ne seront pas exИcutИes tant que l'application ne rentrera pas dans la boucle d'ИvХnement. Dans les applications qui ne sont pas normalement pilotИes par ИvХnement, telles que tclsh, on peut activer la boucle d'ИvХnement avec les commandes vwait et update. +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/append.htm b/hlp/fr/tcl/append.htm new file mode 100644 index 0000000..9b47afc --- /dev/null +++ b/hlp/fr/tcl/append.htm @@ -0,0 +1,18 @@ + + + + +

    append      Commandes Internes Tcl

    +
    + +
    NOM

    +
    append - Ajoute Ю une variable +

    +
    SYNTAXE

    +
    append varName ?value value value ...? +

    +
    DESCRIPTION

    +
    Ajoute tous les arguments value Ю la valeur courante de la variable varName.  Si varName n'existe pas, il lui est donnИ une valeur Иgale Ю la concatИnation de tous les arguments value. Cette commande fournit un moyen efficace de construire des variables longues par incrИmentation. Par exemple, “append a $b” est beaucoup plus efficace que “set a $a$b” si $a est long.
    +
    +
    + diff --git a/hlp/fr/tcl/array.htm b/hlp/fr/tcl/array.htm new file mode 100644 index 0000000..97c508d --- /dev/null +++ b/hlp/fr/tcl/array.htm @@ -0,0 +1,42 @@ + + + + +

    array      Commandes Internes Tcl

    +
    +
    NOM

    +
    array - Manipule les variables tableau +

    +
    SYNTAXE

    +
    array option arrayName ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande effectue une des opИrations sur la variable donnИe par arrayName. Sauf spИcification contraire pour certaines commandes individuelles ci-dessous, arrayName doit Йtre le nom d'une variable tableau existante. L'argument option dИtermine l'action effectuИe par la commande. Les options lИgales (qui peuvent Йtre abrИgИes) sont: +
    +
    array anymore arrayName searchId
    Renvoie 1 s'il reste au moins un ИlИment Ю traiter pour une recherche dans le tableau, 0 si tous les ИlИments ont dИjЮ ИtИ renvoyИs. SearchId indique la recherche Ю vИrifier dans arrayName, et doit avoir ИtИ la valeur de retour d'un prИcИdent appel de array startsearch. Cette option est particuliХrement utile si un tableau contient un ИlИment avec un nom vide, parce que la valeur de retour de array nextelement n'indiquera pas si la recherche est terminИe. +
    +

    array donesearch arrayName searchId
    Cette commande termine une recherche dans un tableau et dИtruit l'Иtat associИ Ю cette recherche. SearchId indique quelle recherche dИtruire dans arrayName; et doit avoir ИtИ la valeur de retour d'un prИcИdent appel de array startsearch. Renvoie une chaНne vide. +
    +

    array exists arrayName +
    Renvoie 1 si arrayName est une variable tableau, 0 s'il n'y a pas de variable de ce nom ou si c'est une variable scalaire.
    +

    array get arrayName ?pattern?
    +Renvoie une liste contenant des paires d'ИlИments. Le premier ИlИment de chaque paire est le nom d'un ИlИment de arrayName et le second ИlИment de chaque paire est la valeur de l'ИlИment de tableau. L'ordre des paires est indИfini. Si pattern n'est pas spИcifiИ, alors tous les ИlИments du tableau sont inclus dans le rИsultat. Si pattern est spИcifiИ, alors seuls les ИlИments dont les noms correspondent Ю pattern (en utilisant les rХgles de correspondances de string match) sont inclus. Si arrayName n'est pas le nom d'une variable tableau, ou si le tableau ne contient pas d'ИlИments, alors une liste vide est renvoyИe. +
    +

    array names arrayName ?pattern?
    Renvoie une liste contenant le noms de tous les ИlИments dans le tableau qui correspondent Ю pattern (en utilisant les rХgles de correspondance de string match). Si pattern est omis alors la commande renvoie tous les noms des ИlИments dans le tableau. S'il n'y a pas d 'ИlИments (correspondants) dans le tableau, ou si arrayName n'est pas le nom d'une variable tableau, alors une chaНne vide est renvoyИe. +
    +

    array nextelement arrayName searchId
    Renvoie le nom de l'ИlИment suivant dans arrayName, ou une chaНne vide si tous les ИlИments de arrayName ont dИjЮ ИtИs renvoyИ dans cette recherche. L'argument searchId identifie la recherche, et doit avoir ИtИ la valeur de retour d'une commande array startsearch. Attention: si des ИlИments sont ajoutИs Ю ou effacИs de ce tableau, alors toutes les recherches sont automatiquement terminИes exactement comme si array donesearch avait ИtИ appelИe; ceci causerait l'echec des opИrations array nextelement pour ces recherches. +
    +

    array set arrayName list
    Fixe les valeurs d'un ou plusieurs ИlИments de arrayName. list doit avoir une forme identique Ю celle renvoyИe par array get, consistant d'un mЙme nombre d'ИlИments. Chaque ИlИment impair dans list est traitИ comme un nom d'ИlИment dans arrayName, et les ИlИments suivants de list sont utilisИs comme une nouvelle valeur pour cet ИlИment de tableau. Si la variable arrayName n'existe pas dИjЮ et que list est vide, arrayName est crИИe avec une valeur tableau vide. +
    +

    array size arrayName
    Renvoie une chaНne dИcimale donnant le nombre d'ИlИments dans le tableau. Si arrayName n'est pas le nom d'un tableau alors 0 est renvoyИ. +
    +

    array startsearch arrayName
    Cette commande initialise une recherche ИlИment-par-ИlИment dans le tableau dИsignИ par arrayName, dont les appels de la commande array nextelement renverront les noms des ИlИments individuels dans le tableau. Quand la recherche est terminИe, la commande tableau donesearch sera appelИe. La valeur de retour est un identificateur de recherche qui doit Йtre utilisИ dans les commandes array nextelement et array donesearch; il permet Ю de multiples recherches d'Йtre menИes simultanИment sur le mЙme tableau. +
    +

    array unset arrayName ?pattern? +
    Efface tous les ИlИments du tableau qui correspondent Ю pattern (en utilisant les rХgles correspondantes de string match). Si arrayName n'est pas le nom d'une variable tableau ou qu'il n'y a pas d'ИlИments correspondant dans le tableau, alors une chaНne vide est renvoyИe. Si pattern est omis et que c'est une variable tableau, alors la commande efface le tableau entier.
    +

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/bgerror.htm b/hlp/fr/tcl/bgerror.htm new file mode 100644 index 0000000..f15286e --- /dev/null +++ b/hlp/fr/tcl/bgerror.htm @@ -0,0 +1,25 @@ + + + + +

    bgerror      Commandes Internes Tcl

    +
    + +
    NOM

    +
    bgerror - Commande appelИe pour traiter les erreurs d'arriХre-plan +

    +
    SYNTAXE

    +
    bgerror message +

    +
    DESCRIPTION

    +
    La commande bgerror n'existe pas en tant que partie de Tcl. Par contre, les applications individuelles ou les utilisateurs peuvent definir une commande bgerror (ex. comme une fonction Tcl) s'ils souhaitent gИrer les erreurs d'arriХre-plan.
    +
    Une erreur d'arriХre-plan est une erreur qui se produit dans un gestionnaire d'ИvХnement ou une autre commande qui n'est pas produite par l'application. Par exemple, si une erreur se produit pendant l'exИcution d'une commande spИcifiИe avec la commande after, alors c'est une erreur d'arriХre-plan. Pour une erreur qui n'est pas d'arriХre-plan, l'erreur peut simplement Йtre remontИe par les Иvaluations de commandes imbriquИes Tcl jusqu'a ce qu'elle atteigne le code de premier plan dans l'application; alors l'application peut rapporter l'erreur de la maniХre souhaitИe. Quand une erreur d'arriХre-plan se produit, le dИroulement s'achХve dans la bibliothХque Tcl et il n'y a pas de moyen precis pour Tcl de rapporter l'erreur.
    +
    Quand Tcl detecte une erreur d'arriХre-plan, il sauvegarde l'information relative Ю l'erreur et appelle la commande bgerror plus tard comme un gestionnaire d'ИvХnement inactif. Avant d'appeler bgerror, Tcl restaure les variables errorInfo et errorCode aux valeurs en cours Ю l'instant ou l'erreur s'est produite, et appelle bgerror avec le message d'erreur comme seul argument. Tcl suppose que l'application a implИmentИ la commande bgerror, et que la commande rapporte l'erreur d'une maniХre sensИe pour l'application.  Tcl ignore tout rИsultat renvoyИ par le commande bgerror tant qu'aucune erreur n'est gИnИrИe.
    +
    Si une autre erreur Tcl se produit Ю l'intИrieur de la commande bgerror (par exemple, parcequ'aucune commande bgerror n'a ИtИ dИfinie) alors Tcl rapporte l'erreur lui-mЙme en Иcrivant un message sur la sortie standard.
    +
    Si plusieurs erreurs d'arriХre-plan s'accumulent avant que bgerror soit appelИe pour les traiter, bgerror sera appelИe une fois pour chaque erreur, dans l'ordre ou elles se sont produites. NИanmoins, si bgerror retourne avec une exception break, alors toute les erreurs restantes seront ignorИes sans appeller bgerror.
    +
    Tcl n'a pas d'implИmentation par dИfaut de bgerror. NИanmoins, dans une application utilisant Tk il y a une fonction bgerror par dИfaut qui affiche une boite de dialogue contenant le message d'erreur et offre Ю l'utilisateur la possibilitИ de visualiser la trace de la pile montrant oЫ l'erreur s'est produite. 

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/binary.htm b/hlp/fr/tcl/binary.htm new file mode 100644 index 0000000..39df021 --- /dev/null +++ b/hlp/fr/tcl/binary.htm @@ -0,0 +1,178 @@ + + + + +

    binary      Commandes Internes Tcl

    +
    +
    NOM

    +
    binary - InsХre et extrait des champs Ю partir de chaНnes binaires +

    +
    SYNTAXE

    +
    binary format formatString ?arg arg ...?
    +binary scan string formatString ?varName varName ...? +

    +
    DESCRIPTION

    +
    Cette commande fournit des facilitИs pour la manipulation de donnИes binaires. La premiХre forme, binary format, crИe une chaНne binaire Ю partir de valeurs Tcl standards. Par exemple, en partant des valeurs 16 et 22, elle produira une chaНne binaire de 8 octets constituИe de deux entiers de 4 octets, un pour chacun des nombres. La seconde forme de la commande, binary scan, fait le contraire: elle extrait les donnИes Ю partir d'une chaНne binaire et les renvoie comme des valeur chaНnes Tcl ordinaire. +

    +
    BINARY FORMAT

    +
    La commande binary format gИnХre une chaНne binaire dont le format est spИcifiИ par le formatString et dont le contenu provient des arguments supplИmentaires.  La valeur binaire rИsultante est renvoyИe.
    +
    Le formatString est constituИ d'une sИquence de zИro ou plus de spИcificateurs de champs sИparИs par zИro ou plusieurs espaces. Chaque spИcificateur de champ est un simple caractХre suivi par un nombre optionnel compte. La plupart des spИcificateurs de champs attendent un argument pour formater la valeur. Le caractХre spИcifie comment la valeur est formatИe. Le nombre compte indique combien d'items du type spИcifiИ sont prИsents dans la valeur. Si prИsent, compte est un entier dИcimal non-nИgatif ou *, qui indique normalement que tous les ИlИments de la valeur doivent Йtre utilisИs. Si le nombre d'arguments ne correspond  pas au nombre de champs dans le format chaНne qui attend les arguments, alors une erreur est gИnИrИe.
    +
    Chaque paire type-compte dИplace un curseur imaginaire au travers des donnИes binaires, en stockant les octets Ю la position courante et avancant le curseur juste aprХs le dernier octet stockИ.  Le curseur est initialement Ю la position 0 au dИbut des donnИes. Le type peut Йtre l'un des caractХres suivants:
    +
    +
    +
    a
    Stocke une chaНne de caractХres de longueur compte dans la chaНne de sortie. Si arg a moins d'octets que compte, alors des octets supplИmentaire nuls sont utilisИs pour remplir le champ. Si arg est plus long que la longueur spИcifiИe, les caractХres supplИmentaires sont ignorИs. Si compte est *, alors tous les octets de arg sont formatИs. Si compte est omis, alors un caractХre est formatИ. Par exemple, +binary format a7a* alpha bravo charlie +renverra une chaНne Иquivalente Ю alpha\000\000bravoc. +
    +
    A
    Cette forme est la mЙme que a exceptИ que des espaces sont utilisИs pour le remplissage au lieu de nuls. Par exemple, +binary format A6A*A alpha bravo charlie +renverra alpha bravoc. +
    +
    b
    Stocke une chaНne de compte chiffres binaires en ordre croissant dans chaque octet de la chaНne de sortie. Arg doit contenir une sИquence de 1 et de 0. Les octets rИsultants sont emis du premier au dernier  avec les bits formatИs de bas en haut dans chaque octet. Si arg a moins de chiffres que compte, alors des zИros seront utilisИs pour les bits restant. Si arg a plus de chiffres que le nombre spИcifiИs, les chiffres supplИmentaires sont ignorИs.  Si compte est *, alors tous les chiffres de arg sont formatИs. Si compte est omis, alors un digit est formatИ. Si le nombre de bits formatИs ne finit pas Ю un  une limite d'octet, les bits restants du dernier octet seront des zИros. Par exemple, +binary format b5b* 11100 111000011010 +renverra une chaНne Иquivalentee Ю \x07\x87\x05.
    +
    B
    Cette forme est la mЙme que b exceptИ que le bits sont stockИs dans l'ordre descendant dans chaque octet. Par exemple, +binary format B5B* 11100 111000011010 +renverra une chaНne Иquivalentee Ю \xe0\xe1\xa0. +
    +
    h
    Stocke une chaНne de compte chiffres hexadИcimaux de bas en haut dans chaque octet de la chaНne de sortie.  Arg doit contenir une sИquence de caractХres comprise dans ``0123456789abcdefABCDEF''. Les octets rИsultants sont Иmis du premier au dernier avec les chiffres hexa formatИs de bas en haut dans chaque octet.  Si arg a moins de chiffres que compte, alors des zИros sont utilisИs pour les chiffres restants. Si arg a plus de chiffres que le nombre spИcifiИs, les chiffres supplИmentaires seront ignorИs.  Si compte est *, alors tous les chiffres de arg seront formatИs.  Si compte est omis, alors un digit est formatИ.  Si le nombre de chiffres formatИe ne finit pas Ю une limite d'octet, les bits restants du dernier octet seront des zИros. Par exemple, +binary format h3h* AB def +renverra une chaНne Иquivalente Ю \xba\x00\xed\x0f. +
    +
    H
    Cette forme est la mЙme que h exceptИ que le chiffres sont stockИs de  haut en bas dans chaque octet.  Par exemple, +binary format H3H* ab DEF +renverra une chaНne Иquivalente Ю \xab\x00\xde\xf0. +
    +
    c
    Stocke une ou plusieurs valeur entiХres 8-bit dans la chaНne de sortie.  Si aucun compte n'est spИcifiИ, alors arg doit Йtre une valeur entiХre; autrement arg doit Йtre une liste contenant au moins compte ИlИments entiers.  Les 8 bits de poids faible de chaque entier sont stockИs comme une valeur d'un octet Ю la position du curseur.  Si compte est *, alors tous les entiers de la liste sont formatИs.  Si le nombre d'ИlИments dans la liste est infИrieur Ю compte, alors une erreur est gИnИrИe.  Si le nombre d'ИlИments dans la liste est supИrieur Ю compte, alors les ИlИments supplИmentaires sont ignorИs.  Par exemple, +binary format c3cc* {3 -3 128 1} 260 {2 5} +renverra une chaНne Иquivalente Ю \x03\xfd\x80\x04\x02\x05, alors que +binary format c {2 5} +gИnИrera une erreur. +
    +
    s
    Cette forme est la mЙme que c exceptИ qu'elle stocke un ou plusieurs entiers 16-bit en ordre little-endian dans la chaНne de sortie. Les 16 bits de poids faible de chaque entier sont stockИs comme une valeur de deux-octet Ю la position du curseur avec l'octet de poids faible stockИ en premier.  Par exemple, +binary format s3 {3 -3 258 1} +renverra une chaНne Иquivalente Ю  \x03\x00\xfd\xff\x02\x01. +
    +
    S
    Cette forme est la mЙme que s exceptИ qu'elle stocke un ou plusieurs entiers 16-bit en ordre big-endianx dans la chaНne de sortie.  Par exemple, +binary format S3 {3 -3 258 1} +renverra une chaНne Иquivalente Ю  \x00\x03\xff\xfd\x01\x02. +
    +
    i
    Cette forme est la mЙme que c exceptИ qu'elle stocke un ou plusieurs entiers 32-bit en ordre little-endian dans la chaНne de sortie. Les 32 bits de poids faible de chaque entier sont stockИs comme une valeur de quatre-octet Ю la position du curseur avec l'octet de poids faible stockИ en premier.Par exemple, +binary format i3 {3 -3 65536 1} +renverra une chaНne Иquivalente Ю \x03\x00\x00\x00\xfd\xff\xff\xff\x00\x00\x01\x00 +
    +
    I
    Cette forme est la mЙme que i exceptИ qu'elle stocke un ou plusieurs 32-bit entiers en ordre big-endian dans la chaНne de sortie. Par exemple, +binary format I3 {3 -3 65536 1} +renverra une chaНne Иquivalente Ю \x00\x00\x00\x03\xff\xff\xff\xfd\x00\x01\x00\x00 +
    +
    f
    Cette forme est la mЙme que c exceptИ qu'elle stocke un ou plusieurs flottants simple precision dans la reprИsentation native de la machine dans la chaНne de sortie. Cette reprИsentation n'est pas portable, donc elle ne doit pas Йtre utilisИe pour communiquer des nombres flottants sur le rИseau. La taille d'un nombre flottant peut varier selon les architectures, donc le nombre d'octets gИnИrИs peut varier.Si la valeur deborde de la reprИsentation native de la machine, alors la valeur de FLT_MAX dИfinie par le systХme sera utilisИe.Parce que Tcl utilise des nombres flottants double-precision en interne, il peut y avoir une certaine perte de precision dans la conversion en simple-precision. Par exemple, sur un systХme Windows s'exИcutant sur un processeur Pentium Intel, +binary format f2 {1.6 3.4} +renverra une chaНne Иquivalente Ю\xcd\xcc\xcc\x3f\x9a\x99\x59\x40. +
    +
    d
    Cette forme est la mЙme que f exceptИ qu'elle stocke un ou plusieurs flottants double-precision dans la reprИsentation native de la machine dans la chaНne de sortie.  Par exemple, sur un systХme Windows s'exИcutant sur un processeur Pentium Intel, +binary format d1 {1.6} +renverra une chaНne Иquivalente Ю \x9a\x99\x99\x99\x99\x99\xf9\x3f. +
    +
    x
    Stocke compte octet nuls dans la chaНne de sortie. Si compte n'est pas spИcifiИ, elle stocke un octet null.  Si compte est *, elle gИnХre une erreur. Ce type n'attend pas d'argument.Par exemple, +binary format a3xa3x2a3 abc def ghi +renverra une chaНne Иquivalente Ю abc\000def\000\000ghi. +
    +
    X
    DИplace le curseur en arriХre de compte octets dans la chaНne de sortie.  Si compte est *ou est supИrieur Ю la position courante du curseur, alors le curseur est positionnИ Ю l'emplacement 0 ainsi l'octet suivant stockИ sera le premier octet dans la chaНne rИsultat. Si compte est omis alors le curseur est dИplacИ d'un octet vers l'arriХre. Ce type n'attend pas d'argument.Par exemple, +binary format a3X*a3X2a3 abc def ghi +renverra dghi. +
    +
    @
    DИplace le curseur Ю l'emplacement absolu spИcifiИ par compte dans la chaНne de sortie.  La position 0 correspond au premier octet dans la chaНne de sortie.  Si compte correspond Ю  une position au-dela du dernier octet stockИ, alors des octet nuls seront  placИs aux emplacements non initalisИs et le curseur sera placИ Ю l'emplacement spИcifiИ.  Si compte est *, alors le curseur est dИplacИ Ю la fin de la chaНne de sortie actuelle.  Si compte est omis, alors une erreur est gИnИrИe. Ce type n'attend pas d'argument. Par exemple, +binary format a5@2a1@*a3@10a1 abcde f ghi j +renverra abfdeghi\000\000j.
    +
    +
    +
    + +
    BINARY SCAN

    +
    La commande binary scan analyse les champs d'une chaНne binaire, retournant le nombre de conversions effectuИes.  String donne l'entrИe Ю analyser et formatString indique comment l'analyser. Chaque varName donne le nom d'une variable; quand un champ de string est analysИ le rИsultat est assignИ Ю la variable correspondante.
    +
    Comme avec binary format, le formatString est constituИ d'une sИquence de zИro ou plusieurs spИcificateurs de champs sИparИes par zИro ou plusieurs espaces.  Chaque spИcificateur de champ est un simple caractХre suivi par un nombre optionnel compte.  La plupart des spИcificateurs de champs utilisent un argument pour obtenir la variable dans laquelle les valeurs seront placИes.  Le caractХre spИcifie comment les donnИes binaires sont interprИtИes.  Le compte indique typiquement combien d'examplaires du type spИcifiИ sont extraits des donnИes.  Si prИsent, compte est un entier dИcimal non-nИgatif ou *, qui indique normalement que tous les items restant dans les donnИes doivent Йtre utilisИs. S'il n'y a pas assez d'octets aprХs la position courante du curseur pour satisfaire le spИcificateur de champ courant, alors la variable correspondante est inchangИe et binary scan retourne immИdiatement avec le nombre de variables qui ont ИtИ de'finies. S'il n'y a pas assez d'arguments pour tous les champs de la chaНne format nИcessitant des arguments, alors une erreur est gИnИrИe.
    +
    Il est important de noter que les c, s, et S (et i et I sur les systХmes 64bit) extraient les donnИes dans des entiers de type long.  Ce faisant, les entiers qui ont leurs bit haut  positionnИ (0x80 pour chars, 0x8000 pour shorts, 0x80000000 pour ints), seront signИes.Ainsi :
    +
    set signShort [binary format s1 0x8000]
    +binary scan $signShort s1 val;# val == 0xFFFF8000
    +
    Si vous voulez produire une valeur non signИe, vous pouvez masquer la valeur de retour Ю la taille dИsirИe.  Par exemple, pour produire un entier court non signИe:
    +
    set val [expr {$val & 0xFFFF}];# val == 0x8000
    +
    Chaque paire type-compte dИplace un curseur imaginaire le long des donnИes binaires, en lisant les octets Ю la position courante.  Initialement le curseur est Ю la position 0 au dИbut des donnИes. Le type peut Йtre l'un des caractХres suivants: +
    +
    a
    Les donnИes sont une chaНne de caractХres de longueur compte.  Si compte est *, alors tous les octets restants dans string seront scannИs dans la variable.  Si compte est omis, alors un caractХre sera scannИ. Par exemple, +binary scan abcde\000fghi a6a10 var1 var2 +retournera 1 avec la chaНne Иquivalente Ю abcde\000 stockИe dans var1 et var2 inchangИe. +
    +
    A
    Cette forme est la mЙme que a, exceptИ que les espaces et les nulls sont enlevИs de la valeur scannИe avant d'Йtre stockИ dans la variable.  Par exemple, +binary scan "abc efghi \000" A* var1 +renverra 1 avec abc efghi stockИ dans  var1. +
    +
    b
    Les donnИes sont transformИes en une chaНne de compte chiffres binaires de bas en haut representИs comme une sИquence de caractХres "1" et "0". Les octets de donnИes sont scannИes du premier au dernier avec les bits rangИs de bas en haut pour chaque octet. Les bits supplИmentaires dans le dernier octet sont ignorés;. Si compte est *, alors tous les bits restant dans string seront scannИs. Si compte est omis, alors un bit sera scannИ.Par exemple, +binary scan\x07\x87\x05 b5b* var1 var2 +renverra 2 avec 11100 stockИ dans var1 et 1110000110100000 stockИ dans var2. +
    +
    B
    Cette forme est la mЙme que b, exceptИ que les bits sont stockИs dans l'ordre descendant dans chaque octet. Par exemple, +binary scan\x70\x87\x05 B5B* var1 var2 +renverra 2 avec 01110 stockИ dans  var1 et 1000011100000101 stockИ dans var2. +
    +
    h
    Les donnИes sont transformИes en une chaНne de compte chiffres hexadИcimaux dans l'ordre de bas en haut representИs par une sИquence de caractХres de "0123456789abcdef". Les octets de donnИes sont scannИs du premier au dernier avec les chiffres hexa extraits de bas en haut dans chaque octet. Les bits supplИmentaires dans le dernier octet sont ignorИs. Si compte est *, alors tous les chiffres hexa restant dans string sont scannИs. Si compte est omis, alors un digit hexa sera scannИ. Par exemple, +binary scan\x07\x86\x05 h3h* var1 var2 +renverra 2 avec 706 stockИ dans var1 et 50 stockИ dans var2. +
    +
    H
    Cette forme est la mЙme que h, exceptИ que les chiffres sont extraits de haut en bas dans chaque octet. Par exemple, +binary scan\x07\x86\x05 H3H* var1 var2 +renverra 2 avec 078 stockИ dans var1 et 05 stockИ dans var2. +
    +
    c
    Les donnИes sont transformИes en compte entiers signИs 8-bit et stockИes dans la variable correspondante sous forme de liste. Si compte est *, alors tous les octets restant de string seront scannИs. Si compte est omis, alors un entier 8-bit sera scannИ. Par exemple, +binary scan\x07\x86\x05 c2c* var1 var2 +renverra 2 avec 7 -122 stockИ dans var1 et 5 stockИ dans var2. Notez que les entiers renvoyИs sont signИs, mais ils peuvent Йtre convertis en entiers 8-bit non signИes en utilisant une expression telle que: +expr ( $num + 0x100 ) % 0x100 +
    +
    s
    Les donnИes sont interprИtИes comme compte entiers signИs 16-bit representИ en little-endian.  Les entiers sont stockИs dans la variable correspondante sous forme de liste. Si compte est *, alors tous les octets restants de string seront scannИs. Si compte est omis, alors un entier 16-bit sera scannИ. Par exemple, +binary scan\x05\x00\x07\x00\xf0\xff s2s* var1 var2 +renverra 2 avec 5 7 stockИ dans var1 et -16 stockИ dans var2.Notez que les entiers renvoyИs sont signИs, mais ils peuvent Йtre convertis en entiers 16-bit non signИes en utilisant une expression telle que: +expr ( $num + 0x10000 ) % 0x10000 +
    +
    S
    Cette forme est la mЙme que s exceptИ que les donnИes sont interprИtИes comme compte entiers 16-bit signИs representИ en big-endian.  Par exemple, +binary scan\x00\x05\x00\x07\xff\xf0 S2S* var1 var2 +renverra 2 avec 5 7 stockИ dans var1 et -16 stockИ dans var2. +
    +
    i
    Les donnИes sont interprИtИes comme compte entiers 32-bit signИs representИs en little-endian. Les entiers sont stockИs dans la variable correspondante sous forme de liste. Si compte est *, alors tous octets restants de string seront scannИs. Si compte est omis, alors un entier 32-bit sera scannИ. Par exemple, +binary scan\x05\x00\x00\x00\x07\x00\x00\x00\xf0\xff\xff\xff i2i* var1 var2 +renverra 2 avec 5 7 stockИ dans var1 et -16 stockИ dans var2. Notez que les entiers renvoyИs sont signИs et ne peuvent pas Йtre representИs par Tcl comme valeurs non signИes. +
    +
    I
    Cette forme est la mЙme que i exceptИ que les donnИes sont  interprИtИes comme compte entiers 32-bit signИs representИ en big-endian.  Par exemple, +binary\x00\x00\x00\x05\x00\x00\x00\x07\xff\xff\xff\xf0 I2I* var1 var2 +renverra 2 avec 5 7 stockИ dans var1 et -16 stockИ dans var2. +
    +
    f
    Les donnИes sont interprИtИes comme compte nombre flottants simple-prИcision dans la reprИsentation native de la machine.  Les nombres flottants sont stockИs dans la variable correspondante sous forme de liste.  Si compte est *, alors tous les octets restants de string seront scannИs. Si compte est omis, alors un nombre flottant simple-prИcision sera scannИ. La taille d'un nombre flottant peut varier selon les architectures, donc le nombre d'octets scannИs peut varier. Si les donnИes ne reprИsentent pas un nombre flottant valide, la valeur rИsultante est indИfinie et dИpend du compilateur. Par exemple, sur un systХme Windows s'exИcutant sur un processeur Pentium Intel, +binary scan\x3f\xcc\xcc\xcd f var1 +>renverra 1 avec 1.6000000238418579 stockИ dans var1. +
    +
    d
    Cette forme est la mЙme que f exceptИ que les donnИes sont interprИtИes comme compte nombre flottants double-precision dans la reprИsentation native de la machine. Par exemple, , sur un systХme Windows s'exИcutant sur un processeur Pentium Intel, +binary scan\x9a\x99\x99\x99\x99\x99\xf9\x3f d var1 +renverra 1 avec 1.6000000000000001 stockИ dans var1. +
    +
    x
    DИplace le curseur en avant de compte octets dans string. Si compte est * ou est supХrieur au nombre d'octets aprХs la position courante du curseur, alors le curseur est positionnИ aprХs le dernier octet de string.  Si compte est omis, alors le curseur est dИplacИ en avant d'un octet. Notez que ce type n'attend pas d'argument. Par exemple, +binary scan\x01\x02\x03\x04 x2H* var1 +renverra 1 avec 0304 stockИ dans var1. +
    +
    X
    DИplace le curseur en arriХre de  compte octets dans string. Si compte est * ou est supИrieur Ю la position courante du curseur, alors le curseur est positionnИ Ю la position 0 de telle sorte que le prochain octet scannИ sera le premier octet de string. Si compte est omis alors le curseur est dИplacИ en arriХre d'un octet.  Notez que ce type n'attend pas d'argument.  Par exemple, +binary scan\x01\x02\x03\x04 c2XH* var1 var2 +renverra 2 avec 1 2 stockИ dans var1 et 020304 stockИ dans var2. +
    +
    @
    DИplace le curseur Ю la position absolu de la chaНne spИcifiИe par compte. Notez que la position 0 correspondante au premier octet de string. Si compte correspond Ю une position au-dela de la fin de string, alors le curseur est positionnИ aprХs le dernier octet. Si compte est omis, alors une erreur est gИnИrИe. Par exemple, +binary scan\x01\x02\x03\x04 c2@1H* var1 var2 +renverra 2 avec 1 2 stockИ dans var1 et 020304 stockИ dans var2.
    +
    +
    +
    +
    PLATFORM ISSUES

    +
    Il est parfois souhaitable de formater ou scanner des valeur entiХres dans l'ordre natif des octets de la machine. RИfИrez vous Ю l'ИlИment byteOrder du tableau tcl_platform pour connaНtre le caractХre Ю utiliser pour formater ou scanner des entiers. +

    +
    VOIR EGALEMENT

    + +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/break.htm b/hlp/fr/tcl/break.htm new file mode 100644 index 0000000..b237300 --- /dev/null +++ b/hlp/fr/tcl/break.htm @@ -0,0 +1,18 @@ + + + + +

    break      Commandes Internes Tcl

    +
    +
    NOM

    +
    break √ Sort d'une commande de boucle +

    +
    SYNTAXE

    +
    break +

    +
    DESCRIPTION

    +
    Cette commande est habituellement appelИe dans le corps d'une commande de boucle tel que for ou foreach ou while. Elle renvoie un code TCL_BREAK, qui cause une exception break. L'exception cause l'arrЙt du script courant Ю l'intИrieur de la commande de boucle, qui cesse alors son exИcution et retourne normalement. Les exceptions break sont aussi gИrИes dans quelques autres cas, tels que la commande catch, les bindings d'ИvХnement Tk, et les scripts externes des corps de fonction.
    +
    +
    + diff --git a/hlp/fr/tcl/case.htm b/hlp/fr/tcl/case.htm new file mode 100644 index 0000000..4de88b9 --- /dev/null +++ b/hlp/fr/tcl/case.htm @@ -0,0 +1,21 @@ + + + + +

    case      Commandes Internes Tcl

    +
    +
    NOM

    +
    case - Evalue un parmi plusieurs scripts, dИpendant d'une valeur donnИe +

    +
    SYNTAXE

    +
    case string ?in? patList body ?patList body ...?
    +case string ?in? {patList body ?patList body ...?} +

    +
    DESCRIPTION

    +
    Note: la commande case est obsolХte et est supportИe uniquement pour compatibilitИ ascendante.  Elle sera supprimИe un jour ou l'autre. Utilisez la plutot la commande switch .
    +
    La commande case compare string Ю chacun des arguments patList dans l'ordre. Chaque argument patList est une liste d'un ou plusieurs modХles. Si un de ces modХles correspond Ю string alors case Иvalue l'argument body suivant en le transmettant rИcursivement Ю l'interprИteur Tcl et renvoie le rИsultat de cette evaluation. Chaque argument patList est constituИ d'un simple modХle ou d'une liste de modХles.  Chaque modХle peut contenir un des jokers dИcrits dans string match.  Si un argument patList est default, le body correspondant sera ИvaluИ si aucun patList ne correspond Ю string.  Si aucun argument patList ne correspond Ю string et default n'est pas dИfini, alors la commande case renvoie une chaНne vide.
    +
    Deux syntaxes sont fournies pour les arguments patList et body. La premiХre utilise un argument sИparИ pour chacun des modХles et commandes; cette forme convient si les substitutions sont dИsirИes dans un des modХles ou des commandes. La seconde forme regroupe tous les modХles et commandes dans un simple argument; l'argument doit avoir une structure de liste correcte, les ИlИments de la liste etant les modХles et commandes. La seconde forme facilite la construction de commandes case multi-ligne, car les accolades englobant la liste rendent inutile l'inclusion d'un antislash Ю la fin de chaque ligne. Comme les arguments patList sont entre accolades dans la seconde forme, aucune substitution de commande ou de variable ne leur sont appliquИes; ceci rend le comportement de la seconde forme diffИrent de la premiХre dans quelque cas.

    +
    DerniХre rИvision: 7.0
    +
    +
    + diff --git a/hlp/fr/tcl/catch.htm b/hlp/fr/tcl/catch.htm new file mode 100644 index 0000000..96f8702 --- /dev/null +++ b/hlp/fr/tcl/catch.htm @@ -0,0 +1,34 @@ + + + + +

    catch     Commandes Internes Tcl

    +
    +
    NOM

    +
    catch - Evalue un script et intercepte les renvois d'exceptions +

    +
    SYNTHESE

    +
    catch script ?varName? +

    +
    DESCRIPTION

    +
    La commande catch peut Йtre employИe pour empecher les erreurs de faire Иchouer l'Иvaluation d'une commande. Catch appelle l'interprИteur Tcl rИcursivement pour exИcuter script, et retourne toujours sans lever une erreur, indИpendemment de toute erreur produite pendant l'exИcution de script.
    +
    Si script lХve une erreur, catch renverra une valeur entiХre diffИrente de zИro correspondant Ю un des code de retours d'exceptions (voir tcl.h pour la dИfinitions des codes). Si l'argument varName est fourni, alors le message d'erreur de l'Иvaluation de script est affectИ Ю la variable dИsigne par varName.
    +
    Si script ne lХve pas d'erreur, catch renverra 0 (TCL_OK) et la valeur renvoyИe par script est affectИe Ю la variable.
    +
    Notez que catch intercepte toutes exceptions, incluant celles gИnИrИes par break et continue aussi bien que les erreurs. Les seules erreurs qui ne sont pas interceptИes sont les erreurs de syntaxe trouvИes quand le script est compilИ. Ceci est du Ю ce que la commande catch n'intercepte les erreurs qu'Ю l'exИcution. Quand l'instruction catch est compilИe, le script est aussi compilИ et toutes les erreurs de syntaxe gИnИrent une erreur Tcl.
    +

    +
    EXEMPLES

    +
    La commande catch peut Йtre employИe dans un if pour des choix basИs sur le succХs d'un script.
    +
    if { [catch {open $someFile w} fid] } {
    + puts stderr "Ne peut ouvrir $someFile en Иcriture\n$fid"
    + exit 1
    +}
    +
    +
    La commande catch n'interceptera pas les erreurs de syntaxe compilИes. La premiХre fois que la proc foo sera appelИe, le corps sera compilИ et une erreur Tcl sera gИnИrИe.
    +
    proc foo {} {
    + catch {expr {1 +- }}
    +}
    +

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/cd.htm b/hlp/fr/tcl/cd.htm new file mode 100644 index 0000000..6ec091f --- /dev/null +++ b/hlp/fr/tcl/cd.htm @@ -0,0 +1,20 @@ + + + + +

    +cd       Commandes Internes Tcl +

    +
    +
    NOM

    +
    cd - Change le rИpertoire de travail +

    +
    SYNTAXE

    +
    cd ?dirName?
    +

    +
    DESCRIPTION

    +
    Change le rИpertoire de travail courant en dirName, ou en +rИpertoire home (dИfini par la variable d'environnement HOME) si dirName n'est pas donnИ. Retoune une chaНne vide.
    +
    +
    + diff --git a/hlp/fr/tcl/clock.htm b/hlp/fr/tcl/clock.htm new file mode 100644 index 0000000..026fd09 --- /dev/null +++ b/hlp/fr/tcl/clock.htm @@ -0,0 +1,90 @@ + + + +

    clock      Commandes Internes Tcl

    +
    +
    NOM

    +
    clock- Obtient et manipule l'heure +

    +
    SYNTAXE

    +
    clock option ?arg arg ...
    +

    +
    DESCRIPTION

    +
    Cette commande effectue l'une des opИrations qui permettent d'obtenir ou de manipuler des chaНnes ou des valeurs qui reprИsentent une notion de temps. L'argument option dИtermine l'action effectuИe par la commande. Les options lИgales (qui peuvent Йtre abrИgИes) sont: +
    +
    clock clicks ?-milliseconds?
    Retourne une valeur haute-rИsolution de l'heure en tant que valeur entiХre dependante du systХme. L'unitИ de valeur dИpend du systХme mais est la plus haute rИsolution d'horloge disponible sur le systХme tel un cycle CPU. Si -milliseconds est spИcifiИ, alors on a la garantie que la valeur a une granularitИ de la milliseconde. Cette valeur ne doit Йtre utilisИe que pour la mesure relative du temps ИcoulИ. +
    +

    +clock format clockValue ?-format string? ?-gmt boolean?
    Convertit un entier reprИsentant un temps, typiquement renvoyИ par clock seconds, clock scan, ou les options atime, mtime, ou ctime de la commande file, en une forme comprИhensible. Si l'argument -format est prИsent l'argument suivant est une chaНne qui dИcrit comment date et l'heure doivent Йtre formatИs. Les descripteurs de champs sont constituИs d'un % suivi par un caractХre descripteur de champ. Tous les autre caractХres sont copiИs dans rИsultat. Les descripteurs de champs valides sont: +
      +
    • %% InsХre un %.
    • +
    • %a Nom abrИgИ d'un jour de la semaine (Mon, Tue, etc.). +
    • +
    • %A Nom complet d'un jour de la semaine (Monday, Tuesday, etc.). +
    • +
    • %b Nom abrИgИ d'un mois (Jan, Feb, etc.).
    • +
    • %B Nom complet d'un mois
    • +
    • %c Date et heure Locale spИcifique.
    • +
    • %d Jour du mois (01 - 31).
    • +
    • %H Heure en format 24-heure (00 - 23).
    • +
    • %I Heure en format 12-heure (00 - 12).
    • +
    • %j Jour de l'annИe (001 - 366).
    • +
    • %m Numero du mois (01 - 12).
    • +
    • %M Minute (00 - 59).
    • +
    • %p indicateur AM/PM.
    • +
    • %S Secondes (00 - 59).
    • +
    • %U Semaine de l 'annИe (00 - 52), Dimanche est le premier jour de la semaine. +
    • +
    • %w Numero du jour de la semaine. (Dimanche = 0).
    • +
    • %W Semaine de l 'annИe (00 - 52), Lundi est le premier jour de la semaine +
    • +
    • %x Format de Date Locale.
    • +
    • %X Format d'Heure Locale.
    • +
    • %y AnnИe sans siХcle (00 - 99).
    • +
    • %Y AnnИe avec siХcle (ex. 1990)
    • +
    • %Z Nom de Time zone.
    • + De plus, les descripteurs de champs suivants peuvent Йtre supportИs sur quelque systХmes (ex. Unix mais pas Windows): + +
    • %D Date comme %m/%d/%y.
    • +
    • %e Jour du mois (1 - 31), sans le zИro complИmentaire.
    • +
    • %h Nom abrИgИ d'un mois.
    • +
    • %n InsХre un saut de ligne.
    • +
    • %r Heure comme %I:%M:%S %p.
    • +
    • %R Heure comme %H:%M.
    • +
    • %t InsХre une tabulation.
    • +
    • %T Heure comme %H:%M:%S.
    • +
    +Si l'argument - format n'est pas spИcifiИ, la chaНne de formatage "%a %b %d %H:%M:%S %Z %Y" est utilisИe. Si l'argument -gmt est prИsent il doit Йtre suivi d'un boolИen qui s'il est vrai spИcifie que l'heure doit Йtre formatИe comme une heure Greenwich Mean Time. S'il est faux, la timezone locale dИfinie par l'environnement d'exploitation est utilisИe. +
    +

    clock scan dateString ?-base clockVal? ?-gmt boolean? +
    Convertit dateString en une valeur d'horloge entiХre (voir clock seconds). Cette commande peut virtuellement analyser et convertir toute chaНne de date et/ou d'heure standard, qui peut inclure des mnИmoniques timezone standards. Si une heure est spИcifiИe seule, la date courante est supposИe. Si la chaНne ne contient pas de mnИmoniques timezone, la timezone locale est supposИe, Ю moins que l'argument -gmt soit vrai, auquel cas la valeur horloge est calculИe en prИsumant que l'heure spИcifiИe est relative Ю Greenwich Mean Time. -gmt, si spИcifiИ, affecte seulement la valeur de l'heure calculИe; elle n'influe pas sur l'interprИtation de -base.
    +Si le flag -base est spИcifiИ, l'argument suivant doit contenir une valeur horloge entiХre. Seule la date de cette valeur est utilisИe, pas l'heure. Ceci est utile pour dИterminer l'heure d'un jour spИcifique ou faire d'autres conversions relatives Ю la date.
    +La dateString est constituИ de zИro ou plus ИlИments de la forme suivante: +

      +
    • time L'heure du jour, qui est de la forme: hh?:mm?:ss?? ?meridian? ?zone? ou hhmm ?meridian? ?zone?. Si mИridien n'est spИcifiИ, hh est interprИtИ sur une horloge 24-heures. +
    • +
    • date Une date mois et jour spИcifique avec l'annИe optionnelle. Les formats acceptables sont mm/dd?/yy?, monthname dd ?, yy?, dd monthname ?yy?, day, dd monthname yy, ?CC?yymmdd, ?CC?yy-mm-dd, dd-monthname-?CC?yy. L'annИe par dИfaut est l'annИe courante. Si l'annИe est infИrieure Ю 100, les annИes 00-68 seront interprИtИes 2000-2068 et les annИes 69-99 comme 1969-1999. Toutes les plateformes ne savent pas reprИsenter les annИes 38-70, aussi l'utilisation de ces annИes peut entrainer une erreur. +
    • +
    • ISO 8601 point-in-time + Une spИcification ISO 8601, telle que CCyymmddThhmmss, ou T est le literal T, CCyymmdd hhmmss, ou CCyymmddThh:mm:ss. +
    • +
    • relative time + Une spИcification relative Ю l'heure courante. Le format est number unit , les unitИs acceptables sont year, fortnight, month, week, day, hour, minute (ou min), et second (ou sec). L'unitИ peut Йtre donnИe au singulier ou au pluriel, comme dans 3 weeks. Ces modificateurs peuvent aussi Йtre: tomorrow, yesterday, today, now, last, this, next, ago.
      +
    • +

    +La date actuelle est calculИe selon les Иtapes suivantes. D'abord, toute date et/ou temps absolu est traitИe et convertie. Partant de cet instant comme base, les spИcifications du jour de la semaine sont ajoutИes. Ensuite, des spИcifications relatives sont utilisИes. Si une date ou un jour est spИcifiИ, et qu'aucune heure absolue ou relative n'est donnИe, minuit est utilisИ. Finalement, une correction est appliquИe ainsi l'heure du jour correcte est produite aprХs les rectifications pour l'heure d'ИtИ et la date correcte est donnИe au passage de la fin d'un mois long Ю un mois court.
    +La correction d'heure d'ИtИ est appliquИe seulement quand l'heure relative est spИcifiИe dans les unitИs de jour ou plus, c.a.d., jours, semaines, quinzaines, mois ou annИes. Ceci signifie que quand on change d'heure, des rИsultats diffИrents seront donnИs pour clock scan "1 day" et clock scan "24 hours": +% clock scan "1 day" -base [clock scan 1999-10-31]
    +
    941443200
    +
    % clock scan "24 hours" -base [clock scan 1999-10-31]
    +
    941439600 +
    +

    clock seconds
    Retourne l'heure et la date courante comme valeur entiХre dИpendante du systХme . L'unitИ de valeur est la seconde, lui permettant d'Йtre utilisИe pour les calculs de temps relatif. La valeur est usuellement dИfinie comme le temps total ИcoulИ depuis un “epoch”. Vous ne pouvez prИsumer la valeur de l'epoch. +
    +
    +
    +
    DerniХre rИvision: 8.3
    +
    +
    + + diff --git a/hlp/fr/tcl/close.htm b/hlp/fr/tcl/close.htm new file mode 100644 index 0000000..7d12476 --- /dev/null +++ b/hlp/fr/tcl/close.htm @@ -0,0 +1,24 @@ + + + + +

    close      Commandes Internes Tcl

    +
    +
    NOM

    +
    close - Ferme un canal ouvert. +

    +
    SYNTAXE

    +
    close channelId +

    +
    DESCRIPTION

    +
    Ferme le canal donnИ par channelIdChannelId doit Йtre un identificateur de canal tel que la valeur de retour d'une prИcИdente commande open ou socket. Tout le tampon de sortie est vidИ dans le pИriphИrique de sortie du canal, Tout ce qu'il y a dans le tampon d'entrИe est ИliminИ, le fichier ou pИriphИrique sous-jacent est fermИ, et channelId devient inutilisable.
    +
    Si le canal est bloquant, la commande ne retourne pas jusqu'Юvce que toute sortie soit vidИe. Si le canal est non bloquant et qu'il reste des donnИes Ю emettre, le canal reste ouvert et la commande retourne immИdiatement; la sortie sera vidИe en arriХre-plan et le canal sera fermИ quand toutes les donnИes auront ИtИ flushИes.
    +
    Si channelId est un canal bloquant pour une commande pipeline alors close attend que les processus enfants soient terminИs.
    +
    Si le canal est partagИ entre des interprИteurs, alors close rend channelId indisponible pour l'interprИteur appelant mais n'a pas autre effet jusqu'a ce que tous les interprИteurs aient fermИ le canal. Quand le dernier interprИteur dans lequel le canal est declarИ appelle close, les actions de nettoyage dИcrites plus haut se dИclenchent. Voir la commande interp pour une description du partage de canal.
    +
    Les canaux sont automatiquement fermИs quand un interprИteur est dИtruit et quand le processus se termine. Les canaux sont passent en mode bloquant, pour s'assurer que toute sortie est correctement vidИe avant que le processus se termine.

    +
    La commande renvoie une chaНne vide, et peut gИnИrer une erreur si une erreur se produit pendant le flushing de sortie.

    +
    DerniХre rИvision: 7.5
    +
    +
    + + diff --git a/hlp/fr/tcl/concat.htm b/hlp/fr/tcl/concat.htm new file mode 100644 index 0000000..ba07b2a --- /dev/null +++ b/hlp/fr/tcl/concat.htm @@ -0,0 +1,23 @@ + + + + +

    concat      Commandes Internes Tcl

    +
    +
    NOM

    +
    concat √ concatХne des listes +

    +
    SYNTAXE

    +
    concat ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande traite chaque argument comme une liste et les concatХne dans une simple liste. Elle Иlimine aussi les espaces de dИbut et de fin dans les arg's et ajoute un simple separateur espace entre les arg's. Elle permet quelconque nombre d'arguments. Par exemple, la commande
    +
    concat a b {c d e} {f {g h}}
    +
    renverra
    +
    a b c d e f {g h}
    +
    comme rИsultat.
    +
    Si aucun args n'est fourni, le rИsultat est une chaНne vide.
    +
    +
    + + diff --git a/hlp/fr/tcl/continue.htm b/hlp/fr/tcl/continue.htm new file mode 100644 index 0000000..6624afc --- /dev/null +++ b/hlp/fr/tcl/continue.htm @@ -0,0 +1,19 @@ + + + + +

    continue      Commandes Internes Tcl

    +
    + +
    NOM

    +
    continue - Passe Ю l'itИration suivante d'une boucle +

    +
    SYNTAXE

    +
    continue +

    +
    DESCRIPTION

    +
    Cette commande est typiquement appelИe dans le corps d'une commande de boucle telle que for ou foreach ou while. Elle renvoie un code TCL_CONTINUE, qui provoque une exception continue. L'exception provoque l'arrЙt du script courant, et la boucle continue avec l'itИration suivante. Les exceptions sont aussi gИrИes dans d'autres situations, telles que la commande catch et les scripts les plus externes des corps de fonction.
    +
    +
    + + diff --git a/hlp/fr/tcl/dde.htm b/hlp/fr/tcl/dde.htm new file mode 100644 index 0000000..33773e1 --- /dev/null +++ b/hlp/fr/tcl/dde.htm @@ -0,0 +1,58 @@ + + + + +

    dde      Commandes Internes Tcl

    +
    +
    NOM

    +
    dde - ExИcute une commande Dynamic Data Exchange +

    +
    SYNTAXE
    +

    +package require dde 1.1
    +dde servername ?topic?
    +dde ?-async? command service topic ?data
    +

    +
    DESCRIPTION

    +
    Cette commande permet Ю une application d'envoyer une commande Dynamic Data Exchange (DDE) sous Microsoft Windows. Dynamic Data Exchange est un mИcanisme qui permet aux applications d'Иchanger des donnИes . Chaque transaction DDE a besoin d'un service name et d'un topic. L'ensemble de service name et topic sont dИfinis par l'application; Tcl utilise le nom de service TclEval, et le nom du topic est le nom de l'interprИteur donnИ par dde servername. D'autres applications ont leurs propres service names et topics. Par exemple, Microsoft Excel a le nom de service Excel.
    +
    La seule option de la commande dde est: +
    +
    -async
    Demande un appel asynchrone. Ceci est valide seulement pour la sous-commande execute. Normalement, la sous-commande dde execute attend jusqu'Ю ce que la commande se termine, en retournant un message d'erreur appropriИ. Quand l'option - async est utilisИe, la commande retourne immИdiatement, et aucune information d'erreur n'est disponible.
    +
    +
    +
    +
    COMMANDES DDE

    +
    Les commandes suivantes sont un sous ensemble des commandes Dynamic Data Exchange. +
    +
    dde servername ?topic?
    dde servername dИclare l'interprИteur comme serveur DDE avec le nom de service TclEval et le nom de topic spИcifiИ par topic. Si aucun topic n'est donnИ, dde servername retourne le nom du topic courant ou une chaНne vide s'il n'est pas declarИ comme un service. +
    +

    +dde execute service topic data
    dde execute prends data et l'envoie au serveur indiquИ par service avec le topic indiquИ par topic. Typiquement, service est le nom d'une application, et topic est un fichier Ю traiter. Le champ data est donnИ Ю l'application distante. Typiquement, l'application traite le champ data comme un script, et le script est lancИ dans l'application. La commande retourne une erreur si le script n'est pas exИcutИ. Si le flag -async a ИtИ utilisИ, la commande retourne immИdiatement sans erreur. +
    +

    +dde poke service topic item data
    dde poke passes les data au serveur indiquИ par service en utilisant les topic et item spИcifiИ. Typiquement, service est le nom d'un application. topic est spИcifique Ю l'application mais peut Йtre une commande au serveur ou le nom d'un fichier Ю traiter. L' item est aussi spИcifique Ю l'application et est souvent non utilisИ, mais il doit toujours Йtre non-null. Le champ data est transmis Ю l'application distante. +
    +

    +dde request service topic item
    dde request est typiquement utilisИ pour rИcupИrer une valeur; la valeur d'une cellule dans Microsoft Excel ou le texte d'une selection dans Microsoft Word. service est typiquement le nom de l'application, topic est typiquement le nom du fichier, et item est spИcifique Ю l'application. La commande retourne la valeur de item comme dИfini dans l'application. +
    +

    +dde services service topic
    dde services retourne une liste de service-topic pairs qui existe actuellement sur la machine. Si service et topic sont tous deux des null chaНnes ({}), alors toute les paires service-topic disponibles sur le systХme sont renvoyИes. Si service est null et topic non, alors tout les services avec le topic spИcifiИ sont renvoyИs. Si service n'est pas null et que topic est null, tout les topics pour un service donnИ sont renvoyИs. Si les deux ne sont pas null, si cette paire service-topic existe actuellement, elle est renvoyИe; autrement, null est renvoyИ. +
    +

    +dde eval topic cmd ?arg arg ...?
    dde eval Иvalue une commande et ses arguments en utilisant l'interprИteur spИcifiИ par topic. Le service DDE doit Йtre le service TclEval. Cette commande peut Йtre utilisИe pour remplacer send sous Windows.
    +
    +
    +
    +
    DDE ET TCL

    +
    Un InterprИteur Tcl a toujours pour nom de service TclEval. A chaque interprИteur diffИrent parmi toutes les applications Tcl en cours doit Йtre donnИ un nom unique spИcifiИ par dde servername. Chaque interp est disponible comme topic DDE seulement si la commande dde servername a ИtИ utilisИe pour fixer le nom du topic pour chaque interp. Donc une commande dde services TclEval {} renverra une liste de paires service-topic, oЫ chacun des interprИteurs qui s'exИcutent actuellement seront un topic.
    +
    Quand Tcl traite une commande dde execute, les donnИes de execute sont exИcutИes comme script dans l'interprИteur designИ par les topic de la commande dde execute.
    +
    Quand Tcl traite une commande dde request, il retourne la valeur de la variable donnИe dans la commande dde dans le contexte de l'interprИteur designИ par le topic dde. Tcl reserve la variable $TCLEVAL$EXECUTE$RESULT pour usage interne, et une commande dde request pour cette variable donnera un rИsultat imprИvisible.
    +
    Une application externe qui souhaite exИcuter un script Tcl aura besoin que le script stocke son rИsultat dans une variable, devra exИcuter la commande dde execute, puis dde request pour obtenir la valeur de la variable.
    +
    En utilisant DDE, assurez vous soigneusement que la file d'ИvХnements est vidИe en utilisant soit update ou vwait. Ceci se produit par dИfaut en utilisant wish Ю moins qu'une commande bloquante soit appelИe (telle que exec sans ajouter le & pour envoyer le processus en arriХre-plan). Si pour une raison quelconque la file d'ИvХnements n'est pas vidИe, les commandes DDE peuvent se figer jusqu'a ce que la file d'ИvХnements soit vidИe. Ceci peut crИer une situation d'impasse (" deadlock " N.D.T.). +

    +
    VOIR EGALEMENT
    +
    tk, winfo, send
    +
    DerniХre rИvision: 8.1
    +
    + + diff --git a/hlp/fr/tcl/encoding.htm b/hlp/fr/tcl/encoding.htm new file mode 100644 index 0000000..fe67b6a --- /dev/null +++ b/hlp/fr/tcl/encoding.htm @@ -0,0 +1,41 @@ + + + + +

    encoding      Commandes Internes Tcl

    +
    +
    NOM

    +
    encoding - Manipule les encodages +

    +
    SYNTAXE

    +
    encoding option ?arg arg ...? +

    +
    INTRODUCTION

    +
    Les chaНnes en Tcl sont encodИes en utilisant les caractХres Unicode 16-bit. DiffИrentes interfaces au systХme d'exploitation ou applications peuvent gИnИrer des chaНnes dans d'autres encodages tel que Shift-JIS. La commande encoding lance un pont entre Unicode et ces autres formats. +

    +
    DESCRIPTION

    +
    ExИcute une parmi plusieurs opИrations relatives Ю l'encodage, dИpendantes de option. Les options lИgales sont: +
    +
    encoding convertfrom ?encoding? data
    Convertit data en Unicode Ю partir de l'encoding spИcifiИ. Les caractХres dans data sont traitИs comme des donnИes binaires oЫ les 8-bits infИrieurs de chaque caractХre sont traitИs comme un seul octet. La sИquence d'octets rИsultante est traitИe comme une chaНne dans l'encoding spИcifiИ. Si encoding n'est pas spИcifiИ, l'encodage systХme courant est utilisИ. +
    +

    encoding convertto ?encoding? string
    Convertit string d'Unicode en encoding spИcifiИ. Le rИsultat est une sИquence d'octets qui reprИsente la chaНne convertie. Chaque octet est stockИ dans les 8-bits infИrieurs d'un caractХre Unicode. Si encoding n'est pas spИcifiИ, l'encodage systХme courant est utilisИ. +
    +

    encoding names
    Renvoie une liste contenant les noms de tous les encodages qui sont actuellement disponibles. +
    +

    encoding system ?encoding?
    +
    Fixe l'encodage systХme Ю encoding. Si encoding est omis alors la commande retourne l'encodage systХme courant. L'encodage systХme est utilisИ chaque fois que Tcl transmet des chaНnes aux appels systХmes. +
    +
    +
    +
    EXEMPLE

    +
    Il est courant d'Иcrire des scripts en utilisant un editeur de texte qui produit une sortie dans l'encodage euc-jp, qui reprИsente les caractХres ASCII avec un octet et les caractХres Japonais avec deux octets. Ceci facilite l'incorporation de chaНnes litterales qui correspondent Ю des caractХres non-ASCII en tapant simplement la chaНne dans le script. NИanmoins, parce que la commande source lit toujours les fichiers en utilisant l'encodage ISO8859-1, Tcl traitera chaque octet dans le fichier comme un caractХre sИparИ qui pointe sur la page Unicode 00. Les chaНnes Tcl rИsultantes ne contiendront pas les caractХres Japonais attendus. A la place, elles contiendront une sИquence de caractХres Latin-1 qui correspondront aux octets de la chaНne originale. La commande encoding peut Йtre utilisИe pour convertir cette chaНne en caractХres Unicodes Japonais attendus. Par exemple,
    +
    set s [encoding convertfrom euc-jp "\xA4\xCF"]
    +
    retournera la chaНne Unicode "\u306F", qui est la lettre Hiragana HA.
    +
    +
    +
    VOIR EGALEMENT
    +
    Tcl_GetEncoding

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/eof.htm b/hlp/fr/tcl/eof.htm new file mode 100644 index 0000000..1af75c2 --- /dev/null +++ b/hlp/fr/tcl/eof.htm @@ -0,0 +1,19 @@ + + + + +

    eof      Commandes Internes Tcl

    +
    +
    NOM

    +
    eof - VИrifie la condition fin de fichier d'un canal +

    +
    SYNTAXE

    +
    eof channelId +

    +
    DESCRIPTION

    +
    Renvoie 1 si la condition fin de fichier s'est produite pendant l'opИration d'entrИe la plus rИcente de channelId (tel que gets), 0 autrement.

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/error.htm b/hlp/fr/tcl/error.htm new file mode 100644 index 0000000..8525faa --- /dev/null +++ b/hlp/fr/tcl/error.htm @@ -0,0 +1,23 @@ + + + + +

    error      Commandes Internes Tcl

    +
    +
    NOM
    +
    error - GenХre une erreur +

    +
    SYNTHESE

    +
    error message ?info? ?code? +

    +
    DESCRIPTION

    +
    Renvoie un code TCL_ERROR, qui provoque l'interruption de l'interprИtation de la commande. Message est une chaНne qui est renvoyИe Ю l'application pour indiquer ce qui s'est mal passИ.
    +
    Si l'argument info est fourni et est non-vide, il est utilisИ pour initialiser la variable globale errorInfo. errorInfo est utilisИe pour accumuler une trace de la pile de ce qui Иtait en cours quand l 'erreur s'est produite; quand des commandes imbriquИes se dИroulent, l'interprИteur Tcl ajoute l'information Ю errorInfo. Si l'argument info est prИsent, il est utilisИ pour initialiser errorInfo et le premier increment d'information ne sera pas ajoutИ par l'interprИteur Tcl. En d'autre mots, la commande contenant la commande error n'apparaitra pas dans errorInfo; Ю sa place il y aura info. Cette fonctionnalitИ est plus utile en conjonction avec la commande catch: si une erreur interceptИe ne peut Йtre gИrИe avec succХs, info peut Йtre utilisИe pour renvoyer une trace de la pile reflИtant le point original oЫ l'erreur s'est produite:
    +
    catch {...} errMsg
    +
    set savedInfo $errorInfo
    +
    ...
    +
    error $errMsg $savedInfo
    +
    Si l'argument code est prИsent, alors sa valeur est stockИe dans la variable globale errorCode. Cette variable est conГue pour recevoir une description machine-lisible de l'erreur dans le cas oЫ cette information est disponible; voyez la page de manuel de tclvars pour des informations sur le format correct de la variable. Si l'argument code n'est pas prИsent, alors errorCode est automatiquement rИinitialisИ Ю "NONE" par l'interprИteur Tcl comme partie du traitement de l'erreur gИnИrИe par la commande.
    +
    +
    + diff --git a/hlp/fr/tcl/eval.htm b/hlp/fr/tcl/eval.htm new file mode 100644 index 0000000..abd486c --- /dev/null +++ b/hlp/fr/tcl/eval.htm @@ -0,0 +1,18 @@ + + + + +

    eval      Commandes Internes Tcl

    +
    +
    NOM

    +
    eval - Evalue un script Tcl
    +

    +
    SYNTAXE

    +
    eval arg ?arg ...? +

    +
    DESCRIPTION

    +
    Eval attend un ou plusieurs arguments, qui ensemble constituent un script Tcl contenant une ou plusieurs commandes. Eval concatХne tout ses arguments de la mЙme faГon que la commande concat, puis transmet la chaНne concatИnИe Ю l'interprИteur Tcl rИcursivement, et retourne le rИsultat de cette Иvaluation (ou l'erreur gИnИrИe).
    +
    +
    + diff --git a/hlp/fr/tcl/exec.htm b/hlp/fr/tcl/exec.htm new file mode 100644 index 0000000..592bee8 --- /dev/null +++ b/hlp/fr/tcl/exec.htm @@ -0,0 +1,101 @@ + + + + +

    exec      Commandes Internes Tcl

    +
    +
    NOM

    +
    exec - Appelle un ou des sous-processus +

    +
    SYNTAXE

    +
    exec ?switches? arg ?arg ...? +

    +
    DESCRIPTION

    +
    Cette commande traite ses arguments comme la spИcification d'exИcution d'un ou plusieurs sous-processus. Les arguments prennent la forme d'un pipeline shell standard oЫ chaque arg devient un mot d'une commande, et chaque commande distincte devient un sous-processus.
    +
    Si les arguments initiaux Ю exec commencent avec un tiret alors ils sont traitИs comme des commutateurs de ligne de commande et ne font pas partie du pipeline. Les commutateurs suivants sont couramment supportИs: +
    +
    -keepnewline
    InsХre un saut de ligne dans la sortie de pipeline. Normalement le saut de ligne sera effacИ. +
    +
    --
    Marque la fin des commutateurs. L'argument suivant sera traitИ comme le premier arg mЙme s'il commence avec un tiret. +
    +
    +
    +
    Si un arg (ou paire d'args) a une des formes dИcrites ci-dessous alors il est utilisИ par exec pour contrТler les flux d'entrИe et de sortie dans le(s) sous-processus. Ces arguments ne seront pas transmis au(x) sous-processus. Sous les formes telles que "< fileName", fileName peut soit Йtre dans un argument sИparИ de "<" ou dans le mЙme argument sans espace (ex. "<fileName"). +
    +
    |
    SИpare des commandes distinctes dans le pipeline. La sortie standard de la commande prИcИdente sera injectИe dans l'entrИe standard de la commande suivante. +
    +

    |&
    SИpare des commandes distinctes dans le pipeline. L'ensemble sortie standard et erreur standard de la prИcИdante commande sera injectИe dans l'entrИe standard de la commande suivante. Cette forme de redirection surcharge les formes telles que 2> et >&. +
    +

    < fileName
    Le fichier designИ par fileName est ouvert et utilisИ comme l'entrИe standard pour le premiХre commande dans le pipeline. +
    +

    <@ fileId
    FileId doit Йtre l'identificateur pour un fichier ouvert, tel que la valeur de retour d'un prИcИdent appel de open. Il est utilisИ comme l'entrИe standard de la premiХre commande dans le pipeline. FileId doit avoir ИtИ ouvert en lecture. +
    +

    << value
    Value est transmise Ю la premiХre commande comme son entrИe standard. +
    +

    > fileName
    La sortie standard de la derniХre commande est redirigИe sur un fichier nommИ fileName, en Иcrasant son prИcedent contenu. +
    +

    2> fileName
    L'erreur standard de toute commande dans le pipeline est redirigИe sur un fichier nommИ fileName, en Иcrasant son prИcedent contenu. +
    +

    >& fileName
    L'ensemble sortie standard de la derniХre commande et erreur standard de toute commande sont redirigИe sur un fichier nommИ fileName, en Иcrasant son contenu prИcИdent . +
    +

    >> fileName
    La sortie standard de la derniХre commande est redirigИe et ajoutИe Ю la fin d'un fichier nommИ fileName. +
    +

    2>> fileName
    L'erreur standard de toute commande dans le pipeline est redirigИe et ajoutИe Ю la fin d'un fichier nommИ fileName. +
    +

    >>& fileName
    L'ensemble sortie standard de la derniХre commande et erreur standard de toute commande sont redirigИes et ajoutИes Ю la fin d'un fichier nommИ fileName. +
    +

    >@ fileId
    FileId doit Йtre l'identificateur d'un fichier ouvert, tel que la valeur de retour d'un prИcИdent appel de open. La sortie standard de la derniХre commande est redirigИe vers le fichier fileId's, qui doit avoir ИtИ ouvert en Иcriture. +
    +

    2>@ fileId
    FileId doit Йtre l'identificateur d'un fichier ouvert, tel que la valeur de retour d'un prИcИdent appel de open. L'erreur standard de toute commande dans le pipeline est redirigИe vers le fichier fileId. Le fichier doit avoir ИtИ ouvert en Иcriture. +
    +

    >&@ fileId
    FileId doit Йtre l'identificateur pour un fichier ouvert, tel que la valeur de retour d'un prИcИdent appel de open. L'ensemble sortie standard de la derniХre commande et erreur standard from toute commande sont redirigИe vers le fichier fileId. Le fichier doit avoir ИtИ ouvert en Иcriture. +
    +
    +
    +
    Si la sortie standard n'a pas ИtИ redirigИe alors la commande exec retourne la sortie standard de la derniХre commande dans le pipeline. Si une des commandes dans le pipeline finit anormalement ou est killed ou suspendue, alors exec renverra une erreur et le message d'erreur inclura la sortie du pipeline suivi par le message d'erreur dИcrivant la terminaison anormale; la variable errorCode contiendra des informations supplИmentaires concernant la derniХre terminaison anormale rencontrИe. Si une des commandes ecrit vers son fichier standard d'erreur et que cette erreur standard n'est pas redirigИe, alors exec renverra une erreur; le message d'erreur inclura la sortie standard du pipeline, suivi par les messages au sujet de la terminaison anormale (si elle existe), suivi par la sortie d'erreur standard .
    +
    Si le dernier caractХre du rИsultat ou du message d'erreur est un saut de ligne alors ce caractХre est normalement effacИ du rИsultat ou du message d'erreur. Ceci est cohИrent par rapport aux autres valeurs de retour Tcl, qui ne finisssent normalement pas avec des sauts de ligne. NИanmoins, si -keepnewline est spИcifiИ alors le saut de ligne est ajoutИ.
    +
    Si l'entrИe standard n'est pas redirigИe avec "<" ou "<<" ou "<@" alors l'entrИe standard pour la premiХre commande dans le pipeline est prise de l'entrИe standard de l'application courante.
    +
    Si le dernier arg est "&" alors le pipeline sera exИcutИ en arriХre-plan. Dans ce cas la commande exec renverra une liste dont les ИlИments sont les identificateurs de processus pour tous les sous-processus dans le pipeline. La sortie standard de la derniХre commande dans le pipeline ira dans la sortie standard de l'application si elle n'a pas ИtИ redirigИe, et la sortie d'erreur de toutes les commandes dans le pipeline ira vers le fichier standard d'erreur de l'application sauf si elle est redirigИe.
    +
    Le premier mot de chaque commande est interprИtИ comme le nom de la commande; la substitution tilde est effectuИe, et si le rИsultat ne contient pas de slashes alors les rИpertoires dans la variable d'environnement PATH sont recherchИs pour un exИcutable donnИs. Si le nom contient un slash alors il doit se rИfИrer Ю un exИcutable accessible du rИpertoire courant. Aucune expansion "glob" ou autre substitutions shell-like ne sont effectuИes sur les arguments des commandes.
    +

    +
    NOTES DE PORTABILITE

    +
    +
    +
    Windows (toutes versions)
    Lire ou Иcrire une socket, en +utilisant la notation "@ fileId", ne fonctionne pas. En essayant de lire une socket, une application DOS 16-bit se plantera et une application 32-bit retournera immИdiatement avec fin-de-fichier. Quand ces deux types d'application ecrivent une socket, l'information est en fait envoyИe Ю la console, si une est prИsente, ou est ИliminИe.
    +La console texte Tk ne fournit pas de possibilitИs IO standard. Sous Tk, quand on redirige depuis l'entrИe standard, toutes les applications verront une fin-de-fichier immИdiate; l'information redirigИe vers la sortie standard ou l'erreur standard sera ИliminИe.
    +Les slashes ou anti slashes sont acceptИs comme sИparateurs de chemin pour les arguments des commandes Tcl. A l'exИcution d'une application, le nom de chemin spИcifiИ pour l'application peut aussi contenir des slashes ou des anti slashes comme sИparateurs de chemin. Ayez Ю l'esprit, nИanmoins, que la plupart des applications Windows acceptent des arguments avec seulement des slashes comme dИlimiteurs d'option et seulement des backslashes dans les chemins. N'importe quels arguments Ю une application qui spИcifie un nom de chemin avec des slashes ne seront pas automatiquement convertis en caractХres backslash. Si un argument contient des slashes comme sИparateur de chemin, il peut ou ne peut pas Йtre reconnu comme un nom de chemin, dИpendant du programme.
    +De plus, Ю l'appel d'une application 16-bit DOS ou Windows 3.X, tout les noms de chemin doivent utiliser le format de chemin court(ex, en utilisant "applba~1.def" au lieu de of "applbakery.default").
    +Deux slashes ou backslashes ou plus dans un chemin se refХrent Ю un chemin rИseau. Par exemple, une simple concatenation du rИpertoire racine c:/ avec un sous rИpertoire /windows/system donnera c://windows/system (deux slashes ensemble), qui se rИfХre Ю un point de montage appelИ system sur la machine appelИ windows (et le c:/ est ignorИ), et n'est pas Иquivalent Ю c:/windows/system, qui dИcrit un rИpertoire sur l'ordinateur courant . La commande file join sera utilisИe pour concatИner les composants de chemin.
    +

    Windows NT
    Quand il tente d'exИcuter une application, exec recherche en premier le nom comme il a ИtИ spИcifiИ. Ensuite, dans l'ordre, .com, .exe, et .bat sont ajoutИs Ю la fin du nom spИcifiИ et il recherche le nom plus l'extension. Si un nom de rИpertoire n'a pas ИtИ spИcifiИ comme partie du nom de l'application, les rИpertoires suivants sont automatiquement recherchИs dans l'ordre pour tenter de localiser l'application:
    +
    Le rИpertoire duquel l'exИcutable Tcl a ИtИ chargИ.
    +Le rИpertoire courant.
    +Le rИpertoire systХme Windows NT 32-bit.
    +Le rИpertoire systХme Windows NT 16-bit.
    +Le rИpertoire home Windows NT.
    +Les rИpertoires listИs dans le chemin.

    +De maniХre Ю exИcuter les commandes shell internes comme dir et copy, l'appelant doit ajouter en tЙte de la commande "cmd.exe /c ". +
    +

    Windows 95
    Quand il tente d'exИcuter une application, exec recherche en premier le nom comme il a ИtИ spИcifiИ. Ensuite, dans l'ordre, .com, .exe, et .bat sont ajoutИ Ю la fin du nom spИcifiИ et il recherche le nom plus l'extension. Si un nom de rИpertoire n'a pas ИtИ spИcifiИ comme partie du nom de l'application, les rИpertoires suivants sont automatiquement recherchИs dans l'ordre pour tenter de localiser l'application:
    +
    Le rИpertoire duquel l'exИcutable Tcl a ИtИ chargИ.
    +Le rИpertoire courant.
    +Le rИpertoire systХme Windows 95.
    +Le rИpertoire home Windows 95.
    +Les rИpertoires listИs dans le chemin.

    +De maniХre Ю exИcuter les commandes shell internes comme dir et copy, l'appelant doit ajouter en tЙte de la commande "command.com /c "
    +Une fois qu'une application DOS 16-bit a lu l'entrИe standard d'une console et quittИ, toutes les applications DOS 16-bit exИcutИes ensuite verront l'entrИe standard comme dИjЮ fermИe. Les applications 32-bit n'ont pas ce problХme et s'exИcuteront correctement, mЙme aprХs une application DOS 16-bit qui pense que l'entrИe standard est fermИe. Il n'y a pas de correction connue de ce bug Ю ce jour . La redirection entre le pИriphИrique NUL: et une application 16-bit ne fonctionne pas toujours. Quand on redirige de NUL:, certaines applications se planteront, d'autres emmetront un flux infini d'octets "0x01", et d'autres obtiendront correctement une fin-de-fichier immИdiate; ce comportement semble dИpendre de quelque chose compilИ dans l'application elle-mЙme. Quand la redirection vers NUL: est supИrieure Ю 4K , quelques applications se planteront. Les problХmes prИcИdents ne se produisent pas avec les applications 32-bit.
    +Toutes les applications DOS 16-bit sont exИcutИes de maniХre synchrone. Toute entrИe standard d'un pipe vers une application DOS 16-bit est collectИ dans un fichier temporaire; l'autre extrИmitИ du pipe doit Йtre fermИe avant que l'application DOS 16-bit commence l'exИcution. Toute sortie ou erreur standard d'une application DOS 16-bit vers un pipe est collectИe dans des fichiers temporaires; l'application doit se terminer avant que les fichiers temporaires soient redirigИs Ю l'Иtape suivante du pipeline. Ceci est du Ю une correction d'un bug de Windows 95 dans l'implИmentation des pipes, et est la maniХre standard du shell DOS sous Windows 95 de gИrer les pipes.
    +Certaines applications, tel que command.com, ne seront pas exИcutИes interactivement. Les applications qui accХdent directement Ю la fenЙtre Dos, au lieu de lire depuis leur entrИe standard et d'Иcrire sur leur sortie standard peut Иchouer, planter Tcl, ou mЙme planter le systХme si leur propre console ne leur est pas disponible. +
    +

    Macintosh
    La commande exec n'est pas implИmentИe et n'existe pas sous Macintosh.
    +

    Unix
    La commande exec est pleinement fonctionnelle et fonctionne comme dИcrit. +
    +
    +

    +
    VOIR EGALEMENT

    +
    open(n)
    +
    DerniХre rИvision: 7.6
    +
    +
    + diff --git a/hlp/fr/tcl/exit.htm b/hlp/fr/tcl/exit.htm new file mode 100644 index 0000000..ec18cdf --- /dev/null +++ b/hlp/fr/tcl/exit.htm @@ -0,0 +1,18 @@ + + + + +

    exit      Commandes Internes Tcl

    +
    +
    NOM

    +
    exit - Termine l'application
    +

    +
    SYNTAXE

    +
    exit ?returnCode? +

    +
    DESCRIPTION

    +
    Termine le processus, retournant returnCode au systХme comme statut de fin. Si returnCode n'est pas spИcifiИ alors sa valeur par dИfaut est de 0.
    +
    +
    + diff --git a/hlp/fr/tcl/expr.htm b/hlp/fr/tcl/expr.htm new file mode 100644 index 0000000..272d94f --- /dev/null +++ b/hlp/fr/tcl/expr.htm @@ -0,0 +1,256 @@ + + + + +

    expr      Commandes Internes Tcl

    +
    + +
    NOM

    +
    expr - Evalue une expression +

    +
    SYNTAXE

    +
    expr arg ?arg arg ...? +

    +
    DESCRIPTION

    +
    ConcatХne arg's (en y ajoutant des sИparateurs espaces), Иvalue le rИsultat comme expression Tcl, et retourne la valeur. Les opИrateurs autorisИs dans les expressions Tcl sont un sous ensemble des opИrateurs autorisИs dans les expressions C, et ils ont les mЙme sens et prИcИdence que les opИrateurs C correspondants. Les expressions donnent presque toujours des rИsultats numИriques (entier ou valeurs flottantes). Par exemple, l'expression
    +
    expr 8.2 + 6
    +
    est ИvaluИe Ю 14.2. Les expressions Tcl diffХrent des expressions C dans le sens ou les opИrandes sont spИcifiИs. De plus, les expressions Tcl supportent les opИrandes non-numИriques et les comparaisons de chaНnes. +

    +
    OPERANDES

    +
    Une expression Tcl consiste en une combinaison d'opИrandes, d'opИrateurs, et de parenthХses. L'espace peut Йtre employИ entre les opИrandes, opИrateurs et parenthХses; il est ignorИ par les instructions d'expression. Si possible, les opИrandes sont interprИtИs comme des valeurs entiХres. Les valeurs entiХres peuvent Йtre spИcifiИes en dИcimal (le cas normal), en octal (si le premier caractХre de l'opИrande est 0), ou en hexadИcimal (si les deux premiers caractХres de l'opИrande sont 0x). Si un opИrande n'est pas un des formats entiers donnИs plus haut, alors il est traitИ comme un nombre flottant si c'est possible. Les nombres flottants peuvent Йtre spИcifiИs de toutes les maniХres acceptИes par un compilateur compatible ANSI-C (exceptИ que les suffixes f, F, l, et L ne seront pas autorisИs dans la plupart des installations). Par exemple, tous les nombres flottants suivants sont valides : 2.1, 3., 6e4, 7.91e+16. Si aucune interprИtation numИrique n'est possible, alors un opИrande est considИrИ comme une chaНne (et seulement un ensemble limitИ d'opИrateurs peut lui Йtre appliquИ).
    +
    Les opИrandes peuvent Йtre spИcifiИs d'une des faГons suivantes:
    +
    [1]    Comme une valeur numИrique, soit entiХre soit flottante.
    +
    [2]    Comme une variable Tcl, en utilisant la notation standard $. La valeur de la variable sera utilisИe comme opИrande.
    +
    [3]    Comme une chaНne entourИe de doubles-guillemets. L'analyseur d'expression effectuera les substitution de backslash, de variable, et de commandes sur l'information entre guillemets, et utilisera la valeur rИsultante comme opИrande
    +
    [4]    Comme une chaНne entourИe d'accolades. Les caractХres entre l'accolade ouverte et l'accolade fermante correspondante seront utilisИs comme opИrande sans aucunes substitutions.
    +
    [5]    Comme une commande Tcl entourИe de crochets. La commande sera exИcutИe et son rИsultat sera utilisИ comme opИrande.
    +
    [6]    Comme une fonction mathИmatique dont les arguments ont une des formes definies plus haut pour les opИrandes , tel que sin($x). Voir ci-dessous pour une liste de fonctions dИfinies.
    +
    Ou les substitutions se produisent plus haut (ex. dans les chaНnes entre guillemets), elles sont effectuИes par les instructions des expressions. NИanmoins, une couche de substitution supplИmentaire peut dИjЮ avoir ИtИ effectuИe par l'analyseur de commande avant que le processeur d'expression ait ИtИ appelИ. Comme expliquИ ci-dessous, il est prИfИrable d'entourer les expressions dans des accolades pour empЙcher l'analyseur de commande d'effectuer des substitutions sur le contenu.
    +
    Pour quelques exemples d'expressions simples, supposez que la variable a a pour valeur 3 et la variable b a pour valeur 6.
    +
    expr 3.1 + $a6.1
    +
    expr 2 + "$a.$b"5.6
    +
    expr 4*[llength "6 2"]8
    +
    expr {{word one} < "word $a"}0
    +

    +
    OPERATEURS

    +
    Les opИrateurs valides sont listИs ci-dessous, groupИs en ordre de prИcИdence dИcroissant: +
    +
    - + ~ !
    Moins unaire, plus unaire, NOT bit Ю bit, NOT logique. Aucun de ces opИrateurs ne peut Йtre appliquИ aux opИrandes chaНne, et NOT bit Ю bit peut seulement Йtre appliquИ aux entiers. +
    +
    * / %
    Multiplication, division, modulo. Aucun de ces opИrandes ne peut Йtre appliquИ aux opИrandes chaНne, et modulo peut Йtre appliquИ seulement aux entiers. modulo Modulo aura toujours le mЙme signe que le diviseur et une valeur absolue infИrieure au diviseur. +
    +
    + -
    Addition et soustraction. Valides pour tout opИrande numИrique. +
    +
    << >>
    DИcalage Ю gauche et Ю droite. Valides seulement pour les opИrandes entiers. Un dИcalage Ю droite propage toujours le bit de signe. +
    +
    < > <= >=
    BoolИens infИrieur Ю, supИrieur Ю, infИrieur Ю ou Иgal, et supИrieur Ю ou Иgal. Chaque opИrateur donne 1 si la condition est vraie, 0 autrement. Ces opИrateurs peuvent Йtre appliquИs aux chaНnes aussi bien qu'aux opИrandes numИriques, dans le cas des chaНnes, une comparaison est utilisИe. +
    +
    == !=
    BoolИen Иgal et diffИrent. Chaque opИrateur produit un zИro/un rИsultat. Valides pour tout types d'opИrande. +
    +
    &
    ET Bit Ю bit. Valide pour des opИrandes entiers seulement. +
    +
    ^
    OU exclusif Bit Ю bit. Valide pour des opИrandes entiers seulement. +
    +
    |
    OU Bit Ю bit. Valide pour des opИrandes entiers seulement.
    +
    &&
    ET logique. Donne 1 si les deux opИrandes sont diffИrent de zИro, 0 autrement. Valide seulement pour pour les opИrandes boolИens et numИriques (entiers ou flottants). +
    +
    ||
    OU logique. Donne 0 si les deux opИrandes sont zИro, 1 autrement. Valide seulement pour opИrandes boolИens et numИriques (entiers ou flottants). +
    +
    x?y:z
    If-then-else, comme en C. Si x est ИvaluИ diffИrent de zИro, alors le rИsultat est la valeur de y. Autrement le rИsultat est la valeur de z. L'opИrande x doit avoir une valeur numИrique. +
    +
    +
    +
    Voir le manuel C pour plus de dИtails sur les rИsultats produits par chaque opИrateur. Tous les opИrateurs binaire sont groupИs de gauche Ю droite Ю l'intИrieur d'un mЙme niveau de prИcИdence. Par exemple, la commande
    +
    expr 4*2 < 7
    +
    retourne 0.
    +
    Les opИrateurs &&, ||, et ?: ont une "Иvaluation paresseuse", juste comme en C, ce qui signifie que ces opИrandes ne ont pas ИvaluИs s'ils ne sont pas nИcessaires pour dИterminer le rИsultat. Par exemple, dans la commande
    +
    expr {$v ? [a] : [b]}
    +
    seulement un des [a] ou [b] sera ИvaluИ, dИpendant de la valeur de $v. Notez, nИanmoins, que ceci est seulement vrai si l'expression entiХre est entourИe d'accolades; autrement l'analyseur Tcl evaluera [a] et [b] avant d'appeler la commande expr. +

    +
    FONCTIONS MATHEMATIQUES

    +
    Tcl supporte les fonctions mathИmatiques suivantes dans les expressions:
    + +
    (.*?)(.*?)
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + abs + + cosh + + log + + sqrt +
    + acos + + double + + log10 + + srand +
    + asin + + exp + + pow + + tan +
    + atan + + floor + + rand + + tanh +
    + atan2 + + fmod + + round + + +
    + ceil + + hypot + + sin + + +
    + cos + + int + + sinh + + +

    +

    +
    abs(arg)
    Renvoie la valeur absolue de arg. Arg peut Йtre entier ou flottant, et le rИsultat renvoyИ est de la mЙme forme. +
    +
    acos(arg)
    Renvoie l'arc cosinus de arg, dans l'intervalle [0,pi] radians. Arg sera dans l'intervalle [-1,1]. +
    +
    asin(arg)
    Renvoie l'arc sinus de arg, dans l'intervalle [-pi/2,pi/2] radians. Arg sera dans l'intervalle [-1,1]. +
    +
    atan(arg)
    Renvoie l'arc tangente de arg, dans l'intervalle [-pi/2,pi/2] radians. +
    +
    atan2(x, y)
    Renvoie l'arc tangente de y/x, dans l'intervalle [-pi,pi] radians. x et y ne peuvent Йtretous les deux 0. +
    +
    ceil(arg)
    Renvoie la plus petite valeur entiХre non infИrieure Ю arg. +
    +
    cos(arg)
    Renvoie le cosinus de arg, mesurИ en radians. +
    +
    cosh(arg)
    Renvoie le cosinus hyperbolique de arg. Si le rИsultat cause un dИbordement, une erreur est renvoyИe. +
    +
    double(arg)
    Si arg est une valeur flottante , retourne arg, autrement convertit arg en flottant et retourne la valeur convertie. +
    +
    exp(arg)
    Renvoie l'exponentiel de arg, dИfini comme e**arg. Si le rИsultat cause un dИbordement, une erreur est renvoyИe. +
    +
    floor(arg)
    Renvoie la plus grande valeur entiХre non supИrieure Ю arg.
    +
    fmod(x, y)
    Renvoie le reste flottant de la division of x par y. Si y est 0, une erreur est renvoyИe. +
    +
    hypot(x, y)
    Calcule la longueur de l'hypotИnuse d'un triangle rectangle(x*x+y*y). +
    +
    int(arg)
    Si arg est une valeur entiХre, retourne arg, autrement convertit arg en entier par truncature et retourne la valeur convertie. +
    +
    log(arg)
    Renvoie le logarithme naturel de arg. Arg doit Йtre une valeur positive. +
    +
    log10(arg)
    Renvoie le logarithme base 10 de arg. Arg doit Йtre une valeur positive. +
    +
    pow(x, y)
    Calcule la valeur de x elevИ Ю la puissance y. Si x est nИgatif, y doit Йtre une valeur entiХre. +
    +
    rand()
    Renvoie un nombre flottant compris entre zИro et juste infИrieur Ю un ou, en termes mathИmatiques, l'intervalle [0,1]. La graine vient de l'horloge interne de la machine ou peut Йtre fixИe manuelllement avec la fonction srand. +
    +
    round(arg)
    Si arg est une valeur entiХre, retourne arg, autrement convertit arg en entier arrondi et retourne la valeur convertie. +
    +
    sin(arg)
    Renvoie le sinus de arg, mesurИ en radians. +
    +
    sinh(arg)
    Renvoie le sinus hyperbolique de arg. Si rИsultat cause un dИbordement, une erreur est renvoyИe. +
    +
    sqrt(arg)
    Renvoie la racine carrИe de arg. Arg doit Йtre non-nИgatif. +
    +
    srand(arg)
    Le arg, qui doit Йtre un entier, est utilisИ pour rИinitialiser la graine du generateur de nombre alИatoire. Renvoie le premier nombre alИatoire de cette graine. Chaque interprИteur a sa propre graine. +
    +
    tan(arg)
    Renvoie la tangente de arg, mesurИe en radians. +
    +
    tanh(arg)
    Renvoie la tangente hyperbolique de arg.
    +
    + +
    En plus de ces fonctions prИdИfinies, les applications peuvent definir des fonctions additionelles en utilisant Tcl_CreateMathFunc(). +

    +
    TYPES, DEBORDEMENT, ET PRECISION

    +
    Tous les calculs internes impliquant des entiers sont fait avec le type C long, et tous calculs internes impliquant des flottants sont fait avec le type C double. Pendant la conversion d'une chaНne en valeur flottante, le dИbordement d'exposant est dИtectИ et donne une erreur Tcl. Pour la conversion d'une chaНne en entier, la detection du dИbordement depend du comportement de quelques routines dans la bibliothХque C locale, donc il doit Йtre considИrИ comme non fiable. Dans tous les cas, le dИbordement entier n'est gИnИralement pas dИtectИ avec fiabilitИ dans les rИsultats intermИdiaires. Le dИbordement flottant est dИtectИ par le matИriel, qui est gИnИralement fiable.
    +
    La conversion dans les representations internes des opИrandes entiers, flottants, et chaНnes est faite automatiquement si besoin. Pour les calculs arithmИtiques, les entiers sont utilisИs jusqu'a ce qu'un nombre flottant soit introduit, aprХs lequel les flottants sont utilisИs. Par exemple,
    +
    expr 5 / 4
    +
    renvoie 1, alors que
    +
    expr 5 / 4.0
    +expr 5 / ( [string length "abcd"] + 0.0 )
    +
    renvoient 1.25. Les valeurs flottantes sont toujours renvoyИes avec un "." ou un e ainsi elles ne ressemblent pas aux valeur entiХres. Par exemple,
    +
    expr 20.0/5.0
    +
    retourne 4.0, pas 4. +

    +
    OPERATIONS SUR DES CHAINES

    +
    Les valeurs chaНne peuvent Йtre employИes comme opИrandes des opИrateurs de comparaison, bien que l'evaluateur d'expression essaye de comparer si possible des entiers ou des flottants. Si un des opИrandes d'une comparaison est une chaНne et que l'autre a une valeur numИrique, l'opИrande numИrique est converti en une chaНne en utilisant le spИcificateur de format C sprintf %d pour les entiers et %g pour les valeurs flottantes. Par exemple, les commandes
    +
    expr {"0x03" > "2"}
    +expr {"0y" < "0x12"}
    +
    renvoient toutes les deux 1. La premiХre comparaison est faite en utilisant la comparaison entiХre, et la seconde est faite en utilisant la comparaison de chaНnes aprХs que le second opИrande ait ИtИ converti en la chaНne 18. parce que Tcl a tendance a traiter les valeurs comme des nombres chaque fois que possible, ce n'est gИnИralement pas une bonne idИe d'utiliser des operateurs comme == quand vous desirez une comparaison de chaНnes et les valeurs des opИrandes pourraient Йtre arbitraires; il est prИfИrable dans ces cas d'utiliser la commande string . +

    +
    CONSIDERATIONS DE PERFORMANCE

    +
    Entourez les expressions d'accolades pour la rapiditИ et le stockage le moins encombrant. Ceci permet au compilateur bytecode Tcl de gИnИrer le meilleur code.
    +
    Comme mentionnИ plus haut, les expressions sont substituИes deux fois: une fois par l'analyseur Tcl et une fois par la commande expr. Par exemple, les commandes
    +
    set a 3
    +set b {$a + 2}
    +expr $b*4
    +
    retourne 11, pas un multiple de 4. Ceci parce que l'analyseur Tcl substituera en premier $a + 2 pour la variable b, ensuite la commande expr evaluera l'expression $a + 2*4.
    +
    La plupart des expressions n'exigent pas une seconde passe de substitutions. Soit elles sont entourИes d'accolades ou, sinon, leurs substitutions de variable et de commandes donnent des nombres ou des chaНnes qui eux-mЙme n'exigent pas de substitutions. NИanmoins, parce que quelques expressions non entourИes d'accolades nИcИssitent deux passes de substitutions, le compilateur bytecode doit emettre des instructions supplИmentaires pour gИrer cette situation. Le code le plus couteux est requis pour les expressions non entourИes d'accolades qui contiennent des substitutions de commandes. Ces expressions doivent Йtre implИmentИes par la gИnИration de nouveau code chaque fois que l'expression est exИcutИe.

    +
    DerniХre rИvision: 8.3
    +
    +
    + + diff --git a/hlp/fr/tcl/fblocked.htm b/hlp/fr/tcl/fblocked.htm new file mode 100644 index 0000000..cc844e1 --- /dev/null +++ b/hlp/fr/tcl/fblocked.htm @@ -0,0 +1,22 @@ + + + + +

    fblocked      Commandes Internes Tcl

    +
    +
    NOM

    +
    fblocked - Teste si la derniХre opИration d'entrИe a pu traiter toutes les entrИes disponibles +

    +
    SYNTAXE

    +
    fblocked channelId  +

    +
    DESCRIPTION

    +
    La commande fblocked retourne 1 si la plus rИcente opИration d'entrИe pour channelId a renvoyИ moins d'information que requis parce que toutes les entrИes disponibles ont ИtИ ИpuisИes. Par exemple, si gets est appelИe quand il y a seulement trois caractХres disponibles pour l'entrИe et pas de sИquence de fin-de-ligne, gets retourne une chaНne vide et un appel suivant de fblocked renverra 1. +

    +
    VOIR EGALEMENT

    +
    gets(n), read(n)

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/fconfigure.htm b/hlp/fr/tcl/fconfigure.htm new file mode 100644 index 0000000..0a1e9eb --- /dev/null +++ b/hlp/fr/tcl/fconfigure.htm @@ -0,0 +1,56 @@ + + + + +

    fconfigure     Commandes Internes Tcl

    +
    +
    NOM

    +
    fconfigure - Fixe et lit les options d'un canal +

    +
    SYNTAXE

    +
    fconfigure channelId
    +fconfigure channelId name
    +fconfigure channelId name value ?name value ...?
    +
    +
    +
    DESCRIPTION

    +
    La commande fconfigure fixe et lit les options des canaux. ChannelId identifie le canal pour lequel fixer ou consulter une option. Si aucun arguments name ou value ne sont fournis, la commande retourne une liste contenant des options alternИes de noms et de valeurs pour le canal. Si name est fourni mais pas value alors la commande retourne la valeur courante de l 'option donnИe. Si une ou plusieurs paires de name et value sont fournies, la commande fixe chacune des options dИsignИes Ю la value correspondante; dans ce cas la valeur de retour est une chaНne vide.
    +
    Le options dИcrites ci-dessous sont supportИes par tous les canaux. De plus, chaque type de canal peut ajouter les options qu'il est seul Ю supporter. Voir la page de manuel pour la commande qui crИe chaque type de canaux pour les options que ce type de canal spИcifique supporte. Par exemple, voyez la page de manuel de la commande socket pour ses options supplИmentaires. +
    +
    -blocking boolean
    L'option -blocking dИtermine si les opИrations I/O sur le canal peuvent provoquer le bloquage du processus. La valeur de l'option doit Й tre une valeur boolИenne correcte. Les canaux sont normalement en mode bloquant; si un canal est placИ en mode non bloquant ceci affectera l'opИration des commandes gets, read, puts, flush, et close; voyez la documentation de ces commandes pour les dИtails. Pour que le mode non bloquant fonctionne correctement, l'application doit utiliser la boucle d'ИvХnement Tcl (ex. en appelant Tcl_DoOneEvent ou la commande vwait). +
    +
    -buffering newValue
    Si newValue est full alors le systХme I /O mettra la sortie en tampon jusqu'a ce que son tampon interne soit plein ou jusqu'a ce que la commande flush soit appelИe. Si newValue est line, alors le systХme I/O flushera automatiquement la sortie pour le canal chaque fois que un caractХre newline est Иmis. Si newValue est none, le systХme I/O flushera automatiquement aprХs tout opИration de sortie. La valeur par dИfaut de -buffering est fixИe Ю full exceptИ pour les canaux qui se connectent Ю des pИriphИriques terminal-like; pour ces canaux la valeur initiale est line. De plus, stdin et stdout sont initialement fixИs Ю line, et stderr est fixИ Ю none. +
    +
    -buffersize newSize
    Newvalue doit Йtre un entier; sa valeur est utilisИe pour fixer la taille, en octets, du tampon allouИ pour ce canal pour stocker l'entrИe ou la sortie. Newvalue doit Йtre entre dix et un million, permettant des tampons d'une taille de dix Ю un million octets. +
    +
    -encoding name
    Cette option est utilisИe pour specifier l'encodage du canal, ainsi les donnИes peuvent Йtre converties de et Ю partir d'Unicode pour Йtre utilisИes en Tcl. Par exemple, pour permettre Ю Tcl de lire des caractХres d'un fichier Japonais en shiftjis et d'en traiter et d'afficher correctement le contenu, l'encodage devra Йtre fixИ Ю shiftjis. Ainsi, en lisant Ю partir du canal, les octets du fichier Japonais seront convertis en Unicode au fur et Ю mesure de leur lecture. L'Иcriture est aussi supportИe √ quand les chaНnes Tcl seront Иcrites dans le canal elles seront automatiquement converties en l'encodage spИcifiИ pour la sortie. +Si un fichier contient des donnИes binaires pures (par exemple, une image JPEG), l'encodage du canal sera configurИ en binary. Tcl alors n'assignera aucune interprИtation aux donnИes dans le fichier et simplement lira ou ecrira des octets. La commande Tcl binary peut Йtre utilisИe pour manipuler ces donnИes orientИes-octet. +L'encodage par dИfaut pour les canaux nouvellement ouverts est le mЙme que le systХme d'encodage utilisИ pour l 'interface avec le systХme d'exploitation. +
    +
    -eofchar char
    +
    -eofchar {inChar outChar}
    Cette option supporte le systХme de fichiers DOS qui utilise Control-z (\x1a) comme marqueur de fin de fichier. Si char n'est pas une chaНne vide, alors ce caractХre signale fin-de-fichier quand il est rencontrИ pendant l'entrИe. Pour la sortie, le caractХre fin-de-fichier est Иmis quand le canal est fermИ. Si char est la chaНne vide, alors il n'y a pas de caractХre spИcial marqueur de fin de fichier. Pour les canaux en lecture-Иcriture, une liste Ю deux-ИlИment spИcifie le marqueur de fin de fichier pour l'entrИe et la sortie, respectivement. Comme convИnience, quand vous fixez le caractХre de fin-de-fichier pour un canal en lecture-Иcriture vous pouvez specifier une simple valeur qui s'appliquera Ю la fois Ю la lecture et Ю l'Иcriture. Quand vous interrogez le caractХre de fin-de-fichier d'un canal en lecture-Иcriture, une liste Ю deux-ИlИments sera toujours renvoyИe. La valeur par dИfaut de -eofchar est la chaНne vide dans tout les cas exceptИ pour les fichiers sous Windows. Dans ce cas, -eofchar est Control-z (\x1a) pour la lecture et la chaНne vide pour l'Иcriture. +
    +
    -translation mode
    +
    -translation {inMode outMode}
    Dans les scripts Tcl la fin d'une ligne est toujours representИe en utilisant un simple caractХre newline (\n). NИanmoins, dans les fichiers et pИriphИriques la fin d'une ligne peut Йtre representИe diffИremment sur diffИrentes plateformes, ou mЙme pour diffИrents pИriphИriques sur la mЙme plateforme. Par exemple, sous UNIX les saut de lignes sont utilisИs dans les fichiers, alors que les sИquences retour-chariot/linefeed sont normalement utilisИes dans les connections rИseau. En entrИe (ex., avec gets et read) le systХme I/O Tcl traduit automatiquement traduit la reprИsentation fin-de-ligne externe en caractХres newline. En sortie (ex., avec puts), le systХme I/O traduit le saut de lignes en reprИsentation externe fin-de-ligne. Le mode de traduction par dИfaut, auto, gХre tout les cas communs automatiquement, mais l'option -translation fournit un contrТle explicite des traductions de fin de ligne. +La valeur associИe Ю -translation est un simple item pour les canaux lecture-seule et Иcriture-seule. La valeur est une liste Ю deux-ИlИment pour les canaux en lecture-Иcriture; le mode de traduction de lecture est le premier ИlИment de la liste, et le mode de traduction d'Иcriture est le second ИlИment. Comme convenience, quand vous fixez le mode de traduction pour un canal en lecture-Иcriture vous pouvez specifier une seule valeur qui s'appliquera autant Ю la lecture qu'Ю l'Иcriture. Quand vous demandez le mode de traduction d'un canal lecture-Иcriture, une liste Ю deux-ИlИments sera toujours renvoyИe. Les valeurs suivantes sont couramment supportИes: +
    +
    auto
    Comme mode traduction d'entrИe, auto traite newline (lf), retour chariot (cr), ou retour chariot suivi par une newline (crlf) comme la reprИsentation de fin de ligne. La reprИsentation de fin de ligne peut mЙme changer d'une ligne Ю l'autre, et tout les cas sont traduits en newline. Comme mode de traduction de sortie, auto choisit une reprИsentation spИcifique Ю la plateforme; pour les sockets sur toutes les plateformes Tcl choisit crlf, pour tous les Unix, il choisit lf, pour la plateforme Macintosh il choisit cr et pour les diffИrentes versions de Windows il choisit crlf. La valeur par dИfaut de -translation est auto pour l'entrИe et la sortie. +
    +
    binary
    Aucunes traductions fin de ligne ne sont effectuИes. Ceci est presque identique au mode lf, exceptИ qu'en plus le mode binary fixe aussi le caractХre fin-de-fichier Ю la chaНne vide (qui le dИsactive) et fixe l'encodage Ю binary (qui dИsactive le fitrage par l'encodage). Voir la description de -eofchar et -encoding pour plus d'information. +
    +
    cr
    La fin d'une ligne dans le fichier ou pИriphИrique sous-jacent est representИe par un simple caractХre retour chariot. Comme mode de traduction d'entrИe, le mode cr convertit les retours chariot en caractХres newline. Comme le mode de traduction de sortie, le mode cr traduit les caractХres newline en retour chariot. Ce mode est typiquement utilisИ sur les plateformes Macintosh. +
    +
    crlf
    La fin d'une ligne dans le fichier ou pИriphИrique sous-jacent est representИe par un caractХre retour chariot suivi par un caractХre linefeed. Comme mode de traduction d'entrИe,le mode crlf convertit le sИquences retour chariot /linefeed en caractХres newline. Comme mode de traduction de sortie, le mode crlf traduit caractХres newline en sИquences retour chariot /linefeed. Ce mode est principalement utilisИ sur les plateformes Windows et pour les connections rИseau. +
    +
    lf
    la fin d'une ligne dans le fichier ou pИriphИrique sous-jacent est reprИsentИe par un seul caractХre newline; Dans ce mode, aucune traduction ne se fait pendant soit l'entrИe soit la sortie. Ce mode est utilisИ principalement sur les plateformes UNIX.
    +
    +
    +
    +
    +
    VOIR EGALEMENT

    +
    close(n), flush(n), gets(n), puts(n), read(n), socket(n)

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/fcopy.htm b/hlp/fr/tcl/fcopy.htm new file mode 100644 index 0000000..24cff21 --- /dev/null +++ b/hlp/fr/tcl/fcopy.htm @@ -0,0 +1,65 @@ + + + + +

    fcopy      Commandes Internes Tcl

    +
    +
    NOM

    +
    fcopy - Copie des donnИes d'un canal Ю un autre. +

    +
    SYNTAXE

    +
    fcopy inchan outchan ?-size size? ?-command callback? +

    +
    DESCRIPTION

    +
    La commande fcopy copie donnИes d'un canal I/O, inchan Ю un autre canal I/O, outchan. La commande fcopy force la mise en tampon dans le systХme I/O Tcl pour Иviter une copie supplИmentaire et pour Иviter la mise en tampon de trop de donnИes en mИmoire pendant la copie de gros fichiers vers des destinations lentes comme les sockets rИseau.
    +
    La commande fcopy transfХre les donnИes de inchan jusqu'a la fin du fichier ou bien que size octets aient ИtИ transfИrИs. Si aucun argument -size n'est donnИ, alors la copie va jusqu'a la fin du fichier. Toute les donnИes lues Ю partir de inchan sont copiИes vers outchan. Sans l'option -command, fcopy bloque jusqu'a ce que la copie soit complХte et retourne le nombre d'octets Иcrits dans outchan.
    +
    L'argument -command fait travailler fcopy en arriХre-plan. Dans ce cas elle retourne immИdiatement et le callback est appelИ plus tard quand la copie se termine. Le callback est appelИ avec un ou deux arguments supplИmentaire qui indique combien d'octets ont ИtИ Иcrits dans outchan. Si une erreur s'est produite pendant la copie en arriХre-plan, le second argument est la chaНne associИe Ю l'erreur. Avec une copie en arriХre-plan, it n'est pas nИcessaire de mettre inchan ou outchan dans un mode non-bloquant; la commande fcopy en prend soin de automatiquement. NИanmoins, il est nИcessaire d'entrer dans la boucle d'ИvХnement en utilisant la commande vwait ou en utilisant Tk.
    +
    Vous n'Хtes pas autorisИs Ю faire d'autre opИrations I/O avec inchan ou outchan pendant une fcopy en arriХre-plan. Si soit inchan soit outchan est fermИ pendant la copie est en cours, la copie courante est stoppИe et le callback n'est pas fait. Si inchan est fermИ, alors toutes les donnИes dИjЮ en file pour outchan sont Иcrites.
    +
    Notez que inchan peut devenir lisible pendant une copie en arriХre-plan. Vous devez arrЙter quelconque gestionnaires fileevent pendant une copie en arriХre-plan ainsi ces gestionnaires n' interfХreront pas avec la copie. N'importe quel I/O tentИ par un gestionnaire fileevent aura une erreur " canal busy".
    +
    Fcopy traduit les sИquences de fin de ligne de inchan et outchan en accord avec l'option -translation pour ces canaux. Voir la page de manuel de fconfigure pour des dИtails sur l'option -translation. Les traductions signifient que le nombre d'octets lus de inchan peut Йtre diffИrent du nombre d'octets Иcrits Ю outchan. Seul le nombre d'octets Иcrits sur outchan est rapportИ, soit comme la valeur de retour d'un fcopy synchrone ou comme l'argument du callback pour un fcopy asynchrone.
    +
    +
    EXEMPLE

    +
    Ce premier exemple montre comment le callback rИcupХre le nombre d'octets transfИrИ. Il aussi utilise vwait pour placer l'application dans la boucle d'ИvХnement. Bien sur, cet exemple simplifiИ pourrait Йtre fait sans la commande callback.
    +
    proc Cleanup {in out bytes {error {}}} {
    + global total
    + set total $bytes
    + close $in
    + close $out
    + if {[string length $error] != 0} {
    +# l'erreur s'est produite pendant la copie
    + }
    +}
    +set in [open $file1]
    +set out [socket $serveur $port]
    +fcopy $in $out -command [liste Cleanup $in $out]
    +vwait total
    +
    +
    +
    Le second exemple copie par tranches et teste la fin de fichier dans la commande callback
    +
    proc CopyMore {in out chunk bytes {error {}}} {
    + global total done
    + incr total $ bytes
    + if {([string length $error] != 0) || [eof $in] {
    +set done $total
    +close $in
    +close $out
    + } else {
    +fcopy $in $out -command [list CopyMore $in $out $chunk] \
    + -size $chunk
    + }
    +}
    +set in [open $file1]
    +set out [socket $serveur $port]
    +set chunk 1024
    +set total 0
    +fcopy $in $out -command [list CopyMore $in $out $chunk] -size $chunk
    +vwait done
    +
    +
    +
    VOIR EGALEMENT

    +
    eof(n), fblocked(n), fconfigure(n)

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/file.htm b/hlp/fr/tcl/file.htm new file mode 100644 index 0000000..f3d3662 --- /dev/null +++ b/hlp/fr/tcl/file.htm @@ -0,0 +1,112 @@ + + + + +

    file      Commandes Internes Tcl

    +
    +
    NOM

    +
    file - Manipule les noms et les attributs de fichier +

    +
    SYNTHESE

    +
    file option name ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande fournit plusieurs opИrations sur un nom ou des attributs de fichier. Name est le nom d'un fichier; s'il commence avec un tilde, alors la substitution tilde est faite avant l'exИcution de la commande (voyez la page de manuel de filename pour les dИtails). Option indique que faire avec le nom de fichier. N'importe quelle abrИviation unique pour option est acceptable. Les options valides sont: +
    +
    file atime name ?time?
    Renvoie une chaНne dИcimale donnant la date du dernier accХs au fichier name. Si time est spИcifiИ, c'est pour fixer la date d'accХs au fichier. Le temps est mesurИ de la faГon POSIX standard comme nombre de secondes depuis une date fixe (souvent January 1, 1970). Si le fichier n'existe pas ou que sa date d'accХs ne peut Йtre trouvИe ou fixИe alors une erreur est gИnИrИe. Sous Windows, le systХme de fichiers FAT ne supporte pas la date d'accХs (POSIX). +
    +

    file attributes name
    +
    file attributesname ?option? +
    +
    file attributesname ?option value option value...? +
    Cette sous commande retourne ou fixe les valeurs spИcifiques Ю la plateforme associИes Ю un fichier. La premiХre forme retourne une liste de flags spИcifiques Ю la plateforme et leurs valeurs. La seconde forme retourne la valeur de l'option spИcifique. Le troisiХme forme fixe une ou plusieurs des valeurs. La valeurs sont les suivantes: +Sous Unix, -group lit ou fixe le nom de groupe pour le fichier. Un group id peut Йtre donnИ Ю la commande, mais elle retourne un nom de groupe. -owner gets ou fixe le nom de l'utilisateur propriИtaire du fichier. La commande retourne le nom du propriИtaire, mais l'id numИrique peut Йtre transmise quand on fixe le propriИtaire. -permissions fixe ou lit le code octal que chmod(1) utilise. Cette commande a aussi un support limitИ pour fixer en utilisant les attributs symboliques pour chmod(1), de la forme [ugo]?[[+-=][rwxst],[...]], ou les attributs symboliques multiples peuvent Йtre sИparИs par des virgules (exemple: u+s,go-rw ajoute sticky bit pour l'utilisateur, et enlХve les permissions lecture et Иcriture pour le groupe et le reste du monde). Un style chaНne simplifiИ ls, de la forme rwxrwxrwx (doit Йtre 9 caractХres), est aussi supportИ (exemple: rwxr-xr-t est Иquivalent Ю 01755). +Sous Windows, -archive donne la valeur ou bien fixe ou efface l'attribut archive du fichier. -hidden donne la valeur ou bien fixe ou efface l'attribut cachИ du fichier. -longname expanse chaque ИlИment de chemin en sa version longue. Cet attribut ne peut pas Йtre fixИ. -readonly donne la valeur ou bien fixe ou efface l'attribut lecture seule du fichier. -shortname donne une chaНne ou tout ИlИment de chemin est remplacИ avec sa version courte (8.3). Cet attribut ne peut pas Йtre fixИ. -system donne ou bien fixe ou efface la valeur de l'attribut systХme du fichier. +Sous Macintosh, -creator donne ou fixe le type Finder createur du fichier. -hidden donne ou bien fixe ou efface l'attribut cachИ du fichier. -readonly donne ou bien fixe ou efface l'attribut lecture seule du fichier. Notez que les rИpertoires peuvent seulement Йtre vИrouillИs si File Sharing est activИ. -type donne ou fixe le type Finder du fichier. +
    +

    file channels ?pattern?
    Si pattern n'est pas spИcifiИ, retourne une liste de noms de tous les canaux declarИs ouverts dans cet interprИteur. Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont renvoyИs. La correspondance est dИterminИe en utilisant les mЙmes rХgles que pour string match.
    +

    file copy ?-force? ?--? source target +
    +
    file copy?-force? ?--? source ?source ...? targetDir +
    +
    La premiХre forme fait une copie du fichier ou rИpertoire source sous le nom de chemin target. Si target est un rИpertoire existant, alors la seconde forme est utilisИe. La seconde forme fait une copie dans targetDir de chaque fichier source listИ. Si un rИpertoire est spИcifiИ comme source, alors le contenu du rИpertoire sera rИcursivement copiИ dans targetDir. Les fichiers existants ne seront pas ИcrasИs Ю moins que l'option -force soit spИcifiИe. Essayer d'Иcraser un rИpertoire non-vide, Иcraser un rИpertoire avec un fichier, ou un fichier avec un rИpertoire donnera des erreurs mЙme si -force a ИtИ spИcifiИ. Les arguments sont traitИs dans l'ordre spИcifiИ, s'arrХtant Ю la premiХre erreur, si elle existe. Un -- marque la fin des commutateurs; l'argument suivant le -- sera traitИ comme un source mЙme s'il commence avec un -. +
    +

    file delete ?-force? ?--? pathname ?pathname ... ? +
    Efface le fichier ou rИpertoire spИcifiИ par chaque argument pathname. Les rИpertoires non-vide seront enlevИs seulement si l'option -force est spИcifiИe. Essayer d'effacer un fichier non-existant n'est pas considerИ comme une erreur. Essayer d'effacer un fichier lecture-seule provoquera l'effacement du fichier, mЙme si le -force flags n'est pas spИcifiИ. Les arguments sont traitИ dans l'ordre spИcifiИ, s'arrХtant Ю la premiХre erreur, si elle existe. Un -- marque la fin des commutateurs; l'argument suivant le -- sera traitИ comme un pathname mЙme s'il commence avec un -. +
    +

    file dirname
    name
    Renvoie un nom comportant tout les composants de chemin de name excluant le dernier ИlИment. Si name est un nom de fichier relatif et contient seulement un ИlИment de chemin, alors retourne "." (ou ":" sur le Macintosh). Si name se refХre Ю un rИpertoire racine, alors le rИpertoire racine est renvoyИ. Par exemple, +file dirname c:/ +retourne c:/. +Notez que la substitution tilde sera effectuИe seulement si c'est nИcessaire pour que la commande aboutisse. Par exemple, +file dirname ~/src/foo.c +retourne ~/src, alors que +file dirname ~ +retourne /home (ou quelque chose de similaire). +
    +

    file exИcutable name
    Renvoie 1 si le fichier name est exИcutable par l'utilisateur courant, 0 autrement. +
    +

    file exists name
    Renvoie 1 si fichier name existe et que l'utilisateur courant a les privileges de recherche pour les rИpertoires y menant, 0 autrement. +
    +

    file extension name
    Renvoie tous caractХres de name aprХs et incluant le dernier point dans le dernier ИlИment de name. S'il n'y a pas point dans le dernier ИlИment de name alors retourne la chaНne vide. +
    +

    file isdirectory name
    Renvoie 1 si le fichier name est un rИpertoire, 0 autrement. +
    +
    file isfile name
    Renvoie 1 si le fichier name est un fichier ordinaire, 0 autrement. +
    +

    file join name ?name ...?
    Prend un ou plusieurs noms de fichiers et les combine, en utilisant le sИparateur de chemin correct pour la plateforme courante. Si un name particulier est relatif, alors il sera joint au prИcedent argument nom de fichier. Autrement, tout argument precИdent sera ИcartИ, et la jointiure commencera Ю l'argument courant. Par exemple, +file join a b /foo bar +retourne /foo/bar. +Notez que n'importe quel des noms peut contenir des sИparateurs, et que le rИsultat est toujours canonique pour la plateforme courante : / pour Unix et Windows, et : pour Macintosh. +
    +

    file lstat name varName
    Identique Ю l'option stat (voir ci-dessous) exceptИ qu'elle utilise l' appel kernel lstat au lieu de stat. Ceci signifie que si name se refХre Ю un lien symbolique l'information renvoyИe dans varName concerne le lien plutТt que le fichier auquel il se refХre. Sur les systХmes qui ne supportent pas les lien symboliques cette option se comporte exactement comme l'option stat. +
    +

    file mkdir dir ?dir ...?
    file mkdir dir ?dir ...?
    +
    file mkdir dir ?dir ...?
    +
    file mtime name ?time?
    Renvoie une chaНne dИcimale donnant le temps auquel fichier name a ИtИ modifiИ pour la derniХre fois. Si time est spИcifiИ, c'est une pour fixer le temps pour le fichier (Иquivalent Ю touch sous Unix). Le temps est mesurИ de la faГon standard POSIX en tant que secondes depuis une date fixe (souvent 1 Janvier 1970). Si le fichier n'existe pas ou la date de modification ne peut Йtre trouvИe ou rИglИe, une erreur est gИnИrИe. +
    +

    file nativename name
    Renvoie le nom du fichier spИcique Ю la plate-forme. Ceci est utile si le nom de fichier est nИcessaire Ю transmettre Ю un appel spИcique Ю la plate-forme, tel que exec sous Windows ou AppleScript sur Macintosh. +file owned name +Renvoie 1 si fichier name appartient Ю l'utilisateur courant, 0 autrement. +
    +

    file pathtype name
    Renvoie un de absolute, relative, ou volumerelative. Si name se refХre Ю un fichier spИcifique sur un volume spИcifique , le chemin type sera absolute. Si name se refХre Ю un fichier relatif au rИpertoire de travail courant, alors le type du chemin sera relative. Si name se refХre Ю un fichier relatif au rИpertoire de travail courant sur un volume spИcifiИ, ou Ю un fichier spИcifique sur le volume de travail courant, alors le type fichier est volumerelative. +
    +

    file readable name
    Renvoie 1 si le fichier name est lisible par l'utilisateur courant, 0 autrement. +
    +
    file readlink name
    Renvoie la valeur du lien symbolique dИsignИ par name (ex. le nom du fichier vers lequel il pointe). Si name n'est pas un lien symbolique ou que sa valeur ne peut pas Йtre lue, alors une erreur est gИnИrИe. Sur les systХmes qui ne supportent pas les liens symboliques cette option est indИfinie. +
    +

    file rename?-force? ?--? source target +
    +
    file rename?-force? ?--? source ?source ...? targetDir +
    La premiХre forme prend le fichier ou le rИpertoire spИcifiИ par le nom de chemin source et le renomme en target, en dИplacant le fichier si le nom de chemin target spИcifie un nom dans un rИpertoire diffИrent. Si target est un rИpertoire existant, alors la seconde forme est utilisИe. La seconde forme dИplace chaque fichier ou rИpertoire source dans le rИpertoire targetDir. Les fichiers existants ne seront pas ecrasИs Ю moins que l'option -force soit spИcifiИe. Essayer d'Иcraser un rИpertoire non-vide, Иcraser un rИpertoire avec un fichier, ou un fichier avec un rИpertoire generera des erreurs. Les arguments sont traitИs dans l'ordre spИcifiИ, s'arrЙtant Ю la premiХre erreur, si elle existe. Un -- marque la fin des commutateurs; l'argument suivant le -- sera traitИ comme une source mЙme s'il commence avec un -. +
    +

    file rootname name
    Renvoie tous les caractХres dans name jusqu'a mais non inclus le dernier caractХre "." dans le dernier composant du nom. Si le dernier composant de name ne contient pas de point, alors retourne name. +
    +

    file size name
    Renvoie une chaНne dИcimale donnant la taille du fichier name en octets. Si le fichier n'existe pas ou si sa taille ne peut pas Йtre obtenue alors une erreur est gИnИrИe. +
    +

    file split name
    Renvoie une liste dont les ИlИments sont les composants de chemin in name. Le premier ИlИment de la liste aura le mЙme type chemin que name. Tous les autres ИlИments seront relatifs. Les sИparateurs de chemin seront ИcartИs Ю moins que ils soit nИcessaires pour s'assurer qu'un ИlИment est relatif sans ambiguitИ. Par exemple, sous Unix +file split /foo/~bar/baz +retourne / foo ./~bar baz pour s'assurer que les commandes suivantes qui utiliseront le troisiХme composant ne tentent pas d'effectuer une substitution de tilde. +
    +

    file stat name varName
    DИclenche l'appel kernel stat sur name, et utilise la variable dИsignИe par varName pour recevoir information renvoyИe par l'appel kernel. VarName est traitИ comme une variable tableau, et les ИlИments suivants de cette variable sont fixes: atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, uid. Chaque ИlИment exceptИ type est une chaНne dИcimale avec la valeur du champ correspondant de la stat structure de retour; voyez la page de manuel de stat pour des dИtails sur le sens des valeurs. L'ИlИment type donne le type du fichier sous la mЙme forme que celle renvoyИe par la commande file type. Cette commande retourne une chaНne vide. +
    +

    file tail name
    Renvoie tous les caractХres dans name aprХs le dernier sИparateur de rИpertoire. Si name ne contient pas de sИparateurs alors retourne name. +
    +

    file type name
    Renvoie une chaНne donnant le type de fichier name, qui sera l'un de file, directory, characterSpecial, blockSpecial, fifo, link, ou socket. +
    +

    file volume
    Renvoie le chemin absolu des volumes montИs sur le systХme, comme liste Tcl correcte. Sur Macintosh, ce sera une liste des lecteurs montИs, locaux ou rИseaux. N.B. si deux lecteurs ont le mЙme nom, ils apparairont tous deux sur la liste de volumes, mais il n'y a pas de faГon, avec Tcl, d'acceder Ю un autre que le premier de ces lecteurs. Sous UNIX, la commande retournera toujours "/", car tous les systХmes de fichier sont montИs localement. Sous Windows, elle renverra une liste des lecteurs locaux disponibles (ex. {a:/ c:/}). +
    +

    file writable name
    Renvoie 1 si le fichier name est inscriptible par l'utilisateur courant , 0 autrement. +
    +
    +

    +
    PROBLEMES DE PORTABILITE

    +
    Unix
    +Cette commande opХre toujours en utilisant les identificateurs rИels d'utilisateur et de groupe, et non les identificateurs effectifs. +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/fileevent.htm b/hlp/fr/tcl/fileevent.htm new file mode 100644 index 0000000..ca7d7c4 --- /dev/null +++ b/hlp/fr/tcl/fileevent.htm @@ -0,0 +1,33 @@ + + + + +

    fileevent      Commandes Internes Tcl

    +
    +
    NOM

    +
    fileevent - ExИcute un script quand un canal devient lisible ou inscriptible +

    +
    SYNTAXE

    +
    fileevent channelId readable ?script?
    +fileevent channelId writable ?script +

    +
    DESCRIPTION

    +
    Cette commande est utilisИe pour crИer des file event handlers Un gestionnaire d'ИvХnement de fichier est une liaison entre un canal et un script, Ainsi le script est ИvaluИ chaque fois que le canal devient lisible ou inscriptible. Les gestionnaires d'ИvХnement de fichier sont plus couramment utilisИs pour autoriser les donnИes Ю Йtre reГues d'un autre processus sur une base pilotИe par ИvХnement, permettant au rИcepteur de continuer Ю interagir avec l'utilisateur en attendant que les donnИes arrivent. Si une application appelle gets ou read sur un canal bloquant quand il n'y a pas de donnИes entrantes disponibles, le processus bloquera; jusqu'a ce que les donnИes entrantes arrivent, il ne sera pas capable de prendre en charge d'autres ИvХnements, donc il apparaitra Ю l'utilisateur "gelИ" Avec fileevent, le processus peut savoir quand les donnИes sont prИsentes et appeller seulement gets ou read quand elles ne bloqueront pas.

    +
    L'argument channelId Ю fileevent se refХre Ю un canal ouvert, tel que la valeur de retour d'une prИcИdente commande open ou socket. Si l'argument script est spИcifiИ, alors fileevent crИe un nouveau gestionnaire d'ИvХnement script qui sera ИvaluИ chaque fois que le canal devient lisible ou inscriptible (dИpendant du second argument de fileevent). Dans ce cas fileevent retourne une chaНne vide. Les gestionnaires d'ИvХnements readable et writable sont indИpendants, et peuvent Йtre crИИs et effacИs sИparИment. NИanmoins, il peut y avoir au plus un gestionnaire readable et writable pour un fichier Ю +un instant donnИ dans un interprИteur donnИ. Si fileevent est appelИ quand le gestionnaire spИcifiИ existe dИjЮ dans l'interprИteur d'appel, le nouveau script remplace l'ancien.

    +
    Si l'argument script n'est pas spИcifiИ, fileevent retourne le script courant de channelId, ou une chaНne vide s'il n'y en a aucun. Si l'argument script est spИcifiИ comme chaНne vide alors le gestionnaire d'ИvХnement est effacИ, ainsi aucun script ne sera appelИ. Un gestionnaire d'ИvХnement de fichier est aussi effacИ automatiquement chaque fois que son canal est fermИ ou son interprИteur effacИ.

    +
    Un canal est considerИ lisible si il y a des donnИes non lues disponibles sur le pИriphИrique sous-jacent. Un canal est aussi considerИ lisible si il y a des donnИes non lues dans un tampon d'entrИe, exceptИ dans le cas spИcial oЫ la plus rИcente tentative de lire Ю partir du canal comme un appel Ю gets qui n'a pas pu trouver une ligne complХte dans le tampon d'entrИe. Cette fonctionnalitИ permet Ю un fichier d'Йtre lu une ligne Ю la fois en mode non bloquant en utilisant les ИvХnements. Un canal est aussi considerИ lisible si une fin de fichier ou une condition d'erreur est prИsente sur le fichier ou le pИriphИrique sous-jacent. Il est important pour le script de vИrifier ces conditions et de les gИrer opportunИment par exemple, s'il n'y a pas de verification spИciale pour la fin du fichier, une boucle infinie peut se produire si le script ne lit pas de donnИes, retourne, et est immИdiatement appelИ de nouveau.

    +
    Un canal est considerИ inscriptible si au moins un octet de donnИes peut Йtre Иcrit sur le fichier ou pИriphИrique sous-jacent sans bloquer, ou si une condition d'erreur est prИsente sur le fichier ou pИriphИrique sous-jacent.
    +
    Les I/O pilotИes par ИvХnements fonctionnent mieux avec les canaux placИs en mode non bloquant avec la commande fconfigure. En mode bloquant, une commande puts peut bloquer si vous lui donnez plus de donnИes que le fichier ou pИriphИrique sous-jacent peut accepter, et une commande gets ou read bloquera si vous tentez de lire plus de donnИes que prХtes aucun ИvИnement ne sera traitИ pendant que les commandes bloquent. En mode non bloquant puts, read, et gets ne bloquent jamais. Voir la documentation de ces commandes individuelles pour plus d'informations sur comment elles gХrent les canaux bloquants et non bloquants.

    +
    Le script pour un ИvХnement fichier est exИcutИ au niveau global (en dehors du contexte de quelconque fonction Tcl) dans l'interprИteur dans lequel la commande fileevent a ИtИ appelИe. Si une erreur se produit pendant l'exИcution du script alors le mИcanisme bgerror est utilisИ pour rapporter l'erreur. De plus, le gestionnaire d'ИvХnement fichier est effacИ si jamais il retourne une erreur, c'est fait de maniХre Ю empЙcher les boucles infinies dues aux gestionnaires boguИs +

    +
    CREDITS

    +
    fileevent est basИe sur la commande addinput crИИe par Mark Diekhans +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/filename.htm b/hlp/fr/tcl/filename.htm new file mode 100644 index 0000000..5758e67 --- /dev/null +++ b/hlp/fr/tcl/filename.htm @@ -0,0 +1,81 @@ + + + + +

    filename      Commandes Internes Tcl

    +
    +
    NOM

    +
    filename - conventions de nom de fichiers supportИes par les commandes Tcl +

    +
    INTRODUCTION

    +
    Toutes les commandes Tcl et les fonctions C qui attendent des noms de fichier comme arguments les attendent sous une parmi trois formes, dИpendantes de la plateforme courante. Sur chaque plateforme, Tcl supporte les noms de fichier standard de cette plateforme. De plus, sur toutes les plateformes, Tcl supporte une syntaxe Unix-like conГue pour fournir une maniХre pratique de construire des noms de fichier simples. NИanmoins, les scripts qui sont conГus pour Йtre portables ne devront pas prИsumer d'une forme particuliХre pour les noms de fichier. Par contre, les scripts portables doivent utiliser les commandes file split et file join pour manipuler les noms de fichier (voyez la page de manuel de file pour plus de dИtails) +

    +
    TYPES DE CHEMIN

    +
    Les noms de fichier sont groupИs dans trois types gИnИraux basИs sur le point de dИpart du chemin utilisИ pour dИsigner le fichier: absolu, relatif, et volume-relatif. Les noms absolus sont complХtement qualifiИs, donnant un chemin vers le fichier relativement Ю un volume particulier et au rИpertoire racine sur ce volume. Les noms relatifs sont non-qualifiИs, donnant un chemin vers le fichier relativement au rИpertoire de travail courant. Les noms Volume-relatif sont partiellement qualifiИs, soit donnant le chemin relativement au rИpertoire racine sur le volume courant, ou relativement au rИpertoire courant du volume spИcifiИ. La commande file pathtype peut Йtre utilisИe pour determiner le type d'un chemin donnИ. +

    +
    SYNTAXE DE CHEMIN

    +
    Les rХgles des noms natifs dependent de la valeur rapportИe dans l'ИlИment du tableau Tcl tcl_platform(platform):
    +
    +
    mac
    Sur les systХmes Apple Macintosh, Tcl supporte deux formes de noms de chemin. Les styles normaux de noms Mac utilisent les deux points comme sИparateurs de chemin Les chemins peuvent Йtre relatifs ou absolus, et les noms de fichier peuvent conternir tout caractХre autre que les deux points Un caractХre deux points en tЙte cause l'interprИtation du reste du chemin comme relatif au rИpertoire courant. Si un chemin contient deux points qui ne sont pas en tЙte, alors le chemin est interprИtИ comme un chemin absolu Des sИquences de deux ou plus deux points ailleurs dans le chemin sont utilisИes pour construire des chemins relatifs ou :: se rИfХre au parent du rИpertoire courant, ::: se rИfХre au parent du parent, et ainsi de suite. +En supplИment au noms style Macintosh, Tcl aussi supporte un sous ensemble de noms Unix-like Si un chemin ne contient pas les deux points, alors il est interprИtИ comme un chemin Unix Le slash est utilisИ comme sИparateur de chemin Le nom de chemin . se rИfХre au rИpertoire courant, et .. se rИfХre au parent du rИpertoire courant NИanmoins, quelque noms comme / ou /.. ne sont pas assignИs, et sont interprИtИs comme noms Macintosh En general, les commandes qui gИnИrent les noms de fichier renverront des  noms style Macintosh, mais les commandes qui attendent des noms de fichier acceptent aussi bien les noms style Macintosh que Unix. +Les exemples suivants illustrent les formes variИes de noms de chemin: +
    +

    :
    Chemin relatif au dossier courant.
    +

    MyFile
    Chemin relatif Ю un nom de chemin MyFile dans le dossier courant. +
    +

    MyDisk:MyFile
    Chemin absolu Ю un fichier nommИ MyFile sur le pИriphИrique nommИ MyDisk. +
    +

    :MyDir:MyFile
    Chemin relatif Ю un fichier nommИ MyFile dans un dossier nommИ MyDir dans le dossier courant. +
    +

    ::MyFile
    Chemin relatif Ю un fichier nommИ MyFile dans le dossier parent du dossier courant. +
    +

    :::MyFile
    Chemin relatif Ю un fichier nommИ MyFile dans le dossier deux niveaux au dessus du dossier courant. +
    +

    /MyDisk/MyFile
    Chemin absolu Ю un fichier nommИ MyFile sur le pИriphИrique nommИ MyDisk. +
    +

    ../MyFile
    Chemin relatif Ю un fichier nommИ MyFile dans le dossier parent du dossier courant. +
    +
    +
    +
    unix
    Sur les plateformes Unix, Tcl utilise des noms de chemin oЫ les composants sont sИparИs par des slashes. Les noms de chemin peuvent Йtre relatifs ou absolus, et les noms de fichier peuvent contenir tout caractХre autre que le slash Les noms de fichier . et .. sont spИciaux et se refХrent  au rИpertoire courant et au parent du rИpertoire courant respectivement Plusieurs caractХres slashes adjacents sont interprИtИ comme un seul sИparateur. Les exemples suivants illustrent les formes variИes de noms de chemin: +
    +

    /
    Chemin absolu au rИpertoire racine.
    +

    /etc/passwd
    Chemin absolu vers le fichier nommИ passwd dans le rИpertoire etc du rИpertoire racine. +
    +

    .
    Chemin relatif au rИpertoire courant.
    +

    foo
    Chemin relatif au fichier foo dans le rИpertoire courant. +
    +

    foo/bar
    Chemin relatif au fichier bar dans le rИpertoire foo du rИpertoire courant. +
    +

    ../foo
    Chemin relatif au fichier foo dans le rИpertoire parent du rИpertoire courant. +
    +
    + +
    +
    windows

    Sur les plateformes Microsoft Windows, Tcl supporte les noms relatifs au lecteur et UNC L'ensemble / et \ peut Йtre employИ comme sИparateurs de rИpertoires dans les deux types de nom. Les noms relatifs au lecteur consistent en un spИcificateur optionnel de lecteur suivi par un chemin absolu ou relatif Les chemins UNC ont la forme generale \\servername\sharename\path\file Sous les deux formes, les noms de fichier . et .. sont spИciaux et se refХrent respectivement au rИpertoire courant et au parent du rИpertoire courant. Les exemples suivants illustrent les formes variИes de noms de chemin: +
    +

    \\Host\share/file
    chemin UNC absolu vers un fichier appelИ file dans le rИpertoire racine du partage share sur la machine Host.
    +

    c:foo +
    Chemin relatif au volume vers un fichier foo dans le rИpertoire courant du lecteur c. +
    +

    c:/foo
    Chemin absolu vers un fichier foo dans le rИpertoire racine du lecteur c. +
    +

    foo\bar
    Chemin relatif vers un fichier bar dans le rИpertoire foo dans le rИpertoire courant sur le volume courant . +
    +

    \foo
    Chemin relatif au volume vers un fichier foo dans le rИpertoire racine du volume courant .
    +
    +
    +
    +
    +
    +
    SUBSTITUTION DE TILDE

    +
    En plus des rХgles de nom de chemin dИcrites plus haut, Tcl supporte aussi la substitution de tilde csh-style Si un nom de chemin commence avec un tilde, alors le nom de chemin sera interprИtИ comme si le premier ИlИment etait remplacИ par l'emplacement du rИpertoire home d'un utilisateur donnИ. Si le tilde est suivi immИdiatement par un sИparateur, alors la variable d'environnement $HOME est substituИe. Sinon les caractХres entre le tilde et le sИparateur suivant sont pris pour un nom d'utilisateur, qui est utilisИ pour rИcupИrer le rИpertoire home de l'utilisateur pour substitution.
    +
    Les plateformes Macintosh et Windows ne supportent pas la substitution tilde quand un nom d'utilisateur suit le tilde. Sur ces plateformes, tenter d'utiliser un tilde suivi d'un nom d'utilisateur gИnИrera une erreur. Les noms de fichiers qui ont un tilde sans nom d'utilisateur seront substituИs en utilisant la variable d'environnement $HOME, comme sous Unix +

    +
    PROBLEMES DE PORTABILITE

    +
    Tous les systХme de fichiers ne sont pas sensibles Ю la casse, donc les scripts eviteront l'emploi d'un code dИpendant de la casse dans un nom de chemin. De plus, les jeux de caractХres autorisИs sur des pИriphИriques diffИrents peuvent diffИrer, donc on choisira des noms de fichiers qui ne contiennent pas de caractХres spИciaux comme: <>:"/\| La meilleure approche est d'utiliser des noms consistant de caractХres alphanumeriques seulement. Windows 3.1 Иgalement ne supporte que les noms de fichier de 8 caractХres et une extension de 3 caractХres

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/flush.htm b/hlp/fr/tcl/flush.htm new file mode 100644 index 0000000..b746609 --- /dev/null +++ b/hlp/fr/tcl/flush.htm @@ -0,0 +1,22 @@ + + + + +

    flush      Commandes Internes Tcl

    +
    +
    NOM

    +
    flush √ Vide le tampon de sortie d'un canal +

    +
    SYNTAXE

    +
    flush channelId +

    +
    DESCRIPTION

    +
    Vide toute sortie mise en tampon de channelId. ChannelId doit Йtre un identificateur de canal tel que celui renvoyИ par unecommande prИcИdent open ou socket, et il doit avoir ИtИ ouvert en Иcriture. Si le canal est en mode bloquant la commande ne retourne pas jusqu'a ce que tout le tampon de sortie ait ИtИ vidИ dans le canal. Si le canal est en mode non bloquant, la commande peut retourner avant que tout le tampon de sortie ait ИtИ vidИ; le restant sera vidИ en arriХre-plan aussi vite que le fichier ou pИriphИrique sous-jacent sera capable de l'absorber
    +

    +
    VOIR EGALEMENT

    +
    open(n), socket(n)

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/for.htm b/hlp/fr/tcl/for.htm new file mode 100644 index 0000000..a3d9672 --- /dev/null +++ b/hlp/fr/tcl/for.htm @@ -0,0 +1,22 @@ + + + + +

    for      Commandes Internes Tcl

    +
    +
    NOM

    +
    for - boucle "For" +

    +
    SYNTAXE

    +
    for start test next body +

    +
    DESCRIPTION

    +
    For est une commande de boucle, semblable de structure Ю l'instruction C for Les arguments start, next, et body doivent Йtre des chaНnes de commande Tcl, et test est une expression chaНne. La commande for appelle d'abord l'interprИteur Tcl pour exИcuter start. Ensuite elle Иvalue rИpИtitivement test comme expression; si le rИsultat est diffИrent de zИro elle appelle l'interprИteur Tcl sur body, ensuite appelle l'interprИteur Tcl sur next, enfin rИpХte la boucle. La commande se termine quand test est ИvaluИ Ю 0 Si une commande continue est appelИe dans body alors toutes les commandes restantes dans l'exИcution courante de body sont omises; le traitement se poursuit en appelant l'interprИteur Tcl sur next, puis Иvalualuation de test, et ainsi de suite. Si une commande break est appelИe dans body ou next, alors la commande for retourne immИdiatement. L'opИration de break et continue est semblable aux instructions C correspondantes. For retourne une chaНne vide.
    +
    Note: test sera presque toujours entourИe d'accolades. Sinon, la substitution de variable sera faite avant que la commande for dИbute l'exИcution, ce qui signifie que les modifications de la variable par le corps de la boucle ne seront pas prises en compte dans l'expression. Ceci rИsulterait en une boucle infinie. Si test est entourИe d'accolades, la substitution de variable est retardИe jusqu'a ce que l'expression soit ИvaluИe (avant chaque itИration de la boucle), donc les modifications de la variables seront visibles. Comme exemple, essayez les script suivants avec et sans accolades autour de $x<10:
    +
    for {set x 0} {$x<10} {incr x} {
    +      puts "x est $x"
    +}
    +
    +
    + diff --git a/hlp/fr/tcl/foreach.htm b/hlp/fr/tcl/foreach.htm new file mode 100644 index 0000000..644842c --- /dev/null +++ b/hlp/fr/tcl/foreach.htm @@ -0,0 +1,47 @@ + + + + +

    foreach      Commandes Internes Tcl

    +
    +
    NOM

    +
    foreach - ItХre sur tout lesИlИments d'une ou plusieurs listes +

    +
    SYNTAXE

    +
    foreach varname list body
    +foreach varlist1 list1 ?varlist2 list2 ...? body +

    +
    DESCRIPTION

    +
    La commande foreach implИmente une boucle ou la ou les variable(s) de boucle  tirent leur valeurs d'une ou de plusieurs listes. Dans le cas le plus simple il y a une variable de boucle, varname, et une liste, list, qui est une liste de valeurs a assigner Ю  varname. L'argument body est un script Tcl. Pour chaque ИlИment de  list (dans l'ordre du premier au dernier), foreach assigne le contenu de l'ИlИment Ю varname comme si la commande lindex avait ИtИ utilisИe pour extraire l'ИlИment, ensuite elle appelle l'interprИteur Tcl pour exИcuter body.
    +
    Dans le cas general il peut y avoir plus d'une liste de valeurs (ex., list1 et list2), et chaque liste de valeurs peut Йtre associИe Ю une liste de variables de boucle (ex., varlist1 et varlist2). Durant chaque iteration de la boucle, aux variables de chaque varlist sont assignИs les valeurs consecutive de la  correspondante list. Les valeurs de chaque list sont utilisИes dans l'ordre du premier to dernier, et chaque valeur est utilisИe une seule fois. Le nombre total d'itИrations est suffisant pour utiliser toutes les valeurs Ю partir de toutes les listes de valeurs. Si une liste de valeurs ne contient pas assez d'ИlИments pour chacune de  ses variables de boucle Ю chaque iteration, des valeurs vides sont utilisИes pour les ИlИments manquants.
    +
    Les instructions break et continue peuvent Йtre appelИes dans body, avec le mЙme effet que dans la commande for. Foreach retourne une chaНne vide. +

    +
    EXEMPLES

    +
    La boucle suivante utilise i et j comme variables de boucle pour itИrer sur des paires d'ИlИments d'une simple liste.

    +
    set x {}
    +foreach {i j} {a b c d e f} {
    +    lappend x $j $i
    +}
    +# La valeur de x est "b a d c f e"
    +# Il y a 3 iterations de boucle. +

    +
    La boucle suivante utilise i et j pour itИrer sur deux listes en parallХle.

    +
    set x {}
    +foreach i {a b c} j {d e f g} {
    + lappend x $i $j
    +}
    +# La valeur de x est "a d b e c f {} g"
    +# Il y a 4 iterations de boucle.
    +

    +
    Les deux formes sont combinИes dans le suivant exemple.

    +
    set x {}
    +foreach i {a b c} {j k} {d e f g} {
    + lappend x $i $j $k
    +}
    +# La valeur de x est "a d e b f g c {} {}"
    +# Il y a 3 iterations de boucle. +

    +
    +
    + diff --git a/hlp/fr/tcl/format.htm b/hlp/fr/tcl/format.htm new file mode 100644 index 0000000..2353f48 --- /dev/null +++ b/hlp/fr/tcl/format.htm @@ -0,0 +1,68 @@ + + + + +

    format      Commandes Internes Tcl

    +
    +
    NOM

    +
    format - Formate une chaНne dans le style de sprintf +

    +
    SYNTAXE

    +
    format formatString ?arg arg ...? +

    +
    INTRODUCTION

    +
    Cette commande gИnХre une chaНne formatИe de la mЙme faГon que la fonction C ANSI sprintf (elle utilise sprintf dans son implИmentation). FormatString indique comment formater le rИsultat, en utilisant des spИcificateurs de conversion % comme in sprintf, et les arguments supplИmentaires, s'ils existent, fournissent les valeurs Ю substituer dans le rИsultat. La valeur de retour de format est la chaНne formatИe
    +

    +
    DETAILS SUR LE FORMATAGE

    +
    La commande opХre en scannant formatString de gauche Ю droite Chaque caractХre de la chaНne format est ajoutИ Ю la chaНne resultante Ю moins que ce soit un signe pourcentage. Si le caractХre est un % alors il n'est pas copiИ dans la chaНne resultante. Par contre, les caractХres suivants le caractХre % sont traitИs comme un spИcificateur de conversion. Le spИcificateur de conversion contrТle la conversion des arg suivant en un format particulier et le rИsultat est ajoutИ Ю la chaНne resultante Ю la place du spИcificateur de conversion. Si il y a plusieurs spИcificateurs de conversion dans la chaНne format, alors chacun d'entre eux contrТle la conversion d'un arg supplИmentaire. Les commande format doit avoir assez d'args pour satisfaire tous les spИcificateurs de conversion de formatString.
    +
    Chaque spИcificateur de conversion peut contenir jusqu'a six parties diffИrentes: un spИcificateur de position XPG3, un ensemble de flags, une largeur de champ minimum, une prИcision, un modificateur de longueur, et un caractХre de conversion. N'importe quel de ces champs peut Йtre omis exceptИ le caractХre de conversion. Les champs prИsents doivent apparaitre dans l'ordre donnИ plus haut. Le paragraphe ci-dessous dИcrit chacun de ces champs.
    +
    Si le % est suivi par un nombre dИcimal et un $, comme dans "%2$d", alors la valeur Ю convertir n'est pas extraite du suivant argument. Par contre, elle est extraite de l'argument indiquИ par les nombre, oЫ 1.htm corresponds au premier arg. Si le spИcificateur de conversion exige plusieurs arguments Ю cause de caractХres * dans le spИcificateur alors les arguments successifs sont utilisИs, en commenГant par l'argument donnИ par le nombre. Ceci suit les conventions XPG3.htm pour les spИcificateurs de position. Si il y a des spИcificateurs de position dans formatString alors tous spИcificateurs doivent Йtre positionnels.
    +
    La seconde partie d'un spИcificateur de conversion peut contenir un des caractХres flag suivants, dans n'importe quel ordre: +
    +

    -
    SpИcifie que l'argument converti sera justifiИ Ю gauche dans son champ (les nombres sont normalement justifiИs Ю droite avec des espaces en tЙte si besoin). +
    +

    +
    SpИcifie qu'un nombre doit toujours Йtre affichИ avec un signe, mЙme si positif. +
    +

    space
    SpИcifie qu'un espace sera ajoutИ au dИbut du nombre si le premier caractХre n'est pas un signe. +
    +

    0
    SpИcifie que les nombre seront remplis Ю gauche avec des zИros au lieu des espaces. +
    +

    #
    Demande une forme de sortie alternative. Pour les conversions o et O ceci garantit que le premier digit sera toujours 0. Pour conversions x ou X, 0x ou 0X (respectivement) sera ajoutИ au dИbut du rИsultat Ю moins que ce soit zИro. Pour toutes conversions flottantes (e, E, f, g, et G) ceci garantit que le rИsultat a toujours un point (ou le sИparateur dИcimal local ? NDT). Pour les conversions g et G ceci spИcifie que les zИros Ю la fin ne seront pas enlevИs. +
    +
    +
    +
    La troisiХme partie d'un spИcificateur de conversion est un nombre donnant une largeur de champ minimum pour cette conversion. Il est typiquement utilisИ pour tracer des colonnes dans les sorties tabulaires. Si l'argument converti contient moins de caractХres que la largeur de champ minimum alors il sera rempli pour atteindre la taille de la largeur de champ minimum. Le remplissage se produit normalement en ajoutant des espaces Ю gauche de l'argument converti, mais les flags 0 et - peuvent Йtre employИs pour spИcifier le remplissage avec zИros Ю gauche ou avec des espaces Ю droite, respectivement. Si la largeur de champ minimum est spИcifiИe comme * plutТt qu'un nombre, alors l'argument suivant la commande format dИtermine la largeur de champ minimum; ce doit Йtre une chaНne numИrique.
    +
    La quatriХme partie d'un spИcificateur de conversion est la prИcision, qui consiste en un point suivi d'un nombre. Le nombre est utilisИ de plusieurs faГons pour des conversions diffИrentes. Pour les conversions e, E, et f spИcifient le nombre de chiffres qui apparaissent Ю droite du sИparateur dИcimal. Pour les conversions g et G il spИcifie le nombre total de chiffres qui apparaissent, incluant ceux des deux cotИs du sИparateur dИcimal (nИanmoins, les zИros aprХs le sИparateur dИcimal seront toujours omis Ю moins que le flag # ait ИtИ spИcifiИ). Pour les conversions entiХres, il spИcifie une nombre minimum de chiffres Ю afficher (des zИros en tЙte seront ajoutИs si nИcessaire). Pour les conversions s il spИcifie le nombre maximum de caractХres Ю afficher; si la chaНne est plus longue les caractХres en excedant seront omis. Si la prИcision est spИcifiИe avec * plutТt qu'un nombre alors l'argument suivant la commande format dИtermine la prИcision; il doit Йtre une chaНne numИrique.
    +
    La cinquiХme partie d'un spИcificateur de conversion est un modificateur de longueur, qui doit Йtre h ou l. Si c'est h il spИcifie que la valeur numИrique sera tronquИe en une valeur 16-bit avant conversion. Cette option est rarement utile. Le modificateur l est ignorИ.
    +
    La derniХre chose dans un spИcificateur de conversion est un caractХre alphabИtique qui dИtermine quelle sorte de conversion effectuer. Les caractХre de conversions suivants sont couramment supportИs: +
    +

    d
    Convertit un entier en chaНne dИcimale signИe.
    +

    u
    Convertit un entier en chaНne dИcimale non signИe.
    +

    i
    Convertit un entier en chaНne dИcimale signИe; l'entier peut soit Йtre dИcimal, octal (avec 0 en tЙte) ou en hexadИcimal (avec 0xen tЙte).
    +

    o
    Convertit un entier en chaНne octale non signИe.
    +

    x ou X
    Convertit un entier en chaНne hexadИcimale non signИe, en utilisant les chiffres "0123456789abcdef" pour x et "0123456789ABCDEF" pour X). +
    +

    c
    Convertit un entier en le caractХre Unicode qu'il reprИsente. +
    +

    s
    Pas de conversion; insХre juste une chaНne.
    +

    f
    Convertit un nombre flottant en chaНne dИcimale signИe de la forme xx.yyy, oЫ le nombre de y est dИterminИ par la prИcision (par dИfaut: 6). Si la prИcision est 0 alors aucun sИparateur dИcimal n'est affichИ. +
    +

    e ou e
    Convertit un nombre flottant en notation scientifique de la forme x.yyyzz, oЫ le nombre de y's est dИterminИ par la prИcision (par dИfaut: 6). Si la prИcision est 0 alors aucun sИparateur dИcimal n'est affichИ. Si la forme E est utilisИe alors E est affichИ au lieu de e. +
    +

    g ou G
    Si l'exposant infИrieur Ю -4 ou supИrieur Ю ou Иgal Ю la prИcision, alors convertit nombre flottant comme pour %e ou %E. Autrement convertit comme pour %f. les zИros Ю la fin et le sИparateur dИcimal sont omis. +
    +

    %
    Pas de conversion; insХre juste %.
    +
    +

    +
    Pour les conversions numИriques l'argument converti doit Йtre un entier ou une chaНne flottante; format convertit l'argument en binaire et alors le convertit en une chaНne en accord avec le spИcificateur de conversion +

    +
    DIFFERENCES AVEC ANSI SPRINTF

    +
    Le comportement de la commande format est le mЙme que le fonction ANSI C sprintf exceptИ les diffИrences suivantes:

    +
    [1]  les spИcificateurs %p et %n ne sont pas couramment supportИs.

    +
    [2]  Pour les conversions %c l'argument doit Йtre une chaНne dИcimale, qui sera alors convertie en la valeur caractХre correspondante.

    +
    [3]  Le modificateur l est ignorИ; les valeurs entiХres sont toujours converties comme si'il n'y avait pas de modificateur prИsent et les valeurs rИelles sont toujours converties comme si le modificateur l etait prИsent (ex.le type double est utilisИ pour la reprИsentation interne). Si le modificateur h est spИcifiИ alors les valeur entiХres sont tronquИes en short avant conversion

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/gets.htm b/hlp/fr/tcl/gets.htm new file mode 100644 index 0000000..fba513c --- /dev/null +++ b/hlp/fr/tcl/gets.htm @@ -0,0 +1,23 @@ + + + + +

    gets      Commandes Internes Tcl

    +
    +
    NOM

    +
    gets - Lit une ligne Ю partir d'un canal +

    +
    SYNTAXE

    +
    gets channelId ?varName? +

    +
    DESCRIPTION

    +
    Cette commande lit la ligne suivante Ю partir channelId, retourne toute la ligne jusqu'a (non inclus) le(s) caractХre(s) fin de ligne et Иcarte le(s) caractХre(s) fin de ligne. Si varName est omise la ligne est renvoyИe comme rИsultat de la commande. Si varName est spИcifiИ alors la ligne est placИe dans la variable sous son nom et la valeur de retour  est un compte du nombre de caractХres renvoyИs.
    +
    Si une fin de fichier se produit pendant la recherche d'une fin de ligne, la commande retourne toute entrИe disponible jusqu'a la fin du fichier. Si channelId est en mode non bloquant et qu'il n'y a pas une ligne complХte disponible, la commande retourne une chaНne vide et ne consomme plus aucune entrИe. Si varName est spИcifiИ et qu'une chaНne vide est renvoyИe dans varName parce que la fin-de-fichier est atteinte ou Ю cause de donnИes insuffisantes en mode non bloquant, alors le compte retournИ est -1. Notez que si varName n'est pas spИcifiИe alors les cas de fin-de-fichier et de pas-de-ligne-complХte-disponible peuvent produire les mЙmes rИsultats que si on avait entrИ une ligne consistant seulement du caractХre fin de ligne. Les commandes eof et fblocked peuvent Йtre utilisИes pour distinguer ces trois cas +

    +
    VOIR EGALEMENT

    +
    eof(n), fblocked(n) 

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/glob.htm b/hlp/fr/tcl/glob.htm new file mode 100644 index 0000000..72c97ae --- /dev/null +++ b/hlp/fr/tcl/glob.htm @@ -0,0 +1,68 @@ +[portail::entete "Manuel Tcl/Tk" "M.SALVAGNIAC"] +[Doc_Dynamic] + + + + +

    glob      Commandes Internes Tcl

    +
    +
    NOM

    +
    glob - Retourne des noms de fichiers correspondant Ю des modХles +

    +
    SYNTAXE

    +
    glob ?switches? pattern ?pattern ...? +

    +
    DESCRIPTION

    +
    Cette commande effectue le "globbing" d'un nom de chemin d'une faГon semblable au shell csh Elle retourne une liste de fichiers dont les noms correspondent Ю au moins un des arguments pattern (modХles N.D.T.).
    +
    Si les arguments initiaux de glob commencent avec un - alors ils sont traitИs comme des commutateurs Les commutateurs suivants sont couramment supportИs: +
    +

    -directory directory
    Recherche les fichiers qui correspondent au modХles donnИs commenГant dans le directory donnИ Ceci permet la recherche de rИpertoires dont le nom contient des caractХres glob-sensitive sans le besoin de placer ces caractХres entre guillemets. Cette option ne peut pas Йtre utilisИe en conjonction avec -path. +
    +

    -join
    Les arguments modХles restants sont traitИs comme un seul modХle obtenu en joignant les arguments avec des sИparateurs de rИpertoire. +
    +

    -nocomplain
    Permet Ю une liste vide d'Йtre renvoyИe sans erreur; sans ce switch une erreur est gИnИrИe si la liste rИsultat est vide. +
    +

    -path pathPrefix
    Recherche les fichiers avec le pathPrefix donnИ oЫ le reste du nom correspond aux modХles donnИs Ceci permet la recherche de fichiers avec des noms identiques Ю un fichier donnИ mЙme quand les noms contient des caractХres glob-sensitive Cette option ne peut pas Йtre utilisИe en conjonction avec -directory. + +
    +

    -types typeList
    Liste seulement les fichiers ou rИpertoires qui correspondent Ю typeList, oЫ les articles dans la liste ont deux formes La premiХre forme est comme l'option -type de la commande Unix find: b (bloc spИcial fichier), c (caractХre spИcial fichier), d (rИpertoire), f (plain fichier), l (lien symbolique), p (named pipe), ou s (socket), ou de multiple types peuvent Йtre spИcifiИs dans la liste. Glob renverra tous les fichiers qui correspondent Ю au moins un des types donnИs. +La seconde forme spИcifie les types auquels tous les types donnИs doivent correspondre. Ce sont r, w, x comme permissions de fichier, et readonly, hidden comme permission spИciales Sur Macintosh, MacOS types et creators sont aussi supportИs, ou tout article de quatre caractХres est supposИ Йtre un type MacOS (ex. TEXT) Les articles qui sont de la forme {macintosh type XXXX} ou {macintosh creator XXXX} correspondront aux types ou creators respectivement Les types non reconnus, ou les spИcifications de types/creators MacOS multiples signaleront une erreur. +Les deux formes peuvent Йtre mИlangИes, ainsi -types {d f r w} trouvera tous les fichiers ordinaires  OU les rИpertoires qui ont les permissions de lecture ET d'Иcriture. Les formes suivantes sont Иquivalentes: +
      glob-type d * +
      glob */ +
    exceptИ que le premier cas ne retourne pas le "/"final et est plus indИpendant de la plateforme. +
    +

    --
    Marque la fin des commutateurs L'argument suivant cela sera traitИ comme un pattern mЙme s'il commence avec un -. +
    +
    +
    +
    Les arguments pattern peuvent contenir n'importe quel des caractХres spИciaux suivants: +
    +

    ?
    Correspond Ю n'importe quel caractХre. +
    +

    *
    Correspond Ю n'importe quelle sИquence de zИro ou plus caractХres. +
    +

    [chars]
    Correspond Ю n'importe quel caractХre de chars Si chars contient une sИquence de la forme a-b alors n'importe quel caractХre entre a et b (inclus) correspondra. +
    +

    \x
    Correspond au caractХre x.
    +

    {a,b,...}
    Correspond Ю quelconque de la chaНnes a, b, etc.
    +
    +
    +
    Comme avec csh, un "." au dИbut d'un nom de fichier ou juste aprХs un "/" doit correspondre explicitement ou avec une construction {}. De plus, tout "/" caractХres doit correspondre explicitement. +
    +
    Si le premier caractХre dans un pattern est "~" alors il se rИfХre au rИpertoire home de l'utilisateur dont le nom suit le "~". Si le "~" est suivi immИdiatement par "/" alors la valeur de la variable d'environnement HOME est utilisИ.
    +
    La commande glob diffХre du globbing csh de deux faГons. D'abord, elle ne trie pas la liste rИsultat (utilisez la commande lsort si vous voulez une liste triИe). DeuxiХmement, glob retourne seulement les noms des fichiers qui existent;  avec csh aucune vИrification d'existence n'est faite Ю moins qu'un modХle contienne une construction?, *, ou [] +

    +
    PROBLEMES DE PORTABILITE

    +
    DiffИremment des autres commandes Tcl qui acceptent aussi bien les noms rИseau et natifs (voyez la page de manuel filename pour des dИtails sur comment les noms natifs et rИseau sont spИcifiИs), la commande glob accepte seulement noms natifs. +
    +

    Windows
    Pour les noms Windows UNC, les composants serveur et partage du chemin ne peuvent pas contenir de constructions?, *, ou [] Sous Windows NT, si pattern est de la forme "~username@domain" il se rИfХre au rИpertoire home de l'utilisateur dont l'information de compte rИside sur le PDC NT spИcifiИ Autrement, l'information de compte del'utilisateur est obtenue de l 'ordinateur local Sous Windows 95 et 98, glob accepte les modХles comme ".../" et "..../" pour les rИpertoires successivement parents. +
    +

    Macintosh
    En utilisant les options, -dir, -join ou -path, glob suppose que le sИparateur de rИpertoire pour le modХle entier est le standard ":" En n'utilisant pas ces options, glob examine chaque argument modХle et utilise "/" Ю moins que le modХle contienne un ":" .
    +
    +

    +
    DerniХre rИvision: 8.3
    +
    +
    + +[portail::pied] diff --git a/hlp/fr/tcl/global.htm b/hlp/fr/tcl/global.htm new file mode 100644 index 0000000..0c0e3e8 --- /dev/null +++ b/hlp/fr/tcl/global.htm @@ -0,0 +1,20 @@ + + + + +

    global      Commandes Internes Tcl

    +
    +
    NOM

    +
    global √ AccХs au variables globales +

    +
    SYNTAXE

    +
    global varname ?varname ...? +

    +
    DESCRIPTION

    +
    Cette commande est ignorИe Ю moins qu'une fonction Tcl  soit interprИtИe. Dans ce cas elle dИclare les varname donnИes comme variables globales plutТt que locales. Les variables globales sont des variables accessibles dans le namespace global. Pour la durИe de la fonction courante (et seulement pendant son exИcution), toute rИfИrence Ю varnames se refХrera Ю la variable globale du mЙme nom. +

    +
    VOIR EGALEMENT

    +
    namespace(n), variable(n)  
    +
    +
    + diff --git a/hlp/fr/tcl/history.htm b/hlp/fr/tcl/history.htm new file mode 100644 index 0000000..2399c66 --- /dev/null +++ b/hlp/fr/tcl/history.htm @@ -0,0 +1,53 @@ + + + + +

    history      Commandes Internes Tcl

    +
    +
    NOM

    +
    history - Manipule l'historique +

    +
    SYNTAXE

    +
    history ?option? ?arg arg ...? +

    +
    DESCRIPTION

    +
    La commande history effectue une des opИrations relatives aux commandes rИcemment exИcutИes et enregistrИes dans un historique Chacune de ces commandes enregistrИes est rИfИrencИe comme un "ИvХnement" Quand on specifie un ИvХnement Ю la commande history, les formes suivantes peuvent Йtre employИes:

    +
    [1]      Un nombre si positif, se rИfХre Ю l'ИvХnement (tous les ИvХnements sont numИrotИs en commenГant Ю 1) Si le nombre est nИgatif, il dИsigne un ИvХnement relatif Ю l'ИvХnement courant (-1 se rИfХre Ю l'ИvХnement prИcedent, -2 Ю celui avant -1, et ainsi de suite) L'Иvenement 0 se rИfХre Ю l'Иvenement courant.

    +
    [2]      Une chaНne: dИsigne l'ИvХnement le plus recent qui correspond Ю la chaНne. Un ИvХnement est considerИ correspondre Ю la chaНne soit si la chaНne est la mЙme que le premier caractХres de l'ИvХnement, ou si la chaНne correspond Ю l'ИvХnement dans le sens de la commande string match.

    +
    La commande history peut prendre chacune des formes suivantes: +
    +

    history
    Identique Ю history info, dИcrit ci-dessous. +
    +

    history add command ?exec?
    Ajoute l'argument command Ю l'historique comme nouvel ИvХnement. Si exec est spИcifiИ (ou abrИgИ) alors la commande est aussi exИcutИe et son rИsultat est renvoyИ. Si exec n'est pas spИcifiИ alors une chaНne vide est renvoyИe comme rИsultat. +
    +

    history change newValue ?event? +
    Remplace la valeur enregistrИe pour un ИvХnement avec newValue Event spИcifie l'ИvХnement Ю remplacer, et pointe par dИfaut sur l'ИvХnement courant (pas l'ИvХnement -1). Cette commande est conГue pour Йtre utilisИe dans les commandes qui implИmentent les nouvelles formes de substitution d'historique et souhaitent remplacer l'ИvХnement courant (qui appelle la substitution) avec la commande crИИe par la substitution La valeur de retour est une chaНne vide. +
    +

    history clear +
    Efface l'historique. La limite courante est retenue. Les numИros d'ИvХnement d'historique sont rИinitialisИs. +
    +

    history event ?event? +
    Renvoie la valeur de l'ИvХnement donnИe par event Event est Иgal Ю √1 par dИfaut. +
    +

    history info ?count? +
    Renvoie une chaНne formatИe (et lisible) donnant les numИros et contenus d'ИvХnement pour chacun des ИvХnements dans l'historique exceptИ l'ИvХnement courant. Si count est spИcifiИ alors seulement les count ИvХnements les plus recent sont renvoyИs. +
    +

    history keep ?count? +
    Cette commande peut Йtre employИe pour changer la taille de l'historique Ю count ИvХnements. Initialement, 20 ИvХnements sont retenus dans l'historique. Si count n'est pas spИcifiИ, la limite courante est renvoyИe. +
    +

    history nextid +
    Renvoie le nombre de l'ИvХnement suivant enregistrИ dans l'historique. Il est utile par exemple pour afficher le numИro d'ИvХnement dans une ligne de commande. +
    +

    history redo ?event? +
    Re-exИcute la commande indiquИe par event et retourne son rИsultat. Event est Иgal Ю √1 par dИfaut. Cette commande rИsulte en une rИvision de l'historique, voir ci-dessous pour les dИtails. +
    +
    +

    +
    REVISION DE L'HISTORIQUE

    +
    Tcl avant la version 8.0 avait un mИcanisme de rИvision de l'historique complexe. Le mИcanisme courant est plus limitИ, et les anciennnes opИrations substitute et words ont ИtИ enlevИes. (Comme consolation, l'opИration clear a ИtИ ajoutИe.)
    +
    L'option redo rend plus simple la " rИvision de l'historique ". Quand cette option est appelИe alors l'ИvХnement le plus rИcent est modifiИ et remplacИ par le rИsultat de la commande d'historique. Si vous voulez refaire un ИvХnement sans modifier l'historique, alors utilisez l'opИration event pour rИcupИrer un ИvХnement, et l'opИration add pour  l'ajouter Ю l'historique et l'exИcuter
    +
    +
    Index  PrИcИdent  Suivant +
    +
    + diff --git a/hlp/fr/tcl/http.htm b/hlp/fr/tcl/http.htm new file mode 100644 index 0000000..fb0fd31 --- /dev/null +++ b/hlp/fr/tcl/http.htm @@ -0,0 +1,261 @@ + + + + +

    Http      Commandes Internes Tcl

    +
    +
    NOM

    +
    Http - ImplИmentation client du protocole HTTP/1.0. +

    +
    SYNTAXE

    +
    package require http ?2.3?
    +::http::config ?options?
    +::http::geturl url ?options?
    +::http::formatQuery list
    +::http::reset token
    +::http::wait token +::http::status token
    +::http::size token
    +::http::code token
    +::http::ncode token
    +::http::data token
    +::http::error token
    +::http::cleanup token
    +::http::register proto port command
    +::http::unregister proto +

    +
    DESCRIPTION

    +
    Le paquetage http fournit la partie client du protocole HTTP/1.0. Le paquetage implИmente les opИrations GET, POST, et HEAD de HTTP/1.0. Il permet la configuration d'un +proxy pour traverser les firewalls Le paquetage est compatible avec la politique de sИcuritИ Safesock, donc il peut Йtre utilisИ par un applet non vИrifiИ pour rИcupИrer des URL Ю partir d'un ensemble restreint d'hТtes. Ce paquetage peut Йtre Иtendu pour supporter d'autres protocoles de transport HTTP, tel que HTTPS, en fournissant une commande socket utilisateur, via http::register.
    +
    La fonction ::http::geturl effectue une transaction HTTP. Ses options  determinent si une transaction GET, POST, ou HEAD est effectuИe  La valeur de retour de ::http::geturl est un jeton pour la transaction. La valeur est aussi le nom d'un tableau dans le ::http namespace qui contient information d'Иtat concernant la transaction Les ИlИments de ce tableau sont dИcrits dans la section TABLEAU D'ETAT.
    +
    Si l'option -command est spИcifiИe, alors l'opИration HTTP est faite en arriХre-plan. ::http::geturl retourne immИdiatement aprХs la gИnИration  de la requЙte HTTP et le callback est appelИ quand la transaction se termine Pour que cela fonctionne, la boucle d'ИvХnement Tcl doit Йtre active Dans les applications Tk c'est toujours vrai Pour les applications purement Tcl, l'appelant peut utiliser ::http::wait aprХs l'appel de ::http::geturl pour lancer la boucle d'ИvХnement. +

    +
    COMMANDES

    +
    +
    +

    ::http::config ?options?
    La commande::http::config est utilisИ pour fixer et consulter le nom et le port du serveur proxy, et le nom de l'Agent Utilisateur utilisИ dans les requЙtes HTTP Si aucunes options ne sont spИcifiИes, alors la configuration courante est renvoyИe Si un seul argument est spИcifiИ, alors il doit Йtre un des flags dИcrits ci-dessous Dans ce cas la valeur courante de ce paramХtre est renvoyИe Autrement, les options seront un ensemble de flags et de valeurs qui definissent la configuration: +
    +

    -accept mimetypes +
    L'en-tЙte Accept de la requЙte La valeur par dИfaut est */*, ce qui signifie que qui tout types de documents sont acceptИs Autrement vous pouvez donner une  liste sИparИe par des virgules de types mime que vous souhaitez recevoir recevoir Par exemple, "image/gif, image/jpeg, text/*". +
    +

    -proxyhost hostname +
    Le nom du proxy, s'il existe. Si cette valeur est la chaНne vide, l'URL est contactИ directement. +
    +

    -proxyport number +
    Le numИro de port du proxy. +
    +

    -proxyfilter command +
    La commande est un callback qui est appelИ pendant ::http::geturl pour determiner si un proxy est requis pour un host donnИ Un argument, un nom de machine, est ajoutИ Ю command quand elle est appelИe Si un proxy est requis, le callback renverra une liste de deux ИlИment contenant le serveur proxy et le port proxy Autrement le filtre renverra une liste vide Le filtre par dИfaut retourne les valeurs des paramХtres -proxyhost et -proxyport si ils sont non-vides. +
    +

    -useragent string +
    La valeur de l'en-tЙte Agent Utilisateur dans la requЙte HTTP Par dИfaut "Tcl http client package 2.2." +
    +
    +
    +

    ::http::geturl url ?options? + +
    La commande::http::geturl est la fonction principale dans le paquetage. L'option - query provoque une opИration POST et l'option -validate provoque une opИration HEAD; autrement, une opИration GET est effectuИe La commande::http::geturl retourne une valeur token qui peut Йtre utilisИe pour obtenir l'information concernant la transaction Voir les sections TABLEAU D'ETAT et ERRORS pour les dИtails La commande::http::geturl bloque jusqu'a ce que l'opИration se termine, Ю moins que l'option -command spИcifie un callback appelИ quand la transaction HTTP se termine. ::http::geturl accepte plusieurs options: +
    +

    -blocksize size
    La taille de bloc utilisИe en lisant l'URL. Au plus size octets sont lus en une fois. AprХs chaque bloc, un appel Ю -progress est fait (si cette option est spИcifiИe). +
    +

    -channel name +
    Copie l'URL contenu dans le canal name au lieu de le sauvegarder dans state(body). +
    +

    -command callback +
    Appelle callback aprХs la fin de la transaction HTTP. Cette option cause le retour immИdiat de ::http::geturl. Le callback recoit un argument supplИmentaire qui est le token renvoyИ par ::http::geturl. Ce jeton est le nom d'un tableau qui est dИcrit dans la section TABLEAU D'ETAT.Voici un modХle pour le callback: +
    proc httpCallback {token} { +
        upvar #0 $token state +
        # AccХde au tableau d'Иtat Tcl +
    } +
    +

    -handler callback +
    Appelle callback chaque fois que des donnИes HTTP sont disponibles; si prИsent, rien d'autre ne sera fait avec les donnИes HTTP. Cette fonction attend deux arguments supplИmentaire: la socket pour les donnИes HTTP et le token renvoyИ par ::http::geturl. Le jeton est le nom d'un tableau global qui est dИcrit dans la section TABLEAU D'ETAT. La fonction est censИe renvoyer le nombre d'octets lus de la socket. Voici un modХle pour le callback: +
    proc httpHandlerCallback {socket token } { +
        upvar #0 $token state +
        # AccХde la socket, et au tableau d'Иtat Tcl +
        ... +(exemple: set data [read $socket 1000];set nbytes [string length $data])
        ..   return nbytes +
    } +
    +

    -headers keyvaluelist +
    Cette option est utilisИe pour ajouter des en-tЙtes Ю la requЙte HTTP. L'argument keyvaluelist doit Йtre une liste avec le mЙme nombre d'ИlИments alternant entre clИs et valeurs. Les clИs deviennent les en-tЙte des champ noms. Les sauts de lignes sont enlevИs des valeurs pour que l'en-tЙte ne puisse Йtre corrompu. Par exemple, si keyvaluelist est Pragma no-cache alors l'en-tЙte suivant est inclus dans la requЙte HTTP:
    +Pragma: no-cache +
    +

    -progress callback +
    Le callback est appelИ aprХs chaque transfert de donnИes de l'URL. Le callback attend trois arguments additionels: le token de ::http::geturl, la taille totale attendue des meta-donnИes contenues dans Content-Length, et le nombre courant d'octets transfИrИs effectivement. La taille totale attendue peut Йtre inconnue, auquel cas zИro est transmis au callback. Voici un modХle pour le callback progress:
    +proc httpProgress {token total current} {
    +    upvar #0 $token state
    +} +
    +

    -query query +
    Ce flag fait effectuer Ю ::http::geturl une requЙte POST qui transmet la query au serveur. La query doit Йtre une demande formatИe x-url-encoding La fonction::http::formatQuery peut Йtre utilisИe pour le formatage. +
    +

    -queryblocksize size +
    La taille de bloc utilisИe en postant des donnИes query Ю l'URL. Au plus size octets sont Иcrits Ю la fois. AprХs chaque bloc, un appel Ю -queryprogress callback est fait (si cette option est spИcifiИe). +
    +

    -querychannel channelID +
    Ce flag fait effectuer Ю ::http::geturl une requЙte POST qui passe les donnИes contenues dans channelID au serveur. Les donnИes contenue dans channelID doivent Йtre une demande formatИe x-url-encoding Ю moins que l'option -type soit utilisИe. Si un en-tЙte Content-Length n'est pas spИcifiИ via l'option -headers, ::http::geturl tente de dИterminer la taille des donnИes post dans l'ordre de crИation de l'en-tЙte. Si elle est incapable de determiner la taille, elle retourne une erreur. +
    +

    -queryprogress callback +
    Le callback est faite aprХs chaque transfert de donnИes Ю URL (ex. POST) et agit exactement comme l'option -progress (le format de callback est le mЙme). +
    +

    -timeout millisecondes +
    Si millisecondes est diffИrent de zИro, alors ::http::geturl programme un timeout aprХs le nombre spИcifiИ de millisecondes. Un timeout provoque un appel de ::http::reset et un callback -command, si spИcifiИ. La valeur de retour de ::http::status est timeout aprХs un timeout. +
    +

    -type mime-type
    Utilisez mime-type comme la valeur Content-Type, au lieu de de la valeur par dИfaut (application/x-www-form-urlencoded) pendant une opИration POST. +
    +

    -validate boolean +
    Si boolean est diffИrent de zИro, alors ::http::geturl does un HTTP HEAD requЙte. Cette requЙte retourne la meta information concernant l'URL, mais le contenu n'est pas renvoyИ. La meta information est disponible dans la variable state(meta) aprХs la transaction. Voir la section TABLEAU D'ETAT pour les dИtails. +
    +
    +
    +

    ::http::formatQuery key value ?key value ...? +
    Cette fonction opХre un x-url-encodage des donnИes consultИes. Elle attend un mЙme nombre d'arguments qui sont les clИs et valeurs de la requЙte. Elle encode les clИs et valeurs, et gИnХre une chaНne avec les sИparateurs corrects (& et =). Le rИsultat est convenable pour la valeur -query transmise Ю ::http::geturl. +
    +
    ::http::reset token?why?
    +
    Cette commande rИinitialise la transaction HTTP identifiИe par token, si elle existe. Ceci fixe la valeur state(status) Ю why, qui est par dИfaut de reset, et alors appelle le callback declarИ par -command. +
    +

    ::http::wait token +
    Ceci est une fonction utilitaire qui bloque et attend que la transaction soit complИtИe. Elle fonctionne seulement avec du code de confiance parcequ'elle utilise vwait. D'autre part, elle n'est pas utile pour les cas oЫ ::http::geturl est appelИe sans l'option -command parce que dans ce cas l'appel Ю::http::geturl ne retourne pas jusqu'a ce que la transaction HTTP soit complХte, et donc qu'il n'y a rien Ю attendre. +
    +

    ::http::data token +
    Ceci est une fonction utilitaire qui retourne l'ИlИment body (ex., l'URL donnИe) du tableau d'Иtat. +
    +

    ::http::error token
    Ceci est une fonction utilitaire qui retourne l'ИlИment error du tableau d'Иtat. +
    +

    ::http::status token +
    Ceci est une fonction utilitaire qui retourne l'ИlИment status du tableau d'Иtat. +
    +

    ::http::code token +
    Ceci est une fonction utilitaire qui retourne l'ИlИment http du tableau d'Иtat. +
    +

    ::http::ncode token
    Ceci est une fonction utilitaire qui retourne juste le code numИrique de retour (200, 404, etc.) de l'ИlИment http du tableau d'Иtat. +
    +

    ::http::size token +
    Ceci est une fonction utilitaire qui retourne l'ИlИment currentsize du tableau d'Иtat, qui reprИsente le nombre d'octets reГus de l' URL dans l'appel Ю ::http::geturl. +
    +

    ::http::cleanup token +
    Cette fonction nettoye l'Иtat associИ Ю la connection identifiИe par token AprХs cet appel, les fonctions comme ::http::data ne peuvent pas Йtre utilisИes pour obtenir l'information concernant l'opИration Il est fortement recommandИ que vous appeliez cette fonction aprХs avoir fini avec une requЙte HTTP Ne pas le faire proquera la non-libИration de la mИmoire, et si votre appli appelle ::http::geturl plusieurs fois, la fuite mИmoire pourrait provoquer un pic de performance...ou bien pire. +
    +

    ::http::register proto port command +
    Cette fonction permet de fournir des types de transport HTTP tel que HTTPS, en enregistrant un prИfixe, le port par dИfaut, et la commande Ю exИcuter pour crИer le channel Tcl. Ex.:
    +
    package require http +
    package require tls +
    http::register https 443 ::tls::socket +
    set token [http::geturl https://my.secure.site/] +
    +

    ::http::unregister proto +
    Cette fonction libХre un gestionnaire de protocole prИcedemment declarИ via http::register +
    +
    +

    +
    ERREURS

    +
    La fonction http::geturl lХvera des erreurs dans les cas suivants: options de ligne de commande invalides, URL invalide, une URL sur une machine inexistante, ou une URL Ю un mauvais port sur une machine existante. Ces erreurs signifient que la transaction rИseau n'a mЙme pas  dИmarrИ. Elle lХve aussi une erreur si elle recoit une erreur I/O pendant l'Иcriture de l'en-tЙte de la requЙte HTTP. Pour les appels::http::geturl synchrones (oЫ -command n'est pas spИcifiИe), elle lХvera une erreur si elle recoit une erreur I /O en lisant l'en-tЙtes ou les donnИes de la rИponse HTTP parce que ::http::geturl ne retourne pas de jeton dans ces cas, elle fait tout le nettoyage requis et il n'y a pas de nИcessitИ pour votre appli d'appeler ::http::cleanup.
    +
    Pour les appels asynchrones de ::http::geturl, toutes les situations d'erreur prИcИdentes s'appliquent, exceptИ que si s'il y a une erreur pendant  la lecture de l'en-tЙtes ou les donnИes de la rИponse HTTP, aucune exception n'est lИvХe Ceci parcequ'aprХs l'Иcriture des en-tЙtes HTTP, ::http::geturl retourne, et le reste de la transaction HTTP se produit en arriХre-plan La commande callback peut verifier si l'erreur s'est produite pendant la lecture en appelant ::http::status pour vИrifier le statut et si c'est error, appeller ::http::error pour obtenir le message d'erreur.
    +
    Alternativement, si le flux du programme principal atteint un point ou il a besoin de connaitre le rИsultat de la requЙte HTTP asynchrone, il peut appeller ::http::wait et alors verifier les statut et erreur, comme le callback le fait.
    +
    Dans tous les cas, vous devez toujours appeller http::cleanup pour effacer le tableau d'Иtat quand vous avez fini.
    +
    Les autres rИsultats possibles de la transaction HTTP dИterminИs par l'examen du statut Ю partir de http::status sont dИcrit ci-dessous. + +
    +

    ok +
    Si la transaction HTTP se termine entiХrement, alors le statut sera ok. NИanmoins, vous pouvez toujours vИrifier la valeur http::code pour obtenir le statut HTTP La fonction http::ncode fournit just l'erreur numИrique (ex., 200, 404 ou 500) alors que  la fonction http::code retourne une valeur comme "HTTP 404 File not found". +
    +

    eof +
    Si le serveur ferme la socket sans rИponse, alors aucune erreur n'est levИe, mais le statut de la transaction sera eof. +
    +

    error +
    Le message d'erreur sera aussi stockИ dans l'ИlИment error du tableau d'Иtat, accessible via ::http::error. +
    +
    +
    +
    Une autre possibilitИ d'erreur est que http::geturl soit incapable d'Иcrire toutes les donnИes post sur le serveur avant que le serveur rИponde et ferme la socket. Le message d'erreur est sauvegardИ dans  l'ИlИment posterror du tableau d'Иtat et alors  http::geturl tente de finaliser la transaction. Si elle peut lire la rИponse du serveur elle finira avec un statut ok, autrement elle aura un statut eof
    +

    +
    TABLEAU D'ETAT

    +
    La fonction::http::geturl retourne un token qui peut Йtre utilisИ pour obtenir l'Иtat de la transaction HTTP sous la forme d'un tableau Tcl. Utilisez cette construction pour crИer une variable tableau facile Ю utiliser:
    +
    upvar #0 $token state
    +
    Une fois que les donnИes associИes Ю l'url ne sont plus nИcessaires, le tableau d'Иtat sera dИtruit pour libИrer la mИmoire. La fonction http::cleanup est fournie Ю cet usage. Les ИlИments suivants du tableau sont supportИs: +
    +

    body +
    Le contenu de l'URL. Sera vide si l'option -channel a ИtИ spИcifiИe Cette valeur est renvoyИee par la commande::http::data. +
    +

    currentsize +
    Le nombre courant d'octets rИcupИrИ de l'URL. Cette valeur est renvoyИe par la commande::http::size. +
    +

    error +
    Si dИfini, c'est la chaНne d'erreur vue quand la transaction HTTP est avortИe. +
    +

    http +
    Le statut de la rИponse HTTP du serveur Cette valeur est renvoyИe par la commande::http::code Le format de cette valeur est: +
    HTTP/1.0 code string +Le code est un nombre de trois-digit dИfini dans le standard HTTP. Un code de 200 est OK Les codes commenГant avec 4 ou 5 indiquent des erreurs. Les codes commenГant avec 3 sont des erreurs de redirection Dans ce cas la meta-donnИe Location spИcifie une nouvelle URL qui contient l'information requise. +
    +

    meta +
    Le protocole HTTP retourne les meta-donnИes qui dИcrivent les contenus de l'URL. L'ИlИment meta du tableau d'Иtat est une liste de clИs et valeurs des meta-donnИes Ceci dans un format utile pour l'initialisation d'un tableau qui contient les meta-donnИes: +array set meta $state(meta) +Certaines des clИs meta-donnИes sont listИes ci-dessous, mais le standard HTTP en dИfinit plus, et les serveurs sont libres d'ajouter les leurs. +
    +

    Content-Type +
    Le type de contenus de l'URL Les exemples inclutnt text/html, image/gif, application/postscript et application/x-tcl.
    +

    Content-Length +
    La taille dИclarИe des contenus La taille obtenue par ::http::geturl est disponibles comme state(size). +
    +

    Location +
    Une URL alternative qui contient les donnИes requises.
    +
    +
    +

    posterror +
    L'erreur, si elle existe, qui s'est produite pendant l'Иcriture du post des donnИes sur le serveur. +
    +

    status +
    Soit ok, en cas de succХs, reset si rИinitialisИ par l'utilisateur, timeout si un timeout s'est produit avant que la transaction soit complХte, ou error pour une condition d'erreur Durant la transaction cette valeur est une chaНne vide. +
    +

    totalsize +
    Un copie de la valeur des meta-donnИes Content-Length. +
    +

    type +
    Une copie de la valeur des meta-donnИes Content-Type. +
    +

    url +
    L'URL requise. +
    +
    +

    +
    EXEMPLE

    +
    # Copie une URL dans un fichier et affiche les meta-donnИes
    +proc ::http::copy { url file {chunk 4096} } {
    +    set out [open $file w]
    + set token [geturl $url -canal $out -progress ::http::Progress \
    +      -blocksize $chunk]
    +    close $out
    +    # Ceci finit la ligne lancИ par http::Progress
    +    puts stderr ""
    +    upvar #0 $token state
    + set max 0
    +    foreach {name value} $state (meta) {
    +      if {[string longueur $name] > $max} {
    +       set max [string longueur $name]
    +      }
    +      if {[regexp -nocase ^location$ $name]} {
    +          # GХre la redirection d'URL
    +          puts stderr "Location:$value "
    +          return [copy [string trim $value] $file $chunk]
    +      }
    +    }
    +    incr max
    +    foreach {name value } $ state (meta) {
    +      puts [format "%-*s %s" $max $name: $value]
    +    }
    +
    + return $token
    +}
    +proc ::http::Progress {args} {
    +    puts -nunwline stderr . ; flush stderr
    +}
    + +

    +
    VOIR EGALEMENT

    +
    safe(n), socket(n), safesock(n)

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/if.htm b/hlp/fr/tcl/if.htm new file mode 100644 index 0000000..5d0770f --- /dev/null +++ b/hlp/fr/tcl/if.htm @@ -0,0 +1,17 @@ + + + + +

    if      Commandes Internes Tcl

    +
    +
    NOM

    +
    if - Execute des scripts conditionellement +

    +
    SYNTAXE

    +
    if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN? +

    +
    DESCRIPTION

    +
    La commande if Иvalue expr1 comme expression (de la mЙme faГon que expr Иvalue ses argument) La valeur de l'expression doit Йtre boolИenne (une valeur numИrique, oЫ 0 est faux et tout le reste est vrai, ou une valeur chaНne tel que true ou yes pour vrai et false ou no pour faux); si vrai alors body1 est exИcutИ par passage Ю l'interprИteur Tcl. Autrement expr2 est ИvaluИ comme expression et si vrai alors body2 est exИcutИ, et ainsi de suite. Si aucune des expressions n'est ИvaluИe Ю vrai alors bodyN est exИcutИ. Les arguments then et else sont optionnels, ils facilitent la lecture de la commande. Il peut y avoir n'importe quel nombre de clauses elseif, incluant zИro. BodyN peut aussi Йtre omis tant que else est Иgalement omis. La valeur de retour de la commande est le rИsultat du script qui a ИtИ exИcutИ, ou une chaНne vide si aucune des expressions n'a ИtИ diffИrente de zИro et qu'il n'y avait pas de bodyN
    +
    +
    + diff --git a/hlp/fr/tcl/incr.htm b/hlp/fr/tcl/incr.htm new file mode 100644 index 0000000..3d86c60 --- /dev/null +++ b/hlp/fr/tcl/incr.htm @@ -0,0 +1,18 @@ + + + + +

    incr      Commandes Internes Tcl

    +
    +
    NOM
    +
    incr - IncrИmente la valeur d'une variable +

    +
    SYNTAXE

    +
    incr varName ?increment? +

    +
    DESCRIPTION

    +
    IncrИmente la valeur stockИe dans la variable dont le nom est varName. La valeur de la variable doit Йtre un entier. Si increment est fourni alors sa valeur (qui doit Йtre un entier) est ajoutИ Ю valeur de la variable varName;  autrement 1 est ajoutИ Ю varName. La nouvelle valeur est stockИe comme chaНne dИcimale dans la variable varName et Иgalement renvoyИe comme rИsultat
    +
    +
    + diff --git a/hlp/fr/tcl/index.htm b/hlp/fr/tcl/index.htm new file mode 100644 index 0000000..5ad840e --- /dev/null +++ b/hlp/fr/tcl/index.htm @@ -0,0 +1,41 @@ +Manuel des Commandes Tcl +

    Commandes Internes Tcl


    + + + + + + + + + + + + + + + + + + + + + + + +
    Http dde if pkg::create tcl_endOfWord
    Safe Base encoding incr pkg_mkIndex tcl_findLibrary
    Tcl eof info proc tcl_startOfNextWord
    after error interp puts tcl_startOfPreviousWord
    append eval join pwd tcl_wordBreakAfter
    array exec lappend re_syntax tcl_wordBreakBefore
    auto_execok exit lindex read tcltest
    auto_import expr linsert regexp tclvars
    auto_load fblocked list registry tell
    auto_mkindex fconfigure llength regsub time
    auto_mkindex_old fcopy load rename trace
    auto_qualify file lrange resource unknown
    auto_reset fileevent lreplace return unset
    bgerror filename lsearch scan update
    binary flush lsort seek uplevel
    break for memory set upvar
    catch foreach msgcat socket variable
    cd format namespace source vwait
    clock gets open split while
    close glob package string
    concat global parray 166
    continue history pid switch
    +
    +Copyright © 1990-1994 The Regents of the University of California
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1992-1995 Karl Lehenbauer and Mark Diekhans.
    +Copyright © 1992-1999 Karl Lehenbauer and Mark Diekhans
    +Copyright © 1993-1997 Bell Labs Innovations for Lucent Technologies
    +Copyright © 1994-2000 Sun Microsystems, Inc.
    +Copyright © 1998 Mark Harrison.
    +Copyright © 1998-1999 Scriptics Corporation
    +Copyright © 1998-2000 Ajuba Solutions
    +Copyright © 1998-2000 Ajuba Solutions.
    +Copyright © 1998-2000 Scriptics Corporation.
    +Copyright © 2001 Donal K. Fellows
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    +
    diff --git a/hlp/fr/tcl/info.htm b/hlp/fr/tcl/info.htm new file mode 100644 index 0000000..860f9f1 --- /dev/null +++ b/hlp/fr/tcl/info.htm @@ -0,0 +1,77 @@ + + + + +

    info      Commandes Internes Tcl

    +
    +
    NOM

    +
    info - Retourne l'information concernant l'Иtat de l'interprИteur Tcl +

    +
    SYNTAXE

    +
    info option ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande fournit des informations concernant les rouages de l'interprИteur Tcl. Les options lИgales (qui peuvent Йtre abrИgИes) sont: +
    +
    info args procname
    Renvoie une liste contenant les noms des arguments de la fonction procname, dans l'ordre Procname doit Йtre le nom d'une fonction de commande Tcl. +
    +

    info body procname +
    Renvoie le corps de la fonction procname Procname doit Йtre le nom d'une fonction Tcl . +
    +

    info cmdcount +
    Renvoie un compte du nombre total de commandes qui ont ИtИ appelИes dans cet interprИteur. +
    +

    info commands ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de noms de toutes les commandes Tcl dans le namespace courant, incluant Ю la fois les commandes interne Иcrites en C et les fonction de commandes dИfinies en utilisant la commande proc. Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont renvoyИs. A correspondance est dИterminИe en utilisant les mЙme rХgles que pour string match. pattern peut Йtre un nom qualifiИ comme Foo::print*. Ainsi, il peut spИcifier un namespace particulier en utilisant une sИquence de noms de namespace sИparИs par ::, et peut avoir un modХle correspondant Ю des caractХres spИciaux Ю la fin pour spИcifier un ensemble de commandes dans ce namespace. Si pattern est un nom qualifiИ, la liste rИsultante de noms de commande a chacun des noms qualifiИs avec le nom du namespace spИcifiИ . +
    +

    info complete command +
    Renvoie 1 si command est une commande complХte Tcl dans le sens oЫ elle n'a pas de guillemets, accolades, crochets ou noms ИlИment de tableau non fermants, Si la commande n'apparait pas complХte alors 0 est renvoyИ. Cette commande est typiquement utilisИe dans les environnements orientИs ligne de commande pour autoriser les utilisateurs Ю saisir des commandes rИparties sur plusieurs lignes;  si la commande n'est pas complХte, le script peut retarder l'Иvalualuation jusqu'a ce que des lignes supplИmentaire ait ИtИ saisies pour complИter la commande. < +info default procname arg varname
    +Procname doit Йtre le nom d'une fonction de commande Tcl et arg doit Йtre le nom d'un argument Ю cette fonction Si arg n'a pas de valeur par dИfaut alors la commande retourne 0. Autrement elle retourne 1 et place la valeur par dИfaut de arg dans la variable varname. +
    +

    info exists varName +
    Renvoie 1 si le nom de variable varName existe dans le contexte courant (soit comme variable globale ou locale) et a ИtИ dИfinie en lui donnant une valeur, retourne 0 autrement. +
    +

    info globals ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de tout les noms des variables globales couramment dИfinies. Les variables globales sont des variables dans le namespace global . Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont renvoyИs La correspondance est dИterminИe en utilisant les mЙme rХgles que pour string match. +
    +

    info hostname +
    Renvoie le nom de l'ordinateur sur lequel cet appel est exИcutИ. +
    +

    info level ?number? +
    Si number n'est pas spИcifiИ, cette commande retourne un nombre donnant le niveau dans la pile de la fonction appelИe, ou 0 si la commande est appelИe au premier plan Si number est spИcifiИ, alors le rИsultat est une liste consistant des noms et arguments de la fonction appellИe au niveau number sur la pile Si number est positif alors il dИsigne un niveau de pile particulier (1 se rИfХre Ю la fonction active, 2 Ю la fonction qu'elle a appelИ, et ainsi de suite); autrement cela donne un niveau relatif au niveau courant (0.htm se rИfХre Ю la fonction courante, -1.htm Ю l'appelant, et ainsi de suite). Voir la commande uplevel pour plus d'information sur la signification des niveaux de pile d'appel. +
    +

    info library +
    Renvoie le nom du rИpertoire bibliothХque dans lequel les scripts Tcl standards sont stockИs. Ceci est actuellement la valeur de la variable tcl_library et peut Йtre changИ en fixant tcl_library. Voir la page de manuel tclvars pour plus d'information. +
    +

    info loaded ?interp?
    Renvoie une liste dИcrivant tous les packages qui ont ИtИ chargИs dans interp avec la commande load. Chaque ИlИment de la liste est une sous-liste de deux ИlИments consistant du nom du fichier duquel le package a ИtИ chargИ et du nom du package. Pour les packages statiquement chargИs le nom de chemin sera une chaНne vide. Si interp est omis alors il'nformation est renvoyИe pour tout packages chargИ dans tout interprИteur du processus. Pour obtenir une liste des packages dans le courant interprИteur, SpИcifiez une chaНne vide pour l'argument interp. +
    +

    info locals ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de tout les noms des variables locales couramment-dИfinies, incluant les arguments Ю la fonction courante, s'ils existent. Les variables dИfinies avec les commandes global et upvar ne seront pas renvoyИes. Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont renvoyИs La correspondance est dИterminИe en utilisant les mЙme rХgles que pour string match. +
    +

    info nameofexecutable +
    Renvoie le nom de chemin complet du fichier binaire duquel l'application a ИtИ appelИe. Si Tcl a ИtИ incapable d'identifier le fichier, alors une chaНne vide est renvoyИe. +
    +

    info patchlevel +
    Renvoie la valeur de la variable globale tcl_patchLevel; voyez la page de manuel tclvars pour plus d'information. +
    +

    info procs ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de tout les noms des fonctions Tcl dans le namespace courant. Si pattern est spИcifiИ, seulement les noms de fonction dans le namespace  courant correspondants Ю pattern sont renvoyИs. La correspondance est dИterminИ en utilisant les mЙme rХgles que pour string match. +
    +

    info script +
    Si un fichier script Tcl est couramment ИvaluИ (ex. il y a un appel actif de Tcl_EvalFile ou il y a un appel actif de la commande source), alors cette commande retourne le nom du fichier traitИ Autrement la commande retourne une chaНne vide. +
    +

    info sharedlibextension +
    Renvoie l'extension utilisИe sur cette plateforme pour les noms des fichiers contenant des librairies partagИes (par exemple, .so sous Solaris). Si les librairies partagИes ne sont pas supportИes sur cette plateforme alors une chaНne vide est renvoyИe. +
    +

    info tclversion +
    Renvoie la valeur de la variable globale tcl_version; voyez la page de manuel tclvars pour plus d'information.
    +

    info vars ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de tout les noms des variables (locales et globales incluses)couramment visibles. Si pattern est spИcifiИ, seuls les noms correspondants Ю pattern sont renvoyИs. La correspondance est dИterminИe en utilisant les mЙme rХgles que pour string match. pattern peut Йtre un nom qualifiИ comme Foo::option*. Ainsi, il peut spИcifier un namespace particulier en utilisant une sИquence de noms de namespace sИparИs par ::, et peut avoir modХle correspondant Ю des caractХres spИciaux Ю la fin pour spИcifier un ensemble de variables dans ce namespace. Si pattern est un nom qualifiИ, la liste rИsultante de noms de variable contient chaque variable namespace correspondante qualifiИe avec le nom de son namespace +
    +
    +

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/interp.htm b/hlp/fr/tcl/interp.htm new file mode 100644 index 0000000..f6efedc --- /dev/null +++ b/hlp/fr/tcl/interp.htm @@ -0,0 +1,432 @@ + + + + +

    interp      Commandes Internes Tcl

    +
    +
    NOM

    +
    interp - CrИe et manipule des interprИteurs Tcl +

    +
    SYNTAXE

    +
    interp option ?arg arg ...?  +

    +
    DESCRIPTION

    +
    Cette commande permet la crИation d'un ou plusieurs nouveaux interprИteurs Tcl qui coexistent avec l'interprИteur crИateur dans la mЙme application. L'interprИteur crИateur est appelИ le maНtre et le nouvel interprИteur est appelИ l'esclave. Un maНtre peut crИer n'importe quel nombre d'esclaves, et chaque esclave peut lui-mЙme crИer des esclaves supplИmentaires pour lequel il est maНtre, crИant ainsi une hiИrarchie d'interprИteurs.
    +
    Chaque interprИteur est indИpendant des autres: il a son propre namespace pour les commandes, fonctions, et variables globales. Un maНtre interprИteur peut crИer des connections entre ses esclaves et lui-mЙme en utilisant un mИcanisme appelИ un alias Un alias est une commande dans un interprИteur esclave qui, quand elle est appelИe, provoque l'appel d'une commande dans son interprИteur maНtre ou dans un autre interprИteur esclave Les seules autres connections entre interprИteurs sont au travers de variable d'environnements (la variable env), qui sont normalement partagИes entre tous les interprИteurs dans l'application. Notez que le namespace pour les fichiers (tel que les noms renvoyИ par la commande open) n'est pas partagИ entre interprИteurs. Des commandes explicites sont fournies pour partager les fichiers et transfИrer les rИfИrences Ю un fichier ouvert d'un interprИteur Ю un autre.
    +
    La commande interp fournit aussi le support des interprИteurs safe Un interprИteur sЫr est un esclave dont les fonctions ont ИtИ grandement restreintes, ainsi il est plus sЫr d'exИcuter un script Иtranger sans risque pour les autres interprИteurs ou l'environnement d'application. Par exemple, toutes commandes de crИation de canal IO et les commandes de crИation de sous-process sont rendues inaccessible aux interprИteurs sЫrs. Voir INTERPRETEURS SURS ci-dessous pour plus d'information sur les fonctionnalitИs prИsentes dans un interprИteur sЫr. Les fonctionalitИs dangereuses ne sont pas enlevИes de l'interprИteur sЫr; par contre, elle sont cachИes, ainsi seul les interprИteurs de confiance peuvent y acceder. Pour une explication dИtaillИe des commandes cachИes, voir COMMANDES CACHEES, ci-dessous. Le mИcanisme d'alias peut Йtre utilisИ pour une communication protИgИe (analogue Ю un appel kernel) entre un interprИteur esclave et son maНtre. Voir INVOCATION D'ALIAS, ci-dessous, pour plus de dИtails sur comment le mИcanisme d'alias fonctionne.
    +
    Un nom d'interprИteur qualifiИ est une liste Tcl correcte contenant une sous ensemble de ses ancЙtres dans la hiИrarchie de l'interprИteur, terminИe par les chaНne dИsignant l'interprИteur dans son maНtre immИdiat. Les noms d'interprИteur sont relatif Ю l'interprИteur dans lequel ils sont utilisИs. Par exemple, si a est un esclave de l'interprИteur courant et qu'il a un esclave a1, qui Ю son tour a un esclave a11, le nom qualifiИ de a11 dans a est la liste a1 a11.
    +
    La commande interp, dИcrite ci-dessous, accepte des noms d'interprИteur qualifiИs comme arguments; l'interprИteur dans lequel la commande est ИvaluИe peut toujours Йtre rИfИrencИ comme {} (la liste ou chaНne vide). Notez qu'il est impossible de se referer  Ю un maНtre (ancestor) interprИteur par son nom dans un interprИteur esclave exceptИ au travers d'alias. Egalement, il n'y a pas de nom global par lequel se referer  au premier interprИteur crИИ dans une application. L'ensemble de ces restrictions sont motivИes par des raisons de sИcuritИ
    +

    +
    LA COMMANDE INTERP

    +
    La commande interp est utilisИe pour crИer, effacer, et manipuler des interprИteurs esclaves, et pour partager ou transferer des canaux entre interprИteurs Elle peut avoir une parmi plusieurs formes, dИpendantes de l'argument option: +
    +

    interp alias srcPath srcCmd +
    Renvoie une liste Tcl dont les ИlИments sont les targetCmd et args associИs Ю l'alias nommИ srcCmd (ce sont toutes les valeurs spИcifiИes quand l'alias a ИtИ crИИ; il est possible que la commande source actuelle dans l'esclave soit diffИrente de srcCmd si elle a ИtИ renommИe). +
    +

    interp alias srcPath srcCmd {} +
    Efface l'alias de srcCmd dans l'interprИteur esclave identifiИ par srcPath. srcCmd se rИfХre au nom sous lequel l'alias a ИtИ crИИ si la commande source a ИtИ renommИe, la commande renommИe sera effacИe. +
    +

    interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...? +
    Cette commande crИe un alias entre un esclave et un autre (voyez la commande alias esclave ci-dessous pour la crИation d'alias entre un esclave et son maНtre) Dans cette commande, chacun des interprИteurs esclave peut Йtre n'importe oЫ dans la hiИrarchie des interprИteurs sous l'interprИteur qui appelle la commande. SrcPath et srcCmd identifient le source de l'alias. SrcPath est une liste Tcl dont les ИlИments dИsignent un interprИteur particulier Par exemple, "a b" identifie un interprИteur b, qui est une esclave de l'interprИteur a, qui est un esclave de l'interprИteur appelant Une liste vide spИcifie l'interprИteur appelant la commande srcCmd donne le nom d'une nouvelle commande, qui sera crИИe dans l'interprИteur source. TargetPath et targetCmd spИcifient une cible interprИteur et commande, et l'arguments arg, s'il existe, SpИcifie les arguments supplИmentaires Ю targetCmd qui sont ajoutИs Ю tout argument spИcifiИ dans l'appel de srcCmd. TargetCmd peut Йtre indИfini Ю l'instant de cet appel, ou il peut existe dИjЮr; il n'est pas crИИ par cette commande. L'alias prИpare la commande cible Ю Йtre appelИe  dans l'interprИteur cible chaque fois que la commande source est appelИe dans l'interprИteur source Voir APPEL D'ALIAS ci-dessous pour plus de dИtails. +
    +

    interp aliases ?path? +
    Cette commande retourne une liste Tcl de noms de toutes les commandes source des alias dИfinis dans l'interprИteur identifiИ par path. +interp create ?-safe? ?--? ?path?
    +CrИe un interprИteur esclave identifiИ par path et une nouvelle commande, appelИ une slave command. Le nom de la commande esclave est le dernier composant de path. Le nouvel interprИteur esclave et la commande esclave sont crИИe dans l'interprИteur identifiИ par le chemin obtenu en enlevant le dernier composant de path. Par exemple, si path est a bc alors un nouvel interprИteur et commande esclave nommИs c sont crИИs dans l'interprИteur identifiИ par les chemin a b. La commande esclave peut Йtre employИe pour manipuler le nouvel interprИteur comme dИcrit ci-dessous. Si path est omis, Tcl crИe un nom unique de la forme interpx, oЫ x est un entier, et l'utilise pour l'interprИteur et la commande esclave. Si le switch -safe est spИcifiИ (ou si le maНtre interprИteur est un interprИteur sЫr), le nouvel interprИteur esclave sera crИИ comme un interprИteur sЫr avec des fonctionalitИ limitИes; autrement l'esclave inclutra le jeu complet des commandes et variables Tcl internes. Le -- switch peut Йtre utilisИ pour marquer la fin des commutateurs;  il peut Йtre nИcessaires si path est une valeur inhabituelle telle que -safe. Le rИsultat de la commande est le nom du nouvel interprИteur. Le nom d'un interprИteur esclave doit Йtre unique parmi tout les esclaves; une erreur se produit si le nom d'un interprИteur esclave existe dИjЮ pour ce maНtre. +
    +

    interp delete ?path ...? +
    Efface zИro ou plus interprИteurs donnИs par les arguments optionnels path, et pour chaque interprИteur, efface aussi ses esclaves. La commande efface aussi la commande esclave de chaque interprИteur effacИ. Pour chaque argument path, si aucun interprИteur de ce nom existe, la commande lХve une erreur. +
    +

    interp eval path arg ?arg ...? +
    Cette commande concatХne tous les arguments arg de la mЙme faГon que la commande concat, et Иvalue alors la chaНne rИsultante comme script Tcl dans l'interprИteur esclave identifiИ par path. Le rИsultat de cette evaluation (incluant l'information d'erreur telle que les variables errorInfo et errorCode, si une erreur se produit) est renvoyИ Ю l'interprИteur appelant . +
    +

    interp exists path
    Renvoie 1 si un interprИteur esclave du path spИcifiИ existe dans ce maНtre, 0 autrement. Si path est omis, l'interprИteur appelant est utilisИ. +
    +

    interp expose path hiddenName ?exposedCmdName? +
    Rend la commande cachИe hiddenName visible, en lui donnant Иventuellement un nouveau nom exposedCmdName (ce nom est couramment acceptИ seulement si c'est un nom global valide sans quelconque ::), dans l'interprИteur dИsignИ par path. Si une commande visible avec le nom cible existe dИjЮ, cette commande Иchoue. Les commandes cachИes sont expliquИes plus en dИtail dans COMMANDES CACHEES , ci-dessous. +
    +

    interp hide path exposedCmdName ?hiddenCmdName? +
    Cache la commande visible exposedCmdName, en la renommant en commande cachИe hiddenCmdName, ou conservant le mЙme nom si hiddenCmdName n'est pas donnИ, dans l'interprИteur dИsignИ  par path. Si une commande cachИe avec le nom ciblИ existe dИjЮ, cette commande Иchoue. exposedCmdName et hiddenCmdNamene  peuvent  pas contenir en mЙme temps de qualificateurs namespace, ou une erreur est levИe. Les commandes Ю cacher par interp hide sont recherchИes dans le namespace global  mЙme si le namespace  courant n'est pas le global. Ceci empЙche les esclaves d'abuser un maНtre interprИteur en cachant les mauvaises commandes, en rendant le namespace courant diffИrent du global. Les commandes cachИes sont expliquИes plus en dИtail dans COMMANDES CACHEES , ci-dessous. +
    +

    interp hidden path +
    Renvoie une liste des noms de toutes les commandes cachИes dans l'interprИteur identifiИ par path. +
    +

    interp invokehidden path ?-global? hiddenCmdName ?arg ...? +
    Appelle la commande cachИe hiddenCmdName avec les arguments fournis dans l'interprИteur dИsignИ par path. Aucune substitution ou Иvaluation ne sont appliquИes aux arguments. Si le flag -global est prИsent, la commande cachИe est appelИe au niveau global dans l'interprИteur cible; autrement elle est appelИe dans le cadre d'appel courant et peut acceder aux variables locales dans ce cadre et appeler des cadres externes. Les commandes cachИes sont expliquИes plus en dИtail dans COMMANDES CACHEES , ci-dessous. +
    +

    interp issafe ?path? +
    Renvoie 1 si l'interprИteur identifiИ par le path spИcifiИ est sЫr, 0 autrement. +
    +

    interp marktrusted path +
    Marque l'interprИteur identifiИ par path comme fiable. Ne montre pas les commande cachИes. Cette commande peut seulement Йtre appelИe Ю partir d'un interprИteur de confiance. La commande n'a pas d'effet si l'interprИteur identifiИ par path est dИjЮ fiable. +
    +

    interp share srcPath channelId destPath +
    Met en place le partage du canal IO identifiИ par channelId entre l'interprИteur identifiИ par srcPath et l'interprИteur identifiИ par destPath. Les deux interprИteurs ont les mЙme permissions sur le canal IO. Les deux interprИteurs doivent le fermer pour fermer le IO canal sous-jacent; les canaux IO accessibles dans un interprИteur sont automatiquement fermИs quand un interprИteur est dИtruit. +
    +

    interp slaves ?path? +
    Renvoie une liste Tcl des noms de tous les interprИteurs esclaves associИs Ю l'interprИteur identifiИ par path. Si path est omis, l'interprИteur appelant est utilisИ. +
    +

    interp target path alias +
    Renvoie une liste Tcl dИcrivant l'interprИteur cible d'un alias. L'alias est spИcifiИ avec un chemin d'interprИteur et le nom de la commande source, juste comme dans interp alias plus haut. Le nom de  l'interprИteur cible est renvoyИ comme un chemin d'interprИteur, relatif Ю l'interprИteur appelant . Si l'interprИteur cible de l'alias est l'interprИteur appelant alors une liste vide est renvoyИe. Si l'interprИteur cible de l'alias n'est pas l'interprИteur appelant ou un de ses descendants alors une erreur est gИnИrИe. La commande cible n'a pas a Йtre dИfinie Ю l'instant de cet appel. +
    +

    interp transfer srcPath channelId destPath +
    Rends le canal IO identifiИ par channelId disponible dans l'interprИteur identifiИ par destPath et indisponible dans l'interprИteur identifiИ par srcPath +
    +
    +

    +
    LA COMMANDE SLAVE

    +
    Pour chaque interprИteur esclave crИИ avec lA commande interp, une nouvelle commande Tcl est crИИe dans le maНtre interprИteur avec le mЙme nom que le nouvel interprИteur. Cette commande peut Йtre employИe pour faire des opИrations variИes sur l'interprИteur Elle a la forme gИnИrale suivante: +slave command ?arg arg ...?
    +
    Slave est le nom de l'interprИteur, et command et args determinent le comportement exact de la commande. Les formes valides de cette commande sont: +
    +

    slave aliases +
    Renvoie une liste Tcl dont les ИlИments sont les noms de tous les alias dans slave Les noms renvoyИs sont les valeurs srcCmd utilisИes quand les alias ont ИtИ crИИs (qui ne peuvent pas Йtre les mЙme que les noms des commandes courantes, si elles ont ИtИ renommИes). +
    +

    slave alias srcCmd +
    Renvoie une liste Tcl dont les ИlИments sont les targetCmd et args associИs Ю l'alias nommИ srcCmd (toutes sont les valeurs spИcifiИes quand l'alias a ИtИ crИИe; il est possible que la commande source actuelle dans l'esclave soit diffИrente de srcCmd si elle a ИtИ renommИe). +
    +

    slave alias srcCmd {} +
    Efface l'alias de srcCmd dans l'interprИteur esclave. srcCmd se rИfХre au nom sous lequel l'alias a ИtИ crИИ si la commande source a ИtИ renommИe, la commande renommИe sera effacИ. +
    +

    slave alias srcCmd targetCmd ?arg ..? +
    CrИe un alias tel que chaque fois que srcCmd est appelИe dans slave, targetCmd est appelИe dans le maНtre. Les arguments arg seront transmis Ю targetCmd comme arguments supplИmentaires, ajoutИs avant tout argument transmis dans l'appel de srcCmd. Voir  APPEL D'ALIAS ci-dessous pour les dИtails. +
    +

    slave eval arg ?arg ..?
    Cette commande concatХne tous les arguments arg de la mЙme faГon que  la commande concat, et Иvalue la chaНne rИsultante comme un script Tcl dans slave. Le rИsultat de cette Иvaluation (incluant information erreur telle que les variables errorInfo et errorCode, si une erreur se produit) est renvoyИ Ю l'interprИteur appelant . +
    +

    slave expose hiddenName ?exposedCmdName? +
    Cette commande expose la commande cachИehiddenName, lui donnant Иventuellement un nouveau nom exposedCmdName (ce nom est couramment acceptИ seulement si c'est une nom global valide sans quelconque ::), dans slave. Si une commande visible avec le nom ciblИ existe dИjЮ, cette commande Иchoue. Pour plus details sur les commande cachИes, voir COMMANDES CACHEES , ci-dessous. +
    +

    slave hide exposedCmdName ?hiddenCmdName? +
    Cette commande cache la commande visible exposedCmdName, en la renommant en la commande cachИe hiddenCmdName, ou gardant le mЙme nom si l'argument n'est pas donnИ, dans l'interprИteur slave. Si une commande cachИe avec le nom ciblИ existe dИjЮ, cette commande Иchoue. Autant exposedCmdName que hiddenCmdName ne peuvent contenir de qualificateurs namespace, ou une erreur est levИe. Les commandes a cacher sont recherchИe dans le namespace global  mЙme si le namespace  courant n'est pas le global un . Ceci empЙche les esclaves d'abuser un maНtre interprИteur en cachant les mauvaises commandes, en rendant le namespace courant diffИrent du global. Pour plus details sur les commande cachИes, voir COMMANDES CACHEES , ci-dessous. +
    +

    slave hidden
    Renvoie une liste des noms de toutes les commande cachИes dans slave. +slave invokehidden ?-global hiddenName ?arg ..?
    +Cette commande appelle la commande cachИe hiddenName avec les arguments fournis, dans slave. Aucune substitutions ou Иvaluations ne sont appliquИes aux arguments. Si le flag -global est donnИ, la commande est appelИe au niveau global dans l'esclave; autrement elle est appelИe dans le cadre d'appel courant et peut acceder Ю ses variables locales ou appeler des cadres externes. Pour plus details sur les commande cachИes, voir COMMANDES CACHEES , ci-dessous. +
    +

    slave issafe +
    Renvoie 1 si l'interprИteur esclave est sЫr, 0 autrement. +

    slave marktrusted +
    Marque l'interprИteur esclave comme fiable. Peut seulement Йtre appelИe par un interprИteur de confiance. Cette commande ne rend visible aucune commande cachИe dans l'interprИteur esclave. La commande n'a pas d'effet si l'esclave est dИjЮ fiable
    +
    +
    +

    +
    SAFE INTERPRETERS

    +
    Un interprИteur sЫr a des fonctionalitИ restreintes, ainsi il est sЫr d'exИcuter un script arbitraire donnИ par votre pire ennemi sans s'inquiИter pour l'application hТte ou le reste de votre environnement de travail De maniХre Ю rendre un interprИteur sЫr, certaines commandes et variables sont enlevИse de l'interprИteur. Par exemple, les commandes pour crИer fichiers sur disque sont enlevИes, et la commande exec est enlevИe, car elle pourrait Йtre utilisИe pour faire des dИgats Ю l'aide de sous-processus. Un accХs limitИ Ю ces facilitИs peut Йtre fourni, par crИation d'alias du maНtre interprИteur pour vИrifier leurs arguments soigneusement et fournir un accХs restreint Ю une sous ensemble sЫr de facilitИs. Par exemple, la crИation de fichier pourra Йtre autorisИ dans un sous rИpertoire particulier et l'appel de sous-processus pourra Йtre autorisИ pour un ensemble soigneusement choisi de programmes.
    +
    Un interprИteur sЫr est crИИe en specifiant le switch -safe Ю la commande interp create NИanmoins, tout esclave crИИ par un interprИteur sЫr sera aussi sЫr.
    +
    Un interprИteur sЫr est crИИe avec exactement ce jeu de commandes internes:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + after + + append + + array + + binary +
    + break + + case + + catch + + clock +
    + close + + concat + + continue + + eof +
    + error + + eval + + expr + + fblocked +
    + fcopy + + fileevent + + flush + + for +
    + foreach + + format + + gets + + global +
    + history + + if + + incr + + info +
    + interp + + join + + lappend + + lindex +
    + linsert + + list + + llength + + lrange +
    + lreplace + + lsearch + + lsort + + namespace +
    + package + + pid + + proc + + puts +
    + read + + regexp + + regsub + + rename +
    + return + + scan + + seek + + set +
    + split + + string + + subst + + switch +
    + tell + + trace + + unset + + update +
    + uplevel + + upvar + + variable + + vwait +
    + while + + + + + + +
    + +
    +
    +
    Les commandes suivantes sont cachИes par interp create quand il crИe un interprИteur sЫr:

    + + + + + + + + + + + + + + + + + + + +
    + cd + + exec + + exit + + fconfigure +
    + file + + glob + + load + + open +
    + pwd + + socket + + source + + vwait +

    + +
    Ces commandes peuvent Йtre recrИИes plus tard comme fonctions ou alias Tcl, ou rИexposИes avec interp expose.
    +
    De plus, la variable env n'est pas prИsente dans un interprИteur sЫr, donc il ne peut partager des variables d'environnement avec les autres interprИteurs. La variable env pose un problХme de sИcuritИ, parce que les utilisateurs peuvent stocker de l'information sensible dans une variable d'environnement. Par exemple, le manuel PGP recommende de stocker le mot de passe de protection de la clИ PGP privИe dans la variable d'environnement PGPPASS. Rendre cette variable disponible Ю l'exИcution de code Иtranger dans un interprИteur sЫr induirait une faille de sИcuritИ.
    +
    Si les extensions sont chargИes dans un interprИteur sЫr, elles peuvent aussi restraindre leur propre fonctionalitИ pour Иliminer les commandes sensibles. Pour une discussion sur la getion des extensions pour la sИcuritИ voyez l 'entrИe de manuel des commandes Tcl Safe-Tcl et load +

    +
    APPEL D'ALIAS

    +
    Le mИcanisme alias a ИtИ soigneusement conГu ainsi il peut Йtre utilisИ sЫrement quand un script non fiable est exИcutИ dans un esclave sЫr et que le cible de l'alias est une maНtresЫr Lachose la plus importante pour garantir la sИcuritИ est de s'assurer qui l'information transmise de l'esclave au maНtre n'est jamais ИvaluИe ou substituИe dans le maНtre; si ceci se produisait, cela pourrait activer un script de la mort dans l'esclave qui appelerait des fonctions arbitraires dans le maНtre, pour compromettre la sИcuritИ.
    +
    Quand la source d'un alias est appelИe dans l'interprИteur esclave, les substitutions Tcl usuelles sont effectuИes Ю l'analyse de la commande. Ces substitutions sont effectuИes dans l'interprИteur source juste comme elles seraient faites pour tout autre commande appelИe dans cet interprИteur. La fonction de commande de la commande source prend ses arguments et les mИlange avec les targetCmd et args de l'alias pour crИer un nouveau tableau d'arguments Si les mots de srcCmd etaient "srcCmd arg1 arg2 ... argN", le nouvel ensemble de mots sera "targetCmd arg arg ... arg arg1 arg2 ... argN", oЫ targetCmd et args sont les valeurs fournies quand l'alias a ИtИ crИИ. TargetCmd est alors utilisИe pour localiser une fonction de commande dans l'interprИteur cible, et cette fonction de commande est appelИe avec le nouveau jeu d'aguments Un erreur se produit s'il n'y a pas commande nommИe targetCmd dans l'interprИteur cible. Aucunes substitutions supplИmentaires ne sont effectuИes sur les mots, la fonction de commande cible est appelИe directement, sans passer au travers du mИcanisme evaluation Tcl normal. Les substitutions sont ainsi effectuИes sur chaque mot exactement une seule fois: targetCmd et args ont ИtИ substituИes pendant l'analyse de la commande qui crИИe l'alias, et arg1 - argN sont substituИes quand la commande source de l'alias est analysИe dans l'interprИteur source.
    +
    A l'Иcriture de targetCmds pour des alias dans des interprИteurs sЫrs, il est trХs important que les arguments de cette commande ne soient jamais ИvaluИs ou substituИs, car ceci fournirait un mИcanisme d'Иchappement par lequel les interprИteurs esclaves pourraient exИcuter du code arbitraire dans le maНtre Par consИquent, ceci pourrait compromettre la sИcuritИ du systХme +

    +
    COMMANDES CACHEES

    +
    Les interprИteurs sЫrs restreignent grandement les fonctionalitИs disponibles pour les programmes Tcl qui seraient ИxecutИs. Permettre Ю du code Tcl non fiable un accХs direct Ю ces fonctionalitИs est dangeureux, parce que il peut Йtre utilisИ pour un grand nombre d'attaques sur l'environnement. NИanmoins, il y a parfois un besoin legitime d'utiliser les fonctionalitИs dangereuses dans le contexte de l'interprИteur sЫr. Par exemple, parfois un programme doit Йtre sourced dans l'interprИteur. Un autre exemple est Tk, ou des fenЙtres sont attachИes Ю une hiИrarchie de fenЙtres pour un interprИteur spИcifique; quelque potentiellement dangereuse fonctions, ex. gestion de fenЙtres, doit Йtre effectuИe sur ces fenЙtres dans le contexte de l'interprИteur.
    +
    La commande interp fournit une solution Ю ce problХme sous la forme des hidden commands. Au lieu d'enlever entiХrement les commandes dangereuses d'un interprИteur sЫr, ces commandes sont cachИes donc elles deviennent indisponibles pour les l'exИcution de scripts Tcl dans l'interprИteur. NИanmoins, ces commande cachИes peuvent Йtre appelИe par ancЙtre fiable de l'interprИteur sЫr, dans le contexte de l'interprИteur sЫr, en utilisant interpinvoke. Les commandes cachИes et commandes visibles rИsident dans des namespaces sИparИs. Il est possible de definir une commande cachИe et un commande visible portant les mЙme nom dans un interprИteur.
    +
    Les commandes cachИes dans un interprИteur esclave peuvent Йtre appelИes dans le corps des fonctions appelИes dans le maНtre pendant l'appel d'alias. Par exemple, un alias de source pourrait Йtre crИИ dans un interprИteur esclave. Quand elle est appelИe dans l'interprИteur esclave, une fonction est appelИe dans le maНtre interprИteur pour vИrifier si l'opИration est autorisИe (ex. il demande de sourcer un fichier que l'interprИteur esclave est autorisИ Ю accИder). La fonction alors appelle la commande source cachИe dans l'interprИteur esclave pour sourcer le contenu du fichier. Notez que deux commandes nommИes source existent dans l'interprИteur esclave: l'alias, et la commande cachИe.
    +
    Parcequ'un interprИteur maНtre peut appeller une commande cachИe comme partie de la gestion d'un appel d'alias, grans soin doit Йtre pris d'Иviter l'Иvalualuation de tout arguments transmis au travers de l'appel de l'alias. Autrement, un interprИteur esclave malin pourrait faire exИcuter Ю l'interprИteur maНtre de confiance des commandes dangereuses. Voir la section sur l' APPEL D'ALIAS pour une discussion plus complХte de ce topic. Pour aider Ю Иviter ce problХme, aucune substitutions ou Иvaluations ne sont appliquИes aux arguments de interp invokehidden.
    +
    Les interprИteurs sЫrs ne sont pas autorisИs Ю appeler des commande cachИes dans eux-mЙmes ou dans leurs descendants. Ceci empЙche les esclaves sЫr d'acceder aux fonctionalitИ cachИes dans eux-mЙmes ou leurs descendants.
    +
    L'ensemble des commandes cachИes dans un interprИteur peut Йtre manipulИ par un interprИteur de confiance en utilisant interp expose et interp hide. La commande interp expose dИplace une commande cachИe dans le jeu de commande visibles dans l'interprИteur identifiИ par path, potentiellement renommant la commande dans le processus. Si une commande visible du nom ciblИ existe dИjЮ, l'opИration Иchoue. Pareillement, interp hide dИplace une commande visible dans le jeu de commande cachИes dans cet interprИteur. Les interprИteurs sЫrs ne sont pas autorisИs Ю dИplacer les commandes entre l'ensemble des commandes cachИes et visibles, dans soit eux-mЙme ou leurs descendants.
    +
    Actuellement, les noms des commande cachИes ne peuvent pas contenir de qualificateurs namespace, et vous devez en premier renommer une commande d'un namespace dans le namespace global avant de pouvoir la cacher. Les commandes cachИes par interp hide sont recherchИe dans le namespace global mЙme si le namespace courant n'est pas le global. Ceci empЙche les esclaves d'abuser un maНtre interprИteur en cachant les mauvaises commandes, en rendant le namespace courant diffИrent du global. +

    +
    CREDITS

    +
    Ce mИcanisme est basИ sur le prototype Safe-Tcl implИmentИ par Nathaniel Borenstein et Marshall Rose +

    +
    VOIR EGALEMENT

    +
    load(n), safe(n), Tcl_CreateSlave(3)
    +
    DerniХre rИvision: 7.6
    +
    +
    + diff --git a/hlp/fr/tcl/join.htm b/hlp/fr/tcl/join.htm new file mode 100644 index 0000000..0e20cb4 --- /dev/null +++ b/hlp/fr/tcl/join.htm @@ -0,0 +1,18 @@ + + + + +

    join      Commandes Internes Tcl

    +
    + +
    NOM

    +
    join - CrИe une chaНne en joignant ensemble les ИlИments d'une liste +

    +
    SYNTAXE

    +
    join list ?joinString? +

    +
    DESCRIPTION

    +
    L'argument list doit Йtre une liste Tcl valide. Cette commande retourne la chaНne formИe en joignant tous les ИlИments de list ensemble avec joinString separant chaque paire d'ИlИments adjacents. L'argument joinString est par dИfaut un caractХre espace
    +
    +
    + diff --git a/hlp/fr/tcl/lappend.htm b/hlp/fr/tcl/lappend.htm new file mode 100644 index 0000000..f4d1a8e --- /dev/null +++ b/hlp/fr/tcl/lappend.htm @@ -0,0 +1,17 @@ + + + + +

    lappend      Commandes Internes Tcl

    +
    +
    NOM

    +
    lappend √ Ajoute les ИlИments d'une liste Ю une variable +

    +
    SYNTAXE

    +
    lappend varName ?value value value ...
    +

    +
    DESCRIPTION

    +
    Cette commande traite la variable dИignИe par varName en tant que liste et ajoute chacun des arguments value de cette liste comme ИlИment sИparИ, avec des espaces entre les ИlИments. Si varName n'existe pas, elle est crИИe comme liste dont les ИlИments sont dИsignИs par les arguments value. Lappend est identique Ю append exceptИ que les values sont ajoutИes comme ИlИments de liste plutТt que texte pur. Cette commande fournit un moyen relativement efficace de construire de grandes listes Par exemple, "lappend a $b" est beaucoup plus efficace que "set a [concat $a [list $b]]" quand $a est long
    +
    +
    + diff --git a/hlp/fr/tcl/library.htm b/hlp/fr/tcl/library.htm new file mode 100644 index 0000000..bc0a663 --- /dev/null +++ b/hlp/fr/tcl/library.htm @@ -0,0 +1,119 @@ + + + + +

    library      Commandes Internes Tcl

    +
    +
    NOM

    +
    auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - bibliothХque standard des fonctions Tcl +

    +
    SYNTAXE

    +
    auto_execok cmd
    +auto_import pattern
    +auto_load cmd
    +auto_mkindex dir pattern pattern ...
    +auto_mkindex_old dir pattern pattern ...
    +auto_qualify command namespace
    +auto_reset
    +tcl_findLibrary basename version patch initScript enVarName varName
    +parray arrayName
    +tcl_endOfWord str start
    +tcl_startOfNextWord str start
    +tcl_startOfPreviousWord str start
    +tcl_wordBreakAfter str start
    +tcl_wordBreakBefore str start
    + +

    +
    INTRODUCTION

    +
    Tcl inclut une bibliothХque de fonctions d'usage courant. Les fonctions dИfinies dans la bibliothХque Tcl sont gИnИriques et peuvent Йtre utilisИes par de nombreuses applications diffИrentes. L'emplacement de la bibliothХque Tcl est renvoyИ par la commande info library. En plus de la bibliothХque Tcl, chaque application doit normalement avoir sa propre bibliothХque de fonctions; l'emplacement de cette bibliothХque est normalement donnИe par la valeur de la variable globale $app_library, oЫ app est le nom de l'application. Par exemple, l'emplacement de la bibliothХque Tk est conservИ dans la variable $tk_library.
    +
    Pour accИder aux fonctions de la bibliothХque Tcl, une application doit " sourcer " le fichier init.tcl dans la bibliothХque, par exemple avec la commande Tcl
    +
    source [file join [info library] init.tcl]
    +
    Si la fonction de bibliothХque Tcl_Init est appelИe de la fonction d'une application Tcl_AppInit, ceci se produit automatiquement. Le code de init.tcl dИfinira la fonction unknown et prИpare les autres fonctions Ю Йtre chargИes Ю la demande en utilisant le mИcanisme auto_load dИfini ci-dessous. +

    +
    FONCTIONS COMMANDES

    +
    Les fonctions suivantes sont fournies dans la bibliothХque Tcl: +
    +
    auto_execok cmd
    DИtermine si cmd est un fichier exИcutable ou une commande interne. Si c'est le cas, elle retourne une liste d'arguments Ю transmettre Ю exec pour exИcuter le fichier exИcutable ou la commande interne dИsignИe par cmd. Sinon, elle retourne une chaНne vide. Cette commande examine les rИpertoires dans le chemin de recherche courant (donnИs par la variable d'environnement PATH) dans sa recherche d'un fichier exИcutable nommИ cmd. Sur les plateformes Windows, la recherche est ИtИndue avec les mЙmes rИpertoires et extensions de fichier utilisИs par exec. Auto_exec conserve l'information au sujet des recherches prИcedentes dans un tableau nommИ auto_execs; ceci Иvite la recherche du chemin dans les appels suivants pour la mЙme cmd. La commande auto_reset peut Йtre employИe pour forcer auto_execok Ю vider son cache. +
    +

    auto_import pattern
    Auto_import est appelИe pendant namespace import pour voir si les commandes importИes spИcifiИes par pattern rИsident dans une bibliothХque auto-chargИe. Si vrai, les commandes sont chargИes, ainsi elles seront disponibles dans l'interprИteur pour la crИation des liens d'import. Si les commandes ne rИsident pas dans une bibliothХque auto-chargИe, auto_import ne fait rien. +
    +

    auto_load cmd
    Cette commande tente de charger la dИfinition d'une commande Tcl nommИe cmd. Pour ceci elle recherche un auto-load path, qui est une liste d'un ou plusieurs rИpertoires. Le chemin auto-load est donnИs par la variable globale $auto_path si elle existe. S'il n'y a pas de variable $auto_path, alors la variable d'environnement TCLLIBPATH est utilisИe, si elle existe. Autrement le chemin auto-load contient juste le rИpertoire de la bibliothХque Tcl. A l'intИrieur de chaque rИpertoire dans le chemin auto-load il doit y avoir un fichier tclIndex qui dИcrit une ou plusieurs commandes dИfinies dans ce rИpertoire et un script Ю Иvaluer pour charger chacune des commandes. Le fichier tclIndex sera gИnИrИ avec la commande auto_mkindex Si cmd est trouvИ dans un fichier index, alors le script appropriИ est ИvaluИ pour crИer la commande. La commande auto_load retourne 1 si cmd est crИИe avec succХs. La commande retourne 0 si il n'y a pas d'entrИe index pour cmd ou si le script ne definit actuellement pas cmd (ex. parce que l'information d'index est pИrimИe). Si une erreur se produit pendant le traitement du script, alors cette erreur est renvoyИe. Auto_load lit seulement l'information d'index une fois et la sauvegarde dans le tableau auto_index les appels suivants Ю auto_load recherchent cmd dans le tableau plutТt que de relire les fichiers d'index. L'information d'index mise en cache peut Йtre effacИe avec la commande auto_reset. Ceci forcera la commande auto_load suivante Ю recharger la base de donnИes d'index Ю partir du disque. +
    +

    auto_mkindex dir pattern pattern ...
    GИnХre un index utilisable par auto_load. La commande recherche dir pour tout fichiers dont les noms correspondent Ю un des arguments pattern (la correspondance est Иtablie avec la commande glob), gИnХre un index de toutes les fonctions de commande Tcl dИfinies dans tout les fichiers correspondants, et stocke l'information d'index dans un fichier nommИ tclIndex dans dir. Si aucun modХle n'est prИcisИ, un modХle de *.tcl sera supposИ. Par exemple, la commande +
       auto_mkindex foo *.tcl +
    lira tout les fichiers.tcl dans le sous-rИpertoire foo et gИnИrera un nouveau fichier d'index foo/tclIndex. +
    Auto_mkindex analyse les scripts Tcl en les "sourcant" dans un interprИteur esclave et en interceptant les commandes proc et namespace qui sont exИcutИes Des extensions peuvent utiliser le package (non documentИ) auto_mkindex_parser pour dИclarer d'autres commandes qui peuvent collaborer avec auto_load index. Vous pourrez parcourir auto.tcl pour voir comment cela fonctionne. +
    Auto_mkindex_old analyse les scripts Tcl d'une maniХre relativement rustique s'il existe une ligne qui contient le mot proc en premiers caractХres alors c'est supposИ Йtre une dИfinition de fonction et le mot suivant de la ligne est interprИtИ comme le nom de la fonction. Les dИfinitions de fonction qui n'apparaissent de cette maniХre (ex. elles ont des espaces avant proc) ne seront pas indexИes. Si votre script contient du code "dangereux", tel que du code d'initialisation globale ou des noms de fonction avec des caractХres spИciaux comme $, *, [ ou ], il sera plus sur d'utiliser auto_mkindex_old. +
    +

    auto_reset
    DИtruit toute l'information mise en cache par auto_execok et auto_load. Cette information sera relue Ю partir du disque la prochaine fois que c'est nИcessaire. Auto_reset efface aussi toutes fonctions listИes dans l'index auto_load, ainsi une copie rИcente sera chargИe la fois suivante qu'elles seront utilisИes. +
    +

    auto_qualify command namespace +
    Calcule une liste de noms pleinement qualifiИs pour command. Cette liste reflХte le chemin qu'un interprИteur standard Tcl suit pour la recherche de commande: d'abord il cherche la commande dans le namespace courant, et ensuite dans le namespace global. ConformИment, si command est relatif et que namespace n'est pas ::, la liste renvoyИe a deux ИlИments command visible par namespace, comme si c'Иtait une commande dans le namespace namespace; et command comme si c'Иtait une commande dans le namespace global. Autrement, si command est absolue (elle commence par ::), ou bien que namespace est ::, la liste contient seulement command comme si c'etait une commande dans le namespace global. +
    Auto_qualify est utilisИ par les auto-loading facilitИs en Tcl, autant pour produire des index auto-loading tel que pkgIndex.tcl, que pour effectuer l'auto-loading des fonctions Ю l'exИcution. +
    +

    tcl_findLibrary basename version patch initScript enVarName varName +
    Ceci est une fonction de recherche standard Ю utiliser par les extensions pendant leur initialisation. Elles appellent cette fonction pour rechercher leur bibliothХque de scripts dans plusieurs rИpertoires standard. Le dernier composant du nom de rИpertoire de la bibliothХque est normalement basenameversion (ex., tk8.0), mais il pourra Йtre "library" quand il est situИ dans les hiИrarchies de construction. Le fichier initScript sera "sourcИ" dans l'interprИteur une fois qu'il est trouvИ. Le rИpertoire dans lequel ce fichier est trouvИ est stockИ dans la variable globale varName. Si cette variable est dИjЮ dИfinie (ex., par du code C pendant l'initialisation de l'application) alors aucune recherche n'est effectuИe. Autrement la recherche se fait dans ces rИpertoires: le rИpertoire nommИ par la variable d'environnement enVarName; relatif au rИpertoire bibliothХque Tcl; relatif au fichier exИcutable dans l'installation standard (rИpertoire bin ou bin/arch); relatif au fichier exИcutable dans l'arbre de construction courant; relatif au fichier exИcutable dans un arbre de construction parallХle. + +
    +

    parray arrayName +
    Affiche sur la sortie standard les noms et valeurs de tous les ИlИments dans le tableau arrayName. ArrayName doit Йtre un tableau accessible Ю l'appelant de parray. Il peut Йtre soit local ou global. +
    +

    tcl_endOfWord str start +
    Renvoie l'index du premier emplacement de fin-de-mot qui se trouve aprХs un index de dИpart start dans la chaНne str. Un emplacement de fin-de-mot est dИfini pour Йtre le premier caractХre non-mot suivant le premier caractХre mot aprХs le point de dИpart. Renvoie -1 si il n'y a plus d'emplacement fin-de-mot aprХs le point de dИpart. Voir la description de tcl_wordchars et tcl_nonwordchars ci-dessous pour plus de dИtails sur comment Tcl dИtermine quels caractХres sont des caractХre mots. +
    +

    tcl_startOfNextWord str start +
    Renvoie l' index du premier emplacement dИbut-de-mot qui se trouve aprХs un index de dИpart start dans la chaНne str. Un emplacement dИbut-de-mot est dИfini pour Йtre le premier caractХre mot suivant un caractХre non-mot. Renvoie -1 si il n'y a plus d'emplacement de dИbut-de-mot aprХs le point de dИpart. +
    +

    tcl_startOfPreviousWord str start +
    Renvoie l'index du premier emplacement dИbut-de-mot qui se trouve avant un index de dИpart start dans la chaНne str. Renvoie -1 si il n'y a plus d'emplacement de dИbut-de-mot aprХs le point de dИpart. +
    +

    tcl_wordBreakAfter str start +
    Renvoie l'index de la premiХre limite de mot aprХs l'index de dИpart start dans la chaНne str. Renvoie -1 si il n'y a pas de plus limites aprХs le point de dИpart dans la chaНne donnИe L'index renvoyИ se rИfХre au second caractХre de la paire qui comporte une limite. +
    +

    tcl_wordBreakBefore str start +
    Renvoie l'index de la premiХre limite de mot avant l'index de dИpart start dans la chaНne str Renvoie -1 si il n'y a pas de plus limites avant le point de dИpart dans la chaНne donnИe. L'index renvoyИ se rИfХre au second caractХre de la paire qui comporte une limite. +
    +
    +

    +
    VARIABLES

    +
    Les variables globales suivantes sont dИfinies ou utilisИes par les fonctions dans la bibliothХque Tcl: +
    +
    auto_execs +
    UtilisИe par auto_execok pour enregistrer si des commandes particuliХres existent comme fichiers exИcutables. +
    +

    auto_index +
    UtilisИe par auto_load pour sauvegarder l'information index lue Ю partir du disque. +
    +

    auto_noexec +
    Si fixИe Ю une quelconque valeur, alors unknown ne tentera pas " d'auto-exec " quelconques commandes. +
    +

    auto_noload +
    Si fixИe Ю une quelconque valeur, alors unknown ne tentera pas " d'auto-load " quelconque commandes. +
    +

    auto_path +
    Si fixИe, alors doit contenir une liste Tcl valide indiquant les rИpertoires Ю rechercher pendant les opИrations auto-load. Cette variable est initialisИe au dИmarrage pour contenir, dans l'ordre: les rИpertoires listИs dans la variable d'environnement TCLLIBPATH, le rИpertoire nommИ par la variable $tcl_library, le rИpertoire parent de $tcl_ library, les rИpertoires listИs dans la variable $tcl_pkgPath. +
    +

    env(TCL_LIBRARY) +
    Si fixИe, alors spИcifie l'emplacement du rИpertoire contenant la bibliothХque des scripts (la valeur de cette variable sera assignИs Ю tcl_library variable et therefore renvoyИ par la commande info library). Si cette variable n'est pas fixИe alors une valeur par dИfaut est utilisИe. +
    +

    env(TCLLIBPATH) +
    Si fixИe, alors doit contenir une liste Tcl valide donnant les rИpertoires Ю rechercher pendant les opИrations auto-load. Les rИpertoires doivent Йtre spИcifiИs en format Tcl , en utilisant "/" comme sИparateur de chemin, indИpendemment de la plateforme. Cette variable est seulement utilisИe Ю l'initialisation de la variable auto_path . +
    +

    tcl_nonwordchars +
    Cette variable contient une expression rationelle qui est utilisИ par les routines comme tcl_endOfWord pour identifier si un caractХre fait partie d'un mot ou non. Si le modХle correspond Ю un caractХre, le caractХre est considerИ comme caractХre non-mot. Sur les plateformes Windows, les espaces, tabulations, et saut de lignes sont considerИs comme caractХres non-mots. Sous Unix, tout sauf les chiffres, lettres et underscores sont considerИs comme caractХre non-mots. +
    +

    tcl_wordchars +
    Cette variable contient une expression rationelle qui est utilisИe par les routines comme tcl_endOfWord pour identifier si un caractХre fait partie d'un mot ou non. Si le modХle correspond Ю un caractХre, le caractХre est considerИ comme caractХre d'un mot. Sur les plateformes Windows,les mots comportent tout caractХre qui n'est pas un espace, une tabulation, ou une nouvelle ligne. Sous Unix, les mots comportent des chiffres, lettres ou underscores. +
    +

    unknown_pending +
    UtilisИe par unknown pour enregistrer la commande(s) recherchИe. Elle est utilisИe pour detecter les erreurs oЫ unknown s'appelle rИcursivement dans une boucle infinie. La variable est dИtruite avant que unknown retourne. +
    +
    + +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/lindex.htm b/hlp/fr/tcl/lindex.htm new file mode 100644 index 0000000..1f78c0d --- /dev/null +++ b/hlp/fr/tcl/lindex.htm @@ -0,0 +1,18 @@ + + + + +

    lindex      Commandes Internes Tcl

    +
    +
    NOM

    +
    lindex - RИcupИre un ИlИment d'une liste +

    +
    SYNTAXE

    +
    lindex list index +

    +
    DESCRIPTION

    +
    Cette commande traite list comme une liste Tcl et renvoie son index'iХme ИlИment  (0 se rИfХre au premier ИlИment de la liste). En extrayant l'ИlИment, lindex observe les mЙme rХgles concernant les accolades, guillemets et backslashes que l'interprИteur de commande Tcl; nИanmoins, les substitution de variable  et de commandes ne se produisent pas. Si index est nИgatif ou supИrieur ou Иgal au nombre d'ИlИments de value, alors une chaНne vide est renvoyИe. Si index a la valeur end, il se rИfХre au dernier ИlИment de la liste, et end-integer se rИfХre au dernier ИlИment de la liste moins l'offset entier spИcifiИ 

    +
    DerniХre rИvision: 8.2
    +
    +
    + diff --git a/hlp/fr/tcl/linsert.htm b/hlp/fr/tcl/linsert.htm new file mode 100644 index 0000000..e51cf7c --- /dev/null +++ b/hlp/fr/tcl/linsert.htm @@ -0,0 +1,18 @@ + + + + +

    linsert      Commandes Internes Tcl

    +
    +
    NOM

    +
    linsert √ InsХre des ИlИments dans une liste +

    +
    SYNTAXE

    +
    linsert list index element ?element element ...? +

    +
    DESCRIPTION

    +
    Cette commande produit une nouvelle liste Ю partir de  list en insИrant tous les arguments element juste avant l'ИlИment index de list. Chaque argument element deviendra un ИlИment sИparИ de la nouvelle liste. Si index est infИrieur ou Иgal Ю zИro, alors les nouveaux ИlИments sont insИrИs au dИbut de la liste. Si index a la valeur end, ou s'il est supИrieur ou Иgal au nombre d'ИlИments dans la liste, alors les nouveaux ИlИments sont ajoutИs Ю la liste. end-integer se rИfХre au dernier ИlИment dans la liste moins l'offset entier spИcifiИ

    +
    DerniХre rИvision: 8.2
    +
    +
    + diff --git a/hlp/fr/tcl/list.htm b/hlp/fr/tcl/list.htm new file mode 100644 index 0000000..0a3e692 --- /dev/null +++ b/hlp/fr/tcl/list.htm @@ -0,0 +1,23 @@ + + + + +

    list      Commandes Internes Tcl

    +
    +
    NOM
    +
    liste - CrИe une liste +

    +
    SYNTAXE

    +
    list ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande renvoie une liste comprenant tout les args, ou une chaНne vide si aucun args n'est spИcifiИ. Les accolades et backslashes sont ajoutИs comme nИcessaire, ainsi la commande index peut Йtre employИe sur le rИsultat pour rИextraire les arguments originaux, et eval peut Йtre aussi employИe pour exИcuter la liste rИsultante, avec arg1 comme nom de la commande et les autres args comme arguments. List produit des rИsultats lИgХrement diffИrents de concat ; concat enlХve un niveau de regroupement avant de former la liste, alors que list fonctionne directement Ю partir des arguments originaux. Par exemple, la commande
    +
    list a b {c d e} {f {g h}}
    +
    renverra
    +
    a b {c d e} {f {g h}}
    +
    alors que concat avec les mЙmes arguments renverra
    +
    a b c d e f {g h}
    +
    +
    +
    + diff --git a/hlp/fr/tcl/llength.htm b/hlp/fr/tcl/llength.htm new file mode 100644 index 0000000..2243e57 --- /dev/null +++ b/hlp/fr/tcl/llength.htm @@ -0,0 +1,18 @@ + + + + +

    llength      Commandes Internes Tcl

    +
    + +
    NOM

    +
    llength - Compte le nombre d'ИlИments dans une liste +

    +
    SYNTAXE

    +
    llength list +

    +
    DESCRIPTION

    +
    Traite list en tant que liste et renvoie une chaНne dИcimale en donnant le nombre d'ИlИments
    +
    +
    + diff --git a/hlp/fr/tcl/load.htm b/hlp/fr/tcl/load.htm new file mode 100644 index 0000000..c6ec258 --- /dev/null +++ b/hlp/fr/tcl/load.htm @@ -0,0 +1,43 @@ + + + + +

    load      Commandes Internes Tcl

    +
    +
    NOM

    +
    load - Charge du code machine et initialise de nouvelles commandes. +

    +
    SYNTAXE

    +
    load fileName
    +load fileName packageName
    +load fileName packageName interp +

    +
    DESCRIPTION

    +
    Cette commande charge du code binaire Ю partir d'un fichier dans l'espace d'adressage de l'application et appelle une fonction d'initialisation dans le package pour l'incorporer dans un interprИteur. fileName est le nom du fichier contenant le code sa forme exacte varie d'un systХme Ю l'autre mais le plus souvent c'est une bibliothХque partagИe, tel un fichier.so sous Solaris ou une DLL sous Windows. packageName est le nom du package, et est utilisИ pour calculer le nom d'une fonction d'initialisation. interp est le nom du chemin de l'interprИteur dans lequel charger le package (voyez la page de manuel interp pour les dИtails); si interp est omis, il devient l'interprИteur dans lequel la commande load a ИtИ appelИe.
    +
    Une fois le fichier chargИ dans l'espace d'adressage de l'application, une des deux fonction d'initialisations sera appelИe dans le nouveau code. Typiquement la fonction d'initialisation ajoute de nouvelles commandes Ю un interprИteur Tcl. Le nom de la fonction d'initialisation est dИterminИ par packageName et si le l'interprИteur cible est sЫr ou non Pour les interprИteurs normaux le nom de la fonction d'initialisation aura le forme pkg_Init, oЫ pkg est le mЙme que packageName exceptИ que la premiХre lettre est convertie en majuscule et tout autre lettres sont converti en minuscule Par exemple, si packageName est foo ou FOo, le nom de la fonction d'initialisation sera Foo_Init.
    +
    Si l'interprИteur cible est un interprИteur sЫr, alors le nom de la fonction d'initialisation sera pkg_SafeInit au lieu de of pkg_Init. La fonction pkg_SafeInit sera Иcrite soigneusement, ainsi elle initialisera l'interprИteur sЫr avec seulement les fonctionalitИs fournies par le package sИcurisИ pour Йtre utilisИ par du code inconnu. Pour plus information sur Safe-Tcl, voyez la page de manuel safe.
    +
    La fonction d'initialisation doit correspondre au prototype suivant:
    +
    typedef int Tcl_PackageInitProc(Tcl_Interp *interp);
    +
    L'argument interp identifie l'interprИteur dans lequel le package est chargИ La fonction d'initialisation retourne TCL_OK ou TCL_ERROR pour indiquer si oui ou non elle s'est complИtИe avec succХs; dans le cas d'une erreur elle doit fixer le rИsultat de l'interprИteur Ю pointer vers un message d'erreur. Le rИsultat de la commande load sera le rИsultat renvoyИ par la fonction d'initialisation.
    +
    Le chargement d'un fichier doit Йtre fait seulement une fois pour chaque fileName dans une application. Si un fileName donnИ est chargИ dans plusieurs interprИteurs, alors le premier load chargera le code et appellera la fonction d'initialisation; le suivant load appelera la fonction d'initialisation sans recharger le code. Il n'est pas possible de dИcharger ou recharger un package.
    +
    La commande load supporte aussi les packages statiquement liИs Ю l'application, si ces packages ont ИtИ declarИs en appelant la fonction Tcl_StaticPackage. Si fileName est une chaНne vide, alors packageName doit Йtre spИcifiИ.
    +
    Si packageName est omis ou spИcifiИ comme chaНne vide, Tcl essaie de deviner le nom du package. Ceci peut Йtre fait diffИremment sur diffИrentes plateformes. La mИthode divinatoire par dИfaut, qui est utilisИ sur plusieurs plateformes UNIX, est de prendre le dernier ИlИment de fileName, enlever les premier trois caractХres si ils sont lib, et utiliser tout caractХres suivants alphabИtiques et underline comme le nom du module. Par exemple, la commande load libxyz4.2.so utilise le nom de module xyz et la commande load bin/last.so {} utilise le nom de module last.
    +
    Si fileName est une chaНne vide, alors packageName doit Йtre spИcifiИ. La commande load recherche en premier un package chargИ statiquement (qui a ИtИ declarИ en appelant la fonction Tcl_StaticPackage) par son nom; s'il en trouve un, il est utilisИ. Autrement, la commande load recherche un package chargИ dynamiquement par son nom, et l'utilise si trouvИ Si plusieurs fichiers diffИrents ont ИtИ loaded avec diffИrentes versions du package, Tcl prend le fichier qui a ИtИ chargИ en premier +

    +
    PROBLEMES DE PORTABILITE

    +
    +
    +
    Windows
    Quand un load Иchoue avec une erreur "library not found", il est aussi possible qu'une n'ait ИtИ trouvИe Pour voir les bibliothХque dИpendante, tapez "dumpbin -imports <dllname>" dans une console DOS pour voir les import de la bibliothХque. Quand vous chargez une DLL dans le rИpertoire courant, Windows ignorera "./" comme spИcificateur de chemin et utilisera une recherche heuristique pour trouver la DLL. Pour Иviter cela, chargez la DLL avec +
        load [file join [pwd] mylib.DLL] +
    +
    +
    +
    BUGS

    +
    Si le mЙme fichier est loadИ par diffИrent fileNames, il sera chargИ plusieurs fois dans l'espace d'adressage du processus . Ce comportement peut varier d'un systХme Ю un autre (certains systХmes peuvent detecter le chargement redondant, d'autres non)
    +

    +
    VOIR EGALEMENT

    +
    info sharedlibextension, Tcl_StaticPackage, sЫr(n)

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/lrange.htm b/hlp/fr/tcl/lrange.htm new file mode 100644 index 0000000..8e4e731 --- /dev/null +++ b/hlp/fr/tcl/lrange.htm @@ -0,0 +1,18 @@ + + + + +

    lrange      Commandes Internes Tcl

    +
    +
    NOM

    +
    lrange - Retourne  un ou plusieurs ИlИments adjacents d'une liste +

    +
    SYNTAXE

    +
    lrange list first last +

    +
    DESCRIPTION

    +
    List doit Йtre une liste Tcl valide. Cette commande renverra une nouvelle liste consistant des ИlИments first Ю last, inclus. First ou last peuvent Йtre end (ou quelconque de ses abrИviations) pour se rИfИrer au dernier ИlИment de la liste. Si first est infИrieur Ю zИro, il est traitИ comme zИro. Si last est supИrieur Ю ou Иgal au nombre d'ИlИments dans la liste, alors il est traitИ comme end. Si first est supИrieur Ю last alors une chaНne vide est renvoyИe. Note: "lrangelist first first" ne produit pas toujours le mЙme rИsultat que "lindex list first" (bien que souvent le fait pour les champs qui ne sont pas entourИs d'accolades); il produit , nИanmoins, exactement le mЙme rИsultat que "list [lindexlist first]"

    +
    DerniХre rИvision: 7.4
    +
    +
    + diff --git a/hlp/fr/tcl/lreplace.htm b/hlp/fr/tcl/lreplace.htm new file mode 100644 index 0000000..7fd99f1 --- /dev/null +++ b/hlp/fr/tcl/lreplace.htm @@ -0,0 +1,18 @@ + + + + +

    lreplace      Commandes Internes Tcl

    +
    +
    NOM

    +
    lreplace - Remplace les ИlИments d'une liste avec de nouveaux ИlИments +

    +
    SYNTAXE

    +
    lreplace list first last ?element element ...? +

    +
    DESCRIPTION

    +
    lreplace retourne une nouvelle liste formИe en remplaГant un ou plusieurs ИlИments de list avec les arguments element. first et last spИcifient le premier et dernier index de l'intervalle d'ИlИments Ю remplacer 0 se rИfХre au premier ИlИment de la liste, et end (ou toutes ses abrИviations) peut Йtre employИ pour se rИfИrer au dernier ИlИment de la liste. Si list est vide, alors first et last sont ignorИs. Si first est infИrieur Ю zИro, il est considerИ se rИfИrer au premier ИlИment de la liste. Pour les listes non-vides, l'ИlИment indiquИ par first doit exister. Si last est infИrieur Ю zИro mais supИrieur Ю first, alors tout ИlИment spИcifiИ sera ajoutИ Ю la liste. Si last est infИrieur Ю first alors aucun ИlИments ne sont effacИs; les nouveaux ИlИments sont simplement insИrИs avant first. Les arguments element spИcifient zИro ou plusieurs nouveaux arguments Ю ajouter Ю la liste Ю la place de ceux qui ont ИtИ effacИs. Chaque argument element deviendra un ИlИment sИparИ de la liste. Si aucun argument element n'est spИcifiИ, alors les ИlИments entre first et last sont simplement effacИs. Si list est vide, tous les arguments element sont ajoutИs Ю fin de la liste.

    +
    DerniХre rИvision: 7.4
    +
    +
    + diff --git a/hlp/fr/tcl/lsearch.htm b/hlp/fr/tcl/lsearch.htm new file mode 100644 index 0000000..ba3f34d --- /dev/null +++ b/hlp/fr/tcl/lsearch.htm @@ -0,0 +1,28 @@ + + + + +

    lsearch      Commandes Internes Tcl

    +
    +
    NOM
    +
    lsearch - Recherche un ИlИment particulier dans une liste. +

    +
    SYNTAXE

    +
    lsearch ?mode? list pattern +

    +
    DESCRIPTION

    +
    Cette commande recherche les ИlИments de list pour voir si l'un d'eux correspond Ю pattern. Si c'est le cas, la commande retourne l'index du premier ИlИment correspondant. Sinon, la commande retourne -1. L'argument mode indique comment les ИlИments de la liste doivent correspondre Ю pattern et il doit avoir une des valeurs suivantes: +
    +
    -exact
    L'ИlИment de la liste doit contenir exactement la mЙme chaНne que pattern. +
    +

    -glob
    Pattern est un modХle glob-style qui est comparИ Ю chaque ИlИment de liste en utilisant les mЙme rХgles que la commande string match . +
    +

    -regexp
    Pattern est traitИ comme un expression rationelle et comparИ Ю chaque ИlИment de laliste en utilisant les rХgles dИcrites dans la page de rИfИrence re_syntax. +
    +
    +

    +
    Si mode est omis alors il est par dИfaut de -glob

    +
    DerniХre rИvision: 7.0
    +
    +
    + diff --git a/hlp/fr/tcl/lsort.htm b/hlp/fr/tcl/lsort.htm new file mode 100644 index 0000000..c574e3e --- /dev/null +++ b/hlp/fr/tcl/lsort.htm @@ -0,0 +1,47 @@ + + + + +

    lsort      Commandes Internes Tcl

    +
    +
    NOM

    +
    lsort - Trie les ИlИments d'une liste +

    +
    SYNTAXE

    +
    lsort ?options? list +

    +
    DESCRIPTION

    +
    Cette commande trie les ИlИments de list, retournant une nouvelle liste triИe. L'implИmentation de la commande lsort utilise l'algorithme merge-sort qui est un tri stable ayant pour performance caractИristique O(n log n).
    +
    Par dИfaut un tri ASCII est utilisИ avec le rИsultat renvoyИ en ordre ascendant NИanmoins, quelconque des options suivantes peut Йtre spИcifiИe avant list pour contrТler le processusde tri (les abrИviations uniques sont acceptИes): +
    +
    -ascii
    Utilise comparaison de chaНne avec tri ASCII. Par dИfaut. +
    +

    -dictionary
    Utilise une comparaison dictionary-style. Identique Ю -ascii exceptИ que (a) la casse est ignorИe sauf pour diffИrencier et que (b) si deux chaНnes contiennent des nombres, les nombres sont comparИs comme des entiers, pas des caractХres Par exemple, en mode -dictionary, bigBoy est entre bigbang et bigboy, et x10y entre x9y et x11y. +
    +

    -integer
    Convertit les ИlИments de la liste en entiers et utilise la comparaison entiХre. +
    +

    -real
    Convertit les ИlИments de la liste en valeurs flottantes et utilise la comparaison flottante. +
    +

    -command command +
    Utilise command comme commande de comparaison. Pour comparer deux ИlИments, Иvalue un script Tcl consistant de command avec les deux ИlИments ajoutИs comme arguments supplИmentaires. Le script renverra un entier infИrieur Ю, Иgal Ю, ou supИrieur Ю zИro si le premier ИlИment est considerИ infИrieur Ю, Иgal Ю, ou supИrieur au second, respectivement. +
    +

    -increasing +
    Trie la liste en ordre croissant ("plus petit" articles en premier). Par dИfaut. +
    +

    -decreasing +
    Trie la liste en ordre dИcroissant ("plus grand " articles en premier). +
    +

    -index index +
    Si cette option est spИcifiИe, chacun des ИlИments de list doit lui-mЙme Йtre une sous liste Tcl correcte. Au lieu de tris basИs sur des sous listes complХtes, lsort extrait l'index'iХme ИlИment de chaque sous liste et trie en se basant sur l'ИlИment indiquИ. Le mot-clИ end est autorisИ pour l'index Ю trier sur le dernier ИlИment de la sous-liste. Par exemple, +
            lsort -integer -index 1 {{First 24} {Second 18} {Third 30}} +
            retourne {Second 18} {First 24} {Third 30}. +
    Cette option est beaucoup plus efficace que l'utilisation de -command pour atteindre le mЙme but. +
    +

    -unique

    -uniqueSi cette option est spИcifiИe, alors seulement le dernier jeu d'ИlИments dupliquИs trouvИ dans la liste sera retenu. Notez que les doublons sont dИterminИs relativement Ю la comparaison utilisИe dans le tri. Ainsi si -index 0 est utilisИ, {1 a} et {1 b} seront considerИs dupliquИs et seulement le second ИlИment, {1 b}, sera retenu.
    +
    +
    +
    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/memory.htm b/hlp/fr/tcl/memory.htm new file mode 100644 index 0000000..3bf1eeb --- /dev/null +++ b/hlp/fr/tcl/memory.htm @@ -0,0 +1,43 @@ + + + + +

    memory      Commandes Internes Tcl

    +
    +
    NOM

    +
    memory - ContrТle les possibilitИs Tcl de debugging mИmoire. +

    +
    SYNTAXE

    +
    memory option ?arg arg ...? +

    +
    DESCRIPTION

    +
    La commande memory donne au developpeur Tcl le contrТle des possibilitИs Tcl de debugging mИmoire La commande memory a plusieurs sous-options, qui sont dИcrites ci-dessous Elle sont seulement disponibles quand Tcl a ИtИ compilИ avec le debugging mИmoire activИ (quand TCL_MEM_DEBUG est dИfini Ю la compilation ). +
    +
    memory info +
    Produit un rapport contenant le total allouИ et libХre les blocs allouИs depuis que Tcl Ю ИtИ lancИ(le nombre courant d'appels Ю ckalloc auquel ne correspond pas un appel Ю ckfree), les octets courant allouИs, et le nombre maximum de blocs et d'octets allouИs. +
    +

    memory trace [on|off] +
    Active/dИsactive le traГage mИmoire Quand le traГage mИmoire est activИ, tout appel de ckalloc cause l'Иcriture d'une ligne de trace vers stderr, consistant du mot ckalloc, suivi par l'adresse renvoyИe, le total de mИmoire allouИe, et le nom de fichier C et numИro de ligne de le code qui a effectuИ l'allocation Par exemple: +
    ckalloc 40e478 98 tclProc.c 1406 +
    Les appels Ю ckfree sont tracИs de la mЙme maniХre. +
    +

    memory validate [on|off] +
    Active/dИsactive la validation mИmoire. Quand la validation mИmoire est activИe, Ю tout appel de ckalloc ou ckfree, les zone gardИes sont vИrifiИes pour toute piХce de mИmoire couramment existante qui a ИtИ allouИe par ckalloc. Ceci a un grand impact sur la performance et doit seulement Йtre utilisИ quand des problХmes d'Иcrasement sont sИrieusement suspectИs. L'avantage d'activer la validation mИmoire est qu'une zone gardИe ИcrasИe peut Йtre dИtectИe au premier appel de ckalloc ou ckfree suivant l'Иcrasement, plutТt que quand la mИmoire spИcifique avec la zone gardИe(s) ecrasИe(s) est libИrИe, ce qui peut arriver longtemps aprХs l'Иcrasement. +
    +

    memory trace_on_at_malloc count +
    Active le traГage mИmoire aprХs count ckalloc aient ИtИ effectuИs. Par exemple, si vous tapez memory trace_on_at_malloc 100, aprХs le 100Хme appel de ckalloc, l'information de trace mИmoire sera affichИe pour toute allocations et libИration. Comme il peut y avoir une grande activitИ mИmoire avant qu'un problХme se produise, un usage judicieux de cette option peut reduire le ralentissement causИ par le traГage (et le volume de trace produit), si vous pouvez identifier un nombre d'allocations effectuИes avant le problХme. Le nombre courant d'allocations mИmoire qui se sont produites depuis que Tcl a ИtИ lancИ est Иcrit dans une zone prИservИe des echecs. +
    +

    memory break_on_malloc count +
    AprХs que count allocations aient ИtИ effectuИes, ckalloc emet un message Ю cet effet et qui signale Иgalement qu'il tente de lancer le debugger C Tcl emet alors un signal SIGINT vers lui-mЙme. Si vous exИcutez Tcl sous un debugger C, le debugger doit alors entrer en mode commande. +
    +

    memory display file +
    Ecrit une liste de toute la mИmoire couramment allouИe dans le fichier spИcifiИ +
    +
    +

    +
    VOIR EGALEMENT

    +
    ckalloc, ckfree, Tcl_ValidateAllMemory, Tcl_DumpActiveMemory, TCL_MEM_DEBUG 

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/msgcat.htm b/hlp/fr/tcl/msgcat.htm new file mode 100644 index 0000000..6c5f438 --- /dev/null +++ b/hlp/fr/tcl/msgcat.htm @@ -0,0 +1,117 @@ +msgcat + + + +

    msgcat      Commandes Internes Tcl

    +
    +
    NOM

    +
    msgcat - catalogue de messages Tcl +

    +
    SYNTAXE

    +
    ::msgcat::mc src-string
    +::msgcat::mclocale ?newLocale?
    +::msgcat::mcpreferences
    +::msgcat::mcload dirname
    +::msgcat::mcset locale src-string ?translate-string?
    +::msgcat::mcunknown locale src-string +

    +
    DESCRIPTION

    +
    Le package msgcat fournit un ensemble de fonctions qui peuvent Йtre utilisИes pour gИrer des interfaces utilisateur multi-linguales. Les chaНnes de texte sont dИfinies dans un "catalogue de messages" qui est indИpendant de l'application, et qui peut Йtre editИ ou localisИ sans modifier le code source de l'application. Les nouvelles langues ou locales sont fournies en ajoutant un nouveau fichier au catalogue de messages.
    +
    L'usage du catalogue de messages est optionnel pour quelconque application ou package, mais est encouragИ si l'application ou package souhaite Йtre prЙt pour les applications multi-langues. +

    +
    COMMANDES

    +
    +
    +
    ::msgcat::mc src-string ?arg arg ...? +
    Renvoie une traduction de src-string en accord avec la locale de l'utilisateur courant. Si des arguments supplИmentaire aprХs src-string sont donnИs, la commande format est utilisИe pour substituer les arguments supplИmentaires dans la traduction de src-string ::msgcat::mc recherchera les messages dИfinis dans le namespace courant pour une traduction de src-string; si aucun n'est trouvИ, il recherchera dans le parent du namespace courant, et ainsi de suite jusqu'a ce qu'il atteigne le namespace global. Si aucune chaНne de traduction n'existe, ::msgcat::mcunknown est appelИ et la chaНne renvoyИe par ::msgcat::mcunknown est renvoyИe. +
    ::msgcat::mc est la fonction principale utilisИe pour localiser une application. Au lieu d'utiliser une chaНne Anglaise directement, une application peut passer la chaНne Anglaise au travers de ::msgcat::mc et utiliser le rИsultat. Si une application est Иcrite pour une seule langue de cette faГon, il est facile d'ajouter un support pour des langues supplИmentaires plus tard simplement en dИfinissant une nouvelle entrИe de catalogue de messages. +
    +

    ::msgcat::mclocale ?newLocale? +
    Cette fonction fixe locale Ю newLocale Si newLocale est omise, la locale courante est renvoyИe, autrement la locale courante est fixИe Ю newLocale. La locale initiale est par dИfaut la locale spИcifiИe dans l'environnement utilisateur. Voir SPECIFICATIONS LOCALE ET SUBLOCALE ci-dessous pour une description du format chaНne locale. +
    +

    ::msgcat::mcpreferences +
    Renvoie une liste ordonnИe des locales prefИrИes des utilisateurs, basИe sur la spИcification de langue de l'utilisateur. La liste est ordonnИe de la preference la plus spИcifique Ю la moins spИcifique. Si l'utilisateur a spИcifiИ LANG=en_US_funky, cette fonction retournera {en_US_funky en_US en}. +
    +

    ::msgcat::mcload dirname +
    Recherche dans le rИpertoire spИcifiИ les fichiers qui correspondent au spИcifications de langue renvoyИes par ::msgcat::mcpreferences. Chaque fichier trouvИ est "sourcИ". L'extension de fichier est ".msg". Le nombre de fichiers message qui satisfont la spИcification et ont ИtИ chargИs est renvoyИ.
    +

    ::msgcat::mcset locale src-string ?translate-string? +
    Fixe la traduction de src-string en translate-string dans la locale spИcifiИe Si translate-string n'est pas spИcifiИe, src-string est utilisИ pour les deux La fonction retourne translate-string. +
    +

    ::msgcat::mcunknown locale src-string +
    Cette routine est appelИe par ::msgcat::mc dans le cas oЫ une traduction de src-string n'est pas dИfinie dans la locale courante L'action par dИfaut est de renvoyer src-string Cette fonction peut Йtre redИfinie par les applications, par exemple pour mettre dans un journal de message d'erreurs chaque chaНne inconnue. La fonction::msgcat::mcunknown est appelИe dans le mЙme contexte de pile que l'appel de ::msgcat::mc La valeur de retour de ::msgcat::mcunknown est utilisИe comme la valeur de retour de l'appel de ::msgcat::mc. +
    +
    +
    +
    +
    SPECIFICATIONS LOCALE ET SUBLOCALE

    +
    La locale est spИcifiИe par une chaНne locale. La chaНne locale consiste en un code de langue, un code optionnel de pays, et un code optionnel spИcifique au systХme, chacun sИparИs par "_". Les codes de pays et de langue sont spИcifiИ dans les standards ISO-639 et ISO-3166. Par exemple, la locale "en" spИcifie Anglais et "en_US" spИcifie Anglais U.S..
    +
    La locale prend la valeur par dИfaut de env(LANG) Ю l'instant oЫ le package msgcat est chargИ. Si env(LANG) n'est pas dИfini, alors la locale prend la valeur par dИfaut de "C".
    +
    Quand une locale est spИcifiИe par les utilisateurs, une recherche "meilleure correspondance" est effectuИe pendant la traduction de la chaНne Par exemple, si un utilisateur spИcifie en_UK_Funky, les locales "en_UK_Funky", "en_UK", et "en" sont recherchИes dans l'ordre jusqu'a ce qu'une chaНne de traduction correspondante soit trouvИe Si aucune chaНne traduction n'est disponible, alors ::msgcat::unknown est appelИ +

    +
    NAMESPACES ET CATALOGUES DE MESSAGES

    +
    Les chaНnes stockИes dans le catalogue de messages sont stockИes relativement au namespace auquel elles ont ИtИ ajoutИes. Ceci permet Ю de multiple packages d'utiliser les mЙme chaНnes sans craindre de collisions avec d'autre packages. Cela permet aussi Ю la chaНne source d'Йtre plus courte et moins sujette aux fautes de frappes.
    +
    Par exemple, l'exИcution du code
    +
    mcset en hello "hello from ::"
    +namespace eval foo {mcset en hello "hello from ::foo"}
    +puts [mc hello]
    +namespace eval foo {puts [mc hello]}
    +
    affichera
    +
    hello from ::
    +hello from ::foo
    +
    Quand il cherche la traduction d'un message, le catalogue de messages recherchera en premier dans le namespace courant, ensuite le parent du namespace courant, et ainsi de suite jusqu'a ce que le namespace global  soit atteint Ceci permet aux namespaces enfants d'hИriter les messages de leurs namespace parents.
    +
    Par exemple, l'exИcution du code
    +
    mcset en m1 ":: message1"
    +mcset en m2 ":: message2"
    +mcset en m3 ":: message3"
    +namespace eval ::foo {
    +    mcset en m2 "::foo message2"
    +    mcset en m3 "::foo message3"
    +}
    +namespace eval ::foo::bar {
    +    mcset en m3 "::foo::bar message3"
    +}
    +puts "[mc m1]; [mc m2]; [mc m3]"
    +namespace eval ::foo {puts "[mc m1]; [mc m2]; [mc m3]"}
    +namespace eval ::foo::bar {puts "[mc m1]; [mc m2]; [mc m3]"}
    +
    affichera
    +
    :: message1; :: message2; :: message3
    +:: message1; ::foo message2; ::foo message3
    +:: message1; ::foo message2; ::foo::bar message3
    +
    +

    +
    EMPLACEMENT ET FORMAT DES FICHIERS DE MESSAGE

    +
    Les fichiers message peuvent Йtre situИs dans n'importe quel rИpertoire, soumis aux conditions suivantes:
    +
    [1]      Tous les fichiers message d'un package sont dans le mЙme rИpertoire.
    +
    [2]      Le nom de chemin du message est un spИcificateur de locale suivi par ".msg" Par exemple:
    +
                es.msg    -- spanish
    +            en_UK.msg -- UK English
    +
    [3]      Le fichier contient une series d'appels Ю mcset, qui fixent les chaНnes de traduction nИcessaires pour la langue. Par exemple:
    +
               ::msgcat::mcset es "Free Beer!" "Cerveza Gracias!"
    +
    +

    +
    PARAMETRAGE DES MESSAGES DANS LES PACKAGES

    +
    Si un package est installИ dans un sous rИpertoire de  tcl_pkgPath et chargИ via package require, les procИdures suivantes sont recommandИes.
    +
    [1]      Durant l'installation du package, crИer un sous rИpertoire msgs sous votre rИpertoire de package.
    +
    [2]      Copiez vos fichiers *.msg dans ce rИpertoire.
    +
    [3]       Ajoutez les commandes suivantes Ю votre script d'initialisation de package:
    +
             # charge les fichiers de langue, stockИs dans le sous rИpertoire msgs
    +         ::msgcat::mcload [file join [file dirname [info script]] msgs]
    +
    +
    CODES DE POSITION POUR LES COMMANDES FORMAT ET SCAN

    +
    Il est possible qu'un message chaНne utilisИ comme argument Ю format ait des paramХtres dИpendants de la position qui auraient besoin d'Йtre repositionnИs. Par exemple, il pourra Йtre syntaxiquement dИsirable de rИarranger la structure de cette phrase Ю la traduction.
    +
    format "Nous produisons %d unitИs sur le site %s" $num $city
    +format "Sur le site %s nous produisons %d unitИs" $city $num
    +
    Ceci peut Йtre gИrИ en utilisant les paramХtres positionels:
    +
    format " Nous produisons %1\$d unitИs sur le site %2\$s" $num $city
    +format " Sur le site %2\$s nous produisons %1\$d unitИs" $num $city
    +
    De mЙme, les paramХtres positionels peuvent Йtre utilisИs avec scan pour extraire des valeurs Ю partir de chaНnes internationalisИes
    +

    +
    CREDITS

    +
    Le code du catalogue de messages a ИtИ developpИ par Mark Harrison +

    +
    VOIR EGALEMENT

    +
    format(n), scan(n), namespace(n), package(n)

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/namespace.htm b/hlp/fr/tcl/namespace.htm new file mode 100644 index 0000000..8424828 --- /dev/null +++ b/hlp/fr/tcl/namespace.htm @@ -0,0 +1,195 @@ + + + + +

    namespace      Commandes Internes Tcl

    +
    +
    NOM

    +
    namespace - crИe et manipule des contextes pour les commandes et variables +

    +
    SYNTAXE

    +
    namespace ?option? ?arg ...? +

    +
    DESCRIPTION

    +
    La commande namespace vous permet de crИer, d'acceder, et de dИtruire des contextes sИparИs pour les commandes et variables. Voir la section QU'EST CE QU'UN NAMESPACE? ci-dessous pour un bref aperГu des namespaces. Les options lИgales sont listИes ci-dessous. Notez que vous pouvez abrИger les options. +
    +

    namespace children ?namespace? ?pattern? +
    Renvoie une liste de tous les namespaces enfants qui appartiennent Ю namespace. Si namespace n'est pas spИcifiИ, alors les enfants sont renvoyИs pour le namespace courant. Cette commande retourne des noms pleinement qualifiИs, qui commencent avec ::. Si l'option pattern est donnИe, alors cette commande retourne seulement les noms qui correspond au modХle glob-style. Le modХle actuel utilisИ est dИterminИ comme suit: un modХle qui commence avec :: est utilisИ directement, autrement le namespace namespace (ou le nom pleinement qualifiИ du namespace courant) est ajoutИ au modХle. +
    +

    namespace code script +
    Capture le contexte namespace courant pour une exИcution ultИrieure du script script. Retourne un nouveau script dans lequel script aura ИtИ englobИ dans une commande namespace code. Le nouveau script a deux propriИtИs importantes. D'abord, il peut Йtre ИvaluИ dans tout namespace et provoquera l'Иvaluation de script dans le namespace courant (celui oЫ la commande namespace code a ИtИ appelИe). +DeuxiХmement, des arguments supplИmentaires peuvent Йtre ajoutИs au script rИsultant et ils seront transmis Ю script comme arguments additionels. Par exemple, supposez que la commande set script [namespace code {foo bar}] est appelИe dans le namespace ::a::b. Ensuite eval "$script x y" peut Йtre exИcutИ dans tout namespace (en supposant que la valeur de script lui ait ИtИ transmise correctement) et aura le mЙme effet que la commande namespace eval ::a::b {foo bar x y}. Cette commande est nИcessaire parce que les extensions comme Tk exИcutent normalement les scripts callback dans le namespace global . Une commande visible capture une commande et son contexte namespace de faГon Ю l'exИcuter correctement plus tard. Voir la section VALEURS VISIBLES pour quelques exemples montrant comment l'utiliser pour crИer des scripts callback. +
    +

    namespace current +
    Renvoie le nom pleinement qualifiИ pour le namespace courant. Le nom actuel du namespace global est "" (ex., une chaНne vide), mais cette commande retourne :: pour le namespace global par convИnience pour les programmeurs. +
    +

    namespace delete ?namespace namespace ...? +
    Chaque namespace namespace est effacИ et toutes variables, fonctions, et namespaces enfants contenus dans le namespace sont effacИs. Si une fonction est en cours d'exИcution dans le namespace, le namespace sera maintenu jusqu'a ce que la fonction retourne; nИanmoins, le namespace est marquИ pour empЙcher tout autre code de le rechercher par son nom. Si un namespace n'existe pas, cette commande retourne une erreur. Si aucuns noms de namespace ne sont donnИs, cette commande ne fait rien. +
    +

    namespace eval namespace arg ?arg ...? +
    Active un namespace appelИ namespace et Иvalue tout code dans ce contexte. Si le namespace n'existe pas dИjЮ, il est crИИ. Si plus d'un argument arg est spИcifiИ, les arguments sont concatИnИs, sИparИs par des espaces de la mЙme faГon qu'avec la commande eval, et le rИsultat est ИvaluИ. +
    Si namespace a des qualificateurs namespace en tЙte et que les namespaces en tЙte n'existent pas, ils sont automatiquement crИИs. +
    +

    namespace export ?-clear? ?pattern pattern ...? +
    SpИcifie quelles commandes sont exportИes par un namespace. Le commandes exportИes sont celles qui peuvent Йtre plus tard importИes dans un autre namespace en utilisant une commande namespace import. L'ensembles des commandes dИfinies dans un namespace et des commandes que le namespace a prИcedemment importИ peut Йtre exportИ par un namespace. La commandes n'ont pas Ю Йtre dИfinies Ю l'instant oЫ la commande namespace export est exИcutИe. Chaque pattern peut contenir des caractХres spИciaux glob-style, mais il ne peut pas inclure quelconque qualificateurs namespace. Ainsi, le modХle peut seulement spИcifier des commandes dans le namespace courant (exportant). Chaque pattern est ajoutИ Ю la liste de modХles d'export du namespace. Si le flag -clear est donnИ, la liste de modХles d'export du namespace est rИinitialisИe en chaНne vide avant que quelconques pattern arguments soient ajoutИs. Si aucuns patterns ne sont donnИs et que le flag -clear n'est pas fourni, cette commande retourne la liste d'export du namespace courant. +
    +

    namespace forget ?pattern pattern ...? +
    RedИplace les commandes prИcedemment importИes d'un namespace. Chaque pattern est un nom qualifiИ tel que foo::x ou a::b::p*. Les noms qualifiИs contiennent des ::s et qualifient un nom avec le nom d'un ou plusieurs namespaces. Chaque pattern est qualifiИ avec le nom d'un namespace exportant et peut avoir des caractХres spИciaux glob-style dans le nom de commande Ю la fin du nom qualifiИ. Les caractХres glob ne peuvent pas apparaitre dans un nom de namespace. Cette commande trouve en premier les commandes exportИes correspondantes. Elle vИrifie ensuite si une ou plusieurs de ces commandes ont ИtИ prИcedemment importИes par le namespace courant. Si c'est le cas, cette commande efface les commandes importИes correspondantes. Ceci annule effectivement l'action d'une commande namespace import. +
    +

    namespace import ?-force? ?pattern pattern ...? +
    Importe des commandes dans un namespace. Chaque pattern est un nom qualifiИ comme foo::x ou a::p*. Ainsi, elle inclut le nom d'un namespace exportant et peut avoir des caractХres spИciaux glob-style dans le nom de commande Ю la fin du nom qualifiИ. Les caractХres glob ne peuvent pas apparaitre dans un nom de namespace. Toutes les commandes qui correspondent Ю une chaНne pattern et qui sont couramment exportИes de leurs namespace sont ajoutИes au namespace courant. Ceci est fait par crИation d'une nouvelle commande dans le namespace courant qui pointe vers la commande exportИe dans son namespace original; quand la nouvelle commande importИe est appelИe, elle appelle la commande exportИe. Cette commande normalement retourne une erreur si une commande importИe rentre en conflit avec une commande existante. NИanmoins, si l'option -force est donnИe, les commandes importИes remplaceront silencieusement les commandes existantes. La commande namespace import a une sИmantique photographique: ainsi, seulement les commandes requises couramment dИfinies dans le namespace exportant sont importИes. En d'autres mots, vous pouvez importer seulement les commandes qui sont dans un namespace Ю l'instant oЫ la commande namespace import est exИcutИe. Si une autre commande est dИfinie et exportИe dans ce namespace plus tard, elle ne sera pas importИe. +
    +

    namespace inscope namespace arg ?arg ...? +
    Execute un script dans le contexte d'un namespace particulier. Cette commande n'est pas sensИe Йtre utilisИ directement par les programmeurs; des appels sont gИnИrИs implicitement quand les applications utilisent la commande namespace code pour crИer scripts callback que l'applications alors enregistre avec, par ex., des widgets Tk. La commande namespace inscope ressemble plus Ю la commande namespace eval exceptИ qu'elle a une sИmantique lappend et que le namespace doit dИjЮ exister. Elle traite le premier argument comme une liste, et ajoute tout argument aprХs le premier jusqu'Ю la fin comme des ИlИments de liste correcte. namespace inscope ::foo a x y z est Иquivalent Ю namespace eval ::foo [concat a [list x y z]] Cette sИmantique lappend est importante parce que de nombreux scripts callback sont actuellement des prИfixes. +
    +

    namespace origin command +
    Renvoie le nom pleinement qualifiИ de la commande originale Ю laquelle la commande importИe command se rИfХre. Quand une commande est importИe dans un namespace, une nouvelle commande est crИИe dans ce namespace qui pointe vers la commande actuelle dans le namespace exportant. Si une commande est importИe dans une sИquence de namespaces a, b,...,n oЫ chaque namespace successif importe juste la commande du prИcedent namespace, cette commande retourne le nom pleinement qualifiИ de la commande originale dans le premier namespace, a. Si command ne se refХre pas Ю une commande importИe, le propre nom pleinement qualifiИ de la commande est renvoyИ. +
    +

    namespace parent ?namespace? +
    Renvoie le nom pleinement qualifiИ du namespace parent de namespace. Si namespace n'est pas spИcifiИ, le nom pleinement qualifiИ du parent du namespace courant est renvoyИ. +
    +

    namespace qualifiers string +
    Renvoie tous les qualificateurs namespace en tЙte de string. Les qualificateurs sont les noms de namespace sИparИes par ::. Pour la string ::foo::bar::x, cette commande retourne ::foo::bar, et pour :: elle retourne une chaНne vide. Cette commande est le complИment de la commande namespace tail. Notez qu'elle ne vИrifie pas si les noms de namespace sont, en fait, les noms des namespaces couramment dИfinis. +
    +

    namespace tail string +
    Renvoie le simple nom Ю la fin d'une chaНne qualifiИe. Les qualificateurs sont les noms de namespace sИparИes par ::. Pour la string ::foo::bar::x, cette commande retourne x, et for :: elle retourne une chaНne vide. Cette commande est le complement de la commande namespace qualifiers. Elle ne vИrifie pas si les noms de namespace sont, en fait, les noms des namespaces couramment dИfinis. +
    +

    namespace which ?-command? ?-variable? name +
    Recherche name soit comme commande ou variable et retourne son nom pleinement qualifiИ. Par exemple, si name n'existe pas dans le namespace courant mais existe dans le namespace global, cette commande retourne un nom pleinement qualifiИ dans le namespace global. Si la commande ou variable n'existe pas, cette commande retourne une chaНne vide. Si la variable a ИtИ crИИe mais non dИfinie, tel qu'avec la commande variable ou au travers d'une trace sur la variable, cette commande renverra le nom pleinement qualifiИ de la variable. Si aucun flag n'est donnИ, name est traitИ comme un nom de commande. Voir la section RESOLUTION DE NOM ci-dessous pour une explication des rХgles concernant la rИsolution de nom. +
    +
    +

    +
    QU'EST CE QU'UN NAMESPACE?

    +
    Un namespace est une collection de commandes et de variables. Il encapsule les commandes et variables pour s'assurer qu'elles ne vont pas interfИrer avec les commandes et variables des autres namespaces. Tcl a toujours eu une telle collection, Ю laquelle nous nous rИfХrerons comme le namespace global. Le namespace global contient toutes les variables globales et commandes. La commande namespace eval vous permet de crИer de nouveaux namespaces. Par exemple,
    +
    +namespace eval Counter {
    +
    namespace export bump
    +
    variable num 0
    +

    +
    proc bump {} {
    +
    variable num
    +
    incr num
    +
    }
    +
    }
    +
    crИe un nouveau namespace contenant la variable num et la fonction bump. Les commandes et les variables dans ce namespace sont sИparИes des autres commandes et variables dans le mЙme programme. S'il y a une commande nommИe bump dans le namespace global , par exemple, elle sera diffИrente de la commande bump dans le namespace Counter.
    +
    Les variables namespace ressemblent aux variables globales en Tcl. Elles existent en dehors des fonctions dans un namespace mais peuvent Йtre accИdИes dans une fonction via la commande variable, comme montrИ dans l'exemple ci-dessus.
    +
    Les namespaces sont dynamiques. Vous pouvez ajouter et effacer des commandes et des variables Ю tout instant, et vous pouvez construire le contenu d'un namespace au fur et Ю mesure en utilisant une sИrie de commandes namespace eval. Par exemple, les sИries suivantes de commandes ont le mЙme effet que les dИfinitions namespace montrИes plus haut:
    +
    +namespace eval Counter {
    +
    variable num 0
    +
    proc bump {} {
    +
    variable num
    +
    return [incr num]
    +
    }
    +
    }
    +
    namespace eval Counter {
    +
    proc test {args} {
    +
    return $args
    +
    }
    +
    }
    +
    namespace eval Counter {
    +
    rename test ""
    +
    }
    +
    Notez que la fonction test est ajoutИe au namespace Counter, et enlevИe plus tard via la commande rename.
    +
    Les namespaces peuvent contenir d'autres namespaces, donc Йtre imbriquИs hiИrarchiquement. Un namespace imbriquИ est encapsulИ dans son namespace parent et ne peut pas interfИrer avec d'autres namespaces.
    +

    +
    NOMS QUALIFIES

    +
    Chaque namespace a un nom textuel tel que history ou ::safe::interp. Comme les namespaces peuvent s'imbriquer, les noms qualifiИs sont utilisИs pour se rИfИrer Ю des commandes, variables, et namespaces enfants contenus dans les namespaces. Les noms qualifiИs sont semblables aux noms de chemin hiИrarchique des fichiers Unix ou des widgets Tk, exceptИ que :: est utilisИ comme sИparateur au lieu de '/' ou '.'. Le namespace global a pour nom "" (ex., une chaНne vide), bien que :: soit un synonyme. Comme exemple, le nom ::safe::interp::create se rИfХre Ю la commande create dans le namespace interp qui est un enfant du namespace ::safe, qui Ю son tour est un enfant du namespace global ::.
    +
    Si vous voulez Ю acceder aux commandes et variables Ю partir d'un autre namespace, vous devez utiliser une syntaxe supplИmentaire. Les noms doivent Йtre qualifiИs par les namespace qui les contiennent. A partir du namespace global , nous accХderions Ю la fonction Counter comme ceci:
    +

    +Counter::bump 5
    +
    Counter::Reset

    +
    Nous accХderions au compte courant comme ceci:

    +
    puts "count = $Counter::num"

    +
    Quand un namespace en contient un autre, vous pouvez avoir besoin de plus d'un qualificateur pour atteindre ses ИlИments. Si nous avions un namespace Foo qui contenait le namespace Counter, vous pourriez appeller sa fonction bump Ю partir du namespace global comme ceci:
    +
    Foo::Counter::bump 3
    +
    Vous pouvez aussi utiliser les noms qualifiИs quand vous crИez et renommez des commandes. Par exemple, vous pouvez ajouter une fonction au namespace Foo comme ceci:
    +
    proc Foo::Test {args} {return $args}
    +
    Et vous pourriez dИplacer la mЙme fonction vers un autre namespace comme ceci:
    +
    rename Foo::Test Bar::Test
    +
    Il y a quelques points restants au sujet des noms qualifiИs que nous devons couvrir. Les namespaces ont des noms non-vides exceptИ le namespace global . '::' est interdit dans une simple commande, variable, et les noms de namespace exceptИ comme sИparateur namespace. Les ':' supplИmentaires dans un nom qualifiИ sont ignorИs; ainsi, deux ou plus ':' sont traitИs comme sИparateur namespace. Deux '::' Ю la fin d'une variable qualifiИe ou d'un nom de commande se rИfХrent Ю une variable ou commande nommИe {}. NИanmoins, :: Ю la fin d'un nom de namespace qualifiИ est ignorИ. +

    +
    RESOLUTION DE NOM

    +
    En gИnИral, toute commande Tcl qui attend des noms de variable et de commande supporte les noms qualifiИs. Ceci signifie que vous pouvez donner des noms qualifiИs Ю des commandes comme set, proc, rename, et interp alias. Si vous fournissez un nom pleinement qualifiИ qui commence avec ::, il n'y a pas d'ambiguitИ sur le sens de la commande, la variable, ou le namespace. NИanmoins, si le nom ne commence pas avec :: (ex., est relatif), Tcl suit une rХgle prИcise pour la recherche: Les noms de commandes et nom de variables sont toujours rИsolus en cherchant en premier dans le namespace courant, et ensuite dans le namespace global . Les noms de namespace, d'un autre point de vue, sont toujours rИsolus en recherchant seulement dans le namespace courant.
    +
    Dans les exemples suivants,
    +
    set traceLevel 0
    +
    namespace eval Debug {
    +
    printTrace $traceLevel
    +
    }
    +
    Tcl recherche traceLevel dans le namespace Debug et ensuite dans le namespace global. Il recherche la commande printTrace de la mЙme faГon. Si un nom de variable ou de commande n'est pas trouvИ dans ce contexte, le nom est indИfini. Pour rendre ce point tout Ю fait clair, examinez les exemples suivants:
    +
    set traceLevel 0
    +
    namespace eval Foo {
    +
    variable traceLevel 3
    +

    +
    namespace eval Debug {
    +
    printTrace $traceLevel
    +
    }
    +
    }
    +
    Ici, Tcl recherche traceLevel en premier dans le namespace Foo::Debug. Comme il n'est pas trouvИ lЮ, Tcl le recherche alors dans le namespace global . La variable Foo::traceLevel est complХtement ignorИe pendant le processus de rИsolution de nom.
    +
    Vous pouvez utiliser la commande namespace which pour repondre aux questions au sujet de la rИsolution de nom. Par exemple, la commande:
    +
    namespace eval Foo::Debug {namespace which-variable traceLevel}
    +
    retourne ::traceLevel. d'une autre maniХre, la commande,
    +
    namespace eval Foo {namespace which-variable traceLevel}
    +
    retourne ::Foo::traceLevel.
    +
    Comme mentionnИ plus haut, les noms de namespace sont recherchИs diffИremment des noms de variables et commandes. Les noms de namespace sont toujours rИsolus dans le namespace courant. Ceci signifie que, par exemple, une commande namespace eval qui crИe un nouveau namespace crИe toujours un enfant du namespace courant Ю moins que le nouveau nom de namespace commence avec un ::.
    +
    Tcl n'a pas de contrТle pour limiter quelles variables, commandes, ou namespaces vous pouvez rИfИrencer. Si vous fournissez un nom qualifiИ qui resolve un ИlИment par les rХgles de rИsolution de nom plus haut, vous pouvez accИder Ю l'ИlИment.
    +
    Vous pouvez accИder Ю une variable namespace Ю partir d'une fonction dans le mЙme namespace en utilisant la commande variable. Comme la commande global, elle crИe un lien local vers une variable namespace. Si nИcessaire, elle crИe aussi la variable dans le namespace courant et l'initialise. Notez que la commande global crИe seulement des liens vers les variables dans le namespace global . Il n'est pas nИcessaire d'utiliser une commande variable si vous vous referez toujours Ю une variable namespace en utilisant un nom qualifiИ appropriИ. +

    +
    IMPORTATION DE COMMANDES

    +
    Les namespaces sont souvent utilisИs pour reprИsenter des bibliothХques. Certaines commandes de bibliothХque sont utilisИes si souvent que c'est une corvИe de taper leurs noms qualifiИs. Par exemple, supposez que toutes les commandes dans un package comme BLT soient contenues dans un namespace appelИ Blt. Ensuite vous accХderez Ю ces commandes comme ceci:
    +
    Blt::graph .g-background red
    +
    Blt::table . .g 0,0
    +
    Si vous utilisez les commandes graph et table frИquemment, vous pouvez vouloir y acceder sans le prИfixe Blt::. Vous pouvez faire cela en important les commandes dans le namespace courant, comme ceci:
    +
    namespace import Blt::*
    +
    Ceci ajoute toutes les commandes exportИes du namespace Blt dans le contexte du namespace courant, donc vous pouvez Иcrire du code comme ceci:
    +
    graph .g-background red
    +
    table . .g 0,0
    +
    La commande namespace import importe seulement des commandes d'un namespace exportИ avec une commande namespace export.
    +
    Importer toutes les commandes d'un namespace est gИnИralement une mauvaise idИe car vous ne savez pas ce que vous rИcupИrez. Il vaut mieux importer juste les commandes spИcifiques dont vous avez besoin. Par exemple, la commande
    +
    namespace import Blt::graph Blt::table
    +
    importe seulement les commandes graph et table dans le contexte courant.
    +
    Si vous essayez d'importer une commande qui existe dИjЮ, vous aurez une erreur. Ceci vous empЙche d'importer la mЙme commande Ю partir de deux packages diffИrent. Mais de temps en temps (peut-Йtre en debuggant), vous pouvez vouloir contourner cette restriction. Vous pouvez vouloir relancer la commande namespace import pour profiter de nouvelles commandes qui ont apparu dans un namespace. Dans ce cas, vous pouvez utiliser l'option -force, et les commandes existantes seront ecrasИes silencieusement:
    +
    namespace import-force Blt::graph Blt::table
    +
    Si pour quelque raison, vous voulez cesser d'utiliser les commandes importИes, vous pouvez les enlever avec une commande namespace forget, comme ceci:
    +
    namespace forget Blt::*
    +
    Ceci recherche dans le namespace courant toutes commandes importИes de Blt. Si elle en trouve une, elle l'enlХve. Autrement, elle ne fait rien. AprХs cela, les commandes Blt doivent Йtre accИdИes avec le prИfixe Blt::.
    +
    Quand vous effacez une commande du namespace exportant comme ceci:
    +
    rename Blt::graph ""
    +
    la commande est automatiquement enlevИe de tous les namespaces qui l'importaient. +

    +
    EXPORTATION DE COMMANDES

    +
    Vous pouvez exporter des commandes d'un namespace comme ceci:
    +
    namespace eval Counter {
    +
    namespace export bump reset
    +
    variable Num 0
    +
    variable Max 100
    +

    +
    proc bump {{by 1}} {
    +
    variable Num
    +
    incr Num $by
    +
    Check
    +
    return $Num
    +
    }
    +
    proc reset {} {
    +
    variable Num
    +
    set Num 0
    +
    }
    +
    proc Check {} {
    +
    variable Num
    +
    variable Max
    +
    if {$Num > $Max} {
    +
    error "too high!"
    +
    }
    +
    }
    +
    }
    +
    Les fonctions bump et reset sont exportИes, donc elles sont inclues quand vous importez du namespace Counter, comme ceci:
    +
    namespace import Counter::*
    +
    NИanmoins, la fonction Check n'est pas exportИe, donc elle est ignorИe par les opИrations d'import.
    +
    La commande namespace import importe seulement les commandes qui ont ИtИ declarИs comme exportИes par leurs namespace. La commande namespace export spИcifie quelles commandes peuvent Йtre importИes par d'autres namespaces. Si une commande namespace import spИcifie une commande qui n'est pas exportИe, la commande n'est pas importИe. +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 8.0

    +
    +
    + diff --git a/hlp/fr/tcl/open.htm b/hlp/fr/tcl/open.htm new file mode 100644 index 0000000..a274ec7 --- /dev/null +++ b/hlp/fr/tcl/open.htm @@ -0,0 +1,93 @@ + + + + +

    open      Commandes Internes Tcl

    +
    +
    NOM

    +
    open - Ouvre un canal basИ fichier ou un pipeline +

    +
    SYNTAXE

    +

    +open fileName
    +open fileName access
    +open fileName access permissions +

    +
    DESCRIPTION

    +
    Cette commande ouvre un fichier, un port sИrie, ou un pipeline de commandes et retourne un identificateur de canal qui peut Йtre employИ dans les appels suivants des commandes comme read, puts, et close. Si le premier caractХre de fileName n'est pas | alors la commande ouvre un fichier: fileName donne le nom du fichier Ю ouvrir, et il doit se conformer aux conventions dИcrite dans la page de manuel filename.
    +
    L'argument access, si prИsent, indique la faГon de laquelle le fichier (ou commande pipeline) sera accИdИ. Dans la premiХre forme access peut avoir quelconque des valeurs suivantes: +
    +
    r
    Ouvre le fichier pour la lecture seulement; le fichier doit dИjЮ exister. C'est la valeur par dИfaut si access n'est pas spИcifiИ. +
    +
    r+
    Ouvre le fichier pour la lecture et l'Иcriture; le fichier doit dИjЮ exister. +
    +
    w
    Ouvre le fichier pour l'Иcriture seulement. Le tronque s'il existe. S'il n'existe pas, crИe un nouveau fichier. +
    +
    w+
    Ouvre le fichier pour la lecture et l'Иcriture. Le tronque s'il existe. S'il n'existe pas, crИe un nouveau fichier. +
    +
    a
    Ouvre le fichier pour l'Иcriture seulement. Si le fichier n'existe pas, crИe un nouveau fichier vide. Positionne le curseur Ю la fin du fichier. +
    +
    a+
    Ouvre le fichier pour la lecture et l'Иcriture. Si le fichier n'existe pas, crИe un nouveau fichier vide. Positionne le curseur Ю la fin du fichier. +
    +
    +
    +
    Dans la seconde forme, access consiste en une liste de quelconque des flags suivants, chacun d'eux ayant la signification standard POSIX. Un des flags doit Йtre soit RDONLY, WRONLY ou RDWR. +
    +
    RDONLY
    Ouvre le fichier pour la lecture seulement.
    +
    WRONLY
    Ouvre le fichier pour l'Иcriture seulement.
    +
    RDWR
    Ouvre le fichier en lecture et Иcriture.
    +
    APPEND
    Positionne le curseur Ю la fin du fichier avant chaque Иcriture.
    +
    CREAT
    CrИe le fichier s'il n'existe pas dИjЮ.
    +
    EXCL
    Si CREAT est Иgalement spИcifiИ, une erreur est gИnИrИe si le fichier existe dИjЮ. +
    +
    NOCTTY
    Si le fichier est un terminal, ce flag empЙche le fichier de devenir le terminal de contrТle du processus. +
    +
    NONBLOCK
    EmpЙche le processus de bloquer pendant l'ouverture du fichier, et eventuellement pendant les opИrations I/O suivantes. Le comportement exact de ce flag est systХme- et pИriphИrique-dependant; son emploi est dИconseillИ (il vaut mieux utiliser la commande fconfigure pour mettre un fichier en mode non bloquant). Pour des dИtails se referer Ю la documentation de votre systХme sur le flag O_NONBLOCK de l'appel systХme open +
    +
    TRUNC
    Si le fichier existe il est tronquИ Ю longueur zИro. +
    +
    +
    +
    Si un nouveau fichier est crИИ en mЙme temps qu'ouvert, permissions (un entier) est utilisИ pour fixer les permissions pour le nouveau fichier en conjonction avec le masque de crИation fichier. Permissions est par dИfaut de 0666. +

    +
    PIPELINES

    +
    Si le premier caractХre de fileName est "|" alors les caractХres restants de fileName sont traitИs comme une liste d'arguments qui decrivent un pipeline Ю appeler, dans le mЙme style que les arguments Ю exec. Dans ce cas, l'identificateur de canal renvoyИ par open peut Йtre employИ pour Иcrire Ю l'entrИe du pipe ou lire de sa sortie, dИpendant de la valeur de access. Si un accХs Иcriture-seule est utilisИ (ex. access est w), alors la sortie standard du pipeline est dirigИe vers la sortie standard courante sauf si ecrasИ par la commande. Si un accХs lecture-seule est utilisИ (ex. access est r), l'entrИe standard du pipeline est prise de l'entrИe standard courante sauf si ecrasИ par la commande. +

    +
    COMMUNICATIONS SERIE

    +
    Si fileName se refХre Ю un port sИrie, alors le port sИrie spИcifiИ est ouvert et initialisИ d'une maniХre plateforme-dependante. Les valeurs acceptables de fileName pour ouvrir un port sИrie sont dИcrites dans la section PROBLEMES DE PORTABILITE. +

    +
    OPTIONS DE CONFIGURATION

    +
    La commande fconfigure peut Йtre utilisИe pour consulter et fixer les options de configuration suivantes pour ouvrir un port sИrie: +
    +
    -mode baud,parity,data,stop
    Cette option est un ensemble de 4 valeurs sИparИes par des virgules: le baud rate, paritИ, nombre de bits de donnИes, et nombre de bits stop pour ce port sИrie. Le baud rate est un simple entier qui spИcifie la vitesse de connection. Parity est une des lettres suivantes: n, o, e, m, s; signifiant respectivement les options de paritИ "aucune", "impaire", "paire", "marque", ou "espace". Data est le nombre de bits de donnИes et sera un entier de 5 Ю 8, alors que stop est le nombre de bits de stop et sera l'entier 1 ou 2. +
    +
    -pollinterval msec
    Cette option, disponible seulement sous Windows pour les port sИries, est utilisИe pour fixer le temps maximum entre l'ecoute d'ИvХnements fichier. Ceci affecte le intervalle de temps de vИrification d'ИvХnements par l'interprИteur Tcl (la plus petite valeur l'emporte toujours). Utilisez cette option seulement si vous voulez Иcouter le port sИrie plus souvent que 10 msec (la valeur par dИfaut). +
    +
    -lasterror
    Cette option est disponible seulement sous Windows pour les port sИries, et est en lecture seule (ne peut Йtre que signalИe). En cas d'une erreur de communication sИrie, read ou puts retourne une erreur Tcl gИnИrale I/O fichier. fconfigure -lasterror peut Йtre appelИe pour obtenir une liste des details d'erreur (ex. FRAME RXOVER). +
    +
    +

    +
    PROBLEMES DE PORTABILITE

    +
    +
    +
    Windows (toutes versions)
    Les valeurs valides de fileName pour ouvrir un port sИrie sont de la forme comX:, where X est un nombre, gИnИralement de 1 Ю 4. Cette notation fonctionne seulement pour les port sИries de 1 Ю 9, si le systХme en a plus que quatre. Une tentative d'ouvrir un port sИrie qui n'existe pas ou a un nombre supИrieur Ю 9 Иchouera. Une forme alternative d'ouvrir des port sИries est d'utiliser le nom de fichier \\.\comX, oЫ X est un nombre quelconque qui correspond Ю un port sИrie; veuillez noter que cette mИthode est considerablement plus lente sous Windows 95 et Windows 98. +
    +
    Windows NT
    Quand vous exИcutez Tcl interactivement, il peut y avoir des interactions Иtranges entre la console rИelle, si elle est prИsente, et une commande pipeline qui utilise l'entrИe ou la sortie standard. Si une commande pipeline est ouverte pour la lecture, toutes les lignes entrИes sur la console seront envoyИes Ю la commande pipeline puis Ю l'evaluateur Tcl. Si une commande pipeline est ouverte pour l'Иcriture, les frappes de touches entrИes sur la console ne seront pas visible jusqu'a ce que le le pipe soit fermИ. Ce comportement se produit si la commande pipeline est une application 16-bit ou 32-bit. Ces problХmes se produisent seulement parce que Ю la fois Tcl et application enfant essayent d'acceder Ю la console en mЙme temps. Si la commande pipeline est lancИe Ю partir d'un script, Tcl n'accХde pas Ю la console, ou si la commande pipeline n'utilise pas l'entrИe ou la sortie, standard mais est redirigИe Ю partir ou vers un fichier, alors les problХmes vus plus haut ne se produisent pas.
    +
    Windows 95
    Une commande pipeline qui exИcute une application DOS 16-bit ne peut pas Йtre ouvert en lecture et Иcriture, car les applications DOS 16-bit qui recoivent l'entrИe standard d'un pipe et envoient la sortie standard dans un pipe sont exИcutИes de maniХre synchrone. Les commande pipelines qui n'exИcutent pas d'applications DOS 16-bit sont exИcutИes de maniХre asynchrone et peuvent Йtre ouvertes en lecture et Иcriture.
    +Quand vous exИcutez Tcl interactivement, il peut y avoir des interactions Иtranges entre la console rИelle, si elle est prИsente, et une commande pipeline qui utilise l'entrИe ou la sortie standard. Si une commande pipeline est ouvert pour la lecture Ю partir d'une application 32-bit, , les frappes de touches entrИes sur la console seront envoyИes Ю la commande pipeline et puis Ю l'evaluateur Tcl. Si une commande pipeline est ouvert pour l'Иcriture sur une application 32-bit, aucune sortie n'est visible sur la console jusqu'a ce que le le pipe soit fermИ. Ces problХmes se produisent seulement parce que Ю la fois Tcl et application enfant essayent d'acceder Ю la console en mЙme temps. Si la commande pipeline est lancИe Ю partir d'un script, Tcl n'accХde pas Ю la console, ou si la commande pipeline n'utilise pas l'entrИe ou la sortie, standard mais est redirigИe Ю partir ou vers un fichier, alors les problХmes vus plus haut ne se produisent pas. +Que Tcl s'exИcute interactivement ou non, si une commande pipeline est ouvert pour la lecture Ю partir une application 16-bit DOS, l'appel de open ne retourne pas jusqu'a ce que la fin-de-fichier avoir ИtИ transmise Ю la sortie standard du pipeline. Si un pipeline est ouvert pour l'Иcriture sur une application 16-bit DOS, aucune donnИe ne sera envoyИes Ю la sortie standard du pipeline jusqu'a ce que le pipe soit fermИ. Ce problХme se produit parce que les applications 16-bit DOS sont exИcutИes de maniХre synchrone, comme dИcrit plus haut. +
    +
    Macintosh
    Ouvrir un port sИrie n'est pas encore implИmentИ sous Macintosh.
    +Ouvrir un pipeline n'est pas supportИ sous Macintosh, car les applications ne supportent pas le concept d'entrИe ou de sortie standard. +
    +
    Unix
    Les valeurs valides de fileName pour ouvrir un port sИrie sont gИnИralement de la forme /dev/ttyX, oЫ X est a ou b, mais le nom de tout pseudo-fichier qui pointe vers un port sИrie peut Йtre employИ.
    +Quand vous exИcutez Tcl interactivement, il peut y avoir des interactions Иtranges entre la console rИelle, si elle est prИsente, et une commande pipeline qui utilise l'entrИe ou la sortie standard. Si une commande pipeline est ouvert pour la lecture, toutes lignes entrИes sur la console seront envoyИes au pipeline et puis Ю l'evaluateur Tcl. Ces problХmes se produisent seulement parce que Ю la fois Tcl et application enfant essayent d'acceder Ю la console en mЙme temps. Si la commande pipeline lancИe Ю partir d'un script, Tcl n'accХde pas Ю la console, ou si la commande pipeline n'utilise pas l'entrИe ou la sortie, standard mais est redirigИe Ю partir ou vers un fichier, alors les problХmes vus plus haut ne se produisent pas. Voir la section PROBLEMES DE PORTABILITE de la commande exec pour une information supplИmentaire non spИcifique au pipelines au sujet de l'exИcution d'applications sur les diffИrentes plateformes +
    +
    +

    +
    VOIR EGALEMENT

    +
    close(n), filename(n), gets(n), read(n), puts(n), exec(n)
    +
    DerniХre rИvision: 7.6

    +
    +
    + diff --git a/hlp/fr/tcl/package.htm b/hlp/fr/tcl/package.htm new file mode 100644 index 0000000..c1f1fab --- /dev/null +++ b/hlp/fr/tcl/package.htm @@ -0,0 +1,56 @@ + + + + +

    package      Commandes Internes Tcl

    +
    +
    NOM

    +
    package - UtilitИs pour le chargement et le contrТle de version de package +

    +
    SYNTAXE

    +
    package forget ?package package ...?
    +package ifneeded package version ?script?
    +package names
    +package present ?-exact? package ?version?
    +package provide package ?version?
    +package require ?-exact? package ?version?
    +package unknown ?command?
    +package vcompare version1 version2
    +package versions package
    +package vsatisfies version1 version2
    +

    +
    DESCRIPTION

    +
    Cette commande maintient une base de donnИes simple des packages disponibles pour l'interprИteur courant et comment les charger dans l'interprИteur. Elle supporte plusieurs versions de chaque package et prИpare la version correcte d'un package Ю Йtre chargИe en se basant sur ce qui est nИcessaire pour l'application. Cette commande detecte et rapporte aussi les conflits de version. Typiquement, seules les commandes package require et package provide sont appelИes dans les scriptsTcl normaux, les autres commandes sont utilisИes par les scripts systХme qui maintiennent la base de donnИes des packages.
    +
    Le comportement de la commande package est dИterminИ par son premier argument. Les formes suivantes sont permises: +
    +
    package forget ?package package ...?
    Efface toute information concernant chaque package spИcifiИ de cet interprИteur, incluant l'information fournie par package ifneeded et package provide. +
    +
    package ifneeded package version ?script?
    Cette commande apparait seulement dans les scripts de configuration systХme pour rИparer la base de donnИes des packages. Elle indique qu'une version particuliХre d'un package est disponible si besoin, et que le package peut Йtre ajoutИ Ю l'interprИteur par l'exИcution de script. Le script est sauvegardИs dans une base de donnИes pour Йtre utilisИ par les commandes suivantes package require typiquement, script parmХtre l'auto-loading pour les commandes dans le package (ou appelle load et/ou source directement), et ensuite appelle package provide pour indiquer que le package est prИsent. Il peut y avoir l'information dans la base de donnИes pour plusieurs versions diffИrentes d'un seul package. Si la base de donnИes contient dИjЮ l'information pour package et version, le nouveau script remplace l'existant. Si l'argument script est omis, le script courant pour la version version du package package est renvoyИ, ou une chaНne vide si aucune commande package ifneeded a ИtИ appelИe pour ces package et version. +
    +
    package names
    Renvoie une liste des noms de tous les packages dans l'interprИteur pour lequel une version a ИtИ fournie (via package provide) ou pour lequel un script package ifneeded est disponible. L'ordre des ИlИments dans la liste est arbitraire. +
    +
    package present ?-exact? package ?version?
    Cette commande est Иquivalente Ю package require exceptИ qu'elle n'essaye pas et charge le package s'il n'est pas dИjЮ chargИ. +
    +
    package provide package ?version?
    Cette commande est appelИe pour indiquer quelle version version du package package est maintenant prИsente dans l'interprИteur. Elle est typiquement appelИe une fois comme partie d'un script ifneeded, et de nouveau par les package lui-mЙme quand il est finalement chargИ. Un erreur se produit si une version diffИrente de package a ИtИ fournie par une prИcИdente commande package provide. Si l'argument version est omis, alors la commande retourne le numИro de version qui est couramment fourni, ou une chaНne vide si aucune commande package provide n'a ИtИ appelИe pour package dans cet interprИteur. +
    +
    package require ?-exact? package ?version?
    Cette commande est typiquement appelИe par le code Tcl qui souhaite utiliser une version particuliХre d'un package. Les arguments indiquent quel package est demandИ, et la commande assure qu'une version convenable du package est chargИ dans l'interprИteur. Si la commande rИussit, elle retourne le numИro de version qui est chargИ autrement elle gИnХre une erreur. Si le switch - exact et l'argument version sont spИcifiИs alors seulement la version donnИe est admise. Si -exact est omis mais que version est spИcifiИ, alors les versions supИrieures Ю version sont aussi admises tant qu'elles ont le mЙme numИro de version majeure que version. Si -exact et version sont omis alors toute version est acceptable. Si une version de package a dИjЮ ИtИ fournie (en appelant l commande package provide), alors son numИro de version doit satisfaire les critХres donnИs par -exact et version et la commande retourne immИdiatement. Autrement, la commande recherche la base de donnИes d'information fournie par les prИcedentes commandes package ifneeded pour voir si une version acceptable du package est disponible. Si c'est le cas, le script avec le numИro de version acceptable le plus ХlevИ est appelИ; elle doit faire tout ce qui est nИcessaire pour charger le package, incluant l'appel de package provide pour le package. Si la base de donnИes package ifneeded ne contient pas de version acceptable du package et qu'une commande package unknown a ИtИ spИcifiИe pour l'interprИteur alors cette commande est appelИe;Й quand elle se termine, Tcl vИrifie de nouveau si le package est maintenant fourni ou s'il y a un script package ifneeded pour celui-ci. Si toutes ces Иtapes Иchouent pour fournir une version acceptable du package, alors la commande retourne une erreur. +
    +
    package unknown ?command?
    Cette commande apporte une commande "de la derniХre chance" Ю appeler pendant package require si aucune version convenable d'un package ne peut Йtre trouvИe dans la base de donnИes package ifneeded. Si l'argument command est fourni, il contient la premiХre partieЙ d'une commande;Й quand la commande est appelИe pendant une commande package require, Tcl ajoute deux arguments supplИmentaires donnant les nom et version du package dИsirИ. Par exemple, si command est foo bar et que plus tard la commande package require test 2.4 est appelИe, alors Tcl exИcutera la commande foo bar test 2.4 pour charger le package. Si aucun numИro de version n'est donnИ Ю la commande package require, alors l'argument version pour la commande appelИe sera une chaНne vide. Si la commande package unknown est appelИe sans argument command, alors le courant script package unknown est renvoyИ, ou une chaНne vide s'il n'existe pas. Si command est spИcifiИ comme chaНne vide, alors le courant script package unknown est enlevИ, s'il existe. +
    +
    package vcompare version1 version2
    Compare les numИros de versions donnИs par version1 et version2. Renvoie -1 si version1 est une version prИcИdente Ю version2, 0 si ils sont Иgal, et 1 si version1 est plus rИcente que version2. +
    +
    package versions package
    Renvoie une liste de tout les numИros de versions de package pour lequel l'information a ИtИ fournie par des commandes package ifneeded. +
    +
    package vsatisfies version1 version2
    Renvoie 1 si les scripts Иcrits pour version2 fonctionneront avec version1 (ex. version1 est Иgal Ю ou supИrieur Ю version2 et elles ont le mЙme numИro de version majeure), 0 autrement. +
    +
    +
    +
    NUMEROS DE VERSION

    +
    Les numИros de version consistent en un ou plusieurs nombres dИcimaux sИparИs par des points, tel que 2 ou 1.162 ou 3.1.13.1. Le premier nombre est appelИ le numИro de version majeure. Des nombres supИrieurs correspondentЙ Ю des versions ultИrieures d'un package, avec le nombre le plus Ю gauche plus significatif. Par exemple, la version 2.1 est ultИrieure Ю 1.3 et version 3.4.6 est ultИrieure Ю 3.3.5. Les champs manquants sont Иquivalent Ю zИros:Й la version 1.3 est la mЙme que la version 1.3.0 et 1.3.0.0, donc elle est antИrieure Ю 1.3.1 ou 1.3.0.2. Un numИro de version ultИrieur est supposИ Йtre compatible avec un numИro de version prИcИdent tant que les deux versions ont le mЙme numИro de version majeure. Par exemple, les scripts Tcl Иcrits pour la version 2.3 d'un package devraient fonctionner sous les versions 2.3.2, 2.4, et 2.5.1. Les changements dans le numИro de version majeure signifient des changements incompatible: si le code est Иcrit pour utiliser la version 2.1 d'un package, it n'est pas garanti qu'il fonctionne non modifiИ avec soit la version 1.7.3 soit la version 3.1.Й
    +

    +
    INDEX DE PACKAGES

    +
    La maniХre recommandИe d'utiliser les packages en Tcl est d'appeler les commandes package require et package provide dans les scripts, et d'utiliser la fonction pkg_mkIndex pour crИer des fichiers index de package. Une fois que vous avez fait ceci, les packages seront chargИs automatiquement en rИponse aux commandes package require. Voir la documentation d pkg_mkIndex pour les dИtails.

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/package_create.htm b/hlp/fr/tcl/package_create.htm new file mode 100644 index 0000000..b20172a --- /dev/null +++ b/hlp/fr/tcl/package_create.htm @@ -0,0 +1,30 @@ + + + + +

    pkg::create      Commandes Internes Tcl

    +
    +
    NOM

    +
    pkg::create √ Construit une commande package ifneeded appropriИe pour un package donnИ +

    +
    SYNTAXE

    +
    ::pkg::create -name packageName -version packageVersion ?-load filespec? ... ?-source filespec? ... +

    +
    DESCRIPTION

    +
    ::pkg::create est une fonction utilitaire qui fait partie de la bibliothХque standard Tcl. Elle est utilisИe pour crИer une commande package ifneeded appropriИe pour une spИcification de package donnИe. Elle peut Йtre utilisИe pour construire un fichier pkgIndex.tcl utilisИ avec le mИcanisme package. +

    +
    OPTIONS

    +
    Les paramХtres supportИs sont: +
    +
    -name packageName
    Ce paramХtre spИcifie le nom du package. Il est requis.
    +
    -version packageVersion
    Ce paramХtre spИcifie la version du package. Il est requis.
    +
    -load filespec
    Ce paramХtre spИcifie une bibliothХque binaire qui doit Йtre chargИ avec la commande -load. filespec est une liste de deux ИlИments. Le premier ИlИment est le nom du fichier Ю charger. Le second, l'ИlИment optionnel est une liste de commandes fournies en chargeant ce fichier. Si la liste des fonctions est vide ou omise, ::pkg::create prИpare la bibliothХque Ю un chargement direct (voir pkg_mkIndex). N'importe quel nombre de paramХtres -load peut Йtre spИcifiИ. +
    +
    -source filespec
    Ce paramХtre est semblable au paramХtre -load , exceptИ qu'il spИcifie une bibliothХque Tcl qui doit Йtre chargИe avec la commande source. N'importe quel nombre de paramХtres -source peut Йtre spИcifiИ.
    +
    +
    +
    Au moins un paramХtre-load ou -source doit Йtre donnИ.

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/pid.htm b/hlp/fr/tcl/pid.htm new file mode 100644 index 0000000..f3a86ab --- /dev/null +++ b/hlp/fr/tcl/pid.htm @@ -0,0 +1,18 @@ + + + + +

    pid      Commandes Internes Tcl

    +
    +
    NOM

    +
    pid √ RИcupИre l'id(s) de processus +

    +
    SYNTAXE

    +
    pid ?fileId? +

    +
    DESCRIPTION

    +
    Si l'argument fileId est donnИ alors il doit normalement se rИferer Ю un processus pipeline crИИ avec la commande open. Dans ce cas la commande pid renverra une liste dont les ИlИments sont les identificateurs de processus de tout les processus dans le pipeline, dans l'ordre. La liste sera vide si fileId se refХre Ю un fichier ouvert qui n'est pas un processus pipeline. Si aucun argument fileId n'est donnИ alors pid retourne le identificateur processus du processus courant. Tous les identificateurs de processus sont renvoyИs comme chaНnes dИcimales.

    +
    DerniХre rИvision: 7.0
    +
    +
    + diff --git a/hlp/fr/tcl/pkg_mkindex.htm b/hlp/fr/tcl/pkg_mkindex.htm new file mode 100644 index 0000000..0445842 --- /dev/null +++ b/hlp/fr/tcl/pkg_mkindex.htm @@ -0,0 +1,58 @@ + + + + +

    pkg_mkIndex      Commandes Internes Tcl

    +
    +
    NOM

    +
    pkg_mkIndex - Construit un index pour le chargement automatique des packages +

    +
    SYNTAXE

    +
    pkg_mkIndex ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...?
    +

    +
    DESCRIPTION

    +
    Pkg_mkIndex est une fonction utilitaire qui fait partie de la bibliothХque standard Tcl. Elle est utilisИe pour crИer des fichiers index qui permettent aux packages Ю Йtre chargИs automatiquement quand des commandes package require sont exИcutИes. Pour utiliser pkg_mkIndex, suivre ces Иtapes: +
    +
    [1]
    CrИer le(s) package(s). Chaque package peut consister en un ou plusieurs fichiers script Tcl ou fichiers binaires. Les fichiers binaires doivent Йtre compatibles pour le chargement avec la commande load avec un seul argument; par exemple, si le fichier est test.so il doit Йtre possible de charger ce fichier avec la commande load test.so. Chaque fichier script doit contenir une commande package provide pour dИclarer le package et son numИro de version, et chaque fichier binaire doit contenir un appel Ю Tcl_PkgProvide.
    +
    [2]
    CrИer l'index en appelant pkg_mkIndex. L'argument dir donne le nom d'un rИpertoire et chaque argument pattern est un modХle glob-style qui choisit les scripts ou fichiers binaires dans dir. Le modХle par dИfaut est *.tcl et *.[info sharedlibextension].
    +Pkg_mkIndex crИera un fichier pkgIndex.tcl dans dir avec l'information de package au sujet de tous les fichiers donnИs par les arguments pattern. Ceci est fait par chargement de chaque fichier dans un interprИteur esclave et constatation de quels packages et nouvelles commandes apparaissent (c'est pourquoi il est essentiel d'avoir des commandes package provide ou un appel Ю Tcl_PkgProvide dans le fichier, comme dИcrit plus haut). Si vous avez un package divisИ en scripts et fichiers binaires, ou si vous avez des dИpendances entre les fichiers, vous pouvez utiliser l'option -load ou ajuster l'ordre dans lequel pkg_mkIndex traite les fichiers. Voir CAS COMPLEXES ci-dessous. +
    +
    [3]
    Installer le package dans un sous rИpertoire d'un des rИpertoires donnИs par la variable tcl_pkgPath. Si $tcl_pkgPath contient plus d'un rИpertoire, les packages dИpendants de la machine (ex., ceux qui contient libraries partagИes binaires) doivent normalement Йtre installИs sous le premier rИpertoire et les packages indИpendants de la machine (ex., ceux qui contiennent seulement des scripts Tcl) seront installИs sous le second rИpertoire. Le sous rИpertoire doit inclure le script du package et/ou les fichiers binaires aussi bien que le fichier pkgIndex.tcl. Tant que le package est installИ dans un sous rИpertoire d'un rИpertoire de $tcl_pkgPath il sera automatiquement trouvИ pendant les commandes package require.
    +Si vous installez le package nulle part ailleurs, alors vous devez vous assurer que le rИpertoire contenant le package est dans la variable globale auto_path ou un sous rИpertoire immИdiat d'un des rИpertoires de auto_path. Auto_path contient une liste de rИpertoires qui sont recherchИ par le auto-loader et le package loader; qui par dИfaut inclut $tcl_pkgPath. Le package loader vИrifie aussi tous les sous rИpertoire des rИpertoires dans auto_path. Vous pouvez ajouter un rИpertoire Ю auto_path explicitement dans votre application, ou vous pouvez ajouter le rИpertoire Ю votre variable d'environnement TCLLIBPATH: si cette variable d'environnement est prИsente, Tcl initialise auto_path avec pendant le dИmarrage de l'application.
    +
    [4]
    Une fois les Иtapes prИcedentes accomplies, tout ce que vous avez besoin de faire pour utiliser le package est d'appeler package require. Par exemple, si les versions 2.1, 2.3, et 3.1 du package Test ont ИtИ indexИes par pkg_mkIndex, la commande package require Test rendra la version 3.1 disponible et la commande package require-exact Test 2.1 rendra la version 2.1 disponible. Il peut y avoir de nombreuses versions d'un package dans les fichiers d'index de auto_path, mais seulement un sera actuellement chargИ dans un interprИteur donnИ, en se basant sur le premier appel de package require. DiffИrentes versions d'un package peuvent Йtre chargИes dans diffИrents interprИteurs. +
    +
    +

    +
    OPTIONS

    +
    Les commutateurs optionnels sont: +
    +
    -lazy
    L'index gИnИrИ retardera le chargement du package jusqu'Ю l'utilisation d'une des commandes fourni par le package, au lieu de le charger immИdiatement avec package require. +
    +
    -load pkgPat
    Le processus d'index prechargera tous les packages existants dans l'interprИteur courant et correspondants Ю pkgPat dans l'interprИteur esclave utilisИ pour gИnИrer l' index. La correspondance de modХle utilise les rХgles de chaНne de correspondance. Voir CAS COMPLEXES ci-dessous. +
    +
    -verbose
    GИnХre une sortie pendant le processus d'indexage. La sortie se fait via la fonction tclLog, qui par dИfaut affiche sur stderr. +
    +
    --
    Termine les flags, dans les cas ou dir commence avec un tiret. +
    +
    +

    +
    PACKAGES ET AUTO-LOADER

    +
    Les utilitИs de gestion de package font double emploi avec l'auto-loader, dans le sens ou ils prИparent tous les deux les fichiers Ю Йtre chargИs Ю la demande. NИanmoins, la gestion package est un mИcanisme de plus haut niveau qui utilise l'auto-loader pour la derniХre Иtape dans le processus de chargement. Il est gИnИralement meilleur d'indexer un package avec pkg_mkIndex plutТt que auto_mkindex parce que le mИcanisme de package fournit un contrТle de version: plusieurs versions d'un package peuvent Йtre rendues disponibles dans les fichiers d'index, avec diffИrentes applications utilisant diffИrentes versions basИes sur des commandes package require. Au contraire, auto_mkindex ne reconnaНt pas les versions donc il peut seulement gИrer une seule version de chaque package. Ce n'est probablement pas une bonne idИe d'indexer un package donnИ avec pkg_mkIndex et auto_mkindex. Si vous utilisez pkg_mkIndex pour indexer un package, ses commandes ne peuvent pas appelИes jusqu'a ce que package require ait ИtИ utilisИ pour choisir une version; au contraire, les packages indexИs avec auto_mkindex peuvent Йtre utilisИs immИdiatement car il n'y a pas de contrТle de version. +

    +
    COMMENT CA MARCHE ?

    +
    Pkg_mkIndex depend de la commande package unknown, de la commande package ifneeded, et de l'auto-loader. la premiХre fois qu'une commande package require est appelИe, le script package unknown est appelИ. Ceci est fixИ par l'initialisation Tcl dans un script qui Иvalue tous les fichiers pkgIndex.tcl dans le auto_path. Les fichiers pkgIndex.tcl contiennent des commandes package ifneeded pour chaque version de chaque package disponible; ces commandes appellent package provide pour annoncer la disponibilitИ du package, et elles Иcrivent l'information d'auto-loader pour charger les fichiers du package. Si le flag -lazy a ИtИ fourni quand pkgIndex.tcl a ИtИ gИnИrИ, un fichier donnИ d'une version donnИs d'un package donnИ n'est pas chargИ jusqu'au premier appel d'une de ses commandes dans l'interprИteur, mais vous pourrez appeler les commandes et elles seront auto-chargИes.
    +

    +
    CHARGEMENT DIRECT

    +
    Certains packages, par exemple packages qui utilisent les namespaces et exportent descommandes ou ceux qui exigent une initialisation spИciale, peuvent choisir que leurs fichiers package seront chargИs immИdiatement Ю package require au lieu de retarder le chargement Ю la premiХre utilisation d'une commande du package. C'est le mode par dИfaut pendant la gИnИration de l'index de package. Ceci peut Йtre surchargИ en specifiant l'argument -lazy. +

    +
    CAS COMPLEXES

    +
    La plupart des cas complexes de dИpendances entre scripts et fichiers binaires, et packages divisИs entre scripts et fichiers binaires sont gИrИes correctement. NИanmoins, vous pouvez avoir Ю ajuster l'ordre dans lequel les fichiers sont traitИs par pkg_mkIndex. Ce problХme est dИcrit en dИtail ci-dessous.
    +
    Si chaque script ou fichier contient un package, et que les packages sont contenus dans un seul fichier, alors les choses sont faciles. Vous spИcifiez simplement tous les fichiers Ю indexer dans n'importe quel ordre avec quelques modХles glob.
    +
    En general, il est OK pour les scripts d'avoir des dИpendances avec d'autres packages. Si les scripts contiennent des commandes package require, elles sont extraites dans l'interprИteur utilisИ pour traiter les scripts, donc elles ne causent pas de problХmes. Si les scripts appellent d'autre packages dans le code global, ces appels sont gИrИs par une commande unknown. NИanmoins, si les scripts font rИfИrence Ю des variables d'un autre package dans le code global, cela causera des erreurs. C'est aussi un mauvais style de codage.
    +
    Si les fichiers binaires ont des dИpendances avec d'autres packages, les choses peuvent devenir compliquИes parcequ'il n'est pas possible d'extraire des API niveau C telle que Tcl_PkgRequire en chargeant un fichier binaire. Par exemple, supposez que le package BLT exige Tk, et exprime ceci avec un appel de Tcl_PkgRequire dans sa routine Blt_Init. Pour supporter ceci, vous devez exИcuter pkg_mkIndex dans un interprИteur qui aura chargИ Tk . Vous pouvez accomplir ceci avec l'option -loadpkgPat. Si vous spИcifiez cette option, pkg_mkIndex chargera tous les packages listИs par info loaded et qui correspondent Ю pkgPat dans l'interprИteur utilisИ pour traiter les fichiers. Dans la plupart des cas ceci satisfera l'appel Ю Tcl_PkgRequire fait par les fichiers binaires.
    +
    Si vous indexez deux fichiers binaires et qu'un dИpend de l'autre, vous devez spИcifier celui qui a les dИpendances en dernier. De cette faГon, celui sans dИpendances sera chargИ et indexИ, et alors le package qu'il fournit sera disponible quand le second fichier sera traitИ. Vous pouvez aussi avoir besoin de charger le premier package dans un interprИteur temporaire utilisИ pour crИer l'index en utilisant le flag -load; vous pourrez spИcifier des modХles package qui ne sont pas encore chargИs.
    +
    Si vous avez un package qui est divisИ en scripts et fichiers binaires, alors vous devez Иviter le flag -load. Le problХme est que si vous chargez un package avant de calculer l'index, il masque tout autre fichier qui fait partie du mЙme package. Si vous devez utiliser -load, alors vous devez spИcifier les scripts en premier; autrement le package chargИ du fichier binaire peut masquer le package dИfini par les scripts.

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/proc.htm b/hlp/fr/tcl/proc.htm new file mode 100644 index 0000000..6dc71fa --- /dev/null +++ b/hlp/fr/tcl/proc.htm @@ -0,0 +1,20 @@ + + + + +

    proc      Commandes Internes Tcl

    +
    +
    NOM

    +
    proc - CrИe une fonction Tcl +

    +
    SYNTAXE

    +
    proc name args body +

    +
    DESCRIPTION

    +
    La commande proc crИe une nouvelle fonction Tcl nommИe name, remplaГant toute commande ou fonction existante de ce nom. Chaque fois que la nouvelle commande est appelИe, le contenu de body sera exИcutИ par l'interprИteur Tcl. Normalement, name est non qualifiИ (n'inclut pas les noms des namespaces contenant), et la nouvelle fonction est crИИe dans le namespace courant. Si name inclut un quelconque qualificateurs namespace, la fonction est crИИe dans le namespace spИcifiИ . Args spИcifie les arguments formels Ю la fonction. Ils consiste d'une liste, qui peur Йtre vide, dont chaque ИlИments spИcifie un argument. Chaque spИcificateur d'argument est aussi une liste avec soit un ou deux champs. S'il y a seul champ dans le spИcificateur alors c'est le nom de l'argument; s'il y a deux champs, alors le premier est le nom de l'argument et le second est sa valeur par dИfaut.
    +
    Quand name est appelИe une variable locale sera crИИe pour chacun des arguments formel Ю la fonction; leur valeur sera la valeur de l'argument correspondant dans la commande appelИe ou la valeur par dИfaut de l'argument. Les arguments avec une valeur par dИfaut n'ont pas besoin Йtre spИcifiИs dans un appel de fonction. NИanmoins, il doit y avoir assez d'arguments pour tous les arguments qui n'ont pas de valeur par dИfaut, et il ne doit pas y avoir d'arguments supplИmentaires. Il y a un cas spИcial pour permettre les fonctions avec un nombre variable d'arguments. Si le dernier argument a le nom args, alors un appel Ю la fonction peut contenir plus d'arguments que la fonction en a. Dans ce cas, tous les arguments Ю partir de celui qui serait assignИ Ю args sont combinИs en une liste (comme si la commande list avait ИtИ utilisИe); ces valeurs combinИes sont assignИes Ю la variable locale args.
    +
    Quand body est exИcutИ,les noms de variables normalement se refХrent aux variables locales, qui sont crИИes automatiquement quand rИfИrencИes et effacИes quand la fonction retourne. Une variable locale est automatiquement crИИe pour chacun de ses arguments de fonction. Les variables globales peuvent seulement Йtre accИdИe en appelant la commande global ou la commande upvar. Les variables namespace peuvent seulement Йtre accИdИes en appelant la commande variable ou la commande upvar.
    +
    La commande proc retourne une chaНne vide. Quand une fonction est appelИe, la valeur de retour de la fonction est la valeur spИcifiИe dans une instruction return. Si la fonction n'exИcute pas un return explicite , alors sa valeur de retour est la valeur de la derniХre commande exИcutИe dans le corps de la fonction. Si une erreur se produit pendant l'exИcution du corps la fonction, alors la fonction renverra cette mЙme erreur.
    +
    +
    + diff --git a/hlp/fr/tcl/puts.htm b/hlp/fr/tcl/puts.htm new file mode 100644 index 0000000..74eb134 --- /dev/null +++ b/hlp/fr/tcl/puts.htm @@ -0,0 +1,25 @@ + + + + +

    puts      Commandes Internes Tcl

    +
    + +
    NOM

    +
    puts - Ecrit dans un canal +

    +
    SYNTAXE

    +
    puts ?-nonewline? ?channelId? string +

    +
    DESCRIPTION

    +
    Ecrit les caractХres donnИs par string dans le canal donnИ par channelId. ChannelId doit Йtre un identificateur de canal tel que celui renvoyИ par un prИcИdent appel de open ou socket. It doit avoir ИtИ ouvert pour une sortie. Si aucun channelId n'est spИcifiИ alors il est par defaut de stdout. Puts normalement emet un caractХre newline aprХs string, mais cette fonctionnalitИ peut Йtre supprimИ en specifiant le switch - nonewline.
    +
    Les caractХres newline dans la sortie sont traduits par puts en sИquences fin de ligne spИcifique Ю la plate-forme en accord avec la valeur courante de l'option -translation pour le canal (par exemple, sur les PCs les saut de lignes sont normalement remplacИ avec carriage-return-linefeed sИquences;  sur Macintosh les saut de lignes sont normalement remplacИ avec carriage- return). Voir la page de manuel fconfigure pour une discussion sur la maniХre dans laquelle fconfigure modifie la sortie.
    +
    Tcl met la sortie en tampon en interne, donc les caractХres Иcrits avec puts peuvent ne pas apparaitre immИdiatement sur le fichier ou pИriphИrique de sortie;  Tcl retarde normalement la sortie jusqu'a ce que le tampon soit plein ou le canal fermИ. Vous pouvez forcer la sortie Ю apparaitre immИdiatement avec la commande flush.
    +
    Quand le tampon de sortie est plein, la commande puts bloquera  normalement jusqu'a ce que toutes les donnИes en tampon aient ИtИ acceptИes pour sortie par le systХme d'exploitation. Si channelId est en mode non bloquant alors la commande puts ne bloquera pas mЙme si le systХme d'exploitation ne peut pas accepter  les donnИes. Par contre, Tcl continue Ю mettre les donnИes en tampon et les Иcrit en arriХre-plan aussi vite que le sous-jacent fichier ou pИriphИrique peut les accepter. L'application doit utiliser la boucle d'ИvХnement Tcl pour que la sortie non bloquante fonctionne; autrement Tcl ne voit jamais que le fichier ou le pИriphИrique est prХt Ю sortir plus de donnИes. Il est possible pour une arbitrairement large quantitИ de donnИes d'Йtre en tampon pour un canal en mode non bloquant, ce qui peut consommer une large quantitИ de mИmoire. Pour Иviter de gaspiller la mИmoire, les I/O nonbloquantes doivent normalement Йtre utilisИes d'une faГon pilotИe par ИvХnement avec la commande fileevent (n'appellez pas puts Ю moins que vous ayez recemment notifiИ via un ИvХnement fichier que le canal est prХt Ю afficher plus de donnИes). +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/pwd.htm b/hlp/fr/tcl/pwd.htm new file mode 100644 index 0000000..81a5e49 --- /dev/null +++ b/hlp/fr/tcl/pwd.htm @@ -0,0 +1,15 @@ + + + + +

    pwd      Commandes Internes Tcl

    +
    +
    NOM

    +
    pwd - Retourne le rИpertoire de travail courant +

    +
    SYNTAXE

    +
    pwd

    +DESCRIPTION

    +
    Renvoie le nom de chemin du rИpertoire de travail courant.

    +
    + diff --git a/hlp/fr/tcl/re_syntax.htm b/hlp/fr/tcl/re_syntax.htm new file mode 100644 index 0000000..0f4de7f --- /dev/null +++ b/hlp/fr/tcl/re_syntax.htm @@ -0,0 +1,399 @@ + + + + +

    re_syntax      Commandes Internes Tcl

    +
    +
    NOM
    +
    re_syntax √ Syntaxe des expressions rationelles Tcl +

    +
    DESCRIPTION

    +
    Une regular expression (expression rationelle) dИcrit des chaНnes de caractХres. C'est un modХle qui correspond Ю certaines chaНnes et ne correspond pas Ю d'autres +

    +
    DIFFERENTES SORTES DE REs

    +
    Les expressions rationelles ("RE"s), comme dИfini par POSIX, existent de deux sortes: Иtendue REs ("EREs") et basiques REs ("BREs"). Les EREs sont celles du egrep traditionel, alors que BREs sont celles du ed traditionel. Cette implИmentation ajoute une troisiХme sorte, advanced REs ("AREs"), EREs avec quelques extensions significatives.
    +
    Cette page de manueluel dИcrit d'abord les AREs. Les BREs existent principalement pour compatibilitИ ascendante avec quelques anciens programmes; elles seront vues Ю la fin. Les EREs POSIX sont presque un sous ensemble exact des AREs. Les fonctionnalitИs des AREs qui ne sont pas prИsentes dans les EREs seront indiquИes
    +

    +
    SYNTAXE DES EXPRESSIONS RATIONELLES

    +
    Les expressions Tcl rationelles sont implИmentИes en utilisant le package Иcrit par Henry Spencer, basИ sur les spec 1003.2 et quelques unes (pas toutes) des extensions Perl5 (thanks, Henry!) la plus grande partie de la description des expressions rationelles ci-dessous est copiИe texto de sa page de manuel.
    +
    Une ARE est composИe d'une ou plusieurs branches, sИparИes par `|', Иgales Ю tout ce qui correspond Ю quelconque des branches.
    +
    Une branche est zИro ou plusieurs contraintes ou atomes quantifiИ, concatИnИs. C'est une correspondance au premier, suivi par une correspondance au second, etc; une branche vide correspond Ю la chaНne vide.
    +
    Un atome quantifiИ est un atome eventuellement suivi d'un quantificateur. Sans quantificateur, c'est une correspondance Ю l'atome. Les quantificateurs, et leur atome correspondant, sont:
    +
    +
    +
    *
    une sИquence de 0 ou plus correspondances Ю l'atome +
    +

    + +
    une sИquence de 1 ou plus correspondances Ю l'atome +
    +

    ? +
    une sИquence de 0 ou 1 correspondance Ю l'atome +
    +

    {m} +
    une sИquence de exactement m correspondances Ю l'atome +
    +

    {m,} +
    une sИquence de m ou plus correspondances Ю l'atome +
    +

    {m,n} +
    une sИquence de m Ю n (incluses) correspondances Ю l'atome; m infИrieur Ю n +
    +

    *?  +?  ??  {m}?  {m,}?  {m,n}? +
    quantificateurs non-greedy, qui correspondent au mЙme possibilitИs, mais se refХrent au plus petit nombre plutТt qu'au plus grand nombre de correspondances (voir CORRESPONDANCES) +
    +
    +
    +
    Les formes utilisant { et } sont appelИes limites. Les nombres m et n sont des entiers dИcimaux non signИs avec des valeurs autorisИes de 0 Ю 255 inclus.
    +
    Un atome est l'un de:
    +
    +
    +
    (re)
    (oЫ re est toute expression rationelle) correspond une correspondance Ю re, avec la correspondance marquИe pour rapport +
    +

    (?:re) +
    comme prИcedent, mais sans reporting (une "non-capturing" ensemble de parenthХses) +
    +

    () +
    correspond Ю une chaНne vide, marquИe pour rapport. +
    +

    (?:) +
    correspond Ю une chaНne vide, sans rapport +
    +

    [chars] +
    une bracket expression, correspondante Ю un quelconque chars (voir BRACKET EXPRESSIONS pour plus de dИtail) +
    +

    . +
    correspond Ю un seul caractХre quelconque +
    +

    \k +
    (oЫ k est un caractХre non-alphanumИrique) correspond au caractХre interprИtИ comme un caractХre ordinaire, e.x \\ correspond un caractХre antislash +
    +

    \c +
    c est alphanumИrique (Иventuellement suivi par autre caractХres), un escape (AREs seulement), voir ESCAPES ci-dessous +
    +

    { +
    quand suivi par un caractХre autre qu'un chiffre, correspond Ю l'accolade ouvrante `{'; quand suivi par un chiffre, c'est le dИbut d'un intervalle (voir plus haut) +
    +

    x +
    x est un simple caractХre sans autre signification, correspond Ю ce caractХre. +
    +
    +
    +
    Une contrainte correspond Ю une chaНne vide quand des conditions spИcifique sont rencontrИes. Une contrainte ne peut pas Йtre suivie par un quantificateur. Les contraintes simples sont comme suit; quelques autres sont dИcrite plus tard, sous ESCAPES.
    +
    +
    +
    ^
    correspond au dИbut d'une ligne +
    +

    $ +
    correspond Ю la fin d'une ligne +
    +

    (?=re) +
    positive lookahead (AREs seulement), correspond au point quelconque oЫ une sous chaНne correspondante Ю re commence +
    +

    (?!re) +
    negative lookahead (AREs seulement), correspond au point quelconque oЫ aucune sous chaНne correspondante Ю re ne commence
    +
    +
    +
    Les contraintes lookahead ne peuvent pas contenir de rИfИrences arriИres (voir plus loin), et toutes parenthХses Ю l'intИrieur sont considerИes non-capturantes.
    +
    Une RE ne peut pas finir avec `\' +

    +
    BRACKET EXPRESSIONS (EXPRESSIONS CROCHETS)

    +
    Une expression crochets est une liste de caractХres entourИe de `[]'. Elle correspond normalement Ю tout caractХre de la liste (mais voir ci-dessous). Si la liste commence avec `^', elle correspond Ю tout caractХre (mais voir ci-dessous) non inclus dans la liste.
    +
    Si deux caractХres de la liste sont sИparИs par `-', c'est un raccourci pour l'intervalle complet des caractХres entre les deux (inclus) dans la sИquence ordonnИe, ex. [0-9] en ASCII correspond Ю tout chiffre dИcimal. Deux intervalles ne peuvent pas partager une limite, donc par ex. a-c-e est illИgal. Les intervalles sont trХs dИpendant de l'ordre de tri, et les programmes portables ne peuvent s'appuyer dessus.
    +
    Pour inclure un ] ou - literal dans la liste, la mИthode la plus simple est de l'entourer de [. et .] pour en faire un  ИlИment d'assemblage (voir ci-dessous). Alternativement, placez le en premier (suivant un `^' eventuel), ou (AREs seulement) faites le preceder de `\'. Alternativement, pour `-', faites en le dernier caractХre, ou le second point d'un intervalle. Pour utiliser un - literal comme le premier point d'un intervalle, faites en un ИlИment d'assemblage ou (AREs seulement) faites le preceder de `\'. A l'exception de ceux-ci, de toutes combinaisons utilisant [ (voir paragraphes suivant), et les echappements, tout autres des caractХres spИciaux perdent leur signification spИciale Ю l'intИrieur d'une expression crochet.
    +
    Dans une expression crochet, un ИlИment d'assemblage (un caractХre, une sИquence multi-caractХre qui est assemblИe comme si c'etait un simple caractХre, ou un nom de sИquence d'assemblage pour les deux) entourИ de [. et .] Иquivaut Ю la sИquence de caractХres de cet ИlИment d'assemblage. La sИquence est un seul ИlИment de liste de l'expression crochet. Une expression crochet dans une locale qui a des ИlИments d'assemblages multi-caractХre peut donc correspondre Ю plus d'un caractХre. Ainsi (insidieusement), une expression crochet qui commence avec ^ peut correspond Ю des ИlИment d'assemblages multi-caractХre mЙme si aucun d'eux n'apparait dans l'expression crochet! (Note: Tcl n'a pas d'ИlИment d'assemblages multi-caractХre. Cette information est seulement prИsente pour  illustration.)
    +
    Par exemple, supposez une sИquence d'assemblage incluant un ИlИment d'assemblage ch multi-caractХre. Ensuite la RE [[.ch.]]*c (zИro ou plus ch's suivi par c) correspond les cinq premiers caractХres de `chchcc'. Egalement, la RE [^c]b correspond Ю tout de `chb' (parce que [^c] correspond au multi-caractХre ch).
    +
    Dans une expression crochet, un ИlИment d'assemblage entourИ de [= et =] est une classe d'Иquivalence, remplaГant la sИquence de caractХres de tout ИlИment d'assemblage Иquivalent Ю celui-ci, incluant lui-mЙme. (Si il n'y a pas d'autre ИlИment d'assemblage Иquivalent, le traitement est le mЙme que si les dИlimiteurs  Иtaient `[.' et `.]'.) Par exemple, si o et Т sont les membres d'une classe d'Иquivalence, alors `[[=o=]]', `[[=Т=]]', et `[oТ]' sont tous synonymes. Une classe d'Иquivalence ne peut pas Йtre le point final d'un intervalle. (Note:  Tcl implИmente seulement la locale Unicode. Il ne definit aucune classes d'Иquivalence. Les exemples prИcИdents sont juste des illustrations.)
    +
    Dans une expression crochet, le nom d'une character class entourИe de [: et :] Иquivaut Ю la liste de tous les caractХres (pas tous les ИlИments d'assemblage!) appartenant Ю cette classe. Les classes standard de caractХres sont:
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + alpha + + Une lettre. +
    + upper + + Une lettre majuscule. +
    + lower + + Une lettre minuscule. +
    + digit + + Un chiffre dИcimal. +
    + xdigit + + Un chiffre hexadИcimal. +
    + alnum + + Un caractХre alphanumИrique (lettre ou chiffre). +
    + print + + Un caractХre alphanumИrique (mЙme que alnum). + +
    + blank + + + Un espace ou tabulation.> +
    + space + + Un caractХre produisant un espace dans du texte affichИ. +
    + punct + + Un caractХre de ponctuation. +
    + graph + + + Un caractХre avec une reprИsentation visible.
    + cntrl + + Un caractХre de contrТle.
    +
    +

    +
    Une locale peut en fournir d'autres. (Notez que l'implИmentation Tcl courante a seulement une locale: la locale Unicode.) Une classe de caractХre ne peut pas Йtre utilisИe comme point final d'un intervalle.

    +
    Il y a deux cas spИciaux d'expressions crochet: les expressions crochet [[:<:]] et [[:>:]] sont des contraintes, correspondant Ю des chaНne vides respectivement au dИbut et Ю la fin d'un mot. Un mot est dИfini comme une sИquence de mots caractХres qui est ni prИcИdИe  ni suivie par des mots caractХres. Un mot caractХre est un caractХre alnum ou un underscore (_). Ces expressions crochet spИciales sont obsolХtes; les utilisateurs d'AREs devraient utiliser les contraintes Иchappement Ю la place (voir ci-dessous). +

    +
    ECHAPPEMENTS

    +
    Les echappements (AREs seulement), qui commencent avec un \ suivi d'un caractХre alphanumИrique, existent de plusieurs sortes: entrИe caractХre, classe, constraint escapes, et back rИfИrences. Un \ suivi par un caractХre alphanumИrique mais ne constituant pas un echappement valide est illИgal dans une ARE. Dans les EREs, il n'y a pas d'echappements: en dehors d'une expression crochet, un \ suivi par un caractХre alphanumИrique Иquivaut simplement Ю cecaractХre comme un caractХre ordinaire, et dans une expression crochet, \ est un caractХre ordinaire. (Le dernier est une incompatibilitИ entre les EREs et les AREs.)
    +
    Les echappements entrИe caractХre (AREs seulement) existent pour faciliter la spИcification de caractХres non imprimables et autrement inutilisables dans REs:
    +
    +
    +
    \a +
    caractХre bip (bell), comme en C +
    +
    \b
    backspace, comme en C +
    +
    \B +
    synonyme pour \ reduire la rИpИtition des backslash dans quelques applications ou il y a des niveaux multiples de traitement des backslash +
    +
    \cX +
    (oЫ X est un caractХre quelconque) le caractХre dont les 5 bits de poids faible sont les mЙme que ceux de X, et dont les autres bits sont tous Ю zИro +
    +
    \e +
    caractХre dont le nom de sИquence d'assemblage est `ESC', ou le caractХre avec une valeur octale de 033 +
    +
    \f +
    formfeed, comme en C +
    +
    \n +
    newline, comme en C +
    +
    \r +
    retour chariot, comme en C +
    +
    \t +
    tabulation horizontale, comme en C +
    +
    \uwxyz +
    (oЫ wxyz est exactement quatre chiffres hexadИcimaux) le caractХre Unicode U+wxyz dans l' ordre d'octet local +
    +
    \Ustuvwxyz +
    (oЫ stuvwxyz est exactement huit chiffres hexadИcimaux) reservИ pour une extension Unicode hypothИtiquel Ю 32 bits +
    +
    \v +
    tabulation verticale, comme en C. +
    +
    \xhhh +
    (oЫ hhh est une sИquence quelconque de chiffres hexadИcimaux) le caractХre dont la valeur hexadИcimale est 0xhhh (un simple caractХre sans tenir compte de combien de chiffres hexadИcimaux sont utilisИs). +
    +
    \0 +
    le caractХre dont la valeur est 0 +
    +
    \xy
    (oЫ xy est exactement deux chiffres octal, et n'est pas une back reference (voir ci-dessous)) le caractХre dont la valeur octale est 0xy +
    +
    \xyz
    (oЫ xyz est exactement trois chiffres octaux, et n'est pas une back rИfИrence (voir ci-dessous)) le caractХre dont la valeur octale est 0xyz +
    +
    +
    +
    Les chiffres Hexadecimaux sont `0'-`9', `a-`f', et `A'-`F'. Les chiffres Octaux sont `0'-`7'.
    +
    Les echappements caractХre-entrИe sont toujours interprИtИs comme des caractХres ordinaires. Par exemple, \135 est ] en ASCII, mais \135 ne peut terminer une expression crochet. Attention, nИanmoins, que quelque application (ex.,un compilateur C) n'interprХte ces sИquences elle-mЙme avant le package regular-expression, qui peut exiger le doublage (quadruplage, etc.) du `\'.
    +
    Les echappements Class-shorthand (AREs seulement) fournissent des raccourcis pour certaines classes de caractХre communИment utilisИes:
    +
    +
    +
    \d
    [[:digit:]]
    +
    \s
    [[:space:]] +
    +
    \w +
    [[:alnum:]_] (notez l'underscore) +
    +
    \D +
    [^[:digit:]]
    +
    \S +
    [^[:space:]] +
    +
    \W +
    [^[:alnum:]_] (notez l'underscore) +
    +
    +
    +
    Dans les expressions crochets, `\d', `\s', et `\w' perdent leurs crochets externes, et `\D', `\S', et `\W' sont illИgaux. (Ainsi, par exemple, [a-c\d] est Иquivalent Ю [a-c[:digit:]]. Egalement, [a-c\D], qui est Иquivalent Ю [a-c^[:digit:]], est illegal.)
    +
    Un constraint escape (AREs seulement) est une contrainte, correspondant Ю la chaНne vide si des conditions spИcifiques sont rencontrИes, Иcrite comme un echappement:
    +
    +
    +
    \A +
    correspond seulement au dИbut de la chaНne (voir CORRESPONDANCES, ci-dessous, pour comment ceci diffХre de `^') +
    +
    \m +
    correspond seulement au dИbut d'un mot +
    +
    \M +
    correspond seulement Ю la fin d'un mot +
    +
    \y +
    correspond seulement au dИbut ou Ю la fin d'un mot +
    +
    \Y +
    correspond seulement Ю un point qui n'est pas le dИbut ou la fin d'un mot +
    +
    \Z +
    correspond seulement Ю la fin de la chaНne (voir CORRESPONDANCES, ci-dessous, pour comment ceci diffХre de `$') +
    +
    \m +
    (oЫ m est un chiffre non nul) une back reference, voir ci-dessous +
    +
    \mnn +
    (oЫ m est un chiffre non nul, et nn sont d'autres chiffres, et la valeur dИcimale mnn n'est pas supИrieure au nombre de parenthХses fermantes) une back reference, voir ci-dessous +
    +
    +
    +
    Un mot est dИfini comme dans la spИcification de  [[:<:]] et [[:>:]] plus haut. Constraint escapes sont illИgales dans les expressions crochets.
    +
    Une back rИfИrence (AREs seulement) correspond Ю la mЙme chaНne que celle qui correspond aux sous expressions entre parenthХses spИcifiИ par les nombres, ainsi ([bc])\1 correspond bb ou cc mais pas `bc'. La sous expression doit entiХrement prИcИder la back rИfИrence dans la RE. Les sous expressions sont numИrotИes dans l'ordre de leur premiХres parenthХses. Les parenthХses non-capturantes ne dИfinissent pas de sous expressions.
    +
    Il y a une ambiguitИ inhИrente historique entre les Иchappements caractХre-entrИe octal et les back rИfИrences, qui est rИsolue par heuristique, comme dИvoilИ plus haut. Un zИro en tЙte indique toujours un Иchappement octal. Un seul chiffre diffИrent de zИro, non suivi par un autre chiffre, est toujours interprИtИ comme une back rИfИrence. Une sИquence multi-chiffre ne commenГant pas avec un zИro est interprИtИe comme une back rИfИrence si elle est situИe aprХs une sous expression convenable (ex. le nombre est dans l'intervalle lИgal pour une back rИfИrence), et autrement est interprИtИe comme octale.

    +
    METASYNTAXE

    +
    En plus de la syntaxe principale dИcrite plus haut, il y a quelques formes spИciales et diverses facilitИs syntaxiques disponibles.
    +
    Normalement la sorte de RE utilisИe est spИcifiИe par l'application. NИanmoins, ceci peut Йtre modifiИ par un director. Si un RE d'une sorte quelconque commence avec `***:', le reste de la RE est une ARE. Si une RE d'une sorte quelconque commence avec `***=', le reste de la RE est pris comme une chaНne littИrale, avec tous les caractХres considerИs comme des caractХres ordinaires.
    +
    Une ARE peut commencer avec des contenue options: une sИquence (?xyz) (oЫ xyz est un ou plusieurs caractХres alphabИtiques) spИcifie les options affectant le reste de la RE. Ceci vient en supplИment, et peut modifier toute option spИcifiИe par l'application. Le lettres d'option disponibles sont:
    +
    +
    +
    b +
    le reste de la RE est une BRE +
    +
    c +
    correspondance sensible Ю la casse (par dИfaut) +
    +
    e +
    le reste de la RE est une ERE +
    +
    i +
    correspondance insensible Ю la casse (voir CORRESPONDANCES, ci-dessous) +
    +
    m +
    synonyme historique de n +
    +
    n +
    correspondance sensible au saut de ligne(voir CORRESPONDANCES, ci-dessous) +
    +
    p +
    correspondance partiellement sensible au saut de ligne (voir CORRESPONDANCES, ci-dessous) +
    +
    q +
    le reste de la RE est une chaНne littИrale ("entre guillemets"), toute de caractХres ordinaires +
    +
    s +
    correspondance insensible au saut de ligne (par dИfaut) +
    +
    t +
    syntaxe sИrrИe (par dИfaut; voir ci-dessous) +
    +
    w +
    correspondance inverse partiellement sensible au saut de ligne ("weird") (voir CORRESPONDANCES, ci-dessous) +
    +
    x
    syntaxe expansИe (voir ci-dessous)
    +
    +
    +
    Les options incluses prennent effet Ю la ) terminant la sИquence. Elles sont disponibles seulement au dИbut d'une ARE, et ne peuvent pas Йtre utilisИes plus loin.
    +
    En plus de la syntaxe usuelle (tight) RE, dans laquelle tous les caractХres sont signifiants, il y a une syntaxe expansИe, disponible dans toutes les sortes de RE avec le switch -expanded, ou dans les  AREs avec l'option x. Dans la syntaxe expansИe, les espaces sont ignorИs et tout caractХre entre un # et les newline suivantes (ou la fin de la RE) sont ignorИ, permettant de paragrapher et de commenter une RE complexe. Il y a trois exceptions Ю cette rИgle de base:
    +
    un espace ou un `#' prИcИdИs  par `\' est retenu
    +
    un espace ou un `#' Ю l'intИrieur d'une expression crochet est retenu
    +
    un espace et des commentaires sont illИgaux dans les symboles multi-caractХres comme le `(?:' ARE ou le `\( ' BRE

    +
    Les caractХres espace de la syntaxe expansИe sont le blank, tab, newline, et tout caractХre qui appartient Ю la classe de caractХre space.
    +
    Finalement, dans une ARE, en dehors des expressions crochet, la sИquence `(?#ttt)' (oЫ ttt est un texte quelconque ne contenant pas de `)') est un commentaire, complХtement ignorИ. De mЙme, ceci n'est pas autorisИ entre les caractХres de symboles multi-caractХre comme `(?:'. Ces commentaires sont plus un artefact historique que une utile facilitИ, et leur usage est obsolХte; utilisez plutot la syntaxe expansИe de.
    +
    Aucune de ces extensions de mИtasyntaxe ne sont disponibles si l'application (ou un director initial ***=) a spИcifiИ que les entrИes de l'utilisateur doivent Йtre traitИes comme une chaНne littИrale plutТt que comme une RE. +

    +
    CORRESPONDANCES

    +
    Dans l'ИvХnement oЫ une RE peut correspondre Ю plus d'une sous chaНne d'une chaНne donnИe, la RE correspond Ю la premiХre occurence dans la chaНne. Si la RE peut correspondre Ю plus d'une sous chaНne commenГant Ю ce point, le choix est dИterminИ par sa prИfИrence: soit la plus longue sous chaНne, soit la plus courte.
    +
    La plupart des atomes, et toutes les contraintes, n'ont pas de prИfИrence. Une RE entre parenthХses a la mЙme prИfИrence (Иventuellement aucune) que la RE. Un atome quantifiИ avec {m} ou {m}? a la mЙme prИfИrence (Иventuellement aucune)que l'atome lui-mЙme. Un atome quantifiИ avec d'autres quantificateurs normaux (incluant {m,n} avec m Иgal Ю n) prefХre la correspondance la plus longue. Un atome quantifiИ avec d'autre quantificateurs non-greedy (incluant {m,n}? avec m Иgal Ю n) prefХre la correspondance la plus courte. Une branche a la mЙme prИfИrence que le premier atome quantifiИ inclus qui a une prИfИrence. Une RE consistant de deux branches ou plus connectИes par l'opИrateur | prИfХre la correspondance la plus longue.
    +
    Sujettes aux contraintes imposИes par les rХgles de correspondance Ю la totalitИ de la RE, les sous-expressions correspondent au sous-chaНnes les plus longues ou les plus courtes possible, basИes sur leurs preferences, avec les sous-expressions commenГant en premier dans la RE prioritaires sur celles commenГant plus loin. Notez que les sous-expressions prennent le pas sur leurs sous-expressions internes.
    +
    Notez que les quantificateurs {1,1} et {1,1}? peuvent Йtre utilisИs pour forcer la prИfИrence, sur une sous-expression ou une RE complХte.
    +
    Les longueurs des correpondances sont mesurИes en caractХres, pas en ИlИments d'assemblage. Une chaНne vide est considerИe plus longue qu'aucune correspondance. Par exemple, bb* correspond aux trois caractХres cebtraux de `abbbc', (week|wee)(night|knights) correspond aux dix caractХres de `weeknights', quand (.*).* est comparИ Ю abc la sous-expression entre parenthХses correspond aux trois caractХres, et quand (a*)* est comparИ Ю bc Ю la fois la RE complХte et la sous-expression entre parenthХses correspond Ю une chaНne vide.
    +
    Si une correspondance indИpendante de la casse est spИcifiИe, l'effet est le mЙme que si toute distinction de casse avait disparu de l'alphabet. Quand un caractХre qui existe dans les deux casses apparait comme un caractХre ordinaire en dehors d'une expression crochet, il est effectivement transforme en une expression crochet contenant les deux casses, ainsi x devient `[xX]'. Quand il apparait dans une expression crochet, toute contrepartie de sa casse est  ajoutИe Ю l'expression crochet, ainsi [x] devient [xX] et [^x] devient `[^xX]'.
    +
    Si une correspondance sensible au saut de ligne est spИcifiИe, les expressions . et crochets utilisant ^ ne correspondront  jamais au caractХre newline (ainsi la correspondance ne traverse jamais les saut de lignes Ю moins que la RE le demande explicitement ) et ^ et $ correspondront Ю la chaНne vide respectivement aprХs et avant un saut de ligne, en plus de correspondre respectivement au dИbut et Ю la fin d'une chaНne. Les \A et \Z ARE continuent Ю correspondre au dИbut et Ю la fin d'une chaНne seulement.
    +
    Si une correspondance sensible au saut de ligne partielle est spИcifiИe, elle affecte les expressions . et crochets comme la correspondance sensible au saut de ligne, mais pas ^ et `$'.
    +
    Si une correspondance sensible au saut de ligne partielle inverse est spИcifiИe, elle affecte ^ et $ comme la correspondance sensible au saut de ligne, mais pas les expressions . et crochets. Ceci n'est pas trИs utile mais est fourni pour la symИtrie +

    +
    LIMITES ET COMPATIBILITE

    +
    Aucune limite particuliХre n'est imposИe Ю la longueur des REs. Les programmes conГue pour Йtre hautement portables ne devront pas employer de REs plus longues que 256 octets, car une implИmentation POSIX-compatible peut les refuser.
    +
    La seule fonctionnalitИ des AREs actuellement incompatible avec les EREs POSIX est que \ ne perd pas sa signification spИciale Ю l'intИrieur des expression crochets. Toutes les autres fonctionnalitИs ARE utilisent une syntaxe qui est illИgale ou a des effets indИfinis ou non specifiИs dans les EREs POSIX; la syntaxe *** des directors est de mЙme en dehors de la syntaxe POSIX pour les BREs et les EREs.
    +
    Beaucoup des extensions ARE sont extraites de Perl, mais quelques unes ont ИtИ nettoyИes, et quelques extensions Perl ne sont pas prИsentes. Les incompatibilitИs inclutnt `\b', `\B', l'absence de traitement spИcial pour un newline Ю la fin, l'addition d'expression crochets pour les cas affectИs par la correspondance sensible au saut de ligne, les restrictions sur les parenthХses et les back rИfИrences dans les contraintes avant, et la sИmantique des correspondances plus long/plus court (plutТt que premier-trouvИ).
    +
    Les rХgles de correspondance pour les REs contenant Ю la fois des quantificateurs normaux et non-greedy ont changИ depuis les premiХres versions beta-test de ce package. (Les nouvelles rХgles sont plus simples et plus propre, mais ne travaillent pas trop dur pour deviner les intentions rИelles de l'utilisateur.)
    +
    Le package original regexp de 1986 par Henry Spencer, toujours largement utilisИ (ex., dans les pre-8.1 releases de Tcl), implИmentait une premiХre version des EREs d'aujourd'hui. Il y a quatre incompatibilitИs entre les regexp  proches des EREs (`RREs') et les AREs. Dans un ordre croissant de signification:
    +
    Dans les AREs, \ suivi d'un caractХre alphanumИrique est soit un Иchappement soit une erreur, alors que dans les RREs, c'Иtait juste un autre moyen d'Иcrire l'alphanumИrique. Ceci ne sera pas une problХme parce que il n'y a pas de raison d'Иcrire une sИquence pareille dans les RREs.
    +
    Un { suivi d'un chiffre dans un ARE est le dИbut d'un intervalle, alors que dans les RREs, { a toujours ИtИ un caractХre ordinaire. De telles sИquences seront rares, et donneront souvent une erreur parce que les caractХres suivants ne ressembleront pas Ю un intervalle valide.
    +
    Dans les AREs, \ introduit un caractХre spИcial dans `[]', donc un \ littИral dans [] doit Йtre Иcrit `\\'. \\ donne aussi un \ littИral dans [] dans les RREs, mais seuls les programmeurs vraiment paranoïaques doublent le backslash par routine.
    +
    AREs rapporte la plus longue/plus courte correspondance de la RE, plutТt que le premier trouvИ dans l'ordre de recherche spИcifiИ. Ceci peut affecter quelque RREs qui aurait ИtИ Иcrites dans l'hypothХse oЫ la premiХre correspondance serait rapportИe. (La rИdaction soigneuse des RREs pour optimiser l'ordre de recherche pour une comparaison rapide est obsolХte (les AREs examinent toutes les correspondances possible en parallХle, et leurs performances sont largement insensible Ю leur complexitИ) mais les cas oЫ l'ordre de recherche a ИtИ exploitИ pour trouver delibИrИment une correspondance qui n'est pas la plus longue/plus courte devront Йtre rИИcrits.) +

    +
    BASIC REGULAR EXPRESSIONS

    +
    Les BREs diffХrent des EREs sous plusieurs aspects `|', `+', et ? sont des caractХres ordinaires et il n'y a pas d'Иquivalent Ю leurs fonctionalitИ. Les dИlimiteurs des intervalles sont \{ et `\}', avec les { et } interprИtИes seules comme des caractХres ordinaires. Les parenthХses des sous expressions imbriquИes sont \( et `\)', avec les ( et ) interprИtИes seules comme des caractХres ordinaires. ^ est un caractХre ordinaire exceptИ au dИbut de la RE ou au dИbut d'une sous expressions entre parenthХses, $ est un caractХre ordinaire exceptИ Ю la fin de la RE ou la fin d'une sous expressions entre parenthХses, et * est un caractХre ordinaire s'il apparait au dИbut de la RE ou au dИbut d'une sous-expression entre parenthХses (aprХs un `^'possible en tЙte). Finalement, les back rИfИrences Ю un seul chiffre sont disponibles, et \< et \> sont des synonymes de [[:<:]] et [[:>:]] respectivement; aucun autre echappement ne sont disponibles +

    +
    VOIR EGALEMENT

    +
    RegExp(3.htm), regexp(n), regsub(n), lsearch(n), switch(n), text(n)

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/read.htm b/hlp/fr/tcl/read.htm new file mode 100644 index 0000000..a03619a --- /dev/null +++ b/hlp/fr/tcl/read.htm @@ -0,0 +1,21 @@ + + + + +

    read      Commandes Internes Tcl


    +
    NOM

    +
    read √ Lit  Ю partir d'un canal +

    +
    SYNTAXE

    +
    read ?-nonewline? channelId
    +read channelId numChars +

    +
    DESCRIPTION

    +
    Sous la premiХre forme, la commande read lit toutes les donnИes provenant de channelId jusqu'Ю la fin du fichier. Si le switch - nonewline est spИcifiИ alors le dernier caractХre du fichier est retirИ si c'est un caractХre de fin de ligne. Sous la seconde forme, l'argument supplИmentaire spИcifie combien de caractХres la commande doit lire. Ce nombre exact de caractХres sera lu et retournИ, sauf s'il y a moins que numChars caractХres restant dans le fichier; dans ce cas tous les caractХres restant sont retournИs. Si le canal  de communication est configurИ pour utiliser un encodage sur plusieurs octets, le nombre de caractХres lus peut Йtre diffИrent du nombre d'octets lus..
    +
    Si channelId est en mode non bloquant, la commande peut ne pas lire autant de caractХres que requisune fois que toutes les donnИes d'entrИe auront ИtИ luesa commande renverra les donnИes disponibles plutТt que de bloquer en attente de donnИes complИmentaires . Si le canal de communication est configurИ pour utiliser un encodage sur plusieurs octets, alors il peut rИellement rester quelques octets dans les tampons internes, qui ne forment pas un caractХre complet. Ces octets ne seront retournИs que lorsqu'un caractХre complet sera  disponible ou qu'une fin de fichier sera rencontrИe. Le switch - nonewline est ignorИ si la commande se termine avant d'atteindre la fin du fichier. Read traduit les sИquences de fin de ligne de l'entrИe en caractХres de fin de ligne, en fonction de l'option -translation associИe au canal de communication. Voir l'entrИe fconfigure du manuel pour une explication sur les moyens par lesquels fconfigure modifiera les donnИes d'entrИe.

    +
    VOIR EGALEMENT

    +
    eof(n), fblocked(n), fconfigure(n) 

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/regexp.htm b/hlp/fr/tcl/regexp.htm new file mode 100644 index 0000000..36146be --- /dev/null +++ b/hlp/fr/tcl/regexp.htm @@ -0,0 +1,57 @@ + + + + +

    regexp      Commandes Internes Tcl +

    +

    +
    NOM
    +
    regexp - Compare une expression rationelle Ю une chaНne +

    +
    SYNTAXE

    +
    regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...
    +

    +
    DESCRIPTION

    +
    Determine si l'expression rationelle exp correspond Ю tout ou partie de string et retourne 1 si vrai, 0 si faux, Ю moins que -inline soit spИcifiИ (voir ci-dessous). (la correspondance des expressions rationelles est dИcrite dans la page de rИfИrence de re_syntax.)
    +
    Si des arguments supplИmentaires sont spИcifiИs aprХs string alors ils sont traitИs comme les noms des variables dans lesquelles renvoyer l'information au sujet de la ou les parties de string correspondant Ю exp. MatchVar sera fixИ Ю la partie de string correspondant Ю exp La premiХre subMatchVar contiendra les caractХres de string qui correspondent Ю la sous expression entre parenthХses la plus Ю gauche dans exp, la subMatchVar suivante contiendra les caractХres qui correspondent Ю la sous expression entre parenthХses suivante Ю droite dans exp, et ainsi de suite.
    +
    Si les arguments initiaux Ю regexp commencent avec - alors ils sont traitИs comme des commutateurs. Les commutateurs suivants sont couramment supportИs:
    +
    +
    +
    -about
    Au lieu de tenter de correspondre Ю une expression rationelle, retourne une liste contenant l'information concernant l'expression rationelle Le premier ИlИment de la liste est un compte des sous expressions Le second ИlИment est une liste de noms de propriИtИ qui decrivent plusieurs attributs de l'expression rationelle. Ce switch est conГu dans un but de debugging. +
    +
    -expanded
    Active l'usage de la syntaxe Иtendue des expressions rationelles oЫ l'espace et les commentaires sont ignorИs. Identique Ю la spИcification de l'option (?x) (voir METASYNTAXE, ci-dessous). +
    +
    -indices
    Change ce qui est stockИ dans les subMatchVars Au lieu de stocker les caractХres correspondants de string, chaque variable contiendra une liste de deux chaНnes dИcimales donnant les indices dans string des premiers et derniers caractХres dans l'intervalle correspondant des caractХres. +
    +
    -line
    Active la correspondance sensible au saut de ligne Par dИfaut, le saut de ligne est un caractХre ordinaire sans signification spИciale Avec ce flag, l' expression crochets `[^' et `.' ne correspond jamais Ю newline, `^' correspond Ю une chaНne vide aprХs toute newline en plus de sa fonction normale, et `$' correspond une chaНne vide avant toute newline en en plus de sa fonction normale Ce flag est Иquivalent Ю la spИcification Ю la fois de          -linestop et -lineanchor, ou de l'option (?n) (voir METASYNTAXE, ci-dessous). +
    +
    -linestop
    Change le comportement de l'expression crochets `[^' et `.' de faГon Ю ce qu'elles s'arrХtent aux saut de lignes Ceci est identique Ю la spИcification de l'option (?p) (voir METASYNTAXE, ci-dessous). +
    +
    -lineanchor
    Change le comportement de `^' et `$' (les "ancres") de faГon Ю ce qu'ils correspondent au dИbut et Ю la fin d'une ligne respectivement Ceci est identique Ю la spИcification de l'option (?w) (voir METASYNTAXE, ci-dessous). +
    +
    -nocase
    Cause l'interprИtation des caractХres majuscules de string comme minuscules pendant le traitement des correspondances. +
    +
    -all
    Teste la correspondance de l'expression rationelle le plus grand nombre de fois possible dans la chaНne, retournant le nombre total de correspondances trouvИes Si spИcifiИ avec des variables de correspondance, ne contiendront l'information que pour la derniХre correspondance. +
    +
    -inline
    Provoque le renvoi, comme liste, des donnИes qui auraient ИtИ autrement placИes dans des variables de correspondance Quand √inline est utilisИe, les variables de correspondance ne peuvent pas Йtre spИcifiИes Si utilisИ avec -all, la liste sera concatИnИe Ю chaque itИration, de ce fait une liste plate est toujours renvoyИe Pour chaque itИration, la commande ajoutera les correspondances supplИmentaires aux donnИes, plus un ИlИment pour chaque sous expression dans l'expression rationelle. Exemples:
    + regexp -inline -- {\w(\w)} " inlined "
    + => {in n}
    + regexp -all -inline -- {\w(\w)} " inlined "
    + => {in n li i ne e}
    + +
    +
    +
    -start index
    SpИcifie un index de caractХre dans une chaНne pour commencer la correspondance Ю une expression rationelle A l'utilisation de ce switch, `^' ne correspond plus au dИbut de la ligne, et \A correspond toujours au dИbut de la chaНne Ю index Si -indices est spИcifiИ, les indices seront indexИs en partant du  dИbut de la chaНne d'entrИe. index sera contraint au limites de la chaНne d'entrИe. +
    +
    --
    Marque la fin des commutateurs L'argument suivant ceci sera traitИ comme exp mЙme s'il commence avec un -. +
    +
    +
    +
    S'il y a plus de subMatchVar que de sous expressions entre parenthХses dans exp, ou si une sous expression particuliХre dans exp ne correspond pas Ю la chaНne (ex. parcequ'il etait dans une partie de l'expression qui n'a pas ИtИ trouvИe), alors la subMatchVar correspondante sera fixИe Ю "-1-1" si -indices a ИtИ spИcifiИ ou Ю une chaНne vide autrement +

    +
    VOIR EGALEMENT

    +
    re_syntax(n) 

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/registry.htm b/hlp/fr/tcl/registry.htm new file mode 100644 index 0000000..0892f27 --- /dev/null +++ b/hlp/fr/tcl/registry.htm @@ -0,0 +1,85 @@ + + + + +

    registry      Commandes Internes Tcl



    +
    NOM
    +
    registry - Manipule la base de registre Windows +

    +
    SYNTAXE

    +

    +package require registry 1.0
    +registry option keyName ?arg arg ...? +

    +
    DESCRIPTION

    +
    Le package registry fournit un ensemble gИnИral d'opИrations pour manipuler la base de registre Windows Le package implИmente la commande Tcl registry. Cette commande est supportИe seulement sur la plateforme Windows. Attention: cette commande sera utilisИe avec prИcaution car une base de registre corrompue peut rendre votre systХme inutilisable.
    +
    KeyName est le nom d'une clИ de registre. Les clИs doivent avoir une des formes suivantes:
    +
    \\hostname\rootname\keypath
    +
    rootname\keypath
    +
    rootname
    +
    Hostname spИcifie le nom d'une machine Windows quelconque qui exporte sa base de registre. Le composant rootname doit Йtre un d'entre HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, ou HKEY_DYN_DATA. Le keypath peut Йtre un ou plusieurs noms de clИ de registre sИparИes par des caractХres backslash (\).
    +
    Option indique que faire avec le nom de clИ de registre. N'importe quelle abrИviation unique pour option est acceptable. Les options valides sont: +
    +
    registry delete keyName ?valueName? +
    Si l'argument optionnel valueName est prИsent, la valeur spИcifiИe sous keyName sera effacИe de la base de registre. Si l'optionnelle valueName est omise, la clИ spИcifiИe et toute sous-clИ ou valeurs en dessous dans la hiИrarchie de la base de registre seront effacИes. Si la clИ n'a pu Йtre effacИe alors une erreur est gИnИrИe. Si la clИ n'existe pas, la commande n'a pas d'effet. +
    +

    +registry get keyName valueName +
    Renvoie les donnИes associИes Ю la valeur valueName sous la clИ keyName. Si la clИ ou la valeur n'existe pas, alors une erreur est gИnИrИe. Pour plus details sur le format des donnИes renvoyИes, voir TYPES SUPPORTES, ci-dessous. +
    +

    +registry keys keyName ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de noms de tout les sous-clИs de keyName Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont retournИs La correspondance est dИterminИe en utilisant le mЙme rХgles que pour string match. Si le keyName spИcifiИ n'existe pas, alors une erreur est gИnИrИe. +
    +

    registry set keyName ?valueName data ?type?? +
    +Si valueName n'est pas spИcifiИ, crИe la clИ keyName si elle n'existe pas dИjЮ. Si valueName est spИcifiИ, crИe la clИ keyName et la valeur valueName si nИcessaire Le contenu de valueName est fixИ Ю data avec le type indiquИe par type. Si type n'est pas spИcifiИ, le type sz est supposИ. Pour plus details sur les types de donnИes et d'arguments , voir TYPES SUPPORTES ci-dessous. +
    +

    registry type keyName valueName +
    +Renvoie le type de la valeur valueName dans la clИ keyName. Pour plus ample information sur les types possibles, voir TYPES SUPPORTES, ci-dessous. +
    +

    +registry values keyName ?pattern? +
    Si pattern n'est pas spИcifiИ, retourne une liste de noms de toutes les valeurs de keyName. Si pattern est spИcifiИ, seulement les noms correspondants Ю pattern sont renvoyИs. La correspondance est dИterminИe en utilisant les mЙme rХgles que pour string match +
    +
    +

    +
    TYPES SUPPORTES

    +
    Chaque valeur sous une clИ dans la base de registre contient des donnИes d'un type particulier dans une reprИsentation spИcifique. La commande registry convertit entre cette reprИsentation interne et celle qui peut Йtre manipulИe par les scripts Tcl. Dans la plupart des cas, les donnИes sont simplement renvoyИes comme chaНnes Tcl. Le type indique pour quel usage sont conГues les donnИes, mais ne change pas la reprИsentation. Pour certains types, la commande registry retourne les donnИes sous une forme diffИrente pour en faciliter la manipulation. Les types suivant sont reconnus par la commande registry: +
    +
    binary
    La valeur du registre contient des donnИes binaires arbitraires. Les donnИes sont representИes exactement enTcl, incluant tous les nulls contenus. +
    +

    none +
    La valeur du registre contient des donnИes binaires arbitraires sans type dИfini. Les donnИes sont representИes exactement en Tcl, incluant tous les nulls contenus. +
    +

    sz +
    La valeur du registre contient une chaНne Ю zИro terminal. Les donnИes sont representИes en Tcl comme chaНnes. +
    +

    expand_sz +
    La valeur du registre contient une chaНne Ю zИro terminal qui contient des rИfИrences non expansИes aux variables d'environnements dans le style Windows normal (par exemple, "%PATH%") Les donnИes sont representИes en Tcl comme chaНne. +
    +
    +

    dword +
    La valeur du registre contient un nombre 32-bit little-endian. Les donnИes sont representИes en Tcl comme une chaНne dИcimale. +
    +

    dword_big_endian +
    La valeur du registre contient un nombre 32-bit big-endian. Les donnИes sont representИes en Tcl comme une chaНne dИcimale. +
    +

    link +
    La valeur du registre contient un lien symbolique. Les donnИes sont representИes exactement en Tcl, incluant tous les nulls contenus. +
    +

    multi_sz +
    La valeur du registre contient un tableau chaНnes Ю zИro terminal. Les donnИes sont representИes en Tcl comme une liste de chaНnes. +
    +

    resource_list +
    La valeur du registre contient une liste de pilotes de pИriphИriques. Les donnИes sont representИes exactement en Tcl, incluant tous les nulls contenus. +
    +

    +
    En plus des noms de types symboliques listИs plus haut, les types inconnus sont identifiИs en utilisant un entier 32-bit qui correspond au code de type renvoyИ par les interfaces systХme. Dans ce cas, les donnИes sont representИes exactement en Tcl, incluant tous les nulls contenus. +

    +
    PROBLEMES DE PORTABILITE

    +
    La commande registry est seulement disponible sous Windows
    +
    +
    + diff --git a/hlp/fr/tcl/regsub.htm b/hlp/fr/tcl/regsub.htm new file mode 100644 index 0000000..87c05fc --- /dev/null +++ b/hlp/fr/tcl/regsub.htm @@ -0,0 +1,38 @@ + + + + +
    regsub      Commandes Internes Tcl
    +
    +
    NOM

    +
    regsub - Effectue des substitutions de chaНnes basИes sur l'identification d'expressions rationnelles
    +

    +
    SYNTAXE

    +
    regsub ?switches? exp string subSpec varName  +

    +
    DESCRIPTION

    +
    Cette commande cherche une correspondance de l'expression exp dans string, et elle copie string dans la variable dont le nom est donnИ par varName. (la correspondance avec les expressions rationnelles est dИcrite dans la page de rИfИrence de re_syntax.) S'il y a une correspondance, alors pendant la copie de string vers varName, la partie de "string" qui correspond Ю "exp" est remplacИe par subSpec. Si subSpec contient un ''&'' ou ''\0'', cette sИquence est remplacИe lors de la substitution, par la partie de chaНne qui correspond Ю "exp". Si subSpec contient un ''\n'' oЫ n est un chiffre entre 1 et 9, cette sИquence est remplacИe pendant la substitution par la partie de chaНne qui correspond Ю la n_iХme sous expression de "exp". Pour Иviter cette interprИtation spИciale de ''&'',  ''\0'' ou ''\n'', on peut ajouter des antislashs additionnels. Attention, l'usage d'antislashs dans subSpec tend Ю provoquer des conflits avec l'emploi des antislashs dans le parser de Tcl, c'est pourquoi il est souvent plus sûr d'encadrer subSpec par des accolades s'il contient des antislashs. Si les arguments initiaux de regexp commencent avec -, ils sont alors traitИs comme des switchs. Les switchs suivants sont actuellement reconnus:
    +
    +
    +
    -all
    Toutes les sИquences dans "string" qui interceptent "exp" sont trouvИes et la substitution est faite sur chacune de ces sИquences. Sans ce switch, seule la premiХre sИquence est substituИe. Si -all est indiquИ, alors les sИquences ''&' et ''\n'' sont traitИes pour chaque substitution en utilisation l'information de l'interception adИquate. +
    +
    -expanded
    Autorise l'utilisation d'expressions rationnelles Иtendues, oЫ le blanc et les commentaires sont ignorИs. Ceci est la mЙme chose que d'indiquer l'option embarquИe (?x). (voir METASYNTAXE, dans la page re_syntax) +
    +
    -line
    Autorise la sensibilitИ au retour-chariot (newline). Par dИfaut newline est un caractХre ordinaire sans signification particuliХre. Avec ce switch, les expressions entre crochets '[^' et le '.' n'interceptent jamais newline, '^' intercepte une chaНne vide aprХs newline en complИment de sa fonction normale, et '$' intercepte une chaНne vide avant newline en plus de sa fonction normale. Ce switch est Иquivalent aux switchs -linestop et -lineanchor rИunis, ou bien Ю l'option embarquИe (?n). (voir METASYNTAXE, dans la page re_syntax ) +
    +
    -linestop
    Change le comportement des expressions entre crochets '[^' et l'expression '.' de faГon qu'ils s'interrompent en rencontrant des retours chariots (newline). Ceci est Иquivalent Ю l'option embarquИe (?p). (voir METASYNTAXE, dans la page re_syntax) +
    +
    -lineanchor
    Change le comportement des expression '^' et '$' (les ''ancres'') de telle sorte qu'ils interceptent respectivement le dИbut et la fin d'une ligne. Ceci est le mЙme que d'indiquer l'option embarquИe (?w). (voir METASYNTAXE, dans la page re_syntax) +
    +
    -nocase
    Les lettres majuscules de "string" seront converties en minuscules avant d'Йtre comparИes Ю "exp"; cependant les substitutions indiquИes par subSpec utilisent la forme originale, avant conversion, de "string". +
    +
    -start index
    Indique une position de caractХre dans string, Ю partir de laquelle il faut commencer la recherche d'expression rationnelle. Quand on utilise ce switch, '^' n'interceptera pas le dИbut de la ligne, et \A interceptera toujours le dИbut de la chaНne Ю l'index indiquИ. L'index sera contraint dans les limites effectives de la chaНne entrИe. +
    +
    --
    Marque la fin des switches. L'argument suivant cette fin sera traitИ comme Иtant l'expresssion "exp", mЙme s'il commence par -.
    +
    +

    +
    Cette commande renvoie le nombre de sИquences qui ont ИtИ interceptИes et remplacИes. Voir le manuel Ю regexp pour des prИcisions sur l'interprИtation des expressions rationnelles.

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/rename.htm b/hlp/fr/tcl/rename.htm new file mode 100644 index 0000000..476c7d7 --- /dev/null +++ b/hlp/fr/tcl/rename.htm @@ -0,0 +1,16 @@ + + + + +

    rename      Commandes Internes Tcl

    +
    +
    NOM

    +
    rename - Renomme ou efface une commande

    +
    SYNTAXE

    +
    rename oldName newName +

    +
    DESCRIPTION

    +
    Renomme la commande appelИe oldName en newName. Si newName est une chaНne vide alors oldName est effacИe. oldName et newName peuvent inclure des qualificateurs namespace (les noms des namespaces contenant). Si une commande est renommИe dans un namespace diffИrent , ses appels futurs s'exИcuteront dans le nouveau namespace.
    +
    +
    + diff --git a/hlp/fr/tcl/resource.htm b/hlp/fr/tcl/resource.htm new file mode 100644 index 0000000..1a6455b --- /dev/null +++ b/hlp/fr/tcl/resource.htm @@ -0,0 +1,79 @@ + + + + +

    resource      Commandes Internes Tcl

    +
    +
    NOM
    +
    resource - Manipule les resources Macintosh +

    +
    SYNTAXE

    +
    resource option ?arg arg ...? +

    +
    DESCRIPTION

    +
    La commande resource fournit des opИrations gИnИriques pour la gestion des resources Macintosh Cette commande est supportИe seulement sur la plateforme Macintosh. Chaque fichier Macintosh consiste en deux forks: une fork data et une fork resource. Vous utilisez les commandes normales open, puts, close, etc. pour manipuler les fork data. Vous devez utiliser cette commande, nИanmoins, pour interagir avec le fork resource Option indique quelle commande resource effectuer. N'importe quel abrИviation unique pour option est acceptable Les options valides sont: +
    +
    resource close rsrcRef +
    Ferme la rИfИrence resource donnИe (obtenue par resourceopen) Les resources de ce fichier resource ne seront plus disponibles. +
    +

    resource delete ?options? resourceType +
    Cette commande effacera la resource spИcifiИe par options et le type resourceType (voir TYPES DE RESOURCES ci-dessous) Les options vous donnent plusieurs faГons de spИcifier l'effacement de la resource. +
    +
    -id resourceId +
    Si l'option -id est donnИe l'id resourceId (voir IDS DE RESOURCE ci-dessous) est utilisИ pour spИcifier la resource Ю effacer L'id doit  Йtre un nombre - pour spИcifier un nom utiliser l'option -name. +
    +
    -name resourceName +
    Si -name est spИcifiИ, la resource nommИe resourceName sera effacИe. Si -id est aussi fournie, alors il doit exister une resource avec A LA FOIS ce nom et cet id. Si aucun nom n'est fourni, alors l'id sera utilisИ indИpendemment du nom de la resource. +
    +
    -file resourceRef +
    Si l'option -file est spИcifiИe alors la resource sera effacИe du fichier pointИ par resourceRef Autrement la premiХre resource avec le resourceName donnИ et ou resourceId qui est trouvИ dans le chemin du fichier resource sera  effacИ. Pour inspecter le chemin du fichier, utiliser la commande resource files. +
    +
    +
    +

    resource files ?resourceRef? +
    Si resourceRef n'est pas fournie, cette commande retourne une liste Tcl des rИfИrences de resource pour tous les fichiers resources couramment ouverts. La liste est dans l'ordre de recherche normal Macintosh pour les resources. Si resourceRef est spИcifiИ, la commande renverra le chemin vers le fichier dont le fork resource est representИ par ce jeton. +
    +

    resource list resourceType?resourceRef? +
    Liste tous les ids resources de type resourceType (voir TYPES DE RESOURCE ci-dessous) Si resourceRef est spИcifiИ alors la commande limitera la recherche Ю ce fichier resource particulier. Autrement, tout fichier resource couramment ouvert par l'application sera recherchИ. Une liste Tcl de soit le nom soit l'id de resource des resources trouvИes sera renvoyИe. Voir la section IDS DE RESOURCE ci-dessous pour plus de dИtails au sujet de ce qu'est un id de resource. +
    +

    resource open fileName ?access? +
    Ouvre la resource pour le fichier fileName. Les permissions d'accХs fichier standard peuvent aussi Йtre spИcifiИes (voyez la page de manuel de open pour les dИtails). Une rИfИrence de resource (resourceRef) est renvoyИe qui peut Йtre utilisИe par les autres commandes resource. Une erreur peut se produire si le fichier n'existe pas ou si le fichier n'a pas de fork resource. NИanmoins, si vous ouvrez le fichier avec des permissions d'Иcriture le fichier et/ou le fork resource sera crИИ au lieu de gИnИrer une erreur. +
    +

    resource read resourceType resourceId ?resourceRef? +
    Lit la totalitИ de la resource de type resourceType (voir TYPES DE RESOURCE ci-dessous) et le nom ou l'id of resourceId (voir IDS DE RESOURCE ci-dessous) en mИmoire et retourne le rИsultat. Si resourceRef est spИcifiИ, la recherche sera limitИe au fichier resource, autrement on recherchera tous les forks resource ouverts dans l'application. Il est important de noter que la plupart des resource Macintosh utilisent un format binaire et les donnИes renvoyИ par cette commande peuventt contenir des NULLs ou d'autres donnИes non-ASCII. +
    +

    resource types ?resourceRef? +
    Cette commande retourne une liste Tcl de tous les types de resource (voir TYPES DE RESOURCE ci-dessous) trouvИs dans le fichier resource pointИ par resourceRef. Si resourceRef n'est pas spИcifiИ elle renverra tout les types de resource trouvИs dans tous les fichiers resource couramment ouverts par l'application. +
    +

    resource write ?options? resourceType data +
    Cette commande Иcrit les data transmises en tant qu'une nouvelle resource de type resourceType (voir TYPES DE RESOURCE ci-dessous). Plusieurs options sont disponibles qui decrivent oЫ et comment la resource est stockИe. +
    +
    -id resourceId
    Si l'option -id est donnИe, l'id resourceId (voir IDS DE RESOURCE ci-dessous) est utilisИ pour la nouvelle resource, autrement un id unique sera gИnИrИ qui n'entrera pas en conflit avec une resource existante. NИanmoins, l'id doit Йtre un nombre - pour spИcifier un nom utiliser l'option -name. +
    +
    -name resourceName +
    Si -name est spИcifiИ le resource sera nommИe resourceName, autrement elle aura pour nom la chaНne vide. +
    +
    -file resourceRef +
    Si l'option -file est spИcifiИe alors la resource sera Иcrite dans le fichier pointИ par resourceRef, autrement la resource la plus recemment ouverte sera utilisИe. +
    +
    -force +
    Si la resource cible existe dИjЮ, alors par dИfaut Tcl ne l'Иcrasera pas, mais lХvera une erreur. Utilisez le flag -force pour forcer l'Иcrasement de la resource existante +
    +
    +
    +
    +

    +
    TYPES DE RESOURCE

    +
    Les types de resource sont dИfinis comme une chaНne de quatre caractХre qui est alors mappИe Ю un id sous-jacent Par exemple, TEXT se rИfХre au type de resource Macintosh pour le texte. Le type STR# est une liste de chaНnes indexИe. Toutes les resources Macintosh doivent avoir un type. Voir la documentation Macintosh pour une liste plus complХte des types de resource qui sont communИment utilisИs. +

    +
    IDS DE RESOURCE

    +
    Pour cette commande la notion d'un id de resource se refХre Ю deux idИes sur les resources Macintosh. Partout oЫ vous pouvez utiliser un Id de resource, vous pouvez utiliser soit le nom de resource ou un numИro de resource. Les noms sont toujours recherchИs ou renvoyИs de prИfИrence aux numИros. Par exemple, la commande resource list renverra les noms s'ils existent ou les numИros si le nom est NULL. +

    +
    PROBLEMES DE PORTABILITE

    +
    La commande resource est seulement disponible sur Macintosh.

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/return.htm b/hlp/fr/tcl/return.htm new file mode 100644 index 0000000..5bb47d6 --- /dev/null +++ b/hlp/fr/tcl/return.htm @@ -0,0 +1,45 @@ + + + + +

    return      Commandes Internes Tcl

    +
    +
    NOM

    +
    return - Retourne d'une fonction +

    +
    SYNTAXE

    +
    retourne ?-code code? ?-errorinfo info? ?-errorcode code? ?string
    +

    +
    DESCRIPTION

    +
    Retourne immИdiatement de la fonction courante (ou d'une commande d'avant plan ou d'une commande source), avec string comme valeur de retour. Si string n'est pas spИcifiИe alors une chaНne vide sera renvoyИe comme rИsultat
    +

    +
    RETOURS EXCEPTIONNELS

    +
    Dans le cas normal oЫ l'option -code n'est pas spИcifiИe la fonction renverra normalement (son code de retour sera TCL_OK). NИanmoins, l'option -code peut Йtre employИe pour gИnИrer un retour exceptionnel de la fonction. Code peut avoir une des valeurs suivantes: +
    +
    ok +
    Retour normal: idem que si l'option est omise. +
    +

    error +
    Retour d'erreur: idem que si la commande error avait ИtИ utilisИe pour terminer la fonction, exceptИ pour la gestion des variables errorInfo et errorCode (voir ci-dessous). +
    +

    return +
    La fonction courante renvoie un code de retour de TCL_RETURN, ainsi que la fonction qui l'a appelИe. +
    +

    break +
    La fonction courante renvoie un code de retour de TCL_BREAK, qui terminera la boucle la plus imbriquИe dans le code qui a appelИ la fonction courante. +
    +

    continue +
    La fonction courante renvoie un code de retour de TCL_CONTINUE, qui terminera l'itИration courante de la boucle la plus imbriquИe dans le code qui appelИe la fonction courante. +
    +

    value +
    Value doit Йtre un entier, il sera renvoyИ comme code de retour de la fonction courante. +
    +

    +
    L'option -code est rarement utilisИe. Elle est fournie pour que les fonctions qui implИmentent de nouvelles structures de contrТle puissent reflИter les conditions exceptionnelle Ю leurs appelants.
    +
    Deux options supplИmentaires, -errorinfo et -errorcode, peuvent Йtre employИes pour fournir une information supplИmentaire pendant le retour d'erreur. Ces options sont ignorИes Ю moins que code soit error.
    +
    L'option -errorinfo spИcifie une trace initiale de la pile pour la variable errorInfo;  si elle n'est pas spИcifiИe alors la trace de la pile transmise Ю errorInfo inclutra l'appel Ю la fonction et les niveaux supИrieurs sur la pile mais n'inclutra pas d'information concernant le contexte de l'erreur Ю l'intИrieur de la fonction. Typiquement la valeur info est fournie en partant de la valeur transmise Ю errorInfo aprХs qu'une commande catch ait interceptИ une erreur Ю l'intИrieur de la fonction.
    +
    Si l'option -errorcode est spИcifiИe alors code fournit une valeur pour la variable errorCode. Si l'option n'est pas spИcifiИe alors errorCode sera par dИfaut de NONE

    +
    DerniХre rИvision: 7.0
    +
    +
    + diff --git a/hlp/fr/tcl/safe.html b/hlp/fr/tcl/safe.html new file mode 100644 index 0000000..1778ac7 --- /dev/null +++ b/hlp/fr/tcl/safe.html @@ -0,0 +1,130 @@ + + + + +

    Safe Tcl      Commandes Internes Tcl

    +
    +
    NOM

    +
    Safe Base - MИcanisme pour la crИation et la manipulation d'interprИteurs sШr. +

    +
    SYNTAXE

    +
    ::safe::interpCreate ?slave? ?options...?
    +::safe::interpInit slave ?options...?
    +::safe::interpConfigure slave ?options...?
    +::safe::interpDelete slave
    +::safe::interpAddToAccessPath slave directory
    +::safe::interpFindInAccessPath slave directory
    +::safe::setLogCmd ?cmd arg...? +

    +
    OPTIONS

    +
    ?-accessPath pathList? ?-statics boolean? ?-noStatics? ?-nested boolean? ?-nestedLoadOk? ?-deleteHook script? +

    +
    DESCRIPTION

    +
    Safe Tcl est un mИcanisme pour exИcuter des scripts Tcl Иtrangers sans risque et pour fournir un accХs Ю de tels scripts potentiellement dangereux.
    +
    Safe Base s'assure que des scripts Tcl Иtrangers ne peuvent nuire Ю l'application hТte. Safe Base prИvient les attaques d'intИgritИ et de sИcuritИ. Les scripts Иtrangers sont empЙchИs de corrompre l'Иtat de l'application ou de l'ordinateur hТte. Ces scripts sont Иgalement empЙchИs de rИvИler l'information stockИe sur l'ordinateur principal ou dans l'application hТte Ю n'importe quel espion.
    +
    Safe Base permet Ю un interprХteur maНtre de crИer des interprХteurs sИcurisИs et restreints qui contiennent un ensemble d'alias prИdИfinis pour les commandes source, load, file, encoding, et exit et peuvent employer des mИcanismes d'auto-chargement et de paquet.
    +
    Aucune connaissance de la structure de systХme de fichiers n'est nИcessaire Ю l'interprХteur sШr, parce qu'il accХde seulement Ю un chemin virtuel contenant des repХres. Quand l'interprХteur sШr demande le source d'un fichier, il emploie les repХres dans le chemin  virtuel en tant qu'ИlИment du nom du fichier; l'interprХteur maНtre d'une maniХre transparente traduit les repХres en vrais noms de rИpertoires et exИcute l'opИration demandИe (voir la section SECURITE ci-dessous pour les dИtails). DiffИrents niveaux de sИcuritИ peuvent Йtre choisis en employant les flags optionnels des commandes dИcrites ci-dessous.
    +
    Toutes les commandes fournies dans l'interprХteur maНtre par la commande Safe Base rИsident dans le namespace safe:
    +
    +
    COMMANDES

    +
    Les commandes suivantes sont fournies dans le maНtre interprИteur: +
    +
    ::safe::interpCreate ?slave? ?options...? +
    CrИe un interprХteur sШr, installe les alias dИcrits dans la section ALIAS et initialise le mИcanisme d'auto-chargement et de paquet comme indiquИ par les options fournies. Voir la section OPTIONS ci-dessous pour un description de l optionnel arguments. ci-dessous pour une description des  arguments facultatifs. Si l'argument slave est omis, un nom sera gИnИrИ.. ::safe::interpCreate renvoie toujours le nom d'interprХteur. +
    +

    ::safe::interpInit slave ?options...? +
    Cette commande est identique Ю interpCreate exceptИ qu'elle ne crИe pas l'interprХteur sШr. slave doit avoir ИtИ crИИ par d'autres moyens, comme interp create-safe. +
    +

    ::safe::interpConfigure slave ?options...? +
    Si aucunes options ne sont donnИes, renvoie les paramХtres pour toutes les options de l'interprХteur sШr comme liste d'options et leurs valeurs courantes pour slave. Si un argument additionnel est fourni, renvoie une liste de 2 ИlИments name et valuename est le nom complet de cette option et value la valeur courante pour cette option et slave. Si plus de deux arguments additionnels sont fournis, il modifiera l'interprХteur sШr et changera chacunes et seulement les option fournies. Voir la section OPTIONS ci-dessous pour la description d'options. Exemple d'utilisation: +
            # CrИe un nouvel interp avec la mЙme configuration que "$i0" : +
            set i1 [eval safe::interpCreate [safe::interpConfigure $i0]] +
           # Obtient le deleteHook courant
    +
            set dh [safe::interpConfigure $i0  -del] +
           # Change (seulement) l'attribut de chargement statics ok d'un interp +
           # et son deleteHook (laissant le reste inchangИ) :
    +        safe::interpConfigure $i0  -delete {foo bar} -statics 0 ;
    +
    +

    ::safe::interpDelete slave +
    Efface l'interprХteur sШr et nettoie les structures de donnИes  principales correspondantes d'interprХteur. Si un script deleteHook a ИtИ spИcifiИ pour cet interprИteur, il est ИvaluИ avant l'interprИteur que soit effacИ, avec le nom de l'interprИteur comme argument additionnel. +
    +

    ::safe::interpFindInAccessPath slave directory +
    Cette commande trouve et renvoie le jeton pour le vrai rИpertoire directory de l'accХs au chemin virtuel courant de l'interprХteur sШr. Elle gИnХre une erreur si le rИpertoire n'est pas trouvИ. Exemple d'utilisation: +
           $slave eval [list set tk_library [::safe::interpFindInAccessPath $ name $tk_library]] +
    +

    ::safe::interpAddToAccessPath slave directory +
    Cette commande ajoute directory au chemin virtuel maintenu pour  l'interprХteur sШr dans le maНtre, et retourne un jeton qui peut Йtre utilisИ dans l'interprИteur sШr pour obtenir accХs aux fichiers dans ce rИpertoire. Si le rИpertoire est dИjЮ dans le chemin virtuel, elle renvoie seulement le jeton sans ajouter le rИpertoire au chemin virtuel de nouveau. Exemple d'utilisation: +
           $slave eval [list set tk_library [::safe::interpAddToAccessPath $nom $ tk_library]] +
    +

    ::safe::setLogCmd ?cmd arg...? +
    Cette commande installe un script qui sera appelИ quand les  ИvИnements intИressants du cycle de vie se produisent pour un  interprХteur sШr. Une fois appelИe sans arguments, elle renvoie le script actuellement installИ. Si appelИe avec un  argument, une chaНne vide, le script actuellement installИ est  enlevИ et la journalisation est arrЙtИe. Le script sera appelИ avec un argument supplИmentaire, une chaНne dИcrivant l'ИvХnement intИressant. Le but principal est d'aider le debugging des interprИteur sШrs. En utilisant ce service vous pouvez obtenir des message d'erreurs complets pendant que l'interprИteur sШr reГoit seulement des messages d'erreurs gИnИriques. Ceci empЙche l'interprИteur sШr de voir des messages au sujet des Иchecs et d'autres ИvИnements qui pourraient contenir une information sensible telle que de vrais noms de rИpertoire. +
    Exemple d'utilisation: +
    ::safe::setLogCmd puts stderr +
    +
    +

    +
    Ci-dessous vous trouverez la sortie d'une session exemple dans laquelle un interprИteur sШr a essayИ de " sourcer " un fichier non trouvИ dans son chemin d'accХs virtuel. Notez que l'interprИteur sШr a seulement reГu un message d'erreur disant que le fichier n'a pas ИtИ trouvИ:
    +
    NOTICE for slave interp10 : Created
    +NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
    +NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
    +ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory
    + +
    +
    OPTIONS

    +
    Les options suivantes sont communes Ю ::safe::interpCreate, ::safe::interpInit, et ::safe::interpConfigure. N'importe quel nom d'option peut Йtre abrИgИ Ю son nom non-ambigu minimal. Les noms d'option ne sont ne sont pas sensibles Ю la casse. +
    +
    -accessPath directoryList
    Cette option place la liste de rИpertoires desquels l'interprИteur sШr peut source et load des fichiers. Si cette option n'est pas spИcifiИe, ou si elle est donnИe comme liste vide, l'interprИteur sШr emploiera les mЙme rИpertoires que son maНtre pour auto-chargement. Voir la section SECURITE ci-dessous pour plus de dИtail au sujet des chemins virtuels, des jetons et du contrТle d'accХs. +
    +

    -statics boolean +
    Cette option indique si l'interprИteur sШr sera autorisИ Ю charger les packages statiquement liИs (comme load {} Tk). La valeur par dИfaut est true : les interprИteur sШrs sont autorisИ Ю charger les packages statiquement liИs. +
    +

    -noStatics +
    Cette option est un raccourci de convenance pour -statics false et indique ainsi que l'interprИteur sШr ne sera pas autorisИ Ю charger les packages statiquement liИs. +
    +

    -nested boolean +
    Cette option spИcifie si l'interprИteur sШr sera autorisИ Ю charger des packages dans ses propre sous-interprИteurs. La valeur par dИfaut est false: les interprИteur sШrs ne sont pas autorisИ Ю charger de packages dans leurs propres interprХteurs secondaires. +
    +

    -nestedLoadOk +
    Cette option est un raccourci de convenance pour -nested true et indique ainsi que l'interprИteur sШr sera autorisИ Ю charger des packages dans ses propres interprХteurs secondaires. +
    +

    -deleteHook script +
    Quand Ю cette option est donnИ un script non vide, elle est ИvaluИe dans le maНtre avec le nom de l'interprХteur sШr comme argument additionnel juste avant supprimer rИellement l'interprХteur sШr. Donner une valeur vide enlХve n'importe quel script d'effacement actuellement installИ pour cet interprИteur sШr. La valeur par dИfaut ({}) n'est n'avoir aucun appel de suppression. +
    +
    +

    +
    ALIAS

    +
    Les alias suivants sont fournis dans un interprИteur sШr: +
    +
    source fileName +
    Le fichier requis, un fichier source Tcl, est "sourcИ" dans interprИteur sШr s'il est trouvИ. L'alias source peut seulement " sourcer " les fichier des rИpertoires qui se trouvent dans le chemin virtuel pour l'interprИteur sШr. L'alias source exige de l'interprИteur sШr qu'il utilise un des noms de jeton dans son chemin virtuel pour dИsigner le rИpertoire dans lequel le fichier a "sourcer" peut Йtre trouvИ. Voir la section sur la SECURITE pour une discussion plus approfondie des restrictions sur les noms de fichiers valides. +
    +

    load fileName +
    Le fichier requis, un fichier objet partagИ, est chargИ dynamiquement dans l'interprИteur sШr s'il est trouvИ. Le nom de fichier doit contenir le nom d'un jeton mentionnИ dans le chemin virtuel de l'interprИteur sШr pour Йtre trouvИ avec succХs. De plus, le fichier objet partagИ doit contenir un point d'entrИe sШr; voyez la page de manueluel de la commande load pour plus de dИtails. +
    +

    file ?subCmd args...? +
    L'alias file donne accХs Ю un sous ensemble sШr des sous-commandes de  file; il permet seulement les sous-commandes dirname, join, extension, root, tail, pathname et split. Pour plus de dИtails sur ces sous-commandes voyez la page de manueluel pour la commande file. +
    +

    encoding ?subCmd args...? +
    L'alias encoding donne accХs Ю un sous ensemble sШr des sous-commandes de encoding il interdit de fixer l'encodage systХme, mais permet tout autre sous-commandes incluant system Ю vИrifier l'encodage courant. +
    +

    exit +
    L'interprХteur appelant est supprimИ et son traitement est arrЙtИ, mais le processus Tcl dans lequel cet interprХteur existe n'est pas terminИ.
    +
    +
    +
    +
    SECURITE

    +
    La Safe Base n'essaye pas d'empЙcher complХtement les attaques d'ennui et de deni de service. Ces formes d'attaque empЙchent temporairement l'application ou l'utilisateur d'utiliser l'ordinateur pour effectuer des tБches utiles, par exemple en consommant tout le temps CPU ou tout l'affichage disponible. Ces attaques, quoique graves, sont considИrИes comme moins importantes en gИnИral que les attaques d'intИgritИ et d'intimitИ que la Safe Base doit empЙcher.
    +
    Les commandes disponibles dans un interprИteur sШr, en plus de  l'ensemble sШr comme dИfini en page de manueluel d' interp, sont des alias de source, load, exit, et des sous-ensembles sШrs de file et encoding. L'interprИteur sШr peut aussi auto-charger du code et il peut demander que des packages soient chargИs..
    +
    Puisque certaines de ces commandes accХdent au systХme de fichiers local, il y a un danger potentiel de fuites d'information au sujet de la structure des rИpertoires. Pour empЙcher ceci, les commandes qui prennent des noms de fichier comme aguments dans un interprИteur sШr utilisent des jetons au lieu des noms rИels de rИpertoires. Ces jetons sont traduits en nom rИel de rИpertoire pendant qu'une requЙte pour, ex., sourcer un fichier est traitИe par le maНtre interprИteur. Ce systХme de chemin virtuel est maintenu dans l'interprХteur principal pour chaque interprХteur sШr crИИ par ::safe::interpCreate ou initialisИ par ::safe::interpInit et le chemin pointe des jetons accessibles dans l'interprИteur sШr vers les noms de chemin rИels sur le systХme de fichier local empЙchant de ce fait les interprХteurs sШrs de connaНtre la structure du systХme de fichiers de la machine sur lequel l'interprХteur s'exИcute. Les seuls arguments valides de noms de fichier pour les alias source et load fournis Ю l'esclave sont des chemin sous la forme de [file jointokenfilename] (ie, en utilisant les formats natifs de chemin: token/filename sous Unix, token\filename sous Windows, et token:filename sur Mac), oЫ token reprИsente un des rИpertoires de la liste accessPath et filename est un fichier dans ce rИpertoire (on ne permet aucun accХs aux sous-rИpertoires).
    +
    Quand un jeton est utilisИ par un interprИteur sШr dans un requЙte pour " sourcer " ou charger un fichier, le jeton est vИrifiИ et traduit en un nom rИel de chemin et le fichier a "sourcer" ou chargИ est localisИ sur le systХme de fichier. L'interprИteur sШr n'a jamais connaissance du nom de chemin actuel sous lequel le fichier est stockИ sur le systХme de fichier.
    +
    Pour empЙcher une fuite d'information potentielle Ю partir de fichiers sensibles accidentellement inclus dans l'ensemble de fichiers qui peut Йtre "sourcИ" par un interprИteur sШr, l'alias source restreint l'accХs aux fichiers respectant les contraintes suivantes: le nom de chemin ne doit pas avoir plus de quatorze caractХres, ne doit pas contenir plus d'un point ("."), doit finir avec l'extension .tcl ou Йtre appelИ tclIndex.
    +
    Chaque ИlИment de la liste initiale de chemin d'accХs sera assignИ Ю un jeton qui sera placИe dans l'auto_path de l'esclave et le premier ИlИment de cette liste sera fixИ en tant que tcl_library pour cet esclave.
    +
    Si l'argument de chemin d'accХs n'est pas donnИ ou est une liste vide, le comportement par dИfaut est de laisser l'esclave acceder aux mЙmes packages que le maНtre (ou pour Йtre plus prИcis: seulement les packages Иcrits en Tcl (ne peuvent pas Йtre dangereux tant qu'ils fonctionnent dans l'interprИteur esclave) et les extensions C qui fournissent un point d'entrИe Safe_Init). Dans ce but, l'auto_path du maНtre sera employИ pour construire le chemin d'accХs de l'esclave. Pour que l'esclave charge avec succХs la bibliothХque Tcl (qui inclut le mИcanisme d'auto-chargement) la tcl_library sera ajoutИe ou dИplacИe Ю la premiХre position si nИcessaire, dans le chemin d'accХs de l'esclave, ainsi la tcl_library esclave sera la mЙme que celle du maНtre (son vrai chemin sera cependant toujours invisible Ю l'esclave). Pour que l'auto-chargement fonctionne de mЙme pour l'esclave et le maНtre dans ce cas par dИfaut, les sous rИpertoires de premier-niveau de chaque rИpertoire dans l'auto_path du maНtre sera aussi ajoutИ (si aucun n'est dИjЮ inclus) au chemin d'accХs de l'esclave. Vous pouvez toujours indiquer un chemin plus restrictif pour lequel les sous rИpertoires ne seront jamais recherchИs explicitement en spИcifiant votre liste de rИpertoires avec le flag -accessPath au lieu de compter sur ce mИcanisme par dИfaut.
    +
    Quand le accessPath est changИ aprХs la premiХre crИation ou l'initialisation (c.a.d au travers de interpConfigure -accessPathlist), un auto_reset est automatiquement ИvaluИ dans l'interprИteur sШr pour synchroniser son auto_index avec la nouvelle liste de jetons
    +

    +
    VOIR EGALEMENT

    +
    interp(n), library(n), load(n), package(n), source(n), unknown(n)

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/scan.htm b/hlp/fr/tcl/scan.htm new file mode 100644 index 0000000..238b6a1 --- /dev/null +++ b/hlp/fr/tcl/scan.htm @@ -0,0 +1,66 @@ + + + + +

    scan      Commandes Internes Tcl

    +
    +
    NOM

    +
    scan √ Analyse une chaНne en utilisant des spИcificateurs de conversion dans le style de sscanf +

    +
    SYNTAXE

    +
    scan string format ?varName varName ...? +

    +
    INTRODUCTION

    +
    Cette commande analyse les champs Ю partir d'une chaНne d'entrИe de la mЙme faГon que la fonction ANSI C sscanf et retourne un compte du nombre de conversions effectuИes, ou -1 si la fin de la chaНne d'entrИe est atteinte avant qu'une conversion ait ИtИ effectuИe String donne l'entrИe a analyser et format indique comment l'analyser, en utilisant les spИcificateurs de conversions % comme dans sscanf. Chaque varName donne le nom d'une variable; quand un champ est scannИ Ю partir de string le rИsultat est converti en une chaНne et assignИ Ю la variable correspondante. Si aucunes variables varName ne sont spИcifiИes, alors scan fonctionne d'une maniХre linИaire, retournant les donnИes qui seraient autrement stockИes dans les variables comme une liste. Dans le cas linИaire, une chaНne vide est renvoyИe quand la fin de la chaНne d'entrИe est atteinte avant qu'une conversion ait ИtИ effectuИe +

    +
    DETAILS SUR LE SCANNING

    +
    Scan opХre en scannant string et format ensemble. Si le caractХre suivant dans format est un espace ou une tabulation alors il correspond Ю un nombre quelconque d'espaces dans string (incluant zИro). Autrement, si ce n'est pas un caractХre % alors il doit correspondre au caractХre suivant de string. Quand un % est rencontrИe dans format, il indique le dИbut d'un spИcificateur de conversion. Un spИcificateur de conversion contient jusqu'a quatre champs aprХs le %: une *, indique que la valeur convertie est ИcartИe  au lieu d'Йtre assignИe Ю une variable; un spИcificateur de position XPG3; un nombre indiquant une largeur de champ maximum; et un caractХre de conversion. Tous ces champs sont optionnels exceptИ le caractХre de conversion. Les champs prИsents doivent apparaitre dans l'ordre indiquИ plus haut.
    +
    Quand scan trouve un spИcificateur de conversion dans format, il saute en premier tout espace dans string (Ю moins que le spИcificateur soit [ ou c). Ensuite il convertit les caractХres d'entrИe suivants en accord avec le  spИcificateur de conversion et range le rИsultat dans la variable dИsignИe par l'argument suivant Ю scan.
    +
    Si le % est suivi par un nombre dИcimal et un $, comme dans "%2$d", alors la variable Ю utiliser n'est pas extraite de l'argument suivant. Contrairement, elle est extraite de l'argument indiquИ par le nombre, where 1 corresponds Ю la premiХre varName. Si il y a un quelconque spИcificateur de position dans format alors tous les spИcificateurs doivent Йtre positionnels. Toutes les varName sur la liste d'arguments doivent correspondre exactement Ю un spИcificateur de conversion ou une erreur est gИnИrИe, ou dans le cas linИaire, toute position peut Йtre spИcifiИe au moins une fois et les positions vides seront remplies avec des chaНnes vides.
    +
    Les caractХres de conversions suivants sont supportИs: +
    +
    d
    Le champ d'entrИe doit Йtre un entier dИcimal. Il est lu et la valeur est stockИe dans la variable comme chaНne dИcimale. +
    +

    o +
    Le champ d'entrИe doit Йtre un entier octal. Il est lu et la valeur est stockИe dans la variable comme chaНne dИcimale. +
    +

    x +
    Le champ d'entrИe doit Йtre un entier hexadИcimal. Il est lu et la valeur est stockИe dans la variable comme chaНne dИcimale. +
    +

    u +
    Le champ d'entrИe doit Йtre un entier dИcimal. La valeur est stockИe dans la variable comme chaНne entiХre dИcimale non signИe. +
    +

    i +
    Le champ d'entrИe doit Йtre un entier La base (ex. dИcimale, octal, ou hexadИcimal) est dИterminИe de la mЙme faГon que dИcrite dans expr. La valeur est stockИe dans la variable comme chaНne dИcimale. +
    +

    c +
    Un seul caractХre est lu et sa valeur binaire est stockИe dans la variable comme chaНne dИcimale. L'espace initial n'est pas sautИ dans ce cas, donc le champ d'entrИe peut Йtre un espace. Cette conversion est diffИrente du standard ANSI dans lequel le champ d'entrИe consiste toujours en un simple caractХre et ou aucune largeur de champ ne peut Йtre spИcifiИe. +
    +

    s +
    Le champ d'entrИe consiste en tous les caractХres jusqu'a l'espace suivant; les caractХres sont copiИs dans la variable. +
    +

    e ou f ou g +
    Le champ d'entrИe doit Йtre un nombre Ю virgule flottante consistant  d'un signe optionnel, une chaНne de chiffres dИcimaux pouvant contenir un point dИcimal, et un exposant optionnel consistant  d'un e ou E suivi par un signe optionnel et une chaНne de chiffres dИcimaux. Il est lu et stockИ dans la variable comme une chaНne flottante. +
    +

    [chars] +
    Le champ d'entrИe consiste en un nombre quelconque de caractХres dans  chars. La chaНne correspondante est stockИe dans la variable. Si le premier caractХre entre crochets est un ] alors il est traitИ comme faisant partie de chars plutТt que le crochet fermant l'ensemble. Si chars contient une sИquence de la forme a-z alors tout caractХre entre a et z (inclus) correspondra. Si le premier ou dernier caractХre entre crochets est un -, alors il est traitИ comme faisant partie de chars plutТt que d'indiquer un intervalle. +
    +

    [^chars] +
    Le champ d'entrИe consiste en un nombre quelconque de caractХres non inclus dans chars. La chaНne correspondante est stockИe dans la variable. Si le caractХre suivant immИdiatement le ^ est un ] alors il est  traitИ comme partie de l'ensemble plutТt que le crochet fermant l'ensemble. Si chars contient une sИquence de la forme a-z alors tout caractХre entre a et z (inclus) sera exclu de l'ensemble. Si le premier ou le dernier caractХre entre crochets est un -, alors il est traitИ comme faisant partie de chars plutТt que d'indiquer un intervalle. +
    +

    n +
    Aucune entrИe n'est utilisИe de la chaНne d'entrИe. Par contre, le nombre total de caractХres scannИs de la chaНne d'entrИe est stockИ dans la variable. +
    +
    +

    +
    Le nombre de caractХres lus de l'entrИe pour conversion est le plus grand nombre qui a un sens pour cette conversion (ex. le plus grand nombre de chiffres dИcimaux possibles pour %d, le plus grand nombre de chiffres octaux possibles pour %o, et ainsi de suite). Le champ d'entrИe pour une conversion donnИe se termine soit quand un espace est rencontrИ ou quand la largeur maximum de champ a ИtИ atteinte, suivant lequel est rencontrИ en premier. Si une * est prИsente dans le spИcificateur de conversion alors aucune variable n'est assignИe et l'argument suivant n'est pas utilisИ

    +
    DIFFERENCES AVEC SSCANF ANSI

    +
    Le comportement de la commande scan est le mЙme que celui de la fonction ANSI C sscanf exceptИ les diffИrences suivantes:
    +
    [1]      Le spИcificateur de conversion %p n'est pas supportИ.
    +
    [2]      Pour les conversions %c une seule valeur caractХre est convertie en chaНne dИcimale, qui est alors assignИe Ю la correspondante varName; aucune largeur de champ ne peut Йtre spИcifiИe pour cette conversion.
    +
    [3]      Les modificateurs l, h, et L sont ignorИs;  les valeurs entiХres sont toujours converties comme s'il n'y avait pas de modificateur prИsent et les valeurs rИelles sont toujours converties comme si le modificateur l etait prИsent (ex. le type double est utilisИ pour la reprИsentation interne).
    +
    [4]      Si la fin de la chaНne d'entrИe est atteinte avant que quelconque conversion ait ИtИ effectuИe et qu'aucune variable n'ait ИtИ donnИe, une chaНne vide est renvoyИe

    +
    DerniХre rИvision: 8.3
    +
    +
    + diff --git a/hlp/fr/tcl/seek.htm b/hlp/fr/tcl/seek.htm new file mode 100644 index 0000000..1c64101 --- /dev/null +++ b/hlp/fr/tcl/seek.htm @@ -0,0 +1,32 @@ + + + + +

    seek      Commandes Internes Tcl

    +
    +
    NOM

    +
    seek - Change la position du curseur dans un canal ouvert +

    +
    SYNTAXE
    +
    seek channelId offset ?origin?  +

    +
    DESCRIPTION

    +
    Change la position du curseur courante pour channelId. ChannelId doit Йtre un identificateur de canal tel que renvoyИ par un prИcИdent appel de open ou socket. Les arguments offset et origin spИcifient la position Ю laquelle la lecture ou Иcriture suivante se produira pour channelId. Offset doit Йtre un entier (qui peut Йtre nИgatif) et origin doit Йtre un des suivants: +
    +
    start
    La nouvelle position sera Ю offset octets du dИbut du fichier ou pИriphИrique sous-jacent. +
    +

    current +
    La nouvelle position sera sera Ю offset octets de la position courante; un offset nИgatif dИplace le curseur en arriХre dans le fichier ou pИriphИrique sous-jacent. +
    +

    end +
    La nouvelle position sera Ю offset octets de la fin du fichier ou pИriphИrique Un offset nИgatif place le curseur avant la fin de fichier, et un offset positif place le curseur aprХs la fin du fichier. +
    +
    +L'argument origin est par dИfaut Ю start. +
    +
    La commande vide toutes les donnИes dans le tampon de sortie du canal avant que la commande retourne, mЙme si le canal est en mode non bloquant. Elle Иcarte aussi toute entrИe en tampon non lue. Cette commande retourne une chaНne vide. Une erreur se produit si cette commande est appliquИe aux canaux dont le fichier ou pИriphИrique sous-jacent ne supporte pas la recherche.
    +
    Notez que les valeurs offset sont offsets d'octets, pas des offsets caractХres L'ensemble seek et tell opХre en termes d'octets, pas de caractХres, contrairement Ю read

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/set.htm b/hlp/fr/tcl/set.htm new file mode 100644 index 0000000..787d5cb --- /dev/null +++ b/hlp/fr/tcl/set.htm @@ -0,0 +1,18 @@ + + + + +

    set      Commandes Internes Tcl

    +
    +
    NOM

    +
    set - Lit et ecrit des variables
    +

    +
    SYNTAXE

    +
    set varName ?value?  +

    +
    DESCRIPTION

    +
    Renvoie la valeur de la variable varName. Si value est spИcifiИ, alors fixe la valeur de varName to value, crИe une nouvelle variable si une n'existe pas dИjЮ, et retourne sa valeur. Si varName contient une parenthХse ouverte et finit avec une parenthХse fermИe, alors elle se refХre Ю un ИlИment de tableau: les caractХres avant la premiХre parenthХse ouverte sont le nom du tableau, et les caractХres entre le parenthХses sont l'index Ю l'intИrieur du tableau. Autrement varName se refХre Ю une variable scalaire . Normalement, varName est non qualifiИe (n'inclut pas les noms des namespaces contenant), et la variable de ce nom dans le namespace  courant est lue ou Иcrite. Si varName inclut des qualificateurs namespace (dans le nom du tableau si elle se refХre Ю un ИlИment de tableau), la variable dans le namespace spИcifiИ est lue ou Иcrite.

    +
    Si aucune fonction n'est active, alors varName se refХre Ю une variable namespace (variable globale si le namespace  courant est le namespace global ). Si une fonction est active, alors varName se refХre Ю un paramХtre ou une variable locale de la fonction Ю moins que la commande global ait ИtИ appelИe pour dИclarer varName comme globale, ou Ю moins qu'une commande variable a ИtИ appelИe pour dИclarer varName comme une variable namespace
    +
    +
    + diff --git a/hlp/fr/tcl/socket.htm b/hlp/fr/tcl/socket.htm new file mode 100644 index 0000000..a417d4f --- /dev/null +++ b/hlp/fr/tcl/socket.htm @@ -0,0 +1,62 @@ + + + + +

    socket      Commandes Internes Tcl

    +
    +
    NOM

    +
    socket - Ouvre une connection rИseau TCP +

    +
    SYNTAXE

    +

    +socket ?options? host port
    +socket -server command ?options? port 
    +

    +
    DESCRIPTION

    +
    Cette commande ouvre une socket rИseau et retourne un identificateur de canal qui peut Йtre employИ dans les appels futurs des commandes comme read, puts et flush. A prИsent seul le protocole rИseau TCP est supportИ; les versions futures pourront inclure un support pour des protocoles supplИmentaires. La commande socket peut Йtre employИe pour ouvrir soit le cotИ client ou serveur d'une connection, dИpendant de si le switch -server est spИcifiИ
    +

    +
    SOCKETS CLIENTES

    +
    Si l'option -server n'est pas spИcifiИe, alors la partie client d'un connection est ouverte et la commande retourne un identificateur de canal qui peut Йtre utilisИ pour la lecture et l'Иcriture. Port et host spИcifient un port pour la connection;  il doit y avoir un serveur qui accepte des connections sur ce port Port est un numИro de port entier et host est soit un nom qualifiИ tel que www.sunlabs.com ou une adresse numИrique IP telle que 127.0.0.1. Utilisez localhost pour vous rИfИrer Ю la machine sur laquelle la commande a ИtИ appelИe.
    +
    Les options suivantes peuvent Йtre aussi prИsentes avant host pour spИcifier des information supplИmentaires concernant la connection: +
    +
    -myaddr addr +
    Addr donne le nom qualifiИ ou l'adresse IP numИrique de l'interface rИseau cotИ client Ю utiliser pour la connection. Cette option peut Йtre utile si la machine cliente a plusieurs interfaces rИseau Si l'option est omise alors l'interface cotИ client sera choisie par le logiciel systХme. +
    +

    -myport port
    Port spИcifie un numИro de port entier Ю utiliser pour le cotИ client de la connection. Si cette option est omise, un numИro de port client alИatoire sera choisi par le logiciel systХme. +
    +

    -async +
    L'option -async induit une connection asynchrone pour  la socket cliente. Ceci signifie que la socket sera crИe immИdiatement mais ne peut pas encore Йtre connectИe au serveur, quand l'appel de socket retourne. Quand une gets ou flush est fait sur le socket avant que la tentative de connection ait rИussi ou ИchouИ, si la socket est en mode bloquant, l'opИration attendra jusqu'a ce que la connection soit complИtИe ou Иchoue. Si la socket est en mode non bloquant et qu'une gets ou flush est fait sur la socket avant que la tentative de connection ait rИussi ou ИchouИ, l'opИration retourne immИdiatement et fblocked sur le socket retourne 1. +
    +
    +

    +
    SOCKETS SERVEUR

    +
    Si l'option -server est spИcifiИe alors la nouvelle socket sera un serveur pour le port indiquИ par port. Tcl acceptera automatiquement les connections sur ce port. Pour chaque connection Tcl crИera un nouveau canal qui pourra Йtre employИ pour communiquer avec le client Tcl appelle alors command avec trois arguments supplИmentaire: le nom du nouveau canal, l'adresse, en notation rИseau, de la machine cliente, et le numИro de port du client.
    +
    L'option supplИmentaire suivante peut aussi Йtre spИcifiИe avant host: +
    +
    -myaddr addr +
    Addr donne le nom qualifiИ ou l'adresse IP numИrique de l'interface rИseau du cotИ serveur Ю utiliser pour la connection. Cette option peut Йtre utile si la machine serveur a plusieurs interfaces rИseau. Si l'option est omise alors la socket serveur est attachИe Ю l'adresse spИciale INADDR_ANY ainsi elle peut accepter les connections sur une interface quelconque. +
    +
    +
    +
    Les canaux serveurs ne peuvent pas Йtre utilisИs pour les entrИes ou sorties; leur seul usage est d'accepter de nouvelles connections client. Les canaux crИИs pour chaque connection client entrante sont ouvert pour l'entrИe et la sortie. Fermer le canal serveur ferme le serveur ainsi aucune nouvelle connectios ne sera acceptИe nИanmoins, les connections existantes ne seront pas affectИes.
    +
    Les sockets serveurs dИpendent du mИcanisme d'ИvХnement Tcl pour rИagir aux nouvelles connections ouvertes. Si l'application n'entre pas dans la boucle d'ИvХnement, par exemple en appelant la commande vwait ou l'appel de fonction C Tcl_DoOneEvent, alors aucunes connections ne seront acceptИes
    +

    +
    OPTIONS DE CONFIGURATION

    +
    La commande fconfigure peut Йtre utilisИe pour consulter plusieurs options de configuration en lecture seule pour les canaux socket: +
    +
    -error
    Cette option lit le statut d'erreur courant de la socket donnИe. Ceci est utile quand vous avez besoin de determiner si une opИration de connection asynchrone a rИussi. S'il y a eu une erreur, le message d'erreur est renvoyИ. Si il n'y avait pas d'erreur, une chaНne vide est renvoyИe. +
    +

    -sockname +
    Cette option retourne une liste de trois ИlИments, l'adresse, le nom de machine et le numИro de port pour la socket. Si le nom de machine ne peut pas calculИ, le second ИlИment est identique Ю l'adresse, le premier ИlИment de la liste. +
    +

    -peername +
    Cette option n'est pas supportИe par les sockets serveur. Pour les sockets clients acceptИs, cette option retourne une liste de trois ИlИments; ce sont l'adresse, le nom de machine et le port auquels la socket peer est connectИe ou liИe. Si le nom de machine ne peut Йtre calculИ, le second ИlИment de la liste est identique Ю l'adresse, son premier ИlИment.
    +
    +
    +
    +
    VOIR EGALEMENT

    +
    flush(n), open(n), read(n)

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/source.htm b/hlp/fr/tcl/source.htm new file mode 100644 index 0000000..a62b171 --- /dev/null +++ b/hlp/fr/tcl/source.htm @@ -0,0 +1,19 @@ + + + + +

    source      Commandes Internes Tcl

    +
    +
    NOM

    +
    source - Evalue un fichier ou resource en tant que script Tcl
    +

    +
    SYNTAXE

    +
    source fileName
    +source -rsrc resourceName ?fileName?
    +source -rsrcid resourceId ?fileName
    +

    +
    DESCRIPTION

    +
    Cette commande prend le contenu du fichier ou resource spИcifiИ et le transmet Ю l'interprИteur Tcl comme un texte de script. La valeur de retour de source est la valeur de retour de la derniХre commande exИcutИe dans le script. Si une erreur se produit pendant l'Иvalualuation du contenu du script alors la commande source renverra cette erreur. Si une commande return est appelИe Ю l'intИrieur du script alors le restant du fichier sera sautИ et la commande source retournera normalement avec le rИsultat de la commande return. Les formes -rsrc et -rsrcid de cette commande sont seulement disponibles sur les ordinateurs Macintosh. Ces versions de la commande vous autorisent Ю sourcer un script en partant d'une resource TEXT. Vous pouvez spИcifier quelle resource TEXT sourcer soit par nom soit par id. Par dИfaut Tcl recherche tout fichier resources ouvert, incluant l'application courante et toute extension C chargИe. Alternativement, vous pouvez spИcifier le fileName oЫ la resource TEXT peut Йtre trouvИe.
    +
    +
    + diff --git a/hlp/fr/tcl/split.htm b/hlp/fr/tcl/split.htm new file mode 100644 index 0000000..f058401 --- /dev/null +++ b/hlp/fr/tcl/split.htm @@ -0,0 +1,21 @@ + + + + +

    split      Commandes Internes Tcl

    +
    +
    NOM

    +
    split √ Divise une chaНne en une liste Tcl +

    +
    SYNTAXE

    +
    split string ?splitChars
    +

    +
    DESCRIPTION

    +
    Renvoie une liste crИИe en divisant string Ю chaque caractХre qui est dans l'argument splitChars. Chaque ИlИment de la liste rИsultat consistera des caractХres de string qui sont situИs entre les instances des caractХres dans splitChars. Une liste vide sera gИnИrИe si string contient des caractХres adjacents dans splitChars, ou si le premier ou le dernier caractХre de string est dans splitChars. Si splitChars est une chaНne vide alors chaque caractХre de string devient un ИlИment sИparИ de la liste rИsultat. SplitChars est par dИfaut un caractХre espace standard. Par exemple,
    +
    split "comp.unix.misc" .
    +
    retourne "comp unix misc" et
    +
    split "Hello world" {}
    +
    retourne "H e l l o { } w o r l d"
    +
    +
    + diff --git a/hlp/fr/tcl/string.htm b/hlp/fr/tcl/string.htm new file mode 100644 index 0000000..13d62e2 --- /dev/null +++ b/hlp/fr/tcl/string.htm @@ -0,0 +1,131 @@ + + + + +

    string      Commandes Internes Tcl

    +
    +
    NOM

    +
    string - Manipulation des chaНnes
    +

    +
    SYNTAXE

    +
    string option arg ?arg ...? 
    +

    +
    DESCRIPTION

    +
    RИalise une parmi plusieurs opИrations sur les chaНnes, dИpendant d' option. Les options lИgales (qui peuvent Йtre abrИgИes) sont: +
    +
    string bytelength string +
    Renvoie une chaНne dИcimale donnant le nombre d'octets utilisИs pour reprИsenter string en mИmoire. Comme UTF-8 utilise de un Ю trois octets pour reprИsenter les caractХres Unicode, la longueur en octets ne sera pas la mЙme en gИnИral que la longueur des caractХres. Les cas oЫ un script gХre la longueur en octets sont rares. Dans presque tous les cas, vous devrez utiliser l'opИration string length. Referez-vous Ю la page de manuel Tcl_NumUtfChars pour plus de dИtails sur la reprИsentation UTF-8. +
    +

    string compare ?-nocase? ?-length int? string1 string2 +
    RИalise une comparaison caractХre-par-caractХre des chaНnes string1 et string2. Renvoie -1, 0, ou 1, dИpendant de si string1 est lexicographiquement infИrieure Ю, Иgale Ю, ou supИrieure Ю string2. Si -length est spИcifiИe, alors seulement les length premiers caractХres sont utilisИs dans la comparaison. Si -length est nИgatif, elle est ignorИe. Si -nocase est spИcifiИ, alors les chaНnes sont comparИes sans tenir compte de la casse. +
    +

    string equal ?-nocase? ?-length int? string1 string2 +
    RИalise une comparaison caractХre-par-caractХre des chaНnes string1 et string2. Renvoie 1 si string1 et string2 sont identiques, ou 0 sinon. Si -length est spИcifiИe, alors seulement les length premiers caractХres sont utilisИs dans la comparaison Si -length est nИgatif, elle est ignorИe Si -nocase est spИcifiИ, alors la chaНnes sont comparИes sans tenir compte de la casse. +
    +

    string first string1 string2 ?startIndex? +
    Recherche dans string2 la sИquence de caractХres qui correspond exactement au caractХres de string1. Si trouvИ, retourne l' index du premier caractХre de la premiХre correspondance dans string2. Sinon, retourne -1. Si startIndex est spИcifiИ (dans toutes formes acceptИes par la mИthode index), alors la recherche est forcИe de commencer avec le caractХre de string2 spИcifiИ par l'index. Par exemple, +
        string first a 0a23456789abcdef 5 +
    renverra 10, mais +
        string first a 0123456789abcdef 11 +
    renverra -1. +
    +

    string index string charIndex
    Renvoie le charIndex iХme caractХre de l'argument string Un charIndex de 0 corresponds au premier caractХre de la chaНne charIndex peut Йtre spИcifiИ comme suit: +
       integer      Le caractХre spИcifiИ Ю cet index intИgral
       end      Le dernier caractХre de la chaНne. +
      end-integer      Le dernier caractХre de la chaНne moins l'offset entier spИcifiИ (ex. end-1 se refХre Ю "c" dans "abcd"). +
    Si charIndex est infИrieur Ю 0 ou supИrieur Ю ou Иgal Ю la longueur de la chaНne alors une chaНne vide est renvoyИe. +
    +

    string is class ?-strict? ?-failindex varname? string +
    Renvoie 1 si string est un membre valide de la classe de caractХre spИcifiИe, retourne 0 autrement Si -strict est spИcifiИ, alors une chaНne vide retourne 0, autrement une chaНne vide renverra 1 avec toute classe. Si -failindex est spИcifiИ, alors si la fonction retourne 0, l'index dans la chaНne oЫ la classe n'est plus valide sera stockИ dans la variable dИsignИe par varname. varname ne sera pas fixИe si la fonction retourne 1. Les classes de caractХre suivantes sont reconnues (le nom de classe peut Йtre abrИgИ):
    +
    +
    +
    alnum      N'importe quel caractХre alphabИtique ou chiffre Unicode. +
    alpha      N'importe quel caractХre alphabИtique Unicode. +
    ascii      N'importe quel caractХre avec une valeur infИrieure Ю \u0080 (ceux qui sont dans l'intervalle ascii 7-bit). +
    boolean      N'importe quelle des formes autorisИes par Tcl_GetBoolean. +
    control      N'importe quel caractХre de contrТle Unicode. +
    digit      N'importe quel chiffre Unicode. Notez que ceci inclut les caractХres en dehors de l'intervalle [0-9]. +
    double      N'importe quelle des formes valides pour un double en Tcl, eventuellement entourИ d'espaces. En cas de sous/ dИbordement, 0 est renvoyИ et varname contiendra -1. +
    false      N'importe quelle forme autorisИe par Tcl_GetBoolean oЫ la valeur est false. +
    graph      N'importe quel caractХre Unicode imprimable, exceptИ l'espace. +
    integer      N'importe quelle des formes valides pour un entier en Tcl, eventuellement entourИ d'espaces. En cas de sous/dИbordement, 0 est renvoyИ et varname contiendra -1. +
    lower      N'importe quel caractХre alphabИtique Unicode minuscule. +
    print      N'importe quel caractХre Unicode imprimable, incluant l'espace. +
    punct      N'importe quel caractХre de ponctuation Unicode. +
    space      N'importe quel caractХre espace Unicode . +
    true      N'importe quelle forme autorisИe par Tcl_GetBoolean oЫ la valeur est true. +
    upper      N'importe quel caractХre alphabИtique Unicode majuscule. +
    wordchar      N'importe quel caractХre d'un mot Unicode. Donc tout caractХre alphanumИrique, et tout caractХres connecteur ou de ponctuation Unicode (ex. underscore). +
    xdigit      N'importe quel caractХre chiffre hexadИcimal ([0-9A-Fa-f]). +
    + + +
    Dans le cas de boolean, true et false, si la fonction renvoie 0, alors le varname sera toujours fixИ Ю 0, ceci etant dû Ю la nature variИe d'une valeur boolИenne valide.
    +
    +
    +

    string last string1 string2 ?startIndex? +
    Recherche dans string2 la sИquence de caractХres qui correspond exactement au caractХres de string1. Si trouvИ, retourne l'index du premier caractХre de la derniХre correspondance dans string2. S'il n'y a pas de correspondance, alors retourne -1. Si startIndex est spИcifiИ (dans une des formes acceptИes par la mИthode index), alors seulement les caractХres dans string2 Ю ou avant le startIndex spИcifiИ seront pris en compte dans la recherche. Par exemple, +
    string last a 0a23456789abcdef 15 +
    renverra 10, mais +
    string last a 0a23456789abcdef 9 +
    renverra 1. +
    +


    string length string +
    Renvoie une chaНne dИcimale donnant le nombre de caractХres dans string. Notez que ce n'est pas nИcИssairement le mЙme que le nombre d'octets utilisИ pour stocker la chaНne. +
    +

    string map ?-nocase? charMap string +
    Remplace les caractХres dans string basИs sur les paires clИ-valeur dans charMap charMap est une liste de key value key value ... comme sous la forme renvoyИe par array get. Chaque instance d'une clИ dans la chaНne sera remplacИe par sa valeur correspondante. Si -nocase est spИcifiИ, alors la correspondance est Иtablie sans tenir compte de la casse. L'ensemble key et value peut Йtre de multiples caractХres. Le remplacement est fait d'une maniХre ordonnИe, donc la clИ apparaissant en premier dans la liste sera vИrifiИe en premier, et ainsi de suite string est parcourue un seule fois, donc les premiers remplacements de clИ n'affecteront pas les correspondances suivantes. Par exemple, +
    string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc +
    renverra la chaНne 01321221. +
    +

    string match ?-nocase? pattern string +
    Teste si pattern correspond Ю string; retourne 1 si oui, 0 sinon. Si -nocase est spИcifiИ, alors le modХle est comparИ Ю la chaНne sans tenir compte de la casse. Pour que deux chaНnes correspondent, leurs contenus doivent Йtre identiques exceptИ que les sИquences spИciales suivantes peuvent apparaitre dans pattern: +
    +
    *
    Correspond Ю toute sИquence de caractХres dans string, incluant une chaНne vide. +
    +
    ?
    Correspond Ю quelconque caractХre unique dans string. +
    +
    [chars]
    Correspond Ю tout caractХre de l'ensemble indiquИ par chars. Si une sИquence de la forme x-y apparait dans chars, alors tout caractХre entre x et y, inclus, correspondra. Quand utilisИ avec -nocase, les points extrХmes de l'intervalle sont convertis en minuscule en premier. En considИrant que {[A-z]} correspond Ю '_' quand la correspondance est sensible Ю la casse ('_' est entre 'Z' et 'a'), avec -nocase c'est considerИ comme {[A-Za-z]} (et probablement ce qui etait exprimИ prИcedemment). +
    +
    \x
    Correspond au caractХre unique x. Ceci fournit un moyen d'Иviter l'interprИtation spИciale des caractХres *?[]\ dans pattern. +
    +
    +
    +

    string range string first last +
    Renvoie un intervalle de caractХres consИcutifs de string, en commenГant par le caractХre dont l'index est first et finissant par le caractХre dont l'index est last. Un index de 0 se rИfХre au premier caractХre de la chaНne. first et last peuvent Йtre spИcifiИs comme dans la mИthode index. Si first est infИrieur Ю zИro alors il est traitИ comme si c'Иtait zИro, et si last est supИrieur Ю ou Иgal Ю longueur de la chaНne alors il est traitИ comme si c'Иtait end. Si first est supИrieur Ю last alors une chaНne vide est renvoyИe. +
    +

    string repeat string count +
    Renvoie string rИpИtИe count fois. +
    +

    string replace string first last ?newstring? +
    Supprime un intervalle de caractХres consecutifs de string, commenГant avec le caractХre dont l'index est first et finissant avec le caractХre dont l'index est last. Un index de 0 se rИfХre au premier caractХre de la chaНne First et last peuvent Йtre spИcifiИs comme dans la mИthode index. Si newstring est spИcifiИe, alors elle est placИe dans l'intervalle des caractХres supprimИs. Si first est infИrieur Ю zИro alors il est traitИ comme si c'Иtait zИro, et si last est supИrieur ou Иgal Ю la longueur de la chaНne alors il est traitИ comme si c'Иtait end. Si first est supИrieur Ю last ou la longueur de la chaНne initiale, ou last infИrieur Ю 0, alors la chaНne initiale est renvoyИ inchangИe. +
    +

    string tolower string ?first? ?last? +
    Renvoie une valeur Иgale Ю string exceptИ que toute lettre en majuscule (ou titre) aura ИtИ convertie en minuscule. Si first est spИcifiИ, il se rИfХre Ю l'index du premier caractХre dans la chaНne ou commencer les modifications. Si last est spИcifiИ, il se rИfХre Ю l'index du caractХre dans la chaНne ou arrЙter (inclus) first et last peuvent Йtre spИcifiИs comme dans la mИthode index. +
    +

    string totitle string ?first? ?last? +
    Renvoie une valeur Иgale Ю string exceptИ que le premier caractХre de string est converti en sa variante Unicode titre (ou majuscule s'il n'y a pas de variante titre) et le reste de la chaНne est converti en minuscule. Si first est spИcifiИ, il se rИfХre Ю l'index du premier caractХre dans la chaНne ou commencer les modifications. Si last est spИcifiИ, il se rИfХre Ю l'index du caractХre dans la chaНne ou arrЙter (inclus). first et last peuvent Йtre spИcifiИs comme dans la mИthode index. +
    +

    string toupper string ?first? ?last? +
    Renvoie une valeur Иgale Ю string exceptИ que toute lettre minuscule (ou titre) aura ИtИ convertie en majuscule. Si first est spИcifiИ, il se rИfХre Ю l'index du premier caractХre dans la chaНne ou commencer les modifications. Si last est spИcifiИ, il se rИfХre Ю l'index du caractХre dans la chaНne ou arrЙter (inclus). first et last peuvent Йtre spИcifiИs comme dans la mИthode index. +
    +

    string trim string ?chars? +
    Renvoie une valeur Иgale Ю string exceptИ que tous les caractХres en tЙte ou Ю la fin de l'ensemble indiquИ par chars sont enlevИs. Si chars n'est pas spИcifiИ alors tous les espaces sont enlevИs (les espaces, tabulations, saut de lignes, et retour chariot). +
    +

    string trimleft string ?chars? +
    Renvoie une valeur Иgale Ю string exceptИ que tous les caractХres en tЙte de l'ensemble indiquИ par chars sont enlevИs. Si chars n'est pas spИcifiИ alors tous les espaces sont enlevИs (les espaces, tabulations, saut de lignes, et retour chariot). +
    +

    string trimright string ?chars? +
    Renvoie une valeur Иgale Ю string exceptИ que tous les caractХres Ю la fin de l'ensemble indiquИ par chars sont enlevИs. Si chars n'est pas spИcifiИ alors tous les espaces sont enlevИs (les espaces, tabulations, saut de lignes, et retour chariot). +
    +

    string wordend string charIndex +
    Renvoie l'index du caractХre juste aprХs le dernier dans le mot contenant le caractХre charIndex de string. charIndex peut Йtre spИcifiИ comme dans la mИthode index. Un mot est considerИ comme tout intervalle contigu de caractХres alphanumeriques (lettres Unicode ou chiffres dИcimaux ) ou underscore (connecteur de ponctuation Unicode), ou tout caractХre unique autre que ceux-ci. +
    +

    string wordstart string charIndex +
    Renvoie l'index du premier caractХre dans le mot contenant le caractХre charIndex de string charIndex peut Йtre spИcifiИ comme dans la mИthode index. Un mot est considerИ comme tout intervalle contigu de caractХres alphanumeriques (lettres Unicode ou chiffres dИcimaux ) ou underscore (connecteur de ponctuation Unicode), ou tout caractХre unique autre que ceux-ci. +
    +
    +

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/subst.htm b/hlp/fr/tcl/subst.htm new file mode 100644 index 0000000..0ae4d1f --- /dev/null +++ b/hlp/fr/tcl/subst.htm @@ -0,0 +1,23 @@ + + + + +

    subst      Commandes Internes Tcl

    +
    +
    NOM

    +
    subst - RИalise des substitution backslash, de commandes, et de variables
    +

    +
    SYNTAXE

    +
    subst ?-nobackslashes? ?-nocommands? ?-novariables? string +

    +
    DESCRIPTION

    +
    Cette commande effectue des substitution de variables, substitution de commandes, et substitutions backslash sur son argument string et retourne le rИsultat substituИ. Les substitutions sont effectuИes exactement de la mЙme faГon que pour la commande Tcl. Comme rИsultat, l'argument string est actuellement substituИ deux fois, une fois par l'analyseur Tcl de faГon usuelle pour la commande Tcl, et de nouveau par la commande subst.
    +
    Si un des commutateurs  -nobackslashes, -nocommands, ou -novariables est spИcifiИ, alors les substitutions correspondantes ne sont pas effectuИes. Par exemple, si -nocommands est spИcifiИ, aucune substitution de commandes n'est effectuИe:  les crochets ouvert et fermants sont traitИs comme des caractХres ordinaires sans interprИtation spИciale.
    +
    Note: quand elle effectue ses substitutions, subst ne traite pas de faГon spИciale les double guillemets ou les accolades Par exemple, le script
    +
    set a 44
    +
    subst {xyz {$a}}
    +
    retourne "xyz {44}", not "xyz {$a}"

    +
    DerniХre rИvision: 7.4
    +
    +
    + diff --git a/hlp/fr/tcl/switch.htm b/hlp/fr/tcl/switch.htm new file mode 100644 index 0000000..945ff0f --- /dev/null +++ b/hlp/fr/tcl/switch.htm @@ -0,0 +1,61 @@ + + + + +

    switch      Commandes Internes Tcl

    +
    +
    NOM

    +
    switch - Evalue un parmi plusieurs scripts, dИpendant d'une valeur donnИe +

    +
    SYNTAXE

    +
    switch ?options? string pattern body ?pattern body ...?
    +switch ?options? string {pattern body ?pattern body ...?} 
    +

    +
    DESCRIPTION

    +
    La commande switch compare son argument string Ю chacun des arguments pattern dans l'ordre. DХs qu'elle trouve un pattern qui correspond Ю string elle Иvalue les argument body suivants en les transmettant rИcursivement Ю l'interprИteur Tcl et retourne le rИsultat de cette Иvaluation . Si le dernier argument pattern est default alors il correspond Ю tout. Si aucun argument pattern correspond Ю string et qu'aucun dИfaut n'est donnИ, alors switch retourne une chaНne vide.
    +
    Si les arguments initiaux de switch commencent avec - alors ils sont traitИs comme des options Les options suivantes sont couramment supportИes: +
    +
    -exact
    Utilise la correspondance exacte pendant la comparaison de string Ю un modХle C'est le dИfaut. +
    +

    -glob +
    Pendant la comparaison de string aux modХles, utilise une correspondance glob-style (ex. la mЙme qu'implИmentИe par la commande string match). +
    +

    -regexp +
    Pendant la comparaison de string aux modХles, utilise la correspondance expression rationelle (comme dИcrit dans la page de rИfИrence re_syntax). +
    +

    -- +
    Marque la fin des options L'argument suivant sera traitИ comme string mЙme s'il commence avec un -. +
    +
    +
    +
    Deux syntaxes sont fournie pour les arguments pattern et body. Le premier utilise un argument sИparИ pour chacun des modХles et commandes; cette forme est pratique si des substitutions sont dИsirИes sur un modХle ou une commande. La seconde forme place tous les modХles et les commandes ensemble dans un seul argument; l'argument doit avoir une structure de liste correcte, avec les ИlИments de la liste Иtant les modХles et les commandes. La seconde forme facilite la construction de commandes switch multi-ligne, puisque les accolades entourant la liste rendent inutile l'inclusion d'un antislash Ю la fin de chaque ligne. Comme les arguments pattern sont dans accolades dans la seconde forme, aucunes substitutions de commande ou de variable ne sont effectuИe sur ceux-ci; cela rend le comportement de la seconde forme diffИrent de la premiХre forme dans certains cas.
    +
    Si un body est spИcifiИ comme "-" cela signifie que le body du modХle suivant doit Йtre aussi utilisИ comme le corps pour ce modХle (si le modХle suivant a aussi un corps de "-" alors le corps qui est utilisИ aprХs, et ainsi de suite). Cette fonctionnalitИ rend possible de partager une seul body entre plusieurs modХles.
    +
    Attention Ю l'emplacement des commentaires dans les commandes switch Ils devront Йtre placИs seulement dans l'exИcution du corps d'un des modХles, et pas mИlangИs avec les modХles.
    +
    Voici quelques exemples de commandes switch:
    +
    switch   abc   a   -   b   {format 1}   abc   {format 2}   default   {format 3}
    +
    renverra 2
    +
    switch   -regexp   aaab {
    +
          ^a.*b$   -
    +
          b   {format 1}
    +
          a*   {format 2.htm}
    +
          default   {format 3}
    +
    }
    +
    renverra 1, et
    +
    switch   xyz {
    +
          a
    +
                -
    +
          b
    +
                {
    +
                # Placement Correct du Commentaire
    +
                format 1
    +
          }
    +
          a*
    +
                {format 2}
    +
          default
    +
                {format 3}
    +
    }
    +
    renverra 3

    +
    DerniХre rИvision: 7.0
    +
    +
    + diff --git a/hlp/fr/tcl/tcl.toc.html b/hlp/fr/tcl/tcl.toc.html new file mode 100644 index 0000000..1c4e68f --- /dev/null +++ b/hlp/fr/tcl/tcl.toc.html @@ -0,0 +1,110 @@ +Tk Commands +Http
    +continue
    +history
    +pid
    +switch
    +Safe Base
    +dde
    +if
    +pkg::create
    +tcl_endOfWord
    +Tcl
    +encoding
    +incr
    +pkg_mkIndex
    +tcl_findLibrary
    +Tcltest
    +eof
    +info
    +proc
    +tcl_startOfNextWord
    +after
    +error
    +interp
    +puts
    +tcl_startOfPreviousWord
    +append
    +eval
    +join
    +pwd
    +tcl_wordBreakAfter
    +array
    +exec
    +lappend
    +re_syntax
    +tcl_wordBreakBefore
    +auto_execok
    +exit
    +lindex
    +read
    +tclvars
    +auto_import
    +expr
    +linsert
    +regexp
    +tell
    +auto_load
    +fblocked
    +list
    +registry
    +time
    +auto_mkindex
    +fconfigure
    +llength
    +regsub
    +trace
    +auto_mkindex_old
    +fcopy
    +load
    +rename
    +unknown
    +auto_qualify
    +file
    +lrange
    +resource
    +unset
    +auto_reset
    +fileevent
    +lreplace
    +return
    +update
    +bgerror
    +filename
    +lsearch
    +scan
    +uplevel
    +binary
    +flush
    +lsort
    +seek
    +upvar
    +break
    +for
    +memory
    +set
    +variable
    +catch
    +foreach
    +msgcat
    +socket
    +vwait
    +cd
    +format
    +namespace
    +source
    +while
    +clock
    +gets
    +open
    +split
    +close
    +glob
    +package
    +string
    +concat
    +global
    +parray
    +subst
    + + diff --git a/hlp/fr/tcl/tclsh.htm b/hlp/fr/tcl/tclsh.htm new file mode 100644 index 0000000..635ed0e --- /dev/null +++ b/hlp/fr/tcl/tclsh.htm @@ -0,0 +1,48 @@ + + + + +

    tclsh      Tcl Applications

    +
    +
    NOM

    +
    tclsh - Simple shell contenant un InterprИteur Tcl +

    +
    SYNTAXE

    +
    tclsh ?fileName arg arg ...? +

    +
    DESCRIPTION

    +
    Tclsh est une application shell-like qui lit les commandes Tcl Ю partir de son entrИe standard ou Ю partir d'un fichier et les Иvalue. Si appelИe sans arguments alors s'exИcute interactivement, en lisant les commandes Tcl de l'entrИe standard et affichant les rИsultats et les message d'erreurs sur la sortie standard. Elle s'exИcute jusqu'Ю ce que la commande exit soit appelИe ou jusqu'Ю ce que la fin-de-fichier soit atteinte sur son entrИe standard. S'il existe un fichier .tclshrc (ou tclshrc.tcl sur les plateformes Windows) dans le rИpertoire home de l'utilisateur, tclsh Иvalue le fichier comme script Tcl juste avant de lire la premiХre commande sur l'entrИe standard +

    +
    FICHIERS SCRIPT

    +
    Si tclsh est appelИ avec des arguments alors le premier argument est le nom d'un script et tous les arguments supplИmentaires sont rendus disponibles au script comme variables (voir ci-dessous). Au lieu de lire les commandes Ю partir de l'entrИe standard tclsh lira les commandes Tcl du fichier indiquИ;  tclsh finira quand il atteint la fin du fichier. Il n'y a pas d'Иvaluation automatique de .tclshrc dans ce cas, mais le script peut toujours le sourcer si dИsirИ.
    +
    Si vous crИer un script Tcl dans un fichier dont premiХre ligne est
    +
    #!/usr/local/bin/tclsh
    +
    alors vous pouvez appeller le script directement Ю partir de votre shell si vous rendez le fichier exИcutable. Ceci suppose qui tclsh aura ИtИ installИ dans l'emplacement par dИfaut dans /usr/local/bin;  s'il est installИ ailleurs vous aurez Ю modifier la ligne plus haut. De nombreux systХmes UNIX n'autorisent pas la ligne #! Ю dИpasser 30 caractХres, donc soyez sûrs que l'exИcutable tclsh peut Йtre accИdИ avec un nom de chemin court.
    +
    Une meilleure approche est de commencer vos fichiers script avec les trois lignes suivantes:
    +
    #!/bin/sh
    +
    # la ligne suivante lance tclsh\
    +
    exec tclsh "$0" "$@"
    +
    Cette approche a trois avantages sur l'approche prИcedente. PremiХrement, l'emplacement du binaire tclsh n'a pas d'Йtre codИ en dur dans le script: il peut Йtre n'importe oЫ dans votre chemin de recherche shell. DeuxiХmement, elle resout la limite de 30 caractХres pour le nom de chemin dans la prИcedente approche. TroisiХmement, cette approche fonctionnera mЙme si tclsh est lui-mЙme un shell script (c'est fait sur quelques systХmes de maniХre Ю gИrer de multiples architectures ou systХmes d'exploitations: le script tclsh selectionne un parmi plusieurs binaire Ю exИcuter) Les trois lignes mettent en cause Ю la fois sh et tclsh pour traiter le script, mais exec est seulement exИcutИ par sh. sh traite le script en premier; il traite la seconde ligne comme un commentaire et exИcute la troisiХme ligne. L'instruction exec provoque l'arrЙt du traitement par le shell et le dИmarrage de tclsh pour traiter le script entier. Quand tclsh dИmarre, it traite les trois lignes comme des commentaires, car le backslash Ю la fin de la second ligne cause l'interprИtation de la troisiХme ligne comme suite du commentaire sur la seconde ligne
    +

    +
    VARIABLES

    +
    Tclsh fixe les variables Tcl suivantes: +
    +
    argc
    Contient un compte du nombre des arguments arg (0 si aucun), non inclus le nom du fichier script. +
    +

    argv +
    Contient une liste Tcl dont les ИlИments sont les arguments arg, dans l'ordre, ou une chaНne vide si il n'y a pas d'arguments arg. +
    +

    argv0 +
    Contient fileName si il a ИtИ spИcifiИ. Autrement, contient le nom par lequel tclsh a ИtИ appelИ. +
    +

    tcl_interactive +
    Contient 1 si tclsh s'exИcute interactivement (aucun fileName n'a ИtИ spИcifiИ et l'entrИe standard est un pИriphИrique terminal-like), 0 autrement. +
    +
    + +

    +
    PROMPTS

    +
    Quand tclsh est appelИ interactivement il attend normalement chaque commande avec "%" Vous pouvez changer le prompt en fixant les variables tcl_prompt1 et tcl_prompt2 Si la variable tcl_prompt1 existe alors elle doit consister en un script Tcl pour produire un prompt;  au lieu de produire un prompt tclsh evaluera le script dans tcl_prompt1. La variable tcl_prompt2 est utilisИe d'une maniХre analogue quand un saut de ligne est tapИ mais que la commande courante n'est pas encore complХte; si tcl_prompt2 n'est pas fixИ alors aucun prompt ne s'affiche pour les commandes incomplХtes
    +
    +
    + diff --git a/hlp/fr/tcl/tcltest.html b/hlp/fr/tcl/tcltest.html new file mode 100644 index 0000000..f9b8b3b --- /dev/null +++ b/hlp/fr/tcl/tcltest.html @@ -0,0 +1,309 @@ + + + + +

    Tcltest      Commandes internes Tcl

    +
    +
    NOM

    +
    Tcltest -  Support du systХme de test et utilitaires
    +

    +
    SYNTAXE

    +
    package require tcltest ?1.0?
    +::tcltest::test name desc ?constraint? script expectedAnswer
    +::tcltest::cleanupTests ?runningMultipleTests?
    +::tcltest::getMatchingTestFiles
    +::tcltest::loadTestedCommands
    +::tcltest::makeFile contents name
    +::tcltest::removeFile name
    +::tcltest::makeDirectory name
    +::tcltest::removeDirectory name
    +::tcltest::viewFile name
    +::tcltest::normalizeMsg msg
    +::tcltest::bytestring string
    +::tcltest::saveState
    +::tcltest::restoreState
    +::tcltest::threadReap
    +

    +
    DESCRIPTION

    +
    Le package tcltest fournit Ю l'utilisateur des utilitaires pour Иcrire et faire fonctionner des tests dans le systХme de test Tcl. Il peut Иgalement Йtre utilisИ pour crИer un systХme de test personnalisИ pour une extension.
    +
    Le systХme de test Tcl comporte de multiples fichiers .test, chacun d'entre eux comprenant plusieurs cas de test. Chaque test comporte un appel Ю la commande test, qui indique le nom du test, une description brХve, les contraintes qui s'appliquent au cas testИ, le script Ю exИcuter, et les rИsultats attendus. Voir les sections "Tests", "Contraintes de test", et " Faire fonctionner les fichiers de test " pour plus d'informations. +
    Il est Иgalement possible d'enrichir ce systХme de test pour mettre en place votre propre systХme de test sur mesure. Pour plus d'information, voir la section "Personnaliser le systХme de test". +
    Cette approche pour tester a ИtИ conГue et initialement mise en place par Mary Ann May-Pumphrey de Sun Microsystems au dИbut des annИes 1990. Nous lui adressons de sincХres remerciements pour avoir fait don de son travail au profit de la version publique de Tcl.
    +
    COMMANDES
    +
    +
    +
    ::tcltest::test name desc ?constraints? script expectedAnswer
    La commande ::tcltest::test lance script et compare son rИsultat Ю expectedAnswer. Elle imprime un message d'erreur si les deux ne correspondent pas. Si::tcltest::verbose contient "p" ou "s", elle imprime aussi un message si le test rИussit (p: passed) ou a ИtИ omis (s: skipped). Le test sera omis s'il ne correspond pas Ю la variable ::tcltest::match, s'il correspond Ю l'un des ИlИments de ::tcltest::skip, ou si l'un des ИlИments de constraints s'avХre ne pas Йtre vrai. La commande ::tcltest::test n'a pas de valeur de retour dИfinie. Voir la section "Ecrire un nouveau test" pour plus d'informations sur cette commande.
    +
    ::tcltest::cleanupTests ?runningMultipleTests?
    Cette commande doit normalement Йtre appelИe Ю la fin d'un fichier de test. Elle imprime des statistiques au sujet des tests ИxИcutИs et supprime les fichiers crИИs par ::tcltest::makeDirectory et ::tcltest::makeFile. Les noms des fichiers et rИpertoires crИИs en dehors de ::tcltest::makeFile et ::tcltest::makeDirectory, et qui n'ont jamais ИtИ dИtruits, sont affichИs dans ::tcltest::outputChannel. Cette commande restaure Иgalement l'environnement d'ИxИcution initial, tel que dИcrit par le tableau ::env.calledFromAll doit normalement Йtre indiquИ quand ::tcltest::cleanupTests est appelИ depuis un fichier "all.tcl". Des fichiers Tcl sont gИnИralement utilisИs pour exИcuter des tests multiples. Pour plus d'information sur comment exИcuter des tests multiples, voir la section "ExИcuter des fichiers de test". Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::getMatchingTestFiles
    Cette commande est utilisИe quand vous voulez exИcuter plusieurs fichiers de test. Elle retourne la liste des tests qui doivent Йtre sourcИs dans un fichier "all.tcl". Voir la section "ExИcuter des fichiers de test" pour plus d'informations.
    +
    ::tcltest::loadTestedCommands
    Cette commande utilise le script indiquИ par l'option -load ou -loadfile pour charger les commandes testИes par le systХme de test. AutorisИe Ю Йtre vide, dans le cas oЫ; les commandes testИes sont accumulИes dans  l'interprИteur qui ИxИcute le systХme de test.
    +
    ::tcltest::makeFile contents name
    CrИe un fichier qui sera automatiquement supprimИ par ::tcltest::cleanupTests Ю la fin du fichier de test. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::removeFile name
    Force la suppression du fichier rИfИrencИ par name. Ce nom de fichier doit Йtre indiquИ en rИfИrence au ::tcltest::temporaryDirectory. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::makeDirectory name
    CrИe un rИpertoire name, qui sera automatiquement supprimИ par ::tcltest::cleanupTests Ю la fin du fichier de test. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::removeDirectory name
    Force la suppression du fichier rИfИrencИ par name. Cette procИdure n'a pas de valeur de retour dИfinie.
    +
    ::tcltest::viewFile file
    Renvoie le contenu de file.
    +
    ::tcltest::normalizeMsg msg
    Retire les fins de lignes superflues de msg.
    +
    ::tcltest::bytestring string
    Construit une chaНne qui se compose de la suite des octets demandИs, et non la chaНne formИe de caractХres UTF-8 corrects, Ю partir de la valeur de string. Cela permet au testeur de crИer des chaНnes dИnormalisИes ou impropement formИes, pour les passer Ю des procИdures C qui sont supposИes accepter des chaНnes comprenant des NULL, et confirmer que le rИsultat sous forme de chaНne correspond bien Ю la suite d'octets prИvue.
    +
    ::tcltest::saveState
    et ::tcltest::restoreState sauvent et restaurent les procИdures et les variables globales. Un fichier de test peut contenir des appels Ю ::tcltest::saveState et ::tcltest:restoreState s'il crИe des variables globales ou des procИdures.
    +
    ::tcltest::threadReap
    ::tcltest::threadReap fonctionne seulement si testthread est dИfini, gИnИralement en compilant tcltest. Si testthread est dИfini, ::tcltest::threadReap tue tous les threads Ю l'exception du thread principal. Il rИcupХre l'ID du thread principal en appelant testthread names pendant l'initialisation. Cette valeur est stockИe dans ::tcltest::mainThread::tcltest::threadReap retourne le nombre de threads existants en tout. (?)
    +
    +

    +
    TESTS

    +
    La procИdure test ИxИcute un script de test est affiche un message d'erreur si le rИsultat du script ne correspond pas au rИsultat attendu. Voici la spИcification de la commande test :
    +
      +
    test <name> <description> ?<constraint>? <script> <expectedAnswer>
    +
    +
      +
    L'argument <name> doit obИir au motif:
    +
          <target>-<majorNum>.<minorNum>
    +
      +
    Pour les tests "en boНte blanche" (tests de rИgression), la cible <target > doit Йtre le nom de la fonction C ou de la procИdure Tcl  qui est testИe. Pour les tests "en boНte noire", la cible  <target> doit Йtre le nom de la fonctionnalitИ testИe.  Des tests apparentИs doivent avoir le mЙme numИro majeur <majorNum>.
    +
      +
    L'argument <description> est une courte description textuelle du test, pour aider les personnes Ю comprendre ce qui est testИ. Le nom de la fonction Tcl ou C devrait y Йtre inclus pour les tests de rИgression. Si le cas de test est dИfini pour reproduire un bug, inclure l'identifiant (bugID) dans la description.
    +
      +
    L'argument optionnel <constraints> peut Йtre une liste d'un ou plusieurs mots-clИs ou une expression. Si l'argument <constraints> se compose de mots-clИs, chacun d'entre eux doit Йtre le nom d'un ИlИment du tableau ::tcltest::testConstraints.  Si l'un de ces ИlИments est faux ou n'existe pas, le test est sautИ. Si l'argument <constraints> est une expression, cette expression sera ИvaluИe: si le rИsultat est vrai, alors le test sera ИxИcutИ.
    +
      +
    Ajoutez des contraintes appropriИes (par exemple, unixOnly) pour les tests qui ne doivent pas toujours Йtre ИxИcutИs. Par exemple, un test qui ne doit Йtre effectuИ que sur Unix devrait ressembler Ю:
    +
    test getAttribute-1.1 {testing file permissions} {unixOnly} {
    +    lindex [file attributes foo.tcl] 5
    +} {00644}
    +
    Exemple de test contenant une expression:
    +
    test unixNotfy-1.1 {Tcl_DeleteFileHandler} {unixOnly && !testthread} {
    +    catch {vwait x}
    +    set f [open foo w]
    +    fileevent $f writable {set x 1}
    +    vwait x
    +    close $f
    +    list [catch {vwait x} msg] $msg
    +} {1 {ne peut pas attendre la variable "x":  attendrait indИfiniment }}
    +
    +
    Voir la section "Contraintes de Test" pour la liste des contraintes prИdИfinies et pour savoir comment ajouter vos propres contraintes.
    +
      +
    L'argument <script> contient le script a exИcuter pour effectuer le test. Il doit retourner un rИsultat dont la validitИ peut Йtre vИrifiИe. Si votre script demande qu'un fichier soit crИИ Ю la volИe, utilisez svp la procИdure ::tcltest::makeFile. Si votre test demande qu'un petit fichier (moins de 50 lignes) soit contrôlИ en lecture, svp pensez Ю crИer le fichier Ю la volИe en utilisant la procИdure ::tcltest::makeFile. Les fichiers crИИs par la procИdure ::tcltest::makeFile seront automatiquement supprimИs par la procИdure ::tcltest::cleanupTests appelИe Ю la fin de chaque fichier de test.
    +
      +
    L'argument <expectedAnswer> sera comparИ au rИsultat de l'Иvaluation de l'argument <script>. S'ils correspondent, le test passe, sinon il Иchoue.
    +
    +
    LES VARIABLES DU NAMESPACE TCLTEST

    +
    Les variables suivantes sont dИfinies dans le namespace tcltest et peuvent Йtre utilisИes par des tests: +
    +
    ::tcltest::outputChannel
    outputfileID - par dИfaut stdout, peut Йtre prИcisИ en indiquant -outfile sur la ligne de commande. Tout test qui imprime des rИsultats devrait envoyer cette sortie Ю ::tcltest::outputChannel plutôt que de sortir par dИfaut sur stdout.
    +

    ::tcltest::errorChannel
    errorfileID - par dИfaut stderr, peut Йtre prИcisИ en indiquant -errfile sur la ligne de commande. Tout test qui imprime des messages d'erreur devrait le faire vers ::tcltest::errorChannel plutôt que directement dans stderr.
    +

    ::tcltest::mainThread
    main thread ID - 1 par dИfaut. Ce sera le seul thread qui ne sera pas tuИ par ::tcltest::threadReap et qui sera assignИ conformИment Ю la valeur de retour de testthread names Ю l'initialisation.
    +

    ::tcltest::originalEnv
    copie du tableau global "env" au dИbut de l'ИxИcution du test. Ce tableau est utilisИ pour restaurer le tableau "env" Ю sa valeur initiale quand ::tcltest::cleanupTests  est appelИe.
    +

    ::tcltest::workingDirectory
    le rИpertoire dans lequel le systХme de test a ИtИ lancИ.
    +

    ::tcltest::temporaryDirectory
    le rИpertoire de sortie - par dИfaut ::tcltest::workingDirectory , peut Йtre prИcisИ en indiquant   -tmpdir en ligne de commande.
    +

    ::tcltest::testsDirectory
    lЮ oЫ; se trouvent les tests - par dИfaut  ::tcltest::workingDirectory , si le script ne peut pas dИterminer oЫ; le rИpertoire de tests se trouve. Il est possible de changer cette valeur par dИfaut en prИcisant -testdir en ligne de commande. Cette variable devrait toujours Йtre prИcisИe explicitement si les tests sont ИxИcutИs depuis un fichier all.tcl.
    +

    ::tcltest::tcltest
    le nom de l'ИxИcutable utilisИ pour appeler le systХme de test.
    +

    ::tcltest::loadScript
    Le script ИxИcutИ en tant que loadTestCommands. PrИcisИ par -load ou -loadfile.
    +
    +
    +
    +
    CONTRAINTES DE TEST
    +
    +
    Les contraintes sont utilisИes pour dИterminer si un test doit Йtre ignorИ.  Chaque contrainte est stockИe comme un indice du tableau ::tcltest::testConstraints. Par exemple, la contrainte unixOnly est dИfinie de la faГon suivante:
    +
    set ::tcltest::testConstraints(unixOnly) \
    +    [string equal $tcl_platform(platform) "unix"]
    +
    +
    Si un test est contraint par "unixOnly", il ne s'exИcutera que si la valeur de ::tcltest::testConstraints(unixOnly) est vraie. Plusieurs contraintes sont dИfinies dans le package tcltest.  Pour ajouter des contraintes spИcifiques Ю un fichier ou Ю un test, vous pouvez crИer l'index correspondant du tableau ::tcltest::testsConstraints dans votre propre fichier de test.
    +
      +
    Voici la liste des contraintes dИfinies dans le package tcltest : +
    +
    unix
    le test ne peut s'exИcuter que sur les plateformes UNIX
    +
    pc
    le test ne peut s'exИcuter que sur les plateformes Windows
    +
    nt
    le test ne peut s'exИcuter que sur les plateformes Windows NT
    +
    95
    le test ne peut s'exИcuter que sur les plateformes Windows 95
    +
    98
    le test ne peut s'exИcuter que sur les plateformes Windows 98
    +
    mac
    le test ne peut s'exИcuter que sur les plateformes Mac
    +
    unixOrPc
    le test ne peut s'exИcuter que sur les plateformes UNIX ou PC
    +
    macOrPC
    le test ne peut s'exИcuter que sur les plateformes Mac ou PC
    +
    macOrUnix
    le test ne peut s'exИcuter que sur les plateformes Mac ou Unix
    +
    tempNotPc
    le test ne peut Йtre ИxИcutИ sur Windows. C'est un flag pour dИsactiver temporairement un test.
    +
    tempNotMac
    le test ne peut Йtre ИxИcutИ sur un Mac. C'est un flag pour dИsactiver temporairement un test.
    +
    unixCrash
    le test se plante s'il est ИxИcutИ sur UNIX. C'est un flag pour dИsactiver temporairement un test.
    +
    pcCrash
    le test se plante s'il est ИxИcutИ sur PC. C'est un flag pour dИsactiver temporairement un test.
    +
    macCrash
    le test se plante s'il est ИxИcutИ sur Mac. C'est un flag pour dИsactiver temporairement un test.
    +
    emptyTest
    le test est vide, et donc ne vaut pas la peine d'Йtre ИxИcutИ, mais il reste afin d'Йtre Иcrit dans le futur. Cette contrainte provoque l'omission systИmatique du test.
    +
    knownBug
    le test est connu pour se planter, et le bug n'est pas encore corrigИ. Cette contrainte provoque l'omission du test., sauf si l'utilisateur demande le contraire. Voir la section "Introduction" pour plus d'informations.
    +
    nonPortable
    ce test ne peut Йtre effectuИ que dans l'environnement de dИveloppement Tcl/Tk maНtre. Certains tests sont par nature non portables, parce qu'ils dИpendent de choses telles que la longueur de mot du processeur, la configuration du systХme de fichiers, le gestionnaire de fenЙtres, etc. Ces tests sont seulement ИxИcutИs dans l'environnement de dИveloppement Tcl principal, oЫ; la configuration est bien connue. Cette contrainte provoque l'omission du test, sauf si l'utilisateur demande le contraire.
    +
    userInteraction
    ce test demande une interaction avec l'utilisateur. Cette contrainte provoque l'omission du test, sauf si l'utilisateur demande le contraire.
    +
    interactive
    ce test ne peut Йtre effectuИ qu'en mode interactif, c'est Ю dire si la variable globale tcl_interactive est positionnИe Ю 1.
    +
    nonBlockFiles
    ce test ne peut s'exИcuter que si la plateforme supporte de mettre les fichiers en mode non-bloquИ.
    +
    asyncPipeClose
    ce test ne peut s'exИcuter que si la plateforme supporte "async flush" et "async close" sur un pipe.
    +
    unixExecs
    le test ne peut s'exИcuter que si la machine dispose des commandes telles que 'cat', 'echo', etc.
    +
    hasIsoLocale
    le test ne peut s'exИcuter que s'il peut passer dans une locale ISO.
    +
    root
    le test ne peut s'exИcuter que si l'utilisateur Unix est root
    +
    notRoot
    le test ne peut s'exИcuter que si l'utilisateur Unix n'est pas root
    +
    eformat
    le test ne peut s'exИcuter que si l'application a une version fonctionnelle de sprintf respectant le format "e" des nombres flottants.
    +
    stdio
    le test ne peut s'exИcuter que si l'application courante peut fonctionner au travers d'un pipe
    +
    +

    +
    FAIRE FONCTIONNER LES FICHIERS DE TEST

    +
    Utiliser la commande suivante pour exИcuter un fichier de test qui utilise le package tcltest:
    +
    <shell> <testFile> ?<option> ?<value>?? ...
    +
    Les options de ligne de commande sont les suivantes (les variables du namespace tcltest qui correspondent Ю chacune des options sont indiquИes entre parenthХses Ю la fin de la description) : +
    +
    -help
    affiche le mode d'utilisation
    +
    -verbose <level>
    +dИfinit le niveau de verbositИ comme une sous-chaНne de "bps". Voir la section "Informations issus des tests" pour une explication de cette option.  (::tcltest::verbose)
    +
    -match <matchList>
    +effectue seulement les tests qui correspondent aux motifs de "glob" dИfinis dans <matchList>.  (::tcltest::match)
    +
    -skip <skipList>
    +n'effectue pas les tests qui correspondent Ю un ou plusieurs motifs de "glob" dИfinis dans <skipList>.  (::tcltest::skip)
    +
    -file <globPatternList>
    +source seulement les fichiers de test dont les noms rИpondent Ю l'un des motifs de  <globPatternList> dИfinis par rapport au rИpertoire::tcltest::testsDirectory. Cette option n'a de sens qui si vous effectuez des tests utilisant "all.tcl" en tant que <testFile> au lieu d'effectuer directement des fichiers unitaires de test. (::tcltest::matchFiles)
    +
    -notfile <globPatternList>
    +source tous les fichiers sauf ceux dont les noms rИpondent Ю l'un des motifs de <globPatternList> dИfinis par rapport au rИpertoire::tcltest::testsDirectory.   Cette option n'a de sens qui si vous effectuez des tests utilisant "all.tcl" en tant que <testFile> au lieu d'effectuer directement des fichiers unitaires de test. (::tcltest::skipFiles)
    +
    -constraints <list>
    +les tests contenant une contrainte parmi la liste <list> ne seront pas sautИs. Notez que les ИlИments de <list> doivent correspondrent exactement aux contraintes existantes. Ceci est utile si vous voulez avoir la certitude que les tests ayant une contrainte particuliХre sont effectuИs (par exemple, si le testeur souhaite que tous les tests contenant la contrainte knownBug soient effectuИs). (::tcltest::testConstraints(constraintName))
    +
    -limitconstraints <bool>
    Si l'argument de cette option est 1, les tests effectuИs seront ceux qui respectent les contraintes dИfinies par l'option -constraints. La valeur par dИfaut de cet indicateur est 0 (false). Ceci est utile si vous voulez exИcuter seulement les tests qui rИpondent aux contraintes listИes par l'option -constraints. Un testeur peut vouloir cela par exemple pour n'effectuer que les tests contraints par unixOnly et aucun autre. (::tcltest::limitConstraints)
    +
    -load <script>
    utilisera le script indiquИ pour charger les commandes Ю tester (::tcltest::loadTestedCommands). La valeur par dИfaut est un script vide. Voir Иgalement -loadfile ci-dessous. (::tcltest::loadScript)
    +
    -loadfile <scriptfile>
    utilisera le contenu du fichier indiquИ pour charger les commandes Ю tester (::tcltest::loadTestedCommands).Voir Иgalement -load ci-dessus. La valeur par dИfaut est un script vide. (::tcltest::loadScript)
    +
    -tmpdir <directoryName>
    mettra tous les fichiers temporaires (crИИs avec ::tcltest::makeFile et ::tcltest::makeDirectory) dans le rИpertoire indiquИ.  L'emplacement par dИfaut est ::tcltest::workingDirectory.  (::tcltest::temporaryDirectory)
    +
    -testdir <directoryName>
    cherche les tests Ю exИcuter dans le rИpertoire indiquИ. L'emplacement par dИfaut est ::tcltest::workingDirectory. (::tcltest::testsDirectory)
    +
    -preservecore <level>
    contrôle pour les fichiers core.  Cette option dИtermine quel niveau de contrôle sera effectuИ pour les fichiers "core". La valeur par dИfaut pour <level> est 0. Les niveaux <level> sont dИfinis comme suit :
    +
    0
    Pas de contrôle - ne pas contrôler les fichiers core Ю la fin de chaque test, mais les contrôler Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl.
    +
    1
    VИrifier l'existence de fichiers core Ю la fin de chaque commande de test et Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl.
    +
    2
    VИrifier l'existence de fichiers core Ю la fin de chaque commande de test et Ю chaque fois que::tcltest::cleanupTests est appelИ depuis un fichier all.tcl. Sauvegarder tout fichier core produit dans ::tcltest::temporaryDirectory. (::tcltest::preserveCore)
    +
    +
    +
    -debug <debugLevel>
    afficher l'information de debug dans stdout. Ceci est utilisИ pour dИbugger le code du systХme de test. Le niveau de debug par dИfaut est 0. Les niveaux sont dИfinis ainsi:
    +
    0
    Ne pas afficher les informations de debug.
    +
    1
    Afficher l'information indiquant si un test est sautИ parce qu'il ne rИpond Ю aucune des conditions indiquИes dans -match ou ::tcltest::match (userSpecifiedNonMatch), ou parce qu'il rИpond Ю une quelconque des conditions indiquИes par -skip ou ::tcltest::skip ((userSpecifiedSkip).
    +
    2
    Affiche le tableau des options interprИtИ par le processeur de ligne de commande, le contenu du tableau ::env, et toutes les variables utilisateur dИfinies dans le namespace courant, quand elles sont utilisИes.
    +
    3
    Affiche l'information concernant ce que font les procИdures individuelles de le systХme de test.(::tcltest::debug)
    +
    +
    +
    -outfile <filename>
    envoie la sortie gИnИrИe par le package tcltest vers le fichier indiquИ. La valeur par dИfaut est stdout. Notez que la sortie de debug va systИmatiquement dans stdout, quelque soit la valeur de cette option. (::tcltest::outputChannel)
    +
    -errfile <filename>
    envoie les erreurs gИnИrИes par le package tcltest vers le fichier indiquИ. La valeur par dИfaut est stderr. (::tcltest::errorChannel)
    +
    +
    +
    Une seconde faГon d'exИcuter les tests est de dИmarrer un shell, de charger le package tcltest, puis de sourcer un fichier de test appropriИ ou d'utiliser la commande test. Pour utiliser les options en mode interactif, alimenter la variable qui leur correspond dans le namespace tcltest aprХs avoir chargИ le package.
    +
    Voir la section "Contraintes de Test" pour toutes les contraintes prИ-construites qui peuvent Йtre utilisИes dans le tableau ::tcltest::testConstraints. Voir la section "Les variables du namespace Tcltest" pour des informations sur les autres variables dИfinies dans le namespace tcltest.
    +
    Une derniХre faГon d'exИcuter les tests est d'indiquer les fichiers de test Ю exИcuter Ю l'intИrieur d'un fichier all.tcl (qui peut Йtre nommИ diffИremment). C'est l'approche utilisИe par le systХme de test de Tcl. Ce fichier charge le package tcltest, dИfinit l'emplacement du rИpertoire de test (::tcltest::testsDirectory), dИtermine quels fichiers de test exИcuter, source chacun de ces fichiers, appelle ::tcltest::cleanupTests et finit de s'exИcuter.
    +
    Un fichier all.tcl plus ИlaborИ peut faire du prИ- et du post-processing avant de sourcer chaque fichier .test, utiliser des interprИteurs diffИrents pour chaque fichier, ou manipuler des structures de rИpertoires complexes. Pour un exemple de fichier all.tcl, voir la section "Exemples" de ce document.
    +
    RESULTATS DES TESTS

    +
    AprХs que tous les fichiers de test indiquИs aient ИtИ ИxИcutИs, le nombre de tests rИussis, sautИs ou ИchouИs est envoyИ dans::tcltest::outputChannel.  A côtИ de cette information statistique, la sortie peut Йtre pilotИe pour chaque test par la variable ::tcltest::verbose.
    +
      +
    ::tcltest::verbose peut avoir pour valeur n'importe quelle sous-chaНne ou permutation de "bps".   Dans la chaНne "bps", le 'b' se rИfХre au corps (body) du test, le 'p' se rИfХre aux tests rИussis  (passed) et le 's' signifiИ tests sautИs (skipped). La valeur par dИfaut de ::tcltest::verbose est "b". Si 'b' est prИsent, alors le corps entier du test est imprimИ pour chaque test ИchouИ;  sinon seulement le nom du test, la sortie souhaitИe et la sortie obtenue sont imprimИs pour chaque test ИchouИ. Si 'p' est prИsent, alors une ligne est imprimИe pour chaque test rИussi, sinon aucune ligne n'est imprimИe pour les tests rИussis. Si 's' est prИsent, alors une ligne (contenant les contraintes qui ont  fait que le test a ИtИ sautИ) est imprimИe pour chaque test sautИ, sinon aucune ligne n'est imprimИe dans ce cas.
    +
    Vous pouvez positionner ::tcltest::verbose, soit interactivement (une fois que le package tcltest a ИtИ chargИ) ou en utilisant l'argument de ligne de commande -verbose, par exemple:
    +
          tclsh socket.test -verbose bps
    +
    +
    CONTENUS D'UN FICHIER DE TEST
    +
    +
    Les fichiers de test doivent commencer par charger le package tcltest:
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +
    Les fichiers de tests doivent se terminer par l'appel de la fonction de nettoyage ::tcltest::cleanupTests. La procИdure ::tcltest::cleanupTests affiche des statistiques au sujet du nombre de tests rИussis, sautИs ou ИchouИs,  et supprime tous les fichiers crИИs au moyen des procИdures ::tcltest::makeFile et ::tcltest::makeDirectory.
    +
      +
    # Supprime les fichiers crИИs par ces tests
    +
    # Retour au rИpertoire de travail initial
    +# Supprime les tableaux globaux
    +::tcltest::cleanupTests
    +return
    +
    +
    Les fichiers de tests doivent se finir par une extension .test. Les noms des fichiers de tests qui contiennent des tests de rИgression (dits de boНte transparente) doivent Йtre nommИs d'aprХs les fichiers de code Tcl ou C qu'ils testent. Par exemple, le fichier de test du programme C "tclCmdAH.c" doit Йtre "cmdAH.test". Les fichiers qui contiennent des tests "boНte noire" (black-box tests) devraient se conformer au motif "*_bb.test".
    +

    +
    SELECTIONNER DES TESTS A EXECUTER DANS UN FICHIER

    +
    Normalement, quand un fichier est sourcИ, tous les tests qu'il contient sont ИxИcutИs. Individuellement, un test sera sautИ si l'une des conditions suivantes est vraie: +
    +
    [1]
    le nom du test ne correspond pas (en utilisant la correspondance de type "glob") Ю un ou plusieurs ИlИments de la variable ::tcltest::match.
    +
    [2]
    le nom du test correspond (en utilisant la correspondance de type "glob") Ю un ou plusieurs ИlИments de la variable ::tcltest::skip.
    +
    [3]
    l'argument constraints de l'appel Ю ::tcltest::call, s'il existe, contient une ou plusieurs valeurs fausses.
    +
    +
    +
    Vous pouvez dИfinir ::tcltest::match et/ou ::tcltest::skip, soit interactivement (aprХs que le package tcltest a ИtИ sourcИ), ou en utilisant les arguments de ligne de commande -match et -skip, par exemple :  
    +
    tclsh info.test -match '*-5.* *-7.*' -skip '*-7.1*'
    +
    Soyez sûr de bien placer les quotes, de faГon que votre shell ne fasse pas les substitutions de type glob sur les motifs que vous indiquez  (que ce soit bien l'interprИteur tcl qui fasse ces substitutions). 
    +
    Les contraintes prИdИfinies (par exemple knownBug et nonPortable) peuvent Йtre changИes soit interactivement (aprХs que le package tcltest a ИtИ sourcИ), en dИfinissant la variable ::tcltest::testConstraints(constraint), ou en utilisant l'option de ligne de commande -constraints avec le nom de la contrainte comme argument. L'exemple suivant montre comment faire fonctionner des tests contraints par les restrictsions knownBug et nonPortable:
    +
                 tclsh all.tcl -constraints "knownBug nonPortable"
    +
    Voir la section "Contraintes de Test" pour plus d' information sur l'utilisation des contraintes prИdИfinies et l'ajout de nouvelles contraintes.
    +
    +
    PERSONNALISER LE SYSTEME DE TEST
    +
    +
    Pour crИer votre propre systХme de test, crИer un fichier .tcl qui contient votre namespace. Dans ce fichier, appeller le package tcltest (package require tcltest). Les commandes qui peuvent Йtre redИfinies pour personnaliser le systХme de test sont: +
    +
    ::tcltest::PrintUsageInfoHook
    afficher de l'information complИmentaire, spИcifique Ю votre situation.
    +
    ::tcltest::processCmdLineArgsFlagHook
    avertir le systХme au sujet d'options additionnelles que vous voulez qu'il comprenne.
    +
    ::tcltest::processCmdLineArgsHook flags
    traiter les options additionnelles que vous avez communiquИes au systХme de test au travers de ::tcltest::processCmdLineArgsFlagHook.
    +
    ::tcltest::initConstraintsHook
    ajouter des contraintes additionnelles aux contraintes prИdИfinies par tcltest.
    +
    ::tcltest::cleanupTestsHook
    faire du nettoyage additionnel
    +
    +
    +
    Pour ajouter de nouvelles options Ю votre systХme de test personnalisИ, redИfinissez ::tcltest::processCmdLineArgsAddFlagHook pour la liste des options additionnelles Ю interprИter, et ::tcltest::processCmdLineArgsHook pour les traiter effectivement . Par exemple:
    +
    proc ::tcltest::processCmdLineArgsAddFlagHook {} {
    +    return [list -flag1 -flag2]
    +}
    +
    +proc ::tcltest::processCmdLineArgsHook {flagArray} {
    +    array set flag $flagArray
    +
    +    if {[info exists flag(-flag1)]} {
    +        # Handle flag1
    +    }
    +
    +    if {[info exists flag(-flag2)]} {
    +        # Handle flag2
    +    }
    +
    +    return
    +}
    +
    +
      +
    Vous pouvez aussi vouloir ajouter un mode d'emploi pour ces options.  Ce mode d'emploi s'affichera quand l'utilisateur indiquera -help. Pour dИfinir le mode d'emploi additionnel, dИfinissez votre propre procИdure ::tcltest::PrintUsageInfoHook. A l'intИrieur de cette procИdure, vous afficherez le mode d'emploi complИmentaire pour chacune des options que vous avez ajoutИes.
    +
      +
    Pour ajouter de nouvelles contraintes prИdИfinies au systХme de test, dИfinissez votre propre version de ::tcltest::initConstraintsHook.  A l'intИrieur de cette procИdure, vous pouvez complИter le tableau ::tcltest::testConstraints. Par exemple:
    +
    proc ::tcltest::initConstraintsHook {} {
    +    set ::tcltest::testConstraints(win95Or98) \
    +            [expr {$::tcltest::testConstraints(95) || \
    +            $::tcltest::testConstraints(98)}]
    +}
    +
    +
    Enfin, si vous voulez ajouter du code de nettoyage complИmentaire, vous pouvez dИfinir votre propre ::tcltest::cleanupTestsHook.  Par exemple:
    +
    proc ::tcltest::cleanupTestsHook {} {
    +    # Add your cleanup code here
    +}
    +
    +
    EXEMPLES
    +
      +
    [1]      Un fichier de test simple (foo.test)
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +test foo-1.1 {enregistrer 1 dans la variable foo} {} {
    +    set foo 1
    +} {1}
    +
    +::tcltest::cleanupTests
    +return
    +
    +
    [2]      Un fichier all.tcl simple
    +
    if {[lsearch [namespace children] ::tcltest] == -1} {
    +    package require tcltest
    +    namespace import ::tcltest::*
    +}
    +
    +set ::tcltest::testSingleFile false
    +set ::tcltest::testsDirectory [file dir [info script]]
    +
    +foreach file [::tcltest::getMatchingTestFiles] {
    +    if {[catch {source $file} msg]} {
    +        puts stdout $msg
    +    }
    +}
    +
    +::tclttest::cleanupTests 1
    +return
    +
    +
    [3]      ExИcuter un test simple
    +
    tclsh foo.test
    +
    +
    [4]      ExИcuter des tests multiples
    +
    tclsh all.tcl -file 'foo*.test' -notfile 'foo2.test'
    +
    +
      +
    DerniХre rИvision: 8.2
    + diff --git a/hlp/fr/tcl/tclvars.htm b/hlp/fr/tcl/tclvars.htm new file mode 100644 index 0000000..94571b5 --- /dev/null +++ b/hlp/fr/tcl/tclvars.htm @@ -0,0 +1,111 @@ + + + + +

    tclvars      Commandes Internes Tcl

    +
    +
    NOM

    +
    tclvars - Variables utilisИes par Tcl  +

    +
    DESCRIPTION

    +
    Les variables globales suivantes sont crИИe et gИrИes automatiquement par les bibliothХque Tcl. ExceptИ quand signalИ ci-dessous, ces variables doivent normalement Йtre traitИes en lecture seule par le code spИcifique Ю l'application et par les utilisateurs. +
    +
    env
    Cette variable est gИrИe par Tcl comme un tableau dont les ИlИments sont les variables d'environnements pour le processus. Lire un ИlИment renverra la valeur de la variable d'environnement correspondante. Ecrire un ИlИment du tableau modifiera la variable d'environnement correspondante ou en crИera une nouvelle si elle n'existe pas dИjЮ. Effacer un ИlИment de  env enlХvera la variable d'environnement correspondante. Les changements du tableau env affectent l'environnement transmis aux enfants par les commandes comme exec. Si le tableau entier env est effaГИ alors Tcl arrХtera de surveiller l'accХs Ю env et ne mettra plus Ю jour les variables d'environnements. +
    Sous Windows, les variables d'environnements PATH et COMSPEC sont converties automatiquement en majuscule Par exemple, la variable PATH pourrait Йtre exportИe par le systХme d'exploitation comme "path", "Path", "PaTh", etc., ce qui autrement demanderait au code Tcl de supporter de nombreux cas spИciaux. Toutes les autres variables d'environnement hИritИes par Tcl sont inchangИes. +
    Sur Macintosh, la variable d'environnement est construite par Tcl car aucune variable globale d'environnement n'existe. Les variable d'environnements qui sont crИИes par Tcl inclutnt: +
    +

    LOGIN +
    Contient le nom Chooser du Macintosh. +
    +

    USER +
    Contient aussi le nom Chooser du Macintosh.
    +

    SYS_FOLDER +
    Le chemin du rИpertoire systХme.
    +

    APPLE_M_FOLDER +
    Le chemin du rИpertoire du Menu Pomme.
    +

    CP_FOLDER +
    Le chemin du rИpertoire du panneau de contrТle.
    +

    DESK_FOLDER +
    Le chemin du rИpertoire du bureau.
    +

    EXT_FOLDER +
    Le chemin du rИpertoire d'extensions systХme.
    +

    PREF_FOLDER +
    Le chemin du rИpertoire des prИferences.
    +

    PRINT_MON_FOLDER +
    Le chemin du rИpertoire print monitor.
    +

    SHARED_TRASH_FOLDER +
    Le chemin du rИpertoire de la corbeille rИseau.
    +

    TRASH_FOLDER +
    Le chemin du rИpertoire de la corbeille.
    +

    START_UP_FOLDER +
    Le chemin du rИpertoire de dИmarrage.
    +

    PWD +
    Le chemin du rИpertoire par dИfaut de l'application.
    +
    +
    Vous pouvez aussi crИer votre propre variable d'environnement pour le Macintosh. Un fichier nommИ Tcl Environment Variables peut Йtre placИ dans le dossier prИferences dans le dossier systХme Mac. Chaque lignes de ce fichier seront de la forme VAR_NAME=var_data. +
    La derniХre alternative est de placer les variable d'environnements dans une resource 'STR#' nommИe Tcl Environment Variables de l'application. Ceci est considerИ un peu plus "Mac like" qu'un fichier style Unix Environment Variable. Chaque entrИe dans la resource 'STR#' a le mЙme format que ci-dessous. Le fichier source tclMacEnv.c contient l'implИmentation des mИcanismes de env. Ce fichier contient de nombreux #define qui autorisent la customisation des mИcanismes env pour les adapter aux besoins de votre applications. +
    +

    errorCode
    AprХs une erreur, cette variable est fixИe pour recevoir l'information supplИmentaire au sujet de l'erreur sous une forme qui est facile Ю traiter pour les programmes. errorCode consiste d'une liste Tcl avec un ou plusieurs ИlИments. Le premier ИlИment de la liste identifie une classe gИnИrale d'erreurs, et dИtermine le format du reste de la liste. Les formats suivants pour errorCode sont utilisИs par le noyau Tcl; les applications peuvent definir des formats supplИmentaires. +
    +
    ARITH code msg
    Ce format est utilisИ quand une erreur arithmИtique se produit (ex. une tentative de division par zИro dans une commande expr). Code identifie l'erreur prИcise et msg fournit une description comprИhensible de l'erreur Code sera soit DIVZERO (pour une tentative de division par zИro), DOMAIN (si un argument est en dehors du domaine d'une fonction, tel acos(-3)), IOVERFLOW (dИbordement entier), OVERFLOW (dИbordement flottant), ou UNKNOWN (si la cause de l'erreur ne peut pas Йtre dИterminИe).
    +

    CHILDKILLED pid sigName msg +
    Ce format est utilisИ quand un processus enfant a ИtИ tuИ Ю cause d'un signal. Le second ИlИment de errorCode sera l'identificateur de processus (en dИcimal). Le troisiХme ИlИment sera le nom symbolique du signal qui Ю causИ la fin du processus; il sera un des noms du fichier include signal.h, tel que SIGPIPE. Le quatriХme ИlИment sera un court message dИcrivant le signal, tel que "write on pipe whith no readers" pour SIGPIPE.
    +

    CHILDSTATUS pid code +
    Ce format est utilisИ quand un processus enfant s'est terminИ avec un statut diffИrent de zИro Le second ИlИment de errorCode sera l'identificateur de processus (en dИcimal). et le troisiХme ИlИment sera le code de fin renvoyИ par le processus (aussi en dИcimal).
    +

    CHILDSUSP pid sigName msg +
    Ce format est utilisИ quand un processus enfant a ИtИ suspendu Ю cause d'un signal. Le second ИlИment de errorCode sera l'identificateur de processus (en dИcimal).. Le troisiХme ИlИment sera le nom symbolique du signal qui a causИ la suspension du processus; ce sera un des noms du fichier include signal.h,, tel que SIGTTIN. Le quatriХme ИlИment sera sera un court message dИcrivant le signal, tel que "background tty read" pour SIGTTIN.
    +

    NONE +
    Ce format est utilisИ pour les erreurs oЫ aucune information supplИmentaire n'est disponible pour une erreur en plus du message renvoyИ avec l'erreur Dans ces cas errorCode consistera en une liste contenant un seul ИlИment dont le contenu sera NONE.
    +
    POSIX errName msg
    Si le premier ИlИment de errorCode est POSIX, alors l'erreur s'est produite pendant un appel noyau POSIX. Le second ИlИment de la liste contiendra le nom symbolique de l'erreur qui s'est produite, tel que ENOENT; ce sera une des valeurs dИfinies dans le fichier include errno.h. Le troisiХme ИlИment de la liste sera un message comprИhensible correspondant Ю errName, tel que "aucun fichier ou rИpertoire" dans le cas de ENOENT.
    Pour fixer errorCode, les applications devraient utiliser une fonction de bibliothХque telle que Tcl_SetErrorCode et Tcl_PosixError, ou elles peuvent appeller la commande error. Si une de ces mИthodes n'a pas ИtИ utilisИe, alors l'interprИteur Tcl rИinitialisera la variable Ю NONE aprХs l'erreur suivante. +
    +
    +
    +

    errorInfo
    AprХs une erreur, cette chaНne contiendra une ou plusieurs lignes identifiant la commande Tcl et les fonctions qui Иtaient exИcutИes quand l'erreur la plus recente s'est produite. Son contenu prend la forme d'une trace de la pile montrant les commandes Tcl imbriquИes qui avait ИtИ appelИes Ю l'instant de l'erreur.
    +

    tcl_library +
    Cette variable contient le nom d'un rИpertoire contenant les bibliothХques systХme de scripts Tcl, tel que celles utilisИes pour un auto-chargement. La valeur de cette variable est renvoyИ par la commande info library. Voir la page de manuel library pour les dИtails des facilitИs fournies par la bibliothХque de scripts Tcl. Normalement chaque application ou package aura sa propre bibliothХque spИcifique en plus de la bibliothХque Tcl; chaque application devra fixer une variable globale avec un nom comme $app_library (oЫ app est le nom de l'application) pour recevoir le nom de chemin rИseau du rИpertoire de la bibliothХque de cette de l'application. La valeur initiale de tcl_library est fixИe quand un interprИteur est crИИ en cherchant plusieurs rИpertoire diffИrents jusqu'a ce qu'un soit trouvИ contenant un script de dИmarrage appropriИ. Si la variable d'environnement TCL_LIBRARY existe, alors le rИpertoire qu'elle indique est vИrifiИ en premier. Si TCL_LIBRARY n'est pas fixИ ou ne se refХre pas Ю un rИpertoire appropriИ, alors Tcl vИrifie plusieurs autre rИpertoires en se basant sur l'emplacement compilИ par dИfaut, l'emplacement du binaire contenant l'application, et le rИpertoire de travail courant.
    +

    tcl_patchLevel +
    Quand un interprИteur est crИИ Tcl initialise cette variable pour recevoir une chaНne donnant le courant niveau de patch de Tcl, tel que 7.3p2 for Tcl 7.3 avec les deux premier patches officiels, ou 7.4b4 pour la quatriХme release beta de Tcl 7.4. La valeur de cette variable est renvoyИ par la commande info patchlevel.
    +

    tcl_pkgPath +
    Cette variable contient une liste de rИpertoires indiquant oЫ les packages sont normalement installИs. Elle n'est pas utilisИe sous Windows. Elle contient typiquement soit une ou deux entrИes; si elle contient deux entrИes, la premiХre est normalement un rИpertoire pour les packages dependant de la plateforme (ex., bibliothХques partagИes binaires) et le second est normalement un rИpertoire pour les packages indИpendants de la plateforme- (ex., fichiers script). Typiquement un package est installИ comme sous rИpertoire d'une des entrИes de $tcl_pkgPath. Les rИpertoires de $tcl_pkgPath sont inclus par dИfaut dans la variable auto_path, donc eux et leurs sous-rИpertoires immИdiats sont automatiquement recherchИ pendant les commandes package require Note: tcl_pkgPath n'est pas conГue pour Йtre modifiИe par les application. Sa valeur est ajoutИe Ю auto_path au dИmarrage; les changement dans tcl_pkgPath ne sont pas reflИtИs dans auto_path. Si vous voulez que Tcl recherche les packages dans des rИpertoires supplИmentaires vous devrez ajouter leurs noms Ю auto_path, pas Ю tcl_pkgPath.
    +

    tcl_platform +
    Ceci est un tableau associatif dont les ИlИments contiennent l'information concernant la plateforme sur laquelle l'application s'exИcute, tel que le nom du systХme d'exploitation, son numИro de release courant, et le jeu d'instruction de la machine Les ИlИments listИs ci-dessous seront toujours dИfinis, mais ils peuvent avoir des chaНne vides comme valeurs si Tcl n'a pu rИcupИrer quelconque information en rapport De plus, les extensions et les applications peuvent ajouter des valeurs supplИmentaires au tableau Les ИlИments prИdИfinis sont: +
    +
    byteOrder
    L'ordre natif des octets de cette machine: soit littleEndian ou bigEndian
    +

    debug +
    Si cette variable existe, alors l'interprИteur a ИtИ compilИ avec les symboles debuggage activИs. Cette variable existe seulement sous Windows donc les programmeurs d'extension peuvent spИcifier quel package charger, ceci dИpendant de la bibliothХque d'exИcution C qui est chargИe.
    +

    machine +
    Le jeu d'instruction exИcutИ par cette machine, tel que intel, PPC, 68k, ou sun4m Sur les machines UNIX, c'est la valeur renvoyИe par uname -m.
    +

    os +
    Le nom du systХme d'exploitation exИcutИ sur cette machine, tel que Windows 95, Windows NT, MacOS, ou SunOS. Sur les machines UNIX, c'est la valeur renvoyИe par uname -s. Sur Windows 95 et Windows 98, la valeur renvoyИe sera Windows95 pour fournir une meilleure compatibilitИ ascendante avec Windows 95; pour distinguer entre les deux, vИrifier osVersion.
    +

    osVersion +
    Le numИro de version du systХme d'exploitation exИcutИ sur cette machine. Sur les machines UNIX, c'est la valeur renvoyИe par uname -r Sur Windows 95, la version sera 4.0; sur Windows 98, la version sera 4.10.
    +

    platform +
    Soit windows, macintosh, ou unix. Identifie l'environnement de la machine.
    +

    threaded +
    Si cette variable existe, alors l'interprИteur a ИtИ compilИ avec les threads activИs.
    +

    user +
    Ceci identifie l'utilisateur courant basИes sur l'information de login disponible sur la plateforme. Est tirИ de la variable d'environnement USER ou LOGNAME sous Unix, et de la valeur de GetUserName sous Windows et Macintosh.
    +
    +

    tcl_precision +
    Cette variable contrТle le nombre de chiffres Ю gИnИrer pendant la conversion de valeurs flottantes en chaНnes Par dИfaut de 12. 17 chiffres est "parfait" pour les flottants IEEE  car il permet de convertir les valeurs double-prИcision en  chaНnes puis de revenir en binaire sans perte d'information NИanmoins, l'utilisation de 17 chiffres empЙche tout arrondi, et produit des rИsultats plus long, et moins intuitifs Par exemple, expr 1.4 retourne 1.3999999999999999 avec tcl_precision fixИ Ю 17, contre 1.4 si tcl_precision est Ю 12. Tous les interprИteurs dans un processus partagent une seule valeur tcl_precision: la changer pour un interprИteur affectera tous les autres interprИteurs. NИanmoins, les interprИteur sЫrs ne sont pas autorisИ Ю modifier la variable. /DD> +

    tcl_rcFileName +
    Cette variable est utilisИe pendant l'initialisation pour indiquer le nom d'un fichier de dИmarrage spИcifique Ю l'utilisateur. Si elle est fixИe par l'initialisation spИcifique Ю l'application, alors le code Tcl de dИmarrage vИrifiera l'existence de ce fichier et le source s'il existe. Par exemple, pour wish la variable est fixИe Ю ~/.wishrc sous Unix et ~/wishrc.tcl sous Windows.
    +

    tcl_rcRsrcName +
    Cette variable est utilisИe seulement sur les systХmes Macintosh. La variable est utilisИe pendant l'initialisation pour indiquer le nom d'une resource TEXT spИcifique Ю l'utilisateur localisИe dans les resource forks de l'application ou de l'extension. Si elle est fixИe par l'initialisation spИcifique Ю l'application, alors le code Tcl de dИmarrage vИrifiera l'existence de cette resource et la source si elle existe. Par exemple, l'application Macintosh wish a la variable fixИe Ю tclshrc.
    +

    tcl_traceCompile +
    La valeur de cette variable peut Йtre fixИe pour contrТler combien d'information de traГage est affichИe pendant la compilation du bytecode. Par dИfaut, tcl_traceCompile est Ю zИro et aucune information n'est affichИe. Fixer tcl_traceCompile Ю 1 gИnХre une ligne sur la sortie standard chaque fois qu'une fonction ou commande de premier niveau est compilИe. La fixer Ю 2 gИnХre un listing dИtaillИ sur la sortie standard des instructions bytecode Иmises pendant toute la compilation. Cette variable est utile pour rechercher des problХmes suspectИs avec le compilateur Tcl. Elle est aussi parfois utile pour la conversion de code existant en Tcl8.0.
    +

    tcl_traceExec +
    La valeur de cette variable peut Йtre fixИe pour contrТler combien d'information de traГage est affichИe pendant l'exИcution du bytecode. Par dИfaut, tcl_traceExec est Ю zИro et aucune information n'est affichИe. Fixer tcl_traceExec Ю 1 gИnХre une ligne sur la sortie standard Ю chaque appel d'une fonction Tcl. La fixer Ю 2 gИnХre une ligne de sortie chaque fois qu'une commande Tcl est appelИe, qui contient le nom de la commande et ses arguments. La fixer Ю 3 produit une trace dИtaillИe montrant le rИsultat de l'exИcution chaque instruction bytecode. Notez que quand tcl_traceExec est Ю 2 ou Ю 3, les commandes tel que set et incr qui ont ИtИ entiХrement remplacИes par une sИquence d'instructions bytecode ne sont pas montrИes. Fixer cette variable est utile pour rechercher des problХmes suspectИs avec le compilateur et l'interprИteur Tcl. Elle est aussi parfois utile pour la conversion de code existant en Tcl8.0.
    +

    tcl_wordchars +
    La valeur de cette variable est une expression rationelle qui peut Йtre fixИe pour contrТler ce qui est considerИ comme des caractХres "mot", pour des utiisations comme la selection d'un mot par double-click dans le texte dans Tk. Il est dИpendant de la plateforme. Sous Windows, il est par dИfaut de \S, signifiant tout sauf le caractХre espace Unicode Autrement il est par dИfaut de \w, qui est tout caractХre Unicode (nombre, lettre, ou underscore).
    +

    tcl_nonwordchars +
    La valeur de cette variable est une expression rationelle qui peut Йtre fixИe pour contrТler ce qui est considerИ comme des caractХres "non-mot", pour des utilisations comme la selection d'un mot par double-click dans le texte dans Tk. Il est dИpendant de la plateforme Sous Windows, il est par dИfaut de \s, signifiant tout caractХre espace Unicode Autrement il est par dИfaut de \W, qui est tout sauf un caractХre Unicode (nombre, lettre, ou underscore).
    +

    tcl_version +
    Quand un interprИteur est crИИ Tcl initialise cette variable pour recevoir le numИro de version de cette version de Tcl sous la forme x.y. Les changements de x reprИsentent les changements majeurs avec probable incompatibilitИs et les changements de y reprИsentent les petites amИliorations et les corrections de bugs qui conservent une compatibilitИ ascendante. La valeur de cette variable est renvoyИ par la commande info tclversion
    +
    +

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/tell.htm b/hlp/fr/tcl/tell.htm new file mode 100644 index 0000000..a248c50 --- /dev/null +++ b/hlp/fr/tcl/tell.htm @@ -0,0 +1,18 @@ + + + + +

    tell      Commandes Internes Tcl

    +
    +
    NOM

    +
    tell - Retourne la position courante du curseur dans un canal ouvert +

    +
    SYNTAXE

    +
    tell channelId 
    +

    +
    DESCRIPTION

    +
    Renvoie une chaНne entiХre donnant la position courante du curseur dans channelId Cette valeur renvoyИe est un offset d'octet qui peut Йtre transmise Ю seek de maniХre Ю fixer le canal Ю une position particuliХre. Notez que cette valeur est en terme d'octets, pas de caractХres comme read. La valeur renvoyИe est -1 pour les canaux qui ne supportent pas la recherche

    +
    DerniХre rИvision: 8.1
    +
    +
    + diff --git a/hlp/fr/tcl/time.htm b/hlp/fr/tcl/time.htm new file mode 100644 index 0000000..b34ecff --- /dev/null +++ b/hlp/fr/tcl/time.htm @@ -0,0 +1,19 @@ + + + + +

    time      Commandes Internes Tcl

    +
    +
    NOM
    +
    time - chronomХtre l'exИcution d'un script +

    +
    SYNTAXE

    +
    time script ?count? +

    +
    DESCRIPTION

    +
    Cette commande appelera l'interprИteur Tcl count fois Ю Иvaluer script (ou une fois si count n'est pas spИcifiИ) Elle retournera ensuite une chaНne de la forme
    +
    503 microseconds per iteration
    +
    ce qui indique le temps moyen requis par itИration, en microsecondes. Time est mesurИ en temps ИcoulИ, pas en temps CPU
    +
    +
    + diff --git a/hlp/fr/tcl/trace.htm b/hlp/fr/tcl/trace.htm new file mode 100644 index 0000000..ec70e44 --- /dev/null +++ b/hlp/fr/tcl/trace.htm @@ -0,0 +1,44 @@ + + + + +

    trace      Commandes Internes Tcl

    +
    +
    NOM

    +
    trace - suivre l'accХs aux variables
    +

    +
    SYNTAXE

    +
    trace option ?arg arg ...?  +

    +
    DESCRIPTION

    +
    Cette commande provoque l'exИcution de certaines commandes Tcl quand certaines opИrations sont appelИes. Actuellement, seule la trace de variables est mise en place. Les options valides (qui peuvent Йtre abrИgИes) sont: +
    +
    trace variable name ops command
    Provoque l'ИxИcution de la commande command Ю chaque fois que la variable name est accИdИe par un des moyens indiquИ par ops. Name peut faire rИfИrence Ю une variable simple, un ИlИment d'un tableau , ou un tableau dans son entier (c'est Ю dire que  name peut juste Йtre le nom d'un tableau, sans parenthХses d'index). Si name se rИfХre Ю un tableau entier, alors command est appelИe pour chaque manipulation d'un ИlИment du tableau. Si la variable n'existe pas, elle sera crИИe mais n'aura pas de valeur, donc elle sera visible par les requЙtes namespace which, mais pas par les requЙtes info exists.
    +Ops indique quelles opИrations sont suivies, et comprend une ou plusieurs des lettres suivantes: +
    +
    r
    Appelle command Ю chaque fois que la variable est lue.
    +
    w
    Appelle command Ю chaque fois que la variable est Иcrite. +
    +
    u
    Appelle command Ю chaque fois que la variable est annulИe. Les variables peuvent Йtre annulИes explicitement avec la commande unset, ou implicitement Ю la fin des procИdures (toutes leurs variables locales sont annulИes). Les variables sont aussi annulИes quand des interprИteurs sont dИtruits, mais les commandes de trace ne seront pas appelИes parce qu'il n'y aura pas d'interprИteur pour les ИxИcuter. +
    +

    +Quand la trace se dИclenche, trois arguments sont ajoutИs Ю la fin de command , de telle sorte que la commande est rИellement appelИe comme suit:
    +command name1 name2 op
    +Name1 et name2 donnent le(s) nom(s) pour la variable accИdИe: si la variable est scalaire, alors name1 donne le nom de la variable et name2 est une chaНne vide; si la variable est un ИlИment de tableau, name1 donne le nom du tableau et name2 l'index dans le tableau; si un tableau entier est dИtruit et que la trace Иtait enregistrИe sur la totalitИ du tableau et non sur un seul ИlИment, alors name1 donnera le nom du tableau et name2 une chaНne vide. Name1 et name2 ne sont pas nИcessairement les mЙmes noms que celui utilisИ dans la commande trace variable: la commande upvar permet Ю une procИdure de rИfИrencer une variable sous un nom diffИrent. Op indique quelle opИration est effectuИe sur la variable, et est l'une des trois lettres r, w ou u qui sont dИfinies plus haut.
    +Command s'ИxИcute dans le mЙme contexte que le code qui a appelИ l'opИration tracИe: si la variable Иtait accИdИe comme partie d'une procИdure Tcl, alors command aura accХs aux mЙmes variables locales que le code de la procИdure. Ce contexte peut Йtre diffИrent de celui dans lequel la trace a ИtИ crИИe. Si command appelle une procИdure (ce qui est le cas normal) alors la procИdure devra utiliser upvar ou uplevel si elle souhaite accИder Ю la variable tracИe.  Noter aussi que name1 n'est pas nИcessairement le mЙme que le nom utilisИ pour dИfinir la trace sur la variable; des diffИrences peuvent se produire si l'accХs est fait au travers d'une variable dИfinie par la commande upvar.
    +Pour les traces en lecture et en Иcriture, command peut changer la variable pour modifier le rИsultat de l'opИration tracИe. Si command modifie la valeur de la variable pendant une trace en lecture ou en Иcriture, alors la nouvelle valeur sera retournИe comme Иtant le rИsultat de l'opИration tracИe. La valeur de retour de command est ignorИe sauf dans le cas oЫ elle retourne une erreur quelconque; dans ce cas l'opИration tracИe renvoie aussi une erreur avec le mЙme message d'erreur que celui renvoyИ par la commande appelИe par trace (ce mИcanisme peut Йtre utilisИ pour mettre en place des variables en lecture seule, par exemple). Pour les traces en Иcriture, command est appelИe aprХs que la valeur de la variable ait ИtИ changИe; elle peut Иcrire une nouvelle valeur dans la variable pour forcer la valeur produite par l'opИration d'Иcriture. Pour mettre en place des variables en lecture seule, command aura Ю charge de  remettre l'ancienne valeur dans la variable.
    +Pendant que command s'ИxИcute durant une trace en lecture ou en Иcriture, les traces sur la variable sont temporairement dИsactivИes. Cela signifie que les lectures ou les Иcritures appelИes par command se produiront directement, sans invoquer command  (ni aucune autre trace) une nouvelle fois. Cependant, si command annule la variable, les traces d'annulation seront appelИes.
    +Quand une trace d'annulation est appelИe, la variable a dИjЮ ИtИ dИtruite: elle apparaНtra comme indИfinie et ne possИdant pas de traces. Si une annulation de variable se produit Ю cause d'une fin de procИdure, la trace sera appelИe dans le contexte de variables de la procИdure appelante: le contexte de pile de la procИdure qui s'est finie n'existera plus. Les traces ne seront pas dИsactivИes pendant les traces d'annulation, donc si une commande de trace d'annulation crИe une nouvelle trace et accХde Ю la variable correspondante, cette commande de trace sera appelИe. Les erreurs dans les traces d'annulation sont ignorИes.
    +S'il y a plusieurs traces sur une variable elles seront appelИes selon leur ordre de crИation, les plus rИcentes en premier. Si une trace renvoie une erreur, les traces suivantes portant sur la mЙme variable ne seront pas appelИes. Si un ИlИment de tableau a une trace positionnИe, et qu'il y a aussi une trace positionnИe sur le tableau dans son ensemble, la trace globale est appelИe avant celle qui porte sur l'ИlИment seul.
    +Une fois crИИe, la trace reste en effet jusqu'Ю ce qu'elle soit retirИe au moyen de la commande trace vdelete dИcrite ci-dessous, ou bien jusqu'Ю ce que la variable soit annulИe, ou bien jusqu'Ю ce que l'interprИteur soit dИtruit. L'annulation de l'ИlИment d'un tableau retirera toutes les traces sur cet ИlИment, mais ne retirera pas les traces sur l'ensemble du tableau.
    +Cette commande retourne une chaНne vide. +
    +

    trace vdelete name ops command
    S'il existe une trace positionnИe sur la variable name avec les opИrations ops et la commande command, alors la trace est supprimИe, de telle sorte que command ne sera plus jamais appelИe. Retourne une chaНne vide.
    +

    trace vinfo name
    +Retourne une liste contenant un ИlИment pour chaque trace positionnИe sur la variable name. Chaque ИlИment de la liste est lui-mЙme une liste contenant deux ИlИments, qui sont les ops et command associИes Ю la trace. Si name n'existe pas ou n'a aucune trace positionnИe, le rИsultat de la commande sera une chaНne vide. +
    +
    +
    +
    +
    + diff --git a/hlp/fr/tcl/unknown.htm b/hlp/fr/tcl/unknown.htm new file mode 100644 index 0000000..38e84d8 --- /dev/null +++ b/hlp/fr/tcl/unknown.htm @@ -0,0 +1,19 @@ + + + + +

    unknown      Commandes Internes Tcl

    +
    +
    NOM

    +
    unknown- GХre les tentatives d'utiliser des commandes inexistantes +

    +
    SYNTAXE

    +
    unknown cmdName ?arg arg ...? +

    +
    DESCRIPTION

    +
    Cette commande est appelИe par l'interprИteur Tcl chaque fois qu'un script essaie d'appeler une commande qui n'existe pas. L'implИmentation d'unknown ne fait pas partie du noyau Tcl; en fait, c'est une fonction de bibliothХque dИfinie par dИfaut quand Tcl dИmarre. Vous pouvez surcharger unknown pour changer sa fonctionalitИ.
    +
    Si l'interprИteur Tcl rencontre un nom de commande pour lequel il n'y a pas de commande dИfinie, alors Tcl vИrifie l'existence d'une commande nommИe unknown. S'il n'y a pas de commande de ce nom, alors l'interprИteur retourne une erreur. Si la commande unknown existe, alors elle est appelИe avec les arguments consistant des nom et arguments pleinement-substituИs de la commande originale inexistante. La commande unknown typiquement fait des choses comme chercher Ю travers des rИpertoires de bibliothХque une commande avec le nom cmdName, ou expanser un nom de commande abrИgИ, ou exИcuter automatiquement des commandes inconnues en tant que sous-processus. Dans quelques cas (tel que l'expansion d'abrИviations) unknown changera lИgХrement la commande originale et alors la (re-)exИcutera. Le rИsultat de la commande unknown est utilisИ comme rИsultat de la commande inexistante originale.
    +
    L'implИmentation par dИfaut d'unknown se comporte comme suit. Elle appelle en premier la fonction de bibliothХque auto_load pour charger la commande. Si cela rИussit, alors elle exИcute la commande originale avec ses arguments originaux. Si l'auto-load Иchoue alors unknown appelle auto_execok pour voir si il y a un fichier exИcutable de nom cmd. Si c'est le cas, elle appelle la commande Tcl exec avec cmd et tout les args comme aguments. Si cmd peut Йtre auto-exИcutИ, unknown verifie si la commande a ИtИ appelИe au premier plan et en dehors de quelconque script Si c'est le cas, alors unknown suit deux Иtapes supplИmentaires. D'abord, elle regarde si cmd a une des trois formes suivantes: !!, !event, ou ^old^new?^?. Si c'est le cas, alors unknown produit des substitutions d'historique de la mЙme faГon que csh pour ces constructions. Finalement, unknown verifie si cmd est une abrИviation unique d'une commande Tcl existante. Si c'est le cas, elle expanse le nom de la commande et exИcute la commande avec les arguments originaux. Si aucun des efforts prИcИdents n'ont pu exИcuter la commande, unknown gИnХre une erreur. Si la variable globale auto_noload est dИfinie, alors l'Иtape auto-load est sautИe. Si la variable globale auto_noexec est dИfinie alors l'Иtape auto-exec est sautИe. Sous des circonstances normales la valeur de retour de unknown est la valeur de retour de la commande qui a ИtИ Иventuellement exИcutИe.
    +
    +
    + diff --git a/hlp/fr/tcl/unset.htm b/hlp/fr/tcl/unset.htm new file mode 100644 index 0000000..b9a00ba --- /dev/null +++ b/hlp/fr/tcl/unset.htm @@ -0,0 +1,17 @@ + + + + +

    unset      Commandes Internes Tcl

    +
    +
    NOM

    +
    unset √ Efface des variables +

    +
    SYNTAXE

    +
    unset name ?name name ...? +

    +
    DESCRIPTION

    +
    Cette commande efface une ou plusieurs variables. Chaque name est un nom de variable, spИcifiИ d'une des maniХres acceptables par la commande set. Si un name se refХre Ю un ИlИment d'un tableau alors cet ИlИment est effacИ sans affecter le reste du tableau. Si un name consiste en un nom de tableau sans index entre parenthХses, alors le tableau entier est effacИe. La commande unset retourne une chaНne vide comme rИsultat. Un erreur se produit si une des variables n'existe pas, et toutes les variables aprХs l'inexistante ne sont pas effacИes
    +
    +
    + diff --git a/hlp/fr/tcl/update.htm b/hlp/fr/tcl/update.htm new file mode 100644 index 0000000..7744b95 --- /dev/null +++ b/hlp/fr/tcl/update.htm @@ -0,0 +1,21 @@ + + + + +

    update      Commandes Internes Tcl

    +
    +
    NOM

    +
    update - Traite les ИvХnements en attente et les callbacks inactifs +

    +
    SYNTAXE

    +
    update ?idletasks?& +

    +
    DESCRIPTION

    +
    Cette commande est utilisИe pour mettre l'application "up to date" en entrant dans la boucle d'ИvХnement rИpИtitivement jusqu'a ce que tout ИvХnement en attente (incluant les callbacks inactifs ) ait ИtИ traitИ.
    +
    Si le mot-clИ idletasks est spИcifiИ comme argument Ю la commande, alors aucun nouveaux ИvХnements ou erreurs ne sont traitИs seuls les callbacks inactifs sont appelИs. Ceci cause le traitement immИdiat des opИrations qui sont normalement diffИrИes, tel que les rafraichissement de l'Иcran et les calculs de fenЙtrage.
    +
    La commande update idletasks est utile dans les scripts oЫ les changements d'Иtat de l'application ont ИtИ effectuИs et que vous voulez que ces changements apparaissent immИdiatement, plutТt que d'attendre que le script soit complИtИ. La plupart des rafraichissement de l'Иcran sont effectuИe comme callbacks inactifs , donc update idletasks provoquera leur exИcution. NИanmoins, il y a des mises Ю jour qui se produisent seulement en rИponse aux ИvХnements, tels que ceux dИclenchИ par les changements de taille de fenЙtre; ces mises Ю jour ne se produiront pas dans update idletasks.
    +
    La commande update sans options est utile dans les scripts oЫ vous effectuez de longs calculs mais oЫ vous dИsirez que l'application rИponde aux ИvХnements tels que les interactions avec l'utilisateur. Si vous appellez occasionellement update alors l'entrИe utilisateur sera traitИe pendant l'appel suivant de update

    +
    DerniХre rИvision: 7.5
    +
    +
    + diff --git a/hlp/fr/tcl/uplevel.htm b/hlp/fr/tcl/uplevel.htm new file mode 100644 index 0000000..2d5178a --- /dev/null +++ b/hlp/fr/tcl/uplevel.htm @@ -0,0 +1,29 @@ + + + + +

    uplevel      Commandes Internes Tcl

    +
    +
    NOM

    +
    uplevel - Execute un script dans un cadre de pile diffИrent +

    +
    SYNTAXE

    +
    uplevel ?level? arg ?arg ...? +

    +
    DESCRIPTION

    +
    Tous les arguments arg sont concatИnИs comme si ils avait ИtИ transmis Ю concat; le rИsultat est alors ИvaluИ dans le contexte de variable indiquИ par level Uplevel retourne le rИsultat de cette Иvaluation .
    +
    Si level est un entier alors cela donne la distance (au-dessus de la pile d'appel de la fonction) Ю franchir avant l'exИcution de la commande Si level consiste en # suivi par un nombre alors le nombre donne un numИro absolu de niveau Si level est omis alors il est par dИfaut de 1 Level ne peut pas avoir la valeur par dИfaut si le premier argument command commence avec un chiffre ou un #.
    +
    Par exemple, supposez que la fonction a a ИtИ appelИe au premier plan, et qu'elle a appelИ b, et que b appelИ c. Supposez que c appelle la commande uplevel Si level est 1 ou #2  ou omis, alors la commande sera exИcutИe dans le contexte de variable de b Si level est 2 ou #1 alors la commande sera exИcutИe dans le contexte de variable de a. Si level est 3 ou #0 alors la commande sera exИcutИ au premier plan (seulement les variables globales seront visibles).
    +
    La commande uplevel cause la disparition de la fonction appelante de la pile d'appel pendant la que commande est exИcutИe. Dans l'exemple ci-dessus , supposez que c appelle la commande
    +
    uplevel 1 {set x 43; d}
    +
    d est une autre fonction Tcl La commande set modifiera la variable x dans le contexte de b, et d s'exИcutera au niveau 3, comme si elle etait appelИe de b. Si elle exИcute ensuite la commande
    +
    uplevel {set x 42}
    +
    alors la commande set modifiera la mЙme variable x dans le contexte de b: la fonction c n'apparait pas Йtre sur la pile d'appel quand d s'exИcute. La commande "info level" peut Йtre employИe pour obtenir le niveau de la fonction courante.
    +
    Uplevel rend possible l'implИmentation de nouvelles structures de contrТle comme fonctions Tcl (par exemple, uplevel pourrait Йtre utilisИe pour implИmenter la construction while comme fonction Tcl).
    +
    namespace eval est une autre faГon (outre l'appel de fonction) de modifier le contexte de nom Tcl. Elle ajoute un cadre d'appel Ю la pile pour reprИsenter le contexte namespace. Ceci signifie que chaque commande namespace eval compte comme un autre niveau d'appel pour les commandes uplevel et upvar. Par exemple, info level 1 renverra une liste dИcrivant une commande qui est soit l'appel de fonction le plus externe ou la commande namespace eval la plus externe. Egalement, uplevel #0 Иvalue un script au premier plan dans le namespace le plus externe (le namespace global ) +

    +
    VOIR EGALEMENT

    + +
    +
    + diff --git a/hlp/fr/tcl/upvar.htm b/hlp/fr/tcl/upvar.htm new file mode 100644 index 0000000..bfb9ffd --- /dev/null +++ b/hlp/fr/tcl/upvar.htm @@ -0,0 +1,44 @@ + + + + +

    upvar      Commandes Internes Tcl

    +
    +
    NOM

    +
    upvar - CrИe un lien vers une variable dans un cadre de pile diffИrent +

    +
    SYNTAXE

    +
    upvar ?level? otherVar myVar ?otherVar myVar ...? +

    +
    DESCRIPTION

    +
    Cette commande prИpare une ou plusieurs variables locales dans la fonction courante Ю se referer Ю des variables dans un appel de fonction externe ou Ю des variables globales. Level peut avoir quelconque des formes permises pour la commande uplevel, et peut Йtre omis si la premiХre lettre de la premiХre otherVar n'est pas # ou un chiffre (il est par dИfaut de 1). Pour chaque argument otherVar, upvar rend la variable de ce nom dans le cadre de fonction indiquИ par level (ou au niveau global, si niveau est #0) accessible dans la fonction courante par le nom donnИ dans l'argument correspondant myVar. Le nom de variable otherVar n'a pas besoin d'exister Ю l'instant de l'appel il sera crИИ la premiХre fois que myVar est rИfИrencИe, juste comme une variable ordinaire. Il ne doit pas exister une variable du nom de myVar Ю l'instant oЫ upvar est appelИe. MyVar est toujours traitИ comme le nom d'une variable, pas un ИlИment de tableau. MЙme si le nom ressemble Ю un ИlИment detableau, tel que a(b), une variable ordinaire est crИИe. OtherVar peut se referer Ю une variable scalaire , un tableau, ou un ИlИment de tableau. Upvar retourne une chaНne vide.
    +
    La commande upvar simplifie l'implИmentation d'appel-par-nom des fonctions et facilite aussi la crИation de structures de contrТle en tant que fonctions Tcl. Par exemple, considИrez les fonctions suivantes:
    +
    proc add2 name {
    +
          upvar $name x
    +
          set x [expr $x+2]
    +
    }
    +
    Add2 est appelИe avec un argument donnant le nom d'une variable, et elle ajoute deux Ю la valeur de cette variable. Bien que add2 aurait pu Йtre implИmentИe en utilisant uplevel au lieu de upvar, upvar simplifie l'accХs aux variables de add2 dans le cadre de la fonction appelante.
    +
    namespace eval est une autre faГon (en plus des appels de fonction)de changer le contexte de nom Tcl. Elle ajoute un cadre d'appel Ю la pile pour reprИsenter le contexte namespace. Ceci signifie que chaque commande namespace eval compte comme un niveau d'appel supplИmentaire pour les commandes uplevel et upvar. Par exemple, info level 1 renverra une liste dИcrivant une commande qui est soit l'appel de fonction le plus externe ou la commande namespace eval la plus externe. Egalement, uplevel #0 Иvalue un script au premier plan dans le namespace le plus externe (le namespace global ).
    +
    Si une variable upvar est effacИe (ex. x dans add2 plus haut), l'opИration unset affecte la variable liИe, pas la variable upvar. Il n'y a aucun moyen d'effacer une variable upvar exceptИ en sortant de la fonction dans lequel elle est dИfinie. NИanmoins, il est possible de recibler une variable upvar par l'exИcution d'une autre commande upvar. +

    +
    Traces et upvar

    +
    Upvar interagit avec les traces d'une maniХre directe mais qui peut Йtre inattendue. Si une trace de variable est dИfinie sur otherVar, cette trace sera dИclenchИe par les actions impliquant myVar. NИanmoins, Ю la fonction trace sera transmis le nom de myVar, plutТt que le nom de otherVar. Ainsi, la sortie du code suivant sera localVar plutТt que originalVar:
    +
    proc traceproc { name index op } {
    +
          puts $name
    +
    }
    +
    proc setByUpvar { name value } {
    +
          upvar $name localVar
    +
          set localVar $value
    +
    }
    +
    set originalVar 1
    +
    trace variable originalVar w traceproc
    +
    setByUpvar originalVar 2
    +
    }
    +
    Si otherVar se refХre Ю un ИlИment de tableau, alors les traces de variables fixИe pour le tableau entier ne seront pas appelИes quand myVar est accИdИe (mais les traces sur un ИlИment particulier pourront Йtre appelИes). En particulier, si le tableau est env, alors les changement faits Ю myVar ne seront pas transmis au sous-processus correctement +

    +
    VOIR EGALEMENT

    + +
    +
    + diff --git a/hlp/fr/tcl/variable.htm b/hlp/fr/tcl/variable.htm new file mode 100644 index 0000000..3e1d84c --- /dev/null +++ b/hlp/fr/tcl/variable.htm @@ -0,0 +1,24 @@ + + + + +

    variable      Commandes Internes Tcl

    +
    +
    NOM

    +
    variable - crИe et initialise une variable namespace +

    +
    SYNTAXE

    +
    variable ?name value...? name ?value? +

    +
    DESCRIPTION

    +
    Cette commande est normalement utilisИe Ю l'intИrieur d'une commande namespace eval pour crИer une ou plusieurs variables Ю l'intИrieur un namespace. Chaque variable name est initialisИe avec value. La value pour la derniХre variable est optionnelle.
    +
    Si une variable name n'existe pas, elle est crИИe. Dans ce cas, si value est spИcifiИe, elle est assignИe Ю la variable nouvellement crИИe. Si aucune value n'est spИcifiИe, la nouvelle variable est indИfinie. Si la variable existe dИjЮ, elle est fixИe Ю value si value est spИcifiИ ou laissИe inchangИe si aucune value n'est donnИe. Normalement, name est non qualifiИ (n'inclut pas les noms des eventuels namespaces contenant), et la variable est crИИe dans le namespace courant. Si name inclut des qualificateurs namespace quelconque, la variable est crИИe dans le namespace spИcifiИ. Si la variable n'est pas dИfinie, elle sera visible pour la commande namespace which, mais pas pour info exists.
    +
    Si la commande variable est exИcutИe dans une fonction Tcl, elle crИe des variables locales liИes aux variables namespace correspondantes. De cette faГon la commande variable ressemble Ю la commande global, bien que la commande global crИe des liens seulement vers les variables dans le namespace global . Si quelconque values sont indiquИes, elles sont utilisИes pour modifier les valeurs des variables namespace associИes. Si une variable namespace n'existe pas, elle est crИИe et optionellement initialisИe.
    +
    Un argument name ne peut rИfИrencer un ИlИment Ю l'intИrieur un tableau. Par contre, name devra rИfИrencer le tableau entier, et la value d'initialisation sera ignorИe. AprХs que la variable ait ИtИ declarИe, les ИlИments Ю l'intИrieur du tableau peuvent Йtre fixИs en utilisant les commandes ordinaires set ou array +

    +
    VOIR EGALEMENT

    +
    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/vwait.htm b/hlp/fr/tcl/vwait.htm new file mode 100644 index 0000000..326b59b --- /dev/null +++ b/hlp/fr/tcl/vwait.htm @@ -0,0 +1,20 @@ + + + + +

    vwait      Commandes Internes Tcl

    +
    +
    NOM

    +
    vwait - Traite les ИvХnements jusqu'a ce qu'une variable soit Иcrite +

    +
    SYNTAXE

    +
    vwait varName 
    +

    +
    DESCRIPTION

    +
    Cette commande entre dans la boucle d'ИvХnement Tcl pour traiter les ИvХnements, bloquant l'application si aucun ИvХnement n'est prХt. Elle continue le traitement des ИvХnements jusqu'a ce que quelque gestionnaire d'ИvХnement fixe la valeur de la variable varName. Une fois que varName Ю ИtИ fixИe, la commande vwait renverra aussitТt que le gestionnaire d'ИvХnement qui a modifiИ varName se termine. varName doit Йtre globalement visible (soit avec un appel de global pour varName, ou avec la spИcification du chemin namespace complet).
    +
    Dans quelques cas la commande vwait ne peut pas retourner immИdiatement aprХs que varName soit fixИe. Ceci peut arriver si le gestionnaire d'ИvХnement qui fixe varName ne se termine pas immИdiatement. Par exemple, si un gestionnaire d'ИvХnement fixe varName et ensuite appelle lui-mЙme vwait pour attendre une variable diffИrente, alors il peut ne pas retourner pendant longtemps. Durant ce temps le vwait de premier plan est bloquИ en attendant que le gestionnaire d'ИvХnement soit complИtИ, donc il ne peut pas retourner non plus

    +
    DerniХre rИvision: 8.0
    +
    +
    + diff --git a/hlp/fr/tcl/while.htm b/hlp/fr/tcl/while.htm new file mode 100644 index 0000000..4cebde1 --- /dev/null +++ b/hlp/fr/tcl/while.htm @@ -0,0 +1,23 @@ + + + + +

    while      Commandes Internes Tcl

    +
    +
    NOM

    +
    while - Execute un script rИpИtitivement tant qu'une condition est rencontrИe +

    +
    SYNTAXE

    +
    while test body +

    +
    DESCRIPTION

    +
    La commande while Иvalue test comme expression (de la mЙme faГon que expr Иvalue ses arguments). La valeur de l'expression doit une valeur boolИenne correcte; si c'est la valeur true alors body est exИcutИ par transmission Ю l'interprИteur Tcl. Une fois que body a ИtИ exИcutИ alors test est ИvaluИ de nouveau, et le processus recommence jusqu'a ce que Иventuellement test Иvalue Ю une valeur boolИenne false. Des commandes continue peuvent Йtre exИcutИes Ю l'interieur de body pour terminer l'itИration courante de la boucle, et des commandes break peuvent Йtre exИcutИes Ю l'interieur body pour provoquer la fin immИdiate de la commande while. La commande while retourne toujours une chaîne vide.
    +
    Note: test devra presque toujours Йtre entourИe d'accolades Sinon, les substitutions de variable seront faites avant que la commande while dИmarre l'exИcution, ce qui signifie que le changement de la variable fait par le corps de la boucle ne sera pas considerИ dans l'expression. Ceci donnera souvent une boucle infinie. Si test est entourИe d'accolades, les substitutions de variables sont retardИes jusqu'a ce que l'expression soit ИvaluИe (avant chaque itИration de boucle), donc les changements de la variables seront visible. Comme exemple, essayez le script suivant avec et sans accolades autour de $x<10:
    +
    set x 0
    +while {$x<10} {
    +      puts "x est $x"
    +      incr x
    +}
    +
    +
    + diff --git a/hlp/ru/CHANGELOG.html b/hlp/ru/CHANGELOG.html new file mode 100644 index 0000000..0fba6e5 --- /dev/null +++ b/hlp/ru/CHANGELOG.html @@ -0,0 +1,14 @@ + + + + + + + + +

    п≤п╥п╪п╣п╫п╣п╫п╦я▐ п©п╬ п╡п╣я─я│п╦я▐п╪

    +
    1.0.0 - п╦п╫п╦я├п╦п╦я─п╬п╡п╟п╫ я─п╣п╩п╦п╥ п©я─п╬пЁя─п╟п╪п╪я▀ +
    1.0.1 - п╢п╬п╠п╟п╡п╩п╣п╫ п╟п╡я┌п╬п╪п╟я┌п╦я┤п╣я│п╨п╦п╧ я┐я┤я▒я┌ п╦п╥п╪п╣п╫п╣п╫п╦п╧ п©п╟я─п╟п╪п╣я┌я─п╬п╡ п╡ п╨п╬п╪п╟п╫п╢я▀я┘ я└п╟п╧п╩п╟я┘ п╫п╬ п╬я┌я│я┐я┌я│я┌п╡я┐я▌я┴п╦я┘ п╡ я└п╟п╧п╩п╣ fields (я┌.п╣. п╡ я└п╟п╧п╩п╟я┘ п©я─п╣п╢я▀п╢я┐я┴п╣п╧ п╡п╣я─я│п╦п╦), п©я┐я┌я▒п╪ п©п╣я─п╣пЁп╦п╫п╣я─п╟я├п╦п╦ я└п╟п╧п╩п╟ fields. п²п╣п╬п╠я┘п╬п╢п╦п╪п╬ п╢п╩я▐ п╨п╬я─я─п╣п╨я┌п╫п╬п╧ я─п╟п╠п╬я┌я▀ я│ я└п╟п╧п╩п╟п╪п╦ п╫п╬п╡я▀я┘ п╡п╣я─я│п╦п╧ (п©п╬я│п╩п╣ п╬п╠п╫п╬п╡п╩п╣п╫п╦я▐ п╨п╬п╫я└п╦пЁя┐я─п╟я├п╦п╦ MSOFTa) + + + diff --git a/hlp/ru/bwidget/ArrowButton.html b/hlp/ru/bwidget/ArrowButton.html new file mode 100644 index 0000000..3969d3d --- /dev/null +++ b/hlp/ru/bwidget/ArrowButton.html @@ -0,0 +1,276 @@ + +ArrowButton + +
    NAME
    +
    ArrowButton + - Button widget with an arrow shape. +
    +
    +
    CREATION
    +
    ArrowButton pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -activebackground
      -activeforeground
      -background or -bg  -borderwidth or -bd
      -disabledforeground
      -foreground or -fg
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -relief
      -repeatdelay
      -repeatinterval
      -takefocus
      -troughcolor
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -armcommand
      -arrowbd
      -arrowrelief
      -clean
      -command
      -dir
      -disarmcommand
      -height
      -helptext
      -helptype
      -helpvar
      -ipadx
      -ipady
      -state
      -type
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName invoke +
    +
    +


    +DESCRIPTION
    +

    + +ArrowButton can be of two types following type option: +for button type, it is standard button with an arrow drawn on it; +for arrow type, it is an arrow like scrollbar's arrow. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -armcommand
    +
    + +Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is pressed +over the ArrowButton. When repeatdelay or repeatinterval option is positive +integer, this command is repeatedly called if mouse pointer is over the button and until +mouse button 1 is released. +
    +
    +
    -arrowbd
    +
    + +When ArrowButton type is arrow, specifies the border width of the +arrow. Must be 1 or 2. + +
    +
    +
    -arrowrelief
    +
    + +When ArrowButton type is arrow, specifies the relief of the arrow. +Must be raised or sunken. + +
    +
    +
    -clean
    +
    + +Specifies a level of quality, between 0 and 2, for the arrow. +If 0, the arrow is drawn with its maximum width and height. +If 1, the base of arrow is arranged to be odd to have same edges. +If 2, the base of arrow is arranged to be odd and the orthogonal to be (base+1)/2 to +have 'straight' diagonal for edges. +
    +
    +
    -command
    +
    + +Specifies a Tcl command to associate with the ArrowButton. This command +is typically invoked when mouse button 1 is released over the ArrowButton +window. +
    +
    +
    -dir
    +
    + +Specifies the direction of the arrow: top, bottom, left +or right. +
    +
    +
    -disarmcommand
    +
    + +Specifies a Tcl command to associate with the ArrowButton when mouse button 1 is released. +This command is called even if pointer is not over the ArrowButton, and always before +the command specified by command option. +It is typically used in conjuntion with armcommand, repeatdelay and +repeatinterval. +
    +
    +
    -height
    +
    + +Specifies a desired height for the ArrowButton. The value is in screen units. +
    +
    +
    -helptext
    +
    + +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
    +
    +
    -helptype
    +
    +Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
    +
    +
    -helpvar
    +
    +Variable to use when helptype option is variable. +See also DynamicHelp. +
    +
    +
    -ipadx
    +
    + +Specifies a minimun pad between the ArrowButton border and the right and left side +of the arrow. The value is in screen units. +
    +
    +
    -ipady
    +
    + +Specifies a minimun pad between the ArrowButton border and the top and bottom side +of the arrow. The value is in screen units. +
    +
    +
    -state
    +
    + +Specifies one of three states for the ArrowButton: normal, active, +or disabled. +
    If ArrowButton type is button:
    +
    In normal state the ArrowButton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the ArrowButton. In active state +the ArrowButton is displayed using the activeforeground and +activebackground options. In disabled state the disabledforeground and +background options determine how the ArrowButton is displayed. +
    +
    If ArrowButton type is arrow:
    +
    Only colors of arrow change. The background of ArrowButton is always +displayed using troughcolor option. +In normal state the ArrowButton is displayed using the background option. The active +state is typically used when the pointer is over the ArrowButton. In active state +the ArrowButton is displayed using the activebackground option. In disabled state +the ArrowButton is displayed with a dark stipple. +
    +
    +Disabled state means that the ArrowButton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +
    +
    +
    -type
    +
    + +Determines the type of the ArrowButton: button for standard button look, or +arrow scrollbar's arrow look. +
    +
    +
    -width
    +
    + +Specifies a desired width for the ArrowButton. The value is in screen units. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName invoke +
    + +If ArrowButton state is not disabled, this invoke the commands of the button. +ArrowButton is redisplayed with active color and sunken relief, and +armcommand is called. Then ArrowButton is redisplayed with +normal color and its defined relief, and disarmcommand then command +are called. +

    invoke is called when ArrowButton has input focus and user press the space bar. +

    + diff --git a/hlp/ru/bwidget/BWidget.html b/hlp/ru/bwidget/BWidget.html new file mode 100644 index 0000000..337906b --- /dev/null +++ b/hlp/ru/bwidget/BWidget.html @@ -0,0 +1,116 @@ + +BWidget + +
    NAME
    +
    BWidget + - Description text +
    +
    +
    COMMAND
    +
    BWidget::XLFDfont + cmd + ?arg...? +
    +
    BWidget::assert + exp + ?msg? +
    +
    BWidget::clonename + menu +
    +
    BWidget::focus + option + path +
    +
    BWidget::get3dcolor + path + bgcolor +
    +
    BWidget::getname + name +
    +
    BWidget::grab + option + path +
    +
    BWidget::lreorder + list + neworder +
    +
    BWidget::parsetext + text +
    +
    BWidget::place + path + w + h + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    +Description text +

    +

    +COMMAND
    +
    BWidget::XLFDfont + cmd + ?arg...? +
    +Description text +
    +
    BWidget::assert + exp + ?msg? +
    +Description text +
    +
    BWidget::clonename + menu +
    +Description text +
    +
    BWidget::focus + option + path +
    +Description text +
    +
    BWidget::get3dcolor + path + bgcolor +
    +Description text +
    +
    BWidget::getname + name +
    +Description text +
    +
    BWidget::grab + option + path +
    +Description text +
    +
    BWidget::lreorder + list + neworder +
    +Description text +
    +
    BWidget::parsetext + text +
    +Description text +
    +
    BWidget::place + path + w + h + ?arg...? +
    +Description text +
    + diff --git a/hlp/ru/bwidget/Button.html b/hlp/ru/bwidget/Button.html new file mode 100644 index 0000000..8a2f49b --- /dev/null +++ b/hlp/ru/bwidget/Button.html @@ -0,0 +1,273 @@ + +Button + +
    NAME
    +
    Button + - Button widget with enhanced options +
    +
    +
    CREATION
    +
    Button pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -activebackground
      -activeforeground
      -anchor
      -background or -bg
      -bitmap
      -borderwidth or -bd
      -cursor
      -disabledforeground
      -font
      -foreground or -fg
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -image
      -justify
      -padx
      -pady
      -repeatdelay
      -repeatinterval
      -takefocus
      -text
      -textvariable
      -wraplength
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -armcommand
      -command
      -default
      -disarmcommand
      -height
      -helptext
      -helptype
      -helpvar
      -name
      -relief
      -state
      -underline
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName invoke +
    +
    +


    +DESCRIPTION
    +

    + +Button widget extends the Tk button with new options. +DynamicHelp options, +a new relief style, callback for arm/disarm, and +repeatdelay/repeatinterval options has been added. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -armcommand
    +
    + +Specifies a Tcl command to associate with the Button when mouse button 1 is pressed over the +Button. When repeatdelay or repeatinterval option is positive integer, +this command is repeatedly called if mouse pointer is over the Button and until mouse +button 1 is released. +
    +
    +
    -command
    +
    + +Specifies a Tcl command to associate with the Button. This command +is typically invoked when mouse button 1 is released over the Button +window. +
    +
    +
    -default
    +
    + +Specifies one of three states for the default ring: normal, active, +or disabled. In active state, the button is drawn with the platform specific +appearance for a default button. In normal state, the button is drawn with the platform +specific appearance for a non-default button, leaving enough space to draw the default +button appearance. The normal and active states will result in buttons of the same size. +In disabled state, the button is drawn with the non-default button appearance without +leaving space for the default appearance. The disabled state may result +in a smaller button than the active state. +
    +
    +
    -disarmcommand
    +
    + +Specifies a Tcl command to associate with the Button when mouse button 1 is released. +This command is called even if pointer is not over the Button, and always before +the command specified by command option. +It is typically used in conjuntion with armcommand, repeatdelay and +repeatinterval. +
    +
    +
    -height
    +
    + +Specifies a desired height for the Button. +If an image or bitmap is being displayed in the Button then the value is in +screen units; +for text it is in lines of text. +If this option isn't specified, the Button's desired height is computed +from the size of the image or bitmap or text being displayed in it. +
    +
    +
    -helptext
    +
    + +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
    +
    +
    -helptype
    +
    +Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
    +
    +
    -helpvar
    +
    +Variable to use when helptype option is variable. +See also DynamicHelp. +
    +
    +
    -name
    +
    + +Specifies a standard name for the button. If the option *nameName is +found in the resources database, then text and underline options +are extracted from its value. + +
    +
    +
    -relief
    +
    + +Specifies the 3-D effect desired for the widget. Acceptable values are standard values for +button relief (raised, sunken, flat, ridge, solid, and groove) and link, which specifies that button relief is flat when pointer +is outside the button and raised when pointer is inside. +
    +
    +
    -state
    +
    + +Specifies one of three states for the Button: normal, active, +or disabled. In normal state the Button is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the Button. In active state +the Button is displayed using the activeforeground and +activebackground options. Disabled state means that the Button +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledforeground and +background options determine how the Button is displayed. +
    +
    +
    -underline
    +
    + +Specifies the integer index of a character to underline in the label of the button. +0 corresponds to the first character of the text displayed, 1 to the next character, +and so on. +
    The binding <Alt-char> is automatically set on the toplevel +of the Button to call Button::setfocus. + +
    +
    +
    -width
    +
    + +If an image or bitmap is being displayed in the Button then the value is in +screen units; +for text it is in characters. +If this option isn't specified, the Button's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName invoke +
    + +If Button state is not disabled, this invoke the commands of the Button. +Button is redisplayed with active color and sunken relief, and +armcommand is called. Then Button is redisplayed with +normal color and its defined relief, and disarmcommand then command +are called. +

    invoke is called when Button has input focus and user press the space bar. +

    + diff --git a/hlp/ru/bwidget/ButtonBox.html b/hlp/ru/bwidget/ButtonBox.html new file mode 100644 index 0000000..09200e6 --- /dev/null +++ b/hlp/ru/bwidget/ButtonBox.html @@ -0,0 +1,220 @@ + +ButtonBox + +
    NAME
    +
    ButtonBox + - Set of buttons with horizontal or vertical layout +
    +
    +
    CREATION
    +
    ButtonBox pathName ?option value...?
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + +
      -background or -bg  -default
      -homogeneous
      -orient
      -padx
      -pady
      -spacing
    +
    +
    +
    WIDGET COMMAND
    +
    pathName add + ?option value...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName index + index +
    +
    pathName invoke + index +
    +
    pathName itemcget + index + option +
    +
    pathName itemconfigure + index + ?option? ?value option value ...? +
    +
    pathName setfocus + index +
    +
    +


    +DESCRIPTION
    +

    + +ButtonBox layouts Button horizontally or vertically. +Some commands take an index as argument indicating on which +Button it work. This index may be specified in any of the following forms: +

    +

    +
    +number +
    +Specifies the Button numerically, where 0 corresponds +to the first added Button, 1 to the next, and so on. +
    +end or last +
    +Indicates the last item added. +
    default +
    +Indicates the default Button. +
    + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -background
    +
    + +Specifies a default background color for all added buttons and for the frame. + +
    +
    +
    -default
    +
    + +Specifies the default button of the button box. The value is an integer +referencing the n-th added button, starting from 0. +If this value is -1 (the default), all button wil be drawn with their -default +option set to disabled, and this value can not be changed.
    If this value is +not -1, the associated button is drawn with -default option set to active and +the others are drawn with -default option set to normal. The value can be changed +by configure. + +
    +
    +
    -homogeneous (read-only)
    +
    + +Specifies wether or not buttons must have the same width for horizontal layout. + +
    +
    +
    -orient (read-only)
    +
    + +Specifies the orientation of the button box. If this option is horizontal +(the default), buttons are added from top to bottom. +If this option is vertical, buttons are added from left to right. + +
    +
    +
    -padx
    +
    + +Specifies a default value for the -padx option of all added buttons. + +
    +
    +
    -pady
    +
    + +Specifies a default value for the -pady option of all added buttons. + +
    +
    +
    -spacing
    +
    + +Specifies the default spacing between buttons. This value can be changed before each +call to add. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName add + ?option value...? +
    + +Add a button to the button box. +

    +See Button for description of options. +

    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName index + index +
    + +Return the numerical index corresponding to the item. + +
    +
    pathName invoke + index +
    + +Invoke the Button given by index. + +
    +
    pathName itemcget + index + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + index + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName setfocus + index +
    + +Set the focus to the Button given by index. + +
    + diff --git a/hlp/ru/bwidget/ComboBox.html b/hlp/ru/bwidget/ComboBox.html new file mode 100644 index 0000000..766c849 --- /dev/null +++ b/hlp/ru/bwidget/ComboBox.html @@ -0,0 +1,306 @@ + +ComboBox + +
    NAME
    +
    ComboBox + - ComboBox widget +
    +
    +
    CREATION
    +
    ComboBox pathName ?option value...?
    +
    +
    +
    OPTIONS from ArrowButton
    +
    + + + + + + + + +
      -background or -bg  -disabledforeground
      -foreground or -fg  -state
    +
    +
    +
    OPTIONS from Entry
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -command  -disabledforeground
      -dragenabled  -dragendcmd
      -dragevent  -draginitcmd
      -dragtype  -dropcmd
      -dropenabled  -dropovercmd
      -droptypes  -editable
      -entrybg (see -background)  -entryfg (see -foreground)
      -exportselection  -font
      -helptext  -helptype
      -helpvar  -highlightbackground
      -highlightcolor  -highlightthickness
      -insertbackground  -insertborderwidth
      -insertofftime  -insertontime
      -insertwidth  -justify
      -selectbackground  -selectborderwidth
      -selectforeground  -show
      -state  -takefocus
      -text  -textvariable
      -width  -xscrollcommand
    +
    +
    +
    OPTIONS from LabelFrame
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -disabledforeground  -foreground or -fg
      -helptext  -helptype
      -helpvar  -label (see -text)
      -labelanchor (see -anchor)  -labelfont (see -font)
      -labelheight (see -height)  -labeljustify (see -justify)
      -labelwidth (see -width)  -name
      -padx  -pady
      -relief  -side
      -state  -underline
      -wraplength
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + +
      -height
      -modifycmd
      -postcommand
      -values
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getvalue +
    +
    pathName setvalue + index +
    +
    +


    +DESCRIPTION
    +

    + +ComboBox widget enables the user to select a value among a list given by the values option. +The list of possible values can be popped by pressing the ArrowButton or by clicking in the entry +when editable value of the ComboBox is false.
    +If editable value of the ComboBox is true and the entry has the focus, the user can +press the top and bottom arrow keys to modify its value. If the current value exactly match a value in the list, +then the previous (for top arrow key) or then next (for bottom arrow key) value in the list is displayed. +If the current value match the beginning of a value in the list, then this value is displayed. +If the current value doesnt match anything, then the first value is displayed. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -height
    +
    + +Specifies the desired height for the window, in lines. If zero or less, then the desired +height for the window is made just large enough to hold all the elements in the listbox. +
    +
    +
    -modifycmd
    +
    + +Specifies a Tcl command called when the user modify the value of the ComboBox by selecting it in the listbox or pressing arrow key. +
    +
    +
    -postcommand
    +
    + +Specifies a Tcl command called before the listbox of the ComboBox is mapped. +
    +
    +
    -values
    +
    + +Specifies the values to display in the listbox of the ComboBox. +
    +
    +

    +WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    + +Set bindings on the entry widget. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getvalue +
    + +Returns the index of the current text of the ComboBox in the list of values, +or -1 if it doesn't match any value. + +
    +
    pathName setvalue + index +
    + +Set the text of the ComboBox to the value indicated by index in the list of values. +index may be specified in any of the following forms: +

    +

    +
    +last +
    +Specifies the last element of the list of values. +
    first +
    +Specifies the first element of the list of values. +
    +next +
    +Specifies the element following the current (ie returned by getvalue) in the list +of values. +
    previous +
    +Specifies the element preceding the current (ie returned by getvalue) in the list +of values. +
    +@number +
    +Specifies the integer index in the list of values. +
    + +
    +

    BINDINGS

    + +When Entry of the ComboBox has the input focus, it has the following bindings, in addition +to the default Entry bindings: +
      +
    • Page up set the value of the ComboBox to the first value. +
    • Page down set the value of the ComboBox to the last value. +
    • Arrow up set the value of the ComboBox to the previous value. +
    • Arrow down set the value of the ComboBox to the next value. +
    +If the listbox is not mapped and ComboBox is not editable or disabled, +mouse button 1 on the Entry cause the listbox to popup, as if the user press the ArrowButton. + + diff --git a/hlp/ru/bwidget/Dialog.html b/hlp/ru/bwidget/Dialog.html new file mode 100644 index 0000000..19dfcbe --- /dev/null +++ b/hlp/ru/bwidget/Dialog.html @@ -0,0 +1,293 @@ + +Dialog + +
    NAME
    +
    Dialog + - Dialog abstraction with custom buttons +
    +
    +
    CREATION
    +
    Dialog pathName ?option value...?
    +
    +
    +
    OPTIONS from ButtonBox
    +
    + + + + + + + + + + +
      -background or -bg  -homogeneous
      -padx  -pady
      -spacing
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + +
      -anchor
      -bitmap
      -cancel
      -default
      -image
      -modal
      -parent
      -separator
      -side
      -title
    +
    +
    +
    WIDGET COMMAND
    +
    pathName add + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName draw + ?focus? +
    +
    pathName enddialog + result +
    +
    pathName getframe +
    +
    pathName invoke + index +
    +
    pathName itemcget + index + option +
    +
    pathName itemconfigure + index + ?option? ?value option value ...? +
    +
    pathName setfocus + index +
    +
    pathName withdraw +
    +
    +


    +DESCRIPTION
    +

    + +Dialog widget enables the user to create a dialog box. +Some commands take an index as argument indicating on which +Button it work. This index is the same specified for equivalent ButtonBox command: +

    +

    +
    +number +
    +Specifies the Button numerically, where 0 corresponds +to the first added Button, 1 to the next, and so on. +
    +end or last +
    +Indicates the last item added. +
    default +
    +Indicates the default Button. +
    + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -anchor (read-only)
    +
    + +Specifies the anchor point of the ButtonBox. +Must be one of w, e, n, s or c. +If side option is set to top or bottom, +anchor values n, s and c have the same effect. +If side option is set to left or right, +anchor values w, e and c have the same effect. + +
    +
    +
    -bitmap (read-only)
    +
    + +Specifies a bitmap to display at the left of the user frame. +image option override bitmap. +
    +
    +
    -cancel
    +
    + +Specifies the number of the cancel button of the Dialog. When user press Esc in the Dialog, +this button is invoked. +
    +
    +
    -default
    +
    + +Specifies the number of the default button of the Dialog. +When user press Return in the Dialog, this button is invoked. +
    +
    +
    -image (read-only)
    +
    + +Specifies an image to display at the left of the user frame. +image option override bitmap. +
    +
    +
    -modal
    +
    + +This option must be none, local or global. The value of this option +specifies the grab mode of the dialog and how works Dialog::draw. + +
    +
    +
    -parent
    +
    + +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
    +
    +
    -separator (read-only)
    +
    + +Specifies wether or not to draw a separator between the user frame and the ButtonBox. + +
    +
    +
    -side (read-only)
    +
    + +Specifies where to draw the ButtonBox relative to the user frame. Must be one of +top, left, bottom or right. +
    +
    +
    -title
    +
    + +Title of the Dialog toplevel. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName add + ?arg...? +
    + +Add a button to the button box of the dialog box. Default -command option is +Dialog::enddialog $path index where index is number of button added. +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName draw + ?focus? +
    + +This command draw the Dialog, and set grab to it following modal option. +If modal option is set to none, the command returns immediatly +an empty string. In all other case, the command returns when Dialog::enddialog +is called or when Dialog is destroyed. +The return value is the result argument of Dialog::enddialog or -1 if it is destroyed. +

    +By default, the focus is set to the default button referenced by default option, +or to the toplevel of Dialog if no default button has been set. +If focus is present, it must be a pathname, or an index to a button. +Initial focus is set on this pathname or corresponding button. + +

    +
    pathName enddialog + result +
    + +This command is typically called within a command of a button to make Dialog::draw +return. + +
    +
    pathName getframe +
    + +Returns the pathname of the user window. +
    +
    pathName invoke + index +
    + +Invoke the Button given by index. + +
    +
    pathName itemcget + index + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + index + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName setfocus + index +
    + +Set the focus to the Button given by index. + +
    +
    pathName withdraw +
    + +Call this command to hide the dialog box. + +
    + diff --git a/hlp/ru/bwidget/DragSite.html b/hlp/ru/bwidget/DragSite.html new file mode 100644 index 0000000..bc6f9b4 --- /dev/null +++ b/hlp/ru/bwidget/DragSite.html @@ -0,0 +1,139 @@ + +DragSite + +
    NAME
    +
    DragSite + - Commands set for Drag facilities +
    +
    +
    COMMAND
    +
    DragSite::include + class + type + event +
    +
    DragSite::register + path + ?option value...? +
    +
    DragSite::setdrag + path + subpath + initcmd + endcmd + ?force? +
    +
    +


    +DESCRIPTION
    +

    + +Commands of this namespace enable user to define a BWidget or a Tk widget as a drag site. + + + +

    +

    +COMMAND
    +
    DragSite::include + class + type + event +
    + +This command provides a simple way to include options relatives to a drag site into +BWidget resources definition. +It includes the options needed for register: -dragevent, initialized to +event, -draginitcmd and -dragendcmd, initialized to empty string, +and two new options: + +
    -dragenabledSpecifies wether or not drag is active (initialized to 0) +
    -dragtypeDefault or alternate dragged data type (initialized to type) +
    + +
    +
    DragSite::register + path + ?option value...? +
    + +This command is used to declare path as a drag site. Options are: + +

    +

    -dragendcmd
    +
    + +Command called when drag terminates (ie when user release drag icon). +This command is called with the following arguments: +
      +
    • the pathname of the drag source (the widget itself), +
    • the pathname of the drop target, +
    • the operation, +
    • the type of the dragged data, +
    • the dragged data, +
    • result of the drop (result of the call to -dropcmd of the target), +
    +If the drop does not occurs, the target and the operation are empty string and the result +is 0. + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +Command called when drag initiates. When the event of option dragevent occurs on +path, this command is called with the following arguments: +
      +
    • pathname of the drag source (path), +
    • root x-coordinate of pointer, +
    • root y-coordinate of pointer, +
    • a toplevel created to represent dragged data. When returning, if it +has no children, a bitmap is automatically displayed. +
    +The command must return a list containing three elements: +
      +
    • the type of the data, +
    • the list of acceptable basic operations (copy, move and link) +
    • and the data. +
    +Note that even if copy does not appear in the list of basic operation, +it is considered as an acceptable operation, since copy semantic does not modify +the drag source. + +
    +
    +
    +
    DragSite::setdrag + path + subpath + initcmd + endcmd + ?force? +
    + +This command provides a simple way to call register during a BWidget creation or +configuration. +
      +
    • path is the pathname of the BWidget, +
    • subpath is the pathname of the tk widget where drag event occurs, +
    • initcmd BWidget command for drag-init event, +
    • endcmd BWidget command for drag-end event, +
    • force specifies wether or not to call register whenever no option value has +changed (0 by default - for BWidget configuration, use 1 for BWidget creation). +
    +setdrag verifies the modification flag of options dragenabled and +dragevent and calls register if needed according to the options values and +initcmd and endcmd arguments. draginitcmd and dragendcmd are not +taken from options of widget because they are considered as user command, called by +BWidget implementation of drag-init and drag-end events. +
    + + diff --git a/hlp/ru/bwidget/DropSite.html b/hlp/ru/bwidget/DropSite.html new file mode 100644 index 0000000..264f4c9 --- /dev/null +++ b/hlp/ru/bwidget/DropSite.html @@ -0,0 +1,258 @@ + +DropSite + +
    NAME
    +
    DropSite + - Commands set for Drop facilities +
    +
    +
    COMMAND
    +
    DropSite::include + class + types +
    +
    DropSite::register + path + ?option value...? +
    +
    DropSite::setcursor + cursor +
    +
    DropSite::setdrop + path + subpath + dropover + drop + ?force? +
    +
    DropSite::setoperation + op +
    +
    +


    +DESCRIPTION
    +

    + +Commands of this namespace enable user to define a BWidget or a Tk widget as a drop site. +A drop site is composed of the type of object that can be dropped and associated operation, +a command called when drop occurs, and a command when an object is dragged over the widget. +A drop site must have at least one type of acceptable object and a drop command. + +

    +

    +COMMAND
    +
    DropSite::include + class + types +
    + +This command provides a simple way to include options relatives to a drop site into +BWidget resources definition. +It includes the options needed for register, -dropovercmd and -dropcmd, +initialized to empty string, and -droptypes, initialized to types, +and one new option: + +
    -dropenabledSpecifies wether or not drop is active (initialized to 0) +
    + +
    +
    DropSite::register + path + ?option value...? +
    + +This command is used to declare path as a drop site. Options are: + +

    +

    -dropcmd
    +
    + +This command is called when user release the drag icon over a valid drop target widget. +It takes the same arguments as -dragovercmd command. Its return values is passed +as a result to the -dragendcmd command of the drag source widget. + +
    +
    +
    -dropovercmd
    +
    + +This command can be used to provide a dynamic drag while drag-over events. +While a drag occurs, events <Enter>, <Motion> and <Leave> are catched. +Arguments passed to the command are: +
      +
    • pathname of the drop target (the widget itself), +
    • pathname of the drag source, +
    • event over the drop target: enter, motion or leave, +
    • root x-coordinate of the pointer, +
    • root y-coordinate of the pointer, +
    • operation, +
    • type of the dragged data, +
    • dragged data. +
    +Command must the new status of the drag: +
      +
    • 0 if widget refuse this drag. Command will not be recalled on motion/leave event. +
    • 1 if widget accept this drag. Command will not be recalled on motion/leave event. +
    • 2 if widget refuse this drag. Command will be recalled on each motion event to reevaluate. +
    • 3 if widget accept this drag. Command will be recalled on each motion event to reevaluate. + +
    +Here is a list of events and associated actions on a DropSite widget. This example +assumes that dragged data type is valid for the drop target. +status is the status of the drag on a DropSite. Its value is: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Event

    +

    Old status

    +

    Action

    +

    New status

    +

    <Enter>

    +

    -

    +

    if DropSite has dropovercmd, call it with enter

    +

    result of dropovercmd

    +

    else

    +

    1

    +

    <Motion>

    +

    0 or 1

      +

    unchanged

    +

    2 or 3

    +

    call dropovercmd with motion

    +

    result of dropovercmd

    +

    <Leave>

    +

     

    +

    0 or 1

      +

    -

    +

    2 or 3

    +

    call dropovercmd with leave

    +

    -

    +

    <Drop>

    +

    0

    +

    call dragendcmd of drag source

    +

    -

    +

    1

    +

    call dropcmd and call dragendcmd of drag source

    +

    2

    +

    call dropovercmd with leave and call dragendcmd of drag source

    +

    3

    +

    call dropcmd and call dragendcmd of drag source

    +
    + +
    +
    +
    -droptypes
    +
    + +Specifies a list {type oplist ?type oplist? ...} of acceptable +types and associated operations for the drop target. +For each type, oplist is a list +{descops mod ?descops mod? ...} describing operations and +modifier keys for these operations. +descops describe an operation. It can be a predefined operations (copy, +move or link) or a new user defined operation, of the form {subop +baseop ?bitmap?}. +subop is the name given to the sub operation, baseop is the name of the +base operation (copy, move or link) and bitmap is a bitmap +to display for the operation. +
    If bitmap is empty, the default bitmap of the base operation is used for the +sub operation. +
    subop can be a base operation, in order to change the bitmap of a base operation. +In this case, baseop must be empty or equal to subop. +
    mod is the modifer key for the operation. It can be: +
      +
    • none to specify that no modifier key is pressed. This modifier can only be used +with a sub operation named default (and vice versa), which has the behaviour of not +display any bitmap operation. For all type, if the modifier none is not given, it is +automatically associated to the default sub operation of a copy base operation. +
    • program to specifies a sub operation accessible only by DropSite::setoperation. +
    • A list combining shift, control and alt, which means their +corresponding key. +
    + +
    +
    +
    +
    DropSite::setcursor + cursor +
    + +This command can be used within the script dragovercmd. It is usefull to provide +visual effect about the state of the drag. +
    +
    DropSite::setdrop + path + subpath + dropover + drop + ?force? +
    + +This command provides a simple way to call register during a BWidget creation or +configuration. +
      +
    • path is the pathname of the BWidget, +
    • subpath is the pathname of the tk widget where drag event occurs, +
    • dropover is a command for drag-over event, +
    • drop is a command for drop event, +
    • force specifies wether or not to call register whenever no option value +has changed (0 by default - for BWidget configuration, use 1 for BWidget creation). +
    +setdrop verifies the modification flag of options dropenabled and +droptypes and calls register if needed according to the options values and +dropover and drop arguments. dropovercmd and dropcmd are not +taken from options of widget because they are considered as user command, called by +BWidget implementation of drag-over and drop events. + +
    +
    DropSite::setoperation + op +
    +Description text +
    + diff --git a/hlp/ru/bwidget/DynamicHelp.html b/hlp/ru/bwidget/DynamicHelp.html new file mode 100644 index 0000000..a0a338a --- /dev/null +++ b/hlp/ru/bwidget/DynamicHelp.html @@ -0,0 +1,126 @@ + +DynamicHelp + +
    NAME
    +
    DynamicHelp + - Provide help to Tk widget or BWidget +
    +
    +
    COMMAND
    +
    DynamicHelp::configure + ?option? ?value option value ...? +
    +
    DynamicHelp::include + class + type +
    +
    DynamicHelp::register + path + type + ?arg...? +
    +
    DynamicHelp::sethelp + path + subpath + ?force? +
    +
    +


    +DESCRIPTION
    +

    +Description text +

    +

    +COMMAND
    +
    DynamicHelp::configure + ?option? ?value option value ...? +
    +This command configure the ballon help. +

    +

    -borderwidth
    +
    +Width of the black border around the balloon. +
    +
    +
    -delay
    +
    +Define the delay in millisecond of mouse inactivity before displaying +the balloon. +
    +
    +
    Other standard options are: +
    + + + + + + + + +
      -background or -bg  -font
      -foreground or -fg  -justify
    +
    +
    DynamicHelp::include + class + type +
    +Description text +
    +
    DynamicHelp::register + path + type + ?arg...? +
    +Register a help text to the widget path. +type determines the type of the help or the type of the widget. +Depending on type, other options must be provided. +
    + + + + + + +
    type options
    balloon text
    variable varName text
    menu varName
    menuentry index text
    +
    If one of the option is missing or is empty, help is removed for this widget. +
    For type other than balloon, varName is typically a variable +linked to a label. +
    For menu, balloon type help is not available. To declare a help for menu, +you first declare the menu, and then entries of this menu. +
    For example: +

    +
    + +
    +     # create menu
    +menu .m -type menubar
    +# associate menubar to toplevel BEFORE DynamicHelp::register
    +# to make it works with menu clone name
    +. configure -menu .m
    +.m add cascade -label "File" -menu .m.file
    +menu .m.file
    +.m.file add command -label "Open..."
    +.m.file add command -label "Quit"
    +# create label for help, using variable varinfo
    +label .l -textvariable varinfo
    +# associate all entries of menu .m.file to variable varinfo
    +DynamicHelp::register .m.file menu varinfo
    +# then declare entries of .m.file
    +DynamicHelp::register .m.file menuentry 0 "Detach menu"
    +DynamicHelp::register .m.file menuentry 1 "Open a file"
    +DynamicHelp::register .m.file menuentry 2 "Exit demo"
    +
    +
    +
    Notice that if popup menu is owned by a menubar, you must associate first the menubar +to its toplevel. In this case, when you create a menu popup, its clone window is also +created, and DynamicHelp::register detects the exitence of the clone window and maps +events to it. +
    +
    DynamicHelp::sethelp + path + subpath + ?force? +
    +Description text +
    + diff --git a/hlp/ru/bwidget/Entry.html b/hlp/ru/bwidget/Entry.html new file mode 100644 index 0000000..585107d --- /dev/null +++ b/hlp/ru/bwidget/Entry.html @@ -0,0 +1,340 @@ + +Entry + +
    NAME
    +
    Entry + - Entry widget with state option, dynamic help and drag and drop facilities +
    +
    +
    CREATION
    +
    Entry pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -disabledforeground
      -exportselection
      -font
      -foreground or -fg
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -insertbackground
      -insertborderwidth
      -insertofftime
      -insertontime
      -insertwidth
      -justify
      -relief
      -selectbackground
      -selectborderwidth
      -selectforeground
      -takefocus
      -text
      -textvariable
      -xscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -command
      -dragenabled
      -dragendcmd
      -dragevent
      -draginitcmd
      -dragtype
      -dropcmd
      -dropenabled
      -dropovercmd
      -droptypes
      -editable
      -helptext
      -helptype
      -helpvar
      -show
      -state
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName invoke +
    +
    +


    +DESCRIPTION
    +

    + +The Entry widget extends the default Tk entry. Options have been added to provide +visual effect depending on the state of the Entry, +DynamicHelp options, +and Drag and +Drop. +Entry behaves much like a Label, with text option to set its contents. +
    Tk entry command can also be used on Entry widget. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -command
    +
    + +Specifies a command when user press <Return> in the Entry. +
    +
    +
    -dragenabled
    +
    +A boolean specifying if drag is enabled. +
    +
    +
    -dragendcmd
    +
    + +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
    If dragendcmd is empty, the internal dragend command updates the entry +following the operation (move or copy) and the dragged data +(whole or selected part of the entry). + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +Specifies a command to be called when dragevent occurs on widget. +draginitcmd must be a command conforming to the description of the +option draginitcmd of DragSite::register. + +
    if draginitcmd is empty, the command refuse the drag if entry is empty or if +portion of text is selected and event doesn't occur above the selection. In all other cases, +the command returns: +
      +
    • as the data type, the value of option dragtype or TEXT if empty, +
    • as the operations, {copy move} if state is normal and editable +is true, or {copy} only in other cases, +
    • as the data, the whole content or the selected portion of the entry. +
    + +
    +
    +
    -dragtype
    +
    + +Specifies an alternate type of dragged object. + +
    +
    +
    -dropcmd
    +
    + +Entry has a command wrapper for drop events. This command stops auto scrolling +and extract current position. +
    If dropcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the Entry, +
    • the pathname of the drag source, +
    • the numeric index in the entry designated by the cursor, +
    • the current operation, +
    • the data type, +
    • the data. +
    +and must return a value conforming to dropcmd option described in +DropSite::register. +If dropcmd is empty, the wrapper updates the entry following the type of data: +
    + + + + + + +
    COLOR or FGCOLORreconfigure the foreground of the Entry
    BGCOLORreconfigure the background of the Entry
    TEXT,
    or any other tag
    reconfigure the Entry to display the associated string.
    +and returns 1. + +
    +
    +
    -dropenabled
    +
    +A boolean specifying if drop is enabled. +
    +
    +
    -dropovercmd
    +
    + +Entry has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +
    If dropovercmd is empty, the wrapper accepts the drop if editable option is +true and state option is normal. +
    If dropovercmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the Entry, +
    • the pathname of the drag source, +
    • the event, +
    • the numeric index in the entry designated by the cursor, +
    • the current operation, +
    • the data type, +
    • the data. +
    +and must return a value conforming to dropovercmd option described in +DropSite::register. + +
    +
    +
    -droptypes
    +
    + +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +Default accepts FGCOLOR, COLOR, BGCOLOR and TEXT, +all with copy and move operations. + +
    +
    +
    -editable
    +
    + +Specifies whether the Entry is editable by the user. Equivalent to the state option +of the Tk entry widget. +
    +
    +
    -helptext
    +
    + +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
    +
    +
    -helptype
    +
    +Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
    +
    +
    -helpvar
    +
    +Variable to use when helptype option is variable. +See also DynamicHelp. +
    +
    +
    -show
    +
    + +If this option is specified, then the true contents of the entry are not displayed in the +window. Instead, each character in the entry's value will be displayed as the first character +in the value of this option, such as ``*''. This is useful, for example, if the entry is to +be used to enter a password. If characters in the entry are selected and copied elsewhere, the +information copied will be what is displayed, not the true contents of the entry. +
    +
    +
    -state
    +
    + +Specifies one of two states for the Entry: normal or disabled. +In normal state the text of the Entry is displayed using the foreground option. +In disabled state the text of the Entry is displayed using the disabledforeground +option. If the entry is disabled then the value may not be changed by user input +and no insertion cursor will be displayed, even if the input focus is in the widget. +Disabled state is the same as not editable with visual effect. +
    +
    +
    -width
    +
    + +Specifies an integer value indicating the desired width of the entry window, in average-size +characters of the widget's font. If the value is less than or equal to zero, the widget picks +a size just large enough to hold its current text. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName invoke +
    + +Calls the command specified by the option -command. + +
    + diff --git a/hlp/ru/bwidget/Label.html b/hlp/ru/bwidget/Label.html new file mode 100644 index 0000000..7eeb67e --- /dev/null +++ b/hlp/ru/bwidget/Label.html @@ -0,0 +1,331 @@ + +Label + +
    NAME
    +
    Label + - Label widget with state option, dynamic help and drag and drop facilities +
    +
    +
    CREATION
    +
    Label pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -anchor
      -background or -bg
      -bitmap
      -borderwidth or -bd
      -cursor
      -disabledforeground
      -font
      -foreground or -fg
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -image
      -justify
      -padx
      -pady
      -relief
      -takefocus
      -text
      -textvariable
      -wraplength
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -dragenabled
      -dragendcmd
      -dragevent
      -draginitcmd
      -dragtype
      -dropcmd
      -dropenabled
      -dropovercmd
      -droptypes
      -focus
      -height
      -helptext
      -helptype
      -helpvar
      -name
      -state
      -underline
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName setfocus +
    +
    +


    +DESCRIPTION
    +

    + +The Label widget extends the default Tk label. Options have been added to provide +visual effect depending on the state of the Label, DynamicHelp options, and Drag + and Drop. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -dragenabled
    +
    +A boolean specifying if drag is enabled. +
    +
    +
    -dragendcmd
    +
    + +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +Specifies a command to be called when dragevent occurs on widget. +draginitcmd must be a command conforming to the description of the +option draginitcmd of DragSite::register. + +
    If draginitcmd is empty, the internal draginitcmd command is used instead +and returns: +
    +
    IMAGE {copy} <image name> +if an image is displayed. +
    BITMAP {copy} <bitmap name> +if a bitmap is displayed. +
    TEXT {copy} <text> +if a text is displayed. +
    +Note that if dragtype option is not empty, its value is used instead of those above. + +
    +
    +
    -dragtype
    +
    + +Specifies an alternate type of dragged object. + +
    +
    +
    -dropcmd
    +
    + +Specifies a command to be called when drop occurs on the widget. +dropcmd must be a command conforming to the description of the +option dropcmd of DropSite::register. + +
    If dropcmd is empty, the command updates the label following the type of the data: +
    + + + + + + + + + + +
    COLOR or FGCOLORreconfigure the foreground of the Label.
    BGCOLORreconfigure the background of the Label.
    IMAGEreconfigure the Label to display the associated image.
    BITMAPreconfigure the Label to display the associated bitmap. +image option is set to empty.
    TEXT,
    or any other tag
    reconfigure the Label to display the associated string. +image and bitmap options are set to empty.
    +and returns 1. + +
    +
    +
    -dropenabled
    +
    +A boolean specifying if drop is enabled. +
    +
    +
    -dropovercmd
    +
    + +Specifies a command to be called when drag icon is over the widget. +dropovercmd must be a command conforming to the description of the +option dropovercmd of DropSite::register. + +
    If dropovercmd is empty, Label always accepts the drop if data type is +FGCOLOR, COLOR, BGCOLOR, and accepts all other data type only if +state is normal. + +
    +
    +
    -droptypes
    +
    + +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +Default accepts FGCOLOR, COLOR, BGCOLOR, TEXT, BITMAP +and IMAGE, all with copy and move operations. + +
    +
    +
    -focus
    +
    + +Specifies a pathname to set the focus on for Label::setfocus command. + +
    +
    +
    -height
    +
    + +Specifies a desired height for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units, for text it is in lines of text. +If this option isn't specified, the label's desired height is computed +from the size of the image or bitmap or text being displayed in it. +
    +
    +
    -helptext
    +
    + +Text for dynamic help. If empty, no help is available for this widget. +See also DynamicHelp. +
    +
    +
    -helptype
    +
    +Type of dynamic help. Use balloon or variable. +See also DynamicHelp. +
    +
    +
    -helpvar
    +
    +Variable to use when helptype option is variable. +See also DynamicHelp. +
    +
    +
    -name
    +
    + +Specifies a standard name for the label. If the option *nameName is +found in the resource database, then text and underline options +are extracted from its value. + +
    +
    +
    -state
    +
    + +Specifies one of two states for the Label: normal or disabled. +In normal state the text of the Label is displayed using the foreground option. +In disabled state the text of the Label is displayed using the disabledforeground option. +
    +
    +
    -underline
    +
    + +Specifies the integer index of a character to underline in the label. +0 corresponds to the first character of the text displayed, 1 to the next character, +and so on. +
    The binding <Alt-char> is automatically set on the toplevel +of the Label to call Label::setfocus. + +
    +
    +
    -width
    +
    + +Specifies a desired width for the label. +If an image or bitmap is being displayed in the label then the value is in +screen units, for text it is in characters. +If this option isn't specified, the label's desired width is computed +from the size of the image or bitmap or text being displayed in it. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName setfocus +
    + +Set the focus on the pathname given by -focus option if -state is normal. + +
    + diff --git a/hlp/ru/bwidget/LabelEntry.html b/hlp/ru/bwidget/LabelEntry.html new file mode 100644 index 0000000..c0858c7 --- /dev/null +++ b/hlp/ru/bwidget/LabelEntry.html @@ -0,0 +1,194 @@ + +LabelEntry + +
    NAME
    +
    LabelEntry + - +LabelFrame containing an Entry widget. + +
    +
    +
    CREATION
    +
    LabelEntry pathName ?option value...?
    +
    +
    +
    OPTIONS from Entry
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -borderwidth or -bd  -command
      -disabledforeground  -dragenabled
      -dragendcmd  -dragevent
      -draginitcmd  -dragtype
      -dropcmd  -dropenabled
      -dropovercmd  -droptypes
      -editable  -entrybg (see -background)
      -entryfg (see -foreground)  -exportselection
      -font  -helptext
      -helptype  -helpvar
      -highlightbackground  -highlightcolor
      -highlightthickness  -insertbackground
      -insertborderwidth  -insertofftime
      -insertontime  -insertwidth
      -justify  -relief
      -selectbackground  -selectborderwidth
      -selectforeground  -show
      -state  -takefocus
      -text  -textvariable
      -width  -xscrollcommand
    +
    +
    +
    OPTIONS from LabelFrame
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -disabledforeground
      -foreground or -fg  -helptext
      -helptype  -helpvar
      -label (see -text)  -labelanchor (see -anchor)
      -labelfont (see -font)  -labelheight (see -height)
      -labeljustify (see -justify)  -labelwidth (see -width)
      -name  -padx
      -pady  -side
      -state  -underline
      -wraplength
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +LabelEntry is a widget composed of LabelFrame widget +containing an Entry widget. +Tk entry command can also be used on LabelEntry widget. + +

    +

    +WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    + +Set bindings on the entry widget. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    + diff --git a/hlp/ru/bwidget/LabelFrame.html b/hlp/ru/bwidget/LabelFrame.html new file mode 100644 index 0000000..1e027fd --- /dev/null +++ b/hlp/ru/bwidget/LabelFrame.html @@ -0,0 +1,139 @@ + +LabelFrame + +
    NAME
    +
    LabelFrame + - Frame with a Label +
    +
    +
    CREATION
    +
    LabelFrame pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -borderwidth or -bd  -relief
    +
    +
    +
    OPTIONS from Label
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -anchor  -background or -bg
      -disabledforeground  -focus
      -font  -foreground or -fg
      -height  -helptext
      -helptype  -helpvar
      -justify  -name
      -padx  -pady
      -state  -text
      -underline  -width
      -wraplength
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + +
      -side
    +
    +
    +
    WIDGET COMMAND
    +
    LabelFrame::align + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    +


    +DESCRIPTION
    +

    + +LabelFrame enables user to create a frame with a +Label positionned at any side. +LabelFrame is used by ComboBox +and SpinBox. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -side (read-only)
    +
    + +Specifies where to position the Label relative to the user frame: top, bottom, left or right. +
    +
    +

    +WIDGET COMMAND
    +
    LabelFrame::align + ?arg...? +
    + +This command align label of all widget given by args of class LabelFrame +(or "derived") by setting their width to the max one +1 + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the frame where the user can create any other widget. +
    + diff --git a/hlp/ru/bwidget/ListBox.html b/hlp/ru/bwidget/ListBox.html new file mode 100644 index 0000000..39a8790 --- /dev/null +++ b/hlp/ru/bwidget/ListBox.html @@ -0,0 +1,608 @@ + +ListBox + +
    NAME
    +
    ListBox + - ListBox widget +
    +
    +
    CREATION
    +
    ListBox pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -cursor
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -relief
      -selectbackground
      -selectforeground
      -takefocus
      -xscrollcommand
      -yscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -deltax
      -deltay
      -dragenabled
      -dragendcmd
      -dragevent
      -draginitcmd
      -dragtype
      -dropcmd
      -dropenabled
      -dropovercmd
      -dropovermode
      -droptypes
      -height
      -multicolumn
      -padx
      -redraw
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bindImage + event + script +
    +
    pathName bindText + event + script +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName delete + ?arg...? +
    +
    pathName edit + item + text + ?verifycmd? + ?clickres? + ?select? +
    +
    pathName exists + item +
    +
    pathName index + item +
    +
    pathName insert + index + item + ?option value...? +
    +
    pathName item + first + ?last? +
    +
    pathName itemcget + item + option +
    +
    pathName itemconfigure + item + ?option? ?value option value ...? +
    +
    pathName items + ?first? + ?last? +
    +
    pathName move + item + index +
    +
    pathName reorder + neworder +
    +
    pathName see + item +
    +
    pathName selection + cmd + ?arg...? +
    +
    pathName xview + ?arg...? +
    +
    pathName yview + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +ListBox widget uses canvas to display a list of items. +Each item is composed of a label with its own font and foreground attributes, and an optional +image or window. Each item is drawn in a single line, whose height is defined by the +deltay option, so they must have at most this height. +A item is uniquely identified by a string given at creation (by the +insert command). The ListBox can have one or more columns, depending on +multicolumn option. The user do not handle columns; the number of columns +is determined following the height of the ListBox in order to see each item vertically. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -deltax
    +
    + +Specifies horizontal pad between each columns. + +
    +
    +
    -deltay
    +
    + +Specifies vertical size of the items. + +
    +
    +
    -dragenabled
    +
    +A boolean specifying if drag is enabled. +
    +
    +
    -dragendcmd
    +
    + +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +ListBox has a command wrapper for drag-init events. This command refused the drag +if no item is designated. In other cases: +
    If draginitcmd is empty, it returns: +
      +
    • the value of option dragtype or LISTBOX_ITEM if empty as the data type, +
    • {move copy link} as the operations, +
    • the item identifier as the data. +
    +If draginitcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the listbox, +
    • the identifier of the dragged item, +
    • the toplevel created to represent dragged data. +
    +and must return a value conforming to draginitcmd option described in +DragSite::register. + +
    +
    +
    -dragtype
    +
    + +Specifies an alternate type of dragged object. + +
    +
    +
    -dropcmd
    +
    + +ListBox has a command wrapper for drop events. This command stops auto scrolling +and extract item and position. +
    If dropcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the listbox, +
    • the pathname of the drag source, +
    • a list describing where the drop occurs. It can be: +
        +
      • {widget}, +
      • {item item} or +
      • {position index}. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    + +
    +
    +
    -dropenabled
    +
    +A boolean specifying if drop is enabled. +
    +
    +
    -dropovercmd
    +
    + +LsitBox has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +If dropovercmd is not empty, the command is called with the following aguments: +
      +
    • the pathname of the listbox, +
    • the pathname of the drag source, +
    • a list describing where the drop can occur, whose elements are: +
        +
      • the string widget if dropovertype option contains w, else empty string. +
      • the targeted item if drag icon points an item and dropovertype option contains +i, else empty string. +
      • an index within two items where drag icon points to if dropovertype option +contains p, else empty string. +
      • optionally, the preferred method if drop can occur both inside an item and between two +items. The value is position or item. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    +The command must return a list with two elements: +
      +
    • the drop status, conforming to those described in dropovercmd option of +DropSite::register, +
    • the choosen method: widget, item or position. +
    + +
    +
    +
    -dropovermode
    +
    + +Specifies the type of drop-over interaction. Must be a combination of +w, which specifies that drop can occurs everywhere on widget, +p, which specifies that drop can occurs between two items, +and i, which specifies that drop occurs inside items. + +
    +
    +
    -droptypes
    +
    + +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +
    Default is LISTBOX_ITEM with operations copy and move. + +
    +
    +
    -height
    +
    + +Specifies the desired height for the listbox in units of deltay pixels. + +
    +
    +
    -multicolumn
    +
    + +Specifies wether or not ListBox layouts items in order to see each one vertically. + +
    +
    +
    -padx
    +
    + +Specifies distance between image or window and text of the items. + +
    +
    +
    -redraw
    +
    + +Specifies wether or not the listbox should be redrawn when entering idle. +Set it to false if you call update while modifying the listbox. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the listbox in units of 8 pixels. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName bindImage + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the image of a item. +The item idenfier on which the event occurs is appended to the command. + +
    +
    pathName bindText + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the label of a item. +The item idenfier on which the event occurs is appended to the command. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName delete + ?arg...? +
    + +Deletes all items in arg. arg can be a list +of items or a list of list of items. +To delete all items, do $pathName delete [$pathName items]. + +
    +
    pathName edit + item + text + ?verifycmd? + ?clickres? + ?select? +
    + +Provides a way for the user to edit in place the label of an item. +
    The command takes the initial text as argument and does not modify the label of the +edited node, but returns an empty string if edition is canceled, or the typed text +if edition is accepted. +
    When editing, the user can cancel by pressing Escape, or accept by pressing Return. +
    clickres specifies what to do if the user click outside the editable area. +If clickres is 0 (the default), the edition is canceled. +If clickres is 1, the edition is accepted. +In all other case, the edition continues. +
    If edition is accepted and modifycmd is not empty, then it is called with +the new text as argument and must return 1 to accept the new text, 0 to refuse it +and continue edition. +
    select specifies wether or not the initial text should be selected. Default is 1. + +
    +
    pathName exists + item +
    + +Returns 1 if item exists in the listbox, else 0. + +
    +
    pathName index + item +
    + +Returns the position of item in the list. + +
    +
    pathName insert + index + item + ?option value...? +
    + +Inserts a new item identified by item in the list at position index. + +

    +

    -data
    +
    + +User data associated to the item. + +
    +
    +
    -fill
    +
    + +Specifies the foreground color of the label of the item. + +
    +
    +
    -font
    +
    + +Specifies a font for the label of the item. + +
    +
    +
    -image
    +
    + +Specifies an image to display at the left of the label of the item. +window option override image. +
    +
    +
    -indent
    +
    + +Specifies the amount of extra space in pixels at the left of the item. + +
    +
    +
    -text
    +
    + +Specifies the label of the item. + +
    +
    +
    -window
    +
    + +Specifies a pathname to display at the left of the label of the item. +window option override image. +
    +
    +
    +
    pathName item + first + ?last? +
    + +Its use is deprecated. Use items instead.
    +If last is omitted, returns the item at index first in the list, +or an empty string if first refers to a non-existent element. +If last is specified, the command returns a list whose elements are all +of the items between first and last, inclusive. +Both first and last may have any of the standard forms for indices. + +
    +
    pathName itemcget + item + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + item + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName items + ?first? + ?last? +
    + +If first and last are omitted, returns the list of all items. +If first is specified and last omitted, returns the item at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the items between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName move + item + index +
    + +Moves item at position index in the list. + +
    +
    pathName reorder + neworder +
    + +Modifies the order of items in the listbox given by neworder. Items that do not +appear in neworder are no moved. + +
    +
    pathName see + item +
    + +Arrange the scrolling area to make item visible. + +
    +
    pathName selection + cmd + ?arg...? +
    + +Modifies the list of selected items following cmd: +
    +
    clear +
    remove all items of the selection. +
    set +
    set the selection to all items in arg +
    add +
    add all items of arg in the selection +
    remove +
    remove all items of arg of the selection +
    get +
    return the current selected items +
    + +
    +
    pathName xview + ?arg...? +
    + +Standard command to enable horizontal scrolling of pathName. + +
    +
    pathName yview + ?arg...? +
    + +Standard command to enable vertical scrolling of pathName. + +
    + diff --git a/hlp/ru/bwidget/MainFrame.html b/hlp/ru/bwidget/MainFrame.html new file mode 100644 index 0000000..b7d6302 --- /dev/null +++ b/hlp/ru/bwidget/MainFrame.html @@ -0,0 +1,283 @@ + +MainFrame + +
    NAME
    +
    MainFrame + - Manage toplevel with menu, toolbar and statusbar +
    +
    +
    CREATION
    +
    MainFrame pathName ?option value...?
    +
    +
    +
    OPTIONS from ProgressBar
    +
    + + + + + + + + + + +
      -background or -bg  -progressfg (see -foreground)
      -progressmax (see -maximum)  -progresstype (see -type)
      -progressvar (see -variable)
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + +
      -height
      -menu
      -separator
      -textvariable
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName addindicator + ?arg...? +
    +
    pathName addtoolbar +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    pathName getindicator + index +
    +
    pathName getmenu + menuid +
    +
    pathName gettoolbar + index +
    +
    pathName setmenustate + tag + state +
    +
    pathName showstatusbar + name +
    +
    pathName showtoolbar + index + bool +
    +
    +


    +DESCRIPTION
    +

    + +MainFrame manage toplevel to have:
    +

      +
    • simple menu creation, with automatic accelerator bindings and +DynamicHelp association, +
    • one or more toolbar that user can hide, +
    • a status bar, displaying a user message or a menu description, and optionnaly a +ProgressBar. +
    +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -height
    +
    + +Specifies the desired height for the user frame in any of the forms acceptable to +Tk_GetPixels. If this option is less than or equal to zero (the default) then the window +will not request any size at all. +
    +
    +
    -menu (read-only)
    +
    + +This option describes the menu. This is a list whose each five elements describe +one cascad menu. It has the following form: +{menuname tags menuId tearoff menuentries...} +where menuentries is a list where each element describe one menu entry, which can be: +
      +
    • for a separator:
      + {separator} +
    • for a command:
      + {command menuname ?tags? ?description? ?accelerator? ?option value? ...} +
    • for a check button:
      + {checkbutton menuname ?tags? ?description? ?accelerator? ?option value? ...} +
    • for a radio button:
      + {radiobutton menuname ?tags? ?description? ?accelerator ?option value? ...} +
    • for a cascad menu:
      + {cascad menuname tags menuId tearoff menuentries} +
    +where: +
      +
    • menuname is the name of the menu. If it contains a &, the following character +is automatically converted to the corresponding -underline option of menu add +command. +
    • tags is the tags list for the entry, used for enabling or disabling menu +entries with MainFrame::setmenustate. +
    • menuId is an id for the menu, from which you can get menu pathname with + MainFrame::getmenu. +
    • tearoff specifies if menu has tearoff entry. +
    • description specifies a string for DynamicHelp. +
    • accelerator specifies a key sequence. It is a list of two elements, where the first +is one of Ctrl, Alt or CtrlAlt, and the second as letter or a digit. +An accelerator string is build and corresponding binding set on the toplevel to invoke the +menu entry. +
    • option value specifies additionnal options for the entry (see menu add +command). +
    +Each value enclosed by ? are optional and defaulted to empty string, but must be +provided if one or more following options is not empty. +
    Example: +
    +set descmenu {
    +    "&File" {} {} 0 {
    +        {command "&New"     {} "Create a new document"     {Ctrl n} -command Menu::new}
    +        {command "&Open..." {} "Open an existing document" {Ctrl o} -command Menu::open}
    +        {command "&Save"    open "Save the document" {Ctrl s} -command Menu::save}
    +        {cascad  "&Export"  {} export 0 {
    +            {command "Format &1" open "Export document to format 1" {} -command {Menu::export 1}}
    +            {command "Format &2" open "Export document to format 2" {} -command {Menu::export 2}}
    +        }}
    +        {separator}
    +        {cascad "&Recent files" {} recent 0 {}}
    +        {separator}
    +        {command "E&xit" {} "Exit the application" {} -command Menu::exit}
    +    }
    +    "&Options" {} {} 0 {
    +        {checkbutton "Toolbar" {} "Show/hide toolbar" {} 
    +            -variable Menu::_drawtoolbar
    +            -command  {$Menu::_mainframe showtoolbar toolbar $Menu::_drawtoolbar}
    +        }
    +    }
    +}
    +
    + +
    +
    +
    -separator (read-only)
    +
    + +Specifies if separator should be drawn at the top and/or at the bottom of the user window. +Must be one of the values none, top, bottom or both. +It depends on the relief of subwidgets of user window. +
    +
    +
    -textvariable
    +
    + +Specifies the textvariable option for the label of the status bar. +DynamicHelp description +of menu entries are mapped to this variable at the creation of the MainFrame. +If this variable is changed by MainFrame::configure, menu description will +not be available. +
    You change the text of the label by modifying the value of the variable. +
    +
    +
    -width
    +
    + +Specifies the desired width for the user frame in any of the forms acceptable to +Tk_GetPixels. If this option is less than or equal to zero (the default) then the window +will not request any size at all. +
    +
    +

    +WIDGET COMMAND
    +
    pathName addindicator + ?arg...? +
    + +Add an indicator box at the right of the status bar. Each indicator are added from left +to right. An indicator is a Tk label widget configured with option-value pair +given by ?arg...?. -relief and -borderwidth options are respetively +defaulted to sunken and 1. Returns the pathname of the created label. +
    +
    pathName addtoolbar +
    + +Add a toolbar to the MainFrame. Returns the pathname of the new window where to place +toolbar items. +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Returns the pathname of the user window. +
    +
    pathName getindicator + index +
    + +Returns the pathname of the indexth added indicator. +
    +
    pathName getmenu + menuid +
    + +Returns the pathname of the menu whose id is menuid. +
    +
    pathName gettoolbar + index +
    + +Returns the pathname of the indexth added toolbar. +
    +
    pathName setmenustate + tag + state +
    + +Set the -state option value of all the menu entries that have the tag tag +to state. + +
    +
    pathName showstatusbar + name +
    + +name is one of none, status or progression. +Use none to hide the status bar, status to display the label only, or +progression to display the label and the +ProgressBar. +
    +
    pathName showtoolbar + index + bool +
    + +Hide if bool is 0, or show if bool is 1 the indexth added toolbar. +To prevent your toplevel from resizing while hiding/showing toolbar, +do [wm geometry $top [wm geometry $top]] when it is managed. +
    + diff --git a/hlp/ru/bwidget/MessageDlg.html b/hlp/ru/bwidget/MessageDlg.html new file mode 100644 index 0000000..e6f51da --- /dev/null +++ b/hlp/ru/bwidget/MessageDlg.html @@ -0,0 +1,208 @@ + +MessageDlg + +
    NAME
    +
    MessageDlg + - Message dialog box +
    +
    +
    CREATION
    +
    MessageDlg pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + +
      -anchor
      -font
      -foreground or -fg  -padx
      -pady
    +
    +
    +
    OPTIONS from Dialog
    +
    + + + + + + + + +
      -background or -bg  -cancel
      -default  -parent
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + +
      -aspect
      -buttons
      -icon
      -justify
      -message
      -title
      -type
      -width
    +
    +


    +DESCRIPTION
    +

    + +MessageDlg provides a simple way to display a message dialog. +MessageDlg::create creates the message dialog, displays +it and return the index of the pressed button, or -1 if it is destroyed. +When returning, the dialog no longer exists. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -aspect
    +
    + +Specifies a non-negative integer value indicating desired +aspect ratio for the text. The aspect ratio is specified as +100*width/height. 100 means the text should +be as wide as it is tall, 200 means the text should +be twice as wide as it is tall, 50 means the text should +be twice as tall as it is wide, and so on. +Used to choose line length for text if width option +isn't specified. +Defaults to 150. + +
    +
    +
    -buttons
    +
    + +Specifies a list of buttons to display when type option is user. +If a button has a symbolic name, its associated text will be displayed. + +
    +
    +
    -icon
    +
    + +Specifies an icon to display. Must be one of the following: error, info, +question or warning. + +
    +
    +
    -justify
    +
    + +Specifies how to justify lines of text. +Must be one of left, center, or right. Defaults +to left. +This option works together with the anchor, aspect, +padx, pady, and width options to provide a variety +of arrangements of the text within the window. +The aspect and width options determine the amount of +screen space needed to display the text. +The anchor, padx, and pady options determine where this +rectangular area is displayed within the widget's window, and the +justify option determines how each line is displayed within that +rectangular region. +For example, suppose anchor is e and justify is +left, and that the message window is much larger than needed +for the text. +The the text will displayed so that the left edges of all the lines +line up and the right edge of the longest line is padx from +the right side of the window; the entire text block will be centered +in the vertical span of the window. + +
    +
    +
    -message
    +
    + +Specifies the message to display in this message box. + +
    +
    +
    -title
    +
    + +Specifies a string to display as the title of the message box. +If the value is empty (the default), a default title will be set corresponding +to the icon option. +The default associated title is in english, and can be modified to set it in +another language by specifying the resource: +
        *MessageDlg.nameTitle:   value
    +or the equivalent tcl command: +
        option add *MessageDlg.nameTitle value
    +where name is the name of an icon as defined in the icon option. +
    For example, for french language, you can specify for a warning dialog: +
        option add *MessageDlg.warningTitle  "Attention"
    + +
    +
    +
    -type
    +
    + +Specifies a set of buttons to be displayed. The following values are possible: +
    +

    +

    +
    +abortretryignore +
    +Displays three buttons whose symbolic names are abort, +retry and ignore.

    +

    +ok +
    +Displays one button whose symbolic name is ok.

    +

    +okcancel +
    +Displays two buttons whose symbolic names are ok and cancel.

    +

    +retrycancel +
    +Displays two buttons whose symbolic names are retry and cancel.

    +

    +yesno +
    +Displays two buttons whose symbolic names are yes and no.

    +

    +yesnocancel +
    +Displays three buttons whose symbolic names are yes, no +and cancel. +

    +

    +user +
    +Displays buttons of -buttons option.

    +

    +
    + +
    +
    +
    -width
    +
    + +Specifies the length of lines in the window. +If this option has a value greater than zero then the aspect +option is ignored and the width option determines the line +length. +If this option has a value less than or equal to zero, then +the aspect option determines the line length. + +
    +
    + diff --git a/hlp/ru/bwidget/NoteBook.html b/hlp/ru/bwidget/NoteBook.html new file mode 100644 index 0000000..bf40b36 --- /dev/null +++ b/hlp/ru/bwidget/NoteBook.html @@ -0,0 +1,343 @@ + +NoteBook + +
    NAME
    +
    NoteBook + - Notebook manager widget +
    +
    +
    CREATION
    +
    NoteBook pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + +
      -font
    +
    +
    +
    OPTIONS from ArrowButton
    +
    + + + + + + + + + + + + + + + + +
      -activebackground  -activeforeground
      -background or -bg  -borderwidth or -bd
      -disabledforeground  -foreground or -fg
      -repeatdelay  -repeatinterval
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + +
      -height
      -homogeneous
      -side
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bindtabs + event + script +
    +
    pathName cget + option +
    +
    pathName compute_size +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName delete + page + ?destroyframe? +
    +
    pathName getframe + page +
    +
    pathName index + page +
    +
    pathName insert + index + page + ?option value...? +
    +
    pathName itemcget + page + option +
    +
    pathName itemconfigure + page + ?option? ?value option value ...? +
    +
    pathName move + page + index +
    +
    pathName page + first + ?last? +
    +
    pathName pages + ?first? + ?last? +
    +
    pathName raise + ?page? +
    +
    pathName see + page +
    +
    +


    +DESCRIPTION
    +

    + +NoteBook widget manage a set of pages and displays one of them. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -height
    +
    + +Specifies the desired height for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call NoteBook::compute_size to make NoteBook larger +enough to contains the largest page. +
    +
    +
    -homogeneous
    +
    + +Specifies wether or not the label of the pages must have the same width. + +
    +
    +
    -side (read-only)
    +
    + +Specifies the side where to place the label of the pages. Must be one +of top or bottom. +Only top is implemented for the moment. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call NoteBook::compute_size to make NoteBook larger +enough to contains the largest page. +
    +
    +

    +WIDGET COMMAND
    +
    pathName bindtabs + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on a tabs. The page idenfier on which +the event occurs is appended to the command. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName compute_size +
    + +This command can be called to make the NoteBook large enough to contain the largest page. +Note that if all pages use -createcmd, they will have no requested size. + +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName delete + page + ?destroyframe? +
    + +Deletes the page page. If destroyframe is 1 (the default), the frame +associated to page is destroyed. If destroyframe is 0, the frame is not +destroyed and is reused by further call to insert with the same page. + +
    +
    pathName getframe + page +
    + +Returns the pathname of the page page. + +
    +
    pathName index + page +
    + +Return the numerical index corresponding to the item. + +
    +
    pathName insert + index + page + ?option value...? +
    + +Insert a new page idendified by page at position index in the pages list. +index must be numeric or end. The pathname of the new page is returned. + +

    +

    -createcmd
    +
    + +Specifies a command to be called the first time the page is raised. + +
    +
    +
    -image
    +
    + +Specifies an image to display for the page at the left of the label + +
    +
    +
    -leavecmd
    +
    + +Specifies a command to be called when a page is about to be leaved. +The command must return 0 if the page can not be leaved, or 1 if it can. + +
    +
    +
    -raisecmd
    +
    + +Specifies a command to be called each time the page is raised. + +
    +
    +
    -state
    +
    + +Specifies the state of the page. Must be normal or disabled. + +
    +
    +
    -text
    +
    + +Specifies a label to display for the page. + +
    +
    +
    +
    pathName itemcget + page + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + page + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName move + page + index +
    + +Moves page tab to index index. + +
    +
    pathName page + first + ?last? +
    + +Its use is deprecated. Use pages instead.
    +If last is omitted, returns the page at index first, or an empty string if +first refers to a non-existent element. If last is specified, the command +returns a list whose elements are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName pages + ?first? + ?last? +
    + +If first and last are omitted, returns the list of all pages. +If first is specified and last omitted, returns the page at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName raise + ?page? +
    + +Raise the page page, or return the raised page if page is omitted. + +
    +
    pathName see + page +
    + +Scrolls labels to make the label of the page page visible. + +
    + diff --git a/hlp/ru/bwidget/PagesManager.html b/hlp/ru/bwidget/PagesManager.html new file mode 100644 index 0000000..33e30c4 --- /dev/null +++ b/hlp/ru/bwidget/PagesManager.html @@ -0,0 +1,174 @@ + +PagesManager + +
    NAME
    +
    PagesManager + - Pages manager widget +
    +
    +
    CREATION
    +
    PagesManager pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + +
      -background
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + +
      -height
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName add + page +
    +
    pathName cget + option +
    +
    pathName compute_size +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName delete + page +
    +
    pathName getframe + page +
    +
    pathName page + first + ?last? +
    +
    pathName pages + ?first? + ?last? +
    +
    pathName raise + ?page? +
    +
    +


    +DESCRIPTION
    +

    + +PagesManager widget manage a set of pages and displays one of them. +PagesManager does not provide any user access method, as NoteBook does, +so it can be done through a listbox, a menu, radiobutton, or whatever. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -height
    +
    + +Specifies the desired height for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call PagesManager::compute_size to make PagesManager +larger enough to contains the largest page. +
    +
    +
    -width
    +
    + +Specifies the desired width for the pages. If this option is equal to zero (the default) +then the window will not request any size at all. +In this case, user may want to call PagesManager::compute_size to make PagesManager +larger enough to contains the largest page. +
    +
    +

    +WIDGET COMMAND
    +
    pathName add + page +
    + +Add a new page idendified by page. The pathname of the new page +is returned. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName compute_size +
    + +This command can be called to make the PagesManager large enough to contain the largest page. + +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName delete + page +
    + +Deletes the page page. + +
    +
    pathName getframe + page +
    + +Returns the pathname of the page page. + +
    +
    pathName page + first + ?last? +
    + +Its use is deprecated. Use pages instead.
    +If last is omitted, returns the page at index first, or an empty string if +first refers to a non-existent element. If last is specified, the command +returns a list whose elements are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName pages + ?first? + ?last? +
    + +If first and last are omitted, returns the list of all pages. +If first is specified and last omitted, returns the page at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the pages between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName raise + ?page? +
    + +Raise the page page, or return the raised page if page is omitted. + +
    + diff --git a/hlp/ru/bwidget/PanedWindow.html b/hlp/ru/bwidget/PanedWindow.html new file mode 100644 index 0000000..3db37e4 --- /dev/null +++ b/hlp/ru/bwidget/PanedWindow.html @@ -0,0 +1,130 @@ + +PanedWindow + +
    NAME
    +
    PanedWindow + - Tiled layout manager widget +
    +
    +
    CREATION
    +
    PanedWindow pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + +
      -background or -bg
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + +
      -pad
      -side
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName add + ?option value...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe + index +
    +
    +


    +DESCRIPTION
    +

    + +PanedWindow is a widget that lays out children in +a vertically or horizontally tiled format. +The user can adjust the size of the panes, with a pane control sash created +between children. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -pad (read-only)
    +
    + +Specifies additional space between the button of the sash and children. + +
    +
    +
    -side (read-only)
    +
    + +Specifies the side of the sash, which implies the layout: top or bottom +(horizontal layout), left or right (vertical layout). +
    +
    +
    -width (read-only)
    +
    + +Specifies the width of the button of the sash. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName add + ?option value...? +
    + +This command add a new pane. The new pane is placed below the previous pane for vertical +layout or at right for horizontal layout. This command returns a frame where user can place +its widget. Valid options are: +

    +

    -minsize
    +
    + +Specifies the minimum size requested for the pane. +See the grid command for more information. +
    +
    +
    -weight
    +
    + +Specifies the relative weight for apportioning any extra spaces among panes. +See the grid command for more information. +
    +
    +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe + index +
    + +Returns the pathname of the indexth added pane. +
    + diff --git a/hlp/ru/bwidget/PasswdDlg.html b/hlp/ru/bwidget/PasswdDlg.html new file mode 100644 index 0000000..3511c8e --- /dev/null +++ b/hlp/ru/bwidget/PasswdDlg.html @@ -0,0 +1,214 @@ + +PasswdDlg + +
    NAME
    +
    PasswdDlg + - Login/Password dialog box +
    +
    +
    CREATION
    +
    PasswdDlg pathName ?option value...?
    +
    +
    +
    OPTIONS from Dialog
    +
    + + + + + + + + + + + + + + + + + + +
      -anchor  -background or -bg
      -homogeneous  -modal
      -padx  -pady
      -parent  -spacing
      -title
    +
    +
    +
    OPTIONS from LabelEntry
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -disabledforeground  -entrybg
      -entryfg  -exportselection
      -font  -foreground or -fg
      -helptype  -highlightbackground
      -highlightcolor  -highlightthickness
      -insertbackground  -insertborderwidth
      -insertofftime  -insertontime
      -insertwidth  -labelanchor
      -labelfont  -labelheight
      -labeljustify  -labelwidth
      -loginhelptext (see -helptext)  -loginhelpvar (see -helpvar)
      -loginlabel (see -label)  -logintext (see -text)
      -logintextvariable (see -textvariable)  -loginunderline (see -underline)
      -passwdeditable (see -editable)  -passwdhelptext (see -helptext)
      -passwdhelpvar (see -helpvar)  -passwdlabel (see -label)
      -passwdstate (see -state)  -passwdtext (see -text)
      -passwdtextvariable (see -textvariable)  -passwdunderline (see -underline)
      -relief  -selectbackground
      -selectborderwidth  -selectforeground
      -wraplength
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + +
      -command
      -type
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +PasswdDlg provides a simple way to display a login/password dialog. +PasswdDlg::create creates the dialog, displays it, and return the value of login +and password in a list, or an empty list if it is destroyed or user press cancel. +When returning, the dialog no longer exists. +
    Additionnal resources can be set to modify other text: +

    +    *loginName     Label for login LabelEntry
    +    *passwordName  Label for password LabelEntry
    +
    + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -command
    +
    + +Specifies a command to call when user press ok button. + +
    +
    +
    -type
    +
    + +Specifies a set of buttons to be displayed. The following values are possible: +
    +

    +

    +
    +ok +
    +Displays one button whose symbolic name is ok.

    +

    +okcancel +
    +Displays two buttons whose symbolic names are ok and cancel.

    +

    + +
    +
    + + + +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    + +Stephane Lavirotte (Stephane.Lavirotte@sophia.inria.fr) + + diff --git a/hlp/ru/bwidget/ProgressBar.html b/hlp/ru/bwidget/ProgressBar.html new file mode 100644 index 0000000..142971c --- /dev/null +++ b/hlp/ru/bwidget/ProgressBar.html @@ -0,0 +1,136 @@ + +ProgressBar + +
    NAME
    +
    ProgressBar + - Progress indicator widget +
    +
    +
    CREATION
    +
    ProgressBar pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -foreground or -fg  -orient
      -relief
      -troughcolor
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + +
      -height
      -maximum
      -type
      -variable
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +ProgressBar widget indicates the user the progress of a lengthly operation. +It is used by MainFrame +and ProgressDlg. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -height
    +
    + +Specifies the desired height for the progress indicator. +
    +
    +
    -maximum
    +
    + +Specifies the maximum value of the variable. + +
    +
    +
    -type
    +
    + +Specifies the type of the ProgressBar. Must be one of normal, incremental or +infinite. +
    If type is normal, the progress indicator is drawn proportional +to the variable value and maximum option each time the variable is set. +
    If type is incremental, the value of the progress indicator is maintained internally, +and incremented each time the variable is set by its value. The progress indicator is drawn proportional +to the internal value and maximum option. +
    If type is infinite, the value of the progress indicator is maintained internally, +and incremented each time the variable is set by its value. The progress indicator grow from left to +right if internal value (modulo maximum) is less than maximum/2, and from right to left if +internal value is greater than maximum/2. +
    See -variable option for special case of its value, + +
    +
    +
    -variable
    +
    + +Specifies the variable attached to the progress indicator. +Progress indicator is updated when the value of the variable changes. +If the value of the variable is negative, the progress indicator is not +displayed (it is drawn flat with background color +- usefull for ProgressDlg to make it invisible). If its value 0, progress indicator +is reinitialized. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the progress indicator. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    + diff --git a/hlp/ru/bwidget/ProgressDlg.html b/hlp/ru/bwidget/ProgressDlg.html new file mode 100644 index 0000000..99506e9 --- /dev/null +++ b/hlp/ru/bwidget/ProgressDlg.html @@ -0,0 +1,143 @@ + +ProgressDlg + +
    NAME
    +
    ProgressDlg + - Progress indicator dialog box +
    +
    +
    CREATION
    +
    ProgressDlg pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -font
      -textvariable
    +
    +
    +
    OPTIONS from Dialog
    +
    + + + + + + + + +
      -background or -bg  -parent
      -separator  -title
    +
    +
    +
    OPTIONS from ProgressBar
    +
    + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -foreground or -fg  -maximum
      -relief  -troughcolor
      -type  -variable
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + +
      -command
      -height
      -stop
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +ProgressDlg provides a simple way to display a progress indicator dialog. +ProgressDlg::create creates the dialog, displays it, set a local +grab to it and immediatly return. The dialog is updated by modifying the +value of the variable of options -textvariable and -variable. +You have to destroy the dialog after use. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -command
    +
    + +Specifies a command to call when user press stop button. + +
    +
    +
    -height
    +
    + +Specifies a desired height for the label in lines of text. + +
    +
    +
    -stop
    +
    + +Specifies the text of the button typically used to stop process. If empty, no button will +be drawn. This can be a symbolic name. + +
    +
    +
    -width
    +
    + +Specifies a desired width for the label in characters. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    + diff --git a/hlp/ru/bwidget/ScrollView.html b/hlp/ru/bwidget/ScrollView.html new file mode 100644 index 0000000..c94fc1e --- /dev/null +++ b/hlp/ru/bwidget/ScrollView.html @@ -0,0 +1,130 @@ + +ScrollView + +
    NAME
    +
    ScrollView + - Display the visible area of a scrolled window +
    +
    +
    CREATION
    +
    ScrollView pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -cursor
      -relief
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + +
      -fill
      -foreground or -fg
      -height
      -width
      -window
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +ScrollView displays the visible area of a scrolled window within +its scroll region. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -fill
    +
    + +Specifies the fill color of the rectangle. + +
    +
    +
    -foreground
    +
    + +Specifies the color of the border of the rectangle. + +
    +
    +
    -height
    +
    + +Specifies the desired height for the ScrollView. +
    +
    +
    -width
    +
    + +Specifies the desired width for the ScrollView. +
    +
    +
    -window
    +
    + +Specifies the window to view. This widget must have -xscrollcommand and +-yscrollcommand options, and respond to xview and yview command. +In order to make ScrollView working with other scrollbar, -xscrollcommand and +-yscrollcommand options of the widget must be set before the widget is passed to +the -window option of the ScrollView (for example, if the widget is handled by +a ScrolledWindow, call setwidget before setting -window option). + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +

    BINDINGS

    + +
    If mouse button 1 is pressed and dragged over the ScrollView, the top left corner of +the visible area of the scrolled window is moved proportionally to the mouse displacement. +
    +
    If mouse button 3 is pressed over the ScrollView, the top left corner of the visible +area is proportionally set to this point. +
    + + diff --git a/hlp/ru/bwidget/ScrollableFrame.html b/hlp/ru/bwidget/ScrollableFrame.html new file mode 100644 index 0000000..afe7f4a --- /dev/null +++ b/hlp/ru/bwidget/ScrollableFrame.html @@ -0,0 +1,191 @@ + +ScrollableFrame + +
    NAME
    +
    ScrollableFrame + - Scrollable frame containing widget +
    +
    +
    CREATION
    +
    ScrollableFrame pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + +
      -background or -bg  -xscrollcommand
      -yscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + +
      -areaheight
      -areawidth
      -constrainedheight
      -constrainedwidth
      -height
      -width
      -xscrollincrement
      -yscrollincrement
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    pathName see + widget + ?vert? + ?horz? +
    +
    pathName xview + ?arg...? +
    +
    pathName yview + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +ScrollableFrame widget containing widget. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -areaheight
    +
    + +Specifies the height for the scrollable area. If zero, then the height +of the scrollable area is made just large enough to hold all its children. +
    +
    +
    -areawidth
    +
    + +Specifies the width for the scrollable area. If zero, then the width +of the scrollable area window is made just large enough to hold all its children. +
    +
    +
    -constrainedheight
    +
    + +Specifies whether or not the scrollable area should have the same height of the +scrolled window. If true, vertical scrollbar is not needed. + +
    +
    +
    -constrainedwidth
    +
    + +Specifies whether or not the scrollable area should have the same width of the +scrolled window. If true, horizontal scrollbar is not needed. + +
    +
    +
    -height
    +
    + +Specifies the desired height for the window in pixels. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the window in pixels. + +
    +
    +
    -xscrollincrement
    +
    + +See xscrollincrement option of canvas widget. + +
    +
    +
    -yscrollincrement
    +
    + +See yscrollincrement option of canvas widget. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the pathname of the scrolled frame where widget should be created. + +
    +
    pathName see + widget + ?vert? + ?horz? +
    + +Arrange scrollable area to make widget visible in the window. +vert and horz specify which part of widget must be preferably +visible, in case where widget is too tall or too large to be entirely visible. +vert must be top (the default) or bottom, +and horz must be left (the default) or right. +If vert or horz is not a valid value, area is not scrolled in this direction. + +
    +
    pathName xview + ?arg...? +
    + +Standard command to enable horizontal scrolling of pathName. + +
    +
    pathName yview + ?arg...? +
    + +Standard command to enable vertical scrolling of pathName. + +
    + diff --git a/hlp/ru/bwidget/ScrolledWindow.html b/hlp/ru/bwidget/ScrolledWindow.html new file mode 100644 index 0000000..7c48ba9 --- /dev/null +++ b/hlp/ru/bwidget/ScrolledWindow.html @@ -0,0 +1,115 @@ + +ScrolledWindow + +
    NAME
    +
    ScrolledWindow + - Generic scrolled widget +
    +
    +
    CREATION
    +
    ScrolledWindow pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + +
      -background or -bg  -borderwidth or -bd
      -relief
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + +
      -auto
      -scrollbar
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    pathName setwidget + widget +
    +
    +


    +DESCRIPTION
    +

    + +ScrolledWindow enables user to create easily a widget with its scrollbar. +Scrollbars are created by ScrolledWindow and scroll commands are automatically associated to +a scrollable widget with ScrolledWindow::setwidget. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -auto
    +
    + +Specifies the desired auto managed scrollbar: +
  • none means scrollbar are always drawn +
  • horizontal means horizontal scrollbar is drawn as needed +
  • vertical means vertical scrollbar is drawn as needed +
  • both means horizontal and vertical scrollbars are drawn as needed +
  • horizontal means horizontal scrollbar is drawn as needed +
  • +
    +
    -scrollbar (read-only)
    +
    + +Specifies the desired scrollbar: none, horizontal, vertical +or both. This option is not modifiable with ScrolledWindow::configure. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the pathname of the frame where the scrolled widget should be created. This command +is no longer needed. You can directly create the scrolled widget as the child +of pathName. +
    +
    pathName setwidget + widget +
    + +Associate widget to the the scrollbars. widget is packed +in with option expand to yes and fill to both. +widget must be a scrollable widget, i.e. have the options +xscrollcommand/yscrollcommand and the command xview/yview, +such as canvas or text. +
    + diff --git a/hlp/ru/bwidget/SelectColor.html b/hlp/ru/bwidget/SelectColor.html new file mode 100644 index 0000000..cf9199d --- /dev/null +++ b/hlp/ru/bwidget/SelectColor.html @@ -0,0 +1,152 @@ + +SelectColor + +
    NAME
    +
    SelectColor + - Color selection widget +
    +
    +
    CREATION
    +
    SelectColor pathName ?option value...?
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + +
      -color
      -command
      -height
      -parent
      -title
      -type
      -variable
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    SelectColor::setcolor + index + color +
    +
    +


    +DESCRIPTION
    +

    + +SelectColor provides a simple way to select color. It can be displayed +as a dialog box or as a menubutton. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -color
    +
    + +Specifies the color value of the widget. + +
    +
    +
    -command
    +
    + +When type is menubutton, +specifies a command to call when user select a color. + +
    +
    +
    -height
    +
    + +When type is menubutton, specifies the desired height for the button. + +
    +
    +
    -parent
    +
    + +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
    +
    +
    -title
    +
    + +Title of the Dialog toplevel. + +
    +
    +
    -type (read-only)
    +
    + +Specifies the type of the SelectColor widget. Must be dialog or menubutton. +
    If type option is dialog, SelectColor::create directly creates the +dialog, displays it and return an empty string if cancel button is pressed or if dialog is +destroyed, and the selected color if ok button is pressed. In all cases, dialog is destroyed. +
    If type option is menubutton, SelectColor::create returns the +pathname of the widget created. It is composed of a button from which user can access a menu +displaying predefined colors. + +
    +
    +
    -variable
    +
    + +Specifies a variable to link to the color value of the widget. + +
    +
    +
    -width
    +
    + +When type is menubutton, specifies the desired width for the button. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    SelectColor::setcolor + index + color +
    + +Set the value of user predefined color at index index to color. +index must be between 1 and 5. + +
    + diff --git a/hlp/ru/bwidget/SelectFont.html b/hlp/ru/bwidget/SelectFont.html new file mode 100644 index 0000000..e2929a6 --- /dev/null +++ b/hlp/ru/bwidget/SelectFont.html @@ -0,0 +1,132 @@ + +SelectFont + +
    NAME
    +
    SelectFont + - Font selection widget +
    +
    +
    CREATION
    +
    SelectFont pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -background or -bg  -font
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + +
      -command
      -parent
      -sampletext
      -title
      -type
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    SelectFont::loadfont +
    +
    +


    +DESCRIPTION
    +

    + +SelectFont provides a simple way to choose font. It can be displayed +as a dialog box or as a toolbar. +
    Textual items in Dialog box uses -name options so they +can be translated to any language. Symbolic name used are +ok, cancel, font, size, style, +bold, italic, underline and overstrike. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -command
    +
    + +Specifies a command to call when user select a new font when SelectFont type +option is toolbar. + +
    +
    +
    -parent
    +
    + +Parent of the Dialog. Dialog is centered in its parent. If empty, it is centered in +root window. +
    +
    +
    -sampletext
    +
    + +Specifies the text displayed in the preview area. + +
    +
    +
    -title
    +
    + +Title of the Dialog toplevel. + +
    +
    +
    -type
    +
    + +Specifies the type of the SelectFont widget. Must be dialog or toolbar. +
    If type option is dialog, SelectFont::create directly creates the +dialog, displays it and return an empty string if cancel button is pressed or if dialog is +destroyed, and the selected font if ok button is pressed. In all cases, dialog is destroyed. +
    If type option is toolbar, SelectFont::create returns the pathname +of the widget created. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    SelectFont::loadfont +
    + +Load the font available in the system. + +
    + diff --git a/hlp/ru/bwidget/Separator.html b/hlp/ru/bwidget/Separator.html new file mode 100644 index 0000000..c015e0a --- /dev/null +++ b/hlp/ru/bwidget/Separator.html @@ -0,0 +1,77 @@ + +Separator + +
    NAME
    +
    Separator + - 3D separator widget +
    +
    +
    CREATION
    +
    Separator pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + +
      -background or -bg  -orient
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + +
      -relief
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    +


    +DESCRIPTION
    +

    + +Separator is a widget that display an horizontal or vertical 3-D line. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -relief
    +
    + +Specifies the relief of the Separator. Must be groove (the default) or ridge. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    + diff --git a/hlp/ru/bwidget/SpinBox.html b/hlp/ru/bwidget/SpinBox.html new file mode 100644 index 0000000..2c510dc --- /dev/null +++ b/hlp/ru/bwidget/SpinBox.html @@ -0,0 +1,250 @@ + +SpinBox + +
    NAME
    +
    SpinBox + - SpinBox widget +
    +
    +
    CREATION
    +
    SpinBox pathName ?option value...?
    +
    +
    +
    OPTIONS from ArrowButton
    +
    + + + + + + + + + + + + +
      -background or -bg  -disabledforeground
      -foreground or -fg  -repeatdelay
      -repeatinterval  -state
    +
    +
    +
    OPTIONS from Entry
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -command  -disabledforeground
      -dragenabled  -dragendcmd
      -dragevent  -draginitcmd
      -dragtype  -dropcmd
      -dropenabled  -dropovercmd
      -droptypes  -editable
      -entrybg (see -background)  -entryfg (see -foreground)
      -exportselection  -font
      -helptext  -helptype
      -helpvar  -highlightbackground
      -highlightcolor  -highlightthickness
      -insertbackground  -insertborderwidth
      -insertofftime  -insertontime
      -insertwidth  -justify
      -selectbackground  -selectborderwidth
      -selectforeground  -show
      -state  -takefocus
      -text  -textvariable
      -width  -xscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + +
      -modifycmd
      -range
      -values
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getvalue +
    +
    pathName setvalue + index +
    +
    +


    +DESCRIPTION
    +

    + +SpinBox widget enables the user to select a value among a list given by the values +option or a set of values defined by a mininum, a maximum and an increment. +Notice that range option defines a list of values, so getvalue and +setvalue work with both values and range. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -modifycmd
    +
    + +Specifies a Tcl command called when the user modify the value of the SpinBox. +
    +
    +
    -range
    +
    + +Specifies a list of three intergers (or real) describing the minimum, maximum and increment +of the SpinBox. +
    +
    +
    -values
    +
    + +Specifies the values accepted by the SpinBox. This option takes precedence over +range option. +
    +
    +

    +WIDGET COMMAND
    +
    pathName bind + ?arg...? +
    + +Set bindings on the entry widget. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getvalue +
    + +Returns the index of the current text of the SpinBox in the list of values, +or -1 if it doesn't match any value. + +
    +
    pathName setvalue + index +
    + +Set the text of the SpinBox to the value indicated by index in the list of values. +index may be specified in any of the following forms: +

    +

    +
    +last +
    +Specifies the last element of the list of values. +
    first +
    +Specifies the first element of the list of values. +
    +next +
    +Specifies the element following the current (ie returned by getvalue) in the list +of values. +
    previous +
    +Specifies the element preceding the current (ie returned by getvalue) in the list +of values. +
    +@number +
    +Specifies the integer index in the list of values. +
    + +
    +

    BINDINGS

    + +When Entry of the SpinBox has the input focus, it has the following bindings, in addition +to the default Entry bindings: +
      +
    • Page up set the value of the SpinBox to the last value. +
    • Page down set the value of the SpinBox to the first value. +
    • Arrow up set the value of the SpinBox to the next value. +
    • Arrow down set the value of the SpinBox to the previous value. +
    + + diff --git a/hlp/ru/bwidget/TitleFrame.html b/hlp/ru/bwidget/TitleFrame.html new file mode 100644 index 0000000..c1b8261 --- /dev/null +++ b/hlp/ru/bwidget/TitleFrame.html @@ -0,0 +1,107 @@ + +TitleFrame + +
    NAME
    +
    TitleFrame + - Frame with a title +
    +
    +
    CREATION
    +
    TitleFrame pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -font
      -foreground or -fg
      -relief
      -text
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + +
      -baseline
      -ipad
      -side
    +
    +
    +
    WIDGET COMMAND
    +
    pathName cget + option +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName getframe +
    +
    +


    +DESCRIPTION
    +

    + +TitleFrame enables user to create a frame with a title like XmFrame Motif widget. +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -baseline
    +
    + +Specifies the vertical alignment of the title: top, center or bottom. +
    +
    +
    -ipad
    +
    + +Specifies a pad between the border of the frame and the user frame. +The value is in screen units. +
    +
    +
    -side
    +
    + +Specifies the horizontal alignment of the title: left, center or right. +
    +
    +

    +WIDGET COMMAND
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName getframe +
    + +Return the frame where the user can create any other widget. +
    + diff --git a/hlp/ru/bwidget/Tree.html b/hlp/ru/bwidget/Tree.html new file mode 100644 index 0000000..6d2b3d2 --- /dev/null +++ b/hlp/ru/bwidget/Tree.html @@ -0,0 +1,696 @@ + +Tree + +
    NAME
    +
    Tree + - Tree widget +
    +
    +
    CREATION
    +
    Tree pathName ?option value...?
    +
    +
    +
    STANDARD OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
      -background or -bg  -borderwidth or -bd
      -cursor
      -highlightbackground
      -highlightcolor
      -highlightthickness
      -relief
      -selectbackground
      -selectforeground
      -takefocus
      -xscrollcommand
      -yscrollcommand
    +
    +
    +
    WIDGET-SPECIFIC OPTIONS
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      -closecmd
      -deltax
      -deltay
      -dragenabled
      -dragendcmd
      -dragevent
      -draginitcmd
      -dragtype
      -dropcmd
      -dropenabled
      -dropovercmd
      -dropovermode
      -droptypes
      -height
      -linesfill
      -linestipple
      -opencmd
      -padx
      -redraw
      -showlines
      -width
    +
    +
    +
    WIDGET COMMAND
    +
    pathName bindImage + event + script +
    +
    pathName bindText + event + script +
    +
    pathName cget + option +
    +
    pathName closetree + node +
    +
    pathName configure + ?option? ?value option value ...? +
    +
    pathName delete + ?arg...? +
    +
    pathName edit + node + text + ?verifycmd? + ?clickres? + ?select? +
    +
    pathName exists + node +
    +
    pathName index + node +
    +
    pathName insert + index + parent + node + ?option value...? +
    +
    pathName itemcget + node + option +
    +
    pathName itemconfigure + node + ?option? ?value option value ...? +
    +
    pathName move + parent + node + index +
    +
    pathName nodes + node + ?first? + ?last? +
    +
    pathName opentree + node +
    +
    pathName parent + node +
    +
    pathName reorder + node + neworder +
    +
    pathName see + node +
    +
    pathName selection + cmd + ?arg...? +
    +
    pathName visible + node +
    +
    pathName xview + ?arg...? +
    +
    pathName yview + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +Tree widget uses canvas to display a hierarchical list of items (called nodes). +Each node is composed of a label with its own font and foreground attributes, and an optional +image or window. Each node can have a list of subnodes, which can be collapsed or expanded. +Each node is drawn in a single line, whose height is defined by the +deltay option, so they must have at most this height. +A node is uniquely identified by a string given at creation (by the +insert command). The node named root is the root of +the tree and is not drawn. +The tree structure is directly maintained by the widget. + +

    +


    +WIDGET-SPECIFIC OPTIONS
    +
    -closecmd
    +
    + +Specifies a command to be called when user close a node. The +closed node is appended to the command. + +
    +
    +
    -deltax
    +
    + +Specifies horizontal indentation between a node and its children. + +
    +
    +
    -deltay
    +
    + +Specifies vertical size of the nodes. + +
    +
    +
    -dragenabled
    +
    +A boolean specifying if drag is enabled. +
    +
    +
    -dragendcmd
    +
    + +Specifies a command to be called when drag ended. +dragendcmd must be a command conforming to the description of the +option dragendcmd of DragSite::register. + +
    +
    +
    -dragevent
    +
    + +Specifies the number of the mouse button associated to the drag. +Must be 1, 2 or 3. + +
    +
    +
    -draginitcmd
    +
    + +Tree has a command wrapper for drag-init events. This command refused the drag +if no node is designated. In other cases: +
    If draginitcmd is empty, it returns: +
      +
    • the value of option dragtype or TREE_NODE if empty as the data type, +
    • {copy move link} as the operations, +
    • the node identifier as the data. +
    +If draginitcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the tree, +
    • the identifier of the dragged node, +
    • the toplevel created to represent dragged data. +
    +and must return a value conforming to draginitcmd option described in +DragSite::register. + +
    +
    +
    -dragtype
    +
    + +Specifies an alternate type of dragged object. + +
    +
    +
    -dropcmd
    +
    + +Tree has a command wrapper for drop events. This command stops auto scrolling +and extract node and position. +
    If dropcmd is not empty, it is called with the following arguments: +
      +
    • the pathname of the tree, +
    • the pathname of the drag source, +
    • a list describing where the drop occurs. It can be: +
        +
      • {widget}, +
      • {node node} or +
      • {position node index}. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    + + +
    +
    +
    -dropenabled
    +
    +A boolean specifying if drop is enabled. +
    +
    +
    -dropovercmd
    +
    + +Tree has a command wrapper for drag-over events. This command enables auto scrolling +and position extraction during the drag-over. +If dropovercmd is not empty, the command is called with the following aguments: +
      +
    • the pathname of the tree, +
    • the pathname of the drag source, +
    • a list describing where the drop can occur, whose elements are: +
        +
      • the string widget if dropovertype option contains w, else empty string. +
      • the targeted node if drag icon points a node and dropovertype option contains n, else empty string. +
      • a list containing a node and the position within the children of the node where drag +icon points to if dropovertype option contains p, else empty string. +
      • optionally, the preferred method if drop can occur both inside a node and between two +nodes. The value is position or node. +
      +
    • the current operation, +
    • the data type, +
    • the data. +
    +The command must return a list with two elements: +
      +
    • the drop status, conforming to those described in dropovercmd option of +DropSite::register, +
    • the choosen method: widget, node or position. +
    + +
    +
    +
    -dropovermode
    +
    + +Specifies the type of drop-over interaction. Must be a combination of +w, which specifies that drop can occurs everywhere on widget, +p, which specifies that drop can occurs between two nodes, +and n, which specifies that drop occurs inside nodes. + +
    +
    +
    -droptypes
    +
    + +Specifies a list of accepted dropped object/operation. +See option droptypes of +DropSite::register. +for more infromation. + +
    Default is TREE_NODE with operations copy and move. + +
    +
    +
    -height
    +
    + +Specifies the desired height for the tree in units of deltay pixels. + +
    +
    +
    -linesfill
    +
    + +Specifies a foreground color for the lines between nodes. + +
    +
    +
    -linestipple
    +
    + +Specifies a stipple bitmap for the lines between nodes. + +
    +
    +
    -opencmd
    +
    + +Specifies a command to be called when user open a node. The +opened node is appended to the command. + +
    +
    +
    -padx
    +
    + +Specifies distance between image or window and text of the nodes. + +
    +
    +
    -redraw
    +
    + +Specifies wether or not the tree should be redrawn when entering idle. +Set it to false if you call update while modifying the tree. + +
    +
    +
    -showlines
    +
    + +Specifies whether or not lines should be drawn between nodes. + +
    +
    +
    -width
    +
    + +Specifies the desired width for the tree in units of 8 pixels. + +
    +
    +

    +WIDGET COMMAND
    +
    pathName bindImage + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the image of a node. +The node idenfier on which the event occurs is appended to the command. + +
    +
    pathName bindText + event + script +
    + +This command associates a command to execute whenever the event +sequence given by event occurs on the label of a node. +The node idenfier on which the event occurs is appended to the command. + +
    +
    pathName cget + option +
    + +Returns the current value of the configuration option given by option. +Option may have any of the values accepted by the creation command. +
    +
    pathName closetree + node +
    + +This command close all the subtree given by node (recurse +through the tree starting at node and set open option to 0) + +
    +
    pathName configure + ?option? ?value option value ...? +
    + +Query or modify the configuration options of the widget. If no option is specified, +returns a list describing all of the available options for pathName. +If option is specified with no value, then the command returns a list +describing the one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If one or +more option-value pairs are specified, then the command modifies the given widget +option(s) to have the given value(s); in this case the command returns an empty string. +Option may have any of the values accepted by the creation command. +Read-only options are not be modified. + +
    +
    pathName delete + ?arg...? +
    + +Deletes all nodes (and children of them) in arg. arg can be a list +of nodes or a list of list of nodes. +To delete all the tree, do $pathName delete [$pathName nodes root]. + +
    +
    pathName edit + node + text + ?verifycmd? + ?clickres? + ?select? +
    + +Provides a way for the user to edit in place the label of a node. This is +possible only if node is visible (all its parents are open). +
    The command takes the initial text as argument and does not modify the label of the +edited node, but returns an empty string if edition is canceled, or the typed text +if edition is accepted. +
    When editing, the user can cancel by pressing Escape, or accept by pressing Return. +
    clickres specifies what to do if the user click outside the editable area. +If clickres is 0 (the default), the edition is canceled. +If clickres is 1, the edition is accepted. +In all other case, the edition continues. +
    If edition is accepted and modifycmd is not empty, then it is called with +the new text as argument and must return 1 to accept the new text, 0 to refuse it +and continue edition. +
    select specifies wether or not the initial text should be selected. Default is 1. + +
    +
    pathName exists + node +
    + +Returns whether or not node exists in the tree. + +
    +
    pathName index + node +
    + +Returns the position of node in its parent. + +
    +
    pathName insert + index + parent + node + ?option value...? +
    + +Inserts a new node identified by node in the children list of parent +at position index. + +

    +

    -data
    +
    + +User data associated to the node. + +
    +
    +
    -drawcross
    +
    + +Specifies how the cross used to expand or collapse the children of a node +should be drawn. +Must be one of auto, allways or never. +
    If auto, the cross is drawn only if the node has children. +If allways, the cross is always drawn. +If never, the cross is never drawn. + +
    +
    +
    -fill
    +
    + +Specifies the foreground color of the label of the node. + +
    +
    +
    -font
    +
    + +Specifies a font for the label of the node. + +
    +
    +
    -image
    +
    + +Specifies an image to display at the left of the label of the node. +window option override image. +
    +
    +
    -open
    +
    + +Specifies wether or not the children of the node should be drawn. + +
    +
    +
    -text
    +
    + +Specifies the label of the node. + +
    +
    +
    -window
    +
    + +Specifies a pathname to display at the left of the label of the node. +window option override image. +
    +
    +
    +
    pathName itemcget + node + option +
    + +Returns the current value of a configuration option for the item. +Option may have any of the values accepted by the item creation command. + +
    +
    pathName itemconfigure + node + ?option? ?value option value ...? +
    + +This command is similar to the configure command, except that it applies to the +options for an individual item, whereas configure applies to the options for +the widget as a whole. Options may have any of the values accepted by the +item creation widget command. If options are specified, options are modified as indicated +in the command and the command returns an empty string. If no options are specified, +returns a list describing the current options for the item. +Read-only options are not be modified. + +
    +
    pathName move + parent + node + index +
    + +Moves node to the children list of parent at position index. +parent can not be a descendant of node. + +
    +
    pathName nodes + node + ?first? + ?last? +
    + +Returns parts of the children of node, following first and last.
    +If first and last are omitted, returns the list of all children. +If first is specified and last omitted, returns the child at index +first, or an empty string if first refers to a non-existent element. +If first and last are specified, the command returns a list whose elements +are all of the children between first and last, +inclusive. Both first and last may have any of the standard +forms for indices. + +
    +
    pathName opentree + node +
    + +This command open all the subtree given by node (recurse +through the tree starting at node and set open option to 1) + +
    +
    pathName parent + node +
    + +Returns the parent of node. + +
    +
    pathName reorder + node + neworder +
    + +Modifies the order of children of node given by neworder. Children of +node that do not appear in neworder are no moved. + +
    +
    pathName see + node +
    + +Arrange the scrolling area to make node visible. + +
    +
    pathName selection + cmd + ?arg...? +
    + +Modifies the list of selected nodes following cmd: +
    +
    clear +
    remove all nodes of the selection. +
    set +
    set the selection to all nodes in arg +
    add +
    add all nodes of arg in the selection +
    remove +
    remove all nodes of arg of the selection +
    get +
    return the current selected nodes +
    + +
    +
    pathName visible + node +
    + +Returns whether or not node is visible (all its parents are open). + +
    +
    pathName xview + ?arg...? +
    + +Standard command to enable horizontal scrolling of pathName. + +
    +
    pathName yview + ?arg...? +
    + +Standard command to enable vertical scrolling of pathName. + +
    + diff --git a/hlp/ru/bwidget/Widget.html b/hlp/ru/bwidget/Widget.html new file mode 100644 index 0000000..e6c0340 --- /dev/null +++ b/hlp/ru/bwidget/Widget.html @@ -0,0 +1,409 @@ + +Widget + + Under construction ...
    +
    NAME
    +
    Widget + - The Widget base class +
    +
    +
    COMMAND
    +
    Widget::addmap + class + subclass + subpath + options +
    +
    Widget::bwinclude + class + subclass + subpath + ?arg...? +
    +
    Widget::cget + path + option +
    +
    Widget::configure + path + options +
    +
    Widget::declare + class + optlist +
    +
    Widget::destroy + path +
    +
    Widget::focusNext + w +
    +
    Widget::focusOK + w +
    +
    Widget::focusPrev + w +
    +
    Widget::generate-doc + dir + widgetlist +
    +
    Widget::generate-widget-doc + class + iscmd + file +
    +
    Widget::getoption + path + option +
    +
    Widget::hasChanged + path + option + pvalue +
    +
    Widget::init + class + path + options +
    +
    Widget::setoption + path + option + value +
    +
    Widget::subcget + path + subwidget +
    +
    Widget::syncoptions + class + subclass + subpath + options +
    +
    Widget::tkinclude + class + tkwidget + subpath + ?arg...? +
    +
    +


    +DESCRIPTION
    +

    + +The Widget namespace handle data associated to all BWidget and provide commands +to easily define BWidget. +
    For commands can be used to define a BWidget: +tkinclude, bwinclude, declare, addmap and syncoptions. +Here is the definition of ComboBox widget: +

    +

    + + +
    +namespace eval ComboBox {
    +    # We're using ArrowButton, Entry and LabelFrame
    +    ArrowButton::use
    +    Entry::use
    +    LabelFrame::use
    +
    +    # Include resources of LabelFrame
    +    Widget::bwinclude ComboBox LabelFrame .labf \ 
    +        rename     {-text -label} \ 
    +        remove     {-focus} \ 
    +        prefix     {label -justify -width -anchor -height -font} \ 
    +        initialize {-relief sunken -borderwidth 2}
    +
    +    # Include resources of Entry
    +    Widget::bwinclude ComboBox Entry .e \ 
    +        remove {-relief -bd -borderwidth -bg -fg} \ 
    +        rename {-foreground -entryfg -background -entrybg}
    +
    +    # Declare new resources
    +    Widget::declare ComboBox {
    +        {-height      TkResource 0  0 listbox}
    +        {-values      String     "" 0}
    +        {-modifycmd   String     "" 0}
    +        {-postcommand String     "" 0}
    +    }
    +
    +    # Map resources to subwidget
    +    Widget::addmap ComboBox "" :cmd {-background {}}
    +    Widget::addmap ComboBox ArrowButton .a \ 
    +        {-foreground {} -background {} -disabledforeground {} -state {}}
    +
    +    # Synchronize subwidget options
    +    Widget::syncoptions ComboBox Entry .e {-text {}}
    +    Widget::syncoptions ComboBox LabelFrame .labf {-label -text -underline {}}
    +
    +    proc use {} {}
    +}
    +
    + +

    +

    +COMMAND
    +
    Widget::addmap + class + subclass + subpath + options +
    + +This command map some resources to subwidget. +Mapped resources automatically configure subwidget when widget is configured. +
      +
    • class is the class of the new BWidget +
    • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget) +
    • subpath is the path of the subwidget +
    • options is the list {option realres ...} of options to map to subwidget +
    +
    +
    Widget::bwinclude + class + subclass + subpath + ?arg...? +
    + +This command includes into a new BWidget the resources of another BWidget. +Arguments are: +
      +
    • class class of the new widget +
    • subclass class name of the BWidget to be included +
    • subpath path of the widget to configure when BWidget is configured +
    • options is: +
        +
      • include {option option ...} +
        list of options to include (all if not defined) +
      • remove {option option ...} +
        list of options to remove +
      • rename {option name option name ...} +
        list of options to rename +
      • prefix {prefix option option ...} +
        pefix all option by prefix +
      • initialize {option value option value ...} +
        default value of options +
      • readonly {option value option value ...} +
        new readonly flag +
    +
    +
    Widget::cget + path + option +
    + +Returns the value of option of BWidget path. cget tests the option +existence and takes care of synchronization with subwidget. +Typically called by the BWidget cget command. + +
    +
    Widget::configure + path + options +
    +Description text +
    +
    Widget::declare + class + optlist +
    + +This command declare new resources for a BWidget. +
      +
    • class is class of the new widget +
    • options is the list describing new options. Each new option is a list +{option type value ro ?args?} where: +
        +
      • option is the name of the option +
      • type is the type of the option +
      • value is the default value of the option +
      • ro is the readonly flag of the option +
      • args depends on type +
    +
    +type can be: +
    +
    +
    TkResource
    +
    +value of option denotes a resource of a Tk widget. args must be class or +{class realoption}. class is the creation command of the Tk widget, e.g. +entry. +The second form must be used if option has not the same name in Tk widget, +but realoption. +
    If value is empty, it is initialized to the default value of the Tk widget. +
    + +
    BwResource
    +
    +value of option denotes a resource of a BWidget. args must be class or +{class realoption}. class is the name of the namespace of the BWidget, e.g. +LabelFrame. +The second form must be used if option has not the same name in BWidget, +but realoption. +
    If value is empty, it is initialized to the default value of the BWidget. +
    + +
    Int
    +
    value of option is an integer. +args can be {?min? ?max?} to force it to be in a range. The test is +[expr $option>$min] && [expr $option<$max] so +if args is {0 10}, value must be beetween 0 and 10 exclude, +if args is {=0 =10} , value must be beetween 0 and 10 include. +
    + +
    Boolean
    +
    value of option is a boolean. True values can be 1, true or yes. +False values can be 0, false or no. Widget::cget always return +0 or 1. +
    + +
    Enum
    +
    +value of option is a element of a enumeration. args must be the list +of enumeration, e.g. {top left bottom right}. +
    + +
    Flag
    +
    +value of option is a combination of a set of chars. args must be a +string defining the set. +
    + +
    String
    +
    +
    value of option is any uncontrolled string. +
    + +
    Synonym
    +
    +
    option is a synonym of option args. value has no effect here. +
    + +
    +
    +
    Widget::destroy + path +
    +Description text +
    +
    Widget::focusNext + w +
    +Description text +
    +
    Widget::focusOK + w +
    +Description text +
    +
    Widget::focusPrev + w +
    +Description text +
    +
    Widget::generate-doc + dir + widgetlist +
    +Description text +
    +
    Widget::generate-widget-doc + class + iscmd + file +
    +Description text +
    +
    Widget::getoption + path + option +
    + +Returns the value of option of BWidget path. This command does not test +option existence, does not handle synonym and does not take care of synchronization with +subwidget. + +
    +
    Widget::hasChanged + path + option + pvalue +
    +Description text +
    +
    Widget::init + class + path + options +
    +Description text +
    +
    Widget::setoption + path + option + value +
    + +Set the value of option of BWidget path without option test, subwidget mapping, +synonym handling and does not set the modification flag. + +
    +
    Widget::subcget + path + subwidget +
    + +Returns the list of all option/value of BWidget path that are mapped to subwidget. + +
    +
    Widget::syncoptions + class + subclass + subpath + options +
    + +This command synchronize options value of a subwidget. +Used when an option of a subwidget is modified out of the BWidget configure command. +
      +
    • class is the class of the new BWidget +
    • subclass is the class the subwidget (BWidget class, e.g Entry, or empty for Tk widget) +
    • subpath is the path of the subwidget +
    • options is the list {option realres ...} of options to synchronize +with subwidget +
    +
    +
    Widget::tkinclude + class + tkwidget + subpath + ?arg...? +
    + +This command includes into a new BWidget the resources of a Tk widget. +Arguments are: +
      +
    • class class of the new widget +
    • tkwidger command name of the Tk widget to be included +
    • subpath path of the widget to configure when BWidget is configured +
    • options is: +
        +
      • include {option option ...} +
        list of options to include (all if not defined) +
      • remove {option option ...} +
        list of options to remove +
      • rename {option name option name ...} +
        list of options to rename +
      • prefix {prefix option option ...} +
        pefix all option by prefix +
      • initialize {option value option value ...} +
        default value of options +
      • readonly {option value option value ...} +
        new readonly flag +
    +
    + diff --git a/hlp/ru/bwidget/bw.toc.html b/hlp/ru/bwidget/bw.toc.html new file mode 100644 index 0000000..e6ccfdc --- /dev/null +++ b/hlp/ru/bwidget/bw.toc.html @@ -0,0 +1,34 @@ +BWidget +Label
    +Entry
    +Button
    +ArrowButton
    +ProgressBar
    +ScrollView
    +Separator
    +MainFrame
    +LabelFrame
    +TitleFrame
    +ScrolledWindow
    +ScrollableFrame
    +PanedWindow
    +ButtonBox
    +PagesManager
    +NoteBook
    +Dialog
    +LabelEntry
    +ComboBox
    +SpinBox
    +Tree
    +ListBox
    +MessageDlg
    +ProgressDlg
    +PasswdDlg
    +SelectFont
    +SelectColor
    +Widget
    +DynamicHelp
    +DragSite
    +DropSite
    +BWidget
    + diff --git a/hlp/ru/bwidget/navtree.html b/hlp/ru/bwidget/navtree.html new file mode 100644 index 0000000..d6ca56d --- /dev/null +++ b/hlp/ru/bwidget/navtree.html @@ -0,0 +1,39 @@ + +Brief description
    +Simple Widgets
    +  Label
    +  Entry
    +  Button
    +  ArrowButton
    +  ProgressBar
    +  ScrollView
    +  Separator
    +Manager Widgets
    +  MainFrame
    +  LabelFrame
    +  TitleFrame
    +  ScrolledWindow
    +  ScrollableFrame
    +  PanedWindow
    +  ButtonBox
    +  PagesManager
    +  NoteBook
    +  Dialog
    +Composite Widgets
    +  LabelEntry
    +  ComboBox
    +  SpinBox
    +  Tree
    +  ListBox
    +  MessageDlg
    +  ProgressDlg
    +  PasswdDlg
    +  SelectFont
    +  SelectColor
    +Commands Classes
    +  Widget
    +  DynamicHelp
    +  DragSite
    +  DropSite
    +  BWidget
    + diff --git a/hlp/ru/bwidget/options.htm b/hlp/ru/bwidget/options.htm new file mode 100644 index 0000000..0c6f494 --- /dev/null +++ b/hlp/ru/bwidget/options.htm @@ -0,0 +1,449 @@ +Tk Built-In Commands - options manual page + +
    +
    NAME +
    options - Standard options supported by widgets
    +
    DESCRIPTION +
    +
    -activebackground, activeBackground, Foreground +
    -activeborderwidth, activeBorderWidth, BorderWidth +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -exportselection, exportSelection, ExportSelection +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -insertbackground, insertBackground, Foreground +
    -insertborderwidth, insertBorderWidth, BorderWidth +
    -insertofftime, insertOffTime, OffTime +
    -insertontime, insertOnTime, OnTime +
    -insertwidth, insertWidth, InsertWidth +
    -jump, jump, Jump +
    -justify, justify, Justify +
    -orient, orient, Orient +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -repeatdelay, repeatDelay, RepeatDelay +
    -repeatinterval, repeatInterval, RepeatInterval +
    -selectbackground, selectBackground, Foreground +
    -selectborderwidth, selectBorderWidth, BorderWidth +
    -selectforeground, selectForeground, Background +
    -setgrid, setGrid, SetGrid +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -troughcolor, troughColor, Background +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    -xscrollcommand, xScrollCommand, ScrollCommand +
    -yscrollcommand, yScrollCommand, ScrollCommand +
    +
    KEYWORDS +

    +

    NAME

    +options - Standard options supported by widgets +

    DESCRIPTION

    +This manual entry describes the common configuration options supported +by widgets in the Tk toolkit. Every widget does not necessarily support +every option (see the manual entries for individual widgets for a list +of the standard options supported by that widget), but if a widget does +support an option with one of the names listed below, then the option +has exactly the effect described below. +

    +In the descriptions below, ``Command-Line Name'' refers to the +switch used in class commands and configure widget commands to +set this value. For example, if an option's command-line switch is +-foreground and there exists a widget .a.b.c, then the +command +

    .a.b.c  configure  -foreground black
    +may be used to specify the value black for the option in the +the widget .a.b.c. Command-line switches may be abbreviated, +as long as the abbreviation is unambiguous. +``Database Name'' refers to the option's name in the option database (e.g. +in .Xdefaults files). ``Database Class'' refers to the option's class value +in the option database. +
    +
    Command-Line Name: -activebackground +
    Database Name: activeBackground +
    Database Class: Foreground +
    Specifies background color to use when drawing active elements. +An element (a widget or portion of a widget) is active if the +mouse cursor is positioned over the element and pressing a mouse button +will cause some action to occur. +If strict Motif compliance has been requested by setting the +tk_strictMotif variable, this option will normally be +ignored; the normal background color will be used instead. +For some elements on Windows and Macintosh systems, the active color +will only be used while mouse button 1 is pressed over the element. +

    Command-Line Name: -activeborderwidth +
    Database Name: activeBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating +the width of the 3-D border drawn around active elements. See above for +definition of active elements. +The value may have any of the forms acceptable to Tk_GetPixels. +This option is typically only available in widgets displaying more +than one element at a time (e.g. menus but not buttons). +

    Command-Line Name: -activeforeground +
    Database Name: activeForeground +
    Database Class: Background +
    Specifies foreground color to use when drawing active elements. +See above for definition of active elements. +

    Command-Line Name: -anchor +
    Database Name: anchor +
    Database Class: Anchor +
    Specifies how the information in a widget (e.g. text or a bitmap) +is to be displayed in the widget. +Must be one of the values n, ne, e, se, +s, sw, w, nw, or center. +For example, nw means display the information such that its +top-left corner is at the top-left corner of the widget. +

    Command-Line Name: -background or -bg +
    Database Name: background +
    Database Class: Background +
    Specifies the normal background color to use when displaying the +widget. +

    Command-Line Name: -bitmap +
    Database Name: bitmap +
    Database Class: Bitmap +
    Specifies a bitmap to display in the widget, in any of the forms +acceptable to Tk_GetBitmap. +The exact way in which the bitmap is displayed may be affected by +other options such as anchor or justify. +Typically, if this option is specified then it overrides other +options that specify a textual value to display in the widget; +the bitmap option may be reset to an empty string to re-enable +a text display. +In widgets that support both bitmap and image options, +image will usually override bitmap. +

    Command-Line Name: -borderwidth or -bd +
    Database Name: borderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the outside of the widget (if such a +border is being drawn; the relief option typically determines +this). The value may also be used when drawing 3-D effects in the +interior of the widget. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -cursor +
    Database Name: cursor +
    Database Class: Cursor +
    Specifies the mouse cursor to be used for the widget. +The value may have any of the forms acceptable to Tk_GetCursor. +

    Command-Line Name: -disabledforeground +
    Database Name: disabledForeground +
    Database Class: DisabledForeground +
    Specifies foreground color to use when drawing a disabled element. +If the option is specified as an empty string (which is typically the +case on monochrome displays), disabled elements are drawn with the +normal foreground color but they are dimmed by drawing them +with a stippled fill pattern. +

    Command-Line Name: -exportselection +
    Database Name: exportSelection +
    Database Class: ExportSelection +
    Specifies whether or not a selection in the widget should also be +the X selection. +The value may have any of the forms accepted by Tcl_GetBoolean, +such as true, false, 0, 1, yes, or no. +If the selection is exported, then selecting in the widget deselects +the current X selection, selecting outside the widget deselects any +widget selection, and the widget will respond to selection retrieval +requests when it has a selection. The default is usually for widgets +to export selections. +

    Command-Line Name: -font +
    Database Name: font +
    Database Class: Font +
    Specifies the font to use when drawing text inside the widget. +

    Command-Line Name: -foreground or -fg +
    Database Name: foreground +
    Database Class: Foreground +
    Specifies the normal foreground color to use when displaying the widget. +

    Command-Line Name: -highlightbackground +
    Database Name: highlightBackground +
    Database Class: HighlightBackground +
    Specifies the color to display in the traversal highlight region when +the widget does not have the input focus. +

    Command-Line Name: -highlightcolor +
    Database Name: highlightColor +
    Database Class: HighlightColor +
    Specifies the color to use for the traversal highlight rectangle that is +drawn around the widget when it has the input focus. +

    Command-Line Name: -highlightthickness +
    Database Name: highlightThickness +
    Database Class: HighlightThickness +
    Specifies a non-negative value indicating the width of the highlight +rectangle to draw around the outside of the widget when it has the +input focus. +The value may have any of the forms acceptable to Tk_GetPixels. +If the value is zero, no focus highlight is drawn around the widget. +

    Command-Line Name: -image +
    Database Name: image +
    Database Class: Image +
    Specifies an image to display in the widget, which must have been +created with the image create command. +Typically, if the image option is specified then it overrides other +options that specify a bitmap or textual value to display in the widget; +the image option may be reset to an empty string to re-enable +a bitmap or text display. +

    Command-Line Name: -insertbackground +
    Database Name: insertBackground +
    Database Class: Foreground +
    Specifies the color to use as background in the area covered by the +insertion cursor. This color will normally override either the normal +background for the widget (or the selection background if the insertion +cursor happens to fall in the selection). +

    Command-Line Name: -insertborderwidth +
    Database Name: insertBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -insertofftime +
    Database Name: insertOffTime +
    Database Class: OffTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``off'' in each blink cycle. +If this option is zero then the cursor doesn't blink: it is on +all the time. +

    Command-Line Name: -insertontime +
    Database Name: insertOnTime +
    Database Class: OnTime +
    Specifies a non-negative integer value indicating the number of +milliseconds the insertion cursor should remain ``on'' in each blink cycle. +

    Command-Line Name: -insertwidth +
    Database Name: insertWidth +
    Database Class: InsertWidth +
    Specifies a value indicating the total width of the insertion cursor. +The value may have any of the forms acceptable to Tk_GetPixels. +If a border has been specified for the insertion +cursor (using the insertBorderWidth option), the border +will be drawn inside the width specified by the insertWidth +option. +

    Command-Line Name: -jump +
    Database Name: jump +
    Database Class: Jump +
    For widgets with a slider that can be dragged to adjust a value, +such as scrollbars, this option determines when +notifications are made about changes in the value. +The option's value must be a boolean of the form accepted by +Tcl_GetBoolean. +If the value is false, updates are made continuously as the +slider is dragged. +If the value is true, updates are delayed until the mouse button +is released to end the drag; at that point a single notification +is made (the value ``jumps'' rather than changing smoothly). +

    Command-Line Name: -justify +
    Database Name: justify +
    Database Class: Justify +
    When there are multiple lines of text displayed in a widget, this +option determines how the lines line up with each other. +Must be one of left, center, or right. +Left means that the lines' left edges all line up, center +means that the lines' centers are aligned, and right means +that the lines' right edges line up. +

    Command-Line Name: -orient +
    Database Name: orient +
    Database Class: Orient +
    For widgets that can lay themselves out with either a horizontal +or vertical orientation, such as scrollbars, this option specifies +which orientation should be used. Must be either horizontal +or vertical or an abbreviation of one of these. +

    Command-Line Name: -padx +
    Database Name: padX +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the X-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will +add this amount to the width it would normally need (as determined +by the width of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space to the left and/or right of what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -pady +
    Database Name: padY +
    Database Class: Pad +
    Specifies a non-negative value indicating how much extra space +to request for the widget in the Y-direction. +The value may have any of the forms acceptable to Tk_GetPixels. +When computing how large a window it needs, the widget will add +this amount to the height it would normally need (as determined by +the height of the things displayed in the widget); if the geometry +manager can satisfy this request, the widget will end up with extra +internal space above and/or below what it displays inside. +Most widgets only use this option for padding text: if they are +displaying a bitmap or image, then they usually ignore padding +options. +

    Command-Line Name: -relief +
    Database Name: relief +
    Database Class: Relief +
    Specifies the 3-D effect desired for the widget. Acceptable +values are raised, sunken, flat, ridge, +solid, and groove. +The value +indicates how the interior of the widget should appear relative +to its exterior; for example, raised means the interior of +the widget should appear to protrude from the screen, relative to +the exterior of the widget. +

    Command-Line Name: -repeatdelay +
    Database Name: repeatDelay +
    Database Class: RepeatDelay +
    Specifies the number of milliseconds a button or key must be held +down before it begins to auto-repeat. Used, for example, on the +up- and down-arrows in scrollbars. +

    Command-Line Name: -repeatinterval +
    Database Name: repeatInterval +
    Database Class: RepeatInterval +
    Used in conjunction with repeatDelay: once auto-repeat +begins, this option determines the number of milliseconds between +auto-repeats. +

    Command-Line Name: -selectbackground +
    Database Name: selectBackground +
    Database Class: Foreground +
    Specifies the background color to use when displaying selected +items. +

    Command-Line Name: -selectborderwidth +
    Database Name: selectBorderWidth +
    Database Class: BorderWidth +
    Specifies a non-negative value indicating the width +of the 3-D border to draw around selected items. +The value may have any of the forms acceptable to Tk_GetPixels. +

    Command-Line Name: -selectforeground +
    Database Name: selectForeground +
    Database Class: Background +
    Specifies the foreground color to use when displaying selected +items. +

    Command-Line Name: -setgrid +
    Database Name: setGrid +
    Database Class: SetGrid +
    Specifies a boolean value that determines whether this widget controls the +resizing grid for its top-level window. +This option is typically used in text widgets, where the information +in the widget has a natural size (the size of a character) and it makes +sense for the window's dimensions to be integral numbers of these units. +These natural window sizes form a grid. +If the setGrid option is set to true then the widget will +communicate with the window manager so that when the user interactively +resizes the top-level window that contains the widget, the dimensions of +the window will be displayed to the user in grid units and the window +size will be constrained to integral numbers of grid units. +See the section GRIDDED GEOMETRY MANAGEMENT in the wm manual +entry for more details. +

    Command-Line Name: -takefocus +
    Database Name: takeFocus +
    Database Class: TakeFocus +
    Determines whether the window accepts the focus during keyboard +traversal (e.g., Tab and Shift-Tab). +Before setting the focus to a window, the traversal scripts +consult the value of the takeFocus option. +A value of 0 means that the window should be skipped entirely +during keyboard traversal. +1 means that the window should receive the input +focus as long as it is viewable (it and all of its ancestors are mapped). +An empty value for the option means that the traversal scripts make +the decision about whether or not to focus on the window: the current +algorithm is to skip the window if it is +disabled, if it has no key bindings, or if it is not viewable. +If the value has any other form, then the traversal scripts take +the value, append the name of the window to it (with a separator space), +and evaluate the resulting string as a Tcl script. +The script must return 0, 1, or an empty string: a +0 or 1 value specifies whether the window will receive +the input focus, and an empty string results in the default decision +described above. +Note: this interpretation of the option is defined entirely by +the Tcl scripts that implement traversal: the widget implementations +ignore the option entirely, so you can change its meaning if you +redefine the keyboard traversal scripts. +

    Command-Line Name: -text +
    Database Name: text +
    Database Class: Text +
    Specifies a string to be displayed inside the widget. The way in which +the string is displayed depends on the particular widget and may be +determined by other options, such as anchor or justify. +

    Command-Line Name: -textvariable +
    Database Name: textVariable +
    Database Class: Variable +
    Specifies the name of a variable. The value of the variable is a text +string to be displayed inside the widget; if the variable value changes +then the widget will automatically update itself to reflect the new value. +The way in which the string is displayed in the widget depends on the +particular widget and may be determined by other options, such as +anchor or justify. +

    Command-Line Name: -troughcolor +
    Database Name: troughColor +
    Database Class: Background +
    Specifies the color to use for the rectangular trough areas +in widgets such as scrollbars and scales. +

    Command-Line Name: -underline +
    Database Name: underline +
    Database Class: Underline +
    Specifies the integer index of a character to underline in the widget. +This option is used by the default bindings to implement keyboard +traversal for menu buttons and menu entries. +0 corresponds to the first character of the text displayed in the +widget, 1 to the next character, and so on. +

    Command-Line Name: -wraplength +
    Database Name: wrapLength +
    Database Class: WrapLength +
    For widgets that can perform word-wrapping, this option specifies +the maximum line length. +Lines that would exceed this length are wrapped onto the next line, +so that no line is longer than the specified length. +The value may be specified in any of the standard forms for +screen distances. +If this value is less than or equal to 0 then no wrapping is done: lines +will break only at newline characters in the text. +

    Command-Line Name: -xscrollcommand +
    Database Name: xScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with horizontal +scrollbars. +When the view in the widget's window changes (or +whenever anything else occurs that could change the display in a +scrollbar, such as a change in the total size of the widget's +contents), the widget will +generate a Tcl command by concatenating the scroll command and +two numbers. +Each of the numbers is a fraction between 0 and 1, which indicates +a position in the document. 0 indicates the beginning of the document, +1 indicates the end, .333 indicates a position one third the way through +the document, and so on. +The first fraction indicates the first information in the document +that is visible in the window, and the second fraction indicates +the information just after the last portion that is visible. +The command is +then passed to the Tcl interpreter for execution. Typically the +xScrollCommand option consists of the path name of a scrollbar +widget followed by ``set'', e.g. ``.x.scrollbar set'': this will cause +the scrollbar to be updated whenever the view in the window changes. +If this option is not specified, then no command will be executed. +

    Command-Line Name: -yscrollcommand +
    Database Name: yScrollCommand +
    Database Class: ScrollCommand +
    Specifies the prefix for a command used to communicate with vertical +scrollbars. This option is treated in the same way as the +xScrollCommand option, except that it is used for vertical +scrollbars and is provided by widgets that support vertical scrolling. +See the description of xScrollCommand for details +on how this option is used. + +
    +

    KEYWORDS

    +class, name, standard option, switch +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1996 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/ru/convert.tcl b/hlp/ru/convert.tcl new file mode 100644 index 0000000..ca86a62 --- /dev/null +++ b/hlp/ru/convert.tcl @@ -0,0 +1,82 @@ +###################################################### +# Tk LaTeX Editor +# Distributed under GNU Public License +# Author: Sergey Kalinin (BanZaj) banzaj@lrn.ru +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru +###################################################### + + +proc Latex2Html {} { + global tree module cmdString + set selFiles [$tree selection get] + if {[llength $selFiles] == 0} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Don't selected file"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + if {[llength $selFiles] == 1} { + if {$selFiles != ""} { + set file [$tree itemcget $selFiles -data] + } + CommandStringDialog $file + } + #puts $command +} +proc CommandStringDialog {action file} { + global nb files font color cmdString module convert_cmd preview_cmd + set w .cmd + # destroy the find window if it already exists + if {[winfo exists $w]} { + destroy $w + } + + toplevel $w + wm title $w [::msgcat::mc "Command options"] + wm resizable $w 0 0 + wm transient $w . + frame $w.frmCombo -borderwidth 1 -background $color(bg) + frame $w.frmBtn -borderwidth 1 -background $color(bg) + pack $w.frmCombo $w.frmBtn -side top -fill x + + # set combo [entry $w.frmCombo.entFind] + label $w.frmCombo.lblModule -text $module() -background $color(bg) + set combo [entry $w.frmCombo.txtString] + + pack $w.frmCombo.lblModule $combo -fill x -padx 2 -pady 2 -side top + + button $w.frmBtn.btnFind -text [::msgcat::mc "Run"]\ + -font $font(normal) -width 12 -relief groove -background $color(bg)\ + -command { + RunConverter [.cmd.frmCombo.txtString get] + } + button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"]\ + -relief groove -width 12 -font $font(normal) -background $color(bg)\ + -command "destroy $w" + pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left + + bind $w {RunConverter [.cmd.frmCombo.txtString get]} + bind $w "destroy $w" + if [info exists convert_cmd($m)] { + $combo insert end "$convert_cmd($action)" + } + if [info exists preview_cmd($m)] { + $combo insert end "$preview_cmd($action)" + } else { + $combo insert end "$module($action)" + } + + focus -force $combo +} + +proc RunConverter {string} { + global module + destroy .cmd + set pipe [open "|$module(latex2html) $string" "r"] + fileevent $pipe readable [list EndProc latex2html $pipe] + fconfigure $pipe -buffering none -blocking no +} + diff --git a/hlp/ru/links_add.html b/hlp/ru/links_add.html new file mode 100644 index 0000000..a58dfa8 --- /dev/null +++ b/hlp/ru/links_add.html @@ -0,0 +1,20 @@ +

    Добавить ссылку

    +
    + + + + + + + + + + + + + + +
    Заголовок:
    Тело новости:
    +
    + + diff --git a/hlp/ru/log b/hlp/ru/log new file mode 100644 index 0000000..e69de29 diff --git a/hlp/ru/mail.tcl b/hlp/ru/mail.tcl new file mode 100644 index 0000000..12df1c8 --- /dev/null +++ b/hlp/ru/mail.tcl @@ -0,0 +1,7 @@ +###################################################### +# Terminal +# Distributed under GNU Public License +# Author: Sergey Kalinin svk@amur.dti.ru +# Copyright (c) "DTi", 2003, http://www.amur.dti.ru +###################################################### + diff --git a/hlp/ru/projman/about.html b/hlp/ru/projman/about.html new file mode 100644 index 0000000..af99090 --- /dev/null +++ b/hlp/ru/projman/about.html @@ -0,0 +1,17 @@ + + + + about + + +

    Документация

    +

    Документация предоставлена компанией +DataX/FLORIN, Inc. +

    © Все права защищены 1992-2001. +

    Разрешается некоммерческое использование документации как целиком так и отдельных частей с разрешения авторов и с обязательной ссылкой на +DataX/FLORIN, Inc. и на +CONERO lab + + + + diff --git a/hlp/ru/projman/faq.txt b/hlp/ru/projman/faq.txt new file mode 100644 index 0000000..0ba1c71 --- /dev/null +++ b/hlp/ru/projman/faq.txt @@ -0,0 +1,60 @@ +Tcl/Tk Project Manager FAQ 0.1 + +В. Что такое ProjMan? + +О.Tcl/Tk Project Manager - это интегрированная среда программирования на +интерпретирующем языке высокого уровня Tcl/Tk, приспособленная для +создания и поддержки многофайловых проектов. + +В. Почему ProjMan лучше других IDE? + +О. * Встроенная справочная ситема позволяет разобраться в языке даже новичку. +* Простота визуального интерфейса не влияет на удобочитаемость кода. +* Адаптированность под развитые средства системы Linux делают ProjMan еще более мощным инструментом в руках опытного программиста +* Среда как и сама Linux является OpenSource. + +В. Как установить ProjMan? Что для этого нужно? + +О. Поскольку ProjMan написан непосредственно на Tcl/Tk, он способен работать +под управлением UNIX/XWindow, MSWindows, Macintosh c установленным +дистрибутивом языка Tcl/Tk(в Linux и Win32 проверенна работоспособность, +на счет других ОС дайте знать). + +Вам потребуется интерпретатор языка Tcl/Tk(более подробную информацию по +Tcl/Tk можно найти на сайте http://www.tcl-tk.org), BWidget и последняя версия дистрибутива +Tcl/Tk Project Manager(ее можно скачать с сайта http://conero.lrn.ru) + +Следуйте инструкциям по установке вашего дистрибутива ProjMan +изложенными в файле INSTALL архива. + +В. Где узнать более детальную информацию о предназначении каталогов и файлов в ProjMan? + +О. Расположение каталогов и файлов: +~/.projman - рабочий каталог +~/projman/projman.conf - файл настроек +~/.projman/*.proj - файлы проектов +~/.projman/*.tags - файлы с описанием процедур, создается с помощью CTags +~/projects/tcl - каталог с проектами + +В. Как я могу отслеживать изменения в разрабатываемом мной проекте? + +О. Встроенные tkCVS и tkdiff должны помочь. + +В. Kак из ProjMan создать tgz/rpm-пакет моей программы? + +О. TAR.GZ архив делается нажатием F7 на активном проекте или в меню +Под виндой должно zip-овать. + +В. Существует-ли в ProjMan поддержка заготовок кода(templates)? + +О. В принципе да такая возможность есть но, не особо развита - сейчас шаблон +забит в код :( это можно видеть при создании например html документа + +В. На каких языках локализован интерфейс ProjMan-a + +О. В настоящий момент программа локализована на 4-х языках - русский, английский, немецкий, французский. + +-- +Igor Didkovsky aka Gor (ididkovsky@mail.ru) +Segey Kalinin aka BanZaj (banzaj@lrn.ru) + diff --git a/hlp/ru/projman/gpl.ru b/hlp/ru/projman/gpl.ru new file mode 100644 index 0000000..4ed552e --- /dev/null +++ b/hlp/ru/projman/gpl.ru @@ -0,0 +1,427 @@ +УНИВЕРСАЛЬНАЯ ОБЩЕСТВЕННАЯ ЛИЦЕНЗИЯ GNU +Версия 2, июнь 1991 +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +(C) Перевод. О.В. Кузина, В.М. Юфа, 1993 +(C) Перевод. О.С. Тихонов, 1998 + +Этот документ можно копировать, а также распространять его +дословные копии, однако вносить в него изменения запрещено. + +Преамбула + +Лицензии на большую часть программного обеспечения (ПО) составлены так, +чтобы лишить вас свободы совместно использовать и изменять его. В +противоположность этому, предназначение Универсальной Общественной +Лицензии GNU состоит в том, чтобы гарантировать вашу свободу совместно +использовать и изменять свободное ПО, т.е. обеспечить свободу ПО для +всех его пользователей. Данная Универсальная Общественная Лицензия +применима к большей части ПО Фонда Свободного ПО и ко всем другим +программам, чьи авторы принимают на себя обязательство ее использовать. +(Для некоторых программ Фонда Свободного ПО вместо нее применяется +Универсальная Общественная Лицензия GNU для библиотек.) Вы тоже можете +применить ее к своим программам. + + +Когда мы говорим о свободном ПО, мы имеем в виду свободу, а не +бесплатность. Наши Универсальные Общественные Лицензии разрабатывались +для того, чтобы гарантировать, что вы пользуетесь свободой +распространять копии свободного ПО (и при желании получать за это +вознаграждение); что вы получаете исходный код или можете получить его, +если захотите; что вы можете изменять ПО или использовать его части в +новых свободных программах; и что вы знаете обо всех этих правах. + + +Чтобы защитить ваши права, нам нужно ввести некоторые ограничения, +которые запретят кому бы то ни было отказывать вам в этих правах или +потребовать от вас отказаться от этих прав. Эти ограничения накладывают +на вас некоторые обязательства, если вы распространяете копии ПО или +изменяете его. + + +Например, если вы распространяете копии такой программы бесплатно или за +вознаграждение, вы должны предоставить получателям все права, которыми +обладаете вы сами. Вы должны гарантировать, что они тоже получат или +смогут получить исходный код. Наконец, вы должны показать им текст +данных условий, чтобы они знали о своих правах. + + +Мы защищаем ваши права в два этапа: (1) сохраняем авторские права на ПО +и (2) предлагаем вам эту лицензию, которая дает вам законное право +копировать, распространять и/или модифицировать ПО. + + +Кроме того, в целях защиты как каждого автора, так и нас, мы хотим +удостовериться, что каждый понимает, что гарантий на это свободное ПО +нет. Если ПО модифицируется и передается кем-то еще, мы хотим, чтобы +получатели ПО знали, что то, что у них есть, -- это не оригинал, чтобы +любые проблемы, созданные другими, не отразились на репутации +первоначальных авторов. + + +И наконец, каждой свободной программе постоянно угрожают патенты на ПО. +Мы хотим избежать той опасности, что повторные распространители +свободной программы самостоятельно получат патенты, делая программу +таким образом частной собственностью. Чтобы предотвратить это, мы со +всей определенностью заявляем, что любой патент должен быть либо +предоставлен всем для свободного использования, либо не предоставлен +никому. + + +Ниже следуют точные определения и условия для копирования, +распространения и модификации. + + + + +ОПРЕДЕЛЕНИЯ И УСЛОВИЯ ДЛЯ КОПИРОВАНИЯ, РАСПРОСТРАНЕНИЯ И МОДИФИКАЦИИ + + Эта Лицензия применима к любой программе или другому произведению, +содержащему уведомление, помещенное держателем авторских прав и +сообщающее о том, что оно может распространяться при условиях, +оговоренных в данной Универсальной Общественной Лицензии. В дальнейшем +термин "Программа" относится к любой такой программе или произведению, +а термин "произведение, основанное на Программе" означает Программу +или любое произведение, содержащее Программу или ее часть, дословную, +или модифицированную, и/или переведенную на другой язык. (Здесь и далее +перевод включается без ограничений в понятие "модификация".) Каждый +обладатель лицензии адресуется как "вы". + + + Виды деятельности, не являющиеся копированием, распространением или +модификацией, не охватываются данной Лицензией; они лежат за пределами +ее влияния. Использование Программы по ее функциональному назначению не +ограничено, а выходные данные Программы охватываются этой Лицензией, +только если их содержание является произведением, основанным на +Программе (вне зависимости от того, были ли они получены в процессе +использования Программы). Являются ли они таковыми, зависит от того, +что именно делает Программа. + + + +Вы можете копировать и распространять дословные копии исходного кода +Программы по его получении на любом носителе, при условии что вы +соответствующим образом помещаете на видном месте в каждой копии +соответствующее уведомление об авторских правах и отказ от +предоставления гарантий; оставляете нетронутыми все уведомления, +относящиеся к данной Лицензии и к отсутствию каких-либо гарантий; и +передаете всем другим получателям Программы копию данной Лицензии вместе +с Программой. + +Вы можете назначить плату за физический акт передачи копии и можете по +своему усмотрению предоставлять гарантии за вознаграждение. + + +Вы можете изменять свою копию или копии Программы или любой ее части, +создавая таким образом произведение, основанное на Программе, и +копировать и распространять эти модификации или произведение в +соответствии с Разделом 1, приведенным выше, при условии, что вы +выполните все нижеследующие условия: + + + +Вы обязаны снабдить модифицированные файлы заметными уведомлениями, +содержащими указания на то, что вы изменили файлы, и дату каждого +изменения. + + +Вы обязаны предоставить всем третьим лицам лицензию на бесплатное +использование каждого произведения, которое вы распространяете или +публикуете, целиком, и которое полностью или частично содержит Программу +или какую-либо ее часть, на условиях, оговоренных в данной Лицензии. + + +Если модифицированная программа обычно читает команды в интерактивном +режиме работы, вы должны сделать так, чтобы при запуске для работы в +таком интерактивном режиме обычным для нее способом она печатала или +выводила на экран объявление, содержащее соответствующее уведомление об +авторских правах и уведомление о том, что гарантий нет (или, наоборот, +сообщающее о том, что вы обеспечиваете гарантии), и что пользователи +могут повторно распространять программу при этих условиях, и указывающее +пользователю, как просмотреть копию данной Лицензии. (Исключение: если +сама Программа работает в интерактивном режиме, но обычно не выводит +подобных сообщений, то ваше произведение, основанное на Программе, не +обязано выводить объявление.) + +Эти требования применяются к модифицированному произведению в +целом. Если известные части этого произведения не были основаны на +Программе и могут обоснованно считаться независимыми и самостоятельными +произведениями, то эта Лицензия и ее условия не распространяются на эти +части, если вы распространяете их как отдельные произведения. Но если вы +распространяете эти части как часть целого произведения, основанного на +Программе, то вы обязаны делать это в соответствии с условиями данной +Лицензии, распространяя права получателей лицензии на все произведение +и, таким образом, на каждую часть, вне зависимости от того, кто ее +написал. + +Таким образом, содержание этого раздела не имеет цели претендовать на +ваши права на произведение, написанное полностью вами, или оспаривать +их; цель скорее в том, чтобы реализовать право управлять +распространением производных или коллективных произведений, основанных +на Программе. + +Кроме того, простое нахождение другого произведения, не основанного на +этой Программе, совместно с Программой (или с произведением, основанным +на этой Программе) на одном носителе для постоянного хранения или +распространяемом носителе не распространяет действие этой Лицензии на +другое произведение. + + +Вы можете копировать и распространять Программу (или произведение, +основанное на ней) согласно Разделу 2) в объектном коде или в выполнимом +виде в соответствии с Разделами 1 и 2, приведенными выше, при условии, +что вы также выполните одно из следующих требований: + + +Сопроводите ее полным соответствующим машиночитаемым исходным кодом, +который должен распространяться в соответствии с Разделами 1 и 2, +приведенными выше, на носителе, который обычно используется для обмена +ПО; или, + + +Сопроводите ее письменным предложением, действительным по крайней мере в +течение трех лет, предоставить любому третьему лицу за вознаграждение, +не превышающее стоимость физического акта изготовления копии, полную +машиночитаемую копию соответствующего исходного кода, подлежащую +распространению в соответствии с Разделами 1 и 2, приведенными выше; или + + +Сопроводите ее информацией, полученной вами в качестве предложения +распространить соответствующий исходный код. (Эта возможность допустима +только для некоммерческого распространения, и только если вы получили +программу в объектном коде или в исполняемом виде с предложением в +соответствии с Пунктом b) выше.) + +Исходный код для произведения означает его вид, предпочтительный для +выполнения в нем модификаций. Для исполняемого произведения полный +исходный код означает все исходные коды для всех модулей, которые он +содержит, плюс любые связанные с произведением файлы определения +интерфейса, плюс сценарии, используемые для управления компиляцией и +установкой исполняемого произведения. Однако, в виде особого исключения +распространяемый исходный код не обязан включать то, что обычно +предоставляется (как в объектных, так и в исходных кодах) с основными +компонентами (компилятор, ядро и так далее) операционной системы, под +управлением которой работает исполняемое произведение, за исключением +случая, когда сам компонент сопровождает исполняемое произведение. + +Если распространение исполняемого произведения или объектного кода +происходит путем предоставления доступа для копирования с обозначенного +места, то предоставление доступа для копирования исходного кода с того +же места считается распространением исходного кода, даже если третьи +лица не принуждаются к копированию исходного кода вместе с объектным +кодом. + + +Вы не можете копировать, изменять, повторно лицензировать, или +распространять Программу никаким иным способом, кроме явно +предусмотренных данной Лицензией. Любая попытка копировать, изменять +или распространять Программу каким-либо другим способом или с измененной +лицензией неправомерна и автоматически прекращает ваши права, данные вам +этой Лицензией. Однако лицензии лиц, получивших от вас копии или права +согласно данной Универсальной Общественной Лицензии, не прекращают +своего действия, если эти лица полностью соблюдают условия. + + +Вы не обязаны соглашаться с этой Лицензией, так как вы не подписывали +ее. Однако, ничто, кроме этой Лицензии, не дает вам право изменять или +распространять эту Программу или основанные на ней произведения. Эти +действия запрещены законом, если вы не принимаете к соблюдению эту +Лицензию. А значит, изменяя или распространяя Программу (или +произведение, основанное на Программе), вы изъявляете свое согласие с +этой Лицензией и всеми ее условиями о копировании, распространении или +модификации Программы или основанных на ней произведений. + + +Каждый раз, когда вы повторно распространяете Программу (или любое +произведение, основанное на Программе), получатель этого произведения +автоматически получает от первоначального выдавшего лицензию лица свою +лицензию на копирование, распространение или модификацию Программы, +обсуждаемую в этих определениях и условиях. Вы не можете налагать +каких-либо дополнительных ограничений на осуществление получателем прав, +предоставленных данным документом. Вы не несете ответственности за +соблюдение третьими лицами условий этой Лицензии. + + +Если в результате судебного разбирательства, или обвинения в нарушении +патента или по любой другой причине (не обязательно связанной с +патентами), вам навязаны условия, противоречащие данной Лицензии (по +постановлению суда, по соглашению или иным способом), это не освобождает +вас от соблюдения Лицензии. Если вы не можете заниматься +распространением так, чтобы одновременно удовлетворить требованиям и +этой Лицензии, и всем другим требованиям, то вы не должны заниматься +распространением Программы. Например, если патент не позволяет +безвозмездное повторное распространение Программы всем, кто получил +копии от вас непосредственно или через посредников, то единственным +способом удовлетворить и патенту, и этой Лицензии будет ваш полный отказ +от распространения Программы. + +Если какая-либо часть этого раздела не имеет силы или не может быть +исполнена при некоторых конкретных обстоятельствах, то подразумевается, +что имеет силу остальная часть раздела, а при других обстоятельствах +имеет силу весь Раздел. + +Цель этого раздела -- не побудить вас делать заявления о нарушениях +прав на патент, или заявлять о других претензиях на право собственности +или оспаривать правильность подобных претензий; единственная цель этого +раздела -- защита целостности системы распространения свободного ПО, +которая реализуется использованием общественных лицензий. Многие люди +внесли щедрый вклад в широкий спектр ПО, распространяемого по этой +системе, полагаясь на ее согласованное применение; только автору +принадлежит право решать, хочет ли он или она распространять ПО в этой +системе или в какой-то другой, и получатель лицензии не может влиять на +принятие этого решения. + +Этот раздел предназначен для того, чтобы тщательно прояснить, что +полагается следствием из остальной части данной Лицензии. + + +Если распространение и/или применение Программы ограничено в ряде стран +либо патентами, либо авторскими правами на интерфейсы, первоначальный +обладатель авторских прав, выпускающий Программу с этой Лицензией, может +добавить явное ограничение на географическое распространение, исключив +такие страны, так что распространение разрешается только в тех странах, +которые не были исключены. В этом случае данная Лицензия включает в +себя это ограничение, как если бы оно было написано в тексте данной +Лицензии. + + +Фонд Свободного ПО может время от времени публиковать пересмотренные +и/или новые версии Универсальной Общественной Лицензии. Такие новые +версии будут сходны по духу с настоящей версией, но могут отличаться в +деталях, направленных на новые проблемы или обстоятельства. + +Каждой версии придается отличительный номер. Если в Программе +указывается, что к ней относится некоторый номер версии данной Лицензии +и "любая последующая версия", вы можете по выбору следовать +определениям и условиям либо данной версии, либо любой последующей +версии, опубликованной Фондом Свободного ПО. Если в Программе не +указан номер версии данной Лицензии, вы можете выбрать любую версию, +когда-либо опубликованную Фондом Свободного ПО. + + +Если вы хотите встроить части Программы в другие свободные программы с +иными условиями распространения, напишите автору с просьбой о +разрешении. Для ПО, которое охраняется авторскими правами Фонда +Свободного ПО, напишите в Фонд Свободного ПО; мы иногда делаем такие +исключения. Наше решение будет руководствоваться двумя целями: +сохранения свободного статуса всех производных нашего свободного ПО и +содействия совместному и повторному использованию ПО вообще. + + + +НИКАКИХ ГАРАНТИЙ + + +ПОСКОЛЬКУ ПРОГРАММА ПРЕДОСТАВЛЯЕТСЯ БЕСПЛАТНО, НА ПРОГРАММУ НЕТ +ГАРАНТИЙ В ТОЙ МЕРЕ, КАКАЯ ДОПУСТИМА ПРИМЕНИМЫМ ЗАКОНОМ. ЗА +ИСКЛЮЧЕНИЕМ ТЕХ СЛУЧАЕВ, КОГДА ОБРАТНОЕ ЗАЯВЛЕНО В ПИСЬМЕННОЙ ФОРМЕ, +ДЕРЖАТЕЛИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИЕ СТОРОНЫ ПОСТАВЛЯЮТ ПРОГРАММУ "КАК +ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ +ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ПОДРАЗУМЕВАЕМЫЕ +ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ. ВЕСЬ +РИСК В ОТНОШЕНИИ КАЧЕСТВА И ПРОИЗВОДИТЕЛЬНОСТИ ПРОГРАММЫ ОСТАЕТСЯ ПРИ +ВАС. ЕСЛИ ПРОГРАММА ОКАЖЕТСЯ ДЕФЕКТНОЙ, ВЫ ПРИНИМАЕТЕ НА СЕБЯ +СТОИМОСТЬ ВСЕГО НЕОБХОДИМОГО ОБСЛУЖИВАНИЯ, ВОССТАНОВЛЕНИЯ ИЛИ +ИСПРАВЛЕНИЯ. + + +НИ В КОЕМ СЛУЧАЕ, ЕСЛИ НЕ ТРЕБУЕТСЯ СООТВЕТСТВУЮЩИМ ЗАКОНОМ, ИЛИ НЕ +УСЛОВЛЕНО В ПИСЬМЕННОЙ ФОРМЕ, НИ ОДИН ДЕРЖАТЕЛЬ АВТОРСКИХ ПРАВ И НИ ОДНО +ДРУГОЕ ЛИЦО, КОТОРОЕ МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ +ПРОГРАММУ, КАК БЫЛО РАЗРЕШЕНО ВЫШЕ, НЕ ОТВЕТСТВЕННЫ ПЕРЕД ВАМИ ЗА +УБЫТКИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СПЕЦИАЛЬНЫЕ, СЛУЧАЙНЫЕ ИЛИ ПОСЛЕДОВАВШИЕ +УБЫТКИ, ПРОИСТЕКАЮЩИЕ ИЗ ИСПОЛЬЗОВАНИЯ ИЛИ НЕВОЗМОЖНОСТИ ИСПОЛЬЗОВАНИЯ +ПРОГРАММЫ (ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ПОТЕРЕЙ ДАННЫХ, ИЛИ ДАННЫМИ, +СТАВШИМИ НЕПРАВИЛЬНЫМИ, ИЛИ ПОТЕРЯМИ, ПОНЕСЕННЫМИ ИЗ-ЗА ВАС ИЛИ ТРЕТЬИХ +ЛИЦ, ИЛИ ОТКАЗОМ ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ЛЮБЫМИ ДРУГИМИ +ПРОГРАММАМИ), ДАЖЕ ЕСЛИ ТАКОЙ ДЕРЖАТЕЛЬ ИЛИ ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О +ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ. + + +КОНЕЦ ОПРЕДЕЛЕНИЙ И УСЛОВИЙ + + + +Как применять эти условия к вашим новым программам + + Если вы разрабатываете новую программу и хотите, чтобы она принесла +максимально возможную пользу обществу, лучший способ достичь этого --- +включить ее в свободное ПО, которое каждый может повторно распространять +и изменять согласно данным условиям. + + + Чтобы сделать это, добавьте в программу следующие уведомления. +Надежнее всего будет добавить их в начало каждого исходного файла, чтобы +наиболее эффективно передать сообщение об отсутствии гарантий; каждый +файл должен содержать по меньшей мере строку, содержащую знак охраны +авторского права и указание на то, где находится полное уведомление. + + + +

    +одна строка, содержащая название программы и краткое
    +описание того, что она делает.
    +(C) наименование (имя) автора 19гг
    +
    +Это свободная программа; вы можете повторно распространять ее и/или
    +модифицировать ее в соответствии с Универсальной Общественной
    +Лицензией GNU, опубликованной Фондом Свободного ПО; либо версии 2,
    +либо (по вашему выбору) любой более поздней версии.
    +
    +Эта программа распространяется в надежде, что она будет полезной,
    +но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ; даже без подразумеваемых гарантий
    +КОММЕРЧЕСКОЙ ЦЕННОСТИ или ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ.  Для
    +получения подробных сведений смотрите Универсальную Общественную
    +Лицензию GNU.
    +
    +Вы должны были получить копию Универсальной Общественной Лицензии
    +GNU вместе с этой программой; если нет, напишите по адресу: Free
    +Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    +02111-1307 USA
    +
    +Добавьте также сведения о том, как связаться с вами по электронной и
    +обычной почте.
    +
    +
    +Если программа интерактивная, сделайте так, чтобы при запуске в
    +интерактивном режиме она выдавала краткое уведомление вроде следующего:
    +
    +
    +
    +Гномовизор, версия 69, (C) имя автора 19  гг
    +Гномовизор поставляется АБСОЛЮТНО БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ;
    +для получения подробностей напечатайте 'show w'.  Это свободная
    +программа, и вы приглашаетесь повторно распространять ее при
    +определенных условиях; для получения подробностей введите 'show c'.
    +
    +
    +Гипотетические команды 'show w' и 'show c' должны показывать
    +соответствующие части Универсальной Общественной Лицензии.  Конечно,
    +используемые вами команды могут называться как-нибудь иначе, нежели
    +`show w' и `show c'; они даже могут выбираться с помощью мыши
    +или быть пунктами меню -- как больше подходит для вашей программы.
    +
    +
    +Вы также должны добиться того, чтобы ваш работодатель (если вы работаете
    +программистом) или ваше учебное заведение, если таковое имеется,
    +подписали в случае необходимости "отказ от имущественных прав" на эту
    +программу.  Вот образец; замените фамилии:
    +
    +
    +
    +Компания ``Братья Ёёдины'' настоящим отказывается от всех
    +имущественных прав на программу 'Гномовизор' (которая делает
    +пассы в сторону компиляторов), написанную Абстрактным К.И.
    +
    +подпись Мага Ната, 1 апреля 1989 г
    +Маг Нат, Президент фирмы Вице.
    +
    +
    +
    +Данная Универсальная Общественная Лицензия не позволяет вам включать
    +вашу программу в программы, являющиеся частной собственностью.  Если
    +ваша программа -- это библиотека процедур, вам стоит подумать, не будет
    +ли лучше разрешить программам, являющимся частной собственностью,
    +связываться с вашей библиотекой.  Если это то, чего вы хотите,
    +используйте вместо этой Лицензии Универсальную Общественную Лицензию GNU
    +для библиотек.
    \ No newline at end of file
    diff --git a/hlp/ru/projman/pmabout.html b/hlp/ru/projman/pmabout.html
    new file mode 100644
    index 0000000..a33328f
    --- /dev/null
    +++ b/hlp/ru/projman/pmabout.html
    @@ -0,0 +1,25 @@
    +About Tcl/Tk Project Manager
    +

    Tcl/Tk Project Manager

    +Version 1.0.0
    +

    Автор: Сергей Калинин (aka BanZaj) banzaj@lrn.ru +
    Домашняя страница: http://conero.lrn.ru + +

    IDE для программирования на Tcl/Tk +

    Включает в себя: +
    - менеджер проектов +
    - менеджер файлов +
    - текстовый редактор +
      -- подсветка синтаксиса нескольких языков (Tcl, Html, Rpm.spec) +
      -- навигация по процедурам +
      -- поиск/замена информации +
      -- переход на строку с заданным номером +
      -- возможность повторения/отмены операций +
    - встроенная контекстно-зависимая справочная ситема +
      -- помощь по командам Tcl +
      -- помощь по командам Tk +
      -- помощь по IDE +
    - запуск приложений из IDE + +

    © Copyright CONERO lab, 2002 + + diff --git a/hlp/ru/projman/pmbegin.html b/hlp/ru/projman/pmbegin.html new file mode 100644 index 0000000..0dc9a8b --- /dev/null +++ b/hlp/ru/projman/pmbegin.html @@ -0,0 +1,27 @@ +Начало работы +

    Начало работы с Project Manager-ом

    +

    СОЗДАНИЕ ПРОЕКТА +

    Для начала необходимо создать новый (либо открыть существующий) проект. +
    Для этого в меню "Проект" выберите пункт "Новый проект" (либо "Открыть проект"). Откроется форма создания нового проекта, заполните все необходимые поля. Рассмотрим процедуру создания проекта на примере "Tcl/Tk Project manager": +
    "Название проекта" - полное название проекта (программы), это может быть любое предложение, например "Tcl/Tk Project Manager" +
    "Файл проекта" - имя файла проекта, т.е. имя основного файла вашей программы, в нашем примере это projman. При создании проекта к имени будет автоматически добавлено расширение .tcl +
    "Каталог проекта" - наименование каталога проекта. Каталог под этим именем будет создан в каталоге с проектами, который можно изменить в настройках(меню "Файл" -> "Установки"). По умолчанию все проекты будут помещены в Ваш домашний каталог в директорию /projects/tcl/"каталог проекта". +
    Tcl интерпретатор - название интерпретатора tcl для выполнения проекта, например tclsh, wish и т.п. Путь к интерпретатору следует указывать полностью - /usr/bin/tclsh +
    "Версия" - текущая версия программы (проекта), используется в имени файла архива, rpm-пакета и так далее. +
    "Выпуск" - по другому можно назвать "релиз", номер релиза, используется так же как и номер версии. +
    "Автор" - имя автора программы, используется в заголовках всех файлов проекта +
    "Эл. почта" - адрес электронной почты +
    Компания - наименование компании +
    Домашняя страница - адрес домашней страницы автора (либо компании) где в будущем будет размещен создаваемый проект. +
    Все пункты, кроме первых четырех, заполнять не обязательно, но желательно. +

    ОТКРЫТИЕ ПРОЕКТА +

    Чтобы открыть (добавить в дерево проектов) существующий проект, необходимо в меню "Проекты" выбрать пункт "Открыть проект". После этого на экран будет выведено окно выбора директории, где Вам следует выбрать каталог с тем проектом, который хотите добавить, для этого щелкните левой кнопкой мыши на нужном каталоге (в нижнем поле должно появиться полное путевое имя этого каталога) и нажмите кнопку "Выбрать". После этого откроется форма нового проекта с заполненными некоторыми полями, необходимо заполнить все поля и нажать кнопку "Создать". файлы проекта будут скопированы в директорию с проектами, установленную в "Настройках" и проект отобразится в дереве проектов. +

    ВЫБОР АКТИВНОГО ПРОЕКТА +

    Все операции с проектами доступны только для активного проекта. +Название активного проекта отображается в строке статуса внизу основного окна программы. Чтобы сделать нужный проект активным необходимо щелкнуть мышкой на имени проекта в дереве проектов. +

    УДАЛЕНИЕ ПРОЕКТА +

    Для удаления текущего (активного) проекта нужно в меню "Проекты" выбрать пункт "Удалить проект" и подтвердить операцию. +

    РЕДАКТИРОВАНИЕ ФАЙЛА +

    Чтобы открыть нужный файл для просмотра или редактирования щелкните два раза мышкой на имени этого файла. Редактор позволяет одновременно открывать большое количество файлов. Переключения между окнами редактора осуществляется нажатием сочитания клавиш Control + m. + + diff --git a/hlp/ru/projman/pmhelp.html b/hlp/ru/projman/pmhelp.html new file mode 100644 index 0000000..4025193 --- /dev/null +++ b/hlp/ru/projman/pmhelp.html @@ -0,0 +1,7 @@ +Help system +

    Использование справочной системы

    +

    Для облегчения доступа к справочной информации Project Manager оснащен контекстно-зависимой справочной системой. Через систему помощи доступна документация по Tcl/Tk Project manager, по операторам и командам языка Tcl и графического расширения Tk. +

    Чтобы воспользоваться встроенной справочной системой нужно нажать на клавишу F1, в результате чего на экран будет выведено окно справочной системы. +

    Для получения справки по какому-либо оператору необходимо в редакторе выделить этот оператор и нажать F1. Либо в окне справочной системы найти в списке операторов нужный Вам и щелкнуть на него мышкой. + + diff --git a/hlp/ru/projman/pmkeys.html b/hlp/ru/projman/pmkeys.html new file mode 100644 index 0000000..e7449d4 --- /dev/null +++ b/hlp/ru/projman/pmkeys.html @@ -0,0 +1,27 @@ +Hot keys +

    Сочетания клавиш

    + +

    Ctrl + A - Сохранить файл под другим именем. +

    Ctrl + C - Команда копирует выделенный в окне редактора текст в буфер обмена. +

    Ctrl + F - Поиск заданного выражения в тексте. +

    Ctrl + G - Перейти к строке с заданным номером. +

    Ctrl + J - Вывести список функций с именами полностью или частично совпадающими с введенным. +

    Ctrl + L - Вывести список слов, полностью или частично совпадающих с введенным. +

    Ctrl + M - Переключение между открытыми файлами (между окнами редактора). +

    Ctrl + N - Создать новый файл. Команда вызывает диалог создания файла. +

    Ctrl + O - Открыть файл. +

    Ctrl + Q - Выход из Project Manager-a. +

    Ctrl + R - Поиск и замена заданного выражения в тексте. +

    Ctrl + S - Сохранить файл. Сохраняется файл, который открыт в текущем окне редактора. +

    Ctrl + T - Поменять местами два символа, стоящих до и после курсора. +

    Ctrl + U - Перемещает курсор на соответствующую открытую или закрытую скобку. +

    Ctrl + V - Вставка фрагмента текста из буфера обмена, скопированного предыдущей командой. +

    Ctrl + W - Закрыть файл. Команда закрывает файл открытый в текущем окне редактора. +

    Ctrl + X - Вырезать выделенный фрагмент текста в буфер омена. +

    Ctrl + Z - Отменить операцию +

    F1 - Вызов системы помощи по программе и по языку. Если в тексте выделить команду и нажать данную клавишу то будет выведена на экран подсказка по этой команде. +

    F3 - Повторный поиск, команда работает с последним введенным выражением в диалоговом окне поиска +

    F5 - Команда создания архивного файла. Работает только с активным проектом +

    F6 - Создание RPM. +

    F9 - Выполнение ("компиляция") текущего (активного) проекта. + diff --git a/hlp/ru/projman/pmregexp.html b/hlp/ru/projman/pmregexp.html new file mode 100644 index 0000000..12ab354 --- /dev/null +++ b/hlp/ru/projman/pmregexp.html @@ -0,0 +1,81 @@ +VisualREGEXP +

    VisualREGEXP

    +

    Copyright (c) 2000-2001 Laurent Riesterer +
    Latest version 2.2

    + +

    ABOUT +

    VisualREGEXP helps you to design, debug or more generally work with regular +expression. As it is often difficult to write the right regexp at the first +try, this tool will show you the effect of your regexp on a sample you can +choose. +

    REQUIREMENTS +

    This program requires Tcl/Tk 8.3.0 or later. +

    HOW TO USE + +

    Launching the program +

    On Unix, use 'chmod +x ...' to make the program executable. You can then +integrate it with your Window Manager or put it into an executable path. +
    On Windows, create a shortcut and invoke the script with 'wish.exe' + +

    Design of regexps +

    To design regexp, just type the expression in the top text widget. +Press the 'Go' button to highlight the matched part of the text in the sample +text widget. + +

    To get a quickref of the regexp syntax use the menu 'View/Show regexp help'. + +

    You can specify some options using the checkboxes (please read Tcl help to +learn the meaning of these options). + +

    Recursive design of regexps + +

    Sometimes you will need more than one step to extract the information you want +from the sample. For example, imagine you want to retrieve information from +an HTML table inside an another HTML table : + + ' + + +
    + + + +
    One 1
    Two 2
    +
    Foo Bar
    + ' + +

    You cannot use one global regexp to extract the two lines "One 1" and "Two 2". +You have to use a first regexp to narrow the processed region. +Type the following regexp ']*?>(.*?)
    ' and press 'Go'. +You see now that the interessing area is shown in blue. Press the Match '1' +button which will extract the blue text (the regexp to use to get this text +is then printed on the console). +Now use '.*?' to get the information you need. + +

    Optimization of regexps + +

    When you need to match a list of words, use the menu +'Insert regexp/Make regexp' to design an optimized version of the word list. + +

    For example, the list 'aa aab ab ad' is optimized into 'a(ab?|b|d)'. + +

    Processing the sample text + +

    Use can use VisualREGEXP to perform modification of a text. +Just use the menu 'Select mode/Use replace'. You can now design a regexp to +match what you want. Then use the replace text widget to enter the substitution +you want to apply (use \0, \1, \2, ... to match the subregexp, use the color +to map the number with the matched sub-expressions). + +

    After the substitution, you can save the new text using the 'File/Save ...' +menu. You can let the program choose the end-of-line format or force them for +a specific environment (Unix, Windows, Mac). + +

    CONTACT + +

    Send your bug reports, suggestions or any feedback to: +

    +

    laurent.riesterer@free.fr
    +http://laurent.riesterer.free.fr +

    + diff --git a/hlp/ru/projman/pmtkdiff.html b/hlp/ru/projman/pmtkdiff.html new file mode 100644 index 0000000..a80ae7b --- /dev/null +++ b/hlp/ru/projman/pmtkdiff.html @@ -0,0 +1,108 @@ +TkDIFF+ +

    TkDIFF+

    + +

    The top row contains the File, Edit, View, Mark, Merge and Help menus. The second row contains the labels which identify the contents of each text window. Below that is a toolbar which contains navigation and merge selection tools. + +

    The left-most text widget displays the contents of FILE1, the most recently checked-in revision, REV or REV1, respectively (as per the startup options described in the "On Command Line" help). The right-most widget displays the contents of FILE2, FILE or REV2, respectively. Clicking the right mouse button over either of these windows will give you a context sensitive menu with actions that will act on the window you clicked over. For example, if you click right over the right hand window and select "Edit", the file displayed on the right hand side will be loaded into a text editor. + +

    At the bottom of the display is a two line window called the "Line Comparison" window. This will show the "current line" from the left and right windows, one on top of the other. The "current line" is defined by the line that has the blinking insertion cursor, which can be set by merely clicking on any line in the display. This window may be hidden if the View menu item Show Line Comparison is deselected. +

    All difference regions (DRs) are highlighted to set them apart from the surrounding text. The current difference region, or CDR, is further set apart so that it can be correlated to its partner in the other text widget (that is, the CDR on the left matches the CDR on the right). + +

    Changing the CDR + +

    The CDR can be changed in a sequential manner by means of the Next and Previous buttons. The First and Last buttons allow you to quickly navigate to the first or last CDR, respectively. For random access to the DRs, use the dropdown listbox in the toolbar or the diff map, described below. + +

    By clicking right over a window and using the popup menu you can select Find Nearest Diff to find the diff record nearest the point where you clicked. + +

    You may also select any highlighted diff region as the current diff region by double-clicking on it. + +

    Operations + +

    1. From the File menu: + +

    The New... button displays a dialog where you may choose two files to compare. Selecting "Ok" from the dialog will diff the two files. The Recompute Diffs button recomputes the differences between the two files whose names appear at the top of the TkDiff window. The Write Report... lets you create a report file that contains the information visible in the windows. Lastly, the Exit button terminates TkDiff. + +

    2. From the Edit menu: + +

    Copy copies the currently selected text to the system clipboard. Find pops up a dialog to let you search either text window for a specified text string. Edit File 1 and Edit File 2 launch an editor on the files displayed in the left- and right-hand panes. Preferences pops up a dialog box from which display (and other) options can be +changed and saved. + +

    3. From the View menu: + +

    Show Line Numbers toggles the display of line numbers in the text widgets. If Synchronize Scrollbars is on, the left and right text widgets are synchronized i.e. scrolling one of the windows scrolls the other. If Auto Center is on, pressing the Next or Prev buttons centers the new CDR automatically. Show Diff Map toggles the display of the diff map (see below) on or off. Show Merge Preview shows or hides the merge preview (see below). Show Line Comparison toggles the display of the "line comparison" window at the bottom of the display. + +

    4. From the Mark menu: + +The Mark Current Diff creates a new toolbar button that will jump to the current diff region. The Clear Current Diff Mark will remove the toolbar mark button associated with the current diff region, if one exists. + +

    5. From the Merge menu: + +The Show Merge Window button pops up a window with the current merged version of the two files. The Write Merge File button will allow you to save the contents of that window to a file. + +

    6. From the Help menu: + +The About TkDiff button displays copyright and author information. The On GUI button generates this window. The On Command Line button displays help on the TkDiff command line options. The On Preferences button displays help on the user-settable preferences. + +

    7. From the toolbar: + +The first tool is a dropdown list of all of the differences in a standard diff-type format. You may use this list to go directly to any diff record. The Next and Previous buttons take you to the "next" and "previous" DR, respectively. The First and Last buttons take you to the "first" and "last" DR. The Center button centers the CDRs in their respective text windows. You can set Auto Center in Preferences to do this automatically for you as you navigate through the diff records. + +

    Keyboard Navigation + +

    When a text widget has the focus, you may use the following shortcut keys: +

    + f First diff + c Center current diff + l Last diff + n Next diff + p Previous diff + 1 Merge Choice 1 + 2 Merge Choice 2 + u Switch back to directories view + +

    The cursor, Home, End, PageUp and PageDown keys work as expected, adjusting the view in whichever text window has the focus. Note that if Synchronize Scrollbars is set in Preferences, both windows will scroll at the same time. + +

    Scrolling + +

    To scroll the text widgets independently, make sure Synchronize Scrollbars in Preferences is off. If it is on, scrolling any text widget scrolls all others. Scrolling does not change the current diff record (CDR). + +

    Diff Marks + +

    You can set "markers" at specific diff regions for easier navigation. To do this, click on the Set Mark button. It will create a new toolbar button that will jump back to this diff region. To clear a diff mark, go to that diff record and click on the Clear Mark button. + +

    Diff Map + +

    The diff map is a map of all the diff regions. It is shown in the middle of the main window if "Diff Map" on the View menu is on. The map is a miniature of the file's diff regions from top to bottom. Each diff region is rendered as a patch of color, Delete as red, Insert as green and Change as blue. In the case of a 3-way merge, overlap regions are marked in yellow. The height of each patch corresponds to the relative size of the diff region. A thumb lets you interact with the map as if it were a scrollbar. +All diff regions are drawn on the map even if too small to be visible. For large files with small diff regions, this may result in patches overwriting each other. + +

    Merging + +

    To merge the two files, go through the difference regions (via "Next", "Prev" or whatever other means you prefer) and select "Left" or "Right" (next to the "Merge Choice:" label) for each. Selecting "Left" means that the the left-most file's version of the difference will be used in creating the final result; choosing "Right" means that the right-most file's difference will be used. Each choice is recorded, and can be changed arbitrarily many times. To commit the final, merged result to disk, choose "Write Merge File..." from the Merge menu. + +

    Merge Preview + +

    To see a preview of the file that would be written by "Write Merge File...", select "Show Merge Window" in the View menu. A separate window is shown containing the preview. It is updated as you change merge choices. It is synchronized with the other text widgets if "Synchronize Scrollbars" is on. + +

    Credits + +

    Thanks to Wayne Throop for beta testing, and for giving valuable suggestions (and code!) along the way. Thanks (and credit) to John Heidemann for his window tags routines, which I shamelessly stole (with permission) out of his great Tk-based Solitaire game, Klondike. Thanks to D. Elson (author of tkCVS) for writing the code that extends the RCS support to include CVS. Thanks to John Brown for writing the code that extends the revision control support to SCCS. + +

    Major thanks to Warren Jones (wjones@tc.fluke.com) and Peter Brandstrom (qraprbm@era-lvk.ericsson.se) for going way above and beyond the call. Warren added support for NT and cleaned up the Unix code as well. Peter, independently, did the same thing and then added the new interface. The end result was the 2.x series... Many, many thanks to you both! + +

    Major thanks also to Bryan Oakley (boakley@vignette.com), who made the GUI even more appealing... Bryan did a ton of work, the result of which was the 3.x series. Dorothy Robinson provided helpful comments and patches for 3.x, too. Thanks, Bryan and Dorothy! + +

    Thanks to Dean Jones (dean@gallant.com) for permission to use his icons in the toolbar. + +

    Thanks to Laurent Riesterer (laurent.riesterer@free.fr) for adding support to display the differences between files in directories. + +

    Many, many thanks also to the many others who have written and provided ideas and encouragement and code since TkDiff was first released! I haven't done much coding since the 1.x series; almost every new feature that has come about since then has been the result of volunteer efforts. Thanks, folks! +

    Author +
    John M. Klassa +

    Comments + +

    Questions and comments should be sent to the TkDiff mailing list at +http://www.accurev.com/free/tkdiff. + +

    To get it, please visit: +
    http://www.gnu.org/gnulist/production/diffutils.html + diff --git a/hlp/ru/projman/projman.toc.html b/hlp/ru/projman/projman.toc.html new file mode 100644 index 0000000..c68bd7c --- /dev/null +++ b/hlp/ru/projman/projman.toc.html @@ -0,0 +1,12 @@ +Tcl/Tk Project Manager +О программе
    +Работа с программой
    +Справочная система
    +Работа с VisualREGEXP
    +Работа с TkDIFF+
    +Горячие клавиши
    +Документация
    +Лицензия
    + + + diff --git a/hlp/ru/snodbc_test.tcl b/hlp/ru/snodbc_test.tcl new file mode 100644 index 0000000..d327b40 --- /dev/null +++ b/hlp/ru/snodbc_test.tcl @@ -0,0 +1,18 @@ +#!/usr/bin/tclsh +###################################################### +# scripts +# Distributed under GNU Public License +# Author: +# Copyright (c) "", 2006, +###################################################### + +package require snodbc + +database db PCS Administrator ",bkfqy+" +db tables sm_address_range +puts [ db "SELECT * from sm_address_range"] + +db disconnect + + + diff --git a/hlp/ru/tcl/Http.html b/hlp/ru/tcl/Http.html new file mode 100644 index 0000000..86483e0 --- /dev/null +++ b/hlp/ru/tcl/Http.html @@ -0,0 +1,450 @@ + + + + Http + + + +

    Http

    + +

    Клиентская часть реализации протокола HTTP/1.0.

    + +

    СИНТАКСИС

    + +
    +      package require http ?2.0?
    +      ::http::config ?options?
    +      ::http::geturl url ?options?
    +      ::http::formatQuery list
    +      ::http::reset token ?why?
    +      ::http::wait token
    +      ::http::status token
    +      ::http::size token
    +      ::http::code token
    +      ::http::data token
    +    
    + +

    ОПИСАНИЕ

    + +

    Пакет http обеспечивает клиентскую часть протокола + HTTP/1.0 и реализует операции GET, POST и HEAD. Он позволяет + конфигурировать сервер-представитель (proxy) для выхода через + межсетевые экраны. Пакет совместим с политикой безопасности + Safesock.

    + +

    Процедура ::http::geturl + выполняет HTTP транзакцию. В зависимости от заданной опции это + может быть GET, POST или HEAD транзакция. Величина, + возвращаемая процедурой + ::http::geturl, является признаком (token) выполнения + транзакции. Кроме того, ее значение совпадает с именем массива в + пространстве имен ::http, который содержит информацию о + выполнении транзакции. Элементы массива описаны ниже, см. "Массив + состояния транзакции".

    + +

    Если процедура вызвана с опцией -command, операция + выполняется в фоновом режиме. Процедура ::http::geturl + завершается сразу после формирования HTTP запроса, а результаты + запроса обрабатываются после их получения. Для успешной работы в + таком режиме необходимо, чтобы был запущен обработчик + событий. Это всегда так для Tk-приложений. В чисто Tcl - + приложениях можно использовать процедуру ::http::wait для запуска + обработчика событий.

    + +

    КОМАНДЫ

    + +
    +
    ::http::config + ?options?
    + +

    Команда ::http::config используется, чтобы + установить или запросить имя proxy-сервера, порта и + пользовательского приложения (User-Agent), используемые в + HTTP запросах. Если никакие опции не заданы, возвращается + текущая конфигурация. Если задан единственный аргумент, + тогда, он должен быть именем одной из опций, описанных + ниже. В этом случае возвращается текущая величина указанной + опции. В противном случае аргументы состоят из пар: имя + опции - присваиваемое значение.

    + +
    +
    -accept mimetypes
    + +
    Определяет типы документов, которые могут быть приняты + по запросу. Значение по умолчанию "*/*" означает, что + могут быть приняты документы любого типа. Чтобы ограничить + список допустимых документов, можно использовать список + (через запятую) шаблонов документов следующего вида: + "image/gif, image/jpeg, text/*".
    + +
    -proxyhost hostname
    + +
    Имя proxy-сервера, через который осуществляется связь. + Если не указано, связь осуществляется напрямую.
    + +
    -proxyport number
    + +
    Имя proxy-порта.
    + +
    -proxyfilter command
    + +
    Определяет команду, которая возвращает имена + proxy-сервера и proxy-порта, необходимые для данной + связи. В противном случае возвращает пустое значение. В + качестве аргумента при вызове команды используется имя + сервера (host). Если команда не задана, используются + значения опций -proxyhost и + -proxyport.
    + +
    -useragent string
    + +
    Определяет имя пользовательского приложения + (User-Agent). Значение по умолчанию "Tcl http client + package 2.0."
    +
    +
    + +
    ::http::geturl url + ?options?
    + +

    Команда ::http::geturl - основная команда пакета. + Если задана опция -query, выполняется операция POST, + если задана опция -validate, выполняется операция + HEAD. В противном случае выполняется операция GET. Команда + возвращает признак - имя массива, который может быть + использован для получения дополнительной информации о + состоянии транзакции. Подробности см. "Массив + состояния транзакции". Команда завершается после + завершения соответствующей операции, если она вызвана без + опции -command. В противном случае команда + ::http::geturl завершается немедленно, а по + завершении операции вызывается соответствующая команда для + обработки ее результатов. Команда ::http::geturl + может использоваться с различными опциями:

    + +
    +
    -blocksize size
    + +
    Используется при чтении информации. Определяет + максимальный размер блока (в байтах), который может быть + прочитан за один раз. После каждого чтения блока + вызывается команда, определенная с помощью опции + -progress. +
    + +
    -channel name
    + +
    Перенаправляет полученную информация в соответствующий + канал вместо того, чтобы сохранять ее в переменной + state(body). +
    + +
    -command callback
    + +

    Обеспечивает вызов команды callback после + завершения транзакции. При использовании этой опции + команда ::http::geturl завершается сразу. Команда + callback вызывается с аргументом token, + который содержит имя массива, описанного ниже, см. "Массив + состояния транзакции". Ниже приведен шаблон + типовой процедуры для использования в данной опции:

    +
    +    proc httpCallback {token} { 
    +                  upvar #0 $token state 
    +                  # Далее возможна работа со state как с обычным Tcl-массивом
    +	      }
    +	    
    +
    + +
    -handler callback
    + +

    Опция обеспечивает вызов команды callback как + только HTTP данные получены. Команда получает два + дополнительных аргумента: HTTP socket и имя + массива token, возвращенное командой + ::http::geturl (см. "Массив состояния + транзакции"). Команда должна возвращать число + байтов, прочитанных из socket. Ниже приведен + шаблон подобной процедуры:

    +
    +     proc httpHandlerCallback {socket token} {
    +                   upvar #0 $token state
    +                   # Получен доступ к socket и Tcl-массиву state 
    +                   # ... 
    +                   # (например: 
    +                   # set data [read $socket 1000];
    +                   # set nbytes [string length $data])
    +                   # ...
    +                   return nbytes
    +               }
    +
    +
    + +
    -headers keyvaluelist
    + +

    Опция используется для включения в заголовок HTTP + запроса дополнительных полей. Аргумент должен быть + правильным списком с четным числом элементов, состоящим + попеременно из ключей и их значений. Ключи используются + как имена полей заголовка. Из значений удаляются символы + перехода на новую строку, чтобы избежать формирования + неправильного заголовка. Например, если + keyvaluelist содержит список {Pragma + no-cache} будет сформирован следующий заголовок + запроса:

    +
    +	      Pragma: no-cache
    +	    
    +
    + +
    -progress callback
    + +

    Опция обеспечивает вызов команды callback для + обработки очередной порции данных. Команда + callback получает три аргумента: значение + token, возвращенное командой + ::http::geturl, предполагаемый полный размер + данных из мета-данных и текущее количество поступивших + данных в байтах. Если предполагаемый полный размер + неизвестен, вместо него подставляется 0. Ниже приведен + шаблон для процедуры, вызываемой по опции + -progress:

    + +
    +    proc httpProgress {token total current} { 
    +                  upvar #0 $token state 
    +	      }
    +	    
    +
    + +
    -query query
    + +
    Если указана данная опция, ::http::geturl + формирует запрос POST и передает его на сервер. Запрос + должен быть сформатирован. Для выполнения форматирования + может использоваться процедура ::http::formatQuery. +
    + +
    -timeout milliseconds
    + +
    Если значение milliseconds не равно нулю, + устанавливается соответствующее время задержки. Задержка + выполняется перед вызовом команды ::http::reset и команды, + заданной опцией -command. Во время задержки команда + ::http::status + возвращает значение timeout. +
    + +
    -validate boolean
    + +
    Если значение boolean не равно нулю, + ::http::geturl выполняет HTTP HEAD запрос. Такой + запрос возвращает мета информацию об источнике данных + (URL), а не его содержание. Мета информация содержится в + переменной state(meta) (см. "Массив + состояния транзакции"). +
    +
    +
    + +
    ::http::formatQuery + key value ?key value...?
    + +
    Команда выполняет перекодирование запроса. Команда + использует четное число аргументов, являющихся соответственно + ключами запроса и их значениями. Она преобразует ключи и + значения и возвращает одну строку, в которой расставлены + необходимые "&" и "=" + разделители. Результат можно использовать в качестве значения + для опции -query команды + ::http::geturl. +
    + +
    ::http::reset token + ?why?
    + +
    Команда перезапускает HTTP транзакцию token, если + такая исполняется. Значение переменной state(status) + при этом переустанавливается в why (по умолчанию - + reset) и вызывается команда, заданная опцией + -command. +
    + +
    ::http::wait + token
    + +
    Эта команда обеспечивает ожидание завершения транзакции. Она + работает только в надежных интерпретаторах, так как она + использует команду vwait. +
    + +
    ::http::data + token
    + +
    Эта команда возвращает значение переменной + state(body). +
    + +
    ::http::status + token
    + +
    Эта команда возвращает значение переменной + state(status). +
    + +
    ::http::code + token
    + +
    Эта команда возвращает значение переменной + state(http). +
    + +
    ::http::size + token
    + +
    Эта команда возвращает значение переменной + state(currentsize). +
    +
    + +

    МАССИВ СОСТОЯНИЯ ТРАНЗАКЦИИ

    + +

    Команда + ::http::geturl возвращает token - имя + Tcl-массива, содержащего информацию о HTTP транзакции. Для + упрощения доступа к массиву можно использовать следующую + конструкцию:

    +
    +      upvar #0 $token state
    +    
    + +

    Массив содержит следующие элементы:

    +
    + +
    body
    + +
    Содержание документа, заданного с помощью URL. Пусто, если + указана опция -channel. Значение переменной можно + получить также с помощью команды ::http::data. +
    + +
    сurrentsize
    + +
    Текущий объем информации в байтах, полученный от + источника. Значение переменной можно получить с помощью + команды ::http::size. +
    + +
    error
    + +
    Если элемент определен, он содержит строку с сообщением об + ошибке, полученную при прерывании HTTP транзакции.
    + +
    http
    + +
    Элемент содержит значение HTTP статуса, полученное от + сервера. Значение переменной можно получить также с помощью + команды ::http::code. Статус + представляет собой строку из трех цифр, значения которой + соответствуют HTTP стандарту. Код 200 соответствует успешному + выполнению транзакции. Коды, начинающиеся с '4' или '5';, + указывают на ошибку. Коды, начинающиеся с '3', соответствуют + ошибкам перенаправления. В этом случае мета данные + Location определяют новый источник информации, который + содержит запрошенные данные.
    + +
    meta
    + +

    Мета данные, описывающие содержание документа. Данный + элемент массива содержит список ключей и их значений. Чтобы + облегчить доступ к данным можно использовать следующую + конструкцию:

    +
    +	  array set meta $state(meta)
    +	
    +

    Некоторые ключи мета данных перечислены ниже, но в HTTP + стандарте их перечислено больше, кроме того, сервер может + добавлять собственные.

    +
    + +
    Content-Type
    + +
    Тип документа. Например, text/html, image/gif, + application/postscript или application/x-tcl.
    + +
    Content-Length
    + +
    Объявленный размер документа. Реальный объем информации, + полученной с помощью команды + ::http::geturl, содержится в переменной + state(size). +
    + +
    Location
    + +
    Измененный адрес документа.
    + +
    status
    + +
    Возможные значения ok,reset или + error. Во время транзакции значение пустое.
    + +
    totalsize
    + +
    Копия значения мета данных Content-Length.
    + +
    type
    + +
    Копия значения мета данных Content-Type.
    + +
    url
    + +

    Запрошенный адрес. Пример:

    +
    +	  # Копирование источника в файл и печать мета данных
    +	  proc ::http::copy { url file {chunk 4096} } { 
    +              set out [open $file w]
    +              set token [geturl $url -channel $out -progress ::http::Progress \
    +                  -blocksize $chunk]
    +              close $out
    +              # Следующая команда завершает строку, начатую
    +              # процедурой http::Progress
    +              puts stderr ""
    +              upvar #0 $token state
    +              set max 0
    +              foreach {name value} $state(meta) {
    +                  if {[string length $name] > $max} { 
    +                      set max [string length $name]
    +	          }
    +	          if {[regexp -nocase ^location$ $name]} { 
    +                      # Обработка перенаправления адреса 
    +                      puts stderr "Location:$value" 
    +	              return [copy [string trim $value] $file $chunk] 
    +	          }
    +	      }
    +	      incr max
    +	      foreach {name value} $state(meta) { 
    +	          puts [format "%-*s %s" $max $name: $value]
    +	      }
    +	      return $token 
    +	  }
    +	  proc ::http::Progress {args} { 
    +	      puts -nonewline stderr . ;
    +	      flush stderr
    +	  }
    +	
    +
    +
    + + diff --git a/hlp/ru/tcl/SafeTcl.html b/hlp/ru/tcl/SafeTcl.html new file mode 100644 index 0000000..15b5004 --- /dev/null +++ b/hlp/ru/tcl/SafeTcl.html @@ -0,0 +1,448 @@ + + + + Safe Tcl + + + +

    Safe Tcl

    + +

    Механизм создания и управления безопасными + интерпретаторами.

    + +

    СИНТАКСИС

    + +
    +      ::safe::interpCreate ?slave? ?options...?
    +      ::safe::interpInit slave ?options...?
    +      ::safe::interpConfigure slave ?options...?
    +      ::safe::interpDelete slave
    +      ::safe::interpAddToAccessPath slave directory
    +      ::safe::interpFindInAccessPath slave directory
    +      ::safe::setLogCmd ?cmd arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Safe Tcl - это механизм безопасного исполнения + ненадежных Tcl скриптов и предоставления этим скриптам + опосредованного доступа к потенциально опасным функциям.

    + +

    Safe Tcl служит для того, чтобы ненадежные скрипты не + смогли нарушить работу вызывающего их приложения: он + предотвращает покушения на несанкционированный доступ к + информации и нарушение целостности вызывающего этот скрипт + процесса.

    + +

    Safe Tcl позволяет интерпретатору-предку + создавать безопасные интерпретаторы с ограниченными + возможностями, в которых содержится набор предопределенных + синонимов для команд source, load, file и exit и сохраняются + возможности автозагрузки команд и пакетов.

    + +

    Безопасный интерпретатор не позволяет получить какую-либо + информацию о структуре файловой системы, поскольку для доступа к + файлам в безопасном интерпретаторе используются специальные + метки. Когда безопасный интерпретатор запрашивает доступ к + файлу, он использует метку как часть виртуального имени файла. + Родительский интерпретатор заменяет метку на реальное имя + каталога и выполняет требуемую операцию с файлом. С помощью + опций команд, описанных ниже, можно выбрать требуемый уровень + безопасности интерпретатора.

    + +

    Все команды для работы с безопасными интерпретаторами + содержатся в пространстве имен safe. Команда ::safe::interpCreate + создает безопасный интерпретатор. Возможные опции команды + описаны ниже, см. "Опции".

    + +

    Команда возвращает имя созданного интерпретатора. Команда ::safe::interpInit + аналогична, но ее первым аргументом должно быть имя + интерпретатора, созданного с помощью команды interp. Команда ::safe::interpDelete + удаляет интерпретатор, имя которого использовано в качестве + аргумента. Команда ::safe::interpConfigure позволяет задать + опции для безопасного интерпретатора или получить информацию + об заданных ранее опциях. Подробно опции описаны ниже + (см. "Опции").

    + +

    Для каждого безопасного интерпретатора, созданного с помощью + команды ::safe::interpCreate + или инициированного с помощью команды ::safe::interpInit + в родительском интерпретаторе создается список доступных + каталогов - виртуальный путь. Каждый каталог в пути связывается + с реальным каталогом локальной файловой системы и с меткой, + доступной в безопасном интерпретаторе. В результате надежный + интерпретатор обходится без сведений о реальной файловой системе + на машине, на которой исполняется интерпретатор. Когда в + надежном интерпретаторе используется метка для доступа к + конкретному файлу (например, для выполнения команды source или load), метка заменяется в + родительском интерпретаторе на настоящее имя каталога и + необходимый файл ищется в файловой системе. Надежный + интерпретатор не получает сведений о реальном имени файла в + файловой системе. Для работы с виртуальными именами файлов + предусмотрены специальные команды. Команда ::safe::interpConfigure + позволяет задавать новый виртуальный путь для интерпретатора. + Команда ::safe::interpAddToAccessPath позволяет + добавлять каталоги к виртуальному пути указанного безопасного + интерпретатора. Команда ::safe::interpFindInAccessPath позволяет + найти каталог в виртуальном пути для безопасного интерпретатора + и получить его метку. Если каталог не найден, выдается сообщение + об ошибке.

    + +

    Команда ::safe::setLogCommand позволяет задать + скрипт, который выполняется при каждом событии в безопасном + интерпретаторе. Этот скрипт вызывается с одним аргументом - + строкой, содержащей описание события.

    + +

    СИНОНИМЫ

    + +

    При создании безопасного интерпретатора в нем определяются + следующие команды - синонимы:

    + +
    +
    source fileName
    + +
    Аналогична команде source, однако + позволяет работать только с файлами в виртуальном пути + безопасного интерпретатора. Имя файла fileName должно + содержать одну из меток, определенных для каталогов в + виртуальном пути. Допустимые имена файлов более подробно + описаны ниже (см. "Безопасность"). +
    + +
    load fileName
    + +
    Требуемый файл (обычно, объектный файл из разделяемой + библиотеки) загружается в безопасный интерпретатор, если его + удается найти. Имя файла должно содержать одну из меток для + каталогов виртуального пути. Кроме того, разделяемый объектный + файл должен содержать безопасную точку входа. Подробности + приведены в описании команды + load. +
    + +
    file ?options?
    + +
    Синоним команды file содержит + только безопасные подкоманды обычной команды file, а именно: dirname, + join, + extension, + root, + tail, + pathname и + split. + Назначение подкоманд приведено в + описании команды file. +
    + +
    exit
    + +
    При выполнении команды безопасный + интерпретатор удаляется, вычисления в нем прерываются, но + родительский интерпретатор продолжает существовать. +
    +
    + +

    КОМАНДЫ

    + +

    В родительском интерпретаторе для работы с безопасными + интерпретаторами предусмотрены следующие команды:

    + +
    +
    ::safe::interpCreate + ?slave? ?options...?
    + +
    Создает безопасный интерпретатор, инициализирует в нем + команды - синонимы, описанные выше, и механизмы автозагрузки + команд и пакетов в соответствии с заданными опциями + (см. "Опции"). Если аргумент + slave отсутствует, имя интерпретатора формируется + автоматически. Команда всегда возвращает имя созданного + интерпретатора. +
    + +
    ::safe::interpInit + slave ?options...?
    + +
    Команда аналогична предыдущей, однако интерпретатор должен + быть уже создан каким-либо иным способом, например с помощью + команды ::interp create-safe. +
    + +
    ::safe::interpConfigure + slave ?options...?
    + +
    Если опции не заданы, возвращает значения всех опций для + указанного безопасного интерпретатора. В противном случае + устанавливает указанные значения опций (подробнее см. "Опции"). +
    + +
    + ::safe::interpDelete slave
    + +
    Удаляет безопасный интерпретатор и + вычищает в родительском интерпретаторе информацию о нем. Перед + удалением выполняется скрипт, заданный с помощью опции + -deletehook, если он был задан. К скрипту добавляется + дополнительный аргумент - имя удаляемого интерпретатора. +
    + +
    + ::safe::interpFindInAccessPath slave + directory
    + +
    Команда возвращает метку, которую можно использовать в + безопасном интерпретаторе для каталога directory. Если + в виртуальном пути нет такого каталога, возвращается сообщение + об ошибке. Пример использования команды: +
    +	  ###Создание безопасного интерпретатора 
    +	  ::safe::interpCreate qqq
    +	  ###Присваивание переменной tk_library метки соответствующего каталога
    +	  qqq eval [list set tk_library \
    +	      [::safe::interpFindInAccessPath qqq $tk_library]] 
    +	  ###Выполнение команды source в безопасном интерпретаторе
    +	  qqq eval source \$tk_library/msgbox.tcl
    +	
    +
    + +
    + ::safe::interpAddToAccessPath slave + directory
    + +
    Команда позволяет добавить к виртуальному пути указанного + безопасного интерпретатора каталог directory. Команда + возвращает значение метки для каталога directory. Если + каталог уже содержался в виртуальном пути, команда только + возвращает его метку и не добавляет его в виртуальный + путь. Пример использования команды (см. пример к предыдущей + команде): +
    +	  ::safe::interpAddToAccessPath qqq $my_lib 
    +	  qqq eval source \$my_lib/\$my_file
    +	
    +
    + +
    + ::safe::setLogCmd ?cmd arg...?
    + +

    Эта команда позволяет задать скрипт, который будет + выполняться при различных событиях, связанных с безопасными + интерпретаторами. Если команда вызвана без аргументов, то + она возвращает установленный ранее скрипт. Вызванная с одним + аргументом - пустой строкой - команда удаляет установленный + ранее скрипт и отменяет процесс журнализации. Установленный + скрипт выполняется с одним дополнительным аргументом - + строкой, описывающей событие. Основное назначение команды - + использование при отладке скриптов, выполняемых в безопасных + интерпретаторах. Используя ее, вы сможете получить полную + информацию об ошибке, в то время как безопасный + интерпретатор возвращает только обобщенное сообщение об + ошибке (это позволяет избежать разглашения в сообщении об + ошибке конфиденциальной информации, например, о реальных + именах файлов). Пример использования:

    +
    +	  ::safe::setLogCmd puts stderr
    +	
    +

    Ниже приведен журнал сессии, в которой безопасный + интерпретатор пытается прочитать файл, который не найден в + виртуальном пути. Обратите внимание, что сам безопасный + интерпретатор получает при этом только сообщение о том, что + файл не найден:

    +
    +	  NOTICE for slave interp10 : Created
    +	  NOTICE for slave interp10 : Setting accessPath=(/foo/bar)
    +	  staticsok=1 nestedok=0 deletehook=()
    +	  NOTICE for slave interp10 : auto_path in interp10 has been
    +	  set to {$p(:0:)}
    +	  ERROR for slave interp10 : /foo/bar/init.tcl: no such file
    +	  or directory
    +	
    +
    +
    + +

    ОПЦИИ

    + +

    Для команд ::safe::interpCreate, + ::safe::interpInit, и :safe::interpConfigure + определены перечисленные ниже опции. Имена опций могут быть + сокращены до минимальных однозначных имен. Имена опций не + чувствительны к регистру, в котором они набраны.

    + +
    +
    -accessPath ?directoryList?
    + +
    Опция задает список каталогов, к которым может иметь доступ + безопасный интерпретатор, и возвращает метки соответствующих + каталогов. Если список не задан или если он пуст, безопасный + интерпретатор получает доступ к каталогам, используемым для + автозагрузки в родительском интерпретаторе. Подробнее + см. "Безопасность".
    + +
    -noStatics
    + +
    Если эта опция задана, то не допускается загрузка статически + связанных пакетов (как load {} Tk). По умолчанию + загрузка таких пакетов разрешена. +
    + +
    -nestedLoadOk
    + +
    Если эта опция задана, безопасный интерпретатор может + загружать пакеты в собственные подинтерпретаторы. По умолчанию + загрузка пакетов в подинтерпретаторы запрещена. +
    + +
    -deleteHook ?script?
    + +
    Если скрипт задан, он выполняется в родительском + интерпретаторе (с дополнительным аргументом - именем + безопасного интерпретатора) перед удалением безопасного + интерпретатора. Если скрипт не задан, то удаляется заданный + ранее скрипт (если такой был) и никаких дополнительных + действий перед удалением безопасного интерпретатора не + производится. По умолчанию скрипт не задан.
    +
    + +

    БЕЗОПАСНОСТЬ

    + +

    Save Tcl не дает полной гарантии безопасности. В частности, он + не защищает от атак на сервер, когда поглощаются все ресурсы + процессора и пользователь не может использовать компьютер для + полезной работы. Однако такие атаки считаются, как правило, + менее опасными, чем несанкционированный доступ к информации и + нарушение целостности, от которых безопасный интерпретатор + защищает. В безопасном интерпретаторе, помимо безопасного набора + команд, который описан в описании команды interp, имеются синонимы для команд source, load, exit и безопасное подмножество + подкоманд команды file. В + безопасном интерпретаторе возможна автозагрузка библиотек и + пакетов. Поскольку эти команды имеют дело с локальной файловой + системой, существует потенциальная опасность использования их + для доступа к конфиденциальной информации. Чтобы предотвратить + эту возможность, в безопасном интерпретаторе используются не + настоящие имена каталогов, а специальные метки. Эти метки + транслируются в реальные имена файлов только в родительском + интерпретаторе.

    + +

    Чтобы исключить доступ к файлам, которые оказались в силу тех + или иных причин в разрешенных для чтения в безопасном + интерпретаторе каталогах, синоним команды source обеспечивает + доступ только к файлам с расширением tcl, в именах которых + содержится ровно одна точка, а общая длина имени не превышает + четырнадцати символов.

    + +

    По умолчанию в Tcl переменной auto_path содержатся метки + для каталогов, содержащихся в аналогичной переменной в + родительском интерпретаторе и их непосредственных подкаталогов. + Первая метка в списке присваивается также Tcl переменной + tcl_library безопасного интерпретатора. Вы можете + сократить этот список, в явном виде задав доступные каталоги для + безопасного интерпретатора с помощью опции + -accessPath.

    + +

    Safe Tcl - это механизм безопасного исполнения + ненадежных Tcl скриптов и предоставления этим скриптам + опосредованного доступа к потенциально опасным функциям.

    + +

    Safe Tcl служит для того, чтобы ненадежные скрипты не + смогли нарушить работу вызывающего их приложения: он + предотвращает покушения на несанкционированный доступ к + информации и нарушение целостности вызывающего этот скрипт + процесса.

    + +

    Safe Tcl позволяет интерпретатору-предку создавать + безопасные интерпретаторы с ограниченными возможностями, в + которых содержится набор предопределенных синонимов для команд + source, load, file и exit и сохраняются возможности + автозагрузки команд и пакетов.

    + +

    Безопасный интерпретатор не позволяет получить какую-либо + информацию о структуре файловой системы, поскольку для доступа к + файлам в безопасном интерпретаторе используются специальные + метки. Когда безопасный интерпретатор запрашивает доступ к + файлу, он использует метку как часть виртуального имени файла. + Родительский интерпретатор заменяет метку на реальное имя + каталога и выполняет требуемую операцию с файлом. С помощью + опций команд, описанных ниже, можно выбрать требуемый уровень + безопасности интерпретатора.

    + +

    Все команды для работы с безопасными интерпретаторами + содержатся в пространстве имен safe. Команда + ::safe::interpCreate создает безопасный интерпретатор. + Возможные опции команды описаны ниже, см. "Опции".

    + +

    Команда возвращает имя созданного интерпретатора. Команда + ::safe::interpInit аналогична, но ее первым аргументом + должно быть имя интерпретатора, созданного с помощью команды + interp.

    + +

    Команда ::safe::interpDelete удаляет интерпретатор, имя + которого использовано в качестве аргумента. Команда + ::safe::interpConfigure позволяет задать опции для + безопасного интерпретатора или получить информацию об заданных + ранее опциях. Подробно опции описаны ниже (см. "Опции").

    + +

    Для каждого безопасного интерпретатора, созданного с помощью + команды ::safe::interpCreate или инициированного с + помощью команды ::safe::interpInit в родительском + интерпретаторе создается список доступных каталогов - + виртуальный путь. Каждый каталог в пути связывается с реальным + каталогом локальной файловой системы и с меткой, доступной в + безопасном интерпретаторе. В результате надежный интерпретатор + обходится без сведений о реальной файловой системе на машине, на + которой исполняется интерпретатор. Когда в надежном + интерпретаторе используется метка для доступа к конкретному + файлу (например, для выполнения команды source или load), метка заменяется в родительском + интерпретаторе на настоящее имя каталога и необходимый файл + ищется в файловой системе. Надежный интерпретатор не получает + сведений о реальном имени файла в файловой системе. Для работы с + виртуальными именами файлов предусмотрены специальные + команды. Команда ::safe::interpConfigure позволяет + задавать новый виртуальный путь для интерпретатора. Команда + ::safe::interpAddToAccessPath позволяет добавлять + каталоги к виртуальному пути указанного безопасного + интерпретатора. Команда ::safe::interpFindInAccessPath + позволяет найти каталог в виртуальном пути для безопасного + интерпретатора и получить его метку. Если каталог не найден, + выдается сообщение об ошибке.

    + +

    Команда ::safe::setLogCommand позволяет задать скрипт, + который выполняется при каждом событии в безопасном + интерпретаторе. Этот скрипт вызывается с одним аргументом - + строкой, содержащей описание события.

    + + diff --git a/hlp/ru/tcl/Tcl.html b/hlp/ru/tcl/Tcl.html new file mode 100644 index 0000000..6cfc34d --- /dev/null +++ b/hlp/ru/tcl/Tcl.html @@ -0,0 +1,194 @@ + + + + Tcl + + +

    Tcl

    + +

    Основные правила синтаксиса команд.

    + +

    ОПИСАНИЕ

    + +

    Синтаксис и семантика языка Tcl определены описанным ниже + образом.

    + +

    Скрипт на Tcl представляет собой одну или более команд. + Символы точки с запятой (;) и новой строки служат + разделителями команд, если не находятся между символами + кавычек. Закрывающие скобки служат окончанием тела команды при + подстановках команд, если не находятся между символами + кавычек.

    + +

    Команда обрабатывается за два прохода. При первом проходе + интерпретатор Tcl разбивает команду на слова и выполняет + подстановки, как рассказано ниже. Эти подстановки выполняются + одинаково для всех команд. Первое слово считается именем + процедуры, которая исполняет команду. Когда процедура найдена, + ей передаются остальные слова команды. Процедура может + интерпретировать каждое из слов произвольным образом, например, + как число, имя переменной, список или Tcl скрипт. Разные + командные процедуры интерпретируют свои слова по-разному.

    + +

    Слова команд разделяются пробельными символами (пробел, + табуляция). Символ новой строки разделяет команды.

    + +

    Если первый символ слова есть двойные кавычки ("), то слово + должно заканчиваться также на двойные кавычки. Если в промежутке + между знаками кавычек находятся точка с запятой, закрывающая + скобка или пробельные символы (включая символ новой строки), то + они будут поняты как обычные символы в составе + слова. Подстановки команд, переменных и подстановки с обратным + слэшем в таком слове описаны ниже. Двойные кавычки не являются + частью слова.

    + +

    Если слово начинается с открывающей фигурной скобки ({), + то оно должно заканчиваться на парную ей закрывающую скобку + (}). Внутри фигурных скобок могут также содержаться + слова в фигурных скобках. При этом каждая открывающая фигурная + скобка должна иметь парную ей закрывающую фигурную + скобку. Однако, если открывающая или закрывающая фигурная скобка + отмечена обратным слэшем, то она не учитывается при поиске + парной скобки. Для символов между фигурными скобками не + выполняется никаких подстановок, за исключением описанной ниже + подстановки "обратный слэш - новая строка". Также не + приписывается никакого специального смысла символам точки с + запятой, новой строки, закрывающей скобки и пробела. Слово будет + состоять из символов между скобками, за исключением самих + скобок.

    + +

    Если слово содержит открывающую квадратную скобку ([), + то Tcl выполняет подстановку команды. Для этого он рекурсивно + вызывает интерпретатор Tcl, который обрабатывает символы, + следующие за скобкой, как скрипт Tcl. Скрипт может иметь любое + количество команд и должен оканчиваться закрывающей квадратной + скобкой (]). Результат выполнения скрипта (т.е., результат его + последней команды) подставляется в слово на место скобок и всех + символов между ними. В слове может быть любое количество + подстановок команд. Подстановки команд не выполняются в словах, + заключенных в фигурные скобки.

    + +

    Если слово содержит символ доллара ($), тогда Tcl + выполняет подстановку переменной: символ доллара и последующие + символы заменяются в слове на значение этой переменной. + Существует три способа подстановки переменной:

    +
    +      $name
    +    
    +

    Здесь name - имя скалярной переменной, оно заканчивается + любым символом, за исключением буквы, цифры или символа + подчеркивания.

    +
    +      $name(index)
    +    
    +

    Здесь name есть имя массива данных, а index - имя + элемента внутри этого массива. name должен состоять + только из букв, цифр и символов подчеркивания. Все виды + подстановок выполняются по отношению к символам + index.

    +
    +      ${name}
    +    
    +

    Здесь name - имя скалярной переменной, оно может + состоять из каких угодно символов, кроме закрывающей фигурной + скобки. В слове может быть любое количество подстановок + переменных. Подстановки переменных не выполняются для слов, + заключенных в фигурные скобки.

    + +

    Если в слове есть символ обратного слэша, то выполняется + подстановка с обратным слэшем. Во всех случаях, кроме + перечисленных ниже, обратный слэш пропускается, а следующий за + ним символ обрабатывается как обычный символ и включается в + состав слова. Таким способом в слово можно включать такие + символы, как двойные кавычки, закрывающие скобки и символ + доллара без непреднамеренной специальной обработки. Ниже + перечислены последовательности символов, для которых подстановка + с обратным слэшем выполняется специальным образом, и + соответствующие подставляемые значения.

    +
    (.*?)(.*?)
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    \aЗвуковой сигнал (гудок) (0х7).
    \bСдвиг на одну позицию влево (0х8).
    \fПрогон листа (0xc).
    \nНовая строка, newline (0ха).
    \rВозврат каретки (0хd).
    \tТабуляция (0х9).
    \vВертикальная табуляция (0xb).
    \<newline>пробелОбратный слэш, символ новой строки и все пробелы и + табуляции после этого символа заменяются на одиночный + пробел. Данная последовательность уникальна в том смысле, + что она замещается в отдельном суб-проходе перед тем, как + начинается непосредственно анализ команды. Поэтому эта + последовательность будет замещена, даже если она стоит + между фигурными скобками, и результирующий пробел будет + интерпретироваться как разделитель слов, если только он + не будет стоять между фигурными скобками или + кавычками.
    \\Обратный слэш (\).
    \oooЦифры ooo (одна, две или все три) дают + восьмеричное значение символа.
    \xhhШестнадцатеричное число "hh" дает шестнадцатеричное + значение символа. Может присутствовать любое количество + цифр.
    +

    Подстановки с обратным слэшем не выполняются в словах, + заключенных в фигурные скобки, кроме подстановки "обратный слэш + - новая строка".

    + +

    Если символ "#" будет стоять в том месте, где Tcl + предполагает первый символ первого слова команды, то этот символ + и все последующие символы до следующего символа новой строки + включительно истолковываются как комментарии и + игнорируются. Символ комментария действителен только тогда, + когда он стоит в начале команды.

    + +

    При воссоздании слов команды каждый символ обрабатывается + интерпретатором Tcl только один раз. Например, если выполнялась + подстановка переменной, то в значении переменной никаких + подстановок не производится; значение вставляется в слово без + изменений. Если выполнялась подстановка команды, то вставленная + команда обрабатывается целиком посредством рекурсивного вызова + интерпретатора Tcl; не делается никаких подстановок перед + рекурсивным вызовом и не делается никаких дополнительных + подстановок в результат исполнения вставленного скрипта.

    + +

    Подстановки не воздействуют на границы слов в команде. + Например, при подстановке переменной все значение переменной + становится частью одного слова, даже если это значение содержит + пробелы.

    + + diff --git a/hlp/ru/tcl/after.html b/hlp/ru/tcl/after.html new file mode 100644 index 0000000..6c92c7a --- /dev/null +++ b/hlp/ru/tcl/after.html @@ -0,0 +1,115 @@ + + + + after + + +

    after

    + +

    Команда after указывает, что некоторая команда должна + быть выполнена с задержкой по времени.

    + +
    +      after ms 
    +      after ms ?script script script...?
    +      after cancel id
    +      after cancel script script script...
    +      after idle ?script script script...?
    +      after info ?id?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда используется для того, чтобы отложить выполнение + программы или выполнить указанную команду в фоновом режиме в + некоторый момент в будущем. У команды есть несколько форм, + зависящих от ее первого аргумента.

    +
    +
    after ms
    + +
    Ms - целое число, задающее задержку в миллисекундах. + Команда обеспечивает задержку на соответствующее число + миллисекунд до своего завершения. Во время задержки приложение + не реагирует на события. +
    + +
    after ms + ?script script script...?
    + +
    В этой форме команда завершается немедленно, но при этом + она обеспечивает выполнение Tcl-команды script script + script через соответствующее время. Команда выполняется + ровно один раз в установленный момент времени. Команда + формируется объединением всех перечисленных аргументов + script таким же образом, как при выполнении команды concat. Команда выполняется + на глобальном уровне (вне контекста какой-либо + Tcl-процедуры). Ошибки во время выполнения команды (если они + происходят) обрабатываются с помощью процедуры bgerror. Команда + after в этой форме возвращает идентификатор, который + может быть использован для отмены отложенной команды с помощью + команды after cancel. +
    + +
    after cancel + id
    + +
    Отменяет исполнение ранее заявленной отложенной команды. + Id определяет, какая именно команда будет отменена. + Значение id должно совпадать со значением, возвращенным + предыдущей командой after. Если соответствующая команда + уже выполнена, команда after cancel игнорируется. +
    + +
    after + cancel script script...
    + +
    Эта команда также отменяет выполнение ранее заявленной + отложенной команды. Все перечисленные скрипты script + объединяются через пробел таким же образом, как при выполнении + команды concat. После + чего ищется отложенная команда с аналогичным скриптом. Если + такая команда будет найдена, ее исполнение будет отменено. В + противном случае команда after cancel игнорируется. +
    + +
    after idle script + ?script script...?
    + +
    Все перечисленные скрипты объединяются через пробел таким + же образом, как при выполнении команды concat. Сформированная таким + образом Tcl команда выполняется позже. Она выполняется ровно + один раз в первом цикле обработчика событий, в котором не + будет других необработанных событий. Команда after idle + возвращает идентификатор, который может быть использован для + отмены отложенной команды. Ошибки во время выполнения команды + (если они происходят) обрабатываются с помощью процедуры bgerror. +
    + +
    after info ?id?
    + +
    Эта команда используется для получения информации об + отложенных командах. Если аргумент id отсутствует , то + возвращает список идентификаторов отложенных команд. Если + аргумент id указан и соответствует идентификатору + отложенной команды, которая не отменена и еще не выполнена, + возвращается список из двух элементов. Первый элемент списка + - Tcl-скрипт соответствующей команды, второй - idle + или timer в зависимости от того, по какому событию + предполагается вызов команды. +
    +
    + +

    Команды after ms и after idle предполагают, что + приложение управляется событиями. Отложенные команды не + выполняются, если в приложении не активизирован цикл обработки + событий. В приложениях, в которых он обычно не активизирован, + таких как tclsh, цикл обработки событий может быть + активизирован с помощью команд vwait и update.

    + + diff --git a/hlp/ru/tcl/append.html b/hlp/ru/tcl/append.html new file mode 100644 index 0000000..396b494 --- /dev/null +++ b/hlp/ru/tcl/append.html @@ -0,0 +1,29 @@ + + + + append + + + +

    append

    + +

    Команда дописывает значения аргументов к значению переменной.

    + +
    +      append varName ?value value value...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда append добавляет все аргументы value к + значению переменной varName. Если такой переменной не + было, она будет создана, и ее значение будет равно соединению + значений аргументов value. Эта команда предоставляет + удобный способ постепенного наращивания длинных переменных. + Если переменная a содержит длинное значение, то команда + append a $b выполняется значительно быстрее, чем + set a $a$b. +

    + + + diff --git a/hlp/ru/tcl/array.html b/hlp/ru/tcl/array.html new file mode 100644 index 0000000..a880121 --- /dev/null +++ b/hlp/ru/tcl/array.html @@ -0,0 +1,150 @@ + + + + array + + +

    array

    + +
    +      array option arrayName ?arg arg...?
    +      array anymore arrayName searchId
    +      array donesearch arrayName searchId
    +      array exists arrayName
    +      array get arrayName ?pattern?
    +      array names arrayName ?pattern?
    +      array nextelement arrayName searchId
    +      array set arrayName list
    +      array size arrayName
    +      array startsearch arrayName
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда предназначена для выполнения перечисленных ниже + операций с массивами. Если иное не оговорено специально, + arrayName должно быть именем существующего массива. + Аргумент option определяет конкретную операцию. Для + команды определены перечисленные ниже опции.

    +
    +
    array anymore + arrayName searchId
    + +
    Возвращает 1 если при выполнении команды поиска (см. + ниже) остались невыбранные элементы массива, и 0 в + противном случае. SearchId указывает операцию поиска, + информация о которой запрашивается (величина searchId + возвращается при выполнении команды array startsearch). Эта + опция особенно удобна, если массив содержит элемент с пустым + именем, поскольку команда array + nextelement не позволяет в таком случае определить, + закончен ли поиск. +
    + +
    array + donesearch arrayName searchId
    + +
    Команда прерывает поиск элементов массива и удаляет всю + связанную с поиском информацию. SearchId указывает + операцию поиска, информация о которой удаляется (величина + searchId возвращается при выполнении команды array + startsearch). Команда возвращает пустую строку. +
    + +
    array exists + arrayName
    + +
    Возвращает 1, если arrayName есть имя + массива, и 0, если такой переменной не существует + или она является скалярной переменной. +
    + +
    array get + arrayName ?pattern?
    + +
    Возвращает список, содержащий пары элементов. Первый + элемент пары - имя элемента массива arrayName, второй + элемент пары - значение этого элемента. Порядок пар не + определен. Если шаблон не задан, то все элементы массива будут + включены в результат. Если шаблон задан, то в результат будут + включены только те элементы, чьи имена соответствуют шаблону + (используя те же правила, что и в команде glob). Если arrayName + не является переменной массива или массив не содержит + элементов, то возвращается пустой список. +
    + +
    array names + arrayName ?pattern?
    + +
    Возвращает список, содержащий имена всех элементов массива, + соответствующих шаблону (используя те же правила, что и в + команде glob). Если шаблона + нет, то команда возвращает имена всех элементов массива. Если + в массиве нет элементов, соответствующих шаблону или + arrayName не является именем переменной массива, то + возвращается пустая строка. +
    + +
    array + nextelement arrayName searchId
    + +
    Возвращает имя следующего элемента массива + arrayName, или пустую строку, если все элементы массива + уже возвращены. SearchId указывает операцию поиска, + (величина searchId возвращается при выполнении команды + array + startsearch). Предупреждение: если в массив внесен + новый элемент или из массива удален один из элементов, то все + операции поиска в этом массиве автоматически заканчиваются, + как если бы была выполнена команда array donesearch. + Соответственно, попытка выполнить после этого команду array + nextelement приведет к ошибке. +
    + +
    array set + arrayName list
    + +
    Устанавливает значение одного или нескольких элементов + массива arrayName. Список list должен иметь + такую же структуру, как список, возвращаемый командой array get, то есть + состоять из четного числа элементов. Все нечетные элементы + списка рассматриваются как имена элементов массива + arrayName, а следующие за ними четные элементы - как новые + значения соответствующих элементов. +
    + +
    array size + arrayName
    + +
    Возвращает строку, содержащую десятичное число, равное + количеству элементов указанного массива. Если + arrayName не является именем массива, возвращается + 0. +
    + +
    array + startsearch arrayName
    + +
    Эта команда инициализирует процесс поиска элементов + указанного массива. После этого имя каждого следующего + элемента массива можно получить с помощью команды array nextelement. По + завершении поиска необходимо выполнить команду array + donesearch. Команда array startsearch возвращает + идентификатор процесса поиска, который должен использоваться в + командах array + nextelement и array + donesearch. Благодаря этому механизму возможно + проведение нескольких процессов поиска элементов одного и того + же массива одновременно. +
    +
    + + diff --git a/hlp/ru/tcl/bell.html b/hlp/ru/tcl/bell.html new file mode 100644 index 0000000..15eed96 --- /dev/null +++ b/hlp/ru/tcl/bell.html @@ -0,0 +1,14 @@ +Bell +

    bell

    +Команда подает звуковой сигнал. +

    СИНТАКСИС

    +

    bell -displayof window +

    ОПИСАНИЕ +

    Команда 'bell'  +подает сигнал громкоговорителем дисплея для window. +Если этот аргумент не +задан, то по умолчанию используется дисплей главного окна приложения. В +некоторых случаях команда гасит работающий в данный момент хранитель +экрана (screen-saver), и окно снова становится видимым.

    +

    ПРИМЕР +

    \ No newline at end of file diff --git a/hlp/ru/tcl/bgerror.html b/hlp/ru/tcl/bgerror.html new file mode 100644 index 0000000..dbbed2d --- /dev/null +++ b/hlp/ru/tcl/bgerror.html @@ -0,0 +1,64 @@ + + + + bgerror + + +

    bgerror

    + +

    Команда bgerror предназначена для обработки фоновых + ошибок.

    + +
    +      bgerror сообщение
    +    
    + +

    ОПИСАНИЕ

    + +

    В Tcl нет встроенной команды bgerror. Если в приложении + тем не менее необходимо обрабатывать фоновые ошибки, + пользователь может определить собственную команду + bgerror, например, как Tcl-процедуру.

    + +

    Фоновые ошибки - это ошибки в командах, которые не вызваны + непосредственно из приложения. Например, фоновыми являются + ошибки в командах, вызванных с помощью конструкции + after. Для нефоновых ошибок + сообщение об ошибке возвращается через вложенные вызовы команд, + пока не достигнет верхнего уровня приложения. После этого + приложение выдает сообщение об ошибке в одной из команд верхнего + уровня. При фоновой ошибке подобный процесс не достигает команд + верхнего уровня и формирование сообщения об ошибке оказывается + затруднительным.

    + +

    Когда Tcl обнаруживает фоновую ошибку, он сохраняет информацию + об ошибке и вызывает команду bgerror с помощью + обработчика событий. Перед вызовом bgerror + восстанавливаются значения переменных errorInfo и errorCode, которые были при + обнаружении ошибки. После этого вызывается команда + bgerror с единственным аргументом - сообщением об ошибке. + Предполагается, что в приложении определена команда + bgerror и что она выдает сообщение об ошибке надлежащим + образом. Если при выполнении команды bgerror не произошло + новой ошибки, возвращаемый ею результат игнорируется.

    + +

    Если при исполнении команды bgerror произошла новая + ошибка (например, если эта команда не существует), сообщение об + ошибке поступает в канал вывода ошибок.

    + +

    Если до вызова обработчиком событий команды bgerror + произошло несколько фоновых ошибок, то, как правило, команда + будет вызвана для каждой из обнаруженных ошибок. Однако, если + сама команда bgerror возвращает код break (см. описание + команды return), + последующие ее вызовы пропускаются.

    + +

    В чисто Tcl-приложениях команда bgerror не + реализована. Однако, в Tk-приложениях определена процедура + bgerror, которая выводит сообщение об ошибке в диалоговое + окно и позволяет пользователю просмотреть стек, описывающий, где + именно эта ошибка произошла.

    + + diff --git a/hlp/ru/tcl/binary.html b/hlp/ru/tcl/binary.html new file mode 100644 index 0000000..5076e00 --- /dev/null +++ b/hlp/ru/tcl/binary.html @@ -0,0 +1,101 @@ + + + + binary + + + +

    binary

    + +

    Команда вставляет и извлекает поля из двоичных строк.

    + +
    +      binary format formatString ?arg arg...?
    +      binary scan string formatString ?varName varName...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда binary предоставляет средства для + манипулирования двоичными данными. Первая из форм команды + конвертирует обычные Tcl-значения arg в двоичное + число. Например, вызванная с аргументами 16 и 22, + она вернет 8-байтовое двоичную строку, состоящую из двух + 4-байтовых чисел, представляющих соответственно 16 и + 22. Вторая форма команды выполняет обратное действие, + она извлекает из двоичной строки данные и возвращает их как + обычные Tcl строки.

    + +
    +
    binary format
    + +

    Команда binary format создает двоичную строку по + правилам, заданным с помощью шаблона formatString. + Содержание этой строки задается дополнительными аргументами + arg. Команда возвращает сформированную двоичную + строку.

    + +

    Шаблон formatString содержит последовательность из + нуля или более спецификаторов преобразования, разделенных + одним или более пробелами. Каждый спецификатор + преобразования состоит из буквы, за которой может следовать + число count. Как правило, спецификатор использует один из + аргументов arg чтобы получить величину для + форматирования. Буква в спецификаторе указывает тип + преобразования (форматирования). Число count обычно + указывает сколько объектов для форматирования выбирается из + значения arg. Соответственно, count должно + быть неотрицательным десятичным числом. Если значение count + равно *, это обычно указывает, что надо использовать все + значение аргумента. Если число аргументов arg не + соответствует числу спецификаторов, требующих для себя + дополнительного аргумента, выдается ошибка.

    + +

    Обычно результат каждого нового преобразования дописывается + в конец возвращаемой строки. Однако, с помощью специальных + спецификаторов точку ввода нового значения (курсор) можно + передвигать по формируемой строке.

    + +

    Ниже приведены допустимые значения спецификаторов + преобразований и описаны соответствующие преобразования.

    + +
    + +
    a ?count?
    + +

    Передает в выходную строку count символов из + соответствующего аргумента arg. Если в arg + содержится меньше count байт, добавляются нулевые + байты. Если в arg содержится больше count + байт, "лишние" байты игнорируются. Если + count равно *, используются все байты из + arg. Если count отсутствует, используется + один байт. Например, команда

    +
    +	      binary format a7a*a alpha bravo charlie
    +	    
    +

    вернет строку, эквивалентную alpha\000\000bravoc.

    +
    + +
    A ?count?
    + +

    То же, что и a, за исключением того, что для + заполнения используются не нулевые байты, а + пробелы. Например, команда

    +
    +	      binary format A6A*A alpha bravo charlie
    +	    
    +

    вернет alpha bravoc.

    +
    + +
    b ?count?
    + +

    Передает в выходную строку count бит в порядке + от младших к старшим в каждом байте. Аргумент arg + должен состоять из последовательности нулей и единиц. + Порядок байтов в выходной строке тот же, что и во + входной информации. Лишние биты отсекаются, недостающие + дополняются нулями. По умолчанию форматируется один бит. + Если число форматируемых битов не соответствует целому + числу байтов, недостающие биты дополняются нулями. + \ No newline at end of file diff --git a/hlp/ru/tcl/break.html b/hlp/ru/tcl/break.html new file mode 100644 index 0000000..a2f8122 --- /dev/null +++ b/hlp/ru/tcl/break.html @@ -0,0 +1,30 @@ + + + + break + + + +

    break

    + +

    Команда прекращает выполнение цикла.

    + +
    +      break
    +    
    + +

    ОПИСАНИЕ

    + +

    Обычно данная команда помещается внутрь цикла, например + созданного командами for, foreach или while. Команда возвращает код + TCL_BREAK, который вызывает завершение исполнения наименьшего + охватывающего ее цикла. Цикл завершается нормальным образом (без + ошибки) как если бы он отработал до конца. Код TCL_BREAK + обрабатывается также в некоторых других ситуация - при + исполнении команды catch, + при обработке событий и в скрипте самого верхнего уровня. +

    + + diff --git a/hlp/ru/tcl/case.html b/hlp/ru/tcl/case.html new file mode 100644 index 0000000..88ab730 --- /dev/null +++ b/hlp/ru/tcl/case.html @@ -0,0 +1,59 @@ + + + + case + + + +

    case

    + +

    Команда case исполняет один из нескольких скриптов в + зависимости от полученного значения.

    + +
    +      case string ?in? patList body ?patList body...?
    +      case string ?in? {patList body ?patList body...?}
    +    
    + +

    ОПИСАНИЕ

    + +

    Замечание. Команда case - устаревшая, она поддерживается + только для совместимости с предыдущими версиями. В последующих + версиях она может быть опущена. Поэтому предпочтительнее + использование команды switch. +

    + +

    Команда сравнивает string со всеми аргументами + patList по очереди. Каждый аргумент patList + представляет собой один или несколько (список) образцов. Если + string соответствует одному из образцов, то case + рекурсивно вызывает интерпретатор Tcl, передает ему следующий за + этим списком образцов скрипт body для выполнения и + возвращает результат этого выполнения. Каждый аргумент + patList состоит из одного или нескольких образцов. Каждый + образец может содержать спецсимволы, как в команде string match. Кроме + того, есть специальный образец default. Соответствующий + ему скрипт выполняется, если string не соответствует + никакому другому образцу.

    + +

    Если string не соответствует ни одному из образцов, а + образец default не используется, то case вернет + пустую строку.

    + +

    У команды есть две формы записи для аргументов patList и + body. Первая использует отдельные аргументы для каждого + шаблона и команды. Эта форма более удобна, если в образцах или + командах желательно выполнить какие-либо подстановки. Во второй + форме все шаблоны и команды объединены в один аргумент, который + должен быть списком, состоящим из шаблонов и команд. Вторая + форма позволяет проще записывать многострочные команды, + поскольку при этом фигурные скобки вокруг списка позволяют не + ставить обратный слэш в конце каждой строки. Однако из-за этих + фигурных скобок подстановки в шаблонах и командах не + производятся. Поэтому одна и та же команда, записанная в + различных формах, может работать по-разному. + + + diff --git a/hlp/ru/tcl/catch.html b/hlp/ru/tcl/catch.html new file mode 100644 index 0000000..320c369 --- /dev/null +++ b/hlp/ru/tcl/catch.html @@ -0,0 +1,39 @@ + + + + catch + + + +

    catch

    + +

    Команда выполняет скрипт и обрабатывает ошибки, если они + возникают.

    + +
    +      catch script ?varName?
    +    
    + +

    ОПИСАНИЕ

    + +

    Данную команду можно использовать для того, чтобы не дать + возникшим ошибкам прекратить процесс интерпретации команд. Для + исполнения скрипта script команда catch рекурсивно + вызывает интерпретатор Tcl и всегда возвращает код TCL_OK, + независимо от возможно возникших при исполнении скрипта + script ошибок.

    + +

    Команда catch возвращает десятичную строку, содержащую + код, возвращаемый Tcl-интерпретатором по исполнению скрипта. + Если при исполнении скрипта не возникло ошибок, возвращается код + 0 (TCL_OK). В противном случае возвращается ненулевое значение, + соответствующее коду прерывания (см. файл tcl.h). Если задан + аргумент varName, он определяет имя переменной, которой + присваивается значение, возвращаемое скриптом (результат + выполнения или сообщение об ошибке). Команда catch + обрабатывает все прерывания, в том числе от команд break и continue. +

    + + diff --git a/hlp/ru/tcl/cd.html b/hlp/ru/tcl/cd.html new file mode 100644 index 0000000..bd367c3 --- /dev/null +++ b/hlp/ru/tcl/cd.html @@ -0,0 +1,26 @@ + + + + cd + + + +

    cd

    + +

    Команда предназначена для перехода в другой каталог.

    + +

    СИНТАКСИС

    + +
    +      cd dirName
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда делает текущим каталогом каталог dirName, или, + если параметр dirName не указан, каталог, заданный в + переменной окружения HOME. Команда возвращает пустую строку.

    + +

    ПРИМЕР

    + + diff --git a/hlp/ru/tcl/clock.html b/hlp/ru/tcl/clock.html new file mode 100644 index 0000000..70bf299 --- /dev/null +++ b/hlp/ru/tcl/clock.html @@ -0,0 +1,281 @@ + + + + clock + + + +

    clock

    + +

    С помощью команды clock можно получить и преобразовать + значение времени.

    + +
    +      clock option ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда выполняет одно из перечисленных ниже действий, с + помощью которых можно получить и преобразовать строки или + значения, являющиеся той или иной формой записи времени. + Параметр option определяет выполняемое командой действие, + одно из следующего списка (параметр может быть сокращен): +

    +
    clock clicks
    + +
    Возвращает целое число, с высокой точностью представляющее + машинное время. Единица измерения зависит от операционной + системы и компьютера и представляет собой минимальную + доступную величину, например, счетчик циклов процессора. Эта + величина может использоваться только для относительного + измерения пройденного времени. +
    + +
    clock format clockValue ?-format + string? ?-gmt boolean?
    + +

    Переводит целое число, возвращаемое командами clock + seconds, clock scan или командами file atime, file mtime и file + ctime в удобочитаемую форму. Если в команде + присутствует аргумент -format, следующий аргумент + должен быть строкой, описывающей формат представления + времени. Строка состоит из описаний полей, состоящих из + символа % и буквы. Все остальные символы в строке + просто копируются в результат. Ниже перечислены допустимые + описания полей.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    %%вставляет %
    %aсокращенное название дня недели (Mon, Tue, etc.).
    %Aполное название дня недели (Monday, Tuesday, etc.).
    %bсокращенное название месяца (Jan, Feb, etc.).
    %Bполное название месяца.
    %cлокальные дата и время.
    %dдень месяца (01 - 31).
    %Hчасы в двадцатичетырехчасовом формате (00 - 23).
    %Iчасы в двенадцатичасовом формате (00 - 12).
    %jдень года (001 - 366).
    %mномер месяца (01 - 12).
    %Mминуты (00 - 59).
    %pAM/PM индикатор (до/после полудня).
    %Sсекунды (00 - 59).
    %Uнеделя года (01 - 52), Воскресенье - первый день + недели.
    %wномер дня недели (Воскресенье = 0).
    %Wнеделя года (01 - 52), Понедельник первый день + недели.
    %xлокальный формат даты.
    %Xлокальный формат времени.
    %yгод без столетия (00 - 99).
    %Yгод со столетием (например, 1990)
    %Zимя часового пояса.
    Кроме того, в некоторых операционных + системах могут поддерживаться
    %Dдата в формате %m/%d/%y.
    %eдень месяца (1 - 31), без нулей впереди.
    %hсокращенное имя месяца.
    %nновая строка.
    %rвремя в формате %I:%M:%S %p.
    %Rвремя в формате %H:%M.
    %tтабуляция.
    %Tвремя в формате %H:%M:%S.
    + + +

    Если аргумент -format не задан, используется + формат %a %b %d %H:%M:%S %Z %Y. Если задан аргумент + -gmt, следующий аргумент должен быть булевой + величиной. Значение true означает, что используется время по + Гринвичу, значение false означает, что используется время по + локальному часовому поясу, который задан для операционной + системы.

    +
    + + +
    clock scan + dateString ?-base clockVal? ?-gmt + boolean?
    + +

    Переводит дату dateString в целое число (см. clock seconds). + Команда может перевести в число любую стандартную строку, + содержащую время и/или дату, включая название часового + пояса. Если строка содержит только время, предполагается + текущая дата. Если название часового пояса не указано, + предполагается локальный часовой пояс (если значение опции + -gmt не равно true. В этом случае предполагается, что + время задано по Гринвичу).

    + +

    Если в команде указан флаг -base, следующий аргумент + должен содержать время в виде целого числа. По этому числу + определяется дата и используется вместо указанной в строке + или текущей. Такая возможность полезна при необходимости + перевести в целое число время на заданную дату.

    + +

    Аргумент dateString должен состоять из одной или + более спецификаций следующих видов:

    + + + + + + + + + + + + + + + + + + + +
    timeВремя суток в форме: hh?:mm?:ss?? + ?meridian? ?zone? или в форме + hhmm?meridian? ?zone?, где + meridian - индикатор AM или PM, zone - + имя часового пояса. Если индикатор meridian не + определен, hh считается числом часов в + двадцатичетырехчасовом формате. +
    date Месяц, день и, возможно, год. Допустимые форматы + mm/dd?/yy?, monthname dd?, yy?, + dd monthname?yy? и day, dd monthname + yy. По умолчанию год считается текущим годом. Если + год меньше 100, то года 00-38 считаются годами в + диапазоне 2000-2038, а года 70-99 считаются годами в + диапазоне 1970-1999. Года 39-70 могут быть + недопустимыми на некоторых платформах. Для тех + платформ, для которых они определены, они считаются + годами в диапазоне 1939-1999. +
    relative timeВремя относительно текущего момента. Формат - число + единица измерения. Возможные единицы измерения + year, fortnight, month, + week, day, hour, + minute(или min), и second (или + sec). Единицы измерения могут указываться во + множественном числе, например 3 weeks. Кроме того, + могут использоваться модификаторы: tomorrow, + yesterday, today, now, + last, this, next, ago. +
    + +

    Реальная дата вычисляется в следующей последовательности. + Сначала определяется абсолютная дата и/или время, которые + переводятся в целое число. Это число используется как базис, + к которому добавляется заданный день недели. Далее + используется относительное время. Если задана дата, а время + (абсолютное или относительное) отсутствует, считается, что + это полночь. И последним шагом производится коррекция + вычисленной даты, при которой учитываются летнее время и + число дней в различных месяцах.

    +
    + +
    clock seconds
    + +
    Возвращает время в секундах от начала + "эпохи". Может использоваться для вычисления + разности времен. "Эпоха" зависит от используемой + операционной системы и компьютера. +
    +
    + + diff --git a/hlp/ru/tcl/close.html b/hlp/ru/tcl/close.html new file mode 100644 index 0000000..2919021 --- /dev/null +++ b/hlp/ru/tcl/close.html @@ -0,0 +1,55 @@ + + + + close + + +

    close

    + +

    Команда закрывает открытый канал.

    + +
    +      close channelId
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда close закрывает канал, идентификатор которого + задан аргументом channelId. Идентификатор + channelId возвращается командами open и socket при открытии + канала.

    + +

    Команда отправляет все накопившиеся в выходном буфере данные на + выходное устройство канала, удаляет все данные во входном + буфере, закрывает назначенное каналу устройство или файл. Доступ + к каналу прекращается.

    + +

    Для каналов в блокирующем и неблокирующем режимах действие + команды несколько различно. Если канал находится в блокирующем + режиме, команда завершается только после завершения вывода + данных из буфера. В противном случае команда завершается + немедленно, а вывод данных из буфера производится в фоновом + режиме. Канал закрывается после завершения вывода.

    + +

    Если канал в блокирующем режиме открыт для конвейера, команда + close завершается после завершения порожденного + процесса.

    + +

    Если канал совместно используется несколькими + интерпретаторами, то команда делает канал channelId + недоступным в вызвавшем команду интерпретаторе, но не оказывает + никакого другого действия на канал, пока все использующие канал + интерпретаторы не закроют его. При выполнении команды в + последнем из интерпретаторов, использовавших его, выполняются + описанные выше действия. Подробности совместного использования + канала несколькими интерпретаторами приведены в описании + команды interp. +

    + +

    Команда close возвращает пустую строку. Она может + порождать ошибку, если при выводе данных произошла ошибка. +

    + + diff --git a/hlp/ru/tcl/concat.html b/hlp/ru/tcl/concat.html new file mode 100644 index 0000000..931d4a4 --- /dev/null +++ b/hlp/ru/tcl/concat.html @@ -0,0 +1,38 @@ + + + + concat + + + +

    concat

    + +

    Команда соединяет списки в один общий список.

    + +

    СИНТАКСИС

    + +
    +      concat ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Аргументы arg считаются списками, команда concat + объединяет их в один общий список. При этом она удаляет пробелы + в начале и конце arg, и вставляет по одному пробелу между + ними. Команда допускает произвольное число аргументов. Например, + команда +

    +
    +      concat a b {c d e} {f {g h}}
    +    
    +

    возвращает список

    +
    +      a b c d e f {g h}
    +    
    + +

    Если не задано никаких аргументов, то команда возвращает + пустую строку.

    + + + diff --git a/hlp/ru/tcl/continue.html b/hlp/ru/tcl/continue.html new file mode 100644 index 0000000..d6b5a04 --- /dev/null +++ b/hlp/ru/tcl/continue.html @@ -0,0 +1,32 @@ + + + + continue + + + +

    continue

    + +

    Команда continue прекращает выполнение текущего шага + цикла.

    + +
    +      continue
    +    
    + +

    ОПИСАНИЕ

    + +

    Обычно данная команда помещается внутрь цикла, например, + созданного командами for, foreach или while. Команда возвращает код + TCL_CONTINUE, который вызывает завершение текущей + итерации наименьшего охватывающего ее цикла. Управление + возвращается команде цикла, которая начинает следующий шаг + цикла. Код TCL_CONTINUE обрабатывается также в некоторых + других ситуациях - при исполнении команды catch и в скрипте самого + верхнего уровня. +

    + + diff --git a/hlp/ru/tcl/eof.html b/hlp/ru/tcl/eof.html new file mode 100644 index 0000000..3ed754f --- /dev/null +++ b/hlp/ru/tcl/eof.html @@ -0,0 +1,26 @@ + + + + eof + + + +

    eof

    + +

    Команда проверяет в канале условие конца файла.

    + +

    СИНТАКСИС

    + +
    +      eof channelId
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда eof возвращает " 1 " если во время + последней операции ввода в канале channelId произошло + условие конца файла, и " 0 " в противном случае.

    + +

    ПРИМЕР

    + + diff --git a/hlp/ru/tcl/error.html b/hlp/ru/tcl/error.html new file mode 100644 index 0000000..277d9c0 --- /dev/null +++ b/hlp/ru/tcl/error.html @@ -0,0 +1,56 @@ + + + + error + + + + +

    error

    + +

    Команда генерирует ошибку.

    + +

    СИНТАКСИС

    + +
    +      error message info code
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда возвращает код TCL_ERROR, прерывающий + интерпретацию команды. Строка message возвращается + приложению, чтобы указать, что именно произошло. Если задан + непустой аргумент info, его значение присваивается + глобальной переменной errorInfo. Переменная + errorInfo обычно используется для формирования сведений о + вложениях команды, в которой произошла ошибка. Другими словами, + как только оказывается, что невыполненная команда была вложена в + другую команду, информацию об этой команде добавляется к + errorInfo. Если же аргумент info был задан, этого + не происходит. Эта особенность позволяет при использовании + команды error совместно с командой catch выдать + информацию о реальном месте ошибки (а не о месте вызова команды + error). Для этого можно использовать следующую + конструкцию:

    + +
    +      catch {...} errMsg
    +      set savedInfo $errorInfo
    +      ...
    +      error $errMsg $savedInfo
    +    
    + +

    Если задан аргумент code, то его значение будет + присвоено глобальной переменной errorCode. Эта переменная + предназначена для хранения машинного описания ошибки в тех + случаях, когда такое описание возможно. Форматы различных + сообщений приведены в разделе tell. Если аргумент не задан, + переменной errorCode в процессе обработки + Tcl-интерпретатором ошибки, порожденной командой, присваивается + значение "NONE".

    + +

    ПРИМЕР

    + + diff --git a/hlp/ru/tcl/eval.html b/hlp/ru/tcl/eval.html new file mode 100644 index 0000000..c99a3f4 --- /dev/null +++ b/hlp/ru/tcl/eval.html @@ -0,0 +1,29 @@ + + + + eval + + + +

    eval

    + +

    Команда исполняет Tcl-скрипт.

    + +

    СИНТАКСИС

    + +
    +      eval arg arg...
    +    
    + +

    ОПИСАНИЕ

    + +

    Аргументы команды eval вместе образуют Tcl-скрипт, + состоящий из одной или нескольких команд. Команда соединяет + аргументы (подобно команде concat) и передает их рекурсивно + запущенному интерпретатору Tcl. Команда возвращает результат + работы интерпретатора (или обнаруженную им ошибку).

    + +

    ПРИМЕР

    + + diff --git a/hlp/ru/tcl/exec.html b/hlp/ru/tcl/exec.html new file mode 100644 index 0000000..db86774 --- /dev/null +++ b/hlp/ru/tcl/exec.html @@ -0,0 +1,255 @@ + + + + exec + + + +

    exec

    + +

    Команда запускает подпроцессы.

    + +

    СИНТАКСИС

    + +
    +      exec ?switches? arg ?arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Аргументы команды определяют один или нескольких подпроцессов, + которые необходимо выполнить. Аргументы принимают форму + конвейера, в котором каждый arg задает одно слово + команды, а каждая отдельная команда порождает подпроцесс.

    + +

    Если первые аргументы команды начинаются со знака + "-", они считаются ключами команды, а не частью + описания конвейера.

    + +

    Возможные ключи:

    +
    +
    -keepnewline
    + +
    Сохраняет конечные пробелы в выходных данных + конвейера. Обычно они отсекаются.
    + +
    -
    + +
    Отмечает конец ключей. Аргумент, следующий за этим ключом, + рассматривается как первый аргумент arg, даже если он + начинается со знака "-".
    +
    + +

    Перечисленные ниже аргументы (пары аргументов) используют не + для определения подпроцессов, а для перенаправления потоков + ввода и вывода между ними. В выражения типа + "<fileName" fileName может писаться + как отдельно, так и слитно + ("<fileName>").

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    |разделяет команды в конвейере. Стандартный вывод + предыдущей команды направляется на стандартный вход + следующей команды.
    |&разделяет команды в конвейере. Стандартный вывод и + стандартный вывод ошибок предыдущей команды направляются + на стандартный вход следующей команды. Такое выражение + перебивает выражения типа 2> и >&.
    < fileNameфайл fileName отрывается и используется как + стандартный ввод для первой команды конвейера.
    <@ fileIdв этой форме fileId это идентификатор файла, + открытого с помощью команды open. Он используется как + стандартный ввод для первой команды конвейера. Файл должен + быть открыт для чтения.
    << valuevalue используется как стандартный ввод для + первой команды конвейера.
    > fileNameСтандартный вывод последней команды перенаправляется в + файл fileName и перезаписывает его содержимое.
    2> fileNameСтандартный вывод ошибок всех команд в конвейере + перенаправляется в файл fileName и перезаписывает + его содержимое.
    >& fileNameСтандартный вывод последней команды и стандартный вывод + ошибок всех команд в конвейере перенаправляется в файл + fileName и перезаписывает его содержимое.
    >>fileNameСтандартный вывод последней команды перенаправляется в + файл fileName и добавляется к его прежнему + содержимому.
    2>>fileNameСтандартный вывод ошибок всех команд в конвейере + перенаправляется в файл fileName и добавляется к его + прежнему содержимому.
    >>& fileNameСтандартный вывод последней команды и стандартный вывод + ошибок всех команд в конвейере перенаправляется в файл + fileName и добавляется к его прежнему содержимому. +
    >@ ileIdВ этой форме fileId это идентификатор файла, + открытого с помощью команды open. Стандартный вывод + последней команды перенаправляется в файл fileName + и перезаписывает его содержимое. Файл должен быть открыт + для записи.
    2>@ fileIdВ этой форме fileId это идентификатор файла, + открытого с помощью команды open. Стандартный вывод + ошибок всех команд в конвейере перенаправляется в файл + fileName и перезаписывает его содержимое. Файл должен + быть открыт для записи. +
    >&@ fileIdВ этой форме fileId это идентификатор файла, + открытого с помощью команды open. Стандартный вывод + последней команды и стандартный вывод ошибок всех команд в + конвейере перенаправляется в файл fileName и + перезаписывает его содержимое. Файл должен быть открыт для + записи.
    + +

    Если стандартный вывод последней команды конвейера не был + перенаправлен, то команда exec возвращает его + значение. Если одна из команд конвейера вернула код ошибки, была + прервана или приостановлена, то команда exec вернет код + ошибки. При этом сообщение об ошибке будет включать стандартный + вывод конвейера и сообщение об ошибке. В переменной + errorCode будет записана + дополнительная информация о последней встреченной ошибке. Если + хотя бы одна из команд конвейера пишет информацию об ошибках в + файл и стандартный вывод ошибок не перенаправлен, команда + exec вернет ошибку, сообщение об ошибке будет включать в + себя стандартный вывод конвейера, дополненный сообщениями об + ошибках (если их было несколько) и стандартным выводом + ошибок.

    + +

    Если последний символ результата исполнения конвейера или + сообщения об ошибке - перевод каретки, то он будет удален из + результата или сообщения соответственно. Это соответствует + общему правилу Tcl, по которому возвращаемая величина, как + правило, не оканчивается символом перевода каретки. Однако, если + указана опция -keepnewline, символ перевода каретки в + конце сохраняется.
    Если стандартный ввод конвейера не + перенаправлен с помощью символов "<", + "<<" или "<@", стандартный ввод в первую + команду конвейера осуществляется со стандартного ввода + приложения.

    + +

    Если последним аргументом конвейера является "&", + конвейер выполняется в фоновом режиме. В этом случае команда + exec возвращает список идентификаторов всех процессов + конвейера. Стандартный вывод последней команды конвейера, если + он не перенаправлен, выводится на стандартный вывод + приложения. Стандартный вывод ошибок, если он не перенаправлен, + осуществляется в стандартный вывод ошибок приложения.

    + +

    Первое слово в каждой команде считается именем команды. В нем + выполняются тильда - подстановки. Если получившийся при этом + результат не содержит слэшей, соответствующая команда ищется в + каталогах, перечисленных в переменной окружения PATH. Если имя + команды после подстановок содержит слэши, оно должно указывать + на исполняемый файл, доступный из текущего каталога. Никакие + другие подстановки в командах, например, принятые в shell + подстановки * и ?, не выполняются. +

    + +

    ВОПРОСЫ ПЕРЕНОСИМОСТИ НА ДРУГИЕ ПЛАТФОРМЫ

    + +
    +
    Windows (все версии)
    + +

    Чтение и запись с использование ``@ fileId'' не + работают. Исполнение 16- и 32-разрядных приложений + различается между собой и отличается от описанного выше. Tk + консоль не реализует всех стандартных возможностей + ввода/вывода.

    + +

    В командах допускается использование как прямых, так и + обратных слэшей при указании пути команды. Однако, если путь + является аргументом команды, это может оказаться и не + так.

    + +

    Двойной слэш в путях указывает на сетевой адрес.

    +
    + +
    Windows NT
    + +
    Для выполнения встроенных команд shell, таких, как + dir или copy, перед ними необходимо указать + "cmd.exe /c".
    + +
    Windows 95
    + +
    Для выполнения встроенных команд shell, таких, как + dir или copy, перед ними необходимо указать + "command.com /c".
    + +
    Windows 3.X
    + +
    Возможности команды exec сильно ограничены.
    + +
    Macintosh
    + +
    Команда exec не реализована.
    + +
    Unix
    + +
    Команда exec позволяет исполнять любые приложения и + действует как описано выше.
    + +
    + + diff --git a/hlp/ru/tcl/exit.html b/hlp/ru/tcl/exit.html new file mode 100644 index 0000000..597b3a5 --- /dev/null +++ b/hlp/ru/tcl/exit.html @@ -0,0 +1,24 @@ + + + + exit + + + +

    exit

    + +

    Команда exit прекращает исполнение приложения.

    + +

    СИНТАКСИС

    + +
    +      exit returnCode
    +    
    + +

    ОПИСАНИЕ

    + +

    Прекращает процесс и возвращает системе returnCode в + качестве кода завершения. Если returnCode не определен, + то команда использует значение по умолчанию 0.

    + + diff --git a/hlp/ru/tcl/expr.html b/hlp/ru/tcl/expr.html new file mode 100644 index 0000000..d08941e --- /dev/null +++ b/hlp/ru/tcl/expr.html @@ -0,0 +1,397 @@ + + + + expr + + + +

    expr

    + +

    Команда expr вычисляет значение выражения.

    + +
    +      expr arg ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда соединяет аргументы arg через пробел в одно + Tcl-выражение, вычисляет и возвращает его значение. Допустимые + в Tcl-выражениях операторы математических действий составляют + подмножество операторов языка С, и имеют такое же значение и + порядок выполнения, что и соответствующие операторы С. Почти + всегда результатом вычисления является число: целое или с + плавающей запятой. Например, результат выражения

    +
    +        expr 8.2 + 6
    +      
    +

    равен 14.2.

    + +

    Выражения в Tcl отличаются от выражений в С способом описания + операндов. Кроме того, Tcl-выражения поддерживают нечисловые + операнды и сравнение строк.

    + +

    ОПЕРАНДЫ

    + +

    Выражение Tcl состоит из комбинации операндов, операторов и + скобок. Между ними всеми можно ставить пробелы, потому что при + вычислении значения пробелы игнорируются. По возможности, все + операнды интерпретируются как целые числа, если не задано + иное. Целые числа могут быть десятичными числами (обычно), + восьмеричными (если первая цифра числа есть 0) или + шестнадцатеричными (если первые два символа числа - 0х). Если + операнд не подпадает ни под один из названных форматов, он + считается числом с плавающей запятой, если это возможно. Числа + с плавающей запятой можно задавать любым из способов, + воспринимаемым совместимым с ANSI компилятором С. Исключение + составляет запрет в большинстве версий на суффиксы f, + F, l и L. Примеры правильных чисел с + плавающей запятой: 2.1, 3., 6e4, 7.91e+16. Если числовая + интерпретация невозможна, то операнд считается строковым, и + работать с ним может только ограниченный набор операторов.

    + +

    Операнды могут быть заданы одним из следующих способов:

    + +
      +
    • числовым значением - целым или с плавающей + запятой;
    • + +
    • переменной Tcl, используя обычную нотацию со знаком + $. В качестве операнда будет использовано значение + переменной;
    • + +
    • строкой символов, заключенной в двойные кавычки. Анализатор + выражения выполнит подстановки переменных, подстановки команд + и подстановки с обратным слэшем; полученное значение будет + использовано в качестве операнда;
    • + +
    • строкой, заключенной в фигурные скобки. Все символы между + открывающей и закрывающей скобками будут считаться операндом + без каких-либо подстановок;
    • + +
    • командой Tcl, заключенной в угловые скобки. Команда будет + выполнена, и ее результат будет использован в качестве + операнда;
    • + +
    • как вызов математической функции, аргумент которой может + иметь любую из перечисленных выше форм, например + sin($x). Список допустимых математических функций + приведен ниже.
    • +
    + +

    Если в выражении имели место подстановки (например, внутри + двойных кавычек), то они будут обработаны процессором выражения, + хотя анализатор команд тоже может выполнить свою часть + подстановок (дополнительную серию подстановок) до вызова + процессора выражения. Поэтому обычно, чтобы избежать выполнения + анализатором команд подстановок в содержимое выражения, лучше + всего заключать выражение в фигурные скобки.

    + +

    В качестве примеров рассмотрим простые выражения, в которых + переменная a имеет значение "3", а значение переменной + b есть "6". Тогда выражение в левой части + каждой строки даст значение в ее правой части:

    + + + + + + + + + + + + + + + + + + + + +
    3.1 + $a6.1
    2 + ($a.$b)5.6
    4*[llength "6 2"]8
    {word one} < "word $a"0
    + +

    ОПЕРАТОРЫ

    + +

    Действующие операторы перечислены ниже в порядке убывания + приоритетности исполнения. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    - + ~ !Унарный минус, унарный плюс, побитовое неравенство NOT, + логическое NOT. Ни один из этих операторов не может быть + использован со строковыми операндами, а побитовое NOT + может использоваться только с целыми числами.
    * / %Умножить, разделить, остаток деления. Ни один из этих + операторов не может быть использован со строковыми + операндами, а оператор остатка может использоваться только + для целых чисел.
    + -Сложение и вычитание. Могут использоваться для любых + числовых операндов.
    << >>Сдвиг влево и вправо. Операторы можно использовать + только с целыми числами. Сдвиг вправо также сдвигает и + знаковый бит.
    < > <= >=Операторы булевой алгебры: меньше, больше, не больше, не + меньше. Каждый оператор дает результат 1, если неравенство + верно, и 0 - в обратном случае. Кроме числовых операндов, + операторы можно применять для строковых выражений, в этом + случае выполняется сравнение строк.
    == !=Булевские операторы: равно и не равно. Результат + операции - число 0 или 1. Операторы можно применять с + любыми аргументами.
    & Оператор побитового AND. Используется только с целыми + операндами.
    ^ Оператор побитового исключающего OR. Применяется только + с целыми числами.
    | Оператор побитового OR. Применяется только с целыми + числами.
    && Оператор логического AND. Результат равен 1, если оба + операнда равны 1, и 0 - в обратном случае. Операндами + могут быть любые числа, как целые, так и с плавающей + запятой.
    || Оператор логического OR. Результат равен 0, если оба + операнда равны 0, и 1 - в обратном случае. Операндами + могут быть любые числа, как целые, так и с плавающей + запятой.
    x?y:z Конструкция if-then-else, подобная аналогичной + конструкции в языке C. Операнд х должен иметь + числовое значение. Если значение х не равно нулю, + то результат команды будет у. В обратном случае + результат будет z.
    + +

    Более подробные описания операторов можно найти в любом + руководстве по языку С.

    + +

    Операторы одного уровня приоритета исполнения выполняются по + очереди, слева направо. Например, команда

    +
    +      expr 4*2 < 7
    +    
    +

    возвращает результат 0.

    + +

    Подобно языку C, операторы &&, ||, и + ?: имеют свойство "ленивого вычисления", т.е., + если операнд не нужен для получения результата, то он не + вычисляется. Например, в команде

    +
    +        expr {$v? [a] : [b]}
    +    
    +

    будет вычислено только одно из выражений [a] и + [b], в зависимости от значения $v. Однако, это + справедливо только тогда, когда все выражение заключено в + фигурные скобки. В противном случае анализатор Tcl сначала + вычислит [a] и [b], и только потом вызовет команду + expr.

    + +

    МАТЕМАТИЧЕСКИЕ ФУНКЦИИ

    + +

    Tcl поддерживает в выражениях следующие математические + функции:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    acos cos hypot sinh
    asin cosh log sqrt
    atan exp log10 tan
    atan2 floor pow tanh
    ceil fmod sin
    + +

    Каждая из этих функций вызывает одноименную функцию из + математической библиотеки.

    + +

    Кроме них можно использовать также перечисленные ниже функции + преобразования чисел и генерации случайных чисел.

    +
    +
    abs(arg)
    + +
    Возвращает абсолютное значение аргумента. Аргумент может + быть целым или числом с плавающей точкой. Результат + возвращается в такой же форме.
    + +
    double(arg)
    + +
    Переводит аргумент в десятичное число в плавающей + точкой.
    + +
    int(arg)
    + +
    Переводит аргумент в целое число, обрезая дробную + часть.
    + +
    rand()
    + +
    Возвращает случайное десятичное число в интервале + [0,1]. Исходное значение, используемое при генерации, + берется от внутренних часов или задается с помощью функции + srand.
    + +
    round(arg)
    + +
    Округляет число до целого.
    + +
    srand(arg)
    + +
    Аргумент, который должен быть целым числом, используется для + генерации последовательности случайных чисел. Возвращает + первое случайное число из последовательности. Каждый + интерпретатор может использовать собственное значение и + порождать собственную последовательность случайных чисел.
    +
    + +

    Пользовательские приложения могут определять дополнительные + функции, используя процедуру Tcl_CreateMathFunc().

    + +

    ТИПЫ ДАННЫХ, ТОЧНОСТЬ ВЫЧИСЛЕНИЙ И + ПЕРЕПОЛНЕНИЯ

    + +

    Все внутренние вычисления с целыми числами выполняются с + C-типом long, все внутренние вычисления с числами с + плавающей запятой выполняются с C-типом double. + +

    В общем случае, обнаружение переполнения и исчезновения + значения при операциях с целыми числами зависит от поведения + функций конкретной библиотеки С, и потому для промежуточных + результатов не может считаться надежным. Переполнение и + исчезновение значения при операциях с числами с плавающей + запятой обнаруживаются на аппаратном уровне, что обычно надежно + обеспечивается.

    + +

    При необходимости выполняются преобразования внутренних + представлений операндов между целыми, строковыми и с плавающей + запятой. При арифметических вычислениях используются целые числа + до тех пор, пока не будет подставлено или указано число с + плавающей запятой. После этого тип данных будет с плавающей + запятой.

    + +

    Числа с плавающей запятой возвращаются либо с точкой, либо с + буквой e, так что они заведомо не похожи на целые значения. + Например:

    +
    +        expr 5 / 4
    +    
    +

    вернет 1, тогда как

    +
    +      expr 5 / 4.0
    +      expr 5 / ( [string length "abcd"] + 0.0 )
    +    
    +

    оба вернут 1.25.

    + +

    Выражение

    +
    +      expr 20.0/5.0
    +    
    +

    вернет 4.0, а не 4.

    + +

    ОПЕРАЦИИ СО СТРОКАМИ

    + +

    Операторы сравнения могут работать со строковыми аргументами, + хотя при вычислении выражений аргументы по возможности + интерпретируются как целые или числа с плавающей запятой. Если + один из операндов строковый, а другой - число, то числовой + операнд будет конвертирован в строковый. Например, обе команды

    +
    +        expr {"0x03" > "2"}
    +        expr {"0y" < "0x12"}
    +    
    +

    вернут 1. При этом первое сравнение будет выполнено как + сравнение чисел, а второе будет выполнено как сравнение строк, + после того как второй операнд будет преобразован в строку + 18.

    + +

    Если необходимо сравнить аргументы именно как строки, а + операнды могут быть восприняты неоднозначно, то рекомендуется + использовать команду string compare вместо операторов + вида ==.

    + +

    ПРОИЗВОДИТЕЛЬНОСТЬ ПРИЛОЖЕНИЙ

    + +

    Байтовый компилятор Tcl генерирует наиболее быстрый и + компактный код, если выражения заключать в скобки. Это связано с + тем, что в общем случае, в выражениях подстановки выполняются + дважды: один раз - грамматическим анализатором Tcl, и второй раз + - командой expr. Наиболее трудным является случай, когда + выражение без фигурных скобок содержит подстановки команд. +

    + + diff --git a/hlp/ru/tcl/fblocked.html b/hlp/ru/tcl/fblocked.html new file mode 100644 index 0000000..dad45a4 --- /dev/null +++ b/hlp/ru/tcl/fblocked.html @@ -0,0 +1,36 @@ + + + + fblocked + + + +

    fblocked

    + +

    Проверяет, что предыдущая операция ввода исчерпала всю + информацию для ввода.

    + +

    СИНТАКСИС

    + +
    +      fblocked channelId
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда fblocked возвращает "1" если последняя + операция ввода по каналу channelId возвратила меньше + информации, чем было запрошено, поскольку вся доступная + информация уже исчерпана. Например, если команда gets вызвана, когда для ввода + доступны только три символа без символов конца строки, команда + gets вернет пустую строку, + последующий вызов команды fblocked вернет 1.

    + +

    СМ. ТАКЖЕ

    + +

    gets и read. +

    + + diff --git a/hlp/ru/tcl/fconfigure.html b/hlp/ru/tcl/fconfigure.html new file mode 100644 index 0000000..c421389 --- /dev/null +++ b/hlp/ru/tcl/fconfigure.html @@ -0,0 +1,209 @@ + + + + fconfigure + + +

    fconfigure

    + +

    fconfigure - устанавливает и читает опции канала.

    + +
    +      fconfigure channelId 
    +      fconfigure channelId name
    +      fconfigure channelId name value ?name value...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда fconfigure устанавливает и читает опции + каналов. Аргумент channelId определяет конкретный канал, + с которым работает команда. Если аргументы name и + value отсутствуют, команда возвращает список, содержащий + поочередно имена опций и их значения для канала. Если имя опции + указано, а значение - нет, команда возвращает текущее значение + указанной опции. Если в команде указаны одна или больше пар имен + и значений, то команда устанавливает каждой из перечисленных + опций указанное значение. В этом случае команда возвращает + пустую строку.

    + +

    Описанные ниже опции поддерживаются для всех типов каналов. + Кроме того, каждый тип канала может иметь дополнительно + собственные опции. Они приведены в описаниях команд создания + каналов, например, в описании команды socket.

    + +
    +
    -blocking boolean
    + +
    Опция -blocking определяет, вызывают ли команды + ввода/вывода блокировку процесса. Величина этой опции должна + быть правильным булевым выражением. Обычно каналы открываются + в блокирующем режиме. Если канал переведен в неблокирующий + режим, это окажет влияние на выполнение команд gets, read, puts, flush и close (смотри описание + соответствующих команд). Чтобы работа в неблокирующем режиме + выполнялась корректно, в приложении должен быть запущен + обработчик событий (например, с помощью команды vwait). +
    + +
    -buffering newValue
    + +

    Если аргумент newValue равен full, система + ввода-вывода будет накапливать вывод в буфере, пока буфер не + заполнится целиком. После этого буфер будет выдан в канал.

    + +

    Если аргумент newValue равен line, система + ввода-вывода будет выдавать буфер в канал каждый раз при + поступлении символа конца строки.

    + +

    Если аргумент newValue равен none, система + ввода-вывода будет выводить каждый символ сразу после его + поступления.

    + +

    Значение по умолчанию full для всех каналов, кроме + устройств типа терминалов. Для них значение по умолчанию + line.

    +
    + +
    -buffersize newSize
    + +
    Аргумент newSize должен быть целым числом. Его + значение определяет размер буфера (в байтах), используемый для + данного канала. Величина newSize должна быть в пределах + от десяти до миллиона, что позволяет задавать величину буфера + от десяти до миллиона байт. +
    + +
    -eofchar char
    + +
    -eofchar {inChar outChar}
    + +
    Эти опции поддерживают структуру файлов DOS, в которой + символ Control-z (\x1a) используется как символ конца + файла. Если аргумент char не равен пустой строке, то + этот символ, если он встречается во вводе, означает конец + файла. При выводе информации символ конца файла выдается при + закрытии канала. Если аргумент char равен пустой + строке, то специальный символ конца файла отсутствует. Для + каналов ввода-вывода элементы списка {inChar + outChar} определяют символы конца файла для ввода и + вывода соответственно. Пользователь может указать в списке + единственный символ, который будет использоваться и для ввода, + и для вывода. Однако, при запросе команда возвратит текущие + установки в виде списка из двух одинаковых элементов. Значения + по умолчанию для символов конца файла - пустая строка всегда, + кроме файлов Windows. В этом случае inChar равно + Control-z (\x1a), outChar - пустой строке. +
    + +
    -translation mode
    + +
    -translation {inMode outMode}
    + +

    В Tcl-скриптах конец строки всегда представляется + единственным символом новой строки (\n). Однако, в реальных + файлах и устройствах конец строки может быть представлен + разными символами или наборами символов в зависимости от + используемой платформы или даже конкретного устройства. + Например, на UNIX- платформах символ новой строки + используется в файлах, в то время как для сетевых соединений + используется последовательность "возврат каретки - + новая строка". При вводе данных (например, при + исполнении команд gets + или read) система ввода - + вывода Tcl сама автоматически преобразует внешнее + представление конца строк во внутреннее представление + (символ новой строки). При выводе (например, при команде puts) также происходит + преобразование ко внешнему формату представления конца + строки. Значение аргумента по умолчанию равно auto. + При этом символы конца строки для большинства ситуаций + правильно определяются автоматически. Однако, опция + -translation позволяет при необходимости задать + соответствующие символы в явном виде.

    + +

    Аргумент mode задает представление конца строки для + каналов, открытых только на чтение или только на + запись. Список {inMode outMode} определяет + представление конца строки для каналов ввода - вывода. + Пользователь может указать в списке единственный символ, + который будет использоваться и для ввода, и для вывода. + Однако, при запросе команда возвратит текущие установки в + виде списка из двух одинаковых элементов.

    + +

    Поддерживаются следующие значения опции:

    +
    +
    auto
    + +
    При вводе в качестве конца строки могут использоваться + символ возврата каретки (cr), символ новой строки + (lf), или их последовательность + (crlf). Причем разные строки могут заканчиваться + по-разному. Все эти представления будут переведены в + символ новой строки. При выводе используется разное + представление для различных платформ и каналов. Для + сетевых соединений на всех платформах используется + crlf, для всех Unix- платформ - lf, для + Macintosh - cr, а для всех Windows-платформ - + crlf. +
    + +
    binary
    + +
    Никакого преобразования символов конца строки не + производится. Это значение опции очень схоже со значением + lf, однако, при значении binary пустая + строка воспринимается как конец файла (см. описание опции + -eofchar). +
    + +
    cr
    + +
    В качестве символа конца строки используется возврат + каретки (cr). Соответственно, при вводе символ + возврата каретки преобразуется в символ новой строки, а + при выводе, наоборот, символ новой строки преобразуется в + символ возврата каретки. Это значение опции используется, + обычно, на Macintosh-платформах. +
    + +
    crlf
    + +
    В качестве символа конца строки используется + последовательность "возврат каретки - новая + строка" (crlf). Соответственно, при вводе + последовательность "возврат каретки - новая + строка" преобразуется в символ новой строки, а при + выводе, наоборот, символ новой строки преобразуется в + последовательность "возврат каретки - новая + строка". Это значение опции используется обычно на + Windows-платформах и при сетевых соединениях. +
    + +
    lf
    + +
    В качестве символа конца строки используется символ + новой строки (lf). Никакого преобразования символов + конца строки при вводе и выводе не происходит. Это + значение опции используется, обычно, на UNIX-платформах. +
    +
    +
    +
    + +

    См. также close(n), flush(n), gets(n), puts(n), read(n), socket(n) +

    + + + diff --git a/hlp/ru/tcl/fcopy.html b/hlp/ru/tcl/fcopy.html new file mode 100644 index 0000000..f8cfdf1 --- /dev/null +++ b/hlp/ru/tcl/fcopy.html @@ -0,0 +1,130 @@ + + + + fcopy + + + +

    fcopy

    + +

    Копирует данные из одного канала в другой.

    + +
    +      fcopy inchan outchan ?-size size? ?-command callback?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда fcopy копирует данные из одного канала ввода - + вывода, заданного идентификатором канала inchan, в другой + канал ввода - вывода, заданный идентификатором канала + outchan. Команда позволяет упростить буферизацию и + избежать излишнего копирования в Tcl-системе ввода - вывода, а + также избежать использования больших объемов памяти при + копировании данных по таким медленным каналам, как сетевые + соединения.

    + +

    Команда fcopy передает данные из канала inchan, + пока не будет достигнут конец файла или не будет передано + size байтов. Если аргумент -size не задан, + передается весь файл. Если опция -command не задана, + команда блокирует процесс до завершения копирования и возвращает + число переданных байтов.

    + +

    При наличии аргумента -command команда fcopy + работает в фоновом режиме. Она завершается немедленно, а команда + callback вызывается позже, когда завершается процесс + копирования. Команда callback вызывается с одним или + двумя дополнительными аргументами, которые указывают число + переданных байтов. Если при исполнении фонового процесса + произошла ошибка, второй аргумент - строка описания ошибки. При + фоновом выполнении копирования каналы inchan и + outchan не обязательно открывать в неблокирующем режиме, + команда fcopy выполнит это автоматически. Однако при + этом необходимо организовать обработку событий, например, с + помощью команды vwait или + используя Tk.

    + +

    Не допускается выполнение других операций ввода - вывода с теми + же каналами во время фонового копирования. Если один из каналов + во время копирования будет закрыт, процесс копирования будет + прерван и вызова команды callback не произойдет. Если + будет закрыт канал ввода данных, то все полученные данные, + хранящиеся в очереди, будут выданы в выходной канал.

    + +

    Необходимо отметить, что канал inchan может стать + открытым на чтение во время копирования. Все обработчики + файловых событий во время фонового копирования должны быть + выключены, чтобы они не создавали помех копированию. Любые + попытки ввода - вывода с помощью обработчиков файловых событий + будут завершены с ошибкой "канал занят".

    + +

    Команда fcopy преобразует символы конца строк в + соответствии со значениями опций -translation для + соответствующих каналов (см. описание команды fconfigure). Преобразование + означает, в частности, что число прочитанных и число переданных + символов может отличаться. В синхронном режиме команда + возвращает только число переданных в outchan канал + символов. В фоновом режиме только это число подается на вход + команды callback.

    + +

    ПРИМЕРЫ

    + +

    Первый пример показывает, как в фоновом режиме получить число + переданных байтов. Конечно, это показательный пример, поскольку + то же самое может быть сделано проще без использования фонового + режима.

    +
    +      proc Cleanup {in out bytes {error {}}} {
    +          global total
    +          set total $bytes
    +          close $in
    +          сlose $out
    +          if {[string length $error]!= 0} { 
    +              # error occurred during the copy
    +          }
    +      }
    +      #### Открыть файл на чтение
    +      set in [open $file1]
    +      #### Открыть сетевое соединение
    +      set out [socket $server $port]
    +      #### Скопировать, по окончании копирования вызвать
    +      Cleanup
    +      fcopy $in $out -command [list Cleanup $in $out]
    +      #### Ожидать завершения копирования
    +      vwait total
    +    
    + +

    Второй пример показывает, как можно организовать копирование + файла по фрагментам и проверять конец файла.

    + +
    +      proc CopyMore {in out chunk bytes {error {}}} { 
    +          global total done
    +          incr total $bytes
    +          if {([string length $error]!= 0) || [eof $in] {
    +              set done $total
    +              close $in
    +              close $out
    +          } else {
    +              fcopy $in $out -command [list CopyMore $in $out $chunk] \
    +                  -size $chunk
    +          }
    +      }
    +      set in [open $file1]
    +      set out [socket $server $port]
    +      #### Установить размер фрагмента для копирования.
    +      set chunk 1024
    +      set total 0
    +      fcopy $in $out -command [list CopyMore $in $out $chunk]\
    +          -size $chunk
    +      vwait done
    +    
    + +

    См. также eof(n), fblocked(n), fconfigure(n).

    + + + diff --git a/hlp/ru/tcl/file.html b/hlp/ru/tcl/file.html new file mode 100644 index 0000000..60597c1 --- /dev/null +++ b/hlp/ru/tcl/file.html @@ -0,0 +1,396 @@ + + + + file + + +

    file

    + +

    Команда для работы с файлами и их именами.

    + +
    +      file option name ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда осуществляет различные действия с файлами, их + именами или свойствами. Аргумент name содержит имя + файла. Если он начинается с символа "~", то перед + выполнением команды выполняются "тильда"-подстановки, + как описано в filename. + Опция команды указывает, какие действия необходимо выполнить с + файлом. Ниже приведены возможные опции. В команде их имена могут + быть сокращены до уровня, сохраняющего уникальность их имен.

    + +
    +
    file atime name
    + +
    Возвращает десятичную строку, содержащую время последнего + доступа к файлу name. Время представляется стандартным + для POSIX образом в числе секунд от фиксированного начального + момента (обычно, с 1 января 1970 г.). Если файл не существует + или время последнего доступа не может быть получено, выдается + сообщение об ошибке. +
    + +
    file attributes + name
    + +
    file attributes name ?option?
    + +
    file attributes name ?option + value option value...?
    + +

    Эта подкоманда возвращает или устанавливает зависящие от + платформы атрибуты файла. Первая форма возвращает список + атрибутов и их значений, вторая возвращает значение + указанного атрибута, а третья - позволяет установить + значения одного или нескольких атрибутов. Возможные атрибуты + перечислены ниже.

    + +

    НА UNIX-ПЛАТФОРМАХ:

    + +
      +
    • -group - возвращает или устанавливает имя + группы. В команде группа может быть задана числовым + идентификатором, но возвращается всегда имя группы.
    • + +
    • -owner - возвращает или устанавливает имя + "хозяина" файла. В команде хозяин может быть задан + числовым идентификатором, но возвращается всегда имя + хозяина.
    • + +
    • -permissions - возвращает или устанавливает + восьмеричный код, используемый командой операционной + системы chmod. Символьное описание соответствующих + атрибутов файла не поддерживается.
    • +
    + +

    НА WINDOWS-ПЛАТФОРМАХ

    + +

    На Windows-платформах поддерживаются атрибуты + -archive, -hidden, -longname (атрибут + не может быть установлен), -readonly, + -shortname (атрибут не может быть установлен), + -system.

    + +

    НА MACINTOSH-ПЛАТФОРМАХ

    + +

    На Macintosh-платформах поддерживаются атрибуты + -creator, -hidden, -readonly, + -type.

    +
    + +
    file copy ?-force? + ?--? source target
    + +
    file copy ?-force? ?--? + source ?source...? targetDir
    + +
    Первая форма используется для того, чтобы скопировать файл + или каталог source соответственно в файл или каталог + target. Вторая форма используется, чтобы скопировать + файл(ы) или каталог(и) внутрь существующего каталога + targetDir. Если один из аргументов source есть имя + каталога, то этот каталог копируется рекурсивно вместе со всем + его содержимым. При копировании существующие файлы не + перезаписываются, если только не указана опция + -force. Попытки перезаписать непустой каталог, а также + перезаписать каталог файлом или файл каталогом приводят к + ошибке, даже если опция -force + указана. Аргументы команды обрабатываются в порядке + перечисления до первой ошибки. Отметка "--" означает конец + опций. Следующий аргумент считается именем файла или каталога, + даже если он начинается с символа "-". +
    + +
    file delete ?-force? + ?--? pathname ?pathname...?
    + +
    Удаляет файлы или каталоги, заданные аргументами + pathname. Непустые каталоги удаляются, только если задана + опция -force. Попытка удалить несуществующий + файл не рассматривается как ошибка. Попытка удалить файл, + доступный только для чтения, приведет к удаления файла, даже + если опция -force не задана. Аргументы команды + обрабатываются в порядке перечисления до первой + ошибки. Отметка "--" означает конец опций. Следующий + аргумент считается именем файла или каталога, даже если он + начинается с символа "-". +
    + +
    filedirname name
    + +

    Возвращает имя, составленное из всех элементов + name, кроме последнего. Если name - относительное имя + файла и состоит из единственного элемента, возвращает + "." (":" для Macintosh). Если имя + указывает на корневой каталог, возвращается имя корневого + каталога.

    + +

    Например:

    +
    +          file dirname c:/
    +        
    +

    вернет c:/.

    + +

    "Тильда"-подстановки выполняются, только если они + необходимы для формирования правильного результата.

    + +

    Например:

    +
    +          file dirname ~/src/foo.c
    +        
    +

    вернет ~/src, тогда как

    +
    +          file dirname ~
    +        
    +

    вернет /home (или что-то подобное).

    +
    + +
    file executable + name
    + +
    Возвращает 1, если файл name исполнимый, и + 0 в противном случае.
    + +
    file exists name
    + +
    Возвращает 1, если файл name существует, + и пользователь имеет права на просмотр каталога, в котором + лежит файл, и 0 в противном случае. +
    + +
    file extension + name
    + +
    Возвращает все символы в name, начиная с последней + точки в последнем элементе. Если в последнем элементе нет + точек, возвращается пустая строка. +
    + +
    file isdirectory name
    + +

    Возвращает 1, если name - имя каталога, + и 0 в противном случае.

    +
    +          file isfile name
    +        
    +

    Возвращает 1, если файл name - + регулярный файл, и 0 в противном случае.

    +
    + +
    file join name + ?name...?
    + +

    Соединяет аргументы name в одно имя с помощью + разделителя, используемого на данной платформе. Если + очередной аргумент name представляет собой + относительное имя, он присоединяется к предыдущим, в + противном случае предыдущие аргументы отбрасываются, и + процесс формирования имени начинается заново с текущего + аргумента.

    + +

    Например:

    +
    +          file join a b /foo bar
    +        
    +

    вернет /foo/bar.

    + +

    Аргументы name могут содержать разделитель, это не + помешает получить правильный результат для используемой + платформы ("/" для Unix и Windows, ":" + для Macintosh).

    +
    + +
    file lstat name + varName
    + +
    То же самое, что опция stat, описанная ниже, за + исключением того, что используется команда ядра lstat + вместо stat. Это означает, что если name есть + имя связи, то команда вернет данные о связи, а не об исходном + файле. Для платформ, не поддерживающих связи, команды + полностью идентичны. +
    + + +
    file mkdir dir + ?dir...?
    + +
    Создает все перечисленные каталоги. Для каждого аргумента + dir команда создает все несуществующие родительские + каталоги и сам каталог dir. Если указан существующий + каталог, ничего не происходит. При этом команда считается + выполненной успешно. Попытка перезаписать существующий файл + каталогом приведет к ошибке. Аргументы команды обрабатываются + в порядке перечисления до первой ошибки. +
    + +
    file mtime name
    + +
    Возвращает десятичную строку, содержащую время последнего + изменения файла name. Время представляется стандартным + для POSIX образом в числе секунд от фиксированного начального + момента (обычно, с 1 января 1970 г.). Если файл не существует + или время последнего изменения не может быть получено, + выдается сообщение об ошибке. +
    + +
    file nativename name
    + +
    Возвращает имя файла в виде, характерном для используемой + платформы. Опция полезна для подготовки исполнения файла с + помощью команды exec под + Windows. +
    + +
    file owned name
    + +
    Возвращает 1, если файл name принадлежит + пользователю, и 0 в противном случае. +
    + +
    file pathtype name
    + +
    Возвращает одно из значений absolute, + relative, volumerelative. Если name + указывает на определенный файл в определенном томе, + возвращается absolute. Если name указывает на + имя файла относительно текущего рабочего каталога - + возвращается relative. Если name указывает имя + файла относительно текущего рабочего каталога в определенном + томе или на определенный файл в текущем рабочем томе, + возвращается volumerelative. +
    + +
    file readable name
    + +
    Возвращает 1, если файл name доступен для + чтения пользователю, и 0 в противном случае. +
    + +
    file readlink name
    + +
    Возвращает имя связи name (например, имя файла, на + который указывает name). Если name не есть + связь, или ее невозможно прочитать, возвращает ошибку. На + платформах, на которых связи не поддерживаются, опция не + определена. +
    + +
    file rename ?-force? ?--? + source target
    + +
    file rename ?-force? ?--? + source ?source...? targetDir
    + +
    Первая форма используется для того, чтобы переименовать + файл или каталог source соответственно в файл или + каталог target (и переместить их в соответствующий + каталог, если это необходимо). Вторая форма используется, + чтобы переместить файл(ы) или каталог(и) внутрь существующего + каталога targetDir. Если один из аргументов + source есть имя каталога, то этот каталог перемещается + рекурсивно вместе со всем его содержимым. При перемещении + существующие файлы не перезаписываются, если только не указана + опция -force. Попытки перезаписать непустой каталог, а + также перезаписать каталог файлом или файл каталогом приводят + к ошибке, даже если опция -force указана. Аргументы + команды обрабатываются в порядке перечисления до первой + ошибки. Отметка "-" означает конец опций. Следующий + аргумент считается именем файла или каталога, даже если он + начинается с символа "-". +
    + +
    file rootname + name
    + +
    Возвращает все символы в name за исключением + последней точки в последнем элементе. Если в последнем + элементе нет точек, возвращается name. +
    + +
    file size name
    + +
    Возвращает десятичную строку, содержащую размер файла в + байтах. Если файл не существует или его размер не может быть + получен, выдается ошибка. +
    + +
    file split name
    + +

    Возвращает список элементов пути name. Первый элемент + списка при этом имеет тот же тип пути, что и name. Все + остальные элементы - относительные. Разделители удаляются, + если только они не необходимы для указания на относительный + тип элементов. Например, под Unix

    +
    +          file split /foo/~bar/baz
    +        
    +

    вернет / foo/~bar baz, чтобы гарантировать, что + последующие команды не попытаются выполнить "тильда"- + подстановку в третьем элементе.

    +
    + +
    file stat name varName
    + +
    Исполняет вызов функции ядра stat и записывает + возвращаемую информацию о name в элементы массива + varName. Формируются следующие элементы массива: + atime, ctime, dev, gid, + ino, mode, mtime, nlink, + size, type, uid. Значения всех элементов, + кроме type, - десятичные строки. Описания их приведены + в описании команды ядра stat. Элемент type + содержит тип файла в том же виде, в каком он возвращается + командой file type. Команда file stat возвращает + пустую строку. +
    + +
    file tail name
    + +
    Возвращает все символы в name после последнего + разделителя каталогов. Если в name нет каталогов, + возвращает name. +
    + +
    file type name
    + +
    Возвращает строку, содержащую тип файла. Возможные значения + file, directory, characterSpecial, + blockSpecial, fifo, link или socket. +
    + +
    file volume
    + +
    Возвращает список, содержащий абсолютные пути ко всем + подмонтированным томам. На Macintosh-платформах это список + всех подмонтированных дисков, локальных и сетевых. На + Unix-платформах команда всегда возвращает '/', + поскольку все файловые системы монтируются как локальные. На + Windows-платформах команда возвращает список локальных дисков + (например, {a:/ c:/}). +
    + +
    file writable name
    + +
    Возвращает 1, если файл name доступен для + записи, и 0 в противном случае. +
    +
    + +

    ПРОБЛЕМЫ ПЕРЕНОСИМОСТИ

    + +
    +
    Unix
    + +
    На Unix-платформах эти команды всегда используют реальные, а + не эффективные идентификаторы пользователя и группы.
    +
    + +

    См. также filename.

    + + diff --git a/hlp/ru/tcl/fileevent.html b/hlp/ru/tcl/fileevent.html new file mode 100644 index 0000000..9213fcc --- /dev/null +++ b/hlp/ru/tcl/fileevent.html @@ -0,0 +1,107 @@ + + + + fileevent + + +

    fileevent

    + +

    Исполняет скрипт, когда канал открывается на чтение или + запись.

    + +
    +      fileevent channelId readable ?script?
    +      fileevent channelId writable ?script?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда используется для создания обработчиков файловых + событий. Обработчик файловых событий связывает канал и скрипт + таким образом, что скрипт исполняется, когда канал открывается + на чтение или запись. Обработчики файловых событий используются, + чтобы получение данных от другого процесса управлялось + событиями. При этом получающий процесс, ожидая поступление + данных, сможет продолжать взаимодействовать с + пользователем. Если приложение выполняет команду gets или read из блокирующего канала, оно + не способно обслуживать другие события, поэтому оно кажется + пользователю "замороженным". С использованием файловых + событий процесс обратится к команде gets или read только когда информация + поступит в канал. +

    + +

    Аргумент channelId должен быть идентификатором + открытого канала, который вернула предыдущая команда open или socket. Если в команде присутствует + аргумент script, команда создает новый обработчик + событий: скрипт script будет выполнен, когда канал + channelId откроется на чтение или запись (в зависимости + от второго аргумента команды). В такой форме команда возвращает + пустую строку. Обработчики для обработки открытия файла на + чтение или запись соответственно независимы и могут создаваться + и удаляться по одному, независимо один от другого. Однако для + каждого из событий может быть только один обработчик, так что + если команда fileevent выполняется, когда соответствующий + обработчик (в текущем интерпретаторе) уже задан, новый скрипт + заменит старый. +

    + +

    Если аргумент script не задан, команда fileevent + возвратит скрипт, заданный для данного события для канала + channelId, или пустую строку, если скрипт не + задан. Обработчик событий удаляется автоматически при закрытии + канала или удалении интерпретатора. +

    +

    Канал считается открытым на чтение, если на соответствующем + устройстве есть непрочитанные данные. Также канал считается + открытым на чтение, если есть непрочитанные данные во входном + буфере, кроме того случая, когда команда gets не смогла найти в буфере + законченную строку. Эта особенность позволяет читать файл + построчно в неблокирующем режиме, используя обработчик + событий. Канал также считается открытым на чтение, если + достигнут конец соответствующего файла или на соответствующем + устройстве сгенерирована ошибка. Поэтому скрипт должен уметь + распознавать и корректно обрабатывать такие ситуации, чтобы не + возникало зацикливаний, когда скрипт не может прочитать данные, + завершается и тут же вызывается вновь. +

    +

    Канал считается открытым на запись, если по крайней мере один + байт данных может быть записан в соответствующий файл или + передан на соответствующее устройство, или на устройстве (в + файле) сгенерирована ошибка. +

    +

    Событийно управляемый ввод - вывод лучше всего работает с + каналами, переведенными в неблокирующий режим с помощью команды + fconfigure. В + блокирующем режиме команды puts, gets или read могут заблокировать + процесс, если они не могут быть выполнены сразу (например, при + попытке прочитать больше данных, чем доступно в настоящий + момент). При этом никакой обработки событий не происходит. В + неблокирующем режиме команды puts, gets или read никогда не блокируют + процесс. Детальное описание работы команд с блокирующими и + неблокирующими каналами приведено в описаниях соответствующих + команд. +

    +

    Скрипт обработчика файловых событий выполняется на самом + верхнем уровне вне контекста какой-либо процедуры в + интерпретаторе, в котором обработчик событий был задан. Если при + исполнении скрипта происходит ошибка, сообщение о ней выдается с + помощью процедуры bgerror. Кроме того, при ошибке + соответствующий обработчик событий удаляется. Это делается для + того, чтобы избежать зацикливания из-за ошибок в обработчике. +

    + + diff --git a/hlp/ru/tcl/filename.html b/hlp/ru/tcl/filename.html new file mode 100644 index 0000000..68f3929 --- /dev/null +++ b/hlp/ru/tcl/filename.html @@ -0,0 +1,155 @@ + + + + filename + + +

    filename

    + +

    Правила именования файлов в Tcl.

    + + +

    ВВЕДЕНИЕ

    + +

    Все команды Tcl и процедуры С, использующие имена файлов в + качестве аргументов, позволяют использовать имена в форме, + установленной для данной платформы. Кроме того, на всех + платформах Tcl поддерживается синтаксис UNIX с целью + предоставления удобного способа составления простых имен + файлов. Тем не менее, скрипты, предназначенные для переноса + между платформами, не должны пользоваться конкретной формой имен + файлов. Вместо этого такие скрипты должны использовать команды + file split и file join для + преобразования имен к нужной форме. +

    + +

    ТИПЫ ПУТЕЙ

    + +

    Все имена файлов поделены на три типа, в зависимости от + начальной точки для отсчета пути: абсолютные, относительные и + имена внутри тома (volume-relative).

    + +

    Абсолютные имена являются самодостаточными, они содержат полный + путь файла внутри тома и адрес корневого каталога + тома. Относительные имена являются неполными, они указывают + положение файла по отношению к текущему каталогу. Имена внутри + тома занимают промежуточное положение между первыми двумя, они + указывают положение файла относительно корневого каталога + текущего тома или относительно текущего каталога указанного + тома.

    + +

    Для определения типа указанного пути можно использовать команду + file pathtype.

    + +

    СИНТАКСИС ПУТЕЙ

    + +

    Пути формируются различным образом для различных платформ. + Текущая платформа определяется по значению переменной + tcl_platform(platform):

    +
    +
    mac
    + +
    Для Macintosh-платформ Tcl поддерживает две формы + представления путей: с двоеточием, в обычном для Macintosh + стиле, и со слэшем, в Unix-стиле. Если путь не содержит + двоеточий, то он считается путем в в Unix-стиле. При этом + "." означает текущий каталог, ".." - + родительский каталог для текущего каталога. Однако такие + имена, как / или /.. считаются именами каталогов + в Macintosh-стиле. При этом команды, генерирующие имена + файлов, возвращают их в Macintosh-стиле, тогда как команды, + использующие имена файлов, могут получать их и в + Macintosh-стиле, и в Unix-стиле. +
    + +
    unix
    + +

    На Unix-платформах используются пути, которые содержат + компоненты, разделенные символом слэш. Пути могут быть + абсолютными или относительными, имена файлов могут содержать + любые символы, кроме слэша. Имена файлов. и. являются + специальными и обозначают текущий каталог и родительский + каталог текущего каталога, соответственно. Несколько слэшей + подряд понимаются как один разделитель.

    + +

    Ниже приведено несколько примеров различных типов путей: +

    +
    +
    /
    + +
    Абсолютный путь к корневому каталогу.
    + +
    /etc/passwd
    + +
    Абсолютный путь к файлу passwd к каталогу etc в + корневом каталоге.
    + +
    .
    + +
    Относительный путь к текущему каталогу.
    + +
    foo
    + +
    Относительный путь к файлу foo в текущем + каталоге.
    + +
    foo/bar
    + +
    Относительный путь к файлу bar в подкаталоге + foo текущего каталога
    + +
    ../foo
    + +
    Относительный путь к файлу foo в каталоге над + текущим.
    +
    +
    + +
    windows
    + +
    Для Windows-платформ Tcl поддерживает дисковые и сетевые + имена. В обоих типах имен можно использовать в качестве + разделителя как прямой, так и обратный слэш. Дисковые имена + состоят из (при необходимости) имени диска и последующего + абсолютного или относительного пути. Сетевые пути обычно имеют + вид \\servername\sharename\path\file. В обеих формах + "." и ".." ссылаются соответственно на + текущий каталог и его предка. +
    +
    + +

    "ТИЛЬДА"-ПОДСТАНОВКИ

    + +

    В дополнение к правилам, описанным выше, Tcl позволяет + использовать "тильда"-подстановки в стиле cshell. Если + имя файла начинается с ~, за которой сразу следует + сепаратор, она заменяется на значение переменной окружения + $HOME. В противном случае символы от "тильды" + до следующего разделителя интерпретируются как имя пользователя + и заменяются на имя домашнего каталога пользователя. +

    + +

    На Macintosh- и Windows-платформах + "тильда"-подстановки с именем пользователя не + поддерживаются. При попытке использовать такое имя файла + выдается ошибка. Однако "тильда" без имени + пользователя заменяется, как и на Unix-платформах, на значение + переменной окружения $HOME. +

    + +

    ВОПРОСЫ ПЕРЕНОСИМОСТИ

    + +

    При разработке переносимых приложений необходимо учитывать, + что не все файловые системы различают заглавные и прописные + буквы. Поэтому следует избегать использования имен файлов, + различающихся только регистром букв. Кроме того, необходимо + отказаться от использования символов, имеющих специальное + назначение хотя бы на одной из платформ, например, + <>:"/\|. А также, если предполагается + использовать программу на Windows 3.1, необходимо учитывать, что + имена файлов при этом должны быть ограничены восемью буквами, а + расширения - тремя.
    +

    + + diff --git a/hlp/ru/tcl/flush.html b/hlp/ru/tcl/flush.html new file mode 100644 index 0000000..cf300fe --- /dev/null +++ b/hlp/ru/tcl/flush.html @@ -0,0 +1,34 @@ + + + + flush + + +

    flush

    + +

    Команда организует немедленную выдачу выходных данных в канал.

    + +

    СИНТАКСИС

    + +
    +      flush channelId
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда направляет накопленные в выходном буфере данные в + канал с идентификатором channelId (значение + идентификатора возвращается командами открытия канала open или socket), который должен быть + открыт для записи. Если канал находится в блокирующем режиме, то + команда будет оставаться незавершенной до тех пор, пока все + содержимое буфера не будет отправлено в канал. Если канал + находится в неблокирующем режиме, то команда может завершиться + до окончания отправки выходных данных в канал. Остающиеся + данные будут передаваться в канал в фоновом режиме с такой + скоростью, с какой назначенный каналу файл или устройство сможет + принимать их. +

    + + diff --git a/hlp/ru/tcl/for.html b/hlp/ru/tcl/for.html new file mode 100644 index 0000000..5bda405 --- /dev/null +++ b/hlp/ru/tcl/for.html @@ -0,0 +1,55 @@ + + + + for + + + +

    for

    + +

    Команда for организует цикл.

    + +

    СИНТАКСИС

    + +
    +      for start test next body
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда for является командой цикла. По структуре + команда for похожа на аналогичную команду языка С. Здесь + аргументы start, next и body должны быть + командными строками Tcl, а test - строкой выражения. + Сначала команда for запускает интерпретатор Tcl для + выполнения start. Затем она вычисляет значение выражения + test; если оно не равно нулю, то запускает + Tcl-интерпретатор для выполнения body, затем + next. Цикл повторяется до тех пор, пока test не + станет равно 0. Если при выполнении body будет выполнена + команда continue, то + последующие команды в body пропускаются и начинает + выполняться next, затем test и т.д. Если при + исполнении body или next встретится команда + break, исполнение команды + for немедленно прекращается. Команда for + возвращает пустую строку. +

    + +

    Замечание. Строку test почти всегда следует + помещать в фигурные скобки. В противном случае подстановки + переменных будут выполнены до выполнения команды. Из-за этого + измененное в ходе цикла значение переменной может перестать + передаваться в выражение, что может породить бесконечный + цикл. Если же строка test заключена в фигурные скобки, + подстановка значения переменных выполняется в каждом цикле. Для + примера можно выполнить следующий скрипт со скобками и без + скобок вокруг выражения $x<10: +

    +
    +      for {set x 0} {$x<10} {incr x} { 
    +        puts "x is $x"
    +      }
    +    
    + + diff --git a/hlp/ru/tcl/foreach.html b/hlp/ru/tcl/foreach.html new file mode 100644 index 0000000..749ae0c --- /dev/null +++ b/hlp/ru/tcl/foreach.html @@ -0,0 +1,97 @@ + + + + foreach + + + +

    foreach

    + +

    Команда цикла по элементам одного или нескольких списков.

    + +

    СИНТАКСИС

    + +
    +      foreach varname list body 
    +      foreach varlist1 list1 ?varlist2 list2...? body
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда организует выполнение цикла, в котором переменные + цикла последовательно принимают все значения из списков + значений. В простейшем случае имеется одна переменная цикла + varname и один список значений list для присвоения + переменной цикла. Аргумент body есть скрипт Tcl. Для + каждого элемента списка list, по очереди с первого до + последнего, foreach присваивает содержимое очередного + элемента списка переменной varname и затем вызывает + интерпретатор Tcl для исполнения body. +

    + +

    В общем случае в команде может быть указано несколько списков + значений (например, list1 и list2), и каждый из + них может быть связан с одной переменной или со списком + переменных цикла (например, varlist1 и + varlist2). Во время каждой итерации переменные каждого + списка переменных принимают значения последовательных элементов + соответствующего списка значений. Значения из списков значений + используются последовательно от первого до последнего, и каждое + значение используется только один раз. Общее число итераций + выбирается таким, чтобы использовать все значения из всех + списков значений. Если список значений не содержит достаточного + числа значений для всех связанных с ним переменных цикла, вместо + недостающих элементов используются пустые значения. +

    + +

    Внутри скрипта body можно использовать команды break и continue, аналогично команде + for. +

    + +

    Команда foreach возвращает пустую строку.

    + +

    ПРИМЕРЫ

    + +

    В цикле используются переменные цикла i и j для цикла по + элементам одного списка

    +
    +        set x {}
    +        foreach {i j} {a b c d e f} { 
    +          lappend x $j $i
    +        }
    +    
    + +

    В результате величина x равна "a d c f e".

    + +

    При вычислении цикла используются три итерации.

    + +

    В цикле переменные цикла i и j используются для различных + списков значений.

    + +
    +        set x {}
    +        foreach i {a b c} j {d e f g} { 
    +          lappend x $i $j
    +        }
    +    
    + +

    В результате величина x равна "a d b e c f {} g".

    + +

    При вычислении цикла используются четыре итерации.

    + +

    Обе предыдущие формы скомбинированы в следующем цикле

    + +
    +        set x {}
    +        foreach i {a b c} {j k} {d e f g} { 
    +          lappend x $i $j $k
    +        }
    +    
    + +

    В результате величина x равна "a d e b f g c {} {}".

    + +

    При вычислении цикла используются три итерации.

    + + diff --git a/hlp/ru/tcl/format.html b/hlp/ru/tcl/format.html new file mode 100644 index 0000000..b23ea88 --- /dev/null +++ b/hlp/ru/tcl/format.html @@ -0,0 +1,274 @@ + + + + format + + + +

    format

    +
    + +

    Команда форматирует строку в стиле процедуры + sprintf.

    + +

    СИНТАКСИС

    + +
    +      format formatString ?arg arg...?
    +    
    + +

    ВВЕДЕНИЕ

    + +

    Данная команда создает и возвращает программе форматированную + строку так же, как это делает процедура ANSI C sprintf (эта + процедура используется в реализации команды). Подобно + sprintf, formatString указывает с помощью + спецификаторов преобразований,как именно сформатировать + результат, а возможные дополнительные аргументы предназначены + для подстановки в результат. +

    + +

    Команда немного отличается от sprintf в части отдельных + спецификаторов и ключей. +

    + +

    ПРОЦЕСС ФОРМИРОВАНИЯ

    + +

    Команда просматривает строку formatString слева + направо. Все символы из строки непосредственно переносятся в + результирующую строку, кроме символа % и следующих + непосредственно за ним. Такая последовательность символов + рассматривается как спецификатор преобразования. Этот + спецификатор управляет преобразованием очередного аргумента + arg в указанный формат, после чего тот добавляется к + результирующей строке вместо соответствующего спецификатора. + Если в строке formatString содержится несколько + спецификаторов, каждый из них управляет преобразованием одного + дополнительного аргумента. Число таких аргументов должно быть + достаточным для всех спецификаторов в строке. +

    + +

    Каждый из спецификаторов преобразования может содержать до + шести различных частей: указатель позиции, набор флагов, + минимальная ширина поля, точность, преобразователь длины и тип + преобразования. Любые из полей, кроме типа преобразования, могут + отсутствовать. Ниже обсуждаются соответствующие разделы + спецификаторов. +

    + +

    УКАЗАТЕЛЬ ПОЗИЦИИ

    + +

    Если за символом % следуют целое число и знак $, + как например в %2$d, то величина для преобразования + берется не из следующего аргумента, а из аргумента, занимающего + соответствующую позицию в списке (1 соответствует первому + аргументу arg). Если спецификатор преобразования требует + нескольких аргументов (когда он содержит символ *), то + используются последовательные аргументы, начиная с + указанного. Если один из спецификаторов содержит указание + позиции аргумента, то и все остальные спецификаторы должны его + содержать. +

    + +

    ФЛАГИ + ПРЕОБРАЗОВАНИЯ

    + +

    Второй раздел спецификатора может содержать в произвольном + порядке любые флаги из перечисленных ниже.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    -Указывает, что соответствующий аргумент будет выровнен + влево (числа обычно выравниваются вправо с добавлением + лидирующих пробелов при необходимости).
    +Указывает, что числа всегда будут вставлены со знаком, + даже если они положительные.
    spaceУказывает, что перед числом будет добавлен пробел, если + первый символ не знак.
    0Указывает, что число будет выровнено с добавлением + лидирующих нулей.
    #Указывает на использование альтернативной формы + вывода. Для o и O преобразований + гарантирует, что первой цифрой всегда будет 0. Для + x и X преобразований - что 0x или + 0X соответственно будет добавлен в начало + числа. Для e, E, f, g, и + G - что в числе будет использована десятичная + точка. Для g и G - что конечные нули не + будут отброшены.
    + +

    МИНИМАЛЬНАЯ + ШИРИНА ПОЛЯ

    + +

    Третья часть спецификатора преобразования представляет собой + число, задающее минимальную ширину поля для данного + преобразования. Обычно она используется для формирования данных + в таблицу. Если преобразуемое значение не содержит указанного + числа символов, одно будет дополнено до необходимого + размера. Обычно поле заполняется пробелами слева, однако, + указанные выше флаги 0 и - позволяют заполнять его + нулями слева или пробелами справа. Если минимальная ширина поля + указана как *, а не как число, то в качестве числового + значения используется значение следующего аргумента в команде. +

    + +

    ТОЧНОСТЬ

    + +

    Четвертая часть спецификатора определяет точность + представления чисел. Она состоит из точки и последующего + числа. Число имеет различный смысл при различных + преобразованиях. Для e, E и f + преобразования оно определяет число цифр справа от десятичной + точки. Для g и G - общее число чисел слева и + справа от десятичной точки (однако, конечные нули будут + обрезаться, если не указан флаг #). Для целочисленных + преобразований оно определяет минимальное число символов (при + необходимости будут добавляться лидирующие нули). Для s + преобразований определяет максимальное число символов, которое + будет выводиться. Если строка длиннее, конечные символы будут + отброшены. Если точность указана как *, а не как число, + то в качестве числового значения используется значение + следующего аргумента в команде. +

    + +

    ПРЕОБРАЗОВАТЕЛЬ + ДЛИНЫ

    + +

    + Пятая часть спецификатора может принимать значения + hили l. Значение h означает, что + все числовые значения предварительно обрезаются до 16 бит. + Значение l означает, что никаких предварительных + преобразований не производится. +

    + +

    ТИП + ПРЕОБРАЗОВАНИЯ

    + +

    Последняя часть спецификатора представляет собой букву, + которая определяет тип преобразования. Допускаются следующие + значения.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    dПреобразует целое число в десятичную строку со + знаком.
    uПреобразует целое число в десятичную строку без + знака.
    iПреобразует целое число в десятичную строку со + знаком. Целое может быть десятичным, восьмеричным (с + 0 вначале) или шестнадцатеричным (с 0x + вначале).
    oПреобразует целое число в восьмеричную строку без + знака.
    x or XПреобразует целое число в шестнадцатиричную строку без + знака. Используются символы `0123456789abcdef'' для + x и ``0123456789ABCDEF'' для X. +
    cПреобразует целое число в восьмибитный символ, который + оно представляет.
    sНе преобразует, но просто вставляет строку
    fПреобразует число с плавающей точкой в десятичное со + знаком в форме xx.yyy, где число символов после + запятой определяется точностью.
    e or EПреобразует число с плавающей точкой в число в + экспоненциальной форме x.yyye╠zz, где число + символов после запятой определяется точностью (по + умолчанию 6). Для E в записи числа + используется E вместо e.
    g or GЕсли порядок числа меньше -4 или больше, чем точность, + или равен точности, преобразует число с плавающей точкой + как %e или %E. В противном случае + преобразует как %f. +
    %Просто подставляет символ %.
    + +

    Для числовых преобразований аргумент должен быть целым числом + или десятичным с плавающей точкой. Аргумент преобразуется в + двоичное число, а затем преобразуется обратно в строку в + соответствии с указанным типом преобразования.

    + +

    ОТЛИЧИЯ ОТ + ANSI SPRINTF

    + +

    Поведение команды format отличается от процедуры + sprintf в следующих моментах:

    +

      +
    1. %p и %n типы не поддерживаются.
    2. + +
    3. Для %c аргумент должен быть десятичным числом.
    4. +
    + +

    При преобразованиях длины значение l игнорируется.

    + + + diff --git a/hlp/ru/tcl/gets.html b/hlp/ru/tcl/gets.html new file mode 100644 index 0000000..8fea778 --- /dev/null +++ b/hlp/ru/tcl/gets.html @@ -0,0 +1,50 @@ + + + + gets + + + +

    gets

    + +

    Команда читает строку из канала.

    + +

    СИНТАКСИС

    + +
    +      gets channelId ?varName?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда gets читает из канала channelId + очередную строку символов. Если имя переменной varName не + задано, тогда команда возвращает полученную строку за + исключением символов конца строки. Если varName задано, + тогда команда записывает полученную строку в переменную и + возвращает количество символов в принятой строке. +

    + +

    Если при поиске конца строки был обнаружен конец файла, + команда возвращает всю полученную информацию вплоть до конца + файла.

    + +

    Если канал находится в неблокирующем режиме и поступила + неполная входная строка, то команда не использует поступившие + данные и возвращает пустую строку.

    + +

    Если указана переменная varName и возвращается пустая + строка из-за конца файла или из-за неполноты полученной строки, + команда возвращает 1.

    + +

    Обратите внимание, что если аргумент varName не задан, + конец файла и неполная строка приведут к тому же результату, что + и строка, состоящая из символа конца строки. Команды eof и fblocked позволяют различить эти + ситуации.

    + +

    См. также eof и fblocked .

    + + diff --git a/hlp/ru/tcl/glob.html b/hlp/ru/tcl/glob.html new file mode 100644 index 0000000..d861fbd --- /dev/null +++ b/hlp/ru/tcl/glob.html @@ -0,0 +1,110 @@ + + + + glob + + + +

    glob

    + +

    Команда возвращает имена файлов, удовлетворяющих шаблону. +

    + +

    СИНТАКСИС

    + +
    +      glob ?switches? pattern ?pattern?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда glob выполняет поиск имен файлов подобно тому, + как это делает оболочка csh, и возвращает список имен, + удовлетворяющих шаблону pattern. Аргументы, начинающиеся + со знака -, являются управляющими ключами switches. +

    + +

    Возможные ключи:

    + +
    +
    -nocomplain
    + +
    Позволяет вернуть пустой список без генерации ошибки. Если + ключ не задан, то при пустом списке формируется ошибка. +
    + +
    --
    + +
    Означает конец ключей. Аргумент после этого ключа считается + шаблоном, даже если он начинается с -. +
    +
    + +

    Шаблоны могут включать следующие специальные символы:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ?Удовлетворяет любому символу;
    *Удовлетворяет любой последовательности из нуля или + больше символов;
    [chars]Удовлетворяет любому символу из chars. Если + chars включает последовательность символов типа + a-b, то удовлетворяет всем символам от a до + b (включительно). +
    \xУдовлетворяет символу x.
    {a,b,...}Удовлетворяет любой из строк a, b,> и т.д.
    + +

    Как и в csh, символ . в начале имени файла или сразу + после / должен соответствовать явно или с помощью + конструкции {}.

    + +

    Если первый символ образца ~, то он указывает на + домашний каталог пользователя, чье имя указано после + ~. Если сразу после ~ идет /, то + используется значение переменной окружения HOME.

    + +

    Действие команды glob отличается от работы в csh в + следующем:

    + +
      +
    • она не сортирует составленный ей список;
    • + +
    • она возвращает имена только существующих файлов (в csh + проверку наличия файлов надо задавать отдельно, если только + шаблон не содержит символов ?, *, или + []).
    • +
    + +

    ОСОБЕННОСТИ РАБОТЫ НА РАЗЛИЧНЫХ ПЛАТФОРМАХ

    + +

    В отличие от другихTcl-команд команда glob может + работать с именами файлов только в нотации, поддерживаемой на + той платформе, на которой она исполняется. Кроме того, на + Windows-платформах специальные символы не допустимы в сетевых + именах. +

    + + diff --git a/hlp/ru/tcl/global.html b/hlp/ru/tcl/global.html new file mode 100644 index 0000000..4b1b10a --- /dev/null +++ b/hlp/ru/tcl/global.html @@ -0,0 +1,36 @@ + + + + global + + + +

    global

    + +

    Команда для объявления глобальных переменных.

    + +

    СИНТАКСИС

    + +
    +      global varname ?varname?
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда выполняется только при выполнении процедуры, а + в остальных случаях игнорируется. Команда объявляет + переменные varname глобальными. Глобальные переменные - + это переменные глобальной области имен. +

    + +

    Только в течение работы данной процедуры и только при + выполнении в данной процедуре любая ссылка на значение любого из + аргументов varname будет указывать на одноименную + глобальную переменную.

    + +

    См. также namespace(n), + variable(n) +

    + + + diff --git a/hlp/ru/tcl/history.html b/hlp/ru/tcl/history.html new file mode 100644 index 0000000..edb4eee --- /dev/null +++ b/hlp/ru/tcl/history.html @@ -0,0 +1,132 @@ + + + + history + + + +

    history

    + +

    Команда работает со списком выполнявшихся команд.

    + +

    СИНТАКСИС

    + +
    +      history ?option? ?arg arg
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда history выполняет действия по отношению к + недавно выполненным командам, занесенным в журнал. Каждая из + этих зарегистрированных команд обозначается термином + "событие". Ссылаться на события в команде + history можно одним из следующих способов:

    +
      +
    1. Число. Если положительное - ссылается на событие с + этим номером (все события нумеруются начиная с 1). Если число + отрицательное, то оно указывает номер события относительно + текущего (-1 - предыдущее, -2 - перед предыдущим + и т.д.). Событие 0 ссылается на текущее событие.
    2. + +
    3. Строка. Ссылается на наиболее позднее событие, + которое удовлетворяет строке. Событие удовлетворяет строке, + если оно начинается со строки, или в соответствии с правилами + команды string match.
    4. +
    + +

    Команда history может принимать одну из следующих + форм.

    + +
    +
    history
    + +
    То же самое, что команда history info, описанная + ниже.
    + +
    history add command ?exec?
    + +
    Добавляет аргумент command в журнал как новое + событие. Если присутствует аргумент exec(или произвольное сокращение), то + команда command выполняется и возвращается ее + результат. В противном случае возвращается пустая строка. +
    + +
    history change newValue + ?event?
    + +
    Заменяет описание события event на newValue. + Аргумент event определяет событие, описание которого + будет заменено. По умолчанию - текущее событие (даже не + предыдущее!). Эта форма команды предназначается для + использования в тех случаях, когда переформировывается журнал + событий и позволяет заменить текущее событие (переформирование + журнала) на необходимое. Команда возвращает пустую строку. +
    + +
    history clear
    + +
    Удаляет журнал событий. Количество запоминаемых событий + (см. history keep) сохраняется. Нумерация + событий начинается сначала. +
    + +
    history event ?event?
    + +
    Возвращает описания события event. Значение по + умолчанию -1. +
    + +
    history info ?count?
    + +
    Возвращает в удобном для чтения виде список, состоящий из + номеров и описаний событий (кроме текущего). Если аргумент + count задан, то только count последних событий + возвращаются. +
    + +
    history keep ?count?
    + +
    Команда изменяет размер журнала на count событий. + Исходно в журнале сохраняются 20 последних событий. Если + аргумент count не указан, команда возвращает текущее + значение размера журнала. +
    + +
    history nextid
    + +
    Возвращает номер следующего события, которое будет записано + в журнал. Полезно, например, для вывода номера события в + приглашении командной строки. +
    + +
    history redo ?event?
    + +
    Повторно выполняет команду, указанную с помощью аргумента + event. Значение аргумента по умолчанию -1. Эта + команда вызывает переформирование журнала, см. ниже. +
    +
    + +

    ПЕРЕФОРМИРОВАНИЕ ЖУРНАЛА

    + +

    До версии 8.0 Tcl имел весьма сложный механизм + переформирования журнала. Новый механизм несколько сокращен за + счет старых опций substitute и words. (Взамен + добавлена новая опция clear). + +

    Опция redo позволяет переформировывать журнал + значительно проще. При ее выполнении последнее событие + изменяется таким образом, что удаляется "служебная" + команда history, которая реально выполнялась, а вместо + нее записывается та команда, которая необходима.

    + +

    Если вы хотите повторить прежнюю команду, не модифицируя + журнал, выполните сначала команду history event, чтобы + извлечь описание команды, а затем history add, чтобы + выполнить ее.

    + + + diff --git a/hlp/ru/tcl/if.html b/hlp/ru/tcl/if.html new file mode 100644 index 0000000..58d1350 --- /dev/null +++ b/hlp/ru/tcl/if.html @@ -0,0 +1,45 @@ + + + + if + + + +

    if

    + +

    Команда if проверяет соблюдение условия в ходе + выполнения скрипта.

    + +

    СИНТАКСИС

    + +
    +      if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... 
    +      ?else? ?bodyN?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда вычисляет значение выражения expr1(Точно так, + как это делает команда + expr). Это и все остальные выражения expr + должны быть булева типа (то есть это должна быть числовая + величина, причем 0 соответствует false, а все остальные + значения - true, либо строка со значениями true + или yes для true и false или no для + false). Если выражение равно true, то скрипт + body1 передается на выполнение интерпретатору Tcl. Если + нет, то вычисляется значение выражения expr2, и если оно + равно true, то исполняется body2, и так + далее. Если ни одно из выражений не равно true, тогда + выполняется bodyN.

    + +

    Слова then и else необязательны и используются + только для простоты понимания команды. Аргумент + bodyNтакже может отсутствовать, если отсутствует + else.

    + +

    Команда возвращает значение выполненного скрипта или пустую + строку, если ни одно из выражений не было равно true, и + bodyN отсутствовал.

    + + diff --git a/hlp/ru/tcl/incr.html b/hlp/ru/tcl/incr.html new file mode 100644 index 0000000..618d876 --- /dev/null +++ b/hlp/ru/tcl/incr.html @@ -0,0 +1,42 @@ + + + + incr + + + +

    incr

    + +

    Команда увеличивает значение переменной на заданную + величину.

    + +

    СИНТАКСИС

    + +
    +      incr varName increment
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда incr увеличивает значение переменной + varName на величину increment. И значение + переменной, и increment должны быть целыми числами. По + умолчанию increment равно 1. Новое значение переменной + сохраняется в виде десятичной строки и одновременно возвращается + командой.

    + +

    ПРИМЕР

    + +
    +      incr variable 3
    +    
    + +

    Данная команда увеличивает переменную variable на 3.

    + +
    +      incr variable
    +    
    + +

    Данная команда увеличивает переменную variable на 1.

    + + diff --git a/hlp/ru/tcl/index-tcl.html b/hlp/ru/tcl/index-tcl.html new file mode 100644 index 0000000..51f2420 --- /dev/null +++ b/hlp/ru/tcl/index-tcl.html @@ -0,0 +1,94 @@ + + + + + +

    Table of contents

    + + + diff --git a/hlp/ru/tcl/info.html b/hlp/ru/tcl/info.html new file mode 100644 index 0000000..ce93ce0 --- /dev/null +++ b/hlp/ru/tcl/info.html @@ -0,0 +1,229 @@ + + + + info + + + +

    info

    + +

    Команда сообщает сведения о состоянии интерпретатора Tcl.

    + +

    СИНТАКСИС

    + +
    +      info option ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда обеспечивает доступ к внутренней информации + Tcl-интерпретатора. Ниже перечислены поддерживаемые опции (имена + которых могут быть сокращены). +

    + +
    + +
    info args procname
    + +
    Возвращает список имен аргументов процедуры procname в + том порядке, в котором они определены при описании + процедуры. Аргумент procname должен содержать имя + Tcl-процедуры. +
    + +
    info body procname
    + +
    Возвращает тело процедуры procname. Аргумент + procname должен содержать имя Tcl-процедуры. +
    + +
    info cmdcount
    + +
    Возвращает полное число команд, введенных в данный + интерпретатор. +
    + +
    info commands ?pattern?
    + +
    Если аргумент pattern не задан, возвращает полный + список команд в текущем пространстве имен, включая как + встроенные команды, написанные на C, так и процедуры, заданные + с помощью команды proc. Если аргумент + pattern задан, возвращается список только тех имен, + которые удовлетворяют шаблону pattern. Правила + использования шаблонов такие же, как в команде string + match. Шаблон может быть полным именем, например + Foo::print*. То есть он может задавать определенное + пространство имен и шаблон в нем. В этом случае каждая команда + в возвращаемом списке будет представлена полным именем с + указанием пространства имен. +
    + +
    info complete command
    + +
    Возвращает 1, если команда command есть + завершенная Tcl-команда, то есть не содержит + "незакрытых" кавычек, квадратных или фигурных скобок + и имен массивов. В противном случае возвращается 0. Эта + команда обычно используется при построчном вводе команд + пользователем для того, чтобы позволить ему вводить команды из + нескольких строк. Для этого, если введенный скрипт не + представляет собой законченную команду, его исполнение + откладывается до завершения следующей строки. +
    + +
    info default procname arg + varname
    + +
    Аргумент procname должен быть именем Tcl-процедуры, + а аргумент arg - именем одного из аргументов этой + процедуры. Если указанный аргумент не имеет значения по + умолчанию, команда возвращает 0. В противном случае + команда возвращает 1 и помещает значение по + умолчанию в переменную varname. +
    + +
    info exists varName
    + +
    Возвращает 1, если переменная varName + существует в текущем контексте как локальная или как + глобальная переменная. В противном случае возвращает + 0. +
    + +
    info globals ?pattern?
    + +
    Если аргумент pattern не задан, возвращает список + имен определенных в данный момент глобальных переменных + (переменных, определенных в глобальном пространстве имен). + Если шаблон задан, возвращаются только имена, удовлетворяющие + шаблону. Правила использования шаблонов такие же, как в + команде string match. +
    + +
    info hostname
    + +
    Возвращает имя компьютера, на котором выполняется этот + вызов. +
    + +
    info level + ?number?
    + +
    Если аргумент number не задан, возвращает уровень + стека выполняемой процедуры, или 0, если команда + выполняется на верхнем уровне. Если аргумент number + указан, команда возвращает список, состоящий из имени и + аргументов процедуры, находящейся в стеке вызовов на + соответствующем месте. Если number положительное число, + оно указывает номер уровня в стеке (1 - самая верхняя + вызванная процедура, 2 - процедура, вызванная из процедуры 1, + и так далее), если же number отрицательное, оно + указывает уровень относительно уровня выполняемой процедуры (0 + - выполняемая процедура, -1 - процедура, из которой вызвана + исполняемая, и так далее). Более подробно уровни стека + описаны в uplevel. +
    + +
    info library
    + +
    Возвращает имя каталога, в котором хранятся стандартные + Tcl-скрипты. Обычно совпадает со значением переменной + tcl_library и может быть изменено с помощью + переопределения этой переменной. Дополнительная информация + приведена вtclvars +
    + +
    info loaded ?interp?
    + +
    Возвращает список библиотек (package), загруженных в + интерпретатор с помощью команды + load. Каждый элемент списка представляет собой + подсписок из двух элементов: имени файла и имени + библиотеки. Для статически загруженных библиотек имя файла + отсутствует. Если имя интерпретатора interp + отсутствует, возвращается список всех библиотек, загруженных + во все интерпретаторы. Чтобы получить список библиотек, + загруженных в текущий интерпретатор, используйте пустую строку + в качестве аргумента interp. +
    + +
    info locals ?pattern?
    + +
    Если образец не задан, возвращает имена всех определенных в + текущий момент локальных переменных, включая аргументы + процедуры, если они есть. Переменные, заданные с помощью + команд global и upvar, не возвращаются. Если + шаблон задан, возвращаются только имена, удовлетворяющие + шаблону. Правила использования шаблонов такие же, как в + команде string match. +
    + +
    info nameofexecutable
    + +
    Возвращает полное имя бинарного файла, с помощью которого + приложение было запущено. Если Tcl не может определить файл, + возвращается пустая строка. +
    + +
    info patchlevel
    + +
    Возвращает значение глобальной переменной + tcl_patchLevel. См. также раздел tclvars. +
    + +
    info procs ?pattern?
    + +
    Если аргумент pattern не задан, возвращает полный + список Tcl-процедур в текущем пространстве имен. Если аргумент + pattern задан, возвращается список только тех имен, + которые удовлетворяют шаблону pattern. Правила + использования шаблонов такие же, как в команде string + match. +
    + +
    info script
    + +
    Если в данный момент обрабатывается Tcl-скрипт (например, + вызванный с помощью команды + source), то команда возвращает имя файла, + содержащего самый внутренний обрабатываемый скрипт. В + противном случае возвращает пустую строку. +
    + +
    info sharedlibextension
    + +
    Возвращает расширение, используемое на текущей платформе + для файлов разделяемых библиотек (например,.so + для Solaris). Если разделяемые библиотеки на текущей платформе + не поддерживаются, возвращает пустую строку. +
    + +
    info tclversion
    + +
    Возвращает значение глобальной переменной + tcl_version. Дополнительная информация приведена в + tclvars. +
    + +
    info vars ?pattern?
    + +
    Если аргумент pattern не задан, возвращает список + имен всех видимых в текущий момент переменных, включая + локальные и видимые глобальные. Если аргумент pattern + задан, возвращается список только тех имен, которые + удовлетворяют шаблону pattern. Правила использования + шаблонов такие же, как в команде string match. Шаблон + может быть полным именем, например Foo::option*. То + есть он может задавать определенное пространство имен и шаблон + в нем. В этом случае каждая команда в возвращаемом списке + будет представлена полным именем с указанием пространства + имен. +
    +
    + + diff --git a/hlp/ru/tcl/interp.html b/hlp/ru/tcl/interp.html new file mode 100644 index 0000000..9f60cf0 --- /dev/null +++ b/hlp/ru/tcl/interp.html @@ -0,0 +1,742 @@ + + + + interp + + + +

    interp

    + +

    Команда создает и управляет Tcl-интерпретаторами.

    + +

    СИНТАКСИС

    + +
    +      interp option ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда позволяет создавать один или несколько новых + Tcl-интерпретаторов, которые сосуществуют в одном приложении с + создавшим их интерпретатором. Создавший интерпретатор называется + мастер-интерпретатором, а созданные интерпретаторы называются + подчиненными (slave) интерпретаторами. + Мастер-интерпретатор может создавать произвольное число + подчиненных интерпретаторов, а каждый из подчиненных может в + свою очередь создавать подчиненные интерпретаторы, для которых + он сам является мастер-интерпретатором. В результате в + приложении может создаваться иерархия интерпретаторов. +

    + +

    Каждый интерпретатор независим от остальных. Он имеет + собственное пространство имен для команд, процедур и глобальных + переменных. Мастер-интерпретатор может создавать связи между + подчиненными интерпретаторами и собой, используя механизм + алиасов. Алиас - это команда в подчиненном интерпретаторе, + которая, при ее вызове, вызывает другую команду в + мастер-интерпретаторе или в другом подчиненном + интерпретаторе. Кроме механизма алиасов, связь между + интерпретаторами поддерживается только через переменные + окружения. Массив env>обычно является общим для + всех интерпретаторов в приложении. Необходимо заметить, что + идентификаторы каналов (например, идентификатор, возвращаемый + командой open) больше не + разделяются между интерпретаторами, как это было в предыдущих + версиях Tcl. Чтобы обеспечить совместный доступ к каналам, + необходимо использовать явные команды для передачи + идентификаторов каналов из интерпретатора в интерпретатор. +

    + +

    Команда interp позволяет также создавать надежные + интерпретаторы. Надежный интерпретатор - это интерпретатор с + существенно урезанной функциональностью, поэтому он может + исполнять ненадежные скрипты без риска нарушить работу + вызывающего их приложения. Например, из безопасных + интерпретаторов недоступны команды создания каналов и + подпроцессов. Более подробно см. Безопасные интерпретаторы. Опасная + функциональность не удалена из безопасных интерпретаторов, но + скрыта таким образом, что только надежные интерпретаторы могут + получить к ней доступ. Более подробно см. Скрытые команды. Механизм + алиасов может быть использован для безопасного взаимодействия + между подчиненным интерпретатором и его + мастер-интерпретатором. Более подробно этот вопрос обсуждается в + разделе "Использование алиасов". +

    + +

    Полное имя интерпретатора представляет собой список, содержащий + имена его предков в иерархии интерпретаторов и заканчивающийся + именем интерпретатора в его непосредственном предке. Имена + интерпретаторов в списке - это их относительные имена в их + непосредственных мастер-интерпретаторах. Например, если a + есть подчиненный интерпретатор текущего интерпретатора и, в свою + очередь, имеет подчиненный интерпретатор a1, а тот, в + свою очередь, имеет подчиненный интерпретатор a11, то + полное имя a11 в a есть список {a1 a11}. +

    + +

    В качестве аргумента описанной ниже команды interp + используется полное имя интерпретатора. Интерпретатор, в котором + исполняется команда, всегда обозначается как {} (пустая + строка). Обратите внимание, что в подчиненном интерпретаторе + невозможно сослаться на мастер-интерпретатор кроме как через + алиасы. Также нет никакого имени, под которому можно было бы + сослаться на мастер-интерпретатор, первым созданный в + приложении. Оба ограничения вызваны соображениями безопасности. +

    + +

    КОМАНДА INTERP

    + +

    Команда interp используется для создания, удаления и + выполнения команд в подчиненном интерпретаторе, а также для + разделения или передачи каналов между интерпретаторами. Она + может иметь одну из перечисленных ниже форм в зависимости от + значения аргумента option. +

    + +
    +
    interp alias + srcPath srcCmd
    + +
    Возвращает список, состоящий из исходной команды и + аргументов, связанных с алиасом srcCmd в интерпретаторе + srcPath (возвращаются значения, использовавшиеся при + создании алиаса, так как имя команды могло быть изменено с + помощью команды rename). +
    + +
    interp alias srcPath srcCmd + {}
    + +
    Удаляет алиас srcCmd в подчиненном интерпретаторе + srcPath. Имя srcCmd - это имя, под которым алиас + был создан. Если созданная команда была переименована, то + будет удалена переименованная команда. +
    + +
    interp alias srcPath srcCmd + targetPath targetCmd ?arg arg...?
    + +

    Эта команда создает алиас между двумя подчиненными + интерпретаторами (для создания алиаса между подчиненным + интерпретатором и мастер-интерпретатором используется + команда slave alias). Оба интерпретатора + srcPath и targetPath должны быть в иерархии + интерпретаторов ниже того интерпретатора, в котором + выполняется команда. Аргументы srcPath и + srcCmd задают интерпретатор, в котором будет создан + алиас и его имя. Аргумент srcPath должен быть + Tcl-списком, задающим имя существующего интерпретатора. + Например, "a b" определяет интерпретатор + b, который является подчиненным интерпретатором + интерпретатора a, который в свою очередь является + подчиненным интерпретатором текущего интерпретатора. Пустой + список соответствует текущему интерпретатору (в котором + исполняется команда). Аргумент srcCmd определяет имя + новой команды-алиаса, которая будет создана в интерпретаторе + srcPath. Аргументы targetPath и + targetCmd определяют целевой интерпретатор и команду, + а аргументы arg, если они есть, определяют + дополнительные аргументы для команды targetCmd, + которые будут вставлены перед аргументами, заданным при + вызове srcCmd. Команда targetCmd может как + существовать, так и не существовать в момент создания + алиаса. В последнем случае она не создается командой + interp alias.

    + +

    Алиас позволяет использовать команду targetCmd в + интерпретаторе targetPath каждый раз, когда + вызывается команда-алиасsrcCmd в интерпретаторе + srcPath. Подробнее см. "Использование алиасов". +

    +
    + +
    interp aliases ?path?
    + +
    Эта команда возвращает список имен всех команд-алиасов, + определенных в интерпретаторе path. +
    + +
    interp create ?-safe? ?--? + ?path?
    + +

    Создает подчиненный интерпретатор с именем path и + новую команду для работы с этим интерпретатором, называемую + также подчиненной (slave) командой. Имя подчиненной команды + совпадает с последним элементом списка path. Новый + подчиненный интерпретатор и подчиненная команда создаются в + интерпретаторе, имя которого состоит из всех элементов + списка path, кроме последнего. Например, если + аргумент path равен a b c, то в результате в + интерпретаторе a b будет создан подчиненный + интерпретатор c и подчиненная команда c. + Синтаксис подчиненной команды описан ниже см. "Команда + работы с интерпретатором". Если аргумент path + отсутствует, Tcl создает уникальное имя в форме + interpx, где x - целое число, и использует его + для подчиненного интерпретатора и подчиненной команды. Если + в команде указана опция -safe или если + мастер-интерпретатор сам является безопасным + интерпретатором, новый подчиненный интерпретатор будет + безопасным, то есть с ограниченной функциональностью. В + противном случае новый интерпретатор будет включать полный + набор встроенных Tcl-команд и переменных. Аргумент - + используется для того, чтобы обозначить конец опций. + Следующий аргумент будет использоваться как имя + интерпретатора, даже если он равен -safe.

    + +

    Команда interp create возвращает имя нового + интерпретатора. Имя подчиненного интерпретатора должно быть + уникальным среди подчиненных интерпретаторов его мастера. + Если у мастер-идентификатора уже существует.

    +
    + +
    interp delete ?path...?
    + +
    Удаляет ноль или больше интерпретаторов с именем + path. Для каждого удаляемого интерпретатора удаляются + также его подчиненные интерпретаторы. Если для одного из + аргументов path интерпретатора с таким именем не + существует, команда генерирует ошибку. +
    + +
    interp eval path arg + ?arg...?
    + +
    Команда объединяет все аргументы так же, как команда concat, а затем исполняет + сформированный скрипт в подчиненном интерпретаторе, заданном + аргументом path. Результат выполнения (включая + информацию об ошибках в переменных errorInfo и errorCode, если произошла + ошибка) возвращается в вызывающий интерпретатор. +
    + +
    interp exists + path
    + +
    Возвращает 1, если подчиненный интерпретатор с + именем path существует в его мастер-интерпретаторе. В + противном случае возвращает 0. Если аргумент + path представляет относительное имя, то он ищется в том + интерпретаторе, в котором выполняется команда. +
    + +
    interp expose + path hiddenName ?exposedCmdName?
    + +
    Разрешает использование в интерпретаторе path + скрытой команды hiddenName под новым именем + exposedCmdName (в настоящее время поддерживаются только + имена в глобальном пространстве имен, не содержащие + "::"). Если обычная (не скрытая) команда + exposedCmdName уже существует, генерируется сообщение + об ошибке. Скрытые команды обсуждаются подробно см. "Скрытые команды". +
    + +
    interp hide path + exposedCmdName ?hiddenCmdName?
    + +
    Запрещает использование в интерпретаторе path + обычной команды exposedCmdName и переименовывает ее в + скрытую команду hiddenCmdName (или в скрытую команду + под старым именем, если новое не было задано). Если скрытая + команда с заданным именем уже существует, команда возвращает + ошибку. В настоящее время exposedCmdName и + hiddenCmdName не могут содержать "::". + Команды, которые должны быть скрыты с помощью interp + hide, ищутся только в глобальном пространстве имен, даже + если текущее пространство имен не глобальное. Скрытые команды + обсуждаются подробно ниже (см. "Скрытые команды"). +
    + +
    interp hidden path
    + +
    Возвращает список скрытых команд интерпретатора + path. +
    + +
    interp invokehidden path + ?-global? hiddenCmdName ?arg...?
    + +
    Вызывает в интерпретаторе path скрытую команду + hiddenCmdName с перечисленными аргументами. Никаких + подстановок или вычислений в аргументах не производится. Если + указана опция -global, скрытая команда выполняется на + глобальном уровне в целевом интерпретаторе. В противном + случае она выполняется в текущем контексте и может + использовать значения локальных переменных и переменных из + вышестоящих стеков. Скрытые команды обсуждаются подробно в + соответствующем разделе ниже. +
    + +
    interp issafe ?path?
    + +
    Возвращает 1, если интерпретатор path + безопасный, и 0 в противном случае. +
    + +
    interp marktrusted path
    + +
    Отмечает интерпретатор path как надежный. Не + раскрывает скрытые команды. Команда interp marktrusted + может выполняться только из надежного интерпретатора. Если + интерпретатор path уже надежный, команда не оказывает + никакого воздействия. +
    + +
    interp share srcPath channelId + destPath
    + +
    Позволяет разделить канал ввода - вывода channelId + между интерпретаторами srcPath и destPath. Оба + интерпретатора после этого будут иметь одинаковые права на + канал. Каналы ввода - вывода, доступные в интерпретаторе, + автоматически закрываются, когда удаляется интерпретатор. +
    + +
    interp slaves ?path?
    + +
    Возвращает список подчиненных интерпретаторов для + интерпретатора path. Если аргумент path + отсутствует, возвращает список подчиненных интерпретаторов для + интерпретатора, в котором выполняется команда. +
    + +
    interp target path alias
    + +
    Возвращает список, описывающий целевой интерпретатор + (интерпретатор, в котором выполняется реальная команда при + вызове команды-алиаса) для алиаса alias. Алиас задается + именем интерпретатора path и команды-алиаса + alias как в команде interp alias выше. Имя + целевого интерпретатора возвращается как имя интерпретатора + относительно имени интерпретатора, в котором выполняется + команда. Если это текущий интерпретатор, то возвращается + пустой список. Если этот интерпретатор не является потомком + интерпретатора, в котором выполняется команда, генерируется + ошибка. Реальная команда не обязана быть определена в момент + выполнения данной команды. +
    + +
    interp transfer srcPath + channelId destPath
    + +
    Делает канал ввода - вывода channelId доступным в + интерпретаторе destPath и недоступным в интерпретаторе + srcPath. +
    +
    + +

    КОМАНДА РАБОТЫ С + ИНТЕРПРЕТАТОРОМ (ПОДЧИНЕННАЯ КОМАНДА)

    + +

    Для каждого подчиненного интерпретатора, созданного с помощью + команды interp, в мастер-интерпретаторе создается команда + с тем же именем, что и подчиненный интерпретатор. Эта команда + предназначена для выполнения различных операций в подчиненном + интерпретаторе. В общем случае она имеет следующий вид: +

    + +
    +      slave command ?arg arg...?
    +    
    +

    где slave - имя подчиненного интерпретатора, а + аргументы command и arg arg... определяют + конкретное назначение команды. Ниже перечислены возможные + формы команды.

    + +
    +
    slave aliases
    + +
    Возвращает список всех алиасов в подчиненном интерпретаторе + slave. Возвращаемые имена - это имена, + использовавшиеся при создании соответствующих алиасов. Они + могут не совпадать с текущими именами команд, если те были + переименованы. +
    + +
    slave alias srcCmd
    + +
    Возвращает список, состоящий из имени реальной команды и ее + аргументов, ассоциированных с алиасом srcCmd. + Возвращаются те же значения, что и в команде создания + алиаса. Если созданный алиас был переименован, то в команде + надо указывать имя srcCmd, которое использовалось при + создании алиаса. +
    + +
    slave alias srcCmd {}
    + +
    Удаляет алиас srcCmd в подчиненном интерпретаторе. + Аргумент srcCmd указывает имя алиаса в момент + создания. Если после этого он был переименован, удалится + переименованная команда. +
    + +
    slave alias srcCmd targetCmd + ?arg..?
    + +
    Эта команда создает команду - алиас в подчиненном + интерпретаторе. Каждый раз, когда в подчиненном интерпретаторе + будет вызываться команда srcCmd, реально выполняться + будет команда targetCmd в + мастер-интерпретаторе. Аргументы arg, если они есть, + определяют дополнительные аргументы для команды + targetCmd, которые будут вставлены перед аргументами, + заданными при вызове srcCmd. Подробнее см. "Использование + алиасов". +
    + +
    slave eval arg ?arg..?
    + +
    Эта команда объединяет все свои аргументы так же, как + команда concat, и выполняет + сформированный таким образом скрипт в подчиненном + интерпретаторе. Результат выполнения (включая информацию об + ошибках в переменных + errorInfo и errorCode, если + произошла ошибка) возвращается в вызывающий интерпретатор. +
    + +
    slave expose hiddenName + ?exposedCmdName?
    + +
    Разрешает использование в подчиненном интерпретаторе + скрытой команды hiddenName под новым именем + exposedCmdName (в настоящее время поддерживаются только + имена в глобальном пространстве имен, не содержащие + "::"). Если обычная (не скрытая) команда + exposedCmdName уже существует, генерируется сообщение + об ошибке. Скрытые команды обсуждаются ниже (см. "Скрытые команды"). +
    + +
    slave hide exposedCmdName + ?hiddenCmdName?
    + +
    Запрещает использование в подчиненном интерпретаторе обычной + команды exposedCmdName и переименовывает ее в скрытую + команду hiddenCmdName (или в скрытую команду под старым + именем, если новое не было задано). Если скрытая команда с + заданным именем уже существует, команда возвращает ошибку. В + настоящее время exposedCmdName и hiddenCmdName + не могут содержать "::". Команды, которые + должны быть скрыты с помощью interp hide, ищутся только + в глобальном пространстве имен, даже если текущее пространство + имен не глобальное. Скрытые команды обсуждаются ниже + (см. "Скрытые + команды"). +
    + +
    slave hidden
    + +
    Возвращает список скрытых команд в подчиненном + интерпретаторе. +
    + +
    slave invokehidden ?-global? + hiddenName ?arg..?
    + +
    Вызывает в подчиненном интерпретаторе скрытую команду + hiddenCmdName с перечисленными аргументами. Никаких + подстановок или вычислений в аргументах не производится. Если + указана опция -global, скрытая команда выполняется на + глобальном уровне в подчиненном интерпретаторе. В противном + случае она выполняется в текущем контексте и может + использовать значения локальных переменных и переменных из + вышестоящих стеков. Скрытые команды обсуждаются подробно в + соответствующем разделе ниже. +
    + +
    slave issafe
    + +
    Возвращает 1, если подчиненный интерпретатор + безопасный, и 0 в противном случае. +
    + +
    slave marktrusted
    + +
    Отмечает подчиненный интерпретатор как надежный. Не + раскрывает скрытые команды. Команда может выполняться только + из надежного интерпретатора. Если подчиненный интерпретатор + уже надежный, команда не оказывает никакого воздействия. +
    +
    + +

    + БЕЗОПАСНЫЕ ИНТЕРПРЕТАТОРЫ

    + +

    Безопасный интерпретатор - это интерпретатор с ограниченной + функциональностью. Поэтому в нем можно без опасений выполнять + произвольные скрипты, даже написанные вашим злейшим врагом, не + опасаясь нарушить выполнение вашего приложения или испортить + содержимое дисков вашего компьютера. Чтобы обеспечить + безопасность, из таких интерпретаторов удалены определенные + команды и переменные. Например, команда создания файлов на диске + и команда запуска подпроцессов. Тем не менее, в безопасном + интерпретаторе можно обеспечить ограниченный доступ к подобным + командам с помощью механизма алиасов. В результате при + выполнении потенциально опасных команд будут вызываться + специально написанные процедуры в мастер-интерпретаторе, которые + могут тщательно проверять заданные аргументы и позволять + использовать только ограниченный набор средств. Например, + создание файлов может быть разрешено только в ограниченном + наборе подкаталогов, а запуск подпроцессов разрешен только для + ограниченного (и фиксированного) набора хорошо проверенных + программ. +

    + +

    Чтобы создаваемый интерпретатор был безопасным, необходимо при + его создании указать опцию -safe. Кроме того, любой + интерпретатор, созданный из безопасного интерпретатора, также + будет безопасным. +

    + +

    Безопасный интерпретатор создается со следующим набором + команд:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    afterappendarraybreakcase
    catchclockconcatcontinueeof
    errorevalexprfblockedfileevent
    flushforforeachformatgets
    globalhistoryifincrinfo
    interpjoinlappendlindexlinsert
    listllengthlowerlrangelreplace
    lsearchlsortpackagepidproc
    putsreadrenamereturnscan
    seeksetsplitstringsubst
    switchtelltraceunsetupdate
    uplevelupvarvwaitwhile
    + +

    Следующие команды в безопасном интерпретаторе скрыты:

    + + + + + + + + + + + + + + + + + + + + + + +
    cdexecexitfconfigure
    fileglobloadopen
    pwdsocketsource
    + +

    Эти команды могут быть созданы заново как Tcl-процедуры или + алиасы или разрешены к использованию с помощью команды interp expose.

    + +

    Сверх того, в безопасных интерпретаторах отсутствует массив + env, содержащий обычно + переменные окружения. Это связано с тем, что в переменных + окружения может храниться конфиденциальная информация.

    + +

    Расширения, загружаемые в безопасный интерпретатор, также + обладают ограниченной функциональностью. Более подробно эти + вопросы обсуждаются в пп. SafeTcl и load. +

    + +

    ИСПОЛЬЗОВАНИЕ + АЛИАСОВ

    + +

    Механизм алиасов весьма тщательно спроектирован таким образом, + чтобы он позволял без опасений выполнять ненадежные скрипты в + безопасных подчиненных интерпретаторах, используя для алиасов + проверенные команды в мастер-интерпретаторах. Для обеспечения + безопасности принципиально важно, чтобы информация из + подчиненного интерпретатора никогда не обрабатывалась (то есть + скрипты не исполнялись, и в них не производились подстановки) в + мастер-интерпретаторе. В противном случае всегда будет + оставаться возможность написать такой скрипт для подчиненного + интерпретатора, который выполнил бы произвольные действия в + мастер-интерпретаторе и мог бы нарушить его безопасность.

    + +

    Когда в подчиненном интерпретаторе вызывается команда-алиас, + необходимые Tcl-подстановки в аргументах выполняются там же, как + для обычной Tcl-команды. После этого аргументы объединяются с + целевой командой и ее аргументами, определенными при создании + алиаса. Так, если команда вызова алиаса имела вид ``srcCmd + arg1 arg2... argN'', то сформируется команда ``targetCmd + arg arg... arg arg1 arg2... argN'', где arg + arg... arg - аргументы, указанные при создании + алиаса. После этого сформированная команда выполняется в целевом + интерпретаторе (со сформированным набором аргументов). Если в + целевом интерпретаторе нет команды targetCmd, будет + сгенерирована ошибка. Перед выполнением команды в целевом + интерпретаторе больше никаких подстановок в аргументах + произведено не будет. Команда будет вызвана напрямую, а не через + обычный механизм выполнения. Таким образом, подстановки в каждом + слове команды оказываются выполненными ровно один раз: в + targetCmd и arg... arg - при выполнении команды, + с помощью которой был создан алиас, а в arg1 - argN - при + анализе команды алиаса в соответствующем интерпретаторе.

    + +

    При написании процедуры targetCmd, которую + предполагается использовать для алиаса в безопасном + интерпретаторе, нужно придерживаться следующего правила. + Недопустимо, чтобы в значениях ее аргументов в теле процедуры + производились подстановки, либо чтобы аргументы были скриптами, + исполняемыми в теле процедуры. Нарушение этого правила дает + возможность подчиненному интерпретатору выполнить произвольный + код в мастер-интерпретаторе и нарушить, таким образом, + безопасность системы.

    + +

    СКРЫТЫЕ КОМАНДЫ

    + +

    Безопасные интерпретаторы существенно ограничивают + функциональные возможности выполняемых в них Tcl-скриптов. С + одной стороны, это позволяет избежать нежелательных последствий + при их исполнении, но, с другой стороны, рано или поздно + возникает насущная необходимость выполнить потенциально опасную + команду в безопасном интерпретаторе. Например, прочитать + дополнительный скрипт с помощью команды source. Или выполнить в + Tk-приложении некоторые команды управления окнами.

    + +

    Команда interp обеспечивает решение этой проблемы с + помощью механизма скрытых команд. Потенциально опасные команды + не удаляются из безопасного интерпретатора, а становятся + скрытыми. При этом их невозможно выполнить из скрипта, + выполняемого "внутри" интерпретатора. Но их можно выполнить + "извне" из любого надежного предка интерпретатора с помощью + команды interp invoke. Скрытые и обычные (не скрытые) + команды размещаются в различных пространствах имен. Это + позволяет иметь в одном интерпретаторе скрытую и обычную команды + с одним и тем же именем.

    + +

    Скрытые команды могут использоваться в теле процедуры, + использованной при определении алиаса. Например, в подчиненном + интерпретаторе можно создать алиас source. Вызываемая при этом + процедура в мастер-интерпретаторе проверяет допустимость + запрошенной операции (например, что запрошенный файл находится в + соответствующем каталоге, к которому разрешен доступ из + подчиненного интерпретатора) и вызывает в подчиненном + интерпретаторе скрытую команду source. Обратите внимание, что + в этом случае в подчиненном интерпретаторе существует две + команды source: скрытая и + алиас.

    + +

    Из мастер-интерпретатора возможен вызов скрытых команд + подчиненного интерпретатора через механизм алиасов. Поэтому в + теле процедур, предназначенных для создания алиаса, необходимо + избегать подстановок и команд исполнения для + аргументов. См. "Использование алиасов".

    + +

    Безопасные интерпретаторы не могут "изнутри" вызвать скрытую + команду в себе или своих потомках.

    + +

    Множество скрытых команд может быть изменено из надежного + интерпретатора с помощью команд interp + expose и interp + hide. Безопасный интерпретатор не может изменить набор + скрытых команд в себе или своих потомках.

    + +

    В настоящее время имена скрытых команд не могут содержать имени + пространства имен. Поэтому, прежде чем скрыть команду, ее надо + перевести в глобальное пространство имен. Команды, которые + необходимо скрыть, должны находиться в глобальном пространстве + имен. Это позволяет избежать ошибочного скрытия одноименной + команды из другого пространства имен.

    + + diff --git a/hlp/ru/tcl/join.html b/hlp/ru/tcl/join.html new file mode 100644 index 0000000..ea488e7 --- /dev/null +++ b/hlp/ru/tcl/join.html @@ -0,0 +1,27 @@ + + + + join + + + +

    join

    + +

    Команда соединяет элементы списка в одну строку.

    + +

    СИНТАКСИС

    + +
    +      join list joinString
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда возвращает строковое значение, состоящее из всех + элементов спискаlist, отделенных друг от друга символом + joinString. Список list должен быть Tcl-списком, + joinString по умолчанию есть пробел.

    + +

    ПРИМЕР

    + + diff --git a/hlp/ru/tcl/lappend.html b/hlp/ru/tcl/lappend.html new file mode 100644 index 0000000..a395960 --- /dev/null +++ b/hlp/ru/tcl/lappend.html @@ -0,0 +1,37 @@ + + + + lappend + + + +

    lappend

    + +

    Команда дополняет переменную элементами списка.

    + +

    СИНТАКСИС

    + +
    +      lappend varName value value value ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда добавляет в список varName каждый из аргументов + value как новый элемент, отделенный пробелом. Если + varName не существует, то он будет создан с элементами, + заданными value. Команда lappend подобна команде + append, за исключением того, + что аргументы добавляются в качестве элементов списка, а не + просто текста. С помощью этой команды можно эффективно создавать + большие списки. Например, для больших списков команда

    +
    +      lappend a $b
    +    
    +

    намного эффективнее, чем

    +
    +      set a [concat $a [list $b]]
    +    
    + + + diff --git a/hlp/ru/tcl/library.html b/hlp/ru/tcl/library.html new file mode 100644 index 0000000..772f9aa --- /dev/null +++ b/hlp/ru/tcl/library.html @@ -0,0 +1,268 @@ + + + + library + + +

    library

    + +

    Команды стандартной библиотеки процедур Tcl.

    + +

    СИНТАКСИС

    + +
    +      auto_execok cmd
    +      auto_load cmd
    +      auto_mkindex dir pattern pattern
    +      auto_reset
    +      parray arrayName
    +      tcl_endOfWord str start
    +      tcl_startOfNextWord str start
    +      tcl_startOfPreviousWord str start
    +      tcl_wordBreakAfter str start
    +      tcl_wordBreakBefore str start
    +    
    + +

    ОПИСАНИЕ

    + +

    Tcl содержит библиотеку Tcl-процедур общего назначения.

    + +

    Местонахождение библиотеки Tcl можно получить с помощью команды + info + library. Обычно, помимо этой библиотеки, приложения + имеют собственные библиотеки служебных процедур. Местонахождение + процедур приложения обычно содержит глобальная переменная + $app_library, где app - имя приложения. Например, + для Tk это переменная $tk_library.

    + +

    Для того, чтобы использовать процедуры из Tcl-библиотеки, + приложению необходимо прочитать файл init.tcl библиотеки, + например, командой

    +
    +      source [file join [info library] init.tcl]
    +    
    +

    Если в приложении процедура Tcl_AppInit вызывает + библиотечную процедуру Tcl_Init, то такая команда + выполняется автоматически. Код в файле init.tcl определит + процедуру unknown и + позволит остальным процедурам загружаться по требованию при + помощи механизма автозагрузки, описанного ниже.

    + +

    КОМАНДНЫЕ ПРОЦЕДУРЫ

    + +

    Библиотека Tcl предоставляет пользователю следующие + процедуры:

    + +
    + +
    auto_execok cmd
    + +
    Эта команда просматривает каталоги в текущем пути поиска + (заданном переменной окружения PATH) и проверяет, есть ли в + каталогах исполняемый файл по имени cmd. Если файл + присутствует, то команда возвращает 1, если нет - то + 0. Команда запоминает сведения о предыдущем поиске в + массиве auto_execs, это позволяет обходиться без поиска + в каталогах при последующих вызовах этой же команды. Для + удаления из памяти этой информации можно использовать команду + auto_reset. +
    + +
    auto_load cmd
    + +

    Эта команда загружает определение для Tcl-команды + cmd. Для этого она просматривает путь автозагрузки, + являющийся списком из одного или более каталогов. Он + содержится в глобальной переменной auto_path, если + она существует. В противном случае используется переменная + окружения TCLLIBPATH. Если же и она не существует, список + автозагрузки состоит из каталога, в котором находится + Tcl-библиотека.

    + +

    В каждом из каталогов, входящих в путь автозагрузки, должен + находиться файл tclIndex, список команд, определенных + в этом каталоге, и скрипты для загрузки каждой команды. Файл + tclIndex должен быть создан с помощью команды + auto_mkindex.

    + +

    Если команда была успешно загружена, то auto_load + возвращает 1. Команда возвращает 0, если + нужная команда не была найдена в списках команд или + указанная команда загрузки не позволила создать команду + (например, если файл tclIndex устарел). Если при + выполнении указанного загрузочного скрипта возникла ошибка, + команда возвращает ошибку.

    + +

    Команда auto_load читает индексные файлы только один + раз и сохраняет полученную информацию в массиве + auto_index. При последующих обращениях к команде + auto_load сначала проверяется массив и только если + информация о процедуре не найдена, приступает к просмотру + индексных файлов. Эта информация может быть удалена с + помощью команды auto_reset. После команды + auto_reset следующий вызов auto_load к + повторному чтению индексных файлов.

    +
    + +
    auto_mkindex dir + pattern pattern...
    + +

    Команда создает индекс для использования его командой + auto_load. Для этого команда просматривает каталог + dir в поисках файлов с именами, удовлетворяющими + аргументам pattern (сравнение выполняется командой glob), и создает индекс всех + командных процедур Tcl, определенных в обнаруженных файлах, + и сохраняет индекс в файле tclIndex в этой + dir. Если не задано ни одного шаблона pattern, + то по умолчанию принимается *.tcl. Например, + команда

    +
    +	  auto_mkindex foo *.tcl
    +	
    +

    просматривает все .tcl-файлы в каталоге foo и + создает новый индексный файл foo/tclIndex.

    + +

    Команда auto_mkindex просматривает Tcl-скрипты очень + простым способом: если в очередной строке, начиная с первого + символа, написано слово proc, считается, что это + определение процедуры, а следующее слово есть имя + процедуры. Процедуры, определение которых не подходит под + описанное (например, если перед словом proc стоят пробелы), не попадают в + индексный файл.

    +
    + +
    auto_reset
    + +
    Команда удаляет всю информацию, накопленную командами + auto_execok и auto_load. При следующем обращении + к этой информации она будет считана с диска заново. Эта + команда также удаляет все процедуры, перечисленные в массиве + auto_index, так что при следующем обращении к ним будут + загружены новые копии. +
    + +
    parray arrayName
    + +
    Команда выдает на стандартный выход имена и значения + элементов массива arrayName. Массив должен быть + доступен в контексте вызова. Он может быть как локальным, так + и глобальным. +
    + +
    tcl_endOfWord str + start
    + +
    Возвращает индекс первого конца слова после указанного + индекса start в строке str. Первым концом слова + считается первый символ, не принадлежащий слову, следующий за + первым после начальной точки символом слова. Возвращает + -1, если после начальной точки больше нет концов + слова. Способ распознавания символов слов, используемый в Tcl, + приведен в описании переменных tcl_wordchars и + tcl_nonwordchars. +
    + +
    tcl_startOfNextWord + str start
    + +
    Возвращает индекс первого начала слова после указанного + индекса start в строке str. Первым началом слова + считается первый символ слова, следующий за символом, не + принадлежащим слову. Возвращает -1, если после + начальной точки больше нет начала слова. +
    + +
    + tcl_startOfPreviousWord str start
    + +
    Возвращает индекс первого начала слова до указанного + индекса start в строке str. Возвращает + -1, если после начальной точки больше нет начала + слова. +
    + +
    + tcl_wordBreakAfterstr start
    + +
    Возвращает индекс первой границы слова после указанного + индекса start в строке str. Возвращает + -1, если в указанной строке после начальной точки + больше нет границ слова. Возвращаемый индекс относится ко + второму символу пары, образующей границу. +
    + +
    + tcl_wordBreakBefore str start
    + +
    Возвращает индекс первой границы слова до указанного + индекса start в строке str. Возвращает + -1, если в указанной строке до начальной точки + больше нет границ слова. Возвращаемый индекс относится ко + второму символу пары, образующей границу. +
    +
    + +

    ПЕРЕМЕННЫЕ

    + +

    Процедуры Tcl используют или определяют следующие глобальные + переменные.

    + +

    auto_execs - используется командой auto_execok + для записи информации о том, существуют ли конкретная команда в + виде исполняемого файла.

    + +

    auto_index - используется auto_load для + сохранения индексной информации, считанной с диска.

    + +

    auto_noexec - если переменная задана с любым значением, + то команда unknown не + будет пытаться автоматически исполнить какую-либо команду.

    + +

    auto_noload - если переменная задана с любым значением, + то команда unknown не + будет пытаться автоматически загрузить какую-либо команду.

    + +

    auto_path - если переменная задана, то она должна + содержать Tcl-список с каталогами для просмотра при операциях + автозагрузки.

    + +

    env(TCL_LIBRARY) - если переменная задана, то она + указывает местоположение каталога с библиотечными скриптами + (команда info + library возвращает значение этой переменной). Если + переменная не определена, то используется значение по + умолчанию.

    + +

    env(TCLLIBPATH) - если переменная задана, то она должна + содержать действующий Tcl список каталогов для поиска при + операциях автозагрузки. Эта переменная используется только + тогда, когда не определена переменная auto_path.

    + +

    tcl_nonwordchars - переменная содержит регулярное + выражение, используемое такими процедурами, как + tcl_endOfWord для определения, является ли символ частью + слова или нет. Если образец соответствует символу, то символ + считается не принадлежащим к слову. В Unix такими символами + являются все символы, кроме цифр, букв и символа + подчеркивания.

    + +

    tcl_wordchars - переменная содержит регулярное + выражение, используемое такими процедурами, как + tcl_endOfWord для определения, является ли символ частью + слова или нет. Если образец соответствует символу, то символ + считается частью слова. В Unix слова состоят из цифр, букв и + символа подчеркивания.

    + +

    unknown_active - эта переменная служит флагом для + индикации активности команды unknown: команда сама + устанавливает ее. Переменная используется для выявления ошибок, + при которых unknown + бесконечно рекурсивно обращается к себе. Перед окончанием работы + unknown переменная + сбрасывается.

    + + diff --git a/hlp/ru/tcl/lindex.html b/hlp/ru/tcl/lindex.html new file mode 100644 index 0000000..8da48f0 --- /dev/null +++ b/hlp/ru/tcl/lindex.html @@ -0,0 +1,32 @@ + + + + lindex + + + +

    lindex

    + +

    Команда извлекает элемент списка.

    + +

    СИНТАКСИС

    + +
    +      lindex list index
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда lindex считает list Tcl списком и + возвращает index-ный элемент этого списка. Для + index значение 0 соответствует первому элементу + списка, а значение end - последнему. При выполнении + команды соблюдаются общие правила интерпретатора Tcl + относительно фигурных скобок, двойных кавычек и обратного слэша, + хотя подстановки переменных и команд не происходят. Если + index отрицательное число или больше или равно числу + элементов, команда возвращает пустое значение. Если значение + аргумента index равно end, команда возвращает + последний элемент списка.

    + + diff --git a/hlp/ru/tcl/linsert.html b/hlp/ru/tcl/linsert.html new file mode 100644 index 0000000..c5fd38e --- /dev/null +++ b/hlp/ru/tcl/linsert.html @@ -0,0 +1,29 @@ + + + + linsert + + + +

    linsert

    + +

    Команда служит для вставки элементов в список.

    + +

    СИНТАКСИС

    + +
    +      linsert listName index element element element ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда создает из listNameновый список при + помощи вставки аргументов element непосредственно перед + index-ным элементом списка list. Каждый из + аргументов element станет отдельным элементом нового + списка. Если индекс index меньше или равен нулю, новые + элементы вставляются в начало списка. Если индекс index + больше или равен числу элементов в списке или равен end, + новые элементы вставляются в конец списка.

    + + diff --git a/hlp/ru/tcl/list.html b/hlp/ru/tcl/list.html new file mode 100644 index 0000000..659cc86 --- /dev/null +++ b/hlp/ru/tcl/list.html @@ -0,0 +1,53 @@ + + + + list + + + +

    list

    + +

    Команда создает список.

    + +

    СИНТАКСИС

    + +
    +      list arg arg ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда list возвращает новый список из всех элементов + arg или пустой список, если аргументы не указаны. При + формировании списка по необходимости используются фигурные + скобки и обратные слэши, что позволяет потом использовать + команду index для извлечения исходных аргументов, а также + использовать команду eval для + исполнения результирующего списка, с arg1, содержащим имя + команды, и остальными arg в качестве ее + аргументов. Команда list несколько отличается от команды + concat: тем, что команда concat удаляет один уровень + группирования перед образованием списка, тогда как команда + list работает непосредственно с исходными + аргументами. Например, команда

    + +
    +      list a b {c d e} {f {g h}}
    +    
    + +

    вернет

    + +
    +      a b {c d e} {f {g h}}
    +    
    + +

    Тогда как команда concat с + теми же аргументами вернет

    + +
    +      a b c d e f {g h}
    +    
    + + + diff --git a/hlp/ru/tcl/llength.html b/hlp/ru/tcl/llength.html new file mode 100644 index 0000000..80518eb --- /dev/null +++ b/hlp/ru/tcl/llength.html @@ -0,0 +1,25 @@ + + + + llength + + + +

    llength

    + +

    Команда подсчитывает количество элементов в списке.

    + +

    СИНТАКСИС

    + +
    +      llength list
    +    
    + +

    ОПИСАНИЕ

    + +

    Аргумент list истолковывается как список; команда + возвращает строку с десятичным числом, равным количеству + элементов в этом списке.

    + + + diff --git a/hlp/ru/tcl/load.html b/hlp/ru/tcl/load.html new file mode 100644 index 0000000..84746e0 --- /dev/null +++ b/hlp/ru/tcl/load.html @@ -0,0 +1,118 @@ + + + + load + + + +

    load

    + +

    Команда загружает машинный код и инициализирует новые команды.

    + +

    СИНТАКСИС

    + +
    +      load fileName 
    +      load fileName packageName
    +      load fileName packageName interp
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда загружает двоичный код из файла в адресное + пространство приложения и вызывает инициализирующую процедуру + библиотеки, чтобы включить ее в интерпретатор. Аргумент + fileName есть имя файла, содержащего код. Конкретная + форма кода различна на разных платформах, но чаще всего он + должен быть разделяемой библиотекой, такой как .so-файлы + для Solaris и .dll-файлы для Windows. Аргумент + packageName есть имя библиотеки. Оно используется для + определения имени инициализационной процедуры. Аргумент + interp содержит имя интерпретатора (см. описание команды + interp). Если аргумент + interp не указан явно, то по умолчанию библиотека + загружается в текущий интерпретатор.

    + +

    Как только файл загружен в адресное пространство приложения, + вызывается одна из двух процедур инициализации нового + кода. Обычно процедура инициализации добавляет в интерпретатор + новые Tcl-команды. Имя процедуры определяется исходя из имени + библиотеки и из того, является интерпретатор, в который будут + добавляться команды, безопасным (см. команду interp). Для обычного + интерпретатора имя процедуры pkg_Init, где pkg - + имя библиотеки, преобразованное следующим образом: Первая буква + переведена в верхний регистр, а все остальные - в + нижний. Например, если имя библиотеки Foo, то имя + инициализационной процедуры должно быть Foo_Init.

    + + +

    Для безопасного интерпретатора имя процедуры должно быть + pkg_SafeInit. Эта функция должна быть написана очень + тщательно, чтобы позволить включить в безопасный интерпретатор + только те команды библиотеки, которые безопасны при + использовании в ненадежном коде. Дополнительная информация + приведена в п. Safe.

    + +

    Процедура инициализации должна соответствовать следующему + прототипу:

    + +
    +      typedef int Tcl_PackageInitProc(Tcl_Interp  *interp);
    +    
    + +

    Аргумент interp определяет интерпретатор, в который + библиотека будет загружена. Процедура инициализации должна + вернуть код TCL_OK или TCL_ERROR чтобы указать, + была ли она завершена успешно. В случае ошибки она должна + присвоить переменной interp->result значение указателя + на сообщение об ошибке. Результат процедуры инициализации будет + возвращен командой load как ее результат.

    + +

    Реально каждый файл загружается в приложение только один + раз. Если команда load вызывается несколько раз, чтобы + загрузить один и тот же файл в различные интерпретаторы, то + реально загрузка кода выполняется только в первый раз. При + последующих вызовах будет выполняться только процедура + инициализации библиотеки в соответствующем интерпретаторе. + Выгрузить или повторно загрузить библиотеку невозможно.

    + +

    Команда load также поддерживает библиотеки, статически + связанные с приложением, если они зарегистрированы с + использованием процедуры Tcl_StaticPackage. Если аргумент + fileName есть пустая строка, то необходимо указывать имя + библиотеки.

    + +

    Если аргумент packageName отсутствует или равен пустой + строке, Tcl пытается сам сформировать имя библиотеки. На разных + платформах это выполняется по-разному. На Unix-платформах обычно + для этого берется последний элемент имени файла. Если первые три + буквы в нем - lib, то они отбрасываются. После чего + берутся все последовательные символы, которые являются буквами + или символом подчеркивания. Например, если имя файла + libxyz4.2.so, то в качестве имени библиотеки будет + сформировано xyz, а при исполнении команды

    + +
    +      load bin/last.so {}
    +    
    + +

    сформируется имя библиотеки last. Если аргумент + fileName равен пустой строке, то должен быть задан + аргумент packageName. Команда load в таком случае + ищет сначала статически загружаемую библиотеку (то есть, + библиотеку, зарегистрированную с помощью процедуры + Tcl_StaticPackage) с указанным именем. Если такая будет + найдена, то она используется в команде. В противном случае + ищется динамически загружаемая процедура с этим именем. Если + загружено несколько версий одной и той же библиотеки, то Tcl + выбирает ту, которая была загружена первой.

    + +

    ОШИБКИ

    + +

    Если одна и та же библиотека загружается несколько раз из + различных файлов, на некоторых платформах она будет загружена в + адресное пространство несколько раз. +

    + + diff --git a/hlp/ru/tcl/lrange.html b/hlp/ru/tcl/lrange.html new file mode 100644 index 0000000..3957f2e --- /dev/null +++ b/hlp/ru/tcl/lrange.html @@ -0,0 +1,50 @@ + + + + lrange + + + +

    lrange

    + +

    Команда возвращает один или несколько последовательных + элементов списка.

    + +

    СИНТАКСИС

    + +
    +      lrange list first last
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда возвращает новый список - подмножество Tcl-списка + list, начиная с элемента first и заканчивая + элементом last включительно. Для обозначения последнего + элемента списка list в аргументе first или + last можно использовать значение end. Если аргумент + first меньше нуля, он считается равным нулю. Если + аргумент last больше или равен числу элементов в списке, + он считается равным end. Если аргумент first + больше, чем last, то команда возвращает пустой список. + Команда

    + +
    +      lrange list first first
    +    
    + +

    не всегда возвращает тот же результат, что и

    + +
    +      lindex list first
    +    
    + +

    (хотя это обычно так при простых элементах списка, которые не + заключены в фигурные скобки). Но она всегда возвращает тот же + результат, что и команда

    + +
    +      list [lindex list first]
    +    
    + + diff --git a/hlp/ru/tcl/lreplace.html b/hlp/ru/tcl/lreplace.html new file mode 100644 index 0000000..423bd62 --- /dev/null +++ b/hlp/ru/tcl/lreplace.html @@ -0,0 +1,36 @@ + + + + lreplace + + + +

    lreplace

    + +

    Команда замещает элементы списка новыми элементами.

    + +

    СИНТАКСИС

    + +
    +      lreplace list first last element element ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда lreplace возвращает новый список, образованный + из списка list путем замены его элементов, начиная с + first до last, на аргументы element. Если + аргумент first меньше нуля, он считается равным + нулю. Если аргумент last больше или равен числу элементов + в списке, он считается равным end. Если last + меньше, чем first, тогда не будет удалено ни одного + прежнего элемента, и новые элементы будут просто вставлены перед + first. Для аргументов first и last можно + использовать значение end для ссылки на последний элемент + списка. Каждый аргумент element становится отдельным + элементом списка. Если не было задано ни одного аргумента + element, тогда прежние элементы списка с first по + last будут просто удалены.

    + + + diff --git a/hlp/ru/tcl/lsearch.html b/hlp/ru/tcl/lsearch.html new file mode 100644 index 0000000..56a3505 --- /dev/null +++ b/hlp/ru/tcl/lsearch.html @@ -0,0 +1,49 @@ + + + + lsearch + + + +

    lsearch

    + +

    Команда проверяет наличие заданного элемента в списке.

    + +

    СИНТАКСИС

    + +
    +      lsearch mode list pattern
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда просматривает по очереди элементы + спискаlist с целью найти первый из них, совпадающий с + заданным образцом pattern. Команда возвращает индекс + первого найденного такого элемента или "-1" если такой + элемент не найден. Аргумент mode указывает конкретный + способ сравнения элементов списка и образца. Возможные значения + аргумента:

    + +
    +
    -exact
    + +
    Означает, что элемент списка должен быть в точности равен + образцу.
    + +
    -glob
    + +
    Означает, что используются такие же правила сравнения, как в + команде string match.
    + +
    -regexp
    + +
    Означает, что образец считается регулярным выражением, и для + сравнения используются те же правила, что и в команде regexp.
    +
    + +

    По умолчанию аргумент mode имеет занчение + -glob.

    + + diff --git a/hlp/ru/tcl/lsort.html b/hlp/ru/tcl/lsort.html new file mode 100644 index 0000000..ea501a9 --- /dev/null +++ b/hlp/ru/tcl/lsort.html @@ -0,0 +1,99 @@ + + + + lsort + + + +

    lsort

    + +

    Команда сортирует элементы списка.

    + +

    СИНТАКСИС

    + +
    +      lsort ?options? list
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда сортирует элементы списка list и + возвращает новый список с уже упорядоченными элементами. По + умолчанию используется упорядочивание в порядке возрастания + символов в таблице ASCII. Кроме того, для управления процессом + сортировки в команде можно указать произвольные из перечисленных + ниже опций (допускаются уникальные сокращения).

    + +
    +
    -ascii
    + +
    Упорядочивание в порядке возрастания символов в таблице + ASCII. Значение по умолчанию.
    + +
    -dictionary
    + +

    Словарный режим. Тоже, что и -ascii, но со + следующими отличиями:

    +
      +
    • регистр не учитывается;
    • + +
    • если две строки содержат цифры, то числа сравниваются + как целые, а не как символы ASCII.
    • +
    +

    Например, bigBoy окажется между bigbang и + bigboy, а x10y между x9y и + x11y.

    +
    + +
    -integer
    + +
    Режим целых чисел, когда все элементы списка конвертируются + в целые числа и при сравнении трактуются именно как целые + числа.
    + +
    -real
    + +
    Режим чисел с плавающей запятой; этот режим аналогичен + предыдущему и используется для действительных чисел.
    + +
    -command command
    + +
    Режим сортировки при помощи произвольной команды + пользователя. Для сравнения двух элементов списка выполняется + скрипт, состоящий из command и дополненный + соответствующими элементами списка. Скрипт должен вернуть + целое число, большее нуля, равное нулю, или меньшее нуля в + зависимости от того, считается ли первый элемент больше + второго, равен ему или меньше его.
    + +
    -increasing
    + +
    Сортировка в порядке возрастания (от меньших к большим). + Это значение по умолчанию.
    + +
    -decreasing
    + +
    Сортировка в порядке убывания (от больших к меньшим).
    + +
    -index index
    + +

    Эта опция может использоваться, если каждый из элементов + списка сам есть список (то есть list есть список + списков). Опция позволяет отсортировать список по "одной + из колонок", то есть по элементам подсписков с + фиксированным индексом index. Значение аргумента + index, равное end, означает генерацию по + последнему элементу подсписков. Например, команда

    +
    +	  lsort -integer -index 1 {{First 24} {Second 18} {Third 30}}
    +	
    + +

    вернет {Second 18} {First 24} {Third 30}.

    + +

    Эта опция значительно более эффективна для данной задачи, + чем опция -command с соответствующей процедурой + сравнения.

    +
    +
    + + diff --git a/hlp/ru/tcl/namespace.html b/hlp/ru/tcl/namespace.html new file mode 100644 index 0000000..3f3cff3 --- /dev/null +++ b/hlp/ru/tcl/namespace.html @@ -0,0 +1,601 @@ + + + + namespace + + + +

    namespace

    + + +

    Команда предназначена для создания и управления областями имен + для команд и переменных.

    + +

    СИНТАКСИС

    + +
    +      namespace ?option? ?arg?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда позволяет создавать, обращаться и уничтожать отдельные + области имен для команд и переменных. Более детально назначение + и использование команды описаны ниже см. + Пространства имен. + Действия, выполняемые командой, + зависят от значения аргумента option. Ниже приведены + возможные опции команды.

    + +
    +
    namespace children ?namespace? + ?pattern?
    + +
    Позволяет получить список областей-потомков для области имен + namespace. Если аргумент namespace отсутствует, + то возвращается список областей-потомков для текущего + пространства имен. Команда возвращает полные имена, + начинающиеся с ::. Если указан аргумент pattern, + команда возвращает только те имена, которые удовлетворяют + шаблону pattern. Проверка на соответствие производится + по тем же правилам, что и в команде glob. При этом шаблон, + начинающийся с ::, используется непосредственно, в + противном случае используемый шаблон составляется из + namespace (или полного имени текущего пространства + имен) и pattern.
    + +
    namespace code script
    + +

    Позволяет захватить контекст текущей области имен для + скрипта script с тем, чтобы потом использовать этот + контекст при выполнении данного скрипта. Команда возвращает + новый скрипт, в котором старый скрипт завернут в + команду namespace code. Новый скрипт имеет две важные + особенности: во-первых, он может быть вызван в произвольном + пространстве имен, при этом реально он будет выполняться в + текущем пространстве имен (том, в котором выполнялась команда + namespace code). Во-вторых, к созданному таким образом + скрипту можно дописывать произвольные аргументы и они + действительно будут использоваться как дополнительные + аргументы. Например, предположим, что команда

    +
    +	  set script [namespace code {foo bar}]
    +	
    +

    выполняется в пространстве имен ::a::b. Тогда + команда

    +
    +	  eval "$script x y"
    +	
    +

    может быть выполнена в любом пространстве имен и будет + иметь тот же эффект, что и команда

    +
    +	  namespace eval ::a::b {foo bar x y}
    +	
    + +

    Эта команда необходима потому, что расширения Tcl, + например, Tk, обычно выполняют вызванные по событиям скрипты в + глобальном пространстве имен. Обертывающая команда захватывает + необходимую команду вместе с ее пространством имен и позволяет + корректно выполнить ее позже по соответствующему + вызову. Примеры использования данного механизма приведены ниже + см. Правила + видимости имен.

    +
    + +
    namespace current
    + +
    Позволяет получить полное имя текущей области имен. Хотя + реальное имя глобального пространства имен "" + (пустая строка), эта команда возвращает для него ::, + поскольку это часто бывает удобнее при программировании.
    + +
    namespace delete ?namespace + namespace...?
    + +
    Позволяет удалить одну или несколько областей имен, при этом + удаляются все переменные, процедуры и области-потомки заданной + области имен. Если внутри одного из удаляемых пространств имен + выполняется какая-либо процедура, оно будет сохранено до + завершения процедуры, но помечено, как приготовленное к + удалению, чтобы исключить вызов других процедур. Если + указанное пространство имен не существует, команда возвращает + ошибку. Если ни одно пространство имен не указано, команда не + делает ничего.
    + +
    namespace eval + namespace arg ?arg...?
    + +
    Позволяет активизировать пространство имен namespace + и выполнить в его контексте заданный код. Если пространство + имен namespace не существует, оно будет создано. Если + пространство имен должно быть предком несуществующего + пространства имен, то оно тоже создается. Если задано более + одного аргумента, все они объединяются в одну строку через + пробел (как при выполнении команды eval) и полученный скрипт + выполняется.
    + +
    namespace export ?-clear? + ?pattern pattern...?
    + +
    Позволяет указать, какие команды разрешено экспортировать из + данного пространства имен. Эти команды потом могут быть + импортированы в другие пространства имен с помощью команды + namespace import. Можно разрешать экспорт как + команд, созданных в данном пространстве имен, так и команд, + ранее импортированных из других пространств. Команда, + разрешаемая для экспорта, может в данный момент не + существовать. Каждый из шаблонов pattern может + содержать специальные символы как в команде glob, но не может содержать имени + пространства имен. То есть шаблон может указывать команды + только в текущем пространстве имен. Каждый из шаблонов + добавляется к списку шаблонов команд, разрешенных для импорта + из данного пространства имен. Если в команде указан флаг + -clear, команда предварительно удаляет старый + список. Если не указаны ни флаг, ни шаблоны, команда + возвращает текущий список шаблонов.
    + +
    namespace forget ?pattern + pattern...?
    + +
    Удаляет из пространства имен ранее импортированные команды. + Каждый образец pattern должен быть полным именем + команды с указанием хотя бы одного пространства имен и может + содержать специальные символы, как в команде glob, например: foo::x + или a::b::p*. Специальные символы нельзя использовать в + именах пространств имен. При выполнении данной команды сначала + ищутся команды, удовлетворяющие шаблону и разрешенные к + экспорту из соответствующих пространств имен. Далее + проверяется, какие из них были импортированы в текущее + пространство имен. После чего импортированные команды + удаляются. То есть команда выполняет действия, противоположные + действиям команды namespace import.
    + +
    namespace + import ?-force? ?pattern pattern...?
    + +
    Импортирует команды в текущее пространство имен. Каждый + образец pattern должен быть полным именем команды с + указанием хотя бы одного пространства имен и может содержать + специальные символы, как в команде glob, например foo::x или + a::b::p*. Специальные символы нельзя использовать в + именах пространств имен. Все команды, которые удовлетворяют + шаблонам и разрешены для экспорта, добавляются к текущему + пространству имен. Для этого в текущем пространстве имен + создается новая команда, которая указывает на экспортируемую + команду в исходном пространстве имен. При вызове этой новой + команды она вызывает исходную команду. Если в текущем + пространстве имен уже есть команда с таким именем, + возвращается ошибка, если не указана опция -force. В + противном случае импортируемая команда заменяет команду, + определенную ранее. Команда namespace import + импортирует в текущее пространство имен только те функции, + которые в момент исполнения существуют в соответствующем + пространстве имен. Если позже там будут созданы новые команды + с именами, удовлетворяющими шаблонам, разрешающим экспорт, и + шаблонам, определяющим импорт, то они не импортируются + автоматически.
    + +
    namespace inscope namespace arg + ?arg...?
    + +

    Выполняет скрипт в контексте пространства имен + namespace. Эта команда не предназначена для + непосредственного исполнения программистом. Ее вызовы + создаются автоматически при использовании команды + namespace code для создания скриптов, выполняемых в + фоновом режиме, например, для Tk-виджетов. Команда + namespace inscope похожа на команду namespace + eval, но отличается от нее наличием возможности + указывать дополнительные аргументы и тем, что пространство + имен namespace должно существовать в момент + выполнения команды. При выполнении команды первый аргумент + рассматривается как список, к которому остальные аргументы + добавляются как элементы списка. Так команда

    +
    +          namespace inscope ::foo a x y z
    +	
    +

    эквивалентна

    +
    +	  namespace eval ::foo [concat a [list x y z]]
    +	
    +

    Такая семантика весьма удобна при формировании скриптов, + выполняемых в фоновом режиме.

    +
    + +
    namespace origin command
    + +
    Возвращает полное имя оригинальной команды command, + от которой происходит заданная импортированная команда. При + импорте команды в текущем пространстве имен создается новая + команда, которая указывает на экспортируемую команду в + исходном пространстве имен. Если команда последовательно + импортировать в пространства имен a, b, ..., + n, причем в каждое последующее пространство имен она + импортировалась из предыдущего, то namespace origin + вернет полное имя команды в первом пространстве имен, то есть + a. Если команда command не импортирована, то + namespace origin вернет ее полное имя. +
    + +
    namespace parent ?namespace?
    + +
    Возвращает полное имя родительского пространства имен для + пространства namespace. Если аргумент namespace + не указан, возвращает полное имя предка текущего пространства + имен.
    + +
    namespace qualifiers string
    + +
    Возвращает полное имя пространства имен для string, + то есть часть строки string от начала до последнего + символа :: (но не включая его). Например, для строки + ::foo::bar::x эта команда вернет ::foo::bar, а + для :: - "" (пустую строку). Команда является + парной для команды namespace tail. При выполнении + команды проверка существования соответствующих пространств + имен не производится.
    + +
    namespace tail string
    + +
    Возвращает простое имя, завершающее полное имя + string, то есть часть строки string от + последнего символа :: (но не включая его) до конца + строки. Например, для строки ::foo::bar::x эта + команда вернет x, а для :: - "" + (пустую строку). Команда является парной для команды + namespace qualifiers. При выполнении команды проверка + существования соответствующих пространств имен не + производится.
    + +
    namespace which ?-command? + ?-variable? name
    + +
    Рассматривает name как имя команды или переменной (в + зависимости от указанной опции; по умолчанию - как имя + команды) и возвращает ее полное имя. Например, если + name не существует в текущем пространстве имен, но + существует в глобальном, то возвращает полное имя в глобальном + пространстве имен. Если команда или переменная не существует, + данная команда возвращает пустую строку. Более подробно + правила поиска имен см. Правила видимости имен.
    +
    + +

    ЧТО ТАКОЕ + ПРОСТРАНСТВО ИМЕН?

    + +

    Пространство имен - это обособленный набор команд и + переменных. Содержащиеся в нем команды и переменные не + взаимодействуют с командами и переменными в других пространствах + имен. В Tcl всегда был один такой набор, который мы будем + называть глобальным пространством имен. В нем содержатся все + глобальные переменные и команды. Команда namespace eval + позволяет создавать другие пространства имен, например, команда + +

    +        namespace eval Counter {
    +      		namespace export Bump
    +      		variable num 0
    +      		proc Bump {} {
    +      			variable num
    +      			incr num
    +		}
    +	}
    +      
    +

    создает новое пространство имен, содержащее переменную + num и процедуру Bump. Команды и переменные в этом + пространстве имен изолированы от других команд и имен в той же + программе. Например, в глобальном пространстве имен может + существовать другая команда Bump.

    + +

    Переменные пространства имен напоминают глобальные + переменные. Они существуют вне процедур, но могут использоваться + в процедурах с помощью команды variable, как показано в + предыдущем примере.

    + +

    Пространства имен - динамические образования. В них можно + в любой момент добавлять команды и переменные с помощью + дополнительных команд namespace eval. Например, то же + пространство имен, что и в предыдущем примере, можно было + создать с помощью последовательности команд:

    + +
    +      namespace eval Counter {
    +      	variable num 0
    +        proc Bump {} {
    +      		variable num
    +      		return [incr num]
    +      	}
    +      }
    +      namespace eval Counter {
    +      	proc test {args} {
    +      		return $args
    +      	}
    +      }
    +
    +      namespace eval Counter {
    +      	rename test ""
    +      }
    +    
    +

    Обратите внимание, что процедура test создана в + пространстве имен Counter, а затем удалена с помощью + команды rename. + +

    Пространства имен могут иметь собственные вложенные + пространства имен и образовывать иерархию пространств имен. + Вложенное пространство имен содержится в своем предке и не может + взаимодействовать с другими пространствами имен.

    + + +

    ПОЛНЫЕ ИМЕНА

    + +

    Каждое пространство имен имеет собственное имя, например history или + ::safe::interp. Полные имена используются для указания + команд, переменных или подпространств имен, содержащихся в + соответствующем пространстве имен. Полные имена напоминают + полные имена файлов в Unix или виджетов в Tk, но в качестве + разделителей в них используется не слэш или точка, а двойное + двоеточие "::". Самое верхнее или глобальное + пространство имен имеет имя "" (пустая строка) и + :: как синоним. Как пример, имя + ::safe::interp::create ссылается на команду create + в пространстве имен interp, + которое является подпространством пространства имен + ::safe, которое в свою очередь является подпространством + глобального пространства имен ::.

    + +

    Если вы хотите указать команду или переменную в другом + пространстве имен, вы можете указать имя пространства имен, в + котором она содержится. Например, из глобального пространства + имен вызвать процедуру из пространства имен Counter + можно следующим образом:

    + +
    +      Counter::Bump 5
    +      Counter::Reset
    +    
    +

    А вывести текущее значение переменной count можно с + помощью команды

    +
    +      puts "count = $Counter::num"
    +    
    +

    Если одно пространство имен содержит другое, может понадобиться + более длинное имя. Если пространство имен Foo содержит + пространство имен Counter, то чтобы вызвать процедуру + Bump в последнем из глобального пространства имен, нужно + воспользоваться именем

    +
    +      Foo::Counter::Bump 3
    +    
    +

    Полное имя может использоваться при создании или переименовании + команд. Например, можно добавить процедуру в пространство имен + Foo следующей командой:

    +
    +      proc Foo::Test {args} { return $args}
    +    
    +

    А переопределить ее в другом пространстве имен командой:

    +
    +      rename Foo::Test Bar::Test
    +    
    +

    Дополнительные замечания. Имена пространств имен, за + исключением глобального, не могут быть пустой строкой. + Сочетание :: запрещено в именах простых команд, + переменных и пространств имен кроме как в роли разделителя имен + пространств имен. Дополнительные символы : в полных + именах игнорируются, то есть два или больше символов : + подряд считаются одним разделителем. Сочетание :: в + конце имени команды или переменной указывает на команду или + переменную с именем {} (пустая строка). Однако в полном + имени пространства имен :: на конце игнорируется.

    + +

    ПРАВИЛА ВИДИМОСТИ ИМЕН

    + +

    Все Tcl-команды, которые работают с именами переменных и + команд, поддерживают полные имена. Это значит, что можно + использовать полные имена в таких командах, как set, proc, rename, или interp alias. Если вы + используете абсолютное имя, начинающееся с ::, то такое + имя всегда интерпретируется однозначно. Однако, если вы + используете относительное имя, не начинающееся с ::, + поиск объекта с соответствующим именем происходит по следующим + правилам: команды и переменные сначала ищутся в текущем + пространстве имен, а затем (если не найдены) - в + глобальном. Имена пространств имен ищутся только в текущем + пространстве имен.

    + +

    В следующем примере

    +
    +      set traceLevel 0
    +      namespace eval Debug {
    +      	printTrace $traceLevel
    +      }
    +    
    + +

    Tcl ищет переменную traceLevel в пространстве имен + Debug и затем в глобальном пространстве имен. Аналогично + ищется и процедура printTrace. Чтобы не оставлять + неясностей, рассмотрим еще один пример:

    + +
    +      set traceLevel 0
    +      namespace eval Foo {
    +      	variable traceLevel 3
    +        namespace eval Debug {
    +            printTrace $traceLevel
    +        }
    +      }
    +    
    +

    Здесь Tcl ищет переменную traceLevel в пространстве имен + Foo::Debug. Поскольку там ее нет, он продолжает поиск в + глобальном пространстве имен. Переменная Foo::traceLevel + в процессе поиска полностью игнорируется.

    + +

    Чтобы разобраться в сложных ситуациях, можно использовать + команду namespace which. Например, следующая команда:

    +
    +      namespace eval Foo::Debug {namespace which -variable traceLevel}
    +    
    +

    вернет ::traceLevel. С другой стороны, команда:

    + +
    +      namespace eval Foo {namespace which -variable traceLevel}
    +    
    +

    вернет ::Foo::traceLevel.

    + +

    Как уже упоминалось, относительные имена пространств имен + ищутся иначе, чем имена команд и переменных. Они ищутся только в + текущем пространстве имен. Это значит, что, например, команда + namespace eval всегда создает потомка текущего + пространства имен, если только имя нового пространства не + начинается с ::.

    + +

    Tcl не ограничивает доступ к командам, переменным или + пространствам имен. Если вы указали имя, которое в соответствие + с перечисленными выше правилами ссылается на нужный вам элемент, + вы можете использовать этот элемент.

    + +

    Переменные, определенные в данном пространстве имен, можно + использовать в процедурах в этом же пространстве имен с помощью + команды variable. Похожая на + команду global, эта команда + создает связь между локальной переменной в процедуре и + одноименной переменной в пространстве имен. Если необходимо, эта + команда также создает и инициализирует эту переменную (команда + global только создает связь + с переменной в глобальном пространстве имен). Команду variable можно не + использовать, если вы всегда используете полное имя + переменной.

    + +

    ИМПОРТ КОМАНД

    + +

    Пространств имен часто используются для создания + библиотек. Некоторые библиотечные команды могут использоваться + так часто, что необходимость использования полных имен станет + раздражать. Например, если все команды в такой библиотеке, как + BLT, содержатся в пространстве имен Blt. Тогда вы смогли + бы использовать их только следующим образом:

    + +
    +      Blt::graph .g -background red
    +      Blt::table .g 0,0
    +    
    + +

    Если Вы используете команды graph и table + регулярно, предпочтительнее использовать их без префикса + Blt::. Для этого достаточно импортировать эти команды в + текущее пространство имен, например, следующим образом:

    +
    +      namespace import Blt::*
    +    
    +

    В результате выполнения этой команды все команды из + пространства имен Blt будут экспортированы в текущее + пространство имен, и вы сможете использовать их без + соответствующего префикса:

    +
    +      graph .g -background red
    +      table .g 0,0
    +    
    + +

    Команда namespace import импортирует только те команды, + экспорт которых разрешен с помощью команды namespace + export.

    + +

    Как правило, не стоит импортировать все команды из пространства + имен, так как при этом может быть сложно отследить все команды, + которые вы получите. Лучше указать явно, какие именно команды + вам нужны. Например, команда

    +
    +      namespace import Blt::graph Blt::table
    +    
    +

    импортирует только команды graph и table.

    + +

    Если вы попытаетесь импортировать команду, которая уже + существует в текущем пространстве имен, то вы получите + ошибку. Это предупредит, например, попытки скопировать одну и ту + же команду из двух разных библиотек. Однако время от времени + (например, при отладке) у вас может появиться желание преодолеть + данное ограничение. Для этого нужно указать в команде опцию + -force, и тогда существующая команда будет заменена на + импортируемую команду без сообщения об ошибке:

    +
    +      namespace import -force Blt::graph Blt::table
    +    
    +

    Если вам почему-либо надо прекратить использование библиотечной + команды, это можно сделать следующим образом:

    +
    +      namespace forget Blt::*
    +    
    +

    Эта команда ищет в текущем пространстве имен все команды, + импортированные из Blt, и удаляет их. Если таких + команд не оказалось, команда ничего не делает. После + исполнения команды namespace forget Blt::* команды из + пространства имен Blt можно использовать только с + префиксом Blt::.

    + +

    Если вы удаляете команду из того пространства имен, где она + была создана, например:

    + +
    +      rename Blt::graph ""
    +    
    +

    то она будет удалена из всех пространств имен, в которые она + была импортирована.

    + +

    ЭКСПОРТ КОМАНД

    + +

    Вы можете разрешить экспорт команд из определенного + пространства имен:

    + +
    +      namespace eval Counter {
    +      	namespace export Bump Reset
    +        variable num 0
    +        variable max 100
    +        proc Bump {{by 1}} {
    +      		variable num
    +        	incr num $by
    +      		check
    +      		return $num
    +      	}
    +        proc Reset {} {
    +      		variable num
    +      		set num 0
    +        }
    +      	proc check {} {
    +      		variable num
    +      		variable max
    +      		if {$num > $max} {
    +      			error "too high!"
    +      		}
    +      	}
    +      }
    +    
    +

    После этого процедуры Bump и Reset можно + импортировать, например, с помощью команды:

    +
    +      namespace import Counter::*
    +    
    + +

    Но экспорт процедуры check не разрешен, и она не будет + импортирована этой командой.

    + +

    Команда namespace import позволяет импортировать + только те команды, которые разрешено экспортировать из их + пространства имен с помощью команды namespace export. + Если в команде namespace import указана команда, + которую нельзя экспортировать, она не будет импортирована в + соответствующее пространство имен.

    + + + diff --git a/hlp/ru/tcl/open.html b/hlp/ru/tcl/open.html new file mode 100644 index 0000000..c20d10d --- /dev/null +++ b/hlp/ru/tcl/open.html @@ -0,0 +1,266 @@ + + + + open + + + +

    open

    + +

    Открывает канал для связи с файлом или программой.

    + +

    СИНТАКСИС

    + +
    +      open fileName 
    +      open fileName access
    +      open fileName access permissions
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда открывает файл, последовательный порт или командный + конвейер и возвращает идентификатор канала, который может + использоваться в дальнейшем в таких командах, как read, puts и close. Если первый символ + атрибута fileName не равен |, то команда отрывает + файл fileName, соответственно значение аргумента fileName + должно соответствовать обычным соглашениям, описанным в п. filename.

    + +

    Аргумент access, если он используется, указывает + разрешенные режимы доступа к файлу. Аргумент access может + указываться в одной из двух нотаций. В первой он может иметь + следующие значения:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    rОткрывает файл только на чтение. Это значение по умолчанию.
    r+Открывает файл на чтение и запись. Файл должен + существовать.
    wОткрывает файл только на запись. Удаляет содержимое + файла, если он существовал. Если нет, то создает новый + файл.
    w+Открывает файл на чтение и запись. Удаляет содержимое + файла, если он существовал. Если нет, то создает новый + файл.
    aОткрывает файл на чтение. Файл должен + существовать. Новые данные записываются в конец файла.
    a+Открывает файл на чтение и запись. Если файл не + существует, создает новый файл. Новые данные + записываются в конец файла.
    + +

    Во второй нотации аргумент access может содержать набор + из флагов, описанных ниже. Среди флагов обязательно должен быть + один из следующих: RDONLY, WRONLY или + RDWR.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    RDONLYОткрывает файл только на чтение.
    WRONLYОткрывает файл только на запись
    RDWRОткрывает файл на чтение и запись.
    APPENDПереставляет указатель в конец файла перед каждой + записью.
    CREATСоздает файл, если он не существует. Без этого флага + попытка открыть несуществующий флаг приведет к + ошибке.
    EXCLЕсли указан также флаг CREAT, то будет + сгенерирована ошибка, если файл уже существует.
    NOCTTYЕсли файл открыт для терминального устройства, этот флаг + не позволяет ему стать управляющим терминалом + процесса.
    NONBLOCKПозволяет в неблокирующем режиме открыть файл и, + возможно, выполнять в этом режиме последующие операции + ввода/вывода. Последствия использования этого флага + зависят от платформы и устройства. Предпочтительнее + вместо него использовать команду fconfigure. Конкретные + особенности использования флага описаны в руководстве по + вашей операционной системе, системный вызов open, флаг + O_NONBLOCK. +
    TRUNCЕсли файл существует, то его содержимое удаляется.
    + +

    Если файл создается при выполнении команды open, то + аргумент permissions (целое число) используется для + установки прав доступа к вновь созданному файлу. Значение по + умолчанию 0666.

    + +

    КОМАНДНЫЙ КОНВЕЙЕР

    + +

    Если первый символ в fileName ``|'', то + считается, что остальные символы описывают командный конвейер, + который запускается так же, как командой exec. В этом случае идентификатор + открытого канала может использоваться для ввода информации в + стандартный ввод запущенного конвейера или для чтения его + стандартного вывода в зависимости от значения аргумента + access. Если канал открыть только на запись, то + стандартный вывод конвейера направляется на текущий стандартный + вывод (если он не перенаправлен в конвейере). Если канал открыт + только на чтение, стандартный ввод для конвейера берется из + текущего стандартного ввода (если он не перенаправлен в + конвейере).

    + +

    ПОСЛЕДОВАТЕЛЬНЫЙ ПОРТ

    + +

    Если аргумент fileName указывает на параллельный порт, + то соответствующий порт открывается и инициализируется (реальные + действия в зависимости от платформы). Допустимые значения + fileName для различных платформ см. + Особенности реализации на различных платформах.

    + +

    КОНФИГУРИРОВАНИЕ

    + +

    Команда fconfigure может + быть использована для определения и изменения текущей + конфигурации канала. Для последовательного порта можно + использовать следующие опции.

    + +

    -mode + baud,parity,data,stop

    + +

    Эта опция включает 4 величины, записанные через запятую.

    + +

    baud - число, скорость передачи данных в Бодах (бит + в секунду);

    + +

    parity - четность, может принимать одно из значений + n (none), o (odd), e (even), m + (mark), s (space);

    + +

    data - число бит данных (целое от 5 до 8);

    + +

    stop - число стоп битов (целое 1 или 2).

    + +

    + ОСОБЕННОСТИ РЕАЛИЗАЦИИ НА РАЗЛИЧНЫХ ПЛАТФОРМАХ

    + +
    +
    Windows (все версии)
    + +
    Аргумент fileName для сериальных портов должен иметь + форму comX, где X - число (обычно, от 1 до + 4). Попытка открыть несуществующий порт приводит к + ошибке.
    + +
    Windows NT
    + +
    Проблемы могут возникать при интерактивном выполнении Tcl, + поскольку в этом случае консоль используется и для Tcl, и для + порожденного подпроцесса.
    + +
    Windows 95
    + +

    Сложности при работе с 16-битовыми DOS-приложениями.

    + +

    Также проблемы могут возникать при интерактивном выполнении + Tcl, поскольку в этом случае консоль используется и для Tcl, + и для порожденного подпроцесса.

    +
    + +
    Windows 3.X
    + +
    Те же проблемы, что и при выполнении команды exec.
    + +
    Macintosh
    + +

    Открытие последовательного порта не поддерживается.

    +

    Открытие командного конвейера также не поддерживается.

    +
    + +
    Unix
    + +

    Обычно для открытия последовательного порта используется + значение fileName /dev/ttyX, где X + равно a или b, но можно также использовать + любой псевдофайл, назначенный на соответствующий порт.

    + +

    Проблемы могут возникать при интерактивном выполнении Tcl, + поскольку в этом случае консоль используется и для Tcl, и + для порожденного подпроцесса.

    +
    +
    + + + + diff --git a/hlp/ru/tcl/package.html b/hlp/ru/tcl/package.html new file mode 100644 index 0000000..045ad5e --- /dev/null +++ b/hlp/ru/tcl/package.html @@ -0,0 +1,167 @@ + + + + package + + + +

    package

    + +

    Команда загрузки пакетов библиотек и контроля версий.

    + +

    СИНТАКСИС

    + +
    +      package forget package
    +
    +      package ifneeded package version ?script?
    +
    +      package names
    +
    +      package provide package ?version?
    +
    +      package require ?-exact? package ?version?
    +
    +      package unknown ?command?
    +
    +      package vcompare version1 version2
    +
    +      package versions package
    +    
    +      package vsatisfies version1 version2
    +    
    + + +

    ОПИСАНИЕ

    + +

    Команда поддерживает простую базу данных со сведениями о том, + какие пакеты библиотечных функций доступны для использования в + данном интерпретаторе, и как их загрузить в интерпретатор. Она + поддерживает многоверсионность пакетов и гарантирует загрузку в + приложение необходимой версии пакета. При этом она обеспечивает + контроль непротиворечивости версий. Обычно в Tcl-скриптах + достаточно использовать команды package require и + package provide. Остальные команды предназначены в + первую очередь для системных скриптов, которые поддерживают базу + данных пакетов.

    + +

    Поведение команды package определяется ее первым + аргументом. Ниже описаны возможные формы команды.

    + +
    +
    package forget + package
    + +
    Удаляет информацию о пакете из интерпретатора, включая как + информацию, возвращаемую командой package + ifneeded, так и информацию, возвращаемую командой + package provide.
    + +
    package + ifneeded package version ?script?
    + +
    Команда используется в системных скриптах. Если указана + конкретная версия и скрипт, заносит в базу данных информацию о + том, что соответствующая версия пакета доступна и может быть + загружена в интерпретатор с помощью скрипта + script. Если в базе данных уже хранится информация о + скрипте, она обновляется. Если скрипт не указан, возвращается + текущий скрипт.
    + +
    package names
    + +
    Возвращает список всех пакетов в интерпретаторе, для которых + известна доступная версия (заданная с помощью команды + package provide) или скрипт загрузки (заданный + командой package ifneeded).
    + +
    package provide + package ?version?
    + +
    Команда используется для того, чтобы указать, что версия + version пакета package загружена в + интерпретатор. Если ранее была загружена другая версия, + возвращает ошибку. Если версия не указана, возвращает + загруженную версию.
    + +
    package require + ?-exact? package ?version?
    + +

    Команда используется, если для выполнения дальнейшего + кода необходим библиотечный пакет package версии + version. Команда возвращает номер загруженной версии или + ошибку. Если присутствуют оба аргумента -exact и + version, то команда загружает именно указанную версию + (или выдает ошибку, если эта версия недоступна). Если + присутствует номер версии, а -exact опущено, то команда + загружает указанную версию или более позднюю, но с тем же + старшим номером версии (2.7, но не 3.1, когда указана версия + 2.5).

    + +

    Если база данных не содержит необходимой версии, а в + интерпретаторе определена команда для packageunknown + (см. ниже), то она исполняется, после чего повторно + проверяется доступность необходимой версии. Если версия + по-прежнему недоступна, команда возвращает ошибку.

    +
    + +
    package unknown + ?command?
    + +

    Команда последней надежды при поиске необходимой + версии пакета. Если аргумент command указан, то он + дополняется именем пакета и версии и полученный скрипт + выполняется. Если версия не указана, подставляется пустая + строка.

    + +

    Если аргумент command не указан, возвращает текущий + скрипт, заданный для команды package + unknown.

    +
    + +
    package + vcompare version1 version2
    + +
    Команда сравнения версий. Возвращает -1, если + version1 более ранняя версия, чем version2, + 1 - в противном случае, и 0, если они + равны.
    + +
    package + versions package
    + +
    Возвращает список всех доступных версий пакета (информация о + которых занесена в базу данных с помощью команды + package ifneeded).
    + +
    package + vsatisfies version1 version2
    + +
    возвращает 1, если у version1 и + version2 совпадают старшие номера, а младший номер у + version1 не меньше, чем у version2, и 0 - в + противном случае.
    +
    + +

    ИНДЕКСЫ ПАКЕТОВ

    + +

    Рекомендованный способ работы с пакетами в Tcl состоит в том, + чтобы включать в скрипты команды package require и package + provide и использовать процедуру pkg_mkIndex (см. + соответствующие пункты) для создания индексных файлов для + пакетов. Это обеспечивает автоматическую загрузку необходимых + пакетов.

    + +

    См.также close(n), filename(n), gets(n), read(n), puts(n), exec(n).

    + + + + diff --git a/hlp/ru/tcl/pid.html b/hlp/ru/tcl/pid.html new file mode 100644 index 0000000..9966253 --- /dev/null +++ b/hlp/ru/tcl/pid.html @@ -0,0 +1,31 @@ + + + + pid + + + +

    pid

    + +

    Команда сообщает идентификаторы процессов.

    + +

    СИНТАКСИС

    + +
    +      pid fileId
    +    
    + +

    ОПИСАНИЕ

    + +

    Если задан аргумент fileId, то он должен указывать на + конвейер процессов (process pipeline), открытый командой open. В этом случае команда представит + список идентификаторов всех процессов в конвейере, по порядку. + Если fileId указывает на открытый файл, не являющийся + конвейером процессов, то список будет пустой. Если аргумент + fileId не задан, то будет возвращен идентификатор текущего + процесса. Все идентификаторы представлены десятичными + строками.

    + + + diff --git a/hlp/ru/tcl/pkg_mkIndex.html b/hlp/ru/tcl/pkg_mkIndex.html new file mode 100644 index 0000000..7625146 --- /dev/null +++ b/hlp/ru/tcl/pkg_mkIndex.html @@ -0,0 +1,148 @@ + + + + pkg_mkIndex + + + +

    pkg_mkIndex

    + +

    Создает индексный файл для автоматической загрузки пакета.

    + +

    СИНТАКСИС

    + +
    +      pkg_mkIndex dir pattern ?pattern pattern...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура pkg_mkIndex представляет собой утилиту для + работы с Tcl-библиотеками. Она обеспечивает создание индексных + файлов, необходимых для автоматической загрузки пакетов, когда в + приложении встречается команда package require. Для создания + автоматически загружаемых пакетов необходимо выполнить следующие + действия:

    +
      +
    • Создать один или несколько пакетов. Каждый пакет может + состоять из одного или больше файлов с Tcl-скриптами или из + бинарных файлов. Бинарные файлы должны быть пригодны для их + загрузки с помощью команды load с единственным аргументом + - именем файла. Например, если в пакет входит файл + test.so, он должен загружаться командой load + test.so. Каждый файл Tcl-скриптов должен содержать команду + package + provide с именем пакета и версией. Каждый бинарный + файл должен содержать вызов процедуры Tcl_PkgProvide. +
    • + +
    • Создать индексные файлы с помощью команды + pkg_mkIndex. Аргумент dir указывает имя + каталога, в котором лежат файлы пакета, а шаблоны + pattern, которые могут содержать специальные символы, + как в команде glob, указывают + на файлы в этом каталоге. Команда pkg_mkIndex создаст в + каталоге dir файл pkgIndex.tcl, содержащий + информацию обо всех файлах пакета, заданных с помощью + аргументов pattern. Для этого загружаются все файлы + пакета, и определяется, какие новые пакеты и какие новые + процедуры появились (поэтому в каждом файле пакета и должна + быть команда package + provide или вызов Tcl_PkgProvide).
    • + +
    • Установить пакет как подкаталог одного из каталогов, + перечисленных в переменной tcl_pkgPath. Если в списке + $tcl_pkgPath больше одного каталога, то бинарные файлы + с разделяемыми библиотеками обычно устанавливаются в первом + каталоге, а библиотеки Tcl-скриптов - во втором. В этих + каталогах должны также находиться файлы pkgIndex.tcl. + Пока пакеты будут размещаться в подкаталогах каталогов, + перечисленных в переменной tcl_pkgPath, этого будет + достаточно для их автоматической загрузки при выполнении + команды package + require.
    • + +
    • Если вы установили пакеты в каких-либо других каталогах, то + необходимо, чтобы эти каталоги содержались в переменной + auto_path или были бы непосредственными подкаталогами + одного из содержащихся там каталогов. Переменная + auto_path содержит список каталогов, которые + просматриваются как автозагрузчиком, так и загрузчиком + пакетов. По умолчанию он включает $tcl_pkgPath. + Загрузчик пакетов также просматривает и подкаталоги каталогов, + включенных в auto_path. Пользователь может в явном виде + включить в приложении необходимые каталоги в + auto_path. А можно включить эти каталоги в переменную + окружения TCLLIBPATH. Если она существует, то + используется для инициализации переменной auto_path при + запуске приложения.
    • + +
    • Если перечисленные выше шаги выполнены, то для + использования необходимого пакета достаточно выполнить в + приложении команду + package require. Если, например, версии 2.1, 2.3 и + 3.1 пакета Test проиндексированы и хранятся в + соответствующих каталогах, то команда

      +
      +	  package require Test
      +	
      +

      загрузит версию 3.1. А команда

      +
      +	  package require -exact Test 2.1
      +	
      +

      загрузит версию 2.1. В различных каталогах могут храниться + много версий одного и того же пакета, но в данный + интерпретатор может быть загружена только одна из них - та, + которая будет затребована первой. Однако, в различных + интерпретаторах одного приложения могут быть загружены + различные версии одного и того же пакета.

      +
    • +
    + +

    ЗАГРУЗЧИК ПАКЕТОВ И АВТОЗАГРУЗЧИК

    + +

    Автозагрузчик и загрузчик пакетов во многом имеют сходные + возможности, поскольку и тот, и другой предназначены для + загрузки файлов по требованию. Однако загрузчик файлов + представляет собой механизм более высокого уровня, который + использует автозагрузчик на последнем шаге процесса загрузки. + Как правило, предпочтительнее индексировать пакеты с помощью + команды pkg_mkIndex, + чем с помощью команды auto_mkindex, поскольку это + обеспечивает подключение механизма версий. Вы можете иметь + несколько версий одного и того же пакета и, более того, + использовать в различных приложениях различные версии. Напротив, + auto_mkindex позволяет работать с единственной версией + пакета. Скорее всего, не стоит создавать индексы для пакета с + помощью и pkg_mkIndex, + и auto_mkindex, поскольку в этом случае трудно + контролировать, какой из механизмов загрузки пакета сработает + первым, и, соответственно, какая версия пакета будет загружена. +

    + +

    КАК ЖЕ ЭТО РАБОТАЕТ?

    + +

    При первом вызове команды package require + исполняется скрипт package + unknown. При инициализации Tcl-скрипт package unknown + задается таким образом, что он выполняет все файлы + pkgIndex.tcl в каталогах auto_path. Эти файлы + содержат команды package + ifneeded для каждой доступной версии каждого + доступного пакета. Эти команды в свою очередь вызывают команды + package provide, + которые объявляют данные версии доступными. Кроме того, они + формируют необходимую исходную информацию для + автозагрузчика. Данный файл данной версии данного пакета реально + загружается только тогда, когда вызывается первая из + содержащихся в нем команд. Таким образом, после выполнения + команды package + require вы не увидите команд пакета в интерпретаторе, + но, тем не менее, вы сможете их вызвать и при этом они + загрузятся автоматически.

    + + diff --git a/hlp/ru/tcl/proc.html b/hlp/ru/tcl/proc.html new file mode 100644 index 0000000..88122f0 --- /dev/null +++ b/hlp/ru/tcl/proc.html @@ -0,0 +1,70 @@ + + + + proc + + + +

    proc

    + +

    Создает Tcl-процедуры.

    + +

    СИНТАКСИС

    + +
    +      proc name args body
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда proc создает новую Tcl-процедуру с именем + name, если такой процедуры ранее не было, и замещает + ранее существовавшую процедуру или команду с таким именем, если + она была. При вызове новой процедуры скрипт body + передается на выполнение Tcl-интерпретатору. Обычно имя + процедуры указывается без указания имени пространства имен. При + этом новая процедура создается в текущем пространстве + имен. Однако, если пространство имен указано явно, она создается + в указанном пространстве. Аргумент args определяет + формальные аргументы процедуры и представляет собой список + (возможно, пустой), каждый элемент которого представляет + описание одного формального параметра. Каждое такое описание + само является списком из одного или двух элементов. Первый + элемент списка определяет имя формального параметра. Второй + элемент списка, если он указан, определяет значение по умолчанию + для данного параметра.

    + +

    При выполнении процедуры для каждого формального параметра + создается локальная переменная. Ей присваивается значение + соответствующего аргумента, указанного при вызове процедуры, или + значение по умолчанию. Аргумент, для которого при определении + процедуры указано значение по умолчанию, может не присутствовать + в вызове процедуры. Однако общее количество указанных параметров + должно быть достаточным для аргументов, не имеющих значения по + умолчанию, но не больше общего числа формальных параметров. Если + это условие выполнено, все аргументы процедуры собираются в один + список (как при исполнении команды list). Эта комбинированная величина + присваивается локальной переменной args.

    + +

    При исполнении тела процедуры имена переменных обычно считаются + именами локальных переменных, которые создаются автоматически по + мере необходимости и удаляются после завершения процедуры. По + одной локальной переменной создается также для каждого аргумента + процедуры. Для использования глобальных переменных необходимо + использовать команду global или + upvar. Для использования + переменных из пространства имен необходимо использовать команду + variable или + upvar.

    + +

    Команда proc возвращает пустую строку. При вызове + процедуры возвращается величина, заданная в команде return. Если в процедуре не выполнялась + явная команда return, она возвращает результат выполнения + последней команды, выполнявшейся в теле процедуры. Если при + выполнении процедуры произошла ошибка, то процедура в целом + возвращает эту ошибку.

    + + + diff --git a/hlp/ru/tcl/puts.html b/hlp/ru/tcl/puts.html new file mode 100644 index 0000000..eeb1f59 --- /dev/null +++ b/hlp/ru/tcl/puts.html @@ -0,0 +1,64 @@ + + + + puts + + + +

    puts

    + +

    Команда записывает данные в канал.

    + +

    СИНТАКСИС

    + +
    +      puts ?-nonewline? ?channelId? string
    +    
    + +

    ОПИСАНИЕ

    + +

    Записывает символы из аргумента string в канал + channelId. Значение channelId должно быть + идентификатором канала, который вернула предыдущая команда open или socket. Соответствующий канал + должен быть открыт на запись. Если аргумент channelId не + указан, значение по умолчанию соответствует стандартному + выводу. Команда puts обычно выдает после string + символ новой строки, однако, если указана опция + -nonewline, этого не происходит.

    + +

    Символы новой строки при выводе заменяются на + последовательность, используемую на данной платформе (например, + cr lf на Windows-платформах) в соответствии со + значением опции канала -translation. Опция может быть + изменена с помощью команды fconfigure.

    + +

    Tcl осуществляет вывод через буфер. Поэтому символы, выданные + командой puts, могут и не появиться сразу в выходном + устройстве или в файле. Обычно вывод откладывается до заполнения + буфера или закрытия канала. Чтобы обеспечить немедленную выдачу + данных, можно использовать команду flush.

    + +

    Когда буфер заполнится, команда puts обычно блокирует + процесс до тех пор, пока все данные не будут переданы + операционной системе для дальнейшего вывода. Если канал + channelId открыт в неблокирующем режиме, процесс не + блокируется, даже если операционная система еще не приняла + данные. Tcl в этом случае продолжает складывать данные в буфер и + в фоновом режиме передает их в соответствующий файл или + устройство с той скоростью, с которой они могут принять + данные. Чтобы работа в неблокирующем режиме была возможна, + необходимо, чтобы был запущен обработчик событий.

    + +

    При работе в неблокирующем режиме возможен рост буфера, под + который будет выделен неоправданно большой объем памяти. Чтобы + избежать этого, неблокирующие операции ввода/вывода лучше делать + управляемыми по событиям. При этом новая порция данных не будет + передаваться в буфер, пока канал не будет готов к ее приему.

    + + + + diff --git a/hlp/ru/tcl/pwd.html b/hlp/ru/tcl/pwd.html new file mode 100644 index 0000000..f497495 --- /dev/null +++ b/hlp/ru/tcl/pwd.html @@ -0,0 +1,24 @@ + + + + pwd + + + +

    pwd

    + +

    Команда pwd возвращает путь к текущему каталогу.

    + +

    СИНТАКСИС

    + +
    +      pwd
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда pwd возвращает полный путь к текущему + каталогу.

    + + + diff --git a/hlp/ru/tcl/read.html b/hlp/ru/tcl/read.html new file mode 100644 index 0000000..90d4fda --- /dev/null +++ b/hlp/ru/tcl/read.html @@ -0,0 +1,43 @@ + + + + read + + + +

    read

    + +

    Команда выполняет чтение данных из канала.

    + +

    СИНТАКСИС

    + +
    +      read -nonewline channelId
    +      read channelIdnumBytes
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда read зачитывает из канала channelId либо + весь файл до символа конца файла (при первой форме записи), либо + заданное параметром numBytes количество байтов (вторая + форма). Если во втором случае в файле оказалось меньше байтов, + чем задано numBytes, тогда возвращаются все байты, что + остались.

    + +

    Если указана опция -nonewline, при выполнении команды + отбрасывается символ новой строки в конце файла.

    + +

    Если канал открыт в неблокирующем режиме, команда может + прочитать не указанное количество байтов, а только все + доступные. После чего она не заблокирует процесс, дожидаясь + дополнительных данных, а завершится. Если команда завершилась до + конца файла, то опция -nonewline игнорируется.

    + +

    Команда read изменяет во входных данных + последовательность, задающую конец строки, в соответствии с + опцией канала -translation option.Опция может быть + изменена с помощью команды fconfigure.

    + + diff --git a/hlp/ru/tcl/regexp.html b/hlp/ru/tcl/regexp.html new file mode 100644 index 0000000..d8be971 --- /dev/null +++ b/hlp/ru/tcl/regexp.html @@ -0,0 +1,191 @@ + + + + regexp + + + +

    regexp

    + +

    Сравнивает строку и регулярное выражение.

    + +

    СИНТАКСИС

    + +
    +      regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда определяет, соответствует ли регулярное + выражениеexp какой-либо части строки string или + всей строке, и возвращает 1, если соответствует, и + 0 - в противном случае.

    + +

    Если в команде указаны дополнительные аргументы после + string, они считаются именами переменных, в которые + возвращается информация о том, какие именно части строки + соответствуют регулярным выражениям. Переменной присваивается + значение, состоящее из части строки, соответствующей всему + регулярному выражению. Самой левой в списке переменной + subMatchVar присваивается значение, состоящее из части + строки, которая соответствует самому левому заключенному в + скобки выражению в составе exp. Следующей переменной + subMatchVar присваивается значение, соответствующее следующему + заключенному в скобки выражению, и так далее.

    + +

    Если первые аргументы команды начинаются с -, они + считаются опциями команды. Ниже перечислены возможные опции.

    + +
    +
    -nocase
    + +
    При сравнении не различает буквы в верхнем и нижнем + регистре.
    + +
    -indices
    + +
    В переменных subMatchVars сохраняются не части + строки, а списки из двух десятичных чисел - индексов начала и + конца соответствующей области строки.
    + +
    --
    + +
    Означает конец опций. следующий аргумент будет + рассматриваться как exp, даже если он начинается с + -.
    +
    + +

    Если в команде указано больше переменных subMatchVar, + чем выражений в скобках в exp, или если для одного из + выражений не удалось найти соответствующую ему часть строки, то + соответствующей переменной будет присвоено значение -1 + или пустая строка, в зависимости от того, была ли задана опция + -indices.

    + +

    РЕГУЛЯРНЫЕ ВЫРАЖЕНИЯ

    + +

    Регулярное выражение состоит из ни одной или более + ветвей (branch), разделенных символом '|'. Строка + соответствует выражению, если она соответствует одной из его + ветвей.

    + +

    Ветвь состоит из одной или более частей (piece), + соединенных друг с другом. строка соответствует ветви, если ее + можно разбить на подстроки таким образом, что начальная + подстрока соответствует первой части ветви, следующая подстрока + - следующей части ветви и так далее.

    + +

    Часть состоит из атома со следующим за ним необязательным + символом '*', '+' или '?'. Атом с последующим + символом * соответствует любой последовательности из нуля + или более подстрок, каждая из которых соответствует атому. Атом + с символом '+' после него соответствует любой + последовательности из одной или более подстрок, каждая из + которых соответствует атому. Атом с символом '?' после + него соответствует подстроке, которая соответствует атому, или + пустой строке.

    + +

    Атом может быть регулярным выражением в скобках (в этом случае + он соответствует любой строке, которая соответствует этому + регулярному выражению), интервалом (см. ниже), символом + '.' (соответствует ровно одному произвольному символу), + '^' (соответствует нулевой строке в начале + string), '$' (соответствует нулевой строке в конце + string), '\' с последующим одним символом + (соответствует этому символу), или одним символом без + какого-либо иного смысла (соответствует этому символу).

    + +

    Интервал есть последовательность символов, заключенная в + квадратные скобки. Он обычно соответствует любому символу из + этого интервала. Если последовательность начинается с символа + '^', то она соответствует любому символу, кроме символов, + стоящих далее в последовательности. Если два символа в + последовательности разделены символом '-', то это краткая + форма для обозначения всех ASCII символов между этими двумя + (например, '[0-9]' соответствует любой десятичной цифре). Для + того, чтобы включить в последовательность символ ']', + следует поставить его на место первого в последовательности + (следом за возможным символом '^'). Для включения в + последовательность символа '-' следует сделать его первым + или последним символом.

    + +

    ВЫБОР ИЗ АЛЬТЕРНАТИВНЫХ СОСТОЯНИЙ

    + +

    Вообще говоря, регулярное выражение может соответствовать + строке несколькими различными способами. Например, рассмотрим + выражение

    + +
    +      regexp (a*)b* aabaaabb x y
    +    
    + +

    В соответствии с описанными выше правилами переменные x + и y могут принять значение aabb и aa, + aaab и aaa, ab и a или одну из еще + нескольких возможных комбинаций. Чтобы избежать этой + потенциальной неопределенности команда regexp выбирает + между возможными вариантами по правилу "первый и самый + длинный". Другими словами, строка и регулярное выражение + просматриваются слева направо, при этом выбирается часть строки + максимально возможной длины. Говоря точнее, при выборе + используются следующие правила в порядке убывания + приоритета.

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    [1]

    Если регулярное выражение соответствует двум разным + частям строки, выбирается та часть, которая раньше + начинается.

    + +

    Если обе начинаются в одном и том же месте, то это + неопределенный (тяжелый) случай. Его можно объяснить + следующим образом.

    +
    [2]Если регулярное выражение содержит символы | (то + есть состоит из нескольких ветвей), то будет выбрана самая + левая ветвь, которой что-либо соответствует.
    [3]Для выражений, содержащих '*', '+' и + '?', выбираются самые длинные фрагменты строки, + соответствующие им.
    [4]Компоненты выражений рассматриваются слева направо.
    + +

    В приведенном выше примере (a*)b* соответствует + aab, так как для (a*) выбирается первый + соответствующий ему фрагмент, то есть начальные aa, а + затем для b* выбирается следующий символ + b. Рассмотрим еще один пример:

    + +
    +      regexp (ab|a)(b*)c abc x y z
    +    
    + +

    После выполнения команды переменная x будет содержать + значение abc, переменная y - ab и + переменная z будет содержать пустую строку. Правило [4] определяет, что поиск начнется с выражения + (ab|a), а правило [2], что поиск начнется с подвыражения + ab. Поэтому символ b в строке будет использован, и + выражение (b*) будет соответствовать пустой строке.

    + + + diff --git a/hlp/ru/tcl/regsub.html b/hlp/ru/tcl/regsub.html new file mode 100644 index 0000000..627db5a --- /dev/null +++ b/hlp/ru/tcl/regsub.html @@ -0,0 +1,68 @@ + + + + regsub + + + +

    regsub

    + +

    Команда выполняет подстановки, используя регулярные выражения.

    + +

    СИНТАКСИС

    + +
    +      regsub ?switches? exp string subSpec varName
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда сравнивает регулярное выражение exp и строку + string и копирует string в переменную, заданную + именем varName. Если совпадение найдено, то при + копировании часть строки string, соответствующая + exp, замещается на subSpec. Если subSpec + содержит один из символов & or \0, то он + заменяется на часть строки string, которая соответствует + шаблону exp. Если subSpec содержит \n, где + n - целое число от 1 до 9, то это выражение заменяется на часть + строки string, которая соответствует n-ому заключенному в + скобки выражению в exp. Чтобы избежать специальной + интерпретации перечисленных символов и символа обратный + слэш, их необходимо экранировать символом обратный + слэш. Чтобы избежать возможных проблем с интерпретацией + символов обратный слэш в exp, проще всего + заключить exp в фигурные скобки.

    + +

    Если начальные аргументы команды начинаются с символа + -, они считаются опциями команды. Ниже приведен + список поддерживаемых опций.

    + +
    +
    -all
    + +
    Ищутся все подобласти string, соответствующие + exp, и для каждой из них производится замена. Символы + & и \n замещаются на очередной фрагмент + string, соответствующий exp. То есть каждый раз + они могут замещаться на различные выражения.
    + +
    -nocase
    + +
    При поиске соответствующих фрагментов строки не различаются + буквы в верхнем и нижнем регистре. Тем не менее, подстановка + производится в исходном регистре.
    + +
    --
    + +
    Означает конец опций. Следующий аргумент будет + рассматриваться как exp, даже если он начинается с + -.
    +
    + +

    Команда возвращает количество найденных (и, соответственно, + замещенных) интервалов. Правила соответствия строк регулярным + выражениям приведены в описании команды regexp.

    + + diff --git a/hlp/ru/tcl/rename.html b/hlp/ru/tcl/rename.html new file mode 100644 index 0000000..04a4bb5 --- /dev/null +++ b/hlp/ru/tcl/rename.html @@ -0,0 +1,31 @@ + + + + rename + + + +

    rename

    + +

    Команда rename переименовывает или удаляет команду.

    + +

    СИНТАКСИС

    + +
    +      rename oldName newName
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда переименовывает команду по имени oldName + в newName. Если newName отсутствует (равно пустой + строке), тогда команда oldName удаляется.

    + +

    Имена oldName и newName могут содержать + квалификаторы областей имен (указатели на имена областей имен). + Если команда переименовывается в другую область имен, то + последующие вызовы этой команды будут происходить в новой + области имен. Команда rename возвращает пустую + строку.

    + + diff --git a/hlp/ru/tcl/return.html b/hlp/ru/tcl/return.html new file mode 100644 index 0000000..ca6ddcc --- /dev/null +++ b/hlp/ru/tcl/return.html @@ -0,0 +1,97 @@ + + + + return + + + +

    return

    + +

    Команда осуществляет возврат из процедуры.

    + +

    СИНТАКСИС

    + +
    +      return ?-code code? ?-errorinfo info? ?-errorcode code? ?string?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда немедленно осуществляет возврат из текущей процедуры + (или команды верхнего уровня, или команды source) со значением, заданным + string. Если аргумент string не задан, возвращает + пустую строку.

    + +

    Обычно опция -code не используется, и процедура + завершается успешно (с кодом завершения TCL_OK). Однако, ее + можно использовать для генерации других кодов возврата. Ниже + перечислены возможные коды.

    + +
    +
    ok
    + +
    Успешное завершение. То же самое, что отсутствие кода.
    + +
    error
    + +
    Возвращает ошибку. То же самое, что использовать команду + error для прекращения + выполнения процедуры за исключением обработки переменных errorInfo и errorCode + (см. ниже).
    + +
    return
    + +
    Текущая процедура вернет код TCL_RETURN, который вызовет + немедленный возврат также и из вызывающей процедуры.
    + +
    break
    + +
    Текущая процедура вернет код TCL_BREAK, который вызовет + немедленное прекращение выполнения самого внутреннего из + вложенных циклов, из которого была вызвана процедура.
    + +
    continue
    + +
    Текущая процедура вернет код TCL_CONTINUE, который вызовет + немедленное прекращение выполнения текущей итерации самого + внутреннего из вложенных циклов, из которого была вызвана + процедура.
    + +
    value
    + +
    Значение value должно быть целым числом. Оно будет + возвращено как код выполнения процедуры.
    +
    + +

    Опция -code используется относительно редко. Она + предусмотрена для того, чтобы процедуры, реализующие новые + управляющие команды, могли вернуть вызывающим их процедурам + исключительные условия.

    + +

    Опции -errorinfo и -errorcode могут + использоваться совместно с code error, чтобы вернуть + дополнительную информацию о сгенерированной ошибке. В остальных + случаях они игнорируются.

    + +

    Опция -errorinfo используется для того, чтобы задать + исходное значение переменной errorInfo. Если она не будет + задана, то в переменную errorInfo будет включена + информация о вызове процедуры, вернувшей ошибку, и о более + высоких уровнях стека, но не информация непосредственно об + ошибке внутри процедуры. Чаще всего для формирования переменной + info используется сообщение команды catch, обнаружившей ошибку в + процедуре.

    + +

    Если опция -errorcode указана, она позволяет задать + значение переменной + errorCode. В противном случае ей будет присвоено + значение NONE.

    + + + diff --git a/hlp/ru/tcl/scan.html b/hlp/ru/tcl/scan.html new file mode 100644 index 0000000..675913d --- /dev/null +++ b/hlp/ru/tcl/scan.html @@ -0,0 +1,148 @@ + + + + scan + + +

    scan

    + +

    Производит разбор строки в стиле процедуры sscanf.

    + +

    СИНТАКСИС

    + +
    +      scan string format varName ?varName...?
    +    
    + +

    ВВЕДЕНИЕ

    + +

    Данная команда, подобно ANSI C процедуре sscanf, + просматривает строку string, выбирает поля и преобразует + их в соответствии с очередным спецификатором преобразования в + строке format. Выбранные значения преобразуются обратно в + строковый вид и последовательно записываются в переменные + varName.

    + +

    ПРОЦЕСС СКАНИРОВАНИЯ

    + +

    Команда scan просматривает одновременно строки + string и format. Если очередной символ в строке + format пробел или табуляция, то он соответствует любому + числу (включая ноль) пробельных символов (пробел, табуляция, + новая строка) в строке string. Если в строке + format встретился символ %, он означает начало + очередного спецификатора преобразования. Спецификатор + преобразования включает в себя до трех полей после символа + %: первое поле может содержать символ *, + означающий, что преобразуемая величина будет удалена, а не + записана в очередную переменную, второе поле может содержать + число, указывающее максимальную ширину поля, и третье поле + содержит букву, определяющую тип преобразования. Обязательным + является только третье поле.

    + +

    Когда команда scan находит спецификатор + преобразования в строке format, она пропускает + пробельные символы в строке string. Затем она выбирает + следующую группу непробельных символов и преобразует их в + соответствии со спецификатором преобразования и записывает + результат в переменную, соответствующую следующему аргументу + команды. Поддерживаются следующие типы преобразований, + задаваемые соответствующими символами:

    + +
    +
    d
    + +
    Входное поле должно быть десятичным числом. Результат + записывается как десятичная строка.
    + +
    o
    + +
    Входное поле должно быть восьмеричным числом. Результат + преобразуется в десятичную строку.
    + +
    x
    + +
    Входное поле должно быть шестнадцатеричным числом. + Результат преобразуется в десятичную строку.
    + +
    c
    + +
    Читается один символ, его двоичная величина преобразуется и + записывается в переменную как десятичная строка. Начальные + пробельные символы в этом случае не пропускаются. В отличие от + ANSI C процедуры sscanf входное поле всегда состоит + ровно из одного символа, а ширина поля не может быть + задана.
    + +
    s
    + +
    Входное поле состоит из всех непробельных символов до + следующего пробельного. Все символы копируются в + переменную.
    + +
    e или f или g
    + +
    Входное поле должно быть числом с плавающей точкой, + состоящим из знака (не обязательно), строки десятичных цифр, + возможно с десятичной точкой и порядка (не обязательно), + состоящего из буквы e или E, знака порядка (не + обязательно) и строки десятичных цифр.
    + +
    [chars]
    + +
    Входное поле состоит из произвольного числа символов из + chars. Соответствующая строка записывается в + переменную. Если первый символ в скобках ], то он + рассматривается как часть chars, а не как закрывающая + скобка для множества символов.
    + +
    [^chars]
    + +
    Входное поле состоит из произвольного числа символов, не + содержащихся в chars. Соответствующая строка + записывается в переменную. Если первый символ в скобках после + ^ есть ], то он рассматривается как + часть chars, а не как закрывающая скобка для множества + символов.
    +
    + +

    Число символов, которое выбирается для преобразования, это + максимально возможное число символов для соответствующего + преобразования (например, так много десятичных цифр, как это + возможно для %d, или так много восьмеричных цифр, как это + возможно для %o). Поле, выбираемое для очередного + преобразования, закрывается, как только в строке string + встречается пробельный символ или как только поле достигает + указанного максимального размера (в зависимости от того, что + происходит раньше). Если в спецификаторе преобразования для + очередного поля присутствует символ *, то выбранное + значение не присваивает никакой переменной, а очередной аргумент + команды scan по-прежнему считается неиспользованным.

    + +

    ОТЛИЧИЯ ОТ ANSI SSCANF

    + +

    Поведение команды scan не отличается от поведения ANSI + C процедуры sscanf за исключением следующих моментов:

    + + + + + + + + + + + + + +
    [1]Спецификаторы %p и %n не поддерживаются.
    [2]Для спецификатора %c нельзя указывать ширину + поля. Только один символ переводится в десятичную + величину, которая и присваивается соответствующей + переменной.
    [3]Модификаторы l, h и L игнорируются. Целые + числа преобразуются так, как будто никакого модификатора + не было задано, а действительные числа - как при + модификаторе l, то есть с использованием типа + double для внутреннего представления.
    + + diff --git a/hlp/ru/tcl/seek.html b/hlp/ru/tcl/seek.html new file mode 100644 index 0000000..358fb12 --- /dev/null +++ b/hlp/ru/tcl/seek.html @@ -0,0 +1,64 @@ + + + + seek + + + +

    seek

    + +

    Команда изменяет позицию доступа открытого канала.

    + +

    СИНТАКСИС

    + +
    +      seek channelId offset ?origin?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда изменяет текущую позицию доступа канала, заданного + параметром channelId. Значение channelId должно + быть идентификатором канала, который вернула предыдущая команда + open или socket. Аргументы origin и + offset задают новую позицию, в которой будет выполняться + следующая операция чтения или записи. Аргумент offset + должен быть целым числом (возможно, отрицательным), а аргумент + origin может принимать одно из перечисленных ниже + значений.

    +
    +
    start
    + +
    Следующая позиция будет на расстоянии offset байтов + от начала соответствующего файла или устройства.
    + +
    current
    + +
    Следующая позиция будет на расстоянии offset байтов + от текущей позиции. Отрицательное значение offset + передвигает позицию назад.
    + +
    end
    + +
    Следующая позиция будет на расстоянии offset байтов + от конца файла или устройства. Отрицательное значение + offset указывает на позицию до конца файла, а + положительное - на позицию после конца файла.
    +
    + +

    Значение по умолчанию для аргумента origin равно + start.

    + +

    Выполнение команды влечет немедленную передачу всех данных из + выходного буфера в файл или на выходное устройство. Команда не + будет завершена до тех пор, пока все данные не будут переданы, + даже если канал находится в неблокирующем режиме. Кроме того, + будут удалены все не прочитанные данные из входного + буфера. Команда возвращает пустую строку. Если команда + используется для файла или канала, для которого не + поддерживается произвольный доступ, она вернет ошибку.

    + + + + diff --git a/hlp/ru/tcl/send.html b/hlp/ru/tcl/send.html new file mode 100644 index 0000000..63d5272 --- /dev/null +++ b/hlp/ru/tcl/send.html @@ -0,0 +1,94 @@ +send +

    send

    + Выполнить команду в другом + приложении.
      +
  • Синтаксис + +
  • Описание + +
  • Имена + приложений +
  • Блокировка + посылаемых команд +
  • Безопасность +
  • СИНТАКСИС + send ?параметры? прил + кмд ?арг арг ...?ОПИСАНИЕ + Обеспечивает выполнение команды, заданной параметром + кмд (с аргументами, заданными параметрами арг), в приложении + с именем прил. Возвращает результат выполненной команды или ошибку. + Аргумент прил может задавать имя любого из приложений, главное окно + которого расположено на том же дисплее, что и главное окно запрашивающего + приложения; запрошенное приложение не обязано управляться тем же + процессом. Если аргументы отсутствуют, то выполняемая команда полностью + определяется аргументом кмд. Если присутсвует один или несколько + аргументов, то они конкатенируются с кмд в точности так же, как и в + команде eval. + +

    Если первые аргументы команды начинаются + с дефиса "-", то они интерепретируются как параметры. В настоящее время + допустимы следующие параметры: +

    -async +

    + Запрашивает асинхронный вызов. В этом + случае выполнение команды send завершается немедленно, не дожидаясь + завершения выполнения команды, заданной аргументом кмд, в + приложении-адресате; результат выполнения посланной команды или + возникающие при выполнении ошибки игнорируются. Если адресат управляется + тем же процессом, что и посылающее приложение, то параметр -async + игнорируется.-displayof имяПути + + Указывает на то, что главное окно + приложения-адресата должно быть на том же дисплее, что и окно, заданное + аргументом имяПути, а не на дисплее посылающего + приложения.-- + + Единственная задача этого параметра + завершить список параметров. Он используется только если значение + аргумента прил может начинаться с дефиса + "-".
    ИМЕНА + ПРИЛОЖЕНИЙ + Первоначально имя приложения + определяется именем программы или скрипта, его создающего. Имя приложения + можно узнать и изменить с помощью команды appname + Tk.БЛОКИРОВКА ПОСЫЛАЕМЫХ КОМАНД + Если отменить в приложении команду send (например, выполнив команду + rename send {}), то приложение перестанет реагировать на + поступающие запросы send и само не сможет посылать запросы. + Восстановить взаимодействие приложений можно, выполнив команду + appname Tk.БЕЗОПАСНОСТЬ + Команда send является потенциальным источником серьезных нарушений защиты, + так как любое приложение, способное соединиться с Вашим X сервером, может + посылать скрипты в Ваше приложение. С помощью Tcl присланные скрипты могут + читать Ваши файлы и выполнять запись в них и запускать подпроцессы под + Вашим именем. Особенно уязвимо управление доступом вида xhost, так + как всякий пользователь, заведенный на головном компьютере, может + связаться с Вашим сервером; если же это управление доступом отключить, то + связь становится возможной вообще для любого пользователя, где бы он ни + находился. Чтобы обеспечить хотя бы минимальную защиту, Tk проверяет + систему управления доступом на сервере и отвергает все присланные команды, + если либо (а) xhost-система управления доступом отключена (так что лишь + некоторые головные компьютеры могут устанавливать связь); либо (б) список + головных компьютеров, которым такая связь разрешена, пуст. В результате + никакое приложение не сможет связаться с Вашим сервером, если у него не + будет дополнительных прав (например, предоставленных + xauth). diff --git a/hlp/ru/tcl/set.html b/hlp/ru/tcl/set.html new file mode 100644 index 0000000..773fdbb --- /dev/null +++ b/hlp/ru/tcl/set.html @@ -0,0 +1,51 @@ + + + + set + + + +

    set

    + +

    Команда читает и записывает значения переменных.

    + +

    СИНТАКСИС

    + +
    +      set varName value
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда set возвращает значение переменной + varName. Если задан параметр value, то команда + присваивает переменной varName значение value и + возвращает значение value. Если такой переменной не + существовало, тогда она создается вновь.

    + +

    Если varName содержит открывающую скобку и + заканчивается закрывающей скобкой, тогда это элемент массива. + Символы до открывающей скобки являются именем массива, символы + между скобками есть индекс этого элемента в массиве. В + противном случае команда адресуется к скалярной + переменной.

    + +

    Обычно имя переменной указывается без указания пространства + имен, в котором она содержится. При этом соответствующая + переменная для чтения или записи ищется в текущем пространстве + имен. Если же в имени переменной присутствуют имя пространства + имен, то она ищется в указанном пространстве имен.

    + +

    Если команда используется вне тела процедуры, то + varName есть имя глобальной переменной (если текущее + пространство имен есть глобальное пространство) или переменной + текущего пространства имен. В теле процедуры varName + есть имя параметра или локальной переменной процедуры, если + она не объявлена глобальной переменной или переменной + пространства имен с помощью команды + global или + variable соответственно.

    + + + + diff --git a/hlp/ru/tcl/socket.html b/hlp/ru/tcl/socket.html new file mode 100644 index 0000000..923b054 --- /dev/null +++ b/hlp/ru/tcl/socket.html @@ -0,0 +1,136 @@ + + + + socket + + +

    socket

    + +

    Команда открывает сетевое TCP-соединение.

    + +

    СИНТАКСИС

    +
    +      socket ?options? host port
    +      socket -server command ?options? port
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда открывает сетевое соединение и возвращает + идентификатор канала, который может использоваться в + последующих командах read, + puts или + flush. В настоящее время + поддерживается только протокол TCP. Команда может + использоваться для открытия соединения как со стороны + сервера, так и со стороны клиента.

    + +

    КЛИЕНТСКОЕ СОЕДИНЕНИЕ

    + +

    Если опция -server не указана, то канал открывается со + стороны клиента, и возвращаемый идентификатор канала может быть + использован для операции чтения и записи. Аргументы port + и host задают порт для соединения. По данному порту + должен быть сервер, обслуживающий соединение. Аргумент + port должен быть целым числом, а host - адресом + машины в доменном стиле (например, www.sunlabs.com) или + числовым IP-адресом (например, 127.0.0.1). Для ссылки на + локальную машину, на которой выполняется команда, можно + использовать значение localhost.

    + +

    Для задания дополнительной информации о соединении можно + использовать следующие опции.

    + +
    +
    -myaddr addr
    + +
    Аргумент addr задает доменный или числовой адрес + сетевого интерфейса клиентской стороны для упрощения + соединения. Эта опция может быть полезна, если на клиентской + машине есть несколько сетевых интерфейсов. Если опция не + указана, системный интерфейс будет выбран операционной + системой.
    + +
    -myport port
    + +
    Аргумент port задает номер порта для клиентской + стороны соединения. Если опция не указана, номер порта для + клиента будет определен операционной системой.
    + +
    -async
    + +
    Использование опции -async приведет к тому, что + клиент будет подсоединен в асинхронном режиме. Это значит, что + сокет будет создан немедленно, возможно, еще до установления + связи с сервером. Если канал открыт в блокирующем режиме, то + при выполнении команды gets + или flush по такому сокету, + команда завершится только после того, как процесс установления + соединения будет завершен. Если канал открыт в неблокирующем + режиме, то в этой ситуации команда завершится немедленно, а + команда fblocked для + данного канала возвратит 1.
    +
    + +

    СЕРВЕРНОЕ СОЕДИНЕНИЕ

    + +

    Если в команде присутствует опция -server, то новый + сокет будет сервером для порта port. Tcl будет + автоматически устанавливать соединения по данному порту. Для + каждого соединения будет создаваться новый канал, который может + быть использован для связи с клиентом. При этом Tcl выполняет + команду command с тремя дополнительными аргументами: имя + нового канала, адрес клиентской машины в сетевой нотации и номер + порта клиента.

    + +

    В команде можно использовать следующие опции:

    + +
    +
    -myaddr addr
    + +
    Аргумент addr задает доменный или числовой адрес + сетевого интерфейса серверной стороны для упрощения + соединения. Эта опция может быть полезна, если на серверной + машине есть несколько сетевых интерфейсов. Если опция не + указана, сокет связывается со специальным адресом INADDR_ANY, + который позволяет принимать соединения от любого + интерфейса.
    +
    + +

    Канал сервера не может быть использован для приема или выдачи + данных. Его единственное назначение - принимать новые клиентские + подсоединения. Каналы, открываемые для каждого клиентского + соединения, открываются на чтение и запись. Закрытие серверного + канала вызывает отключение сервера, так что никаких новых + соединений не может быть выполнено. Однако существующие + соединения сохраняются.

    + +

    Сокет сервера не может обнаружить новое соединение при + незапущенном обработчике событий. Поэтому в приложении должен + быть запущен обработчик событий, например, командой vwait.

    + +

    КОНФИГУРАЦИОННЫЕ ОПЦИИ

    + +

    Команда fconfigure может + получить значения нескольких неизменяемых опций для сокетов: + +

    + +
    -sockname
    + +
    Эта опция возвращает список из трех элементов: адреса, имени + хоста и номера порта для сокета. Если имя хоста не может быть + определено, второй элемент списка совпадает с первым + адресом.
    + +
    -peername
    + +
    Эта опция не поддерживается для сокетов сервера. Для + сокетов клиента и установленных соединений она выдает список + из трех элементов: адреса, имени хоста и номера порта для + сокета. Если имя хоста не может быть определено, второй + элемент списка совпадает с первым - адресом.
    +
    + + diff --git a/hlp/ru/tcl/source.html b/hlp/ru/tcl/source.html new file mode 100644 index 0000000..4735b9c --- /dev/null +++ b/hlp/ru/tcl/source.html @@ -0,0 +1,35 @@ + + + + source + + + +

    source

    + +

    Команда source исполняет скрипт, содержащийся в + файле.

    + +

    СИНТАКСИС

    + +
    +      source fileName
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда передает интерпретатору Tcl содержимое + названного файла в качестве исполняемого скрипта. Команда + возвращает результат выполнения последней выполненной команды + скрипта. Если при выполнении скрипта возникла ошибка, то команда + source возвратит эту ошибку. Если при выполнении скрипта + была вызвана команда return, то + выполнение скрипта прекращается, и команда завершается. При этом + она возвращает результат выполнения команды return.

    + +

    Для Macintosh-платформ существуют дополнительные варианты + команды, предназначенные для работы с ресурсами.

    + + + + diff --git a/hlp/ru/tcl/split.html b/hlp/ru/tcl/split.html new file mode 100644 index 0000000..8495aeb --- /dev/null +++ b/hlp/ru/tcl/split.html @@ -0,0 +1,45 @@ + + + + split + + + +

    split

    + +

    Команда разделяет строку на части и создает из них правильный + Tcl-список.

    + +

    СИНТАКСИС

    + +
    +      split string splitChars
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда делит строку string в каждом месте, где есть + символ, содержащийся в splitChars. Каждый элемент списка + образован частью исходной строки, заключенной между двумя + последовательными вхождениями символов из splitChars в + строку. В списке формируется пустой элемент, если два символа из + splitChars встречаются подряд или если первый или + последний символ string содержится в splitChars. + Если splitChars есть пустая строка, то строка разбивается + на отдельные символы. По умолчанию splitChars содержит + пробельные символы (пробел, табуляция, новая строка).

    + +

    ПРИМЕР

    + +

    Команда

    +
    +      split "comp.unix.misc"
    +    
    +

    вернет "comp unix misc", а команда

    +
    +      split "Hello world" {}
    +    
    +

    вернет "H e l l o { } w o r l d".

    + + + diff --git a/hlp/ru/tcl/string.html b/hlp/ru/tcl/string.html new file mode 100644 index 0000000..1fffe36 --- /dev/null +++ b/hlp/ru/tcl/string.html @@ -0,0 +1,187 @@ + + + + string + + + +

    string

    + +

    Команда для работы со строками.

    + +

    СИНТАКСИС

    + +
    +      string option arg ?arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Выполняет одну из перечисленных ниже строковых операций в + зависимости от заданной опции option.

    + +
    +
    string compare + string1 string2
    + +
    Выполняет посимвольное сравнение строк string1 и + string2 так же, как С-процедура strcmp. Возвращает + -1, 0 или 1, в зависимости от того, будет ли + строка string1 больше, равна или меньше (при + лексикографическом сравнении) строки string2. +
    + +
    string first + string1 string2
    + +
    Ищет в строке string2 последовательность символов, в + точности совпадающую со string1. Если такая + последовательность есть, возвращает индекс первой буквы в + первой найденной последовательности. В противном случае + возвращает -1. +
    + +
    string index string + charIndex
    + +
    Возвращает charIndex-ный символ в строке + string. Значение charIndex, равное 0, + соответствует первому символу в строке. Если значение + charIndex меньше 0 или не меньше длины строки + - возвращает пустую строку. +
    + +
    string last + string1 string2
    + +
    Ищет в строке string2 последовательность символов, в + точности совпадающую со string1. Если такая + последовательность есть, возвращает индекс первой буквы в + последней найденной последовательности. В противном случае + возвращает -1. +
    + +
    string length + string
    + +
    Возвращает десятичную строку, содержащую число символов в + строке. +
    + +
    string match + pattern string
    + +

    Проверяет, соответствует ли строка образцу. Возвращает + 1, если соответствует, и 0 - в противном + случае. Соответствие проверяется примерно так же, как в + C-shell. Строка соответствует шаблону, если они совпадают + посимвольно, за исключением перечисленных ниже специальных + случаев:

    + + + + + + + + + + + + + + + + + + + +
    *Удовлетворяет любой последовательности из нуля + или больше символов;
    ?Удовлетворяет любому символу;
    [chars] Удовлетворяет любому символу из chars. Если + chars включает последовательность символов типа + a-b, то удовлетворяет всем символам от a + до b (включительно).
    \xУдовлетворяет символу x. Обеспечивает возможность + избежать в шаблонах специального смысла символов *, ?, + [, ], \.
    +
    + +
    string range string + first last
    + +
    Возвращает подстроку строки string, начиная с символа + с индексом first и кончая символом с индексом + last. Индекс 0 указывает на первый символ + строки. Индекс end (или любое его сокращение) указывает + на последний символ строки. Если значение first меньше + 0, используется значение 0. Если last + больше значения индекса последнего символа в строке, + используется значение end. Если first больше, + чем last, команда возвращает пустую строку. +
    + +
    string tolower + string
    + +
    Возвращает строку, тождественную string, за + исключением того, что все символы верхнего регистра в ней + переведены в нижний регистр. +
    + +
    string toupper + string
    + +
    Возвращает строку, тождественную string, за + исключением того, что все символы нижнего регистра в ней + переведены в верхний регистр. +
    + +
    string trim string ?chars?
    + +
    Возвращает строку, тождественную string, за исключением + того, что из нее удалены все начальные и конечные символы, + входящие в chars. Если аргумент chars не указан, + удаляются пробельные символы (пробелы, табуляция, символы + новой строки). +
    + +
    string trimleft + string ?chars?
    + +
    Возвращает строку, тождественную string, за + исключением того, что из нее удалены все начальные символы, + входящие в chars. Если аргумент chars не указан, + удаляются пробельные символы (пробелы, табуляция, символы + новой строки). +
    + +
    string trimright + string ?chars?
    + +
    Возвращает строку, тождественную string, за + исключением того, что из нее удалены все конечные символы, + входящие в chars. Если аргумент chars не + указан, удаляются пробельные символы (пробелы, табуляция, + символы новой строки). +
    + +
    string wordend + string index
    + +
    Возвращает индекс символа, идущего сразу после последнего + символа в слове, содержащем index-ный символ строки + string. Словом считается любая непрерывная + последовательность из букв, цифр и символа подчеркивания, + или любой другой одиночный символ. +
    + +
    string wordstart + string index
    + +
    Возвращает индекс первого символа в слове, содержащем + index-ный символ строки string. Словом считается + любая непрерывная последовательность из букв, цифр и символа + подчеркивания, или любой другой одиночный символ. +
    +
    + + diff --git a/hlp/ru/tcl/subst.html b/hlp/ru/tcl/subst.html new file mode 100644 index 0000000..1c2ab74 --- /dev/null +++ b/hlp/ru/tcl/subst.html @@ -0,0 +1,14 @@ +subst +

    subst

    +

    Команда выполняет подстановки переменных, команд и подстановки с обратным слешем. +

    СИНТАКСИС +

    subst -nobackslashes -nocommands -novariables string +

    ОПИСАНИЕ +

    Команда subst выполняет подстановки переменных, подстановки команд и подстановки с обратным слешем в строке string и возвращает получившуюся строку. Все подстановки выполняются обычным для Tcl образом. В результате подстановки в строке string выполняются дважды: один раз - анализатором команд Tcl и второй раз - командой subst. +

    Если задан любой из ключей -nobackslashes, -nocommands или -novariables, то соответствующие подстановки не выполняются. +

    Внимание! При выполнении подстановок команда subst не обращает внимания на двойные кавычки и фигурные скобки. +

    ПРИМЕР +

    Следующий скрипт +

    set a 44 +
    subst {xyz {$a}}
    +

    вернет "xyz {44}" а не "xyz {$a}". diff --git a/hlp/ru/tcl/switch.html b/hlp/ru/tcl/switch.html new file mode 100644 index 0000000..68b5ddd --- /dev/null +++ b/hlp/ru/tcl/switch.html @@ -0,0 +1,116 @@ + + + + switch + + +

    switch

    + +

    Команда выполняет один из нескольких скриптов в зависимости + от полученного значения.

    + +

    СИНТАКСИС

    + +
    +      switch ?options? string pattern body ?pattern body...?
    +      switch ?options? string {pattern body ?pattern body...?}
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда switch сравнивает аргумент string по + очереди с каждым из образцов, заданных аргументами + pattern. Если строка string соответствует + очередному образцу, выполняется соответствующий скрипт + body и команда возвращает результат его выполнения. Если + последний из образцов равен default, то ему соответствует + любая строка. Если строка не соответствует ни одному из образцов + (что значит, в частности, что образец default + отсутствует), то никакой скрипт не выполняется и команда + возвращает пустое значение.

    + +

    Если один или несколько первых аргументов команды начинаются с + -, они считаются опциями команды. Возможные опции + перечислены ниже.

    + +
    + +
    -exact
    + +
    Строка считается соответствующей образцу, только если она в точности + с ним совпадает. Этот режим используется по умолчанию.
    + +
    -glob
    + +
    При сравнении строки с образцом используются те же правила, + что и в команде string match.
    + +
    -regexp
    + +
    При сравнении строки с образцом используются те же правила, + что и в команде regexp.
    + +
    --
    + +
    Обозначает конец опций. Следующий аргумент считается строкой + string, даже если он начинается с символа + -.
    +
    + +

    Команда предполагает использование одной из двух синтаксических + форм для задания образцов и скриптов. Первая использует + отдельные аргументы для каждого образца и скрипта. Эта форма + удобна при необходимости выполнить подстановки в образцах и/или + скриптах. Во второй форме все они помещаются в один аргумент, + который должен быть списком. Элементами этого списка должны + быть, соответственно, образцы и скрипты. Эта форма более удобна + для длинных команд, не размещающихся в одной строке, поскольку + она не требует использовать обратный слэш в конце каждой + строки. Но при ее использовании необходимо учитывать, что, + поскольку список содержится в фигурных скобках, подстановки + команд и переменных в образцах и скриптах не + производятся. Вследствие этого результат выполнения команды, + записанной в различных формах, может различаться.

    + +

    Если один из аргументов body равен -, это + означает, что при совпадении строки с данным образцом будет + выполняться скрипт body для следующего образца. Если для + следующего образца скрипт также равен -, то будет + использован скрипт для следующего за ним образца и т.д.

    + +

    Ниже приведены примеры использования команды + switch.

    + +

    Команда

    +
    +      switch abc a - b {format 1} abc {format 2} default {format 3}
    +    
    +

    вернет значение 2.

    + +

    Команда

    +
    +      switch -regexp aaab {
    +      	^a.*b$ -
    +        b {format 1}
    +        a* {format 2}
    +        default {format 3}
    +      }
    +    
    +

    вернет значение 1.

    + +

    А команда

    +
    +      switch xyz {
    +      	a
    +        -
    +        b
    +        {format 1}
    +        a*
    +        {format 2}
    +        default
    +        {format 3}
    +      }
    +    
    +

    вернет значение 3.

    + + diff --git a/hlp/ru/tcl/tcl.toc.html b/hlp/ru/tcl/tcl.toc.html new file mode 100644 index 0000000..6d06ecd --- /dev/null +++ b/hlp/ru/tcl/tcl.toc.html @@ -0,0 +1,90 @@ +Команды Tcl +Http
    +SafeTcl
    +Tcl
    +after
    +append
    +array
    +bgerror
    +binary
    +break
    +case
    +catch
    +cd
    +clock
    +close
    +concat
    +continue
    +eof
    +error
    +eval
    +exec
    +exit
    +expr
    +fblocked
    +fconfigure
    +fcopy
    +file
    +fileevent
    +filename
    +flush
    +for
    +foreach
    +format
    +gets
    +glob
    +global
    +history
    +if
    +incr
    +info
    +interp
    +join
    +lappend
    +library
    +lindex
    +linsert
    +list
    +llength
    +load
    +lrange
    +lreplace
    +lsearch
    +lsort
    +namespace
    +open
    +package
    +pid
    +pkg_mkIndex
    +proc
    +puts
    +pwd
    +read
    +regexp
    +regsub
    +rename
    +resource
    +return
    +scan
    +seek
    +set
    +socket
    +source
    +split
    +string
    +subst
    +switch
    +tclvars
    +tell
    +time
    +trace
    +unknown
    +unset
    +update
    +uplevel
    +upvar
    +variable
    +vwait
    +while
    + + diff --git a/hlp/ru/tcl/tclvars.html b/hlp/ru/tcl/tclvars.html new file mode 100644 index 0000000..cff7965 --- /dev/null +++ b/hlp/ru/tcl/tclvars.html @@ -0,0 +1,287 @@ + + + + tclvars + + + +

    tclvars

    + +

    Переменные, используемые Tcl.

    + +

    ОПИСАНИЕ

    + +

    Следующие глобальные переменные автоматически создаются при + запуске программ. Как правило, они ведутся автоматически и в + пользовательском приложении их значения не изменяются.

    + +
    + +
    env
    + +

    Эта переменная представляет собой массив, элементы + которого соответствуют переменным окружения. Присвоение + значения элементу массива приводит к изменению значения (или + созданию) соответствующей переменной окружения. Удаление + элемента массива с помощью команды unset удаляет соответствующую + переменную окружения. Модифицированное состояние массива + используется для процессов - потомков, запущенных командой + exec. +

    + +

    На Windows-платформах переменные PATH, + COMSPEC и WINDIR всегда пишутся в верхнем + регистре. Все остальные переменные оставляются в том виде, в + каком они заданы в операционной системе.

    + +

    На Macintosh-платформах, на которых нет переменных + окружения, автоматически формируемый массив env, тем + не менее, содержит следующие элементы:

    + +

    LOGIN, USER, SYS_FOLDER, APPLE_M_FOLDER, CP_FOLDER, + DESK_FOLDER, EXT_FOLDER, PREF_FOLDER, PRINT_MON_FOLDER, + SHARED_TRASH_FOLDER, TRASH_FOLDER, START_UP_FOLDER, PWD +

    +
    + +
    errorCode
    + +

    При возникновении ошибки эта переменная содержит + дополнительную информацию об ошибке в форме, удобной для + автоматической обработки. Эта информация содержится в виде + списка из одного или более элементов. Первый элемент списка + содержит имя класса ошибки. Его значение определяет формат + остальной части списка. Стандартно используются следующие + классы ошибок (в приложении могут определяться и + дополнительные классы):

    +
    +
    ARITH code msg
    + +
    Этот класс ошибки формируется при арифметической ошибке + (например, при попытке делить на ноль в команде expr). Код code + определяет конкретный тип ошибки, а msg содержит + текст с описанием ошибки. Возможные значения кода + DIVZERO (попытка делить на нуль), DOMAIN + (аргумент не принадлежит области определения функции, + например acos(2)), IOVERFLOW (переполнение + при целочисленных операциях), OVERFLOW + (переполнение при вычислениях с плавающей запятой) или + UNKNOWN (если не удается определить тип ошибки). +
    + +
    CHILDKILLED pid sigName msg
    + +
    Этот класс ошибки используется, если выполнение процесса + - потомка прервано сигналом. Второй элемент списка + (pid) содержит в этом случае идентификатор + прерванного процесса. Элемент sigName содержит + символьное имя сигнала, например SIGPIPE, а в + элементе msg содержит текст с описанием сигнала, + например "write on pipe with no readers". +
    + +
    CHILDSTATUS pid code
    + +
    Этот класс ошибки используется, когда процесс - потомок + завершается с кодом ошибки. Второй элемент списка + (pid) содержит в этом случае идентификатор + прерванного процесса а третий элемент (code) - + значение кода ошибки. +
    + +
    CHILDSUSP pid sigName msg
    + +
    Этот класс ошибки используется, когда выполнение + процесса-потомка приостановлено из-за сигнала. Элементы + списка имеют тот же смысл, что и для CHILDKILLED. +
    + +
    NONE
    + +
    Этот класс используется для тех ошибок, для которых + дополнительная информация не может быть получена, + поскольку при попытке ее выдать произошла ошибка. +
    + +
    POSIX errName msg
    + +
    Этот класс используется для тех ошибок, которые + происходят при выполнении вызовов POSIX. Второй + элемент списка содержит символическое имя ошибки, + например, ENOENT, а в элементе msg содержит текст с + описанием ошибки, например, "no such file or directory". +
    +
    + +
    errorInfo
    + +
    При возникновении ошибки эта переменная содержит описание + команды или процедуры, в которой произошла последняя + ошибка. Описание построено в виде описания стека, указывающего + вложенные Tcl-команды, выполнявшиеся при возникновении ошибки. +
    + +
    tcl_library
    + +
    В этой переменной хранится имя каталога, содержащего + системную библиотеку Tcl-скриптов, используемых, в частности, + при автозагрузке. Величина этой переменной возвращается + командой info + library. Начальное значение переменной формируется + в результате просмотра ряда каталогов и поиска в них + соответствующих скриптов. Если задана переменная окружения + TCL_LIBRARY, указанный в ней каталог проверяется + первым. Если переменная TCL_LIBRARY не задана или в ней + не содержатся необходимые файлы, то просматриваются еще + несколько каталогов, зависящих от расположения каталогов Tcl и + текущего каталога. +
    + +
    tcl_patchLevel
    + +
    В этой переменной хранится информация о текущей версии Tcl, + например 7.3p2 для второй доработки версии 7.3. или + 7.4b4 для четвертого бета релиза версии 7.4. Значение + переменной возвращается командой info patchlevel. +
    + +
    tcl_pkgPath
    + +
    Переменная содержит список каталогов, используемых для + размещения пакетов библиотек. Обычно список состоит из двух + элементов - каталога для бинарных файлов и каталога для + скриптов. Пакеты обычно устанавливаются как подкаталоги этих + каталогов. Исходное значение переменной добавляется к списку + каталогов в auto_path и используются для поиска пакетов + при выполнении команды package require. + Последующие изменения в tcl_pkgPath не отражаются в + переменной auto_path. Поэтому дополнительные каталоги + для поиска пакетов необходимо указывать (если это нужно) + непосредственно в переменной auto_path. +
    + +
    tcl_platform
    + +
    Эта переменная является ассоциативным массивом, в элементах + которого содержится информация о платформе. Ниже содержится + список элементов массива (расширения и приложения могут + хранить информацию о себе в дополнительных элементах этого + массива). +
    + +
    byteOrder
    + +
    Исходный порядок байтов в слове: littleEndian или + bigEndian +
    + +
    machine
    + +
    Набор команд, исполняемых на машине, например intel, + PPC, 68k или sun4m. На Unix - платформах + совпадает с величиной, возвращаемой командой uname -m. +
    + +
    os
    + +
    Имя операционной системы, например Win32s, Windows + NT, MacOS или SunOS. На Unix - платформах + совпадает с величиной, возвращаемой командой uname -s. +
    + +
    osVersion
    + +
    Версия операционной системы. На Unix - платформах совпадает + с величиной, возвращаемой командой uname -r. +
    + +
    platform
    + +
    Может принимать одно из значений windows, macintosh + или unix. +
    + +
    tcl_precision
    + +

    Переменная управляет числом цифр при переводе десятичных + чисел в строки. Значение по умолчанию 12. Максимальное + значение 17 позволяет переводить числа из двоичного + представления в строковое и обратно без потери точности. + Однако при этом отключается округление. В результате команда +

    +
    +	  expr 1.4
    +	
    +

    вернет значение 1.3999999999999999, если tcl_precision + равна 17, и значение. 1.4 если tcl_precision равна + 12.

    + +

    Все интерпретаторы в процессе используют одно и тоже + значение tcl_precision. Изменение точности представления + чисел в одном из интерпретаторов ведет к его синхронному + изменению во всех остальных. Однако, в надежных + интерпретаторах изменять точность нельзя.

    +
    + +
    tcl_rcFileName
    + +
    Эта переменная используется при инициализации для + определения имени пользовательского фала, исполняемого при + запуске. Для wish обычно ее значение + ~/.wishrc для Unix платформ и ~/wishrc.tcl для + Windows платформ. Если соответствующий файл найден, он + читается командой source. +
    + +
    tcl_rcRsrcName
    + +
    Используется только на Macintosh платформах для задания + TEXT ресурса. +
    + +
    tcl_traceCompile
    + +
    Эта переменная позволяет управлять объемом информации, + формирующейся при компиляции Tcl в байт-код. По умолчанию + значение переменной равно 0 и никакая информация не + выводится. Если присвоить tcl_traceCompile значение 1, + то при компиляции каждой процедуры или команды верхнего уровня + на стандартный выход посылается одна строка комментариев. Если + присвоить tcl_traceCompile значение 2, то при + компиляции в стандартный вывод выдается подробный листинг. Это + бывает полезно при проблемах, возникающих в процессе + компиляции, особенно, при переводе старых программ на Tcl8.0. +
    + +
    tcl_traceExec
    + +
    Эта переменная позволяет управлять объемом информации, + выводящейся при исполнении байт-кода. По умолчанию + tcl_traceExec равна 0 и никакая информация не + выводится. Если присвоить tcl_traceExec значение 1, то + при исполнении процедур в стандартный вывод выдается одна + строка текста. Если присвоить tcl_traceExec значение 1, + то строка текста выдается также при выполнении каждой команды, + а если присвоить tcl_traceExec значение 3, то выдается + информация о выполнении каждой инструкции байт-кода. Это + бывает полезно при проблемах, возникающих в процессе + компиляции и исполнения, особенно, при переводе старых + программ на Tcl8.0. +
    + +
    tcl_version
    + +
    Эта переменная содержит номер версии Tcl в форме x.y. + Обычно изменение x может означать потерю совместимости с + предыдущими версиями, тогда как изменение y означает небольшие + улучшения и исправление ошибок. Значение переменной + возвращается командой info tclversion. +
    +
    + + diff --git a/hlp/ru/tcl/tell.html b/hlp/ru/tcl/tell.html new file mode 100644 index 0000000..f1b3f06 --- /dev/null +++ b/hlp/ru/tcl/tell.html @@ -0,0 +1,26 @@ + + + + tell + + + +

    tell

    + +

    Команда возвращает текущую позицию поиска открытого + канала.

    + +

    СИНТАКСИС

    + +
    +      tell channelId
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда tell возвращает десятичную строку, указывающую + текущую позицию доступа в канале channelId. Если канал + не поддерживает прямой доступ, то возвращается значение + "-1".

    + + diff --git a/hlp/ru/tcl/time.html b/hlp/ru/tcl/time.html new file mode 100644 index 0000000..cf11698 --- /dev/null +++ b/hlp/ru/tcl/time.html @@ -0,0 +1,28 @@ + + + + time + + +

    time

    + +

    Команда выполняет скрипт заданное количество раз.

    + +

    СИНТАКСИС

    + +
    +      time script count
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда time вызовет интерпретатор Tcl count раз + для выполнения скрипта script или только один раз, если + аргумент count не задан. Команда возвратит строку вида

    +
    503 microseconds per iteration
    +

    отображающую среднее + время в микросекундах, израсходованное на одну итерацию. В + строке указывается прошедшее время, а не время работы + процессора.

    + + diff --git a/hlp/ru/tcl/trace.html b/hlp/ru/tcl/trace.html new file mode 100644 index 0000000..47df997 --- /dev/null +++ b/hlp/ru/tcl/trace.html @@ -0,0 +1,188 @@ + + + + trace + + +

    trace

    + +

    Команда отслеживает работу с переменными.

    + +

    СИНТАКСИС

    + +
    +      trace option ?arg arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта команда вызывает выполнение указанных Tcl команда при + определенных действиях с переменной. Ниже перечислены возможные + опции команды (допускаются сокращения).

    + +
    + +
    trace variable name ops + command
    + +

    Обеспечивает выполнение команды command при + определенных действиях с переменной name. Ниже + перечислены возможные значения аргумента ops и какие + действия с переменной при этом отслеживаются. Аргумент + name может содержать имя простой переменной, имя + элемента массива или имя массива. Если name содержит + имя массива, то команда command выполняется при + соответствующих действиях с любым элементом массива.

    +

    Аргумент ops состоит из одной или больше букв, + перечисленных ниже.

    + + + + + + + + + + + + + + + +
    rВызывает команду command при чтении переменной.
    wВызывает команду command при присвоении значения + переменной.
    uВызывает команду command при удалении + переменной. Переменная может удаляться как явно (с + помощью команды unset), так и неявно (при + завершении процедуры). переменная также удаляется + при удалении интерпретатора, в котором она была + создана. Однако, при этом соответствующая команда + не вызывается, так как уже нет интерпретатора, в + котором ее можно было бы выполнить. +
    + +

    Когда срабатывает команда trace, то исполняемая + команда command дополняется тремя аргументами, как + указано ниже

    +
    +	  command name1 name2 op
    +
    + +

    Здесь name1 это имя переменной, действия с которой + вызвали срабатывание команды. Если это элемент массива, то + name1 это имя массива, а name2 - имя + конкретного элемента массива. В противном случае + name2 - пустая строка. Если в команде trace + было указано имя массива и он удаляется, то name2 + также будет пустой строкой. Имена в переменных name1 + и name2 не обязано совпадать с теми, что были заданы + в команде trace variable, поскольку команда upvar позволяет процедуре + обращаться к переменной по различным именам. Аргумент + op указывает какое именно действие выполнялось с + переменной и может принимать значения r, w или + u как указано выше. +

    + +

    Команда command исполняется в том же контексте, что + и код, вызвавший срабатывание trace. То есть если + действие с переменной выполнялось в процедуре, то команда + command может обращаться к локальным переменным этой + процедуры. Этот контекст может отличаться от контекста, в + котором выполнялась сама команда trace. Если команда + conmmand есть вызов процедуры (как обычно и бывает), + то в процедуре необходимо использовать команду upvar или uplevel чтобы получить доступ к + контролируемой переменной. Как уже говорилось, имена в + переменных name1 и name2не обязано совпадать с + теми, что были заданы в команде trace variable, + поскольку команда upvar + позволяет процедуре обращаться к переменной по различным + именам.

    + +

    Если команда trace контролирует чтение и запись в + переменную, команда command может изменить результат + отслеживаемой операции. Если команда command изменяет + значение отслеживаемой переменной, то новое значение будет + возвращено как результат отслеживаемой операции. Величина, + возвращаемая командой command, игнорируется, если + только это не ошибка. Тогда отслеживаемая операция также + возвращает ошибку с тем же самым сообщением об ошибке, + которое было сформировано в команде command, не + поясняя, что ошибка произошла в результате отслеживания + переменной. Это может приводить к определенным трудностям в + определении истиной операции, при выполнении которой + возникла ошибка.

    + +

    При отслеживании записи в переменную команда command + вызывается после того, как значение переменной + изменено. Поэтому с ее помощью можно изменить присвоенное + значение. Если при этом возвращать исходное значение, + переменная окажется доступной только для чтения.

    + +

    При выполнении команды command при отслеживании + чтения или записи в переменную механизм слежения временно + отключается. То есть выполнение этих операций в + command не приведет к новых вызовам command. + Однако, если в command выполняется удаление + переменной, это приводит к соответствующему вызову.

    + +

    Когда срабатывает команда trace на удаление переменной, + переменная уже удалена. Если удаление переменной произошло + вследствие завершения процедуры, команда command + вызывается в контексте вызывающей процедуры, поскольку + контекст вызвавшейся процедуры уже не существует. + Отслеживание не отключается при выполнении command в + случае удаления переменной. Поэтому если в command + выполняется новая команда trace и удаляется + соответствующая переменная, выполнится и соответствующая + команда command. Ошибки при отслеживании удаления + игнорируются.

    + +

    Если одна и та же переменная отслеживается с помощью + нескольких команда trace, то выполняться все + соответствующие команды command с учетом порядка + выполнения соответствующих команд trace. Чем позднее + она выполнялась, тем раньше будет выполнена соответствующая + команда command. Если одна из команд command + при этом возвратит ошибку, остальные команды выполняться не + будут. Если одна команда используется для отслеживания + элемента массива, а другая - для массива в целом, первой + выполняется команда отслеживания массива в целом, а затем + уже команда отслеживания элемента.

    + +

    Однажды выполненная команда trace остается активной + пока она не удалена с помощью описанной ниже команды + trace vdelete, пока не удалена переменная или + пока не удален интерпретатор. Удаление элемента массива + приведет к прекращению отслеживания этого элемента, но не + отслеживания массива в целом.

    + +

    Команда trace variable возвращает пустую строку.

    +
    + +
    trace vdelete name ops + command
    + +

    Если задано отслеживание переменной name с + перечнем действий ops и командой command, то + оно будет удалено. Соответственно команда command + никогда не будет вызвана. Команда trace vdelete + возвращает пустую строку.

    +
    + +
    trace vinfo name
    + +

    Возвращает список, содержащий по одному элементу для + каждого заданного отслеживания для переменной name. Каждый + элемент списка содержит два элемента, содержащие значения + ops и command из команды trace, которой + было задано соответствующее отслеживание. Если переменная + name не существует или для нее не задано отслеживания, + команда возвращает пустую строку.

    +
    +
    + + diff --git a/hlp/ru/tcl/unknown.html b/hlp/ru/tcl/unknown.html new file mode 100644 index 0000000..cd51fdd --- /dev/null +++ b/hlp/ru/tcl/unknown.html @@ -0,0 +1,87 @@ + + + + unknown + + +

    unknown

    + +

    Команда unknown обрабатывает попытки обратиться к + несуществующей команде.

    + +

    СИНТАКСИС

    + +
    +      unknown cmdName ?arg arg?
    +    
    + +

    ОПИСАНИЕ

    + +

    Интерпретатор Tcl выполняет эту команду каждый раз, когда + скрипт пытается обратиться к несуществующей команде. Исходный + вариант unknown не является функцией ядра Tcl; + напротив, это библиотечная процедура, определяемая по + умолчанию при запуске Tcl. Разработчик может переопределить + ее функциональность так, как ему нужно.

    + +

    Когда Tcl находит имя команды, которому не соответствует ни + одной из существующих команд, тогда он проверяет наличие команды + unknown. Если команды unknown нет, то он + возвращает ошибку. Если такая команда обнаружена, то она будет + вызвана с аргументами, состоящими из имени и аргументов исходной + несуществующей команды, в которых выполнены все необходимые + подстановки.

    + +

    Команда unknown обычно выполняет поиск по библиотечным + каталогам процедуры с именем cmdName, или поиск полного + имени команды, к которой обратились по сокращенному имени, или + автоматический запуск неизвестной команды как подпроцесса. При + успешном поиске полного имени команды команда unknown + заменяет имя на полное и вызывает команду с полным + именем. Результат работы команды unknown используется + вместо результата неопределенной команды.

    + +

    Создаваемая по умолчанию процедура unknown выполняет + следующие действия.

    + +

    Сначала она вызывает библиотечную процедуру auto_load + чтобы найти и загрузить соответствующую процедуру. Если это + удалось, то выполняется исходная команда с ее исходными + аргументами.

    + +

    В противном случае вызывается процедура auto_execok + чтобы найти исполняемый файл с именем cmdName. Если файл + удалось найти, выполняется команда exec с именем команды и ее + аргументами в качестве аргументов.

    + +

    В противном случае проверяется, была ли неизвестная команда + вызвана на самом верхнем уровне вне какого-либо скрипта. Если + это было так, процедура unknown выполняет следующие + дополнительные действия: проверяется не имеет ли команда одну из + следующих форм:!!, !event, или + ^old^new?^? и если да, то процедура + unknown выполняет для них подстановки по тем же правилам, что и + csh.

    + +

    И при неудаче всех предыдущих попыток процедура unknown + проверяет, не является ли cmdName сокращением для + известной Tcl процедуры. Если так, то cmdName заменяется + на полное имя процедуры и она вызывается с исходными + аргументами.

    + +

    Если же ни одна из попыток не привела к успеху, процедура + возвращает ошибку.

    + +

    Если определена глобальная переменная auto_noload, + попытка загрузить процедуру с помощью auto_load не + производится.

    + +

    Если определена глобальная переменная auto_noexec, + попытка загрузить процедуру с помощью auto_execok не + производится.

    + +

    Если команду удалось найти, то процедура unknown + возвращает результат выполнения найденной команды.

    + + diff --git a/hlp/ru/tcl/unset.html b/hlp/ru/tcl/unset.html new file mode 100644 index 0000000..4a67f0b --- /dev/null +++ b/hlp/ru/tcl/unset.html @@ -0,0 +1,31 @@ + + + + unset + + + +

    unset

    + +

    Команда удаляет переменные.

    + +

    СИНТАКСИС

    + +
    +      unset name name name ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда unset удаляет переменные name. Правила + именования переменных точно такие же, как для команды set. Если в команде указано имя + элемента массива, то этот элемент будет удален из массива, не + влияя на остальную часть массива. Если указано имя массива без + индекса в скобках, то будет удален весь массив.

    + +

    Команда возвращает пустую строку. Если одна из переменных не + существует, команда вернет ошибку, а последующие переменные не + будут удалены.

    + + diff --git a/hlp/ru/tcl/update.html b/hlp/ru/tcl/update.html new file mode 100644 index 0000000..afd2a8a --- /dev/null +++ b/hlp/ru/tcl/update.html @@ -0,0 +1,9 @@ +update +

    update

    +

    Команда update обрабатывает события, находящиеся в состоянии ожидания, и обратные вызовы (idle callbacks). +

    СИНТАКСИС +

    update idletasks +

    ОПИСАНИЕ +

    С помощью этой команды обновляется состояние приложения, поскольку при ее вызове обрабатываются все необработанные события и выполняются все асинхронные вызовы (idle callbacks). +

    Если в команде задана опция idletasks, то новые события и ошибки не обрабатываются, но выполняются все асинхронные вызовы. Команду update idletasks удобно использовать тогда, когда нужно выполнить немедленно действия, которые обычно откладываются, например, обновить отображаемые на дисплее данные или окна. Большинство обновлений изображений на дисплее выполняются в виде фоновых вызовов, и эта команда обеспечит их выполнение. Однако, если изменения были вызваны событиями, они не будут выполнены немедленно. +

    Команда update без опций полезна в тех случаях, когда во время долго выполняющихся вычислений необходимо обеспечить оперативную реакцию приложения на события, например, на действия пользователя. Вызов команды update и обеспечивает обработку таких событий. diff --git a/hlp/ru/tcl/uplevel.html b/hlp/ru/tcl/uplevel.html new file mode 100644 index 0000000..07d6fd1 --- /dev/null +++ b/hlp/ru/tcl/uplevel.html @@ -0,0 +1,92 @@ + + + + uplevel + + + +

    uplevel

    + +

    Команда выполняет скрипт в контексте, отличном от текущего.

    + +

    СИНТАКСИС

    + +
    +      uplevel ?level? arg ?arg...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Все аргументы команды объединяются как при выполнении команды + concat. Получившийся скрипт + выполняется в контексте, указанном level. Команда + возвращает результат выполнения скрипта.

    + +

    Если аргумент level задан как целое число, он указывает + на сколько уровней выше уровня контекста текущей процедуры надо + подняться в стеке вызовов перед выполнением скрипта. Если + аргумент level задан как символ # с последующим + целым числом, то он задает абсолютный уровень контекста в + стеке. Если аргумент level отсутствует, то используется + значение по умолчанию 1. Аргумент level должен + быть указан, если первый из аргументов arg начинается с цифры + или символа #.

    + +

    Например, предположим, что на самом верхнем уровне вызвана + процедура a из нее вызвана процедура b, а из b вызвана процедура + c. Предположим также, что в процедуре c есть вызов команды + uplevel. Тогда если аргумент level равен 1 + или #2 или отсутствует, то указанный в команде скрипт + будет выполнен в контексте процедуры b. Если аргумент + level равен 2 или #1, то указанный в + команде скрипт будет выполнен в контексте процедуры a. Если + аргумент level равен 3 или #0, то указанный + в команде скрипт будет выполнен на вернем уровне (уровень + глобальных переменных).

    + +

    При выполнении команды uplevel контекст вызывающей + процедуры временно удаляется из стека вызовов процедур. Так, + если в приведенном выше примере команда uplevel имеет + вид

    +
    +      uplevel 1 {set x 43; d}
    +    
    +

    где d имя другой Tcl процедуры, то команда set изменит переменную x в контексте + процедуры b, а процедура d будет выполняться на третьем уровне + стека, как если бы она была вызвана непосредственно из b. Если в + процедуре d в свою очередь содержится команда

    +
    +      uplevel {set x 42}
    +    
    +

    то команда set изменит + значение той же переменной x в контексте процедуры b. Процедура + c во время выполнения процедуры d не будет видна в + стеке. Соответственно команда + info level возвратит уровень текущей процедуры. + +

    Команда uplevel позволяет создавать новые управляющие + конструкции как Tcl-процедуры.

    + +

    Команда namespace eval + так же, как и вызовы процедур, изменяет контекст, в котором + выполняются команды. Соответственно, для каждой команды namespace eval создается + дополнительный уровень в стеке. Поэтому при указании уровня + контекста в стеке каждую вложенную команду namespace eval надо + считать наравне с вызовом процедуры. Это относится также к + командам upvar и info level. Например, команда

    +
    +      info level 1
    +    
    +

    вернет список, описывающий самую верхнюю выполняемую команду, + которая является либо вызовом процедуры, либо командой namespace + eval. Независимо от использования команда namespace eval команда + uplevel #0 выполнит соответствующий скрипт на + уровне глобальных переменных (в глобальном пространстве + имен).

    + + diff --git a/hlp/ru/tcl/upvar.html b/hlp/ru/tcl/upvar.html new file mode 100644 index 0000000..f04d609 --- /dev/null +++ b/hlp/ru/tcl/upvar.html @@ -0,0 +1,99 @@ + + + + upvar + + + +

    upvar

    + +

    Команда создает связи между переменными различных уровней + стека.

    + +

    СИНТАКСИС

    + +
    +      upvar ?level? otherVar myVar ?otherVar myVar...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда позволяет одной или больше локальным переменным текущей + процедуры ссылаться на переменные процедуры, стоящей выше в + стеке, или на глобальные переменные. Аргумент level может + иметь те же формы, что и в команде uplevel, или быть опущен, если + первый символ в первой из otherVar отличен от цифры и от + # (значение по умолчанию 1). Для каждой пары аргументов + otherVar myVar команда позволяет сделать + переменную с именем otherVar из указанного уровня стека + (локальную переменную одной из вызывающих процедур или + глобальную переменную, если level равно #0) видимой в + исполняемой процедуре под именем myVar. Переменная с + именем otherVar не обязана существовать в момент + исполнения команды. При необходимости она будет создана при + первом использовании переменной myVar. В момент + исполнения команды не должно быть доступной переменной myVar. + Переменная myVar всегда считается простой переменной (не + массивом и не переменной массива). Даже если значение + myVar выглядит как имя элемента массива, например, a(b), + создается простая переменная. Значение otherVar может + быть именем простой переменной, массива или элемента массива. + Команда upvar всегда возвращает пустую строку.

    + +

    Команда upvar позволяет упростить передачу параметра по ссылке, + а также упрощает создание новых управляющий + конструкций. Например, рассмотрим следующую процедуру:

    +
    +      proc add2 name { 
    +      	upvar $name x
    +        set x [expr $x+2]
    +      }
    +    
    +

    Процедура add2 вызывается с аргументом, содержащим имя + переменной и увеличивает значение этой переменной на два. Хотя + тот же результат мог быть получен с помощью команды uplevel, + команда upvar позволяет легче работать с переменными из + стека вызывающей процедуры.

    + +

    Команда namespace eval + так же, как и вызовы процедур, изменяет контекст, в котором + выполняются команды. Для каждой команды namespace eval создается + дополнительный уровень в стеке. Соответственно, при указании + уровня контекста в стеке каждую вложенную команду namespace eval надо + считать наравне с вызовом процедуры. Это относится также к + командам uplevel и info level. Например, + команда info level 1 + вернет список, описывающий самую верхнюю выполняемую команду, + которая является либо вызовом процедуры, либо командой namespace eval. + Независимо от использования команда namespace eval команда + uplevel #0 выполнит соответствующий скрипт на уровне + глобальных переменных (в глобальном пространстве имен).

    + +

    Если переменная, созданная с помощью команды upvar, + удаляется (например, если добавить в процедуру add2 + строку unset x), то реально будет удалена переменная, + связанная с x, а не сама переменная x. Нет никакого способа + удалить созданные таким образом переменные, кроме как выйти из + процедуры, в которой они были созданы. Тем не менее, возможно + связать переменную верхнего уровня с другой локальной + переменной, выполнив еще одну команду upvar.

    + +

    ОШИБКИ

    + +

    Если otherVar есть элемент массива, то отслеживание + массива в целом, заданной командой trace, не сработает при действиях с + myVar (однако, если отслеживание было задано на + отдельный элемент массива, оно сработает). В частности, + изменения, сделанные с помощью myVar в массиве env, не будут корректно + переданы подпроцессу. +

    + + diff --git a/hlp/ru/tcl/variable.html b/hlp/ru/tcl/variable.html new file mode 100644 index 0000000..e6c613a --- /dev/null +++ b/hlp/ru/tcl/variable.html @@ -0,0 +1,54 @@ + + + + variable + + + +

    variable

    + +

    Команда создает и запускает переменные области имен.

    + +

    СИНТАКСИС

    + +
    +      variable ?name value? name ?value?
    +    
    + +

    ОПИСАНИЕ

    + +

    Обычно команду variable выполняют внутри команды namespace eval для + создания одной или нескольких переменных в области имен. Каждая + переменная name получает начальное значение + value. Значение для последней переменной можно не + указывать.

    + +

    Если переменная name не существует, она будет + создана. Если указан аргумент value, то переменной + присвоится его значение. Если аргумент не указан, то новая + переменная останется неопределенной. Если же переменная уже + существовала, она сохранит свое значение. Обычно имя создаваемой + переменной - это простое имя, не содержащее имя пространств + имен. Соответственно переменная создается в текущем пространстве + имен. Если имя содержит имена пространств имен, переменная + создается в указанном пространстве имен.

    + +

    Если команда variable выполняется внутри Tcl процедуры, + она создает локальную переменную, связанную с соответствующей + переменной пространства имен. В этом случае команда + variable напоминает команду global, которая, однако, + только связывает локальную переменную с глобальной. Если + аргумент value задан, то он используется для изменения + значения соответствующей переменной в пространстве имен. Если + переменная в пространстве имен не существует, она создается и, + при необходимости, инициализируется.

    + +

    Параметр name не может указывать на элемент массива. В + команде variable можно указать только массив в целом, а + затем присвоить значения его элементам командами set или array.

    + + diff --git a/hlp/ru/tcl/vwait.html b/hlp/ru/tcl/vwait.html new file mode 100644 index 0000000..f6a11c7 --- /dev/null +++ b/hlp/ru/tcl/vwait.html @@ -0,0 +1,38 @@ + + + + vwait + + + +

    vwait

    + +

    Команда задает обработку событий до тех пор, пока не будет + записано значение переменной.

    + +

    СИНТАКСИС

    + +
    +      vwait varName
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда vwait активизирует обработчик событий (event + loop), блокируя приложение до тех пор, пока не в результате + какого-либо события не будет присвоено новое значение переменной + varName. После присвоения значения переменной + varName команда vwait завершит работу сразу после + выполнения скрипта, вызванного обработчиком событий.

    + +

    В некоторых ситуациях команда не завершается сразу после + присвоения значения переменной varName. Это происходит, + например, если вызванный по события скрипт, присвоивший новое + значение переменной varName, не завершается сразу. + Например, если в нем в свою очередь выполняется команда + vwait, устанавливающая режим ожидания изменения другой + переменной. Во время этого ожидания вышестоящая команда + vwait блокируется как и приложение до выполнения + соответствующего события.

    + + diff --git a/hlp/ru/tcl/while.html b/hlp/ru/tcl/while.html new file mode 100644 index 0000000..fcabdc4 --- /dev/null +++ b/hlp/ru/tcl/while.html @@ -0,0 +1,54 @@ + + + + while + + + +

    while

    + +

    Команда выполняет скрипт до тех пор, пока не будет выполнено + условие.

    + +

    СИНТАКСИС

    + +
    +      while test body
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда while вычисляет значение выражения test + подобно команде expr. Значение + должно быть булевого типа. Если результат есть "истина", то + скрипт body передается на выполнение Tcl + интерпретатору. После этого выражение test снова + вычисляется, и процесс повторяется до тех пор, пока его значение + не станет "ложь". В тексте скрипта body можно + использовать команду continue + для завершения текущего цикла и команду break для немедленного + завершения команды while.

    + +

    Команда while всегда возвращает пустую строку.

    + +

    Выражение test почти всегда лучше заключать в фигурные + скобки, иначе подстановки команд и переменных в нем будут + выполнены до исполнения команды и никакие изменения значений + переменных в скрипте body не изменят значения выражения + test. Это может привести к возникновению бесконечного + цикла. Если же выражение test помещено в фигурные скобки, + подстановки в нем выполняются при каждом вычислении (перед + каждым выполнением body). Например, если выполнить следующий + скрипт с и без скобок вокруг $x<10, то без скобок + возникнет бесконечный цикл.

    + +

    ПРИМЕР

    + +
    +      while {$x < 10} {
    +      	puts "x is $x"
    +	incr x
    +      }
    +    
    + + diff --git a/hlp/ru/tk/SafeTk.html b/hlp/ru/tk/SafeTk.html new file mode 100644 index 0000000..6d5fa53 --- /dev/null +++ b/hlp/ru/tk/SafeTk.html @@ -0,0 +1,49 @@ + + + + Safe Tk + + +

    Safe Tk

    + +

    Команда загружает Tk в безопасный ИНТЕРПРЕТАТОР.

    + +

    СИНТАКСИС

    + +
    +      ::safe::loadTk slave -use windowId
    +    
    + +

    ОПИСАНИЕ

    + +

    Режим Safe Tk основан на режиме Safe Tcl, + обеспечивающем ограниченный и опосредованный доступ к + автозагрузке и пакетам для безопасных + интерпретаторов. Safe Tk добавляет + способность конфигурирования интерпретатора для безопасных Tk + операций и загрузки Tk в безопасные интерпретаторы.

    + +

    Команда ::safe:: запускает необходимые + структуры данных в безопасном интерпретаторе и загружает в него + Tk. Команда возвращает имя безопасного интерпретатора.

    + +

    При работе с Tk в безопасном интерпретаторе необходимо + следовать правилам поддержания безопасности, а также специальным + рекомендациям для работы с Tk.

    + +

    ПРИМЕР

    + +

    СМ. ТАКЖЕ

    + +

    safe, + interp, + library, + load, + package, + source, + unknowni +

    + + + diff --git a/hlp/ru/tk/bell.html b/hlp/ru/tk/bell.html new file mode 100644 index 0000000..15eed96 --- /dev/null +++ b/hlp/ru/tk/bell.html @@ -0,0 +1,14 @@ +Bell +

    bell

    +Команда подает звуковой сигнал. +

    СИНТАКСИС

    +

    bell -displayof window +

    ОПИСАНИЕ +

    Команда 'bell'  +подает сигнал громкоговорителем дисплея для window. +Если этот аргумент не +задан, то по умолчанию используется дисплей главного окна приложения. В +некоторых случаях команда гасит работающий в данный момент хранитель +экрана (screen-saver), и окно снова становится видимым.

    +

    ПРИМЕР +

    \ No newline at end of file diff --git a/hlp/ru/tk/bind.html b/hlp/ru/tk/bind.html new file mode 100644 index 0000000..c30528f --- /dev/null +++ b/hlp/ru/tk/bind.html @@ -0,0 +1,605 @@ + + + + bind + + + + +

    bind

    + +

    Команда bind позволяет привязать выполнение + скриптов Tcl к X событиям. Команда назначает событиям ввода от + "Мыши" и клавиатуры (Х событиям) исполнение скрипта + Tcl.

    + +

    СИНТАКСИС

    + +
    +      bind тег
    +      bind тег последовательность
    +      bind тег последовательность скрипт
    +      bind тег последовательность +скрипт
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда bind привязывает Tcl скрипты к X + событиям. Если заданы все три аргумента команды, то при каждом + наступлении события последовательность в окне (окнах), + описанных тегом, будет выполняться скрипт + (скрипт Tcl). Если аргументу скрипт предшествует знак + +, то скрипт добавляется к уже существующим привязкам к + последовательности; в противном случае он замещает все + имеющиеся привязки. Если аргумент скрипт пуст, то все + имеющиеся привязки к последовательности отменяются, и + последовательность становится несвязанной. Если + аргумент скрипт присутствует, то команда + bind возвращает пустую строку.

    + +

    Если при отсутствии аргумента скрипт аргумент + последовательность задан, то команда возвращает скрипт, + привязанный к данной последовательности, или, в случае + отсутствия такого скрипта, пустую строку. Если не задан ни один + из аргументов последовательность и скрипт, то + команда возвращает список, элементами которого служат все + последовательности, имеющие привязки к окну тег.

    + +

    Аргумент тег перечисляет окна, к которым выполняется + привязка. Если значение аргумента начинается с точки, скажем + ".a.b.c", то оно должно представлять собой путь к + окну; в противном случае оно может быть произвольной + строкой. Каждому окну приписан некоторый список тегов, и + привязка к данному окну осуществляется, если значение аргумента + тег присутствует в этом списке. Команда bindtags позволяет + приписать окну произвольный набор тегов привязки; кроме того, по + умолчанию окнам приписаны следующие теги:

    + +
      +
    • тег, являющийся именем внутреннего окна, приписывается этому + окну;
    • + +
    • тег, являющийся именем окна верхнего уровня, приписывается + этому окну и всем его внутренним окнам;
    • + +
    • тег, являющийся именем класса примитивов, скажем + Button, приписывается всем примитивам этого + класса;
    • + +
    • тег с именем all приписывается всем окнам + приложения.
    • +
    + +

    ОБРАЗЦЫ СОБЫТИЙ

    + +

    Аргумент последовательность представляет собой + последовательность одного или нескольких образцов + событий. Каждый образец может быть записан в одном из трех + видов. В простейшем случае это символ ASCII, скажем + a или |. Этот символ не может + быть пробелом или знаком <. Этот вид образцов соответствует + событию KeyPress для конкретной + клавиши. Образцы второго вида длиннее, однако, этот вид носит + более общий характер. Его синтаксис выглядит следующим + образом:

    +
    +      <модификатор-модификатор-тип-детализация>
    +    
    + +

    Образец события целиком заключен в угловые скобки. Внутри + угловых скобок располагаются несколько модификаторов (быть + может, ни одного), тип события и дополнительная порция + информации (детализация), указывающая конкретную кнопку + или комбинацию клавиш. Одно из полей тип или + детализация должно обязательно присутствовать, + остальные могут быть опущены. Поля разделяются пробелами или + дефисами.

    + +

    Третья форма образца используется для задания поименованного + виртуального события, определенного пользователем. У нее + следующий синтаксис:

    + +
    +      <<имя>>
    +    
    + +

    Образец события целиком заключен в двойные угловые скобки. + Внутри этих скобок содержится определенное пользователем имя + виртуального события. С виртуальным событием нельзя + комбинировать модификаторы, такие как Shiftили + Control. Привязки к виртуальному событию можно + создавать до описания самого события; при динамическом изменении + этого описания все окна, привязанные к событию, будут обращаться + к новому описанию.

    + +

    МОДИФИКАТОРЫ

    + +

    Модификаторы могут быть следующими:

    +
      +
    • Alt
    • +
    • Button1, B1
    • +
    • Button2, B2
    • +
    • Button3, B3
    • +
    • Button4, B4
    • +
    • Button5, B5
    • +
    • Control
    • +
    • Double
    • +
    • Lock
    • +
    • Meta, M
    • +
    • Mod1, M1
    • +
    • Mod2, M2
    • +
    • Mod3, M3
    • +
    • Mod4, M4
    • +
    • Mod5, M5
    • +
    • Shift
    • +
    • Triple
    • +
    + +

    Если в строке приведено несколько элементов, разделенных + запятыми, то они взаимозаменяемы. У большинства модификаторов + есть очевидное X значение. Например, модификатор + Button1 требует нажатия кнопки 1 для + наступления события. Чтобы привязка соответствовала данному + событию, среди модификаторов события должны содержаться все + модификаторы, заданные в образце события. Кроме того событие + может содержать и другие модификаторы, не приведенные в описании + привязки. Например, при нажатии кнопки 1 одновременно с нажатием + клавиш Shift и Ctrl событие + подойдет под образец <Control-Button-1>, + но не подойдет под образец + <Mod1-Button-1>. Если ни один из + модификаторов не был задан, то в событии может присутствовать + любая комбинация модификаторов.

    + +

    Модификаторы Meta и M + заменяют любой из идентификаторов от M1 до + M5, ассоциированный с метаклавишами на + клавиатуре (коды клавиш Meta_R и + Meta_L). При отсутствии метаклавиш или в + случае, если они не ассоциированы ни с каким модификатором, + модификаторы Meta и M не будут + соответствовать никакому событию. Аналогично модификатор + Alt заменяет любой из модификаторов, + ассоциированных с alt-клавишами на клавиатуре (коды клавиш + Alt_L и Alt_R).

    + +

    Модификаторы Doubleи Triple + обеспечивают удобную обработку двойного щелчка .Мыши. и других + повторяющихся событий. Они требуют, чтобы данное событие + повторилось дважды или трижды, и накладывают ограничения на + время и место его повторения: для того, чтобы последовательность + событий подходила под образец Double или + Triple, промежуток времени между событиями + должен быть коротким, а "Мышь" не должна сдвигаться. Например, + комбинация <Double-Button-1> эквивалентна + паре <Button-1><Button-1> + с дополнительными временными и пространственными + ограничениями.

    + +

    ТИПЫ СОБЫТИЙ

    + +

    Значением поля тип может быть любой из стандартных + типов X событий, а также некоторые дополнительные + сокращения. Ниже приведен список всех допустимых значений. Два + имени, составляющие пару, синонимичны.

    + +
      +
    • Activate
    • +
    • Button
    • +
    • ButtonPress
    • +
    • ButtonRelease
    • +
    • Circulate
    • +
    • Colormap
    • +
    • Configure
    • +
    • Deactivate
    • +
    • Destroy
    • +
    • Enter
    • +
    • Expose
    • +
    • FocusIn
    • +
    • FocusOut
    • +
    • Gravity
    • +
    • Key Unmap
    • +
    • KeyPress
    • +
    • KeyRelease
    • +
    • Leave
    • +
    • Map
    • +
    • Motion
    • +
    • Property
    • +
    • Reparent
    • +
    • Visibility
    • +
    + +

    Последней частью длинной спецификации события является + детализация. Для типов ButtonPress и + ButtonRelease это номер кнопки (1-5). Если + номер кнопки задан, то под образец подойдет только событие на + указанной кнопке; если номер кнопки не задан, то под образец + подойдет событие на любой из кнопок. Замечание: задание номера + кнопки отличается от задания модификатора кнопки: в первом + случае требуется, чтобы кнопка была нажата или отжата; во втором + чтобы какая-то другая кнопка была отжата при наступлении + события. Если номер кнопки задан, то поле тип можно + опустить: по умолчанию оно будет иметь значение + ButtonPress. Например, спецификатор + <1> эквивалентен спецификатору + <ButtonPress-1>. + +

    Для типов KeyPress и + KeyRelease детализацию можно указать в виде + описателя X клавиши. В их число входят все алфавитно-цифровые + символы ASCII (например, описатель a служит для + описания символа ASCII "a"), а также описатели для + неалфавитно-цифровых символов (описатель comma + для запятой) и описатели для всех не ASCII-клавиш клавиатуры + (Shift_L для левой клавиши верхнего регистра, + F1 для первой функциональной клавиши при ее + наличии). Мы не приводим здесь полный список клавиш. Он меняется + от системы к системе, и его можно найти в других частях X + документации. При необходимости можно получить описатель клавиши + с помощью обозначения %K, описанного ниже. Если + приведена детализация описателя клавиши, то поле + тип может отсутствовать, по умолчанию принимается + значение KeyPress. Например, спецификатор + <Control-comma> эквивалентен + спецификатору <Control-KeyPress-comma>.

    + +

    ПОДСТАНОВКИ И СКРИПТЫ ПРИВЯЗКИ

    + +

    Аргумент скрипт команды bind должен + быть скриптом Tcl; при каждом наступлении события происходит + выполнение этого скрипта. Команда выполняется тем же + интерпретатором, что и команда bind, причем + интерпретация происходит на верхнем уровне (доступны только + значения глобальных переменных). Если в скрипте есть + символы %, то его исполнение не будет + осуществляться непосредственно. Каждый символ % + и символ, следующий за ним, заменяются данными о происшедшем + событии, в результате чего генерируется новый + скрипт. Подстановка осуществляется в соответствии с приводимым + ниже списком символов. Если не оговорено противное, то + подставляемая строка представляет собой десятичное содержимое + указанного поля события. Некоторые подстановки допустимы только + для событий определенных типов: при использовании их с событиями + других типов результат подстановки не определен.

    + +
    +
    %%
    + +
    Заменяется однократным процентом.
    + +
    %#
    + +
    Номер последнего обработанного сервером запроса клиента + (сериальное поле события). Допустимо для событий всех + типов.
    + +
    %a
    + +
    Поле выше события, отформатированное как + шестнадцатеричное число. Допустимо только для событий + Configure.
    + +
    %b
    + +
    Номер нажатой или отпущенной кнопки. Допустимо только для + событий ButtonPress и + ButtonRelease.
    + +
    %c
    + +
    Поле счетчик события. Допустимо только для событий + Expose.
    + +
    %d
    + +
    Поле детализация события. Символы + %d заменяются строкой детализации. Для + событий Enter, Leave, + FocusIn, FocusOut строка + должна быть одной из следующих: + NotifyAncestor, + NotifyNonlinearVirtual + NotifyDetailNone, + NotifyPointer, + NotifyInterior, + NotifyPointerRoot, + NotifyNonlinear, + NotifyVirtual. + +

    Для прочих событий подставляемая строка не определена.

    +
    + +
    %f
    + +
    Поле фокус события (0 или + 1). Допустимо только для событий + Enter и Leave.
    + +
    %h
    + +
    Поле высота события. Допустимо только для событий + Configure и Expose.
    + +
    %k
    + +
    Поле код_клавиши события. Допустимо только для + событий KeyPress и + KeyRelease.
    + +
    %m
    + +
    Поле режим события. Подставляется одна из строк + NotifyNormal, NotifyGrab, + NotifyUngrab или + NotifyWhileGrabbed. Допустимо только для + событий Enter, FocusIn, + FocusOut и Leave.
    + +
    %o
    + +
    Поле подавить_перенаправление события.Допустимо + только для событий Map, + Reparent и Configure.
    + +
    %p
    + +
    Поле размещать события. Строка подстановки имеет + вид PlaceOnTop или + PlaceOnBottom. Допустимо только для событий + Circulate.
    + +
    %s
    + +
    Поле состояние события. Для событий + ButtonPress, ButtonRelease, + Enter, KeyPress, + KeyRelease, Leave и + Motion происходит подстановка десятичного + числа. Для события Visibility подставляется + одна из строк isibilityUnobscured, + VisibilityPartiallyObscured или + VisibilityFullyObscured.
    + +
    %t
    + +
    Поле время события. Допустимо только для событий, + содержащих поле время.
    + +
    %w
    + +
    Поле ширина события. Допустимо только для событий + Configure и Expose.
    + +
    %x
    + +
    Поле x события. Допустимо только для событий, + содержащих поле x.
    + +
    %y
    + +
    Поле y события.Допустимо только для событий, + содержащих поле y.
    + +
    %A
    + +
    Заменяется символом ASCII, отвечающим происшедшему + событию,или пустой строкой, если событию не соответствует + никакой символ ASCII (например, нажата клавиша верхнего + регистра). Работу по переводу события в ASCII символ выполняет + XLookupString. Допустимо только для событий + KeyPress и KeyRelease.
    + +
    %B
    + +
    Поле ширина_бордюра события.Допустимо только для + событий Configure.
    + +
    %E
    + +
    Поле послать_событие события.Допустимо для событий + всех типов.
    + +
    %K
    + +
    Код клавиши, соответствующей данному событию, представленный + текстовой строкой. Допустимо только для событий + KeyPress и KeyRelease.
    + +
    %N
    + +
    Код клавиши, соответствующей данному событию, представленный + десятичным числом. Допустимо только для событий + KeyPress и KeyRelease.
    + +
    %R
    + +
    Идентификатор корневого окна события.Допустимо только для + событий содержащих поле корень.
    + +
    %S
    + +
    Идентификатор подокна события, представленный в виде + шестнадцатиричного числа. Допустимо только для событий + содержащих поле подокно.
    + +
    %T
    + +
    Поле тип события. Допустимо для событий всех + типов.
    + +
    %W
    + +
    Путь к окну, к которому отнесено событие (поле окно + события). Допустимо для событий всех типов.
    + +
    %X
    + +
    Поле x_корень события. При использовании + виртуально-корневого менеджера окон подставляемое значение + равняется x-координате в виртуальном корне. Допустимо только + для событий ButtonPress, + ButtonRelease, KeyPress, + KeyRelease и Motion.
    + +
    %Y
    + +
    Поле y_корень события. При использовании + виртуально-корневого менеджера окон подставляемое значение + равняется y-координате в виртуальном корне. Допустимо только + для событий ButtonPress, + ButtonRelease, KeyPress, + KeyRelease и Motion.
    +
    + +

    Строка подстановки для %-замещения форматируется как обычный + элемент списка Tcl. Это означает, что при наличии в строке + пробелов она заключается в фигурные скобки, а специальным + символам, таким как `$' и `{' может предшествовать обратная + косая черта. Такая строка нормально обрабатывается + синтаксическим анализатором Tcl при выполнении скрипта. Строки + подстановки по большей части являются числами или корректно + определенными строками как, например, Above; + такие строки не нуждаются ни в каком специальном + форматировании. Чаще всего форматирования требуют строки, + замещающие %A. Если, например, скрипт имеет + вид

    + +
    insert %A
    + +

    и вводимым символом является открывающая квадратная скобка, то + реально исполняемым скриптом будет

    + +
    insert \[
    + +

    т.е. в качестве первого аргумента insert + получит исходную строку подстановки (открывающую квадратную + скобку). Если бы обратная косая черта не была добавлена, Tcl не + смог бы правильно обработать скрипт.

    + +

    НЕСКОЛЬКО ПРИВЯЗОК, ОТВЕЧАЮЩИХ ОБРАЗЦУ

    + +

    Данному X событию может отвечать несколько привязок. Если эти + привязки соответствуют различным тегам, то все они + выполняются по очереди. По умолчанию сначала исполняется + привязка для примитива, затем привязка класса, затем привязка + верхнего уровня и привязка all. Этот порядок + для конкретного окна можно поменять с помощью команды bindtags, которая + позволяет также выполнить дополнительные привязки к окну.

    + +

    Управление обработкой скриптов, отвечающих образцу, + осуществляется командами continue и break в + привязанном скрипте. При выполнении команды continue + выполнение текущего привязанного скрипта прерывается и Tk + переходит к выполнению скриптов, соответствующих остальным + тегам. При выполнении команды break выполнение + текущего привязанного скрипта прерывается и никакие другие + скрипты не выполняются.

    + +

    Если данному событию соответствует несколько привязок с одним и + тем же тегом, то из них выбирается наиболее конкретная привязка + и выполняется ее скрипт. Выбор наиболее конкретной привязки + осуществляется по следующим критериям:

    + +
      +
    1. образец события, задающий конкретную кнопку или клавишу, + более конкретен, чем тот, в котором такой спецификации не + задано;
    2. + +
    3. более длинная последовательность (по числу отвечающих + образцу событий) конкретнее более короткой;
    4. + +
    5. если модификаторы первого образца содержатся среди + модификаторов второго, то образец с большим числом + модификаторов более конкретен;
    6. + +
    7. виртуальное событие, физический образец которого + соответствует последовательности, менее конкретно, чем тот же + самый физический образец, не связанный ни с каким виртуальным + событием;
    8. + +
    9. если последовательность отвечает двум или более + виртуальным событиям, то из них выбирается какое-нибудь + одно, однако порядок выбора не определен.

      + +

      Если в подходящей последовательности событий больше одного + события, то критерии 1 - 5 применяются ко всем событиям, + начиная с самого последнего и до самого первого события + последовательности. Если критерии не позволяют определить + победителя, то победителем становится событие, + зарегистрированное последним.

      +
    + +

    Если одна и та же последовательность осуществляет переключение + к двум (или более) виртуальным событиям, и теги окон этих + виртуальных событий совпадают, то переключение произойдет лишь к + одному из этих виртуальных событий, выбранному случайным + образом:

    + +
    +      event add <<Paste>> <Control-y>
    +      event add <<Paste>> <Button-2>
    +      event add <<Scroll>> <Button-2>
    +      bind Entry <<Paste>> {puts Paste}
    +      bind Entry <<Scroll>> {puts Scroll}
    +    
    + +

    При нажатии Control-y будет выполнена привязка + <<Paste>>, а при нажатии кнопки 2 + одна из привязок <<Paste>> или + <<Scroll>>, причем определить какой + именно будет эта привязка, невозможно.

    + +

    Если X событие не подходит ни под одну из существующих + привязок, то событие игнорируется. Наступление не привязанного + события не считается ошибкой.

    + +

    ПОСЛЕДОВАТЕЛЬНОСТИ НЕСКОЛЬКИХ СОБЫТИЙ И ИГНОРИРУЕМЫЕ СОБЫТИЯ

    + +

    Если аргумент последовательность в команде + bind состоит из нескольких образцов событий, то + скрипт выполняется в случае, если последние события (включая + самое последнее) подходят под данную последовательность. Это + означает, например, что при неоднократном последовательном + нажатии кнопки 1 каждое из нажатий, за исключением самого + первого, отвечает образцу + <Doudble-ButtonPress-1>. Если в + последовательности событий происходят посторонние события, то + они игнорируются, за исключением событий + KeyPress и ButtonPress. + Например, нажатия на кнопку 1 будут соответствовать образцу + <Doudble-ButtonPress-1>, даже если их + перемежают события ButtonRelease или + Motion. Кроме того событию + KeyPressможет предшествовать произвольная + последовательность событий KeyPress для + модификаторов, среди которых нет модификаторов, нарушающих + соответствие образцу. Например, последовательности событий + aB отвечает нажатие на клавишу + a, отпускание клавиши a, + нажатие на клавишу Shift и нажатие на клавишу + b, так как нажатие на клавишу модификатора + Shift игнорируется. И, наконец, если + последовательно происходит несколько событий + Motion, то для установления соответствия + привязке берется последнее из них.

    + + +

    ОШИБКИ

    + +

    При возникновении ошибки в процессе исполнения привязанного + скрипта для выдачи сообщения об ошибке используется механизм bgerror. Команда + bgerror + исполняется на верхнем уровне (вне контекста любой из процедур + Tcl).

    + + + + + diff --git a/hlp/ru/tk/bindtags.html b/hlp/ru/tk/bindtags.html new file mode 100644 index 0000000..2161032 --- /dev/null +++ b/hlp/ru/tk/bindtags.html @@ -0,0 +1,38 @@ + + + + bindtags + + + +

    bindtags

    + +

    Команда определяет, какие привязки относятся к окну и порядок + обработки.

    + +

    СИНТАКСИС

    + +
    +      bindtags window ?tagList?
    +    
    + +

    ОПИСАНИЕ

    + +

    Когда с помощью команды bind создается привязка, + ей ставятся в соответствие имя окна, имя класса, ключевое слово + или какая-нибудь строка. Все эти формы называются тегами + привязки (binding tag). Каждое окно имеет список тегов привязки, + определяющих, каким образом обрабатываются события для данного + окна. Когда в окне происходит событие, оно по очереди сличается + с каждым из тегов окна, и для каждого тега исполняется та + привязка, которая более всех соответствует событию и тегу.

    + +

    Команда позволяет получать сведения о привязках окна и + модифицировать их: добавлять новые, удалять и замещать + существующие.

    + + + + + diff --git a/hlp/ru/tk/bitmap.html b/hlp/ru/tk/bitmap.html new file mode 100644 index 0000000..db88088 --- /dev/null +++ b/hlp/ru/tk/bitmap.html @@ -0,0 +1,43 @@ + + + + bitmap + + + +

    bitmap

    + +

    Встроенный тип изображений Tk, имеющих только два цвета.

    + +

    СИНТАКСИС

    + +
    +      image create bitmap name options
    +    
    + +

    ОПИСАНИЕ

    + +

    В терминах языка Tcl/Tk, bitmap - это двухцветное изображение, + пиксели которого могут отображать один из двух заданных цветов + или быть прозрачными. Такое изображение имеет четыре аргумента: + два цвета (переднего плана и фона) и два двоичных файла, + называемых source (источник) и mask + (маска). Оба файла задают значения "0" или + "1" для пикселей прямоугольной области, оба файла + должны быть одной размерности. Пиксели, для которых в маске + задано значение "0", не отображают ничего (получается + эффект прозрачности). Остальные пиксели имеют либо цвет + переднего плана, если значение в source для пикселя + равно "1", либо фоновый цвет в обратном случае.

    + +

    Подобно всем прочим изображениям, двухцветные изображения + создаются при помощи команды image create. При + создании нового bitmap Tk также создает команду + с именем этого изображения. Команда может использоваться для + выполнения различных операций над данным изображением.

    + + + + + + diff --git a/hlp/ru/tk/button.html b/hlp/ru/tk/button.html new file mode 100644 index 0000000..fad3d7b --- /dev/null +++ b/hlp/ru/tk/button.html @@ -0,0 +1,247 @@ + + + + button + + + +

    button

    + +

    Создание примитива кнопки и управление им.

    + +

    СИНТАКСИС

    + +
    +      button имяПути параметры
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activebackground
    • +
    • -activeforeground
    • +
    • -anchor
    • +
    • -background
    • +
    • -bitmap
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -disabledforeground
    • +
    • -font
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -image
    • +
    • -justify
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -takefocus
    • +
    • -text
    • +
    • -textvariable
    • +
    • -underline
    • +
    • -wraplength
    • +
    + +

    Подробное описание этих параметров приведено в разделе + options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ

    + + + + + +
    Имя параметра:-command
    Имя в Базе:command
    Класс в Базе:Command
    + +

    Ассоциирует с кнопкой команду Tk. Обычно команда выполняется + при отпускании клавиши 1 "Мыши".

    + + + + + +
    Имя параметра:-default
    Имя в Базе:default
    Класс в Базе:Default
    + +

    Задает одно из трех состояний изображения ободка кнопки: + normal, active или + disabled. В активном состоянии кнопка имеет + изображение по умолчанию для данной платформы. В нормальном + состоянии кнопка изображается в виде, предусмотренном данной + платформой для кнопок не по умолчанию; при этом остается + достаточно места для изображения кнопки по умолчанию. Нормальное + и активное состояние приводят к появлению кнопок одинакового + размера. Отключенное состояние приводит к выводу кнопки не по + умолчанию, не оставляя при этом места для кнопки по умолчанию. + Кнопка в отключенном состоянии может быть меньше кнопки в + активном состоянии.

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту кнопки. Если в кнопке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); высота текстовой кнопки задается числом + строчек текста. Если параметр не задан, то высота кнопки + вычисляется по ее содержимому.

    + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + +

    Задает одно из трех состояний кнопки: normal, + active или disabled. В + нормальном состоянии кнопка изображается с использованием + значений параметров foreground и + background. В активном состоянии кнопка обычно + находится, если на ней расположен курсор. Кнопка в активном + состоянии изображается с использованием значений параметров + activeForeground и + activeBackground. Отключенное состояние + указывает на то, что кнопка должна быть нечувствительной: + привязки по умолчанию не приводят к запуску примитива и нажатия + на кнопку "Мыши" игнорируются. В этом состоянии + изображение кнопки определяется значениями параметров + disabledForeground и + background. +

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину кнопки. Если в кнопке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); ширина текстовой кнопки задается + числом символов. Если параметр не задан, то ширина кнопки + вычисляется по ее содержимому.

    + +

    ОПИСАНИЕ

    + +

    Команда button создает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив кнопки. + Детали изображения кнопки, такие, как ее цвета, шрифт, текст и + объемный вид задаются с помощью описанных выше дополнительных + параметров. Команда button возвращает аргумент + имяПути. В момент выполнения этой команды не должно + существовать окна с именем имяПути, но должен + существовать его предок.

    + +

    Кнопка представляет собой примитив, в котором выводится + текстовая строка, изображение или двуцветное изображение. Весь + выводимый текст должен быть записан одним шрифтом, однако он + может занимать несколько строчек на экране (если в нем есть + символы перевода строки или задан параметр + wrapLength). Один из символов текста может + быть подчеркнут (в соответствии со значением параметра + underline). В зависимости от значения параметра + button кнопка имеет три разных вида; кнопка + может выглядеть выпуклой, вдавленной или плоской, кроме того, + она может мигать. При инициации кнопки (нажатием на клавишу 1 + "Мыши", когда курсор "Мыши" находится на + кнопке) выполняется команда Tcl, указанная в параметре + -command.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда button создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид.

    + +
    +      имяПути параметр арг арг ...
    +    
    + +

    Параметр и аргументы уточняют поведение команды. + Примитивы кнопки допускают следующие формы команды:

    + +
    +      имяПути cget параметр
    +    
    + +

    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров команды + button.

    + +
    +      имяПути configure параметр значение параметр значение ...
    +    
    + +

    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает список, + содержащий значения всех допустимых в имениПути + параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение - нет, то команда возвращает часть + полного списка, относящуюся к указанному параметру. Если заданы + одна или несколько пар параметр-значение, то указанным + параметрам примитива присваиваются новые значения, а команда + возвращает пустую строку. Параметр может быть любым из + параметров команды button.

    + +
    +      имяПути flash
    +    
    + +

    Заставляет кнопку мигать. Этот эффект достигается путем + многократного вывода изображения кнопки поочередно в активном и + нормальном состоянии. По окончании работы команды кнопка + остается в том же состоянии (активном или нормальном), что и + перед началом ее выполнения. Если перед началом выполнения + команды кнопка находится в состоянии disabled, + то команда игнорируется.

    + +
    +      имяПути invoke
    +    
    + +

    Выполняет команду Tcl, ассоциированную с кнопкой (при наличии + такой команды). Возвращаемое значение совпадает с возвращаемым + значением команды Tcl (или является пустой строкой, если с + кнопкой никакой команды не ассоциировано). Если перед началом + выполнения команды кнопка находится в состоянии + disabled, то команда игнорируется.

    + +

    При создании кнопки Tk, в соответствии с типом кнопки, + автоматически создает привязки к ней, определяющие ее поведение + по умолчанию:

    + +

    Кнопка становится активной при появлении над ней курсора + "Мыши" и дезактивируется, когда курсор ее покидает. В + системе Windows привязка активизируется только при нажатии + клавиши "1" "Мыши" на кнопке.

    + +

    При нажатии клавиши "1" "Мыши" на кнопке + кнопка "вдавливается", а при отпускании клавиши она + восстанавливает свой первоначальный вид.

    + +

    Если на кнопке клавиша "1" "Мыши" была + нажата, а затем отпущена, то выполняется команда, привязанная к + данной кнопке. Этого, однако, не происходит, если в момент + отпускания клавиши "Мыши" курсор "Мыши" + находился вне поля кнопки.

    + +

    Если кнопка находится в фокусе ввода, то нажатие на клавишу + пробела приводит к выполнению команды, привязанной к этой + кнопке.

    + +

    Если кнопка находится в состоянии disabled, то + все описанные выше действия не приводят ни к какому результату: + кнопка остается неактивной.

    + +

    Поведение кнопки можно изменить с помощью новых привязок к + конкретным примитивам или путем переопределения привязок данного + класса.

    + + + + + diff --git a/hlp/ru/tk/canvas.html b/hlp/ru/tk/canvas.html new file mode 100644 index 0000000..502952b --- /dev/null +++ b/hlp/ru/tk/canvas.html @@ -0,0 +1,1908 @@ + + + + canvas + + + +

    canvas

    + +

    Создание примитивов канвы и работа с ними.

    + +

    СИНТАКСИС

    + +
    +      canvas имяПути параметры
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    -background-highlightthickness-insertwidth
    -takefocus-borderwidth-insertbackground
    -relief-xscrollcommand-cursor
    -insertborderwidth-selectbackground-yscrollcommand
    -highlightbackground-insertofftime-selectborderwidth
    -highlightcolor-insertontime-selectforeground
    + +

    Подробное описание параметров приведено в разделе options.

    + +

    ПАРАМЕТРЫ, СВЯЗАННЫЕ ИСКЛЮЧИТЕЛЬНО С ПРИМИТИВАМИ

    + + + + + +
    Имя параметра:-closeenough
    Имя в Базе:closeEnough
    Класс в Базе:CloseEnough
    + +

    Задает значение с плавающей точкой, указывающее расстояние от + курсора до объекта на экране, при котором курсор считается + находящимся внутри объекта. По умолчанию имеет значение 1.0

    + + + + + +
    Имя параметра:-confine
    Имя в Базе:confine
    Класс в Базе:Confine
    + +

    Булевское значение, указывающее, допустимо ли устанавливать вид + канвы вне области, заданной аргументом + scrollRegion. По умолчанию имеет значение + истина, т.е. такая установка запрещена.

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту окна, которое примитив канвы должен + запросить у своего графического менеджера. Значение может иметь + любой вид из описанных ниже (см. "Координаты").

    + + + + + +
    Имя параметра:-scrollregion
    Имя в Базе:scrollRegion
    Класс в Базе:ScrollRegion
    + +

    Задает список из четырех величин, описывающих координаты левой, + верхней, правой и нижней границы прямоугольной области. Эта + область используется для прокрутки и считается границей + информации в канве. Каждая из координат может иметь любой вид из + описанных ниже в (см. "Координаты").

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:width
    + +

    Задает желаемую ширину окна, которое примитив канвы должен + запросить у своего графического менеджера. Значение может иметь + любой вид из описанных ниже (см. Координаты).

    + + + + + +
    Имя параметра:-xscrollincrement
    Имя в Базе:xScrollincrement
    Класс в Базе:Scrollincrement
    + +

    Задает шаг горизонтальной прокрутки в любом из принятых видов + для расстояний на экране. Если указанная величина положительна, + то x-координата левой границы будет выбрана + пропорциональной значению xScrollincrement с + четным коэффициентом пропорциональности. Кроме того, шаг + прокрутки (при нажатии на стрелки влево и вправо полосы + прокрутки) также принимает значение + xScrollincrement. Если значение параметра + не положительно, то прокрутка выполняется без ограничений.

    + + + + + + +
    Имя параметра:-yscrollincrement
    Имя в Базе:yScrollincrement
    Класс в Базе:Scrollincrement
    + +

    Задает шаг вертикальной прокрутки в любом из принятых видов для + расстояний на экране. Если указанная величина положительна, то + y-координата верхней границы будет выбрана + пропорциональной значению yScrollincrement с + четным коэффициентом пропорциональности. Кроме того, шаг + прокрутки (при нажатии на стрелки вверх и вниз полосы прокрутки) + также принимает значение yScrollincrement. Если + значение параметра не положительно, то прокрутка выполняется без + ограничений.

    + +

    ВВЕДЕНИЕ

    + +

    Команда canvas создает новое окно (заданное + аргументом имяПути) и преобразует его в примитив + канвы. С помощью описанных выше дополнительных аргументов в + строке команды или в базе данных параметров можно задать такие + характеристики канвы, как цвета или трехмерное + представление. Команда canvas возвращает свой + аргумент имяПути. В момент исполнения команды окно с + именем имяПути должно отсутствовать, однако его + родительское должно существовать. + +

    Примитивы канвы реализуют структурную графику. Канва изображает + некоторый набор элементов, таких как прямоугольники, + окружности, линии или текстовые элементы. Над элементами можно + выполнять различные действия (например, передвигать или + перекрашивать их), и к ним можно приписывать команды способом, + аналогичным тому, как команда bind привязывает команды к + примитивам. Можно, например, приписать некоторую команду + событию <Button-1>, и эта команда будет + выполняться всякий раз при нажатии кнопки 1 на данном + элементе. Таким образом, поведение элементов канвы может + определяться привязанным к ним скриптам Tcl.

    + + +

    СПИСОК ВЫВОДА

    + +

    Элементы канвы упорядочены, так что при выводе на экран + сначала выводится первый элемент, за ним второй и так + далее. Очередные выводимые элементы заслоняют элементы, уже + выведенные на экран; иногда про них говорят, что они выводятся + поверх первых. При создании нового элемента он заносится на + последнее место в списке, поверх всех элементов, созданных + ранее. Порядок элементов в списке можно поменять с помощью + команд примитивов.

    + +

    Элементы-окна представляют собой исключение из приведенного + правила. Базовая система управления окнами предполагает, что + новое окно всегда выводится поверх всех предыдущих. Кроме того, + команды примитивов канвы не влияют на порядок в стеке окон; + вместо них надо использовать команды Tk raise и lower.

    + +

    ИДЕНТИФИКАТОРЫ И ТЕГИ ЭЛЕМЕНТОВ

    + +

    Есть два способа обращаться к элементам примитивов канвы по + идентификатору и по тегу. У каждого элемента есть свой + уникальный идентификационный номер, присваиваемый при создании + элемента. Идентификатор элемента никогда не изменяется, и ни + один идентификатор не используется дважды на протяжении + существования данного примитива канвы.

    + +

    Кроме того, каждому элементу канвы можно приписать несколько + тегов. Тег это просто строка символов, и он может быть + иметь любой вид кроме числового. Например, "x123" + годится, а "123" нет. Один и тот же тег можно + приписывать нескольким элементам. Обычно это свойство + используется для объединения элементов по характерным + признакам. Например, всем выбранным элементам можно приписать + тег "selected".

    + +

    Тег all приписан по умолчанию всем элементам + канвы; с его помощью выполняются операции на всех элементах + канвы.

    + +

    Тегом current автоматически управляет Tk. Он + относится к текущему элементу, находящемуся поверх всех + остальных из тех, чья область покрывает положение курсора. Если + курсор .Мыши. расположен вне примитива канвы или если он не + накрывается никаким элементом, то тег current + не приписывается никакому элементу.

    + +

    При указании элемента в командах примитивов канвы реализован + следующий подход: если описатель является числом, то это число + интерпретируется как идентификатор элемента. В противном случае + описатель относится ко всем элементам с таким + тегом. Используемый ниже символ тегИлиИд указывает на + то, что соответствующий аргумент может быть тегом, которому + отвечает несколько (быть может, ни одного) элемента, или + идентификатором, которому отвечает единственный + элемент. Некоторые команды примитивов могут работать + одновременно только с одним элементом; если символу + тегИлиИд соответствует несколько элементов, то такая + команда обычно обрабатывает первый (самый нижний) элемент списка + вывода, к которому она применима. Исключения приведены ниже в + описаниях команд примитивов.

    + +

    КООРДИНАТЫ

    + +

    Все координаты канвы записываются в форме чисел с плавающей + точкой. Координаты и расстояния на экране задаются в виде чисел + с плавающей точкой, за которыми может следовать одна или + несколько букв. Если буквы нет, то единицей измерения расстояния + является пиксель. Буква m указывает на + измерение расстояний в миллиметрах; буква c в + сантиметрах; i в дюймах; p в + точках принтера (1/72 дюйма). При перемещении по экрану вниз + y-координата увеличивается; x-координата + возрастает при перемещении по экрану вправо.

    + +

    ПРЕОБРАЗОВАНИЯ

    + +

    Обычно начало системы координат канвы расположено в верхнем + левом углу окна, содержащего канву. Положение начала координат + относительно окна можно изменить с помощью команд + xview и yview. Обычно этой + возможностью пользуются при прокрутке. Канва не позволяет + растягивать систему координат или поворачивать ее по отношению к + системе координат окна.

    + +

    Отдельные элементы канвы можно сдвигать с помощью описываемых + ниже команд примитивов; их можно также растянуть или сжать, но + нельзя повернуть.

    + +

    ИНДЕКСЫ

    + +

    Для указания на отдельные части текста в текстовых элементах + поддерживаются индексы. Индексы используются в командах + вставки текста, удаления части текста, установки курсора ввода. + Индекс можно определить одним из нескольких возможных способов; + различные типы элементов поддерживают индексы различных типов. + Ниже приведено описание видов индексов; при введении новых типов + текстовых элементов имеет смысл обеспечить поддержку разумного + подмножества видов индекса. Отметим, что можно ссылаться на + символ, следующий непосредственно за последним символом + текстового элемента; эта возможность полезна, например, при + вводе нового текста в конец элемента.

    + +
    +
    число
    + +
    Десятичное число, указывающее положение нужного символа + внутри текстового элемента. "0" указывает на первый символ, + 1 на второй и т.д. Отрицательные числа интерпретируются как + 0, а числа, большие длины текстового элемента как если бы они + равнялись этой длине.
    + +
    end
    + +
    Указывает на символ, следующий непосредственно за последним + символом текстового элемента (совпадает с числом символов в + элементе).
    + +
    insert
    + +
    Указывает на символ, непосредственно предшествующий курсору + ввода.
    + +
    sel.first
    + +
    Указывает на первый выделенный символ в элементе. Если в + элементе нет выделенных символов, то такая форма + запрещена.
    + +
    sel.last
    + +
    Указывает на последний выделенный символ в элементе. Если в + элементе нет выделенных символов, то такая форма + запрещена.
    + +
    @x,y
    + +
    Указывает на символ в позиции (x,y), где x + и y заданы в координатной системе канвы. Если + значения координат выходят за пределы, занятые текстовым + элементом, то берется первый или последний символ в строке, + ближайшей к указанной позиции.
    +
    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда canvas создает новую команду Tcl с + именем имяПути. С помощью этой новой команды можно + выполнять различные операции над примитивами. Она имеет + следующий общий вид:

    + +
    +      имяПути параметр аргумент аргумент ...
    +    
    + +

    Параметр и аргументы уточняют поведение команды. В примитивах + канвы могут встречаться следующие команды примитивов:

    + +
    +
    имяПути addtag тег спец_поиска + арг арг ...
    + +

    Добавляет тег к списку тегов, связанному с + каждым элементом, удовлетворяющим ограничениям, заданным + спец_поиска и аргументами (если такого тега в + списке еще нет). Если ни один элемент не удовлетворяет + наложенным ограничениям, то команда не производит никаких + действий. Результатом выполнения команды является пустая + строка. Спец_поиска и аргументы могут принимать + следующие значения:

    + +
    +
    above тегИлиИд
    + +
    Выделяет элемент, непосредственно следующий + (расположенный поверх) за элементом тегИлиИд в + списке вывода. Если аргумент тегИлиИд задает + несколько элементов, то команда выполняется по отношению к + последнему (самому верхнему) из них.
    + +
    all
    + +
    Выделяет все элементы канвы.
    + +
    below тегИлиИд
    + +
    Выделяет элемент, непосредственно предшествующий + (расположенный ниже) элементу тегИлиИд в списке + вывода. Если аргумент тегИлиИд задает + несколько элементов, то команда выполняется по отношению к + первому (самому нижнему) из них.
    + +
    closest x y нимб начало
    + +
    Выделяет элемент, ближайший к точке с координатами + (x,y). Если таких элементов несколько + (например, несколько элементов накрывают эту точку), то + выделяется самый верхний из них. Нимб, если он + задан, должен быть неотрицательным числом. Всякий элемент, + расстояние от которого до точки (x,y) + меньше, чем нимб, считается накрывающим эту + точку. Аргумент начало позволяет обходить по + кругу все ближайшие к точке элементы. Начало, + если оно задано, представляет собой идентификатор или тег + элемента (в случае, если это тег, будет выбран первый + элемент списка, соответствующего данному тегу). В этой + форме выделяется не самый верхний элемент из ближайших, а + самый верхний из тех ближайших элементов, которые ниже + элемента начало в списке вывода. В случае если + таких элементов нет, команда выполняется так же, как и в + отсутствие аргумента начало.
    + +
    enclosed x1 y1 x2 y2
    + +
    Выделяет все элементы, заключенные внутри прямоугольника + с углами (x1,y1) и + (x2,y2). Величина x1 должна + быть не меньше, чем x2, а y1 не меньше, + чем y2.
    + +
    overlapping x1 y1 x2 y2I
    + +
    Выделяет все элементы, перекрывающиеся с прямоугольником + с углами (x1,y1) и + (x2,y2). Величина x1 должна + быть не меньше, чем x2, а y1 не меньше, + чем y2.
    + +
    withtag тегИлиИд
    + +
    Выделяет все элементы, заданные тегИлиИд.
    +
    + +
    имяПути bbox тегИлиИд + тегИлиИд тегИлиИд
    + +
    Возвращает список из четырех элементов приближенных значений + координат прямоугольника, ограничивающего все элементы, + заданные аргументами тегИлиИд. Список имеет вид + x1 y1 x2 y2, причем экранные представления + элементов находятся в области, ограниченной слева вертикальной + прямой с координатой x1, справа вертикальной прямой с + координатой x2, сверху горизонтальной прямой с + координатой y1, снизу горизонтальной прямой с + координатой y2. Значения координат могут отличаться + от точных на несколько пикселей. Если под описание + тегИлиИд не подходит ни один элемент или если у этих + элементов прямоугольники вывода пусты, то команда возвращает + пустую строку.
    + +
    имяПути bind + тегИлиИд последовательность команда
    + +

    Эта команда привязывает ко всем элементам, заданным + аргументом тегИлиИд, команду, которая выполняется + всякий раз при наступлении события, описываемого + последовательностью, на одном из этих элементов. Эта команда + похожа на команду bind, + за исключением того, что она действует на элементах канвы, а + не на целых примитивах. Синтаксис последовательности и + подстановки, выполняемые в команде перед ее выполнением, + подробно описаны в bind. Если в команде + заданы все аргументы, то создаваемая привязка замещает все + предыдущие привязки для той же последовательности и + тегИлиИд (если первый символ в команде +, то новая + привязка присоединяется к уже существующим, а не замещает + их). В этом случае команда возвращает пустую строку. Если + аргумент команда опущен, то возвращается строка команды, + связанной с тегИлиИд и последовательностью + (если такой команды нет, то возникает ошибка). Если опущены + оба аргумента команда и последовательность, то результатом + выполнения служит список всех последовательностей, для + которых определена привязка к тегИлиИд.

    + +

    Привязки можно задавать только для событий, связанных с + клавиатурой или "Мышью" (таких как + Enter, Leave, + ButtonPress, Motion и + KeyPress), а также для виртуальных событий. + При работе с событиями в канве используется текущий элемент, + определенный выше (см. "Идентификаторы и теги + элементов"). События Enter и + Leave наступают, когда элемент становится + или перестает быть текущим; обратите внимание на отличие + этих событий от событий Enter и + Leave для окон. События, связанные с + "Мышью", наступают только для текущего элемента + (если таковой имеется; подробности см. ниже в описании + команды примитива focus). При использовании в + привязке виртуального события привязка может подключиться + только, если в определении этого виртуального события + участвует событие, связанное с "Мышью" или + клавиатурой.

    + +

    Данному событию может соответствовать несколько привязок. + Такое может произойти, например, если одна привязка + осуществляется к идентификатору события, а другая к одному + из его тегов. В подобном случае выполняются все привязанные + события. Первым идет скрипт, привязанный к тегу + all, затем поочередно выполняются скрипты, + привязанные к каждому из тегов элемента (в порядке их + следования), последней идет привязка к идентификатору + элемента. Если несколько привязок соответствует одному тегу, + то выполняется лишь самая конкретная из них. Команда continue в + скрипте прекращает его выполнение, команда break + прекращает выполнение скрипта и всех последующих скриптов + для события, как и в случае команды bind.

    + +

    Если с помощью команды bind к окну канвы были + выполнены дополнительные привязки, то они выполняются после + привязок к элементам канвы, выполненных командой примитива + bind.

    +
    + +
    имяПути canvasx xЭкрана + шагСетки
    + + +
    По заданной x-координате xЭкрана окна + возвращает x-координату канвы, расположенной на этом + месте. Если задан шагСетки, то координата канвы + округляется к ближайшему кратному единиц + шагаСетки.
    + +
    имяПути canvasy yЭкрана + шагСетки
    + +
    По заданной y-координате yЭкрана окна + возвращает y-координату канвы, расположенной на этом + месте. Если задан шагСетки, то координата канвы + округляется к ближайшему кратному единиц + шагаСетки.
    + +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации, + заданного аргументом параметр.
    + +
    имяПути cоnfigure параметр + значение параметр значение ...
    + +
    Сообщает текущие параметры конфигурации примитива или + модифицирует их. Если параметр не задан, то + возвращает список всех текущих значений параметров + имениПути (формат списка приведен в описании + Tk_ConfigureInfo). Если параметр + задан без указания значения, то команда возвращает список, + описывающий указанный параметр (этот список совпадает с частью + списка, возвращаемого при отсутствии параметра). Если заданы + одна или несколько пар параметр-значение, то команда + присваивает указанным параметрам примитива данные значения; + результатом ее выполнения в этом случае служит пустая + строка. Параметр может принимать любые + значения, воспринимаемые командой + canvas.
    + +
    имяПути coords тегИлиИд x0 y0 + ...
    + +
    Сообщает текущие значения координат, определяющих элемент, + или модифицирует их. Если координаты не заданы, то возвращает + список, составленный из координат элемента, указанного + аргументом тегИлиИд. Если координаты заданы, то их + значения замещают текущие значения координат означенного + элемента. Если тегИлиИд указывает на + несколько элементов, то команда выполняется для идущего первым + в списке вывода.
    + +
    имяПути create типx y x y + ... параметр значение ...
    + +
    Создает в имяПути новый элемент типа тип. Формат + аргументов, следующих за аргументом тип, зависит от значения + типа, однако обычно эти аргументы представляют собой + координаты одной или нескольких точек, за которыми следуют + спецификации нескольких параметров элемента (быть может, ни + одного). Подробнее синтаксис этой команды описан ниже (см. + "Описания различных типов").
    + +
    имяПути dchars тегИлиИд первый + последний
    + +
    Удаляет символы с первого по последний + включительно в каждом элементе, подходящем под описание + тегИлиИд. Если какие-либо из этих элементов не + поддерживают текстовых операций, то они + пропускаются. Аргументы первый и последний + должны быть индексами символов в элементе, заданными в + соответствии с описанием, приведенным в разделе "Индексы". При опущенном аргументе + последний его значение принимается по умолчанию + равным значению первый. Команда возвращает пустую + строку.
    + +
    имяПути delete тегИлиИд + тегИлиИд ...
    + +
    Удаляет все элементы, подходящие под описание, заданное + аргументами, и возвращает пустую строку.
    + +
    имяПути dtag тегИлиИд + тегДляУдаления
    + +
    Удаляет все теги тегДляУдаления из списка тегов, + ассоциированного с каждым из элементов, описываемых аргументом + тегИлиИд. Если ни один из тегов такого элемента не + входит в тегДляУдаления, то никаких действий не + производится. Если аргумент тегДляУдаления + отсутствует, то его значение по умолчанию совпадает с + тегИлиИд. Команда возвращает пустую строку.
    + +
    имяПути find командаПоиска арг + арг ...
    + +
    Команда возвращает список, состоящий из всех элементов, + удовлетворяющих критериям поиска, заданным аргументами + командаПоиска и арг. Аргументы + командаПоиска и арг могут иметь любой вид, + воспринимаемый командой addtag. Список + элементов представлен в виде стека, в котором нижний элемент + идет последним.
    + +
    имяПути focus тегИлиИд
    + +

    Устанавливает фокус клавиатуры для примитива канвы на + элементе, заданном аргументом тегИлиИд. Если под + описание подходят несколько элементов, то фокус + устанавливается на тот из них, который идет первым в списке + вывода из элементов, поддерживающих курсор ввода. Если под + описание не подходит ни один из элементов или если ни один + из подходящих элементов не поддерживает курсор ввода, то + фокусировка не меняется. Если тегИлиИд представляет + собой пустую строку, то ни один из элементов не оказывается + в фокусе. Если аргумент тегИлиИд не задан, то + команда возвращает идентификатор элемента, находящегося в + фокусе или пустую строку, если такого элемента нет.

    + +

    После установки фокуса на элемент в этом элементе будет + отображаться курсор ввода и все клавиатурные события будут + направлены на этот элемент. Элемент фокусировки канвы и окно + фокусировки на экране (установленное командой focus) + совершенно независимы: элемент находится в фокусе ввода + только если (а) его канва является окном фокусировки и (б) + сам элемент является элементом фокусировки канвы. В + большинстве случаев полезно вслед за командой focus примитива выполнять + команду focus, чтобы + установить фокус на канве (если такая установка еще не была + произведена).

    +
    + +
    имяПути gettags тегИлиИд
    + +
    Возвращает список, элементами которого служат теги, + ассоциированные с элементом, подходящим под описание + тегИлиИд. Если под это описание подходят несколько + элементов, то список относится к тому из них, который идет + первым в списке вывода. Если элементов, подходящих под + описание нет или если у подходящего элемента нет тегов, то + команда возвращает пустую строку.
    + +
    имяПути icursor тегИлиИд + индекс
    + +
    Устанавливает курсор ввода для элемента (элементов), + подходящего под описание тегИлиИд, в положение, + непосредственно предшествующее символу, заданному аргументом + индекс. Если некоторые (быть может, все) подходящие + элементы не поддерживают курсор ввода, то над ними никаких + действий не производится. Допустимые формы аргумента + индекс описаны выше (см. "Индексы"). Замечание: фактическое + высвечивание курсора ввода в элементе производится только, + если этот элемент находится в фокусе (см. описание команды + примитива focus), однако + положение курсора можно установить и в элементе вне + фокуса. Команда возвращает пустую строку.
    + +
    имяПути insert тегИлиИд + передЭтим строка
    + +
    Вставляет строку перед символом, заданным + аргументом передЭтим, в каждом из элементов, + подходящих под описание тегИлиИд и поддерживающих + курсор ввода. Возможные формы аргумента передЭтим + описаны выше (см. Индексы). Команда + возвращает пустую строку.
    + +
    имяПути itemcget тегИлиИд + параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр для элемента тегИлиИд. Команда + аналогична команде примитива cget, за исключением того, что + она относится к отдельному элементу, а не к примитиву в + целом. Значение параметра может быть любым, допустимым для + команды примитива create, используемой для создания + элемента. Если тег тегИлиИд описывает несколько + элементов, то команда применяется к первому из них.
    + +
    имяПути itemconfigure тегИлиИд + параметр значение параметр значение ...
    + +
    Команда аналогична команде примитива + configure за исключением того, что она + изменяет значения параметров элементов, а не всего примитива + канвы. Если аргумент параметр не задан, то команда + возвращает список значений параметров для первого элемента, + подходящего под описание тегИлиИд (формат списка + описан в Tk_ConfigureInfo). Если аргумент + параметр задан, а аргумент значение + отсутствует, то команда возвращает список значений только + указанного параметра (этот список является подсписком списка, + возвращаемого в отсутствие аргумента параметр). Если + задано несколько пар параметр-значение, то команда + устанавливает новые значения указанных параметров для каждого + из элементов тегИлиИд; в этом случае команда + возвращает пустую строку. Допустимые формы параметров + и значений такие же, как в команде примитива + create, которая создает элементы. Допустимые + параметры и возможные их значения описаны ниже (см. описание + отдельных типов элементов).
    + +
    имяПути lower + тегИлиИд нижеЭтого
    + +
    Передвигает все элементы, подходящие под описание + тегИлиИд, в списке вывода непосредственно перед + элементом, заданным аргументом нижеЭтого. Если под + описание подходят несколько элементов, то они передвигаются + все, причем их относительный порядок сохраняется. Аргумент + нижеЭтого представляет собой тег или идентификатор; + если он описывает несколько элементов, то для размещения + тегИлиИд используется первый из них. Замечание: на + элементы окон эта команда влияния не оказывает. Элементы окон + перекрывают элементы других типов и на порядок их расположения + влияют команды raise + и lower, а не + команды raise и lower + примитивов канвы. Команда возвращает пустую строку.
    + + +
    имяПути move тегИлиИд + xКоличество yКоличество
    + +
    Сдвигает каждый из элементов, подходящих под описание + тегИлиИд, прибавляя к координатам каждой точки + элемента координаты xКоличество и + yКоличество. Команда возвращает пустую строку. +
    + +
    имяПути postscript параметр + значение параметр значение ...
    + +

    Генерирует Postscript-представление для каждой канвы или для + некоторых из них. Если параметр имеет вид + -file, то Postscript-представление + записывается в указанный файл, а команда возвращает пустую + строку; в противном случае возвращается сгенерированное + Postscript-представление. Если интерпретатор, владеющий + канвой, помечен как безопасный, то операция закончится + неудачно, так как безопасным интерпретаторам не разрешается + записывать файлы. Если задан параметр + -channel, то аргументом является имя канала, + открытого на вывод. Postscript-представление записывает в этот + канал; по окончании выполнения команды канал остается открытым + для последующих операций вывода. Postscript-представление + создается в форме Encapsulated Postscript в соответствии с + соглашением Documentation Structuring Conventions, + v. 3.0. Замечание: по умолчанию Postscript-представление + создается только для информации, выводимой в окно канвы на + экране. Только что созданная канва имеет размер 1x1 пиксель, + поэтому в Postscript ничего выведено не будет. Чтобы + преодолеть эту трудность, необходимо либо выполнить команду + update и дождаться пока окно достигнет своего нормального + размера, либо задать размеры канвы для печати параметрами + -width и -height. Пары + аргументов параметр-значения используются для + дополнительного управления характеристиками печати. Команда + поддерживает следующие параметры:

    + +
    +
    -colormap имяПеременной
    + +
    ИмяПеременной должно быть именем массива, + описывающего палитру в Postscript. Значение каждого + элемента этого массива должно кодировать установку в + Postscript определенного цвета, например, 1.0 1.0 + 0.0 setrgbcolor.. При выводе информации о цвете + в Postscript Tk проверяет, есть ли в массиве + имяПеременной элемент с таким же именем цвета. + Если это так, то Tk использует значение этого элемента как + команду Postscript для установки цвета. Если параметр + -colormap не указан или если данному + цвету не соответствует никакой элемент массива, то Tk + берет интенсивность красного, голубого или зеленого X + цвета.
    + +
    -colormode режим
    + +
    Задает способ вывода цветовой информации. + Режим может принимать значения + color (для полноцветного вывода), + gray (преобразует все цвета к их серому + аналогу), mono (переводит каждый цвет в + черный или белый).
    + +
    -file имяФайла
    + +
    Задает имя файла вывода. Если этот параметр не указан, + то команда возвращает результирующее + Postscript-представление вместо записи его в файл.
    + +
    -fontmap имяПеременной
    + +
    ИмяПеременной должно быть именем массива, + описывающего преобразование шрифтов. Каждый элемент + массива должен представлять собой Tcl список из двух + элементов имени и размера шрифта. При выводе Postscript + команд для конкретного шрифта Tk проверяет, описан ли в + массиве имяПеременной элемент с соответствующим + именем. Если такой элемент есть, то в Postscript + используется информация, содержащаяся в нем. В противном + случае Tk пытается догадаться о том, какой шрифт + использовать. Обычно эти попытки удаются только для + стандартных шрифтов, таких как Times, Helvetica и Courier, + и только в случае, если в имени X шрифта не пропущено ни + одного дефиса перед размером. Так, например, имя + -*_-Courier-Bold-R-Normal--*_-120-*_ + будет воспринято нормально, а + *Courier-Bold-R-Normal*120* нет; дефисы + нужны Tk для распознавания имени шрифта.
    + +
    -height размер
    + +
    Задает высоту печатаемого поля канвы. По умолчанию имеет + значение высоты окна канвы.
    + +
    -pageanchor якорь
    + +
    Указывает, какая из выводимых точек канвы должна попасть + в опорную точку страницы печати (заданную параметрами + -pagex и + -pagey). Например, задание + -pageanchor n означает, что при печати + верхняя центральная точка окна канвы располагается в + опорной точке страницы. По умолчанию параметр имеет + значение center.
    + +
    -pageheight размер
    + +
    Указывает на необходимость растяжения страницы печати в + горизонтальном и вертикальном направлении так, чтобы + напечатанная в Postscript страница имела высоту + размер. Значением параметра должно быть число + с плавающей точкой, за которым следует символ + c, если размер указан в сантиметрах, + i в дюймах, m в + миллиметрах, p или ничего в точках + принтерах (1/72 часть дюйма). По умолчанию имеет + значение высоты выводимой области экрана. Если заданы + оба параметра -pageheight и + -pagewidth, то для растяжения + используется значение параметра + -pagewidth (возможность неравномерного + растяжения в двух направлениях не предусмотрена).
    + +
    -pagewidth размер
    + +
    Указывает на необходимость растяжения страницы печати в + горизонтальном и вертикальном направлении так, чтобы + напечатанная в Postscript страница имела ширину + размер. Параметр может принимать такие же + значения, что и параметр -pageheight. По + умолчанию имеет значение ширины выводимой области + экрана. Если заданы оба параметра + -pageheight и + -pagewidth, то для растяжения + используется значение параметра + -pagewidth (возможность неравномерного + растяжения в двух направлениях не предусмотрена).
    + +
    -pagex координата
    + +
    Указывает x-координату опорной точки + Postscript-страницы в любом виде, приемлемом для + -pageheight. В сочетании с параметрами + -pagey и -pageanchor + позволяет задать размещение выводимой области на + Postscript-странице. По умолчанию задает координату центра + страницы.
    + +
    -pagey координата
    + +
    Указывает y-координату опорной точки + Postscript-страницы в любом виде, приемлемом для + -pageheight. В сочетании с параметрами + -pagex и -pageanchor + позволяет задать размещение выводимой области на + Postscript-странице. По умолчанию задает координату центра + страницы.
    + +
    -rotate булевское
    + +
    Булевское значение указывает, следует ли при печати + повернуть страницу на 90 градусов. При обычном выводе ось + x идет вдоль короткой стороны страницы (ориентация + "портрет"); после поворота она идет вдоль + длинной стороны (ориентация "пейзаж"). По + умолчанию страница печатается без поворота.
    + +
    -width размер
    + +
    Задает ширину печатаемого поля канвы. По умолчанию имеет + значение ширины окна канвы.
    + +
    -x координата
    + +
    Задает x-координату левого края печатаемой + области канвы (в координатах канвы, а не окна). По + умолчанию совпадает с координатой левого края окна.
    + +
    -y координата
    + +
    Задает y-координату верхнего края печатаемой + области канвы (в координатах канвы, а не окна). По + умолчанию совпадает с координатой верхнего края окна.
    + +
    + +
    имяПути raise + тегИлиИд вышеЭтого
    + +
    Передвигает все элементы, подходящие под описание + тегИлиИд, в списке вывода непосредственно за элемент, + заданный аргументом вышеЭтого. Если под описание + подходят несколько элементов, то они передвигаются все, причем + их относительный порядок сохраняется. Аргумент + вышеЭтого представляет собой тег или идентификатор; + если он описывает несколько элементов, то для размещения + тегИлиИд используется последний (самый верхний) из + них. Замечание: на элементы окон эта команда влияния не + оказывает. Элементы окон перекрывают элементы других типов и + на порядок их расположения влияют команды raise и lower, а не + команды raise и lower примитивов канвы. Команда возвращает + пустую строку.
    + +
    имяПути scale тегИлиИд xЦентр + yЦентр xКоэффициент yКоэффициент
    + +
    Растягивает или сжимает все элементы, подходящие под + описание тегИлиИд в координатном пространстве канвы. + Аргументы xЦентр и yЦентр задают координаты + центра преобразования, а xКоэффициент и + yКоэффициент коэффициенты растяжения по осям + x и y соответственно (значение + 1.0 указывает на отсутствие растяжения). Расстояние по оси + x каждой точки, задающей положение элемента, от + центра растяжения увеличивается в xКоэффициент + раз. Аналогично, расстояние по оси y каждой точки, + задающей положение элемента, от центра растяжения + увеличивается в yКоэффициент раз. Команда возвращает + пустую строку.
    + +
    имяПути scan параметр + аргументы
    + +
    Используется для сканирования канвы. Имеет две формы в + зависимости от значения параметра:
    + +
    имяПути scanmark x y
    + +
    Сохраняет x, y и текущий вид канвы для последующего + использования командами scan dragto. Обычно + эта команда используется в сочетании с нажатием клавиши + "Мыши" в примитиве, а x и y + являются координатами курсора "Мыши". Возвращает + пустую строку.
    + +
    имяПути scan dragto x y
    + +
    Вычисляет разность между значениями координат x и + y и значениями тех же координат, сохраненными + последней командой scan mark на данном + примитиве. Затем переносит изображение примитива на + расстояние, в 10 раз превышающее вычисленную разность. Команда + обычно связана с событиями движения "Мыши" в примитиве и + используется для скоростного перетаскивания канвы в его + окне. Возвращает пустую строку.
    + +
    имяПути select параметр + тегИлиИд аргумент
    + +
    Производит действия над выделенными элементами тем или иным + способом в зависимости от значения параметра. Команда может + иметь одну из описанных ниже форм. В каждой из приведенных + форм тегИлиИд должен описывать элемент, допускающий + индексирование и выделение; если под описание подходит + несколько элементов, то используется первый из них, + допускающий индексирование и выделение. Индекс + представляет собой текстовое указание позиции в + тегИлиИд (см. описание в "Индексы").
    + +
    имяПути select adjust тегИлиИд + индекс
    + +
    Определяет ближайший к указанному аргументом индекс + положению край набора выделенных элементов в тегИлиИд + и устанавливает новое значение этого края в индекс + (т.е. элемент индекс входит в выделение, а соседний с + ним нет). Противоположный край выделения становится опорной + точкой для последующих команд select to. Если + в текущий момент в тегИлиИд выделения отсутствуют, то + команда ведет себя точно так же, как команда примитива + select to. Возвращает пустую строку.
    + +
    имяПути select clear
    + +
    Очищает выделенные элементы в данном примитиве. Если таких + элементов нет, то не производит никаких действий. Возвращает + пустую строку.
    + +
    имяПути select from тегИлиИд + индекс
    + +
    Устанавливает опорную точку выделения непосредственно перед + символом, заданным аргументом индекс. Текущего + выделения команда не меняет. Она лишь фиксирует начало + выделения для последующих команд select + to. Возвращает пустую строку.
    + +
    имяПути select item
    + +
    Возвращает идентификатор выделенного элемента, если + выделение представляет собой элемент канвы. Если в данной + канве выделение отсутствует, то команда возвращает пустую + строку.
    + +
    имяПути select to тегИлиИд + индекс
    + +
    Выделяет все символы между опорным символом выделения и + символом, указанным аргументом индекс, включая этот + символ. Опорный символ включается в выделение, только если + значение аргумента индекс больше номера опорного + символа. Опорный символ устанавливается последней выполненной + на данном примитиве командой select adjust + или select from. Если опорный символ + выделения в примитиве не входит в элемент, описываемый + аргументом тегИлиИд, то опорная точка устанавливается + на символ, указанный аргументом индекс. Команда возвращает + пустую строку.
    + +
    имяПути type тегИлиИд
    + +
    Возвращает тип элемента, описываемого аргументом + тегИлиИд (например, rectangle или + text). Если тегИлиИд описывает + несколько элементов, то возвращается тип первого из них. Если + ни один элемент не подходит под описание тегИлиИд, + то команда возвращает пустую строку.
    + +
    имяПути xview + аргументы
    + +

    Используется для запроса горизонтального положения + информации, выведенной в окне канвы, и изменения этого + положения. Команда может иметь одну из следующих форм:

    + +
    +
    имяПути xview
    + +
    Возвращает список, состоящий из двух элементов. Каждый + из элементов списка представляет собой вещественное число, + заключенное между нулем и единицей; эта пара чисел + описывает видимый в окне горизонтальный интервал. Так, + например, если первое число равно .2, а второе .6, то + 20% области канвы оказывается невидимой слева от окна, в + окне выводится 40% информации, и еще 40% оказывается + невидимой справа от окна.
    + +
    имяПути xview moveto + число
    + +
    Передвигает область видимости так, что слева от + окна остается невидимой часть канвы, указанная аргументом + число. Число должно быть заключено между 0 и 1 +
    + +
    имяПути xview scroll + количество что
    + +
    Сдвигает выводимый в окне текст вправо или влево, + выравнивая его границу в соответствии со значениями + аргументов. Количество должно быть целым числом, + аргумент что может принимать значения + units или pages или быть + сокращением одного из этих слов. Если аргумент + что принимает значение units, то + выравнивание происходит относительно единиц, указанных + значением параметра xScrollIncrement + (если это значение положительно), или относительно десятой + части ширины окна (в противном случае). Если значением + аргумента что является pages, то + единицей выравнивания служит величина в девять десятых + ширины окна. Если количество отрицательно, то + видимая информация сдвигается вправо, в противном случае + влево.
    +
    +
    + +
    имяПути yview + аргументы
    + +

    Используется для запроса вертикального положения + информации, выведенной в окне канвы, и изменения этого положения. + Команда может иметь одну из следующих форм:

    + +
    +
    имяПути yview
    + +
    Возвращает список, состоящий из двух элементов. Каждый + из элементов списка представляет собой вещественное число, + заключенное между нулем и единицей; эта пара чисел + описывает видимый в окне вертикальный интервал. Так, + например, если первое число равно .6., а второе 1.0, то в + окне выводятся нижние 40% области канвы (заданной + значением параметра -scrollregion). Эти + значения совпадают со значениями, передаваемыми полосам + прокрутки через параметр -yscrollcommand. +
    + +
    имяПути yview moveto + число
    + +
    Передвигает область видимости так, что сверху от окна + остается невидимой часть канвы, указанная аргументом + число. Число должно быть заключено между 0 и + 1.
    + +
    имяПути yview scroll + количество что
    + +
    Сдвигает выводимый в окне текст вверх или вниз, + выравнивая его границу в соответствии со значениями + аргументов. Количество должно быть целым числом, + аргумент что может принимать значения + units или pages или быть + сокращением одного из этих слов. Если аргумент + что принимает значение units, то + выравнивание происходит относительно единиц, указанных + значением параметра yScrollIncrement + (если это значение положительно), или относительно десятой + части высоты окна (в противном случае). Если значением + аргумента что является pages, то + единицей выравнивания служит величина в девять десятых + высоты окна. Если количество отрицательно, то + видимая информация сдвигается вниз, в противном случае + вверх. +
    +
    +
    +
    + +

    ОБЗОР ТИПОВ ЭЛЕМЕНТОВ

    + +

    Ниже описываются различные типы элементов, поддерживаемые + примитивами канвы. Каждый тип характеризуется, во-первых, формой + команды create, посредством которой создаются + элементы этого типа, и, во-вторых, набором параметров + конфигурации элементов этого типа, которые можно использовать в + командах примитива create и + itemconfigure. Большинство типов не + поддерживают выделение и индексирование и связанные с этими + операциями команды, такие как index или + insert. Для типов, поддерживающих указанные + возможности, они описаны явно (пока речь идет только о текстовых + элементах).

    + +

    ДУГИ

    + +

    Элементы типа arc выводятся на экран в виде + отрезка дуги. Дуга представляет собой отрезок овала, + заключенный между двумя радиусами (заданными параметрами + -start и -extent); она + изображается на экране в одном из нескольких возможных видов в + зависимости от значения параметра -style. Дуги + создаются командами примитива.

    + +
    +
    имяПути create arc x1 y1 x2 y2 + параметр значение параметр значение ...
    + +

    Аргументы x1 y1 x2 y2 задают координаты + противоположных углов прямоугольной области, в которую вписан + овал. За координатами следует несколько пар + параметр-значение, каждая из которых устанавливает + значение одного из параметров конфигурации элемента. Такие же + пары параметр-значение используются командами + примитива itemconfigure для изменения + параметров конфигурации. Команда поддерживает следующие + параметры:

    + +
    +
    -extent угол
    + +
    Задает величину сектора, содержащего дугу. Дуга + простирается на угол, отсчитываемый от начальной + точки дуги, заданной параметром + -start. Угол может быть и + отрицательным. Если его величина превосходит 360 градусов + или оказывается меньше -360 градусов, то берется его + значение по модулю 360.
    + +
    -fill цвет
    + +
    Закрашивает цветом область, ограниченную + дугой. Аргумент цвет может принимать любое + значение, воспринимаемое командой + Tk_GetColor. Если значением + цвета является пустая строка, то закрашивания не + происходит. Пустая строка также принимается значением + параметра по умолчанию.
    + +
    -outline цвет
    + +
    Цвет задает цвет контура дуги. Этот параметр может + принимать любое значение, воспринимаемое командой + Tk_GetColor. По умолчанию параметр имеет + значение black. Если в качестве параметра + задана пустая строка, то контур дуги не изображается.
    + +
    -outlinestipple двуцвет
    + +
    Указывает, что контур дуги должен изображаться в + соответствии с образцом пунктира. Аргумент + двуцвет указывает этот образец, он может + принимать любое значение, воспринимаемое командой + Tk_GetBitmap. Если параметр -outline не + задан, то задание параметра + -outlinestipple не влияет на вывод. Если + значением данного параметра является пустая строка, то + дуга будет рисоваться сплошной линией.
    + +
    -start угол
    + +
    Задает положение начала сектора, содержащего + дугу. Угол задается в градусах и отсчитывается + против часовой стрелки от 3-часового положения часовой + стрелки. Он может быть как положительным, так и + отрицательным.
    + +
    -stipple двуцвет
    + +
    Указывает необходимость закрашивания области дуги в + соответствии с образцом пунктира. Допустимы любые + значения, воспринимаемые командой + Tk_GetBitmap. Если параметр + -fill не задан, то параметр + -stipple не оказывает влияния на + вывод. Если значением параметра -stipple + является пустая строка, то выполняется сплошное + закрашивание.
    + +
    -style тип
    + +
    Задает тип изображения дуги. Если тип имеет + значение pieslice (по умолчанию), то + область дуги имеет вид сектора, ограниченного дугой и + двумя радиусами, проведенными из центра овала к ее + концам. Тип chord указывает на то, что + область имеет вид сегмента, ограниченного дугой и + отрезком, соединяющим ее концы. Тип arc + означает, что область дуги состоит из самой этой дуги. В + последнем случае параметр -fill + игнорируется.
    + +
    -tags списокТегов
    + +
    Задает набор тегов, относящихся к элементу. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов + может быть пустым.
    + +
    -width ширинаКонтура
    + +
    Задает ширину контура вокруг области дуги; значением + параметра может быть любое допустимое значение координат, + описанное выше (см. "Координаты"). Если значением + параметра -outline является пустая + строка, то параметр -width не влияет на + характер вывода. Широкий контур центрируется на отрезках, + ограничивающих область дуги. По умолчанию параметр имеет + значение 1.0 .
    +
    +
    +
    + +

    ДВУЦВЕТНЫЕ ЭЛЕМЕНТЫ

    + +

    Элементы типа bitmap изображаются на экране с + помощью двух цветов: цвета фона и цвета переднего плана, + Двуцветные изображения создаются командой примитива

    + +
    +
    имяПути create bitmap x y + параметр значение параметр значение ...
    + +

    Аргументы x и y задают координаты опорной + точки двуцветного изображения на экране (подробнее процедура + размещения изображения описана ниже при описании параметра + -anchor). За координатами следует несколько + пар параметр-значение, каждая из которых + устанавливает значение одного из параметров конфигурации + элемента. Такие же пары параметр-значение + используются для изменения значений параметров с помощью + команды примитива itemconfigure. Для + двуцветных изображений допустимы следующие параметры:

    + +
    +
    -anchor положениеОпоры
    + +
    ПоложениеОпоры указывает способ размещения + изображения по отношению к его опорной точке. Параметр + может принимать произвольное значение, воспринимаемое + командой Tk_GetAnchor. Так, если параметр + имеет значение center, то в опорной точке + располагается центр изображения; значение + n указывает, что в опорной точке + располагается верхняя центральная точка изображения и + т.д. По умолчанию параметр имеет значение + center.
    + +
    -background цвет
    + +
    Задает цвет, используемый для отображения пикселей + двуцветного изображения со значением 0. Параметр может + принимать любое значение, воспринимаемое командой + Tk_GetColor. Если параметр не задан или + цвет является пустой строкой, то пиксели со + значением 0 не выводятся, что создает эффект + прозрачности.
    + +
    -bitmap двуцвет
    + +
    Задает двуцветное изображение для вывода в + элементе. Параметр может принимать любое значение, + воспринимаемое командой + Tk_GetBitmap.
    + +
    -foreground цвет
    + +
    Задает цвет пикселей двуцветного изображения, имеющих + значение .1.. Параметр может принимать любое значение, + воспринимаемое командой Tk_GetColor; по + умолчанию его значение black.
    + +
    -tags списокТегов
    + +
    Приписывает элементу список тегов. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов может быть + пустым. +
    +
    +
    +
    + +

    ЛИНИИ

    + +

    Элементы типа line выводятся на экран в виде + прямо- или криволинейной ломаной. Линии создаются командой + примитива

    + +
    +
    имяПути create line x1 y1 + ... xn yn параметр значение параметр значение ...
    + +

    Аргументы от x1 до yn задают координаты + последовательности из двух или более точек, соединенных + отрезками. За координатами может следовать произвольный набор + пар параметр-значение, каждая из которых + устанавливает значение одного из параметров элемента. С + помощью тех же пар параметр-значения можно задать + новые значения параметров командами примитива + itemconfigure. Команда поддерживает + следующие параметры:

    + +
    +
    -arrow где
    + +
    Указывает, следует ли изображать стрелки на одном или + обоих концах линии. Значение где может быть одним + из следующих: none (стрелки не + изображаются), first (изображается + стрелка в начале линии), last + (изображается стрелка в конце линии) или + both (стрелка изображается на обоих + концах).
    + +
    -arrowshape форма
    + +
    Описывает форму стрелки. Значением параметра должен быть + список, содержащий три элемента, каждый из которых + представляет собой расстояние в виде, описанном выше + (см. "Координаты"). + Первый элемент списка задает расстояние вдоль линии от + начала до острия стрелки. Второй элемент задает + расстояние вдоль линии от хвостовых концов стрелки до ее + острия, третий расстояние от внешнего ребра линии до + хвостовых точек. Если параметр не задан, то Tk + самостоятельно выбирает "разумную" форму + стрелки.
    + +
    -capstyle стиль
    + +
    Описывает способ изображения концов линии в отсутствие + стрелок. Параметр может принимать любое значение, + воспринимаемое командой Tk_GetCapstyle + (butt, projecting или + round). По умолчанию имеет значение + butt. При наличии стрелок параметр + игнорируется.
    + +
    -fill цвет
    + +
    Задет цвет изображаемой линии. Параметр может принимать + любое значение, воспринимаемое командой + Tk_GetColor. Если значением параметра + является пустая строка, то линия будет прозрачной. По + умолчанию цвет имеет значение black.
    + +
    -joinstyle стиль
    + +
    Задает способ соединения отрезков линии в + вершинах. Параметр может принимать любое значение, + воспринимаемое командой Tk_GetCapstyle + (bevel, miter или + round). По умолчанию имеет значение + miter. При наличии всего двух вершин + параметр игнорируется.
    + +
    -smooth булевское
    + +
    Параметр может принимать любое значение, воспринимаемое + командой Tk_GetBoolean. Указывает, нужно + ли сглаживать ломаную, превращая ее в кривую (в этом + случае линия изображается в виде набора параболических + сплайнов: для первого и второго отрезка, для второго и + третьего отрезка и т.д.). В кривую можно вставлять + прямолинейные отрезки, удваивая нужные вершины.
    + +
    -splinesteps число
    + +
    Задает желаемую степень гладкости кривой: каждый сплайн + будет аппроксимирован числом прямолинейных + отрезков. При опущенном параметре -spline + параметр -splinesteps игнорируется.
    + +
    -stipple двуцвет
    + +
    Указывает на необходимость пунктирного изображения + линии; двуцвет задает образец изображения в виде, + воспринимаемом командой + Tk_GetBitmap. Если значением параметра + является пустая строка (как, например, по умолчанию), то + линия изображается непрерывной кривой.
    + +
    -tags списокТегов
    + +
    Приписывает к элементу набор тегов. + СписокТегов представляет собой список имен тегов, + замещающих все имеющиеся теги элемента. Он может быть + пустым.
    + +
    -width ширинаЛинии
    + +
    Задает ширину линии в произвольном виде, описанном выше + (см. "Координаты"). + Центр широкой линии проходит через вершины. По умолчанию + параметр имеет значение 1.0.
    +
    +
    +
    + +

    ОВАЛЫ

    + +

    Элементы типа oval появляются на экране в виде + овальных или круглых областей. Каждый овал может быть + закрашенным и иметь контур. Овалы создаются командой примитива

    + +
    +
    имяПути create oval x1 y1 x2 + y2 параметр значение параметр значение ...
    + +

    Аргументы x1, y1, x2 и + y2 задают координаты двух диагонально противоположных + углов прямоугольника, заключающего овал. Овал включает в себя + верхнюю и левую стороны прямоугольника, но не его нижнюю и + правую сторону. Если прямоугольник представляет собой квадрат, + то овал будет кругом, в противном случае он вытянут в одном из + направлений. За координатами может следовать произвольный + набор пар параметр-значение, каждая пара + устанавливает значение одного из параметров. Такие же пары + используются командами примитива + itemconfigure для изменения конфигурации + элемента. Команда поддерживает следующие параметры:

    + +
    +
    -fill цвет
    + +
    Закрашивает цветом область, ограниченную + овалом. Аргумент цвет может принимать любое + значение, воспринимаемое командой + Tk_GetColor. Если значением + цвета является пустая строка, то закрашивания не + происходит. Пустая строка также принимается значением + параметра по умолчанию.
    + +
    -outline цвет
    + +
    Цвет задает цвет контура овала. Этот параметр может + принимать любое значение, воспринимаемое + командойTk_GetColor. По умолчанию + параметр имеет значение black. Если в + качестве параметра задана пустая строка, то контур овала + не изображается.
    + +
    -stipple двуцвет
    + +
    Указывает на необходимость закрашивания внутренности + овала в соответствии с образцом пунктира. Допустимы любые + значения, воспринимаемые командой + Tk_GetBitmap. Если параметр + -fill не задан, то параметр + -stipple не оказывает влияния на + вывод. Если значением параметра -stipple + является пустая строка (по умолчанию), то выполняется + сплошное закрашивание.
    + +
    -tags списокТегов
    + +
    Задает набор тегов, относящихся к элементу. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов + может быть пустым.
    + +
    -width ширинаКонтура
    + +
    Задает ширину контура вокруг овала; значением параметра + может быть любое допустимое значение координат, описанное + выше (см. "Координаты"). Если параметр + -outline не задан, то параметр + -width не влияет на характер + вывода. Широкий контур центрируется на овале, заданном + координатами x1, y1, x2, + y2. По умолчанию параметр имеет значение + 1.0.
    +
    +
    +
    + +

    МНОГОУГОЛЬНИКИ

    + + +

    Элементы типа polygon выводятся на экран в + виде закрашенных многоугольных (возможно, криволинейных) + областей. Многоугольники задаются командами примитива

    + +
    +
    имяПути create polygon x1 y1 ... xn yn + параметр значение параметр значение ...
    + +

    Аргументы с x1 до yn задают координаты не + менее чем трех точек, определяющих замкнутый + многоугольник. Первая и последняя точки могут совпадать; вне + зависимости от того, так это или нет, Tk изображает замкнутый + многоугольник. За координатами может следовать несколько пар + параметр-значение, каждая из которых устанавливает + один из параметров конфигурации элемента. Те же пары + параметр-значение могут быть использованы в команде + примитива itemconfigure для изменения + конфигурации элемента. Команда поддерживает следующие + параметры:

    + +
    +
    -fill цвет
    + +
    Задет цвет закраски многоугольника. Параметр может + принимать любое значение, воспринимаемое командой + Tk_GetColor. Если значением параметра + является пустая строка, то многоугольник будет + прозрачным. По умолчанию цвет имеет значение + black.
    + +
    -outline цвет
    + +
    Цвет задает цвет контура многоугольника. Этот + параметр может принимать любое значение, воспринимаемое + командой Tk_GetColor. Если в качестве + значения параметра задана пустая строка (по умолчанию), то + контур овала не изображается.
    + +
    -smooth булевское
    + +
    Параметр может принимать любое значение, воспринимаемое + командой Tk_GetBoolean. Указывает, нужно + ли сглаживать многоугольник, превращая его в кривую (в + этом случае кривая изображается в виде набора + параболических сплайнов: для первого и второго отрезка, + для второго и третьего отрезка и т.д.). В кривую можно + вставлять прямолинейные отрезки, удваивая нужные + вершины.
    + +
    -splinesteps число
    + +
    Задает желаемую степень гладкости кривой: каждый сплайн + будет аппроксимирован числом прямолинейных + отрезков. При опущенном параметре -smooth + параметр -splinesteps игнорируется.
    + +
    -stipple двуцвет
    + +
    Указывает на необходимость пунктирного закрашивания + многоугольника; двуцвет задает образец + изображения в виде, воспринимаемом командой + Tk_GetBitmap. Если значением параметра + является пустая строка (как, например, по умолчанию), то + осуществляется непрерывное закрашивание.
    + +
    -tags списокТегов
    + +
    Приписывает к элементу набор тегов. + СписокТегов представляет собой список имен тегов, + замещающих все имеющиеся теги элемента. Он может быть + пустым.
    + +
    -width ширинаКонтура
    + +
    Задает ширину контура вокруг многоугольника в + произвольном виде, описанном выше (см. "Координаты"). Если параметр + -outline не задан, то параметр + -width игнорируется. По умолчанию + параметр имеет значение 1.0.
    +
    +
    +
    + +

    Многоугольные элементы отличаются от других прямоугольников, + овалов и дуг в том отношении, что их внутренние точки считаются + находящимися "внутри" многоугольника (например, в + смысле команд примитива find closest и + find overlapping), даже если он и не + закрашен. Для большинства остальных типов элементов внутренние + точки считаются находящимися внутри элемента, только если + элемент закрашен или если он не закрашен и не имеет контура. + Если Вам нужен незакрашенный многоугольник, внутренние точки + которого не считаются находящимися внутри него, то пользуйтесь + вместо этого элементом line.

    + +

    ПРЯМОУГОЛЬНИКИ

    + +

    Элементы типа rectangle появляются на экране в + виде прямоугольных областей. Каждый прямоугольник может быть + закрашенным и иметь контур. Прямоугольники создаются командой + примитива

    + +
    +
    имяПути create rectangle x1 y1 + x2 y2 параметр значение параметр значение ...
    + +

    Аргументы x1, y1, x2 и y2 задают + координаты двух диагонально противоположных углов + прямоугольника (верхняя и левая стороны прямоугольника входят + в него, а нижняя и правая сторона нет). За координатами может + следовать произвольный набор пар параметр-значение, + каждая пара устанавливает значение одного из параметров. Такие + же пары используются командами примитива + itemconfigure для изменения конфигурации + элемента. Команда поддерживает следующие параметры:

    + +
    +
    -fill цвет
    + +
    Закрашивает цветом прямоугольную область. + Аргумент цвет может принимать любое значение, + воспринимаемое командой Tk_GetColor. Если + значением цвета является пустая строка, то + закрашивания не происходит. Пустая строка также + принимается значением параметра по умолчанию.
    + +
    -outline цвет
    + +
    Цвет задает цвет контура прямоугольника. Этот + параметр может принимать любое значение, воспринимаемое + командой Tk_GetColor. По умолчанию + параметр имеет значение black. Если в + качестве параметра задана пустая строка, то контур + прямоугольника не изображается.
    + +
    -stipple двуцвет
    + +
    Указывает на необходимость закрашивания прямоугольника в + соответствии с образцом пунктира. Допустимы любые + значения, воспринимаемые командой + Tk_GetBitmap. Если параметр + -fill не задан, то параметр + -stipple не оказывает влияния на + вывод. Если значением параметра -stipple + является пустая строка (по умолчанию), то выполняется + сплошное закрашивание.
    + +
    -tags списокТегов
    + +
    Задает набор тегов, относящихся к элементу. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов + может быть пустым.
    + +
    -width ширинаКонтура
    + +
    Задает ширину контура вокруг прямоугольника; значением + параметра может быть любое допустимое значение координат, + описанное выше (см. ""Координаты""). Если параметр + -outline не задан, то параметр + -width не влияет на характер + вывода. Широкий контур центрируется на прямоугольнике, + заданном координатами x1, y1, + x2, y2. По умолчанию параметр имеет + значение 1.0.
    +
    +
    +
    + +

    ТЕКСТОВЫЕ ЭЛЕМЕНТЫ

    + +

    Текстовый элемент предназначен для вывода на экран строки + символов в одну или несколько строчек. Текстовые элементы + поддерживают индексы и выделение, и на них могут быть выполнены + команды примитива канвы dchars, + focus, icursor, + index, insert, + select. Текстовые элементы создаются командой + примитива

    + +
    +
    имяПути create text x y + параметр значение параметр значение ...
    + +

    Аргументы x и y задают координаты точки, + используемой для размещения текста на экране (подробнее + размещение текста описано ниже при описании параметров). За + координатами могут следовать несколько пар + параметр-значение, каждая из которых устанавливает + значение одного из параметров конфигурации элемента. Такие же + пары используются командами примитива + itemconfigure для изменения конфигурации + элемента. Команда поддерживает следующие параметры:

    + +
    +
    -anchor положениеОпоры
    + +
    ПоложениеОпоры указывает способ размещения + текста по отношению к его опорной точке. Параметр может + принимать произвольное значение, воспринимаемое командой + Tk_GetAnchor. Так, если параметр + имеет значение center, то в + опорной точке располагается центр текста; значение + n указывает что в опорной точке + располагается верхняя центральная точка текста и т.д. По + умолчанию параметр имеет значение + center.
    + +
    -fill цвет
    + +
    Закрашивает цветом символы текста. Аргумент + цвет может принимать любое значение, + воспринимаемое командой + Tk_GetColor. Значением параметра по + умолчанию является black.
    + +
    -font имяШрифта
    + +
    Задает шрифт текста в элементе. ИмяШрифта может + быть произвольной строкой, воспринимаемой командой + Tk_GetFontStruct. Если параметр не задан, + то его значением по умолчанию является системно-зависимый + шрифт.
    + +
    -justify как
    + +
    Задает способ выравнивания текста внутри области + текста. Аргумент как может принимать одно из + значений left, right или + center. Параметр оказывает влияние на + размещение текста, только если выводится несколько + строчек. По умолчанию параметр имеет значение + left.
    + +
    -stipple двуцвет
    + +
    Указывает на необходимость вывода текста в соответствии + с образцом пунктира. Допустимы любые значения, + воспринимаемые командой + Tk_GetBitmap. Если значением параметра + -stipple является пустая строка (по + умолчанию), то текст выводится сплошной линией.
    + +
    -tags списокТегов
    + +
    Задает набор тегов, относящихся к элементу. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов + может быть пустым.
    + +
    -width длинаСтрочки
    + +
    Задает максимальную длину строчки текста; значением + параметра может быть любое допустимое значение координат, + описанное выше (см. "Координаты"). Если значение + параметра равно нулю (по умолчанию), то перенос строки + происходит только при появлении в тексте символа новой + строчки. Если, однако, значение параметра не равно нулю, + то концом строчки, длина которой превосходит + длинуСтрочки, считается символ пробела с номером, + ближайшим (с недостатком) к длинеСтрочки. Этот + символ пробела рассматривается как символ перехода на + новую строчку.
    +
    +
    +
    + +

    ОКНА

    + +

    Элементы типа window предназначены для вывода + окна в указанное положение на канве. Окна создаются командой

    + +
    +
    имяПути create window x y + параметр значение параметр значение ...
    + +

    Аргументы x и y задают координаты точки, + используемой для размещения окна на экране (подробнее + размещение текста описано ниже при описании параметра + -anchor). За координатами могут следовать + несколько пар параметр-значение, каждая из которых + устанавливает значение одного из параметров конфигурации + элемента. Такие же наборы параметр-значение + используются для изменения значений параметров с помощью + команды примитива itemconfigure. Окна + поддерживают следующие параметры:

    + +
    +
    -anchor положениеОпоры
    + +
    ПоложениеОпоры указывает способ размещения окна + по отношению к опорной точке элемента. Параметр может + принимать произвольное значение, воспринимаемое командой + Tk_GetAnchor. Так, если параметр имеет + значение center, то в опорной точке + располагается центр текста; значение n + указывает что в опорной точке располагается верхняя + центральная точка текста и т.д. По умолчанию параметр + имеет значение center.
    + +
    -height пиксели
    + +
    Задает высоту окна элемента. Аргумент пиксели + может иметь вид, описанный выше (см. "Координаты"). Если + параметр не задан или если его значением является пустая + строка, то высота окна определяется его содержимым.
    + +
    -tags списокТегов
    + +
    Задает набор тегов, относящихся к элементу. + СписокТегов представляет собой список имен тегов, + замещающий имеющиеся теги элемента. СписокТегов + может быть пустым.
    + +
    -width пиксели
    + +
    Задает ширину окна элемента. Аргумент пиксели + может иметь вид, описанный выше (см. "Координаты"). Если параметр не + задан или если его значением является пустая строка, то + ширина окна определяется его содержимым.
    + +
    -window имяПути
    + +
    Приписывает данному элементу окно. Окно, заданное + аргументом имяПути, должно быть либо потомком + примитива канвы, либо потомком одного из наследников + примитива канвы. ИмяПути может и не указывать + окно верхнего уровня.
    +
    +
    +
    + +

    Замечание. Ограничения на управление окнами не + позволяют выводить графические элементы (такие, как кривые и + двуцветные изображения) поверх окон.

    + +

    ТИПЫ ЭЛЕМЕНТОВ, ОПРЕДЕЛЯЕМЫЕ В ПРИЛОЖЕНИЯХ

    + +

    В конкретных приложениях можно определять новые типы элементов + для примитивов канвы с помощью C кода. Описание этой возможности + приведено в документации для Tk_CreateItem.

    + +

    ПРЕДПОЧТЕНИЯ

    + +

    В текущей реализации новая канва не имеет никакого поведения + по умолчанию; для определения этого поведения необходимо явно + выполнить команды Tcl.

    + + + + + diff --git a/hlp/ru/tk/checkbutton.html b/hlp/ru/tk/checkbutton.html new file mode 100644 index 0000000..0d529bf --- /dev/null +++ b/hlp/ru/tk/checkbutton.html @@ -0,0 +1,351 @@ + + + + checkbutton + + + +

    checkbutton

    + + +

    Создание примитива защелкивающейся кнопки и управление им.

    + + +

    СИНТАКСИС

    + +
    +      checkbutton имяПути параметры
    +    
    + + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activebackground
    • +
    • -activeforeground
    • +
    • -anchor
    • +
    • -background
    • +
    • -bitmap
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -disabledforeground
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -image
    • +
    • -justify
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -takefocus
    • +
    • -text
    • +
    • -textvariable
    • +
    • -underline
    • +
    • -wraplength
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-command
    Имя в Базе:command
    Класс в Базе:Command
    + +

    Ассоциирует с кнопкой команду Tk. Обычно команда выполняется + при отпускании клавиши 1 "Мыши" на кнопке. Перед + выполнением этой команды обновляется значение глобальной + переменной (параметр -variable).

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту кнопки. Если в кнопке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); высота текстовой кнопки задается числом + строчек текста. Если параметр не задан, то высота кнопки + вычисляется по ее содержимому.

    + + + + + +
    Имя параметра:-indicatoron
    Имя в Базе:indicatorOn
    Класс в Базе:IndicatorOn
    + +

    Указывает, следует ли выводить индикатор. Значение параметра + должно быть булевским. Если значением является "ложь", то + параметр relief игнорируется и примитив всегда + изображается вдавленным, если он выделен, и выпуклым в противном + случае.

    + + + + + +
    Имя параметра:-offvalue
    Имя в Базе:offValue
    Класс в Базе:OffValue
    + +

    Задает значение, которое нужно сохранять в переменной кнопки + всякий раз при прекращении выделения кнопки. По умолчанию + сохраняемое значение равно 0.

    + + + + + +
    Имя параметра:-onvalue
    Имя в Базе:onValue
    Класс в Базе:OnValue
    + + +

    Задает значение, которое нужно сохранять в переменной кнопки всякий раз + при выделении кнопки. По умолчанию сохраняемое значение равно 1.

    + + + + + +
    Имя параметра:-selectcolor
    Имя в Базе:selectColor
    Класс в Базе:SelectColor
    + + +

    Задает цвет фона для изображения выделенной кнопки. Если параметр + IndicatorOn имеет значение истина, то указанный цвет + применяется для изображения индикатора. В системе Windows тот же цвет + используется в качестве фона изображения индикатора вне зависимости от + состояния выделения. Если значением параметра IndicatorOn + является ложь, то указанный цвет используется в качестве фона для всего + примитива, когда он выделен, вместо значений параметров + background и activeBackground.

    + + + + + +
    Имя параметра:-selectimage
    Имя в Базе:selectImage
    Класс в Базе:SelectImage
    + +


    + Задает изображение, выводимое в кнопке при выделении кнопки + проверки (вместо изображения, заданного параметром -image). Если + параметр -image отсутствует, то значение параметра + -selectimage игнорируется.
    +

    + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + +

    Задает одно из трех состояний защелкивающейся кнопки: + normal, active или + disabled. В нормальном состоянии + защелкивающаяся кнопка изображается с использованием значений + параметров foreground и + background. В активном состоянии + защелкивающаяся кнопка обычно находится, если на ней расположен + курсор. Защелкивающаяся кнопка в активном состоянии изображается + с использованием значений параметров activeForeground и + activeBackground. Отключенное состояние указывает на то, + что кнопка должна быть нечувствительной: привязки по умолчанию + не приводят к запуску примитива и нажатия на кнопку + "Мыши" игнорируются. В этом состоянии изображение кнопки + определяется значениями параметров disabledForeground и + background.

    + + + + + +
    Имя параметра:-variable
    Имя в Базе:variable
    Класс в Базе:Variable
    + +

    Задает имя глобальной переменной, в которой хранится информация + о том, выделена или нет данная кнопка. По умолчанию совпадает с + именем кнопки (т.е. с последним элементом имени пути окна + кнопки).

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину кнопки. Если в кнопке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); ширина текстовой кнопки задается числом + символов. Если параметр не задан, то ширина кнопки вычисляется по + ее содержимому.

    + +

    ОПИСАНИЕ

    + +

    Команда checkbutton создает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив + защелкивающейся кнопки. Детали изображения защелкивающейся + кнопки, такие как ее цвета, шрифт, текст и объемный вид задаются + с помощью описанных выше дополнительных параметров. Команда + button возвращает аргумент имяПути. В момент + выполнения этой команды не должно существовать окна с именем + имяПути, но должен существовать его предок.

    + +

    Защелкивающаяся кнопка представляет собой примитив, в котором + выводится текстовая строка, изображение или двуцветное + изображение, а также квадратик, называемый индикатором. + Весь выводимый текст должен быть записан одним шрифтом, однако + он может занимать несколько строчек на экране (если в нем есть + символы перевода строки или задан параметр wrapLength). + Один из символов текста может быть подчеркнут (в соответствии со + значением параметра underline). Защелкивающаяся кнопка + обладает всеми характеристиками обычной кнопки, включая + следующие: в зависимости от значения параметра button + кнопка имеет три разных вида; кнопка может выглядеть выпуклой, + вдавленной или плоской, кроме того, она может мигать. При + инициации защелкивающейся кнопки (нажатием на клавишу 1 "Мыши", + когда курсор "Мыши" находится на кнопке) выполняется команда + Tcl, указанная в параметре -command.

    + +

    Кроме того, защелкивающиеся кнопки можно выделять. Если + защелкивающаяся кнопка выделена, то индикатор обычно + изображается как выделенный, а переменная Tcl, ассоциированная с + данной кнопкой, имеет предписанное значение (обычно 1). В ОС + Unix индикатор изображается вдавленным и имеет специальный + цвет. В системе Windows вместо этого в индикаторе стоит + галочка. Если защелкивающаяся кнопка не выделена, то индикатор + имеет невыделенный вид, а ассоциированная переменная имеет + другое значение (обычно 0). В ОС Unix такой индикатор + изображается выпуклым и не имеет специального цвета. В системе + Windows в невыделенном индикаторе отсутствует галочка. По + умолчанию имя переменной, ассоциированной с защелкивающейся + кнопкой, совпадает с именем, использующимся при создании самой + кнопки. Имя переменной и записываемые в ней значения + выделенная/невыделенная можно поменять с помощью параметров + командной строки или в базе данных параметров. С помощью + параметров конфигурации можно также поменять вид индикатора (или + даже отменить саму необходимость его вывода). По умолчанию + выделение защелкивающейся кнопки меняется при последовательных + щелчках кнопки. Кроме того, каждая защелкивающаяся кнопка + отслеживает значение своей глобальной переменной и изменяет свое + состояние всякий раз при перемене этого значения с .выделенная. + на невыделенная и обратно.

    + + +

    КОМАНДА ПРИМИТИВА

    + + +

    Команда checkbutton создает новую команду Tcl с именем + имяПути. С помощью этой команды можно выполнять различные + операции над примитивом. Ее общий вид:

    +
    + +
    имяПути параметр арг арг ...
    + +

    Параметр и аргументы уточняют + поведение команды. Примитивы защелкивающейся кнопки допускают + следующие формы команды:

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с + именем параметр. Параметр может быть любым + из параметров команды checkbutton.
    + +
    имяПути configure параметр значение параметр + значение ...
    + +
    Запрашивает значения параметров конфигурации + примитива или изменяет их. Если параметр не указан, + то возвращает список, содержащий значения всех допустимых + в имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр задан, + а его новое значение нет, то команда возвращает + часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения, а команда возвращает пустую + строку. Параметр может быть любым из параметров + команды checkbutton.
    + +
    имяПути deselect
    + +
    Отменяет выделение защелкивающейся кнопки и + устанавливает значение "не выделена" ассоциированной + переменной.
    + +
    имяПути flash
    + +
    Заставляет защелкивающуюся кнопку мигать. Этот эффект + достигается путем многократного вывода изображения кнопки + поочередно в активном и нормальном состоянии. По окончании + работы команды защелкивающаяся кнопка остается в том же + состоянии (активном или нормальном), что и перед началом + ее выполнения. Если перед началом выполнения команды + защелкивающаяся кнопка находится в состоянии + disabled, то команда игнорируется.
    + +
    имяПути invoke
    + +
    Приводит в точности к тому же результату, что и нажатие + клавиши "Мыши" на защелкивающейся кнопке: кнопка + становится выделенной и выполняется команда Tcl, + ассоциированная с кнопкой (при наличии такой + команды). Возвращаемое значение совпадает с возвращаемым + значением команды Tcl (или является пустой строкой, если с + защелкивающейся кнопкой никакой команды не + ассоциировано). Если перед началом выполнения команды + защелкивающаяся кнопка находится в состоянии + disabled, то команда игнорируется.
    + +
    имяПути toggle
    + +
    Выделяет кнопку, перерисовывая ее в новом состоянии и + изменяя значение ассоциированной переменной.
    +
    +
    +
    + +

    ПРЕДПОЧТЕНИЯ

    + + +

    При создании защелкивающейся кнопки Tk, в соответствии с типом + кнопки, автоматически формирует параметры, определяющие ее + поведение по умолчанию:

    +
      +
    • В ОС Unix кнопка становится активной при появлении над ней + курсора "Мыши" и дезактивируется, когда курсор ее + покидает. В системах Mac и Windows при нажатии клавиши 1 + "Мыши" на защелкивающейся кнопке кнопка + активизируется, когда курсор "Мыши" находится на + кнопке и становится неактивной, когда курсор ее покидает.
    • + +
    • При нажатии клавиши 1 "Мыши" на защелкивающейся + кнопке кнопка становится выделенной и выполняется команда, + привязанная к ней.
    • + +
    • Если защелкивающаяся кнопка находится в фокусе ввода, то + нажатие на клавишу пробела приводит к выполнению команды, + привязанной к этой кнопке.
    • + +
    • В системе Windows имеются дополнительные привязки клавиш: плюс + (+) и знак равенства (=) выделяют кнопку, а минус (-) + отменяет выделение.
    • + +
    • Если защелкивающаяся кнопка находится в состоянии + disabled, то все описанные выше действия не + приводят ни к какому результату: кнопка остается + неактивной.
    • + +
    • Поведение защелкивающейся кнопки можно изменить с помощью + новых связей для конкретных примитивов или путем переопределения + связей данного класса.
    • +
    + + + + + diff --git a/hlp/ru/tk/clipboard.html b/hlp/ru/tk/clipboard.html new file mode 100644 index 0000000..eb8a8b6 --- /dev/null +++ b/hlp/ru/tk/clipboard.html @@ -0,0 +1,85 @@ + + + + clipboard + + + +

    clipboard

    + +

    Управление буфером временного хранения Tk.

    + +

    СИНТАКСИС

    + +
    +      clipboard параметр арг арг
    +    
    + +

    ОПИСАНИЕ"

    + +

    Команда обеспечивает Tcl интерфейс с буфером временного + хранения Tk, в котором хранятся данные для последующего + использования с помощью механизма выделения. Для копирования + данных в буфер необходимо вызвать очистку буфера, а затем одну + или несколько команд добавления данных в буфер. Полное + обновление буфера достигается, если все добавления произведены + до завершения события. Первый аргумент определяет формат + последующих аргументов и поведение команды. В настоящее время + поддерживаются следующие формы команды:

    + +
    +
    clipboard clear -displayof окно
    + +
    Заявляет права на буфер в окне и удаляет текущее + содержимое буфера. Значением параметра окно по + умолчанию является ".". Команда возвращает пустую строку.
    + +
    clipboard append -displayof окно -format + формат -type тип -- данные
    + +

    Добавляет данные к содержимому буфера окна в + виде, заданном параметром тип, и представлении, + заданном параметром формат, а также заявляет права на + буфер в окне.

    + +

    Параметр тип задает вид, в котором должно + возвращаться выделение; его значение должно быть именем + атома, например, STRING или FILE_NAME; детали описания см. в + (1). Параметр тип по умолчанию имеет значение + STRING.

    + +

    Аргумент формат задает представление, в котором + выделение передается по запросу (см (1). второй столбец в + Таблице 2); по умолчанию его значение STRING. В + формате STRING выделение передается в виде строки + 8-битовых символов ASCII. В формате ATOM данные + разделяются на поля, отделенные друг от друга пробелами; + каждое поле преобразуется в значение своего атома, а вместо + имени атома передается его 32-битовое значение. Во всех + других форматах данные делятся на поля, + отделенные друг от друга пробелами, каждое поле + преобразуется в 32-битовое целое число; затем массив целых + чисел передается тому, кто запросил выделение. При этом + передаваемые в буфер строки объединяются перед + преобразованием, поэтому необходимо позаботиться заранее о + соответствующем обрамлении их пробелами. Все добавки в + буфер одного типа должны иметь одинаковый формат.

    + +

    Аргумент формат необходим исключительно для + обеспечения совместимости пользователям буфера, не + использующим Tk. При выводе результатов поиска в выделении + CLIPBOARD с помощью инструментов Tk значение буфера + переводится в строковый формат, поэтому значение аргумента + формат не играет роли.

    + +

    С помощью аргумента указывается конец списка параметров: + следующий за ним аргумент всегда интерпретируется как + данные. Такая возможность полезна, например, если + данные начинаются символом "-".

    +
    +
    + + + + + diff --git a/hlp/ru/tk/destroy.html b/hlp/ru/tk/destroy.html new file mode 100644 index 0000000..2cba42e --- /dev/null +++ b/hlp/ru/tk/destroy.html @@ -0,0 +1,30 @@ + + + + destroy + + + +

    destroy

    + +

    Команда удаляет окна.

    + +

    СИНТАКСИС

    + +
    +      destroy window window
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда удаляет одно или несколько заданных аргументами + window окон и всех их потомков. Окна удаляются в порядке + перечисления, и если при удалении очередного окна произойдет + ошибка, то команда прекращает работу без удаления оставшихся + окон. Если удалить окно ".", то будет разрушено все + приложение.

    + + + + + diff --git a/hlp/ru/tk/entry.html b/hlp/ru/tk/entry.html new file mode 100644 index 0000000..a5c5a6d --- /dev/null +++ b/hlp/ru/tk/entry.html @@ -0,0 +1,579 @@ + + + + entry + + + +

    entry

    + +

    Создание примитива поля ввода текста и управление им.

    + + + +

    СИНТАКСИС

    + +
    +      entry имяПути параметры
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -exportselection
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -inserborderwidth
    • +
    • -insertbackground
    • +
    • -insertofftime
    • +
    • -insertontime
    • +
    • -insertwidth
    • +
    • -justify
    • +
    • -relief
    • +
    • -selectbackground
    • +
    • -selectborderwidth
    • +
    • -selectforeground
    • +
    • -takefocus
    • +
    • -textvariable
    • +
    • -xscrollcommand
    • +
    + +

    Подробное описание этих параметров приведено в options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-show
    Имя в Базе:show
    Класс в Базе:Show
    + + + +

    Если этот параметр задан, то истинное содержимое поля не + выводится на экране. Вместо этого каждый символ текста + заменяется первым символом значения параметра + -show, скажем *. Такая возможность полезна, + например, при вводе в поле пароля. Если символы поля ввода были + выделены и скопированы в другом месте, то выводиться будет + скопированная информация, а не истинное содержимое поля + ввода.

    + + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + + + +

    Задает одно из двух состояний поля ввода: + normal или + disabled. Отключенное состояние указывает на + то, что значение поля ввода нельзя изменить с помощью команд + примитива. При этом курсор ввода в поле не отображается, даже + если этот примитив оказался в фокусе ввода.

    + + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + + +

    Задает желаемую ширину окна поля ввода в виде целого + числа. Если введенное значение не положительно, то ширина поля + устанавливается такой, чтобы в него в точности помещался текст + его текущего значения.

    + + +

    ОПИСАНИЕ

    + +

    Команда entry создает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив поля + ввода. Детали изображения кнопки, такие как ее цвета, шрифт и + объемный вид, задаются с помощью описанных выше дополнительных + параметров. Команда entry возвращает аргумент + имяПути. В момент выполнения этой команды не должно + существовать окна с именем имяПути, но должно + существовать его родительское окно.

    + + +

    Поле ввода представляет собой примитив, предназначенный для + вывода одной строки текста и редактирования ее с помощью + описываемых ниже команд примитива, которые по большей части + сводятся к нажатию клавиш на клавиатуре и действиям с + "Мышью". При создании поля ввода его строка текста + пуста. Часть содержимого поля можно выделить, совершив действия, + описываемые ниже. Экспорт выделенного текста (см. описание + параметра exportSelection) осуществляется по + стандартному протоколу X11 для выделений; выделения в поле ввода + имеют тип STRING. Поля ввода также подчиняются + стандартным правилам Tk обращения с фокусом ввода. Когда поле + ввода находится в фокусе ввода, в нем изображается курсор + ввода , который указывает, где будут вставляться вводимые + символы.

    + + +

    Поля ввода могут работать и с длинными строками, которые не + помещаются полностью в окне примитива. С помощью описываемых + ниже команд содержимое окна можно изменить. Поля ввода + взаимодействуют с полосами прокрутки с помощью стандартного + механизма xScrollCommand (подробно механизм + взаимодействия описан при описании параметра + xScrollCommand). Кроме того, они обеспечивают + возможность сканирования (см. описание ниже).

    + + +

    КОМАНДА ПРИМИТИВА

    + + +

    Команда entry создает новую команду Tcl с именем + имяПути. С помощью этой команды можно выполнять различные + операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр арг арг ...
    +    
    + +

    Параметр и аргументы уточняют поведение + команды.

    + +

    Аргументами многих команд примитива поля ввода служат + индексы. Индекс задает положение конкретного символа в строке + поля ввода. Он может иметь один из следующих видов: + +

    +
    число
    +
    Задает номер символа в строке. Первый символ строки имеет + номер "0"
    + +
    anchor
    + +
    Задает опорную точку выделения, которая используется + командами примитива select from и + select adjust.
    + +
    end
    + +
    Указывает положение символа непосредственно после последнего + символа строки в поле ввода. Указание этого индекса + равносильно указанию длины строки.
    + +
    insert
    + +
    Указывает на символ, находящийся непосредственно за курсором + ввода.
    + +
    sel.first
    + +
    Указывает на первый из выделенных символов. Эта форма + индекса недопустима, если выделение не расположено в окне поля + ввода.
    + +
    sel.last
    + +
    Указывает на последний из выделенных символов. Эта форма + индекса недопустима, если выделение не расположено в окне поля + ввода.
    + +
    @число
    + +
    В этом случае число трактуется как x-координата в + окне поля ввода; указывает на символ с этой x-координатой. + Например, "@0" указывает на самый левый + символ в окне ввода.
    +
    + +

    Вместо любой из указанных форм можно использовать ее + сокращение, например, "e" или + "sel.f". Как правило, значения + индексов, выходящие за пределы допустимых, заменяются ближайшими + допустимыми значениями.

    + + +

    Примитивы поля ввода допускают следующие команды:

    + +
    + +
    имяПути bbox индекс
    + +
    Возвращает список из четырех элементов, описывающий клетку, + занимаемую символом, указанным параметром + индекс. Первые два элемента списка задают x- и + y-координаты верхнего левого угла клетки (в пикселях по + отношению к примитиву), последние два элемента ширину и высоту + символа (в пикселях). Клетка может находиться за пределами + видимой части окна.
    + +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметрможет быть любым из + параметров команды entry.
    + +
    имяПути configure параметр + значение параметр значение ...
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в имениПути + параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда возвращает + часть полного списка, относящуюся к указанному параметру. Если + заданы одна или несколько пар параметр-значение, то + указанным параметрам примитива присваиваются новые + значения. В этом случае команда возвращает пустую + строку. Параметр может быть любым из параметров команды + entry.
    + +
    имяПути delete первый + последний
    + +
    Удаляет один или несколько символов в поле ввода. Аргумент + первый является индексом первого удаляемого символа, а + аргумент последний представляет собой индекс символа, + следующего непосредственно за последним удаляемым символом. По + умолчанию значение аргумента последний на единицу + больше значения аргумента первый, т.е. удаляется один + символ. Команда возвращает пустую строку.
    + +
    имяПути get
    + +
    Возвращает строку содержимое поля ввода.
    + +
    имяПути icursor + индекс
    + +
    Устанавливает курсор ввода непосредственно перед символом, + заданным аргументом индекс. Возвращает пустую + строку.
    + +
    имяПути index индекс
    + +
    Команда возвращает числовое значение индекса, заданного + аргументом индекс.
    + +
    имяПути insert индекс + строка
    + +
    Вставляет символы строки непосредственно перед + символом, на который указывает аргумент индекс. Команда + возвращает пустую строку.
    + +
    имяПути scan параметр + аргументы
    + +

    Осуществляет сканирование поля ввода. В зависимости от + значения параметра может иметь две различные формы:

    + +
    +
    имяПути scan mark x +
    + +
    Запоминает значение координаты x и текущее состояние + окна поля ввода; используется в сочетании с последующими + командами scan dragto. Обычно эта команда + связана с нажатием клавиши "Мыши" на + примитиве. Возвращает пустую строку.
    + +
    имяПути scan dragto + x
    + +
    Вычисляет разность между значением своего аргумента x и + значением аргумента x последней выполненной на данном + примитиве команды scan mark. Затем + переносит изображение примитива на расстояние, в 10 раз + превышающее вычисленную разность. Команда обычно связана с + событиями движения "Мыши" в примитиве и + используется для скоростного перетаскивания поля ввода в + окне. Возвращает пустую строку.
    +
    +
    + + +
    имяПути selection параметр + аргумент
    + +

    Производит размещение выделения в поле ввода. Команда может + иметь одну из описанных ниже форм.

    + +
    +
    имяПути selection adjust + индекс
    + +
    Определяет ближайший к указанному аргументом + индекс положению край выделения и устанавливает + новое значение этого края в индекс (т.е. элемент + с индексом индекс входит в выделение, а соседний + с ним нет). Противоположный край выделения становится + опорной точкой для последующих команд select + to. Если в текущий момент выделение в поле + отсутствует, то команда заводит новое выделение, + содержащее символы между указанным аргументом + индекс и последней установленной опорной точкой + выделения. Возвращает пустую строку.
    + +
    имяПути selection clear
    + +
    Очищает выделение в данном примитиве. Если выделение + отсутствует, то не производит никаких действий. Возвращает + пустую строку.
    + +
    имяПути selection from + индекс
    + +
    Устанавливает опорную точку выделения непосредственно + перед символом, заданным аргументом + индекс. Текущего выделения команда не + меняет. Возвращает пустую строку.
    + +
    имяПути selection present
    + +
    Возвращает "1", если в поле ввода имеется + выделение, в противном случае возвращает + "0".
    + +
    имяПути selection range + начало конец
    + +
    Выделяет символы между символом, указанным аргументом + начало, и символом, непосредственно + предшествующим указанному аргументом конец. Если + символ, указанный аргументом конец, совпадает с + символом, указанным аргументом начало, или + предшествует ему, то выделение становится пустым.
    + +
    имяПутиselection to + индекс
    + +
    Если символ, указанный аргументом индекс, + предшествует опорной точке выделения, то команда выделяет + все символы между опорным символом выделения и символом, + указанным аргументом индекс, не включая опорный + символ. Если аргумент индекс указывает на опорный символ, + то команда ничего не делает. Если символ, указанный + аргументом индекс, следует за опорной точкой + выделения, то команда выделяет все символы между опорным + символом выделения и символом, указанным аргументом + индекс, не включая этот символ. Опорный символ + устанавливается последней выполненной на данном примитиве + командой select from или select + adjust. Если в текущий момент выделение в поле + отсутствует, то команда заводит новое выделение, + содержащее символы между указанным аргументом + индекс и последней установленной опорной точкой + выделения. Команда возвращает пустую строку.
    +
    +
    + +
    имяПути xview + аргументы
    + +

    Используется для запроса горизонтального положения + информации, выведенной в поле ввода, и изменения этого + положения. Команда может иметь одну из следующих форм:

    + +
    +
    имяПути xview
    + +
    Возвращает список, состоящий из двух элементов. Каждый + из элементов списка представляет собой вещественное число, + заключенное между нулем и единицей; эта пара чисел + описывает видимый в окне горизонтальный интервал. Так, + например, если первое число равно "2", а второе + "6", то 20% текста в поле ввода оказывается + невидимой слева от окна, в окне выводится 40% информации, + и еще 40% оказывается невидимой справа от окна. Те же + значения передаются полосе прокрутки через параметр + -xscrollcommand.
    + +
    имяПути xview + индекс
    + +
    Переносит строку в поле ввода так, что самым левым + символом в окне становится символ, указанный аргументом + индекс.
    + +
    имяПути xview moveto + число
    + +
    Передвигает область видимости так, что слева от окна + остается невидимой часть поля ввода, указанная аргументом + число. Число должно быть заключено между + "0" и "1".
    + +
    имяПути xview scroll + количество что
    + +
    Сдвигает выводимый в окне текст вправо или влево в + соответствии со значениями аргументов. Количество + должно быть целым числом, аргумент что может + принимать значения units или + pages или быть сокращением одного из этих + слов. Если аргумент что принимает значение + units, то сдвиг происходит на + количество символов средней ширины. Если + значением аргумента что является + pages, то сдвиг осуществляется на + количество полных экранов. Если + количество отрицательно, то видимые символы + сдвигаются вправо, в противном случае влево.
    +
    +
    +
    + +

    ПРИВЯЗКИ ПО УМОЛЧАНИЮ

    + +

    При создании поля ввода Tk автоматически создает привязки + класса, определяющие поведение примитива по умолчанию. В + приводимом ниже описании .слово. есть произвольная непрерывная + группа букв, цифр и символов "_" или любой другой + одиночный символ. + +

    Щелчок клавишей 1 "Мыши" устанавливает курсор ввода + непосредственно перед символом, расположенным под курсором + "Мыши", устанавливает фокус ввода на данном примитиве + и отменяет выделение в нем.

    + +

    Перетаскивание курсора "Мыши" приводит к выделению + символов между курсором ввода и конечным положением курсора + "Мыши".

    Двойной щелчок клавишей 1 + "Мыши" приводит к выделению слова под курсором + "Мыши" и устанавливает курсор ввода перед первым + символом этого слова. Перетаскивание "Мыши" после + двойного щелчка приводит к выделению группы, состоящей из целых + слов.

    + +

    Тройной щелчок клавишей 1 "Мыши" приводит к выделению + всего текста в поле ввода и устанавливает курсор ввода перед + первым символом текста.

    + +

    Края выделения можно выровнять, если тащить .Мышь. с нажатой + клавишей 1 при нажатой клавише Shift; в этом + случае выравнивается край, ближайший к положению курсора + "Мыши" в момент нажатия ее клавиши 1. Если по кнопке + щелкнули дважды перед тем, как тащить "Мышь", то + выделение выравнивается относительно концов полных слов.

    + +

    Щелчок по клавише 1 "Мыши" при нажатой клавише + Control приводит к установке курсора ввода в поле ввода без + изменения текущего выделения.

    + +

    Обычные печатные символы вводятся в месте расположения курсора + ввода.

    + +

    Содержимое поле ввода можно перемещать с помощью клавиши 2 + "Мыши". Щелчок по клавише 2 "Мыши" и без ее + перемещения приводит к копированию выделения в поле ввода в + место расположения курсора "Мыши".

    + +

    Если тащить .Мышь. слева или справа от окна поля ввода по + направлению от окна при нажатой клавише 1, то в окне + автоматически появляется невидимый ранее текст (если в поле со + стороны, где .Мышь. покинула окно, есть текст, невидимый в + окне).

    + +

    Нажатие на клавиши Left или + Right приводит к перемещению курсора ввода на + один символ влево или вправо; при этом текущее выделение + отменяется и устанавливается новая опорная точка выделения. Если + нажатие на клавиши Left или + Right происходит при нажатой клавише + Shift, то курсор ввода перемещается и + пройденный им символ добавляется к выделению. Нажатие на клавиши + Control-Left и Control-Right + приводит к перемещению курсора ввода на полное слово, сочетания + Control-Shift-Left и + Control-Shift-Right еще и расширяют + выделение. Сочетания Control-b и + Control-f играют ту же роль, что и + Left и Right, а сочетания + Meta-b и Meta-f соответственно + ту же роль, что и Control-Shift-Left и + Control-Shift-Right.

    + +

    Нажатие на клавишу Home (или + Control-a) приводит к перемещению курсора к + началу текста с отменой существующих + выделений. Shift-Home перемещает курсор к + началу текста и доводит до этого места выделение.

    + +

    Нажатие на клавишу End (или + Control-e) приводит к перемещению курсора в + конец текста с отменой существующих + выделений. Shift-End перемещает курсор в конец + текста и доводит до этого места выделение.

    + +

    Нажатие на клавишу Select (или + Control-Space) устанавливает опорную точку + выделения в положение курсора ввода. Текущее выделение при этом + не изменяется. Нажатие на клавиши t-Select (или + Control-Shift-Space) доводит выделение до + текущего положения курсора ввода (или устанавливает выделение + между опорной точкой выделения и текущим положением курсора + ввода, если текущее выделение отсутствовало).

    + +

    Control-/ выделяет весь текст в окне.

    + +

    {Control-\} приводит к отмене текущего + выделения.

    + +

    Клавиша F16, на многих станциях Sun + обозначенная py, (или + Meta-w) копирует выделение в примитиве в + карман.

    + +

    Клавиша F20, на многих станциях Sun + обозначенная Cut, (или + Control-w) копирует выделение в примитиве в + карман и удаляет выделение. Если выделение в примитиве + отсутствует, то нажатие на эти клавиши не приводит ни к каким + действиям.

    + +

    Клавиша F18, на многих станциях Sun + обозначенная te, (или + Control-y) копирует содержимое кармана в место + расположения курсора ввода.

    + +

    Нажатие на клавишу Delete приводит к удалению + выделения. Если выделение отсутствует, то удаляется символ, + непосредственно примыкающий к курсору ввода справа.

    + +

    Нажатие на клавишу BackSpace (или + Control-h) приводит к удалению выделения. Если + выделение отсутствует, то удаляется символ, непосредственно + примыкающий к курсору ввода слева.

    + +

    Control-d удаляет символ, непосредственно + примыкающий к курсору ввода справа.

    + +

    Meta-d удаляет слово, непосредственно + примыкающее к курсору ввода справа.

    + +

    Control-k удаляет все символы справа от + курсора ввода.

    + +

    Если поле ввода отключено указанием значения + disabled параметра -state, то + в окне поля по-прежнему можно перемещать текст и производить + выделение, однако курсор ввода в окне не появляется и + редактирование текста невозможно.

    + +

    Определяя новые привязки к отдельным примитивам или + переопределяя привязки класса, поведение полей ввода можно + изменить.

    + + + + diff --git a/hlp/ru/tk/event.html b/hlp/ru/tk/event.html new file mode 100644 index 0000000..c594000 --- /dev/null +++ b/hlp/ru/tk/event.html @@ -0,0 +1,525 @@ + + + + event + + + +

    event

    + +

    Определение виртуальных событий и генерация событий

    + +

    СИНТАКСИС

    + +
    +      event параметр ?арг арг ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда event обеспечивает различные + возможности работы с событиями, включая определение виртуальных + событий и синтезирование событий. У команды есть несколько + различных форм, которые задаются первым аргументом. В настоящее + время поддерживаются следующие формы команды:

    + +
    +
    event add <<виртуальное>> + последовательность ?последовательность...?
    + +
    Связывает виртуальное событие с + последовательностями физических событий, указываемыми + аргументами последовательность; в результате + выполнение одной из указанных последовательностей + событий приводит к возникновению виртуального + события. Аргумент виртуальное может быть произвольной + строкой, а последовательность может принимать любое + значение, допустимое для аргумента последовательность + команды bind. Если + виртуальное событие уже определено, то новая + последовательность физических событий добавляется к списку уже + имеющихся последовательностей.
    + +
    event delete + <<виртуальное>> ?последовательность + последовательность ..?
    + +
    Удаляет все указанные последовательности из списка + связанных с данным виртуальным событием. Аргумент + виртуальное может быть произвольной строкой, а + последовательность может принимать любое значение, + допустимое для аргумента последовательность команды + bind. Если + последовательность не связана с данным + виртуальным событием в текущий момент, то она + игнорируется. Если аргумент последовательность + отсутствует, то из списка удаляются все последовательности + физических событий и данное виртуальное событие не + может быть более осуществлено.
    + +
    event generate окно событие + ?параметр значение параметр значение ...?
    + +
    Генерирует событие в окне и обеспечивает его обработку таким + образом, как если бы оно поступило из менеджера окон. Аргумент + окно задает имя пути окна, в котором будет + генерироваться событие; его значением может быть и + идентификатор окна (такой же, какой служит результатом команды + winfo id), если он относится к окну в текущем + приложении. Аргумент событие задает описание события, + например, в виде <Shift-Button-2> или + <<Paste>>. Аргумент + событие может принимать любое значение, допустимое + для аргумента последовательность команды bind, за исключением + того, что он должен состоять из одного, а не из нескольких + событий. Пары параметр-значение можно использовать + для установки значений дополнительных параметров события, + например, координат курсора "Мыши" ниже + (см. "ПОЛЯ СОБЫТИЯ"). Если + параметр -when не задан, то событие + обрабатывается немедленно; все программы обработки события + будут выполнены до завершения команды event + generate. В противном случае момент обработки + определяется значением параметра -when.
    + +
    event info + ?<<виртуальное>>?
    + +
    Возвращает информацию о виртуальных событиях. Если аргумент + <<виртуальное>> опущен, то возвращается + список всех виртуальных событий, определенных в текущий + момент. Если аргумент <<виртуальное>> + задан, то возвращаемое значение представляет собой список, + элементы которого являются последовательностями физических + событий, связанными с данным виртуальным событием; если + указанное виртуальное событие не определено, то команда + возвращает пустую строку.
    +
    + +

    ПОЛЯ СОБЫТИЯ

    + +

    Команда event generate поддерживает следующие + параметры, которые соответствуют расширению % в + скриптах привязки для команды bind.

    + +
    +
    -above окно
    + +
    Аргумент окно задает поле + above для события либо в виде имени + пути окна либо в виде целочисленного идентификатора + окна. Параметр имеет смысл для событий + Configure. Параметр соответствует подстановке + %a для скриптов привязки.
    + +
    -borderwidth размер
    + +
    Параметр размер представляет собой расстояние на + экране; задает значение поля border_width + события. Параметр имеет смысл для событий + Configure. Параметр соответствует подстановке + %B для скриптов привязки.
    + +
    -button число
    + +
    Значением параметра число должно быть целое число; + задает значение поля detail для события + ButtonPress или + ButtonRelease, подавляя номер кнопки, + задаваемый параметром события base. Параметр + соответствует подстановке %b для скриптов + привязки.
    + +
    -count число
    + +
    Значением параметра число должно быть целое число; + задает значение поля count для + события. Параметр имеет смысл для событий + Expose. Параметр соответствует подстановке + %c для скриптов привязки.
    + +
    -detail детальность
    + +

    Параметр задает значение поля detail для + события и может принимать следующие значения:

    + +
      +
    • NotifyAncestor
    • +
    • NotifyDetailNone
    • +
    • NotifyInferior
    • +
    • NotifyNonlinear
    • +
    • NotifyNonlinearVirtual
    • +
    • NotifyPointer
    • +
    • NotifyPointerRoot
    • +
    • NotifyVirtual
    • +
    + +

    Имеет смысл для событий Enter, + Leave, FocusIn и + FocusOut. Параметр соответствует + подстановке %d для скриптов привязки.

    +
    + +
    -focus булевское
    + +
    Параметр булевское принимает булевские значения; он + задает значение поля focus для события. Имеет + смысл для событий Enter и + Leave. Параметр соответствует подстановке + %f для скриптов привязки.
    + +
    -height размер
    + +
    Параметр размер представляет собой расстояние на + экране; задает значение поля height + события. Параметр имеет смысл для событий + Configure. Параметр соответствует подстановке + %h для скриптов привязки.
    + +
    -keycode число
    + +
    Значением параметра число должно быть целое число; + задает значение поля keycode для + события. Параметр имеет смысл для событий + KeyPress и + KeyRelease. Параметр соответствует + подстановке %k для скриптов привязки.
    + +
    -keysym имя
    + +
    Значением параметра имя должно быть имя допустимого + символа клавиатуры, например, g, + пробел или Return; код этого + символа используется в качестве значения поля + keycode события, подавляя значение + детальности, заданное аргументом base + события. Имеет смысл для событий KeyPress и + KeyRelease. Параметр соответствует + подстановке %K для скриптов привязки.
    + +
    -mode уведомление
    + +
    Параметр уведомление задает значение поля + mode для события; он должен принимать одно из + значений NotifyNormal, + NotifyGrab, NotifyUngrab или + NotifyWhileGrabbed. Имеет смысл для событий + Enter, Leave, + FocusIn и FocusOut. Параметр + соответствует подстановке %m для скриптов + привязки.
    + +
    -override булевское
    + +
    Значение параметра булевское должно быть булевским; + он задает значение поля override_redirect для + события. Имеет смысл для событий Map, + Reparent и + Configure. Параметр соответствует подстановке + %o для скриптов привязки.
    + +
    -place где
    + +
    Параметр где задает значение поля + place для события; может принимать значения + PlaceOnTop или + PlaceOnBottom. Имеет смысл для событий + Circulate. Параметр соответствует подстановке + %p для скриптов привязки.
    + +
    -root окно
    + +
    Аргумент окно задает поле root для + события либо в виде имени пути окна, либо в виде + целочисленного идентификатора окна. Имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave и + Motion. Параметр соответствует подстановке + %R для скриптов привязки.
    + +
    -rootx коорд
    + +
    Параметр коорд представляет собой расстояние на + экране; задает значение поля x_root + события. Параметр имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave и + Motion. Параметр соответствует подстановке + %X для скриптов привязки.
    + +
    -rooty коорд
    + +
    Параметр коорд представляет собой расстояние на + экране; задает значение поля y_root + события. Параметр имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave и + Motion. Параметр соответствует подстановке + %Y для скриптов привязки.
    + +
    -sendevent булевское
    + +
    Значение параметра булевское должно быть булевским; + он задает значение поля send_event для + события. Имеет смысл для всех событий. Параметр соответствует + подстановке %E для скриптов привязки.
    + +
    -serial число
    + +
    Значение параметра должно быть целым числом; задает значение + поля serial для события. Имеет смысл + для всех событий. Параметр соответствует подстановке + %# для скриптов привязки.
    + +
    -state состояние
    + +
    Параметр задает значение поля state для + события. Для событий KeyPress, + KeyRelease, ButtonPress, + ButtonRelease, Enter, + Leave и Motion значение + параметра должно быть целым. Для событий + Visibility параметр может принимать одно из + значений VisibilityUnobscured, + VisibilityPartiallyObscured или + VisibilityFullyObscured. Этот параметр + подавляет любые модификаторы, например, Meta + или Control, указанные в основном + событии. Параметр соответствует подстановке + %s для скриптов привязки.
    + +
    -subwindow окно
    + +
    Аргумент окно задает поле + subwindow для события либо в виде имени пути + примитива event, либо в виде целочисленного идентификатора + окна. Имеет смысл для событий KeyPress, + KeyRelease, ButtonPress, + ButtonRelease, Enter, + Leave и Motion. Аналогичен + подстановке %S для скриптов привязки.
    + +
    -time целое
    + +
    Параметр должен иметь целое значение; задает значение поля + time для события. Имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave, + Motion и Property. Параметр + соответствует подстановке %t для скриптов + привязки.
    + +
    -width размер
    + +
    Параметр размер представляет собой расстояние на + экране; задает значение поля width + события. Параметр имеет смысл для событий + Configure. Параметр соответствует подстановке + %w для скриптов привязки.
    + +
    -when когда
    + +

    Параметр когда задает момент обработки события; + должен принимать одно из следующих значений:

    +
    +
    now
    + +
    Событие обрабатывается немедленно, до завершения + выполнения команды. То же самое происходит и в случае, + если параметр -when опущен.
    + +
    tail
    + +
    Устанавливает событие в очередь событий Tcl вслед за + всеми стоящими в этой очереди событиями данного + приложения.
    + +
    head
    + +
    Устанавливает событие в начало очереди событий Tcl; оно + будет обработано перед остальными событиями, уже стоящими + в очереди.
    + +
    mark
    + +
    Устанавливает событие в начало очереди событий Tcl, но + вслед за всеми событиями, вставшими в очередь посредством + указания параметра -when. Такая + возможность полезна при генерации последовательности + событий, которые должны быть обработаны одно за другим, но + перед всеми событиями уже стоящими в очереди.
    +
    +
    + +
    -x коорд
    + +
    Параметр коорд представляет собой расстояние на + экране; задает значение поля x + события. Параметр имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave, + Motion, Expose, + Configure, Gravity и + Reparent. Параметр соответствует подстановке + %x для скриптов привязки.
    + +
    -y коорд
    + +
    Параметр коордпредставляет собой расстояние на + экране; задает значение поля y + события. Параметр имеет смысл для событий + KeyPress, KeyRelease, + ButtonPress, ButtonRelease, + Enter, Leave, + Motion, Expose, + Configure, Gravity и + Reparent. Параметр соответствует подстановке + %y для скриптов привязки.
    +
    + +

    Значением всякого параметра, не указанного при генерации + события, становится 0, за исключением параметра + serial, которому присваивается серийный номер + очередного X события.

    + +

    ПРИМЕРЫ ВИРТУАЛЬНЫХ СОБЫТИЙ

    + +

    Для обращения к привязке к виртуальному событию необходимо + выполнение двух условий. Во-первых, это виртуальное событие + должно быть определено командой event + add. Во-вторых, к этому виртуальному событию должна + быть создана привязка с помощью команды bind.

    + +

    Рассмотрим следующие определения виртуальных событий:

    + +
    +      event add <<Paste>> <Control-y>
    +      event add <<Paste>><Button-2>
    +      event add <<Save>> <Control-X><Control-S>
    +      event add <<Save>> <Shift-F12>
    +    
    + +

    В команде bind привязка к виртуальным событиям + осуществляется так же, как и ко встроенным типам событий:

    + +
    +      bind Entry <<Paste>> {%W insert[selection get]}
    +    
    + +

    Двойные угловые скобки показывают, что выполняется привязка к + виртуальному событию. При нажатии клавиш + Control-y или кнопки 2 .Мыши. или при + синтезировании виртуального события + <<Paste>> командой event + generate будет выполнена привязка + <<Paste>>.

    + + +

    Если последовательность в виртуальном событии в точности + совпадает с последовательностью в другом физическом событии, то + преимуществом пользуется физическое событие. Рассмотрим + следующий пример:

    + +

    + event add <<Paste>> <Control-y> <Meta-Control-y> + bind Entry <Control-y> {puts Control-y} + bind Entry <<Paste>> {puts Paste} + +

    При нажатии на клавиши Control-y будет + выполнена привязка <Control-y>, так как + физическое событие считается более конкретным, чем виртуальное, + а в остальном все одинаково. Однако при нажатии клавиш + Meta-Control-y будет выполнена привязка + <<Paste>>, так как модификатор + Meta в физическом образце, связанном с + виртуальной привязкой, более конкретен, чем последовательность + <Control-y> для физического события.

    + +

    Привязки к виртуальному событию можно создавать и до + определения самого события. На самом деле определение + виртуального события не является необходимым, например, на + платформах, где конкретное виртуальное событие может оказаться + бессмысленным или не генерируемым.

    + +

    При изменении определения виртуального события в процессе + выполнения все окна немедленно переключаются на новое + определение. Если, в условиях предыдущего примера, выполнить + команды

    + +
    +      bind <Entry> <Control-y> {}
    +      event add <<Paste>> <Key-F6>
    +    
    + +

    то поведение события изменится в двух направлениях. Во-первых, + всплывет подавленная привязка + <<Paste>>. Нажатие на клавиши + Control-y приведет теперь не к выполнению + привязки <Control-y>, а к выполнению + виртуального события <<Paste>>. + Во-вторых, нажатие на клавишу F6 также приведет + к выполнению привязки <<Paste>>. + +

    Если последовательность не связана с данным + виртуальным событием в текущий момент, то она + игнорируется. Если аргумент последовательность + отсутствует, то из списка удаляются все последовательности + физических событий и данное виртуальное событие не + может быть более осуществлено.

    + +
    +      event generate окно событие параметр значение параметр значение ...
    +    
    + +

    Генерирует событие в окне и обеспечивает его обработку таким + образом, как если бы оно поступило из менеджера окон. Аргумент + окно задает имя пути окна, в котором будет + генерироваться событие; его значением может быть и идентификатор + окна (такой же, какой служит результатом команды winfo + id), если он относится к окну в текущем + приложении. Аргумент событие задает описание события, + например, в виде <Shift-Button-2> или + <<Paste>>. Аргумент + событие может принимать любое значение, допустимое для + аргумента последовательность команды + bind, за исключением того, что он должен + состоять из одного, а не из нескольких событий. Пары + параметр-значение можно использовать для установки + значений дополнительных параметров события, например, координат + курсора "Мыши" ниже (см. "ПОЛЯ СОБЫТИЯ"). Если + параметр -when не задан, то событие + обрабатывается немедленно; все программы обработки события будут + выполнены до завершения команды event + generate. В противном случае момент обработки + определяется значением параметра -when. + +

    +      event info <<виртуальное>>
    +    
    + +

    Возвращает информацию о виртуальных событиях. Если аргумент + <<виртуальное>> + опущен, то возвращается список всех виртуальных событий, + определенных в текущий момент. Если аргумент + <<виртуальное>> + задан, то возвращаемое значение представляет собой список, + элементы которого являются последовательностями физических + событий, связанными с данным виртуальным событием; если + указанное виртуальное событие не определено, то команда + возвращает пустую строку.

    + + + + + + diff --git a/hlp/ru/tk/focus.html b/hlp/ru/tk/focus.html new file mode 100644 index 0000000..8d7fe34 --- /dev/null +++ b/hlp/ru/tk/focus.html @@ -0,0 +1,125 @@ + + + + focus + + +

    focus

    + +

    Управление фокусом ввода.

    + + +

    СИНТАКСИС

    + +
    +      focus
    +      focus окно
    +      focus параметр арг арг ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда focus используется для управления + фокусом ввода Tk. В любой момент времени одно из окон на каждом + экране находится в фокусе ввода; всякое событие нажатия или + отпускания клавиши интерпретируются в этом окне. Обычно + переключение фокуса между окнами верхнего уровня на экране + осуществляется менеджером окон. Например, некоторые менеджеры + окон автоматически переключают фокус на окно верхнего уровня, + как только на него попадает курсор "Мыши"; другие устанавливают + фокус только при щелчке на окне. Обычно менеджер окон + устанавливает фокус только на окнах верхнего уровня, а + переключением фокуса между подчиненными окнами занимается + конкретное приложение.

    + +

    Для каждого верхнего уровня Tk запоминает одно окно в фокусе + (последнего наследника данного верхнего уровня, в которое попал + фокус); когда менеджер окон переключает фокус на данный верхний + уровень, Tk автоматически устанавливает его на запомненное + окно. Внутри конкретного верхнего уровня Tk использует явное + моделирование фокуса по умолчанию. Обычно перемещение курсора + "Мыши" без изменения верхнего уровня не приводит к переключению + фокуса; переключение происходит, лишь если его запросил примитив + (например, в результате щелчка по кнопке "Мыши" ) или если + пользователь нажал, например, клавишу Tab. +

    + +

    Неявная модель фокусировки создается процедурой Tcl + tk_focusFollowsMouse; она меняет параметры конфигурации + Tk таким образом, чтобы фокус устанавливался на окно при + попадании на него курсора "Мыши".Процедуры + Tcl tk_focusNext и + tk_focusPrev устанавливают порядок переключения фокуса + между окнами верхнего уровня. Эти процедуры определяют, помимо + прочего, привязки по умолчанию к клавишам Tab и + Shift-Tab.

    + +

    Команда focus может принимать одну из + следующих форм:

    + +
    + +
    focus
    + +
    Возвращает имя пути окна в фокусе на дисплее, содержащем + главное окно приложения, или пустую строку, если никакое окно + данного приложения не находится в фокусе. Замечание: дисплей + лучше указать явно с помощью параметра + -displayof (см.ниже); в этом случае команда + сможет работать и в приложениях, использующих несколько + дисплеев.
    + +
    focus окно
    + +
    Если одно из окон данного приложения находится в фокусе на + дисплее окна, то команда устанавливает фокус ввода на + окно и возвращает пустую строку. Если же у приложения + не было фокуса ввода на дисплее окна, то окно будет запомнено + как окно в фокусе для данного верхнего уровня. При попадании + фокуса на данный верхний уровень в очередной раз Tk установит + его на окно. Если аргументом является пустая строка, то + команда не выполняет никаких действий.
    + +
    focus -displayof окно
    + +
    Возвращает имя окна в фокусе на дисплее, содержащем + окно. Если окно в фокусе на дисплее окна не + принадлежит данному приложению, то команда возвращает пустую + строку.
    + +
    focus -force окно
    + +
    Устанавливает окно в фокус на дисплее окна, даже + если у приложения нет фокуса ввода на этом дисплее. Эту + команду следует использовать экономно или отказаться от его + использования совсем. Обычно приложение не должно запрашивать + для себя фокус самостоятельно, дожидаясь пока на него не + переключит фокус менеджер окон. Если аргументом является + пустая строка, то команда не выполняет никаких действий.
    + +
    focus -lastfor окно
    + +
    Возвращает имя окна , последним получившим фокус + ввода среди всех окон того же верхнего уровня, что и + окно. Если ни на какое из окон данного верхнего уровня фокус + не устанавливался или если окно, на которое фокус + устанавливался последним, удалено, то команда возвращает имя + верхнего уровня. Возвращаемое значение является именем окна, + на котором будет установлен фокус ввода при следующей передаче + фокуса на данный верхний уровень менеджером окна.
    +
    + +

    ОСОБЕННОСТИ РЕАЛИЗАЦИИ

    + +

    При получении фокуса ввода внутренним окном Tk фактически не + устанавливает X фокус на это окно. X ведет себя таким образом, + что фокус сохранится на окне верхнего уровня, которому + подчиняется окно с фокусом. Однако Tk создает события FocusIn и + FocusOut в точности, как если бы X фокус был на внутреннем + окне. Такой подход порождает ряд трудностей при фактическом + переключении X фокуса; то, что X фокус установлен на данный + верхний уровень, незаметно, если не запрашивать X сервер + непосредственно из C программы. +

    + + diff --git a/hlp/ru/tk/font.html b/hlp/ru/tk/font.html new file mode 100644 index 0000000..78857b1 --- /dev/null +++ b/hlp/ru/tk/font.html @@ -0,0 +1,358 @@ + + + + font + + +

    font

    + + +

    Создание шрифтов и контроль за ними.

    + +

    СИНТАКСИС

    + +
    +      font параметр арг арг ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда font обеспечивает работу со шрифтами: + определение поименованных шрифтов и запрос фактических + параметров шрифтов. У команды несколько различных форм, которые + задаются первым аргументом. В настоящее время поддерживаются + следующие формы команды:

    + +
    + +
    font actual шрифт + -displayof окно параметр
    + +
    Возвращает информацию о фактических значениях параметров + шрифта, выводимого на экран. Фактические параметры + могут отличаться от запрошенных благодаря ограничениям, + накладываемым платформами (например, доступность различных + семейств шрифтов или различных кеглей). Аргумент + шрифт представляет собой описатель шрифта ниже + (см. "Описание + шрифта"). Если аргумент окно опущен, то по + умолчанию команда относится к главному окну. Если задан + аргумент параметр, то команда возвращает значение + указанного параметра. Если этот аргумент опущен, то + возвращаемое значение представляет собой список всех атрибутов + и их значений. Список возможных атрибутов приведен ниже + (см. "Параметры + шрифтов").
    + +
    font configure имяшрифта параметр + значение параметр значение ...
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех параметров шрифта имя + шрифта . Если параметр задан, а его новое + значение нет, то команда возвращает текущее значение + указанного параметра . Если заданы одна или несколько + пар параметр-значение, то указанным параметрам шрифта + присваиваются новые значения, а содержимое всех примитивов, + использующих данный шрифт меняется в соответствии с новыми + значениями параметров. Список возможных атрибутов приведен + ниже (см. "Параметры + шрифтов").
    + +
    font createимяшрифта параметр значение + ...
    + +
    Создает новый поименованный шрифт и возвращает его имя. + Аргумент имяшрифта задает имя шрифта; если этот + аргумент опущен, то Tk генерирует новое имя вида + fontx, где x целое + число. Число пар параметр-значение может быть произвольным, + они задают значения соответствующих параметров нового + поименованного шрифта. Список возможных атрибутов приведен + ниже (см. "Параметры + шрифтов").
    + +
    font delete имя_шрифта имя_шрифта ...
    + +
    Удаляет указанные поименованные шрифты. В случае, если + удаляемый шрифт используется в одном из примитивов, + фактическое удаление не происходит пока не будет вычеркнуто + последнее вхождение шрифта в примитив. Если удаленный + поименованный шрифт впоследствии создается вновь повторным + вызовом команды font create, то в примитивах + будет использоваться новый поименованный шрифт с новыми + значениями параметров.
    + +
    font families -displayof окно
    + +
    Возвращает список имен всех семейств шрифтов (без различения + верхнего и нижнего регистров), существующих на дисплее + заданного окна. Если аргумент окно опущен, то его значением по + умолчанию является главное окно.
    + +
    font measure шрифт + -displayof окно текст
    + +
    Подсчитывает протяженность текстовой строки при выводе ее на + экран в данном шрифте. Аргумент шрифт задает + описатель текста (см. "Описание шрифта"). Возвращает + общую ширину текста в пикселах без учета сильно искаженных + символов (как, например, " f " курсивного). Если в + строке есть символы табуляции или перевода строки, то они не + влияют на результат подсчета.
    + +
    font metrics шрифт + -displayof окно параметр
    + +
    Возвращает информацию о метрических характеристиках + шрифта при его выводе на экран. Аргумент шрифт задает + описатель шрифта, (см. "Описание шрифта"). Если аргумент + окно опущен, то его значением по умолчанию является главное + окно. Если задан аргумент параметр, то команда возвращает + значение указанной метрической характеристики; если этот + аргумент опущен, то возвращается список значений всех + метрических характеристик шрифта. Список метрических + характеристик приведен ниже (см. Метрические + характеристики шрифтов").
    + +
    font names
    + +
    Возвращает список всех поименованных на текущий момент + шрифтов.
    +
    + +

    ОПИСАНИЕ ШРИФТА

    + +

    В качестве описателя шрифта в любой из приведенных выше команд + принимаются следующие данные; те же самые форматы допустимы и в + качестве значения параметра -font в описателе + примитива.

    + +
    +
    [1] имя_шрифта
    + +
    Имя поименованного шрифта, созданного командой font + create. Использование поименованного шрифта не + может привести к ошибке вне зависимости от того, насколько + потенциально ошибочны или бессмысленны значения параметров + этого шрифта. Если вывод символов в поименованном шрифте + невозможен, то для их вывода используется автоматически + подбираемый шрифт с близкими значениями параметров.
    + +
    [2] сист_шрифт
    + +
    Имя (зависящее от используемой платформы) шрифта, + интерпретируемого графическим сервером. Сюда входит также (под + X) шрифтXLFD (см. [4]), в котором + используется единственный символ предназначенный для забивки + нескольких полей в середине имени. Список системных шрифтов + приведен в части текста, описывающей особенности данной + платформы.
    + +
    [3] семейство размер стиль стиль ...
    + +
    Список, первым элементом которого является требуемое + семейство шрифтов, а вторым, необязательным, элементом + требуемый размер. Параметр размер интерпретируется по тем же + правилам, что и параметр -size (см. "Параметры шрифтов"). Все + остальные необязательные аргументы, следующие за параметром + размер, представляют собой стили шрифтов. Они могут иметь + следующие значения: normal, + bold, roman, + italic, underline, + overstrike.
    + +
    [4] X-шрифт имена (XLFD)
    + +

    Имя шрифта для Unix-машин, представленное в виде:

    + +

    -заливка-семейство-шрифт-наклон-устширина-добстиль-пиксель-точка-разрешx-разрешy-промежуток-ширина-наборсимволов-кодирование

    + +

    -foundry-family-weight-slant-setwidth-addstyle-pixel-point-resx-resy-spacing-width-charset-encoding.

    + +

    Поля, содержимое которых пользователю безразлично, можно + пропустить, заменив символом " * ". Каждому + пропущенному полю должен соответствовать ровно один символ + " * ", а символ " * " в конце XLFD + приводит к пропуску всех оставшихся полей; кратчайшая форма + имеет вид просто " * ", что означает, что значения + всех полей берутся по умолчанию. Всем пропущенным полям + присваиваются значения по умолчанию. В целях совместимости + XLFD всегда выбирает шрифт заданного размера в пикселах (а + не в точках). Несмотря на некоторую некорректность + выбранного подхода, все приложения, использующие XLFD, + предполагают, что "точка" в действительности + совпадает с одним пикселем, и при использовании корректного + размера шрифта могут привести к неправильному выводу шрифта + (обычно с более крупными символами).

    +
    + +
    [5] параметр значение параметр значение ...
    + +
    Правильно сформированный список пар параметр-значение, + задающих атрибуты шрифта, в том же формате, что и при + определении поименованного шрифта (см. "Параметры шрифтов"). При + использовании описателя шрифта система пытается + проанализировать описание в соответствии с приведенными выше + пятью правилами в указанном порядке. В случаях [1] и [2] имя + шрифта должно соответствовать существующему поименованному + шрифту или системному шрифту. Случаи [3], [4] и [5] + принимаются на всех платформах и в них будет использоваться + шрифт, по параметрам ближайший к требуемому. В некоторых + ситуациях оказывается невозможно найти близкий шрифт + (например, имя семейства оказалось испорченным); в этом случае + выбирается один из системно-зависимых шрифтов по + умолчанию. Если описатель шрифта не подходит ни под один из + приведенных выше образцов, то возникает ошибка.
    +
    + +

    МЕТРИЧЕСКИЕ ХАРАКТЕРИСТИКИ ШРИФТОВ

    + +

    Команда font metrics использует следующие + параметры для запроса данных, определяемых при создании + шрифта. Это характеристики шрифта в целом, а не отдельных его + символов. В нижеследующих определениях "основа шрифта" + это горизонтальная прямая, на которой располагается нижняя часть + большинства букв, некоторые буквы, например, " g " + опускаются ниже основы.

    + +
    +
    -ascent
    + +
    Высота в пикселах самой высокой буквы шрифта над основой + плюс дополнительное пустое пространство, добавленное + разработчиком шрифта
    + +
    -descent
    + +
    Наибольшая протяженность в пикселях буквы шрифта под основой + плюс дополнительное пустое пространство, добавленное + разработчиком шрифта.
    + +
    -linespace
    + +
    Возвращает расстояние между строками текста, использующими + один и тот же шрифт, необходимое для того, чтобы символы + верхней строки не перекрывались с символами нижней. Обычно это + сумма зазора под верхней и над нижней строкой.
    + +
    -fixed
    + +
    Возвращает булевское значение, равное " 1 " для + шрифта постоянной ширины, в котором ширина всех обычных + символов одинакова, и равное " 0 " для + пропорционального шрифта, разные буквы которого имеют + различную ширину. Ширина управляющих символов, символов + табуляции и других непечатаемых символов при вычислении этого + значения не учитывается.
    +
    + +

    ПАРАМЕТРЫ ШРИФТОВ

    + +

    Следующие параметры поддерживаются на всех платформах и + используются для конструирования поименованного шрифта или при + задании шрифта с помощью стиля [5] выше:

    + +
    + +
    -family имя
    + +
    Имя семейства шрифтов (нечувствительное к регистру). Tk + обязательно поддерживает семейства с именами + Courier (моноширинный шрифт "пишущей + машинки"), Times ("газетный" + шрифт с засечками) и Helvetica (рубленый + "европейский" шрифт). При использовании одного из + этих семейств шрифтов оно автоматически заменяется наиболее + подходящим "родным" шрифтом. Имя семейства также + может быть именем одного из "родных" шрифтов, + зависящих от платформы; в этом случае семейство будет работать + на своей платформе, как положено, однако при переходе к другой + платформе могут возникнуть неприятности. Если имя семейства не + задано или не опознано, то будет выбран шрифт по умолчанию для + данной платформы.
    + +
    -size размер
    + +
    Требуемый кегль (размер) шрифта. Если значением аргумента + является положительное число, то оно интерпретируется как + размер символов в точках. Если значение отрицательно, то его + абсолютная величина интерпретируется как размер в + пикселах. Если шрифт указанного кегля нельзя вывести, то + берется ближайший доступный размер. Если размер не задан или + его значение равно нулю, то будет выбран размер по умолчанию + для данной платформы. Как правило, размер шрифта следует + указывать в точках; тогда приложение будет иметь один и тот же + размер на экране даже на мониторах различного разрешения или + при переносе скриптов на другие платформы. Однако использование + пикселей оправдано, например, в ситуациях, когда строчка + текста должна соответствовать по длине двуцветному изображению + фиксированного размера. Коэффициент перехода от точек к + пикселам и обратно устанавливается при запуске приложения на + основе параметров используемого монитора, однако его можно + изменить при помощи команды Tk scaling.
    + +
    -weight вес
    + +
    Условная толщина символов в шрифте. Значение + normal задает шрифт нормальной толщины, + bold жирный шрифт. Выбирается доступная + толщина, ближайшая к заданной. По умолчанию параметр имеет + значение normal.
    + +
    -slant наклон
    + +
    Величина, на которую символы шрифта отклоняются по + вертикали. Допустимы значения roman и + italic. Шрифт с наклоном + roman это обычный прямой шрифт, а символы + шрифта с наклоном italic отклоняются от + вертикали на несколько градусов. Выбирается доступный наклон, + ближайший к заданному. По умолчанию параметр имеет значение + roman.
    + +
    -underline булевское
    + +
    Значением параметра является булевский флажок, указывающий, + следует ли подчеркивать символы шрифта. По умолчанию параметр + имеет значение ложь.
    + +
    -overstrike булевское
    + +
    Значением параметра является булевский флажок, указывающий, + следует ли перечеркивать символы шрифта (горизонтальной прямой + посреди символа). По умолчанию параметр имеет значение + ложь.
    +
    + +

    ОСОБЕННОСТИ РЕАЛИЗАЦИИ НА РАЗЛИЧНЫХ ПЛАТФОРМАХ

    + +

    Различные платформы поддерживают следующие поименованные + системные шрифты:

    + +
    +
    X-Windows:
    + +
    Все допустимые имена X шрифтов, включая перечисляемые + выводятся командой xlsfonts(1).
    + +
    MS Windows:
    + +
    system, ansi, device, systemfixed, ansifixed, oemfixed
    + +
    Apple Macintosh
    + +
    system, application
    +
    + +

    См. также options.

    + + + diff --git a/hlp/ru/tk/frame.html b/hlp/ru/tk/frame.html new file mode 100644 index 0000000..2343772 --- /dev/null +++ b/hlp/ru/tk/frame.html @@ -0,0 +1,179 @@ + + + + frame + + + +

    frame

    + +

    Команда создает и управляет примитивами рамок (frames).

    + +

    СИНТАКСИС

    + +
    +      frame имя_Пути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -borderwidth
    • +
    • -highlightbackground
    • +
    • -highlightthickness
    • +
    • -takefocus
    • +
    • -cursor
    • +
    • -highlightcolor
    • +
    • -relief
    • +
    + +

    Описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-background
    Имя в Базе:background
    Класс в Базе:Background
    + +

    Этот параметр играет ту же роль, что и стандартный параметр + background, однако его значение может быть и + пустой строкой. В последнем случае в примитиве не выводится ни + фон, ни бордюр (и никакие цвета из цветовой схемы примитива не + задействованы на фон или бордюр).

    + + + + + +
    Имя параметра:-class
    Имя в Базе:class
    Класс в Базе:Class
    + +

    Параметр задает класс окна. Этот класс используется при запросе + значений других параметров окна в базе параметров, а также для + других целей (например, при задании привязок). Значение + параметра class нельзя поменять с помощью + команды примитива configure.

    + + + + + +
    Имя параметра:-colormap
    Имя в Базе:colormap
    Класс в Базе:Colormap
    + +

    Задает цветовую схему окна. Может либо принимать значение + new (в этом случае для окна и его потомков + создается новая цветовая схема), либо быть именем другого окна + на том же экране с тем же именемПути (в этом случае + новое окно берет цветовую схему указанного окна). Если параметр + colormap не задан, то новое окно наследует + цветовую схему своего предка. Значение параметра + colormap нельзя поменять с помощью команды + примитива configure.

    + + + + + +
    Имя параметра:-container
    Имя в Базе:container
    Класс в Базе:Container
    + +

    Значение параметра должно быть булевским. Если оно истинно, то + окно предназначено для включения какого-то другого приложения + (например приложение Tk верхнего уровня может быть включено с + помощью параметра -use). В этом случае окно + способно поддерживать соответствующие протоколы управления + окнами (например, обеспечивать исполнение геометрических + запросов). В данном приложении не должно быть собственных + потомков окна. Значение параметра container + нельзя поменять с помощью команды примитива + configure.

    + + + + + + +
    Имя параметра:-visual
    Имя в Базе:visual
    Класс в Базе:Visual
    + +

    Задает визуальную информацию для нового окна в любой из форм, + поддерживаемых Tk_GetVisual. Если параметр не + задан, то окно будет использовать ту же визуальную информацию, + что и его непосредственный предок. Значение параметра + visual нельзя поменять с помощью команды + примитива configure.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину окна в любой из форм, + поддерживаемыхTk_GetPixels. Если значение + параметра не положительно, то окно вообще не запрашивает + места.

    + +

    ОПИСАНИЕ

    + +

    Команда frame создает новое окно (заданное аргументом + имяПути) и превращает его в примитив рамки. Детали + изображения рамки, такие как ее цвет фона и объемный вид, + задаются с помощью описанных выше дополнительных + параметров. Команда frame возвращает имя пути нового окна.

    + +

    Рамка представляет собой простой примитив. Она предназначена в + первую очередь для размещения внутри нее окон сложным + образом. Единственными характеристиками рамки являются цвет ее + фона и (необязательно) способ изображения трехмерного бордюра + выпуклым или вдавленным.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда frame создает новую команду Tcl с + именем пути окна рамки. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид.

    + +
    +      frame имяПути параметр арг арг ...
    +    
    + +

    ИмяПути это имя команды, совпадающее с именем пути + примитива. Параметр и аргументы уточняют поведение + команды. Примитивы кнопки допускают следующие формы команды:

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров + команды frame.
    + +
    имяПути configure + ?параметр? ?значение параметр значение + ...?
    + +
    Запрашивает значения параметров + конфигурации примитива или изменяет их. Если параметр + не указан, то возвращает список, содержащий значения всех + допустимых в имениПути параметров (формат списка + описан в Tk_ConfigureInfo). Если + параметр задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения, а команда возвращает пустую + строку. Параметр может быть любым из параметров команды + frame.
    +
    + +

    ПРИВЯЗКИ

    + +

    При создании новой рамки она не имеет привязок по умолчанию: + рамки не предполагаются интерактивными.

    + + + + + + diff --git a/hlp/ru/tk/grab.html b/hlp/ru/tk/grab.html new file mode 100644 index 0000000..0e6c5ca --- /dev/null +++ b/hlp/ru/tk/grab.html @@ -0,0 +1,137 @@ + + + + grab + + + +

    grab

    + +

    Направляет события, исходящие из клавиатуры и указателя + "Мыши" в модальное окно и его поддерево.

    + + +

    СИНТАКСИС

    + +
    +      grab ?-global? окно
    +      grab параметр ?арг арг...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда реализует простые перехватчики событий ввода с + клавиатуры и "Мыши". Перехватчики Tk отличаются от + перехватчиков, описанных в документации Xlib. Когда для + некоторого окна задан перехватчик, Tk ограничивает все события, + исходящие от курсора, границами модального окна и его потомков в + иерархии окон Tk. Если курсор находится в пределах поддерева + модального окна, то курсор будет вести себя так, будто нет + никакого перехватчика вообще. Если курсор находится вне + поддерева модального окна, то события нажатия и освобождения + кнопок "Мыши" будут передаваться в окно, а + события входа в окно и выхода из окна будут + игнорироваться. Поддерево окон перехватчика "владеет" + курсором: прочие окна будут видны на экране, но будут + нечувствительны к нажатиям кнопок "Мыши" до тех пор, + пока не будет прекращен перехват. В поддерево модального окна + могут входить окна верхнего уровня; в этом случае все эти окна + верхнего уровня и их потомки обрабатывают события курсора + "Мыши" при перехвате обычным образом.

    + +

    С помощью команды grab можно запустить или + прекратить перехват для указанного окна и получить сведения об + установленном для указанного окна перехватчике.

    + +

    Есть два типа перехватчиков: локальные и глобальные. Локальный + перехватчик влияет только на перехватывающее приложение, остальные + приложения ведут себя таким образом, как если бы никакого перехвата + не было. По умолчанию перехватчики локальные. Глобальный + перехватчик блокирует все приложения на экране; чувствительность к + событиям указателя (нажатия и отпускания клавиши "Мыши", + движения указателя, входы в окно и выходы из него) сохраняют только + окна поддерева модального окна. При действии глобального + перехватчика менеджер окон также нечувствителен к событиям + указателя.

    + +

    При действии локальных перехватчиков события клавиатуры + (нажатие и отпускание клавиш) передаются обычным образом: + менеджер окон следит за тем, какое из приложений получает + событие клавиатуры, и всякое такое событие, относящееся к + перехватывающему приложению, перенаправляется в окно в + фокусе. При действии глобального перехватчика Tk перенаправляет + все события клавиатуры в перехватывающее приложение. Какое окно + приложения получает событие клавиатуры, по-прежнему определяется + командой focus. Перехват событий + клавиатуры отменяется при прекращении действия перехватчика.

    + +

    Перехватчики применяются к конкретным дисплеям. Если у + приложения есть окна на различных дисплеях, то оно может запустить + отдельный перехватчик на каждом дисплее. Перехватчик на конкретном + дисплее воздействует только на окно на этом дисплее. Несколько + приложений могут запустить на одном дисплее локальные перехватчики, + но глобальный перехватчик на дисплее может быть только один.

    + +

    Команда grab может иметь одну из следующих + форм:

    + +
    + +
    grab ?-global? окно
    + +
    Совпадает с описанной ниже командой grab + set.
    + +
    grab current window
    + +
    Если задан параметр window, то команда возвращает + имя текущего модального окна в данном приложении; если такого + окна нет, то команда возвращает пустую строку. Если параметр + window опущен, то команда возвращает список, + элементами которого являются все окна, захваченные данным + приложением на всех дисплеях; если таких окон нет, то команда + возвращает пустую строку.
    + +
    grab release окно
    + +
    Отменяет перехватчика на указанном окне; если в окне нет + перехватчика, то команда не выполняет никаких + действий. Команда возвращает пустую строку.
    + +
    grab set -global окно
    + +
    Устанавливает перехватчик на окно. Если задан параметр + -global, то перехватчик будет глобальным; в + противном случае он будет локальным. Если на дисплее окна у + приложения уже был перехватчик, то он автоматически + отменяется. Если на данном окне уже установлен перехватчик + того же вида (глобальный или локальный), что и запрошенный, то + команда не выполняет никаких действий. Команда возвращает + пустую строку.
    + +
    grab status окно
    + +
    Возвращает none, если в окне нет + перехватчика, local, если в окне + установлен глобальный перехватчик, global, + если в окне установлен глобальный перехватчик.
    + +
    + +

    ОШИБКИ

    + +

    Реализация описанного выше эффекта простого перехватчика + оказалась чрезвычайно сложной и громоздкой. В текущей реализации + прямое использование приложениями перехватчиков Xlib небезопасно; + это нужно делать через процедуры Tk.

    + +

    Если несколько приложений Tk управляются одним процессом, то на + данном дисплее только одно из этих приложений может иметь + локального перехватчика в каждый конкретный момент. Этого + ограничения нет для приложений, управляемых различными + процессами.

    + + + + diff --git a/hlp/ru/tk/grid.html b/hlp/ru/tk/grid.html new file mode 100644 index 0000000..37542b8 --- /dev/null +++ b/hlp/ru/tk/grid.html @@ -0,0 +1,418 @@ + + + + grid + + +

    grid

    + +

    Геометрический менеджер, который размещает виджеты в ячейках + сетки.

    + + +

    СИНТАКСИС

    + +
    +      grid option arg ?arg ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда grid используется для управления + соответствующим геометрическим менеджером, размещающим виджеты по + ячейкам сетки, и для получения от него справочной информации. + Команда может иметь перечисленные ниже формы в зависимости от + значения аргумента option.

    + +
    +
    grid slave ?slave ...? + ?options?
    + +
    Если первый аргумент команды является именем окна (любая + величина, начинающаяся с ".", команда выполняется точно + также, как команда grid configure.
    + +
    grid bbox master ?column + row? ?column2 row2?
    + +
    Без аргументов команда возвращает размер ограничивающего + прямоугольника для сетки (в пикселях). Возвращаемая величина + состоит из четырех чисел. Первые два представляют собой + расстояние от границы окна до левого верхнего угла + сетки. Следующие два числа представляют ширину и высоту + сетки. Если указана единственная колонка и строка, + возвращается ограничивающий прямоугольник для соответствующей + ячейки сетки (счет слева сверху, начиная с нуля). Если + указаны два набора колонок и строк, то возвращается размер + прямоугольника, ограничивающего соответствующую область + сетки.
    + +
    grid configure master index ?-option + value...?
    + +

    Запрашивает или устанавливает свойства колонки для колонки + сетки номер index. Допустимые опции + -minsize, -weight и + -pad. Если одна или более опций указаны, + index может быть списком номеров колонок, для которых + соответствующие значения опций должны быть установлены.

    + +

    Опция -minsize устанавливает минимальный + размер колонки на экране.

    + +

    Опция -weight (допустимые значения целые + числа) устанавливает относительный вес, используемый при + распределении свободного пространства между + колонками. Нулевой вес указывает, что колонка не будет + расширяться. Колонка с весом 2 будет расти вдвое быстрее, + чем колонка с весом 1.

    + +

    Опция -pad определяет размер полей, + которые будут добавлены к размерам максимального окна в + колонке при определении необходимой ширины колонки.

    + +

    Если в команде указана опция, а ее величина отсутствует, + команда возвращает установленное значение данной опции. Если + не указана ни одна опция, команда возвращает список опций и + их значений в той же форме, в какой они задаются.

    +
    + +
    grid configure slave ?slave ...? + ?options?
    + +

    Аргумент(ы) slave представляют собой имена + виджетов, которые размещаются в ячейках сетки. За ними следуют + пары аргументов, состоящие из имен опций и их значений, + которые управляют размещением виджетов. Символы "-", + "x" и "^" могут использоваться вместо имен + виджетов, чтобы изменить их типовое размещение (детально + правила использования этих символов описано ниже (см. "Относительное + размещение"). Допустимые имена опций:

    + +
    +
    -column n
    + +
    Вставляет виджет в n-ую колонку сетки. Номера + колонок начинаются с нуля. Если опция не указана, виджет + вставляется правее предыдущего виджета, вставленного той + же командой grid, или в колонку + "0", если это первый виджет в команде. Для + каждого символа "x" непосредственно перед + именем виджета номер колонки увеличивается на 1. То есть + "x" представляет пустую колонку в текущем ряду + сетки.
    + +
    -columnspan n
    + +
    Вставляет виджет таким образом, что он занимает + n колонок сетки. По умолчанию виджет занимает + одну колонку, если только после имени виджета не идет + символ "-". В этом случае каждый последующий + символ "-" увеличивает на единицу величину + columnspan.
    + +
    -in other
    + +
    Вставляет виджет(ы) в мастер-окно other. По + умолчанию виджет вставляется в непосредственного + предка.
    + +
    -ipadx amount
    + +
    Аргумент amount определяет горизонтальные + внутренние поля, которые вставляются в виджет(ы). Эти поля + вставляются внутри границы виджета. Размер должен быть + указан в одной из форм, в которой можно задавать размеры + на экране, например, 2 (2 пикселя) или + .5c (0.5 сантиметра). Значение по + умолчанию "0".
    + +
    -ipady amount
    + +
    Аргумент amount определяет вертикальные + внутренние поля, которые вставляются в виджет(ы). Эти поля + вставляются внутри границы виджета. Размер должен быть + указан в одной из форм, в которой можно задавать размеры + на экране, например, 2 (2 пикселя) или + .5c (0.5 сантиметра). Значение по + умолчанию "0".
    + +
    -padx amount
    + +
    Аргумент amount определяет горизонтальные + внешние поля, которые вставляются в виджет(ы). Эти поля + вставляются вне границы виджета. Размер должен быть указан + в одной из форм, в которой можно задавать размеры на + экране, например, 2 (2 пикселя) или + .5c (0.5 сантиметра). Значение по + умолчанию "0".
    + +
    -pady amount
    + +
    Аргумент amount определяет вертикальные внешние + поля, которые вставляются в виджет(ы). Эти поля + вставляются вне границы виджета. Размер должен быть указан + в одной из форм, в которой можно задавать размеры на + экране, например, 2 (2 пикселя) или + .5c (0.5 сантиметра). Значение по + умолчанию "0".
    + +
    -row n
    + +
    Вставляет виджет в n-ную строку сетки. Номера + строк считаются с нуля. Если опция не указана, виджет + вставляется в ту же строку, что и предыдущий виджет в + данной команде grid, или в первую + свободную строку, если это правый виджет в команде.
    + +
    -rowspan n
    + +
    Вставляет виджет таким образом, чтобы он занимал + n строк. Значение по умолчанию + "1". Если в следующей команде grid содержится + символ "^", то он означает, что виджет, + находящийся в этом же столбце в предыдущей строке, должен + быть расширен еще на одну строку вниз.
    + +
    -sticky style
    + +
    Если виджет меньше размеров ячейки сетки, опция + позволяет разместить (или растянуть) виджет внутри + ячейки. Аргумент style является строкой, + содержащей одну или несколько из букв n, + s, e или + w. Строка может содержать пробелы или + запятые, но они игнорируются. Каждая из букв означает + одну из сторон ячейки, к которой виджет будет + "приклеен". Если в строке содержатся символы для + двух противоположных сторон, например, n + и s (или e и + w), виджет будет увеличен таким образом, + чтобы заполнить всю высоту (или ширину) ячейки. Таким + образом опция -sticky заменяет сразу + опции -anchor и -fill + для менеджера pack. Значение по умолчанию + пустая строка, которая означает, что виджет будет размещен + в центре ячейки и будет иметь свой естественный + размер.
    +
    + +

    Если какой-либо из виджетов, перечисленных в команде, уже + размещен в сетке, а в команде для него указаны не все + возможные опции, для остальных опций используются предыдущие + значения, а не значения по умолчанию.

    +
    + +
    grid forget slave ?slave ...?
    + +
    Удаляет виджет(ы) из сетки и с экрана. Они больше не + управляются менеджером grid. Значения опций + для удаляемых виджетов не сохраняются, так что если виджет + будет через некоторое время помещен в сетку, для него будут + использоваться значения опций по умолчанию.
    + +
    grid info slave
    + +
    Возвращает список опций и их значений для окна slave в той + же форме, в какой они задаются в команде grid + configure. Первые два элемента списка + "-in master", где + "master" имя окна, в котором размещается + slave.
    + +
    grid location master x + y
    + +
    Аргументы x и y должны быть координатами в + системе координат мастер окна. Команда возвращает номер + колонки и строки, в которой находится точка с координатами + x и y. Если она расположена выше или левее + сетки, возвращается "-1".
    + +
    grid propagate master + ?boolean?
    + +
    Аргумент boolean, если он задан, определяет, будет + ли окно master расширяться при необходимости + (подробное описание опции см. "Распространение + размеров"). Команда при этом возвращает пустую + строку. Если аргумент не задан, команда возвращает текущее + значение опции (0 или 1). По + умолчанию расширение разрешено.
    + +
    grid rowconfigure master index + ?-option value...?
    + +

    Запрашивает или устанавливает свойства строки для строки + сетки номер index. Допустимые опции + -minsize, -weight и + -pad. Если одна или более опций указаны, + index может быть списком номеров строк, для которых + соответствующие значения опций должны быть установлены.

    + +

    Опция -minsize устанавливает минимальный + размер строки на экране.

    + +

    Опция -weight (допустимые значения целые + числа) устанавливает относительный вес, используемый при + распределении свободного пространства между + строками. Нулевой вес указывает, что строка не будет + расширяться. Строка с весом 2 будет расти вдвое быстрее, чем + строка с весом 1.

    + +

    Опция -pad определяет размер полей, + которые будут добавлены к размерам максимального окна в + строке при определении необходимой ширины колонки.

    + +

    Если в команде указана опция, а ее величина отсутствует, + команда возвращает установленное значение данной опции. Если + не указана ни одна опция, команда возвращает список опций и + их значений в той же форме, в какой они задаются.

    +
    + +
    grid remove slave ?slave + ...?
    + +
    Удаляет виджет(ы) из сетки и с экрана. Они больше не + управляются менеджером grid. Однако, значения + опций для них сохраняются, так что если виджет будет через + некоторое время помещен в сетку, для него будут использоваться + прежние значения опций.
    + +
    grid size master
    + +
    Возвращает размер сетки (в колонках и строках) для окна + master. Размер определяется наибольшим номером строки + или столбца, в которых размещен виджет или задано ненулевое + значение одной из опций -minsize, + -weight или -pad.
    + +
    grid slaves master ?-option + value?
    + +
    Если опции не заданы, возвращает список всех виджетов, + размещенных в сетке (размещенные позже в списке стоят раньше). + Допустимые опции -row и + -column. Если они указаны, команда + возвращает список виджетов, размещенных в соответствующей + строке или столбце.
    +
    + +

    ОТНОСИТЕЛЬНОЕ РАЗМЕЩЕНИЕ

    + +

    Команда grid содержит ограниченный набор + возможностей для размещения виджетов без явного указания строк и + колонок для каждого. Если номер строки или колонки не указан + явно, он рассчитывается в момент размещения виджета исходя из + текущего заполнения сетки, позиции виджета относительно других + виджетов и наличия в команде специальных символов "-", + "x" и "^" вместо имен виджетов.

    + +
    +
    -
    + +
    Этот символ увеличивает значение опции + -columnspan для виджета слева. Несколько + символов "-" подряд означают последовательное + увеличение значения опции -columnspan. Символ + "-" не может стоять после "^" или + "x".
    + +
    x
    + +
    Этот символ оставляет пустую колонку между виджетом слева и + виджетом справа.
    + +
    ^
    + +
    Этот символ увеличивает значение опции + -rowspan для виджета в соответствующей + колонке предыдущей строки. Число и расположение символов + ^ в строке должно соответствовать числу и + расположению расширяемых виджетов в предыдущей строке.
    +
    + +

    АЛГОРИТМ РАЗМЕЩЕНИЯ grid

    + +

    Геометрический менеджер grid размещает виджеты + в окне в три шага. На первом шаге определяются минимальные + размеры, необходимые для размещения всех виджетов и (если + распространение размеров разрешено) формируется запрос на + изменение размеров мастер-окна. На втором шаге необходимые + размеры сравниваются с реальными размерами мастер-окна. Если они + не совпадают, то размеры виджетов пересчитываются + соответствующим образом. На третьем шаге каждый виджет + размещается в своей колонке (колонках) и строке (строках) в + соответствии со значением опции -sticky.

    + +

    Чтобы определить минимальные размеры, необходимые для колонок и + строк, геометрический менеджер сначала рассматривает те виджеты, + у которых значения обеих опций -columnspan и + -rowspan равны "1", рассчитывает их + размер и определяет минимальный размер колонок и строк как + максимум из соответствующих размеров размещаемых в них виджетов + (включая поля) и значения соответствующей опции + -minsize. После этого рассматриваются виджеты + со значением опции -columnspan или + -rowspan больше единицы. Если отведенная группа + колонок или строк мала для такого виджета, тогда дополнительный + размер распределяется между членами группы пропорционально + значениям их опций -weight. Если все члены + группы имеют нулевой вес, они получают одинаковое приращение + размеров.

    + +

    Для мастер окон, размер которых оказался больше необходимого, + дополнительное пространство распределяется пропорционально весам + колонок и строк соответственно. Если все веса нулевые, виджеты + размещаются в центре мастер-окна. Если размер мастер-окна меньше + необходимого, то размеры колонок и строк уменьшаются + пропорционально их весам. Однако, если размер колонки или строки + уменьшился до значения соответствующей опции + -minsize, ее вес считается равным нулю. Если + все строки или колонки уменьшены до размеров, равных значениям + опций -minsize, и требуется дальнейшее + уменьшение размеров, группа виджетов обрезается справа и + снизу.

    + +

    РАСПРОСТРАНЕНИЕ РАЗМЕРОВ

    + +

    Обычно менеджер рассчитывает размеры мастер-окна, необходимые + для размещения виджетов, и, при необходимости, устанавливает + размеры мастер окна таким образом, чтобы в нем в точности + поместились все необходимые виджеты. Это приводит к тому, что + информация о размерах виджетов распространяется по + иерархическому дереву виджетов, в результате чего целое + поддерево изменяет свои размеры при изменении одного из + листьевых элементов. Однако, команда grid + propagate может быть использована для отключения этого + механизма для одного или нескольких мастер-окон. Если + распространение размеров отключено, информация о необходимых + размерах не передается мастер-окну. Это может оказаться + полезным, если вы хотите, чтобы мастер-окно сохраняло те + размеры, которые вы определили.

    + +

    ОГРАНИЧЕНИЯ НА МАСТЕР-ОКНА

    + +

    Мастер-окно для каждого размещаемого виджета должно быть его + непосредственным предком (по умолчанию) или одним из потомков + его предка. Это ограничение гарантирует разумное поведение + виджетов при удалении toplevel-окон.

    + +

    ПОРЯДОК РАЗМЕЩЕНИЯ

    + +

    Если мастер-окно для виджета не является его непосредственным + предком, необходимо быть уверенным, что виджет лежит в стеке + окон выше, чем мастер-окно. В противном случае мастер-окно + закроет собой виджет и создастся впечатление, что виджет не + упакован правильным образом. Простейший способ избежать подобных + проблем следить, чтобы мастер-окно было создано раньше, чем + виджет: чем позже создано окно, тем выше оно в стеке. Если это + почему-либо неудобно, можно использовать команды raise и lower для изменения + порядка окон в стеке.

    + + + diff --git a/hlp/ru/tk/image.html b/hlp/ru/tk/image.html new file mode 100644 index 0000000..54dfae8 --- /dev/null +++ b/hlp/ru/tk/image.html @@ -0,0 +1,106 @@ + + + + image + + +

    image

    + +

    Создание изображений и манипулирование ими.

    + +

    СИНТАКСИС

    + +
    +      image параметр ?арг арг ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда image предназначена для создания и + удаления изображений, а также для получения информации о них. В + зависимости от значения параметра она может иметь различные + формы. Допустимы следующие формы команды: + +

    +
    image create тип ?имя? + ?параметр значение...?
    + +
    Создает новое изображение и возвращает его имя. Аргумент + тип задает тип изображения, который должен быть одним + из типов, определенных на момент выполнения команды (например, + bitmap). Аргумент имя задает имя + изображения; если он опущен, то Tk генерирует имя вида + imagex, где x целое число. В команде может + присутствовать произвольное число пар + параметр-значение, задающих значения параметров + конфигурации для нового изображения. Для каждого типа + изображения набор допустимых параметров свой; параметры для + встроенных типов изображений подробно описаны ниже. Если + изображение с указанным именем уже существует, то новое + изображение подменит его, а каждая его реализация заменится на + реализацию нового изображения.
    + +
    image delete ?имя имя...?
    + +
    Удаляет каждое из названных изображений; возвращает пустую + строку. Если в примитивах имеются реализации удаляемого + изображения, то фактическое удаление не будет произведено до + удаления всех реализаций. Однако связь между реализациями + изображения и менеджером изображений разрывается. Существующие + реализации сохранят свои размеры, однако станут пустыми. Если + удаленное изображение будет воссоздано командой image + create, то его реализации заполнятся новым + содержимым.
    + +
    image height имя
    + +
    Возвращает десятичную строку, представляющую собой высоту в + пикселах изображения с именем имя.
    + +
    image names
    + +
    Возвращает список имен всех существующих изображений.
    + +
    image type имя
    + +
    Возвращает тип изображения с именем имя + (т.е. значение аргумента тип при создании изображения командой + image create).
    + +
    image types
    + +
    Возвращает список всех допустимых типов изображений + (т.е. всех возможных значений параметра тип команды + image create).
    + +
    image width имя
    + +
    Возвращает десятичную строку, представляющую собой ширину в + пикселах изображения с именем имя.
    +
    + +

    ВСТРОЕННЫЕ ТИПЫ ИЗОБРАЖЕНИЙ

    + +

    Следующие типы изображений определены непосредственно в Tk они + будут доступны в любом приложении. Отдельные приложения или + расширения могут определять дополнительные типы.

    + +
    +
    bitmap
    + +
    Каждый пиксель такого изображения имеет либо цвет переднего + плана, либо цвет фона, либо не имеет никакого цвета. Подробнее + такие изображения описаны в разделе bitmap
    + +
    photo
    + +
    Предназначен для вывода полноцветных изображений с + использованием поправок для приближения цветов на мониторах с + ограниченными цветовыми возможностями. Подробнее такие + изображения описаны в разделе photo.
    +
    + + + diff --git a/hlp/ru/tk/index-tk.html b/hlp/ru/tk/index-tk.html new file mode 100644 index 0000000..f0606c4 --- /dev/null +++ b/hlp/ru/tk/index-tk.html @@ -0,0 +1,67 @@ + + + + Tk commands + + +

    Table of contents

    + + + diff --git a/hlp/ru/tk/label.html b/hlp/ru/tk/label.html new file mode 100644 index 0000000..cbce244 --- /dev/null +++ b/hlp/ru/tk/label.html @@ -0,0 +1,141 @@ + + + + label + + +

    label

    + +

    Команда создает и управляет примитивами ярлыков.

    + +

    СИНТАКСИС

    + +
    +      label имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -anchor
    • +
    • -background
    • +
    • -bitmap
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -image
    • +
    • -justify
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -takefocus
    • +
    • -text
    • +
    • -textvariable
    • +
    • -underline
    • +
    • -wraplength
    • +
    + +

    Подробное описание этих параметров приведено в разделе oрtions.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту ярлыка. Если в ярлыке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); высота текстового ярлыка + задается числом строчек текста. Если параметр не задан, то + высота ярлыка вычисляется по его содержимому.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину ярлыка. Если в ярлыке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселях (т.е., в любом виде, приемлемом для + Tk_GetPixels); ширина текстового ярлыка + задается числом символов. Если параметр не задан, то ширина + ярлыка вычисляется по его содержимому.

    + +

    ОПИСАНИЕ

    + +

    Команда label создает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив + ярлыка. Детали изображения ярлыка, такие как его цвета, шрифт, + текст и исходный объемный вид задаются с помощью описанных выше + дополнительных параметров. Команда label + возвращает аргумент имяПути. В момент выполнения этой + команды не должно существовать окна с именем имяПути, + но должен существовать его предок.

    + +

    Ярлык представляет собой примитив, в котором выводится + текстовая строка, изображение или двуцветное изображение. Весь + выводимый текст должен быть записан одним шрифтом, однако он + может занимать несколько строчек на экране (если в нем есть + символы перевода строки или задан параметр + wrapLength). Один из символов текста может быть + подчеркнут (в соответствии со значением параметра + underline). Есть несколько простых способов + управления ярлыком (например, изменения его формы или + редактирования текста в нем), они описаны ниже.

    + + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда label создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы ярлыка допускают следующие формы команды:

    + +
    + +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметрможет быть любым из + параметров команды label.
    + +
    имяПути configure + ?параметр? ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан + вTk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения, а команда возвращает + пустую строку. Параметр может быть любым из + параметров команды button.
    +
    + +

    ПРИВЯЗКИ

    + +

    При создании нового ярлыка он не имеет привязок по умолчанию: + ярлыки не предполагаются интерактивными.

    + + diff --git a/hlp/ru/tk/listbox.html b/hlp/ru/tk/listbox.html new file mode 100644 index 0000000..7f8d125 --- /dev/null +++ b/hlp/ru/tk/listbox.html @@ -0,0 +1,597 @@ + + + + listbox + + + +

    listbox

    + +

    Команда создает и управляет примитивами окон со списками.

    + + + +

    СИНТАКСИС

    + + +
    +      listbox имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -font
    • +
    • -foreground
    • +
    • -height
    • +
    • -highlightbackground
    • +
    • -highlightthickness
    • +
    • -relief
    • +
    • -selectbackground
    • +
    • -selectborderwidth
    • +
    • -setgrid
    • +
    • -takefocus
    • +
    • -width
    • +
    • -xscrollcommand
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту окна (число строчек текста в нем). Если + значение параметра неположительно, то высота окна выбирается + таким образом, чтобы в нем помещались все элементы списка.

    + + + + + +
    Имя параметра:-selectmode
    Имя в Базе:selectMode
    Класс в Базе:SelectMode
    + +

    Задает один из нескольких стилей управления выделением. Параметр может принимать произвольное значение, однако привязки по умолчанию предполагают, что его значение является одним из следующих: single, browse, multiple или listbox. По умолчанию параметр имеет значение browse.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину окна (число символов в строчке текста в + нем). Если ширина символа в данном шрифте непостоянна, то для + перевода числа символов в единицы экрана используется ширина + символа "0". Если значение параметра неположительно, то ширина + окна выбирается таким образом, чтобы в нем помещались все + элементы списка.

    + +

    ОПИСАНИЕ

    + +

    Команда listbox создает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив окна со + списком. Детали изображения кнопки, такие как ее цвет, шрифт, + текст и объемный вид, задаются с помощью описанных выше + дополнительных параметров. Команда listbox + возвращает аргумент имяПути. В момент выполнения этой + команды не должно существовать окна с именем имяПути, + но должен существовать его предок.

    + +

    Окно со списком представляет собой примитив, в котором + выводятся строки элементы списка по одному на строчку окна. С + помощью описываемых ниже команд примитива в список можно + добавлять новые элементы или удалять элементы оттуда. Кроме + того, можно выделить один или несколько элементов, как описано + ниже. Экспорт выделенного текста (см. описание параметра + exportSelection) осуществляется по стандартному + протоколу X11 для выделений; выделения в поле ввода имеют тип + STRING. Значение строки выделения составляется + из выделенных элементов, разделенных символами перехода на новую + строчку.

    + +

    Все элементы списка не обязательно выводятся в окне со списком + одновременно. Содержимое окна можно поменять с помощью + описываемых ниже команд. Окна со списком поддерживают прокрутку + в обоих направлениях с помощью стандартных параметров + xScrollCommand и + yScrollCommand. Кроме того, возможно + сканирование окон (см. описание ниже).

    + +

    ИНДЕКСЫ

    + +

    Аргументами многих команд примитива окна со списком служат + индексы. Индекс задает положение конкретного элемента в окне со + списком. Он может иметь один из следующих видов:

    + +
    +
    число
    + +
    Задает номер элемента в списке. Первый элемент имеет номер + 0.
    + +
    active
    + +
    Задает элемент, на котором расположен курсор списка. Если + примитив находится в фокусе клавиатуры, то этот элемент + подчеркивается. Он устанавливается командой примитива + activate.
    + +
    anchor
    + +
    Задает опорную точку выделения, которую устанавливает + команда примитива selection anchor.
    + +
    end
    + +
    Указывает конец списка. Для большинства команд это последний + элемент списка, однако некоторые команды, такие как + index и insert считают его элементом, + следующим непосредственно за последним элементом списка.
    + +
    @x,y
    + +
    Указывает элемент, накрывающий точку в окне со списком с + координатами (x,y) (заданными в пикселях). Если + заданная точка не накрывается ни одним элементом, то указывает + элемент, ближайший к этой точке.
    +
    + +

    Аргументы с именами индекс, первый и + последний в описываемых ниже командах примитива + представляют собой индексы в одной из описанных выше форм.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда listbox создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы окна со списком допускает следующие формы + команды:

    + +
    +
    имяПути activate индекс
    + +
    Делает активным элемент, указанный аргументом + индекс. Если значение аргумента индекс + выходит за пределы списка, то активным становится элемент, + ближайший к указанному. Если окно со списком находится в + фокусе ввода, то активный элемент в нем выделен + подчеркиванием, а доступ к нему осуществляется через индекс + active.
    + +
    имяПути bbox индекс
    + +
    Возвращает список из четырех элементов, описывающий клетку, + занимаемую текстом в элементе, указанном параметром + индекс. Первые два элемента списка задают x- и + y-координаты верхнего левого угла клетки (в пикселях по + отношению к примитиву), последние два элемента ширину и высоту + области (в пикселях). Если на экране не видна никакая часть + элемента или если индекс указывает на несуществующий элемент, + то команда возвращает пустую строку. Если же на экране видна + хотя бы часть элемента, то результатом выполнения команды + служит описание всей области, занимаемой элементом (в том + числе и его невидимой частью).
    + +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров команды + listbox.
    + +
    имяПути configure + ?параметр? ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения. В этом случае команда возвращает + пустую строку. Параметр может быть любым из параметров команды + listbox.
    + +
    имяПути curselection
    + +
    Возвращает список, состоящий из числовых значений индекса + всех выделенных элементов. Если ни один из элементов не выделен, + то возвращает пустую строку.
    + +
    имяПути delete первый + ?последний?
    + +
    Удаляет один или несколько элементов списка. Аргумент + первый является индексом первого, а аргумент + последний индексом последнего удаляемого элемента. По + умолчанию значение аргумента последний совпадает со значением + аргумента первый, т.е. удаляется один элемент.
    + +
    имяПути get первый + ?последний?
    + +
    Если аргумент последний не задан, то возвращает + содержимое элемента списка, заданного аргументом + первый (или пустую строку, если первый указывает на + несуществующий элемент). Если аргумент последний задан, то + команда возвращает список, элементами которого являются все + элементы окна между первым и последним + (включая оба эти элемента). Значением каждого из аргументов + первый и последний может быть любое допустимое значение + индекса.
    + +
    имяПути index индекс
    + +
    Команда возвращает числовое значение индекса, заданного + аргументом индекс. Если аргумент индекс + имеет значение end, то возвращаемое значение + равно числу элементов в списке (а не индексу последнего + элемента).
    + +
    имяПути insert индекс + ?элемент элемент ...
    + +
    Вставляет элементы непосредственно перед элементом, на + который указывает аргумент индекс. Если аргумент + индекс имеет значение end, + то новые элементы вставляются в конец списка. Команда + возвращает пустую строку.
    + +
    имяПути nearest y
    + +
    По заданному значению y-координаты в окне со списком + возвращает индекс ближайшего к этому значению (видимого) + элемента списка.
    + +
    имяПути scan параметр + аргументы
    + + +

    Осуществляет сканирование окна со списком. В зависимости от + значения параметра может иметь две различные формы:

    + +
    + +
    имяПути scan mark x y
    + +
    Запоминает значение координаты x и текущее состояние + окна со списком; используется в сочетании с последующими + командами scan dragto. Обычно эта команда + связана с нажатием клавиши "Мыши" на + примитиве. Возвращает пустую строку.
    + +
    имяПути scan dragto x y
    + +
    Вычисляет разность между значением своих аргумента + x и y и значениями аргументов x + и y последней выполненной на данном примитиве + команды scan mark. Затем переносит + изображение примитива на расстояние, в 10 раз превышающее + вычисленную разность. Команда обычно связана с событиями + движения "Мыши" в примитиве и используется для + скоростного перетаскивания списка в окне. Возвращает + пустую строку.
    +
    +
    + +
    имяПути see индекс
    + +
    Выравнивает список в окне так, чтобы элемент с индексом + индекс оказался видимым. Если этот элемент уже + является видимым, то команда не производит никаких + действий. Если указанный элемент находится возле края окна, то + при прокрутке списка элемент оказывается возле того же края; в + противном случае указанный элемент выводится в центре + окна.
    + +
    имяПути selection параметр + аргумент
    + +

    Производит размещение выделения в окне со + списком. Команда может иметь одну из описанных ниже + форм.

    + +
    +
    имяПути selection anchor + индекс
    + +
    Устанавливает опорную точку выделения на элемент, + указанный аргументом индекс. Если индекс + указывает на несуществующий элемент, то опорным становится + элемент, ближайший к указанному. Опорная точка выделения + является фиксированным концом выделения при движении + "Мыши" с нажатой клавишей. На опорную точку выделения + указывает индекс anchor.
    + +
    имяПути selection clear + первый ?последний?
    + +
    Отменяет выделение элементов между первым и + последним. Вне этого интервала выделение не + изменяется.
    + +
    имяПути selection includes + индекс
    + +
    Возвращает "1", если элемент, указанный + аргументом индекс, выделен, и "0" в противном + случае.
    + +
    имяПути selection set + первый ?последний?
    + +
    Выделяет все элементы в промежутке между первым и + последним; на выделение вне указанного интервала команда + влияния не оказывает.
    +
    +
    + +
    имяПути xview аргументы
    + +

    Используется для запроса горизонтального положения + информации, выведенной в окне примитива, и изменения этого + положения. Команда может иметь одну из следующих форм:

    + +
    +
    имяПути xview
    + +
    Возвращает список, состоящий из двух элементов. Каждый + из элементов списка представляет собой вещественное число, + заключенное между нулем и единицей; эта пара чисел + описывает видимый в окне горизонтальный интервал. Так, + например, если первое число равно "2", а второе + "6", то 20% текста в окне со списком оказывается + невидимой слева от окна, в окне выводится 40% информации, + и еще 40% оказывается невидимой справа от окна. Те же + значения передаются полосе прокрутки через параметр + -xscrollcommand.
    + +
    имяПути xview индекс
    + +
    Переносит строку в поле ввода так, что самым левым + символом в окне становится символ, положение которого + указано аргументом индекс. Положения символов определяются + исходя из ширины символа 0.
    + +
    имяПути xview moveto + число
    + +
    Передвигает область видимости так, что слева от окна + остается невидимой часть текста списка, указанная + аргументом число. Число должно быть + заключено между "0" и "1".
    + +
    имяПути xview scroll + количество что
    + +
    Сдвигает выводимый в окне текст вправо или влево в + соответствии со значениями аргументов. Количество + должно быть целым числом, аргумент что может + принимать значения units или + pages или быть сокращением одного из этих + слов. Если аргумент что принимает значение + units, то сдвиг происходит на + количество символов средней ширины (ширины + символов 0). Если значением аргумента + что является pages, то сдвиг + осуществляется на количество полных экранов. Если + количество отрицательно, то видимые символы + сдвигаются вправо, в противном случае влево.
    +
    +
    + +
    имяПути yview аргументы
    + +

    Используется для запроса вертикального положения + информации, выведенной в окне примитива, и изменения этого + положения. Команда может иметь одну из следующих форм:

    + +
    +
    имяПути yview
    + +
    Возвращает список, состоящий из двух элементов. Каждый + из элементов списка представляет собой вещественное число, + заключенное между нулем и единицей. Первый элемент списка + задает положение в списке первого видимого в окне элемента + (например, значение "0.5" указывает на середину + списка). Второй элемент указывает положение в списке + элемента, следующего непосредственно за последним видимым + в окне. Те же значения передаются полосе прокрутки через + параметр -xscrollcommand.
    + +
    имяПути yview индекс
    + +
    Переносит содержимое окна со списком таким образом, + чтобы элемент, заданный аргументом индекс, оказался в + первой строчке окна.
    + +
    имяПути yview moveto + число
    + +
    Переносит содержимое окна со списком таким образом, + чтобы элемент, заданный аргументом число, + оказался в первой строчке окна. Число должно быть + заключено между 0 и 1. 0 указывает на первый + элемент в списке, 0.33 указывает на элемент, отстоящий от + начала списка на одну треть, и т.д.
    + +
    имяПути yview scroll + количество что
    + +
    Сдвигает выводимый в окне текст вверх или вниз в + соответствии со значениями аргументов. Количество + должно быть целым числом, аргумент что может + принимать значения units или + pages или быть сокращением одного из этих + слов. Если аргумент что принимает значение + units, то сдвиг происходит на + количество строчек. Если значением аргумента + что является pages, то сдвиг + осуществляется на количество полных экранов. Если + количество отрицательно, то видимые символы + сдвигаются вниз, в противном случае вверх.
    +
    +
    +
    + +

    ПАРАМЕТРЫ ПО УМОЛЧАНИЮ

    + +

    При создании окна со списком Tk автоматически создает параметры + класса, определяющие его поведение по умолчанию. Поведение окна + со списком в значительной степени определяется значением + параметра selectMode, задающим один из четырех + режимов работы с выделением.

    + +

    В режиме выделения single или + browse допустимо выделение не более одного + элемента. В обоих режимах щелчок клавишей 1 "Мыши" на + элементе приводит к его выделению и отмене всех остальных + выделений. В режиме browse выделенный элемент + можно также перетащить с помощью клавиши 1 "Мыши".

    + +

    В режимах выделения multiple или extended можно одновременно + выделить несколько элементов, не обязательно идущих в списке + подряд. В режиме multiple щелчок клавиши 1 "Мыши" на + элементе переключает состояние его выделенности, не влияя на + выделение остальных элементов. В режиме extended нажатие клавиши + на элементе выделяет его, отменяет выделение всех остальных + элементов и устанавливает опорную точку выделения на элемент под + курсором "Мыши"; если при этом тащить "Мышь" + с нажатой клавишей 1, то выделение + распространится на все элементы между опорным и элементом, + находящимся под сдвинувшимся курсором "Мыши".

    + +

    В большинстве случаев для одиночных выделений используется режим browse, а для кратных режим extended; остальные режимы оказываются полезными в некоторых особых ситуациях.

    +

    Помимо описанного выше поведения привязки по умолчанию задают следующие дополнительные характеристики поведения примитива:

    + +

    В режиме extended выделенную область можно + изменить нажатием клавиши 1 при нажатой клавише + Shift; при этом выделенной становится вся + область между опорной точкой и элементом под курсором + "Мыши".

    + +

    В режиме extended нажатие клавиши 1 при + нажатой клавише Control начинает выполнение + операции переключения: опорная точка устанавливается на элемент + под курсором "Мыши", а состояние его выделения + меняется на противоположное. Выделение остальных элементов не + изменяется. Если тащить "Мышь" с нажатой клавишей 1, + то состояние выделения всех элементов между опорной точкой и + курсором "Мыши" меняется на состояние выделения + опорного элемента; выделение остальных элементов не + изменяется.

    + +

    Если "Мышь" сдвигается с окна со списком при нажатой + клавише 1, то информация в окне прокручивается в противоположном + направлении. Прокрутка продолжается до тех пор, пока либо + "Мышь" не вернется в область окна, либо будет + достигнут конец списка.

    + +

    Для прокрутки можно использовать клавишу 2 + "Мыши". Если ее нажать и протащить "Мышь" по + списку, то содержимое списка будет прокручиваться в направлении + движения "Мыши".

    + +

    При нажатии на клавиши Up или + Down курсор окна (активный элемент) + передвигается на одну строчку вверх или вниз. В режиме + browse или extended новый + активный элемент оказывается выделенным, а выделение всех + остальных элементов отменяется. В режиме + extended новый активный элемент становится + опорной точкой выделения.

    + +

    В режиме extended клавиши + Shift-Up и Shift-Down + передвигают курсор окна на одну строчку вверх или вниз и + расширяют область выделения новым активным элементом подобно + тому, как это делает клавиша 1 "Мыши".

    + +

    Нажатие на клавиши Left или + Right приводит к перемещению курсора ввода на + ширину символа 0 влево или вправо.

    + +

    Нажатие на клавиши Control-Left и + Control-Right приводит к прокрутке списка на + ширину окна, также, как и нажатие на клавиши + Control-Prior и + Control-Next.

    Нажатие + на клавиши Prior и Next + приводит к прокрутке списка на одну страницу (на высоту окна) + вверх или вниз.

    + +

    Нажатие на клавиши Home и End + прокручивает список горизонтально до его левого или правого края + соответственно.

    + +

    Нажатие на клавиши Control-Home устанавливает + курсор окна на первый элемент списка, выделяет этот элемент и + отменяет выделение всех остальных элементов.

    + +

    Нажатие на клавиши Control-End устанавливает + курсор окна на последний элемент списка, выделяет этот элемент и + отменяет выделение всех остальных элементов.

    + +

    В режиме extended нажатие на клавиши + Control-Shift-Home расширяет выделение до + первого элемента в списке, а на клавиши + Control-Shift-End до последнего элемента в + списке.

    + +

    В режиме multiple нажатие на клавиши + Control-Shift-Home устанавливает курсор окна на + первый элемента в списке, а на клавиши + Control-Shift-End на последний элемент в + списке.

    + +

    Клавиши пробела и Select + выделяют активный элемент (курсор окна), как если бы на этом + элементе была нажата клавиша1 "Мыши".

    В режиме + extended нажатие на клавиши + Control-Shift-пробел и + Shift-Select расширяет выделение до активного + элемента, как если бы на этом элементе была нажата клавиша + 1 "Мыши" при нажатой клавише + Shift.

    + +

    В режиме extended нажатие на клавиши + Escape отменяет самое последнее выделение и + восстанавливает предыдущее состояние выделение всех элементов в + области выделения.

    + +

    Control-/ выделяет все элементы окна.

    + +

    Control-\ приводит к отмене текущего + выделения (за исключением режима browse, где + эта команда не приводит ни к какому результату).

    + +

    Клавиша F16, на многих станциях Sun + обозначенная Copy, (или + Meta-w) копирует выделение в примитиве в + карман.

    + +

    Определяя новые параметры для отдельных примитивов или + переопределяя параметры класса, поведение окна со списком можно + изменить.

    + + + + + diff --git a/hlp/ru/tk/lower.html b/hlp/ru/tk/lower.html new file mode 100644 index 0000000..437f513 --- /dev/null +++ b/hlp/ru/tk/lower.html @@ -0,0 +1,33 @@ + + + + lower + + +

    lower

    + +

    Команда изменяет положение окна в очереди стека.

    + + +

    СИНТАКСИС

    + +
    +      lower ?window belowThis?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда lower перемещает окно window + в очереди стека либо ниже всех окон, имеющих одинаковый с + window уровень иерархии, либо после одного из них, + заданного аргументом belowThis. Окна, оказавшиеся выше + данного окна, заслоняют его.

    + + + + + + + + + diff --git a/hlp/ru/tk/menu.html b/hlp/ru/tk/menu.html new file mode 100644 index 0000000..06a60a7 --- /dev/null +++ b/hlp/ru/tk/menu.html @@ -0,0 +1,929 @@ + + + + menu + + + +

    menu

    + +

    Создание примитива меню и управление им.

    + +

    СИНТАКСИС

    + +
    +      menu имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activebackground
    • +
    • -activeborderwidth
    • +
    • -activeforeground
    • +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -disabledforeground
    • +
    • -font
    • +
    • -foreground
    • +
    • -relief
    • +
    • -takefocus
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-postcommand
    Имя в Базе:postCommand
    Класс в Базе:PostCommand
    + +

    Задает команду Tcl, которая должна выполняться при каждом + выводе меню. Эта команда выполняется командой примитива + post непосредственно перед выводом меню. В + версии 8.0 операционной системы Macintosh и в Windows все + команды системы меню выполняются перед выводом меню. Это + объясняется ограничениями, накладываемыми конкретными системами + управления меню данных платформ.

    + + + + + +
    Имя параметра:-selectcolor
    Имя в Базе:selectColor
    Класс в Базе:Background
    + +

    Задает цвет индикатора при выделении входа меню, + представляющего собой защелкивающуюся кнопку или + переключатель.

    + + + + + +
    Имя параметра:-tearoff
    Имя в Базе:tearOff
    Класс в Базе:TearOff
    + +

    Принимает булевское значение, указывающее, должен ли вверху + меню быть ключ отрыва. Если значение параметра истина, то ключ + отрыва имеет номер ноль, а нумерация последующих входов в меню + начинается с единицы.

    + + + + + +
    Имя параметра:-tearoffcommand
    Имя в Базе:tearOffCommand
    Класс в Базе:TearOffCommand
    + +

    Если значение этого параметра не пустая строка, то оно задает + команду, которая должна выполняться при каждом отрыве от меню. В + действительности выполняемая команда состоит из указанной + строки, за которой следуют имя меню и имя окна меню отрыва + (отделенные от строки команды и друг от друга пробелами). Если, + например, параметр имеет значение "a + b" и в результате отрыва от меню + .x.y должно быть создано новое меню + .x.tearoff1, то будет выполнена команда + ".a b .x.y .x.tearoff1".

    + + + + + +
    Имя параметра:-title
    Имя в Базе:title
    Класс в Базе:Title
    + +

    Строка значение параметра задает имя окна, создаваемого при + отрыве от данного меню. Если значением параметра служит NULL, то + именем окна станет либо имя кнопки меню, либо содержимое + элемента каскада, из которого выполняется данное меню.
    + + + + + +
    Имя параметра:-type
    Имя в Базе:type
    Класс в Базе:Type
    + +

    Параметр может принимать одно из значений + menubar, tearoff или + normal; это значение устанавливается при + создании меню. При изменении значения меняется строка, + возвращаемая конфигурационной базой данных, однако это не + оказывает влияния на поведение примитива меню. Это свойство + используется механизмом клонирования и обычно не применяется за + пределами библиотеки Tk.

    + +

    ВВЕДЕНИЕ

    + +

    Команда menu создает новое окно (заданное + аргументом имяПути) и превращает его в примитив + меню. Детали изображения меню, такие как его цвета и шрифты, + задаются с помощью описанных выше дополнительных параметров в + командной строке или в базе данных параметров. Команда + menu возвращает имя пути нового окна. В момент + выполнения команды не должно быть окна с именем + имяПути, однако его непосредственный предок должен + существовать. + +

    Меню представляет собой примитив, предназначенный для вывода + совокупности однострочных входов, разбитых на несколько колонок + (быть может, одну). Входы бывают различных типов и имеют + соответственно различные свойства. Входы различных типов могут + содержаться в одном и том же меню. Вход меню (menu entry) совсем + не то же самое, что примитив поля ввода (entry). Более того, + вход меню не является отдельным примитивом все вместе они + образуют примитив меню.

    + +

    При выводе вход меню может содержать до трех различных + полей. Главное поле представляет собой метку входа; оно содержит + строку текста, изображение или двуцветное изображение в + зависимости от значения параметров входа + -label, -bitmap и + -image. Если для данного входа задан параметр + -accelerator, то справа от метки появляется + второе текстовое поле. Этот параметр обычно описывает + совокупность клавиш, нажатие на которые приводит к тому же + результату, что и выбор данного входа в меню. Третье поле + представляет собой индикатор. Индикатор применяется + только для защелкивающихся входов или переключателей. Он + указывает, выделен или нет данный вход, и располагается слева от + строки входа.

    + +

    При обычном использовании вход становится активным (при этом + меняется вид строки), если на нем расположен курсор "Мыши". Если + клавишу .Мыши. в таком положении отпустить, то вход будет + выполнен. Результат выполнения зависит от типа входа. Подробное + описание результатов приведено ниже при описании конкретных + типов входов.

    + +

    Входы могут быть отключены (disabled); изображение такого входа + тускнеет. Привязки меню по умолчанию блокируют активизацию и + выполнение команды для отключенного входа. Отключенный вход + может быть снова подключен, после чего его вновь можно + активизировать и выполнять соответствующую команду.

    + +

    При изменении активного входа в меню в нем происходит + виртуальное событие + <<MenuSelect>>. В результате из + меню можно запросить активный вход и предпринять какие-либо + действия (например, вывести соответствующую контекстно-зависимую + подсказку).

    + +

    КОМАНДНЫЕ ВХОДЫ

    + +

    Наиболее распространенным типом входа в меню является командный + вход, который ведет себя подобно примитиву кнопки. При запуске + командного входа выполняется команда Tcl, заданная параметром + -command.

    + +

    ВХОДЫ-РАЗДЕЛИТЕЛИ

    + +

    Разделитель представляет собой вход, предназначенный для вывода + горизонтальной разделительной черты. Разделитель нельзя сделать + активным или выполнить, никакого поведения разделителя, + отличного от вывода черты не предусмотрено.

    + +

    ЗАЩЕЛКИВАЮЩИЕСЯ ВХОДЫ

    + +

    Защелкивающийся вход ведет себя подобно защелкивающейся + кнопке. При щелчке на таком входе происходит переключение из + выделенного состояния в невыделенное и обратно. В выделенном + состоянии в некоторую глобальную переменную (указанную + параметром -variable) заносится значение, + фиксированное параметром -onvalue; при отмене + выделения в эту глобальную переменную заносится другое значение, + фиксированное параметром -offvalue. Слева от + метки защелкивающегося входа изображается + квадратик-индикатор. Если вход выделен, то центральная часть + индикатора окрашивается в цвет, указанный параметром + -selectcolor для входа; в противном случае цвет + индикатора совпадает с цветом фона меню. Если для данного входа + задано значение параметра -command, то это + значение интерпретируется как команда Tcl всякий раз при + выделении входа.

    + +

    ВХОДЫ-ПЕРЕКЛЮЧАТЕЛИ

    + +

    Вход-переключатель ведет себя подобно примитиву + переключателя. Входы переключателя разбиты на группы, причем в + каждой группе выделенным может оказаться только один вход. При + выделении конкретного входа в некоторую глобальную переменную + (указанную параметром -variable) заносится + значение, фиксированное параметром -value. В + результате этого действия автоматически отменяется предыдущее + выделение в той же группе. Любое изменение значения переменной, + связанной с входом, автоматически приводит к отмене + существующего выделения. Разбиение входов-переключателей на + группы задается значениями связанных с ними переменных: два + входа с одинаковыми значениями переменной принадлежат одной + группе. Слева от метки входа-переключателя изображается ромб + индикатора. Если вход выделен, то центральная часть индикатора + окрашивается в цвет, указанный параметром + -selectcolor для входа; в противном случае цвет + индикатора совпадает с цветом фона меню. Если для данного входа + задано значение параметра -command, то это + значение интерпретируется как команда Tcl всякий раз при + выделении входа.

    + +

    КАСКАДНЫЕ ВХОДЫ

    + +

    Каскадному входу отвечает новое меню (заданное параметром + -menu). Каскадные входы позволяют строить + ниспадающие меню. Команда примитива postcascade + позволяет изобразить ассоциированное меню непосредственно рядом + с каскадным входом или удалить выведенное меню. Для обеспечения + корректности переключения меню необходимо, чтобы меню, + ассоциированное с входом, было непосредственным потомком того + меню, элементом которого данный вход является.

    + +

    Каскадный вход выводит ассоциированное меню с помощью команды + Tcl вида:

    + +
    +
    меню post x y
    + +
    где меню представляет собой имя пути + ассоциированного меню, а x и y это + координаты верхнего правого угла окна каскадного входа + относительно корневого окна. В системе Unix меню нижнего + уровня стирается с помощью команды Tcl.
    + +
    меню unpost
    + +
    где меню представляет собой имя пути + ассоциированного меню. На других платформах стирание меню + осуществляется их собственными средствами.
    +
    + +

    Если для данного входа задано значение параметра + -command, то это значение интерпретируется как + команда Tcl всякий раз при выделении входа. В системе Windows + данная возможность не поддерживается.

    + +

    ВХОДЫ КЛЮЧИ ОТРЫВА

    + +

    Ключ отрыва появляется в верхней части меню, если параметр + tearOff имеет значение истина. В отличие от + входов других типов его нельзя создать командой примитива + add или удалить командой примитива + delete. При создании ключа отрыва он + изображается в виде пунктирной горизонтальной черты в верхней + части окна. Привязки по умолчанию создают при щелчке на ключе + отрыва оторванную копию меню и всех подчиненных ему меню.

    + +

    ЛИНЕЙКА МЕНЮ

    + +

    Любое меню можно использовать в качестве полосы меню для окна + верхнего уровня (синтаксис см. в описании команды + toplevel ). В системе Macintosh каскадные + элементы меню появляются в полосе меню в верхней части окна, как + только соответствующее окно верхнего уровня оказывается поверх + остальных окон. В системах Windows и Unix эти элементы меню + изображаются в полосе меню в верхней части окна. Поведение меню + определяется особенностями интерфейса каждой из платформ. Для + каждого меню, используемого в качестве полосы меню, создается + его копия (clone menu). Подробное описание приведено ниже (см. + "Клоны").

    + +

    СПЕЦИАЛЬНЫЕ МЕНЮ В ЛИНЕЙКЕ

    + +

    Некоторые меню в полосе меню будут обрабатываться особым + образом. В системе Macintosh обеспечен доступ к специальным меню + Apple и Help. В каждом окне системы Windows обеспечен доступ к + меню Windows System. В системе X Windows предоставляется + специальное меню подсказки, выравненное вправо. Во всех случаях + эти меню создаются посредством команды, имя которой состоит из + имени команды меню в полосе меню, к которому приписывается имя + специального меню. Так, для полосы меню с именем .menubar на + Macintosh именами специальных меню будут + .menubar.apple и + .menubar.help; в Windows + .menubar.system; в X Windows именем меню + подсказки будет .menubar.help.

    + +

    Встречая меню Apple в системе Macintosh, Tk выводит его первые + элементы на экран всякий раз, когда окно, содержащее полосу меню + оказывается поверх остальных окон. Это меню является первым, + которое видит пользователь, а его заголовком служит логотип + Apple. После всех Tk-определенных элементов следует разделитель, + за которым идут все элементы из папки пользователя Apple Menu + Items. Так как используемая System процедура определения меню + отлична от используемой в Tk и API системы не поддерживают всех + возможностей меню Tk, в заголовке меню выводится только текст + заголовка. Никаких дополнительных сведений, изображений, + двуцветных изображений или цветов не выводится. Кроме того, ключ + отрыва имеет вид "TearOff".

    + +

    Встречая меню Help в системе Macintosh, Tk добавляет содержимое + этого меню к стандартному меню подсказки в правой части + пользовательской полосы меню всякий раз, когда пользовательская + полоса меню оказывается поверх остальных окон. Первые элементы + меню берутся из Apple. Аналогично меню Apple возможности вывода + элементов меню ограничены системой.

    + +

    Встречая меню System в системе Windows, Tk добавляет содержимое + этого меню к системному меню, к которому привязана данная полоса + меню. В этом меню имеется картинка, изображающая клавишу + пробела; ее можно запустить с помощью "Мыши" или нажав + клавиши Alt+Spacebar. Ограничения Windows API + не позволяют вывести в системном меню различные шрифты, цвета, + изображения или двуцветные изображения, а также ключи + отрыва.

    + +

    Встречая меню Help в системе X Windows, Tk делает его последним + в полосе меню и выравнивает по правому краю.

    + +

    КЛОНЫ

    + +

    При использовании меню в качестве полосы меню в окне верхнего + уровня, а также при отрыве меню создается его копия. Копия сама + является примитивом меню, но она непосредственный потомок + исходного меню. Изменения конфигурации исходного меню + распространяются и на копию. Кроме того, все каскады, на которые + есть указатели, также копируются, что обеспечивает корректное + переключение меню. Копии уничтожаются, если удаляется ключ + отрыва или полоса меню, а также при уничтожении оригинала.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда menu создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид:

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение команды.

    + +

    Одним из аргументов многих команд примитива меню служит + указатель входа в меню, над которым следует произвести данную + операцию. Такие указатели называются индексами; они + могут иметь один из следующих видов:

    + +
    +
    число
    + +
    Задает номер входа. Самый верхний вход имеет номер 0, + следующий за ним номер 1 и т.д.
    + +
    active
    + +
    Задает вход, который активен в настоящий момент. Если + активного входа нет, то это значение параметра эквивалентно + значению none. Слово active + нельзя сокращать.
    + +
    end
    + +
    Указывает самый нижний вход в меню. Если в меню нет ни + одного входа, то это значение параметра эквивалентно значению + none. Слово end нельзя + сокращать.
    + +
    last
    + +
    Совпадает с end.
    + +
    none
    + +
    Указывает на "никакой" вход. Чаще всего + используется совместно с параметром activate + для дезактивации всех активных входов в меню. Слово + none нельзя сокращать.
    + +
    @число
    + +
    В этом случае число интерпретируется как значение + y-координаты в окне меню; указывает на вход, ближайший к + данной y-координате. Так, например, + "@0" указывает на самый верхний + вход в окне.
    + +
    образец
    + +
    Если индекс не подходит ни под один из указанных видов, то + используется поиск индекса по образцу. Сравнение метки входа с + образцом выполняется последовательно сверху вниз, + пока не встретится подходящая метка. При сравнении + используются правила Tcl_StringMatch.
    +
    + +

    Примитивы меню допускают следующие команды:

    + +
    +
    имяПути activate индекс
    + +
    Делает активным вход, указанный параметром индекс и + соответственно меняет вид строки входа на экране. Всякий вход, + бывший активным в момент выполнения команды, + деактивизируется. Если индекс имеет + значениеnone или если указанный этим + параметром вход отключен, то по окончании работы команды в + меню не будет активных входов. Возвращает пустую строку.
    + +
    имяПути add тип + ?параметр значение параметр значение?
    + +

    Добавляет новый вход на верхушку меню. Аргумент + тип задает вид нового входа; он может + принимать значения cascade, + checkbutton, command, + radiobutton (эти значения допускают + однозначные сокращения). Дополнительные аргументы могут + задавать значения следующих параметров:

    + +
    +
    -activebackground значение
    + +
    Задает цвет фона для вывода данного входа в активном + состоянии. Если значением служит пустая строка + (как, например, по умолчанию), то в качестве цвета фона + берется значение параметра + activeBackground для всего меню. Если + значение переменной tk_strictMotif + требует проверки согласования со стандартом Motif, то + значение данного параметра игнорируется и вместо него + используется значение параметра + -background. Для входа-разделителя и + ключа отрыва данный параметр недоступен.
    + +
    -activeforeground значение
    + +
    Задает цвет переднего плана для вывода данного входа в + активном состоянии. Если значением служит пустая + строка (как, например, по умолчанию), то в качестве цвета + фона берется значение параметра + activeForeground для всего меню.Для + входа-разделителя и ключа отрыва данный параметр + недоступен.
    + +
    -accelerator значение
    + +
    Задает строку, которую следует выводить в правой части + входа. Обычно описывает комбинацию клавиш, на + которые следует нажать, чтобы выполнить те же действия, + что и при обращении к данному входу. Для входа-разделителя + и ключа отрыва данный параметр недоступен.
    + +
    -background значение
    + +
    Задает цвет фона для вывода данного входа в нормальном + (не активном и не отключенном) состоянии. Если + значением служит пустая строка (как, например, по + умолчанию), то в качестве цвета фона берется значение + параметра background для всего меню. Для + входа-разделителя и ключа отрыва данный параметр + недоступен.
    + +
    -bitmap значение
    + +
    Задает двуцветное изображение, выводимое в меню вместо + текстовой метки. Может принимать любое значение, + воспринимаемое командой + Tk_GetBitmap. Данный параметр подавляет + параметр -label, однако если его + значением является пустая строка, то в окне выводится + текстовая метка. Параметр -image, если он + задан, подавляет параметр -bitmap. Для + входа-разделителя и ключа отрыва данный параметр + недоступен.
    + +
    -columnbreak значение
    + +
    Если значение параметра равно "0", то новый + вход выводится после предыдущего входа. Если значение + равно "1", то новый вход выводится вверху нового столбца + меню.
    + +
    -command значение
    + +
    Задает команду Tcl, которую следует выполнить при вызове + данного входа. Для входа-разделителя и ключа отрыва данный + параметр недоступен.
    + +
    -font значение
    + +
    Задает шрифт, используемый при выводе метки входа и + строки горячих клавиш. Если значением параметра является + пустая строка (как, например, по умолчанию), то + используется значение параметра fontдля + всего меню. Для входа-разделителя и ключа отрыва данный + параметр недоступен.
    + +
    -foreground значение
    + +
    Задает цвет переднего плана для вывода данного входа в + нормальном (не активном и не отключенном) состоянии. Если + значением служит пустая строка (как, например, по + умолчанию), то в качестве цвета фона берется значение + параметра foreground для всего меню. Для + входа-разделителя и ключа отрыва данный параметр + недоступен.
    + +
    -hidemargin значение
    + +
    Указывает, следует ли при выводе данного входа выводить + стандартные боковые поля. Такая возможность полезна при + создании различных палитр с картинками (цветовые палитры, + палитры образцов и т.д.). Значение "1" + указывает на то, что поля должны быть спрятаны, при + нулевом значении параметра они используются.
    + +
    -image значение
    + +
    Задает изображение, выводимое в меню вместо текстовой + метки или двуцветного изображения. Изображение должно быть + создано ранее командой image create. + Данный параметр подавляет параметры + -label, и -bitmap, + однако если его значением является пустая строка, то в + окне выводится текстовая метка или двуцветное + изображение. Для входа-разделителя и ключа отрыва данный + параметр недоступен.
    + + +
    -indicatoron значение
    + +
    Доступно только для защелкивающихся входов и + входов-переключателей. Значение является + булевским и указывает, следует или нет выводить индикатор + входа.
    + +
    -label значение
    + +
    Задает текстовую строку, которая служит + меткой-идентификатором входа. Для входа-разделителя и + ключа отрыва данный параметр недоступен.
    + +
    -menu значение
    + +
    Данный параметр доступен только для каскадных + входов. Задает имя пути подменю, ассоциированного с данным + входом. Подменю должно быть непосредственным потомком + данного меню.
    + +
    -offvalue значение
    + +
    Доступен только для защелкивающихся входов. Задает + значение, которое следует записать в переменную входа при + отмене его выделения.
    + +
    -onvalue значение
    + +
    Доступен только для защелкивающихся входов. Задает + значение, которое следует записать в переменную входа при + его выделении.
    + +
    -selectcolor значение
    + +
    Доступен только для защелкивающихся входов и + входов-переключателей. Задает значение, которое + следует записать в переменную входа при его + выделении.
    + +
    -selectimage значение
    + +
    Доступен только для защелкивающихся входов и + входов-переключателей. Задает изображение, которое следует + выводить в поле входа при его выделении (замещает параметр + -image). Изображение должно быть создано + ранее командойimage create. Если параметр + -image не задан, то данный параметр + игнорируется.
    + +
    -state значение
    + +
    Задает одно из трех состояний входа: + normal, active или + disabled. В нормальном состоянии при + выводе входа используются значения параметров + foreground для всего меню и + background для входа или для всего + меню. Обычно вход становится активным при попадании на + него курсора. В активном состоянии при выводе входа + используются значения параметров + activeForeground для всего меню и + activebackground для входа. В отключенном + (disabled) состоянии вход становится + безответным: привязки по умолчанию не позволяют + активизировать его или вызвать соответствующую ему команду + Tcl. При выводе входа в этом случае используются значения + параметров disabledForeground для всего + меню и background для входа. Для + входа-разделителя данный параметр недоступен.
    + +
    -underline значение
    + +
    Задает целочисленный индекс символа в метке, который + следует подчеркнуть. Значение этого индекса используется, + в том числе, привязками по умолчанию для осуществления + переключения с помощью клавиатуры. Значение "0" + указывает на первый символ в строке, "1" на + второй и т.д. Если в поле входа выводится изображение или + двуцветное изображение, то данный параметр + игнорируется. Для входа-разделителя и ключа отрыва данный + параметр недоступен.
    + +
    -value значение
    + +
    Доступен только для входа-переключателя. Задает + значение, которое следует записать в переменную входа при + его выделении. Если значением параметра является + пустая строка, то в переменную заносится значение + параметра -label.
    + +
    -variable значение
    + +
    Доступен только для защелкивающегося входа и + входа-переключателя. Задает имя глобальной переменной, + которую следует установить при выделении входа. Для + защелкивающегося входа значение переменной устанавливается + также при отмене его выделения. Для входа-переключателя + изменение значения переменной приводит к отмене текущего + выделения.
    +
    + +

    Команда примитива add возвращает + пустую строку.

    +
    + +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметрможет быть любым из + параметров команды menu.
    + +
    имяПути clone новоеИмяПути + ?типКопии?
    + +
    Создает копию текущего меню с именем + новоеИмяПути. Копия является отдельным + самостоятельным меню, однако любые изменения в ней приводят к + таким же изменениям оригинала и наоборот. Аргумент + типКопии может принимать значения normal, + menubar и tearoff. Команду не + следует исполнять вне библиотеки Tk. Подробную информацию + см. "Клоны".
    + +
    имяПути configure ?параметр? + ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения. В этом случае команда + возвращает пустую строку. Параметр может быть любым + из параметров команды menu.
    + +
    имяПути delete индекс1 + ?индекс2?
    + +
    Удаляет все входы между входами, указанными аргументами + индекс1 и индекс2, включая оба эти входа. Ключи + отрыва при этом не удаляются для их удаления следует поменять + значение параметра tearOff.
    + +
    имяПути entrycget индекс + параметр
    + +
    Возвращает текущее значение параметра конфигурации для + входа, заданного аргументом + индекс. Параметрможет принимать любые + значения, воспринимаемые командой примитива + add.
    + + +
    имяПути entryconfigure + индекс ?параметры?
    + +
    Команда аналогична команде configure; + отличие состоит в том, что она относится к параметрам + отдельного входа, тогда как команда configure + применима к параметрам меню в целом. Параметры могут + принимать любые значения, воспринимаемые командой примитива + add. Если параметры заданы, то им + присваиваются вновь заданные и команда возвращает пустую + строку. Если параметры не заданы, то команда + возвращает список текущих значений всех параметров для каждого + из входов, указанных аргументом индекс (формат списка + приведен в Tk_ConfigureInfo).
    + +
    имяПути index + индекс
    + +
    Команда возвращает числовое значение индекса, заданного + аргументом индекс или значение none, + если значением аргумента было + none.
    + +
    имяПути insert индекс тип + ?параметр значение параметр значение?
    + +
    Команда аналогична команде примитива add; + отличие состоит в том, что команда insert + вставляет новый вход непосредственно перед входом, на который + указывает аргумент индекс, а не в конец меню. Если в + меню есть ключ отрыва, то вставка входов перед ним + невозможна.
    + +
    имяПути invoke индекс
    + +
    Выполняет действие, ассоциированное с данным входом + меню. Подробное описание выполняемых действий приведено выше + при описании конкретных типов входов. Если с данным входом + ассоциирована какая-нибудь команда Tcl, то команда + invoke возвращает результат выполнения этой + команды Tcl. В противном случае результатом служит пустая + строка. Замечание: при исполнении данной команды меню не + пропадает автоматически это результат действия привязок по + умолчанию перед исполнением команды + invoke.
    + +
    имяПути post x y
    + +
    Обеспечивает вывод меню на экран в месте с координатами + x и y относительно корневого окна. При + необходимости эти координаты корректируются так, чтобы меню на + экране было видно. Обычно команда возвращает пустую + строку. Если задан параметр postCommand, то + его значение интерпретируется как Tcl скрипт, который и + исполняется перед выполнением команды post; в + этом случае команда примитива post возвращает + результат данного скрипта Tcl. Если при выполнении скрипта + возникла ошибка, то post возвращает сообщение + об этой ошибке и меню не выводится.
    + +
    имяПути postcascade + индекс
    + +
    Выводит подменю, вызываемое каскадным входом, указанным + аргументом индекс, и стирает ранее выведенное + подменю. Если аргумент индекс не указывает на + каскадный вход или если меню с именем имяПути не + выведено, то командаpostcascade не производит + никаких действий за исключением стирания ранее выведенных + подменю.
    + +
    имяПути type индекс
    + +
    Возвращает тип входа, указанного аргументом индекс. + Этот тип задается аргументом тип при создании входа + командой примитива add (например, + command, separator или + tearoff для ключа отрыва).
    + +
    имяПути unpost
    + +
    Стирает окно с экрана. Если было выведено каскадное меню + нижнего уровня, то стирает это меню. Возвращает пустую + строку. На платформах Windows и Macintosh эта команда не + работает, так как там имеются собственные системы управления + окнами.
    + +
    имяПути yposition индекс +
    + +
    Возвращает десятичное значение y-координаты в окне меню + верхнего пиксела поля входа, заданного аргументом + индекс.
    +
    + +

    КОНФИГУРАЦИИ МЕНЮ

    + +

    Привязки по умолчанию обеспечивают четыре различных способа + использования меню:

    + +
    +
    Ниспадающие меню в полосе меню
    + +
    Наиболее часто встречающийся случай. Сначала создается + примитив меню, который станет полосой меню. Затем к этому меню + добавляются каскадные входы, описывающие нужные ниспадающие + меню. Затем создаются все ниспадающие меню. Когда все это + проделано, нужно задать значение параметра + -menu в команде примитива верхнего + уровня. Подробное описание toplevel.
    + +
    Ниспадающие меню в кнопках меню
    + +
    Это альтернативный способ создания полосы меню. Сначала + создается примитив кнопки меню для каждого меню верхнего + уровня (обычно цепочка кнопок располагается последовательно в + полосе меню окна). Кроме того следует создать все меню + верхнего уровня и подчиненные им меню и связать их вместе с + помощью параметра -menu в кнопках меню и + каскадных входах меню. Меню верхнего уровня должно быть + непосредственным потомком кнопки меню, а каждое подменю должно + быть непосредственным потомком меню, которое на него + ссылается. После того, как это сделано, привязки по умолчанию + позволяют пользователю переходить от одного меню к другому и + обращаться к дереву меню через кнопку меню.
    + +
    Всплывающие меню
    + +
    Всплывающие меню обычно выводятся при нажатии кнопки + "Мыши" или клавиши на клавиатуре. Сначала создаются + всплывающие меню и все каскадные подменю, затем в нужный + момент времени следует вызвать процедуру + tk_popup, в результате чего будет выведено + меню верхнего уровня.
    + +
    Меню-переключатели с кнопкой
    + +
    Меню-переключатель состоит из кнопки и связанного с ней + меню, которое позволяет выбрать одну из нескольких + возможностей. Описатель выбранной возможности выводится в + кнопке и в глобальной переменной запоминается соответствующее + значение. Для создания меню-переключателей используется + процедура tk_optionMenu.
    + +
    Отрывные меню
    + +
    Отрывное меню создается при исполнении входа ключа отрыва в + верхней части имеющегося меню. Привязки по умолчанию создают + копию исходного меню и выводят ее в виде окна верхнего + уровня. Оторванное меню ведет себя точно так же, как и + исходное.
    +
    + +

    ПАРАМЕТРЫ ПО УМОЛЧАНИЮ

    + +

    При создании меню Tk автоматически создает параметры класса, + определяющие следующее поведение примитива по умолчанию:

    + +

    При попадании курсора "Мыши" в меню вход, на котором + находится курсор, становится активным; при перемещении курсора + по меню соответственно меняется и активный вход.

    + +

    Если курсор "Мыши" покидает меню, то все входы в нем + деактивизируются за исключением случая, когда курсор + перемещается в каскадное подменю.

    + +

    При отпускании клавиши "Мыши" на меню активный вход + (если таковой имеется) исполняется. При этом меню стирается за + исключением случая, когда это оторванное меню.

    + +

    Нажатие на клавиши Space или + Return приводят к исполнению активного входа и + стиранию меню.

    + +

    Если одна из букв в поле входа подчеркнута с помощью параметра + -underline, то нажатие на эту букву (или ее + эквивалент на верхнем или нижнем регистре) приводит к исполнению + входа и стиранию меню.

    + +

    Нажатие на клавишу Escape приводит к отмене + текущего выделения. Меню при этом стирается, если только это не + оторванное меню.

    + +

    Нажатие на клавиши Up или + Down приводит к активизации входа, примыкающего + к текущему активному входу сверху или снизу. Если достигнут + конец меню, то происходит перескок на противоположный его + конец.

    + +

    Нажатие на клавишу Left приводит к переходу на + соседнее слева меню. Если текущее меню представляет собой + каскадное подменю, то это каскадное подменю стирается и текущим + входом в меню становится каскадный вход в его непосредственном + предке. Если текущее меню представляет собой меню верхнего + уровня, выведенное кнопкой меню, то текущая кнопка меню + стирается и выводится соседняя слева кнопка меню. В остальных + случаях нажатие на эту клавишу не приводит ни к какому + результату. Порядок кнопок меню слева направо определяется их + порядком в стеке: Tk считает нижнюю кнопку меню (первой попавшую + в стек) самой левой.

    + +

    Нажатие на клавишу Right приводит к переходу + на соседнее справа меню. Если текущим является каскадный вход, + то выводится соответствующее каскадное подменю и текущий вход + становится первым в этом подменю. В противном случае, если + текущее меню было выведено кнопкой меню, то текущая кнопка меню + стирается, а вместо нее выводится соседняя с ней справа кнопка + меню.

    + +

    Отключенные входы меню остаются безответными: их нельзя сделать + активными и они не реагируют на нажатие и отпускание клавиш + "Мыши".

    + +

    Определяя новые привязки к отдельным примитивам или + переопределяя привязки класса, поведение меню можно + изменить.

    + +

    В настоящее время использование базы данных параметров для + задания значений параметров входов не допускается.

    + + + + + + diff --git a/hlp/ru/tk/menubutton.htm b/hlp/ru/tk/menubutton.htm new file mode 100644 index 0000000..8b8175e --- /dev/null +++ b/hlp/ru/tk/menubutton.htm @@ -0,0 +1,266 @@ +Tk Built-In Commands - menubutton manual page +
    +
    NAME +
    menubutton - Create and manipulate menubutton widgets
    +
    SYNOPSIS +
    +
    menubutton pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -direction, direction, Height +
    -height, height, Height +
    -indicatoron, indicatorOn, IndicatorOn +
    -menu, menu, MenuName +
    -state, state, State +
    -width, width, Width +
    +
    INTRODUCTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +menubutton - Create and manipulate menubutton widgets +

    SYNOPSIS

    +menubutton pathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -direction +
    Database Name: direction +
    Database Class: Height +
    Specifies where the menu is going to be popup up. above tries to +pop the menu above the menubutton. below tries to pop the menu +below the menubutton. left tries to pop the menu to the left of +the menubutton. right tries to pop the menu to the right of the +menu button. flush pops the menu directly over the menubutton. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the menubutton's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -indicatoron +
    Database Name: indicatorOn +
    Database Class: IndicatorOn +
    The value must be a proper boolean value. If it is true then +a small indicator rectangle will be displayed on the right side +of the menubutton and the default menu bindings will treat this +as an option menubutton. If false then no indicator will be +displayed. +

    Command-Line Name: -menu +
    Database Name: menu +
    Database Class: MenuName +
    Specifies the path name of the menu associated with this menubutton. +The menu must be a child of the menubutton. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the menubutton: normal, active, +or disabled. In normal state the menubutton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the menubutton. In active state +the menubutton is displayed using the activeForeground and +activeBackground options. Disabled state means that the menubutton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the button is displayed. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the menubutton's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    INTRODUCTION

    +The menubutton command creates a new window (given by the +pathName argument) and makes it into a menubutton widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the menubutton such as its colors, font, +text, and initial relief. The menubutton command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A menubutton is a widget that displays a textual string, bitmap, or image +and is associated with a menu widget. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. In normal usage, pressing +mouse button 1 over the menubutton causes the associated menu to +be posted just underneath the menubutton. If the mouse is moved over +the menu before releasing the mouse button, the button release +causes the underlying menu entry to be invoked. When the button +is released, the menu is unposted. +

    +Menubuttons are typically organized into groups called menu bars +that allow scanning: +if the mouse button is pressed over one menubutton (causing it +to post its menu) and the mouse is moved over another menubutton +in the same menu bar without releasing the mouse button, then the +menu of the first menubutton is unposted and the menu of the +new menubutton is posted instead. +

    +There are several interactions between menubuttons and menus; see +the menu manual entry for information on various menu configurations, +such as pulldown menus and option menus. + +

    WIDGET COMMAND

    +The menubutton command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for menubutton widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the menubutton +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the menubutton +command. + +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for menubuttons that give them +the following default behavior: +

    +

    +

    [1]
    +A menubutton activates whenever the mouse passes over it and deactivates +whenever the mouse leaves it. +

    [2]
    +Pressing mouse button 1 over a menubutton posts the menubutton: +its relief changes to raised and its associated menu is posted +under the menubutton. If the mouse is dragged down into the menu +with the button still down, and if the mouse button is then +released over an entry in the menu, the menubutton is unposted +and the menu entry is invoked. +

    [3]
    +If button 1 is pressed over a menubutton and then released over that +menubutton, the menubutton stays posted: you can still move the mouse +over the menu and click button 1 on an entry to invoke it. +Once a menu entry has been invoked, the menubutton unposts itself. +

    [4]
    +If button 1 is pressed over a menubutton and then dragged over some +other menubutton, the original menubutton unposts itself and the +new menubutton posts. +

    [5]
    +If button 1 is pressed over a menubutton and released outside +any menubutton or menu, the menubutton unposts without invoking +any menu entry. +

    [6]
    +When a menubutton is posted, its associated menu claims the input +focus to allow keyboard traversal of the menu and its submenus. +See the menu manual entry for details on these bindings. +

    [7]
    +If the underline option has been specified for a menubutton +then keyboard traversal may be used to post the menubutton: +Alt+x, where x is the underlined character (or its +lower-case or upper-case equivalent), may be typed in any window +under the menubutton's toplevel to post the menubutton. +

    [8]
    +The F10 key may be typed in any window to post the first menubutton +under its toplevel window that isn't disabled. +

    [9]
    +If a menubutton has the input focus, the space and return keys +post the menubutton. +

    +

    +If the menubutton's state is disabled then none of the above +actions occur: the menubutton is completely non-responsive. +

    +The behavior of menubuttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +menubutton, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/ru/tk/menubutton.html b/hlp/ru/tk/menubutton.html new file mode 100644 index 0000000..8b8175e --- /dev/null +++ b/hlp/ru/tk/menubutton.html @@ -0,0 +1,266 @@ +Tk Built-In Commands - menubutton manual page +
    +
    NAME +
    menubutton - Create and manipulate menubutton widgets
    +
    SYNOPSIS +
    +
    menubutton pathName ?options? +
    +
    STANDARD OPTIONS +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +
    WIDGET-SPECIFIC OPTIONS +
    +
    -direction, direction, Height +
    -height, height, Height +
    -indicatoron, indicatorOn, IndicatorOn +
    -menu, menu, MenuName +
    -state, state, State +
    -width, width, Width +
    +
    INTRODUCTION +
    WIDGET COMMAND +
    +
    pathName cget option +
    pathName configure ?option? ?value option value ...? +
    +
    DEFAULT BINDINGS +
    +
    +
    KEYWORDS +

    +

    NAME

    +menubutton - Create and manipulate menubutton widgets +

    SYNOPSIS

    +menubutton pathName ?options?
    +

    STANDARD OPTIONS

    +
    +
    -activebackground, activeBackground, Foreground +
    -activeforeground, activeForeground, Background +
    -anchor, anchor, Anchor +
    -background or -bg, background, Background +
    -bitmap, bitmap, Bitmap +
    -borderwidth or -bd, borderWidth, BorderWidth +
    -cursor, cursor, Cursor +
    -disabledforeground, disabledForeground, DisabledForeground +
    -font, font, Font +
    -foreground or -fg, foreground, Foreground +
    -highlightbackground, highlightBackground, HighlightBackground +
    -highlightcolor, highlightColor, HighlightColor +
    -highlightthickness, highlightThickness, HighlightThickness +
    -image, image, Image +
    -justify, justify, Justify +
    -padx, padX, Pad +
    -pady, padY, Pad +
    -relief, relief, Relief +
    -takefocus, takeFocus, TakeFocus +
    -text, text, Text +
    -textvariable, textVariable, Variable +
    -underline, underline, Underline +
    -wraplength, wrapLength, WrapLength +
    +

    WIDGET-SPECIFIC OPTIONS

    +
    +
    Command-Line Name: -direction +
    Database Name: direction +
    Database Class: Height +
    Specifies where the menu is going to be popup up. above tries to +pop the menu above the menubutton. below tries to pop the menu +below the menubutton. left tries to pop the menu to the left of +the menubutton. right tries to pop the menu to the right of the +menu button. flush pops the menu directly over the menubutton. +

    Command-Line Name: -height +
    Database Name: height +
    Database Class: Height +
    Specifies a desired height for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in lines of text. +If this option isn't specified, the menubutton's desired height is computed +from the size of the image or bitmap or text being displayed in it. +

    Command-Line Name: -indicatoron +
    Database Name: indicatorOn +
    Database Class: IndicatorOn +
    The value must be a proper boolean value. If it is true then +a small indicator rectangle will be displayed on the right side +of the menubutton and the default menu bindings will treat this +as an option menubutton. If false then no indicator will be +displayed. +

    Command-Line Name: -menu +
    Database Name: menu +
    Database Class: MenuName +
    Specifies the path name of the menu associated with this menubutton. +The menu must be a child of the menubutton. +

    Command-Line Name: -state +
    Database Name: state +
    Database Class: State +
    Specifies one of three states for the menubutton: normal, active, +or disabled. In normal state the menubutton is displayed using the +foreground and background options. The active state is +typically used when the pointer is over the menubutton. In active state +the menubutton is displayed using the activeForeground and +activeBackground options. Disabled state means that the menubutton +should be insensitive: the default bindings will refuse to activate +the widget and will ignore mouse button presses. +In this state the disabledForeground and +background options determine how the button is displayed. +

    Command-Line Name: -width +
    Database Name: width +
    Database Class: Width +
    Specifies a desired width for the menubutton. +If an image or bitmap is being displayed in the menubutton then the value is in +screen units (i.e. any of the forms acceptable to Tk_GetPixels); +for text it is in characters. +If this option isn't specified, the menubutton's desired width is computed +from the size of the image or bitmap or text being displayed in it. +
    +

    INTRODUCTION

    +The menubutton command creates a new window (given by the +pathName argument) and makes it into a menubutton widget. +Additional +options, described above, may be specified on the command line +or in the option database +to configure aspects of the menubutton such as its colors, font, +text, and initial relief. The menubutton command returns its +pathName argument. At the time this command is invoked, +there must not exist a window named pathName, but +pathName's parent must exist. +

    +A menubutton is a widget that displays a textual string, bitmap, or image +and is associated with a menu widget. +If text is displayed, it must all be in a single font, but it +can occupy multiple lines on the screen (if it contains newlines +or if wrapping occurs because of the wrapLength option) and +one of the characters may optionally be underlined using the +underline option. In normal usage, pressing +mouse button 1 over the menubutton causes the associated menu to +be posted just underneath the menubutton. If the mouse is moved over +the menu before releasing the mouse button, the button release +causes the underlying menu entry to be invoked. When the button +is released, the menu is unposted. +

    +Menubuttons are typically organized into groups called menu bars +that allow scanning: +if the mouse button is pressed over one menubutton (causing it +to post its menu) and the mouse is moved over another menubutton +in the same menu bar without releasing the mouse button, then the +menu of the first menubutton is unposted and the menu of the +new menubutton is posted instead. +

    +There are several interactions between menubuttons and menus; see +the menu manual entry for information on various menu configurations, +such as pulldown menus and option menus. + +

    WIDGET COMMAND

    +The menubutton command creates a new Tcl command whose +name is pathName. This +command may be used to invoke various +operations on the widget. It has the following general form: +
    pathName option ?arg arg ...?
    +Option and the args +determine the exact behavior of the command. The following +commands are possible for menubutton widgets: +

    +

    +

    pathName cget option
    +Returns the current value of the configuration option given +by option. +Option may have any of the values accepted by the menubutton +command. +

    pathName configure ?option? ?value option value ...?
    +Query or modify the configuration options of the widget. +If no option is specified, returns a list describing all of +the available options for pathName (see Tk_ConfigureInfo for +information on the format of this list). If option is specified +with no value, then the command returns a list describing the +one named option (this list will be identical to the corresponding +sublist of the value returned if no option is specified). If +one or more option-value pairs are specified, then the command +modifies the given widget option(s) to have the given value(s); in +this case the command returns an empty string. +Option may have any of the values accepted by the menubutton +command. + +

    +

    DEFAULT BINDINGS

    +Tk automatically creates class bindings for menubuttons that give them +the following default behavior: +

    +

    +

    [1]
    +A menubutton activates whenever the mouse passes over it and deactivates +whenever the mouse leaves it. +

    [2]
    +Pressing mouse button 1 over a menubutton posts the menubutton: +its relief changes to raised and its associated menu is posted +under the menubutton. If the mouse is dragged down into the menu +with the button still down, and if the mouse button is then +released over an entry in the menu, the menubutton is unposted +and the menu entry is invoked. +

    [3]
    +If button 1 is pressed over a menubutton and then released over that +menubutton, the menubutton stays posted: you can still move the mouse +over the menu and click button 1 on an entry to invoke it. +Once a menu entry has been invoked, the menubutton unposts itself. +

    [4]
    +If button 1 is pressed over a menubutton and then dragged over some +other menubutton, the original menubutton unposts itself and the +new menubutton posts. +

    [5]
    +If button 1 is pressed over a menubutton and released outside +any menubutton or menu, the menubutton unposts without invoking +any menu entry. +

    [6]
    +When a menubutton is posted, its associated menu claims the input +focus to allow keyboard traversal of the menu and its submenus. +See the menu manual entry for details on these bindings. +

    [7]
    +If the underline option has been specified for a menubutton +then keyboard traversal may be used to post the menubutton: +Alt+x, where x is the underlined character (or its +lower-case or upper-case equivalent), may be typed in any window +under the menubutton's toplevel to post the menubutton. +

    [8]
    +The F10 key may be typed in any window to post the first menubutton +under its toplevel window that isn't disabled. +

    [9]
    +If a menubutton has the input focus, the space and return keys +post the menubutton. +

    +

    +If the menubutton's state is disabled then none of the above +actions occur: the menubutton is completely non-responsive. +

    +The behavior of menubuttons can be changed by defining new bindings for +individual widgets or by redefining the class bindings. + +

    KEYWORDS

    +menubutton, widget +
    +Copyright © 1990-1994 The Regents of the University of California.
    +Copyright © 1994-1997 Sun Microsystems, Inc.
    +Copyright © 1995-1997 Roger E. Critchlow Jr.
    + diff --git a/hlp/ru/tk/message.html b/hlp/ru/tk/message.html new file mode 100644 index 0000000..1f47460 --- /dev/null +++ b/hlp/ru/tk/message.html @@ -0,0 +1,162 @@ + + + + message + + + +

    message

    + +

    Создание примитива сообщения и управление им.

    + + +

    СИНТАКСИС

    + +
    +      message имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -anchor
    • +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -takefocus
    • +
    • -text
    • +
    • -textvariable
    • +
    • -width
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-aspect
    Имя в Базе:aspect
    Класс в Базе:Aspect
    + +

    Целое число, указывающее желаемые пропорции текста. Его + значение равно 100*ширина/высота. Значение "100" - + означает, что ширина текста должна равняться его высоте, + значение "200" - что текст должен быть вдвое шире по + сравнению с высотой, значение "50" - что его высота + должна быть вдвое больше ширины и т.д. Используется для + определения длины строки, если не задан параметр width. Значение + по умолчанию равно "150".

    + + + + + +
    Имя параметра:-justify
    Имя в Базе:justify
    Класс в Базе:Justify
    + + + + + +
    Имя параметра: -width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину окна (в любом виде, приемлемом для + Tk_GetPixels). Если значение параметра + положительно, то параметр aspect игнорируется, + а параметр width задает длину строки. Если + значение параметра неположительно, то длина строки определяется + параметром aspect.

    + +

    ОПИСАНИЕ

    + +

    Команда messageсозадает новое окно (задаваемое + аргументом имяПути) и превращает его в примитив + сообщения. Детали изображения сообщения, такие как его цвета, + шрифт, текст и объемный вид задаются с помощью описанных выше + дополнительных параметров. Команда message + возвращает аргумент имяПути. В момент + выполнения этой команды не должно существовать окна с именем + имяПути, но должен существовать его предок.

    + +

    Сообщение представляет собой примитив, предназначенный для + вывода строки текста. У примитива сообщения есть три специальных + свойства. Во-первых, он разбивает строку сообщения на строчки, + чтобы обеспечить заданные пропорции окна. Перевод строки + осуществляется, по возможности, на границах слов (если в строку + не помещается ни одного целого слова, то слово разбивается на + несколько строк). Для переноса строки в нее вставляются символы + перевода строки; их можно использовать, например, для вывода + пустых строчек на экран.

    + +

    Вторым свойством примитива сообщения является возможность + выравнивания. Строчки сообщения могут быть выровнены влево + (каждая строка начинается от левого края окна), по центру или + вправо (каждая строка кончается у правого края окна).

    + +

    Третье свойство примитива сообщения состоит в том, что он + специальным образом обрабатывает управляющие символы и + непечатные символы. Символы табуляции заменяются пробелами, + число которых равно расстоянию до ближайшего кратного 8-ми + символам. Символы перевода строки вызывают переход на новую + строку. Другие управляющие символы (код ASCII которых меньше + 0x20) и символы, не определенные в шрифте сообщения, выводятся в + виде последовательности из четырех символов \xhh, где hh это две + шестнадцатиричные цифры, представляющие собой ASCII код данного + символа. В том редком случае, когда в шрифте отсутствуют + некоторые из символов "0123456789abcdef\x" управляющие + символы и неопределенные символы вообще не выводятся.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда message создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы сообщения допускают следующие формы команды

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр.Параметр может быть любым из + параметров команды message.
    + +
    имяПути configure + параметр ?значение параметр значение + ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых + вимениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам + примитива присваиваются новые значения, а команда + возвращает пустую строку. Параметр может быть любым + из параметров команды message .
    +
    + +

    ПАРАМЕТРЫ ПО УМОЛЧАНИЮ

    + +

    При создании сообщения параметры по умолчанию отсутствуют: + сообщения предназначены только для вывода текста.

    + + + diff --git a/hlp/ru/tk/option.html b/hlp/ru/tk/option.html new file mode 100644 index 0000000..88b7274 --- /dev/null +++ b/hlp/ru/tk/option.html @@ -0,0 +1,37 @@ + + + + option + + + +

    option

    + +

    Команда добавляет/получает параметры окон в/из базы данных + параметров окон.

    + +

    СИНТАКСИС

    + +
    +      option add pattern value ?priority?
    +      option clear
    +      option get window name class
    +      option readfile fileName ?priority?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда позволяет добавить в базу данных параметров окон новые + значения, считать из нее значения указанных параметров, очистить + базу или добавить в базу данные из указанного файла стандартного + формата. Аргумент patternзадает конкретный параметр и + состоит из имен параметров и/или классов. Аргумент + value содержит значение параметра. Аргумент + fileName задает файл со значениями + параметров. Необязательный аргумент priority указывает + уровень приоритета для ввода параметра.

    + + + + + diff --git a/hlp/ru/tk/options.html b/hlp/ru/tk/options.html new file mode 100644 index 0000000..8abf4a9 --- /dev/null +++ b/hlp/ru/tk/options.html @@ -0,0 +1,607 @@ + + + + options + + + +

    options

    + +

    Приведено описание стандартных параметров примитивов.

    + +

    Здесь приводится описание всех стандартных параметров + примитивов. Не все параметры используются примитивами, но если + примитив использует некоторый параметр, то действие этого + параметра будет именно таким, как оно описано.

    + +

    ОПИСАНИЕ

    + +

    options стандартные параметры, поддерживаемые + примитивами.

    + +

    В этом разделе руководства описываются общие параметры + конфигурации, поддерживаемые примитивами (виджетами) языка + Tk. Не каждый примитив поддерживает все параметры (список + стандартных параметров примитива приведен в описании этого + примитива), однако если примитив поддерживает параметр, имя + которого приведено в нижеследующем списке, то результат его + указания совпадает с описанным ниже.

    + +

    В приводимом ниже описании строка .Имя Параметра. указывает имя + переключателя в командах класса и командах примитивов configure, + предназначенных для установки значения параметра. Если, + например, в строке. Имя параметра. указано имя + -foreground и имеется примитив .a.b.c, то с + помощью команды

    + +
    +      .a.b.c configure -foreground black
    +    
    + +

    можно присвоить значение black параметру + -foreground примитива .a.b.c. + Для имен параметров можно использовать сокращения, сохраняющие + однозначность интерпретации имени. В поле "Имя в + Базе" приводится имя параметра в базе X-ресурсов (например, в + файле .Xdefaults). В поле "Класс в Базе" приводится имя класса + базы в файле X-ресурсов (например, в файле .Xdefaults).

    + + + + + +
    Имя параметра:-activebackground
    Имя в Базе:activeBackground
    Класс в Базе:Foreground
    + +

    Задает цвет фона при изображении активных элементов. Элемент + (примитив или его часть) активен, если на нем находится курсор + "Мыши" и нажатие на клавишу "Мыши" вызывает + некоторое действие. Если установлено значение переменной + tk_strictMotif, то значение указанного + параметра игнорируется и используется обычный цвет фона. Для + некоторых элементов в системах Windows и Macintosh установленный + цвет активизируется только при щелчке клавиши 1 на элементе.

    + + + + + +
    Имя параметра:-activedorderwidth
    Имя в Базе:activeBorderWidth
    Класс в Базе:BorderWidth
    + +

    Задает неотрицательное значение ширины трехмерного бордюра, + окружающего активные элементы. Определение активных элементов + приведено выше. Значение может быть задано в любом + виде,воспринимаемом командой Tk + GetPixels. Обычно этот параметр доступен только для + примитивов, отображающих более одного элемента одновременно + (меню, а не кнопки).

    + + + + + +
    Имя параметра:-activeforeground
    Имя в Базе:activeForeground
    Класс в Базе:Background
    + +

    Задает цвет изображения активного элемента. Определение + активных элементов приведено выше.

    + + + + + +
    Имя параметра:-anchor
    Имя в Базе:anchor
    Класс в Базе:Anchor
    + +

    Задает способ отображения информации (типа текст или bitmap) в + примитиве. Должен принимать одно из значений + n, ne, e, + se, s, + sw, w, nw + или center, которые указывают на стороны + света. Например, значение nw указывает на необходимость + такого отображения информации, что ее левый верхний угол + совпадает с левым верхним уровнем примитива.

    + + + + + +
    Имя параметра:-background or -bg
    Имя в Базе:background
    Класс в Базе:Background
    + +

    Задает нормальный цвет фона при отображении примитива.

    + + + + + +
    Имя параметра:-bitmap
    Имя в Базе:bitmap
    Класс в Базе:Bitmap
    + +

    Задает информацию типа bitmap в любом виде, + приемлемом для TkGetBitMap для отображения в + примитиве. Другие параметры, вроде anchor и + justify, уточняют способ отображения + информации типа bitmap. Обычно при + задании этого параметра значения остальных параметров, + задающих способ отображения текстовой информации, + игнорируются. Для восстановления возможности вывода текстовой + информации в примитиве следует задать значение параметра + bitmap в виде пустой строки. Задание параметра image подавляет параметр bitmap в примитивах, + использующих оба эти параметра.

    + + + + + +
    Имя параметра:-borderwidth or -bd
    Имя в Базе:borderWidth
    Класс в Базе:BorderWidth
    + +

    Задает неотрицательное значение ширины трехмерного бордюра, + окружающего изображение примитива (при выводе такого бордюра; + необходимость его вывода обычно указывается параметром + relief). То же значение может быть использовано + при имитации трехмерной графики внутри примитива. Значение + параметра может быть любым из тех, что приемлемы для + TkGetPixels.

    + + + + + +
    Имя параметра:-cursor
    Имя в Базе:cursor
    Класс в Базе:Cursor
    + +

    Задает форму курсора .Мыши. на примитиве. Значение параметра + должно быть одним из значений, которые перечислены в файле + /usr/X11R6/unclude/X11/cursorfont.h, например, + X_cursor, arrow, + boat, clock, + cross, то есть можно указывать любое значение + их данного файла, в котором нужно опустить первые три символа + XC_.

    + + + + + +
    Имя параметра:-disabledforeground
    Имя в Базе:disabledForeground
    Класс в Базе:DisabledForeground
    + +

    Задает цвет переднего плана для изображения недоступного + элемента. При вводе пустой строки (типичная ситуация для + монохромного дисплея) недоступные элементы изображаются обычным + цветом, однако их изображение делается более тусклым за счет + штриховки.

    + + + + + +
    Имя параметра:-exportselection
    Имя в Базе:exportSelection
    Класс в Базе:ExportSelection
    + +

    Указывает, должен ли выбранный элемент в примитиве входить + также и в X-выборку. Значение параметра должно быть допустимым + аргументом функции TclGetBoolean, скажем + true, false, + 0, 1, yes или + no. При экспорте выбранного элемента выборка в + примитиве отменяет текущую X-выборку; выборка за пределами + примитива отменяет текущую выборку в примитиве. При наличии в + примитиве выбранного элемента примитив отзывается на запросы + поиска выбранных элементов. По умолчанию примитивы обычно + экспортируют выбранные элементы.

    + + + + + +
    Имя параметра:-font
    Имя в Базе:font
    Класс в Базе:Font
    + +

    Задает шрифт для отображения текста внутри примитива. Синтаксис + имени шрифта описан в команде font. Список доступных + шрифтов можно получить командой xlsfonts.

    + + + + + +
    Имя параметра:-fg
    Имя в Базе:foreground
    Класс в Базе:Foreground
    + +

    Задает нормальный цвет переднего плана примитива.

    + + + + + +
    Имя параметра:-highlightbackground
    Имя в Базе:highlightBackground
    Класс в Базе:HighlightBackground
    + +

    Задает цвет яркого прямоугольника обрамляющего примитив, + находящийся вне фокуса ввода.

    + + + + + +
    Имя параметра:-highlightcolor
    Имя в Базе:highlightColor
    Класс в Базе:HighlightColor
    + +

    Задает цвет яркого прямоугольника обрамляющего примитив, + находящийся в фокусе ввода.

    + + + + + +
    Имя параметра:-highlightthickness
    Имя в Базе:highlightThickness
    Класс в Базе:HighlightThickness
    + +

    Задает неотрицательное значение ширины яркого прямоугольника + вокруг примитива, находящегося в фокусе ввода. Значение + параметра должно быть допустимым аргументом функции + Tk_GetPixels. При значении, равном нулю, яркая + рамочка вокруг примитива не выводится.

    + + + + + +
    Имя параметра:-image
    Имя в Базе:image
    Класс в Базе:Image
    + +

    Задает изображение, которое должно быть выведено в примитиве, + созданном командой image + create. Обычно при задании параметра image значения других + параметров, задающих текстовые или bitmap данные для вывода + в примитиве, подавляются. Для восстановления возможности вывода + текстовых или bitmap данных следует задать пустое значение + параметра image.

    + + + + + +
    Имя параметра:-insertbackground
    Имя в Базе:insertBackground
    Класс в Базе:Foreground
    + +

    Задает цвет фона поля, на котором установлен курсор ввода. Этот + параметр подавляет цвет нормального фона примитива (или фона + выбранного элемента, если курсор ввода оказался на выбранном + элементе).

    + + + + + +
    Имя параметра:-insertborderwidth
    Имя в Базе:insertBorderWidth
    Класс в Базе:BorderWidth
    + +

    Задает неотрицательное значение ширины трехмерного бордюра + вокруг курсора ввода. Значение параметра должно быть допустимым + аргументом функции Tk_GetPixels.

    + + + + + +
    Имя параметра:-insertofftime
    Имя в Базе:insertOffTime
    Класс в Базе:OffTime
    + +

    Задает длину промежутка времени, в течение которого курсор + ввода находится в режиме "off" + (неотрицательное целое значение в миллисекундах) на протяжении + одного цикла мигания. Если введенное значение равно нулю, то + курсор не мигает: он всегда находится в режиме + "on".

    + + + + + +
    Имя параметра:-inserontime
    Имя в Базе:insertOnTime
    Класс в Базе:OnTime
    + +

    Задает длину промежутка времени, в течение которого курсор + ввода находится в режиме "on" (неотрицательное целое + значение в миллисекундах) на протяжении одного цикла мигания.

    + + + + + +
    Имя параметра:-insertwidth
    Имя в Базе:insertWidth
    Класс в Базе:InsertWidth
    + +

    Задает полную ширину курсора ввода. Значение параметра должно + быть допустимым аргументом функции + Tk_GetPixels. Если (с помощью параметра + insertBorderWidth) задана ширина бордюра, то + бордюр будет располагаться внутри отведенной ширины курсора.

    + + + + + +
    Имя параметра:-jump
    Имя в Базе:jump
    Класс в Базе:Jump
    + +

    Задает тип изменения значения примитива для примитивов, + поддерживающих полосу прокрутки. Значение параметра должно быть + допустимым булевским аргументом функции + Tk_GetBoolean. При значении параметра + false значения примитива изменяются + непрерывно. При значении параметра true значение примитива не + меняется до окончания движения бегунка и отпускания клавиши + "Мыши". В этот момент происходит установка нового + значения ("скачок", в отличие от непрерывного + изменения).

    + + + + + +
    Имя параметра:-justify
    Имя в Базе:justify
    Класс в Базе:Justify
    + +

    Описывает способ выравнивания текста, состоящего из нескольких + строк, в окне примитива. Может принимать значения + left, center или + right. Leftозначает, что + выравниваются левые концы строк, center их + середины, right правые концы.

    + + + + + +
    Имя параметра:-orient
    Имя в Базе:orient
    Класс в Базе:Orient
    + +

    Указывает ориентацию примитива, допускающего различные + ориентации (так, полоса прокрутки может быть расположена + горизонтально или вертикально). Может принимать значения + horizontal или vertical, а + также их сокращения.

    + + + + + +
    Имя параметра:padx
    Имя в Базе:padX
    Класс в Базе:Pad
    + +

    Неотрицательное значение, указывающее размер запрашиваемого + дополнительного пространства для примитива в + X-направлении. Значение параметра должно быть допустимым + аргументом функции Tk_GetPixels. При подсчете + необходимого размера окна эта величина добавляется к обычному + размеру, определяемому суммированием всех размеров всех его + деталей. Если программа вывода в состоянии удовлетворить + выданный запрос, то в правой и/или левой части окна примитива + появляется дополнительное пространство. В большинстве случаев + это пространство используется только для расположения там + текста; при выводе bitmap-данных или изображений оно + игнорируется.

    + + + + + +
    Имя параметра:-pady
    Имя в Базе:padY
    Класс в Базе:Pad
    + +

    Неотрицательное значение, указывающее размер запрашиваемого + дополнительного пространства для примитива в + Y-направлении. Значение параметра должно быть допустимым + аргументом функции Tk_GetPixels. При подсчете + необходимого размера окна эта величина добавляется к обычному + размеру, определяемому суммированием всех размеров всех его + деталей. Если программа вывода в состоянии удовлетворить + выданный запрос, то в правой и/или левой части окна примитива + появляется дополнительное пространство. В большинстве случаев + это пространство используется только для расположения там + текста; при выводе bitmap-данных или изображений оно + игнорируется.

    + + + + + +
    Имя параметра:-relief
    Имя в Базе:relief
    Класс в Базе:Relief
    + +

    Задает тип трехмерной графики в примитиве. Допустимы значения + raised, sunken, + flat, ridge, + solid или groove. Значение + указывает на способ размещения внутренней части окна по + отношению к фону. Например, значение raised + указывает, что внутренняя часть окна должна выступать из + экрана.

    + + + + + +
    Имя параметра:-repeatdelay
    Имя в Базе:repeatDelay
    Класс в Базе:RepeatDelay
    + +

    Указывает продолжительность нажатия на кнопку или клавишу (в + миллисекундах), необходимую для установления режима + автоматического повторения. Используется, например, при работе + со стрелками полосы прокрутки.

    + + + + + +
    Имя параметра:-repeatinterval
    Имя в Базе:repeatInterval
    Класс в Базе:RepeatInterval
    + +

    Используется в паре с repeatDelay: при + установлении режима автоматического повторения этот параметр + задает длину промежутка времени между автоматическими + повторениями.

    + + + + + +
    Имя параметра:-selectbackground
    Имя в Базе:selectBackground
    Класс в Базе:Foreground
    + +

    Задает цвет фона при отображении выбранных элементов.

    + + + + + +
    Имя параметра:-selectborderwidth
    Имя в Базе:selectBorderWidth
    Класс в Базе:BorderWidth
    + +

    Задает ширину трехмерного бордюра вокруг выбранных + элементов. Допустимы любые значения, воспринимаемые командой + Tk_GetPixels.

    + + + + + +
    Имя параметра:-selectforeground
    Имя в Базе:selectForeground
    Класс в Базе:Background
    + +

    Задает цвет переднего плана для изображения выбранных элементов.

    + + + + + +
    Имя параметра:-setgrid
    Имя в Базе:setGrid
    Класс в Базе:SetGrid
    + +

    Задает булевское значение, определяющее, управляет ли данный + примитив масштабирующей сеткой своего окна верхнего + уровня. Обычно этот параметр используется в текстовых примитивах + с естественным размером отображаемой информации (размером + символа) и размеры окна осмысленно выбирать пропорциональными + этому стандартному размеру. Эти разумные размеры окон образуют + сетку. Если задано значение true параметра + setGrid, то примитив установит связь с + менеджером окон. В этом случае при интерактивном запросе + пользователя на изменение размеров окна верхнего уровня, + содержащего примитив, возможный список размеров окна будет + передан пользователю в единицах сетки, и значения его длины и + ширины должны быть пропорциональны сторонам ячейки сетки. Более + подробно этот процесс описан ниже (см. "УПРАВЛЕНИЕ + ГЕОМЕТРИЕЙ СЕТОК" в описании команды wm). + + + + + +
    Имя параметра:-takefocus
    Имя в Базе:takeFocus
    Класс в Базе:TakeFocus
    + +

    Указывает, допустима ли установка фокуса на окне с помощью + клавиатуры (клавишами Tab и + Shift-Tab). Перед установкой фокуса на окне + скрипты перевода фокуса проверяют значение параметра + takeFocus. Значение "0" указывает на + необходимость пропускать окно при клавиатурном переключении + фокуса. Значение "1" указывает на то, что при видимом + окне (и всех его наследниках) фокус должен устанавливаться на + нем. Пустое значение указывает на то, что скрипт переключения + сам принимает решение, следует ли устанавливать фокус на данном + окне: в текущем варианте окно пропускается, если оно отключено + или в нем нет ключевых связок, или оно невидимо. При любом + другом значении параметра скрипт переключения добавляет к этому + значению имя окна (через разделяющий пробел) и интерпретирует + получившуюся строку как скрипт Tcl. Скрипт должен возвращать + значение "0", "1" или пустую + строку. Значения "0" и "1" указывают, должен + ли фокус ввода установиться на окно, пустая строка вызывает + обработку по умолчанию, описанную выше. Замечание: подобная + обработка параметра целиком определяется скриптами переключения + Tcl; реализация примитивов полностью игнорирует рассматриваемый + параметр.

    + + + + + +
    Имя параметра:-text
    Имя в Базе:text
    Класс в Базе:Text
    + +

    Задает строку, выводимую в примитиве. Способ вывода строки + зависит от конкретного примитива и определяется значениями + других параметров, таких как anchor или + justify.

    + + + + + +
    Имя параметра:-textvariable
    Имя в Базе:textVariable
    Класс в Базе:Variable
    + +

    Задает имя переменной. Значением переменной является текстовая + строка, которая должна быть выведена в примитиве. При изменении + значения переменной выведенная строка тут же изменяется. Способ + вывода строки зависит от конкретного примитива и определяется + значениями других параметров, таких как anchor + или justify.

    + + + + + +
    Имя параметра:-troughcolor
    Имя в Базе:troughColor
    Класс в Базе:Background
    + +

    Задает цвет обрамляющих прямоугольников полосы прокрутки, поля + масштабов и т.д. в примитиве

    + + + + + +
    Имя параметра:-underline
    Имя в Базе:underline
    Класс в Базе:Underline
    + +

    Задает номер подчеркиваемого символа в примитиве. Этот параметр + используется связками по умолчанию для клавиатурного + переключения кнопок меню и полей меню. "0" + соответствует первому символу, "1" второму, и т.д.

    + + + + + +
    Имя параметра:-wraplength
    Имя в Базе:wrapLength
    Класс в Базе:WrapLength
    + +

    Для примитивов, способных выполнять перенос строк этот + параметр задает максимальную длину строки. Строки, длина которых + превосходит установленную, переносятся на следующую строку. Это + значение может быть задано в любом виде, в котором могут + задаваться экранные расстояния. Если это значение + неположительно, то переноса не происходит: он выполняется только + при появлении символа переноса строки.

    + + + + + +
    Имя параметра:-xscrollcommand
    Имя в Базе:xScrollCommand
    Класс в Базе:ScrollCommand
    + +

    Задает префикс команды, используемой для связи с горизонтальной + полосой прокрутки. При изменении содержимого окна примитива (или + любом другом событии, которое может повлечь за собой изменение + вида полосы прокрутки, скажем изменении размера содержимого + примитива) примитив генерирует команду Tcl путем конкатенации + значения параметра и двух чисел, каждое из которых представляет + собой дробь между нулем и единицей. Числа указывают положение + текста в документе. "0" указывает на начало документа, + "1" на его конец, ".333" на одну треть от + начала документа и т.д. Первое число обозначает начало видимой + части документа, второе на позицию, непосредственно следующую за + концом видимой части. Затем команда передается интерпретатору + Tcl для выполнения. Обычно значение параметра + xScrollCommand состоит из имени пути к + примитиву полосы прокрутки, за которым следует слово + "set", например, .x.scrollbar + set: в результате состояние полосы будет изменяться + всякий раз при изменении содержимого окна. Если параметр не + задан, то никакая команда не будет исполняться.

    + + + + + +
    Имя параметра:-yscrollcommand
    Имя в Базе:yScrollCommand
    Класс в Базе:ScrollCommand
    + +

    Задает префикс команды, используемой для связи с вертикальной + полосой прокрутки. Этот параметр интерпретируется так же, как и + параметр xScrollCommand, за исключением того, + что он относится к вертикальной полосе прокрутки и используется + в примитивах, которые такую полосу поддерживают. Подробное + описание см. выше.

    + + + diff --git a/hlp/ru/tk/pack-old.html b/hlp/ru/tk/pack-old.html new file mode 100644 index 0000000..e61096e --- /dev/null +++ b/hlp/ru/tk/pack-old.html @@ -0,0 +1,235 @@ + + + + pack-old + + +

    pack-old

    + +

    Устаревшая команда для геометрического менеджера упаковки + окон.

    + +

    СИНТАКСИС

    + +
    +      pack after sibling окно параметры ?окно параметры...?
    +      pack append parent окно параметры ?окно параметры...?
    +      pack before sibling окно параметры ?окно параметры...?
    +      pack unpack окно
    +    
    + +

    ОПИСАНИЕ

    + +

    Замечание. Ниже описан синтаксис команды + pack, употреблявшейся в версиях Tk до 3.3. Хотя + в целях совместимости поддержка команды в системе сохранена, + команда является устаревшей и использовать ее не + следует. Возможно, в будущем ее поддержка + прекратится.

    + +

    Упаковщик представляет собой геометрический менеджер, + предназначенный для размещения непосредственных потомков + примитива по сторонам примитива в порядке их появления. Первый + потомок размещается вдоль одной стороны примитива, занимая всю + протяженность окна вдоль этой стороны. В результате, для + следующих потомков остается усеченное окно, как если бы + выбранная сторона сдвинулась внутрь на размер первого + потомка. Вдоль одной из сторон оставшейся области размещается + второй потомок, и так далее до тех пор, пока не будут размещены + все потомки или пока не исчерпается свободное место.

    + +

    Формы before, after и + append команды pack + используются для вставки одного или нескольких непосредственных + потомков в очередь упаковки их родителя. В форме + before команда вставляет окно-потомка перед + родственными узлами; все остальные окна должны быть узлами + одного уровня. В форме after окна вставляются + после родственных узлов, а в форме append + добавляет одно или несколько окон к очереди упаковки их + родителя. Если окно, указанное в любой из этих + команд уже упаковано в родительское окно, то оно удаляется со + своего текущего положения в порядке упаковки и перемещается в + соответствии с командой. Все эти команды возвращают в качестве + результата пустую строку.

    + +

    Форма unpack команды pack + command удаляет окно из очереди упаковки его + родителя и стирает его с экрана. После выполнения этой команды + упаковщик более не управляет геометрией окна.

    + +

    На самом деле, размещение каждого потомка представляет собой + четырехступенчатую процедуру; значение параметра, + следующего за окном, представляет собой список из + одного или нескольких полей, управляющих размещением окна. В + нижеследующем обсуждении термин полость (cavity) + обозначает место в окне-родителе, оставшееся после размещения + конкретного потомка (т.е. все то место, которое не было + запрошено при размещении предыдущих потомков в очереди). Термин + доля (parcel) обозначает количество места, + отведенного конкретному потомку; это количество не обязательно + соответствует окончательной геометрии окна-потомка.

    + +

    Первый шаг в размещении потомка состоит в выборе стороны + полости, вдоль которой он будет располагаться. Для указания + стороны можно пользоваться любым из следующих параметров:

    + +
    +
    top
    + +
    Отводит долю потомка у верхней стороны полости на всю ширину + полости.
    + +
    bottom
    + +
    Отводит долю потомка у нижней стороны полости на всю ширину + полости.
    + +
    left
    + +
    Отводит долю потомка у левой стороны полости на всю высоту + полости.
    + +
    right
    + +
    Отводит долю потомка у правой стороны полости на всю высоту + полости.
    +
    + +

    Для каждого окна следует задать ровно один из этих + параметров. Значением стороны по умолчанию является + top. Второй шаг состоит в определении доли + потомка. Для верхнего и + нижнего окон желательная ширина доли обычно + совпадает с шириной полости, а желательная высота совпадает с + запрошенной высотой доли, которая передается команде + Tk_GeometryRequest. Для левого и + правого окон желательная высота доли обычно + совпадает с высотой полости, а желательная ширина совпадает с + запрошенной шириной доли. Однако с помощью каждого из описанных + ниже параметров для окна можно запросить дополнительное + место:

    + +
    +
    padx число
    + +
    Добавляет число пикселей к запрошенной + ширине окна перед вычислением размера доли, как это было описано + выше.
    + +
    pady число
    + +
    Добавляет число пикселей к запрошенной высоте окна + перед вычислением размера доли, как это было описано + выше.
    + +
    expand
    + +
    Этот параметр указывает на то, что доля окна захватывает все + свободное пространство, оставшееся в полости окна-родителя + после упаковки всех его потомков. Размер оставшегося + пространства зависит от размеров, запрошенных для всех + потомков; он может равняться нулю. Если + расширения (expand) затребовали несколько + окон, то вся дополнительная ширина будет поделена поровну + между всеми левыми и правыми + окнами, запросившими расширение, а вся + дополнительная высота будет поделена поровну между всеми + верхними и нижними окнами, + запросившими расширение.
    +
    + +

    Если желаемая ширина или высота превосходит соответствующую + протяженность полости, то вместо нее используется эта размер + этой протяженности.

    + +

    На третьем шаге размещения окна следует принять решение о его + ширине и высоте. По умолчанию окно получает либо запрошенные + ширину и высоту, либо ширину и высоту доли в зависимости от + того, что из них меньше. Если доля больше, чем запрошенный + размер окна, то окно можно расширить так, чтобы оно полностью + или частично покрывало долю, с помощью следующих параметров:

    + +
    +
    fill
    + +
    Делает размеры окна равными размерам доли.
    + +
    fillx
    + +
    Увеличивает ширину окна до ширины доли, сохраняя высоту + окна.
    + +
    filly
    + +
    Увеличивает высоту окна до высоты доли, сохраняя ширину + окна.
    +
    + +

    На последнем этапе происходит размещение окна внутри его + доли. Если размеры окна и доли совпадают, то окно просто целиком + заполняет долю. Если доля больше окна, то положение окна + определяется с помощью одного из следующих параметров:

    + +
    +
    frame center
    + +
    Размещает окно по центру доли. Если параметр размещения + опущен, то центральное размещение принимается по + умолчанию.
    + +
    frame n
    + +
    Размещает окно так, что его верхняя сторона располагается по + центру верхней стороны доли.
    + +
    frame ne
    + +
    Размещает окно так, что его правый верхний угол + располагается в правом верхнем углу доли.
    + +
    frame e
    + +
    Размещает окно так, что его правая сторона располагается по + центру правой стороны доли.
    + +
    frame se
    + +
    Размещает окно так, что его правый нижний угол располагается + в правом нижнем углу доли.
    + +
    frame s
    + +
    Размещает окно так, что его нижняя сторона располагается по + центру нижней стороны доли.
    + +
    frame sw
    + +
    Размещает окно так, что его левый нижний угол располагается + в левом нижнем углу доли.
    + +
    frame w
    + +
    Размещает окно так, что его левая сторона располагается по + центру левой стороны доли.
    + +
    frame nw
    + +
    Размещает окно так, что его левый верхний угол располагается + в левом верхнем углу доли.
    +
    + +

    Упаковщик управляет состоянием размещенный/неразмещенный всех + упакованных непосредственных окон-потомков. При упаковке окон + упаковщик автоматически выводит их на экран; кроме того, он + стирает окна, для которых в полости остается недостаточно + места.

    + +

    Упаковщик посылает геометрические запросы от имени родителя + размещаемых окон. Для каждого окна-родителя он запрашивает + размер, достаточный для размещения всех упакованных потомков в + соответствии с указанными параметрами, так что на расширение + остается нулевой остаток.

    + + + diff --git a/hlp/ru/tk/pack.html b/hlp/ru/tk/pack.html new file mode 100644 index 0000000..6a1e040 --- /dev/null +++ b/hlp/ru/tk/pack.html @@ -0,0 +1,333 @@ + + + + pack + + + +

    pack

    + +

    Геометрический менеджер, который упаковывает виджеты по + сторонам внутреннего пространства окна.

    + +

    СИНТАКСИС

    + +
    +      pack option arg ?arg ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда pack используется для управления + соответствующим геометрическим менеджером, размещающим виджеты + по различным сторонам родительского окна, и для получения от + него справочной информации. Команда может иметь перечисленные + ниже формы в зависимости от значения аргумента + option.

    + +
    +
    pack slave ?slave ...? + ?options?
    + +
    Если первый аргумент команды является именем окна (любая + величина, начинающаяся с "."), команда выполняется + точно также, как команда pack configure.
    + +
    pack configure slave + ?slave ...? ?options?
    + +

    Аргумент команды состоит из имени одного или нескольких + размещаемых виджетов, после которых идут пары аргументов, + состоящих из имени опции и ее значения. Подробное описание + действий, выполняемых при размещении виджетов приведено ниже + (см. "Алгоритм + упаковки pack"). Ниже перечислены + возможные опции команды.

    + +
    +
    -after other
    + +
    Other должно быть именем другого + окна. Мастер-окна other используется как мастер + для slave. Список slave slave ... вставляется в + список размещаемых окон сразу после other.
    + +
    -anchor anchor
    + +
    Anchor должен быть одной из возможных позиций + якоря, например, n или + sw. Он определяет как размещается slave в + отведенном ему пространстве. Значение по умолчанию + c.
    + +
    -before other
    + +
    Other должно быть именем другого + окна. Мастер-окно окна other используется как + мастер-окно для slave. Список slave slave + ... вставляется в список размещаемых окон + непосредственно перед other.
    + +
    -expand boolean
    + +
    Определяет, будут ли перечисленные виджеты расширяться + при наличии свободного пространства в + мастер-окне. Boolean должно иметь булево + значение, например, 1 или + no. Значение по умолчанию + "0".
    + +
    -fill style
    + +

    Если в мастер-окне для slave имеется свободное + пространство, управляет растяжением виджета slave.

    + +

    Аргумент style может иметь одно из следующих + значений:

    + +
    +
    none
    + +
    Предоставляет виджету slave требуемый + размер (включая поля, запрошенные с помощью опций + -ipadx или + -ipady). Это значение по + умолчанию.
    + +
    x
    + +
    Расширяет виджет slave в горизонтальном + направлении так, чтобы он заполнил все свободное + пространство (за исключением внешних полей, заданных с + помощью опции -padx).
    + +
    y
    + +
    Расширяет виджет slave в вертикальном + направлении так, чтобы он заполнил все свободное + пространство (за исключением внешних полей, заданных с + помощью опции -pady.)
    + +
    both
    + +
    Расширяет виджет slave в обоих + направлениях.
    +
    +
    + +
    -in other
    + +
    Включает slave(s) в конец списка размещаемых окон для + окна other.
    + +
    -ipadx amount
    + +
    Аргумент amount указывает размер горизонтальных + внутренних полей, которые должны быть с обеих сторон + виджета slave. Размер должен быть указан в одной из форм, + в которой можно задавать размеры на экране, например, + 2 (2 пикселя) или .5c + (0.5 сантиметра). Значение по умолчанию 0.
    + +
    -ipady amount
    + +
    Аргумент amount указывает размер вертикальных + внутренних полей, которые должны быть с обеих сторон + виджета slave. Размер должен быть указан в одной из форм, + в которой можно задавать размеры на экране, например, + 2 (2 пикселя) или .5c + (0.5 сантиметра). Значение по умолчанию 0.
    + +
    -padx amount
    + +
    Аргумент amount указывает размер горизонтальных + внешних полей, которые должны быть с обеих сторон виджета + slave. Размер должен быть указан в одной из форм, в + которой можно задавать размеры на экране, например, + 2 (2 пикселя) или .5c + (0.5 сантиметра). Значение по умолчанию 0.
    + +
    -pady amount
    + +
    Аргумент amount указывает размер вертикальных + внешних полей, которые должны быть с обеих сторон виджета + slave. Размер должен быть указан в одной из форм, в + которой можно задавать размеры на экране, например, + 2 (2 пикселя) или .5c + (0.5 сантиметра). Значение по умолчанию 0.
    + +
    -side side
    + +
    Определяет, к какой стороне мастер-окна будут помещены + виджеты slave. Возможные значения аргумента side: + left, right, + top или bottom. Значение + по умолчанию top.
    +
    + +

    Если никакая из опций -in, + -after или -before не + указана, каждый из slave будет внесен в конец + списка размещения своего непосредственного родителя (если + только он не был внесен туда ранее, в этом случае он + останется на своем прежнем месте). Если же одна из + перечисленных опций указана, все slave будут + внесены в соответствующий список в указанное место.

    + +

    Если какие-либо из slave окон ранее уже + обрабатывались геометрическим менеджером, то для не + определенных в команде опций будут использоваться старые + значения, а не значения по умолчанию.

    +
    + +
    pack forget slave ?slave ...?
    + +
    Перечисленные окна удаляются из списка упаковки и с + экрана. Эти окна больше не управляются геометрическим + менеджером.
    + +
    pack info slave
    + +
    Возвращает список опций и их значений для окна + slave в той же форме, в какой они задаются в команде + pack configure. Первые два элемента списка + "-in master", где + "master" - имя окна, в котором размещается + slave.
    + +
    pack propagate master + ?boolean?
    + +
    Аргумент boolean, если он задан, определяет, будет + ли окно master расширяться при необходимости + (подробности приведены ниже, см. "Расширение виджетов"). Команда + при этом возвращает пустую строку. Если аргумент не задан, + команда возвращает текущее значение опции (0 + или 1). По умолчанию расширение + разрешено.
    + +
    pack slaves master
    + +
    Возвращает список всех размещаемых окон для + master. Если в окне master нет размещаемых + окон, возвращается пустой список.
    +
    + + +

    АЛГОРИТМ УПАКОВКИ pack

    + +

    Для каждого мастер-окна менеджер pack формирует список + упаковки. Место каждого виджета в нем может задаваться с помощью + опций -in, -after и + -before. Если эти опции не использовались, + каждый новый виджет добавляется в конец списка своего + непосредственного предка.

    + +

    Менеджер размещает виджеты в окне, последовательно просматривая + список упаковки. В момент обработки каждого из размещаемых + виджетов внутри мастера есть прямоугольная незаполненная + область. Эта область называется "полость". Для первого + обрабатываемого виджета "полость" совпадает со всей + внутренностью мастер-окна.

    + +

    Для каждого из размещаемых виджетов выполняются следующие + действия:

    + +
      +
    • менеджер размещает прямоугольную область для очередного + виджета у стороны полости, заданной опцией + -side. Если значение опции + top или bottom, то ширина + области равна ширине полости, а высота равна требуемой для + виджета высоте плюс внешние и внутренние поля, заданные + опциями -ipady и -pady. Если + значение опции равно left или + right, высота области равна высоте полости, а + ширина определяется размером виджета плюс полями, заданными + опциями -ipadx и + -padx. Область может быть расширена в одном + или обоих направлениях в зависимости от значения опции + -expand (см. ниже "Расширение + виджетов").
    • + +
    • менеджер определяет размеры виджета. Обычно они равны + размерам, необходимым для виджета, плюс удвоенные внутренние + поля, но могут быть расширены до размеров области (минус + удвоенные внешние поля) по одному или обоим направлениям в + зависимости от значения опции -fill.
    • + +
    • менеджер размещает виджет в отведенном ему + пространстве. Если виджет меньше свободного пространства, + используется значение опции -anchor. Если + определены внешние поля, то они всегда сохраняются между + виджетом и границами области, в которой он помещается.
    • +
    + + +

    После того, как очередной виджет размещен, выделенная ему + область (см. 1)) вычитается из полости. Полость + для следующего виджета остается прямоугольной, но меньшей по + размеру. Если виджет не занял полностью выделенную ему область, + ее оставшиеся свободными части не используются при размещении + последующих виджетов. Если полость оказывается мала для + очередного виджета, он получает столько пространства, сколько + осталось. Если полость сокращается до нуля, все оставшиеся + виджеты в списке упаковки удаляются с экрана. Если размеры окна + будут увеличены, они появятся на экране.

    + +

    РАСШИРЕНИЕ ВИДЖЕТОВ

    + + +

    Если мастер-окно оказалось больше, чем необходимо для + размещения всех виджетов, оставшееся пространство распределяется + равномерно между теми виджетами, для которых установлена опция + -expand. Дополнительное горизонтальное + пространство распределяется между теми виджетами, у которых + опция -side равна left или + right. Вертикальное пространство распределяется + между виджетами, у которых опция -side равна + top или bottom.

    + +

    РАСПРОСТРАНЕНИЕ РАЗМЕРОВ

    + +

    Обычно менеджер рассчитывает размеры мастер-окна, необходимые + для размещения виджетов, и, при необходимости, устанавливает + размеры мастер-окна таким образом, чтобы в нем в точности + поместились все виджеты из списка. Это приводит к тому, что + информация о размерах виджетов распространяется по + иерархическому дереву виджетов, в результате чего целое + поддерево изменяет свои размеры при изменении одного из + листьевых элементов. Однако команда pack + propagate может быть использована для отключения этого + механизма для одного или нескольких мастер-окон. Если + распространение размеров отключено, информация о необходимых + размерах не передается мастер-окну. Это может оказаться + полезным, если вы хотите, чтобы мастер-окно сохраняло те + размеры, которые вы определили.

    + +

    ОГРАНИЧЕНИЯ НА МАСТЕР-ОКНА

    + +

    Мастер-окно для каждого размещаемого виджета должно быть его + непосредственным предком (по умолчанию) или одним из потомков + его предка. Это ограничение гарантирует разумное поведение + виджетов при удалении toplevel-окон.

    + +

    ПОРЯДОК РАЗМЕЩЕНИЯ

    + +

    Если мастер-окно для виджета не является его непосредственным + предком, необходимо быть уверенным, что виджет лежит в стеке + окон выше, чем мастер-окно. В противном случае мастер-окно + закроет собой виджет и создастся впечатление, что виджет не + упакован правильным образом. Простейший способ избежать подобных + проблем следить, чтобы -окно было создано раньше, чем виджет + (чем позже создано окно, тем выше оно в стеке). Если это + почему-либо неудобно, можно использовать команды + raise и lower для изменения + порядка окон в стеке.

    + + + + + diff --git a/hlp/ru/tk/photo.html b/hlp/ru/tk/photo.html new file mode 100644 index 0000000..0133db9 --- /dev/null +++ b/hlp/ru/tk/photo.html @@ -0,0 +1,443 @@ + + + + photo + + + +

    photo

    + +

    Встроенный тип полноцветных изображений Tk.

    + +

    СИНТАКСИС

    + +
    +      image create photo ?имя? ?параметры?
    +    
    + +

    ОПИСАНИЕ

    + +

    Пиксели изображения типа photo могут быть + любого цвета, а также могут быть прозрачными. При сохранении + изображений этого типа каждый пиксель кодируется 24 битами; при + выводе пиксела при необходимости используется приближение + (dithering). Закодированные данные могут быть представлены в + виде файла или строки, а также в виде C кода через процедурный + интерфейс. В настоящее время поддерживаются только форматы GIF и + PPM/PGM; однако в системе имеется интерфейс, облегчающий + добавление новых форматов изображений. Области, данные для + которых не представлены, при выводе изображения оказываются + прозрачными.

    + +

    СОЗДАНИЕ ИЗОБРАЖЕНИЙ ТИПА photo

    + +

    Как и все остальные изображения, изображения типа photo + создаются командой image + create. Команда поддерживает следующие параметры: + +

    +
    -channel идКанала
    + +
    Параметр задает имя канала, открытого для чтения, по + которому должно поступить изображение типа photo. Формат + данных в канале должен быть таким, для которого существует + соответствующая программа чтения данных из файла или + канала.
    + +
    -data строка
    + +
    Задает содержимое изображения в виде строки. Формат данных в + строке должен быть таким, для которого существует + соответствующая программа чтения данных из строки. Если заданы + оба параметра -data и + -file, то параметр -file + подавляет значение параметра + -data.
    + +
    -format имя-формата
    + +
    Задает имя файла, содержащего описание формата данных, + указанных параметрами -data или + -file.
    + +
    -file имя
    + +
    Задает имя файла, содержащего данные для изображения типа + photo. Формат файла должен быть таким, для которого существует + соответствующая программа чтения данных из файла или + канала.
    + +
    -gamma значение
    + +
    Указывает на то, что распределение цветов для вывода данного + изображения в окне должно быть исправлено для нелинейного + дисплея с помощью показателя экспоненты + gamma. (В большинстве CRT интенсивность + вывода является показательной функцией введенного значения, + что обеспечивает качественное приближение; + gamma это показатель экспоненты, его значение + обычно близко к "2"). Указанное значение должно быть + положительным. По умолчанию параметр имеет значение + "1" (коррекция не производится). Значения, большие + единицы, осветляют изображение, меньшие единицы делают его + темнее.
    + +
    -height число
    + +
    Задает высоту изображения в пикселах. Этот параметр + оказывается полезным, в первую очередь, в ситуациях, когда + пользователь строит изображение по частям. Значение ноль + (принятое по умолчанию) обеспечивает возможность вертикального + растяжения или сжатия изображения в соответствии с его + содержимым.
    + +
    -palette спец-палитры
    + +
    Задает разрешение цветов выделенного изображению и + число используемых цветов из палитр окон размещения + изображения. Строка параметра спец-палитры может представлять + собой либо одно десятичное число, задающее число используемых + оттенков серого цвета, либо три десятичных числа, разделенных + наклонными косыми чертами (/), задающих число используемых + оттенков красного, зеленого и голубого цветов. Если строка + состоит из одного десятичного числа, то будет выводиться + монохромное изображение (оттенками серого цвета).
    + +
    -width число
    + +
    Задает ширину изображения в пикселах. Этот параметр + оказывается полезным, в первую очередь, в ситуациях, когда + пользователь строит изображение по частям. Значение ноль + (принятое по умолчанию) обеспечивает возможность + горизонтального растяжения или сжатия изображения в + соответствии с его содержимым.
    +
    + +

    КОМАНДА IMAGE

    + +

    При создании изображения типа photo + Tk создает также новую команду, имя которой совпадает с именем + вновь созданного изображения. С помощью этой команды можно + выполнять различные операции над изображением. Она имеет + следующий общий вид:

    + + +
    +      imageName параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды.

    + +

    Параметры, приводящие к дописыванию данных в изображение, + обычно приводят к увеличению размеров изображения, за + исключением случаев, когда пользователь задал ненулевые значения + параметров конфигурации -width и/или + -height; в последнем случае ширина и/или высота + изображения не изменяются.

    + +

    Изображения типа photo поддерживают следующие команды:

    + +
    +
    имяИзображения blank
    + +
    Очищает изображение, т.е. устанавливает, что в изображении + нет данных, поэтому при выводе оно оказывается прозрачным, и + на его месте видно содержимое содержащего его окна.
    + +
    имяИзображения cget + параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из + параметров команды image create photo.
    + +
    имяИзображения configure + ?параметр? ?значение параметр значение + ...?
    + +
    Запрашивает значения параметров конфигурации изображения или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр задан, а его + новое значение - нет, то команда возвращает часть полного + списка, относящуюся к указанному параметру. Если заданы одна + или несколько пар параметр-значение, то указанным параметрам + примитива присваиваются новые значения, а команда возвращает + пустую строку. Параметр может быть любым из параметров команды + image create photo.
    + +
    имяИзображения copy + исхИзобр ?параметр значение(я) ...?
    + +

    Копирует область изображения с именем исхИзобр + (которое должно быть изображением типа photo) в + изображение с именем имяИзображения, возможно с + растяжением пикселей и/или subsampling. Если параметры не + заданы, то команда копирует в имяИзображения все + исходное изображение, начиная с точки с координатами (0,0) в + изображении имяИзображения. В команде могут быть + заданы следующие параметры:

    + +
    +
    -from x1 y1 x2 y2
    + +
    Задает предназначенную для копирования прямоугольную + область в исходном изображении. Точки с координатами + (x1,y1) и (x2,y2) + задают противоположные углы прямоугольника. Если параметры + x2 иy2 не заданы, то их значениями по + умолчанию являются координаты нижнего правого угла + исходного изображения. В копируемую область включаются + левая и верхняя стороны прямоугольника, но не его нижняя и + правая стороны. Значением параметра -from + по умолчанию является все исходное изображение.
    + +
    -to x1 y1 x2 y2
    + +
    Задает прямоугольную подобласть в изображении + имяИзображения. Точки с координатами + (x1,y1) и (x2,y2) + задают противоположные углы прямоугольника. Если + координаты x2 и y2 не заданы, то их + значениями по умолчанию являются значения координат + (x1,y1), к которым прибавлены размеры + исходной области (после subsampling??? и увеличения, если + они требуются). Если координаты x2 и y2 + заданы, то копируемая область будет при необходимости + воспроизведена несколько раз для замещения всего + отведенного прямоугольника.
    + +
    -shrink
    + +
    Указывает на то, что размер отведенной области должен + быть при необходимости уменьшен таким образом, чтобы + копируемый прямоугольник оказался в ее правом нижнем + углу. Если пользователь задал ненулевые значения + параметров конфигурации -width или + -height , то параметр + -shrink не окажет влияния на ширину или + высоту соответственно.
    + +
    -zoom x y
    + +
    Задает необходимость растяжения копируемой области с + коэффициентом x в X-направлении и с коэффициентом + y в Y-направлении. При задании этого параметра + каждый пиксел исходного изображения при копировании будет + представлен в виде прямоугольника x * y пикселей одного + цвета. Оба числа x и y должны быть положительными.
    + +
    -subsample x y
    + +
    Указывает на необходимость уменьшения исходного + изображения за счет использования только каждого x-го + пикселя в X-направлении и каждого y-го пикселя в + Y-направлении. Отрицательные значения параметров приводят + к отражению в соответствующем направлении. Если параметр + y не задан, то его значение по умолчанию + совпадает со значением параметра x.
    +
    +
    + +
    имяИзображения get x y
    + +
    Возвращает цвет пиксела с координатами (x,y) в + указанном изображении в виде списка из трех целых чисел в + промежутке от 0 до 255, описывающих соответственно его + красную, зеленую и голубую составляющие.
    + +
    имяИзображения put данные + ?-to x1 y1 x2 y2?
    + +
    Устанавливает цвета пикселей, заданные параметром + данные. Этот параметр используется для формирования + двумерного массива пикселей, который затем копируется в + изображение имяИзображения. Данные представляют собой + список строк, идущих сверху вниз, каждая из которых является + списком цветов, идущих слева направо. Каждый цвет задается + именем (например, blue) или в + шестнадцатеричном виде (например, #2376af). С + помощью параметра -to можно отвести область + для размещения массива. Если заданы только координаты + x1 и y1, то верхним левым углом отведенной + области является точка с координатами + (x1,y1), а размеры области совпадают с + размерами массива. Если указаны все четыре координаты, то они + задают противоположные углы отведенного прямоугольника, и + содержимое массива будет при необходимости повторено в X- и + Y-направлениях для замещения всего отведенного + прямоугольника.
    + +
    имяИзображения read имяфайла + ?параметр значение(я) ...?
    + +

    Читает данные из файла с именем имяфайла в + изображение с именем имяИзображения. Выполнение + команды начинается с просмотра списка программ обработки + форматов файлов изображений в поисках программы, способной + интерпретировать данные в указанном файле; затем эти данные + читаются из файла в изображение с именем + имяИзображения. Команда может иметь следующие + параметры:

    + +
    +
    -format имя-формата
    + +
    Задает формат данных в файле с именем имяфайла. + Точнее говоря, при поиске в списке программ обработки + будут просматриваться только те программы, имена которых + начинаются с имени-формата.
    + +
    -from x1 y1 x2 y2
    + +
    Задает прямоугольную подобласть в изображении, + описываемом данными файла, которую необходимо скопировать + в изображение с именем имяИзображения. Если + заданы только параметры x1 и y1, то они + задают координаты левого верхнего угла подобласти, а ее + правый нижний угол совпадает с правым нижним углом всего + изображения в файле. Если заданы все четыре координаты, то + они задают два противоположных угла подобласти. Если этот + параметр не задан, то по умолчанию копируется все + изображение.
    + +
    -shrink
    + +
    Если присутствует этот параметр, то размер изображения с + именем имяИзображения при необходимости + уменьшается таким образом, чтобы прямоугольник, отведенный + под содержимое файла изображения, находился в правом + нижнем углу изображения с именем + имяИзображения. Если пользователь задал ненулевые + значения параметров конфигурации -width + или -height, то параметр + -shrink не будет оказывать влияния + соответственно на ширину или высоту изображения.
    + +
    -to x y
    + +
    Задает координаты верхнего левого угла прямоугольника в + изображении с именем имяИзображения, отводимого + под данные из файла. По умолчанию параметр имеет значение + (0,0).
    +
    +
    + +
    имяИзображения redither
    + +
    При выводе изображений типа photo используется алгоритм + приближения (dithering) , который распространяет дискретные + ошибки с пиксела на его соседей. Если данные для изображения + имяИзображения поставляются частями, то результат + приближения может быть не вполне корректным. Обычно эта + некорректность на взгляд незаметна, однако при серьезных + нарушениях с помощью данной команды можно пересчитать + необходимые приближения в каждом окне, в котором выводится + данное изображение.
    + +
    имяИзображения write имяфайла + ?параметр значение(я) ...?
    + +

    Записывает изображение имяИзображения в файл с + именем имяфайла. Может иметь следующие параметры:

    + +
    +
    -format имя-формата
    + +
    Задает имя программы обработки файла изображения, которую + следует использовать при записи данных в файл. Точнее + говоря, данная подкоманда ищет первую программу обработки + в списке, начало имени которой совпадает с началом + имени-формата и которая способна записывать данные в + файл. Если этот параметр не задан, то эта подкоманда + использует первую программу обработки, способную + записывать данные в файл изображения.
    + +
    -from x1 y1 x2 y2
    + +
    Задает прямоугольную область в изображении с именем + имяИзображения, которую следует переписать в файл + изображения. Если заданы только значения x1 и + y1, то они задают верхний левый угол + прямоугольника, а его нижний правый угол совпадает с + нижним правым углом изображения. Если заданы все четыре + координаты, то они задают противоположные углы + прямоугольника. Если параметр не задан, то по умолчанию + копируется все изображение.
    +
    +
    +
    + +

    ФОРМАТЫ ИЗОБРАЖЕНИЙ

    + +

    При создании программ обработки изображений типа photo + предусмотрена возможность легкого добавления новых форматов + файлов изображений. Все программы занесены в список. Добавление + программы в список происходит в результате выполнения команды + Tk_CreatePhotoImageFormat. В стандартном + дистрибутиве Tk содержатся программы обработки для форматов + PPM/PGM и GIF, которые автоматически заносятся в список при + инициализации.

    + +

    При чтении файла изображения или обработке строки данных, + заданной в параметре конфигурации -data, + команда photo image просматривает программы + обработки одну за другой, пока не найдется такая, которая + утверждает, что она способна читать данные из файла или + строки. Результатом поиска обычно бывает правильная программа + обработки. В противном случае пользователь может задать имя + программы обработки с помощью параметра + -format.

    + +

    На самом деле команда photo image + просматривает только те программы обработки, имена которых + начинаются со строки, заданной параметром + -format (при сравнении регистр не + учитывается). Если, например, пользователь указал + -format gif, то могут выполняться программы + обработки GIF87 или GIF89, но не программа JPEG (если такие + программы были внесены в список).

    + +

    При записи изображения в файл параметр -format + обрабатывается несколько другим способом: строка, являющаяся его + значением, должна начинаться с полного имени запрашиваемой + программы обработки, за которым может следовать дополнительная + информация. Эта дополнительная информация может, например, + сообщать программе, какую из версий формата следует + использовать.

    + +

    РАСПРЕДЕЛЕНИЕ ЦВЕТОВ

    + +

    При выводе изображения типа photo в окно команда + photo image отводит цвета и, + при необходимости, возмущает изображение, заменяя отсутствующие + цвета доступными. Выделяемые цвета образуют куб: число возможных + составных цветов представляет собой произведение чисел оттенков + красного, зеленого и голубого цветов.

    + +

    Обычно выбор числа цветов определяется глубиной окна. Например, + в 8-битовом окне PseudoColor команда photo + image пытается отвести семь оттенков красного, семь + оттенков зеленого и четыре оттенка голубого, всего 198 составных + цветов. Для 1-битового окна StaticGray (монохромного) команда + отводит два цвета, белый и черный. Для 24-битовых окон + DirectColor или TrueColor команда отводит по 256 оттенков + каждого из трех цветов. Если не удается отвести все цвета, то + команда photo image уменьшает число оттенков + каждого простого цвета и производит новую попытку + размещения.

    + +

    Пользователь может частично управлять выбором числа цветов с + помощью параметра конфигурации -palette. При + использовании этого параметра в нем задается максимальное число + используемых оттенков каждого из простых цветов. Кроме того с + помощью этого параметра можно потребовать представления + изображения оттенками серого цвета даже в цветном окне, задав + одно число вместо трех, разделенных наклонными чертами.

    + + + + + diff --git a/hlp/ru/tk/pkg_mkIndex.html b/hlp/ru/tk/pkg_mkIndex.html new file mode 100644 index 0000000..3efcf08 --- /dev/null +++ b/hlp/ru/tk/pkg_mkIndex.html @@ -0,0 +1,186 @@ + + + + pkg_mkIndex + + + +

    pkg_mkIndex

    + +

    Создает индексный файл для автоматической загрузки пакета.

    + +

    СИНТАКСИС

    + +
    +      pkg_mkIndex dir pattern ?pattern pattern...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура pkg_mkIndex представляет собой + утилиту для работы с Tcl-библиотеками. Она обеспечивает создание + индексных файлов, необходимых для автоматической загрузки + пакетов, когда в приложении встречается команда package require. Для + создания автоматически загружаемых пакетов необходимо выполнить + следующие действия:

    + + + + + + + + + + + + + + + + + + + + + + + +
    [1]Создать один или несколько пакетов. Каждый пакет может + состоять из одного или больше файлов с Tcl-скриптами или + из бинарных файлов. Бинарные файлы должны быть пригодны + для их загрузки с помощью команды load с единственным + аргументом -именем файла. Например, если в пакет входит + файл test.so, он должен загружаться + командой load test.so. Каждый файл + Tcl-скриптов должен содержать команду package + provide с именем пакета и версией. Каждый + бинарный файл должен содержать вызов процедуры + Tcl_PkgProvide. +
    [2]Создать индексные файлы с помощью команды + pkg_mkIndex. Аргумент dir + указывает имя каталога, в котором лежат файлы пакета, а + шаблоны pattern, которые могут содержать + специальные символы, как в команде glob, указывают на файлы + в этом каталоге. Команда pkg_mkIndex + создаст в каталоге dir файл + pkgIndex.tcl, содержащий информацию обо + всех файлах пакета, заданных с помощью аргументов + pattern. Для этого загружаются все файлы пакета, + и определяется, какие новые пакеты и какие новые процедуры + появились (поэтому в каждом файле пакета и должна быть + команда package + provide или вызов + Tcl_PkgProvide). +
    [3]Установить пакет как подкаталог одного из каталогов, + перечисленных в переменной + tcl_pkgPath. Если в списке + $tcl_pkgPath больше одного каталога, то + бинарные файлы с разделяемыми библиотеками обычно + устанавливаются в первом каталоге, а библиотеки + Tcl-скриптов . во втором. В этих каталогах должны также + находиться файлы pkgIndex.tcl. Пока + пакеты будут размещаться в подкаталогах каталогов, + перечисленных в переменной tcl_pkgPath, + этого будет достаточно для их автоматической загрузки при + выполнении команды package + require. +
    [4]Если вы установили пакеты в каких-либо других каталогах, + то необходимо, чтобы эти каталоги содержались в переменной + auto_path или были бы непосредственными + подкаталогами одного из содержащихся там + каталогов. Переменная auto_path содержит + список каталогов, которые просматриваются как + автозагрузчиком, так и загрузчиком пакетов. По умолчанию + он включает $tcl_pkgPath. Загрузчик + пакетов также просматривает и подкаталоги каталогов, + включенных в auto_path. Пользователь + может в явном виде включить в приложении необходимые + каталоги в auto_path. А можно включить + эти каталоги в переменную окружения + TCLLIBPATH. Если она существует, то + используется для инициализации переменной + auto_path при запуске приложения. +
    + +

    Если перечисленные выше шаги выполнены, то для использования + необходимого пакета достаточно выполнить в приложении команду package + require. Если, например, версии 2.1, 2.3 и 3.1 + пакета Test проиндексированы и хранятся в + соответствующих каталогах, то команда

    + +
    +      package require Test
    +    
    + +

    загрузит версию 3.1. А команда

    + +
    +      package require -exact Test 2.1
    +    
    + +

    загрузит версию 2.1. В различных каталогах могут храниться + много версий одного и того же пакета, но в данный интерпретатор + может быть загружена только одна из них . та, которая будет + затребована первой. Однако, в различных интерпретаторах одного + приложения могут быть загружены различные версии одного и того + же пакета.

    + +

    ЗАГРУЗЧИК ПАКЕТОВ И АВТОЗАГРУЗЧИК

    + +

    Автозагрузчик и загрузчик пакетов во многом имеют сходные + возможности, поскольку и тот, и другой предназначены для + загрузки файлов по требованию. Однако загрузчик файлов + представляет собой механизм более высокого уровня, который + использует автозагрузчик на последнем шаге процесса + загрузки. Как правило, предпочтительнее индексировать пакеты с + помощью команды pkg_mkIndex, чем с + помощью команды auto_mkindex, поскольку это + обеспечивает подключение механизма версий. Вы можете иметь + несколько версий одного и того же пакета и, более того, + использовать в различных приложениях различные версии. Напротив, + auto_mkindex позволяет работать с единственной + версией пакета. Скорее всего, не стоит создавать индексы для + пакета с помощью и pkg_mkIndex, и auto_mkindex, поскольку в этом + случае трудно контролировать, какой из механизмов загрузки + пакета сработает первым, и, соответственно, какая версия пакета + будет загружена.

    + +

    КАК ЖЕ ЭТО РАБОТАЕТ?

    + +

    При первом вызове команды package require + исполняется скрипт package + unknown. При инициализации Tcl-скрипт package unknown + задается таким образом, что он выполняет все файлы + pkgIndex.tcl в каталогах auto_path. Эти файлы содержат + команды package + ifneeded для каждой доступной версии каждого + доступного пакета. Эти команды в свою очередь вызывают команды + package + provide, которые объявляют данные версии + доступными. Кроме того, они формируют необходимую исходную + информацию для автозагрузчика. Данный файл данной версии + данного пакета реально загружается только тогда, когда + вызывается первая из содержащихся в нем команд. Таким образом, + после выполнения команды package require вы + не увидите команд пакета в интерпретаторе, но, тем не менее, + вы сможете их вызвать и при этом они загрузятся + автоматически.

    + + + + diff --git a/hlp/ru/tk/place.html b/hlp/ru/tk/place.html new file mode 100644 index 0000000..57008a1 --- /dev/null +++ b/hlp/ru/tk/place.html @@ -0,0 +1,295 @@ + + + + place + + + +

    place

    + +

    Геометрический менеджер, обеспечивающий размещение виджетов в + абсолютных или относительных координатах.

    + +

    СИНТАКСИС

    + +
    +      place window option value ?option value ...?
    +      place configure window option value ?option value ...?
    +      place forget window
    +      place info window
    +      place slaves window
    +    
    + + +

    ОПИСАНИЕ

    + +

    Геометрический менеджер place позволяет + размещать виджеты в их мастер-окнах, используя прямые указания о + размерах и размещении виджета. Кроме того, с его помощью можно + добиваться режима "резинового листа", указывая размеры и + размещение виджета в долях размера мастер-окна. При этом виджеты + изменяют свои размеры при изменении размеров мастер окна. И, + наконец, менеджер place позволяет сочетать оба этих метода, + размещая, например, виджет определенного размера в центре + мастер-окна.

    + +

    Команда place используется для управления + соответствующим геометрическим менеджером и для получения от + него справочной информации. Команда может иметь перечисленные + ниже формы.

    + +
    +
    place window option value + ?option value ...
    + +
    Если первый аргумент команды является именем окна (любая + величина, начинающаяся с "."), команда выполняется + точно так же, как команда place + configure.
    + +
    place configure window option + value ?option value ...
    + +

    Аргумент команды состоит из имени размещаемого виджета, + после которого идут пары аргументов, состоящих из имени + опции и ее значения. Если виджет уже обрабатывался с помощью + команды place, то для не определенных в + команде опций будут использоваться старые значения, а не + значения по умолчанию. Команда возвращает пустую строку

    + +

    Ниже перечислены возможные опции.

    + +
    +
    -in master
    + +
    Аргумент master определяет полное имя виджета + (мастер-окна), относительно которого будет размещаться + виджет window. Мастер-окно должно быть непосредственным + предком виджета, или потомком этого предка. При этом они + оба должны быть потомками одного и того же + toplevel-окна. Эти ограничения необходимы, чтобы + гарантировать, что виджет будет виден, когда видно + мастер-окно. По умолчанию виджет размещается в своем + непосредственном предке.
    + +
    -x location
    + +

    Аргумент location определяет + x-координату в мастер-окне для якорной точки + виджета. Координата указывается на экране в одной из + следующих форм:

    + +
      +
    • в пикселях (число),
    • + +
    • в сантиметрах (число с буквой c на + конце),
    • + +
    • в миллиметрах (число с буквой m на + конце),
    • + +
    • в дюймах (число с буквой i на + конце)
    • + +
    • в точках (число с буквой pна конце, + точка равна 1/72 дюйма).
    • +
    + +

    Якорная точка не обязана находиться внутри мастер-окна.

    +
    + +
    -relx location
    + +
    Аргумент location определяет + x-координату в мастер окне для якорной точки + виджета. Координата указывается на экране в виде + десятичного числа в долях соответствующего размера + мастер-окна. Так "0.0" соответствует левому краю + мастер окна, "1.0" правому краю. Если указаны + обе опции, -x и + -relx, то соответствующие величины + складываются. Например, -relx 0.5 -x -2 + помещает якорную точку на два пикселя левее центра + мастер-окна.
    + +
    -y location
    + +

    Аргумент location определяет y-координату в + мастер-окне для якорной точки виджета. Координата + указывается на экране в одной из следующих форм:

    + +
      +
    • в пикселях (число),
    • + +
    • в сантиметрах (число с буквой c на + конце),
    • + +
    • в миллиметрах (число с буквой m на + конце),
    • + +
    • в дюймах (число с буквой i на + конце),
    • + +
    • в точках (число с буквой i на + конце, точка равна 1/72 дюйма).
    • +
    + +

    Якорная точка не обязана находиться + внутри мастер-окна.

    +
    + +
    -rely location
    + +
    Аргумент location определяет + y-координату в мастер-окне для якорной точки + виджета. Координата указывается на экране в виде + десятичного числа в долях соответствующего размера + мастер-окна. Так "0.0" соответствует верхнему + краю мастер-окна, "1.0" нижнему краю. Если + указаны обе опции, -y и + -rely, то соответствующие величины + складываются. Например, -rely 0.5 -y -3 + помещает якорную точку на три пикселя ниже центра + мастер-окна.
    + +
    -anchor where
    + +
    Аргумент where определяет, какая точка виджета + будет помещена в якорной точке, заданной с помощью опций + -x, -y, + -relx и -rely. В якорную + точку помещается крайняя точка виджета (включая границу, + если она задана). Так значение se + означает, что в якорную точку будет помещен нижний правый + угол виджета. Значение по умолчанию + nw.
    + +
    -width size
    + +
    Аргумент size определяет ширину виджета на + экране (допустимы те же формы, что и для опций + -xи -y). Ширина это + внешняя ширина виджета, включая его границу (если она + задана). Если аргумент представляет собой пустую строку + или если ни опция -width, ни опция + -relwidth не определены, ширина виджета + определяется исходя из его собственных запросов.
    + +
    -relwidth size
    + +
    Аргумент size определяет ширину виджета на + экране. Ширина указывается в виде десятичного числа в + долях соответствующего размера мастер-окна. Так 0.5 + соответствует ширине в половину ширины мастер-окна. Если + указаны обе опции, -width и + -relwidth, то соответствующие величины + складываются. Например, -relwidth 1.0 -width + 5 делает виджет на 5 пикселей шире + мастер-окна.
    + +
    -height size
    + +
    Аргумент size определяет высоту виджета на + экране (допустимы те же формы, что и для опций + -xи -y). Высота это + внешняя высота виджета, включая его границу (если она + задана). Если аргумент представляет собой пустую строку + или если ни опция -height, ни опция + -relheight не определены, высота виджета + определяется исходя из его собственных запросов.
    + +
    -relheight size
    + +
    Аргумент size определяет высоту виджета на + экране. Высота указывается в виде десятичного числа в + долях соответствующего размера мастер-окна. Так + "0.5" соответствует высоте в половину высоты + мастер-окна. Если указаны обе опции, + -height и -relheight, то + соответствующие величины складываются. Например, + -relheight 1.0 -height -2 делает виджет + на 2 пикселя ниже мастер-окна.
    + +
    -bordermode mode
    + +

    Аргумент mode определяет, используются ли + границы мастер-окна при определении положения + размещаемого виджета.

    + +

    Значение по умолчанию, которое используется наиболее + часто, inside. Оно означает, что + менеджер рассматривает в качестве мастер-окна его + внутреннюю часть без границы. Опция -x + 0 означает при этом точку внутри границы + мастер-окна. А опция -relwidth 1.0 + означает, что виджет будет размещен внутри + соответствующих границ мастер-окна.

    + +

    Значение outside означает, что + менеджер включает границу мастер-окна в его состав. Это + значение используется обычно, когда нужно разместить + виджет вне его мастер-окна (но в пределах границы + мастер-окна), например, как при опциях -x 0 -y 0 + -anchor ne.

    + +

    Значение ignore означает, что менеджер + включает в состав окна все внутренние границы, но не + внешние границы (его официальное X-определение). Это + значение используется, вероятно, реже остальных.

    +
    +
    +
    +
    + + +

    ЗАМЕЧАНИЕ

    + +

    Если значение одной и той же величины определено дважды с + использованием различных опций, например, если x-координата + виджета определена сначала с использованием опции + -x, а позднее повторно определена с + использованием опции -relx, то используется + только более позднее определение.

    + +
    +      place slaves window
    +    
    + +

    Эта команда возвращает список всех виджетов, + размещенных в мастер-окне. Если в нем не размещены виджеты, + команда возвращает пустой список.

    + +
    +      place forget window 
    +    
    + +

    Окно window больше не управляется менеджером + place. Как следствие, оно удаляется с + экрана. Если окно не управлялось менеджером + place, команда не имеет никакого эффекта.

    + +

    Команда возвращает пустую строку.

    + +
    +      place info window
    +    
    + +

    Возвращает список опций и их значений для окна window + в той же форме, в какой они задаются в команде place + configure. Если конфигурацию виджета, полученную с + помощью этой команды, предполагается впоследствии восстановить, + то перед этим необходимо будет использовать команду + place forget, чтобы удалить текущую + конфигурацию, а затем place configure с + сохраненной конфигурацией.

    + +

    В отличие от многих других геометрических менеджеров + place не пытается манипулировать геометрией + мастер-окна (например, переустанавливать их размер "по + потребности"). Чтобы управлять размерами этих окон, для них + желательно использовать такие виджеты, как frame или canvas.

    + + + diff --git a/hlp/ru/tk/radiobutton.html b/hlp/ru/tk/radiobutton.html new file mode 100644 index 0000000..697b370 --- /dev/null +++ b/hlp/ru/tk/radiobutton.html @@ -0,0 +1,344 @@ + + + + radiobutton + + +

    radiobutton

    + +

    Создание примитива кнопки-переключателя и управление им.

    + +

    СИНТАКСИС

    + +
    +      radiobutton имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activeBackground
    • +
    • -activeforeground
    • +
    • -anchor
    • +
    • -background
    • +
    • -bitmap
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -disabledforeground
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -image
    • +
    • -justify
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -takefocus
    • +
    • -text
    • +
    • -textvariable
    • +
    • -underline
    • +
    • -wraplength
    • +
    + + +

    Подробное описание этих параметров приведено в разделе options.

    + + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-command
    Имя в Базе:command
    Класс в Базе:Command
    + +

    Ассоциирует с кнопкой команду Tk. Обычно команда выполняется + при отпускании клавиши 1 "Мыши" на окне + кнопки-переключателя. Перед выполнением команды обновляется + значение глобальной переменной переключателя (параметр + -variable).

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту кнопки. Если в кнопке выводится + изображение или двуцветное изображение, то значение параметра + задается в пикселах (т.е., в любом виде, приемлемом для + Tk_GetPixels); высота текстовой кнопки задается + числом строчек текста. Если параметр не задан, то высота кнопки + вычисляется по ее содержимому.

    + + + + + +
    Имя параметра:-indicatoron
    Имя в Базе:indicatorOn
    Класс в Базе:IndicatorOn
    + +

    Указывает, следует ли выводить индикатор. Значение параметра + должно быть булевским. Если значением является ложь, то параметр + relief игнорируется и примитив всегда + изображается вдавленным, если он выделен, и выпуклым в противном + случае.

    + + + + + +
    Имя параметра:-selectcolor
    Имя в Базе:selectColor
    Класс в Базе:Background
    + +

    Задает цвет фона для изображения выделенной кнопки. Если + параметр IndicatorOn имеет значение истина, то + указанный цвет применяется для изображения индикатора. В системе + Windows тот же цвет используется в качестве фона изображения + индикатора вне зависимости от состояния выделения. Если + значением параметра IndicatorOn является ложь, + то указанный цвет используется в качестве фона для всего + примитива, когда он выделен, вместо значений параметров + background и + activeBackground.

    + + + + + +
    Имя параметра:-selectimage
    Имя в Базе:selectImage
    Класс в Базе:SelectImage
    + +

    Задает изображение, выводимое в кнопке при выделении + кнопки-переключателя (вместо изображения, заданного параметром + -image). Если параметр -image + отсутствует, то значение параметра -selectimage + игнорируется.

    + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + +

    Задает одно из трех состояний кнопки-переключателя: + normal, active или + disabled. В нормальном состоянии + кнопка-переключатель изображается с использованием значений + параметров foreground и + background. В активном состоянии + кнопка-переключатель обычно находится, если на ней расположен + курсор. Кнопка-переключатель в активном состоянии изображается с + использованием значений параметров + activeForeground и + activeBackground. Недоступное состояние + указывает на то, что кнопка должна быть нечувствительной: + привязки по умолчанию не приводят к запуску примитива и нажатия + на кнопку "Мыши:" игнорируются. В этом состоянии + изображение кнопки-переключателя определяется значениями + параметров disabledForeground и + background. +

    + + + + + +
    Имя параметра:-value
    Имя в Базе:value
    Класс в Базе:Value
    + +

    Задает значение, которое следует заносить в переменную + кнопки-переключателя при выделении этой кнопки.

    + + + + + +
    Имя параметра:-variable
    Имя в Базе:variable
    Класс в Базе:Variable
    + +

    Задает имя глобальной переменной, значение которой нужно + устанавливать при выделении кнопки. Изменение значения этой + переменной также приводит к изменению состояния выделения + кнопки. По умолчанию параметр имеет значение + selectedButton.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину кнопки-переключателя. Если в кнопке + выводится изображение или двуцветное изображение, то значение + параметра задается в пикселах (т.е., в любом виде, приемлемом + для Tk_GetPixels); ширина текстовой кнопки задается числом + символов. Если параметр не задан, то ширина кнопки вычисляется + по ее содержимому.

    + + +

    ОПИСАНИЕ

    + +

    Команда radiobutton создает новое окно + (задаваемое аргументом имяПути) и превращает его в + примитив кнопки-переключателя. Детали изображения + кнопки-переключателя, такие как ее цвета, шрифт, текст и + исходный объемный вид задаются с помощью описанных выше + дополнительных параметров. Команда radiobutton + возвращает аргумент имяПути. В момент выполнения этой + команды не должно существовать окна с именем имяПути, + но должен существовать его предок.

    + +

    Кнопка-переключатель представляет собой примитив, в котором + выводится текстовая строка, изображение или двуцветное + изображение, а также ромб или кружок, называемый + индикатором. Весь выводимый текст должен быть записан + одним шрифтом, однако он может занимать несколько строчек на + экране (если в нем есть символы перевода строки или задан + параметр wrapLength). Один из символов текста + может быть подчеркнут (в соответствии со значением параметра + underline). Кнопка-переключатель обладает всеми + характеристиками обычной кнопки, включая следующие: в + зависимости от значения параметра state кнопка + имеет три разных вида; кнопка может выглядеть выпуклой, + вдавленной или плоской, кроме того, она может мигать. При + инициации кнопки-переключателя (нажатием на клавишу 1 + "Мыши", когда курсор "Мыши" находится на + кнопке) выполняется команда Tcl.

    + +

    Кроме того, кнопки-переключатели можно выделять. Если + кнопка выделена, то индикатор обычно изображается как + выделенный, а переменная Tcl, ассоциированная с данной кнопкой, + имеет предписанное значение (обычно 1). В ОС Unix индикатор + изображается вдавленным и имеет специальный цвет. В системе + Windows вместо этого в индикаторе появляется круглая метка. Если + кнопка-переключатель не выделена, то индикатор имеет + невыделенный вид, а ассоциированная переменная имеет другое + значение (обычно "0"). В ОС Unix такой индикатор + изображается выпуклым и не имеет специального цвета. В системе + Windows в невыделенном индикаторе отсутствует круглая + метка. Обычно одна переменная обслуживает несколько + кнопок-переключателей, а ее значение указывает, какая из них + должна быть выделена. При выделении кнопки происходит изменение + значения ассоциированной переменной. Кроме того, каждая + кнопка-переключатель отслеживает значение ассоциированной + переменной и при его изменении состояние выделения кнопки + меняется. По умолчанию используется переменная + selectedButton; ее значением является имя + выделенной кнопки или пустая строка, если ни одна из кнопок, + ассоциированных с данной переменной, не выделена. Имя переменной + и записываемые в ней значения + "выделенная"/"невыделенная" можно поменять с + помощью параметров командной строки или в базе данных + параметров. С помощью параметров конфигурации можно также + поменять вид индикатора (или даже отменить саму необходимость + его вывода). По умолчанию выделение кнопки-переключателя + происходит при щелчке на кнопке.

    + + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда radiobutton создает новую команду Tcl + с именем имяПути. С помощью этой команды можно + выполнять различные операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы кнопки-переключателя допускают следующие + формы команды:

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров команды + radiobutton.
    + +
    имяПути configure ?параметр? + ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение - нет, то команда возвращает часть + полного списка, относящуюся к указанному параметру. Если + заданы одна или несколько пар параметр-значение, то + указанным параметрам примитива присваиваются новые значения, а + команда возвращает пустую строку. Параметр может быть любым из + параметров команды radiobutton.
    + +
    имяПути deselect
    + +
    Отменяет выделение кнопки-переключателя и придает + ассоциированной переменной значение .пустая строка.. Если в + момент исполнения команды данная кнопка-переключатель не была + выделена, то команда не производит никаких действий.
    + +
    имяПути flash
    + +
    Заставляет кнопку-переключатель мигать. Этот эффект + достигается путем многократного вывода изображения кнопки + поочередно в активном и нормальном состоянии. По окончании + работы команды кнопка-переключатель остается в том же + состоянии (активном или нормальном), что и перед началом ее + выполнения. Если перед началом выполнения команды кнопка + находится в состоянии disabled, то команда + игнорируется.
    + +
    имяПути invoke
    + +
    Приводит в точности к тому же результату, что и нажатие + клавиши "Мыши" на кнопке-переключателе: кнопка + становится выделенной и выполняется команда Tcl, + ассоциированная с кнопкой (при наличии такой + команды). Возвращаемое значение совпадает с возвращаемым + значением команды Tcl (или является пустой строкой, если с + кнопкой никакой команды не ассоциировано). Если перед началом + выполнения команды кнопка-переключатель находится в состоянии + disabled, то команда игнорируется.
    + +
    имяПути select
    + +
    Выделяет кнопку, перерисовывая ее в новом состоянии и + изменяя значение ассоциированной переменной.
    +
    + +

    ПРИВЯЗКИ

    + +

    При создании кнопки-переключателя Tk автоматически создает + привязки к ней, определяющие ее поведение по умолчанию:

    + +
      + +
    1. в ОС Unix кнопка становится активной при появлении над ней + курсора "Мыши" и дезактивируется, когда курсор ее + покидает. В системах Mac и Windows при нажатии клавиши 1 + "Мыши" на переключателе кнопка активизируется, когда + курсор "Мыши" находится на кнопке и дезактивируется, когда + курсор ее покидает;
    2. + +
    3. при нажатии клавиши 1 "Мыши" на + кнопке-переключателе кнопка становится выделенной и + выполняется команда, привязанная к ней;
    4. + +
    5. если кнопка-переключатель находится в фокусе ввода, то + нажатие на клавишу пробела приводит к выполнению команды, + привязанной к этой кнопке;
    6. + +
    7. если кнопка-переключатель находится в состоянии + disabled, то все описанные выше действия не + приводят ни к какому результату: кнопка остается + безответной.
    8. +
    + +

    Поведение кнопки-переключателя можно изменить с помощью новых + привязок к конкретным примитивам или путем переопределения + привязок данного класса.

    + + + + + diff --git a/hlp/ru/tk/raise.html b/hlp/ru/tk/raise.html new file mode 100644 index 0000000..5171560 --- /dev/null +++ b/hlp/ru/tk/raise.html @@ -0,0 +1,27 @@ + + + + raise + + + +

    raise

    + +

    Команда изменяет положение окна в очереди стека.

    + +

    СИНТАКСИС

    + +
    +      raise window ?aboveThis?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда raise перемещает окно window в + очереди стека либо выше всех окон, имеющих одинаковый с + window уровень иерархии, либо перед одним из них, + заданного аргументом aboveThis. Данное окно будет + заслонять окна, оказавшиеся ниже его.

    + + + diff --git a/hlp/ru/tk/resource.html b/hlp/ru/tk/resource.html new file mode 100644 index 0000000..3d1fb8e --- /dev/null +++ b/hlp/ru/tk/resource.html @@ -0,0 +1,23 @@ + + + + resource + + +

    resource

    + +

    Управляет Macintosh-ресурсами.

    + +

    СИНТАКСИС

    + +
    +      resource option arg arg...
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда resource позволяет управлять ресурсами + на платформах Macintosh. На остальных платформах не + поддерживается.

    + + diff --git a/hlp/ru/tk/scale.html b/hlp/ru/tk/scale.html new file mode 100644 index 0000000..7a14173 --- /dev/null +++ b/hlp/ru/tk/scale.html @@ -0,0 +1,379 @@ + + + + scale + + +

    scale

    + +

    Создание примитива линейной шкалы и управление им.

    + +

    СИНТАКСИС

    + +
    +      scale имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activebackground
    • +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -orient
    • +
    • -relief
    • +
    • -repeatdelay
    • +
    • -repeatinterval
    • +
    • -takefocus
    • +
    • -troughcolor
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-bigincrement
    Имя в Базе:bigIncrement
    Класс в Базе:BigIncrement
    + +

    Некоторые способы обращения со шкалой требуют использования + "больших" шагов. Этот параметр задает величину + большого шага. Если его значение равно 0 (как, например, по + умолчанию), то большой шаг считается равным 1/10 интервала + шкалы.

    + + + + + +
    Имя параметра:-command
    Имя в Базе:command
    Класс в Базе:Command
    + +

    Задает префикс команды Tcl, исполняемой при всяком изменении + показателя шкалы какой-либо командой примитива. Сама команда Tcl + состоит из этого префикса, за которым следует пробел и + вещественное число, равное новому значению показателя шкалы. + + + + + +
    Имя параметра:-digits
    Имя в Базе:digits
    Класс в Базе:Digits
    + +

    Целое число, указывающее, сколько значащих цифр следует + сохранить при преобразовании показателя шкалы в строку + текста. Если это число неположительно, то выбирается наименьшее + число, обеспечивающее различное представление всех возможных + положений движка шкалы.
    + + + + + + +
    Имя параметра:-from
    Имя в Базе:from
    Класс в Базе:From
    + +

    Вещественное число левая или верхняя граница шкалы.

    + + + + + +
    Имя параметра:-label
    Имя в Базе:label
    Класс в Базе:Label
    + +

    Строка текста, выводимая в качестве названия шкалы. Для + вертикальной шкалы выводится непосредственно справа от верхнего + конца шкалы. Для горизонтальной шкалы название выводится + непосредственно выше левого конца шкалы. Если значением + параметра служит пустая строка, то никакого названия не + выводится.

    + + + + + +
    Имя параметра:-length
    Имя в Базе:length
    Класс в Базе:Length
    + +

    Задает желаемую длину шкалы на экране в пикселах (т.е. в любой + форме, приемлемой для Tk_GetPixels). Это высота + вертикальной шкалы или ширина горизонтальной.

    + + + + + +
    Имя параметра:-resolution
    Имя в Базе:resolution
    Класс в Базе:Resolution
    + +

    Вещественное число, задающее цену деления шкалы. Если это + значение положительно, то показатель шкалы будет всегда + округляться к целому кратному этой величины (такими будут, в + частности, метки шкалы и границы ее интервала). Если это + значение неположительно, то округления не происходит. Значение + параметра по умолчанию равно "1" (т.е. показатели + должны быть целыми).

    + + + + + +
    Имя параметра:-showvalue
    Имя в Базе:showValue
    Класс в Базе:ShowValue
    + +

    Булевское значение, указывающее, следует или нет выводить + текущий показатель шкалы.

    + + + + + +
    Имя параметра:-sliderlength
    Имя в Базе:sliderLength
    Класс в Базе:SliderLength
    + +

    Задает размер движка шкалы (вдоль его длинной стороны) в + пикселах (т.е. в любой форме, приемлемой для + Tk_GetPixels).

    + + + + + + +
    Имя параметра:-sliderrelief
    Имя в Базе:sliderRelief
    Класс в Базе:SliderRelief
    + +

    Задает вид движка шкалы, например, raised или + sunken.

    + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + +

    Задает одно из трех состояний шкалы: + normal,active или + disabled. Если шкала недоступна, то значение ее + показателя нельзя изменить и шкалу нельзя активизировать. Движок + на активной шкале изображается цветом, заданным параметром + activeBackground.

    + + + + + +
    Имя параметра:-tickinterval
    Имя в Базе:tickInterval
    Класс в Базе:TickInterval
    + +

    Вещественное число, определяющее величину промежутка между + числовыми метками снизу или слева от движка. Если значение + параметра равно "0", то метки не выводятся.

    + + + + + +
    Имя параметра:-to
    Имя в Базе:to
    Класс в Базе:To
    + +

    Вещественное число правая или нижняя граница шкалы. Может быть + как меньше, так и больше значения, задаваемого параметром + from.

    + + + + + +
    Имя параметра:-variable
    Имя в Базе:variable
    Класс в Базе:Variable
    + +

    Задает имя глобальной переменной, ассоциированной со + шкалой. При изменении значения переменной шкала обновляется и + показывает новое значение. При интерактивном изменении + показателя шкалы происходит соответствующее изменение значения + переменной.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую толщину полосы шкалы (в любой форме, приемлемой + для Tk_GetPixels). Для вертикальной шкалы это + ее ширина, для горизонтальной высота.

    + +

    ОПИСАНИЕ

    + +

    Команда scale создает новое + окно (задаваемое аргументом имяПути) и превращает его в + примитив линейной шкалы. Детали изображения шкалы, такие как ее + цвета, ориентация и объемный вид задаются с помощью описанных + выше дополнительных параметров. Команда scale возвращает + аргумент имяПути. В момент выполнения этой команды не + должно существовать окна с именем имяПути, но должен + существовать его предок.

    + +

    Шкала представляет собой примитив, который выводит на экран + прямоугольную полоску шкалы и маленький + движок. Полоска отображает интервал вещественных чисел + (определенный параметрами from, + to и resolution), а положение + движка задает некоторое конкретное число на этом + интервале. Положение движка (а значит, и показатель шкалы) можно + менять с помощью "Мыши" или клавиатуры, как описано + ниже (см. "ПРИВЯЗКИ"). При + каждом изменении показателя шкалы исполняется команда Tcl + (заданная параметром command), и другие примитивы получают + доступ к результатам выполненного изменения. Кроме того + показатель шкалы можно (с помощью параметра variable) связать с + некоторой переменной, так что изменения значений показателя или + переменной немедленно отзываются друг на друге.

    + +

    В примитиве шкалы можно вывести также три внешних атрибута: имя + шкалы справа сверху (или слева сверху, если шкала + горизонтальна), число непосредственно слева от движка + (непосредственно сверху, если шкала горизонтальна) и набор + числовых меток непосредственно слева от текущего значения + (непосредственно снизу, если шкала горизонтальна). Вывод любого + из этих атрибутов можно отменить с помощью параметров + конфигурации.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда scale создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид.

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы линейной шкалы допускают следующие формы + команды:

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с + именемпараметр. Параметрможет быть любым из + параметров команды scale.
    + +
    имяПути configure + ?параметр? ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает список, + содержащий значения всех допустимых в имениПути + параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения, а команда возвращает пустую + строку. Параметр может быть любым из параметров + командыscale.
    + +
    имяПути coords ?значение?
    + +
    Возвращает список, элементами которого являются x и y + координаты точки посередине полосы шкалы, отвечающей + указанному значению. Если аргумент значение опущен, + то возвращаются координаты точки, отвечающей текущему + показателю шкалы.
    + +
    имяПути get ?x y?
    + +
    Если аргументы x и y опущены, то + возвращает текущий показатель шкалы. Если они заданы, то они + определяют координаты точки в примитиве; в этом случае команда + возвращает значение показателя шкалы, соответствующего + указанной точке. При этом используется только одна из + координат: x для горизонтальной шкалы и y для + вертикальной.
    + +
    имяПути identify x y
    + +
    Возвращает текстовую строку, указывающую, какая часть шкалы + расположена в точке с координатами x и + y. Возвращаемое значение slider + означает, что это точка на движке; trough1 + означает, что точка находится выше или левее движка; + trough2означает, что точка находится ниже или + правее движка. Если точка расположена вне шкалы, то команда + возвращает пустую строку.
    + +
    имяПути set значение
    + +
    Эта команда предназначена для изменения текущего показателя + шкалы, а значит, и положения движка. Аргумент + значениезадает новое значение показателя. Если шкала + недоступна, то команда не приводит ни к каким + результатам.
    +
    + +

    ПРИВЯЗКИ

    + +

    При создании линейной шкалы Tk автоматически создает привязки + класса, определяющие следующее поведение примитива по + умолчанию. В случае, если имеются различия в поведении + вертикальной и горизонтальной шкалы, описание поведения + горизонтальной приводится в скобках.

    + +

    При нажатии клавиши 1 "Мыши" на полосе шкалы движок + сдвигается в направлении курсора на величину, заданную + параметром resolution. Если клавишу не + отпускать, то сдвиг автоматически повторяется.

    + +

    Если нажать клавишу 1 на движке, то движок можно тащить.

    + +

    Если нажать клавишу 1 на полосе шкалы при нажатой клавише + Control. то движок пробежит до конца полосы в + направлении курсора "Мыши".

    + +

    Если нажать клавишу 2, то показатель шкалы будет установлен в + положение курсора "Мыши". Если тащить "Мышь" + с нажатой клавишей 2, то показатель шкалы будет соответственно + меняться.

    + +

    Нажатие на клавиши Up и Left + приводит к перемещению движка вверх (влево) на величину, + указанную параметромresolution.

    + +

    Нажатие на клавиши Down и + Right приводит к перемещению движка вниз + (вправо) на величину, указанную параметром + resolution.

    + +

    Нажатие на клавиши Control-Up и + Control-Left приводит к перемещению движка + вверх (влево) на величину, указанную параметром + bigIncrement.

    + +

    Нажатие на клавиши Control-Down и + Control-Right приводит к перемещению движка + вниз (вправо) на величину, указанную параметром + bigIncrement.

    + +

    Нажатие на клавишу Home приводит к перемещению + движка вверх (влево) до конца полосы.

    + +

    Нажатие на клавишу End приводит к перемещению + движка вниз (вправо) до конца полосы.

    + +

    Если шкала сделана недоступной с помощью параметра + state, то ни одна из описанных выше привязок не + оказывает какого-либо действия.

    + +

    Определяя новые привязки к отдельным примитивам или + переопределяя привязки класса, поведение линейной шкалы можно + изменить.

    + + + + + + diff --git a/hlp/ru/tk/scrollbar.html b/hlp/ru/tk/scrollbar.html new file mode 100644 index 0000000..8d2f38f --- /dev/null +++ b/hlp/ru/tk/scrollbar.html @@ -0,0 +1,432 @@ + + + + scrollbar + + +

    scrollbar

    + +

    Создание примитива линейки прокрутки и управление им.

    + + + +

    СИНТАКСИС

    + +
    +      scrollbar имяПути ?параметры?
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -activebackground
    • +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -jump
    • +
    • -orient
    • +
    • -relief
    • +
    • -repeatdelay
    • +
    • -repeatinterval
    • +
    • -takefocus
    • +
    • -troughcolor
    • +
    + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-activerelief
    Имя в Базе:activeRelief
    Класс в Базе:ActiveRelief
    + +

    Задает объемный вид изображения активного элемента. Все + неактивные элементы изображаются выпуклыми.

    + + + + + +
    Имя параметра:-command
    Имя в Базе:command
    Класс в Базе:Command
    + +

    Задает префикс команды Tcl, исполняемой при всяком изменении + состоянии линейки прокрутки пользователем. Сама команда Tcl + состоит из этого префикса, за которым следует дополнительная + информация, описанная ниже. Значением этого параметра обычно + является что-нибудь вроде .t xview или + .t yview имя примитива, за которым следует + xview (для горизонтальной линейки) или + yview (для вертикальной). У каждого примитива + линейки прокрутки есть команды xview и + yview, аргументы которых описаны ниже (см. + "Команды + прокрутки").

    + + + + + +
    Имя параметра:-elementborderwidth
    Имя в Базе:elementBorderWidth
    Класс в Базе:ElementBorderWidth
    + +

    Задает ширину окантовки каждого из внутренних элементов линейки + (обеих стрелок и движка). Значение может быть представлено в + любом виде, приемлемом для Tk_GetPixels. Если + заданное значение отрицательно, то вместо него используется + значение параметра borderWidth.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую толщину окна линейки (не включая трехмерной + окантовки, если она имеется) в любой форме, приемлемой для + Tk_GetPixels. Для вертикальной шкалы это ее + ширина, для горизонтальной высота.

    + +

    ОПИСАНИЕ

    + +

    Команда scrollbar создает новое окно + (задаваемое аргументом имяПути) и превращает его в + примитив линейки прокрутки. Детали изображения линейки, такие + как ее цвета, ориентация и объемный вид, задаются с помощью + описанных выше дополнительных параметров. Команда возвращает + аргумент имяПути. В момент выполнения этой команды не + должно существовать окна с именем имяПути, но должен + существовать его предок. + +

    Линейка прокрутки представляет собой примитив, который выводит + на экран две стрелки (по одной на каждом конце линейки) и + движок в средней части линейки. Линейка дает информацию + о том, что видно в ассоциированном окне линейки. Это + окно содержит какой-нибудь документ например, редактируемый + текст или рисунок. Размер и положение движка указывают, какая + часть документа видна в окне. Если, например, движок покрывает + верхнюю треть вертикальной линейки, то в ассоциированном окне + выведена верхняя треть документа.

    + +

    Линейки прокрутки используются для перемещения видимой части + документа в ассоциированном окне с помощью + "Мыши". Подробности описаны ниже (см. "Привязки").

    + + +

    ЭЛЕМЕНТЫ

    + +

    Линейка прокрутки состоит из пяти элементов, на которые + ссылаются команды примитива:

    + +
    +
    arrow1
    + +
    Верхняя или левая стрелка линейки.
    + +
    trough1
    + +
    Промежуток между движком и первой стрелкой.
    + +
    slider
    + +
    Прямоугольник, который показывает, какая часть документа + видна на экране.
    + +
    trough2
    + +
    Промежуток между движком и первой стрелкой.
    + +
    arrow2
    + +
    Нижняя или правая стрелка линейки.
    +
    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда scrollbar создает новую команду Tcl с + именем имяПути. С помощью этой команды можно выполнять + различные операции над примитивом. Ее общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    Параметр и аргументы уточняют поведение + команды. Примитивы линейки прокрутки допускают следующие формы + команды:

    + +
    +
    имяПути activate + ?элемент?
    + +
    Помечает элемент, заданный аргументом элемент, как + активный. Активный элемент отображается на экране с + использованием значений параметров activeBackground и + activeRelief. Значениями аргумента могут быть только + arrow1, slider или + arrow2. Если элемент не задан, то + команда возвращает имя текущего активного элемента; если + активных элементов нет, то команда возвращает пустую + строку.
    + +
    имяПути cget + параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из + параметров команды scrollbar.
    + +
    имяПути configure ?параметр? + ?значение параметр значение ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам примитива + присваиваются новые значения, а команда возвращает пустую + строку. Параметр может быть любым из параметров + команды scrollbar.
    + +
    имяПути delta прирX прирY
    + +
    Возвращает вещественное число, задающее изменение показателя + линейки при данном перемещении движка. Например, если линейка + горизонтальна, то результат указывает, насколько нужно + изменить показатель линейки, чтобы движок сдвинулся вправо на + прирX пикселей (в этом случае значение аргумента + прирY игнорируется). Если линейка вертикальна, то + результат указывает, насколько нужно изменить показатель + линейки, чтобы движок сдвинулся вниз на прирY + пикселей. Как аргументы, так и результат могут принимать + отрицательные и нулевое значения.
    + +
    имяПутиfraction x y
    + +
    Возвращает вещественное число между нулем и единицей, + указывающее, где на полосе линейки лежит точка с координатами + x и y. Значение "0" соответствует самой левой или + самой верхней точке полосы, значение "1" самой + правой или самой нижней, "0.5" указывает на середину + полосы и т.д. Координаты x и y это координаты в пикселях + относительно примитива линейки. Если они задают точку вне + полосы линейки, то вместо нее используется точка полосы, + ближайшая к заданной.
    + +
    имяПути get
    + +
    Возвращает показатели линейки в виде списка, элементы + которого значения аргументов последней выполненной команды + примитива set.
    + +
    имяПути identify x y
    + +
    Возвращает имя элемента, занимающего точку с координатами + (x,y) (например, arrow1). Если точка + расположена вне линейки, то команда возвращает пустую + строку. Координаты x и y это координаты в пикселах + относительно примитива линейки.
    + +
    имяПути set перв + послед
    + +
    Эта команда выполняется примитивом, ассоциированным с + линейкой, и сообщает линейке текущий вид этого + примитива. Значением каждого из двух аргументов команды + является число в промежутке от "0" до + "1". Эти числа описывают видимую в окне примитива + область документа. Если, например, значение аргумента + перв равно "0.2", а значение аргумента + послед равно "0.4", то верхушка видимой части + документа отстоит на 20% от его начала, а конец видимой части + на 40% от начала.
    +
    + +

    КОМАНДЫ ПРОКРУТКИ

    + +

    Когда пользователь взаимодействует с линейкой прокрутки + (например, тащит движок), линейка требует от ассоциированного + примитива изменения его состояния. Это требование осуществляется + за счет исполнения команды Tcl, которая генерируется исходя из + значения параметра -command примитива + линейки. Команда может иметь один из следующих видов, где + префикс это значение параметра + -command (обычно что-нибудь вроде .t + yview).

    + +
    +
    префикс moveto величина
    + +
    Величина представляет собой вещественное число между нулем и + единицей. Примитив должен изменить содержимое окна таким + образом, чтобы точка, заданная аргументом величина, + располагалась в начале окна. Например, величина равная + "0" указывает на начало документа, "1.0" + на его конец, "0.333" на точку, отстоящую от начала + документа на одну треть и т.д.
    + +
    префикс scroll число + units
    + + +
    Сдвигает содержимое окна примитива на число + единиц. Единицы это порции документа, имеющие смысл для + документа данного типа (например, символы или строчки для + текстового примитива). Аргумент число может принимать + значение "1" (и тогда одна единица должна уйти из + окна вверх или влево), или "-1" (и тогда одна + единица должна уйти из окна вниз или вправо).
    + +
    префикс scroll + числоpages
    + +
    Содержимое окна примитива должно сдвинуться на + число страниц. Страницы это порции документа, имеющие + смысл для документа данного типа; обычно размер порции + несколько меньше того, что помещается в окне, и поэтому новое + содержимое окна частично перекрывается со старым. Аргумент + число может принимать значение "1" (и тогда + становится видимой следующая страница), или "-1" (и + тогда становится видимой предыдущая страница).
    +
    + +

    СИНТАКСИС КОМАНДЫ

    + +

    В младших версиях Tk (до 4.0) команды примитива + set и get имели другой вид. В + целях совместимости эта форма команд поддерживается и до сих + пор, однако использовать ее не стоит. Вот старый вид команды:

    + +
    +      имяПути set числоЕдин окноЕдин первЕдин последЕдин
    +    
    + +

    Значения всех аргументов команды должны быть целыми + числами. Аргумент числоЕдин задает общее число единиц в + документе. Единицы это порции документа, имеющие смысл + для документа данного типа (например, строчки для текстового + примитива). Аргумент окноЕдин указывает число единиц, + одновременно помещающихся в окно ассоциированного + примитива. Аргументы первЕдин и последЕдин + указывают индексы первой и последней единиц, находящихся в окне + в текущий момент (ноль указывает на первую единицу объекта).

    + +

    В старом синтаксисе команда get + возвращала список из четырех целых чисел значений аргументов + последней выполненной команды примитива set.

    + +

    В старом синтаксисе команды, генерируемые примитивом линейки, + также имеют другой вид:

    + +
    +      префикс единица
    +    
    + +

    Аргумент единица представляет собой целое число, + указывающее, что должно появляться вверху или слева в окне + ассоциированного примитива. Этот аргумент интерпретируется так + же, как и аргументы первЕдин и последЕдин + команды примитива set.

    + +

    Последняя выполненная команда примитива set определяет, следует + ли использовать старый синтаксис. Если ее аргументы два + вещественных числа, то в дальнейшем будет использоваться новый + синтаксис, а если четыре целых то старый.

    + +

    ПРИВЯЗКИ

    + +

    При создании линейки прокрутки Tk автоматически создает + привязки класса, определяющие следующее поведение примитива по + умолчанию. В случае, если имеются различия в поведении + вертикальной и горизонтальной линеек, описание поведения + горизонтальной приводится в скобках.

    + +
      + +
    • При нажатии клавиши 1 "Мыши" на стрелке 1 + (arrow1) содержимое окна ассоциированного + примитива сдвигается вниз (вправо) на одну единицу. Если + клавишу не отпускать, то сдвиг автоматически повторяется.
    • + +
    • При нажатии клавиши 1 "Мыши" на полосе 1 + (trough1) содержимое окна ассоциированного + примитива сдвигается вниз (вправо) на один экран. Если клавишу + не отпускать, то сдвиг автоматически повторяется.
    • + +
    • Если нажать клавишу 1 на движке, то движок можно + тащить. Если значение параметра jump истина, то содержимое + окна не меняется, пока не отпущена клавиша + "Мыши".
    • + +
    • При нажатии клавиши 1 "Мыши" на полосе 2 + (trough2) содержимое окна ассоциированного + примитива сдвигается вверх (влево) на один экран. Если клавишу + не отпускать, то сдвиг автоматически повторяется.
    • + +
    • При нажатии клавиши 1 "Мыши" на стрелке 2 + (arrow2) содержимое окна ассоциированного + примитива сдвигается вверх (влево) на одну единицу. Если + клавишу не отпускать, то сдвиг автоматически повторяется.
    • + +
    • Если нажать клавишу 2 на полосе или на движке, то содержимое + окна переходит в положение, указанное курсором "Мыши" ; если + тащить курсор при нажатой клавише 2, то содержимое окна + движется вслед за курсором. Нажатие клавиши 2 на стрелках + приводит к тому же результату, что и нажатие клавиши 1.
    • + +
    • Если клавиша 1 нажимается при нажатой клавише + Control, то в окне появляется начало + документа (если курсор "Мыши" находится на стрелке 1 + или полосе 1) или его конец (если курсор находится на стрелке + 2 или полосе 2). При других положениях курсора такое нажатие + на клавиши не приводит ни к каким действиям.
    • + +
    • В вертикальных линейках прокрутки нажатие на клавиши + Up и Down приводят к такому + же результату, что и щелчок "Мыши" на стрелках вверх + и вниз соответственно. В горизонтальных линейках нажатие на + эти клавиши не вызывает никаких действий.
    • + +
    • В вертикальных линейках прокрутки нажатие на клавиши + Control-Up и Control-Down + приводят к такому же результату, что и щелчок "Мыши" + на верхней и нижней полосках линейки соответственно. В + горизонтальных линейках нажатие на эти клавиши не вызывает + никаких действий.
    • + +
    • В горизонтальных линейках прокрутки нажатие на клавиши + Up и Down приводят к такому + же результату, что и щелчок "Мыши" на левой и правой + стрелках соответственно. В вертикальных линейках нажатие на + эти клавиши не вызывает никаких действий.
    • + +
    • В горизонтальных линейках прокрутки нажатие на клавиши + Control-Up и Control-Down + приводят к такому же результату, что и щелчок "Мыши" + на левой и правой полосках линейки соответственно. В + вертикальных линейках нажатие на эти клавиши не вызывает + никаких действий.
    • + +
    • Нажатие на клавиши Prior и + Next приводят к такому же результату, что и + щелчки "Мыши" на полосе 1 и полосе 2 + соответственно.
    • + +
    • Нажатие на клавишу Home приводит к появлению в + окне начала документа.
    • + +
    • Нажатие на клавишу End приводит к появлению в + окне конца документа.
    • +
    + + + diff --git a/hlp/ru/tk/selection.html b/hlp/ru/tk/selection.html new file mode 100644 index 0000000..9ef27e3 --- /dev/null +++ b/hlp/ru/tk/selection.html @@ -0,0 +1,159 @@ + + + + selection + + +

    selection

    + +

    Управление X выделением

    + +

    СИНТАКСИС

    + +
    +      selection параметр ?арг арг...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда предоставляет интерфейс Tcl для механизма Х выделения и + реализует полный набор функций выделения, описанный в + (1). Аргумент параметр определяет формат последующих + аргументов и поведение команды. В настоящее время поддерживаются + следующие формы команды:

    + +
    +
    selection clear + ?-displayof окно? + ?-selection выделение?
    + +
    Если на дисплее окна имеются выделения, их следует очистить + так, чтобы ни одно из окон не владело выделением. Параметр + выделение задает X выделение, которое должно быть + очищено; его значением должно быть имя атома, например, + PRIMARY или CLIPBOARD; полное описание см. в (1). По умолчанию + значением параметра выделение является PRIMARY, а + параметра окно ".". Команда возвращает + пустую строку.
    + +
    selection get ?-displayof + окно ?-selection выделение? + ?-type тип?
    + +
    Ищет выделение на дисплее окна и возвращает его значение в + качестве результата. По умолчанию значением параметра + выделение является PRIMARY, а + параметра окно ".". Параметр тип + задает вид возвращаемого результата (в терминологии (1) + "цель"), его значением должно быть имя атома, + например, STRING или + FILE_NAME; полное описание см. (1). По + умолчанию он имеет значение STRING. Владелец + выделения может выбрать для его вывода любой из форматов + STRING, ATOM, + INTEGER и т.д. (этот формат отличается от + типа выделения; детально различия описаны в (1)). Если формат, + в котором выделение возвращается, не строковый, например, + INTEGER или ATOM, то команда + selection преобразует выделение в строковый + формат, представляя его в виде набора полей, разделенных + пробелами: атомы представляются своими текстовыми именами, а + все остальное преобразуется в последовательность + шестнадцатиричных цифр.
    + +
    selection handle + ?-selection выделение? + ?-typeтип? ?-format + формат? окно команда
    + +

    Создает программу обработки запросов на поиск выделения: + при каждой попытке поиска выделения указанного типа в окне + (например, командой selection get) будет + выполняться команда . По умолчанию значением + параметра выделение является PRIMARY, параметра + тип STRING, и параметра формат тоже + STRING. Если значением параметра команда является + пустая строка, то все программы обработки для указанного + окна , типа и выделения + удаляются.

    + +

    Если при запросе выделения окно является его владельцем и + выделение имеет указанный тип, то к команде + добавляется два числа (отделенных пробелами от имени команды + и друг от друга) и она исполняется как команда Tcl. Эти два + дополнительных числа представляют собой смещение и максБайт: + смещение задает положение первого символа в выделении, а + максБайт максимальное количество байтов для + поиска. Возвращаемое командой значение должно начинаться с + указанного символа в выделении и должно быть не длиннее + максБайт. Для очень больших выделений (длина которых + превышает максБайт) поиск будет повторяться многократно с + возрастающими смещениями. Если длина строки, возвращаемой + командой, меньше максБайт, то предполагается, что + возвращенное значение включает в себя весь остаток + выделения; если длина результата совпадает с максБайт, то + команда будет выполняться повторно пока она не возвратит, + наконец, строку, более короткую, чем указано параметром + максБайт. Значение максБайт всегда довольно велико (порядка + нескольких тысяч байтов).

    + +

    Если в результате работы команды возникает ошибка, то + запрос на поиск отвергается, как если бы никакого выделения + вообще не существовало.

    + +

    Аргумент формат задает представление, используемое + для передачи выделения автору запроса (см. (1), второй + столбец в Таблице 2), его значение по умолчанию STRING. Если + значением аргумента формат является STRING, то + выделение передается в виде 8-битовых символов + ASCII (т.е. в том же виде, в каком его возвращает + команда). Если его значение ATOM, то возвращаемое значение + разбивается на поля, отделенные друг от друга пробелами; + каждое поле преобразуется в свое атомарное значение и вместо + имени атома передается 32-битовое атомарное значение. В + любом другом формате возвращаемое командой значение + разбивается на поля, отделенные друг от друга пробелами, и + каждое поле преобразуется в целое 32-битовое число; + полученный массив целых чисел передается автору запроса.

    + +

    Аргумент формат необходим лишь для обеспечения + совместимости пользователям, не использующим Tk. Если для + поиска выделения используется Tk, то на выходе из запроса + результат преобразуется назад в строку, поэтому аргумент + формат не играет роли.

    +
    + +
    selection own ?-displayof + окно? ?-selection + выделение?
    + +
    selection own + ?-command команда? + ?-selection выделение? + окно
    + +

    Первая форма команды selection own + возвращает имя пути окна в данном приложении, владеющего + выделением на дисплее, содержащем окно; + если таких окон нет, то команда возвращает пустую строку. По + умолчанию значением параметра выделение является + PRIMARY, а параметра окно ".".

    + +

    Вторая форма команды selection own делает + окно новым владельцем выделения на дисплее + окна; она возвращает пустую строку. Текущий владелец + выделения (если такой существует) получает + сообщение о том, что он потерял выделение. Если задан + параметр команда, то его значением является скрипт + Tcl, который должен исполняться при попытке какого-либо + другого окна заявить права на выделение вне данного окна. По + умолчанию значением параметра выделение является + PRIMARY.

    +
    +
    + + + + + + diff --git a/hlp/ru/tk/table.html b/hlp/ru/tk/table.html new file mode 100644 index 0000000..97107a3 --- /dev/null +++ b/hlp/ru/tk/table.html @@ -0,0 +1,850 @@ + + + +table + + +

    table

    + +

    Создание таблиц и действия с ними. +

    + +

    Команда становится доступной для выполнения после загрузки библиотеки Tktable2.3 командой:

    + +

    load /..../lib/Tktable2.3/Tktable.so.2.3
    + +
  • Синтаксис
  • +
  • Стандартные опции
  • +
  • Специальные опции команды
  • +
  • Описание команды
  • +
  • Инициализация
  • +
  • Индексы
  • +
  • Теги
  • +
  • Встроенные окна
  • +
  • Выбор
  • +
  • Командные подстановки
  • +
  • Команды виджета
  • +
  • Стандартное поведение
  • + + +

    СИНТАКСИС + +

    table имя виджета опции
    + +

    СТАНДАРТНЫЕ ОПЦИИ +

    +
    -anchor═ +
    -background═ +
    -borderwidth═ +
    -cursor +
    -exportselection +
    -font═ +
    -foreground +
    -highlightbackground +
    -highlightcolor═ +
    -highlightthickness +
    -insertbackground +
    -insertborderwidth +
    -insertofftime═ +
    -insertontime═ +
    -insertwidth +
    -invertselected═ +
    -padx +
    -pady +
    -relief +
    -takefocus +
    -xscrollcommand +
    -yscrollcommand +
    + +

    Детальное описание стандартных опций (см. .Опции).
    + +

    СПЕЦИАЛЬНЫЕ ОПЦИИ КОМАНДЫ + +

    Имя опции в Командной строке: -autoclear
    +Имя опции в Базе данных Х ресурсов: autoClear
    +Имя Класса в Базе данных Х ресурсов: AutoClear
    + +

    Булева величина, которая определяет, будет ли по первому нажатию на клавишу удаляться из ячейки тот текст, который был прежде там.Значение по умолчанию 0.═ + +

    Имя опции в Командной строке:-bordercursor
    +Имя опции в Базе данных Х ресурсов: borderCursor
    +Имя Класса в Базе данных Х ресурсов: Cursor
    + +

    Определяет имя курсора, который появляется на границе поля и показывает, что размеры поля могут быть изменены интерактивно (определяется значением опции -resizeborders). По умолчанию crosshair (перекрестье).

    + +

    Имя опции в Командной строке:-browsecommand или +-browsecmd
    +Имя опции в Базе данных Х ресурсов: browseCommand
    +Имя Класса в Базе данных Х ресурсов: BrowseCommand
    + +

    Определяет команду, которая выполняется каждый раз, когда изменяется активная ячейка. В команде могут использоваться %-подстановки, описанные ниже в разделе═ Командные подстановки.

    + +

    Имя опции в Командной строке:-cache
    +Имя опции в Базе данных Х ресурсов: cache
    +Имя Класса в Базе данных Х ресурсов: Cache
    + +

    Булева величина, которая определяет, будет ли использоваться внутренний кеш таблицы. Его использование позволяет существенно повысить производительность при использовании опции -command, но требует дополнительной памяти. Может улучшить производительность и тогда, когда опции -command и -variable не заданы. Кеш автоматически сбрасывается всякий раз при изменении опций -cache и -variable, в противном случае Вы должны сами сделать это. Значение по умолчанию ложь.

    + +

    Имя опции в Командной +строке:-colorigin
    +Имя опции в Базе данных Х ресурсов: colOrigin
    +Имя Класса в Базе данных Х ресурсов: Origin
    + +

    Определяет, какой индекс столбца является самым левым столбцом в таблице. Эта величина используется для пользовательских индексов в таблице. Значение по умолчанию "0".
    +═ + +

    Имя опции в Командной строке:-cols
    +Имя опции в Базе данных Х ресурсов: cols
    +Имя Класса в Базе данных Х ресурсов: Cols
    + +

    Число столбцов в таблице. Значение по умолчанию .10..

    + +

    +Имя опции в Командной строке:-colseparator
    +Имя опции в Базе данных Х ресурсов: colSeparator
    +Имя Класса в Базе данных Х ресурсов: Separator
    + +

    Определяет символ, который будет использоваться как разделитель столбцов при выборе данных из таблицы или при вставке данных в таблицу. По умолчанию, столбцы разделяются как элементы tcl-списка.

    + +

    Имя опции в Командной +строке:-colstretchmode
    +Имя опции в Базе данных Х ресурсов: colStretchMode
    +Имя Класса в Базе данных Х ресурсов: StretchMode
    + +

    Определяет один из следующих способов расширения столбцов для заполнения дополнительного пространства окна: + +

    none

    + +

    Столбцы не расширяются и не заполняют все отведенное пространство окна таблицы. Если столбцы слишком узки, то в таблице справа будет пробел. Это значение по умолчанию.
    + +

    unset + +

    Расширяются только те столбцы, которые не имеют явно заданной ширины.
    + +

    all + +

    Все столбцы расширяются на одно и то же количество пикселей, чтобы заполнить все пространство окна. В этом режиме могут возникнуть трудности при ручном изменении размеров ширины ячейки.
    + +

    fill (используется только при значении опции rowstretch, равном currently) + +

    В таблице получится больше или меньше столбцов в соответствии с величиной отведенного пространства. Этот способ имеет многочисленные причуды и может исчезнуть в будущем.
    + +

    last + +

    Последний столбец расширяется так, чтобы заполнить все пространство окна таблицы.
    + +

    Имя опции в Командной строке:-coltagcommand
    +Имя опции в Базе данных Х ресурсов: colTagCommand
    +Имя Класса в Базе данных Х ресурсов: TagCommand

    + +

    Задает имя процедуры, которая выполняется, чтобы определить тэг, который используется для данного столбца. Чтобы определить, как отображать ячейку, сначала проверяется, не задан ли тэг для столбца с помощью команды tag col. Если тэг для столбца не задан, выполняется процедура, определенная с помощью настоящей опции. Процедура получает номер столбца в качестве единственного аргумента. Процедура должна возвратить имя тэга или пустую строку. Если при выполнении процедуры происходит ошибка или процедура возвращает недопустимое имя тэга, сообщения об ошибке не выдается.

    + +

    Имя опции в Командной строке:-colwidth
    +Имя опции в Базе данных Х ресурсов: colWidth
    +Имя Класса в Базе данных Х ресурсов: ColWidth
    + +

    Задает ширину столбца по умолчанию. Ширина столбца определяется в символах шрифта (используемого по умолчанию), если она является положительным числом, или в пикселях, если она является трицательным числом. Значение по умолчанию `10..═ + +

    Имя опции в Командной строке:-command
    +Имя опции в Базе данных Х ресурсов: command
    +Имя Класса в Базе данных Х ресурсов: Command
    + +

    Определяет команду, которая используется в качестве процедурного интерфейса к содержимому ячеек. Если опция -usecommand имеет значение истина , эта команда будет использоваться вместо любой ссылки на массив variable. При выборе значения из таблицы вместо содержимого ячейки возвращается результат выполнения команды. Использует %-подстановки, описанные ниже в разделе═ +Командные подстановки.

    + +

    Имя опции в Командной строке:-drawmode
    +Имя опции в Базе данных Х ресурсов: drawMode
    +Имя Класса в Базе данных Х ресурсов: DrawMode
    + +

    Устанавливает один из следующих режимов рисования таблицы:

    + +

    slow

    + +

    Таблица предварительно формируется в памяти (offscreen pixmap) с использованием двойной буферизации. Для границ используются Tk-функции. Этот способ исключает мигание, но оказывается медленным для больших таблиц.
    + +

    compatible + +

    Таблица изображается непосредственно на экране с использованием Tk-функций для границ. Это более быстрый способ, но экран может мигать При изменениях. Это значение по умолчанию.
    + +

    fast + +

    Таблица изображается непосредственно на экране, причем границы рисуются с использованием быстрых X-вызывов, то есть шириной в один пиксель. Как побочный эффект, сужается область значений допустимых значений опции -borderwidth до `0. и `1.. Этот способ обеспечивает наилучшую производительность для больших таблиц, но при этом возможно мигание. Кроме того, этот способ допустим не при всех возможных в Tk значениях ширины границы.
    + +

    single + +

    Таблица рисуется на экране как в режиме fast, но линии изображаются только одним пикселем.
    + +

    Имя опции в Командной строке: -flashmode
    +Имя опции в Базе данных Х ресурсов: flashMode
    +мя Класса в Базе данных Х ресурсов: FlashMode

    + +

    Булево значение, которое определяет, будут ли ячейки мигать, когда их величина изменяется. Тэг flash назначается этим ячейкам на время, определенное с помощью опции -flashtime. По умолчанию устанавливается на 0.
    +═ +

    Имя опции в Командной строке:-flashtime
    +Имя опции в Базе данных Х ресурсов: flashTime
    +Имя Класса в Базе данных Х ресурсов: FlashTime
    + +

    Время в четвертях секунды, в течение которого ячейка высвечивается при изменении величины. Опция -flashmode должно иметь значение on. Значение по умолчанию 2.

    + +

    Имя опции в Командной строке:-height
    +Имя опции в Базе данных Х ресурсов: height
    +Имя Класса в Базе данных Х ресурсов: Height
    + +

    Определяет желаемую высоту для окна в рядах ячеек. Если задано нуль или менее, высота окна выбирается достаточно большой, чтобы содержать все ряды таблицы. Высота может ограничиваться с помощью опции -maxheight.

    + +

    Имя опции в Командной строке:-invertselected
    +Имя опции в Базе данных Х ресурсов: invertSelected
    +Имя Класса в Базе данных Х ресурсов: InvertSelected
    + +

    Определяет, будут ли цвета переднего и заднего планов ячейки заменены друг на друга вместо использования опций тэга sel, когда ячейка выбрана. По умолчанию устанавливается на 0 (использование опций тэга sel).

    + +

    Имя опции в Командной строке:-maxheight
    +Имя опции в Базе данных Х ресурсов: maxHeight
    +Имя Класса в Базе данных Х ресурсов: MaxHeight
    + +

    Максимально возможная высота окна в пикселях. Значение по умолчанию 600.═ + +

    Имя опции в Командной строке:-maxwidth
    +Имя опции в Базе данных Х ресурсов: maxWidth
    +Имя Класса в Базе данных Х ресурсов: MaxWidth
    + +

    Максимально возможная ширина окна в пикселях. Значение по умолчанию 800. +═ + +

    Имя опции в Командной строке:-multiline
    +Имя опции в Базе данных Х ресурсов: multiline
    +Имя Класса в Базе данных Х ресурсов: Multiline
    + +

    Определяет значение по умолчанию для опции тэгов -multiline. Значение по умолчанию `1'. + +

    Имя опции в Командной строке:-resizeborders
    +Имя опции в Базе данных Х ресурсов: resizeBorders
    +Имя Класса в Базе данных Х ресурсов: ResizeBorders
    + +

    Определяет возможность интерактивного изменения размеров ячеек. Допустимые значения опции row col, both (по умолчанию) и none. + +

    Имя опции в Командной строке:-rowheight
    +Имя опции в Базе данных Х ресурсов: rowHeight
    +Имя Класса в Базе данных Х ресурсов: RowHeight
    + +

    Высота колонки по умолчанию. Задается в числе строк текста (шрифта, устанавливаемого по умолчанию), когда число является положительными, или в пикселях, если оно отрицательное. Значение по умолчанию `1'.
    +═ +

    Имя опции в Командной строке:-roworigin
    +Имя опции в Базе данных Х ресурсов: rowOrigin
    +Имя Класса в Базе данных Х ресурсов: Origin
    + +

    Определяет, какую строку считать самой верхней строкой таблицы. Эта величина используется для индексов пользователя в таблице. По умолчанию устанавливается на "0". + +

    Имя опции в Командной строке:-rows
    +Имя опции в Базе данных Х ресурсов: rows
    +Имя Класса в Базе данных Х ресурсов: Rows

    + +

    Количество строк в таблице. Значение по умолчанию `10' +═ +

    Имя опции в Командной строке:-rowseparator
    +Имя опции в Базе данных Х ресурсов: rowSeparator
    +Имя Класса в Базе данных Х ресурсов: Separator
    + +

    Определяет символ, который будет проинтерпретирован как разделитель строк при вставке или удалении данных из таблицы. По умолчанию, строки разделяются как списки tcl. +═ + +

    Имя опции в Командной строке:-rowstretchmode
    +Имя опции в Базе данных Х ресурсов: rowStretchMode
    +Имя Класса в Базе данных Х ресурсов: StretchMode
    + +

    Определяет способ расширения строк для заполнения дополнительного пространства окна. Допустимые значения опции такие же, как для опции colstretchmode. +═ +

    Имя опции в Командной строке:-rowtagcommand
    +Имя опции в Базе данных Х ресурсов: rowTagCommand
    +Имя Класса в Базе данных Х ресурсов: TagCommand
    + +

    Задает имя процедуры, которая выполняется, чтобы определить тэг, который используется для данной строки. Процедура определяется пользователем. Она получает номер строки в качестве единственного аргумента. Процедура должна возвратить имя тэга или пустую строку. Опция аналогична опции coltagcommand и отличается только тем, что задает тэг строки. + +

    Имя опции в Командной строке:-selectioncommand or -selcmd
    +Имя опции в Базе данных Х ресурсов: selectionCommand
    +Имя Класса в Базе данных Х ресурсов: +SelectionCommand + +

    Определяет команду, которая выполняется при получении значений ячеек через механизм выбора (например, при выполнении команды .selection get.). Результат выполнения команды возвращается как результат выбора. В команде могут использоваться %-подстановки, описанные ниже в разделе═ +Командные подстановки. +Если при выполнении команды происходит ошибка, она обрабатывается как ошибка фонового Tcl процесса и команда ничего не возвращает. + +

    Имя опции в Командной строке:-selectmode
    +Имя опции в Базе данных Х ресурсов: selectMode
    +Имя Класса в Базе данных Х ресурсов: SelectMode
    + +

    Определяет один из возможных режимов выбора ячеек. Величина опции может быть произвольной, но встроенная обработка имеется только для следующих режимов: single, browse, multiple и extended; значение по умолчанию browse. Эти режимы аналогичны соответствующим режимам для Tk listbox, за исключением того, что они применяются для двумерных таблиц. + +

    Имя опции в Командной строке:-selecttitle
    +Имя опции в Базе данных Х ресурсов: selectTitles
    +Имя Класса в Базе данных Х ресурсов: SelectTitles
    + +

    Определяет, допускается ли выбор ячеек заголовков. По умолчанию устанавливается на .0. (выбор не допускается). + +

    Имя опции в Командной строке:-selecttype
    +Имя опции в Базе данных Х ресурсов: selectType
    +Имя Класса в Базе данных Х ресурсов: SelectType
    + +

    Определяет один из различных типов выбора для таблицы. Опция может принимать одно из значений: row, col, cell, или both (означает row && col); значение по умолчанию cell. Определяет, будет ли изменение выбора для ячейки (установление или снятие) воздействовать на весь ряд и(или) колонку. + +

    Имя опции в Командной строке:-state
    +Имя опции в Базе данных Х ресурсов: state
    +Имя Класса в Базе данных Х ресурсов: State
    + +

    Определяет одно из двух состояний таблицы: нормальное или неактивное. Если таблица не активна, то величины в ячейках не могут быть изменены с использованием команд таблицы и никакой курсор вставки не отображается, даже если фокус установлен в таблице. По умолчанию устанавливается нормальное состояние. + +

    Имя опции в Командной строке:-titlecols
    +Имя опции в Базе данных Х ресурсов: titleCols
    +Имя Класса в Базе данных Х ресурсов: TitleCols
    + +

    Количество столбцов, используемое для заголовков. По умолчанию устанавливается на "0". + +

    Имя опции в Командной строке:-titlerows
    +Имя опции в Базе данных Х ресурсов: titleRows
    +Имя Класса в Базе данных Х ресурсов: TitleRows
    + +

    Количество строк, используемое для заголовков. По умолчанию устанавливается на 0. + +

    Имя опции в Командной строке:-usecommand
    +Имя опции в Базе данных Х ресурсов: useCommand
    +Имя Класса в Базе данных Х ресурсов: UseCommand
    + +Булева величина, которое определяет, будет ли использоваться команда, заданная с помощью опции -command. Эта величина переустанавливается в нуль, если команда используется и возвращает ошибку. Значение по умолчанию `1. (команда будет использоваться, если она задана). + +

    Имя опции в Командной строке:-validate
    +Имя опции в Базе данных Х ресурсов: validate
    +Имя Класса в Базе данных Х ресурсов: Validate
    + +

    Булева величина, определяющая, будет ли производиться проверка корректности значения активной ячейки. По умолчанию устанавливается на "0". + +

    Имя опции в Командной строке:-validatecommand или -vcmd
    +Имя опции в Базе данных Х ресурсов: validateCommand
    +Имя Класса в Базе данных Х ресурсов: ValidateCommand
    + +

    Определяет команду, которая выполняется для проверки корректности нового значения при редактировании активной ячейки. Эта команда должна возвращать булеву величину. Если она возвращает true, то считается, что новое значение ячейки корректно. В противном случае считается, что введенное значение некорректно и изменения величины в ячейке не произойдет. Если при выполнении этой команды возникает ошибка, она обрабатывается как ошибка фонового Tcl процесса. В команде могут использоваться %-подстановки, описанные ниже в разделе +Командные подстановки. + +

    Имя опции в Командной строке:-variable
    +Имя опции в Базе данных Х ресурсов: variable
    +Имя Класса в Базе данных Х ресурсов: Variable
    + +

    Задает имя Tcl переменной (глобального массива), для работы с С массивом, связанным с данной таблицей. Массив будет создан, если он не существует или если это простая переменная. Индексы элементов массива имеют вид row,col для соответствующих ячеек. В массиве содержится также элемент active, который содержит величину буфера активной ячейки. Tcl массив может быть разреженным массивом (не требуется, чтобы в нем содержались элементы для всех ячеек таблицы). Более того, никакой элемент массива не содержит пустой величины, и при очистке ячейки соответствующий элемент удаляется из Tcl массива. + +

    +Имя опции в Командной строке:-width
    +Имя опции в Базе данных Х ресурсов: width
    +Имя Класса в Базе данных Х ресурсов: Width
    + +

    Определяет желаемую ширину для окна в столбцах ячеек. Если она задана равной нулю или отрицательной, то ширина для окна выбирается достаточно большой, чтобы содержать все столбцы в таблице. Определенная таким образом величина будет ограничена значением опцииmaxwidth, если она задана. + +

    Имя опции в Командной строке:-wrap
    +Имя опции в Базе данных Х ресурсов: wrap
    +Имя Класса в Базе данных Х ресурсов: Wrap
    + +

    Разрешает для тэга перенос текста в ячейках на следующую строку. Значение по умолчанию "0".

    + +

    ОПИСАНИЕ КОМАНДЫ + +

    Команда table создает таблицу . 2-мерную сетку ячеек. Таблица может использовать переменную Tcl массива или Tcl команду для сохранения и выбора данных. Таблица имеет активную ячейку, содержимое которой может быть отредактировано (если таблица находится в нормальном состоянии). Таблица поддерживает общий стиль для ячеек, а также многочисленные тэги, которые могут использоваться, чтобы изменить стиль колонки, столбца или конкретной ячейки +(см. "Теги"). Для ячеек можно установить поведение, при котором измененные ячейки меняют цвет на определенное время (.мигают.). Ячейки могут содержать не только текст, но и графические изображения или встроенные окна, как указано во фрагментахТеги и .Встроенные окна соответственно. + +

    Одна или более ячеек могут быть выбраны, как указано ниже. Если таблица экспортирует свой выбор (смотри опцию -exportselection), то соблюдаются стандартные протоколы X11 для обработки выбора. (См. .Выбор.).

    + +

    Не обязательно, чтобы все ячейки таблицы были видны сразу в табличном окне; описанные ниже команды могут использоваться для просмотра ячеек. Таблицы допускают .прокрутку. в обоих направлениях, используя стандартные опции -xscrollcommand и -yscrollcommand. Они также поддерживают просмотр ячеек, как указано ниже.

    + +

    Чтобы обеспечить достаточную производительность, для таблиц можно выбирать один из трех методов прорисовки, два из которых являются полностью Tk-совместимыми.

    +
    + +

    ИНИЦИАЛИЗАЦИЯ + +

    Когда команда table загружается в интерпретатор, выполняется встроенная Tcl команда tkTableInit. Она ищет и исполняет файл с описанием стандартного поведения таблиц. Файл ищется в каталогах $tcl_pkgPath (как для конкретной, так и для произвольной версии Tktable), $tk_library и [pwd] (текущий каталог). Вы можете также определить $env(TK_TABLE_LIBRARY), который будет поставлен в начало этого списка. По умолчанию, ищется файл tkTable.tcl, но имя файла может быть изменено с помощью переменной $env(TK_TABLE_LIBRARY_FILE). +

    Этот скрипт может быть заменен на ваш собственный, если вы создадите собственную процедуру tkTableInit прежде, чем библиотека будет загружена. В противном случае, вышеупомянутая переменная env(TK_TABLE_LIBRARY) будет содержать имя каталога, в котором был найден файл $env(TK_TABLE_LIBRARY_FILE).

    +
    + +

    ИНДЕКСЫ + +

    Многие команды для таблиц используют один или более индексов как аргументы. Индекс определяет конкретную ячейку таблицы одним из следующих способов: + +

    число,число

    + +

    Определяет ячейку, соответствующую элементу row,col связанного Tcl массива, где -roworigin,-colorigin соответствует первой ячейке в таблице (0,0 по умолчанию).
    + +

    active + +

    Указывает активную ячейку, (ячейку, которая содержит курсор). Активная ячейка может задаваться командой activate.
    + +

    anchor + +

    Указывает якорную точку для выбора, которая устанавливается с помощью команды selection anchor.
    + +

    bottomright + +

    Указывает самую нижнюю самую правую ячейку, видимую в таблице.
    + +

    end + +

    Указывает самую нижнюю самую правую ячейку в таблице.
    + +

    origin + +

    Указывает самую верхнюю самую левую редактируемую ячейку таблицы, не обязательно видимую на экране.
    + +

    topleft + +

    Указывает самую верхнюю самую левую редактируемую ячейку, видимую в таблице.
    + +

    @x,y + +

    Указывает ячейку, которая покрывает в табличном окне точку с координатами x и y (в пикселях). Если никакая ячейка не покрывает эту точку, используется ближайшая к этой точке ячейка.
    +

    В описаниях команд таблиц, приведенных ниже, аргументы, называющиеся index, first или last всегда обозначают индексы в одной из вышеуказанных форм.

    + +

    ТЕГИ + +

    Тэг является текстовой строкой, которая связывается с нулем или больше колонок, столбцов или ячеек в таблице. Тэги могут содержать произвольные символы, но желательно избегать использования для тегов имен, похожих на индексы. С колонками, столбцами или ячейками таблицы может быть связано любое количество тэгов. В каждой таблице есть несколько постоянных тэгов, которые могут конфигурироваться пользователем и определят атрибуты для специальных ячеек: + +

    active

    + +

    Это тэг активной ячейки.
    + +

    flash + +

    Если режим высвечивания включен, этот тэг дается всем недавно отредактированным ячейкам.
    + +

    sel + +

    Этот тэг дается всем выбранным ячейкам.
    + +

    title + +

    Этот тэг дается всем ячейкам, используемым для заголовков колонок и строк. Для этого тэга по умолчанию определено состояние "неактивно".
    + +

    Тэги определяют, как соответствующие ячейки отображаются на экране. По умолчанию, ячейки отображаются, как определено опциями -background, -font, и foreground для таблицы. Тем не менее, для каждого тэга могут быть заданы индивидуальные значения этих опций с помощью команды + +

    pathName tag configure
    + +

    Если для ячейки задан тэг, опции тэга переопределяют стиль таблицы. В настоящее времени для тэгов поддерживаются следующие опции: +

    -anchor anchor

    +

    якорь для текста или другого объекта в пространстве ячейки;
    +

    -background или -bg color +

    цвет Фона ячейки;
    +

    -font fontName +

    шрифт для текста в ячейке;
    +-foeground или -fg color +

    цвет переднего плана ячейки;
    +

    -justify justify +

    выключка текста в ячейке. Возможные значения +

    left, right, center;

    +

    -image imageName +

    графический объект, который будет отображен в ячейке вместо текста;
    +

    -multiline boolean +

    отобразить текст с символами .конец строки. в виде нескольких строк;
    +

    -relief relief +

    рельеф для ячейки;
    +

    -showtext boolean +

    показывать текст поверх графического объекта;
    +

    -state state +

    состояние ячейки, позволяет определенным ячейкам быть неактивными. Это предохраняет ячейку от редактирования с помощью вставки или удаления, но остается возможным прямое занесение информации в массив, результаты которого отображаются в таблице;
    + +

    -wrap boolean + +

    разрешает переносить символы в следующую строку, если ячейка недостаточно широкая.
    + +

    Для тэгов определен порядок приоритета. Он используется при выполнении некоторых описанных ниже функций, связанных с тэгами. Когда ячейка отображается, ее свойства определяются тэгами, которые ей присвоены. Этот порядок, включая специальные тэги, flash, active, sel, title, celltag, rowtag, coltag, default. + +

    Если с ячейкой связано несколько различных тэгов и если их опции противоречат между собой, используются опции самого приоритетного тэга. Если конкретная опция не определена для конкретного тэга или если она определена как пустая строка, эта опция никогда не будет использована. Будет использовано значение опции от следующего по приоритету тэга. Если ни для одного тэга опция не определена, будет использован стиль, заданный по умолчанию для виджета.

    + +

    Графические объекты используются только для показа. Редактирование текста в таких ячейках остается возможным, и любой запрос покажет текст, хранящийся в ячейке, независимо от значения опции -showtext.

    +
    + +

    ВСТРОЕННЫЕ ОКНА + +

    В таблице может быть произвольное количество встроенных окон (по одному на ячейку), и любой виджет (подчиняющийся обычным правилам, по которым встроенное окно должно быть потомком табличного окна или его родителя) может быть использован в качестве встроенного окна. Позиция встроенного окна на экране будет скорректирована, как только будет изменена или передвинута таблица, и оно будет отображено на экране или спрятано в зависимости от того, находится ли соответствующая ячейка в видимой области таблицы. Каждое встроенное окно занимает одну ячейку таблицы, и на него можно сослаться по индексу ячейки. Встроенные окна уничтожаются, когда уничтожается содержащая их таблица. +

    Окна используются только для показа. Текстовое значение для ячеек, занятых окнами, существует, но оно не отображается, пока окно не удаляется некоторым способом.

    + +

    Когда встроенное окно вставлено в таблицу с помощью команды window configure, с ним связывается несколько опций, которые могут быть изменены с помощью последующих вызовов команды window configure. В настоящее время поддерживаются следующие опции:

    + +

    -create script

    + +

    В НАСТОЯЩЕЕ ВРЕМЯ НЕ ПОДДЕРЖИВАЕТСЯ. Определяет Tcl скрипт, который может выполняться для создания заявленного окна. Если для окна, встроенного в ячейку, опция window не задана, при необходимости отобразить ячейку на экране будет выполнен скрипт. Скрипт должен создать окно и вернуть его имя как результат выполнения скрипта. Если впоследствии окно будет удалено, перед повторным появлением ячейки на экране скрипт будет выполнен опять.
    + +

    -background или -bg color +

    Цвет Фона окна. Если опция не определена, то используется цвет фона таблицы.
    +

    -padx pixels +

    Как определено в руководстве по Tk.
    +

    -pady pixels +

    Как определено в руководстве по Tk.
    +

    -relief relief +

    Рельеф, используемый для ячейки, в которой лежит окно. Если опция не определена, используется значение для таблицы.
    +

    -sticky sticky +

    .Клейкость. окна в ячейке, как определено для команды grid.
    +

    -window pathName +

    Определяет имя окна, которое будет отображено в ячейке. Окно должно существовать прежде, чем может быть использовано здесь.
    +
    + +

    ВЫБОР + +

    Табличные выборы представляют собой данные типа СТРОКА. По умолчанию, величина выбора состоит из величин (значений) выбранных ячеек в форме Tcl списка, где каждый ряд является списком и каждый столбец является элементом списка ряда. Вы можете изменить способ, которым интерпретируется эта величина, с помощью опций -rowseparator и colseparator. Например, формат Эксела устанавливается с помощью значений
    -rowseparator .\n. и -colseparator .\t.. Изменение этих опций влияет как на формирование выбора для таблицы, так и на чтение данных при вставке, гарантируя, что в таблице можно вырезать данные и вставить их в нее же. Можно изменять поведение таблицы при вставке данных с помощью редактирования библиотечной процедуры tk_tablePasteHandler. Это может потребоваться, если установлена опция -selectioncommand.
    + +

    КОМАНДНЫЕ ПОДСТАНОВКИ + +

    Команды, задающиеся с помощью различных опций таблиц, могут использовать традиционные для Tk %-ные подстановки (см. bind). Следующие %-ные подстановки выполняются при работе с таблицами: + +

    %c

    +

    Для SelectionCommand это максимальное количество столбцов в ряду в выбранной области.

    +

    Для остальных команд индекс столбца ячейки, вызвавшей событие.

    +

    %c

    +

    Удобная замена для %r,%c.div> +

    %i +

    Для SelectionCommand это общее число ячеек в выбранной области.
    +

    Для Command это `0. для чтения (get) и `1. для записи (set). +

    Для остальных команд текущая позиция курсора в ячейке.

    +

    %R

    +

    Для SelectionCommand это количество рядов в выбранной области.
    +

    Для остальных команд ряд ячейки, породившей событие. +

    %S

    +

    Для ValidateCommand это текущее значение в ячейке, которое будет проверяться.
    +

    Для SelectionCommand это значение по умолчанию для выбора.
    +Для BrowseCommand это индекс последней активной ячейки.
    +Для Command это пустое значение для чтения (get) и текущая значение в ячейке для записи (set).
    +

    %S

    +
    Для ValidateCommand это потенциальное новое значение в ячейке, значение в которой проверяется.
    + +

    Для BrowseCommand это индекс новой активной ячейки. +

    %W

    +

    Имя окна, вызвавшего событие.
    +
    +

    КОМАНДЫ ВИДЖЕТА +

    Команда table создает новую команду Tcl, чье имя является именем созданного виджета. Эта команда может использоваться, чтобы выполнить различные действия с виджетом. У нее есть следующая общая форма: + +

    pathName option arg arg ...

    + +

    где pathName имя виджета.

    +

    Значение опции и аргументов определяют точное назначение команды.
    +Для таблиц определены следующие опции команды:

    + +

    pathName activate index

    + +

    Активизирует ячейку, заданную индексом.
    + +

    pathName bbox first ?last? + +

    Возвращает параметры области, объемлющей заданную ячейку (группу ячеек) в виде списка из четырех элементов: координат x и y левого верхнего угла области, ее ширины и высоты в пикселях. Область объемлет только те из указанных ячеек, которые видны на экране. Если таких ячеек нет, возвращается пустая строка.
    + +

    pathName border optionargs + +

    Эта команда является волшебным средством, для переноса границ ячеек при изменении их размеров. Обычно она вызывается через события с одной из следующих подопций:
    + +

    pathName border mark x y row|col + +

    Запоминает координаты x и y и границу строки и/или столбца под этой точкой в таблице, если точка лежит на границе. Используется в связке с последующей командой border dragto. Чаще всего эта команда вызывается по нажатию кнопки .Мыши. на таблице. Если аргумент row или col не задан, команда возвращает кортеж из обоих индексов границы (пустой кортеж означает, что точка не принадлежит границе). В противном случае возвращается индекс заданной границы (строки или столбца соответственно).
    + +

    pathName border dragto x y + +

    Эта команда вычисляет разность между своими x и y аргументами и y и x аргументами последней команды border mark для таблицы. Затем она изменяет положение границы на вычисленную разность. Эта команда обычно вызывается по событию движения "Мыши" в таблице, чтобы произвести эффект интерактивного изменения границы.
    + +

    pathName cget option + +

    Возвращает текущую величину опции. Option может быть любой из опций, определенных для таблиц.
    + +

    pathName clear option ?first? ?last? + +

    Эта команда является удобной утилитой, чтобы удалять различные объекты таблицы. first и last представляют правильные табличные индексы. Если ни один индекс не задан, команда выполняется для всей таблицы. Возможные подопции:
    + +

    pathName clear cache first last + +

    Очищает определенный раздел кеша, если таблица использовала кеш.
    + +

    pathName clear sizes ?first? ?last? + +

    Отменяет заданные размеры ячеек для столбцов и колонок, входящих в заданную область. Если задан только один индекс, например, "2,0", то он задает область, состоящую из колонки "2" и столбца "0".
    + +

    pathName clear tags first last +

    Очищает определенную область от тэгов (все row, column и cell тэги).
    +

    pathName clear all first last + +

    Выполняет все вышеуказанные действия в определенной области.
    + +

    pathName configure option value option value .. + +

    Запрашивает или модифицируют опции таблицы. Если никакая опция не определена, возвращает список, описывающий все доступные опции для виджета (смотри Tk_ConfigureInfo для информации о формате этого списка). Если опция указана без значения, команда возвращает список, описывающий одну опцию (этот список идентичен соответствующему подсписку списка, возвращаемого, если никакая опция не задана). Если заданы одна или более пар опция-величина, то команда модифицирует данную опцию виджета, чтобы она имела данное значение (значения); в этом случае команда возвращает пустую строку. Опция может быть любой из опций, определенных для команды table.
    + +

    pathName curselection set value + +

    Если аргументы команды не заданы, то команда возвращает отсортированные индексы выбранных ячеек. В противном случае она устанавливает во все выбранные ячейки заданное значение. Опция set не воздействует на таблицу, если у таблицы нет связанного Tcl массива или состояние таблицы неактивно.
    + +

    pathName curvalue value + +

    Если величина не задана, возвращается величина из редактируемой ячейки (с индексом active), иначе величина устанавливается в активной величине.
    + +

    pathName deleteoptionarg?arg? + +

    Эта команда используется, чтобы удалять различные компоненты таблицы. У нее есть различные формы, в зависимости от подопции:
    + +

    pathName deleteactive index index + +

    Удаляет текст из активной ячейки. Если дан только один индекс, команда удаляет символ после этого индекса, в противном случае удаляются символы с первого индекса по второй. index может быть числом, insert или end/div> + +

    pathName deletecolsswitches index count + +

    Удаляет count колонок, начиная с колонки с индексом index. Если count . отрицательное, удаляет колонки влево от начальной. В противном случае удаляет колонки вправо. Выбор очистится. Дополнительные ключи:
    + +

    -cols value + +

    Устанавливает искусственное ограничение на число столбцов в активной области. Столбцы за пределами активной области при этом изменяться не будут. По умолчанию используется величина опции -cols таблицы, то есть активная область распространяется на все столбцы. Использование опции может вызвать интересные побочные эффекты, когда опция используется в связке с другими опциями.
    + +

    -holddimensions + +

    Обеспечивает сохранение числа столбцов в таблице (при удалении могут появиться пустые столбцы вместо удаленных). По умолчанию число столбцов уменьшается в соответствии со значением count.
    + +

    -holdtags + +

    Обеспечивает сохранение тэгов, созданных с помощью команды tag, при удалении всех ячеек, для которых они были заданы. Тэги присваиваются новым ячейкам с соответствующими индексами. Также предотвращает изменение ширины таблицы, если она задана с помощью команды width. По умолчанию новые ячейки, вставшие на место удаленных, не наследуют их тегов.
    + +

    -keeptitles + +

    Защищает ячейки области заголовка от изменения. В противном случае они могут быть удалены подобно регулярным ячейкам.
    + +

    -rows value + +

    Устанавливает искусственное ограничение на число строк в активной области. Строки за пределами активной области при этом изменяться не будут. По умолчанию используется величина опции -rows таблицы, то есть активная область распространяется на все строки. Использование опции может вызвать интересные побочные эффекты, когда опция используется в связке с другими опциями.
    + +

    -- + +

    Означает конец ключей.
    + +

    pathName delete rows switches index count + +

    Удаляет count строк таблицы, начиная со строки index (и включая ее). Если count отрицательное, то удаляются предшествующие строки. В противном случае удаляются последующие строки. Выбор очищается. Ключи такие же, как для удаления столбца.
    + +

    pathName flushfirst last + +

    Сохраняет табличный кеш от first до last. Если индексы не заданы, сохраняется весь кеш.
    +

    pathName getfirst last + +

    Возвращает (в виде списка) значения из ячеек, содержащихся в прямоугольной области с левым верхним углом, заданным индексом first, и правым нижним углом, определяемым индексом last (если задан).
    + +

    pathName height rowvalue row value ... + +

    Если никакая строка не задана, возвращает список, описывающий все строки, для которых высота установлена. Если колонка задана без величины, возвращает высоту этой колонки в символах (положительное число) или пикселях (отрицательное число). Если одна или более пар строка-величина определены, тогда, устанавливает высоту соответствующих строк в строках символов (положительное число) или пикселях (отрицательный номер). Если задано значение высоты .default., то высота строки определяется значением опции -rowheight.
    + +

    pathName icursor arg + +

    Если команда задана без аргументов, то она возвращает позицию курсора вставки в активной ячейке. Если команда задана с одним аргументом, то она устанавливает курсор в этой точке в строке. 0 . перед первым символом. Допустимые индексы: insert для текущего положения курсора и end для конца текста.
    + +

    pathName index index row|col + +

    Возвращает индекс ячейки, которая соответствует указанному индексу, в форме row,col. Если задана опция row или col, то команда возвращает только индекс строки или столбца соответственно.
    + +

    pathName insertoptionarg arg + +

    Эта команда используется, чтобы вставлять различные объекты (значения, колонки, столбцы и т.п.) в таблицу. У нее есть различные формы в зависимости от подопции:
    + +

    pathName insert active index value + +

    value является текстовой строкой, которая вставляется в активную ячейку, начиная с позиции index. Курсор затем позиционируется после встроенного текста. index может быть числом, insert или end.
    + +

    pathName insert cols switches index count + +

    Вставляет count столбцов, начиная с индекса col. Если count является отрицательным числом, они вставляются перед столбцом с индексом col. В противном случае они вставляются после столбца с индексом col. Выбор очищается. Ключи те же, как при удаления столбца.
    + +

    pathName insert rows switches index count + +

    Вставляет count строк, начиная с индекса col. Если count является отрицательным числом, они вставляются перед строкой с индексом col. В противном случае они вставляются после строки с индексом col. Выбор очистится. Ключи те же, как для удаления строки.
    + +

    pathName reread + +

    Перечитывает старое содержимое ячейки снова в буфер редактирования. Полезно для обработки событий, когда <Escape> нажимается, чтобы прервать редактирование (стандартное поведение).
    + +

    pathName scan option args + +

    Эта команда используется, чтобы осуществить "прокрутку" таблицы. У нее есть две формы в зависимости от опций:
    + +

    pathName scan mark x y + +

    Запоминает текущие координаты x и y и вид таблицы; используется в связке с последующей scan dragto командой. Обычно эта команда вызывается по нажатию на кнопку "Мыши". Возвращает пустую строку.
    + +

    pathName scan dragto x y + +

    Эта команда вычисляет разность между текущими координатами y и x и координатами x и y, запомненными в последней команде scan mark для данного виджета. Затем она .прокручивает. таблицу на 5-кратную разность координат. Эта команда обычно вызывается при движении .Мыши. на таблице и используется для ускоренного просмотра таблицы. Возвращает пустую строку.
    + +

    pathName seeindex + +

    .Прокручивает. таблицу так, чтобы ячейка, заданная индексом, оказалась первой ячейкой с левого верхнего края таблицы (исключая строки и столбцы заголовков), если ячейка к настоящему времени не видна на экране. Фактическая ячейка может не оказаться самой первой, если за ней в таблице недостаточно ячеек, чтобы заполнить экран.
    + +

    pathName selectionoptionarg + +

    Эта команда используется, чтобы управлять выбором в таблице. У нее есть различные формы, в зависимости от опций:
    + +

    pathName selectionanchorinde + +

    Устанавливает якорь выбора в ячейке, заданной индексом. Якорь выбора является концом выбора, который фиксируется, пока второй конец области выбора передвигается с помощью .Мыши.. Индекс anchor может использоваться для ссылок на соответствующую ячейку.
    + +

    pathName selection clear first last + + +

    Снимает выбор с выбранных ячеек от first до last (включительно). Состояние выбора для ячеек за пределами этой области не изменяется. Если first равно all, команда удаляет выбор из всех ячеек.
    + +

    pathName selection includesindex + +

    Возвращает `1', если ячейка, указанная индексом, выбрана, и `0. если нет.
    + +

    pathName selection set first last + +

    Выбирает все ячейки в области от first до last включительно, не влияя на состояние выбора ячеек за пределами этой области.
    + +

    pathName set row|colindex value index value ... + +

    Для каждой пары index value устанавливает значение value в ячейке, определенной индексом. Проверка корректности значений при этом не производится. Если списку пар индекс-величина предшествует row или col, величина value рассматривается как Tcl список, и значения из списка устанавливаются в последовательных ячейках строки или колонки соответственно. Например, команда + +

    set row 2,3 {2,3 2,4 2,5}
    + +

    Установит значения в 3 ячейки, от 2,3 до 2,5.

    + +

    pathName tag option arg arg ... + +

    Эта команда используется, чтобы управлять тэгами. Точное поведение команды зависит от значения опции и аргументов. Только опция cget требует использования реально существующих тэгов. В настоящее время поддерживаются следующие формы команды:
    + +

    pathName tag cell tagName index ... + +

    Если команда задана без аргументов, то она распечатывает список ячеек, которые используют тэг. В противном случае она устанавливает тэг заданным ячейкам. Если тэг пустой ({}), ячейкам восстанавливается тэг по умолчанию. Тэги, добавленные с помощью опций -*tagcommand, здесь не обрабатываются.
    + +

    pathName tag cget tagNameoption + +

    Эта команда возвращает текущую величину опции option для тэга tagName. option может быть любой из опций, определенных для команды tag configure для таблиц.
    + +

    pathName tag col tagName col ... + +

    Если команда задана без аргументов, то она распечатывает список колонок, которые используют данный тэг. В противном случае устанавливает тэг заданным столбцам. Если тэг пустой ({}), столбцам восстанавливается тэг по умолчанию. Тэги, добавленные с помощью опции -coltagcommand, здесь не обрабатываются.
    + +

    pathName tag configure tagName option value option value ... + +

    Эта команда подобна команде configure для таблиц, за исключением того, что она изменяет опции, связыванные с тэгом tagName вместо модификации опций для всей таблицы. Если никакая опция не задана, команда возвращает список всех доступных опций для tag_Name (смотри Tk_ConfigureInfo для информации о формате этого списка). Если опция указана без величины, возвращается подсписок указанного списка, соответствующий указанной опции. Если указана одна или более пар опция- величина, то команда модифицирует данную опцию (опции) для указанного тэга; в этом случае команда возвращает пустую строку. См. "ТЭГИ".
    + +

    pathName tag delete tagName +

    Удаляет тэг. Если тэг не существует, ошибки не возникает.
    + +

    pathName tag exists tagName + +

    Возвращает `1', если указанный тэг существует, и "0" в противном случае.
    + +

    pathName tag includes tagNameindex + +

    Возвращает `1', если ячейка с данным индексом имеет указанный тэг, и "0" в противном случае.
    + +

    pathName tag names pattern + +

    Если никакой образец не задан, показывает имена всех определенных тэгов в таблице. В противном случае образец используется в качестве шаблона, и показываются только тэги, удовлетворяющие этому шаблону.
    + +

    pathName tag row tagName row ... + +

    Если команда задана без аргументов, то она распечатывает список строк, которые используют данный тэг. В противном случае она устанавливает данный тэг указанным строкам. Если тэг пустой ({}), строкам восстанавливается тэг по умолчанию. Тэги, добавленные с помощью опции rowtagcommand, не обрабатываются здесь.
    + +

    pathName validateindex + +

    Явно проверяет корректность значения в ячейке, определенной индексом, с помощью команды, заданной опцией validatecommand. Возвращает `0' или `1' в зависимости от результатов проверки.
    + +

    pathName width col value col value ... + +

    Если никакой столбец не задан, возвращает список, описывающий все столбцы, для которых установлена ширина. Если столбец указан без указания ширины, команда возвращает ширину соответствующего столбца в символах (положительное число) или пикселях (отрицательное число). Если заданы одна или более пар колонка-величина, тогда команда устанавливает каждому перечисленному столбцу соответствующую ширину в символах (положительное число) или пикселях (отрицательное число). Если величина совпадает с шириной, задаваемой по умолчанию, колонка в дальнейшем будет использовать ширину, определенную с помощью опции -colwidth.
    + +

    pathName window option arg arg ... + +

    Эта команда используется, чтобы управлять встроенными окнами. Точное поведение команды зависит от значения опции и аргументов. В настоящее время поддерживаются следующие формы команды:
    + +

    pathName window cget index option + +

    Эта команда возвращает текущую величину опции option для окна в ячейке с данным индексом. option может иметь любое из значений, допустимых для команды window configure.
    + +

    pathName window configureindex option value option value ... + +

    Эта команда подобна команде configure для таблицы, за исключением того, что она изменяет опции, связанные с встроенным окном с данным индексом, а не опции таблицы в целом. Если опция указана без величины, возвращается подсписок указанного списка, соответствующий указанной опции. Если указана одна или более пар опция-величина, то команда модифицирует данную опцию (опции) для указанного окна; в этом случае команда возвращает пустую строку. +См. "Встроенные окна ".
    + +

    pathName window deleteindex index ... +

    Удаляет встроенное окно из таблицы.Соответствующее окно также будет удалено.
    +

    pathName window move indexFrom indexTo +

    Перемещает встроенное окно из одной ячейки в другую. Если в целевой ячейке уже существует другое окно, оно будет удалено.
    +

    pathName window names pattern +

    Если никакой шаблон не задан, команда показывает все ячейки, в которых есть встроенные окна. В противном случае показывает только те ячейки, в которых есть встроенные окна с именами, удовлетворяющими шаблону.
    + +

    pathName xview args +

    Эта команда используется для запросов о горизонтальной позиции таблицы в окне и для изменения горизонтальной позиции таблицы в окне. Команда может использоваться в одной из следующих форм:
    + +

    pathName xview
    + +

    Возвращает список, содержащий два элемента. Каждый из них является действительным числом из диапазона `0' `1'. Они указывают соответственно левую и правую границы видимой области. Например, если первый элемент `2' а второй элемент `6', то 20% табличного текста выходит за пределы экрана слева, средние 40% текста видны в окне, и 40% текста выходит за пределы экрана вправо. Эти величины используются для конфигурации полос прокрутки с помощью команды, заданной опцией -xscrollcommand.
    + +

    pathName xview index
    + +

    .Прокручивает. таблицу так, чтобы столбец с данным индексом отображался на левом крае окна.
    + +

    pathName xview moveto fraction
    +═ +

    .Прокручивает. таблицу так, чтобы доля общей ширины табличного текста, выходящая за пределы экрана влево, равнялась fraction. fraction должно быть дробью между `0' и `1'.
    + +

    pathName xview scroll numberwhat + +

    Эта команда .прокручивает. таблицу влево или вправо на заданное расстояние. number должно быть целым числом. what должно быть units или pages или сокращением одного из их. Если what равно units, таблица сдвигается на number символов (символ равен ширине символа 0); если what равно pages, таблица сдвигается на соответствующее число экранов. Если number является отрицательным числом, тогда более левые символы становятся видимыми; если number положительное число, тогда более правые символы становятся видимыми.
    + +

    pathName yviewargs + +

    Эта команда используется для запросов о вертикальной позиции таблицы в окне и для изменения вертикальной позиции таблицы в окне. Команда может использоваться в одной из следующих форм:
    + +

    pathName xview + +

    Возвращает список, содержащий два элемента. Каждый из них является действительным числом из диапазона `0' - `1'. Они указывают соответственно верхнюю и нижнюю границы видимой области (например, `5' означает середину таблицы) Эти величины используются для конфигурации полос прокрутки с помощью команды, заданной опцией
    +-yscrollcommand.
    + +

    pathName yview index + +

    .Прокручивает. таблицу так, чтобы строка с данным индексом отображалась на верхнем крае окна.
    + +

    pathName yview moveto fraction + +

    .Прокручивает. таблицу так, чтобы доля общей высоты табличного текста, выходящая за пределы экрана вверх, равнялась fraction. fraction должно быть дробью между `0' и `1'.
    + +

    pathName yview scroll number what + +

    Эта команда .прокручивает. таблицу вверх или вниз на заданное расстояние. number должно быть целым числом. what должно быть units или pages или сокращением одного из их. Если what равно units, таблица сдвигается на number строк текста; если what равно pages, таблица сдвигается на соответствующее число экранов. Если number является отрицательным числом, тогда более ранние символы становятся видимыми; если number положительное число, тогда более поздние символы становятся видимыми.
    +
    + +

    СТАНДАРТНОЕ ПОВЕДЕНИЕ
    +═ +

    Вновь созданная таблица обладает следующим поведением. + +

    [1] Нажатие левой кнопки .Мыши. в ячейке активизирует эту ячейку. Нажатие кнопки .Мыши. в уже активной ячейке перемещает курсор вставки на ближайший символ.

    +

    [2] Перемещение курсора .Мыши., при нажатой левой кнопке, позволяет выделить область таблицы. Выход курсора из таблицы вниз, при нажатой левой кнопке .Мыши., обеспечивает прокрутку таблицы одновременно с выделением ячеек.

    +

    [3] Перемещение курсора .Мыши., при нажатой средней кнопке "Мыши", обеспечивает прокрутку таблицы без выделения.

    +

    [4] Клавиша Home возвращает к началу таблицы.

    +

    [5] Клавиша End перемещает в конец таблицы.

    +

    [6] Сочетание клавиш Control-Home перемещает в начало таблицы и активизирует первую ячейку.

    +

    [7] Сочетание клавиш Control-End перемещает в конец таблицы и активизирует последнюю ячейку.

    +

    [8] Сочетание клавиш Shift-Control-Home расширяет выделенную область таблицы до ее начала.

    +

    [9] Сочетание клавиш Shift-Control-End расширяет выделенную область таблицы до ее конца.

    +

    [10] Клавиши с изображениями стрелок позволяют выбрать соседнюю ячейку в соответствующем направлении.

    +

    [11] Сочетание клавиш Shift-<arrow> расширяет выбранную область в направлении, указываемом стрелкой.

    +

    [12] Сочетание клавиш Control-leftarrow и +Control-rightarrow перемещают курсор вставки внутри ячейки.

    +

    [13] Сочетание клавиш Control-slash выбирает все ячейки.

    +

    [14] Сочетание клавиш Control-backslash clears снимает выбор со всех ячеек.

    +

    [15] Клавиша Backspace удаляет символ перед курсором вставки в активной ячейке.

    +

    [16] Клавиша Delete удаляет символ после курсора вставки в активной ячейке.

    +

    [17] Клавиша Escape перечитывает содержимое активной ячейки из заданного источника данных, отменяя любые изменения, выполненные в ячейке.

    +

    [18] Сочетание клавиш Control-a перемещает курсор вставки в начало активной ячейки.

    +

    [19] Сочетание клавиш Control-e перемещает курсор вставки в конец активной ячейки.

    +

    [20] Control-minus и Control-equals уменьшает и увеличивает ширину столбца, содержащего активную ячейку.

    +

    [21] Перемещение курсора .Мыши. с нажатой правой кнопкой когда курсор находится на границе ячейки вызовет изменение размеров строки и/или столбца, (при соответствующей величине опция +resizeborders).

    + +

    Поведение таблицы может незначительно отличаться от описанного выше в зависимости от значения опции -selectionmode.

    + +

    Если таблица дезактивирована с помощью опции -state, то ее вид не отличается от вида активной таблицы, и ячейки могут по-прежнему быть выбраны, но никакой курсор вставки не появится в ячейках и никакие модификации ячейки не произойдут.

    + +

    Поведение таблиц может изменяться путем определения новых событий для конкретной таблицы или путем переопределения событий для всего класса. Описание стандартных событий приведено в файле tkTable.tcl.

    +
    + + + + + diff --git a/hlp/ru/tk/text.html b/hlp/ru/tk/text.html new file mode 100644 index 0000000..a2ef372 --- /dev/null +++ b/hlp/ru/tk/text.html @@ -0,0 +1,2090 @@ + + + + text + + +

    text

    + +

    Создание текстового примитива и управление им.

    + +

    СИНТАКСИС

    + +
    +      text имяПути параметры
    +    
    + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -background
    • +
    • -borderwidth
    • +
    • -cursor
    • +
    • -exportselection
    • +
    • -font
    • +
    • -foreground
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -insertbackground
    • +
    • -insertborderwidth
    • +
    • -insertofftime
    • +
    • -insertontime
    • +
    • -insertwidth
    • +
    • -padx
    • +
    • -pady
    • +
    • -relief
    • +
    • -selectbackground
    • +
    • -selectborderwidth
    • +
    • -selectforeground
    • +
    • -setgrid
    • +
    • -takefocus
    • +
    • -xscrollcommand
    • +
    • -yscrollcommand
    • +
    + +

    Подробное описание этих параметров приведено в разделе + options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + + +

    Задает желаемую высоту окна в символах; размер символа + определяется шрифтом, который задан параметром -font. Значение параметра должно быть не меньше + единицы.

    + + + + + +
    Имя параметра:-spacing1
    Имя в Базе:spacing1
    Класс в Базе:Spacing1
    + +

    Запрашивает дополнительный промежуток перед каждой строкой + текста в примитиве (в любой из разрешенных форм для расстояний + на экране). При переносе строки заданное значение относится + только к первой строчке на экране. Параметр + -spacing1 в тегах подавляет данный.

    + + + + + + +
    Имя параметра:-spacing2
    Имя в Базе:spacing2
    Класс в Базе:Spacing2
    + + +

    Задает величину дополнительного промежутка между двумя + последовательными строчками на экране, полученными в результате + переноса одной строки текста (в любой из разрешенных форм для + расстояний на экране). Параметр spacing2 в + тегах подавляет данный.

    + + + + + +
    Имя параметра:-spacing3
    Имя в Базе:spacing3
    Класс в Базе:Spacing3
    + +

    Запрашивает дополнительный промежуток после каждой строкой + текста в примитиве (в любой из разрешенных форм для расстояний + на экране). При переносе строки заданное значение относится + только к последней строчке на экране. Параметр + -spacing3 в тегах подавляет данный.

    + + + + + +
    Имя параметра:-state
    Имя в Базе:state
    Класс в Базе:State
    + +

    Задает одно из двух состояний текста: нормальное + (normal) или недоступное + (disabled). Текст, находящийся в недоступном + состоянии, нельзя редактировать и в нем не отображается курсор + ввода, даже если данный примитив находится в фокусе ввода.

    + + + + + + +
    Имя параметра:-tabs
    Имя в Базе:tabs
    Класс в Базе:Tabs
    + + +

    Задает набор положений табулятора в окне. Значение параметра + представляет собой список расстояний на экране, задающих эти + положения. Элемент списка, следующий за элементом, который + указывает очередное положение табулятора, может описывать способ + расположения текста относительно этого положения с помощью + ключевых слов left, right, + center или numeric. Значение + по умолчанию равно left; в этом случае левый + край текста, следующего за символом табуляции, располагается в + позиции табуляции. Right означает, что в + позиции табуляции располагается правый край текста, следующего + за символом табуляции, а center указывает на + необходимость центрировать текст относительно позиции + табуляции. Numeric означает, что в позиции + табуляции следует располагать десятичную точку текста; если в + тексте нет десятичной точки, то младшая значащая цифра числа + располагается непосредственно слева от позиции табуляции; если в + тексте нет чисел, то он выравнивается вправо по позиции + табуляции. Например, задание параметра -tabs {2c left + 4c 6c center} приводит к созданию трех позиций + табулятора с двухсантиметровым интервалом, первые два из которых + используют выравнивание влево, а третья выравнивание по + центру. Если в списке положений табулятора их оказывается + недостаточно, чтобы обеспечить все символы табуляции в строке + текста, то Tk создает дополнительные позиции табуляции, + экстраполируя промежуток и способ выравнивания текста, указанные + последним элементом списка. Параметр -tabs в + тегах подавляет данный. Если параметр -tabs не + задан или его значением является пустая строка, то Tk использует + табуляцию по умолчанию с шагом, равным восьми символам среднего + размера.

    + + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + + +

    Задает желаемую ширину окна в символах; размер символа + определяется шрифтом, который задан параметром -font. Если + ширина символа в шрифте непостоянна, то для перевода числа + символов в единицы экрана используется ширина символа "0". +

    + + + + + + +
    Имя параметра:-wrap
    Имя в Базе:wrap
    Класс в Базе:Wrap
    + +

    Задает способ обращения с чересчур длинными строками, которые + не помещаются в одной строчке экрана. Может принимать одно из + значений none, char или + word. Значение none указывает + на то, что каждая строка текста отображается в единственной + строчке экрана не поместившиеся символы не выводятся. В + остальных двух режимах при необходимости осуществляется перенос + каждой строки текста, чтобы все ее содержимое отображалось на + экране. В режиме char переход на новую строчку + можно осуществлять после любого символа; в режиме + word перенос строки выполняется только после + конца слова.

    + +

    ОПИСАНИЕ

    + +

    Команда text создает новое окно (задаваемое + аргументом имяПути) и превращает его в текстовый + примитив. Детали изображения текста, такие как цвет фона по + умолчанию и объемный вид, задаются с помощью описанных выше + дополнительных параметров. Команда text + возвращает имя пути нового окна.

    + +

    Текстовый примитив предназначен для вывода одной или нескольких + строк текста и для редактирования этого текста. Текстовые + примитивы поддерживают четыре способа отметить часть текста так + называемые теги, метки, вставленные окна и вставленные + изображения. Теги позволяют выводить различные части текста + различными шрифтами и цветом. Кроме того с тегами можно связать + команды Tcl, которые будут выполняться каждый раз при совершении + определенных действий, например, при нажатиях на клавиши + клавиатуры и "Мыши", если курсор находится в определенной части + текста. Подробно эти возможности описаны ниже (см. "Теги").

    + +

    Метки представляют собой другой способ отметить часть + текста. Они предназначены для указания на различные интересные + места в тексте, возникающие в процессе его + редактирования. Подробно эти возможности описаны ниже + (см. "Метки").

    + +

    Третий способ обеспечивает возможность вставки в текст + произвольных окон. Подробно эти возможности описаны ниже + (см. "Вставленные + окна").

    + +

    Четвертый способ обеспечивает возможность вставки в текст + изображений Tk. Подробно эти возможности описаны ниже + (см. "Вставленные + изображения".)

    + + +

    ИНДЕКСЫ

    + +

    Аргументами многих команд примитива являются один или несколько + индексов. Индекс представляет собой строку, указывающую + конкретное место в тексте например, место вставки текста или + один из граничных символов удаляемого участка текста. Индексы + имеют следующий синтаксис:

    + +
    +      база модификатор модификатор модификатор ...
    +    
    + +

    База это указатель начальной точки, а + модификаторы указывают сдвиг от начальной точки + (например, на один символ влево или вправо от базы). База + является обязательной частью индекса, а модификаторы + необязательной.

    + +

    База индекса должна быть представлена в одном из + следующих видов:

    + +
    +
    строка.сим
    + +
    Указывает на символ с номером сим в строке с + номером строка . Для совместимости с другими + программами ОС UNIX, использующими тот же подход к нумерации, + строки нумеруются, начиная с "1". Нумерация символов + в строке начинается с "0". Если значением + сим является end, то база ссылается + на символ перевода строки, завершающий строку.
    + +
    @x,y
    + +
    Указывает на символ, в котором находится точка с + координатами в окне текста равными x и + y.
    + +
    end
    + +
    Указывает на конец текста (на символ, следующий + непосредственно за последним символом перехода на новую + строку).
    + +
    метка
    + +
    Указывает на символ, следующий непосредственно за меткой с + именем метка.
    + +
    тег.first
    + +
    Указывает на первый символ в тексте, помеченный тегом с + именем тег. Если в тексте нет символов, помеченных + тегом, то возникает ошибка.
    + +
    тег.last
    + +
    Указывает на символ, непосредственно следующий за последним + символом, помеченным тегом с именем тег. Если в + тексте нет символов, помеченных тегом, то возникает + ошибка.
    + +
    имяПути
    + +
    Указывает положение вставленного окна с именем + имяПути. Если вставленное окно с заданным именем + отсутствует, то возникает ошибка.
    + +
    имяИзобр
    + +
    Указывает положение вставленного изображения с именем + имяИзобр. Если вставленное изображение с заданным + именем отсутствует, то возникает ошибка.
    +
    + +

    Если вид базы не определяется однозначно (так, например, если + метка и имяИзобр имеют одинаковое значение, то + их нельзя различить), то предпочтение отдается виду, + встречающемуся в приведенном списке раньше. Если за индексом + базы идут модификаторы, то каждый из них должен быть представлен + в одном из описанных ниже видов. Ключевые слова, например, + chars или wordend, можно + сокращать, если результат сокращения позволяет однозначно + восстановить слово.

    + +
    +
    + счет chars
    + +
    Увеличивает индекс на счет символов, при + необходимости переходя на следующую строку. Если за символом с + текущим индексом следует меньше символов, чем счет, + то индекс устанавливается на последний символ в + тексте. Пробелы по обе стороны от значения счет + необязательны.
    + +
    - счет chars
    + +
    Уменьшает индекс на счет символов, при + необходимости переходя на предыдущую строку. Если перед + символом с текущим индексом идет меньше символов, чем + счет, то индекс устанавливается на первый символ в + тексте. Пробелы по обе стороны от значения счет + необязательны.
    + +
    + счет lines
    + +
    Увеличивает индекс на счет строк, сохраняя номер + символа в строке. Если за строкой с текущим индексом следует + меньше строк, чем счет, то индекс устанавливается на + символ с тем же номером в последней строчке текста. Если длина + строки с новым положением индекса меньше номера символа, то + индекс указывает на последний символ в этой строке (символ + перевода строки). Пробелы по обе стороны от значения + счет необязательны.
    + +
    - счет lines
    + +
    Уменьшает индекс на счет строк, сохраняя номер + символа в строке. Если перед строкой с текущим индексом идет + меньше строк, чем счет, то индекс устанавливается на + символ с тем же номером в первой строчке текста. Если длина + строки с новым положением индекса меньше номера символа, то + индекс указывает на последний символ в этой строке (символ + перевода строки). Пробелы по обе стороны от значения + счет необязательны.
    + +
    linestart
    + +
    Устанавливает индекс на первый символ в строке.
    + +
    lineend
    + +
    Устанавливает индекс на последний символ в строке (символ + перевода строки).
    + +
    wordstart
    + +
    Устанавливает индекс на первый символ в слове, содержащем + символ с текущим значением индекса. Слово представляет собой + последовательность букв, цифр или символов подчеркивания + (состоящую, быть может, из одного символа).
    + +
    wordend
    + +
    Устанавливает индекс на первый символ в слове, содержащем + символ с текущим значением индекса. Если текущее значение + индекса и без того указывает на последний символ в слове, то + оно не изменяется.
    +
    + +

    Если в команде задано несколько модификаторов, то они + применяются слева направо. Так, например, индекс + "end-1 chars" указывает на + предпоследний символ в тексте, а индекс "insert + wordstart-1 c" указывает на символ, + непосредственно предшествующий первому символу в слове, + содержащем символ с текущим значением индекса.

    + +

    ТЕГИ

    + +

    Участки текста можно помечать с помощью тегов. Тег представляет + собой символьную строку, которая привязана к некоторым символам + текста. В принципе теги могут содержать любые символы, однако + использования символов " " (пробел), "+" + и "-" лучше избегать: это специальные символы + индексов и использование тега, в котором присутствуют такие + символы, в качестве индекса невозможно. С символами данного + текста можно связать произвольное количество тегов. Каждый тег + может относиться к одному символу, последовательности символов + или к нескольким последовательностям символов. С отдельным + символом может быть связано произвольное количество тегов.

    + +

    Все теги упорядочены; на этот порядок опираются некоторые из + описываемых ниже функций работы с тегами. При определении тега + (путем связывания его с символами, или при установке параметров + его представления на экране, или при привязке к нему команд) он + получает более высокий приоритет, чем все существующие + теги. Приоритетный порядок тегов можно изменить с помощью команд + примитива "имяПути tag + raise" и "имяПути tag + lower".

    + +

    В текстовых примитивах теги служат для достижения трех + целей. Во-первых, они управляют отображением информации на + экране. По умолчанию способ отображения текста определяется + значениями параметров background, + font и foreground текстового + примитива. Однако команда примитива "имяПути + tag configure" позволяет связать с каждым тегом + свои значения параметров отображения. Если с символом связан + тег, то значения параметров отображения для этого тега подавляют + значения по умолчанию. В настоящее время для тегов можно + пользоваться следующими параметрами:

    + +
    +
    -background цвет
    + +
    Параметр цвет задает цвет фона для изображения + символов, связанных с данным тегом. Его значение может быть + представлено в любом виде, приемлемом для + Tk_GetColor.
    + +
    -bgstipple двуцвет
    + +
    Параметр двуцвет задает двуцветное изображение, + предназначенное для вывода в качестве фона для текста. Его + значение может быть представлено в любом виде, приемлемом для + Tk_GetBitmap. Если параметр двуцвет + не задан или его значением является пустая строка, то + используется равномерное заполнение фона. +
    + +
    -borderwidth пиксели
    + +
    Параметр пиксели задает ширину трехмерного бордюра, + окружающего фон. Его значение может быть представлено в любом + виде, приемлемом для Tk_GetPixels. Этот + параметр используется в сочетании с параметром + -relief для описания трехмерного + представления фона для символов; если параметр + -background для тега не задан, то параметр + -borderwidth игнорируется.
    + +
    -fgstipple двуцвет
    + +
    Параметр двуцвет задает двуцветное изображение, + предназначенное для вывода в качестве фона для рисования + текста и другой информации переднего плана (например, + подчеркивания). Его значение может быть представлено в любом + виде, приемлемом для Tk_GetBitmap. Если + параметр двуцвет не задан или его значением является + пустая строка, то используется равномерное заполнение + фона.
    + +
    -font имяШрифта
    + +
    Параметр имяШрифта задает имя шрифта для + изображения символов. Его значение может быть представлено в + любом виде, которы описан в команде font.
    + +
    -foreground цвет
    + +
    Параметр цвет задает цвет символов текста и другой + информации переднего плана, например, подчеркивания. Его + значение может быть представлено в любом виде, приемлемом для + Tk_GetColor.
    + +
    -justify вырав
    + +
    Если первый символ строчки на экране связан с тегом, для + которого задан такой параметр, то значение параметра + определяет способ выравнивания текста в строчке. Параметр + вырав может принимать значения left, + right и center. При переносе + строки выравнивание каждой из получившихся строчек на экране + определяется первым символом этой строчки.
    + +
    -lmargin1 пиксели
    + +
    Если первый символ строчки на экране связан с тегом, для + которого задан такой параметр, то значение параметра пиксели + задает величину отступа от левого края окна. Значение + параметра пиксели представляет собой расстояние на экране в + любом допустимом виде. При переносе строки этот параметр + применяется только к первой строчке на экране; отступом + остальных строк управляет параметр + -lmargin2.
    + +
    -lmargin2 пиксели
    + +
    Если первый символ строчки на экране связан с тегом, для + которого задан такой параметр, и если строчка на экране не + является первой строчкой строки текста (т.е. она представляет + собой часть перенесенной строки текста), то значение параметра + пиксели задает величину отступа данной строчки от левого края + окна. Значение параметра пиксели представляет собой расстояние + на экране в любом допустимом виде. Этот параметр используется + только если допускается перенос строки; он применяется только + ко второй и последующим перенесенным строчкам.
    + +
    -offset пиксели
    + +
    Параметр пиксели задает величину сдвига (в + пикселях) по вертикали базиса строки текста от базиса основной + строки. Например, для верхних индексов базисная строка + сдвигается вверх, а для нижних вниз. Значение параметра + пиксели представляет собой расстояние на экране в любом + допустимом виде.
    + +
    -overstrike булевское
    + +
    Указывает, следует ли проводить горизонтальную прямую + посередине символов. Значение параметра булевское + может быть представлено в любом виде, приемлемом для + Tk_GetBoolean.
    + +
    -relief обвид
    + +
    Значение параметра обвид задает объемный вид фона в + любом виде, приемлемом для Tk_GetRelief. Этот + параметр используется в сочетании с параметром + -borderwidth для установления трехмерного + вида фона для символов; если параметр + -background для данного тега не установлен, + то параметр -relief игнорируется.
    + +
    -rmargin пиксели
    + +
    Если первый символ строчки на экране связан с тегом, для + которого задан такой параметр, то значение параметра пиксели + задает величину отступа между последним символом строчки и + правым краем окна. Значение параметра пиксели представляет + собой расстояние на экране в любом допустимом виде. Этот + параметр используется только, если перенос строки + допустим. При переносе строки этот параметр применяется только + ко всем перенесенным строчкам.
    + +
    -spacing1 пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства над каждой строкой текста. Значение параметра + пиксели представляет собой расстояние на экране в любом + допустимом виде. При переносе строки этот параметр применяется + только к первой строчке на экране.
    + +
    -spacing2 пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства над каждой перенесенной строчкой из строчек, + составляющих одну строку текста. Значение параметра пиксели + представляет собой расстояние на экране в любом допустимом + виде.
    + +
    -spacing3 пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства под каждой строкой текста. Значение параметра + пиксели представляет собой расстояние на экране в любом + допустимом виде. При переносе строки этот параметр применяется + только к последней строчке на экране.
    + +
    -tabs списТаб
    + +
    Параметр списТаб задает набор положений табулятора + в том же виде, что и параметр -tabs для + текстового примитива. Этот параметр относится к строке текста + только в том случае, если он связан с первым символом + строки. Если значением параметра является пустая строка, то + параметр считается не заданным для данного тега (по + умолчанию). Если значением параметра является не пустая + строка, а пустой список (например, установка параметра имеет + вид -tags { }), то его значением считается + стандартный набор 8-символьных позиций табулятора + (см. описание параметра -tags для + примитива).
    + +
    -underline булевское
    + +
    Параметр булевское указывает, следует ли + подчеркивать символы. Значение параметра булевское может быть + представлено в любом виде, приемлемом для + Tk_GetBoolean.
    + +
    -wrap режим
    + +
    Параметр режим задает способ обработки строк, длина + которых превышает ширину текстового окна. Допустимые значения + параметра те же, что и у параметра -wrap + текстового примитива: none, + char и word. Если этот + параметр задан, то он подавляет параметр + -wrap текстового примитива.
    +
    + +

    Если с символом связано несколько тегов, причем задаваемые ими + параметры вывода противоречат друг другу, то используются + значения параметров тегов с наивысшим приоритетом. Если + некоторый параметр вывода для конкретного тега не задан или если + его значением является пустая строка, то этот параметр при + выводе не используется; вместо него берется параметр тега со + следующим приоритетом. Если ни один из тегов не определяет + параметра вывода, то используется стиль, принятый для данного + примитива по умолчанию.

    + +

    Во-вторых, теги служат для привязки событий. Привязки к тегу +осуществляются практически таким же образом, как и привязки к + классу примитива: заданная команда Tcl исполняется всякий раз, + когда на символе с данным тегом происходит указанное событие. С + помощью привязок к тегам можно задать поведение групп символов; + помимо прочего таким образом можно реализовать некоторые + свойства гипертекста. Подробное описание этих возможностей + см. ниже в описании команды примитива tag + bind.

    + +

    Третья задача тегов обеспечивать управление выделениями + (См. "Выделение" ).

    + +

    МЕТКИ

    + +

    Метки представляют собой другой способ отмечать части + текста. Они служат для запоминания фиксированных мест в + тексте. Метки похожи на теги в том, что они поименованы и + ссылаются на определенные места в тексте, однако они не связаны + ни с какими конкретными символами. Напротив, метка указывает на + промежуток между двумя символами. В каждый момент времени метка + указывает в точности на одно положение. При удалении символов, + окружающих положение метки, сама метка сохраняется, меняются + лишь ее соседи. Теги же теряют привязку к символам при удалении + этих символов. Для работы с метками предназначена команда + примитива "имяПути mark"; + имя метки можно использовать в качестве индекса в командах + примитива этот индекс указывает на текущее положение метки.

    + +

    Каждой метке приписывается притяжение, которое может + принимать значения left и + right. Притяжение определяет поведение метка + при вводе текста в положении метки. При левом притяжении метка + ведет себя, как если бы она была приписана к символу слева от + нее; такая метка будет оставаться слева от вновь вводимого + текста. Для метки с правым притяжением вновь вводимый текст + окажется слева от нее. По умолчанию притяжение имеет значение + right.

    + +

    Пространства имен меток и тегов различны: одинаковые имена + могут использоваться для метки и тега; при этом они будут + ссылаться на различные объекты.

    + +

    У двух меток есть особый смысл. Метка insert + связана с курсором ввода; см. описание ниже (см. "Курсор ввода"). Метка + current связана с символом, ближайшим к курсору + "Мыши", ее положение меняется автоматически при + изменении позиции курсора и любых изменениях текста в примитиве + (с одним исключением: метка current не + обновляется в ответ на изменение положения курсора при нажатой + клавише "Мыши"; обновление откладывается до момента, + когда все клавиши "Мыши" будут отпущены). Ни одну из + этих двух специальных меток нельзя удалить.

    + +

    ВСТАВЛЕННЫЕ ОКНА

    + +

    Вставленное окно это третий тип ссылок в текстовом + примитиве. Ссылка на вставленное окно приводит к появлению окна + в заданном месте текста. В текстовом примитиве может быть любое + количество вставленных окон; в качестве вставленного окна может + быть использован любой примитив (при соблюдении обычных + ограничений управления геометрией, согласно которым текстовое + окно должно быть непосредственным предком вставленного окна или + потомком этого предка). Положение вставленного окна меняется + при редактировании или прокрутке текста; окно выводится или + стирается в зависимости от того, попадает ли оно в видимую часть + текста. Вставленное окно считается одним символом в индексном + пространстве текстового примитива; на него можно сослаться либо + по имени текстового окна, либо по значению индекса в индексном + пространстве. При удалении области текста, содержащей + вставленное окно, оно разрушается.

    + +

    При добавлении в текстовый примитив вставленного окна с помощью + команды примитива window create с ним можно + связать несколько параметров конфигурации. Значения этих + параметров можно впоследствии изменить командой примитива + window configure. В настоящее время + поддерживаются следующие параметры:

    + +
    + +
    -align где
    + +
    Если высота вставленного окна отличается от высоты строчки, + в которой оно выводится, то этот параметр определяет место, + где выводится окно. Параметр где может принимать следующие + значения: top (верхушка окна совпадает с + верхней частью строчки), center (окно + центрируется в области строчки), bottom + (нижняя часть окна совпадает с нижней частью строчки) и + baseline (нижняя часть окна совпадает с базой + строчки).
    + +
    -create скрипт
    + +
    Задает скрипт Tcl, выполняемый для создания вставленного + окна. Этот скрипт выполняется при выводе окна, если для окна + не был указан параметр -window.Скрипт + создает окно и возвращает в качестве результата имя этого + окна. Если окно удаляется, то при его повторном выводе снова + исполняется тот же скрипт.
    + +
    -padx пиксели
    + +
    Параметр пиксели задает размер дополнительного пространства, + которое следует оставить по обе стороны вставленного окна. Его + значение представляет собой расстояние на экране в любом + допустимом виде.
    + +
    -pady пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства, которое следует оставить сверху и снизу от + вставленного окна. Его значение представляет собой расстояние + на экране в любом допустимом виде.
    + +
    -stretch булевское
    + +
    Параметр указывает, следует ли вытягивать вставленное окно + до высоты строчки, если запрошенная для него высота меньше + высоты строчки, на которой это окно выводится. Если для окна + задан также параметр -pady, то запрошенное + этим параметром обрамление сохраняется и при вытягивании + окна.
    + +
    -window имяПути
    + +
    Задает имя выводимого окна.
    +
    + +

    ВСТАВЛЕННЫЕ ИЗОБРАЖЕНИЯ

    + +

    Последним видом пометок в текстовых примитивах являются + вставленные изображения. Такая пометка приводит к выводу + изображения в заданном месте текста. В текстовом примитиве может + присутствовать произвольное количество вставленных изображений, + а одно и то же изображение может вставляться в произвольном + количестве мест в тексте. Положение вставленного изображения + меняется при редактировании или прокрутке текста. Вставленное + изображение считается одним символом в индексном пространстве + текстового примитива; на него можно сослаться либо по значению + индекса в индексном пространстве, либо по имени, которое оно + получает при создании командой image create. При + удалении области текста, содержащей вставленное изображение, + данная его копия стирается с экрана.

    + +

    При добавлении в текстовый примитив вставленного изображения с + помощью команды примитива image create + команда возвращает уникальное имя данного вхождения изображения + в текст. Это имя в дальнейшем можно использовать для ссылок на + вхождение изображения. Имя совпадает со значением параметра + -name (см. ниже). Если параметр + -name не задан, то вместо него используется имя + -image. Если значение имяИзобр уже + использовано в примитиве, то к нему дописываются символы + #nn, где nn произвольное целое число. Таким + образом обеспечивается уникальность имени. После присвоения + имени данному вхождению изображения это имя в дальнейшем не + меняется, несмотря на то, что значения параметров + -image и -name можно поменять + с помощью команды image + configure.

    + +

    При добавлении в текстовый примитив вставленного изображения с + помощью команды примитива image create с ним + можно связать несколько параметров конфигурации. Значения этих + параметров можно впоследствии изменить командой примитива image + configure. В настоящее время поддерживаются + следующие параметры:

    + +
    +
    -align где
    + +
    Если высота вставленного изображения отличается от высоты + строчки, в которой оно выводится, то этот параметр определяет + место, где выводится изображение. Параметр где может принимать + следующие значения: top (верхушка + изображения совпадает с верхней частью строчки), + center (изображение центрируется в области + строчки), bottom (нижняя часть изображения + совпадает с нижней частью строчки) и baseline + (нижняя часть изображения совпадает с базой строчки).
    + +
    -image изобр
    + +
    Задает имя выводимого изображения Tk. Если значение + параметра не является допустимым именем изображения, то + возвращается сообщение об ошибке.
    + +
    -name ИмяИзобр
    + +
    Задает имя ссылки на данное вхождение изображения. Если + параметр ИмяИзобр не задан, то именем служит имя + изображения Tk. Если значение параметра ИмяИзобр уже + использовалось, то к нему приписываются символы #nn, как + описано выше.
    + +
    -padx пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства, которое следует оставить по обе стороны + вставленного изображения. Его значение представляет собой + расстояние на экране в любом допустимом виде.
    + +
    -pady пиксели
    + +
    Параметр пиксели задает размер дополнительного + пространства, которое следует оставить сверху и снизу от + вставленного изображения. Его значение представляет собой + расстояние на экране в любом допустимом виде.
    +
    + +

    ВЫДЕЛЕНИЕ

    + +

    Выделение реализуется с помощью тегов. Если параметр + exportSelection текстового примитива имеет + значение истина, то с выделением ассоциируется тег + sel: + +

      +
    1. Если некоторые символы помечены тегом + sel, то текстовый примитив притязает на + владение выделением.
    2. + +
    3. Результатом поиска выделения будут служить все символы, + помеченные тегом sel.
    4. + +
    5. Если выделение запрашивается другим приложением или другим + окном данного приложения, то тег sel + снимается со всех символов текста.
    6. +
    + +

    Тег sel определяется автоматически при + создании текстового примитива; его нельзя удалить командой + примитива "имяПути tag + delete". Кроме того параметры + selectBackground, + selectBorderWidth и + selectForeground текстового примитива связаны с + параметрами -background, + -borderwidth и -foreground + тега sel: изменение одного из этих параметров + примитива автоматически вызывает изменение соответствующего + параметра тега и наоборот.

    + + +

    КУРСОР ВВОДА

    + +

    Метка с именем insert имеет в текстовых + примитивах специальное значение. Она определяется автоматически + при создании примитива и ее нельзя отменить командой примитива + "имяПутиmark unset". Метка + insert задает положение курсора ввода; курсор + ввода отображается в этом положении всякий раз, когда текстовый + примитив попадает в фокус ввода.

    + +

    КОМАНДА ПРИМИТИВА

    + +

    Команда text создает новую команду Tcl, имя + которой совпадает с именем текстового окна. С помощью этой + команды можно выполнять различные операции над примитивом. Ее + общий вид

    + +
    +      имяПути параметр ?арг арг ...?
    +    
    + +

    имяПути является именем команды; оно совпадает с + именем пути текстового примитива. Параметр и аргументы уточняют + поведение команды. Текстовые примитивы допускают следующие формы + команды:

    + +
    +
    имяПути bbox индекс
    + +
    Возвращает список из четырех элементов, описывающий область + экрана, занимаемую символом с индексом индекс. Первые + два элемента списка представляют собой координаты x и y + верхнего левого угла этой области; последние два это ее ширина + и высота. Если символ виден на экране лишь частично, то + возвращаемые значения описывают видимую часть области. Если + символ на экране не виден, то возвращаемое значение является + пустым списком.
    + +
    имяПути cget + параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров + команды text.
    + +
    имяПути compare индекс1 оп + индекс2
    + +
    Сравнивает индексы, задаваемые параметрами индекс1 + и индекс2, в соответствии с оператором отношения, + задаваемым параметром оп; команда возвращает + "1", если указанное отношение выполняется, и + "0" в противном случае. Параметр оп может принимать + одно из значений "<", "<=", + "=", ">=", ">" или + "!=". Если значением оператора является + "=", то команда возвращает "1", если оба + индекса ссылаются на один и тот же символ; при операторе + "<" команда возвращает "1", если + индекс1 ссылается на символ, предшествующий символу с + индексом индекс2, и т.д.
    + +
    имяПути configure + ?параметр? ?значение параметр значение + ...?
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр задан, а его новое + значение нет, то команда возвращает часть полного + списка, относящуюся к указанному параметру. Если заданы одна + или несколько пар параметр-значение, то указанным + параметрам примитива присваиваются новые + значения, а команда возвращает пустую + строку. Параметр может быть любым из параметров + команды text.
    + +
    имяПути debug + ?булевское?
    + +
    Если задан параметр булевское, то он может иметь + значение истина или ложь в виде, приемлемом для + Tcl_GetBoolean. Если значение параметра + истина, то в B-дереве, связанном с текстовыми примитивами, + будет выполняться внутренняя проверка согласованности. В + противном случае эта проверка будет отключена. Независимо от + полученного значения команда возвращает пустую строку. Если + параметр булевское не задан, то команда возвращает + on или off в зависимости от + того, подключена или нет в момент выполнения команды система + отладки. Переключатель отладки один на все текстовые + примитивы: изменение его значения в одном примитиве приводит к + изменению этого значения для всех примитивов. Проверка + согласованности для примитивов с длинными текстами может + привести к существенному замедлению работы.
    + +
    имяПути delete индекс1 + ?индекс2?
    + +
    Удаляет последовательность символов в тексте. Если заданы + оба параметра индекс1 и индекс2, то + удаляются все символы, начиная с символа с индексом + индекс1, и кончая символом, непосредственно + предшествующим символу с индексом индекс2 + (т.е. символ с индексом индекс2 не удаляется). Если + параметр индекс2 не задан, то удаляется только символ + с индексом индекс1. Невозможно такое удаление, при + котором последний символ оставшегося текста не будет символом + перевода строки. Команда возвращает пустую строку.
    + +
    имяПути dlineinfo индекс
    + +
    Возвращает список из пяти элементов, описывающий область + экрана, занимаемую строчкой, содержащей символ с индексом + индекс. Первые два элемента списка представляют собой + координаты x и y верхнего левого угла этой области; следующие + два это ее ширина и высота; пятый элемент это расстояние от + верхней границы области вниз до базы строчки. Все значения + измеряются в пикселях. Если текущий режим переноса строки + имеет значение none и строка видна на экране + лишь частично, то возвращаемые значения описывают всю область + строки, включая и ее невидимые части. Если строчка короче + полной ширины экрана, то возвращаемые значения описывают + только ту ее часть, которая занята символами и вставленными + окнами. Если строчка, содержащая символ с индексом + индекс, на экране не видна, то возвращаемое значение + является пустым списком.
    + +
    имяПути dump ?переключатели? + индекс1 ?индекс2?
    + +

    Возвращает содержимое текстового примитива от символа с + индексом индекс1 до символа с индексом + индекс2 (не включая последний), включая сам текст, + а также информацию о метках, тегах и вставленных окнах. Если + параметр индекс2 не задан, то по умолчанию + описывается символ с индексом индекс1. Возвращаемая + информация имеет следующий формат:

    + +
    +          ключ1 значение1 индекс1 ключ 2 значение 2 индекс 2 ...
    +        
    + +

    Ключи могут принимать значения text, + mark, tagon, + tagoff и + window. Соответствующими возвращаемыми + значениями будут текст, имя метки, имя тега или имя + окна. Возвращаемыми значениями индекса будут индекс начала + текста, метки, тегового перехода или окна. Для управления + результатом можно использовать один или несколько из + следующих переключателей (или их аббревиатур):

    + +
    +
    -all
    + +
    Возвращается информация обо всех элементах тексте, + метках, тегах и окнах. Это значение принято по + умолчанию.
    + +
    -command команда
    + +
    В этом случае вместо возвращения информации об элементах + текстового примитива на каждом из этих элементов в + указанной области текста выполняется + команда. Аргументами команды служат + ключ, значение и индекс соответствующего элемента.
    + +
    -mark
    + +
    Включить в результат информацию о метках.
    + +
    -tag
    + +
    Включить в результат информацию о теговых + переходах. Информация о тегах возвращается в виде + элементов tagon и + tagoff, указывающих соответственно начало + и конец каждой области тега.
    + +
    -text
    + +
    Включить в результат информацию о тексте. Значением + служит текст до следующего элемента или до конца области, + указанного параметром индекс2. Текстовый элемент + не захватывает новых строк. Часть текста, содержащая + несколько строк и не включающая меток и теговых переходов, + будет выводиться в виде набора отрезков текста, каждый из + которых кончается символом перевода строки. Эти символы + являются частью результата.
    + +
    -window
    + +
    Включить в результат информацию о вставленных + окнах. Значением является имя Tk пути вставленного окна, + за исключением случая, когда окно еще не создано. (Окно + должно содержать создающий скрипт.) В последнем случае + результатом служит пустая строка, а дополнительную + информацию об окне можно получить, задав значение его + индекса.
    +
    + +
    имяПути get индекс1 + ?индекс2?
    + +
    Возвращает последовательность символов в тексте. В + последовательность включаются все символы текста, начиная с + символа с индексом индекс1 и кончая символом, + непосредственно предшествующим символу с индексом + индекс2 (символ с индексом индекс2 в эту + последовательность не входит). Если параметр индекс2 + опущен, то команда возвращает единственный символ с индексом + индекс1. Если в указанном интервале нет символов + (например, если индекс1 указывает за конец файла или + значение индекс2 меньше, чем индекс1), то + команда возвращает пустую строку. Если в указанном интервале + есть вставленные окна, то информация о них в возвращаемую + строку не входит.
    + +
    имяПути image ?параметр? + ?арг арг ...?
    + +

    Команда предназначена для управления вставленными + изображениями. Поведение команды определяется значением + аргумента параметр. В настоящее время поддерживаются + следующие формы команды:

    + +
    +
    имяПути image cget индекс + параметр
    + +
    Возвращает значение параметра конфигурации вставленного + изображения. Аргумент индекс указывает + вставленное изображение, а параметр задает имя + требуемого параметра конфигурации; это имя должно быть + элементом списка, приведенного (см. "Вставленные + изображения").
    + +
    имяПути image configure + индекс ?параметр значение ...?
    + +
    Запрашивает значение параметров вставленного изображения + или изменяет эти значения. Если ни один аргумент параметр + не задан, то возвращает список, содержащий значения всех + наличных параметров вставленного изображения с индексом + индекс (формат списка описан в Tk_ConfigureInfo). Если + параметр задан, а его значение нет, то команда возвращает + часть списка, относящуюся к данному параметру. Если задано + несколько пар параметр-значение, то команда придает + указанным параметрам новые значения; в этом случае команда + возвращает пустую строку. Описание поддерживаемых + параметров (см. "Вставленные + изображения").
    + +
    имяПути image create + индекс ?параметр значение ...?
    + +
    Команда создает новую ссылку на изображение, которое + появляется в тексте в положении, указанном аргументом + индекс. Для установки параметров конфигурации + изображения можно указать произвольное число пар + параметр-значение. Команда возвращает уникальный + идентификатор, который можно использовать в качестве + индекса при ссылке на данное изображение. Описания + поддерживаемых параметров и возвращаемого идентификатора + (см. "Вставленные + изображения").
    + +
    имяПути image names
    + +
    Возвращает список, элементами которого служат имена всех + вхождений изображений, вставленных в данное + окно.
    +
    +
    + +
    имяПути index индекс
    + +
    Возвращает положение символа с индексом индекс; положение + выдается в виде строч.симв, где строч это номер строчки, а + симв номер символа в этой строчке. Аргумент индекс может + иметь любую из форм, описанных выше (см. "Индексы").
    + +
    имяПути insert индекс + символы ?списТегов символы + списТегов...?
    + +
    Вставляет значения всех аргументов символы непосредственно + перед символом с индексом индекс. Если + индекс ссылается на конец текста (т.е. на символ, + следующий за последним символом перевода строки), то новый + текст вставляется непосредственно перед последним символом + перевода строки. Если у команды один аргумент символы, а + аргументы списТегов отсутствуют, то ко вновь + введенному тексту будут приписаны все теги, присутствующие у + обоих символов слева и справа от нового текста; если тег + приписан лишь к одному из соседних символов, то на вновь + введенный текст он не распространяется. Аргументы + списТегов представляют собой списки имен тегов; + новым символам будут приписаны только эти теги, независимо + от состояния тегов по обе стороны от точки ввода. Если в + аргументах команды присутствует несколько пар + символы -списТегов, то результат ее выполнения + совпадает с результатом выполнения нескольких таких же + команд примитива, по одной на каждую пару. Последний + аргумент списТегов может быть опущен.
    + +
    имяПути mark параметр + ?арг арг ...?
    + +

    Эта команда предназначена для работы с + метками. Поведение команды определяется значением + аргумента параметр. В настоящее время + поддерживаются следующие формы команды:

    + +
    +
    имяПути mark gravity + имяМетки ?направление?
    + +
    Если аргумент направление не задан, то + команда возвращает значение left или + right, указывающее, притягивается ли + метка к символу слева или справа от нее. Если + направление задано, то оно должно иметь + значение left или + right, и притяжению метки с именем + имяМетки присваивается указанное значение.
    + +
    имяПути mark names
    + +
    Возвращает список, элементами которого являются имена + всех уже установленных меток.
    + +
    имяПути mark next + индекс
    + +
    Возвращает имя первой метки, идущей за символом с + индексом индекс (или притягивающейся к этому + символу). Если аргумент индекс задан в числовом + виде, то поиск метки начинается с указанного + символа. Если значением аргумента индекс + является имя метки, то поиск очередной метки начинается + непосредственно после заданной метки. При этом + возвращаемым значением может оказаться имя метки с тем + же самым положением, если в этом положении находится + несколько меток. Смысл этого действия состоит в том, + что команда mark next позволяет + последовательно перебрать все метки в текстовом + примитиве в том же порядке, в котором информация о + метках выводится командой dump. Если + метка установлена в положении, указанном специальным + индексом end, то для операции + mark next эта метка находится + после индекса end. Если после + символа с индексом индекс меток нет, то команда + возвращает пустую строку.
    + +
    имяПути mark previous + индекс
    + +
    Возвращает имя первой метки, идущей перед символом с + индексом индекс (или притягивающейся к этому + символу). Если аргумент индекс задан в числовом + виде, то поиск метки начинается с символа, + непосредственно предшествующего указанному. Если + значением аргумента индекс является имя метки, + то поиск очередной метки начинается непосредственно + перед заданной меткой. При этом возвращаемым значением + может оказаться имя метки с тем же самым положением, + если в этом положении находится несколько меток. Смысл + этого действия состоит в том, что команда mark + previous позволяет последовательно перебрать + все метки в текстовом примитиве в порядке, обратном + тому, в котором информация о метках выводится командой + dump. Если перед символом с индексом + индекс меток нет, то команда возвращает пустую + строку.
    + +
    имяПути mark set + имяМетки индекс
    + +
    Устанавливает метку с именем имяМетки + непосредственно перед символом с индексом индекс. Если + метка с именем имяМетки уже существует, то она + перемещается из своего старого положения в новое; если + такой метки нет, то создается новая метка. Команда + возвращает пустую строку.
    + +
    имяПути mark unset + имяМетки ?имяМетки имяМетки...?
    + +
    Удаляет все метки с именами имяМетки. + Удаленные метки нельзя использовать в качестве индексов; + команда "имяПути mark names" + так же не возвращает их в списке меток. Команда + возвращает пустую строку.
    +
    +
    + +
    имяПути scan параметр + арг
    + +

    Команда используется для сканирования текстов. Она + может иметь один из двух видов в зависимости от значения + параметра:

    + +
    +
    имяПути scan mark x + y
    + +
    Записывает координаты x и y и текущий вид текстового + окна для последующего использования командами + scan dragto. Обычно эта команда связана + с нажатием клавиши "Мыши" в + примитиве. Возвращает пустую строку.
    + +
    имяПути scan dragto + x y
    + +
    Команда вычисляет разность значений аргументов x и y и + значений аргументов x и y последней выполненной на + примитиве команды scan mark. Затем + команда переносит сохраненный вид окна на расстояние, в + 10 раз пресыщающее вычисленную разность. Обычно эта + команда связывается с событиями движения курсора + "Мыши" в примитиве и предназначена для + перетаскивания текста по окну с высокой + скоростью. Возвращает пустую строку.
    +
    +
    + +
    имяПути search + ?переключатели? образец индекс + индексСтоп?
    + +

    Ищет в примитиве с именем имяПути текст + подходящий под образец, начиная с символа с индексом + индекс. Если подходящая последовательность символов найдена, + то команда возвращает в качестве результата индекс первого + символа в этой последовательности; в противном случае + возвращает пустую строку. Для управления поиском можно + задать один или несколько из описываемых ниже переключателей + (или их аббревиатур):

    + +
    +
    -forwards
    + +
    Поиск осуществляется в направлении "вперед", + подходящая последовательность символов ищется в + положении, указанном аргументом индекс, и + дальше по тексту. Это значение принято по + умолчанию.
    + +
    -backwards
    + +
    Поиск осуществляется в направлении "назад", + подходящая последовательность символов ищется перед + положением, указанным аргументом индекс, и + ближе всего к нему.
    + +
    -exact
    + +
    Требует точного соответствия образцу: символы в + подходящей последовательности должны в точности + совпадать с символами образца. Это значение принято по + умолчанию.
    + +
    -regexp
    + +
    Указывает на необходимость считать образец регулярным + выражением и устанавливать соответствие согласно + правилам, принятым для регулярных выражений (подробности + см. в описании команды regexp).
    + +
    -nocase
    + +
    Игнорировать различие регистров в образце и + тексте.
    + +
    -count имяПерем
    + +
    Аргумент имяПерем представляет собой имя + переменной; если подходящая последовательность найдена, + то в эту переменную заносится число символов в ней.
    + +
    --
    + +
    Единственная задача этого переключателя завершение + списка переключателей; следующий за ним аргумент будет + интерпретирован как образец, даже если он и + начинается с "-"
    +
    + +

    Вся подходящая последовательность должна содержаться в + одной строке текста. Перед сопоставлении с регулярным + выражением из текста удаляются все символы перевода + строки. Для поиска соответствия такому символу можно + воспользоваться служебным символом .$. в регулярных + выражениях. Для точных соответствий переводы строк + сохраняются. Если задан аргумент индексСтоп, то + поиск прекращается по достижении символа с этим индексом: + для поиска вперед не будут рассматриваться соответствия, + начинающиеся на символе с этим индексом или позднее, для + поиска назад не рассматриваются соответствия, начинающиеся + раньше указанного индекса. Если аргумент + индексСтоп опущен, то поиск осуществляется по + всему тексту: по достижении одного из краев текста поиск + продолжается, начиная с другого края, до тех пор пока не + будет снова достигнуто исходное положение. Если аргумент + индексСтоп задан, то перескакивания на + противоположный край текста не происходит.

    +
    + +
    имяПути see индекс
    + +
    Сдвигает содержимое окна таким образом, чтобы символ с + индексом индекс был виден полностью. Если этот + символ расположен недалеко от видимой части текста, то сдвиг + осуществляется настолько, чтобы он был виден у края + окна. Если же указанный символ располагается далеко, то в + результате сдвига он оказывается в центре окна. +
    + +
    имяПути tag параметр + ?арг арг ...?
    + +

    Эта команда используется для работы с тегами. Ее поведение + определяется значением аргумента параметр. В + настоящее время поддерживаются следующие формы команды:

    + +
    +
    имяПути tag add имяТега + индекс1 ?индекс2 индекс1 индекс2 ...?
    + +
    Приписывает тег имяТега ко всем символам, + начиная с индекса1 и кончая непосредственно + перед символа с индексом индекс2 (к самому + этому символу данный тег не приписывается). В одной + команде может присутствовать произвольное число пар + индекс1-индекс2. Если последний аргумент + индекс2 опущен, то тег приписывается к + единственному символу с индексом индекс1. Если + в указанном промежутке нет символов (например, + индекс1 указывает за конец файла или + индекс2 оказывается не больше + индекса1), то команда не совершает никаких + действий.
    + +
    имяПути tag bind имяТега + ?послед? ?скрипт
    + +

    Эта команда приписывает скрипт к тегу с именем + имяТега. При наступлении последовательности + событий, заданной аргументом послед, на + символе, к которому приписан тег с именем + имяТега , выполняется указанный + скрипт. Эта команда примитива похожа на + команду bind; единственное ее + отличие состоит в том, что она действует на символах, + а не на всем примитиве. Полное описание синтаксиса + последовательности и подстановок, производимых в + скрипте перед его выполнением, см. в п. 1.3. Если + указаны все аргументы, то создается новая привязка, + заменяющая все предыдущие привязки данной + последовательности к тегу имяТега (если + первым символом аргумента скрипт является + "+", то скрипт присоединяется к текущей + привязке, а не замещает ее). В этом случае команда + возвращает пустую строку. Если аргумент + скрипт опущен, то команда возвращает скрипт, + привязанный к тегу имяТега (при отсутствии + такого скрипта возникает ошибка). Если опущены и + аргумент скрипт, и аргумент послед, + то команда возвращает список всех последовательностей, + привязки к которым определены для тега с именем + имяТега.

    + +

    Привязки можно определять только для событий, + связанных с "Мышью" и клавиатурой (например, + Enter, Leave, + ButtonPress, Motion + и KeyPress), или для виртуальных + событий. Привязки событий для текстового примитива + используют текущую метку (см. "Метки"). Событие + Enter наступает для тега при первом + появлении этого тега на текущем символе, а событие + Leave наступает, когда текущий символ + оказывается несвязанным с данным тегом. События + Enter и Leave могут + наступить либо в результате перемещения текущей метки, + либо как следствие изменения символа в позиции текущей + метки. Обратите внимание на то, что эти события + отличаются от событий Enter и + Leave для окон. События, связанные с + "Мышью" и клавиатурой, направлены на текущий + символ. Если в привязке используется виртуальное + событие, то оно может наступить только в случае если + для его определения был использован выход с + подчеркиванием, связанный с "Мышью" или + клавиатурой.

    + +

    К текущему символу может быть приписано много тегов, + причем каждый из этих тегов может иметь привязку для + одной и той же последовательности событий. В таком + случае исполняется по одной привязке к каждому из + тегов в порядке от наименьшего приоритета к + наибольшему. Если к одному тегу подходят несколько + образцов привязок, то выбирается самая конкретная из + них (подробности приведены в п. 1.3). Команды continue + и break в скрипте привязки обрабатываются так же, как + и в случае привязок, созданных командой bind.

    + +

    Если есть привязки и к примитиву в целом (созданные с + помощью команды bind), то они + служат дополнением привязок к тегам. Сначала + выполняются привязки к тегам, а затем привязки ко + всему примитиву.

    +
    + +
    имяПути tag cget имяТега + параметр
    + +
    Команда возвращает текущее значение параметра с именем + параметр, ассоциированного с тегом + имяТега. Параметр может иметь любое значение, + воспринимаемое командой примитива tag + configure. + +
    имяПути tag configure + имяТега ?параметр? ?значение? + ?параметр значение ...?
    + +
    Эта команда похожа на команду примитива + configure; ее отличие состоит в том, + что она модифицирует параметры, связанные с тегом + имяТега, а не со всем текстовым + примитивом. Если аргумент параметр не задан, то + команда возвращает список значений всех параметров тега + имяТега (формат списка описан в + Tk_ConfigureInfo). Если + параметр задан, а его значение нет, то + возвращается часть списка, относящаяся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то команда присваивает + указанным параметрам тега имяТега новые + значения; в этом случае она возвращает пустую + строку. Подробно параметры тегов описаны выше (см. "Теги").
    + +
    имяПути tag delete + имяТега ?имяТега ...?
    + +
    Стирает всю информацию о тегах для каждого из + аргументов имяТега. Команда снимает теги с + символов и удаляет всю остальную информацию о них + например, привязки и характеристики вывода на + экран. Возвращает пустую строку.
    + +
    имяПути tag lower + имяТегаНижеЭтого
    + +
    Изменяет приоритет тега с именем имяТега , + устанавливая его непосредственно перед тегом с именем + нижеЭтого. Если аргумент нижеЭтого + опущен, то тег имяТега получается самый нижний + приоритет среди всех тегов.
    + +
    имяПути tag names + ?индекс?
    + +
    Возвращает список имен всех тегов, активных в позиции, + указанной аргументом индекс. Если аргумент + индекс опущен, то команда возвращает список + всех существующих тегов в тексте (это все теги, + установленные командой примитива "имяПути + tag" и не удаленные командой + примитива "имяПути tag + delete", в том числе и те из них, которые + в текущий момент не относятся ни к какому + символу). Выводимый список отсортирован в порядке + приоритетов тегов (от тега с наименьшим приоритетом к + тегу с наибольшим).
    + +
    имяПути tag nextrange + имяТега индекс1 ?индекс2?
    + +
    Команда ищет последовательность символов, помеченных + тегом имяТега, первый символ которой стоит + после символа с индексом индекс1, а последний + символ предшествует символу с индексом + индекс2. В случае, если таких + последовательностей несколько, выбирается первая из + них. Команда возвращает список из двух элементов, первый + из которых индекс первого символа последовательности: а + второй индекс символа, непосредственно следующего за + последним символом последовательности. Если подходящей + последовательности нет, то команда возвращает пустую + строку. Если аргумент индекс2 не задан, то его + значением по умолчанию считается конец текста.
    + +
    имяПути tag prevrange + имяТега индекс1 ?индекс2?
    + +
    Команда ищет последовательность символов, помеченных + тегом имяТега, первый символ которой стоит + перед символом с индексом индекс1, но не + раньше, чем символ с индексом индекс2 (символ с + этим индексом допускается). В случае, если таких + последовательностей несколько, выбирается ближайшая к + символу с индексом индекс1. Команда возвращает + список из двух элементов, первый из которых индекс + первого символа последовательности: а второй индекс + символа, непосредственно следующего за последним + символом последовательности. Если подходящей + последовательности нет, то команда возвращает пустую + строку. Если аргумент индекс2 не задан, то его + значением по умолчанию считается начало текста.
    + +
    имяПути tag raise + имяТега ?ВышеЭтого?
    + +
    Изменяет приоритет тега с именем имяТега , + устанавливая его непосредственно после тега с именем + вышеЭтого. Если аргумент вышеЭтого + опущен, то тег имяТега получается самый большой + приоритет среди всех тегов.
    + +
    имяПути tag ranges + имяТега
    + +
    Возвращает список всех участков текста, помеченных + тегом с именем имяТега. Первые два элемента + списка описывают первый участок, следующие два второй и + т.д. Первый элемент каждой пары представляет собой + индекс первого символа на соответствующем участке, + второй элемент пары индекс символа, непосредственно + следующего за последним символом участка. Если тегом + имяТега не помечен ни один символ, то команда + возвращает пустую строку.
    + +
    имяПути tag remove + имяТега индекс1 ?индекс2 индекс1 индекс2 + ...?
    + +
    Снимает пометку тегом имяТега со всех + символов в промежутках, указанных индексами + индекс1 и индекс2 (на символ с + индексом индекс2 команда не действует). Если в + указанном промежутке нет символов (например, если + индекс1 указывает за конец текста или + индекс2 оказывается не меньше + индекса1), то команда не совершает никаких + действий. Возвращает пустую строку.
    +
    +
    + +
    имяПути window параметр + ?арг арг ...?
    + +

    Команда используется для работы со вставленными + окнами. Поведение команды зависит от значения аргумента + параметр. В настоящее время поддерживаются + следующие формы команды:

    + +
    +
    имяПути window cget + индекс параметр
    + +
    Возвращает значение параметра конфигурации + вставленного окна. Окно задается аргументом + индекс, а аргумент параметр указывает + имя конкретного параметра конфигурации; это имя должно + быть одним из тех, которые описаны во фрагменте "Вставленные + окна".
    + +
    имяПути window configure + индекс ?параметр значение ...?
    + +
    Запрашивает или модифицирует значения параметров + конфигурации вставленного окна. Если параметр + не указан, то возвращает список, содержащий значения + всех допустимых параметров вставленного окна (формат + списка описан в Tk_ConfigureInfo). Если + параметр задан, а его новое значение + нет, то команда возвращает часть полного списка, + относящуюся к указанному параметру. Если заданы одна или + несколько пар параметр-значение, то указанным + параметрам присваиваются новые + значения, а команда возвращает пустую + строку. Список возможных параметров приведен в фрагменте + "Вставленные + окна".
    + +
    имяПути window create + индекс ?параметр значение ...?
    + +
    Команда создает ссылку на новое окно, положение + которого в тексте определяется аргументом + индекс. Конфигурация окна задается произвольным + числом пар параметр-значение. Список возможных + параметров см. в "ВСТАВЛЕННЫЕ + ОКНА". Команда возвращает пустую строку.
    + +
    имяПути window names
    + +
    Возвращает список имен всех вставленных в настоящий + момент в окно окон.
    +
    +
    + +
    имяПути xview параметр арг
    + +

    Команда используется для запроса горизонтального положения + текста в окне примитива и изменения этого положения. Она + может принимать одну из следующих форм:

    + +
    +
    имяПути xview
    + +
    Возвращает список из двух элементов, каждый из которых + представляет собой вещественное число в промежутке между + "0" и "1". В совокупности эти два + числа описывают, какая часть документа по горизонтали + видна в окне. Если, например, значение первого числа + равно ".2", а второго ".6", то слева + от экрана не видно 20% текста, 40% видимы на экране и + еще 40% не видимы справа от экрана. Числа относятся + только к строчкам, которые действительно попадают на + экран. Если все строчки в окне короткие и полностью + умещаются на экране, то команда возвращает значения + "0" и "1", даже если в тексте + фактически присутствуют строчки, длина которых намного + превышает ширину окна. Те же самые значения передаются + полосам прокрутки через параметр + -xscrollcommand.
    + +
    имяПути xview moveto + число
    + +
    Сдвигает содержимое окна таким образом, чтобы часть + текста по горизонтали, описываемая аргументом + число, находилась слева от + экрана. Число должно быть вещественным числом в + промежутке между "0" и "1".
    + +
    имяПути xview scroll + число что
    + +
    Команда сдвигает содержимое окна влево или вправо в + соответствии со значениями аргументов число и + что. Число должно быть целым. Аргумент что + может принимать значения units и + pages, а также их аббревиатуры. Если + аргумент что имеет значение + units, то сдвиг происходит на + числосимволов средней ширины; в случае значения + pages сдвиг выполняется на + число страниц (размер страницы равен размеру + экрана). Если число отрицательно, то сдвиг + происходит вправо, в противном случае влево.
    +
    +
    + +
    имяПути yview параметр арг
    + +

    Команда используется для запроса вертикального положения + текста в окне примитива и изменения этого положения. Она + может принимать одну из следующих форм:

    + +
    +
    имяПути yview
    + +
    Возвращает список из двух элементов, каждый из которых + представляет собой вещественное число в промежутке между + "0" и "1". Первый элемент списка + указывает положение в тексте первого символа верхней + строчки на экране (например, значение "0.5" + означает, что этот символ находится в середине + текста). Второй элемент списка указывает положение + символа, следующего непосредственно за последним + символом нижней строчки экрана. Те же самые значения + передаются полосам прокрутки через параметр + -yscrollcommand.
    + +
    имяПути yview moveto + число
    + +
    Сдвигает содержимое окна таким образом, чтобы символ, + положение которого задано аргументом число, + оказался в верхней строчке экрана. Число должно + быть вещественным числом в промежутке между + "0" и "1"; значение "0" + указывает на первый символ в тексте, значение + "0.33" на символ, отстоящий от начала текста + на "1/3" и т.д.
    + +
    имяПути yview scroll + число что
    + +
    Команда сдвигает содержимое окна вверх или вниз в + соответствии со значениями аргументов число и + что. Число должно быть целым. Аргумент что + может принимать значения units и + pages, а также их аббревиатуры. Если + аргумент что имеет значение + units, то сдвиг происходит на + число строчек; в случае значения + pages сдвиг выполняется на + число страниц (размер страницы равен размеру + экрана). Если число отрицательно, то сдвиг + происходит вверх, в противном случае вниз.
    + +
    имяПути yview ?-pickplace? + индекс
    + +

    Сдвигает содержимое окна примитива таким образом, + чтобы сделать видимым символ с индексом + индекс. Если аргумент + -pickplace не задан, то символ с + указанным индексом появляется в верхней строчке + экрана. Если же этот аргумент задан, то примитив + определяет место появления символа на экране по + следующему правилу:

    + +
      +
    1. Если символ с индексом индекс + уже виден на экране, то ничего не изменяется.
    2. + +
    3. Если этот символ находится лишь незначительно выше + экрана, то он оказывается в верхней строчке + экрана.
    4. + +
    5. Если этот символ находится лишь незначительно ниже + экрана, то он оказывается в нижней строчке + экрана.
    6. + +
    7. В остальных случаях указанный символ оказывается в + центре экрана.
    8. +
    + +

    Параметр -pickplace устарел после + введения команды примитива see, + которая управляет движениями как в горизонтальном, так + и в вертикальном направлении, в то время, как + -pickplace влияет только на движение + по вертикали.

    +
    + +
    имяПути yview число
    + +
    Команда сдвигает содержимое в окне таким образом, + чтобы первый символ строки с номером, следующим за + номером число, оказался в верхней строчке + экрана. Аргумент число должен быть + целым. Команда использовалась для прокрутки, но теперь + она устарела. +
    +
    +
    +
    + +

    ПРИВЯЗКИ

    + +

    Tk автоматически создает привязки класса, которые определяют + следующее поведение текстовых примитивов по умолчанию. В + приводимом ниже описании "слово" это непрерывная + последовательность символов, состоящая из букв, цифр и символов + подчеркивания "_", либо из любого другого одиночного + символа.

    + +
      + +
    1. Щелчок клавишей 1 "Мыши" устанавливает курсор + ввода непосредственно перед символом, на котором расположен + курсор "Мыши".
    2. + +
    3. Движение "Мыши" с нажатой клавишей 1 растягивает + выделение от курсора ввода то символа под курсором + "Мыши".
    4. + +
    5. Двойной щелчок по клавише 1 "Мыши" выделяет слово, + на котором находится курсор "Мыши", и устанавливает + курсор ввода на начало этого слова. Если тащить + "Мышь" после двойного щелчка, то выделение + растягивается на полные слова.
    6. + +
    7. Тройной щелчок по клавише 1 "Мыши" выделяет + строку, на которой находится курсор "Мыши", и + устанавливает курсор ввода на начало этой строки. Если тащить + "Мышь" после тройного щелчка, то выделение + растягивается на полные строки.
    8. + +
    9. Край выделения можно переместить, таща "Мышь" с + нажатой клавишей 1 при нажатой клавише Shift: + при этом движется край выделения, ближайший к курсору + "Мыши" в момент нажатия клавиши 1. Если перед + началом движения по клавише "Мыши" был сделан + двойной щелчок, то выделение будет растягиваться на полные + слова; если тройной щелчок то на полные строки.
    10. + +
    11. Щелчок по клавише 1 "Мыши" при нажатой клавише + Control перемещает курсор ввода, не изменяя выделения.
    12. + +
    13. При нажатии на клавиши обычных символов эти символы вводятся + на месте курсора ввода.
    14. + +
    15. Содержимое окна примитива можно сдвинуть с помощью движения + "Мыши" при нажатой клавише 2. Если щелкнуть по + клавише 2 "Мыши", не перемещая "Мышь", то + выделение в тексте копируется в место курсора + "Мыши". Нажатие на клавишу Insert также приводит к + копированию выделения, но в место курсора ввода, а не курсора + "Мыши".
    16. + +
    17. При движении "Мыши" вне экрана с нажатой клавишей + 1 содержимое примитива автоматически прокручивается и на + экране появляется дополнительная порция текста (если вне + экрана в направлении движения "Мыши" есть еще + текст).
    18. + +
    19. Нажатие на клавиши Left или + Right приводит к сдвигу курсора ввода на один + символ влево или вправо соответственно; при этом всякое + выделение в тексте отменяется. Нажатие на клавиши + Left или Right при нажатой + клавише Shift приводит к сдвигу курсора ввода + и расширению выделения на один символ.
    20. + +
    21. Нажатие на клавиши Control-Left или + Control-Right сдвигает курсор ввода на целое + слово, а нажатие на клавиши + Control-Shift-Left и + Control-Shift-Right приводит к сдвигу курсора + ввода и расширению выделения на одно слово.
    22. + +
    23. Нажатие на клавиши Control-b и + Control-f приводит к такому же результату, + что и нажатие на Left и + Right соответственно. Комбинации клавиш + Meta-b и Meta-f дают тот же + эффект, что и Control-Left и + Control-Right соответственно.
    24. + +
    25. Нажатие на клавиши Up и + Down переводит курсор ввода на одну строчку + вверх или вниз, отменяя при этом любое выделение в + тексте. Нажатие на клавиши Up и + Down при нажатой клавише + Shift приводит к сдвигу курсора ввода и + растягиванию выделения до нового положения курсора. Комбинации + Control-Up и Control-Down + сдвигают курсор ввода на один абзац (группу строчек, + отделенную от соседней группы пустой строчкой), а комбинации + Control-Shift-Up и + Control-Shift-Down приводят к тому же к + растягиванию выделения до нового положения курсора + ввода. Комбинации Control-p и + Control-n дают тот же результат, что и + Up и Down + соответственно.
    26. + +
    27. Клавиши Next и Prior + сдвигают курсор ввода вперед или назад на одну страницу; при + этом выделения в тексте отменяются. Нажатие на клавиши + Next и Prior при нажатой + клавише Shift приводит к сдвигу курсора ввода + и растягиванию выделения до нового положения + курсора. Control-v сдвигает видимую часть + текста на одну страницу вперед, причем курсор ввода не меняет + своего положения и выделение также остается неизменным.
    28. + +
    29. Комбинации Control-Next и + Control-Prior сдвигают видимую часть текста + на одну страницу вправо или влево, причем курсор ввода не + меняет своего положения, и выделение также остается + неизменным.
    30. + +
    31. Нажатие на клавиши Home и + Control-a помещает курсор ввода в начало + текущей строчки, причем все выделения в примитиве + отменяются. Shift-Home помещает курсор ввода + в начало текущей строчки и растягивает выделение до нового + положения курсора. Нажатие на клавиши End и + Control-e помещает курсор ввода в конец + текущей строчки, причем все выделения в примитиве + отменяются. Shift-End помещает курсор ввода в + конец текущей строчки и растягивает выделение до нового + положения курсора.
    32. + +
    33. Комбинации Control-Home и + Meta-< устанавливают курсор ввода в начало + текста, причем все выделения в примитиве + отменяются. Control-Shift-Home устанавливает + курсор ввода в начало текста и растягивает выделение до нового + положения курсора.
    34. + +
    35. Комбинации Control-End и + Meta-> устанавливают курсор ввода в конец + текста, причем все выделения в примитиве + отменяются. Control-Shift-End устанавливает + курсор ввода в конец текста и растягивает выделение до нового + положения курсора.
    36. + +
    37. Клавиша Select и комбинация + Control-Space устанавливают опорную точку + выделения в текущее положение курсора ввода. Текущее выделение + при этом не изменяется. Комбинации + Shift-Select и + Control-Shift-Space растягивают выделение до + текущего положения курсора ввода; если в тексте не было + выделения, то выделяются символы между опорной точкой + выделения и курсором ввода.
    38. + +
    39. Нажатие на клавиши Control-/ приводит к + выделению всего содержимого примитива.
    40. + +
    41. Control-\\ отменяет выделение в примитиве.
    42. + +
    43. Клавиша F16 (на многих станциях Sun + обозначенная Copy) или + Meta-w копируют выделение в примитиве (если + оно есть) в буфер обмена.
    44. + +
    45. Клавиша F20 (на многих станциях Sun + обозначенная Cut) или + Control-w копируют выделение в примитиве в + буфер обмена и удаляют выделение. Если выделения нет, то + нажатие на эти клавиши не приводит ни к каким действиям.
    46. + +
    47. Клавиша F18 (на многих станциях Sun + обозначенная Paste) или + Control-y вставляет содержимое буфера обмена + в положении курсора ввода.
    48. + +
    49. Нажатие на клавишу Delete приводит к + удалению выделения (если оно есть в примитиве). Если выделения + нет, то нажатие на эту клавишу приводит к удалению символа + справа от курсора ввода.
    50. + +
    51. Backspace и Control-h + удаляют выделение (если оно есть в примитиве). Если выделения + нет, то нажатие на эти клавиши приводит к удалению символа + слева от курсора ввода.
    52. + +
    53. Control-d удаляет символ справа от курсора + ввода.
    54. + +
    55. Meta-d удаляет слово справа от курсора ввода.
    56. + +
    57. Нажатие на клавиши Control-k приводит к + удалению символов справа от курсора ввода до конца + строки. Если курсор ввода находится в конце строки, то + удаляется символ перевода строки.
    58. + +
    59. Control-o открывает новую строку, вставляя + символ перевода строки перед курсором ввода; положение курсора + ввода при этом не изменяется.
    60. + +
    61. Meta-backspace и + Meta-Delete удаляют слово слева от курсора + ввода.
    62. + +
    63. Control-x удаляет выделение в текстовом + примитиве.
    64. + +
    65. Control-t меняет местами два символа справа + от курсора ввода.
    66. + +
    67. Если примитив сделан недоступным с помощью параметра + -state, то текст можно двигать по экрану и + выделять, однако курсор ввода не будет отображаться в + примитиве и никакие модификации текста невозможны.
    68. + +
    69. Определяя новые привязки к отдельным примитивам или + переопределяя привязки класса, поведение текстовых примитивов + можно изменить.
    70. +
    + +

    ВОПРОСЫ ПРОИЗВОДИТЕЛЬНОСТИ

    + +

    Текстовые примитивы должны обрабатываться эффективно при самых + разнообразных условиях. В них используется 2-3 байта основной + памяти на каждый символ текста, поэтому текст длиной 1 Мегабайт + и более вполне может эффективно обрабатываться на большинстве + рабочих станций. Внутреннее представление текста имеет вид + модифицированного B-дерева, поэтому обработка даже длинных + текстов довольно эффективна. Реализация меток также позволяет + использовать много меток. В большинстве случаев удобно + пользоваться большим числом уникальных тегов или тегом, + приписанным к большому числу различных частей текста.

    + +

    Проблема эффективности может возникнуть при использовании + сотен или тысяч различных тегов со следующими характеристиками: + первая часть текста, приписанная к каждому тегу, начинается + вблизи начала текста, а последняя кончается вблизи его конца или + имеется единственная такая часть, включающая в себя почти весь + текст. Цена добавления или удаления таких тегов пропорциональна + числу тегов с такими свойствами. Напротив, тысячи различных + тегов обрабатываются эффективно, если области их действия + невелики и равномерно распределены по всему тексту.

    + +

    Эффективность может понижаться при наличии очень длинных + строк текста, содержащих большое число меток и тегов.

    + +

    При каждом мигании курсора ввода строчка экрана, на которой он + находится, перерисовывается целиком, что приводит к постоянному + потоку графической информации. Для устранения этого эффекта + установите атрибут insertOffTime в + "0".

    + + + + + + + + diff --git a/hlp/ru/tk/tk.html b/hlp/ru/tk/tk.html new file mode 100644 index 0000000..878f2c2 --- /dev/null +++ b/hlp/ru/tk/tk.html @@ -0,0 +1,84 @@ + + + + tk + + + +

    tk

    + +

    Управляет внутренним состоянием Tk.

    + + +

    СИНТАКСИС

    + +
    +      tk параметр ?арг арг ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда tk обеспечивает доступ к различным + элементам внутреннего состояния Tk. Большая часть информации, с + которой работает команда, относится к приложению в целом или к + экрану или дисплею, а не к конкретному окну. Команда может + принимать одну из нескольких форм в зависимости от значения + аргумента параметр. Допустимы следующие формы:

    + +
    +
    tk appname ?новИмя
    + +
    Если аргумент новИмя не задан, то команда + возвращает имя приложения (которое можно использовать в + команде send для + взаимодействия с приложениями). Если аргумент новИмя + задан, то имя приложения заменяется на новИмя. Если + приложение с заданным именем уже существует, то для того, + чтобы имя было уникальным, к нему добавляется суффикс вида + "#2" или + "#3". Результатом выполнения + команды является фактически присвоенное имя; новИмя + не должно начинаться с прописной буквы. В противном случае + может возникнуть коллизия с обработкой параметров, так как + имена, начинающиеся с прописной буквы, интерпретируются как + имена классов; в результате может случиться так, что Tk не + найдет некоторые параметры приложения. Если блокировать + пересылку путем удаления команды send, то эта команда + отменит блокировку и воссоздаст команду send.
    + +
    tk scaling -displayof окно число
    + +

    Устанавливает коэффициент масштабирования, используемый + Tk, при переводе физических единиц (например, точки, дюймы + или миллиметры) в пиксели, и запрашивает текущее значение + коэффициента. Аргумент число представляет собой + число с плавающей точкой, которое задает число пикселей в + точке на экране. Если аргумент окно опущен, то его + значением по умолчанию является главное окно. Если опущен + аргумент число, то команда возвращает текущее + значение коэффициента масштабирования.

    + +

    "Точка" это единица измерения, равная 1/72 + дюйма. Коэффициент масштабирования 1.0 соответствует одному + пикселу на точку стандартному 72 dpi (точек на дюйм) + монитору. Коэффициент масштабирования 1.25 соответствует + 1.25 пикселю на точку, т.е. стандартному значению для + монитора 90 dpi; установка коэффициента 1.25 для 72 dpi + монитора увеличивает изображение всех элементов приложения в + 1.25 раз по сравнению с нормальным. Исходное значение + коэффициента устанавливается при запуске приложения на + основании характеристик монитора, однако его можно изменить + в любой момент. Все измерения, выполняемые после установки + коэффициента, будут использовать его новое значение, однако + будут ли существующие примитивы динамически меняться, + подстраиваясь под новое значение коэффициента, предсказать + нельзя.

    +
    +
    + + + + + diff --git a/hlp/ru/tk/tk.toc.html b/hlp/ru/tk/tk.toc.html new file mode 100644 index 0000000..fd9de52 --- /dev/null +++ b/hlp/ru/tk/tk.toc.html @@ -0,0 +1,64 @@ +Команды Tk +SafeTk
    +bell
    +bind
    +bindtags
    +bitmap
    +button
    +canvas
    +checkbutton
    +clipboard
    +destroy
    +entry
    +event
    +focus
    +font
    +frame
    +grab
    +grid
    +image
    +label
    +listbox
    +lower
    +menu
    +menubutton
    +message
    +option
    +options
    +pack
    +pack-old
    +photo
    +place
    +radiobutton
    +raise
    +scale
    +scrollbar
    +selection
    +send
    +table
    +text
    +tk
    +tk_bindForTraversal
    +tk_bisque
    +tk_menuBar
    +tk_chooseColor
    +tk_dialog
    +tk_focusFollowsMouse
    +tk_focusNext
    +tk_focusPrev
    +tk_getOpenFile
    +tk_getSaveFile
    +tk_chooseDirectory
    +tk_messageBox
    +tk_optionMenu
    +tk_popup
    +tkerror
    +tkvars
    +tkwait
    +toplevel
    +winfo
    +Wm
    + + + + diff --git a/hlp/ru/tk/tk_bisque.html b/hlp/ru/tk/tk_bisque.html new file mode 100644 index 0000000..33de31d --- /dev/null +++ b/hlp/ru/tk/tk_bisque.html @@ -0,0 +1,90 @@ + + + + tk_bisque, tk_setPalette + + +

    tk_bisque, tk_setPalette

    + +

    Модифицирует цветовую палитру Tk.

    + +

    СИНТАКСИС

    + +
    +      tk_setPalette фон
    +      tk_setPalette имя значение ?имя значение ...
    +      tk_bisque
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_setPalette изменяет цветовую + схему Tk. Это происходит за счет изменения цветов в существующих + примитивах и внесения изменений в базу данных параметров, в + результате чего будущие примитивы будут пользоваться новой + цветовой схемой. При выполнении команды + tk_setPalette с единственным аргументом, этим + аргументом является имя цвета, который становится нормальным + цветом фона; процедура tk_setPalette вычисляет + всю палитру цветов на основе этого цвета фона. Если же аргументы + команды tk_setPalette включают несколько пар + имя-значение, то имя это имя параметра, а второй + элемент пары представляет собой новое значение параметра. В + настоящее время поддерживаются следующие имена параметров в базе + данных:

    + +
      +
    • activeBackground
    • +
    • activeForeground
    • +
    • background
    • +
    • disabledForeground
    • +
    • foreground
    • +
    • highlightBackground
    • +
    • highlightColor
    • +
    • insertBackground
    • +
    • selectBackground
    • +
    • selectColor
    • +
    • selectForeground
    • +
    • troughColor
    • +
    + +

    Процедура tk_setPalette пытается вычислить + разумные значения по умолчанию для любого незаданного + параметра. Можно указать и параметры, отличные от приведенных + выше, и Tk изменит значения и этих параметров. Такая возможность + полезна при использовании специальных примитивов с + дополнительными цветовыми параметрами.

    + +

    После того, как новое значение каждого из цветовых параметров + вычислено, tk_setPalette просматривает иерархию + примитивов, чтобы изменить значения параметров всех существующих + примитивов. Для каждого примитива она проверяет, определен ли + для него какой-либо из заданных параметров. Если это так и если + текущее значение параметра совпадает со значением по умолчанию, + то это значение заменяется новым; если же текущее значение + отлично от значения по умолчанию, то + tk_setPalette не изменяет его. Значением + параметра по умолчанию является то, которое порождено примитивом + ([lindex [$w configure $option] 3]) или, если + процедура tk_setPalette выполнялась и раньше, + то значение, установленное ее предыдущим выполнением.

    + +

    После модификации всех примитивов в приложении + tk_setPalette добавляет параметры в базу данных + параметров, изменяя значения по умолчанию для будущих + примитивов. Новые параметры добавляются с приоритетом + widgetDefault, поэтому они будут подавлены параметрами из файла + .Xdefaults или параметрами, заданными в + командной строке, создающей примитив.

    + +

    Процедура tk_bisque обеспечивает совместимость + с предыдущими версиями: она задает схему "bisque" на + основе светло-коричневого (бисквитного) цвета, которая + использовалась в Tk 3.6 и более ранних версиях.

    + + + + + + + diff --git a/hlp/ru/tk/tk_chooseColor.html b/hlp/ru/tk/tk_chooseColor.html new file mode 100644 index 0000000..8f258ce --- /dev/null +++ b/hlp/ru/tk/tk_chooseColor.html @@ -0,0 +1,53 @@ + + + + tk_ChooseColor + + +

    tk_chooseColor

    + +

    Открывает диалоговое окно для выбора цвета пользователем.

    + +

    СИНТАКСИС

    + +
    +      tk_chooseColor ?параметр значение...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_chooseColor открывает диалоговое + окно для выбора цвета пользователем. В строке аргументов + допустимы следующие пары параметр-значение:

    + +
    +
    -initialcolor цвет
    + +
    Задает начальный цвет, выводимый в окне диалога при его + открытии. Параметр цвет может иметь любое значение, + приемлемое для функции Tk_GetColor.
    + +
    -parent окно
    + +
    Делает окно логическим родителем окна диалога. Окно + диалога выводится поверх своего родительского окна.
    + +
    -title строкаЗаголовка
    + +
    Задает строку, которую нужно вывести в качестве заголовка + окна диалога. Если этот параметр не задан, то будет выведен + заголовок по умолчанию.
    +
    + + +

    При выборе пользователем цвета tk_chooseColor + возвращает имя цвета в виде, приемлемом для + Tk_GetColor. Если пользователь прерывает + операцию, то обе команды возвращают пустую строку.

    + + + + + + + diff --git a/hlp/ru/tk/tk_chooseDirectory.html b/hlp/ru/tk/tk_chooseDirectory.html new file mode 100644 index 0000000..a2f134a --- /dev/null +++ b/hlp/ru/tk/tk_chooseDirectory.html @@ -0,0 +1,69 @@ + + + + tk_chooseDirectory + + + +

    tk_chooseDirectory

    + +

    tk_chooseDirectory - команда выводит + стандартный диалог выбора директории.

    + +

    СИНТАКСИС

    + + +
    +      tk_chooseDirectory ?параметр значение ...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_chooseDirectory открывает + диалоговое окно для выбора пользователем директории.

    + +

    В качестве аргументов допустимы следующие значения:

    + +
    +
    -initialdir имя_директории
    + +
    Этот параметр устанавливает текущую директорию + имя_директории и в окне диалога выводиться содержимое + этой директории. Если этот параметр не указан то процедура + выведет на экран диалог с рабочей директорией. Данная опция + может не работать на Macintosh. Но это не является + ошибкой. Предпочтительнее использовать General + controls панель управления чтобы установить + директорию по умолчанию для приложения.
    + +
    -parent окно
    + +
    Устанавливает окно в качестве родительского для + диалога. Диалог будет введен поверх родительского окна.
    + +
    -title строка
    + +
    Устанавливает заголовок окна диалога. Если данная опция не + установлена то будет выведен заголовок по умолчанию.
    + +
    -mustexist параметр
    + +
    Устанавливается в том случае если пользователь выбрал + несуществующую директорию. Если параметр установлен в + true то пользователь может выбрать директорию только + в том случае если она существует. По умолчанию + параметр установлен в false.
    +
    + +

    СМ. ТАКЖЕ

    + +

    tk_getOpenFile, + tk_getSaveFile +

    + + + + + diff --git a/hlp/ru/tk/tk_dialog.html b/hlp/ru/tk/tk_dialog.html new file mode 100644 index 0000000..c1a11ed --- /dev/null +++ b/hlp/ru/tk/tk_dialog.html @@ -0,0 +1,78 @@ + + + + tk_dialog + + + +

    tk_dialog

    + +

    Создает окно модального диалога и ожидает ответа.

    + +

    СИНТАКСИС

    + +
    +      tk_dialog окно заголовок текст двуцвет умолч строка строка ...
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта процедура является частью библиотеки скриптов Tk. Ее + аргументы описывают диалоговое окно:

    + +
    +
    окно
    + +
    Имя окна верхнего уровня, которое следует использовать для + диалога. Любое существующее под этим именем окно + уничтожается.
    + +
    заголовок
    + +
    Текст, предназначенный для вывода в строке заголовка + менеджера окон.
    + +
    текст
    + +
    Сообщение, которое должно появиться в верхней + части диалогового окна.
    + +
    двуцвет
    + +
    Если значение этого параметра непусто, то оно задает + двуцветное изображение для вывода в верхней части диалогового + окна слева от текста. Если значением является пустая строка, + то никакого двуцветного изображения не выводится.
    + +
    умолч
    + +
    Если значение этого параметра является неотрицательным целым + числом, то оно представляет собой номер кнопки, которая должна + быть кнопкой по умолчанию (0 для самой левой кнопки и т.д.) + Если значение параметра отрицательно или представляет собой + пустую строку, то кнопки по умолчанию не будет.
    + +
    строка
    + +
    Каждому из аргументов строка ставится в + соответствие одна кнопка. Каждая строка задает текст, который + должен быть выведен в соответствующей кнопке слева + направо.
    +
    + +

    После создания диалогового окна процедура + tk_dialog ожидает, пока пользователь выберет + одну из кнопок либо щелкнув по ней .Мышью., либо нажав на + клавишу Return, чтобы выбрать значение по + умолчанию (если такое есть). Затем процедура возвращает номер + выбранной кнопки: 0 для самой левой кнопки, 1 для соседней с + ней и т.д. Если окно диалога уничтожено до того, как + пользователь выбрал одну из кнопок, то процедура возвращает + -1.

    + +

    В ожидании ответа пользователя tk_dialog + производит локальный захват. В результате пользователь может + взаимодействовать только с окном диалога.

    + + + diff --git a/hlp/ru/tk/tk_focus.html b/hlp/ru/tk/tk_focus.html new file mode 100644 index 0000000..0164742 --- /dev/null +++ b/hlp/ru/tk/tk_focus.html @@ -0,0 +1,36 @@ + + + + tk_focusFollowsMouse, tk_focusNext, tk_focusPrev + + + +

    tk_focusFollowsMouse, tk_focusNext, tk_focusPrev

    + +

    Утилиты служат для управления фокусом ввода.

    + +

    СИНТАКСИС

    + +
    +      tk_focusNext window
    +      tk_focusPrev window
    +      tk_focusFollowsMouse
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_focusNext возвращает имя + следующего после window окна в очередности фокусов, + который определяется очередью стека окон и структурой иерархии + окон.

    + +

    Процедура tk_focusPrev противоположна по + действию процедуре tk_focusNext: она возвращает + имя предыдущего окна.

    + +

    Утилита tk_focusFollowsMouse переводит фокус в + то окно, над которым в данный момент находится курсор + "Мыши".

    + + + diff --git a/hlp/ru/tk/tk_getOpenFile.html b/hlp/ru/tk/tk_getOpenFile.html new file mode 100644 index 0000000..acb7811 --- /dev/null +++ b/hlp/ru/tk/tk_getOpenFile.html @@ -0,0 +1,178 @@ + + + + tk_getOpenFile + + +

    tk_getOpenFile

    + +

    Открывает окно диалога, в котором пользователь должен выбрать + файл для того, чтобы открыть его.

    + +

    СИНТАКСИС

    + +
    +      tk_getOpenFile ?параметр значение...? 
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_getOpenFile открывает окно + диалога, в котором пользователь должен выбрать файл для того, + чтобы открыть его.

    + +

    Команда tk_getOpenFile обычно выполняется при + вызове команды Open из меню + File. Она позволяет лишь выбрать один из + существующих файлов. Если пользователь вводит имя + несуществующего файла, то окно диалога информирует его об ошибке + и предлагает сделать другой выбор. Если приложение позволяет + пользователю создавать файлы, то для этой цели должна быть + предназначена специальная команда меню New.

    + +

    В качестве пар аргумент-значение в командной строке + этих двух команд допускаются следующие варианты:

    + +
    +
    -defaultextension расширение
    + +
    Задает строку, которая автоматически приписывается к имени + файла в случае, если имя, введенное пользователем, не имеет + расширения. По умолчанию значение этого параметра пустая + строка, т.е. имя файла не будет получать расширения ни в каком + случае. На платформе Макинтош, где имена файлов не требуют + расширения, этот параметр игнорируется.
    + +
    -filetypes списокТиповФайлов
    + +
    Если в файловом диалоге на конкретной платформе имеется окно + списка типов файлов, то этот параметр задает содержимое + списка. При выборе типа файла в списке выводятся только файлы + этого типа. Если параметр не задан или его значение пустая + строка, а также если на данной платформе не поддерживается + окно списка типов файлов, то выводятся имена всех файлов, + несмотря на их типы. Содержимое списка обсуждается ниже + (см. "ОПИСАНИЕ + ОБРАЗЦОВ ТИПОВ ФАЙЛОВ").
    + +
    -initialdir каталог
    + +
    Указывает, файлы какого каталога должны выводиться при + появлении окна диалога. Если этот параметр не задан, то + выводится список имен файлов в текущем каталоге процесса. На + платформе Макинтош параметр каталог срабатывает не + всегда. Это не результат ошибки. Этот эффект является + следствием того, что панель управления General Controls на + Макинтоше позволяет конечному пользователю подавить значение + каталога приложения по умолчанию.
    + +
    -initialfile имяфайла
    + +
    Задает имя файла, которое должно выводиться в окне диалога + при его появлении.
    + +
    -parent окно
    + +
    Делает окно логическим родителем файлового + диалога. Окно файлового диалога выводится поверх родительского + окна.
    + +
    -title строкаЗаголовка
    + +
    Задает строку, которая выводится в качестве заголовка в окне + диалога. Если параметр не задан, то в окне выводится заголовок + по умолчанию. На платформе Макинтош параметр игнорируется.
    +
    + +

    После того, как пользователь выбрал файл, команда + tk_getSaveFile возвращают полное имя пути к этому + файлу. Если пользователь прерывает выполнение операции, то обе + команды возвращают пустую строку.

    + +

    ОПИСАНИЕ ОБРАЗЦОВ + ТИПОВ ФАЙЛОВ

    + +

    Значение списокТиповФайлов параметра + -filetypes представляет собой список образцов + типов файлов. Каждый из образцов это список вида + +

    +      имяТипа {расширение расширение...} {макТип макТип...}
    +    
    + +

    имяТипа это имя типа файлов; его значение это + текстовая строка, которая попадает в список типов + файлов. расширение это одно из расширений для файлов данного + типа. макТип это четырехсимвольный тип файлов на + платформе Макинтош. Список макТипов необязателен, и для + приложений, которые не планируется использовать на платформе + Макинтош, его можно опустить.

    + +

    Одно и то же имяТипа может встречаться в нескольких + образцах; в этом случае все они описывают файлы одного типа и им + соответствует одна строка в списке типов. При выборе такой + строки в списке выводится список всех файлов, имена которых + подходят хотя бы под один образец. Обычно каждому типу файлов + соответствует в точности один образец. Использование нескольких + образцов необходимо лишь для платформы Макинтош.

    + +

    На платформе Макинтош файл подходит под образец, если + расширение его имени совпадает по крайней мере с одним из + расширений И оно имеется по крайней мере в одном из значений + параметра макТип в образце. Например, под образец + исходных файлов на языке C подходят файлы с расширением + .c И с макТипом TEXT. Для того, чтобы заменить + конъюнкцию И дизъюнкцией ИЛИ, нужно вместо одной строки + образца завести две строки, в одной из которых есть только + расширения, а в другой только макТипы. Под образец + файлового типа GIF подходят файлы с расширением + .gif ИЛИ имеющие макТип GIFF.

    + +

    На платформах Unix и Windows файл подходит под образец + файлового типа, если расширение его имени соответствует одному + из расширений в образце. макТипы игнорируются.

    + +

    ЗАДАНИЕ РАСШИРЕНИЙ

    + +

    На платформах Unix и Macintosh соответствие образцам + устанавливается обычным образом. На платформах Windows + соответствие образцам устанавливается операционной + системой. Возможными расширениями могут быть:

    + +
      +
    1. специальное расширение *, под которое подходит любой файл;
    2. + +
    3. специальное расширение "", под которое подходит + любой файл без расширения (т.е. файл, имя которого не содержит + точки);
    4. + +
    5. произвольная строка символов, среди которых нет символов + маски (* и ?).
    6. +
    + +

    Ввиду того, что на различных платформах используются различные + правила соответствия, появление символов маски в расширениях не + допускается, за исключением специального расширения + "*". Расширения, в которых нет точки (например, + "~"), допустимы, но они могут работать не на всех + платформах.

    + +

    ПРИМЕР

    + +
    +      set types {
    +        {{Text Files}     {.txt}     }
    +        {{TCL Scripts}    {.tcl}     }
    +        {{C Source Files} {.c}   TEXT}
    +        {{GIF Files}      {.gif}     }
    +        {{GIF Files}      {}     GIFF}
    +        {{All Files}      *          }
    +      }
    +
    +      set filename [tk_getOpenFile -filetypes $types]
    +      if {$filename != ""} {
    +        # Открыть файл ...
    +      }
    +    
    + + diff --git a/hlp/ru/tk/tk_getSaveFile.html b/hlp/ru/tk/tk_getSaveFile.html new file mode 100644 index 0000000..fb43520 --- /dev/null +++ b/hlp/ru/tk/tk_getSaveFile.html @@ -0,0 +1,176 @@ + + + + tk_getSaveFile + + +

    tk_getSaveFile

    + +

    Открывает окно диалога, в котором пользователь должен выбрать + файл для того, чтобы открыть или сохранить его.

    + + +

    СИНТАКСИС

    + +
    +      tk_getSaveFile параметр значение...
    +    
    + +

    ОПИСАНИЕ

    + +

    Процедура tk_getSaveFile открывает окно + диалога, в котором пользователь должен выбрать файл для того, + чтобы сохранить его.

    + +

    Команда tk_getSaveFile обычно связана с + командой SaveAs меню File. При + входе пользователя в уже существующий файл окно диалога + предлагает пользователю подтвердить, что старый файл следует + затереть.

    + +

    В качестве пар аргумент-значение в командной строке + этих двух команд допускаются следующие варианты:

    + +
    +
    -defaultextension расширение
    + +
    Задает строку, которая автоматически приписывается к имени + файла в случае, если имя, введенное пользователем, не имеет + расширения. По умолчанию значение этого параметра пустая + строка, т.е. имя файла не будет получать расширения ни в каком + случае. На платформе Макинтош, где имена файлов не требуют + расширения, этот параметр игнорируется.
    + +
    -filetypes списокТиповФайлов
    + +
    Если в файловом диалоге на конкретной платформе имеется окно + списка типов файлов, то этот параметр задает содержимое + списка. При выборе типа файла в списке выводятся только файлы + этого типа. Если параметр не задан или его значение пустая + строка, а также если на данной платформе не поддерживается + окно списка типов файлов, то выводятся имена всех файлов, + несмотря на их типы. Содержимое списка обсуждается ниже + (см. "ОПИСАНИЕ + ОБРАЗЦОВ ТИПОВ ФАЙЛОВ").
    + +
    -initialdir каталог
    + +
    Указывает, файлы какого каталога должны выводиться при + появлении окна диалога. Если этот параметр не задан, то + выводится список имен файлов в текущем каталоге процесса. На + платформе Макинтош параметр каталог срабатывает не + всегда. Это не результат ошибки. Этот эффект является + следствием того, что панель управления General Controls на + Макинтоше позволяет конечному пользователю подавить значение + каталога приложения по умолчанию.
    + +
    -initialfile имяфайла
    + +
    Задает имя файла, которое должно выводиться в окне диалога + при его появлении.
    + +
    -parent окно
    + +
    Делает окно логическим родителем файлового + диалога. Окно файлового диалога выводится поверх родительского + окна.
    + +
    -title строкаЗаголовка
    + +
    Задает строку, которая выводится в качестве заголовка в окне + диалога. Если параметр не задан, то в окне выводится заголовок + по умолчанию. На платформе Макинтош параметр + игнорируется.
    +
    + +

    После того, как пользователь выбрал файл, команда + tk_getSaveFile возвращают полное имя пути к + этому файлу. Если пользователь прерывает выполнение операции, то + обе команды возвращают пустую строку.

    + +

    ОПИСАНИЕ + ОБРАЗЦОВ ТИПОВ ФАЙЛОВ

    + +

    Значение списокТиповФайлов параметра + -filetypes представляет собой список образцов + типов файлов. Каждый из образцов это список вида

    + +
    +      имяТипа {расширение расширение...} {макТип макТип...}
    +    
    + +

    имяТипа это имя типа файлов; его значение это + текстовая строка, которая попадает в список типов + файлов. расширение это одно из расширений для файлов данного + типа. макТип это четырехсимвольный тип файлов на + платформе Макинтош. Список макТипов необязателен, и для + приложений, которые не планируется использовать на платформе + Макинтош, его можно опустить.

    + +

    Одно и то же имяТипа может встречаться в нескольких + образцах; в этом случае все они описывают файлы одного типа и им + соответствует одна строка в списке типов. При выборе такой + строки в списке выводится список всех файлов, имена которых + подходят хотя бы под один образец. Обычно каждому типу файлов + соответствует в точности один образец. Использование нескольких + образцов необходимо лишь для платформы Макинтош.

    + +

    На платформе Макинтош файл подходит под образец, если + расширение его имени совпадает по крайней мере с одним из + расширений И оно имеется по крайней мере в одном из значений + параметра макТип в образце. Например, под образец + исходных файлов на языке C подходят файлы с расширением + .c И с макТипом TEXT. Для того, чтобы заменить + конъюнкцию И дизъюнкцией ИЛИ, нужно вместо одной строки + образца завести две строки, в одной из которых есть только + расширения, а в другой только макТипы. Под образец + файлового типа GIF подходят файлы с расширением + .gif ИЛИ имеющие макТип GIFF.

    + +

    На платформах Unix и Windows файл подходит под образец + файлового типа, если расширение его имени соответствует одному из + расширений в образце. макТипы игнорируются.

    + +

    ЗАДАНИЕ РАСШИРЕНИЙ

    + +

    На платформах Unix и Macintosh соответствие образцам + устанавливается обычным образом. На платформах Windows + соответствие образцам устанавливается операционной + системой. Возможными расширениями могут быть:

    + +
      +
    1. специальное расширение *, под которое подходит любой файл;
    2. + +
    3. специальное расширение "", под которое подходит + любой файл без расширения (т.е. файл, имя которого не содержит + точки);
    4. + +
    5. произвольная строка символов, среди которых нет символов + маски (* и ?).
    6. +
    + +

    Ввиду того, что на различных платформах используются различные + правила соответствия, появление символов маски в расширениях не + допускается, за исключением специального расширения + "*". Расширения, в которых нет точки (например, + "~"), допустимы, но они могут работать не на всех + платформах.

    + +

    ПРИМЕР

    + +
    +      set types {
    +        {{Text Files}     {.txt}     }
    +        {{TCL Scripts}    {.tcl}     }
    +        {{C Source Files} {.c}   TEXT}
    +        {{GIF Files}      {.gif}     }
    +        {{GIF Files}      {}     GIFF}
    +        {{All Files}      *          }
    +      }
    +      set filename [tk_getSaveFile -filetypes $types]
    +      # Сохранить файл ...
    +      }
    +    
    + + + diff --git a/hlp/ru/tk/tk_menuBar.html b/hlp/ru/tk/tk_menuBar.html new file mode 100644 index 0000000..95288f2 --- /dev/null +++ b/hlp/ru/tk/tk_menuBar.html @@ -0,0 +1,26 @@ + + + + tk_menuBar, tk_bindForTraversal + + +

    tk_menuBar, tk_bindForTraversal

    + +

    Устаревшие команды для управления меню.

    + +

    СИНТАКСИС

    + +
    +      tk_menuBar frame ?menu menu?
    +      tk_bindForTraversal arg arg
    +    
    + +

    ОПИСАНИЕ

    + +

    Команды использовались в Tk версии 3.6, и более ранних, для + управления ниспадающими меню взаимодействия с ними при помощи + клавиатуры. В настоящий момент команды остаются только для + обеспечения совместимости с ранними версиями, и их не следует + использовать в новых разработках.

    + + diff --git a/hlp/ru/tk/tk_messageBox.html b/hlp/ru/tk/tk_messageBox.html new file mode 100644 index 0000000..623c28a --- /dev/null +++ b/hlp/ru/tk/tk_messageBox.html @@ -0,0 +1,120 @@ + + + + tk_messageBox + + +

    tk_messageBox

    + +

    Выводит окно сообщения и ждет ответа пользователя.

    + +

    СИНТАКСИС

    + +
    +      tk_messageBox ?параметр значение...?
    +    
    + +

    ОПИСАНИЕ

    + +

    Эта процедура создает и выводит на экран окно сообщения, в + котором находится определяемое приложением сообщение, + пиктограмма и набор кнопок. Каждая из кнопок в окне сообщения + отождествляется с уникальным символическим именем (см. параметры + -type). После появления окна сообщения команда + tk_messageBox ожидает, пока пользователь не + выберет одну из кнопок. После того, как выбор сделан, команда + возвращает символическое имя выбранной кнопки. Команда + поддерживает следующие пары параметр-значение:

    + +
    +
    -default имя
    + +
    Параметр имя задает символическое имя кнопки по + умолчанию для окна сообщения ('ok', 'cancel' и т.п.). Список + возможных символических имен см. в описании параметра + -type. Если в окне сообщения лишь одна + кнопка, то она автоматически делается кнопкой по умолчанию; + если же кнопок несколько, а параметр -default + не задан, то кнопки по умолчанию не будет.
    + +
    -icon изобрПикт
    + +
    Задает выводимую пиктограмму. Параметр изобрПикт + может иметь одно из следующих значений: + error, info, + question или warning. Если + параметр не указан, то пиктограмма не выводится.
    + +
    -message строка
    + +
    Задает сообщение, выводимое в окне сообщений.
    + +
    -parent окно
    + +
    Делает окно логическим родителем окна + сообщений. Окно сообщения выводится поверх своего родительского + окна.
    + +
    -title строкаЗаголовка
    + +
    Задает текстовую строку, которая выводится в качестве + заголовка в окне сообщения. Значением параметра по умолчанию + является пустая строка.
    + +
    -type предопределенныйТип
    + +
    Устанавливает предопределенный набор кнопок в окне. Параметр + предопределенныйТип может иметь следующие + значения: + +
    +
    abortretryignore
    + +
    Выводит три кнопки с символическими именами + abort, retry и + ignore.
    + +
    ok
    + +
    Выводит одну кнопку с символическим именем + ok.
    + +
    okcancel
    + +
    Выводит две кнопки с символическими именами + ok и cancel.
    + +
    retrycancel
    + +
    Выводит две кнопки с символическими именами + retry и cancel.
    + +
    yesno
    + +
    Выводит две кнопки с символическими именами + yes и no.
    + +
    yesnocancel
    + +
    Выводит три кнопки с символическими именами + yes, no и + cancel. +
    +
    +
    +
    + +

    ПРИМЕР

    + +
    +      set answer [tk_messageBox -message "Really quit?" -type yesno -icon question]
    +      case $answer {
    +        yes exit
    +        no {tk_messageBox -message "I know you like this application!" -type ok}
    +      }
    +    
    + + + + + diff --git a/hlp/ru/tk/tk_optionMenu.html b/hlp/ru/tk/tk_optionMenu.html new file mode 100644 index 0000000..3373d43 --- /dev/null +++ b/hlp/ru/tk/tk_optionMenu.html @@ -0,0 +1,36 @@ + + + + tk_optionMenu + + +

    tk_optionMenu

    + +

    Процедура создает меню-кнопку с защелкиванием (option + menubutton) и ее меню.

    + +

    СИНТАКСИС

    + +
    +      tk_optionMenu w varName value ?value value?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда создает меню-кнопку с защелкиванием по имени w и + связанное с ней меню. Такое меню позволяет пользователю выбрать + одно из значений, заданных аргументами value. Текущее + выбранное значение присваивается глобальной переменной + varName, а также отображается на кнопке в виде + ярлыка.

    + +

    Для выбора нового значения следует щелкнуть .Мышью. на кнопке и + в открывшемся меню выбрать значение. Также текущее значение + можно изменить, присвоив переменной varName новое + значение.

    + + + + + + diff --git a/hlp/ru/tk/tk_popup.html b/hlp/ru/tk/tk_popup.html new file mode 100644 index 0000000..72d001f --- /dev/null +++ b/hlp/ru/tk/tk_popup.html @@ -0,0 +1,28 @@ + + + + tk_popup + + +

    tk_popup

    + +

    Процедура открывает всплывающее меню.

    + +

    СИНТАКСИС

    + +
    +      tk_popup menu x y ?entry?
    +    
    + +

    ОПИСАНИЕ + +

    Процедура выводит на дисплей всплывающее меню при помощи + примитива меню menu в позиции, заданной аргументами + x и y. Необязательный аргумент entry + указывает индекс некоторой команды (входа) меню menu, к + которой будет относиться выводимое меню.

    + + + + + diff --git a/hlp/ru/tk/tkerror.html b/hlp/ru/tk/tkerror.html new file mode 100644 index 0000000..95d1900 --- /dev/null +++ b/hlp/ru/tk/tkerror.html @@ -0,0 +1,31 @@ + + + + tkerror + + +

    tkerror

    + +

    Команда обрабатывает фоновые ошибки.

    + + +

    СИНТАКСИС

    + +
    +      tkerror message
    +    
    + +

    ОПИСАНИЕ

    + +

    Данная команда обрабатывает фоновые ошибки и предназначена для + обеспечения совместимости с ранними версиями Tk. В настоящей + версии Tk ее функции исполняет команда bgerror. Поддержка + команды tkerror может быть вскоре прекращена, + поэтому рекомендуется в приложениях заменять эту команду на bgerror.

    + + + + + diff --git a/hlp/ru/tk/tkvars.html b/hlp/ru/tk/tkvars.html new file mode 100644 index 0000000..385519e --- /dev/null +++ b/hlp/ru/tk/tkvars.html @@ -0,0 +1,50 @@ + + + + tkvars + + +

    tkvars

    + +

    Переменные, используемые или задаваемые Tk.

    + + +

    ОПИСАНИЕ

    + +

    Нижеследующие переменные используются Tk в разные моменты + работы, или задаются им.

    + +
    +
    tk_library
    + +
    переменная содержит путь к каталогу с библиотекой скриптов + Tcl, относящихся к Tk.
    + +
    tk_patchLevel
    + +
    переменная содержит десятичное число, соответствующее номеру + версии поправок к Tk.
    + +
    TkPriv
    + +
    эта переменная есть массив значений внутренних данных Tk, + используемых библиотечными процедурами Tk и привязками + (bindings) по умолчанию. Внешние по отношению к Tk программы + эти данные не используют.
    + +
    tk_strictMotif
    + +
    это флаг. Если приложение устанавливает его, то Tk будет + стремиться наиболее полно поддерживать стиль графического + интерфейса Motif.
    + +
    tk_version
    + +
    переменная содержит номер версии библиотеки Tk.
    +
    + + + + + + diff --git a/hlp/ru/tk/tkwait.html b/hlp/ru/tk/tkwait.html new file mode 100644 index 0000000..085b274 --- /dev/null +++ b/hlp/ru/tk/tkwait.html @@ -0,0 +1,38 @@ + + + + tkwait + + +

    tkwait

    + + +

    Команда организует паузу до момента изменения значения переменной + или закрытия окна.

    + + +

    СИНТАКСИС

    + +
    +      tkwait variable name 
    +      tkwait visibility name
    +      tkwait window name
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда ожидает наступления одного из нескольких событий, после + этого она завершает работу без выполнения каких-либо + действий. Если первый аргумент команды есть + variable, то name есть имя глобальной + переменной, и команда ожидает изменения значения этой + переменной. Если первый аргумент команды есть + visibility, то name есть имя окна, и + команда ожидает изменения его состояния внешних параметров + (visibility). Если первый аргумент команды есть + window, то name есть имя окна, и + команда ожидает закрытия этого окна.

    + + + + diff --git a/hlp/ru/tk/toplevel.html b/hlp/ru/tk/toplevel.html new file mode 100644 index 0000000..8e80a1b --- /dev/null +++ b/hlp/ru/tk/toplevel.html @@ -0,0 +1,241 @@ + + + + toplevel + + +

    toplevel

    + +

    Создание примитива верхнего уровня и управление им.

    + +

    СИНТАКСИС

    + +
    +      toplevel имяПути ?параметры?
    +    
    + + +

    СТАНДАРТНЫЕ ПАРАМЕТРЫ

    + +
      +
    • -background
    • +
    • -cursor
    • +
    • -highlightbackground
    • +
    • -highlightcolor
    • +
    • -highlightthickness
    • +
    • -relief
    • +
    • -takefocus
    • +
    + + +

    Подробное описание этих параметров приведено в разделе options.

    + +

    ДОПОЛНИТЕЛЬНЫЕ ПАРАМЕТРЫ ПРИМИТИВА

    + + + + + +
    Имя параметра:-background
    Имя в Базе:background
    Класс в Базе:Background
    + +

    Этот параметр по смыслу совпадает со стандартным параметром + background за исключением того, что его + значением может являться и пустая строка. В последнем случае при + выводе примитива не появляется ни фона, ни бордюра, и для них не + используется ни одна из красок его палитры.

    + + + + + +
    Имя параметра:-class
    Имя в Базе:class
    Класс в Базе:Class
    + +

    Задает класс окна. Этот класс используется при запросах базы + данных параметров о значениях других параметров примитива; а + также при определении привязок. Параметр -class + нельзя переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-colormap
    Имя в Базе:colormap
    Класс в Базе:Colormap
    + +

    Задает палитру, используемую в окне. Значением параметра может + быть либо new (и в этом случае для данного окна + и его потомков создается новая палитра), либо имя другого окна + (которое должно находиться на том же экране и иметь то же + значение параметра -visual, что и + имяПути). Если параметр -colormap не + задан, то новое окно использует палитру экрана по + умолчанию. Параметр -colormap нельзя + переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-container
    Имя в Базе:container
    Класс в Базе:Container
    + +

    Значение параметра должно быть булевским. Если его значение + истина, то окно будет использоваться в качестве контейнера, в + который будет вставляться некоторое другое приложение (например, + можно вставить примитив верхнего уровня Tk с помощью параметра + -use). Окно будет поддерживать соответствующие протоколы + управления окнами, например, для обработки геометрических + запросов. Параметр -container нельзя + переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-height
    Имя в Базе:height
    Класс в Базе:Height
    + +

    Задает желаемую высоту окна в любом виде, приемлемом для + Tk_GetPixels. Если введенное значение + неположительно, то место для окна вообще не запрашивается.

    + + + + + +
    Имя параметра:-menu
    Имя в Базе:menu
    Класс в Базе:Menu
    + +

    Задает примитив меню, используемый в качестве полосы меню. На + Macintosh полоса меню будет выведена вверху основного + монитора. В Microsoft Windows и на всех платформах UNIX меню + выводится поверх окна верхнего уровня как деталь оформления окна + менеджером окон.

    + + + + + +
    Имя параметра:-screen
    Имя в Базе:
    Класс в Базе:
    + +

    Задает экран, на котором следует разместить новое окно. Может + быть использовано произвольное допустимое имя экрана, в том + числе и отличное от текущего. По умолчанию значением является + имя текущего экрана. Параметр -screen является + специальным и его нельзя переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-use
    Имя в Базе:use
    Класс в Базе:Use
    + +

    Используется для вставки. Если значение параметра отлично от + пустой строки, то оно должно быть идентификатором + окна-контейнера, заданным в виде шестнадцатиричной строки, в том + виде, в котором возвращает результат команда window + id. Примитив верхнего уровня будет создаваться как + непосредственный потомок указанного контейнера, а не корневого + окна экрана. Если окно-контейнер содержится в приложении Tk, то + оно должно быть либо рамкой, либо примитивом верхнего уровня, + для которого задан параметр + -container. Параметр -use + нельзя переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-visual
    Имя в Базе:visual
    Класс в Базе:Visual
    + +

    Задает внешний вид окна в любом виде, приемлемом для + Tk_GetVisual. Если параметр не задан, то + используется его значение по умолчанию для экрана. Параметр + -visual нельзя переопределить командой примитива + configure.

    + + + + + +
    Имя параметра:-width
    Имя в Базе:width
    Класс в Базе:Width
    + +

    Задает желаемую ширину окна в любом виде, приемлемом для + Tk_GetPixels. Если введенное значение + неположительно, то место для окна вообще не запрашивается.

    + +

    ОПИСАНИЕ

    + +

    Команда toplevel создает новый примитив + верхнего уровня (задаваемый аргументом имяПути). Детали + изображения примитива верхнего уровня, такие как цвет его фона и + объемный вид, задаются с помощью описанных выше дополнительных + параметров. Команда toplevel возвращает + аргумент имяПути.

    + +

    Примитив верхнего уровня похож на рамку; отличие состоит в том, + что он создается как окно верхнего уровня: его непосредственным + X предком является корневое окна экрана, а не логический предок, + определяемый именем пути. Основная задача примитива верхнего + уровня служить контейнером для диалоговых окон и других наборов + примитивов. Единственными параметрами вывода примитива верхнего + уровня являются цвет его фона и необязательный трехмерный + бордюр, который позволяет примитиву выглядеть выпуклым или + вдавленным.

    + + +

    КОМАНДА ПРИМИТИВА

    + + +

    Команда toplevel создает новую команду Tcl, + имя которой совпадает с именем окна примитива верхнего уровня. С + помощью этой команды можно выполнять различные операции над + примитивом. Ее общий вид

    + +
    +      имяПути параметр арг арг ...
    +    
    + +

    имяПути является именем команды, которое совпадает с + именем пути примитива верхнего уровня. Параметр и + аргументы уточняют поведение команды.

    + + +

    Примитивы верхнего уровня допускают следующие команды:

    + +
    +
    имяПути cget параметр
    + +
    Возвращает текущее значение параметра конфигурации с именем + параметр. Параметр может быть любым из параметров + команды toplevel
    + +
    имяПути configure ?параметр? + ?значение параметр значение ...
    + +
    Запрашивает значения параметров конфигурации примитива или + изменяет их. Если параметр не указан, то возвращает + список, содержащий значения всех допустимых в + имениПути параметров (формат списка описан в + Tk_ConfigureInfo). Если параметр + задан, а его новое значение нет, то команда + возвращает часть полного списка, относящуюся к указанному + параметру. Если заданы одна или несколько пар + параметр-значение, то указанным параметрам + примитива присваиваются новые значения. В этом случае + команда возвращает пустую строку. Параметр может быть + любым из параметров команды toplevel.
    +
    + +

    ПРИВЯЗКИ

    + +

    При создании примитива верхнего уровня никаких привязок не + создается: эти примитивы не предполагаются интерактивными.

    + + + + + + diff --git a/hlp/ru/tk/update.html b/hlp/ru/tk/update.html new file mode 100644 index 0000000..4c7ec7b --- /dev/null +++ b/hlp/ru/tk/update.html @@ -0,0 +1,45 @@ + + + + update + + + +

    update

    + +

    Команда update обрабатывает события, находящиеся в + состоянии ожидания, и обратные вызовы (idle callbacks).

    + +

    СИНТАКСИС

    + +
    +      update idletasks
    +    
    + +

    ОПИСАНИЕ

    + +

    С помощью этой команды обновляется состояние приложения, + поскольку при ее вызове обрабатываются все необработанные + события и выполняются все асинхронные вызовы (idle + callbacks).

    + +

    Если в команде задана опция idletasks, то новые события + и ошибки не обрабатываются, но выполняются все асинхронные + вызовы. Команду update idletasks удобно использовать + тогда, когда нужно выполнить немедленно действия, которые обычно + откладываются, например, обновить отображаемые на дисплее данные + или окна. Большинство обновлений изображений на дисплее + выполняются в виде фоновых вызовов, и эта команда обеспечит их + выполнение. Однако, если изменения были вызваны событиями, они + не будут выполнены немедленно.

    + +

    Команда update без опций полезна в тех случаях, когда во + время долго выполняющихся вычислений необходимо обеспечить + оперативную реакцию приложения на события, например, на действия + пользователя. Вызов команды update и обеспечивает обработку + таких событий.

    + + + + + diff --git a/hlp/ru/tk/winfo.html b/hlp/ru/tk/winfo.html new file mode 100644 index 0000000..465cef4 --- /dev/null +++ b/hlp/ru/tk/winfo.html @@ -0,0 +1,419 @@ + + + + winfo + + +

    winfo

    + +

    winfo -возвращает информацию об + окне.

    + +

    СИНТАКСИС

    + +
    +      winfo option ?arg arg ..?
    +    
    + +

    ОПИСАНИЕ

    + +

    Команда winfo позволяет получать информацию об + окнах, созданных с помощью Tk. Команда имеет несколько + допустимых форм в зависимости от указанных опций. Ниже + перечислены допустимые формы команды:

    + +
    +
    winfo atom ?-displayof + window? name
    + +
    Команда возвращает десятичную строку числовой идентификатор + атома (напрмер, виджета). Если атома name не + существует, он создается. А после создания соответствующего + виджета он получает этот идентификатор атома. Если указана + опция -displayof window, + атом ищется на том же дисплее, на котором находится + указанное окно. В противном случае атом ищется на дисплее, на + котором размещено главное окно + приложения.
    + +
    winfo atomname + ?-displayof window? id
    + +
    Возвращает текстовое имя атома с идентификатором + id. Если указана опция -displayof + window, атом ищется на том же дисплее, на котором + находится указанное окно. В противном случае атом ищется на + дисплее, на котором размещено главное окно приложения. Команда + является обратной к команде winfo + atom. Команда возвращает код ошибки, если атом не + существует.
    + +
    winfo cells window
    + +
    Команда возвращает десятичную строку число возможных цветов + в палитре для window.
    + +
    winfo children window
    + +
    Возвращает список полных имен всех потомков окна + window. Потомки перечисляются в порядке стека, + начиная с нижних. Toplevel-окна также считаются потомками + своих логических предков.
    + +
    winfo class window
    + +
    Возвращает класс окна window.
    + +
    winfo colormapfull window
    + +
    Возвращает 1, если известно, что палитра (colormap) + окна заполнена, и 0 в противном случае. Палитра считается + заполненной, если последняя попытка разместить в ней еще один + цвет окончилась неуспешно, а приложение не освободило с того + момента не одного цвета в палитре.
    + +
    winfo containing + ?-displayof window? rootX + rootY
    + +
    Возвращает имя окна, содержащего точку с координатами + rootX и rootY. Координаты задаются в + экранных единицах (в любой форме, поддерживаемой Tk) в системе + координат корневого окна (если используется менеджер + виртуального корневого окна, координаты задаются в его системе + координат). Если указана опция -displayof + window, окно ищется на дисплее, + содержащем window. В противном случае + координаты считаются указанными для дисплея, на котором + размещено главное окно приложения. Если данная точка не + содержится ни в каком окне приложения, возвращается пустая + строка. Если точка содержится в нескольких виджетах (например, + в кнопке, лежащей в рамке), преимущество имеют логические + потомки. Из окон "одного поколения" выбирается + окно, лежащее выше других в стеке.
    + +
    winfo depth window
    + +
    Возвращает "глубину цвета" число бит на пиксель + изображения для окна window.
    + +
    winfo exists window
    + +
    Возвращает 1, если существует окно window, и 0 в + противоположном случае.
    + +
    winfo fpixels window number
    + +
    Возвращает число пикселей (дробное, с плавающей точкой), + соответствующее на экране расстоянию number. + Расстояние может быть указано в любой форме, поддерживаемой + Tk, например, 2.0c или + 1i. Чтобы получить целое число пикселей, + можно использовать команду winfo pixels.
    + +
    winfo geometry window
    + +
    Возвращает размеры и положение окна в форме + ширинаxвысота+x+y. + Все размеры приводятся в пикселях.
    + +
    winfo height window
    + +
    Возвращает десятичную строку, содержащую высоту окна в + пикселях. Когда окно только что создано, его размер 1 + пиксель. Через некоторое время оно принимает правильные + размеры. Однако, если вы хотите получить правильные размеры + окна сразу после его создания, используйте перед этим команду + update, которая + приведет к прорисовке окна и формированию его правильных + размеров, либо команду winfo reqheight, + которая возвращает требуемые, а не реальные размеры + окна.
    + +
    winfo id window
    + +
    Возвращает шестнадцатеричную строку зависящий от платформы + идентификатор низкого уровня для окна. На Unix-платформах это + X-window идентификатор. Под Windows это Windows HWND. На + Macintosh этот идентификатор не имеет смысла вне + Tk.
    + +
    winfo interps ?-displayof + window?
    + +
    Возвращает список всех Tcl-интерпретаторов (например, + Tk-приложений), зарегистрированных в текущий момент на + определенном дисплее. Если задана опция + ?-displayof window?, имеется в виду + дисплей, на котором находится окно window. В + противном случае дисплей, на котором находится главное окно + приложения.
    + +
    winfo ismapped window
    + +
    Возвращает 1, если окно в данный момент размещено на экране, + и 0 в противном случае.
    + +
    winfo manager window
    + +
    Возвращает имя геометрического менеджера, с помощью которого + размещено окно, или пустую строку, если окно не размещено. Для + виджетов возвращается как правило имя Tcl-команды для + соответствующего менеджера, например, pack или place. Для + toplevel-окон возвращается wm, для встроенных + окон имя команды для соответствующего класса виджетов, + например, canvas.
    + +
    winfo name window
    + +
    Возвращает имя окна, то есть имя относительно родителя в + отличие от полного имени. Команда winfo + name возвращает имя + приложения.
    + +
    winfo parent window
    + +
    Возвращает имя логического родителя окна или пустую строку + для главного окна приложения.
    + +
    winfo pathname + ?-displayof window? id
    + +
    Возвращает полное имя окна с X-идентификатором + id. Идентификатор может быть десятичным, + шестнадцатеричным или восьмеричным числом и должен + принадлежать одному из окон приложения. Если указана опция + -displayof window, + окно ищется на том же дисплее, на котором находится + указанное окно. В противном случае окно ищется на дисплее, на + котором размещено главное окно + приложения.
    + +
    winfo pixels window number
    + +
    Возвращает число пикселей, соответствующее на экране + расстоянию number. Расстояние может быть указано в + любой форме, поддерживаемой Tk, например, + 2.0c или 1i. Результат + округляется до ближайшего целого. Чтобы получить дробное число + пикселей, можно использовать команду winfo + fpixels.
    + +
    winfo pointerx window
    + +
    Если указатель "Мыши" находится на том же экране, + что и окно, возвращает x- координату пойнтера в пикселях в + системе координат корневого окна. Если на экране есть + виртуальное корневое окно, возвращаются координаты в его + системе координат. Если пойнтера "Мыши" на данном + экране нет, возвращается "-1".
    + +
    winfo pointerxy window
    + +
    Если указатель "Мыши" находится на том же экране, + что и окно, возвращает список, содержащий x- и y-координаты + пойнтера в пикселях в системе координат корневого окна. Если + на экране есть виртуальное корневое окно, возвращаются + координаты в его системе координат. Если пойнтера + "Мыши" на данном экране нет, возвращается + "-1".
    + +
    winfo pointery window
    + +
    Если указатель "Мыши" находится на том же экране, что + и окно, возвращает y-координату пойнтера в пикселях в системе + координат корневого окна. Если на экране есть виртуальное + корневое окно, возвращаются координаты в его системе + координат. Если пойнтера "Мыши" на данном экране нет, + возвращается "-1".
    + +
    winfo reqheight window
    + +
    Возвращает десятичную строку, содержащую необходимую высоту + окна. Это та величина, которая используется менеджером окна + при расчете его размеров.
    + +
    winfo reqwidth window
    + +
    Возвращает десятичную строку, содержащую необходимую ширину + окна. Это та величина, которая используется менеджером окна + при расчете его размеров.
    + +
    winfo rgb window color
    + +
    Возвращает список из трех десятичных величин, указывающих + интенсивность красного, зеленого и синего цвета для цвета + color в окне window. Цвет может быть задан в + любой форме, в которой он может задаваться в соответствующих + опциях.
    + +
    winfo rootx window
    + +
    Возвращает десятичную строку, содержащую x-координату левого + верхнего угла рамки окна (или самого окна, если оно не имеет + рамки) в системе координат корневого + окна.
    + +
    winfo rooty window
    + +
    Возвращает десятичную строку, содержащую y-координату левого + верхнего угла рамки окна (или самого окна, если оно не имеет + рамки) в системе координат корневого + окна.
    + +
    winfo screen window
    + +
    Возвращает имя экрана, на котором отображается окно, в форме + ИмяДисплея.ИндексЭкрана.
    + +
    winfo screencells window
    + +
    Возвращает число цветов в палитре по умолчанию для экрана, + содержащего данное окно.
    + +
    winfo screendepth window
    + +
    Возвращает "глубину цвета" число бит на пиксель изображения + для экрана, содержащего окно window.
    + +
    winfo screenheight window
    + +
    Возвращает десятичную строку, содержащую высоту экрана, + содержащего окно window, в + пикселях.
    + +
    winfo screenmmheight window
    + +
    Возвращает десятичную строку, содержащую высоту экрана, + содержащего окно window, в + миллиметрах.
    + +
    winfo screenmmwidth window
    + +
    Возвращает десятичную строку, содержащую ширину экрана, + содержащего окно window, в + миллиметрах.
    + +
    winfo screenvisual window
    + +
    Возвращает одну из строк, указывающих класс (по умолчанию) + экрана, на котором находится окно window: + directcolor, grayscale, + pseudocolor, staticcolor, + staticgray, или + truecolor.
    + +
    winfo screenwidth window
    + +
    Возвращает десятичную строку, содержащую ширину экрана, + содержащего окно window, в + пикселях.
    + +
    winfo serverwindow
    + +
    Возвращает строку, содержащую информацию о сервере дисплея, + на котором находится окно. Точная форма строки зависит от + платформы. Для X-сервера строка имеет вид + "XmajorRminor vendor vendorVersion" где + major и minor соответственно версия и релиз + сервера (например, X11R5), vendor + имя поставщика, vendorRelease номер релиза сервера, + назначенный поставщиком.
    + +
    winfo toplevel window
    + +
    Возвращает полное имя ближайшего toplevel-окна, содержащего + window.
    + +
    winfo viewable window
    + +
    Возвращает 1, если окно и его предки вплоть до ближайшего toplevel + размещены, и 0 в противном случае.
    + +
    winfo visual window
    + +
    Возвращает одну из строк, указывающих класс окна + window: directcolor, + grayscale, pseudocolor, + staticcolor, staticgray, или + truecolor.
    + +
    winfo visualid window
    + +
    Возвращает X-идентификатор класса (возвращаемого командой + winfo visual) для окна + window.
    + +
    winfo visualsavailable window + ?includeids?
    + +
    Возвращает список, элементы которого описывают режимы, + допустимые для экрана, содержащего окно. Каждый элемент + состоит из имени класса и глубины цвета. Имена класса такие + же, как для команды winfovisual. Глубина + указывает число битов на пиксель. Если задана опция + includeids, за глубиной следует + X-идентификатор класса.
    + +
    winfo vrootheight window
    + +
    Возвращает высоту виртуального корневого окна для + window, если такое есть. В противном случае + возвращает высоту экрана, на котором размещено окно + window.
    + +
    winfo vrootwidth window
    + +
    Возвращает ширину виртуального корневого окна + дляwindow, если такое есть. В противном случае + возвращает ширину экрана, на котором размещено окно + window.
    + +
    winfo vrootx window
    + +
    Возвращает x-координату корневого окна в системе координат + виртуального корневого окна. Обычно 0 или + отрицательное число. Если виртуального корневого окна на + существует, возвращает 0.
    + +
    winfo vrooty window
    + +
    Возвращает y-координату корневого окна в системе координат + виртуального корневого окна. Обычно 0 или отрицательное + число. Если виртуального корневого окна на существует, + возвращает 0.
    + + +
    winfo width window
    + +
    Возвращает десятичную строку, содержащую ширину окна в + пикселях. Когда окно только что создано, его размер 1 + пиксель. Через некоторое время оно принимает правильные + размеры. Однако, если вы хотите получить правильные размеры + окна сразу после его создания, используйте перед этим команду + update, которая приведет к прорисовке окна и + формированию его правильных размеров, либо команду + winfo reqwidth, которая + возвращает требуемые, а не реальные размеры + окна.
    + +
    winfo x window
    + +
    Возвращает десятичную строку, содержащую x-координату левого + верхнего угла рамки окна (или самого окна, если оно не имеет + рамки) в системе координат окна + предка.
    + +
    winfo y window
    + +
    Возвращает десятичную строку, содержащую x-координату левого + верхнего угла рамки окна (или самого окна, если оно не имеет + рамки) в системе координат окна предка.
    +
    + + + + diff --git a/hlp/ru/tk/wm.html b/hlp/ru/tk/wm.html new file mode 100644 index 0000000..98891c9 --- /dev/null +++ b/hlp/ru/tk/wm.html @@ -0,0 +1,526 @@ + + + +Wm + + +

    Wm

    +

    Команда взаимодействия с менеджером окон.

    + +

    + +

    СИНТАКСИС + +

    +
    wm option window ?args?
    +
    + +

    ОПИСАНИЕ + +Команда wm предназначена для +взаимодействия с менеджером окон и обеспечивает таким образом +управление такими атрибутами окон, как заголовок, размеры и +размещение, возможность изменять размер. Команда имеет несколько +форм в зависимости от используемых опций. Во всех формах команда +предполагает наличие по крайней мере одного аргумента имени toplevel окна. + +

    Ниже перечислены возможные формы команды. +

    +
    wm aspect window minNumer minDenom maxNumer maxDenom
    + +

    Если аргументы minNumer, minDenom, maxNume и maxDenom +заданы, они передаются менеджеру +окон, который использует их для определения допустимых пропорций +окна. Пропорции (отношение ширина высота) могут быть в диапазоне +от minNumer/minDenom до maxNumer/maxDenom. Если +аргументы minNumer и т.д. определены как пустые строки, то +существующие ограничения на пропорции отменяются. Если аргументы +minNumer и т.д. заданы, то команда возвращает пустое +значение. В противном случае она возвращает список из четырех +элементов текущих значений minNumer, minDenom, maxNumer, и maxDenom +(если ограничения не заданы, возвращается пустая строка). +

    +

    wm client window name

    + +

    Если имя name указано (name должно +быть именем компьютера, на котором исполняется приложение), то +оно сохраняется в свойстве окна WM_CLIENT_MACHINE и может +использоваться менеджером окон или менеджером сессий. В этом +случае команда возвращает пустую строку. Если аргумент +name не задан, команда возвращает последнее установленное +ранее значение свойства. Если аргумент name определен как +пустая строка, свойство окна WM_CLIENT_MACHINE удаляется.
    + +

    wm colormapwindows window ?windowList?

    + +

    Эта команда используется для управления свойством +WM_COLORMAP_WINDOWS, которое обеспечивает менеджер окон +информацией об окнах, имеющих собственную палитру. Если аргумент +windowListне задан, команда возвращает список окон, +имеющих собственную палитру. Если аргумент задан, он представляет +собой список полных имен окон. Команда изменяет старое значение +свойства на новое и возвращает пустую строку. Список окон +перечисляет внутренние окна, палитра которых отличается от +палитры их логических предков. Порядок, в котором перечислены +окна, указывает порядок, в котором менеджер окон просматривает +окна, пытаясь разместить новые цвета в палитре. Не указанные в +списке окна обрабатываются в последнюю очередь. Если команда не +использовалась, Tk автоматически устанавливает свойство для +каждого toplevel окна. В списке перечисляются все его внутренние +окна, имеющие собственную палитру, в случайном порядке. В конце +списка указывается само toplevel окно. Более подробно свойство +WM_COLORMAP_WINDOWS описано в (1).

    + +

    wm command window value

    + +

    Если аргумент value задан, команда +сохраняет его значение в свойстве окна WM_COMMAND, которое +используется менеджером окон или менеджером сессий. В этом случае +команда возвращает пустую строку. Аргумент value должен +содержать список, элементы которого являются словами команды, +используемой для запуска приложения (см. также wmuse).

    + +

    Если аргумент value не задан, команда возвращает последнее +установленное ранее значение свойства. Если аргумент name +определен как пустая строка, свойство окна WM_COMMAND +удаляется.

    + +

    wm deiconify window

    + +

    Заставляет окно появиться на экране в нормальном +виде (а не в виде иконки, например,). Если окно ранее не +появлялось на экране, выполнение команды не приведет к его +появлению, но она гарантирует, что если в будущем окно появится, +оно появится в нормальном виде. Команда возвращает пустую +строку.

    + +

    wm focusmodel windowactive|passive

    + +

    Если тип фокуса для (active или +passive) окна указан в команде, он определяет какой тип +фокуса будет использоваться. В этом случае команда возвращает +пустую строку. Если тип фокуса не указан, команда возвращает +текущее значение типа. Активный тип фокуса означает, что окно +запрашивает фокус ввода себе или своим потомкам, даже если в этот +момент фокус находится в другом приложении. Пассивный фокус +означает, что окно не запрашивает фокус, а получает его от +менеджера окон. Однако, после того, как окно или один из его +потомков получил фокус, приложение может передать его другому +потомку окна. По умолчанию устанавливает пассивный фокус.

    + +

    wm frame window

    + +

    Если окно заключено менеджером окон в +декоративную рамку, команда возвращает идентификатор самой +внешней рамки, которая содержит окно (окно, являющееся потомком +корневого окна или виртуального корневого окна). Вид +идентификатора зависит от платформы. Если окно не заключено в +рамку, возвращается идентификатор окна, вид которого также +зависит от платформы. + +

    wm geometry window newGeometry

    + +

    Если задан аргумент newGeometry, размеры и размещение +окна изменяются, а команда возвращает пустую строку. В противном +случае возвращается последняя информация о размерах и размещении +окна (независимо от того, была ли она задана путем изменения +размеров окна вручную или с помощью команды wm). Аргумент +newGeometry должен быть задан в следующем виде +=ширинаxвысота╠x╠y, где любая из частей +=ширинаxвысота или ╠x╠y может быть опущена. Ширина +и высота должны быть положительными целыми числами, задающими +желаемый размер окна. Если для окна задана сетка +(см. .Управление окнами с +сеткой.), размеры указываются в шагах сетки. В противном +случае размеры указываются в пикселях. X и Y определяют +желаемое размещение окна на экране в пикселях. Если перед +x стоит .+., то величина x определяет +расстояние от левого края экрана до левого края окна, в противном +случае x задает расстояние от правого края экрана до +правого края окна. Если перед y стоит .+., то величина y +определяет расстояние от верхнего края экрана до верхнего края +окна, в противном случае y задает расстояние от низа +экрана до нижнего края окна. Если аргумент newGeometry +задан как пустая строка, текущие установленные пользователем +размеры окна отменяются и окно приобретает размеры, определяемые +размерами составляющих его виджетов.

    + +

    wm grid window baseWidth baseHeight widthInc heightInc

    + +

    Команда определяет наличие сетки в окне и +позволяет задать шаг сетки в пикселях. BaseWidth и +baseHeight определяют в единицах сетки исходный размер +окна (определяемый, исходя из размеров виджетов). WidthIncheightInc определяют соответственно горизонтальный и +вертикальный шаг сетки. Таким образом, эти четыре величины +определяют множество допустимых размеров окна. После выполнения +этой команды команда wm geometry считает размеры окна +заданными в шагах сетки. Более того, при ручном изменении +размеров менеджер окон показывает размер окна в шагах (ячейках) +сетки и позволяет изменять размер только дискретно в целых шагах +сетки.
    +Если BaseWidth и последующие аргументы команды пустые +строки, команда указывает, что окно больше не имеет сетки.
    + +

    Если BaseWidth и последующие аргументы +заданы, команда возвращает пустую строку. В противном случае +команда возвращает список из четырех элементов, содержащий +текущие значения BaseWidth и последующих аргументов. Если +окно не имеет сетки возвращается пустая строка.
    + +

    Замечание. Потребность в использовании команды +wm grid возникает относительно редко, поскольку той же +функциональности поведения окна можно добиться, например, с +помощью опции setGrid в командах создания виджетов.

    + +

    wm group window pathName

    + +

    Если аргумент pathName указан, окно +pathName становится лидером группы для window. +Менеджер окон использует эту информацию, например, для того, +чтобы одновременно выводить с экрана все окна группы, если +сворачивается лидер группы. Если аргумент pathName +представлен пустой строкой, окно window выводится из +состава группы.
    +Если аргумент pathName задан, команда возвращает пустую +строку. В противном случае команда возвращает имя текущего лидера +группы для окна window или пустую строку, если лидер не +определен.

    + +

    wm iconbitmap window bitmap

    + +

    Если аргумент bitmap задан, он определяет +имя растрового образа, которое передается менеджеру окон для +использования в качестве иконки. Имя образа может быть задано в +одной из следующих форм:

    +
    +
    @ИмяФайла файл должен содержать описание растрового +рисунка в формате, соответствующем стандарту X11 или X10
    + +
    name имя образа типа bitmap, ранее созданного в приложении.
    + +
    Если аргумент bitmap представляет собой пустую строку, отменяется использование ранее заданного образа.
    + +
    Если аргумент bitmap задан, команда возвращает пустую строку. В противном случае команда возвращает имя образа, используемого джля иконки, либо пустую строку, если образ не задан.
    + +

    wm iconify window

    + +

    Команда сворачивает указанное окно. Если окно еще не было размещено на экран, оно появится, когда это произойдет, в виде иконки.

    + +

    wm iconmask window bitmap

    + +

    Если аргумент bitmap задан, он определяет +имя растрового образа, которое передается менеджеру окон для +использования в качестве маски для иконки. Там, где маска имеет +значение .0., образ иконки не отображается; там, где маска имеет +значение .1., маска рисуется. Имя образа может быть задано в +одной из следующих форм:

    + +

    @ИмяФайла файл должен содержать описание растрового рисунка в формате, соответствующем стандарту X11 или X10;
    + +

    name имя образа типа bitmap, ранее созданного в приложении.
    + +

    Если аргумент bitmap представляет собой пустую строку, отменяется использование ранее заданной маски (это эквивалентно заданию маски из одних единиц).
    + +

    Если аргумент bitmap задан, команда возвращает пустую строку. В противном случае команда возвращает имя образа, используемого для маски для данного окна, либо пустую строку, если маска не задана.
    + +

    wm iconname window ?newName?
    + +

    Если аргумент newName задан, он передается менеджеру окон для использования в качестве имени иконки для окна. В этом случае команда возвращает пустую строку. Если аргумент newNameне задан, команда возвращает текущее имя иконки для окна; если имя иконки не задано, команда возвращает пустую строку (в этом случае менеджер окон использует в качестве имени иконки имя окна, заданное с помощью команды wmtitle).
    + +

    wm iconposition window x y
    + +

    Если аргументы x и y заданы, они +передаются менеджеру окон и используются как подсказка при +размещении иконки окна window. В этом случае команда +возвращает пустую строку. Если x и y представляют +собой пустые строки, команда отменяет ранее определенную +подсказку для размещения иконки. Если аргументы x и +y не заданы, команда возвращает текущее значение подсказки +(или пустую строку, если она не задана).
    + +

    wm iconwindow window pathName
    + +

    Если аргумент pathName указан, он +определяет имя окна, которое используется в качестве иконки для +окна window: кодгда окно window свертывается, +появляется окно pathName, которое используется в качестве +иконки. Когда окно window разворачивается, окно +pathName выводится с экрана. Если аргумент pathName +представляет собой пустую строку, ранее определенное окно больше +не используется как иконка.
    + +

    Если аргумент pathName указан, команда возвращает пустую +строку. В противном случае команда возвращает имя окна, ранее +заданного в качестве иконки, или пустую строку, если ранее оно не +было задано.
    +

    Нажатие на кнопку .Мыши. в окне-иконке не обрабатываются приложением, что позволяет обрабатывать эти события менеджеру окон.
    + +

    Замечание. Не все менеджеры окон позволяют использовать Tk-окно в качестве иконки.
    + +

    wm maxsize window width height
    + +

    Если аргументы width и height +заданы, они задают максимальный возможный размер окна. Если в +окне определена сетка, размеры указываются в шагах сетки. В +противном случае размеры указываются в пикселях. Менеджер окон не +позволяет окну становиться больше, чем задано в команде.
    +Если аргументы width и height заданы, команда +возвращает пустую строку, в противном случае она возвращает +список, содержащий два элемента: текущие ограничения на размер +окна. По умолчанию максимальные размеры окна равны размеру +экрана. Если изменение размеров окна запрещено с помощью команды +wm resizable, команда wmmaxsize не влияет на +окно. Более подробно этот вопрос рассмотрен ниже +(см. Управление геометрией.)
    + +

    wm minsize window width height> + +


    Если аргументы width и height +заданы, они задают минимальный возможный размер окна. Если в окне +определена сетка, размеры указываются в шагах сетки. В противном +случае размеры указываются в пикселях. Менеджер окон не позволяет +окну становиться меньше, чем задано в команде.
    +Если аргументы width и height заданы, команда +возвращает пустую строку, в противном случае она возвращает +список, содержащий два элемента: текущие ограничения на размер +окна. По умолчанию минимальные размеры окна равны одному пикселю +в каждом направлении. Если изменение размеров окна запрещено с +помощью команды wm resizable, команда wm maxsize не +влияет на окно. Более подробно этот вопрос рассмотрен ниже +(см. Управление геометрией.).
    + +

    wm overrideredirect window boolean

    + +

    Если аргумент boolean задан, он должен +быть булевой величиной. Его значение присваивается +override-redirect флагу окна. Если аргумент не задан, +команда возвращает .1. или .0., в зависимости от того, установлен +ли флаг для window.
    +Установка флага приводит к тому, что окно не управляется +менеджером окон. В частности, окно не будет заключено в +декоративную рамку и пользователь не сможет изменять размеры и +положение окна, используя стандартные механизмы менеджера +окон.
    + +

    wm positionfrom window who

    + +

    Если аргумент who задан, он должен иметь +одно из двух значений program или user (или +произвольное сокращение от одного из них). Оно определяет, будет +ли размещение окна определяться программой или пользователем. +Многие менеджеры окон игнорируют запрошенное программой начальное +размещение окна и требуют от пользователя разместить его вручную. +Если задано значение user, менеджер окон не требует этого +от пользователя. Если аргумент who задан как пустая +строка, текущая установка отменяется.
    +Если аргумент who задан, команда возвращает пустую строку. +В противном случае команда возвращает установленное ранее +значение или пустую строку, если значение не было установлено. +Большинство менеджеров окон считают, что если .источник. не +задан, это то же самое, что program. Tk автоматически +устанавливает значение user при выполнении команды wm +geometry, если ранее не было установлено явно значение +program.
    + +

    wm protocol window name command
    + +

    Эта команда используется для организации +обработки сообщений (протоколов) менеджера окон, таких как +WM_DELETE_WINDOW. Аргумент name, если он задан, должен +быть именем элемента (атома) протокола менеджера окон. Если +заданы оба аргумента name и command, команда +command ассоциируется с протоколом name. Значение +name добавляется к свойству окна WM_PROTOCOLS, +чтобы указывать менеджеру окон, что приложение имеет обработчика +соответствующего сообщения, и какая команда должна быть выполнена +впоследствии, когда менеджер окон пошлет клиентской программе +соответствующее сообщение. В этом случае команда возвращает +пустую строку. +
    Если аргумент name задан, а command +нет, будет возвращена команда, ассоциированная с данным +протоколом или пустая строка, если такой команды нет. Если +command определена как пустая строка, текущий обработчик +соответствующего события будет отменен, а имя протокола будет +удалено из свойства PROTOCOLS окна window. Команда +возвратит пустую строку. +
    И наконец, если ни name, ни command не заданы, +команда возвратит список протоколов, для которых заданы +обработчики событий для данного окна.
    + +

    Tk всегда определяет обработчик событий для протокола +WM_DELETE_WINDOW, даже если он не был задан с помощью +команды wm protocol. Если обработчик события не был задан +явно, то, когда поступает сообщение WM_DELETE_WINDOW, Tk +удаляет окно, для которого было получено это сообщение.
    + +

    wm resizable window width height
    + +

    Эта команда управляет возможностью пользователя +интерактивно изменять размеры окна. Если аргументы width и +height заданы, они должны быть булевыми величинами, +определяющими, может ли пользователь изменять в интерактивном +режиме ширину и высоту окна соответственно. Команда при этом +возвращает пустую строку. Если аргументы width и +height отсутствуют, команда возвращает список из двух +элементов, принимающих значение .0. или .1. и указывающих, может +ли пользователь изменять высоту и ширину окна соответственно. По +умолчанию пользователь может изменять размеры окна в обоих направлениях. +

    Если изменение размеров окна пользователем запрещено, то либо +сохраняются те размеры окна, которые были получены в результате +последнего выполненного пользователем изменения размеров, либо +размеры окна устанавливаются с помощью команды wm geometry. +Если этих действий не было, используются размеры +окна, определяемые размерами составляющих его виджетов. +

    + +

    wm sizefrom window ?who?
    + +

    Если аргумент who задан, он должен иметь +одно из двух значений program или user (или +произвольное сокращение от одного из них). Оно определяет, будет +ли размер окна определяться программой или пользователем. Многие +менеджеры окон игнорируют запрошенный программой начальный размер +окна и требуют от пользователя определить его размер вручную. +Если задано значение user, менеджер окон не требует этого от +пользователя. Если аргумент who задан как пустая строка, +текущая установка отменяется. +
    Если аргумент who задан, команда возвращает пустую +строку. В противном случае команда возвращает установленное ранее +значение; если значение не было установлено, команда возвращает +пустую строку. Большинство менеджеров окон считают, что если +.источник. не задан, это то же самое, что +program. +
    + +

    wm state window
    + +

    Команда возвращает текущее состояние окна:
    +normal, iconic, withdrawn или icon. Разница +между iconic и icon в том, что iconic +используется для свернутого окна (например, с помощью команды +wm iconify ), а icon для окна, которое используется +в качестве иконки для другого окна (с помощью команды wm iconwindow). +
    + +

    wm title window string
    + +

    Если аргумент string определен, он +передается менеджеру окон для использования в качестве имени +(титула) окна, которое менеджер окон высвечивает на рамке окна. В +этом случае команда возвращает рустую строку. Если аргумент +string не задан, команда возвращает ранее установленный +заголовок. По умолчанию титул окна совпадает с его полным именем как виджета. +
    + +

    wm transient window master
    + +

    Если аргумент master задан, команда +передает менеджеру окон информацию о том, что окно window +является временным окном (например, выпадающим меню), работающим +под управлением master-окна (где master полное имя +toplevel-окна). Некоторые менеджеры окон используют эту +информацию для того, чтобы управлять таким окном специальным +образом. Если аргумент master представляет собой пустую +строку, окно перестает быть временным окном. +
    Если аргумент master задан, команда возвращает пустую +строку. В противном случае она возвращает имя управляющего окна +или пустую строку, если окно window не является временным. +
    + +

    wm withdraw window
    + +

    При выполнении команды окно window +удаляется с экрана. Информация о нем удаляется из менеджера окон. +Если окно не присутствовало на экране ранее, оно не появится на +экране при создании. Но не все менеджеры окон знают, как работать с такими окнами! +
    + +

    Замечание. Иногда оказывается необходимым удалить +окно с помощью команды wm withdraw, а затем возвратить его +обратно на экран (например, с помощью команды wm deiconify), чтобы менеджер окон учитывал некоторые его атрибуты, например, группу. +
    +
    + +

    УПРАВЛЕНИЕ ГЕОМЕТРИЕЙ + +

    По умолчанию toplevel-окна при появлении на +экране имеют размеры, определяемые размерами составляющих его +виджетов (.естественные. размеры). Если изменяются размеры или +состав виджетов, то изменяется и размер toplevel-окна. Для +toplevel-окна размеры, отличные от .естественных., могут быть +заданы двумя способами. Первый пользователь может изменить +размеры окна вручную, используя стандартные механизмы менеджера +окон. Второй приложение может запросить изменение размеров окна с +помощью команды wm geometry. Оба зти способа +обрабатываются в Tk единообразно. Размеры окна изменяются на +новые, отличные от .естественных.. Чтобы вернуть .естественные. +размеры окна, нужно выполнить команду wm geometry с пустой +строкой в качестве аргумента, задающего размеры и размещение окна. + +

    Обычно размеры окна могут изменяться произвольно в диапазоне +от 1 пикселя до размеров экрана. Однако, с помощью команд wm +minsize и wm maxsize можно изменить область +возможных размеров окна. Эти ограничения будут использоваться при +всех способах изменения размеров окна, в том числе и при ручном +изменении, и при изменении размеров и состава его виджетов, +приводящем к изменению его .естественных. размеров. С помощью +команды wm resizable можно полностью запретить изменение +размеров окна каким-либо способом в одном или в обоих направлениях.

    + + +

    УПРАВЛЕНИЕ ОКНАМИ С СЕТКОЙ + +

    Окна с сеткой используются, если один из виджетов +окна имеет ограниченное множество .разумных. размеров. Например, +в текстовом редакторе, где полосы прокрутки, меню и т. д. имеют +фиксированный размер, а поле редактирования текста может +содержать произвольное число строк или букв в строке. В этом +случае желательно дать пользователю возможность устанавливать +непосредственно число строк или букв в строке при изменении +размеров окна как вручную, так и с помощью команды wm +geometry. Как в случае с текстом, так и в других аналогичных, +.разумным. является не всякий размер окна в пикселях, а только +размеры, соответствующие целому числу строк или букв в строке. + +

    Введение сетки обеспечивает механизм для реализации этих +требований. Tk (и менеджер окон) предполагают существование сетки +в окне, и что .разумными. являются только размеры, выраженные в +целых шагах сетки, а не в произвольном числе пикселей. Обычно +сетка устанавливается с помощью опции setGrid для +соответствующего виджета. Она может также устанавливаться с +помощью команды wm grid. В любом случае с помощью виджета +или кода приложения определяются размеры окна в пикселях, +соответствующие целым размерам в шагах сетки. Чтобы отменить +сетку, нужно выполнить команду wm grid с пустой строкой, задающей сетку.

    + +

    Если сетка задана, все определения размеров в командах +wm minsize, wm maxsize и wm geometry +считаются заданными в шагах сетки, а не в пикселях. Ручное +изменение размеров окна также производится в целых шагах сетки.

    + +

    ОШИБКИ + +

    Как оказалось, большинство существующих менеджеров окон имеют некоторые ошибки, которые проявляются при выполнении команды wm. Например, некоторые изменения не производятся в окне, если оно активно. Окно должно быть выведено с экрана и возвращено обратно, чтобы изменения выполнились. + +

    ПРИМЕР +

    +
    wm geometry . 750x550+0+0 - устанавливает размер окна
    +
    wm title . "Tcl/Tk Project Manager" - заголовок окна
    +
    wm iconname . "Tcl/Tk Project Manager" - подпись для икнонки
    +
    wm protocol . wm_DELETE_WINDOW Quit - процедура выполняема по закрытии окна
    +
    wm overrideredirect . 0
    +
    wm positionfrom . user - установка позиции окна
    +
    wm resizable . 0 0 - установка атрибутов окна (в данном случае не изменяемое)
    +
    + + + + + diff --git a/html_lib.tcl b/html_lib.tcl new file mode 100644 index 0000000..d9a6f44 --- /dev/null +++ b/html_lib.tcl @@ -0,0 +1,1437 @@ +# Simple HTML display library by Stephen Uhler (stephen.uhler@sun.com) +# Copyright (c) 1995 by Sun Microsystems +# Version 0.3 Fri Sep 1 10:47:17 PDT 1995 +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# To use this package, create a text widget (say, .text) +# and set a variable full of html, (say $html), and issue: +# HM::init_win .text +# HM::parse_html $html "HM::render .text" +# You also need to supply the routine: +# proc HM::link_callback {win href} { ...} +# win: The name of the text widget +# href The name of the link +# which will be called anytime the user "clicks" on a link. +# !!! Use HM::set_link_callback !!! +# The supplied version just prints the link to stdout. +# In addition, if you wish to use embedded images, you will need to write +# proc HM::set_image {handle src} +# handle an arbitrary handle (not really) +# src The name of the image +# Which calls +# HM::got_image $handle $image +# with the TK image. +# +# To return a "used" text widget to its initialized state, call: +# HM::reset_win .text +# See "sample.tcl" for sample usage +################################################################## +############################################ +# mapping of html tags to text tag properties +# properties beginning with "T" map directly to text tags + +namespace eval HM { +} + +# These are Defined in HTML 2.0 + +proc HM::init_array {} { + global HM::tag_map HM::insert_map HM::list_elements HM::param_map + global HM::events HM::esc_map HM::form_map HM::proc_link_callback + +array set HM::tag_map { + b {weight bold} + blockquote {style i indent 1 Trindent rindent} + bq {style i indent 1 Trindent rindent} + cite {style i} + code {family courier} + dfn {style i} + dir {indent 1} + dl {indent 1} + em {style i} + h1 {size 24 weight bold} + h2 {size 22} + h3 {size 20} + h4 {size 18} + h5 {size 16} + h6 {style i} + i {style i} + kbd {family courier weight bold} + menu {indent 1} + ol {indent 1} + pre {fill 0 family courier Tnowrap nowrap} + samp {family courier} + strong {weight bold} + tt {family courier} + u {Tunderline underline} + ul {indent 1} + var {style i} +} + +# These are in common(?) use, but not defined in html2.0 + +array set HM::tag_map { + center {Tcenter center} + strike {Tstrike strike} + u {Tunderline underline} +} + +# initial values + +set HM::tag_map(hmstart) { + family times weight medium style r size 14 + Tcenter "" Tlink "" Tnowrap "" Tunderline "" list list + fill 1 indent "" counter 0 adjust 0 +} + +# html tags that insert white space + +array set HM::insert_map { + blockquote "\n\n" /blockquote "\n" + br "\n" + dd "\n" /dd "\n" + dl "\n" /dl "\n" + dt "\n" + form "\n" /form "\n" + h1 "\n\n" /h1 "\n" + h2 "\n\n" /h2 "\n" + h3 "\n\n" /h3 "\n" + h4 "\n" /h4 "\n" + h5 "\n" /h5 "\n" + h6 "\n" /h6 "\n" + li "\n" + /dir "\n" + /ul "\n" + /ol "\n" + /menu "\n" + p "\n\n" + pre "\n" /pre "\n" +} + +# tags that are list elements, that support "compact" rendering + +array set HM::list_elements { + ol 1 ul 1 menu 1 dl 1 dir 1 +} + +# alter the parameters of the text state +# this allows an application to over-ride the default settings +# it is called as: HM::set_state -param value -param value ... + +array set HM::param_map { + -update S_update + -tab S_tab + -unknown S_unknown + -stop S_stop + -size S_adjust_size + -symbols S_symbols + -insert S_insert +} + +array set HM::events { + Enter {-borderwidth 2 -relief flat -underline 1} + Leave {-borderwidth 2 -relief flat -underline 0} + 1 {-borderwidth 2 -relief sunken} + ButtonRelease-1 {-borderwidth 2 -relief flat} +} + +# table of escape characters (ISO latin-1 esc's are in a different table) + +array set HM::esc_map { + lt < gt > amp & quot \" copy \xa9 + reg \xae ob \x7b cb \x7d nbsp \xa0 +} +############################################################# +# ISO Latin-1 escape codes + +array set HM::esc_map { + nbsp \xa0 iexcl \xa1 cent \xa2 pound \xa3 curren \xa4 + yen \xa5 brvbar \xa6 sect \xa7 uml \xa8 copy \xa9 + ordf \xaa laquo \xab not \xac shy \xad reg \xae + hibar \xaf deg \xb0 plusmn \xb1 sup2 \xb2 sup3 \xb3 + acute \xb4 micro \xb5 para \xb6 middot \xb7 cedil \xb8 + sup1 \xb9 ordm \xba raquo \xbb frac14 \xbc frac12 \xbd + frac34 \xbe iquest \xbf Agrave \xc0 Aacute \xc1 Acirc \xc2 + Atilde \xc3 Auml \xc4 Aring \xc5 AElig \xc6 Ccedil \xc7 + Egrave \xc8 Eacute \xc9 Ecirc \xca Euml \xcb Igrave \xcc + Iacute \xcd Icirc \xce Iuml \xcf ETH \xd0 Ntilde \xd1 + Ograve \xd2 Oacute \xd3 Ocirc \xd4 Otilde \xd5 Ouml \xd6 + times \xd7 Oslash \xd8 Ugrave \xd9 Uacute \xda Ucirc \xdb + Uuml \xdc Yacute \xdd THORN \xde szlig \xdf agrave \xe0 + aacute \xe1 acirc \xe2 atilde \xe3 auml \xe4 aring \xe5 + aelig \xe6 ccedil \xe7 egrave \xe8 eacute \xe9 ecirc \xea + euml \xeb igrave \xec iacute \xed icirc \xee iuml \xef + eth \xf0 ntilde \xf1 ograve \xf2 oacute \xf3 ocirc \xf4 + otilde \xf5 ouml \xf6 divide \xf7 oslash \xf8 ugrave \xf9 + uacute \xfa ucirc \xfb uuml \xfc yacute \xfd thorn \xfe + yuml \xff +} + +########################################################## +# html forms management commands + +# As each form element is located, it is created and rendered. Additional +# state is stored in a form specific global variable to be processed at +# the end of the form, including the "reset" and "submit" options. +# Remember, there can be multiple forms existing on multiple pages. When +# HTML tables are added, a single form could be spread out over multiple +# text widgets, which makes it impractical to hang the form state off the +# HM::$win structure. We don't need to check for the existance of required +# parameters, we just "fail" and get caught in HM::render + +# This causes line breaks to be preserved in the inital values +# of text areas +array set HM::tag_map { + textarea {fill 0} +} + +# These are handled specially +array set HM::form_map { + " " + \n %0d%0a +} + +} +############################################ +# initialize the window and stack state + +proc HM::init_win {win} { + HM::init_array + upvar #0 HM::$win var + + HM::init_state $win + $win tag configure underline -underline 1 + $win tag configure center -justify center + $win tag configure nowrap -wrap none + $win tag configure rindent -rmargin $var(S_tab)c + $win tag configure strike -overstrike 1 + $win tag configure mark -foreground red ;# list markers + $win tag configure list -spacing1 3p -spacing3 3p ;# regular lists + $win tag configure compact -spacing1 0p ;# compact lists + $win tag configure link -borderwidth 0 -foreground blue;# hypertext links + HM::set_indent $win $var(S_tab) + $win configure -wrap word + + # configure the text insertion point + $win mark set $var(S_insert) 1.0 + + # for horizontal rules + $win tag configure thin -font [HM::x_font times 2 medium r] + $win tag configure hr -relief sunken -borderwidth 2 -wrap none \ + -tabs [winfo width $win] + bind $win { + %W tag configure hr -tabs %w + %W tag configure last -spacing3 %h + } + + # generic link enter callback + + $win tag bind link <1> "HM::link_hit $win %x %y" +} + +proc HM::set_link_callback {name} { + global HM::proc_link_callback + set HM::proc_link_callback $name +} + +# set the indent spacing (in cm) for lists +# TK uses a "weird" tabbing model that causes \t to insert a single +# space if the current line position is past the tab setting + +proc HM::set_indent {win cm} { + set tabs [expr $cm / 2.0] + $win configure -tabs ${tabs}c + foreach i {1 2 3 4 5 6 7 8 9} { + set tab [expr $i * $cm] + $win tag configure indent$i -lmargin1 ${tab}c -lmargin2 ${tab}c \ + -tabs "[expr $tab + $tabs]c [expr $tab + 2*$tabs]c" + } +} + +# reset the state of window - get ready for the next page +# remove all but the font tags, and remove all form state + +proc HM::reset_win {win} { + upvar #0 HM::$win var + regsub -all { +[^L ][^ ]*} " [$win tag names] " {} tags + catch "$win tag delete $tags" + eval $win mark unset [$win mark names] + $win delete 0.0 end + $win tag configure hr -tabs [winfo width $win] + + # configure the text insertion point + $win mark set $var(S_insert) 1.0 + + # remove form state. If any check/radio buttons still exists, + # their variables will be magically re-created, and never get + # cleaned up. + catch unset [info globals HM::$win.form*] + + HM::init_state $win + return HM::$win +} + +# initialize the window's state array +# Parameters beginning with S_ are NOT reset +# adjust_size: global font size adjuster +# unknown: character to use for unknown entities +# tab: tab stop (in cm) +# stop: enabled to stop processing +# update: how many tags between update calls +# tags: number of tags processed so far +# symbols: Symbols to use on un-ordered lists + +proc HM::init_state {win} { + upvar #0 HM::$win var + array set tmp [array get var S_*] + catch {unset var} + array set var { + stop 0 + tags 0 + fill 0 + list list + S_adjust_size 0 + S_tab 1.0 + S_unknown \xb7 + S_update 10 + S_symbols O*=+-o\xd7\xb0>:\xb7 + S_insert Insert + } + array set var [array get tmp] +} + +proc HM::set_state {win args} { + upvar #0 HM::$win var + global HM::param_map + set bad 0 + if {[catch {array set params $args}]} {return 0} + foreach i [array names params] { + incr bad [catch {set var($HM::param_map($i)) $params($i)}] + } + return [expr $bad == 0] +} + +############################################ +# manage the display of html + +# HM::render gets called for every html tag +# win: The name of the text widget to render into +# tag: The html tag (in arbitrary case) +# not: a "/" or the empty string +# param: The un-interpreted parameter list +# text: The plain text until the next html tag + +proc HM::render {win tag not param text} { + upvar #0 HM::$win var + if {$var(stop)} return + global HM::tag_map HM::insert_map HM::list_elements + set tag [string tolower $tag] + set text [HM::map_esc $text] + + # manage compact rendering of lists + if {[info exists HM::list_elements($tag)]} { + set list "list [expr {[HM::extract_param $param compact] ? "compact" : "list"}]" + } else { + set list "" + } + + # Allow text to be diverted to a different window (for tables) + # this is not currently used + if {[info exists var(divert)]} { + set win $var(divert) + upvar #0 HM::$win var + } + + # adjust (push or pop) tag state + catch {HM::stack $win $not "$HM::tag_map($tag) $list"} + + # insert white space (with current font) + # adding white space can get a bit tricky. This isn't quite right + set bad [catch {$win insert $var(S_insert) $HM::insert_map($not$tag) "space $var(font)"}] + if {!$bad && [lindex $var(fill) end]} { + set text [string trimleft $text] + } + + # to fill or not to fill + if {[lindex $var(fill) end]} { + set text [HM::zap_white $text] + } + + # generic mark hook + catch {HM::mark $not$tag $win $param text} err + + # do any special tag processing + catch {HM::tag_$not$tag $win $param text} msg + + + # add the text with proper tags + + set tags [HM::current_tags $win] + $win insert $var(S_insert) $text $tags + + # We need to do an update every so often to insure interactive response. + # This can cause us to re-enter the event loop, and cause recursive + # invocations of HM::render, so we need to be careful. + if {!([incr var(tags)] % $var(S_update))} { + update + } +} + +# html tags requiring special processing +# Procs of the form HM::tag_ or HM::tag_ get called just before +# the text for this tag is displayed. These procs are called inside a +# "catch" so it is OK to fail. +# win: The name of the text widget to render into +# param: The un-interpreted parameter list +# text: A pass-by-reference name of the plain text until the next html tag +# Tag commands may change this to affect what text will be inserted +# next. + +# A pair of pseudo tags are added automatically as the 1st and last html +# tags in the document. The default is and . +# Append enough blank space at the end of the text widget while +# rendering so HM::goto can place the target near the top of the page, +# then remove the extra space when done rendering. + +proc HM::tag_hmstart {win param text} { + upvar #0 HM::$win var + $win mark gravity $var(S_insert) left + $win insert end "\n " last + $win mark gravity $var(S_insert) right +} + +proc HM::tag_/hmstart {win param text} { + $win delete last.first end +} + +# put the document title in the window banner, and remove the title text +# from the document + +proc HM::tag_title {win param text} { + upvar $text data + wm title [winfo toplevel $win] $data + set data "" +} + +proc HM::tag_hr {win param text} { + upvar #0 HM::$win var + $win insert $var(S_insert) "\n" space "\n" thin "\t" "thin hr" "\n" thin +} + +# list element tags + +proc HM::tag_ol {win param text} { + upvar #0 HM::$win var + set var(count$var(level)) 0 +} + +proc HM::tag_ul {win param text} { + upvar #0 HM::$win var + catch {unset var(count$var(level))} +} + +proc HM::tag_menu {win param text} { + upvar #0 HM::$win var + set var(menu) -> + set var(compact) 1 +} + +proc HM::tag_/menu {win param text} { + upvar #0 HM::$win var + catch {unset var(menu)} + catch {unset var(compact)} +} + +proc HM::tag_dt {win param text} { + upvar #0 HM::$win var + upvar $text data + set level $var(level) + incr level -1 + $win insert $var(S_insert) "$data" \ + "hi [lindex $var(list) end] indent$level $var(font)" + set data {} +} + +proc HM::tag_li {win param text} { + upvar #0 HM::$win var + set level $var(level) + incr level -1 + set x [string index $var(S_symbols)+-+-+-+-" $level] + catch {set x [incr var(count$level)]} + catch {set x $var(menu)} + $win insert $var(S_insert) \t$x\t "mark [lindex $var(list) end] indent$level $var(font)" +} + +# Manage hypertext "anchor" links. A link can be either a source (href) +# a destination (name) or both. If its a source, register it via a callback, +# and set its default behavior. If its a destination, check to see if we need +# to go there now, as a result of a previous HM::goto request. If so, schedule +# it to happen with the closing tag, so we can highlight the text up to +# the . + +proc HM::tag_a {win param text} { + upvar #0 HM::$win var + + # a source + + if {[HM::extract_param $param href]} { + set var(Tref) [list L:$href] + HM::stack $win "" "Tlink link" + HM::link_setup $win $href + } + + # a destination + + if {[HM::extract_param $param name]} { + set var(Tname) [list N:$name] + HM::stack $win "" "Tanchor anchor" + $win mark set N:$name "$var(S_insert) - 1 chars" + $win mark gravity N:$name left + if {[info exists var(goto)] && $var(goto) == $name} { + unset var(goto) + set var(going) $name + } + } +} + +# The application should call here with the fragment name +# to cause the display to go to this spot. +# If the target exists, go there (and do the callback), +# otherwise schedule the goto to happen when we see the reference. + +proc HM::goto {win where {callback HM::went_to}} { + upvar #0 HM::$win var + if {[regexp N:$where [$win mark names]]} { + $win see N:$where + update + eval $callback $win [list $where] + return 1 + } else { + set var(goto) $where + return 0 + } +} + +# We actually got to the spot, so highlight it! +# This should/could be replaced by the application +# We'll flash it orange a couple of times. + +proc HM::went_to {win where {count 0} {color orange}} { + upvar #0 HM::$win var + if {$count > 5} return + catch {$win tag configure N:$where -foreground $color} + update + after 200 [list HM::went_to $win $where [incr count] \ + [expr {$color=="orange" ? "" : "orange"}]] +} + +proc HM::tag_/a {win param text} { + upvar #0 HM::$win var + if {[info exists var(Tref)]} { + unset var(Tref) + HM::stack $win / "Tlink link" + } + + # goto this link, then invoke the call-back. + + if {[info exists var(going)]} { + $win yview N:$var(going) + update + HM::went_to $win $var(going) + unset var(going) + } + + if {[info exists var(Tname)]} { + unset var(Tname) + HM::stack $win / "Tanchor anchor" + } +} + +# Inline Images +# This interface is subject to change +# Most of the work is getting around a limitation of TK that prevents +# setting the size of a label to a widthxheight in pixels +# +# Images have the following parameters: +# align: top,middle,bottom +# alt: alternate text +# ismap: A clickable image map +# src: The URL link +# Netscape supports (and so do we) +# width: A width hint (in pixels) +# height: A height hint (in pixels) +# border: The size of the window border + +proc HM::tag_img {win param text} { + upvar #0 HM::$win var + + # get alignment + array set align_map {top top middle center bottom bottom} + set align bottom ;# The spec isn't clear what the default should be + HM::extract_param $param align + catch {set align $align_map([string tolower $align])} + + # get alternate text + set alt "" + HM::extract_param $param alt + set alt [HM::map_esc $alt] + + # get the border width + set border 1 + HM::extract_param $param border + + # see if we have an image size hint + # If so, make a frame the "hint" size to put the label in + # otherwise just make the label + set item $win.$var(tags) + # catch {destroy $item} + if {[HM::extract_param $param width] && [HM::extract_param $param height]} { + frame $item -width $width -height $height + pack propagate $item 0 + set label $item.label + label $label + pack $label -expand 1 -fill both + } else { + set label $item + label $label + } + + $label configure -relief ridge -fg orange -text $alt + catch {$label configure -bd $border} + $win window create $var(S_insert) -align $align -window $item -pady 2 -padx 2 + + # add in all the current tags (this is overkill) + set tags [HM::current_tags $win] + foreach tag $tags { + $win tag add $tag $item + } + + # set imagemap callbacks + if {[HM::extract_param $param ismap]} { + # regsub -all {[^L]*L:([^ ]*).*} $tags {\1} link + set link [lindex $tags [lsearch -glob $tags L:*]] + regsub L: $link {} link + global HM::events + regsub -all {%} $link {%%} link2 + foreach i [array names HM::events] { + bind $label <$i> "catch \{%W configure $HM::events($i)\}" + } + bind $label <1> "+HM::link_callback $win $link2?%x,%y" + } + + # now callback to the application + set src "" + HM::extract_param $param src + HM::set_image $win $label $src + return $label ;# used by the forms package for input_image types +} + +# The app needs to supply one of these +proc HM::set_image {win handle src} { + HM::got_image $handle "can't get\n$src" +} + +# When the image is available, the application should call back here. +# If we have the image, put it in the label, otherwise display the error +# message. If we don't get a callback, the "alt" text remains. +# if we have a clickable image, arrange for a callback + +proc HM::got_image {win image_error} { + # if we're in a frame turn on geometry propogation + if {[winfo name $win] == "label"} { + pack propagate [winfo parent $win] 1 + } + if {[catch {$win configure -image $image_error}]} { + $win configure -image {} + $win configure -text $image_error + } +} + +# Sample hypertext link callback routine - should be replaced by app +# This proc is called once for each tag. +# Applications can overwrite this procedure, as required, or +# replace the HM::events array +# win: The name of the text widget to render into +# href: The HREF link for this tag. + +# We need to escape any %'s in the href tag name so the bind command +# doesn't try to substitute them. + +proc HM::link_setup {win href} { + global HM::events + regsub -all {%} $href {%%} href2 + foreach i [array names HM::events] { + eval {$win tag bind L:$href <$i>} \ + \{$win tag configure \{L:$href2\} $HM::events($i)\} + } +} + +# generic link-hit callback +# This gets called upon button hits on hypertext links +# Applications are expected to supply ther own HM::link_callback routine +# win: The name of the text widget to render into +# x,y: The cursor position at the "click" + +proc HM::link_hit {win x y} { + set tags [$win tag names @$x,$y] + set link [lindex $tags [lsearch -glob $tags L:*]] + # regsub -all {[^L]*L:([^ ]*).*} $tags {\1} link + regsub L: $link {} link + HM::link_callback $win $link +} + +# replace this! +# win: The name of the text widget to render into +# href: The HREF link for this tag. + +proc HM::link_callback {win href} { + if {$HM::proc_link_callback != ""} { + $HM::proc_link_callback $win $href + } +} + +# extract a value from parameter list (this needs a re-do) +# returns "1" if the keyword is found, "0" otherwise +# param: A parameter list. It should alredy have been processed to +# remove any entity references +# key: The parameter name +# val: The variable to put the value into (use key as default) + +proc HM::extract_param {param key {val ""}} { + + if {$val == ""} { + upvar $key result + } else { + upvar $val result + } + set ws " \n\r" + + # look for name=value combinations. Either (') or (") are valid delimeters + if { + [regsub -nocase [format {.*%s[%s]*=[%s]*"([^"]*).*} $key $ws $ws] $param {\1} value] || + [regsub -nocase [format {.*%s[%s]*=[%s]*'([^']*).*} $key $ws $ws] $param {\1} value] || + [regsub -nocase [format {.*%s[%s]*=[%s]*([^%s]+).*} $key $ws $ws $ws] $param {\1} value] } { + set result $value + return 1 + } + + # now look for valueless names + # I should strip out name=value pairs, so we don't end up with "name" + # inside the "value" part of some other key word - some day + + set bad \[^a-zA-Z\]+ + if {[regexp -nocase "$bad$key$bad" -$param-]} { + return 1 + } else { + return 0 + } +} + +# These next two routines manage the display state of the page. + +# Push or pop tags to/from stack. +# Each orthogonal text property has its own stack, stored as a list. +# The current (most recent) tag is the last item on the list. +# Push is {} for pushing and {/} for popping + +proc HM::stack {win push list} { + upvar #0 HM::$win var + array set tags $list + if {$push == ""} { + foreach tag [array names tags] { + lappend var($tag) $tags($tag) + } + } else { + foreach tag [array names tags] { + # set cnt [regsub { *[^ ]+$} $var($tag) {} var($tag)] + set var($tag) [lreplace $var($tag) end end] + } + } +} + +# extract set of current text tags +# tags starting with T map directly to text tags, all others are +# handled specially. There is an application callback, HM::set_font +# to allow the application to do font error handling + +proc HM::current_tags {win} { + upvar #0 HM::$win var + set font font + foreach i {family size weight style} { + set $i [lindex $var($i) end] + append font :[set $i] + } + set xfont [HM::x_font $family $size $weight $style $var(S_adjust_size)] + HM::set_font $win $font $xfont + set indent [llength $var(indent)] + incr indent -1 + lappend tags $font indent$indent + foreach tag [array names var T*] { + lappend tags [lindex $var($tag) end] ;# test + } + set var(font) $font + set var(xfont) [$win tag cget $font -font] + set var(level) $indent + return $tags +} + +# allow the application to do do better font management +# by overriding this procedure + +proc HM::set_font {win tag font} { + catch {$win tag configure $tag -font $font} msg +} + +# generate an X font name +proc HM::x_font {family size weight style {adjust_size 0}} { + catch {incr size $adjust_size} + return "-*-$family-$weight-$style-normal-*-*-${size}0-*-*-*-*-*-*" +} + +# Optimize HM::render (hee hee) +# This is experimental + +proc HM::optimize {} { + regsub -all "\n\[ \]*#\[^\n\]*" [info body HM::render] {} body + regsub -all ";\[ \]*#\[^\n]*" $body {} body + regsub -all "\n\n+" $body \n body + proc HM::render {win tag not param text} $body +} +############################################ +# Turn HTML into TCL commands +# html A string containing an html document +# cmd A command to run for each html tag found +# start The name of the dummy html start/stop tags + +proc HM::parse_html {html {cmd HM::test_parse} {start hmstart}} { + regsub -all \{ $html {\&ob;} html + regsub -all \} $html {\&cb;} html + set w " \t\r\n" ;# white space + proc cl x {return "\[$x\]"} + set exp <(/?)([HM::cl ^$w>]+)[HM::cl $w]*([HM::cl ^>]*)> + set sub "\}\n$cmd {\\2} {\\1} {\\3} \{" + regsub -all $exp $html $sub html + eval "$cmd {$start} {} {} \{ $html \}" + eval "$cmd {$start} / {} {}" +} + +proc HM::test_parse {command tag slash text_after_tag} { + puts "==> $command $tag $slash $text_after_tag" +} + +# Convert multiple white space into a single space + +proc HM::zap_white {data} { + regsub -all "\[ \t\r\n\]+" $data " " data + return $data +} + +# find HTML escape characters of the form &xxx; + +proc HM::map_esc {text} { + if {![regexp & $text]} {return $text} + regsub -all {([][$\\])} $text {\\\1} new + regsub -all {&#([0-9][0-9]?[0-9]?);?} \ + $new {[format %c [scan \1 %d tmp;set tmp]]} new + regsub -all {&([a-zA-Z]+);?} $new {[HM::do_map \1]} new + return [subst $new] +} + +# convert an HTML escape sequence into character + +proc HM::do_map {text {unknown ?}} { + global HM::esc_map + set result $unknown + catch {set result $HM::esc_map($text)} + return $result +} + +########################################################## +# html isindex tag. Although not strictly forms, they're close enough +# to be in this file + +# is-index forms +# make a frame with a label, entry, and submit button + +proc HM::tag_isindex {win param text} { + upvar #0 HM::$win var + + set item $win.$var(tags) + if {[winfo exists $item]} { + destroy $item + } + frame $item -relief ridge -bd 3 + set prompt "Enter search keywords here" + HM::extract_param $param prompt + label $item.label -text [HM::map_esc $prompt] -font $var(xfont) + entry $item.entry + bind $item.entry "$item.submit invoke" + button $item.submit -text search -font $var(xfont) -command \ + [format {HM::submit_index %s {%s} [HM::map_reply [%s get]]} \ + $win $param $item.entry] + pack $item.label -side top + pack $item.entry $item.submit -side left + + # insert window into text widget + + $win insert $var(S_insert) \n isindex + HM::win_install $win $item + $win insert $var(S_insert) \n isindex + bind $item {focus %W.entry} +} + +# This is called when the isindex form is submitted. +# The default version calls HM::link_callback. Isindex tags should either +# be deprecated, or fully supported (e.g. they need an href parameter) + +proc HM::submit_index {win param text} { + HM::link_callback $win ?$text +} + +# initialize form state. All of the state for this form is kept +# in a global array whose name is stored in the form_id field of +# the main window array. +# Parameters: ACTION, METHOD, ENCTYPE + +proc HM::tag_form {win param text} { + upvar #0 HM::$win var + + # create a global array for the form + set id HM::$win.form$var(tags) + upvar #0 $id form + + # missing /form tag, simulate it + if {[info exists var(form_id)]} { + puts "Missing end-form tag !!!! $var(form_id)" + HM::tag_/form $win {} {} + } + catch {unset form} + set var(form_id) $id + + set form(param) $param ;# form initial parameter list + set form(reset) "" ;# command to reset the form + set form(reset_button) "" ;# list of all reset buttons + set form(submit) "" ;# command to submit the form + set form(submit_button) "" ;# list of all submit buttons +} + +# Where we're done try to get all of the state into the widgets so +# we can free up the form structure here. Unfortunately, we can't! + +proc HM::tag_/form {win param text} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + # make submit button entries for all radio buttons + foreach name [array names form radio_*] { + regsub radio_ $name {} name + lappend form(submit) [list $name \$form(radio_$name)] + } + + # process the reset button(s) + + foreach item $form(reset_button) { + $item configure -command $form(reset) + } + + # no submit button - add one + if {$form(submit_button) == ""} { + HM::input_submit $win {} + } + + # process the "submit" command(s) + # each submit button could have its own name,value pair + + foreach item $form(submit_button) { + set submit $form(submit) + catch {lappend submit $form(submit_$item)} + $item configure -command \ + [list HM::submit_button $win $var(form_id) $form(param) \ + $submit] + } + + # unset all unused fields here + unset form(reset) form(submit) form(reset_button) form(submit_button) + unset var(form_id) +} + +################################################################### +# handle form input items +# each item type is handled in a separate procedure +# Each "type" procedure needs to: +# - create the window +# - initialize it +# - add the "submit" and "reset" commands onto the proper Q's +# "submit" is subst'd +# "reset" is eval'd + +proc HM::tag_input {win param text} { + upvar #0 HM::$win var + + set type text ;# the default + HM::extract_param $param type + set type [string tolower $type] + if {[catch {HM::input_$type $win $param} err]} { + puts stderr $err + } +} + +# input type=text +# parameters NAME (reqd), MAXLENGTH, SIZE, VALUE + +proc HM::input_text {win param {show {}}} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + # make the entry + HM::extract_param $param name ;# required + set item $win.input_text,$var(tags) + set size 20; HM::extract_param $param size + set maxlength 0; HM::extract_param $param maxlength + entry $item -width $size -show $show + + # set the initial value + set value ""; HM::extract_param $param value + $item insert 0 $value + + # insert the entry + HM::win_install $win $item + + # set the "reset" and "submit" commands + append form(reset) ";$item delete 0 end;$item insert 0 [list $value]" + lappend form(submit) [list $name "\[$item get]"] + + # handle the maximum length (broken - no way to cleanup bindtags state) + if {$maxlength} { + bindtags $item "[bindtags $item] max$maxlength" + bind max$maxlength "%W delete $maxlength end" + } +} + +# password fields - same as text, only don't show data +# parameters NAME (reqd), MAXLENGTH, SIZE, VALUE + +proc HM::input_password {win param} { + HM::input_text $win $param * +} + +# checkbuttons are missing a "get" option, so we must use a global +# variable to store the value. +# Parameters NAME, VALUE, (reqd), CHECKED + +proc HM::input_checkbox {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + HM::extract_param $param name + HM::extract_param $param value + + # Set the global variable, don't use the "form" alias as it is not + # defined in the global scope of the button + set variable $var(form_id)(check_$var(tags)) + set item $win.input_checkbutton,$var(tags) + checkbutton $item -variable $variable -off {} -on $value -text " " + if {[HM::extract_param $param checked]} { + $item select + append form(reset) ";$item select" + } else { + append form(reset) ";$item deselect" + } + + HM::win_install $win $item + lappend form(submit) [list $name \$form(check_$var(tags))] +} + +# radio buttons. These are like check buttons, but only one can be selected + +proc HM::input_radio {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + HM::extract_param $param name + HM::extract_param $param value + + set first [expr ![info exists form(radio_$name)]] + set variable $var(form_id)(radio_$name) + set variable $var(form_id)(radio_$name) + set item $win.input_radiobutton,$var(tags) + radiobutton $item -variable $variable -value $value -text " " + + HM::win_install $win $item + + if {$first || [HM::extract_param $param checked]} { + $item select + append form(reset) ";$item select" + } else { + append form(reset) ";$item deselect" + } + + # do the "submit" actions in /form so we only end up with 1 per button grouping + # contributing to the submission +} + +# hidden fields, just append to the "submit" data +# params: NAME, VALUE (reqd) + +proc HM::input_hidden {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + HM::extract_param $param name + HM::extract_param $param value + lappend form(submit) [list $name $value] +} + +# handle input images. The spec isn't very clear on these, so I'm not +# sure its quite right +# Use std image tag, only set up our own callbacks +# (e.g. make sure ismap isn't set) +# params: NAME, SRC (reqd) ALIGN + +proc HM::input_image {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + HM::extract_param $param name + set name ;# barf if no name is specified + set item [HM::tag_img $win $param {}] + $item configure -relief raised -bd 2 -bg blue + + # make a dummy "submit" button, and invoke it to send the form. + # We have to get the %x,%y in the value somehow, so calculate it during + # binding, and save it in the form array for later processing + + set submit $win.dummy_submit,$var(tags) + if {[winfo exists $submit]} { + destroy $submit + } + button $submit -takefocus 0;# this never gets mapped! + lappend form(submit_button) $submit + set form(submit_$submit) [list $name $name.\$form(X).\$form(Y)] + + $item configure -takefocus 1 + bind $item "catch \{$win see $item\}" + bind $item <1> "$item configure -relief sunken" + bind $item " + set $var(form_id)(X) 0 + set $var(form_id)(Y) 0 + $submit invoke + " + bind $item " + set $var(form_id)(X) %x + set $var(form_id)(Y) %y + $item configure -relief raised + $submit invoke + " +} + +# Set up the reset button. Wait for the /form to attach +# the -command option. There could be more that 1 reset button +# params VALUE + +proc HM::input_reset {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + set value reset + HM::extract_param $param value + + set item $win.input_reset,$var(tags) + button $item -text [HM::map_esc $value] + HM::win_install $win $item + lappend form(reset_button) $item +} + +# Set up the submit button. Wait for the /form to attach +# the -command option. There could be more that 1 submit button +# params: NAME, VALUE + +proc HM::input_submit {win param} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + HM::extract_param $param name + set value submit + HM::extract_param $param value + set item $win.input_submit,$var(tags) + button $item -text [HM::map_esc $value] -fg blue + HM::win_install $win $item + lappend form(submit_button) $item + # need to tie the "name=value" to this button + # save the pair and do it when we finish the submit button + catch {set form(submit_$item) [list $name $value]} +} + +######################################################################### +# selection items +# They all go into a list box. We don't what to do with the listbox until +# we know how many items end up in it. Gather up the data for the "options" +# and finish up in the /select tag +# params: NAME (reqd), MULTIPLE, SIZE + +proc HM::tag_select {win param text} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + + HM::extract_param $param name + set size 5; HM::extract_param $param size + set form(select_size) $size + set form(select_name) $name + set form(select_values) "" ;# list of values to submit + if {[HM::extract_param $param multiple]} { + set mode multiple + } else { + set mode single + } + set item $win.select,$var(tags) + frame $item + set form(select_frame) $item + listbox $item.list -selectmode $mode -width 0 -exportselection 0 + HM::win_install $win $item +} + +# select options +# The values returned in the query may be different from those +# displayed in the listbox, so we need to keep a separate list of +# query values. +# form(select_default) - contains the default query value +# form(select_frame) - name of the listbox's containing frame +# form(select_values) - list of query values +# params: VALUE, SELECTED + +proc HM::tag_option {win param text} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + upvar $text data + set frame $form(select_frame) + + # set default option (or options) + if {[HM::extract_param $param selected]} { + lappend form(select_default) [$form(select_frame).list size] + } + set value [string trimright $data " \n"] + $frame.list insert end $value + HM::extract_param $param value + lappend form(select_values) $value + set data "" +} + +# do most of the work here! +# if SIZE>1, make the listbox. Otherwise make a "drop-down" +# listbox with a label in it +# If the # of items > size, add a scroll bar +# This should probably be broken up into callbacks to make it +# easier to override the "look". + +proc HM::tag_/select {win param text} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + set frame $form(select_frame) + set size $form(select_size) + set items [$frame.list size] + + # set the defaults and reset button + append form(reset) ";$frame.list selection clear 0 $items" + if {[info exists form(select_default)]} { + foreach i $form(select_default) { + $frame.list selection set $i + append form(reset) ";$frame.list selection set $i" + } + } else { + $frame.list selection set 0 + append form(reset) ";$frame.list selection set 0" + } + + # set up the submit button. This is the general case. For single + # selections we could be smarter + + for {set i 0} {$i < $size} {incr i} { + set value [format {[expr {[%s selection includes %s] ? {%s} : {}}]} \ + $frame.list $i [lindex $form(select_values) $i]] + lappend form(submit) [list $form(select_name) $value] + } + + # show the listbox - no scroll bar + + if {$size > 1 && $items <= $size} { + $frame.list configure -height $items + pack $frame.list + + # Listbox with scrollbar + + } elseif {$size > 1} { + scrollbar $frame.scroll -command "$frame.list yview" \ + -orient v -takefocus 0 + $frame.list configure -height $size \ + -yscrollcommand "$frame.scroll set" + pack $frame.list $frame.scroll -side right -fill y + + # This is a joke! + + } else { + scrollbar $frame.scroll -command "$frame.list yview" \ + -orient h -takefocus 0 + $frame.list configure -height 1 \ + -yscrollcommand "$frame.scroll set" + pack $frame.list $frame.scroll -side top -fill x + } + + # cleanup + + foreach i [array names form select_*] { + unset form($i) + } +} + +# do a text area (multi-line text) +# params: COLS, NAME, ROWS (all reqd, but default rows and cols anyway) + +proc HM::tag_textarea {win param text} { + upvar #0 HM::$win var + upvar #0 $var(form_id) form + upvar $text data + + set rows 5; HM::extract_param $param rows + set cols 30; HM::extract_param $param cols + HM::extract_param $param name + set item $win.textarea,$var(tags) + frame $item + text $item.text -width $cols -height $rows -wrap none \ + -yscrollcommand "$item.scroll set" -padx 3 -pady 3 + scrollbar $item.scroll -command "$item.text yview" -orient v + $item.text insert 1.0 $data + HM::win_install $win $item + pack $item.text $item.scroll -side right -fill y + lappend form(submit) [list $name "\[$item.text get 0.0 end]"] + append form(reset) ";$item.text delete 1.0 end; \ + $item.text insert 1.0 [list $data]" + set data "" +} + +# procedure to install windows into the text widget +# - win: name of the text widget +# - item: name of widget to install + +proc HM::win_install {win item} { + upvar #0 HM::$win var + $win window create $var(S_insert) -window $item -align bottom + $win tag add indent$var(level) $item + set focus [expr {[winfo class $item] != "Frame"}] + $item configure -takefocus $focus + bind $item "$win see $item" +} + +##################################################################### +# Assemble and submit the query +# each list element in "stuff" is a name/value pair +# - The names are the NAME parameters of the various fields +# - The values get run through "subst" to extract the values +# - We do the user callback with the list of name value pairs + +proc HM::submit_button {win form_id param stuff} { + upvar #0 HM::$win var + upvar #0 $form_id form + set query "" + foreach pair $stuff { + set value [subst [lindex $pair 1]] + if {$value != ""} { + set item [lindex $pair 0] + lappend query $item $value + } + } + # this is the user callback. + HM::submit_form $win $param $query +} + +# sample user callback for form submission +# should be replaced by the application +# Sample version generates a string suitable for http + +proc HM::submit_form {win param query} { + set result "" + set sep "" + foreach i $query { + append result $sep [HM::map_reply $i] + if {$sep != "="} {set sep =} {set sep &} + } + puts $result +} + +# do x-www-urlencoded character mapping +# The spec says: "non-alphanumeric characters are replaced by '%HH'" + +set HM::alphanumeric a-zA-Z0-9 ;# definition of alphanumeric character class +for {set i 1} {$i <= 256} {incr i} { + set c [format %c $i] + if {![string match \[$HM::alphanumeric\] $c]} { + set HM::form_map($c) %[format %.2x $i] + } +} + +# 1 leave alphanumerics characters alone +# 2 Convert every other character to an array lookup +# 3 Escape constructs that are "special" to the tcl parser +# 4 "subst" the result, doing all the array substitutions + +proc HM::map_reply {string} { + global HM::form_map HM::alphanumeric + regsub -all \[^$HM::alphanumeric\] $string {$HM::form_map(&)} string + regsub -all \n $string {\\n} string + regsub -all \t $string {\\t} string + regsub -all {[][{})\\]\)} $string {\\&} string + return [subst $string] +} + +# convert a x-www-urlencoded string int a a list of name/value pairs + +# 1 convert a=b&c=d... to {a} {b} {c} {d}... +# 2, convert + to " " +# 3, convert %xx to char equiv + +proc HM::cgiDecode {data} { + set data [split $data "&="] + foreach i $data { + lappend result [cgiMap $i] + } + return $result +} + +proc HM::cgiMap {data} { + regsub -all {\+} $data " " data + + if {[regexp % $data]} { + regsub -all {([][$\\])} $data {\\\1} data + regsub -all {%([0-9a-fA-F][0-9a-fA-F])} $data {[format %c 0x\1]} data + return [subst $data] + } else { + return $data + } +} + +# There is a bug in the tcl library focus routines that prevents focus +# from every reaching an un-viewable window. Use our *own* +# version of the library routine, until the bug is fixed, make sure we +# over-ride the library version, and not the otherway around + +#auto_load tkFocusOK +#proc tkFocusOK w { +# set code [catch {$w cget -takefocus} value] +# if {($code == 0) && ($value != "")} { +# if {$value == 0} { +# return 0 +# } elseif {$value == 1} { +# return 1 +# } else { +# set value [uplevel #0 $value $w] +# if {$value != ""} { +# return $value +# } +# } +# } +# set code [catch {$w cget -state} value] +# if {($code == 0) && ($value == "disabled")} { +# return 0 +# } +# regexp Key|Focus "[bind $w] [bind [winfo class $w]]" +#} + + diff --git a/img/.xvpics/caml.gif b/img/.xvpics/caml.gif new file mode 100644 index 0000000..f82dfa7 Binary files /dev/null and b/img/.xvpics/caml.gif differ diff --git a/img/.xvpics/fortran.gif b/img/.xvpics/fortran.gif new file mode 100644 index 0000000..6a87c1f Binary files /dev/null and b/img/.xvpics/fortran.gif differ diff --git a/img/.xvpics/perl.gif b/img/.xvpics/perl.gif new file mode 100644 index 0000000..7d57307 Binary files /dev/null and b/img/.xvpics/perl.gif differ diff --git a/img/.xvpics/tcl.gif b/img/.xvpics/tcl.gif new file mode 100644 index 0000000..6b88597 --- /dev/null +++ b/img/.xvpics/tcl.gif @@ -0,0 +1,5 @@ +P7 332 +#IMGINFO:11x13 Indexed (70 bytes) +#END_OF_COMMENTS +11 13 255 +I$IIш╤╤╤IH%I$IIш╤╤╤IH%ю═ю)ж╩ж╤$IIIю)D╩ж╩╤D)Iш═╩ж═юю)ж╩╤ш═╩ж═I$Iш╤╤ш╤╤╤ю)DIю╩╤ш╤╤╤юю═)Ю╩╤I$IIш╤╤╤ю)HI$IIш╤╤╤ю)HI$IIш╤╤╤юю═I$IIш╤╤╤IH%ш╤╤╤I$IIш╤╤ \ No newline at end of file diff --git a/img/.xvpics/tk.gif b/img/.xvpics/tk.gif new file mode 100644 index 0000000..0dc4fba Binary files /dev/null and b/img/.xvpics/tk.gif differ diff --git a/img/archive.gif b/img/archive.gif new file mode 100644 index 0000000..ff40c60 Binary files /dev/null and b/img/archive.gif differ diff --git a/img/archive.png b/img/archive.png new file mode 100644 index 0000000..da8371f Binary files /dev/null and b/img/archive.png differ diff --git a/img/back.gif b/img/back.gif new file mode 100644 index 0000000..1375542 Binary files /dev/null and b/img/back.gif differ diff --git a/img/books.gif b/img/books.gif new file mode 100644 index 0000000..bc5a268 Binary files /dev/null and b/img/books.gif differ diff --git a/img/c.gif b/img/c.gif new file mode 100644 index 0000000..4577b01 Binary files /dev/null and b/img/c.gif differ diff --git a/img/caml.gif b/img/caml.gif new file mode 100644 index 0000000..0564329 Binary files /dev/null and b/img/caml.gif differ diff --git a/img/class.gif b/img/class.gif new file mode 100644 index 0000000..3f716e3 Binary files /dev/null and b/img/class.gif differ diff --git a/img/close.gif b/img/close.gif new file mode 100644 index 0000000..7bf1cd6 Binary files /dev/null and b/img/close.gif differ diff --git a/img/close.png b/img/close.png new file mode 100644 index 0000000..2db97f5 Binary files /dev/null and b/img/close.png differ diff --git a/img/color_selector.gif b/img/color_selector.gif new file mode 100644 index 0000000..d0a911b Binary files /dev/null and b/img/color_selector.gif differ diff --git a/img/copy.gif b/img/copy.gif new file mode 100644 index 0000000..e4557db Binary files /dev/null and b/img/copy.gif differ diff --git a/img/copy.png b/img/copy.png new file mode 100644 index 0000000..15bcb54 Binary files /dev/null and b/img/copy.png differ diff --git a/img/cpp.gif b/img/cpp.gif new file mode 100644 index 0000000..49b75c8 Binary files /dev/null and b/img/cpp.gif differ diff --git a/img/cut.gif b/img/cut.gif new file mode 100644 index 0000000..c489bda Binary files /dev/null and b/img/cut.gif differ diff --git a/img/cut.png b/img/cut.png new file mode 100644 index 0000000..52360a0 Binary files /dev/null and b/img/cut.png differ diff --git a/img/cvs_in.gif b/img/cvs_in.gif new file mode 100644 index 0000000..32148e8 Binary files /dev/null and b/img/cvs_in.gif differ diff --git a/img/cvs_out.gif b/img/cvs_out.gif new file mode 100644 index 0000000..22928ee Binary files /dev/null and b/img/cvs_out.gif differ diff --git a/img/doit.gif b/img/doit.gif new file mode 100644 index 0000000..2ff9dc0 Binary files /dev/null and b/img/doit.gif differ diff --git a/img/doit.png b/img/doit.png new file mode 100644 index 0000000..3ee5d68 Binary files /dev/null and b/img/doit.png differ diff --git a/img/doit_file.gif b/img/doit_file.gif new file mode 100644 index 0000000..70c1f32 Binary files /dev/null and b/img/doit_file.gif differ diff --git a/img/doit_file.png b/img/doit_file.png new file mode 100644 index 0000000..3ee5d68 Binary files /dev/null and b/img/doit_file.png differ diff --git a/img/file.gif b/img/file.gif new file mode 100644 index 0000000..c64635c Binary files /dev/null and b/img/file.gif differ diff --git a/img/folder.gif b/img/folder.gif new file mode 100644 index 0000000..262aed5 Binary files /dev/null and b/img/folder.gif differ diff --git a/img/font_selector.gif b/img/font_selector.gif new file mode 100644 index 0000000..5bb9b3e Binary files /dev/null and b/img/font_selector.gif differ diff --git a/img/fortran.gif b/img/fortran.gif new file mode 100644 index 0000000..111dec4 Binary files /dev/null and b/img/fortran.gif differ diff --git a/img/forward.gif b/img/forward.gif new file mode 100644 index 0000000..9b56ebb Binary files /dev/null and b/img/forward.gif differ diff --git a/img/gtk-floppy.png b/img/gtk-floppy.png new file mode 100644 index 0000000..2e26b56 Binary files /dev/null and b/img/gtk-floppy.png differ diff --git a/img/gtk-revert-to-saved.png b/img/gtk-revert-to-saved.png new file mode 100644 index 0000000..3295025 Binary files /dev/null and b/img/gtk-revert-to-saved.png differ diff --git a/img/help.gif b/img/help.gif new file mode 100644 index 0000000..d770ae0 Binary files /dev/null and b/img/help.gif differ diff --git a/img/help.png b/img/help.png new file mode 100644 index 0000000..6092c21 Binary files /dev/null and b/img/help.png differ diff --git a/img/html.gif b/img/html.gif new file mode 100644 index 0000000..2a7cd9a Binary files /dev/null and b/img/html.gif differ diff --git a/img/icons/large/projman.png b/img/icons/large/projman.png new file mode 100644 index 0000000..61c52dc Binary files /dev/null and b/img/icons/large/projman.png differ diff --git a/img/icons/large/projman.xpm b/img/icons/large/projman.xpm new file mode 100644 index 0000000..27ad420 --- /dev/null +++ b/img/icons/large/projman.xpm @@ -0,0 +1,148 @@ +/* XPM */ +static char * projman_xpm[] = { +"48 48 97 2", +" c None", +". c #122450", +"+ c #A67D28", +"@ c #715D36", +"# c #FFB310", +"$ c #C48F20", +"% c #3A3C45", +"& c #6B5A38", +"* c #D3981C", +"= c #B58624", +"- c #564D3E", +"; c #26304B", +"> c #F0AA14", +", c #896C30", +"' c #97742C", +") c #61543B", +"! c #675739", +"~ c #2A324A", +"{ c #657096", +"] c #B8BCDB", +"^ c #5F6680", +"/ c #E1A118", +"( c #848DB0", +"_ c #31416A", +": c #4D4840", +"< c #AEB3D2", +"[ c #3C4A73", +"} c #273B72", +"| c #3D5394", +"1 c #445897", +"2 c #5869A0", +"3 c #7380AC", +"4 c #6C7AA9", +"5 c #394F8F", +"6 c #203467", +"7 c #6F7A9E", +"8 c #324783", +"9 c #5268AE", +"0 c #8F9AC9", +"a c #B1B6D8", +"b c #6D7EBA", +"c c #5F73B4", +"d c #4B62AB", +"e c #8F96B8", +"f c #555C77", +"g c #2A3B67", +"h c #9DA6CF", +"i c #A4ABD2", +"j c #5B678D", +"k c #28314A", +"l c #6679B7", +"m c #AAB1D5", +"n c #FF0000", +"o c #CE0000", +"p c #595C6B", +"q c #828FC3", +"r c #7484BD", +"s c #BC0000", +"t c #EC0000", +"u c #A50000", +"v c #7D0000", +"w c #5E0000", +"x c #FE0000", +"y c #790000", +"z c #96A0CC", +"A c #FA0000", +"B c #7B89C0", +"C c #FD0000", +"D c #930000", +"E c #3D3E44", +"F c #363A46", +"G c #454342", +"H c #7A6334", +"I c #596DB1", +"J c #475EA5", +"K c #6375B1", +"L c #9E0000", +"M c #364B89", +"N c #7A83A7", +"O c #8895C6", +"P c #243564", +"Q c #A3A9CA", +"R c #192C5B", +"S c #354981", +"T c #4A5A8A", +"U c #435487", +"V c #2F437E", +"W c #2B3F78", +"X c #20315E", +"Y c #99A0C1", +"Z c #979EBF", +"` c #162753", +" . c #273761", +".. c #1A2C57", +"+. c #3E3F44", +"@. c #212D4C", +"#. c #46547B", +" ", +" . . ", +" . + @ . ", +" . + # $ . ", +" % # # & . ", +" . . . * # = . ", +" - ; ; > # $ . ", +" , + . . + # # ' . ", +" , # ) ) ) ) ) # # # ) ", +" ! # # # # # # # # > ~ ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ # # # # # # # $ . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ + # # # # # # / . ", +" . { ] ] ] ] ( { { { { { { { { { { { { { { { { { { { { { { { { _ : , * # # # # ~ ", +" . { ] ] < [ } | 1 2 3 4 2 2 2 1 | | | | | | | | | | | | | | | 5 6 7 7 + # # # @ ", +" . { ] ] { 8 9 0 a 0 b c d d c 9 d d d d d d d d d d d d d d d d d 6 e f > # # = . ", +" . { ] ] g d h i 9 d d d d d d d d d d d d d d d d d d d d d d d d 5 j e ' # # # k ", +" . { ] ] 6 l m 9 d n n n n n o d d d n n n o d d d n o d d d d d d d [ ] p # # # , . ", +" . { ] ] 6 q r d d o s t u v w d d n x v y w d d d n y d d d d d d d [ ] ( = # # / . ", +" . { ] ] 6 z 9 d d d d A v d d d d n v d d d d d d n y d d d d d d d [ ] ] : # # # @ . ", +" . { ] ] 6 r d d d d d n y d d d d n y d d d d d d n y d d d d d d d [ ] ] . * # # / . ", +" . { ] ] 6 B d d d d d n y d d d d n s d d d d d d n s d d d d d d d [ ] ] . @ # # # @ . ", +" . { ] ] 6 b d d d d d n y d d d d C x A n o d d d n t A n n o d d d [ ] ] . . > # # / ~ ", +" . { ] ] 6 d d d d d d o w d d d d d D y y w d d d o y y y y w d d d [ ] ] . . , # # # , . ", +" . { ] ] 6 d d d d d d d d d d d d d d d d d d d d d d d d d d d d d [ ] ] . E # # # # F ", +" . { ] ] 6 d d d d d d d d d d d d d d d d d d d d d d d d d d d d d [ ] ] . . + # # # $ . ", +" . { ] ] 6 d d n x x x x x x x x x x x x x x x x x x x x x x x o d d [ ] ] . G # # # # - ", +" . { ] ] 6 d d d d d d d d d d d d d d d d d d d d d d d d d d d d d [ ] ] . . $ # # # = . ", +" . { ] ] 6 d d d d d d d d d d d d d d d d d d d d d d d d d d d d d [ ] ] . - # @ . = . ", +" . { ] ] 6 d d d d d d d d n n n n n o d d n o d d n s d d d d d d d [ ] ] . . $ . ) k ", +" . { ] ] 6 9 d d d d d d d o s t u v w d d n s d n u d d d d d d d d [ ] ] . F + ) + . ", +" . { ] ] 6 b d d d d d d d d d A v d d d d n t o u d d d d d d d d d [ ] ] . . % H ~ . ", +" . { ] ] 6 l d d d d d d d d d n y d d d d n x o d d d d d d d d d d [ ] ] . ", +" . { ] ] 6 B d d d d d d d d d n y d d d d n u o t d d d d d d d d d [ ] ] . ", +" . { ] ] 6 q I d d d d d d d d n y d d d d n v d t t d d d d d d d J [ ] ] . ", +" . { ] ] _ K z d d d d d d d d o w d d d d o w d d L v d d d d d d M { ] ] . ", +" . { ] ] N } O i r 9 d d d d d d d d d d d d d d d d d d d d d d J P Q ] ] . ", +" . { ] ] ] { R S T T U V V V V V V V V V V V V V V V V V V V V W X Y ] ] ] . ", +" . { ] ] ] ] < e e e e e e e e e e e e e e e e e e e e e e e e e ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] Q Z Z Z Z Z Z Z Z Z . ", +" . . . . . . . . . ` Y ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] .................... ", +" . e ] ] ] j [ Y N [ ( j [ Y ] ] ] ] . ", +" . e ] ] Y +.+ { @./ .+.+ { ] ] ] ] . ", +" . . . . . . . . . . e ] ] ] #. .Y { .N #. .Y ] ] ] ] . . . . . . . . . . . ", +" . [ { { { { { { { { Q ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] { { { { { { { { { { . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . [ { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "}; diff --git a/img/icons/large/tkregexp.xpm b/img/icons/large/tkregexp.xpm new file mode 100644 index 0000000..b58a7a5 --- /dev/null +++ b/img/icons/large/tkregexp.xpm @@ -0,0 +1,194 @@ +/* XPM */ +static char * 2ic_dev_environment_48_xpm[] = { +"48 48 143 2", +" c None", +". c #122450", +"+ c #A67D28", +"@ c #715D36", +"# c #FFB310", +"$ c #C48F20", +"% c #3A3C45", +"& c #6B5A38", +"* c #D3981C", +"= c #B58624", +"- c #564D3E", +"; c #26304B", +"> c #F0AA14", +", c #896C30", +"' c #97742C", +") c #61543B", +"! c #675739", +"~ c #2A324A", +"{ c #657096", +"] c #B8BCDB", +"^ c #5F6680", +"/ c #E1A118", +"( c #848DB0", +"_ c #31416A", +": c #4D4840", +"< c #AEB3D2", +"[ c #3C4A73", +"} c #273B72", +"| c #3D5394", +"1 c #445897", +"2 c #5869A0", +"3 c #7380AC", +"4 c #6C7AA9", +"5 c #394F8F", +"6 c #203467", +"7 c #6F7A9E", +"8 c #324783", +"9 c #5268AE", +"0 c #8F9AC9", +"a c #B1B6D8", +"b c #6D7EBA", +"c c #5F73B4", +"d c #4B62AB", +"e c #8F96B8", +"f c #555C77", +"g c #2A3B67", +"h c #9DA6CF", +"i c #A4ABD2", +"j c #5B678D", +"k c #28314A", +"l c #6679B7", +"m c #AAB1D5", +"n c #787684", +"o c #5667A1", +"p c #A58B5E", +"q c #837B7B", +"r c #595C6B", +"s c #828FC3", +"t c #7484BD", +"u c #B09054", +"v c #9A8567", +"w c #BC954A", +"x c #C79A40", +"y c #6D718E", +"z c #D29F37", +"A c #96A0CC", +"B c #DDA42D", +"C c #E9A923", +"D c #8F8071", +"E c #303648", +"F c #7B89C0", +"G c #675945", +"H c #3C4575", +"I c #373C5E", +"J c #AC802C", +"K c #7A6334", +"L c #DDA025", +"M c #706B90", +"N c #666699", +"O c #625F84", +"P c #534C45", +"Q c #F4AE1A", +"R c #D5991D", +"S c #5E523D", +"T c #F5AE19", +"U c #83747F", +"V c #C69643", +"W c #3D3E44", +"X c #363A46", +"Y c #5C513C", +"Z c #635642", +"` c #BC914C", +" . c #ECA921", +".. c #E2A52A", +"+. c #CF9B3B", +"@. c #BB8928", +"#. c #464A6C", +"$. c #B38D55", +"%. c #454342", +"&. c #F2AB15", +"*. c #374170", +"=. c #C99325", +"-. c #967E6E", +";. c #626C98", +">. c #444458", +",. c #7F6739", +"'. c #735D3E", +"). c #515687", +"!. c #797088", +"~. c #636396", +"{. c #615541", +"]. c #444349", +"^. c #616294", +"/. c #D9A032", +"(. c #343E6D", +"_. c #353A4D", +":. c #B18631", +"<. c #323D6B", +"[. c #3E3F44", +"}. c #705E3D", +"|. c #B98A2A", +"1. c #596DB1", +"2. c #475EA5", +"3. c #6375B1", +"4. c #364B89", +"5. c #7A83A7", +"6. c #8895C6", +"7. c #243564", +"8. c #A3A9CA", +"9. c #192C5B", +"0. c #354981", +"a. c #4A5A8A", +"b. c #435487", +"c. c #2F437E", +"d. c #2B3F78", +"e. c #20315E", +"f. c #99A0C1", +"g. c #979EBF", +"h. c #162753", +"i. c #273761", +"j. c #1A2C57", +"k. c #212D4C", +"l. c #46547B", +" ", +" . . ", +" . + @ . ", +" . + # $ . ", +" % # # & . ", +" . . . * # = . ", +" - ; ; > # $ . ", +" , + . . + # # ' . ", +" , # ) ) ) ) ) # # # ) ", +" ! # # # # # # # # > ~ ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ # # # # # # # $ . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ + # # # # # # / . ", +" . { ] ] ] ] ( { { { { { { { { { { { { { { { { { { { { { { { { _ : , * # # # # ~ ", +" . { ] ] < [ } | 1 2 3 4 2 2 2 1 | | | | | | | | | | | | | | | 5 6 7 7 + # # # @ ", +" . { ] ] { 8 9 0 a 0 b c d d c 9 d d d d d d d d d d d d d d d d d 6 e f > # # = . ", +" . { ] ] g d h i 9 d d d d d d d d d d d d d d d d d d d d d d d d 5 j e ' # # # k ", +" . { ] ] 6 l m 9 d d d d d d d n d o p q d d d d d d d d d d d d d d [ ] r # # # , . ", +" . { ] ] 6 s t d d d d d d d u # v w # x y z n d d d d d d d d d d d [ ] ( = # # / . ", +" . { ] ] 6 A 9 d d d d n # v B # $ > # # C # D d d d d d d d d d d d [ ] ] : # # # @ . ", +" . { ] ] 6 t d d d d d z # # # $ E $ # # # # z q p o d d d d d d d d [ ] ] . * # # / . ", +" . { ] ] 6 F d d d d d u # # / & G H H I & , : * # D d d d d d d d d [ ] ] . @ # # # @ . ", +" . { ] ] 6 b d d d x u # # J K L M N N N O P K > Q d d d d d d d d d [ ] ] . . > # # / ~ ", +" . { ] ] 6 d d d d # # # R S # T M N N N N U & / # x z n d d d d d d [ ] ] . . , # # # , . ", +" . { ] ] 6 d d d d w $ ' S > # # V N N N N N L K # # # D d d d d d d [ ] ] . W # # # # X ", +" . { ] ] 6 d d d d n , Y Z ` ` .# ..* ` U +.# K # # q d d d d d d d [ ] ] . . + # # # $ . ", +" . { ] ] 6 d d d x # # @.#.N N N $.' . $ # # # = + $ x n o d d d d d [ ] ] . %.# # # # - ", +" . { ] ] 6 d d d z # # &.*.N N N M =., L -.` .$ : E # # y d d d d d [ ] ] . . $ # # # = . ", +" . { ] ] 6 d d d ;.n # # >.N N N N +.V M N N M ,.* $ p n d d d d d d [ ] ] . - # @ . = . ", +" . { ] ] 6 d d d d d Q # '.).N N !.# $.N N N ~.{.# # p d d d d d d d [ ] ] . . $ . ) k ", +" . { ] ] 6 9 d d d D # # &.].^.N /.# $.N N N (.* # # # v d d d d d d [ ] ] . X + ) + . ", +" . { ] ] 6 b d d d Q Q # > = _.:.# # +.N ^.<.+ # # u D ;.d d d d d d [ ] ] . . % K ~ . ", +" . { ] ] 6 l d d d d d z $ [.$ + K K , }.[.' # # # x d d d d d d d d [ ] ] . ", +" . { ] ] 6 F d d d d d # C |.> # # # # # E ' # w w B d d d d d d d d [ ] ] . ", +" . { ] ] 6 s 1.d d d d p o q # # # # # # # # u d d d d d d d d d d 2.[ ] ] . ", +" . { ] ] _ 3.A d d d d d d p # n ;.# B n u # z d d d d d d d d d d 4.{ ] ] . ", +" . { ] ] 5.} 6.i t 9 d d d o D d o x D d o p ;.d d d d d d d d d 2.7.8.] ] . ", +" . { ] ] ] { 9.0.a.a.b.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.d.e.f.] ] ] . ", +" . { ] ] ] ] < e e e e e e e e e e e e e e e e e e e e e e e e e ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] 8.g.g.g.g.g.g.g.g.g.. ", +" . . . . . . . . . h.f.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] i.j.j.j.j.j.j.j.j.j.. ", +" . e ] ] ] j [ f.5.[ ( j [ f.] ] ] ] . ", +" . e ] ] f.[.+ { k./ i.[.+ { ] ] ] ] . ", +" . . . . . . . . . . e ] ] ] l.i.f.{ i.5.l.i.f.] ] ] ] . . . . . . . . . . . ", +" . [ { { { { { { { { 8.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] { { { { { { { { { { . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . [ { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "}; diff --git a/img/icons/mini/projman.png b/img/icons/mini/projman.png new file mode 100644 index 0000000..7a3ab13 Binary files /dev/null and b/img/icons/mini/projman.png differ diff --git a/img/icons/mini/projman.xpm b/img/icons/mini/projman.xpm new file mode 100644 index 0000000..acce304 --- /dev/null +++ b/img/icons/mini/projman.xpm @@ -0,0 +1,45 @@ +/* XPM */ +static char * projman_xpm[] = { +"32 32 10 1", +" c None", +". c #000000", +"+ c #808080", +"@ c #FFFFFF", +"# c #C0C0C0", +"$ c #800080", +"% c #FF00FF", +"& c #008000", +"* c #00FF00", +"= c #808000", +" ... ++++++++ ", +" +@...@@@@@@@@. ....+ ", +" +@#@@@#######@. .###++. ", +" +##++####+++++@. .@#++++. ", +" +++..++#++....+. .@#+++++. ", +" ... ..#.. . .@#++++++. ", +" .#. .@@#+++++. ", +" .#. .#@#++++++. ", +" +++.. .#. .@#++=++++. ", +" +@#+. $$$ .#@#++++++. ", +" +@#+. $@@@. .@#++.+++++ ", +" +@#+. $@%$. .#@#++++++. ", +" +@#.. $@%$. .@#++.++++. ", +" ... $@%$. .@#++++++. ", +" +#. $@%$. .#@#+.++++. ", +" +@. $@%$. .@#++.+++. ", +" +@. $@%$. .@#++=+++= ", +" +@. $@%$. .@#+.+++. ", +" +#. $@%$. .@#+.+++. ", +" &&. $@%$. .@#+.++. ", +" &@**. $@%$. .+@@#+.+++.. ", +" &@*&. $@%$. .#@@..+++. ", +" &@*&. $@%$. .@@..+++ ", +" &@*&. $@%$. .@..+. ", +" &@*&. $@%$. ........ ", +" &@*&. ... .......... ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" ... . "}; diff --git a/img/icons/mini/tkregexp.xpm b/img/icons/mini/tkregexp.xpm new file mode 100644 index 0000000..63016ba --- /dev/null +++ b/img/icons/mini/tkregexp.xpm @@ -0,0 +1,91 @@ +/* XPM */ +static char * 2ic_dev_environment_16_xpm[] = { +"16 16 72 1", +" c None", +". c #122450", +"+ c #303648", +"@ c #F8AF12", +"# c #3F4044", +"$ c #9D782A", +"% c #212D4C", +"& c #FFB310", +"* c #7A6334", +"= c #3F3F44", +"- c #AEB3D2", +"; c #46547B", +"> c #657096", +", c #505D84", +"' c #3C4A73", +") c #78633D", +"! c #EBA715", +"~ c #745F36", +"{ c #6F7A9E", +"] c #69749B", +"^ c #6D7EBA", +"/ c #4B62AB", +"( c #475EA5", +"_ c #253152", +": c #CD951E", +"< c #5F6FA3", +"[ c #626C98", +"} c #C79A41", +"| c #E8A923", +"1 c #9A8667", +"2 c #5667A1", +"3 c #203467", +"4 c #DFA733", +"5 c #4A5E9A", +"6 c #A6855A", +"7 c #8F7868", +"8 c #8F8071", +"9 c #827D7D", +"0 c #DA9D1A", +"a c #3D5394", +"b c #F4AE1A", +"c c #D9A032", +"d c #BC914C", +"e c #D29F37", +"f c #DE9F19", +"g c #242F4B", +"h c #445897", +"i c #DDA42D", +"j c #736982", +"k c #8C7977", +"l c #E2A52A", +"m c #5C513C", +"n c #F6AD13", +"o c #3E3F44", +"p c #F5AE19", +"q c #C69643", +"r c #E9A61E", +"s c #BB954A", +"t c #3D3E44", +"u c #7A83A7", +"v c #7781AA", +"w c #6679B7", +"x c #737690", +"y c #A58B5D", +"z c #445AA0", +"A c #2A3B67", +"B c #B8BCDB", +"C c #848DB0", +"D c #99A0C1", +"E c #5B678D", +"F c #273761", +"G c #898CA3", +" ... ", +" ..+@# ", +" .$%&* ", +"..........&&&= ", +".-;>>,'''')!&~ ", +".{]^//////(_&:. ", +".>5/}&67&8/39&0.", +".>a/bccd&e/3>f&g", +".>h/ijdkli/3>mno", +".>.t.", +".uvwx}i|y/zA>. ", +".B>>;''''';C>. ", +".>>>BDDDBE''F. ", +".'''BCuGBE''F. ", +".>>>>>>>>>>>'. "}; diff --git a/img/icons/projman.png b/img/icons/projman.png new file mode 100644 index 0000000..7ae5962 Binary files /dev/null and b/img/icons/projman.png differ diff --git a/img/icons/projman.xpm b/img/icons/projman.xpm new file mode 100644 index 0000000..acce304 --- /dev/null +++ b/img/icons/projman.xpm @@ -0,0 +1,45 @@ +/* XPM */ +static char * projman_xpm[] = { +"32 32 10 1", +" c None", +". c #000000", +"+ c #808080", +"@ c #FFFFFF", +"# c #C0C0C0", +"$ c #800080", +"% c #FF00FF", +"& c #008000", +"* c #00FF00", +"= c #808000", +" ... ++++++++ ", +" +@...@@@@@@@@. ....+ ", +" +@#@@@#######@. .###++. ", +" +##++####+++++@. .@#++++. ", +" +++..++#++....+. .@#+++++. ", +" ... ..#.. . .@#++++++. ", +" .#. .@@#+++++. ", +" .#. .#@#++++++. ", +" +++.. .#. .@#++=++++. ", +" +@#+. $$$ .#@#++++++. ", +" +@#+. $@@@. .@#++.+++++ ", +" +@#+. $@%$. .#@#++++++. ", +" +@#.. $@%$. .@#++.++++. ", +" ... $@%$. .@#++++++. ", +" +#. $@%$. .#@#+.++++. ", +" +@. $@%$. .@#++.+++. ", +" +@. $@%$. .@#++=+++= ", +" +@. $@%$. .@#+.+++. ", +" +#. $@%$. .@#+.+++. ", +" &&. $@%$. .@#+.++. ", +" &@**. $@%$. .+@@#+.+++.. ", +" &@*&. $@%$. .#@@..+++. ", +" &@*&. $@%$. .@@..+++ ", +" &@*&. $@%$. .@..+. ", +" &@*&. $@%$. ........ ", +" &@*&. ... .......... ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" &@*&. .. ", +" ... . "}; diff --git a/img/icons/tkregexp.xpm b/img/icons/tkregexp.xpm new file mode 100644 index 0000000..b58a7a5 --- /dev/null +++ b/img/icons/tkregexp.xpm @@ -0,0 +1,194 @@ +/* XPM */ +static char * 2ic_dev_environment_48_xpm[] = { +"48 48 143 2", +" c None", +". c #122450", +"+ c #A67D28", +"@ c #715D36", +"# c #FFB310", +"$ c #C48F20", +"% c #3A3C45", +"& c #6B5A38", +"* c #D3981C", +"= c #B58624", +"- c #564D3E", +"; c #26304B", +"> c #F0AA14", +", c #896C30", +"' c #97742C", +") c #61543B", +"! c #675739", +"~ c #2A324A", +"{ c #657096", +"] c #B8BCDB", +"^ c #5F6680", +"/ c #E1A118", +"( c #848DB0", +"_ c #31416A", +": c #4D4840", +"< c #AEB3D2", +"[ c #3C4A73", +"} c #273B72", +"| c #3D5394", +"1 c #445897", +"2 c #5869A0", +"3 c #7380AC", +"4 c #6C7AA9", +"5 c #394F8F", +"6 c #203467", +"7 c #6F7A9E", +"8 c #324783", +"9 c #5268AE", +"0 c #8F9AC9", +"a c #B1B6D8", +"b c #6D7EBA", +"c c #5F73B4", +"d c #4B62AB", +"e c #8F96B8", +"f c #555C77", +"g c #2A3B67", +"h c #9DA6CF", +"i c #A4ABD2", +"j c #5B678D", +"k c #28314A", +"l c #6679B7", +"m c #AAB1D5", +"n c #787684", +"o c #5667A1", +"p c #A58B5E", +"q c #837B7B", +"r c #595C6B", +"s c #828FC3", +"t c #7484BD", +"u c #B09054", +"v c #9A8567", +"w c #BC954A", +"x c #C79A40", +"y c #6D718E", +"z c #D29F37", +"A c #96A0CC", +"B c #DDA42D", +"C c #E9A923", +"D c #8F8071", +"E c #303648", +"F c #7B89C0", +"G c #675945", +"H c #3C4575", +"I c #373C5E", +"J c #AC802C", +"K c #7A6334", +"L c #DDA025", +"M c #706B90", +"N c #666699", +"O c #625F84", +"P c #534C45", +"Q c #F4AE1A", +"R c #D5991D", +"S c #5E523D", +"T c #F5AE19", +"U c #83747F", +"V c #C69643", +"W c #3D3E44", +"X c #363A46", +"Y c #5C513C", +"Z c #635642", +"` c #BC914C", +" . c #ECA921", +".. c #E2A52A", +"+. c #CF9B3B", +"@. c #BB8928", +"#. c #464A6C", +"$. c #B38D55", +"%. c #454342", +"&. c #F2AB15", +"*. c #374170", +"=. c #C99325", +"-. c #967E6E", +";. c #626C98", +">. c #444458", +",. c #7F6739", +"'. c #735D3E", +"). c #515687", +"!. c #797088", +"~. c #636396", +"{. c #615541", +"]. c #444349", +"^. c #616294", +"/. c #D9A032", +"(. c #343E6D", +"_. c #353A4D", +":. c #B18631", +"<. c #323D6B", +"[. c #3E3F44", +"}. c #705E3D", +"|. c #B98A2A", +"1. c #596DB1", +"2. c #475EA5", +"3. c #6375B1", +"4. c #364B89", +"5. c #7A83A7", +"6. c #8895C6", +"7. c #243564", +"8. c #A3A9CA", +"9. c #192C5B", +"0. c #354981", +"a. c #4A5A8A", +"b. c #435487", +"c. c #2F437E", +"d. c #2B3F78", +"e. c #20315E", +"f. c #99A0C1", +"g. c #979EBF", +"h. c #162753", +"i. c #273761", +"j. c #1A2C57", +"k. c #212D4C", +"l. c #46547B", +" ", +" . . ", +" . + @ . ", +" . + # $ . ", +" % # # & . ", +" . . . * # = . ", +" - ; ; > # $ . ", +" , + . . + # # ' . ", +" , # ) ) ) ) ) # # # ) ", +" ! # # # # # # # # > ~ ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ # # # # # # # $ . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ + # # # # # # / . ", +" . { ] ] ] ] ( { { { { { { { { { { { { { { { { { { { { { { { { _ : , * # # # # ~ ", +" . { ] ] < [ } | 1 2 3 4 2 2 2 1 | | | | | | | | | | | | | | | 5 6 7 7 + # # # @ ", +" . { ] ] { 8 9 0 a 0 b c d d c 9 d d d d d d d d d d d d d d d d d 6 e f > # # = . ", +" . { ] ] g d h i 9 d d d d d d d d d d d d d d d d d d d d d d d d 5 j e ' # # # k ", +" . { ] ] 6 l m 9 d d d d d d d n d o p q d d d d d d d d d d d d d d [ ] r # # # , . ", +" . { ] ] 6 s t d d d d d d d u # v w # x y z n d d d d d d d d d d d [ ] ( = # # / . ", +" . { ] ] 6 A 9 d d d d n # v B # $ > # # C # D d d d d d d d d d d d [ ] ] : # # # @ . ", +" . { ] ] 6 t d d d d d z # # # $ E $ # # # # z q p o d d d d d d d d [ ] ] . * # # / . ", +" . { ] ] 6 F d d d d d u # # / & G H H I & , : * # D d d d d d d d d [ ] ] . @ # # # @ . ", +" . { ] ] 6 b d d d x u # # J K L M N N N O P K > Q d d d d d d d d d [ ] ] . . > # # / ~ ", +" . { ] ] 6 d d d d # # # R S # T M N N N N U & / # x z n d d d d d d [ ] ] . . , # # # , . ", +" . { ] ] 6 d d d d w $ ' S > # # V N N N N N L K # # # D d d d d d d [ ] ] . W # # # # X ", +" . { ] ] 6 d d d d n , Y Z ` ` .# ..* ` U +.# K # # q d d d d d d d [ ] ] . . + # # # $ . ", +" . { ] ] 6 d d d x # # @.#.N N N $.' . $ # # # = + $ x n o d d d d d [ ] ] . %.# # # # - ", +" . { ] ] 6 d d d z # # &.*.N N N M =., L -.` .$ : E # # y d d d d d [ ] ] . . $ # # # = . ", +" . { ] ] 6 d d d ;.n # # >.N N N N +.V M N N M ,.* $ p n d d d d d d [ ] ] . - # @ . = . ", +" . { ] ] 6 d d d d d Q # '.).N N !.# $.N N N ~.{.# # p d d d d d d d [ ] ] . . $ . ) k ", +" . { ] ] 6 9 d d d D # # &.].^.N /.# $.N N N (.* # # # v d d d d d d [ ] ] . X + ) + . ", +" . { ] ] 6 b d d d Q Q # > = _.:.# # +.N ^.<.+ # # u D ;.d d d d d d [ ] ] . . % K ~ . ", +" . { ] ] 6 l d d d d d z $ [.$ + K K , }.[.' # # # x d d d d d d d d [ ] ] . ", +" . { ] ] 6 F d d d d d # C |.> # # # # # E ' # w w B d d d d d d d d [ ] ] . ", +" . { ] ] 6 s 1.d d d d p o q # # # # # # # # u d d d d d d d d d d 2.[ ] ] . ", +" . { ] ] _ 3.A d d d d d d p # n ;.# B n u # z d d d d d d d d d d 4.{ ] ] . ", +" . { ] ] 5.} 6.i t 9 d d d o D d o x D d o p ;.d d d d d d d d d 2.7.8.] ] . ", +" . { ] ] ] { 9.0.a.a.b.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.c.d.e.f.] ] ] . ", +" . { ] ] ] ] < e e e e e e e e e e e e e e e e e e e e e e e e e ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] 8.g.g.g.g.g.g.g.g.g.. ", +" . . . . . . . . . h.f.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] i.j.j.j.j.j.j.j.j.j.. ", +" . e ] ] ] j [ f.5.[ ( j [ f.] ] ] ] . ", +" . e ] ] f.[.+ { k./ i.[.+ { ] ] ] ] . ", +" . . . . . . . . . . e ] ] ] l.i.f.{ i.5.l.i.f.] ] ] ] . . . . . . . . . . . ", +" . [ { { { { { { { { 8.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] { { { { { { { { { { . ", +" . { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] . ", +" . [ { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "}; diff --git a/img/img.gif b/img/img.gif new file mode 100644 index 0000000..b6c4d8c Binary files /dev/null and b/img/img.gif differ diff --git a/img/java.gif b/img/java.gif new file mode 100644 index 0000000..9afd868 Binary files /dev/null and b/img/java.gif differ diff --git a/img/mytcladmin.gif b/img/mytcladmin.gif new file mode 100644 index 0000000..3701661 Binary files /dev/null and b/img/mytcladmin.gif differ diff --git a/img/new.gif b/img/new.gif new file mode 100644 index 0000000..541da4f Binary files /dev/null and b/img/new.gif differ diff --git a/img/new.png b/img/new.png new file mode 100644 index 0000000..33a93be Binary files /dev/null and b/img/new.png differ diff --git a/img/new_html.gif b/img/new_html.gif new file mode 100644 index 0000000..49a3281 Binary files /dev/null and b/img/new_html.gif differ diff --git a/img/new_tcl.gif b/img/new_tcl.gif new file mode 100644 index 0000000..28ae130 Binary files /dev/null and b/img/new_tcl.gif differ diff --git a/img/new_text.gif b/img/new_text.gif new file mode 100644 index 0000000..e28f263 Binary files /dev/null and b/img/new_text.gif differ diff --git a/img/new_tk.gif b/img/new_tk.gif new file mode 100644 index 0000000..4d16584 Binary files /dev/null and b/img/new_tk.gif differ diff --git a/img/newfolder.gif b/img/newfolder.gif new file mode 100644 index 0000000..3a914b4 Binary files /dev/null and b/img/newfolder.gif differ diff --git a/img/old/archive.gif b/img/old/archive.gif new file mode 100644 index 0000000..ff40c60 Binary files /dev/null and b/img/old/archive.gif differ diff --git a/img/old/close.gif b/img/old/close.gif new file mode 100644 index 0000000..7bf1cd6 Binary files /dev/null and b/img/old/close.gif differ diff --git a/img/old/copy.gif b/img/old/copy.gif new file mode 100644 index 0000000..e4557db Binary files /dev/null and b/img/old/copy.gif differ diff --git a/img/old/cut.gif b/img/old/cut.gif new file mode 100644 index 0000000..c489bda Binary files /dev/null and b/img/old/cut.gif differ diff --git a/img/old/doit.gif b/img/old/doit.gif new file mode 100644 index 0000000..2ff9dc0 Binary files /dev/null and b/img/old/doit.gif differ diff --git a/img/old/doit_file.gif b/img/old/doit_file.gif new file mode 100644 index 0000000..70c1f32 Binary files /dev/null and b/img/old/doit_file.gif differ diff --git a/img/old/help.gif b/img/old/help.gif new file mode 100644 index 0000000..d770ae0 Binary files /dev/null and b/img/old/help.gif differ diff --git a/img/old/new.gif b/img/old/new.gif new file mode 100644 index 0000000..541da4f Binary files /dev/null and b/img/old/new.gif differ diff --git a/img/old/paste.gif b/img/old/paste.gif new file mode 100644 index 0000000..56d2047 Binary files /dev/null and b/img/old/paste.gif differ diff --git a/img/old/printer.gif b/img/old/printer.gif new file mode 100644 index 0000000..96322af Binary files /dev/null and b/img/old/printer.gif differ diff --git a/img/old/save.gif b/img/old/save.gif new file mode 100644 index 0000000..549c17f Binary files /dev/null and b/img/old/save.gif differ diff --git a/img/old/save_all.gif b/img/old/save_all.gif new file mode 100644 index 0000000..3500311 Binary files /dev/null and b/img/old/save_all.gif differ diff --git a/img/old/save_as.gif b/img/old/save_as.gif new file mode 100644 index 0000000..be9e8c2 Binary files /dev/null and b/img/old/save_as.gif differ diff --git a/img/open.png b/img/open.png new file mode 100644 index 0000000..66c7c80 Binary files /dev/null and b/img/open.png differ diff --git a/img/openfold.gif b/img/openfold.gif new file mode 100644 index 0000000..fc8adc5 Binary files /dev/null and b/img/openfold.gif differ diff --git a/img/paste.gif b/img/paste.gif new file mode 100644 index 0000000..56d2047 Binary files /dev/null and b/img/paste.gif differ diff --git a/img/paste.png b/img/paste.png new file mode 100644 index 0000000..99dabec Binary files /dev/null and b/img/paste.png differ diff --git a/img/perl.gif b/img/perl.gif new file mode 100644 index 0000000..b0ae951 Binary files /dev/null and b/img/perl.gif differ diff --git a/img/php.gif b/img/php.gif new file mode 100644 index 0000000..6af3cfe Binary files /dev/null and b/img/php.gif differ diff --git a/img/printer.gif b/img/printer.gif new file mode 100644 index 0000000..96322af Binary files /dev/null and b/img/printer.gif differ diff --git a/img/printer.png b/img/printer.png new file mode 100644 index 0000000..57f212d Binary files /dev/null and b/img/printer.png differ diff --git a/img/proc.gif b/img/proc.gif new file mode 100644 index 0000000..621fd53 Binary files /dev/null and b/img/proc.gif differ diff --git a/img/projman.gif b/img/projman.gif new file mode 100644 index 0000000..60b3ce2 Binary files /dev/null and b/img/projman.gif differ diff --git a/img/redo.png b/img/redo.png new file mode 100644 index 0000000..a3a9e25 Binary files /dev/null and b/img/redo.png differ diff --git a/img/refresh.gif b/img/refresh.gif new file mode 100644 index 0000000..9b7e599 Binary files /dev/null and b/img/refresh.gif differ diff --git a/img/refresh.png b/img/refresh.png new file mode 100644 index 0000000..d799126 Binary files /dev/null and b/img/refresh.png differ diff --git a/img/rpm.gif b/img/rpm.gif new file mode 100644 index 0000000..521b468 Binary files /dev/null and b/img/rpm.gif differ diff --git a/img/ruby.gif b/img/ruby.gif new file mode 100644 index 0000000..2fc6d3a Binary files /dev/null and b/img/ruby.gif differ diff --git a/img/rvt.gif b/img/rvt.gif new file mode 100644 index 0000000..abe931b Binary files /dev/null and b/img/rvt.gif differ diff --git a/img/save.gif b/img/save.gif new file mode 100644 index 0000000..549c17f Binary files /dev/null and b/img/save.gif differ diff --git a/img/save.png b/img/save.png new file mode 100644 index 0000000..2e26b56 Binary files /dev/null and b/img/save.png differ diff --git a/img/save_all.gif b/img/save_all.gif new file mode 100644 index 0000000..3500311 Binary files /dev/null and b/img/save_all.gif differ diff --git a/img/save_all.png b/img/save_all.png new file mode 100644 index 0000000..0447fb1 Binary files /dev/null and b/img/save_all.png differ diff --git a/img/save_as.gif b/img/save_as.gif new file mode 100644 index 0000000..be9e8c2 Binary files /dev/null and b/img/save_as.gif differ diff --git a/img/save_as.png b/img/save_as.png new file mode 100644 index 0000000..fae921d Binary files /dev/null and b/img/save_as.png differ diff --git a/img/tcl.gif b/img/tcl.gif new file mode 100644 index 0000000..5f81962 Binary files /dev/null and b/img/tcl.gif differ diff --git a/img/tcl_file.gif b/img/tcl_file.gif new file mode 100644 index 0000000..a39dac3 Binary files /dev/null and b/img/tcl_file.gif differ diff --git a/img/tclhtml.gif b/img/tclhtml.gif new file mode 100644 index 0000000..a578d9b Binary files /dev/null and b/img/tclhtml.gif differ diff --git a/img/tex.gif b/img/tex.gif new file mode 100644 index 0000000..5a2e794 Binary files /dev/null and b/img/tex.gif differ diff --git a/img/text.gif b/img/text.gif new file mode 100644 index 0000000..c64635c Binary files /dev/null and b/img/text.gif differ diff --git a/img/tk.gif b/img/tk.gif new file mode 100644 index 0000000..a7ce73b Binary files /dev/null and b/img/tk.gif differ diff --git a/img/tk_file.gif b/img/tk_file.gif new file mode 100644 index 0000000..a7ce73b Binary files /dev/null and b/img/tk_file.gif differ diff --git a/img/top.gif b/img/top.gif new file mode 100644 index 0000000..76b4cab Binary files /dev/null and b/img/top.gif differ diff --git a/img/undo.png b/img/undo.png new file mode 100644 index 0000000..75ad305 Binary files /dev/null and b/img/undo.png differ diff --git a/img/xml.gif b/img/xml.gif new file mode 100644 index 0000000..b76c025 Binary files /dev/null and b/img/xml.gif differ diff --git a/imgviewer.tcl b/imgviewer.tcl new file mode 100644 index 0000000..8940b61 --- /dev/null +++ b/imgviewer.tcl @@ -0,0 +1,60 @@ +package require Img + + +proc ImageViewer {f w node} { + global tab_label noteBook factor im1 im2 editor + set factor($node) 1.0 + frame $w.f -bg $editor(bg) + pack $w.f -side left -fill both -expand true + canvas $w.f.c -xscrollcommand "$w.f.x set" -yscrollcommand "$w.y set" -bg $editor(bg) + scrollbar $w.f.x -ori hori -command "$w.f.c xview" -bg $editor(bg) + scrollbar $w.y -ori vert -command "$w.f.c yview" -bg $editor(bg) + + pack $w.f.c -side top -fill both -expand true + pack $w.f.x -side top -fill x + pack $w.y -side left -fill y + bind $w.f.c "%W yview scroll -3 units" + bind $w.f.c "%W yview scroll 3 units" + bind $w.f.c "%W xview scroll -2 units" + bind $w.f.c "%W xview scroll 2 units" + bind $w.f.c "scale $w.f.c 0.5 $node" + bind $w.f.c "scale $w.f.c 2 $node" + #$w.scrwin setwidget $w.scrwin.f + openImg $f $w.f.c $node + set tab_label [$noteBook itemcget $node -text] + balloon $w.f.c set "Mouse wheel up/down - vertiсal scrolling the image\n\ + Shift + mouse wheel up/down - horizontal image scrolling\n\ + Control + mouse wheel up/down is a scale image -/+" +} + +proc openImg {fn w node} { + global im1 + set im1 [image create photo -file $fn] + #scale $w + list [file size $fn] bytes, [image width $im1]x[image height $im1] + $w create image 1 1 -image $im1 -anchor nw -tag img +} + +proc scale {w {n 1} node} { + global im1 im2 factor noteBook tab_label + set factor($node) [expr {$factor($node) * $n}] + $w delete img + catch {image delete $im2} + set im2 [image create photo] + if {$factor($node)>=1} { + set f [expr int($factor($node))] + $im2 copy $im1 -zoom $f $f + } else { + set f [expr round(1./$factor($node))] + $im2 copy $im1 -subsample $f $f + } + $w create image 1 1 -image $im2 -anchor nw -tag img + $noteBook itemconfigure $node -text "$tab_label (size x$factor($node))" + $w config -scrollregion [$w bbox all] +} + + + + + + diff --git a/install.tcl b/install.tcl new file mode 100644 index 0000000..6b19602 --- /dev/null +++ b/install.tcl @@ -0,0 +1,394 @@ +#!/usr/bin/wish + +########################################################### +# Tcl/Tk Project Manager # +# install script # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +## SETTING VARIABLES AND DIRECTORYES ## +set ver "0.3.8" +set imgDir img +set msgDir msgs +set docDir hlp +set hlDir highlight +set fontNormal "helvetica 12 normal roman" +package require msgcat +package require BWidget + +::msgcat::mclocale en +::msgcat::mcload msgs + +if {$tcl_platform(platform) == "unix"} { + set initDir "$env(HOME)" + set rootDir "/usr/local" + set tmpDir "$env(HOME)/tmp" + set tclDir "/usr/bin" +} elseif {$tcl_platform(platform) == "windows"} { + set initDir "c:\\" + set rootDir "c:\\Tcl" + set tmpDir "c:\\temp" + set tclDir "C:\\Tcl\\bin" +} + +proc InsertEnt {entry text} { + $entry delete 0 end + $entry insert end $text +} +proc SelectDir {dir} { + set dirName [tk_chooseDirectory -initialdir $dir\ + -title "[::msgcat::mc "Select directory"]"\ + -parent .] + return $dirName +} +## GET HELP DIRECTORYES ## +proc GetHelp {} { + global docDir localeList + set localeList "" + if {[catch {cd $docDir}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *]] { + if {[file isdirectory $file] == 1 && $file != "CVS"} { + lappend localeList [list [file rootname $file]] + } + } + catch {cd ..} + return $localeList +} + +proc GetLocale {} { + global msgDir locList + set locList "" + if {[catch {cd $msgDir}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *.msg]] { + puts $file + if {[file isdirectory $file] == 0} { + puts [file rootname $file] + lappend locList [list [file rootname $file]] + } + } + catch {cd ..} + return $locList +} + +set w . +wm title $w "Install Tcl/Tk Project Manager" +#wm resizable $w 0 0 +#wm geometry $w 400x350 +set top [frame .frmTop -relief groove -borderwidth 1 -background white] +pack $top -fill x + +image create photo imgAbout -format gif -file [file join img projman.gif] +label $top.lblImg -image imgAbout -background white +pack $top.lblImg -side top -pady 5 -padx 5 + +set frm [frame .frmMain -relief groove -borderwidth 1] +pack $frm -expand 1 -fill both + +set btn [frame .frmButton -relief groove -borderwidth 1] +pack $btn -fill x + +image create photo imgFold -format gif -file [file join img folder.gif] + +set frm1 [frame $frm.frmRootDir] +pack $frm1 -fill x -pady 2 +label $frm1.lblRootDir -text "Install dir" -width 23 -anchor w +entry $frm1.txtRootDir +button $frm1.btnRootDir -borderwidth {1} -image imgFold\ +-command { + $frm1.txtRootDir delete 0 end + $frm1.txtRootDir insert end [SelectDir $initDir] +} +pack $frm1.lblRootDir -side left +pack $frm1.txtRootDir -side left -fill x -expand true + +pack $frm1.btnRootDir -side left +set frm4 [frame $frm.frmTclDir] +pack $frm4 -fill x -pady 2 +label $frm4.lblTclDir -text "Tcl bin dir" -width 23 -anchor w +entry $frm4.txtTclDir +button $frm4.btnTclDir -borderwidth {1} -image imgFold\ + -command { + $frm4.txtTclDir delete 0 end + $frm4.txtTclDir insert end [SelectDir $initDir] +} +pack $frm4.lblTclDir -side left +pack $frm4.txtTclDir -side left -fill x -expand true +pack $frm4.btnTclDir -side left + +set frm6 [frame $frm.frmDocLang] +pack $frm6 -fill x -pady 2 +label $frm6.lblLang -text [::msgcat::mc "Documentation language"]\ +-width 23 -anchor w +set combo [ComboBox $frm6.txtLang\ +-textvariable langDoc -command "puts 123"\ +-selectbackground "#55c4d1" -selectborderwidth 0\ +-values [GetHelp]] +pack $frm6.lblLang -side left +pack $frm6.txtLang -side left -fill x -expand true + +set frm7 [frame $frm.frmLocale] +pack $frm7 -fill x -pady 2 +label $frm7.lblLocale -text [::msgcat::mc "Interface language"]\ +-width 23 -anchor w +set comboLocale [ComboBox $frm7.txtLocale\ +-textvariable localeSet -command "puts 123"\ +-selectbackground "#55c4d1" -selectborderwidth 0\ +-values [GetLocale]] +pack $frm7.lblLocale -side left +pack $frm7.txtLocale -side left -fill x -expand true + + +button $btn.btnOk -text "Next" -width 10 -borderwidth {1}\ +-command { + CopyFiles [$frm1.txtRootDir get] [$frm4.txtTclDir get] $langDoc $localeSet +} +button $btn.btnCancel -text "Exit" -width 10 -borderwidth {1}\ +-command {exit} + +pack $btn.btnOk $btn.btnCancel -side left -padx 2 -pady 2 -expand 1 + +bind $w "exit" + +InsertEnt $frm1.txtRootDir $rootDir +InsertEnt $frm4.txtTclDir $tclDir +$combo setvalue @0 +$comboLocale setvalue @0 + +proc CopyFiles {rootDir tclDir langDoc locale} { + global ver tcl_platform binDir hlDir + set exeName projman + set modules { + editor.tcl help.tcl html_lib.tcl procedure.tcl + main.tcl settings.tcl projects.tcl imgviewer.tcl + baloon.tcl completition.tcl taglist.tcl supertext.tcl + pane.tcl highlight/html.tcl highlight/spec.tcl highlight/tcl.tcl highlight/tex.tcl + highlight/caml.tcl highlight/fortran.tcl highlight/java.tcl + highlight/perl.tcl highlight/php.tcl highlight/rivet.tcl highlight/ruby.tcl + } + set docFiles {TODO README INSTALL CHANGELOG COPYING THANKS} + set confFiles {projman.spec projman.conf} + + if {[string length [string trim $rootDir]]} { + regsub -all {\\} $rootDir {\\\\} rootDir_ + set rootDir $rootDir_ + } + if {[string length [string trim $tclDir]]} { + regsub -all {\\} $tclDir {\\\\} tclDir_ + set tclDir $tclDir_ + } + destroy .frmMain.frmRootDir + destroy .frmMain.frmTclDir + destroy .frmMain.frmLocale + destroy .frmMain.frmDocLang + set frm ".frmMain" + pack $frm -expand 1 -fill both + set text [text $frm.text -yscrollcommand "$frm.yscroll set" \ + -relief sunken -wrap word -highlightthickness 0\ + -selectborderwidth 0 -selectbackground #55c4d1 -height 15 -width 30] + scrollbar $frm.yscroll -relief sunken -borderwidth {1} -width {10} -takefocus 0 \ + -command "$frm.text yview" + pack $frm.text -side left -fill both -expand true + pack $frm.yscroll -side left -fill y + + $text insert end "Root dir - $rootDir\nTcl dir - $tclDir" + $text insert end "\n-- Copying files --\n" + + set binDir [file join $rootDir bin ] + set dataDir [file join $rootDir share projman ] + set docDir [file join $rootDir share doc projman-$ver] + set imgDir [file join $dataDir img ] + set msgDir [file join $dataDir msgs ] + set hlDir [file join $dataDir highlight ] + + ## CREATE DIRECTORYES ## + if {[file exists $rootDir] != 1} {file mkdir $rootDir} + if {[file exists $binDir ] != 1} {file mkdir $binDir } + if {[file exists $dataDir] != 1} {file mkdir $dataDir} + if {[file exists $docDir ] != 1} {file mkdir $docDir } + if {[file exists $imgDir ] != 1} {file mkdir $imgDir } + if {[file exists $msgDir ] != 1} {file mkdir $msgDir } + if {[file exists $hlDir ] != 1} {file mkdir $hlDir } + + ## CREATE EXECUTION FILE ## + puts [pwd] + set source [open "projman.tcl" "r"] + set exe [open [file join $binDir $exeName] "w"] + while {[gets $source line]>=0} { + if {[string match "set rootDir \"/usr\"" [string trim $line]] == 1} { + puts $exe "set rootDir \"$rootDir_\"" + } elseif {[string match "set tclDir \"/usr/bin\"" [string trim $line]] == 1} { + puts $exe "set tclDir \"$tclDir_\"" + } else { + puts $exe $line + } + } + close $source + close $exe + + ## SET PERMISSIONS ON FILE FOR UNIX OR CREATE start.bat FILE FOR WINDOWS ## + if {$tcl_platform(platform) == "unix"} { + file attributes [file join $binDir $exeName] -permissions 00755 + } elseif {$tcl_platform(platform) == "windows"} { + set bat [open [file join $binDir projman.bat] "w"] + set progPath "[file join $binDir $exeName.tcl]" + file rename -force [file join $binDir $exeName] $progPath + regsub -all {/} $progPath "\\" progPath + set tclPath "[file join $tclDir wish.exe]" + regsub -all {/} $tclPath "\\" tclPath + puts $bat "\"$tclPath\" \"$progPath\"" + close $bat + } + ## COPYING MODULES FILES (*.tcl) ## + foreach file $modules { + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $dataDir $fileName] + } + + ## COPYING CONFIG FILE ## + foreach fileName $confFiles { + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $dataDir $fileName] + } + ## COPYING DOCUMENTATION (HELP) FILES ## + foreach fileName $docFiles { + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $docDir $fileName] + } + if {$locale == ""} { + set locale "en" + } + if {$langDoc == ""} { + set langDoc "en" + } + puts "Locale - $locale LangDoc - $langDoc" + if {[catch {cd [file join hlp $langDoc]}] != 0} { + return "" + } + foreach dir [lsort [glob -nocomplain *]] { + if {[file isdirectory $dir] == 1 && $dir != "CVS"} { + if {[file exists [file join $docDir $dir]] != 1} { + file mkdir [file join $docDir $dir] + #puts [file join $docDir $dir] + } + foreach file [lsort [glob -nocomplain [file join $dir *.*]]] { + #puts $file + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $docDir $fileName] + } + } + } + ## COPYING IMAGE FILES ## + if {[catch {cd [file join .. .. img]}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *.gif]] { + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $imgDir $fileName] + } + foreach file [lsort [glob -nocomplain *.png]] { + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $imgDir $fileName] + } + ## COPYING MESSAGES FILES ## + if {[catch {cd [file join .. msgs]}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *.msg]] { + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $msgDir $fileName] + } + ## COPYING HIGHLIGHT FILES ## + if {[catch {cd [file join .. highlight]}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *.tcl]] { + lappend rList [list [file join . $file]] + set fileName [file join $file] + $text insert end "$fileName\n" + $text mark set insert end + $text see insert + file copy -force -- $fileName [file join $hlDir $fileName] + } + $text insert end "-- Copying file complite --" + $text mark set insert end + $text see insert + destroy .frmButton.btnOk + .frmButton.btnCancel configure -text "Finish" -command {exit} + + SetVarLang $locale +} + + +#Michel SALVAGNIAC 7 avril 2002 +#positionne la variable d'environnement LANG +#n?cessaire pour msgcat +#version de tcl/tk :8.3 +#test? avec Windows 95,Windows NT4,Windows 2000, Windows XP pro + +proc SetVarLang {lang} { + global tcl_platform rootDir + set language $lang + if {$tcl_platform(platform) == "windows"} { + #Windows NT,2000,XP PRO + if {$tcl_platform(os) == "Windows NT"} { + package require registry + tk_messageBox -type ok -icon warning \ + -message "Modifying the Registry..." + set clebase "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment" + registry set $clebase LANG $language sz + #Windows 95 + } elseif {$tcl_platform(os) == "Windows 95"} { + tk_messageBox -type ok -icon warning \ + -message "Modifying the C:\\Autoexec.bat" + file copy -force c:/Autoexec.bat c:/autoexec.sav + set ficsys [open "c:/autoexec.bat" a+] + puts $ficsys "SET LANG=$language " + puts $ficsys "SET HOMEDRIVE=C:\\" + set workDir [file join $rootDir work] + regsub -all {/} $workDir {\\} home + puts $ficsys "SET HOMEPATH=$home" + close $ficsys + } + } +} + + + + + + + + + + + + diff --git a/main.tcl b/main.tcl new file mode 100644 index 0000000..8c3021b --- /dev/null +++ b/main.tcl @@ -0,0 +1,411 @@ +########################################################### +# Tcl/Tk Project Manager # +# Distrubuted under GPL # +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +Modules +## MAIN INTERFACE ## +wm geometry . 1024x768+0+0 +wm title . "Tcl/Tk Project Manager $ver" +wm iconname . "Tcl/Tk Project Manager $ver" +wm protocol . WM_DELETE_WINDOW Quit +wm overrideredirect . 0 +wm positionfrom . user +#wm resizable . 0 0 + +frame .frmMenu -border 1 -relief raised -background $editor(bg) +frame .frmTool -border 1 -relief raised -background $editor(bg) +frame .frmBody -border 1 -relief raised -background $editor(bg) +frame .frmStatus -border 1 -relief sunken -bg $editor(bg) +pack .frmMenu -side top -padx 1 -fill x +pack .frmTool -side top -padx 1 -fill x +pack .frmBody -side top -padx 1 -fill both -expand true +pack .frmStatus -side top -padx 1 -fill x + +########## CREATE MENU LINE ########## +menubutton .frmMenu.mnuFile -text [::msgcat::mc "File"] -menu .frmMenu.mnuFile.m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +set m [menu .frmMenu.mnuFile.m -bg $editor(bg) -fg $editor(fg)] +$m add cascade -label [::msgcat::mc "New"] -menu $m.new -font $fontNormal +set mn [menu $m.new -bg $editor(bg) -fg $editor(fg)] +$mn add command -label [::msgcat::mc "New file"] -command {AddToProjDialog file}\ +-font $fontNormal -accelerator "Ctrl+N" +$mn add command -label [::msgcat::mc "New directory"] -command {AddToProjDialog directory}\ +-font $fontNormal -accelerator "Ctrl+N" +$mn add command -label [::msgcat::mc "New project"] -command {NewProjDialog "new"}\ +-font $fontNormal +$m add command -label [::msgcat::mc "Open"] -command {FileDialog open}\ +-font $fontNormal -accelerator "Ctrl+O" -state disable +$m add command -label [::msgcat::mc "Save"] -command {FileDialog save}\ +-font $fontNormal -accelerator "Ctrl+S" +$m add command -label [::msgcat::mc "Save as"] -command {FileDialog save_as}\ +-font $fontNormal -accelerator "Ctrl+A" +$m add command -label [::msgcat::mc "Save all"] -command {FileDialog save_all}\ +-font $fontNormal +$m add command -label [::msgcat::mc "Close"] -command {FileDialog close}\ +-font $fontNormal -accelerator "Ctrl+W" +$m add command -label [::msgcat::mc "Close all"] -command {FileDialog close_all}\ +-font $fontNormal +$m add command -label [::msgcat::mc "Delete"] -command {FileDialog delete}\ +-font $fontNormal -accelerator "Ctrl+D" +$m add separator +$m add command -label [::msgcat::mc "Compile file"] -command {MakeProj compile file} -font $fontNormal -accelerator "Ctrl+F8" +$m add command -label [::msgcat::mc "Run file"] -command {MakeProj run file} -font $fontNormal -accelerator "Ctrl+F9" +$m add separator +$m add command -label [::msgcat::mc "Print"] -command PrintDialog\ +-font $fontNormal -accelerator "Ctrl+P" +$m add separator +$m add command -label [::msgcat::mc "Settings"] -command Settings -font $fontNormal +$m add separator +$m add command -label [::msgcat::mc "Exit"] -command Quit -font $fontNormal -accelerator "Ctrl+Q" + +##.frmMenu 'Project' ## + +proc GetProjMenu {m} { + global fontNormal + $m add command -label [::msgcat::mc "Project settings"] -command {NewProj edit $activeProject ""}\ + -font $fontNormal + $m add separator + $m add command -label [::msgcat::mc "Open project"] -command {OpenProj} -font $fontNormal + $m add command -label [::msgcat::mc "New project"] -command {NewProjDialog new} -font $fontNormal + $m add command -label [::msgcat::mc "Delete project"] -command DelProj -font $fontNormal + $m add separator + $m add command -label [::msgcat::mc "Add to project"] -command AddToProjDialog -font $fontNormal + $m add command -label [::msgcat::mc "Delete from project"]\ + -command {FileDialog delete} -font $fontNormal + $m add separator + $m add command -label [::msgcat::mc "Make archive"] -command MakeTGZ -font $fontNormal -accelerator "F7" + $m add command -label [::msgcat::mc "Make RPM"] -command MakeRPM -font $fontNormal -accelerator "F6" + $m add separator + $m add command -label [::msgcat::mc "Compile"] -command {MakeProj compile proj} -font $fontNormal -accelerator "F8" + $m add command -label [::msgcat::mc "Run"] -command {MakeProj run proj} -font $fontNormal -accelerator "F9" +} + +menubutton .frmMenu.mnuProj -text [::msgcat::mc "Project"] -menu .frmMenu.mnuProj.m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +set m [menu .frmMenu.mnuProj.m -bg $editor(bg) -fg $editor(fg)] +GetProjMenu $m + +##.frmMenu 'Edit' ## +menubutton .frmMenu.mnuEdit -text [::msgcat::mc "Edit"] -menu .frmMenu.mnuEdit.m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +## BUILDING EDIT-MENU FOR MAIN AND POP-UP MENU ## +proc GetMenu {m} { + global fontNormal fontBold imgDir editor + $m add command -label [::msgcat::mc "Undo"] -font $fontNormal -accelerator "Ctrl+Z"\ + -state normal -command Undo + $m add command -label [::msgcat::mc "Redo"] -font $fontNormal -accelerator "Ctrl+Z"\ + -state normal -command Redo + $m add separator + $m add command -label [::msgcat::mc "Procedure name complit"] -font $fontNormal -accelerator "Ctrl+J" -state normal\ + -command { + set nb "$noteBook.f[$noteBook raise]" + auto_completition_proc $nb.text + unset nb + } + $m add separator + $m add command -label [::msgcat::mc "Copy"] -font $fontNormal -accelerator "Ctrl+C"\ + -command { + set nb "$noteBook.f[$noteBook raise]" + tk_textCopy $nb.text + unset nb + } + $m add command -label [::msgcat::mc "Paste"] -font $fontNormal -accelerator "Ctrl+V"\ + -command { + set nb "$noteBook.f[$noteBook raise]" + tk_textPaste $nb.text + unset nb + } + $m add command -label [::msgcat::mc "Cut"] -font $fontNormal -accelerator "Ctrl+X"\ + -command { + set nb "$noteBook.f[$noteBook raise]" + tk_textCut $nb.text + unset nb + } + $m add separator + $m add command -label [::msgcat::mc "Select all"] -font $fontNormal -accelerator "Ctrl+/"\ + -command { + set nb [$noteBook raise] + if {$nb == "" || $nb == "newproj" || $nb == "about" || $nb == "debug"} { + return + } + set nb "$noteBook.f$nb" + SelectAll $nb.text + unset nb + } + $m add separator + $m add command -label [::msgcat::mc "Goto line"] -command GoToLine -font $fontNormal\ + -accelerator "Ctrl+G" + $m add command -label [::msgcat::mc "Find"] -command Find -font $fontNormal -accelerator "Ctrl+F" + $m add command -label [::msgcat::mc "Replace"] -command ReplaceDialog -font $fontNormal\ + -accelerator "Ctrl+R" + $m add cascade -label [::msgcat::mc "Encode"] -menu $m.encode -font $fontNormal + set me [menu $m.encode -bg $editor(bg) -fg $editor(fg)] + $me add command -label [::msgcat::mc "KOI8-R"] -command {TextEncode koi8-r} -font $fontNormal + $me add command -label [::msgcat::mc "CP1251"] -command {TextEncode cp1251} -font $fontNormal + $me add command -label [::msgcat::mc "CP866"] -command {TextEncode cp866} -font $fontNormal +} +GetMenu [menu .frmMenu.mnuEdit.m -bg $editor(bg) -fg $editor(fg)];# main edit menu +GetMenu [menu .popMnuEdit -bg $editor(bg) -fg $editor(fg)] ;# pop-up edit menu + +## VIEW MENU ## +menubutton .frmMenu.mnuView -text [::msgcat::mc "View"] -menu .frmMenu.mnuView.m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +set m [menu .frmMenu.mnuView.m -bg $editor(bg) -fg $editor(fg)] +$m add checkbutton -label [::msgcat::mc "Toolbar"] -font $fontNormal -state normal\ +-offvalue "No" -onvalue "Yes" -variable toolBar -command {ToolBar} +$m add command -label [::msgcat::mc "Split edit window"] -font $fontNormal -accelerator "F4" -state disable\ +-command SplitWindow +$m add separator +$m add command -label [::msgcat::mc "Refresh"] -font $fontNormal -accelerator "F5" -state normal\ +-command UpdateTree + +##.frmMenu Settings ## +menubutton .frmMenu.mnuCVS -text [::msgcat::mc "Modules"] -menu .frmMenu.mnuCVS.m \ +-font $fontNormal -state normal -bg $editor(bg) -fg $editor(fg) +set m [menu .frmMenu.mnuCVS.m -bg $editor(bg) -fg $editor(fg)] +if {$module(tkcvs) != ""} { + $m add command -label "TkCVS" -command {DoModule tkcvs} -font $fontNormal +} +if {$module(tkdiff) != ""} { + $m add command -label "TkDIFF+" -command {DoModule tkdiff} -font $fontNormal +} +if {$module(tkregexp) != ""} { + $m add command -label "TkREGEXP" -command {DoModule tkregexp} -font $fontNormal +} +if {$module(ctags) != ""} { + $m add command -label "CTags" -font $fontNormal -command { + DoModule ctags + GetTagList [file join $workDir $activeProject.tags] ;# geting tag list + } +} + +menubutton .frmMenu.mnuHelp -text [::msgcat::mc "Help"] -menu .frmMenu.mnuHelp.m \ +-underline 0 -font $fontNormal -bg $editor(bg) -fg $editor(fg) +set m [menu .frmMenu.mnuHelp.m -bg $editor(bg) -fg $editor(fg)] +$m add command -label [::msgcat::mc "Help"] -command ShowHelp \ +-accelerator F1 -font $fontNormal +$m add command -label [::msgcat::mc "About ..."] -command AboutDialog \ +-font $fontNormal + +pack .frmMenu.mnuFile .frmMenu.mnuProj .frmMenu.mnuEdit .frmMenu.mnuView .frmMenu.mnuCVS -side left +pack .frmMenu.mnuHelp -side right +## Bind command ## +bind . ShowHelp +bind . UpdateTree +bind . MakeRPM +bind . MakeTGZ +bind . {MakeProj compile proj} +bind . {MakeProj compile file} +bind . {MakeProj run proj} +bind . {MakeProj run file} +bind . AddToProjDialog +bind . AddToProjDialog +bind . AddToProjDialog +bind . AddToProjDialog +bind . Quit +bind . Quit +bind . PrintDialog +bind . PrintDialog +## TOOLBAR ## +proc add_toolbar_button {path icon command helptext} { + global editor imgDir + image create photo $icon -format png -file [file join $imgDir $icon] + $path add -image $icon \ + -highlightthickness 0 -takefocus 0 -relief link -bd 1 -activebackground $editor(bg)\ + -padx 1 -pady 1 -command $command -helptext $helptext +} +# Separator for toolbar +set sepIndex 0 +proc Separator {} { + global sepIndex editor + set f [frame .frmTool.separator$sepIndex -width 10 -border 1 -background $editor(bg) -relief raised] + incr sepIndex 1 + return $f +} +proc CreateToolBar {} { + global toolBar fontBold noteBook tree imgDir editor + if {$toolBar == "Yes"} { + set bboxFile [ButtonBox .frmTool.bboxFile -spacing 0 -padx 1 -pady 1 -bg $editor(bg)] + add_toolbar_button $bboxFile new.png {AddToProjDialog file} [::msgcat::mc "Create new file"] + add_toolbar_button $bboxFile save.png {FileDialog save} [::msgcat::mc "Save file"] + add_toolbar_button $bboxFile save_as.png {FileDialog save_as} [::msgcat::mc "Save file as"] + add_toolbar_button $bboxFile save_all.png {FileDialog save_all} [::msgcat::mc "Save all"] + add_toolbar_button $bboxFile printer.png {PrintDialog} [::msgcat::mc "Print ..."] + add_toolbar_button $bboxFile close.png {FileDialog close} [::msgcat::mc "Close"] + + set bboxEdit [ButtonBox .frmTool.bboxEdit -spacing 0 -padx 1 -pady 1 -bg $editor(bg)] + add_toolbar_button $bboxEdit copy.png {TextOperation copy} [::msgcat::mc "Copy into clipboard"] + add_toolbar_button $bboxEdit cut.png {TextOperation cut} [::msgcat::mc "Cut into clipboard"] + add_toolbar_button $bboxEdit paste.png {TextOperation paste} [::msgcat::mc "Paste from clipboard"] + add_toolbar_button $bboxEdit undo.png {TextOperation undo} [::msgcat::mc "Undo"] + add_toolbar_button $bboxEdit redo.png {TextOperation redo} [::msgcat::mc "Redo"] + + + set bboxProj [ButtonBox .frmTool.bboxProj -spacing 0 -padx 1 -pady 1 -bg $editor(bg)] + + add_toolbar_button $bboxProj doit.png {MakeProj run proj} [::msgcat::mc "Running project"] + add_toolbar_button $bboxProj doit_file.png {MakeProj run file} [::msgcat::mc "Running file"] + add_toolbar_button $bboxProj archive.png {MakeTGZ} [::msgcat::mc "Make TGZ"] + + set bboxHelp [ButtonBox .frmTool.bboxHelp -spacing 0 -padx 1 -pady 1 -bg $editor(bg)] + add_toolbar_button $bboxHelp help.png {ShowHelp} [::msgcat::mc "Help"] + + pack $bboxFile [Separator] $bboxEdit [Separator] $bboxProj [Separator] $bboxHelp -side left -anchor w + + } +} +########## STATUS BAR ########## +set frm1 [frame .frmStatus.frmHelp -bg $editor(bg)] +set frm2 [frame .frmStatus.frmActive -bg $editor(bg)] +set frm3 [frame .frmStatus.frmProgress -relief sunken -bg $editor(bg)] +set frm4 [frame .frmStatus.frmLine -bg $editor(bg)] +set frm5 [frame .frmStatus.frmFile -bg $editor(bg)] +set frm6 [frame .frmStatus.frmOvwrt -bg $editor(bg)] +pack $frm1 $frm4 $frm6 $frm2 $frm5 -side left -fill x +pack $frm3 -side left -fill x -expand true +label $frm1.lblHelp -width 25 -relief sunken -font $fontNormal -anchor w -bg $editor(bg) -fg $editor(fg) +pack $frm1.lblHelp -fill x +label $frm4.lblLine -width 10 -relief sunken -font $fontNormal -anchor w -bg $editor(bg) -fg $editor(fg) +pack $frm4.lblLine -fill x +label $frm2.lblActive -width 25 -relief sunken -font $fontNormal -anchor center -bg $editor(bg) -fg $editor(fg) +pack $frm2.lblActive -fill x +label $frm3.lblProgress -relief sunken -font $fontNormal -anchor w -bg $editor(bg) -fg $editor(fg) +pack $frm3.lblProgress -fill x +label $frm5.lblFile -width 10 -relief sunken -font $fontNormal -anchor w -bg $editor(bg) -fg $editor(fg) +pack $frm5.lblFile -fill x +label $frm6.lblOvwrt -width 10 -relief sunken -font $fontNormal -anchor center -bg $editor(bg) -fg $editor(fg) +pack $frm6.lblOvwrt -fill x + +########## PROJECT-FILE-FUNCTION TREE ################## + +set frmCat [frame .frmBody.frmCat -border 1 -relief sunken -bg $editor(bg)] +pack $frmCat -side left -fill y -fill both +set frmWork [frame .frmBody.frmWork -border 1 -relief sunken -bg $editor(bg)] +pack $frmWork -side left -fill both -expand true + +## CREATE PANE ## +pane::create .frmBody.frmCat .frmBody.frmWork + +set frmTree [ScrolledWindow $frmCat.frmTree -bg $editor(bg)] +global tree noteBook +set tree [Tree $frmTree.tree \ +-relief sunken -borderwidth 1 -width 5 -height 5 -highlightthickness 1\ +-redraw 0 -dropenabled 1 -dragenabled 1 -dragevent 3 \ +-background $editor(bg) -selectbackground "#55c4d1" \ +-droptypes { + TREE_NODE {copy {} move {} link {}} + LISTBOX_ITEM {copy {} move {} link {}} +} -opencmd {TreeOpen} -closecmd {TreeClose}] +$frmTree setwidget $tree +pack $frmTree -side top -fill both -expand true + +$tree bindText "TreeDoubleClick [$tree selection get]" +$tree bindText "TreeOneClick [$tree selection get]" +$tree bindImage "TreeDoubleClick [$tree selection get]" +$tree bindImage "TreeOneClick [$tree selection get]" +$tree bindText {$tree selection add [$tree selection get]} +bind $frmTree.tree.c {FileDialog delete} +bind $frmTree.tree.c {FileDialog delete} +bind $frmTree.tree.c { + set node [$tree selection get] + TreeOneClick $node + TreeDoubleClick $node +} + +## POPUP FILE-MENU ## +set m .popupFile +menu $m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +$m add command -label [::msgcat::mc "New file"] -command {AddToProjDialog file}\ +-font $fontNormal -accelerator "Ctrl+N" +$m add command -label [::msgcat::mc "New directory"] -command {AddToProjDialog directory}\ +-font $fontNormal -accelerator "Alt + Ctrl+N" +$m add command -label [::msgcat::mc "Open"] -command {FileDialog open}\ +-font $fontNormal -accelerator "Ctrl+O" -state disable +$m add command -label [::msgcat::mc "Save"] -command {FileDialog save}\ +-font $fontNormal -accelerator "Ctrl+S" +$m add command -label [::msgcat::mc "Save as"] -command {FileDialog save_as}\ +-font $fontNormal -accelerator "Ctrl+A" +$m add command -label [::msgcat::mc "Save all"] -command {FileDialog save_all}\ +-font $fontNormal +$m add command -label [::msgcat::mc "Close"] -command {FileDialog close}\ +-font $fontNormal -accelerator "Ctrl+W" +$m add command -label [::msgcat::mc "Close all"] -command {FileDialog close_all}\ +-font $fontNormal +$m add command -label [::msgcat::mc "Delete"] -command {FileDialog delete}\ +-font $fontNormal -accelerator "Ctrl+D" +$m add separator +$m add command -label [::msgcat::mc "Compile file"] -command {MakeProj compile file} -font $fontNormal -accelerator "Ctrl+F8" +$m add command -label [::msgcat::mc "Run file"] -command {MakeProj run file} -font $fontNormal -accelerator "Ctrl+F9" + +## POPUP PROJECT-MENU ## +set m [menu .popupProj -font $fontNormal -bg $editor(bg) -fg $editor(fg)] +GetProjMenu $m + + +## TABS popups ## + +set m .popupTabs +menu $m -font $fontNormal -bg $editor(bg) -fg $editor(fg) +$m add command -label [::msgcat::mc "Close"] -command {FileDialog close}\ +-font $fontNormal -accelerator "Ctrl+W" +$m add command -label [::msgcat::mc "Close all"] -command {FileDialog close_all}\ +-font $fontNormal + + +proc PopupMenuTab {menu x y} { + tk_popup $menu $x $y +} + + + +bind $frmTree.tree.c {catch [PopupMenuTree %X %Y]} + +######### DEDERER: bind Wheel Scroll ################## +#$tree bindText "$tree yview scroll -3 units ; break ;# " +#$tree bindText "$tree yview scroll 3 units ; break ;# " +bind $frmTree.tree.c "$tree yview scroll -3 units" +bind $frmTree.tree.c "$tree yview scroll 3 units" +bind $frmTree.tree.c "$tree xview scroll -2 units" +bind $frmTree.tree.c "$tree xview scroll 2 units" + +#################### WORKING AREA #################### +set noteBook [NoteBook $frmWork.noteBook -font $fontNormal -side top -bg $editor(bg) -fg $editor(fg)] +pack $noteBook -fill both -expand true -padx 2 -pady 2 +#$noteBook bindtabs "PageRaise [$tree selection get]" +$noteBook bindtabs {catch [PopupMenuTab .popupTabs %X %Y]} + + +#bind . PageTab +#bind . PageTab + +bind . {PageTab 1} +bind . {PageTab -1} + +################################################## +CreateToolBar +GetProj $tree +$tree configure -redraw 1 +set activeProject "" +focus -force $tree + + + + + + + + + + + + + + + + + + + + + + + diff --git a/msgcat.add b/msgcat.add new file mode 100644 index 0000000..1945c4a --- /dev/null +++ b/msgcat.add @@ -0,0 +1,18 @@ +Вот пища для размышлений. Уточну. Этот код предназначен для работы под Win32 при условии, что весть текст набран в koi8-r кодировке. Как его доделать, думаю, сообразишь сам: +set lang ru +set mc_source { + mcset $lang "File" "Файл" + mcset $lang "New..." "Новый..." +} + +set mc_source [encoding convertto koi8-r $mc_source] +set mc_source [encoding convertfrom cp1251 $mc_source] + +eval $mc_source + +++++++++++++++++++++++++++ +set mc_source [encoding convertto koi8-r $mc_source] +set mc_source [encoding convertfrom [encoding system] $mc_source] + + + diff --git a/msgs/de.msg b/msgs/de.msg new file mode 100644 index 0000000..8c4c643 --- /dev/null +++ b/msgs/de.msg @@ -0,0 +1,133 @@ +########################################################### +# Tcl/Tk Project Manager # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### +# german messages file # +# Author: Roman Schaller # +########################################################### + +::msgcat::mcset de "About ..." "эber ..." +::msgcat::mcset de "Add to project" "Zu Projekt hinzufЭgen" +::msgcat::mcset de "Author" "Autor" +::msgcat::mcset de "Text autoformat" "Text autoformat" +::msgcat::mcset de "Cancel" "Abbrechen" +::msgcat::mcset de "Can't found file:" "Datei nicht gefunden:" +::msgcat::mcset de "Close" "Schliessen" +::msgcat::mcset de "Close all" "Alles Schliessen" +::msgcat::mcset de "Close Project Manager?" "Project Manager Schliessen?" +::msgcat::mcset de "Company" "Firma" +::msgcat::mcset de "Contents" "Inhalt" +::msgcat::mcset de "Copy" "Kopieren" +::msgcat::mcset de "Copy into clipboard" "In Zwischenablage kopieren" +::msgcat::mcset de "Create backup files" "Backup-Dateien erstellen" +::msgcat::mcset de "Create new project" "Neuse Projekt erstellen" +::msgcat::mcset de "Create new file" "Neue Datei erstellen" +::msgcat::mcset de "Create directory" "Verzeichnis erstelle" +::msgcat::mcset de "Curent directory" "Aktuelles Verzeichnis" +::msgcat::mcset de "Cut" "Ausschneiden" +::msgcat::mcset de "Cut into clipboard" "In Zwischenablage ausschneiden" +::msgcat::mcset de "CVS commit" +::msgcat::mcset de "CVS update" +::msgcat::mcset de "Delete" "LЖschen" +::msgcat::mcset de "Delete backup files" "Backup-Dateien lЖschen" +::msgcat::mcset de "Delete project" "Projekt lЖschen" +::msgcat::mcset de "Delete from project" "Von Projekt entfernen" +::msgcat::mcset de "Docs dir" "Dok Verzeichnis" +::msgcat::mcset de "Don't selected file" +::msgcat::mcset de "E-mail" +::msgcat::mcset de "Edit" "Bearbeiten" +::msgcat::mcset de "Editor font" "Editor Schriftart" +::msgcat::mcset de "Editor font bold Editor Schriftart fett" +::msgcat::mcset de "Error open URL" +::msgcat::mcset de "Exit" "Beenden" +::msgcat::mcset de "File" "Datei" +::msgcat::mcset de "File already exists. Overwrite?" "Datei besteht bereits. эberschreiben?" +::msgcat::mcset de "File modify" "Datei bearbeiten" +::msgcat::mcset de "File was modifyed. Close?" "Datei wurde geДndert. Trotzdem schliessen?" +::msgcat::mcset de "File was modifyed. Save?" "Datei wurde geДndert. Jetzt speichern?" +::msgcat::mcset de "File saved" "Datei gespeichert" +::msgcat::mcset de "Find" "Suchen" +::msgcat::mcset de "Font normal" "Schrift normal" +::msgcat::mcset de "Font bold" "Schrift fett" +::msgcat::mcset de "Goto line" "Gehezu Zeile" +::msgcat::mcset de "Help" "Hilfe" +::msgcat::mcset de "Home dir" "Home Verzeichnis" +::msgcat::mcset de "Home page" "Homepage" +::msgcat::mcset de "Image dir" "Image Verzeichnis" +::msgcat::mcset de "Insert" "EinfЭgen" +::msgcat::mcset de "Interface language" "Interface Sprache" +::msgcat::mcset de "Install Tcl/Tk Project Manager" "Tcl/Tk Project Manager installieren" +::msgcat::mcset de "Line number" "Zeilennummer" +::msgcat::mcset de "Make RPM" "RPM erstellen" +::msgcat::mcset de "Make archive" "Archiv erstellen" +::msgcat::mcset de "Make backup files" "Backup-Dateien erstellen" +::msgcat::mcset de "Must be one file select!" "Eine Datei muss ausgewДhlt sein!" +::msgcat::mcset de "Must be one or two file select!" "Eine oder zwei Dateien mЭssen ausgewДhlt sein!" +::msgcat::mcset de "Modifying the Registry..." +::msgcat::mcset de "Modules" "Module" +::msgcat::mcset de "New" "Neu" +::msgcat::mcset de "New file" "Neue Datei" +::msgcat::mcset de "New project" "Neues Projekt" +::msgcat::mcset de "Not implemented yet" "Noch nicht implementiert" +::msgcat::mcset de "Not found active project" "Kein aktives Projekt gefunden" +::msgcat::mcset de "Open" "жffnen" +::msgcat::mcset de "Open file" "Datei Жffnen" +::msgcat::mcset de "Open project" "Projekt Жffnen" +::msgcat::mcset de "Opened file in progress" "GeЖffnete Datei in Bearbeitung" +::msgcat::mcset de "Overwrite" "эberschreiben" +::msgcat::mcset de "Paste" "EinfЭgen" +::msgcat::mcset de "Paste from clipboard" "Von Zwischenablage einfЭgen" +::msgcat::mcset de "Print ..." "Drucken ..." +::msgcat::mcset de "Print" "Drucken" +::msgcat::mcset de "Print command" "Druck-Befehl" +::msgcat::mcset de "Print selected text" "Markierter Text drucken" +::msgcat::mcset de "Program finished successfully" "Programm wurde erfolgreich beendet" +::msgcat::mcset de "Program failed" "AusfЭhrung fehlgeschlagen" +::msgcat::mcset de "Programm output" "Programm Ausgabe" +::msgcat::mcset de "Project" "Projekt" +::msgcat::mcset de "Projects" "Projekte" +::msgcat::mcset de "Project settings" "Projekt einstellungen" +::msgcat::mcset de "Project name" "Projekt-Name" +::msgcat::mcset de "Project file" "Projekt-Datei" +::msgcat::mcset de "Project dir" "Projekt-Verzeichnis" +::msgcat::mcset de "Question" "Frage" +::msgcat::mcset de "Quit without saving?" "Beenden ohne zu speichern?" +::msgcat::mcset de "Redo" "Wiederherstellen" +::msgcat::mcset de "Refresh" "Auffrischen" +::msgcat::mcset de "Replace" "Ersetzen" +::msgcat::mcset de "Replace with" "Ersetzen mit" +::msgcat::mcset de "Replace all" "Alles ersetzen" +::msgcat::mcset de "Release" +::msgcat::mcset de "RPM dir" "RPM Verzeichnis" +::msgcat::mcset de "RPM file mask" "RPM Datei Maske" +::msgcat::mcset de "Run" "AusfЭhren" +::msgcat::mcset de "Running project" "Projekt ausfЭhren" +::msgcat::mcset de "Running file" +::msgcat::mcset de "Save" "Speichern" +::msgcat::mcset de "Save as" "Speichern unter" +::msgcat::mcset de "Save file" "Datei speichern" +::msgcat::mcset de "Save file as" "Datei speichern unter" +::msgcat::mcset de "Save all" "Alles speichern" +::msgcat::mcset de "Search" "Suchen" +::msgcat::mcset de "Select" "AuswДhlen" +::msgcat::mcset de "Select directory" "Verzeichnis auswДhlen" +::msgcat::mcset de "Selected directory" "AusgewДhltes Verzeichnis" +::msgcat::mcset de "Settings" "Einstellungen" +::msgcat::mcset de "Show backup files" "Backup-Dateien anzeigen" +::msgcat::mcset de "Interpretator" "Interpreter" +::msgcat::mcset de "TGZ dir" "TGZ Verzeichnis" +::msgcat::mcset de "TGZ file mask" "TGZ Datei Maske" +::msgcat::mcset de "Thanks" "Danksagung" +::msgcat::mcset de "Toolbar" "Symbolleiste" +::msgcat::mcset de "Undo" "RЭckgДngig" +::msgcat::mcset de "Update" +::msgcat::mcset de "Version" +::msgcat::mcset de "View" "Ansicht" +::msgcat::mcset de "Warning" "Warnung" +::msgcat::mcset de "Was replacement" +::msgcat::mcset de "Work dir" "Arbeitsverzeichnis" + + + + diff --git a/msgs/en.msg b/msgs/en.msg new file mode 100644 index 0000000..c4ca9a7 --- /dev/null +++ b/msgs/en.msg @@ -0,0 +1,166 @@ +########################################################### +# Tcl/Tk Project Manager # +# english messages file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +::msgcat::mcset en "About ..." +::msgcat::mcset en "Add to project" +::msgcat::mcset en "Author" +::msgcat::mcset en "Braces" +::msgcat::mcset en "Quad braces" +::msgcat::mcset en "Braces background" +::msgcat::mcset en "Braces foreground" +::msgcat::mcset en "Cancel" +::msgcat::mcset en "Can't found file:" +::msgcat::mcset en "Close" +::msgcat::mcset en "Close all" +::msgcat::mcset en "Close Project Manager?" +::msgcat::mcset en "Comments" +::msgcat::mcset en "Company" +::msgcat::mcset en "Compiler" +::msgcat::mcset en "Compile" +::msgcat::mcset en "Compile project" +::msgcat::mcset en "Compile file" +::msgcat::mcset en "Contents" +::msgcat::mcset en "Copy" +::msgcat::mcset en "Copy into clipboard" +::msgcat::mcset en "Create backup files" +::msgcat::mcset en "Create new project" +::msgcat::mcset en "Create new file" +::msgcat::mcset en "Create directory" +::msgcat::mcset en "Curent directory" +::msgcat::mcset en "Cut" +::msgcat::mcset en "Cut into clipboard" +::msgcat::mcset en "CVS commit" +::msgcat::mcset en "CVS update" +::msgcat::mcset en "Delete" +::msgcat::mcset en "Delete backup files" +::msgcat::mcset en "Delete project" +::msgcat::mcset en "Delete from project" +::msgcat::mcset en "Docs dir" +::msgcat::mcset en "Don't selected file" +::msgcat::mcset en "E-mail" +::msgcat::mcset en "Edit" +::msgcat::mcset en "Editor" +::msgcat::mcset en "Editor background" +::msgcat::mcset en "Editor foreground" +::msgcat::mcset en "Editor font" +::msgcat::mcset en "Editor font bold" +::msgcat::mcset en "Error open URL" +::msgcat::mcset en "Exit" +::msgcat::mcset en "File" +::msgcat::mcset en "File already exists. Overwrite?" +::msgcat::mcset en "File modify" +::msgcat::mcset en "File was modifyed. Close?" +::msgcat::mcset en "File was modifyed. Save?" +::msgcat::mcset en "File saved" +::msgcat::mcset en "Find" +::msgcat::mcset en "Font normal" +::msgcat::mcset en "Font bold" +::msgcat::mcset en "FTP server" +::msgcat::mcset en "FTP user" +::msgcat::mcset en "FTP password" +::msgcat::mcset en "Goto line" +::msgcat::mcset en "Help" +::msgcat::mcset en "Home dir" +::msgcat::mcset en "Home page" +::msgcat::mcset en "Image dir" +::msgcat::mcset en "Insert" +::msgcat::mcset en "Interface language" +::msgcat::mcset en "Install Tcl/Tk Project Manager" +::msgcat::mcset en "Input file name" +::msgcat::mcset en "Label" +::msgcat::mcset en "Line number" +::msgcat::mcset en "Main" +::msgcat::mcset en "Make RPM" +::msgcat::mcset en "Make archive" +::msgcat::mcset en "Make backup files" +::msgcat::mcset en "Modifying the Registry..." +::msgcat::mcset en "Must be one file select!" +::msgcat::mcset en "Must be one or two file select!" +::msgcat::mcset en "Modules" +::msgcat::mcset en "Network" +::msgcat::mcset en "New" +::msgcat::mcset en "New directory" +::msgcat::mcset en "New file" +::msgcat::mcset en "New project" +::msgcat::mcset en "Not implemented yet" +::msgcat::mcset en "Not found active project" +::msgcat::mcset en "Open" +::msgcat::mcset en "Open file" +::msgcat::mcset en "Open project" +::msgcat::mcset en "Opened file in progress" +::msgcat::mcset en "Operators" +::msgcat::mcset en "Overwrite" +::msgcat::mcset en "Parameters" +::msgcat::mcset en "Subparameters" +::msgcat::mcset en "Paste" +::msgcat::mcset en "Paste from clipboard" +::msgcat::mcset en "Percent %" +::msgcat::mcset en "Print ..." +::msgcat::mcset en "Print" +::msgcat::mcset en "Print command" +::msgcat::mcset en "Print selected text" +::msgcat::mcset en "Program finished successfully" +::msgcat::mcset en "Procedure name" +::msgcat::mcset en "Procedure name complit" +::msgcat::mcset en "Program failed" +::msgcat::mcset en "Programm output" +::msgcat::mcset en "Project" +::msgcat::mcset en "Projects" +::msgcat::mcset en "Project settings" +::msgcat::mcset en "Project name" +::msgcat::mcset en "Project file" +::msgcat::mcset en "Project dir" +::msgcat::mcset en "Question" +::msgcat::mcset en "Quit without saving?" +::msgcat::mcset en "Quote string" +::msgcat::mcset en "Redo" +::msgcat::mcset en "Refresh" +::msgcat::mcset en "Replace" +::msgcat::mcset en "Replace with" +::msgcat::mcset en "Replace all" +::msgcat::mcset en "Release" +::msgcat::mcset en "RPM dir" +::msgcat::mcset en "RPM file mask" +::msgcat::mcset en "Run" +::msgcat::mcset en "Running project" +::msgcat::mcset en "Running file" +::msgcat::mcset en "Run file" +::msgcat::mcset en "Save" +::msgcat::mcset en "Save as" +::msgcat::mcset en "Save file" +::msgcat::mcset en "Save file as" +::msgcat::mcset en "Save all" +::msgcat::mcset en "Search" +::msgcat::mcset en "Select" +::msgcat::mcset en "Select all" +::msgcat::mcset en "Select directory" +::msgcat::mcset en "Selected directory" +::msgcat::mcset en "Selection color" +::msgcat::mcset en "Settings" +::msgcat::mcset en "Show backup files" +::msgcat::mcset en "Split edit window" +::msgcat::mcset en "Interpretator" +::msgcat::mcset en "Text autoformat" +::msgcat::mcset en "TGZ dir" +::msgcat::mcset en "TGZ file mask" +::msgcat::mcset en "Thanks" +::msgcat::mcset en "Title normal" +::msgcat::mcset en "Title modify" +::msgcat::mcset en "Toolbar" +::msgcat::mcset en "Undo" +::msgcat::mcset en "Update" +::msgcat::mcset en "Variables" +::msgcat::mcset en "Version" +::msgcat::mcset en "View" +::msgcat::mcset en "Warning" +::msgcat::mcset en "Was replacement" +::msgcat::mcset en "Word wrapping" +::msgcat::mcset en "Work dir" + + + + diff --git a/msgs/fr.msg b/msgs/fr.msg new file mode 100644 index 0000000..ae2a222 --- /dev/null +++ b/msgs/fr.msg @@ -0,0 +1,134 @@ +########################################################### +# Tcl/Tk Project Manager # +# french messages file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +# Traduction: Michel SALVAGNIAC michel.salvagniac@free.fr # +########################################################### +# french messages file # +# Author: Michel SALVAGNIAC # +########################################################### + +::msgcat::mcset fr "About ..." "A propos..." +::msgcat::mcset fr "Add to project" "Ajouter au projet" +::msgcat::mcset fr "Author" "Auteur" +::msgcat::mcset fr "Text autoformat" "Autoformatage du texte" +::msgcat::mcset fr "Cancel" "Annuler" +::msgcat::mcset fr "Can't found file:" "Ne peut trouver le fichier:" +::msgcat::mcset fr "Close" "Fermer" +::msgcat::mcset fr "Close all" "Tout fermer" +::msgcat::mcset fr "Close Project Manager?" "Fermer Project Manager?" +::msgcat::mcset fr "Company" "Compagnie" +::msgcat::mcset fr "Contents" "Contenu" +::msgcat::mcset fr "Copy" "Copier" +::msgcat::mcset fr "Copy into clipboard" "Copier dans le Presse-papiers" +::msgcat::mcset fr "Create backup files" "CrИer une copie de sauvegarde" +::msgcat::mcset fr "Create new project" "CrИer nouveau projet" +::msgcat::mcset fr "Create new file" "CrИer nouveau fichier" +::msgcat::mcset fr "Create directory" "CrИer rИpertoire" +::msgcat::mcset fr "Curent directory" "RИpertoire courant" +::msgcat::mcset fr "Cut" "Couper" +::msgcat::mcset fr "Cut into clipboard" "Couper dans le Presse-papiers" +::msgcat::mcset fr "CVS commit" "Ecriture CVS" +::msgcat::mcset fr "CVS update" "Mise Ю jour CVS" +::msgcat::mcset fr "Delete" "Effacer" +::msgcat::mcset fr "Delete backup files" "Effacer les fichiers de sauvegarde" +::msgcat::mcset fr "Delete project" "Effacer projet" +::msgcat::mcset fr "Delete from project" "Effacer du projet" +::msgcat::mcset fr "Docs dir" "RИpertoire de la doc" +::msgcat::mcset fr "Don't selected file" "Fichier non sИlectionnИ" +::msgcat::mcset fr "E-mail" "E-mail" +::msgcat::mcset fr "Edit" "Editer" +::msgcat::mcset fr "Editor font" "Police" +::msgcat::mcset fr "Editor font bold" "Police gras" +::msgcat::mcset fr "Error open URL" "Erreur Ю l'ouverture de l'URL" +::msgcat::mcset fr "Exit" "Quitter" +::msgcat::mcset fr "File" "Fichier" +::msgcat::mcset fr "File already exists. Overwrite?" "Le fichier existe dИja. Ecraser?" +::msgcat::mcset fr "File modify" "Modification de fichier" +::msgcat::mcset fr "File was modifyed. Close?" "Le fichier a ИtИ modifiИ. Fermer?" +::msgcat::mcset fr "File was modifyed. Save?" "Le fichier a ИtИ modifiИ. Enregistrer?" +::msgcat::mcset fr "File saved" "Fichier enregistrИ" +::msgcat::mcset fr "Find" "Trouver" +::msgcat::mcset fr "Font normal" "Police normale" +::msgcat::mcset fr "Font bold" "Police grasse" +::msgcat::mcset fr "Goto line" "Aller Ю la ligne" +::msgcat::mcset fr "Help" "Aide" +::msgcat::mcset fr "Home dir" "RИpertoire Home" +::msgcat::mcset fr "Home page" "Page d'accueil" +::msgcat::mcset fr "Image dir" "RИpertoire des images" +::msgcat::mcset fr "Insert" "InsИrer" +::msgcat::mcset fr "Interface language" "Langage d'interface" +::msgcat::mcset fr "Install Tcl/Tk Project Manager" "Installer Tcl/Tk Project Manager" +::msgcat::mcset fr "Line number" "Ligne numИro" +::msgcat::mcset fr "Make RPM" "Construire RPM" +::msgcat::mcset fr "Make archive" "Construire archive" +::msgcat::mcset fr "Make backup files" "Faire des sauvegardes" +::msgcat::mcset fr "Must be one file select!" "Vous devez choisir un fichier!" +::msgcat::mcset fr "Must be one or two file select!" "Vous devez choisir un ou deux fichiers!" +::msgcat::mcset fr "Modifying the Registry..." +::msgcat::mcset fr "Modules" "Modules" +::msgcat::mcset fr "New" "Nouveau" +::msgcat::mcset fr "New file" "Nouveau fichier" +::msgcat::mcset fr "New project" "Nouveau projet" +::msgcat::mcset fr "Not implemented yet" "Pas encore implИmentИ..." +::msgcat::mcset fr "Not found active project" "Pas de projet actif" +::msgcat::mcset fr "Open" "Ouvrir" +::msgcat::mcset fr "Open file" "Ouvrir fichier" +::msgcat::mcset fr "Open project" "Ouvrir projet" +::msgcat::mcset fr "Opened file in progress" "Ouverture en cours" +::msgcat::mcset fr "Overwrite" "Ecraser" +::msgcat::mcset fr "Paste" "Coller" +::msgcat::mcset fr "Paste from clipboard" "Coller du Presse-papiers" +::msgcat::mcset fr "Print ..." "Imprimer..." +::msgcat::mcset fr "Print" "Imprimer" +::msgcat::mcset fr "Print command" "Commande d'impression" +::msgcat::mcset fr "Print selected text" "Imprimer le texte sИlectionnИ" +::msgcat::mcset fr "Program finished successfully" "Programme terminИ avec succХs" +::msgcat::mcset fr "Program failed" "Programme a ИchouИ" +::msgcat::mcset fr "Programm output" "Sortie du programme" +::msgcat::mcset fr "Project" "Projet" +::msgcat::mcset fr "Projects" "Projets" +::msgcat::mcset fr "Project settings" "RИglages du projet" +::msgcat::mcset fr "Project name" "Nom du projet" +::msgcat::mcset fr "Project file" "Fichier projet" +::msgcat::mcset fr "Project dir" "RИpertoire du projet" +::msgcat::mcset fr "Question" "Question" +::msgcat::mcset fr "Quit without saving?" "Quitter sans sauvegarder?" +::msgcat::mcset fr "Redo" "Refaire" +::msgcat::mcset fr "Refresh" "Rafraichir" +::msgcat::mcset fr "Releace" "Remplacer" +::msgcat::mcset fr "Replace with" "Remplacer avec" +::msgcat::mcset fr "Replace all" "Remplacer tout" +::msgcat::mcset fr "Release" "RИvision" +::msgcat::mcset fr "RPM dir" "RИpertoire RPM" +::msgcat::mcset fr "RPM file mask" "fichiers RPM" +::msgcat::mcset fr "Run" "Executer" +::msgcat::mcset fr "Running project" "ExИcute le projet" +::msgcat::mcset fr "Save" "Enregistrer" +::msgcat::mcset fr "Save as" "Enregistrer sous" +::msgcat::mcset fr "Save file" "Enregistrer fichier" +::msgcat::mcset fr "Save file as" "Enregistrer fichier sous" +::msgcat::mcset fr "Save all" "Tout enregistrer" +::msgcat::mcset fr "Search" "Rechercher" +::msgcat::mcset fr "Select" "Choisir" +::msgcat::mcset fr "Select directory" "Choisir un rИpertoire" +::msgcat::mcset fr "Selected directory" "RИpertoire choisi" +::msgcat::mcset fr "Settings" "ParamХtres" +::msgcat::mcset fr "Show backup files" "Montrer fichiers de sauvegarde" +::msgcat::mcset fr "Interpretator" "InterprИteur" +::msgcat::mcset fr "TGZ dir" "RИpertoire TGZ" +::msgcat::mcset fr "TGZ file mask" "fichiers TGZ" +::msgcat::mcset fr "Thanks" "Remerciements" +::msgcat::mcset fr "Toolbar" "Barre d'outils" +::msgcat::mcset fr "Undo" "DИfaire" +::msgcat::mcset fr "Update" "Mise Ю jour" +::msgcat::mcset fr "Version" "Version" +::msgcat::mcset fr "View" "Vue" +::msgcat::mcset fr "Warning" "Avertissement" +::msgcat::mcset fr "Was replacement" "A ИtИ remplacИ" +::msgcat::mcset fr "Work dir" "RИpertoire de travail" + + + + diff --git a/msgs/ru.msg b/msgs/ru.msg new file mode 100644 index 0000000..40e18fa --- /dev/null +++ b/msgs/ru.msg @@ -0,0 +1,171 @@ +########################################################### +# Tcl/Tk Project Manager # +# russian messages file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +::msgcat::mcset ru "About ..." "п· п©я─п╬пЁя─п╟п╪п╪п╣" +::msgcat::mcset ru "Add to project" "п■п╬п╠п╟п╡п╦я┌я▄ п╡ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Archive created in" "п░я─я┘п╦п╡ п©п╬п╪п╣я┴п╣п╫ п╡" +::msgcat::mcset ru "Author" "п░п╡я┌п╬я─" +::msgcat::mcset ru "Braces" "п║п╨п╬п╠п╨п╦" +::msgcat::mcset ru "Quad braces" "п п╡п╟п╢я─я┌п╟п╫я▀п╣ я│п╨п╬п╠п╨п╦" +::msgcat::mcset ru "Braces background" "п╓п╬п╫ я│п╨п╬п╠п╨п╦" +::msgcat::mcset ru "Braces foreground" "п╕п╡п╣я┌ я│п╨п╬п╠п╨п╦" +::msgcat::mcset ru "Cancel" "п·я┌п╪п╣п╫п╟" +::msgcat::mcset ru "Can't found file:" "п²п╣ п╫п╟п╧п╢п╣п╫ я└п╟п╧п╩:" +::msgcat::mcset ru "Close" "п≈п╟п╨я─я▀я┌я▄" +::msgcat::mcset ru "Close all" "п≈п╟п╨я─я▀я┌я▄ п╡я│п╣" +::msgcat::mcset ru "Close Project Manager?" "п▓я▀п╧я┌п╦ п╦п╥ п©я─п╬пЁя─п╟п╪п╪я▀?" +::msgcat::mcset ru "Comments" "п п╬п╪п╣п╫я┌п╟я─п╦п╦" +::msgcat::mcset ru "Company" "п п╬п╪п©п╟п╫п╦я▐" +::msgcat::mcset ru "Compiler" "п п╬п╪п©п╦п╩я▐я┌п╬я─" +::msgcat::mcset ru "Compile" "п п╬п╪п©п╦п╩я▐я├п╦я▐" +::msgcat::mcset ru "Compile project" "п п╬п╪п©п╦п╩я▐я├п╦я▐ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Compile file" "п п╬п╪п©п╦п╩я▐я├п╦я▐ я└п╟п╧п╩п╟" +::msgcat::mcset ru "Contents" "п║п╬п╢п╣я─п╤п╟п╫п╦п╣" +::msgcat::mcset ru "Copy" "п║п╨п╬п©п╦я─п╬п╡п╟я┌я▄" +::msgcat::mcset ru "Copy into clipboard" "п║п╨п╬п©п╦я─п╬п╡п╟я┌я▄ п╡ п╠я┐я└п╣я─" +::msgcat::mcset ru "Create" "п║п╬п╥п╢п╟я┌я▄" +::msgcat::mcset ru "Create new project" "п║п╬п╥п╢п╟я┌я▄ п╫п╬п╡я▀п╧ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Create new file" "п║п╬п╥п╢п╟я┌я▄ п╫п╬п╡я▀п╧ я└п╟п╧п╩" +::msgcat::mcset ru "Create directory" "п║п╬п╥п╢п╟я┌я▄ п╢п╦я─п╣п╨я┌п╬я─п╦я▌" +::msgcat::mcset ru "Create backup files" "п║п╬п╥п╢п╟п╡п╟я┌я▄ п╡я─п╣п╪п╣п╫п╫я▀п╣ я└п╟п╧п╩я▀" +::msgcat::mcset ru "Curent directory" "п╒п╣п╨я┐я┴п╦п╧ п╨п╟я┌п╟п╩п╬пЁ" +::msgcat::mcset ru "Cut" "п▓я▀я─п╣п╥п╟я┌я▄" +::msgcat::mcset ru "Cut into clipboard" "п▓я▀я─п╣п╥п╟я┌я▄ п╡ п╠я┐я└п╣я─" +::msgcat::mcset ru "CVS commit" "п÷п╬п╪п╣я│я┌п╦я┌я▄ п╡ CVS" +::msgcat::mcset ru "CVS update" "п·п╠п╫п╬п╡п╦я┌я▄ п╦п╥ CVS" +::msgcat::mcset ru "Delete" "пёп╢п╟п╩п╦я┌я▄" +::msgcat::mcset ru "Delete file" "пёп╢п╟п╩п╦я┌я▄ я└п╟п╧п╩" +::msgcat::mcset ru "Delete backup files" "пёп╢п╟п╩я▐я┌я▄ п╡я─п╣п╪п╣п╫п╫я▀п╣ я└п╟п╧п╩я▀" +::msgcat::mcset ru "Delete project" "пёп╢п╟п╩п╦я┌я▄ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Delete from project" "пёп╢п╟п╩п╦я┌я▄ п╦п╥ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Docs dir" "п п╟я┌п╟п╩п╬пЁ п╢п╬п╨я┐п╪п╣п╫я┌п╟я├п╦п╦" +::msgcat::mcset ru "Don't selected file" "п²п╣ п╬п©я─п╣п╢п╣п╩п╣п╫ я└п╟п╧п╩" +::msgcat::mcset ru "E-mail" "п╜п╩. п©п╬я┤я┌п╟" +::msgcat::mcset ru "Edit" "п═п╣п╢п╟п╨я┌п╦я─п╬п╡п╟п╫п╦п╣" +::msgcat::mcset ru "Editor" "п═п╣п╢п╟п╨я┌п╬я─" +::msgcat::mcset ru "Editor background" "п╕п╡п╣я┌ я└п╬п╫п╟" +::msgcat::mcset ru "Editor foreground" "п╕п╡п╣я┌ я┬я─п╦я└я┌п╟" +::msgcat::mcset ru "Editor font" "п╗я─п╦я└я┌ я─п╣п╢п╟п╨я┌п╬я─п╟" +::msgcat::mcset ru "Editor font bold" "п╗я─п╦я└я┌ я─п╣п╢п╟п╨я┌п╬я─п╟ п╤п╦я─п╫я▀п╧" +::msgcat::mcset ru "Encode" "п÷п╣я─п╣п╨п╬п╢п╦я─п╬п╡п╨п╟" +::msgcat::mcset ru "Error open URL" "п·я┬п╦п╠п╨п╟ п╬я┌п╨я─я▀я┌п╦я▐ URL" +::msgcat::mcset ru "Exit" "п▓я▀я┘п╬п╢" +::msgcat::mcset ru "File" "п╓п╟п╧п╩" +::msgcat::mcset ru "File already exists. Overwrite?" "п╓п╟п╧п╩ я┐п╤п╣ я│я┐я┴п╣я│я┌п╡я┐п╣я┌. п÷п╣я─п╣п©п╦я│п╟я┌я▄?" +::msgcat::mcset ru "File was modifyed. Close?" "п╓п╟п╧п╩ п╠я▀п╩ п╦п╥п╪п╣п╫п╣п╫. п≈п╟п╨я─я▀я┌я▄?" +::msgcat::mcset ru "File was modifyed. Save?" "п╓п╟п╧п╩ п╠я▀п╩ п╦п╥п╪п╣п╫п╣п╫. п║п╬я┘я─п╟п╫п╦я┌я▄?" +::msgcat::mcset ru "File modify" "п╓п╟п╧п╩ п╦п╥п╪п╣п╫п╣п╫" +::msgcat::mcset ru "File saved" "п╓п╟п╧п╩ я│п╬я┘я─п╟п╫п╣п╫" +::msgcat::mcset ru "Find" "п²п╟п╧я┌п╦" +::msgcat::mcset ru "Font normal" "п²п╬я─п╪п╟п╩я▄п╫я▀п╧ я┬я─п╦я└я┌" +::msgcat::mcset ru "Font bold" "п√п╦я─п╫я▀п╧ я┬я─п╦я└я┌" +::msgcat::mcset ru "FTP password" "FTP п©п╟я─п╬п╩я▄" +::msgcat::mcset ru "FTP server" "FTP я│п╣я─п╡п╣я─" +::msgcat::mcset ru "FTP user" "FTP п©п╬п╩я▄п╥п╬п╡п╟я┌п╣п╩я▄" +::msgcat::mcset ru "Goto line" "п÷п╣я─п╣п╧я┌п╦ п╨ ..." +::msgcat::mcset ru "Help" "п÷п╬п╪п╬я┴я▄" +::msgcat::mcset ru "Home dir" "п■п╬п╪п╟я┬п╫п╦п╧ п╨п╟я┌п╟п╩п╬пЁ" +::msgcat::mcset ru "Home page" "п■п╬п╪п╟я┬п╫я▐я▐ я│я┌я─п╟п╫п╦я├п╟" +::msgcat::mcset ru "Image dir" "п п╟я┌п╟п╩п╬пЁ п╦п╥п╬п╠я─п╟п╤п╣п╫п╦п╧" +::msgcat::mcset ru "Insert" "п▓я│я┌п╟п╡п╨п╟" +::msgcat::mcset ru "Interface language" "п╞п╥я▀п╨ п╦п╫я┌п╣я─я└п╣п╧я│п╟" +::msgcat::mcset ru "Interpetator" "п≤п╫я┌п╣я─п©я─п╣я┌п╟я┌п╬я─" +::msgcat::mcset ru "Install Tcl/Tk Project Manager" "пёя│я┌п╟п╫п╬п╡п╨п╟ Tcl/Tk Project Manager" +::msgcat::mcset ru "Input file name" "п▓п╡п╣п╢п╦я┌п╣ п╦п╪я▐ я└п╟п╧п╩п╟" +::msgcat::mcset ru "Label" "п°п╣я┌п╨п╟" +::msgcat::mcset ru "Line number" "п²п╬п╪п╣я─ я│я┌я─п╬п╨п╦" +::msgcat::mcset ru "Make RPM" "п║п╬п╥п╢п╟я┌я▄ RPM" +::msgcat::mcset ru "Make archive" "п║п╬п╥п╢п╟я┌я▄ п╟я─я┘п╦п╡" +::msgcat::mcset ru "Make backup files" "п║п╬п╥п╢п╟п╡п╟я┌я▄ п╡я─п╣п╪п╣п╫п╫я▀п╣ я└п╟п╧п╩я▀" +::msgcat::mcset ru "Main" "п·п╠я┴п╦п╣" +::msgcat::mcset ru "Modules" "п°п╬п╢я┐п╩п╦" +::msgcat::mcset ru "Modifying the Registry..." "п▓п╫п╣я│п╣п╫п╦п╣ п╦п╥п╪п╣п╫п╣п╫п╦п╧ п╡ я─п╣п╣я│я┌я─" +::msgcat::mcset ru "Must be one file select!" "п▓я▀ п╢п╬п╩п╤п╫я▀ п╡я▀п╠я─п╟я┌я▄ я┌п╬п╩я▄п╨п╬ п╬п╢п╦п╫ я└п╟п╧п╩" +::msgcat::mcset ru "Must be one or two file select!" "п▓я▀ п╢п╬п╩п╤п╫я▀ п╡я▀п╠я─п╟я┌я▄ п╬п╢п╦п╫ п╦п╩п╦ п╢п╡п╟ я└п╟п╧п╩п╟" +::msgcat::mcset ru "Network" "п║п╣я┌я▄" +::msgcat::mcset ru "New" "п²п╬п╡я▀п╧" +::msgcat::mcset ru "New directory" "п²п╬п╡я▀п╧ п╨п╟я┌п╟п╩п╬пЁ" +::msgcat::mcset ru "New file" "п²п╬п╡я▀п╧ я└п╟п╧п╩" +::msgcat::mcset ru "New project" "п²п╬п╡я▀п╧ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Not implemented yet" "п■п╟п╫п╫п╟я▐ я└я┐п╫п╨я├п╦я▐ п©п╬п╨п╟ п╫п╣ я─п╣п╟п╩п╦п╥п╬п╡п╟п╫п╟" +::msgcat::mcset ru "Not found active project" "п²п╣ п╬п©я─п╣п╢п╣п╩п╣п╫ п╟п╨я┌п╦п╡п╫я▀п╧ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Open" "п·я┌п╨я─я▀я┌я▄" +::msgcat::mcset ru "Open file" "п·я┌п╨я─я▀я┌я▄ я└п╟п╧п╩" +::msgcat::mcset ru "Open project" "п·я┌п╨я─я▀я┌я▄ п©я─п╬п╣п╨я┌" +::msgcat::mcset ru "Opened file in progress" "п·я┌п╨я─я▀я┌п╦п╣ я└п╟п╧п╩п╟" +::msgcat::mcset ru "Operators" "п·п©п╣я─п╟я┌п╬я─я▀" +::msgcat::mcset ru "Overwrite" "п≈п╟п╪п╣п╫п╟" +::msgcat::mcset ru "Parameters" "п÷п╟я─п╟п╪п╣я┌я─я▀" +::msgcat::mcset ru "Subparameters" "п║я┐п╠п©п╟я─п╟п╪п╣я┌я─я▀" +::msgcat::mcset ru "Paste" "п▓я│я┌п╟п╡п╦я┌я▄" +::msgcat::mcset ru "Paste from clipboard" "п▓я│я┌п╟п╡п╦я┌я▄ п╦п╥ п╠я┐я└п╣я─п╟" +::msgcat::mcset ru "Percent %" "п≈п╫п╟п╨ п©я─п╬я├п╣п╫я┌п╟" +::msgcat::mcset ru "Print ..." "п÷п╣я┤п╟я┌я▄ ..." +::msgcat::mcset ru "Print" "п÷п╣я┤п╟я┌я▄" +::msgcat::mcset ru "Print command" "п п╬п╪п╟п╫п╢п╟ п©п╣я┤п╟я┌п╦" +::msgcat::mcset ru "Print selected text" "п÷п╣я┤п╟я┌п╟я┌я▄ п╡я▀п╢п╣п╩п╣п╫п╫я▀п╧ я┌п╣п╨я│я┌" +::msgcat::mcset ru "Procedure name" "п≤п╪я▐ п©я─п╬я├п╣п╢я┐я─я▀" +::msgcat::mcset ru "Procedure name complit" "п░п╡я┌п╬п╢п╬п╠п╦п╡п╨п╟ п©я─п╬я├п╣п╢я┐я─я▀" +::msgcat::mcset ru "Program finished successfully" "п▓я▀п©п╬п╩п╫п╣п╫п╦п╣ п╥п╟п╡п╣я─я┬п╣п╫п╬" +::msgcat::mcset ru "Program failed" "п·я┬п╦п╠п╨п╟ п╡я▀п©п╬п╩п╫п╣п╫п╦я▐" +::msgcat::mcset ru "Programm output" "п▓я▀п╡п╬п╢ п©я─п╬пЁя─п╟п╪п╪я▀" +::msgcat::mcset ru "Project" "п÷я─п╬п╣п╨я┌" +::msgcat::mcset ru "Projects" "п÷я─п╬п╣п╨я┌я▀" +::msgcat::mcset ru "Project settings" "пёя│я┌п╟п╫п╬п╡п╨п╦ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Project name" "п²п╟п╥п╡п╟п╫п╦п╣ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Project file" "п╓п╟п╧п╩ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Project dir" "п п╟я┌п╟п╩п╬пЁ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Quit without saving?" "п▓я▀п╧я┌п╦ п╠п╣п╥ я│п╬я┘я─п╟п╫п╣п╫п╦я▐?" +::msgcat::mcset ru "Question" "п▓п╬п©я─п╬я│" +::msgcat::mcset ru "Quote string" "п║я┌я─п╬п╨п╟ п╡ п╨п╟п╡я▀я┤п╨п╟я┘" +::msgcat::mcset ru "Redo" "п÷п╬п╡я┌п╬я─п╦я┌я▄" +::msgcat::mcset ru "Refresh" "п·п╠п╫п╬п╡п╦я┌я▄" +::msgcat::mcset ru "Replace" "п≈п╟п╪п╣п╫п╟" +::msgcat::mcset ru "Replace with" "п≈п╟п╪п╣п╫п╦я┌я▄ п╫п╟" +::msgcat::mcset ru "Replace all" "п≈п╟п╪п╣п╫п╦я┌я▄ п╡я│п╣" +::msgcat::mcset ru "Release" "п▓я▀п©я┐я│п╨" +::msgcat::mcset ru "RPM dir" "п п╟я┌п╟п╩п╬пЁ RPM" +::msgcat::mcset ru "RPM file mask" "п°п╟я│п╨п╟ RPM" +::msgcat::mcset ru "Run" "п▓я▀п©п╬п╩п╫п╦я┌я▄" +::msgcat::mcset ru "Run file" "п≈п╟п©я┐я│я┌п╦я┌я▄ я└п╟п╧п╩" +::msgcat::mcset ru "Running project" "п▓я▀п©п╬п╩п╫п╣п╫п╦п╣ п©я─п╬п╣п╨я┌п╟" +::msgcat::mcset ru "Running file" "п▓я▀п©п╬п╩п╫п╣п╫п╦п╣ я└п╟п╧п╩п╟" +::msgcat::mcset ru "Save" "п║п╬я┘я─п╟п╫п╦я┌я▄" +::msgcat::mcset ru "Save file" "п║п╬я┘я─п╟п╫п╦я┌я▄ я└п╟п╧п╩" +::msgcat::mcset ru "Save file as" "п║п╬я┘я─п╟п╫п╦я┌я▄ я└п╟п╧п╩ п╨п╟п╨ ..." +::msgcat::mcset ru "Save as" "п║п╬я┘я─п╟п╫п╦я┌я▄ п╨п╟п╨ ..." +::msgcat::mcset ru "Save all" "п║п╬я┘я─п╟п╫п╦я┌я▄ п╡я│п╣" +::msgcat::mcset ru "Search" "п÷п╬п╦я│п╨" +::msgcat::mcset ru "Select" "п▓я▀п╠я─п╟я┌я▄" +::msgcat::mcset ru "Select all" "п▓я▀п╢п╣п╩п╦я┌я▄ п╡я│п╣" +::msgcat::mcset ru "Select directory" "п▓я▀п╠п╬я─ п╢п╦я─п╣п╨я┌п╬я─п╦п╦" +::msgcat::mcset ru "Selected directory" "п■п╦я─п╣п╨я┌п╬я─п╦я▐" +::msgcat::mcset ru "Selection color" "п╕п╡п╣я┌ п╡я▀п╢п╣п╩п╣п╫п╦я▐" +::msgcat::mcset ru "Settings" "пёя│я┌п╟п╫п╬п╡п╨п╦" +::msgcat::mcset ru "Show backup files" "п÷п╬п╨п╟п╥я▀п╡п╟я┌я▄ п╡я─п╣п╪п╣п╫п╫я▀п╣ я└п╟п╧п╩я▀" +::msgcat::mcset ru "Split edit window" "п═п╟п╥п╢п╣п╩п╦я┌я▄ п╬п╨п╫п╬ я─п╣п╢п╟п╨я┌п╬я─п╟" +::msgcat::mcset ru "Text autoformat" "п░п╡я┌п╬я└п╬я─п╪п╟я┌ я┌п╣п╨я│я┌п╟" +::msgcat::mcset ru "TGZ dir" "п п╟я┌п╟п╩п╬пЁ TGZ" +::msgcat::mcset ru "TGZ file mask" "п°п╟я│п╨п╟ TGZ" +::msgcat::mcset ru "Thanks" "п▒п╩п╟пЁп╬п╢п╟я─п╫п╬я│я┌п╦" +::msgcat::mcset ru "Title normal" "п╓п╟п╧п╩ п╫п╬я─п╪п╟п╩я▄п╫я▀п╧" +::msgcat::mcset ru "Title modify" "п╓п╟п╧п╩ п╦п╥п╪п╣п╫п╣п╫" +::msgcat::mcset ru "Toolbar" "п÷п╟п╫п╣п╩я▄ п╦п╫я│я┌я─я┐п╪п╣п╫я┌п╬п╡" +::msgcat::mcset ru "Undo" "п·я┌п╪п╣п╫п╦я┌я▄" +::msgcat::mcset ru "Update" "п·п╠п╫п╬п╡п╦я┌я▄" +::msgcat::mcset ru "Variables" "п÷п╣я─п╣п╪п╣п╫п╫я▀п╣" +::msgcat::mcset ru "Version" "п▓п╣я─я│п╦я▐" +::msgcat::mcset ru "View" "п▓п╦п╢" +::msgcat::mcset ru "Warning" "п▓п╫п╦п╪п╟п╫п╦п╣" +::msgcat::mcset ru "Was replacement" "п▒я▀п╩п╬ п╥п╟п╪п╣п╫п╣п╫п╬" +::msgcat::mcset ru "Word wrapping" "п÷п╣я─п╣п╫п╬я│ я│п╩п╬п╡" +::msgcat::mcset ru "Work dir" "п═п╟п╠п╬я┤п╦п╧ п╨п╟я┌п╟п╩п╬пЁ" + + + + + diff --git a/msgs/ru_koi8.msg b/msgs/ru_koi8.msg new file mode 100644 index 0000000..a3ef67a --- /dev/null +++ b/msgs/ru_koi8.msg @@ -0,0 +1,169 @@ +########################################################### +# Tcl/Tk Project Manager # +# russian messages file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +::msgcat::mcset ru "About ..." "О программе" +::msgcat::mcset ru "Add to project" "Добавить в проект" +::msgcat::mcset ru "Archive created in" "Архив помещен в" +::msgcat::mcset ru "Author" "Автор" +::msgcat::mcset ru "Braces" "Скобки" +::msgcat::mcset ru "Quad braces" "Квадртаные скобки" +::msgcat::mcset ru "Braces background" "Фон скобки" +::msgcat::mcset ru "Braces foreground" "Цвет скобки" +::msgcat::mcset ru "Cancel" "Отмена" +::msgcat::mcset ru "Can't found file:" "Не найден файл:" +::msgcat::mcset ru "Close" "Закрыть" +::msgcat::mcset ru "Close all" "Закрыть все" +::msgcat::mcset ru "Close Project Manager?" "Выйти из программы?" +::msgcat::mcset ru "Comments" "Коментарии" +::msgcat::mcset ru "Company" "Компания" +::msgcat::mcset ru "Compiler" "Компилятор" +::msgcat::mcset ru "Compile" "Компиляция" +::msgcat::mcset ru "Compile project" "Компиляция проекта" +::msgcat::mcset ru "Compile file" "Компиляция файла" +::msgcat::mcset ru "Contents" "Содержание" +::msgcat::mcset ru "Copy" "Скопировать" +::msgcat::mcset ru "Copy into clipboard" "Скопировать в буфер" +::msgcat::mcset ru "Create" "Создать" +::msgcat::mcset ru "Create new project" "Создать новый проект" +::msgcat::mcset ru "Create new file" "Создать новый файл" +::msgcat::mcset ru "Create directory" "Создать директорию" +::msgcat::mcset ru "Create backup files" "Создавать временные файлы" +::msgcat::mcset ru "Curent directory" "Текущий каталог" +::msgcat::mcset ru "Cut" "Вырезать" +::msgcat::mcset ru "Cut into clipboard" "Вырезать в буфер" +::msgcat::mcset ru "CVS commit" "Поместить в CVS" +::msgcat::mcset ru "CVS update" "Обновить из CVS" +::msgcat::mcset ru "Delete" "Удалить" +::msgcat::mcset ru "Delete file" "Удалить файл" +::msgcat::mcset ru "Delete backup files" "Удалять временные файлы" +::msgcat::mcset ru "Delete project" "Удалить проект" +::msgcat::mcset ru "Delete from project" "Удалить из проекта" +::msgcat::mcset ru "Docs dir" "Каталог документации" +::msgcat::mcset ru "Don't selected file" "Не определен файл" +::msgcat::mcset ru "E-mail" "Эл. почта" +::msgcat::mcset ru "Edit" "Редактирование" +::msgcat::mcset ru "Editor" "Редактор" +::msgcat::mcset ru "Editor background" "Цвет фона" +::msgcat::mcset ru "Editor foreground" "Цвет шрифта" +::msgcat::mcset ru "Editor font" "Шрифт редактора" +::msgcat::mcset ru "Editor font bold" "Шрифт редактора жирный" +::msgcat::mcset ru "Error open URL" "Ошибка открытия URL" +::msgcat::mcset ru "Exit" "Выход" +::msgcat::mcset ru "File" "Файл" +::msgcat::mcset ru "File already exists. Overwrite?" "Файл уже существует. Переписать?" +::msgcat::mcset ru "File was modifyed. Close?" "Файл был изменен. Закрыть?" +::msgcat::mcset ru "File was modifyed. Save?" "Файл был изменен. Сохранить?" +::msgcat::mcset ru "File modify" "Файл изменен" +::msgcat::mcset ru "File saved" "Файл сохранен" +::msgcat::mcset ru "Find" "Найти" +::msgcat::mcset ru "Font normal" "Нормальный шрифт" +::msgcat::mcset ru "Font bold" "Жирный шрифт" +::msgcat::mcset ru "FTP password" "FTP пароль" +::msgcat::mcset ru "FTP server" "FTP сервер" +::msgcat::mcset ru "FTP user" "FTP пользователь" +::msgcat::mcset ru "Goto line" "Перейти к ..." +::msgcat::mcset ru "Help" "Помощь" +::msgcat::mcset ru "Home dir" "Домашний каталог" +::msgcat::mcset ru "Home page" "Домашняя страница" +::msgcat::mcset ru "Image dir" "Каталог изображений" +::msgcat::mcset ru "Insert" "Вставка" +::msgcat::mcset ru "Interface language" "Язык интерфейса" +::msgcat::mcset ru "Interpetator" "Интерпретатор" +::msgcat::mcset ru "Install Tcl/Tk Project Manager" "Установка Tcl/Tk Project Manager" +::msgcat::mcset ru "Input file name" "Введите имя файла" +::msgcat::mcset ru "Label" "Метка" +::msgcat::mcset ru "Line number" "Номер строки" +::msgcat::mcset ru "Make RPM" "Создать RPM" +::msgcat::mcset ru "Make archive" "Создать архив" +::msgcat::mcset ru "Make backup files" "Создавать временные файлы" +::msgcat::mcset ru "Main" "Общие" +::msgcat::mcset ru "Modules" "Модули" +::msgcat::mcset ru "Modifying the Registry..." "Внесение изменений в реестр" +::msgcat::mcset ru "Must be one file select!" "Вы должны выбрать только один файл" +::msgcat::mcset ru "Must be one or two file select!" "Вы должны выбрать один или два файла" +::msgcat::mcset ru "Network" "Сеть" +::msgcat::mcset ru "New" "Новый" +::msgcat::mcset ru "New directory" "Новый каталог" +::msgcat::mcset ru "New file" "Новый файл" +::msgcat::mcset ru "New project" "Новый проект" +::msgcat::mcset ru "Not implemented yet" "Данная функция пока не реализована" +::msgcat::mcset ru "Not found active project" "Не определен активный проект" +::msgcat::mcset ru "Open" "Открыть" +::msgcat::mcset ru "Open file" "Открыть файл" +::msgcat::mcset ru "Open project" "Открыть проект" +::msgcat::mcset ru "Opened file in progress" "Открытие файла" +::msgcat::mcset ru "Operators" "Операторы" +::msgcat::mcset ru "Overwrite" "Замена" +::msgcat::mcset ru "Parameters" "Параметры" +::msgcat::mcset ru "Subparameters" "Субпараметры" +::msgcat::mcset ru "Paste" "Вставить" +::msgcat::mcset ru "Paste from clipboard" "Вставить из буфера" +::msgcat::mcset ru "Percent %" "Знак процента" +::msgcat::mcset ru "Print ..." "Печать ..." +::msgcat::mcset ru "Print" "Печать" +::msgcat::mcset ru "Print command" "Команда печати" +::msgcat::mcset ru "Print selected text" "Печатать выделенный текст" +::msgcat::mcset ru "Procedure name" "Имя процедуры" +::msgcat::mcset ru "Procedure name complit" "Автодобивка процедуры" +::msgcat::mcset ru "Program finished successfully" "Выполнение завершено" +::msgcat::mcset ru "Program failed" "Ошибка выполнения" +::msgcat::mcset ru "Programm output" "Вывод программы" +::msgcat::mcset ru "Project" "Проект" +::msgcat::mcset ru "Projects" "Проекты" +::msgcat::mcset ru "Project settings" "Установки проекта" +::msgcat::mcset ru "Project name" "Название проекта" +::msgcat::mcset ru "Project file" "Файл проекта" +::msgcat::mcset ru "Project dir" "Каталог проекта" +::msgcat::mcset ru "Quit without saving?" "Выйти без сохранения?" +::msgcat::mcset ru "Question" "Вопрос" +::msgcat::mcset ru "Quote string" "Строка в кавычках" +::msgcat::mcset ru "Redo" "Повторить" +::msgcat::mcset ru "Refresh" "Обновить" +::msgcat::mcset ru "Replace" "Замена" +::msgcat::mcset ru "Replace with" "Заменить на" +::msgcat::mcset ru "Replace all" "Заменить все" +::msgcat::mcset ru "Release" "Выпуск" +::msgcat::mcset ru "RPM dir" "Каталог RPM" +::msgcat::mcset ru "RPM file mask" "Маска RPM" +::msgcat::mcset ru "Run" "Выполнить" +::msgcat::mcset ru "Run file" "Запустить файл" +::msgcat::mcset ru "Running project" "Выполнение проекта" +::msgcat::mcset ru "Running file" "Выполнение файла" +::msgcat::mcset ru "Save" "Сохранить" +::msgcat::mcset ru "Save file" "Сохранить файл" +::msgcat::mcset ru "Save file as" "Сохранить файл как ..." +::msgcat::mcset ru "Save as" "Сохранить как ..." +::msgcat::mcset ru "Save all" "Сохранить все" +::msgcat::mcset ru "Search" "Поиск" +::msgcat::mcset ru "Select" "Выбрать" +::msgcat::mcset ru "Select all" "Выделить все" +::msgcat::mcset ru "Select directory" "Выбор директории" +::msgcat::mcset ru "Selected directory" "Директория" +::msgcat::mcset ru "Selection color" "Цвет выделения" +::msgcat::mcset ru "Settings" "Установки" +::msgcat::mcset ru "Show backup files" "Показывать временные файлы" +::msgcat::mcset ru "Split edit window" "Разделить окно редактора" +::msgcat::mcset ru "Text autoformat" "Автоформат текста" +::msgcat::mcset ru "TGZ dir" "Каталог TGZ" +::msgcat::mcset ru "TGZ file mask" "Маска TGZ" +::msgcat::mcset ru "Thanks" "Благодарности" +::msgcat::mcset ru "Title normal" "Файл нормальный" +::msgcat::mcset ru "Title modify" "Файл изменен" +::msgcat::mcset ru "Toolbar" "Панель инструментов" +::msgcat::mcset ru "Undo" "Отменить" +::msgcat::mcset ru "Update" "Обновить" +::msgcat::mcset ru "Variables" "Переменные" +::msgcat::mcset ru "Version" "Версия" +::msgcat::mcset ru "View" "Вид" +::msgcat::mcset ru "Warning" "Внимание" +::msgcat::mcset ru "Was replacement" "Было заменено" +::msgcat::mcset ru "Word wrapping" "Перенос слов" +::msgcat::mcset ru "Work dir" "Рабочий каталог" + + + + diff --git a/pane.tcl b/pane.tcl new file mode 100644 index 0000000..61f686d --- /dev/null +++ b/pane.tcl @@ -0,0 +1,99 @@ +package provide pane 1.0 + +namespace eval pane { + + namespace export create + + proc create { f1 f2 args } { + global editor + set t(-orient) vertical + set t(-percent) 0.25 + set t(-gripcolor) $editor(bg) + set t(-gripposition) 0.95 + set t(-gripcursor) crosshair + set t(-in) [winfo parent $f1] + array set t $args + + set master $t(-in) + upvar #0 [namespace current]::Pane$master pane + array set pane [array get t] + + if {! [string match v* $pane(-orient)] } { + set pane(-gripcursor) sb_v_double_arrow + set height 5 ; set width 3000 + } else { + set pane(-gripcursor) sb_h_double_arrow + set height 3000 ; set width 5 + } + + set pane(1) $f1 + set pane(2) $f2 + set pane(grip) [frame $master.grip -background $pane(-gripcolor) \ + -width $width -height $height \ + -bd 1 -relief raised -cursor $pane(-gripcursor)] + + if {! [string match v* $pane(-orient)] } { + set pane(D) Y + place $pane(1) -in $master -x 0 -rely 0.0 -anchor nw -relwidth 1.0 -height -1 + place $pane(2) -in $master -x 0 -rely 1.0 -anchor sw -relwidth 1.0 -height -1 + place $pane(grip) -in $master -anchor c -relx $pane(-gripposition) + } else { + set pane(D) X + place $pane(1) -in $master -relx 0.0 -y 0 -anchor nw -relheight 1.0 -width -1 + place $pane(2) -in $master -relx 1.0 -y 0 -anchor ne -relheight 1.0 -width -1 + place $pane(grip) -in $master -anchor c -rely 0 ;#$pane(-gripposition) + } + $master configure -background gray50 + + bind $master [list [namespace current]::PaneGeometry $master] + bind $pane(grip) \ + [list [namespace current]::PaneDrag $master %$pane(D)] + bind $pane(grip) \ + [list [namespace current]::PaneDrag $master %$pane(D)] + bind $pane(grip) \ + [list [namespace current]::PaneStop $master] + + [namespace current]::PaneGeometry $master + } + + proc PaneDrag { master D } { + upvar #0 [namespace current]::Pane$master pane + if {[info exists pane(lastD)]} { + set delta [expr double($pane(lastD) - $D) \ + / $pane(size)] + set pane(-percent) [expr $pane(-percent) - $delta] + if {$pane(-percent) < 0.0} { + set pane(-percent) 0.0 + } elseif {$pane(-percent) > 1.0} { + set pane(-percent) 1.0 + } + [namespace current]::PaneGeometry $master + } + set pane(lastD) $D + } + + proc PaneStop { master } { + upvar #0 [namespace current]::Pane$master pane + catch {unset pane(lastD)} + } + + proc PaneGeometry { master } { + upvar #0 [namespace current]::Pane$master pane + if {$pane(D) == "X"} { + place $pane(1) -relwidth $pane(-percent) + place $pane(2) -relwidth [expr 1.0 - $pane(-percent)] + place $pane(grip) -relx $pane(-percent) + set pane(size) [winfo width $master] + } else { + place $pane(1) -relheight $pane(-percent) + place $pane(2) -relheight [expr 1.0 - $pane(-percent)] + place $pane(grip) -rely $pane(-percent) + set pane(size) [winfo height $master] + } + } + +} + + + + diff --git a/procedure.tcl b/procedure.tcl new file mode 100644 index 0000000..ae0fce7 --- /dev/null +++ b/procedure.tcl @@ -0,0 +1,1117 @@ +########################################################### +# Tcl/Tk Project Manager # +# Distributed under GPL # +# all procedure file # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +## INSERT TEXT INTO ENTRY BOmX ## +proc InsertEnt {entry text} { + $entry delete 0 end + $entry insert end $text +} + +## GET TEXT FROM ENTRY WIDGET ## +proc Text {entry} { + set text [$entry get] +} +## FONT SELECTOR DIALOG ## +proc SelectFontDlg {font text} { + set font [SelectFont .fontdlg -parent . -font $font] + if { $font != "" } { + InsertEnt $text $font + } +} +## STATUS BAR OR ANYTHING LABEL TEXT UPDATE ## +proc LabelUpdate {widget value} { + global fontNormal + $widget configure -text $value -font $fontNormal +} +## SHOW PUP-UP MENUS ## +proc PopupMenuTree {x y} { + global tree fontNormal fontBold imgDir activeProject + set node [$tree selection get] + if {$node ==""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning] + case $answer { + ok {return 0} + } + } + $tree selection set $node + set item [$tree itemcget $node -data] + if {[string range $item 0 2] == "prj"} { + set activeProject [string range $item 4 end] + .frmStatus.frmActive.lblActive configure -text [$tree itemcget $node -text] -font $fontBold + tk_popup .popupProj $x $y + return + } + if {[info exists fileList($node)] != 1} { + # set fileList($node) $item + tk_popup .popupFile $x $y + } +} +proc PopupMenuEditor {x y} { + tk_popup .popMnuEdit $x $y +} +## GETTING FILE ATTRIBUTES ## +proc FileAttr {file} { + global tcl_platform + set fileAttribute "" + # get file modify time + if {$tcl_platform(platform) == "windows"} { + set unixTime [file mtime $file] + set modifyTime [clock format $unixTime -format "%d/%m/%Y, %H:%M"] + append fileAttribute $modifyTime + } elseif {$tcl_platform(platform) == "mac"} { + +} elseif {$tcl_platform(platform) == "unix"} { + set unixTime [file mtime $file] + set modifyTime [clock format $unixTime -format "%d/%m/%Y, %H:%M"] + append fileAttribute $modifyTime +} +# get file size +set size [file size $file] +if {$size < 1024} { + set fileSize "$size b" + } + if {$size >= 1024} { + set s [expr ($size.0) / 1024] + set dot [string first "\." $s] + set int [string range $s 0 [expr $dot - 1]] + set dec [string range $s [expr $dot + 1] [expr $dot + 2]] + set fileSize "$int.$dec Kb" + } + if {$size >= 1048576} { + set s [expr ($size.0) / 1048576] + set dot [string first "\." $s] + set int [string range $s 0 [expr $dot - 1]] + set dec [string range $s [expr $dot + 1] [expr $dot + 2]] + set fileSize "$int.$dec Mb" + } + append fileAttribute ", $fileSize" +} +## OPEN TREE PROCEDURE +proc TreeOpen {node} { + global fontNormal tree projDir workDir activeProject fileList noteBook findString imgDir fontBold + + $tree selection set $node + set item [$tree itemcget $node -data] + if {[string range $item 0 2] == "prj"} { + set activeProject [string range $item 4 end] + puts $activeProject + .frmStatus.frmActive.lblActive configure -text [$tree itemcget $node -text] -font $fontBold + $tree itemconfigure $node -image [Bitmap::get [file join $imgDir openfold.gif]] + if {[file exists [file join $workDir $activeProject.tags]] == 1} { + GetTagList [file join $workDir $activeProject.tags] ;# geting tag list + } else { + DoModule ctags + } + } + if {[info exists fileList($node)] != 1} { + set fileList($node) $item + if {[file isdirectory $item] == 1} { + $tree itemconfigure $node -image [Bitmap::get [file join $imgDir openfold.gif]] + } + } +} +## CLOSE TREE PROCEDURE ## +proc TreeClose {node} { + global fontNormal tree projDir workDir activeProject fileList noteBook findString imgDir fontBold + + $tree selection set $node + set item [$tree itemcget $node -data] + if {[string range $item 0 2] == "prj"} { + $tree itemconfigure $node -image [Bitmap::get [file join $imgDir folder.gif]] + } + if {[info exists fileList($node)] != 1} { + if {[file isdirectory $item] == 1} { + $tree itemconfigure $node -image [Bitmap::get [file join $imgDir folder.gif]] + } + } +} +## TREE ONE CLICK PROCEDURE ## +proc TreeOneClick {node} { + global fontNormal tree projDir workDir activeProject fileList noteBook findString imgDir fontBold + $tree selection set $node + set item [$tree itemcget $node -data] + if {[string range $item 0 2] == "prj"} { + set activeProject [string range $item 4 end] + puts $activeProject + .frmStatus.frmActive.lblActive configure -text [$tree itemcget $node -text] -font $fontBold + if {[file exists [file join $workDir $activeProject.tags]] == 1} { + GetTagList [file join $workDir $activeProject.tags] ;# geting tag list + } else { + DoModule ctags + } + return + } + if {[info exists fileList($node)] != 1} { + if {[file isdirectory $item] == 1} { + return + } else { + if {[file exists $item] == 1} { + LabelUpdate .frmStatus.frmHelp.lblHelp [FileAttr $item] + } + } + } else { + PageRaise $node + } + if {[string range $item 0 2] == "prc"} { + set parent [$tree parent $node] + set file [$tree itemcget $parent -data] + set fileExt [string range [file extension $file] 1 end] + if {[info exists fileList($parent)] == 0} { + EditFile $parent $file + } + PageRaise $parent + $tree selection set $node + set text "$noteBook.f$parent.text" + set index1 [expr [string first "_" $item]+1] + set index2 [expr [string last "_" $item]11] + if {$fileExt == "java" || $fileExt == "ja"} { + set findString "class [string range $item $index1 $index2] " + } elseif {$fileExt == "perl" || $fileExt == "pl"} { + set findString "sub [string range $item $index1 $index2]" + } elseif {$fileExt == "ml" || $fileExt == "mli"} { + set findString "let [string range $item $index1 $index2]" + } elseif {$fileExt == "php" || $fileExt == "phtml"} { + set findString "function [string range $item $index1 $index2]" + puts $findString + #return + } elseif {$fileExt == "rb"} { + set findString "class [string range $item $index1 $index2]" + } else { + set findString "proc [string range $item $index1 $index2] " + } + FindProc $text $findString $node + focus -force $text + } +} +## TREE DOUBLE CLICK PROCEDURE ## +proc TreeDoubleClick {node} { + global fontNormal tree projDir workDir activeProject fileList noteBook findString imgDir fontBold + + $tree selection set $node + set item [$tree itemcget $node -data] + if {[$tree itemcget $node -open] == 1} { + $tree itemconfigure $node -open 0 + } elseif {[$tree itemcget $node -open] == 0} { + $tree itemconfigure $node -open 1 + } + if {[string range $item 0 2] == "prj"} { + set activeProject [string range $item 4 end] + .frmStatus.frmActive.lblActive configure -text [$tree itemcget $node -text] -font $fontBold + GetTagList [file join $workDir $activeProject.tags] ;# geting tag list + } + + if {[info exists fileList($node)] != 1} { + if {[file isdirectory $item] == 1} { + GetFilesSubdir $node $item + } else { + if {[file exists $item] == 1} { + EditFile $node $item + LabelUpdate .frmStatus.frmFile.lblFile "[file size $item] b." + } + } + } + if {[string range $item 0 2] == "prc"} { + $tree selection set $node + set parent [$tree parent $node] + if {[info exists fileList($parent)] != 1} { + set file [$tree itemcget $parent -data] + EditFile $parent $file + $noteBook raise $parent + } else { + $noteBook raise $parent + } + set text "$noteBook.f$parent.text" + set index1 [expr [string first "_" $item]+1] + set index2 [expr [string last "_" $item]11] + set findString "proc [string range $item $index1 $index2] " + FindProc $text $findString $node + focus -force $text + } + +} +## GETTING FILES FROM SUBCIR ## +proc GetFilesSubdir {node dir} { + global fontNormal tree projDir workDir activeProject imgDir count + global backUpFileShow + set count 1 + set rList "" + if {[catch {cd $dir}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain .*]] { + if {$file == "." || $file == ".."} { + puts $file + } else { + lappend rList [list [file join $dir $file]] + set fileName [file join $file] + set img [GetImage $fileName] + set dot "_" + regsub -all {\.} $fileName "_" subNode + set subNode "$activeProject$dot$node$dot$subNode$dot$count" + if {[$tree exists $subNode] == 1} {return} + if {$backUpFileShow == "Yes"} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + if {$backUpFileShow == "No"} { + if {[file isdirectory $fileName] == 1} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } else { + if {[string index $fileName end] != "~"} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + } + } + } + incr count + } + foreach file [lsort [glob -nocomplain *]] { + lappend rList [list [file join $dir $file]] + set fileName [file join $file] + set img [GetImage $fileName] + set dot "_" + regsub -all {\.} $fileName "_" subNode + set subNode "$activeProject$dot$node$dot$subNode$dot$count" + if {[$tree exists $subNode] == 1} {return} + if {$backUpFileShow == "Yes"} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + if {$backUpFileShow == "No"} { + if {[file isdirectory $fileName] == 1} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } else { + if {[string index $fileName end] != "~"} { + $tree insert end $node $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + } + } + incr count + } + $tree itemconfigure $node -open 1 +} +## GETTING FILES FROM PROJECT DIR AND INSERT INTO TREE WIDGET ## +proc GetFiles {dir project tree} { + global fontNormal backUpFileShow imgDir + set rList "" + set count 1 + if {[catch {cd $dir}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain .*]] { + if {$file == "." || $file == ".."} { + puts $file + } else { + lappend rList [list [file join $dir $file]] + set fileName [file join $file] + set img [GetImage $fileName] + set dot "_" + regsub -all {\.} $fileName "_" subNode + set subNode "$project$dot$subNode$dot$count" + if {$backUpFileShow == "Yes"} { + $tree insert end $project $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + if {$backUpFileShow == "No"} { + if {[string index $fileName end] != "~"} { + $tree insert end $project $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + } + } + incr count + } + + foreach file [lsort [glob -nocomplain *]] { + lappend rList [list [file join $dir $file]] + set fileName [file join $file] + set img [GetImage $fileName] + set dot "_" + regsub -all {\.} $fileName "_" subNode + set subNode "$project$dot$subNode$dot$count" + if {$backUpFileShow == "Yes"} { + $tree insert end $project $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + if {$backUpFileShow == "No"} { + if {[string index $fileName end] != "~"} { + $tree insert end $project $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + } + } + incr count + } + $tree configure -redraw 1 +} +## GETTING PROJECT NAMES FROM DIR AND PUTS INTO +proc GetProj {tree} { + global projDir workDir fontNormal imgDir module + set rList "" + if {[catch {cd $workDir}] != 0} { + return "" + } + foreach proj [lsort [glob -nocomplain *.proj]] { + lappend rList [list [file join $workDir $proj]] + set projFile [open [file join $workDir $proj] r] + set prjName [file rootname $proj] + while {[gets $projFile line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectName"} { + regsub -all " " $string "_" project + set projName "$string" + } + if {$keyWord == "ProjectDirName"} { + set projList($prjName) [file dirname $string] + puts "$projList($prjName) - $string" + $tree insert end root $prjName -text "$projName" -font $fontNormal \ + -data "prj_$prjName" -open 0\ + -image [Bitmap::get [file join $imgDir folder.gif]] + GetFiles [file join $string] $prjName $tree + set dir $string + if {$module(ctags) != ""} { + if {[catch {cd $dir}] != 0} { + return "" + } + if {[file exists [file join $workDir $prjName.tags]] == 1} { + GetTagList_ [file join $workDir $prjName.tags] ;# geting tag list + } else { + set curDir [pwd] + set tagFile [file join $workDir $prjName.tags] + set pipe [open "|ctags -R --sort=yes --tcl-types=p -h -l -f $tagFile" "r"] + #fileevent $pipe readable + #fconfigure $pipe -buffering none -blocking no + if {[catch {cd $curDir}] != 0} { + return "" + } + } + } + } + } + } + $tree configure -redraw 1 +} + +## ABOUT PROGRAMM DIALOG ## +proc AboutDialog {} { + global docDir imgDir tree noteBook ver fontNormal dataDir env + set w {} + # prevent double creation "About" page + if { [catch {set w [$noteBook insert end about -text [::msgcat::mc "About ..."]]} ] } { + $noteBook raise about + return + } + frame $w.frmImg -borderwidth 2 -relief ridge -background white + image create photo imgAbout -format gif -file [file join $imgDir projman.gif] + label $w.frmImg.lblImg -image imgAbout + pack $w.frmImg.lblImg -side top -pady 5 -padx 5 + + frame $w.frmlbl -borderwidth 2 -relief ridge + label $w.frmlbl.lblVersion -text "[::msgcat::mc Version] $ver" + label $w.frmlbl.lblCompany -text "Copyright: Sergey Kalinin, 2001-2015" + label $w.frmlbl.lblAuthorName -text "[::msgcat::mc Author]: Sergey Kalinin" + label $w.frmlbl.lblEmail -text "[::msgcat::mc E-mail]: banzaj28@gmail.com" + label $w.frmlbl.lblWWW -fg black \ + -text "[::msgcat::mc "Home page"]:" + + pack $w.frmlbl.lblVersion $w.frmlbl.lblCompany $w.frmlbl.lblAuthorName \ + $w.frmlbl.lblEmail $w.frmlbl.lblWWW -side top -padx 5 + frame $w.frmThanks -borderwidth 2 -relief ridge + label $w.frmThanks.lblThanks -text "[::msgcat::mc Thanks]" -font $fontNormal + text $w.frmThanks.txtThanks -width 10 -height 10 -font $fontNormal\ + -selectborderwidth 0 -selectbackground #55c4d1 -width 10 + pack $w.frmThanks.lblThanks -pady 5 + pack $w.frmThanks.txtThanks -fill both -expand true + + frame $w.frmBtn -borderwidth 2 -relief ridge + button $w.frmBtn.btnOk -text [::msgcat::mc "Close"] -borderwidth {1} \ + -command { + $noteBook delete about + $noteBook raise [$noteBook page end] + } + pack $w.frmBtn.btnOk -pady 2 + pack $w.frmImg -side top -fill x + pack $w.frmlbl -side top -expand true -fill both + pack $w.frmThanks -side top -expand true -fill both + pack $w.frmBtn -side top -fill x + + bind $w "$noteBook delete about" + bind $w "$noteBook delete about" + bind $w {$noteBook delete about} + # + bind $w.frmlbl.lblWWW { + .frmBody.frmWork.noteBook.fabout.frmlbl.lblWWW configure -fg blue -cursor hand1 + LabelUpdate .frmStatus.frmHelp.lblHelp "Goto http://conero.lrn.ru" + } + bind $w.frmlbl.lblWWW { + .frmBody.frmWork.noteBook.fabout.frmlbl.lblWWW configure -fg black + LabelUpdate .frmStatus.frmHelp.lblHelp "" + } + bind $w.frmlbl.lblWWW {GoToURL "http://conero.lrn.ru"} + # + bind $w.frmlbl.lblEmail { + .frmBody.frmWork.noteBook.fabout.frmlbl.lblEmail configure -fg blue -cursor hand1 + LabelUpdate .frmStatus.frmHelp.lblHelp "Send email \"banzaj@lrn.ru\"" + } + bind $w.frmlbl.lblEmail { + .frmBody.frmWork.noteBook.fabout.frmlbl.lblEmail configure -fg black + LabelUpdate .frmStatus.frmHelp.lblHelp "" + } + bind $w.frmlbl.lblEmail {SendEmail "http://conero.lrn.ru"} + + + $noteBook raise about + focus $w.frmBtn.btnOk + if {[file exists $env(HOME)/projects/tcl/projman]==1} { + set file [open [file join $dataDir THANKS] r] + } else { + set file [open [file join $docDir THANKS] r] + } + while {[gets $file line]>=0} { + $w.frmThanks.txtThanks insert end "$line\n" + } + close $file + $w.frmThanks.txtThanks configure -state disable +} +## CLOSE FILE ## +proc CloseFile {} { + global docDir imgDir tree noteBook ver fontNormal node + set w [$noteBook itemcget page option insert end settings -text [::msgcat::mc "Settings"]] + + $noteBook raise settings +} +## GET LOCALE NAMES FROM MESSAGES FILE ## +proc GetLocale {} { + global msgDir localeList + set localeList "" + if {[catch {cd $msgDir}] != 0} { + return "" + } + foreach file [lsort [glob -nocomplain *.msg]] { + lappend localeList [list [file rootname $file]] + } + return $localeList +} +## MAKING TAR ARCHIVE ## +proc MakeTGZ {} { + global activeProject tgzDir tgzNamed workDir projDir env tcl_platform + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message [::msgcat::mc "Not found active project"]\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + FileDialog save_all + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectDirName"} { + set dir "$string" + } + if {$keyWord == "ProjectVersion"} { + set version "$string" + } + if {$keyWord == "ProjectRelease"} { + set release "$string" + } + } + close $file + set res [split $tgzNamed "-"] + set name [lindex $res 0] + set ver [lindex $res 1] + set rel [lindex $res 2] + if {$name == "projectName"} { + set name $activeProject + } + if {$ver == "version"} { + append name "-$version" + } + if {$rel == "release"} { + append name "-$release" + } + # multiplatform featuring # + if {$tcl_platform(platform) == "windows"} { + append name ".zip" + } elseif {$tcl_platform(platform) == "mac"} { + append name ".zip" + } elseif {$tcl_platform(platform) == "unix"} { + append name ".tar.gz" + } + catch {cd $projDir} res + if {[file exists [file join $tgzDir $name]] == 1} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "File already exists. Overwrite?"] \"$name\" ?"\ + -type yesno -icon question -default yes\ + -title [::msgcat::mc "Question"]] + case $answer { + yes {file delete [file join $tgzDir $name]} + no {return 0} + } + } + # multiplatform featuring # + if {$tcl_platform(platform) == "windows"} { + catch [exec pkzip -r -p [file join $tgzDir $name] [file join $activeProject *]] err + } elseif {$tcl_platform(platform) == "mac"} { + catch [exec zip -c [file join $tgzDir $name] $activeProject] err + } elseif {$tcl_platform(platform) == "unix"} { + catch [exec tar -czvf [file join $tgzDir $name] $activeProject] err + } + # message dialog # + set msg "[::msgcat::mc "Archive created in"] [file join $tgzDir $name]" + set icon info + set answer [tk_messageBox\ + -message "$msg"\ + -type ok -icon $icon] + case $answer { + ok {return 0} + } +} + +## MAKING RPM ## +proc MakeRPM {} { + global activeProject tgzDir tgzNamed workDir projDir env tcl_platform + + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not implemented yet"]"\ + -type ok -icon info] + case $answer { + ok {return 0} + } + + + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectDirName"} { + set dir "$string" + } + if {$keyWord == "ProjectVersion"} { + set version "$string" + } + if {$keyWord == "ProjectRelease"} { + set release "$string" + } + } + close $file + set res [split $tgzNamed "-"] + set name [lindex $res 0] + set ver [lindex $res 1] + set rel [lindex $res 2] + if {$name == "projectName"} { + set name $activeProject + } + if {$ver == "version"} { + append name "-$version" + } + if {$rel == "release"} { + append name "-$release" + } + append name ".tar.gz" + catch {cd $projDir} res + if {[file exists $tgzDir/$name] == 1} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "File already exists. Overwrite?"] \"$name\" ?"\ + -type yesno -icon question -default yes] + case $answer { + yes {file delete $tgzDir/$name} + no {return 0} + } + } + catch [exec tar -czvf $tgzDir/$name $activeProject] pipe +} + +## PROGRESS DIALOG ## +proc Progress {oper} { + global progval + if {$oper == "start"} { + set prg [ProgressBar .frmStatus.frmProgress.lblProgress.progress\ + -variable progval -type infinite -borderwidth 0] + pack $prg -side left -fill both -expand true + } elseif {$oper == "stop"} { + destroy .frmStatus.frmProgress.lblProgress.progress + } +# ProgUpdate +} +proc ProgUpdate { } { + global progval + set progval 5 +} + +## SHOW HELP WINDOW ## +proc ShowHelp {} { + global dataDir + if {[winfo exists .help] == 1} { + focus -force .help + raise .help + } else { + TopLevelHelp + } + if {[catch {set word [selection get]} error] != 0} { + set word " " + } else { + puts $word + TopLevelHelp + SearchWord $word + } +} + +## EXEC EXTERNAL BROWSER AND GOTO URL ## +proc GoToURL {url} { + global env tcl_platform + if {$tcl_platform(platform) == "windows"} { + set pipe [open "|iexplore $url" "r"] + } elseif {$tcl_platform(platform) == "mac"} { + set pipe [open "|iexplore $url" "r"] + } elseif {$tcl_platform(platform) == "unix"} { + set pipe [open "|$env(BROWSER) $url" "r"] + } + fileevent $pipe readable + fconfigure $pipe -buffering none -blocking no +} +## SEND EMAIL PROCEDURE ## +proc SendEmail {mail} { + global env tcl_platform + if {$tcl_platform(platform) == "windows"} { + + } elseif {$tcl_platform(platform) == "mac"} { + + } elseif {$tcl_platform(platform) == "unix"} { +# set pipe [open "|$env(BROWSER) $url" "r"] + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not implemented yet"]"\ + -type ok -icon info] + case $answer { + ok {return 0} + } +} +# fileevent $pipe readable +# fconfigure $pipe -buffering none -blocking no +} +## QUIT PROJECT MANAGER PROCEDURE ## +proc Quit {} { + set v [FileDialog close_all] + if {$v == "cancel"} { + return + } else { + exit + } +} +## PRINT DIALOG ## +proc PrintDialog {} { + global fontNormal fontBold selectPrint + set wp .print + # destroy the print window if it already exists + if {[winfo exists $wp]} { + destroy $wp + } + # create the new "find" window + toplevel $wp + wm transient $wp . + wm title $wp [::msgcat::mc "Print ..."] + wm resizable $wp 0 0 + frame $wp.frmLbl + frame $wp.frmEnt + frame $wp.frmField + frame $wp.frmBtn + pack $wp.frmLbl $wp.frmEnt $wp.frmField $wp.frmBtn -side top -fill x + label $wp.frmLbl.lblPrint -text [::msgcat::mc "Print command"] -font $fontNormal + pack $wp.frmLbl.lblPrint -fill x -expand true -padx 2 + entry $wp.frmEnt.entPrint -font $fontNormal + pack $wp.frmEnt.entPrint -fill x -expand true -padx 2 + + checkbutton $wp.frmField.chkSelect -text [::msgcat::mc "Print selected text"] -variable selectPrint\ + -font $fontNormal -onvalue true -offvalue false ;#-command Check + pack $wp.frmField.chkSelect -fill x -expand true -padx 2 + + button $wp.frmBtn.btnPrint -text [::msgcat::mc "Print"] -font $fontNormal -width 12 -relief groove\ + -command { + Print [.print.frmEnt.entPrint get] + destroy .print + } + button $wp.frmBtn.btnCancel -text [::msgcat::mc "Cancel"] -font $fontNormal -width 12 -relief groove\ + -command "destroy .print" + pack $wp.frmBtn.btnPrint $wp.frmBtn.btnCancel -side left -padx 2 -pady 2 -fill x -expand true + InsertEnt $wp.frmEnt.entPrint "lpr" + bind $wp "destroy .print" +} +## PRINT COMMAND ## +proc Print {command} { + global noteBook fontNormal fontBold fileList selectPrint tmpDir + set node [$noteBook raise] + set text "$noteBook.f$node.frame.text" + set command lpr + + if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Don't selected file"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + if {$selectPrint == "true"} { + set selIndex [$text tag ranges sel] + set start [lindex $selIndex 0] + set end [lindex $selIndex 1] + set prnText [$text get $start $end] + set file [file join $tmpDir projprn.tmp] + set f [open $file "w"] + puts $f $prnText + close $f + } else { + set file [lindex $fileList($node) 0] + } + set pipe [open "|$command $file" "r"] + fileevent $pipe readable + fconfigure $pipe -buffering none -blocking no +} + +## GETTING EXTERNAL MODULES ## +proc Modules {} { + global tcl_platform + global module tclDir dataDir binDir + # TkDIFF loading + foreach m {tkcvs tkdiff ctags tkregexp} { + if {$tcl_platform(platform) == "unix"} { + set string [exec whereis $m] + scan $string "%s%s" v module($m) + if {[info exists module($m)] && [file isdirectory $module($m)] == 0} { + puts "Find $module($m)" + } else { + set module($m) "" + } + } elseif {$tcl_platform(platform) == "mac"} { + set module($m) "" + } elseif {$tcl_platform(platform) == "windows"} { + if {$m == "tkregexp"} { + set module($m) "[file join $binDir tkregexp.tcl]" + } else { + set module($m) "" + } + } + } +} + +## RUNNING MODULE ## +proc DoModule {mod} { + global tcl_platform + global module activeProject projDir tree tclDir dataDir workDir + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectName"} { + set projName "$string" + } + if {$keyWord == "ProjectFileName"} { + set projFileName "$string" + } + if {$keyWord == "ProjectDirName"} { + set dir "$string" + } + if {$keyWord == "ProjectCompiler"} { + set projCompiler "$string" + } + if {$keyWord == "ProjectInterp"} { + set projInterp "$string" + } + } + close $file + + puts $dir + + set curDir [pwd] + case $mod { + tkcvs { + set pipe [open "|$module(tkcvs) -dir $dir" "r"] + fileevent $pipe readable + fconfigure $pipe -buffering none -blocking no + } + tkdiff { + set files [$tree selection get] + if {[llength $files] == 0} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Don't selected file"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + if {[llength $files] == 1} { + if {$files != ""} { + set file1 [$tree itemcget $files -data] + } + set command "-r $file1" + } + if {[llength $files] == 2} { + if {[lindex $files 0] != ""} { + set file1 [$tree itemcget [lindex $files 0] -data] + } + if {[lindex $files 1] != ""} { + set file2 [$tree itemcget [lindex $files 1] -data] + } + set command "$file1 $file2" + } + if {[llength $files] > 2} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Must be one or two file select!"]"\ + -type ok -icon info\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + set pipe [open "|$module(tkdiff) $command" "r"] + fileevent $pipe readable + fconfigure $pipe -buffering none -blocking no + } + tkregexp { + set files [$tree selection get] + if {[llength $files] == 0} { + set command "" + } elseif {[llength $files] == 1} { + if {$files != ""} { + set file [$tree itemcget $files -data] + } + set command "$file" + } else { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Must be one file select!"]"\ + -type ok -icon info\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + puts "$module(tkregexp) $command" + set pipe [open "|$module(tkregexp) $command" "r"] + fileevent $pipe readable + fconfigure $pipe -buffering none -blocking no + } + ctags { + if {[catch {cd $dir}] != 0} { + return "" + } + if {$module(ctags) == ""} { + return + } + set tagFile [file join $workDir $activeProject.tags] + set pipe [open "|ctags -R --sort=yes --tcl-types=p -h -l -f $tagFile" "r"] + #fileevent $pipe readable + #fconfigure $pipe -buffering none -blocking no + if {[catch {cd $curDir}] != 0} { + return "" + } + } + + } +} + +proc SelectDir {dir} { + global projDir workDir openProjDir + set dirName [tk_chooseDirectory -initialdir $dir\ + -title "[::msgcat::mc "Select directory"]"\ + -parent .] + return $dirName +} +## UPDATE TREE ## +proc UpdateTree {} { + global tree + $tree delete [$tree nodes root] + GetProj $tree +} +## TOOLBAR ON/OFF PROCEDURE ## +proc ToolBar {} { + global toolBar + if {$toolBar == "Yes"} { + CreateToolBar + } elseif {$toolBar == "No"} { + destroy .frmTool.btnNew .frmTool.btnSave .frmTool.btnSaveAs .frmTool.btnSaveAll\ + .frmTool.btnCopy .frmTool.btnPaste .frmTool.btnCut .frmTool.btnDo .frmTool.btnPrint\ + .frmTool.btnDoFile .frmTool.btnTGZ .frmTool.btnHelp .frmTool.btnClose + .frmTool configure -height 1 + } +} + + +## LOADING HIGHLIGHT FILES ## +proc HighLight {ext text line lineNumber node} { + global font tree color noteBook hlDir + + if {[file exists [file join $hlDir $ext.tcl]] == 1} { + HighLight[string toupper $ext] $text $line $lineNumber $node + } elseif {($ext == "htm") || ($ext == "xml") || ($ext == "fm") || ($ext == "html")} { + HighLightHTML $text $line $lineNumber $node + } elseif {($ext == "pl")} { + HighLightPERL $text $line $lineNumber $node + } elseif {($ext == "for")} { + HighLightFORTRAN $text $line $lineNumber $node + } elseif {($ext == "ml") || ($ext == "mli")} { + HighLightML $text $line $lineNumber $node + } elseif {($ext == "rvt") || ($ext == "tml")} { + HighLightRIVET $text $line $lineNumber $node + } elseif {($ext == "php") || ($ext == "phtml")} { + HighLightPHP $text $line $lineNumber $node + } elseif {($ext == "rb")} { + HighLightRUBY $text $line $lineNumber $node + } else { + HighLightTCL $text $line $lineNumber $node + } +} + +## GET IMAGE FOR tree AND notebook WIDGETS ## +proc GetImage {fileName} { + global imgDir + if {[file isdirectory $fileName] == 1} { + set img "folder" + set data "dir" + } elseif {[string match "*.tcl" $fileName] == 1} { + set img "tcl" + set data "src" + } elseif {[string match "*.tk" $fileName] == 1} { + set img "tk" + set data "src" + } elseif {[string match "*.rvt" $fileName] == 1} { + set img "rvt" + set data "src" + } elseif {[string match "*.tex" $fileName] == 1} { + set img "tex" + set data "src" + } elseif {[string match "*.html" $fileName] == 1 || [string match "*.htm" $fileName] == 1} { + set img "html" + set data "src" + } elseif {[string match "*.gif" $fileName] == 1 || [string match "*.xpm" $fileName] == 1 || \ + [string match "*.png" $fileName] == 1 || [string match "*.jpg" $fileName] == 1 || \ + [string match "*.xbm" $fileName] == 1 || [string match "*.jpeg" $fileName] == 1 || \ + [string match "*.bmp" $fileName] == 1} { + set img "img" + set data "img" + } elseif {[string match "*.xml" $fileName] == 1} { + set img "xml" + set data "xml" + } elseif {[string match "*.java" $fileName] == 1 || [string match "*.ja" $fileName] == 1} { + set img "java" + set data "src" + } elseif {[string match "*.c" $fileName] == 1} { + set img "c" + set data "src" + } elseif {[string match "*.cpp" $fileName] == 1} { + set img "cpp" + set data "src" + } elseif {[string match "*.spec" $fileName] == 1} { + set img "rpm" + set data "src" + } elseif {[string match "*.pl" $fileName] == 1} { + set img "perl" + set data "src" + } elseif {[string match "*.for" $fileName] == 1 || [string match "*.f" $fileName] == 1} { + set img "fortran" + set data "src" + } elseif {[string match "*.ml" $fileName] == 1 || [string match "*.mli" $fileName] == 1} { + set img "caml" + set data "src" + } elseif {[string match "*.tml" $fileName] == 1 || [string match "*.rvt" $fileName] == 1} { + set img "tclhtml" + set data "src" + } elseif {[string match "*.php" $fileName] == 1 || [string match "*.phtml" $fileName] == 1} { + set img "php" + set data "src" + } elseif {[string match "*.rb" $fileName] == 1} { + set img "ruby" + set data "src" + } else { + set img "file" + set data "txt" + } + + return $img +} + +proc GetExtention {node} { + global fileList + set ext [string range [file extension [file tail [lindex $fileList($node) 0]]] 1 end] + return $ext +} + + +proc TextOperation {oper} { + global noteBook + set nb [$noteBook raise] + if {$nb == "" || $nb == "newproj" || $nb == "about" || $nb == "debug"} { + return + } + set nb "$noteBook.f$nb" + switch $oper { + "copy" {tk_textCopy $nb.text} + "paste" {tk_textPaste $nb.text} + "cut" {tk_textCut $nb.text} + "redo" {$nb.text edit redo} + "undo" {$nb.text edit undo} + } + unset nb +} + + + + + diff --git a/projects.tcl b/projects.tcl new file mode 100644 index 0000000..2869a46 --- /dev/null +++ b/projects.tcl @@ -0,0 +1,905 @@ +######################################################### +# Tcl/Tk project Manager +# Distributed under GNU Public License +# Author: Sergey Kalinin banzaj@lrn.ru +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru +######################################################### + +proc NewProjDialog {type} { + global fontNormal tree projDir workDir activeProject fileList noteBook imgDir prjDir prjName + global openProjDir tclDir + set w .newProj + # destroy the find window if it already exists + if {[winfo exists $w]} { + destroy $w + } + + set typeProjects "Tcl Java Perl Fortran O'Caml PHP Ruby Erlang" + + toplevel $w + wm title $w [::msgcat::mc "New project"] + wm resizable $w 0 0 + wm transient $w . + frame $w.frmCombo -borderwidth 1 + frame $w.frmBtn -borderwidth 1 + pack $w.frmCombo $w.frmBtn -side top -fill x + + # set combo [entry $w.frmCombo.entFind] + set combo [ComboBox $w.frmCombo.txtLocale\ + -textvariable lang -editable false\ + -selectbackground "#55c4d1" -selectborderwidth 0\ + -values $typeProjects] + + pack $combo -fill x -padx 2 -pady 2 + if {$type=="new"} { + button $w.frmBtn.btnFind -text "[::msgcat::mc "Create"]"\ + -font $fontNormal -width 12 -relief groove\ + -command { + NewProj add "" $lang + destroy .newProj + } + } elseif {$type=="open"} { + button $w.frmBtn.btnFind -text "[::msgcat::mc "Open"]"\ + -font $fontNormal -width 12 -relief groove\ + -command { + NewProj open "$prjName" $lang + destroy .newProj + } + } + button $w.frmBtn.btnCancel -text "[::msgcat::mc "Close"] - Esc"\ + -relief groove -width 12 -font $fontNormal\ + -command "destroy $w" + pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left + if {$type=="open"} { + bind $w {NewProj open $prjName $lang; destroy .newProj} + } elseif {$type=="new"} { + bind $w {NewProj add "" $lang; destroy .newProj} + } + bind $w "destroy $w" + focus -force $combo + + # set findIndex [lsearch -exact $findHistory "$findString"] + $combo setvalue @0 +} + +proc NewProj {type proj l} { + global fontNormal tree projDir workDir activeProject fileList noteBook imgDir prjDir + global openProjDir tclDir frm lang operType + set operType $type + if {$operType == "edit" && $proj == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + set lang $l + set node [$noteBook page [$noteBook index newproj]] + if {$node != ""} { + $noteBook raise newproj + return 0 + } else { + set w [$noteBook insert end newproj -text [::msgcat::mc "New project"]] + } + set frm [frame $w.frmProjSettings] + pack $frm -fill both -expand true + + image create photo imgFold -format gif -file [file join $imgDir folder.gif] + + set frm_1 [frame $frm.frmProjName] + label $frm_1.lblProjName -text [::msgcat::mc "Project name"] -width 20 -anchor w + entry $frm_1.txtProjName -textvariable txtProjName + pack $frm_1.lblProjName -side left + pack $frm_1.txtProjName -side left -fill x -expand true + + set frm_2 [frame $frm.frmFileName] + label $frm_2.lblFileName -text [::msgcat::mc "Project file"] -width 20 -anchor w + entry $frm_2.txtFileName -textvariable txtFileName + pack $frm_2.lblFileName -side left + pack $frm_2.txtFileName -side left -fill x -expand true + + set frm_8 [frame $frm.frmDirName] + label $frm_8.lblDirName -text [::msgcat::mc "Project dir"] -width 20 -anchor w + entry $frm_8.txtDirName -textvariable txtDirName -state disable + button $frm_8.btnDirName -borderwidth {1} -image imgFold\ + -command { + $frm.frmDirName.txtDirName configure -state normal + InsertEnt $frm.frmDirName.txtDirName [tk_chooseDirectory -initialdir $projDir -title "[::msgcat::mc "Select directory"]" -parent .] + $frm.frmDirName.txtDirName configure -state disable + } + pack $frm_8.lblDirName -side left + pack $frm_8.txtDirName -side left -fill x -expand true + pack $frm_8.btnDirName -side left + + set frm_13 [frame $frm.frmCompiler] + label $frm_13.lblCompiler -text [::msgcat::mc "Compiler"]\ + -width 20 -anchor w + entry $frm_13.txtCompiler -textvariable txtCompiler + button $frm_13.btnCompiler -borderwidth {1} -image imgFold\ + -command { + InsertEnt $frm.frmCompiler.txtCompiler [tk_getOpenFile -initialdir $tclDir -parent .] + } + pack $frm_13.lblCompiler -side left + pack $frm_13.txtCompiler -side left -fill x -expand true + pack $frm_13.btnCompiler -side left + + set frm_12 [frame $frm.frmProjInterp] + label $frm_12.lblProjInterp -text [::msgcat::mc "Interpetator"]\ + -width 20 -anchor w + entry $frm_12.txtProjInterp -textvariable txtProjInterp + button $frm_12.btnInterp -borderwidth {1} -image imgFold\ + -command { + InsertEnt $frm.frmProjInterp.txtProjInterp [tk_getOpenFile -initialdir $tclDir -parent .] + } + pack $frm_12.lblProjInterp -side left + pack $frm_12.txtProjInterp -side left -fill x -expand true + pack $frm_12.btnInterp -side left + + + set frm_4 [frame $frm.frmVersion] + label $frm_4.lblProjVersion -text [::msgcat::mc "Version"] -width 20 -anchor w + entry $frm_4.txtProjVersion -textvariable txtProjVersion + pack $frm_4.lblProjVersion -side left + pack $frm_4.txtProjVersion -side left -fill x -expand true + InsertEnt $frm_4.txtProjVersion "0.0.1" + + set frm_11 [frame $frm.frmRelease] + label $frm_11.lblProjRelease -text [::msgcat::mc "Release"] -width 20 -anchor w + entry $frm_11.txtProjRelease -textvariable txtProjRelease + pack $frm_11.lblProjRelease -side left + pack $frm_11.txtProjRelease -side left -fill x -expand true + InsertEnt $frm_11.txtProjRelease "1" + + set frm_3 [frame $frm.frmProjAuthor] + label $frm_3.lblProjAuthor -text [::msgcat::mc "Author"] -width 20 -anchor w + entry $frm_3.txtProjAuthor -textvariable txtProjAuthor + pack $frm_3.lblProjAuthor -side left + pack $frm_3.txtProjAuthor -side left -fill x -expand true + + set frm_9 [frame $frm.frmProjEmail] + label $frm_9.lblProjEmail -text [::msgcat::mc "E-mail"] -width 20 -anchor w + entry $frm_9.txtProjEmail -textvariable txtProjEmail + pack $frm_9.lblProjEmail -side left + pack $frm_9.txtProjEmail -side left -fill x -expand true + + set frm_5 [frame $frm.frmProjCompany] + label $frm_5.lblProjCompany -text [::msgcat::mc "Company"] -width 20 -anchor w + entry $frm_5.txtProjCompany -textvariable txtProjCompany + pack $frm_5.lblProjCompany -side left + pack $frm_5.txtProjCompany -side left -fill x -expand true + + set frm_10 [frame $frm.frmProjHome] + label $frm_10.lblProjHome -text [::msgcat::mc "Home page"] -width 20 -anchor w + entry $frm_10.txtProjHome -textvariable txtProjHome + pack $frm_10.lblProjHome -side left + pack $frm_10.txtProjHome -side left -fill x -expand true + + set frm_7 [frame $frm.frmWinTitle -border 2 -relief ridge -background grey] + label $frm_7.lblWinTitle -text "[::msgcat::mc "Create new project"] $lang" -foreground yellow \ + -background black + + pack $frm_7.lblWinTitle -fill x -expand true + + set frm_6 [frame $frm.frmBtn -border 2 -relief ridge] + if {$operType == "edit" && $proj != ""} { + $noteBook itemconfigure newproj -text [::msgcat::mc "Project settings"] + button $frm_6.btnProjCreate -text [::msgcat::mc "Save"] -relief groove\ + -font $fontNormal -command { + regsub -all {\\} $txtProjInterp {\\\\} $txtProjInterp + SaveProj "$txtFileName" "$txtProjName" "$txtFileName" "$txtDirName"\ + "$txtCompiler" "$txtProjInterp" "$txtProjVersion" "$txtProjRelease"\ + "$txtProjAuthor" "$txtProjEmail" "$txtProjCompany" "$txtProjHome" + $noteBook delete newproj + $noteBook raise [$noteBook page end] + } + } else { + button $frm_6.btnProjCreate -text [::msgcat::mc "Create"] -relief groove\ + -font $fontNormal -command { + CreateProj $operType $lang "$txtFileName" "$txtProjName" "$txtFileName" "$txtDirName"\ + "$txtCompiler" "$txtProjInterp" "$txtProjVersion" "$txtProjRelease"\ + "$txtProjAuthor" "$txtProjEmail" "$txtProjCompany" "$txtProjHome" + $noteBook delete newproj + $noteBook raise [$noteBook page end] + } + + } + button $frm_6.btnClose -text [::msgcat::mc "Cancel"] -relief groove -font $fontNormal -command { + $noteBook delete newproj + $noteBook raise [$noteBook page end] + } + pack $frm_6.btnProjCreate $frm_6.btnClose -padx 10 -pady 2 -side left -fill x -expand true + pack $frm_7 $frm_1 $frm_2 $frm_8 $frm_13 $frm_12 $frm_4 $frm_11 $frm_3 $frm_9 $frm_5 $frm_10 $frm_6\ + -side top -fill x + pack $frm_6 -side top -fill x -expand true -anchor s + bind $w "$noteBook delete newproj" + $noteBook raise newproj + + ## EDIT PROJECT SETTINGS ## + if {$operType == "edit" && $proj != ""} { + $frm.frmDirName.txtDirName configure -state normal + $frm_7.lblWinTitle configure -text [::msgcat::mc "Project settings"] + $frm_6.btnProjCreate configure -text "[::msgcat::mc "Save"]" + set file [open [file join $workDir $proj.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + # regsub -all " " $string "_" project + puts $string + switch $keyWord { + ProjectName {InsertEnt $frm_1.txtProjName "$string"} + ProjectFileName {InsertEnt $frm_2.txtFileName "$string"} + ProjectDirName {InsertEnt $frm_8.txtDirName "$string"} + ProjectCompiler {InsertEnt $frm_13.txtCompiler "$string"} + ProjectInterp {InsertEnt $frm_12.txtProjInterp "$string"} + ProjectVersion {InsertEnt $frm_4.txtProjVersion "$string"} + ProjectRelease {InsertEnt $frm_11.txtProjRelease "$string"} + ProjectAuthor {InsertEnt $frm_3.txtProjAuthor "$string"} + ProjectEmail {InsertEnt $frm_9.txtProjEmail "$string"} + ProjectCompany {InsertEnt $frm_5.txtProjCompany "$string"} + ProjectHome {InsertEnt $frm_10.txtProjHome "$string"} + } + } + close $file + } elseif {$operType == "open"} { + $frm_7.lblWinTitle configure -text "[::msgcat::mc "Open project"] $lang" + InsertEnt $frm_1.txtProjName "$proj" + InsertEnt $frm_2.txtFileName "$proj" + InsertEnt $frm_8.txtDirName "$proj" + $frm_8.txtDirName configure -state normal + puts $prjDir + InsertEnt $frm_8.txtDirName "$prjDir" + InsertEnt $frm_13.txtCompiler "" + InsertEnt $frm_12.txtProjInterp "" + InsertEnt $frm_4.txtProjVersion "0.0.1" + InsertEnt $frm_11.txtProjRelease "1" + InsertEnt $frm_3.txtProjAuthor "" + InsertEnt $frm_9.txtProjEmail "" + InsertEnt $frm_5.txtProjCompany "" + InsertEnt $frm_10.txtProjHome "" + } else { + InsertEnt $frm_1.txtProjName "" + InsertEnt $frm_2.txtFileName "" + InsertEnt $frm_8.txtDirName "" + InsertEnt $frm_13.txtCompiler "" + InsertEnt $frm_12.txtProjInterp "" + InsertEnt $frm_4.txtProjVersion "0.0.1" + InsertEnt $frm_11.txtProjRelease "1" + InsertEnt $frm_3.txtProjAuthor "" + InsertEnt $frm_9.txtProjEmail "" + InsertEnt $frm_5.txtProjCompany "" + InsertEnt $frm_10.txtProjHome "" + } +} + +## CREATING PROJECT PROCEDURE ## +proc CreateProj {type lang txtFileName txtProjName txtFileName txtDirName txtCompiler txtProjInterp txtProjVersion txtProjRelease txtProjAuthor txtProjEmail txtProjCompany txtProjHome} { + global projDir workDir tree fontNormal dataDir tcl_platform + + set projShortName [file tail $txtDirName] + + set projFile [open [file join $workDir $projShortName.proj] w] + + puts $projFile "ProjectName \"$txtProjName\"" + puts $projFile "ProjectFileName \"$txtFileName\"" + puts $projFile "ProjectDirName \"$txtDirName\"" + puts $projFile "ProjectCompiler \"$txtCompiler\"" + puts $projFile "ProjectInterp \"$txtProjInterp\"" + puts $projFile "ProjectVersion \"$txtProjVersion\"" + puts $projFile "ProjectRelease \"$txtProjRelease\"" + puts $projFile "ProjectAuthor \"$txtProjAuthor\"" + puts $projFile "ProjectEmail \"$txtProjEmail\"" + puts $projFile "ProjectCompany \"$txtProjCompany\"" + puts $projFile "ProjectHome \"$txtProjHome\"" + close $projFile + if {$type != "open"} { + set dir [file join $projDir $txtDirName] + if {[file exists "$dir"] != 1} { + file mkdir "$dir" + } + # file header + if {$lang=="Tcl" || $lang == "Perl"} { + set text "######################################################\n#\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Home page: $txtProjHome\n######################################################\n" + } elseif {$lang == "Perl"} { + set lang pl + set text "######################################################\n#\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Home page: $txtProjHome\n######################################################\n" + } elseif {$lang=="Java"} { + set text "/*\n*****************************************************\n*\t$txtProjName\n*\tDistributed under GNU Public License\n* Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n*****************************************************\n*/\n" + } elseif {$lang=="Fortran"} { + set text "\nc*****************************************************\nc*\t$txtProjName\n*c\tDistributed under GNU Public License\nc* Author: $txtProjAuthor $txtProjEmail\nc* Home page: $txtProjHome\nc*****************************************************\n*/\n" + } elseif {$lang=="O'Caml"} { + set text "\(*****************************************************\n*\t$txtProjName\n*\tDistributed under GNU Public License\n* Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n******************************************************\)\n" + set lang ml + } elseif {$lang=="Ruby"} { + set lang rb + set text "######################################################\n#\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Home page: $txtProjHome\n######################################################\n" + } elseif {$lang=="PHP"} { + set text "" + set lang php + } elseif {$lang=="Erlang"} { + set text "\%**************************************************\n%\t$txtProjName\n%\tDistributed under GNU Public License\n% Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n%*****************************************************\)\n" + set lang erl + } + + if {[file exists [file join $dir $txtFileName.[string tolower $lang]]] == 0} { + set file [open [file join $dir $txtFileName.[string tolower $lang]] w] + puts $file $text + close $file + } + # spec file generating + if {[file exists [file join $dir $txtFileName.spec]] == 0} { + set file [open [file join $dir $txtFileName.spec] w] + puts $file "%define name $txtFileName" + puts $file "%define version $txtProjVersion" + puts $file "%define release $txtProjRelease" + puts $file "%define instdir $dataDir" + puts $file "Summary:\t$txtProjName" + puts $file "Name:\t\t%\{name\}" + puts $file "Version:\t%\{version\}" + puts $file "Release:\t%\{release\}" + puts $file "Source:\t%\{name\}-%\{version\}.tar.gz" + puts $file "Copyright:\tGPL" + puts $file "Group:\t\tDevelopment" + puts $file "Vendor:\t\t$txtProjAuthor <$txtProjEmail>" + puts $file "BuildRoot:\t%{_tmppath}/%{name}-buildroot" + puts $file "BuildArch:\tnoarch" + puts $file "Requires:\ttcl >= 8.3\n" + puts $file "%description" + puts $file "This project made by Tcl/Tk Project Manager" + puts $file "%prep\n%setup -n%\{name\}\n%build\n" + puts $file "%install" + puts $file "rm -rf \$RPM_BUILD_ROOT" + puts $file "mkdir -p \$RPM_BUILD_ROOT%\{_datadir\}/%\{name\}" + puts $file "cp -f \* \$RPM_BUILD_ROOT%\{_datadir\}/%\{name\}\n" + puts $file "%post\nmkdir \$HOME/.$txtDirName" + puts $file "%clean\nrm -rf \$RPM_BUILD_ROOT" + puts $file "%files" + puts $file "%defattr\(-,root,root\)" + puts $file "%doc README TODO CHANGELOG COPYING INSTALL" + puts $file "%\{_datadir\}/%\{name\}" + puts $file "%define date\t%\(echo \`LC_ALL=\"C\" date +\"%a %b %d %Y\"\`\)" + puts $file "%changelog" + puts $file "\* %\{date\}\n\n# end of file" + close $file + } + # file attributes "$dir/$txtFileName.tcl" -permissions "777" + # catch {chmod 744 "$dir/$txtFileName.tcl"} mes + foreach f {README TODO CHANGELOG COPYING INSTALL} { + if {[file exists [file join $dir $f]] != 1} { + set file [open [file join $dir $f] w] + puts $file "$text" + if {$f == "CHANGELOG"} { + if {$tcl_platform(platform) == "windows"} { + set d [clock format [clock scan "now" -base [clock seconds]] -format %d/%m/%Y] + } elseif {$tcl_platform(platform) == "mac"} { + set d "Needed date command for this platform" + } elseif {$tcl_platform(platform) == "unix"} { + set d [clock format [clock scan "now" -base [clock seconds]] -format %d/%m/%Y] + } + + puts $file "$d\n\t- Beginning the project" + } + close $file + } + } + } else { + ## Insert new project into tree ## + $tree insert end root $projShortName -text "$txtProjName" -font $fontNormal \ + -data "prj_$projShortName" -open 0 -image [Bitmap::get folder] + GetFiles $txtDirName $projShortName $tree + } +} +## SAVING PROJECT SETTINGS ## +proc SaveProj {txtFileName txtProjName txtFileName txtDirName txtCompiler txtProjInterp txtProjVersion txtProjRelease txtProjAuthor txtProjEmail txtProjCompany txtProjHome} { + global projDir workDir tree fontNormal dataDir + + set file [file tail $txtDirName] + + set projFile [open [file join $workDir $file.proj] w] + puts $projFile "ProjectName \"$txtProjName\"" + puts $projFile "ProjectFileName \"$txtFileName\"" + puts $projFile "ProjectDirName \"$txtDirName\"" + puts $projFile "ProjectCompiler \"$txtCompiler\"" + puts $projFile "ProjectInterp \"$txtProjInterp\"" + puts $projFile "ProjectVersion \"$txtProjVersion\"" + puts $projFile "ProjectRelease \"$txtProjRelease\"" + puts $projFile "ProjectAuthor \"$txtProjAuthor\"" + puts $projFile "ProjectEmail \"$txtProjEmail\"" + puts $projFile "ProjectCompany \"$txtProjCompany\"" + puts $projFile "ProjectHome \"$txtProjHome\"" + close $projFile +} + +## OPEN EXISTING PROJECT AND ADDED INYO PROJMAN TREE ## +proc OpenProj {} { + global projDir workDir openProjDir prjDir prjName + set prjDir [SelectDir $projDir] + if {$prjDir != ""} { + set prjName "[file tail $prjDir]" + NewProjDialog open + #file copy $prjDir $projDir + } + return +} +## ADD FILE INTO PROJECTS ## +proc AddToProj {fileName mode} { + global projDir workDir activeProject tree noteBook fontNormal imgDir tree + set type [string trim [file extension $fileName] {.}] + destroy .addtoproj + + set node [$tree selection get] + set fullPath [$tree itemcget $node -data] + + if {[file isdirectory $fullPath] == 1} { + set dir $fullPath + set parentNode $node + } else { + set dir [file dirname $fullPath] + set parentNode [$tree parent $node] + } + + if {$type == "tcl"} { + set img "tcl" + } elseif {$type == "tk"} { + set img "tk" + } elseif {$type == "txt"} { + set img "file" + } elseif {$type == "html"} { + set img "html" + } elseif {$type == "java"} { + set img "java" + } elseif {$type == "pl" || $type == "perl"} { + set img "perl" + } elseif {$type == "for"} { + set img "fortran" + } elseif {$type == "ml" || $type == "mli"} { + set img "caml" + } elseif {$type == "php" || $type == "phtml"} { + set img "php" + } elseif {$type == "rb"} { + set img "ruby" + } elseif {$type == "rb"} { + set img "erl" + } else { + set img "file" + } + if {$mode == "directory"} { + set img "folder" + } + #set dir [file join $projDir $activeProject] + set dot "_" + set name [file rootname $fileName] + set ext [string range [file extension $fileName] 1 end] + set subNode "$name$dot$ext" + $tree insert end $parentNode $subNode -text $fileName \ + -data [file join $dir $fileName] -open 1\ + -image [Bitmap::get [file join $imgDir $img.gif]]\ + -font $fontNormal + if {[$tree itemcget $activeProject -open] == 0} { + $tree itemconfigure $activeProject -open 1 + } + set file [file join $dir $fileName] + #set f [open $file w] + #close $f + puts $file + if {$mode == "directory"} { + file mkdir $file + return + } + InsertTitle $file $type + EditFile $subNode [file join $dir $fileName] +} +## ADD FILE INTO PROJECT DIALOG## +proc AddToProjDialog {mode} { + global projDir workDir activeProject imgDir tree mod + set mod $mode + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning] + case $answer { + ok {return 0} + } + } + + set w .addtoproj + if {[winfo exists $w]} { + destroy $w + } + # create the new "goto" window + toplevel $w + wm title $w [::msgcat::mc "Create new $mod"] + wm resizable $w 0 0 + wm transient $w . + + frame $w.frmCanv -border 1 -relief sunken + frame $w.frmBtn -border 1 -relief sunken + pack $w.frmCanv -side top -fill both -padx 1 -pady 1 + pack $w.frmBtn -side top -fill x + + label $w.frmCanv.lblImgTcl -text [::msgcat::mc "Input $mod name"] + entry $w.frmCanv.entImgTcl + pack $w.frmCanv.lblImgTcl $w.frmCanv.entImgTcl -expand true -padx 5 -pady 5 -side top + + button $w.frmBtn.btnOk -text [::msgcat::mc "Create"] -relief groove -command { + AddToProj [.addtoproj.frmCanv.entImgTcl get] $mod + } + button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"] -command "destroy $w" -relief groove + pack $w.frmBtn.btnOk $w.frmBtn.btnCancel -padx 2 -pady 2 -fill x -side left + + bind $w "destroy .addtoproj" + bind $w.frmCanv.entImgTcl { + AddToProj [.addtoproj.frmCanv.entImgTcl get] $mod + } + focus -force $w.frmCanv.entImgTcl + #unset type +} +proc AddToProjDialog_ {} { + global projDir workDir activeProject imgDir tree + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning] + case $answer { + ok {return 0} + } + } + + set w .addtoproj + if {[winfo exists $w]} { + destroy $w + } + # create the new "goto" window + toplevel $w + wm title $w [::msgcat::mc "Create new file"] + wm resizable $w 0 0 + wm transient $w . + + frame $w.frmCanv -border 1 -relief sunken + frame $w.frmBtn -border 1 -relief sunken + pack $w.frmCanv -side top -fill both -padx 1 -pady 1 + pack $w.frmBtn -side top -fill x + + label $w.frmCanv.lblImgTcl -text [::msgcat::mc "Input file name"] + entry $w.frmCanv.entImgTcl + pack $w.frmCanv.lblImgTcl $w.frmCanv.entImgTcl -expand true -padx 5 -pady 5 -side top + + button $w.frmBtn.btnOk -text [::msgcat::mc "Create"] -relief groove -command { + AddToProj [.addtoproj.frmCanv.entImgTcl get] + } + button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"] -command "destroy $w" -relief groove + pack $w.frmBtn.btnOk $w.frmBtn.btnCancel -padx 2 -pady 2 -fill x -side left + + bind $w "destroy .addtoproj" + bind $w.frmCanv.entImgTcl { + AddToProj [.addtoproj.frmCanv.entImgTcl get] + } + focus -force $w.frmCanv.entImgTcl + +} +## DELETE FILE FROM PROJECT ## +proc DelFromProj {project} { + global projDir workDir + +} +## DELETEING PROJECT PROCEDURE ## +proc DelProj {} { + global workDir activeProject tree + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning] + case $answer { + ok {return 0} + } + } + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectDirName"} { + set projDir "$string" + puts $projDir + } + } + close $file + + set answer [tk_messageBox -message "[::msgcat::mc "Delete project"] \"$activeProject\" ?"\ + -type yesno -icon question -default yes] + case $answer { + yes { + FileDialog close_all + file delete -force $projDir + file delete -force [file join $workDir $activeProject.proj] + file delete -force [file join $workDir $activeProject.tags] + $tree delete [$tree selection get] + $tree configure -redraw 1 + set activeProject "" + LabelUpdate .frmStatus.frmActive.lblActive "" + } + } +} + +proc CompileOption {string} { + global fontNormal cmdCompile editor + set w .cmd + # destroy the find window if it already exists + if {[winfo exists $w]} { + destroy $w + } + + toplevel $w + wm title $w [::msgcat::mc "Command options"] + wm resizable $w 0 0 + wm transient $w . + frame $w.frmCombo -borderwidth 1 -bg $editor(bg) + frame $w.frmBtn -borderwidth 1 -bg $editor(bg) + pack $w.frmCombo $w.frmBtn -side top -fill x + + # set combo [entry $w.frmCombo.entFind] + label $w.frmCombo.lblModule -text "[::msgcat::mc "Convert to"]" -bg $editor(bg) -fg $editor(fg) + label $w.frmCombo.lblFile -text "[::msgcat::mc "File"]" -bg $editor(bg) -fg $editor(fg) + set combo [entry $w.frmCombo.txtString -text "$string"] + + pack $w.frmCombo.lblModule $w.frmCombo.lblFile $combo -fill x -padx 2 -pady 2 -side top + + button $w.frmBtn.btnFind -text [::msgcat::mc "Run"]\ + -font $fontNormal -width 12 -relief groove -bg $editor(bg) -fg $editor(fg)\ + -command { + return [.cmd.frmCombo.txtString get] + destroy .cmd + } + button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"] -bg $editor(bg) -fg $editor(fg)\ + -relief groove -width 12 -font $fontNormal\ + -command "destroy $w" + pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left + + bind $w { + set cmdCompile [.cmd.frmCombo.txtString get] + destroy .cmd + } + bind $w "destroy $w" + $combo insert end "$string" + focus -force $combo +} + +## MAKE PROJ PROCEDURE (RUNNING PROJECT) ## +proc MakeProj {action t} { + global activeProject projDir noteBook fontNormal fontBold workDir tree cmdCompile editor + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + FileDialog save_all + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectName"} { + set projName "$string" + } + if {$keyWord == "ProjectFileName"} { + set projFileName "$string" + } + if {$keyWord == "ProjectDirName"} { + set projDirName "$string" + } + if {$keyWord == "ProjectCompiler"} { + set projCompiler "$string" + } + if {$keyWord == "ProjectInterp"} { + set projInterp "$string" + } + } + close $file + if {$action == "compile"} { + if {$t == "proj"} { + set prog [file join $projDirName $projFileName.java] + } elseif {$t == "file"} { + set node [$tree selection get] + set fullPath [$tree itemcget $node -data] + set dir [file dirname $fullPath] + set file [file tail $fullPath] + set prog $fullPath + } + } elseif {$action == "run"} { + if {$t == "proj"} { + set prog [file join $projDirName $projFileName.tcl] + } elseif {$t == "file"} { + set node [$tree selection get] + set fullPath [$tree itemcget $node -data] + set dir [file dirname $fullPath] + set file [file tail $fullPath] + set prog $fullPath + } + } + + set node "debug" + if {[$noteBook index $node] != -1} { + $noteBook delete debug + } + set w [$noteBook insert end $node -text [::msgcat::mc "Running project"]] + # create array with file names # + frame $w.frame -borderwidth 2 -relief ridge -background $editor(bg) + pack $w.frame -side top -fill both -expand true + + + text $w.frame.text -yscrollcommand "$w.frame.yscroll set" \ + -bg $editor(bg) -fg $editor(fg) \ + -relief sunken -wrap word -highlightthickness 0 -font $fontNormal\ + -selectborderwidth 0 -selectbackground #55c4d1 -width 10 -height 10 + scrollbar $w.frame.yscroll -relief sunken -borderwidth {1} -width {10} -takefocus 0 \ + -command "$w.frame.text yview" -background $editor(bg) + + pack $w.frame.text -side left -fill both -expand true + pack $w.frame.yscroll -side left -fill y + + frame $w.frmBtn -borderwidth 2 -relief ridge -bg $editor(bg) + pack $w.frmBtn -side top -fill x + button $w.frmBtn.btnOk -text [::msgcat::mc "Close"] -borderwidth {1} \ + -bg $editor(bg) -fg $editor(fg) -command { + $noteBook delete debug + $noteBook raise [$noteBook page end] + return 0 + } + pack $w.frmBtn.btnOk -pady 2 + # key bindings # + bind $w.frmBtn.btnOk { + $noteBook delete debug + $noteBook raise [$noteBook page end] + # return 0 + } + bind $w.frmBtn.btnOk { + $noteBook delete debug + $noteBook raise [$noteBook page end] + # return 0 + } + focus -force $w.frmBtn.btnOk + $noteBook raise $node + # insert debug data into text widget # + $w.frame.text tag configure bold -font $fontBold + $w.frame.text tag configure error -font $fontNormal -foreground red + $w.frame.text tag add bold 0.0 0.end + if {$action == "compile"} { + $w.frame.text insert end "[::msgcat::mc "Compile project"] - $activeProject\n" + $w.frame.text insert end "[::msgcat::mc "Compile"] - $prog\n\n" + } elseif {$action == "run"} { + $w.frame.text insert end "[::msgcat::mc "Running project"] - $activeProject\n" + $w.frame.text insert end "[::msgcat::mc "Run"] - $prog\n\n" + } + set pos [$w.frame.text index insert] + set lineNum [lindex [split $pos "."] 0] + $w.frame.text insert end "----------------- [::msgcat::mc "Programm output"] -----------------\n" + $w.frame.text tag add bold $lineNum.0 $lineNum.end + + # open and manipulate executed program chanel # + if {$action == "compile"} { + set cmdCompile "" + CompileOption "$projCompiler $prog" + vwait cmdCompile + puts "string - $projCompiler $prog" ;# debug info + set pipe [open "|$cmdCompile 2> [file join $projDirName errors]" "r"] + set f [open [file join $projDirName errors] "r"] + } elseif {$action == "run"} { + set pipe [open "|$projInterp $prog 2> [file join $projDirName errors]" "r"] + set f [open [file join $projDirName errors] "r"] + } + + fileevent $pipe readable [list DebugInfo $w.frame.text $pipe $f] + fconfigure $pipe -buffering none -blocking no + #fileevent $f readable [list DebugInfo $w.frame.text $f] + #fconfigure $f -buffering none -blocking no +} +## INSERT DEBUG INFORMATION INTO TEXT WIDGET ## +proc DebugInfo {widget file f} { + $widget configure -state normal + if {[eof $file]} { + catch [close $file] msg + if {$msg != ""} { + puts $msg + $widget insert end "[::msgcat::mc "Program failed"]: $msg\n"; + } else { + puts $msg + $widget insert end "\n-------------------------------------------------\n" + $widget insert end "[::msgcat::mc "Program finished successfully"]\n" + } + } else { + $widget insert end [read $file] + } + while {[gets $f line]>=0} { + $widget insert end "$line\n" + puts $line + } + $widget see end + $widget tag add error 0.0 0.end + $widget configure -state disabled +} +## INSERT TITLE INTO NEW FILE ## +proc InsertTitle {newFile type} { + global activeProject projDir workDir ver + puts "$newFile $type" + set year [clock format [clock scan "now" -base [clock seconds]] -format %Y] + if {$activeProject == ""} { + set answer [tk_messageBox\ + -message "[::msgcat::mc "Not found active project"]"\ + -type ok -icon warning\ + -title [::msgcat::mc "Warning"]] + case $answer { + ok {return 0} + } + } + set file [open [file join $workDir $activeProject.proj] r] + while {[gets $file line]>=0} { + scan $line "%s" keyWord + set string [string range $line [string first "\"" $line] [string last "\"" $line]] + set string [string trim $string "\""] + if {$keyWord == "ProjectName"} { + set txtProjName "$string" + } + if {$keyWord == "ProjectFileName"} { + set txtProjFileName "$string" + } + if {$keyWord == "ProjectDirName"} { + set txtProjDirName "$string" + } + if {$keyWord == "ProjectInterp"} { + set txtProjInterp "$string" + } + if {$keyWord == "ProjectVersion"} { + set txtProjVersion "$string" + } + if {$keyWord == "ProjectRelease"} { + set txtProjRelease "$string" + } + if {$keyWord == "ProjectAuthor"} { + set txtProjAuthor "$string" + } + if {$keyWord == "ProjectEmail"} { + set txtProjEmail "$string" + } + if {$keyWord == "ProjectCompany"} { + set txtProjCompany "$string" + } + if {$keyWord == "ProjectHome"} { + set txtProjHome "$string" + } + } + if {$type == "html"} { + set fileTitle "\n\n\n\n\n\n\n\n\n\n" + } elseif {$type == "tcl"} { + set fileTitle "#!$txtProjInterp\n######################################################\n#\t\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Copyright (c) \"$txtProjCompany\", $year, $txtProjHome\n######################################################\n" + } elseif {$type == "perl" || $type == "pl"} { + set fileTitle "######################################################\n#\t\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Copyright (c) \"$txtProjCompany\", $year, $txtProjHome\n######################################################\n" + } elseif {$type == "txt"} { + set fileTitle "#######################################################\n#\t\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Copyright (c) \"$txtProjCompany\", $year, $txtProjHome\n######################################################\n" + } elseif {$type == "rb"} { + set fileTitle "#!$txtProjInterp\n######################################################\n#\t\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Copyright (c) \"$txtProjCompany\", $year, $txtProjHome\n######################################################\n" + } elseif {$type == "java"} { + set fileTitle "/*\n*****************************************************\n*\t$txtProjName\n*\tDistributed under GNU Public License\n* Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n*****************************************************\n*/\n" + } elseif {$type == "for"} { + set fileTitle "*****************************************************\n*\t$txtProjName\n*\tDistributed under GNU Public License\n* Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n*****************************************************\n" + } elseif {$type == "ml" || $type == "mli"} { + set fileTitle "\(*****************************************************\n*\t$txtProjName\n*\tDistributed under GNU Public License\n* Author: $txtProjAuthor $txtProjEmail\n* Home page: $txtProjHome\n*****************************************************\)\n" + } elseif {$type == "php" || $type == "phtml"} { + set fileTitle "" + } elseif {$type == "tml"} { + set fileTitle "\n" + } elseif {$type == "erl"} { + set fileTitle "%*****************************************************\n%\t$txtProjName\n%\tDistributed under GNU Public License\n% Author: $txtProjAuthor $txtProjEmail\n% Home page: $txtProjHome\n%****************************************************\n" + } else { + set fileTitle "######################################################\n#\t\t$txtProjName\n#\tDistributed under GNU Public License\n# Author: $txtProjAuthor $txtProjEmail\n# Copyright (c) \"$txtProjCompany\", $year, $txtProjHome\n######################################################\n" + } + set pipe [open $newFile w] + # puts "$newFile\n $fileTitle" ;# debuf info + puts $pipe $fileTitle + close $pipe +} + diff --git a/projman.conf b/projman.conf new file mode 100644 index 0000000..a1d12b1 --- /dev/null +++ b/projman.conf @@ -0,0 +1,74 @@ +########################################################### +# TCL/Tk Project Manager # +# version 0.0.1 # +# # +# Copyright (c) "CONERO lab", 2001, http://conero.lrn.ru # +# Authors: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +# Normal Font +set fontNormal "helvetica 10 normal roman" +# Bold Font # +set fontBold "helvetica 10 bold roman" +# ToolBar on/off (Yes/No) +set toolBar "Yes" + +set backUpFileCreate "No" +set backUpFileDelete "No" +set backUpFileShow "No" + +set autoFormat "Yes" + +# Directorys Settings # +set projDir "$env(HOME)/projects/tcl" +set rpmDir "$workDir/rpm" +set tgzDir "$workDir/tgz" + +# File mask # +set rpmNamed "projectName-version-release" +set tgzNamed "projectName-version-release" + +# Locale setting +set locale "en" + +## EDITOR INTERFACE SETTINGS ## +# Editor Font # +set editor(font) "courier 10 normal roman" +# Editor Bold Font # +set editor(fontBold) "courier 10 bold roman" +# background color # +set editor(bg) "#dbdbdb" +# foreground color # +set editor(fg) "#000000" +# selection background color # +set editor(selectbg) "#55c4d1" +# NoteBook title normal font color # +set editor(nbNormal) "#000000" +# NoteBook title modify font color # +set editor(nbModify) "#0021ff" +# selection border width # +set editor(selectBorder) "0" +# Editor wraping # +# must be: none, word or char +set editor(wrap) "word" + +## SOURCE CODE HIGHLIGTNING ## +set color(procName) "#0021ff" +set color(keyWord) "#0000a8" +set color(param) "#6a0082" +set color(subParam) "#008282" +set color(comments) "#9b9b9b" +set color(var) "#e50000" +set color(string) "#168400" +set color(brace) "#d33434" +set color(braceBG) "#000000" +set color(braceFG) "#43ff00" +set color(percent) "#a500c6" +set color(bindKey) "#a500c6" +set color(label) "#c9c9c9" +set color(sixFG) "#ff0000" +set color(sixBG) "#ffdbdb" +set color(sql) "#620095" + + + diff --git a/projman.spec b/projman.spec new file mode 100644 index 0000000..c05c6c3 --- /dev/null +++ b/projman.spec @@ -0,0 +1,75 @@ +Name: projman +Version: 0.3.8 +Release: alt1 +Summary: Tcl/Tk Project Manager +License: GPL +Group: Development/Tcl +Url: http://conero.lrn.ru +BuildArch: noarch +Source: %name-%version-%release.tar.gz +Requires: bwidget, ctags, tcl-img + +%description +This programm is Integrated Development Environment for Tcl/Tk language programming. Include - project manager, text and source editor with syntax highlightning, archive (tar.gz) and PRM builder and more. + +%description -l ru_RU.KOI8-R +п≤п╫я┌п╣пЁя─п╦я─п╬п╡п╟п╫п╫п╟я▐ я│я─п╣п╢п╟ п╢п╩я▐ п©я─п╬пЁя─п╟п╪п╪п╦я─п╬п╡п╟п╫п╦я▐ п╫п╟ Tcl/Tk. п▓п╨п╩я▌я┤п╟п╣я┌ п╡ я│п╣п╠я▐ - п╪п╣п╫п╣п╢п╤п╣я─ п©я─п╬п╣п╨я┌п╬п╡, п©п╬п╩п╫п╬я└я┐п╫п╨я├п╦п╬п╫п╟п╩я▄п╫я▀п╧ я─п╣п╢п╟п╨я┌п╬я─, я│п╦я│я┌п╣п╪я┐ п╫п╟п╡п╦пЁп╟я├п╦п╦ п©п╬ я└п╟п╧п╩п╟п╪ п╦ я│я┌я─я┐п╨я┌я┐я─п╣ я└п╟п╧п╩п╬п╡ п╦ п╪п╫п╬пЁп╬п╣ п╢я─я┐пЁп╬п╣. + +%prep +%setup -n %name + +%build + +%install +mkdir -p $RPM_BUILD_ROOT{%_bindir,%_datadir/%name/img,%_datadir/%name/msgs,%_datadir/%name/highlight} + +install -p -m755 projman.tcl $RPM_BUILD_ROOT%_bindir/%name +install -p -m644 *.tcl $RPM_BUILD_ROOT%_datadir/%name/ +install -p -m644 highlight/*.tcl $RPM_BUILD_ROOT%_datadir/%name/highlight/ +install -p -m644 *.conf $RPM_BUILD_ROOT%_datadir/%name/ +install -p -m644 img/*.* $RPM_BUILD_ROOT%_datadir/%name/img/ +install -p -m644 msgs/*.* $RPM_BUILD_ROOT%_datadir/%name/msgs/ + +# Menu support +mkdir -p $RPM_BUILD_ROOT/usr/lib/menu + +cat > $RPM_BUILD_ROOT/usr/lib/menu/%name << EOF +?package(%name): needs=x11 icon="projman.png" section="Applications/Development/Development environments" title=ProjMan longtitle="Tcl/Tk Project Manager" command=projman +EOF +#mdk icons +install -d $RPM_BUILD_ROOT{%_iconsdir,%_liconsdir,%_miconsdir} +install -p -m644 img/icons/%name.png $RPM_BUILD_ROOT%_iconsdir/ +install -p -m644 img/icons/large/%name.png $RPM_BUILD_ROOT%_liconsdir/ +install -p -m644 img/icons/mini/%name.png $RPM_BUILD_ROOT%_miconsdir/ + +%post +%update_menus + +%postun +%clean_menus + +%files +%doc INSTALL CHANGELOG TODO COPYING README THANKS +%doc hlp/ru/* +%_bindir/%name +%_datadir/%name +%_libdir/menu/%name +%_iconsdir/%name.png +%_liconsdir/%name.png +%_miconsdir/%name.png + + +%changelog +* Wed Feb 13 2008 Sergey Kalinin 0.3.8-alt1 +- Added text encoding support from koi8-r,cpp1251,cp866 to UTF-8 + +* Tue Feb 20 2007 Sergey Kalinin 0.3.7-alt4 +- Fixed setiings dialog +- Fixed saved settings parameter + +* Wed Oct 18 2006 Sergey Kalinin 0.3.7-alt3 +- Remove SuperText widget now use native TEXT + + + + diff --git a/projman.tcl b/projman.tcl new file mode 100644 index 0000000..18e54b5 --- /dev/null +++ b/projman.tcl @@ -0,0 +1,102 @@ +#!/usr/bin/wish + +########################################################### +# Tcl/Tk Project Manager # +# Distrubuted under GPL # +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru # +# Author: Sergey Kalinin (aka BanZaj) banzaj@lrn.ru # +########################################################### + +########## VERSION INFORMATION ########## +set ver "0.3.8" + +package require BWidget +package require msgcat + +## DO NOT EDIT THIS LINE! USE install.tcl SCRIPT ## +set rootDir "/usr" +set tclDir "/usr/bin" + +## +if {[file exists $env(HOME)/projects/tcl/projman]==1} { + set dataDir "[file join $env(HOME) projects tcl projman]" + set docDir "[file join $env(HOME) projects tcl projman hlp ru]" + set imgDir "[file join $env(HOME) projects tcl projman img]" + set msgDir "[file join $env(HOME) projects tcl projman msgs]" + set hlDir "[file join $env(HOME) projects tcl projman highlight]" +} else { + set binDir [file join $rootDir bin] + set dataDir [file join $rootDir share projman] + set docDir [file join $rootDir share doc projman-$ver] + set imgDir [file join $dataDir img] + set msgDir [file join $dataDir msgs] + set hlDir [file join $dataDir highlight] +} +if {$tcl_platform(platform) == "unix"} { + set tmpDir "$env(HOME)/tmp" + set workDir "[file join $env(HOME) .projman]" +} elseif {$tcl_platform(platform) == "windows"} { + if [info exists env(TEMP)] { + set tmpDir "$env(TEMP)" + } else { + set tmpDir "c:\\temp" + } + if {[info exist env(HOMEDRIVE)] && [info exists env(HOMEPATH)]} { + set workDir "[file join $env(HOMEDRIVE)/$env(HOMEPATH) .projman]" + } else { + set workDir "[file join $rootDir .projman]" + } +} +if {[file exists $workDir] == 0} {file mkdir $workDir} +if {[file exists $tmpDir] == 0} {file mkdir $tmpDir} + +if {[file exists [file join $workDir projman.conf]] == 0} { + file copy -force -- [file join $dataDir projman.conf] [file join $workDir projman.conf] +} + +source [file join $workDir projman.conf] + +## CREATE WORK DIR ## +if {[file exists $rpmDir] != 1} {file mkdir $rpmDir} +if {[file exists $tgzDir] != 1} {file mkdir $tgzDir} +if {[file exists $projDir] != 1} {file mkdir $projDir} + +## SETTINGS ENVIRONMENT LANGUAGE ## +if [info exists env(LANG)] { + set locale $env(LANG) +} else { + set locale $locale +} + +::msgcat::mclocale $locale +::msgcat::mcload $msgDir +#set mc_source [open [file join $msgDir $locale.msg] "r"] +#set mc_source [encoding convertto koi8-r $mc_source] +#set mc_source [encoding convertfrom [encoding system] $mc_source] + +## LOAD FILE ## + + +source [file join $dataDir procedure.tcl] +source [file join $dataDir supertext.tcl] +source [file join $dataDir editor.tcl] +source [file join $dataDir help.tcl] +source [file join $dataDir settings.tcl] +source [file join $dataDir baloon.tcl] +source [file join $dataDir completition.tcl] +source [file join $dataDir pane.tcl] +source [file join $dataDir taglist.tcl] +source [file join $dataDir projects.tcl] +source [file join $dataDir imgviewer.tcl] +source [file join $dataDir main.tcl] + + +foreach file [lsort [glob -nocomplain [file join $hlDir *.tcl]]] { + source $file + puts "Loaded highlight module $file" +} + +set editor(selectBorder) "0" + + + diff --git a/settings.tcl b/settings.tcl new file mode 100644 index 0000000..7f60890 --- /dev/null +++ b/settings.tcl @@ -0,0 +1,870 @@ +###################################################### +# Tcl/Tk project Manager +# Distributed under GNU Public License +# Author: Sergey Kalinin banzaj@lrn.ru +# Home page: http://conero.lrn.ru +###################################################### + +## SETTING DIALOG ## +proc Settings {} { + global fontNormal fontBold imgDir workDir + global editor color nb + global main editFrm network + global toolBar autoFormat backUpDel backUpCreate backUpShow localeSet localeList wrapSet wrapList + + set w .pref + # destroy the find window if it already exists + if {[winfo exists $w]} { + destroy $w + } + + toplevel $w + wm title $w [::msgcat::mc "Settings"] + # wm resizable $w 0 0 + wm geometry $w 464x450+0+0 + wm transient $w . + frame $w.frmMain -borderwidth 1 + pack $w.frmMain -side top -fill both -expand 1 + frame $w.frmBtn -borderwidth 1 + pack $w.frmBtn -side top -fill x + + set nb [NoteBook $w.frmMain.noteBook -font $fontBold -side top] + pack $nb -fill both -expand true -padx 2 -pady 2 + + button $w.frmBtn.btnFind -text [::msgcat::mc "Save"] -font $fontNormal -width 12 -relief groove\ + -command { + file copy -force [file join $workDir projman.conf] [file join $workDir projman.conf.old] + set file [open [file join $workDir projman.conf] w] + puts $file "###########################################################" + puts $file "# TCL/Tk Project Manager #" + puts $file "# version $ver #" + puts $file "# #" + puts $file "# Copyright \(c\) \"CONERO lab\", 2001, http://conero.lrn.ru #" + puts $file "# Authors: Sergey Kalinin \(aka BanZaj\) banzaj@lrn.ru #" + puts $file "###########################################################" + puts $file "# Modification date: [exec date]" + puts $file "###########################################################\n" + + puts $file "# Normal Font" + puts $file "set fontNormal \"[$main.frmFontNormal.txtFontNormal get]\"" + puts $file "# Bold Font #" + puts $file "set fontBold \"[$main.frmFontBold.txtFontBold get]\"" + puts $file "# ToolBar on/off \(Yes/No\)" + if {$toolBar == "false"} { + puts $file "set toolBar \"No\"\n" + } else { + puts $file "set toolBar \"Yes\"\n" + } + if {$backUpShow == "false"} { + puts $file "set backUpFileShow \"No\"" + } else { + puts $file "set backUpFileShow \"Yes\"" + } + if {$backUpCreate == "false"} { + puts $file "set backUpFileCreate \"No\"" + } else { + puts $file "set backUpFileCreate \"Yes\"" + } + if {$backUpDel == "false"} { + puts $file "set backUpFileDelete \"No\"" + } else { + puts $file "set backUpFileDelete \"Yes\"" + } + puts $file "\n# Don't edit this line" + puts $file "# Directorys Settings #" + puts $file "set projDir \"[$main.frmProjDir.txtProjDir get]\"" + puts $file "set rpmDir \"[$main.frmRpmDir.txtRpmDir get]\"" + puts $file "set tgzDir \"[$main.frmTgzDir.txtTgzDir get]\"" + puts $file "# File mask #" + puts $file "set rpmNamed \"[$main.frmRpmNamed.txtRpmNamed get]\"" + puts $file "set tgzNamed \"[$main.frmTgzNamed.txtTgzNamed get]\"" + puts $file "\n# Locale setting\nset locale \"$localeSet\"" + + if {$autoFormat == "false"} { + puts $file "set autoFormat \"No\"\n" + } else { + puts $file "set autoFormat \"Yes\"\n" + } + puts $file "# Editor Font #" + puts $file "set editor(font) \"[$editFrm.frmEditorFont.txtEditorFont get]\"" + puts $file "# Editor Bold Font #" + puts $file "set editor(fontBold) \"[$editFrm.frmEditorFontBold.txtEditorFontBold get]\"" + puts $file "# background color #" + puts $file "set editor(bg) \"[$editFrm.frmColorEditBG.txtColorEditBG get]\"" + puts $file "# foreground color #" + puts $file "set editor(fg) \"[$editFrm.frmColorEditFG.txtColorEditFG get]\"" + puts $file "# selection background color #" + puts $file "set editor(selectbg) \"[$editFrm.frmColorSelectBG.txtColorSelectBG get]\"" + puts $file "# NoteBook title normal font color #" + puts $file "set editor(nbNormal) \"[$editFrm.frmColorNbNormal.txtColorNbNormal get]\"" + puts $file "# NoteBook title modify font color #" + puts $file "set editor(nbModify) \"[$editFrm.frmColorNbModify.txtColorNbModify get]\"" + puts $file "# selection border width #" + puts $file "set editor(selectBorder) \"0\"" + puts $file "# Editor wraping #" + puts $file "# must be: none, word or char" + puts $file "set editor(wrap) \"$wrapSet\"" + + puts $file "## SOURCE CODE HIGHLIGTNING ##" + puts $file "set color(procName) \"[$editFrm.frmColorProc.txtColorProc get]\"" + puts $file "set color(keyWord) \"[$editFrm.frmColorKeyWord.txtColorKeyWord get]\"" + puts $file "set color(param) \"[$editFrm.frmColorParam.txtColorParam get]\"" + puts $file "set color(subParam) \"[$editFrm.frmColorSubParam.txtColorSubParam get]\"" + puts $file "set color(comments) \"[$editFrm.frmColorComments.txtColorComments get]\"" + puts $file "set color(var) \"[$editFrm.frmColorVar.txtColorVar get]\"" + puts $file "set color(string) \"[$editFrm.frmColorString.txtColorString get]\"" + puts $file "set color(brace) \"[$editFrm.frmColorBrace.txtColorBrace get]\"" + puts $file "set color(bracequad) \"[$editFrm.frmColorBraceQuad.txtColorBraceQuad get]\"" + puts $file "set color(braceBG) \"[$editFrm.frmColorBraceBG.txtColorBraceBG get]\"" + puts $file "set color(braceFG) \"[$editFrm.frmColorBraceFG.txtColorBraceFG get]\"" + puts $file "set color(percent) \"[$editFrm.frmColorPercent.txtColorPercent get]\"" + puts $file "set color(bindKey) \"[$editFrm.frmColorBindKey.txtColorBindKey get]\"" + puts $file "set color(label) \"[$editFrm.frmColorLabel.txtColorLabel get]\"" + puts $file "set color(sixFG) \"[$editFrm.frmColorSixFG.txtColorSixFG get]\"" + puts $file "set color(sixBG) \"[$editFrm.frmColorSixBG.txtColorSixBG get]\"" + puts $file "set color(sql) \"[$editFrm.frmColorSQL.txtColorSQL get]\"" + + close $file + destroy .pref + } + button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"] -relief groove -width 12\ + -font $fontNormal -command "destroy $w" + pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left + + ################## MAIN PREF ########################## + set main [$nb insert end main -text "[::msgcat::mc "Main"]"] + + set scrwin [ScrolledWindow $main.scrwin -relief groove -bd 2] + #pack $scrwin -fill both -expand true + set scrfrm [ScrollableFrame $main.frm] + pack $scrwin -fill both -expand true + pack $scrfrm -fill both -expand true + + $scrwin setwidget $scrfrm + set main [$scrfrm getframe] + + set frm_1 [frame $main.frmFontNormal] + label $frm_1.lblFontNormal -text [::msgcat::mc "Font normal"] -width 30\ + -anchor w -font $fontNormal + entry $frm_1.txtFontNormal + button $frm_1.btnFontNormal -borderwidth {1} -font $fontNormal \ + -command {SelectFontDlg $fontNormal $main.frmFontNormal.txtFontNormal} \ + -image [Bitmap::get [file join $imgDir font_selector.gif]] + pack $frm_1.lblFontNormal -side left + pack $frm_1.txtFontNormal -side left -fill x -expand true + pack $frm_1.btnFontNormal -side left + + set frm_2 [frame $main.frmFontBold] + label $frm_2.lblFontBold -text [::msgcat::mc "Font bold"] -width 30 -anchor w -font $fontNormal + entry $frm_2.txtFontBold + button $frm_2.btnFontBold -borderwidth {1} -font $fontNormal \ + -command {SelectFontDlg $fontBold $main.frmFontBold.txtFontBold} \ + -image [Bitmap::get [file join $imgDir font_selector.gif]] + pack $frm_2.lblFontBold -side left + pack $frm_2.txtFontBold -side left -fill x -expand true + pack $frm_2.btnFontBold -side left + + set frm_3 [frame $main.frmToolBar] + label $frm_3.lblToolBar -text [::msgcat::mc "Toolbar"] -width 30 -anchor w -font $fontNormal + checkbutton $frm_3.chkToolBar -text "" -variable toolBar \ + -font $fontNormal -onvalue true -offvalue false + pack $frm_3.lblToolBar -side left + pack $frm_3.chkToolBar -side left + + set frm_4 [frame $main.frmProjDir] + label $frm_4.lblProjDir -text [::msgcat::mc "Projects"] -width 30 -anchor w -font $fontNormal + entry $frm_4.txtProjDir + button $frm_4.btnProjDir -borderwidth {1} -font $fontNormal \ + -image [Bitmap::get [file join $imgDir folder.gif]]\ + -command { + InsertEnt $main.frmProjDir.txtProjDir [SelectDir $projDir] + } + pack $frm_4.lblProjDir -side left + pack $frm_4.txtProjDir -side left -fill x -expand true + pack $frm_4.btnProjDir -side left + + set frm_5 [frame $main.frmLocale] + label $frm_5.lblLocale -text [::msgcat::mc "Interface language"]\ + -width 30 -anchor w -font $fontNormal + set combo [ComboBox $frm_5.txtLocale\ + -textvariable localeSet -command "puts 123"\ + -selectbackground "#55c4d1" -selectborderwidth 0\ + -values [GetLocale]] + pack $frm_5.lblLocale -side left + pack $frm_5.txtLocale -side left -fill x -expand true + + set frm_6 [frame $main.frmRpmDir] + label $frm_6.lblRpmDir -text [::msgcat::mc "RPM dir"] -width 30 -anchor w -font $fontNormal + entry $frm_6.txtRpmDir + button $frm_6.btnRpmDir -borderwidth {1} -font $fontNormal \ + -image [Bitmap::get [file join $imgDir folder.gif]]\ + -command { + InsertEnt $main.frmRpmDir.txtRpmDir [SelectDir $workDir] + } + pack $frm_6.lblRpmDir -side left + pack $frm_6.txtRpmDir -side left -fill x -expand true + pack $frm_6.btnRpmDir -side left + + set frm_7 [frame $main.frmTgzDir] + label $frm_7.lblTgzDir -text [::msgcat::mc "TGZ dir"] -width 30 -anchor w -font $fontNormal + entry $frm_7.txtTgzDir + button $frm_7.btnTgzDir -borderwidth {1} -font $fontNormal \ + -image [Bitmap::get [file join $imgDir folder.gif]]\ + -command { + InsertEnt $main.frmTgzDir.txtTgzDir [SelectDir $workDir] + } + pack $frm_7.lblTgzDir -side left + pack $frm_7.txtTgzDir -side left -fill x -expand true + pack $frm_7.btnTgzDir -side left + + set frm_8 [frame $main.frmRpmNamed] + label $frm_8.lblRpmNamed -text [::msgcat::mc "RPM file mask"] -width 30 -anchor w\ + -font $fontNormal + entry $frm_8.txtRpmNamed + pack $frm_8.lblRpmNamed -side left + pack $frm_8.txtRpmNamed -side left -fill x -expand true + + set frm_9 [frame $main.frmTgzNamed] + label $frm_9.lblTgzNamed -text [::msgcat::mc "TGZ file mask"] -width 30 -anchor w\ + -font $fontNormal + entry $frm_9.txtTgzNamed + pack $frm_9.lblTgzNamed -side left + pack $frm_9.txtTgzNamed -side left -fill x -expand true + + set frm_10 [frame $main.frmBackUpCreate] + label $frm_10.lblBackUpCreate -text [::msgcat::mc "Create backup files"]\ + -width 30 -anchor w -font $fontNormal + checkbutton $frm_10.chkBackUpCreate -text "" -variable backUpCreate \ + -font $fontNormal -onvalue true -offvalue false + pack $frm_10.lblBackUpCreate -side left + pack $frm_10.chkBackUpCreate -side left + + set frm_11 [frame $main.frmBackUpShow] + label $frm_11.lblBackUpShow -text [::msgcat::mc "Show backup files"]\ + -width 30 -anchor w -font $fontNormal + checkbutton $frm_11.chkBackUpShow -text "" -variable backUpShow \ + -font $fontNormal -onvalue true -offvalue false + pack $frm_11.lblBackUpShow -side left + pack $frm_11.chkBackUpShow -side left + + set frm_12 [frame $main.frmBackUpDel] + label $frm_12.lblBackUpDel -text [::msgcat::mc "Delete backup files"]\ + -width 30 -anchor w -font $fontNormal + checkbutton $frm_12.chkBackUpDel -text "" -variable backUpDel \ + -font $fontNormal -onvalue true -offvalue false + pack $frm_12.lblBackUpDel -side left + pack $frm_12.chkBackUpDel -side left + + pack $frm_1 $frm_2 $frm_5 $frm_3 $frm_4 $frm_6 $frm_7 \ + $frm_8 $frm_9 $frm_10 $frm_11 $frm_12 -side top -fill both -expand true + + #################### EDITOR PREF ######################### + set editFrm [$nb insert end editor -text "[::msgcat::mc "Editor"]"] + + set scrwin [ScrolledWindow $editFrm.scrwin -relief groove -bd 2] + set scrfrm [ScrollableFrame $editFrm.frm] + pack $scrwin -fill both -expand true + pack $scrfrm -fill both -expand true + $scrwin setwidget $scrfrm + + set editFrm [$scrfrm getframe] + + set frm_13 [frame $editFrm.frmEditorFont] + label $frm_13.lblEditorFont -text [::msgcat::mc "Editor font"] -width 30\ + -anchor w -font $fontNormal + entry $frm_13.txtEditorFont + button $frm_13.btnEditorFont -borderwidth {1} -font $fontNormal \ + -command {SelectFontDlg $editor(font) $editFrm.frmEditorFont.txtEditorFont} \ + -image [Bitmap::get [file join $imgDir font_selector.gif]] + pack $frm_13.lblEditorFont -side left + pack $frm_13.txtEditorFont -side left -fill x -expand true + pack $frm_13.btnEditorFont -side left + + set frm_14 [frame $editFrm.frmEditorFontBold] + label $frm_14.lblEditorFontBold -text [::msgcat::mc "Editor font bold"]\ -width 30 -anchor w -font $fontNormal + entry $frm_14.txtEditorFontBold + button $frm_14.btnEditorFontBold -borderwidth {1} -font $fontNormal \ + -command {SelectFontDlg $editor(fontBold) $editFrm.frmEditorFontBold.txtEditorFontBold} \ + -image [Bitmap::get [file join $imgDir font_selector.gif]] + pack $frm_14.lblEditorFontBold -side left + pack $frm_14.txtEditorFontBold -side left -fill x -expand true + pack $frm_14.btnEditorFontBold -side left + + set frm_21 [frame $editFrm.frmColorEditBG] + label $frm_21.lblColorEditBG -text [::msgcat::mc "Editor background"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_21.txtColorEditBG + button $frm_21.btnColorEditBG -borderwidth {1} -font $fontNormal \ + -text "Select color" -image [Bitmap::get [file join $imgDir color_selector.gif]]\ + -command { + ColorSelect $editFrm.frmColorEditBG.txtColorEditBG $editFrm.frmColorEditBG.btnColorEditBG + ConfigureEnt [Text $editFrm.frmColorEditBG.txtColorEditBG] + } + pack $frm_21.lblColorEditBG -side left + pack $frm_21.txtColorEditBG -side left -fill x -expand true + pack $frm_21.btnColorEditBG -side left + + set frm_22 [frame $editFrm.frmColorEditFG] + label $frm_22.lblColorEditFG -text [::msgcat::mc "Editor foreground"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_22.txtColorEditFG + button $frm_22.btnColorEditFG -borderwidth {1} -font $fontNormal \ + -command { + ColorSelect $editFrm.frmColorEditFG.txtColorEditFG $editFrm.frmColorEditFG.btnColorEditFG + } \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_22.lblColorEditFG -side left + pack $frm_22.txtColorEditFG -side left -fill x -expand true + pack $frm_22.btnColorEditFG -side left + + set frm_15 [frame $editFrm.frmAutoFormat] + label $frm_15.lblAutoFormat -text [::msgcat::mc "Text autoformat"]\ + -width 30 -anchor w -font $fontNormal + checkbutton $frm_15.chkAutoFormat -text "" -variable autoFormat \ + -font $fontNormal -onvalue true -offvalue false + pack $frm_15.lblAutoFormat -side left + pack $frm_15.chkAutoFormat -side left + + set wrapList [list none word char] + + set frm_28 [frame $editFrm.frmWrap] + label $frm_28.lblWrap -text [::msgcat::mc "Word wrapping"]\ + -width 30 -anchor w -font $fontNormal + set combo2 [ComboBox $frm_28.txtWrap\ + -textvariable wrapSet -command "puts 123"\ + -selectbackground "#55c4d1" -selectborderwidth 0\ + -values "$wrapList"] + pack $frm_28.lblWrap -side left + pack $combo2 -side left + + set frm_16 [frame $editFrm.frmColorProc] + label $frm_16.lblColorProc -text [::msgcat::mc "Procedure name"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_16.txtColorProc -background $editor(bg) + button $frm_16.btnColorProc -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorProc.txtColorProc $editFrm.frmColorProc.btnColorProc} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_16.lblColorProc -side left + pack $frm_16.txtColorProc -side left -fill x -expand true + pack $frm_16.btnColorProc -side left + + set frm_17 [frame $editFrm.frmColorKeyWord] + label $frm_17.lblColorKeyWord -text [::msgcat::mc "Operators"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_17.txtColorKeyWord -background $editor(bg) + button $frm_17.btnColorKeyWord -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorKeyWord.txtColorKeyWord $editFrm.frmColorKeyWord.btnColorKeyWord} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_17.lblColorKeyWord -side left + pack $frm_17.txtColorKeyWord -side left -fill x -expand true + pack $frm_17.btnColorKeyWord -side left + + set frm_35 [frame $editFrm.frmColorParam] + label $frm_35.lblColorParam -text [::msgcat::mc "Parameters"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_35.txtColorParam -background $editor(bg) + button $frm_35.btnColorParam -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorParam.txtColorParam $editFrm.frmColorParam.btnColorParam} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_35.lblColorParam -side left + pack $frm_35.txtColorParam -side left -fill x -expand true + pack $frm_35.btnColorParam -side left + + set frm_36 [frame $editFrm.frmColorSubParam] + label $frm_36.lblColorSubParam -text [::msgcat::mc "Subparameters"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_36.txtColorSubParam -background $editor(bg) + button $frm_36.btnColorSubParam -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorSubParam.txtColorSubParam $editFrm.frmColorSubParam.btnColorSubParam} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_36.lblColorSubParam -side left + pack $frm_36.txtColorSubParam -side left -fill x -expand true + pack $frm_36.btnColorSubParam -side left + + set frm_18 [frame $editFrm.frmColorComments] + label $frm_18.lblColorComments -text [::msgcat::mc "Comments"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_18.txtColorComments -background $editor(bg) + button $frm_18.btnColorComments -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorComments.txtColorComments $editFrm.frmColorComments.btnColorComments} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_18.lblColorComments -side left + pack $frm_18.txtColorComments -side left -fill x -expand true + pack $frm_18.btnColorComments -side left + + set frm_19 [frame $editFrm.frmColorVar] + label $frm_19.lblColorVar -text [::msgcat::mc "Variables"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_19.txtColorVar -background $editor(bg) + button $frm_19.btnColorVar -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorVar.txtColorVar $editFrm.frmColorVar.btnColorVar} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_19.lblColorVar -side left + pack $frm_19.txtColorVar -side left -fill x -expand true + pack $frm_19.btnColorVar -side left + + set frm_20 [frame $editFrm.frmColorString] + label $frm_20.lblColorString -text [::msgcat::mc "Quote string"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_20.txtColorString -background $editor(bg) + button $frm_20.btnColorString -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorString.txtColorString $editFrm.frmColorString.btnColorString} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_20.lblColorString -side left + pack $frm_20.txtColorString -side left -fill x -expand true + pack $frm_20.btnColorString -side left + + set frm_23 [frame $editFrm.frmColorBrace] + label $frm_23.lblColorBrace -text [::msgcat::mc "Braces"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_23.txtColorBrace -background $editor(bg) + button $frm_23.btnColorBrace -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorBrace.txtColorBrace $editFrm.frmColorBrace.btnColorBrace} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_23.lblColorBrace -side left + pack $frm_23.txtColorBrace -side left -fill x -expand true + pack $frm_23.btnColorBrace -side left + + set frm_24 [frame $editFrm.frmColorBraceBG] + label $frm_24.lblColorBraceBG -text [::msgcat::mc "Braces background"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_24.txtColorBraceBG -background $editor(bg) + button $frm_24.btnColorBraceBG -borderwidth {1} -font $fontNormal \ + -command { + ColorSelect $editFrm.frmColorBraceBG.txtColorBraceBG $editFrm.frmColorBraceBG.btnColorBraceBG + $editFrm.frmColorBraceFG.txtColorBraceFG configure -background [Text $editFrm.frmColorBraceBG.txtColorBraceBG] + } \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_24.lblColorBraceBG -side left + pack $frm_24.txtColorBraceBG -side left -fill x -expand true + pack $frm_24.btnColorBraceBG -side left + + set frm_25 [frame $editFrm.frmColorBraceFG] + label $frm_25.lblColorBraceFG -text [::msgcat::mc "Braces foreground"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_25.txtColorBraceFG -background $color(braceBG) + button $frm_25.btnColorBraceFG -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorBraceFG.txtColorBraceFG $editFrm.frmColorBraceFG.btnColorBraceFG} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_25.lblColorBraceFG -side left + pack $frm_25.txtColorBraceFG -side left -fill x -expand true + pack $frm_25.btnColorBraceFG -side left + + set frm_26 [frame $editFrm.frmColorPercent] + label $frm_26.lblColorPercent -text [::msgcat::mc "Percent \%"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_26.txtColorPercent -background $editor(bg) + button $frm_26.btnColorPercent -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorPercent.txtColorPercent $editFrm.frmColorPercent.btnColorPercent} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_26.lblColorPercent -side left + pack $frm_26.txtColorPercent -side left -fill x -expand true + pack $frm_26.btnColorPercent -side left + + set frm_27 [frame $editFrm.frmColorBindKey] + label $frm_27.lblColorBindKey -text [::msgcat::mc "Key bindings "]\ + -width 30 -anchor w -font $fontNormal + entry $frm_27.txtColorBindKey -background $editor(bg) + button $frm_27.btnColorBindKey -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorBindKey.txtColorBindKey $editFrm.frmColorBindKey.btnColorBindKey} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_27.lblColorBindKey -side left + pack $frm_27.txtColorBindKey -side left -fill x -expand true + pack $frm_27.btnColorBindKey -side left + + set frm_32 [frame $editFrm.frmColorSelectBG] + label $frm_32.lblColorSelectBG -text [::msgcat::mc "Selection color"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_32.txtColorSelectBG -background $editor(bg) + button $frm_32.btnColorSelectBG -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorSelectBG.txtColorSelectBG $editFrm.frmColorSelectBG.btnColorSelectBG} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_32.lblColorSelectBG -side left + pack $frm_32.txtColorSelectBG -side left -fill x -expand true + pack $frm_32.btnColorSelectBG -side left + + set frm_33 [frame $editFrm.frmColorNbNormal] + label $frm_33.lblColorNbNormal -text [::msgcat::mc "Title normal"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_33.txtColorNbNormal -background $editor(bg) + button $frm_33.btnColorNbNormal -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorNbNormal.txtColorNbNormal $editFrm.frmColorNbNormal.btnColorNbNormal} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_33.lblColorNbNormal -side left + pack $frm_33.txtColorNbNormal -side left -fill x -expand true + pack $frm_33.btnColorNbNormal -side left + + set frm_34 [frame $editFrm.frmColorNbModify] + label $frm_34.lblColorNbModify -text [::msgcat::mc "Title modify"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_34.txtColorNbModify -background $editor(bg) + button $frm_34.btnColorNbModify -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorNbModify.txtColorNbModify $editFrm.frmColorNbModify.btnColorNbModify} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_34.lblColorNbModify -side left + pack $frm_34.txtColorNbModify -side left -fill x -expand true + pack $frm_34.btnColorNbModify -side left + + set frm_37 [frame $editFrm.frmColorLabel] + label $frm_37.lblColorLabel -text [::msgcat::mc "Label"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_37.txtColorLabel -background $editor(bg) + button $frm_37.btnColorLabel -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorLabel.txtColorLabel $editFrm.frmColorLabel.btnColorLabel} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_37.lblColorLabel -side left + pack $frm_37.txtColorLabel -side left -fill x -expand true + pack $frm_37.btnColorLabel -side left + + set frm_38 [frame $editFrm.frmColorSixFG] + label $frm_38.lblColorSixFG -text [::msgcat::mc "Six pos. foreground"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_38.txtColorSixFG -background $editor(bg) + button $frm_38.btnColorSixFG -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorSixFG.txtColorSixFG $editFrm.frmColorSixFG.btnColorSixFG} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_38.lblColorSixFG -side left + pack $frm_38.txtColorSixFG -side left -fill x -expand true + pack $frm_38.btnColorSixFG -side left + + set frm_39 [frame $editFrm.frmColorSixBG] + label $frm_39.lblColorSixBG -text [::msgcat::mc "Six pos. background"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_39.txtColorSixBG -background $editor(bg) + button $frm_39.btnColorSixBG -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorSixBG.txtColorSixBG $editFrm.frmColorSixBG.btnColorSixBG} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_39.lblColorSixBG -side left + pack $frm_39.txtColorSixBG -side left -fill x -expand true + pack $frm_39.btnColorSixBG -side left + + set frm_40 [frame $editFrm.frmColorSQL] + label $frm_40.lblColorSQL -text [::msgcat::mc "SQL commands"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_40.txtColorSQL -background $editor(bg) + button $frm_40.btnColorSQL -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorSQL.txtColorSQL $editFrm.frmColorSQL.btnColorSQL} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_40.lblColorSQL -side left + pack $frm_40.txtColorSQL -side left -fill x -expand true + pack $frm_40.btnColorSQL -side left + + set frm_41 [frame $editFrm.frmColorBraceQuad] + label $frm_41.lblColorBraceQuad -text [::msgcat::mc "Quad braces"]\ + -width 30 -anchor w -font $fontNormal + entry $frm_41.txtColorBraceQuad -background $editor(bg) + button $frm_41.btnColorBraceQuad -borderwidth {1} -font $fontNormal \ + -command {ColorSelect $editFrm.frmColorBraceQuad.txtColorBraceQuad $editFrm.frmColorBraceQuad.txtColorBraceQuad} \ + -text "Select color"\ + -image [Bitmap::get [file join $imgDir color_selector.gif]] + pack $frm_41.lblColorBraceQuad -side left + pack $frm_41.txtColorBraceQuad -side left -fill x -expand true + pack $frm_41.btnColorBraceQuad -side left + + pack $frm_13 $frm_14 $frm_15 $frm_28 $frm_21 $frm_22 $frm_32 $frm_33 $frm_34 $frm_16 $frm_17 $frm_35 $frm_36 $frm_18 $frm_19 $frm_20\ + $frm_23 $frm_41 $frm_24 $frm_25 $frm_26 $frm_27 $frm_37 $frm_38 $frm_39 $frm_40 -side top -fill x -expand true + + ################### NETWORK PREF ######################### + set network [$nb insert end network -text "[::msgcat::mc "Network"]" -state disabled] + set scrwin [ScrolledWindow $network.scrwin -relief groove -bd 2] + set scrfrm [ScrollableFrame $network.frm] + pack $scrwin -fill both -expand true + pack $scrfrm -fill both -expand true + $scrwin setwidget $scrfrm + + set network [$scrfrm getframe] + + set frm_29 [frame $network.frmFtpServer] + label $frm_29.lblFtpServer -text [::msgcat::mc "FTP server"] -width 30\ + -anchor w -font $fontNormal + entry $frm_29.txtFtpServer + pack $frm_29.lblFtpServer -side left + pack $frm_29.txtFtpServer -side left -fill x -expand true + + set frm_30 [frame $network.frmFtpUser] + label $frm_30.lblFtpUser -text [::msgcat::mc "FTP user"] -width 30\ + -anchor w -font $fontNormal + entry $frm_30.txtFtpUser + pack $frm_30.lblFtpUser -side left + pack $frm_30.txtFtpUser -side left -fill x -expand true + + set frm_31 [frame $network.frmFtpUserPass] + label $frm_31.lblFtpUserPass -text [::msgcat::mc "FTP password"] -width 30\ + -anchor w -font $fontNormal + entry $frm_31.txtFtpUserPass + pack $frm_31.lblFtpUserPass -side left + pack $frm_31.txtFtpUserPass -side left -fill x -expand true + + pack $frm_29 $frm_30 $frm_31 -side top -fill x + + $nb raise main + # Read a config file # + LoadSettings +} + +proc ColorSelect {ent w} { + set color [SelectColor::menu $w.color [list below $w] -color [$w cget -background]] + if {[string length $color]} { + $ent configure -foreground $color + InsertEnt $ent $color + } +} + +## SHOW SELECTED COLOR IN DIALOG ## +proc ConfigureEnt {col} { + global editor color + global main editFrm network + $editFrm.frmColorEditFG.txtColorEditFG configure -background $col + $editFrm.frmColorProc.txtColorProc configure -background $col + $editFrm.frmColorKeyWord.txtColorKeyWord configure -background $col + $editFrm.frmColorParam.txtColorParam configure -background $col + $editFrm.frmColorSubParam.txtColorSubParam configure -background $col + $editFrm.frmColorComments.txtColorComments configure -background $col + $editFrm.frmColorVar.txtColorVar configure -background $col + $editFrm.frmColorString.txtColorString configure -background $col + $editFrm.frmColorBrace.txtColorBrace configure -background $col + $editFrm.frmColorBraceQuad.txtColorBraceQuad configure -background $col + $editFrm.frmColorBraceBG.txtColorBraceBG configure -background $col + $editFrm.frmColorBraceFG.txtColorBraceFG configure -background $col + $editFrm.frmColorPercent.txtColorPercent configure -background $col + $editFrm.frmColorBindKey.txtColorBindKey configure -background $col + $editFrm.frmColorLabel.txtColorLabel configure -background $col + $editFrm.frmColorSixFG.txtColorSixFG configure -background $col + $editFrm.frmColorSixBG.txtColorSixBG configure -background $col + $editFrm.frmColorSQL.txtColorSQL configure -background $col +} + +## READ CONFIG FILE ## +proc LoadSettings {} { + global fontNormal imgDir workDir msgDir + global editor color nb + global main editFrm network + global toolBar autoFormat backUpDel backUpCreate backUpShow localeSet localeList wrapSet wrapList + + ## load .conf file ## + set file [open [file join $workDir projman.conf] r] + while {[gets $file line]>=0} { + scan $line "%s%s%s" trash keyWord var + if {$trash == "set"} { + set var [string trim $var "\""] + switch $keyWord { + fontNormal { + set v [string trim [string range $line [string first $var $line] end] "\""] + InsertEnt $main.frmFontNormal.txtFontNormal "$v" + } + fontBold { + set v [string trim [string range $line [string first $var $line] end] "\""] + InsertEnt $main.frmFontBold.txtFontBold "$v" + } + locale { + set localeIndex [lsearch -exact $localeList "$var"] + if {$localeIndex != -1} { + $main.frmLocale.txtLocale setvalue @$localeIndex + } else { + puts "$var.msg file not found into $msgDir" + } + } + toolBar {if {$var == "Yes"} {set toolBar "true" } else {set toolBar "false"} } + backUpFileShow { + if {$var == "Yes"} { + set backUpShow "true" + } else { + set backUpShow "false" + } + } + backUpFileCreate { + if {$var == "Yes"} { + set backUpCreate "true" + } else { + set backUpCreate "false" + } + } + backUpFileDel { + if {$var == "Yes"} { + set backUpDel "true" + } else { + set backUpDel "false" + } + } + projDir {InsertEnt $main.frmProjDir.txtProjDir "$var"} + rpmDir {InsertEnt $main.frmRpmDir.txtRpmDir "$var"} + tgzDir {InsertEnt $main.frmTgzDir.txtTgzDir "$var"} + rpmNamed {InsertEnt $main.frmRpmNamed.txtRpmNamed "$var"} + tgzNamed {InsertEnt $main.frmTgzNamed.txtTgzNamed "$var"} + autoFormat {if {$var == "Yes"} {set autoFormat "true"} else {set autoFormat "false"}} + "editor(wrap)" { + set wrapIndex [lsearch -exact $wrapList "$var"] + if {$wrapIndex != -1} { + $editFrm.frmWrap.txtWrap setvalue @$wrapIndex + } + unset wrapIndex + } + "editor(bg)" { + InsertEnt $editFrm.frmColorEditBG.txtColorEditBG "$var" + ConfigureEnt $var + } + "editor(fg)" {InsertEnt $editFrm.frmColorEditFG.txtColorEditFG "$var"} + "editor(selectbg)" {InsertEnt $editFrm.frmColorSelectBG.txtColorSelectBG "$var"} + "editor(nbNormal)" {InsertEnt $editFrm.frmColorNbNormal.txtColorNbNormal "$var"} + "editor(nbModify)" {InsertEnt $editFrm.frmColorNbModify.txtColorNbModify "$var"} + "color(procName)" {InsertEnt $editFrm.frmColorProc.txtColorProc "$var"} + "color(keyWord)" {InsertEnt $editFrm.frmColorKeyWord.txtColorKeyWord "$var"} + "color(param)" {InsertEnt $editFrm.frmColorParam.txtColorParam "$var"} + "color(subParam)" {InsertEnt $editFrm.frmColorSubParam.txtColorSubParam "$var"} + "color(comments)" {InsertEnt $editFrm.frmColorComments.txtColorComments "$var"} + "color(var)" {InsertEnt $editFrm.frmColorVar.txtColorVar "$var"} + "color(string)" {InsertEnt $editFrm.frmColorString.txtColorString "$var"} + "color(brace)" {InsertEnt $editFrm.frmColorBrace.txtColorBrace "$var"} + "color(bracequad)" {InsertEnt $editFrm.frmColorBraceQuad.txtColorBraceQuad "$var"} + "color(braceBG)" {InsertEnt $editFrm.frmColorBraceBG.txtColorBraceBG "$var"} + "color(braceFG)" {InsertEnt $editFrm.frmColorBraceFG.txtColorBraceFG "$var"} + "color(percent)" {InsertEnt $editFrm.frmColorPercent.txtColorPercent "$var"} + "color(bindKey)" {InsertEnt $editFrm.frmColorBindKey.txtColorBindKey "$var"} + "color(label)" {InsertEnt $editFrm.frmColorLabel.txtColorLabel "$var"} + "color(sixFG)" {InsertEnt $editFrm.frmColorSixFG.txtColorSixFG "$var"} + "color(sixBG)" {InsertEnt $editFrm.frmColorSixBG.txtColorSixBG "$var"} + "color(sql)" {InsertEnt $editFrm.frmColorSQL.txtColorSQL "$var"} + } + if {$keyWord == "editor(fontBold)"} { + set v [string trim [string range $line [string first $var $line] end] "\""] + InsertEnt $editFrm.frmEditorFontBold.txtEditorFontBold "$v" + } + if {$keyWord == "editor(font)"} { + set v [string trim [string range $line [string first $var $line] end] "\""] + InsertEnt $editFrm.frmEditorFont.txtEditorFont "$v" + } + } + } + close $file +} + +## SAVE SETTINGS PROCEDURE ## +proc SaveSettings {} { + global editor color workDir + global main editFrm network wrapSet + file copy -force [file join $workDir projman.conf] [file join $workDir projman.conf.old] + set file [open [file join $workDir projman.conf] w] + puts $file "###########################################################" + puts $file "# TCL/Tk Project Manager #" + puts $file "# version $ver #" + puts $file "# #" + puts $file "# Copyright \(c\) \"CONERO lab\", 2001, http://conero.lrn.ru #" + puts $file "# Authors: Sergey Kalinin \(aka BanZaj\) banzaj@lrn.ru #" + puts $file "###########################################################\n" + puts $file "# Modification date: [exec date]" + puts $file "###########################################################\n" + + puts $file "# Normal Font" + puts $file "set fontNormal \"[$main.frmFontNormal.txtFontNormal get]\"" + puts $file "# Bold Font #" + puts $file "set fontBold \"[$main.frmFontBold.txtFontBold get]\"" + puts $file "# ToolBar on/off \(Yes/No\)" + if {$toolBar == "false"} { + puts $file "set toolBar \"No\"\n" + } else { + puts $file "set toolBar \"Yes\"\n" + } + if {$backUpShow == "false"} { + puts $file "set backUpFileShow \"No\"" + } else { + puts $file "set backUpFileShow \"Yes\"" + } + if {$backUpCreate == "false"} { + puts $file "set backUpFileCreate \"No\"" + } else { + puts $file "set backUpFileCreate \"Yes\"" + } + if {$backUpDel == "false"} { + puts $file "set backUpFileDelete \"No\"" + } else { + puts $file "set backUpFileDelete \"Yes\"" + } + puts $file "\n# Don't edit this line" + puts $file "# Directorys Settings #" + puts $file "set projDir \"[$main.frmProjDir.txtProjDir get]\"" + puts $file "set rpmDir \"[$main.frmRpmDir.txtRpmDir get]\"" + puts $file "set tgzDir \"[$main.frmTgzDir.txtTgzDir get]\"" + puts $file "# File mask #" + puts $file "set rpmNamed \"[$main.frmRpmNamed.txtRpmNamed get]\"" + puts $file "set tgzNamed \"[$main.frmTgzNamed.txtTgzNamed get]\"" + puts $file "\n# Locale setting\nset locale \"$localeSet\"" + + if {$autoFormat == "false"} { + puts $file "set autoFormat \"No\"\n" + } else { + puts $file "set autoFormat \"Yes\"\n" + } + puts $file "# Editor Font #" + puts $file "set editor(font) \"[$frm_17.txtEditorFont get]\"" + puts $file "# Editor Bold Font #" + puts $file "set editor(fontBold) \"[$frm_18.txtEditorFontBold get]\"" + puts $file "# background color #" + puts $file "set editor(bg) \"[$editFrm.frmColorEditBG.txtColorEditBG get]\"" + puts $file "# foreground color #" + puts $file "set editor(fg) \"[$editFrm.frmColorEditFG.txtColorEditFG get]\"" + puts $file "# selection background color #" + puts $file "set editor(selectbg) \"[$editFrm.frmColorSelectBG.txtColorSelectBG get]\"" + puts $file "# NoteBook title normal font color #" + puts $file "set editor(nbNormal) \"[$editFrm.frmColorNbNormal.txtColorNbNormal get]\"" + puts $file "# NoteBook title modify font color #" + puts $file "set editor(nbModify) \"[$editFrm.frmColorNbModify.txtColorNbModify get]\"" + puts $file "# selection border width #" + puts $file "set editor(selectBorder) \"0\"" + puts $file "# Editor wraping #" + puts $file "# must be: none, word or char" + puts $file "set editor(wrap) \"$wrapSet\"" + + puts $file "## SOURCE CODE HIGHLIGTNING ##" + puts $file "set color(procName) \"[$editFrm.frmColorProc.txtColorProc get]\"" + puts $file "set color(keyWord) \"[$editFrm.frmColorKeyWord.txtColorKeyWord get]\"" + puts $file "set color(param) \"[$editFrm.frmColorComments.txtColorComments get]\"" + puts $file "set color(subParam) \"[ get]\"" + puts $file "set color(comments) \"[ get]\"" + puts $file "set color(var) \"[$editFrm.frmColorVar.txtColorVar get]\"" + puts $file "set color(string) \"[$editFrm.frmColorString.txtColorString get]\"" + puts $file "set color(brace) \"[$editFrm.frmColorBrace.txtColorBrace get]\"" + puts $file "set color(bracequad) \"[$editFrm.frmColorBraceQuad.txtColorBraceQuad get]\"" + puts $file "set color(braceBG) \"[$editFrm.frmColorBraceBG.txtColorBraceBG get]\"" + puts $file "set color(braceFG) \"[$editFrm.frmColorBraceFG.txtColorBraceFG get]\"" + puts $file "set color(percent) \"[$editFrm.frmColorPercent.txtColorPercent get]\"" + puts $file "set color(bindKey) \"[$editFrm.frmColorBindKey.txtColorBindKey get]\"" + puts $file "set color(label) \"[$editFrm.frmColorLabel.txtColorLabel get]\"" + puts $file "set color(sixFG) \"[$editFrm.frmColorSixFG.txtColorSixFG get]\"" + puts $file "set color(sixBG) \"[$editFrm.frmColorSixBG.txtColorSixBG get]\"" + puts $file "set color(sql) \"[$editFrm.frmColorSQL.txtColorSQL get]\"" + + close $file + $noteBook delete settings + $noteBook raise [$noteBook page end] +} + + + + + + + + + + + diff --git a/supertext.tcl b/supertext.tcl new file mode 100644 index 0000000..65f9866 --- /dev/null +++ b/supertext.tcl @@ -0,0 +1,386 @@ +# supertext.tcl v1.01 +# +# Copyright (c) 1998 Bryan Oakley +# All Rights Reserved +# +# this code is freely distributable, but is provided as-is with +# no waranty expressed or implied. + +# send comments to oakley@channelpoint.com + +# What is this? +# +# This is a replacement for (or superset of , or subclass of, ...) +# the tk text widget. Its big feature is that it supports unlimited +# undo. It also has two poorly documented options: -preproc and +# -postproc. + +# The entry point to this widget is supertext::text; it takes all of +# the same arguments as the standard text widget and exhibits all of +# the same behaviors. The proc supertext::overrideTextCommand may be +# called to have the supertext widget be used whenever the command +# "text" is used (ie: it imports supertext::text as the command "text"). +# Use at your own risk... + +# To access the undo feature, use ".widget undo". It will undo the +# most recent insertion or deletion. On windows and the mac +# this command is bound to ; on unix it is bound to +# + +# if you are lucky, you might find documentation here: +# http://www1.clearlight.com/~oakley/tcl/supertext.html + +package provide supertext 1.01 + +namespace eval supertext { + variable undo + variable undoIndex + variable text "::text" + variable preProc + variable postProc + namespace export text +} + +# this proc is probably attempting to be more clever than it should... +# When called, it will (*gasp*) rename the tk command "text" to "_text_", +# then import our text command into the global scope. +# +# Use at your own risk! + +proc supertext::overrideTextCommand {} { + variable text + set text "::_text_" + rename ::text $text + uplevel #0 namespace import supertext::text +} + +proc supertext::text {w args} { + variable text + variable undo + variable undoIndex + variable preProc + variable postProc + + # this is what we will rename our widget proc to... + set original __$w + + # do we have any of our custom options? If so, process them and + # strip them out before sending them to the real text command + if {[set i [lsearch -exact $args "-preproc"]] >= 0} { + set j [expr $i + 1] + set preProc($original) [lindex $args $j] + set args [lreplace $args $i $j] + } else { + set preProc($original) {} + } + + if {[set i [lsearch -exact $args "-postproc"]] >= 0} { + set j [expr $i + 1] + set postProc($original) [lindex $args $j] + set args [lreplace $args $i $j] + } else { + set postProc($original) {} + } + + # let the text command create the widget... + eval $text $w $args + + # now, rename the resultant widget proc so we can create our own + rename ::$w $original + + # here's where we create our own widget proc. + proc ::$w {command args} \ + "namespace eval supertext widgetproc $w $original \$command \$args" + + # set up platform-specific binding for undo; the only one I'm + # really sure about is winders; the rest will stay the same for + # now until someone has a better suggestion... + switch $::tcl_platform(platform) { + unix { + event add <> + event add <> + } + windows { + event add <> + event add <> + } + macintosh { + event add <> + event add <> + } + } + bind $w <> "$w undo" + + set undo($original) {} + set undoIndex($original) -1 + set clones($original) {} + + return $w +} + +# this is the command that we associate with a supertext widget. +proc supertext::widgetproc {this w command args} { + + variable undo + variable undoIndex + variable preProc + variable postProc + + # these will be the arguments to the pre and post procs + set originalCommand $command + set originalArgs $args + + # is there a pre-proc? If so, run it. If there is a problem, + # die. This is potentially bad, because once there is a problem + # in a preproc the user must fix the preproc -- there is no + # way to unconfigure the preproc. Oh well. The other choice + # is to ignore errors, but then how will the caller know if + # the proc fails? + if {[info exists preProc($w)] && $preProc($w) != ""} { + if {[catch "$preProc($w) command args" error]} { + return -code error "error during processing of -preproc: $error" + } + } + + + # if the command is "undo", we need to morph it into the appropriate + # command for undoing the last item on the stack + if {$command == "undo"} { + + if {$undoIndex($w) == ""} { + # ie: last command was anything _but_ an undo... + set undoIndex($w) [expr [llength $undo($w)] -1] + } + + # if the index is pointing to a valid list element, + # lets undo it... + if {$undoIndex($w) < 0} { + # nothing to undo... + bell + + } else { + + # data is a list comprised of a command token + # (i=insert, d=delete) and parameters related + # to that token + set data [lindex $undo($w) $undoIndex($w)] + + if {[lindex $data 0] == "d"} { + set command "delete" + } else { + set command "insert" + } + set args [lrange $data 1 end] + + # adjust the index + incr undoIndex($w) -1 + + } + } + + # now, process the command (either the original one, or the morphed + # undo command + switch $command { + + reset_undo { + set undo($w) "" + set undoIndex($w) "" + set result {} + } + + configure { + # we have to deal with configure specially, since the + # user could try to configure the -preproc or -postproc + # options... + + if {[llength $args] == 0} { + # first, the case where they just type "configure"; lets + # get it out of the way + set list [$w configure] + lappend list [list -preproc preproc Preproc {} $preProc($w)] + lappend list [list -postproc postproc Postproc {} $postProc($w)] + set result $list + + + } elseif {[llength $args] == 1} { + # this means they are wanting specific configuration + # information + set option [lindex $args 0] + if {$option == "-preproc"} { + set result [list -preproc preproc Preproc {} $preProc($w)] + + } elseif {$option == "-postproc"} { + set result [list -postproc postproc Postproc {} $postProc($w)] + + } else { + if {[catch "$w $command $args" result]} { + regsub $w $result $this result + return -code error $result + } + } + + } else { + # ok, the user is actually configuring something... + # we'll deal with our special options first + if {[set i [lsearch -exact $args "-preproc"]] >= 0} { + set j [expr $i + 1] + set preProc($w) [lindex $args $j] + set args [lreplace $args $i $j] + set result {} + } + + if {[set i [lsearch -exact $args "-postproc"]] >= 0} { + set j [expr $i + 1] + set postProc($w) [lindex $args $j] + set args [lreplace $args $i $j] + set result {} + } + + # now, process any remaining args + if {[llength $args] > 0} { + if {[catch "$w $command $args" result]} { + regsub $w $result $this result + return -code error $result + } + } + } + } + + undo { + # if an undo command makes it to here, that means there + # wasn't anything to undo; this effectively becomes a + # no-op + set result {} + } + + insert { + + if {[catch {set index [text_index $w [lindex $args 0]]}]} { + set index [lindex $args 0] + } + + # since the insert command can have an arbitrary number + # of strings and possibly tags, we need to ferret that out + # now... what a pain! + set myargs [lrange $args 1 end] + set length 0 + while {[llength $myargs] > 0} { + incr length [string length [lindex $myargs 0]] + if {[llength $myargs] > 1} { + # we have a tag... + set myargs [lrange $myargs 2 end] + } else { + set myargs [lrange $myargs 1 end] + } + } + + # now, let the real widget command do the dirty work + # of inserting the text. If we fail, do some munging + # of the error message so the right widget name appears... + + if {[catch "$w $command $args" result]} { + regsub $w $result $this result + return -code error $result + } + + # we need this for the undo stack; index2 couldn't be + # computed until after we inserted the data... + set index2 [text_index $w "$index + $length chars"] + + if {$originalCommand == "undo"} { + # let's do a "see" so what we just did is visible; + # also, we'll move the insertion cursor to the end + # of what we just did... + $w see $index2 + $w mark set insert $index2 + + } else { + # since the original command wasn't undo, we need + # to reset the undoIndex. This means that the next + # time an undo is called for we'll start at the + # end of the stack + set undoIndex($w) "" + } + + # add a delete command on the undo stack. + lappend undo($w) "d $index $index2" + + } + + delete { + + # this converts the insertion index into an absolute address + set index [text_index $w [lindex $args 0]] + + # lets get the data we are about to delete; we'll need + # it to be able to undo it (obviously. Duh.) + set data [eval $w get $args] + + # add an insert on the undo stack + lappend undo($w) [list "i" $index $data] + + if {$originalCommand == "undo"} { + # let's do a "see" so what we just did is visible; + # also, we'll move the insertion cursor to a suitable + # spot + $w see $index + $w mark set insert $index + + } else { + # since the original command wasn't undo, we need + # to reset the undoIndex. This means that the next + # time an undo is called for we'll start at the + # end of the stack + set undoIndex($w) "" + } + + # let the real widget command do the actual deletion. If + # we fail, do some munging of the error message so the right + # widget name appears... + if {[catch "$w $command $args" result]} { + regsub $w $result $this result + return -code error $result + } + } + + default { + # if the command wasn't one of the special commands above, + # just pass it on to the real widget command as-is. If + # we fail, do some munging of the error message so the right + # widget name appears... + if {[catch "$w $command $args" result]} { + regsub $w $result $this result + return -code error $result + } + } + } + + # is there a post-proc? If so, run it. + if {[info exists postProc($w)] && $postProc($w) != ""} { + if {[catch "$postProc($w) originalCommand originalArgs" error]} { + return -code error "error during processing of -postproc: $error" + } + } + + + # we're outta here! (I think this is faster than a + # return, though I'm not 100% sure on this...) + set result $result +} + +# this returns a normalized index (ie: line.column), with special +# handling for the index "end"; to undo something we pretty much +# _have_ to have a precise row and column number. +proc supertext::text_index {w i} { + if {$i == "end"} { + set index [$w index "end-1c"] + } else { + set index [$w index $i] + } + + return $index +} + + + + diff --git a/taglist.tcl b/taglist.tcl new file mode 100644 index 0000000..3e88820 --- /dev/null +++ b/taglist.tcl @@ -0,0 +1,55 @@ +######################################################### +# Tcl/Tk project Manager +# Distributed under GNU Public License +# Author: Sergey Kalinin banzaj@lrn.ru +# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru +######################################################### + +proc GetTagList {tagFile} { + global tmpDir projDir workDir procList activeProject + + if {[file exists $tagFile] == 0} { + return + } + + set file [open $tagFile r] + set procList($activeProject) "" + while {[gets $file line]>=0} { + scan $line "%s%s" proc procFile + if {[regexp -nocase -all -- {\s\{.*?\}+\s} $line par]} { + if [info exists procList($activeProject)] { + lappend procList($activeProject) [list $proc $par $procFile] + } else { + set procList($activeProject) [list [list $proc $par $procFile]] + } + } + } +} + + +proc GetTagList_ {tagFile} { + global tmpDir projDir workDir procList activeProject + if {[file exists $tagFile] == 0} { + return + } + set projName [file rootname $tagFile] + set file [open $tagFile r] + set procList($projName) "" + while {[gets $file line]>=0} { + scan $line "%s%s" proc procFile + if {[regexp -nocase -all -- {\s\{.*?\}+\s} $line par]} { + if [info exists procList($projName)] { + lappend procList($projName) [list $proc $par $procFile] + } else { + set procList($projName) [list [list $proc $par $procFile]] + } + } + } +} + + + + + + + diff --git a/temp.txt b/temp.txt new file mode 100644 index 0000000..124b425 --- /dev/null +++ b/temp.txt @@ -0,0 +1,31 @@ +Аналоги клавиш для bind в WINDOWS + +a ocircumflex +b egrave +c ntilde +d acircumflex +e oacute +f agrave +g idiaeresis +h eth +i oslash +j icircumflex +k ediaeresis +l adiaeresis +m udiaeresis +n ograve +o ugrave +p ccedilla +q eacute +r ecircumflex +s ucircumflex +t aring +u atilde +v igrave +w odiaeresis +x division +y iacute +z ydiaeresis +comma aacute +period thorn + diff --git a/tkregexp.tcl b/tkregexp.tcl new file mode 100644 index 0000000..b625f38 --- /dev/null +++ b/tkregexp.tcl @@ -0,0 +1,1365 @@ +#!/bin/sh +#-*-tcl-*- +# the next line restarts using wish \ +exec wish "$0" -- ${1+"$@"} + + +set version 3.0 + +############################################################################################### +# +# VisualREGEXP -- A graphical front-end to wirte/debug regular expression +# (c) 2000-2002 Laurent Riesterer +# +# VisualREGEXP Home Page: http://laurent.riesterer.free.fr/regexp +# +#---------------------------------------------------------------------------------------------- +# +# Usage: tkregexp +# +#---------------------------------------------------------------------------------------------- +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +############################################################################################### + + + +#---------------------------------------------------------------------------------------------- +# SOME CUSTOMIZATION CAN BE DONE BY MODIFYING VARIABLES BELOW +#---------------------------------------------------------------------------------------------- + +# default geometry +set geometry 800x600+0+0 +# main font used to display the text +if {$tcl_platform(platform) == "windows"} { + set font_regexp {Courier 10} + set font_replace {Courier 10} + set font_sample {Courier 10} +} else { + set font_regexp 9x15 + set font_replace 9x15 + set font_sample 9x15 +} +# the font used in the popup menu (use ---- to get a separator, else format is {font size ?bold?} +set fonts {{Courier 8} {Courier 9} {Courier 10} {Courier 11} {Courier 12} + ---- + {Arial 8} {Arial 9} {Arial 10} {Arial 11} {Arial 12} + ---- + 8x13 8x13bold 9x15 9x15bold 10x20} +# the colors for the different matching groups +set colors {#ff0000 #0000ff darkgreen violetred #ff9000 #537db9 #e4c500 firebrick darkgoldenrod hotpink} +set bgcolors {#ffe6e6 #e6e6ff #e6ffe6 #efd5e1 #fef3e5 #d6dce5 lightyellow white white white} +# use background color in sample by default ? (1 use, 0 do not use) +set background 0 +# background color to visualize the non-reporting group (?:...) +set color_noreport #fffdc4 +# background color to visualize the lookhead group (?=...) and (?!...) +set color_lookahead wheat +# show/hide help about control characters in regexp +set show_help 0 +# show/hide history windows on startup +set history 0 +# mode to use on startup (select/concat = raw, select/insert new lines = nl, replace = replace) +set mode replace +# database of some regexp to appear in the "Insert regexp" menu +set regexp_db { + "URL" {(?:^|")(http|ftp|mailto):(?://)?(\w+(?:[\.:@]\w+)*?)(?:/|@)([^"\?]*?)(?:\?([^\?"]*?))?(?:$|")} + "IP numbers" {[12]?[0-9]?[0-9](\.[12]?[0-9]?[0-9]){3}} + "HTML tags" {<[^<>]+>} + "HTML tag content" {<(\w+)[^>]*?>(.*?)} + "vars and arrays (PHP)" {\$[^0-9 ]{1}[a-zA-Z0-9_]*((?:\[[a-zA-Z0-9_'\"]+\])*)} + "dd/mm/yyyy" {(0[1-9]|[12][0-9]|3[01])(/|-)(0[1-9]|1[12])(/|-)[12][0-9]{3}} + "mm/dd/yyyy" {(0[1-9]|1[12])(/|-)(0[1-9]|[12][0-9]|3[01])(/|-)[12][0-9]{3}} + "hh:mm" {([01][0-9]|2[0-3]):[0-5][0-9]} + "user@domain.net" {[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}} +} + + +#---------------------------------------------------------------------------------------------- +# DO NOT MODIFY BELOW THIS POINT +#---------------------------------------------------------------------------------------------- + +namespace eval regexp {} { + set data(v:undo:index) 0 + set data(v:undo:sample) "" + set data(v:dir) "." + set data(v:file) "untitled.txt" +} + +#---------------------------------------------------------------------------------------------- +# Main GUI +#---------------------------------------------------------------------------------------------- + +proc regexp::gui {} { +variable data +global colors bgcolors color_noreport color_lookahead geometry show_help regexp_db history +global tcl_platform + + + set top "" + + # frame for regexp + set w [frame $top.regexp -bd 2 -relief groove] + # options + set fo [frame $w.options] + set sep 0 + foreach option {nocase all - line lineanchor linestop - inline} \ + label {nocase all - line "lineanchor (k)" "linestop (m)" - inline} \ + underline {0 0 - 0 12 10 - 0} { + if {$option != "-"} { + checkbutton $fo.$option -text $label -bd 1 -underline $underline \ + -variable regexp::data(v:$option) \ + -offvalue "" -onvalue "-$option" + set data(v:$option) "" + pack $fo.$option -side left + } else { + pack [frame $fo.[incr sep] -width 40] -side left + } + } + # text for regexp entry + set data(w:regexp) [text $w.regexp -wrap char -bg white -font $::font_regexp \ + -selectbackground lightblue -selectborderwidth 0 \ + -width 1 -height 3 -bd 1] + if {$tcl_platform(platform) == "windows"} { + set sfont {Courier 8} + set sbfont {Courier 8 bold} + } else { + set sfont 6x13 + set sbfont 6x13bold + } + set data(w:help) [text $w.help -font $sfont -bd 0 -height 9 -wrap none -bg [$w cget -bg]] + $w.help insert 1.0 "\n\n\n\n\n\n\n\n" + $w.help insert 1.0 {\a alert \n newline \0 char 0 \d [[:digit:]] \A beginning of the string } + $w.help insert 2.0 {\b backspace \r carriage \xyz octal code \D [^[:digit:]] \Z end of string } + $w.help insert 3.0 {\B synomyn for \ \t tab \s [[:space:]] \m beginning of a word} + $w.help insert 4.0 {\cX same as X & 0x1F \uwxyz unicode \x backref \S [^[:space:]] \M end of a word} + $w.help insert 5.0 {\e ESC \v vert tab \w [[:alnum:]_] \y beginning or end of a word} + $w.help insert 6.0 {\f form feed \xhhh hexa code \W [^[:alnum:]_] \Y not beginning or end of a word} + $w.help insert 7.0 {----------------------------------------------------------------------------------------------------------------} + $w.help insert 8.0 { ungreedy: ?? single optional *? zero-many +? at least one {n,m}? ungreedy quantifiers} + $w.help insert 9.0 {(?:) ghost group (?=) lookahead (?!) neg. lookahead} + $w.help tag configure bold -font $sbfont + foreach line {1 2 3 4 5 6} { + foreach {min max} {0 2 23 25 42 44 61 63 79 82} { + $w.help tag add bold $line.$min $line.$max + } + } + $w.help tag remove bold 2.43 2.44 4.43 4.44 + # buttons & selection of match + set fb [frame $w.b] + button $fb.go -text "Go" -underline 0 -command "regexp::go" -bd 1 -width 5 + button $fb.clear -text "Clear (z)" -underline 7 -command "regexp::clear" -bd 1 -width 5 + pack $fb.go [frame $fb.00 -width 10] $fb.clear -side left -pady 5 + + # selection - buttons for match level + label $fb.sep + label $fb.l -text "Select:" + pack $fb.sep -side left -fill x -expand true + pack $fb.l -side left -padx 5 -pady 5 + set i 0 + foreach c $colors t {match 1 2 3 4 5 6 7 8 9} { + button $fb.$i -text $t -fg $c -bd 1 -padx 0 -width 6 -command "regexp::select $i" + pack $fb.$i -side left -fill y -pady 5 + incr i + } + # text for replace + set f [frame $w.replace] + set data(w:replace) [text $f.replace -wrap char -bg white -font $::font_replace \ + -selectbackground lightblue -selectborderwidth 0 \ + -width 1 -height 2 -bd 1] + button $f.do -text "Replace" -underline 0 -bd 1 -width 9 -command "regexp::replace" + label $f.nb -textvariable regexp::data(v:nbreplace) -width 12 -anchor e + pack $data(w:replace) -side left -expand true -fill both -pady 5 -padx 5 + pack $f.do -side left -pady 5 + pack $f.nb -side left -pady 5 -padx 5 + # layout + pack [frame $w.0 -height 5] $data(w:regexp) -side top -anchor w -padx 5 -expand true -fill both + pack $fo $fb -side top -anchor w -padx 5 -expand true -fill both + pack $fb -side top -anchor w -padx 5 -expand true -fill both + set data(w:allreplace) $f + + # frame for sample + set w [frame $top.sample -bd 2 -relief groove] + set w [frame $w.inner] + pack $top.sample.inner -padx 5 -pady 5 -fill both -expand true + # text for sample highlighting + set data(w:sample) [text $w.sample -bg white -font $::font_sample -bd 1 -width 1 -height 1 \ + -selectbackground lightblue -selectborderwidth 0 \ + -yscrollcommand "$w.sy set" -xscrollcommand "$w.sx set"] + scrollbar $w.sy -command "$w.sample yview" -orient vertical -bd 1 + scrollbar $w.sx -command "$w.sample xview" -orient horizontal -bd 1 + # set tags for colors & special + set data(v:levels) {e0 e1 e2 e3 e4 e5 e6 e7 e8 e9} + foreach level $data(v:levels) \ + color $colors { + $data(w:regexp) tag configure $level -foreground $color + $data(w:history) tag configure $level -foreground $color + $data(w:sample) tag configure $level -foreground $color + } + $data(w:regexp) tag configure lookahead -background $color_lookahead + $data(w:regexp) tag configure noreport -background $color_noreport + $data(w:history) tag configure lookahead -background $color_lookahead + $data(w:history) tag configure noreport -background $color_noreport + # options + set f [frame $w.matches] + label $f.nb -textvariable regexp::data(v:nbmatches) -anchor w + set regexp::data(v:nbmatches) "0 matches" + # button for navigation + button $f.p -text "Previous" -bd 1 -pady 2 -width 8 -command "regexp::sample:move -1" + button $f.n -text "Next" -bd 1 -pady 2 -width 8 -command "regexp::sample:move +1" + set data(v:positions) [list ] + set data(v:position) 0 + # layout + pack $f.nb [frame $f.0 -width 15] $f.p $f.n -padx 5 -side left + + # layout + grid $w.sample $w.sy -sticky news + grid $w.sx x -sticky news + grid $w.matches - -sticky news + grid rowconfigure $w {0} -weight 1 + grid columnconfigure $w {0} -weight 1 + + # main layout + pack $top.regexp -side top -anchor w -padx 5 -pady 5 -fill x + pack $top.sample -side top -anchor w -padx 5 -pady 5 -expand true -fill both + wm geometry . $geometry + wm title . "Visual REGEXP $::version" + focus $data(w:regexp) + + # main menu + . configure -menu .menubar + set m [menu .menubar -tearoff 0 -bd 1 -activeborderwidth 1] + # file + $m add cascade -menu $m.file -label "File" -underline 0 + set mm [menu $m.file -tearoff 0 -bd 1 -activeborderwidth 1] + $mm add command -label "Load regexp ..." -command "regexp::regexp:load" + $mm add command -label "Load sample ..." -command "regexp::sample:load" -accelerator "Alt-O" + $mm add separator + $mm add command -label "Save sample (auto) ..." -command "regexp::sample:save auto" -accelerator "Alt-S" + $mm add command -label "Save sample Unix (lf) ..." -command "regexp::sample:save lf" + $mm add command -label "Save sample Windows (crlf) ..." -command "regexp::sample:save crlf" + $mm add command -label "Save sample Mac (cr) ..." -command "regexp::sample:save cr" + $mm add separator + $mm add command -label "Quit" -underline 0 -command "exit" -accelerator "Alt-Q" + # edit + $m add cascade -menu $m.edit -label "Edit" -underline 0 + set mm [menu $m.edit -tearoff 0 -bd 1 -activeborderwidth 1] + $mm add command -label "Copy regexp to clipboard" -command "regexp::dump" -accelerator "Alt-C" + $mm add separator + $mm add command -label "Undo" -command "regexp::unredo:regexp -1" -accelerator "Control-Z" + $mm add command -label "Redo" -command "regexp::unredo:regexp +1" -accelerator "Control-R" + # view + $m add cascade -menu $m.view -label "View" -underline 0 + set mm [menu $m.view -tearoff 0 -bd 1 -activeborderwidth 1] + set regexp::data(v:background) $::background + regexp::sample:background + $mm add checkbutton -label "Show background for matches" -command "regexp::sample:background" \ + -variable regexp::data(v:background) + $mm add checkbutton -label "Show regexp help" -command "regexp::regexp:help:toggle" \ + -variable regexp::data(v:help) + set regexp::data(v:help) $show_help + $mm add checkbutton -label "Wrap lines in sample" -variable regexp::data(v:wrap) \ + -command "$data(w:sample) configure -wrap \$regexp::data(v:wrap)" \ + -offvalue "none" -onvalue "char" + set regexp::data(v:history) $history + $mm add checkbutton -label "History of Regexp" -variable regexp::data(v:history) \ + -command "if {\$regexp::data(v:history)} {wm deiconify .history} else {wm iconify .history}" + # select mode + $m add cascade -menu $m.select -label "Select mode" -underline 5 + set mm [menu $m.select -tearoff 0 -bd 1 -activeborderwidth 1] + $mm add radiobutton -label "select / concat raw matches" \ + -variable regexp::data(v:mode) -value "raw" -command regexp::replace:toggle + $mm add radiobutton -label "select / insert new line between matches" \ + -variable regexp::data(v:mode) -value "nl" -command regexp::replace:toggle + $mm add radiobutton -label "replace widget" \ + -variable regexp::data(v:mode) -value "replace" -command regexp::replace:toggle + # insert well know regexp + $m add cascade -menu $m.insert -label "Insert regexp" -underline 11 + set mm [menu $m.insert -tearoff 0 -bd 1 -activeborderwidth 1] + $mm add command -label "Make regexp ..." -command "regexp::make-regexp" + $mm add separator + $mm add command -label "Load patterns ..." -command "regexp::pattern:load" + $mm add separator + foreach {n e} $regexp_db { + $mm add command -label "$n" -command "regexp::regexp:insert [list $e]" + } + set data(w:menu) $mm + # help + $m add cascade -menu $m.help -label "Help" -underline 0 + set mm [menu $m.help -tearoff 0 -bd 1 -activeborderwidth 1] + $mm add command -label "Help" -command "regexp::help" + + + # key binding + bind all "exit" + bind all "regexp::go" + bind $data(w:regexp) "regexp::go; break" + bind all "regexp::dump" + bind all "regexp::replace" + bind all "regexp::sample:load" + bind all "regexp::sample:save auto" + + bind $data(w:regexp) "regexp::unredo:regexp -1" + bind $data(w:regexp) "regexp::unredo:regexp +1" + + bind $data(w:replace) "regexp::undo:sample" + bind $data(w:sample) "regexp::undo:sample" + + bind all "$fo.all toggle" + bind all "$fo.nocase toggle" + bind all "$fo.line toggle" + bind all "$fo.lineanchor toggle" + bind all "$fo.linestop toggle" + bind all "$fo.inline toggle" + bind all "regexp::clear" + + bind $data(w:regexp) { # nothing } + bind $data(w:regexp) { # nothing } + bind $data(w:regexp) { # nothing } + bind $data(w:regexp) { # nothing } + bind $data(w:regexp) "regexp::undo:regexp:compute %W %K %A" + + bind $data(w:replace) "$data(w:replace) insert insert {\\t}; break;" + bind $data(w:sample) "$data(w:sample) insert insert {\t}; break;" + # special for regexp Ctrl+letter = \ + bind $data(w:regexp) "$data(w:regexp) insert insert {\\t}; break;" + foreach key {a b B e f n r t v u x 0 d D s S w W A Z m M y Y} { + bind $data(w:regexp) "$data(w:regexp) insert insert {\\$key}; break;" + } + foreach key {a b B e f n r t v u x 0} { + bind $data(w:replace) "$data(w:replace) insert insert {\\$key}; break;" + } + + bind Text {} + + # font selection popup + foreach w {regexp replace sample} { + set m [menu .fonts_$w -tearoff 0] + foreach f $::fonts { + if {$f == "----"} { + $m add separator + } else { + $m add command -label $f -command "$data(w:$w) configure -font [list $f]" + } + } + bind $data(w:$w) <3> "tk_popup $m %X %Y" + } + + # some init + set data(v:nocase) "-nocase" + set data(v:all) "-all" + set data(v:wrap) "char" + set regexp::data(v:mode) $::mode + replace:toggle ;# set bindings + regexp:help:toggle +} + +proc regexp::pattern:load {{file ""}} { +variable data + + # get filename + if {$file == ""} { + set types [list [list "All" *]] + set file [tk_getOpenFile -filetypes $types -parent .] + if {$file == ""} { + return + } + } + # do it + set in [open $file "r"] + $data(w:menu) delete [expr 4+[llength $::regexp_db]/2] end + while {![eof $in]} { + set name [gets $in] + while {$name == ""} { + set name [gets $in] + } + set pattern [gets $in] + while {$pattern == ""} { + set pattern [gets $in] + } + $data(w:menu) add command -label $name -command "regexp::regexp:insert [list $pattern]" + } + close $in +} + + +#---------------------------------------------------------------------------------------------- +# Main toplevel commands +#---------------------------------------------------------------------------------------------- + +proc regexp::go {} { +variable data + + set exp [$data(w:regexp) get 1.0 end-1char] + # check if regexp is OK + if {[catch { regexp -- $exp dummy } errMsg]} { + tk_messageBox -type ok -icon error -message "Malformed regexp: $errMsg" + return + } + regexp::regexp:colorize + regexp::sample:colorize + regexp::history:add +} + +proc regexp::clear {} { +variable data + + regexp::history:add + $data(w:regexp) delete 1.0 end + regexp::go +} + +proc regexp::dump {} { +variable data + + # update display + go + # built list of options + set dump "regexp" + foreach option {nocase all line lineanchor linestop inline} { + if {$data(v:$option) != ""} { + append dump " $data(v:$option)" + } + } + # build expression + set exp [$data(w:regexp) get 1.0 end-1char] + append dump " -- {$exp} string" + # add variables if needed + if {$data(v:inline) == ""} { + append dump " match" + for {set i 1} {$i < $data(v:nblevels)} {incr i} { + append dump " v$i" + } + } + # put dump into the clipboard (by creating a hidden entry ... anyone has a better solution?) + destroy .e + entry .e + .e insert 0 $dump + .e selection range 0 end + puts "$dump" +} + +proc regexp::select {level} { +variable data + + # update + go + if {[llength $data(v:result)] == 0} { + bell + return + } + # puts regexp + dump + # extract matching parts in sample + set i 0 + set newsample "" + foreach match $data(v:result) { + if {($i % $data(v:nblevels)) == $level} { + set text [$data(w:sample) get \ + [$data(w:sample) index "1.0+[lindex $match 0]chars"] \ + [$data(w:sample) index "1.0+[expr [lindex $match 1]+1]chars"]] + append newsample $text + if {$data(v:mode) == "nl"} { + append newsample "\n" + } + } + incr i + } + $data(w:sample) delete 1.0 end + $data(w:sample) insert 1.0 $newsample + # update with regexp + go +} + +proc regexp::help {} { +global tcl_platform + + toplevel .help + wm title .help "Help" + # logo + label .help.l -image logo + pack .help.l -side top -padx 10 -pady 10 + # help text + if {$tcl_platform(platform) == "windows"} { + text .help.t -bd 2 -relief groove -font {Courier 10} + } else { + text .help.t -bd 2 -relief groove + } + pack .help.t -side top -padx 20 + .help.t tag configure bold -font "[.help.t cget -font] bold" + .help.t insert 1.0 "Version:" bold " $::version + +" normal "Usage:" bold " tkregexp + +" normal "Key bindings:" bold " Alt-q exit + Alt-a toggle 'all' flag + Alt-n toggle 'nocase' flag + Alt-l toggle 'line' flag + Alt-k toggle 'lineanchor' flag + Alt-m toggle 'linestop' flag + Alt-i toggle 'inline' flag + Alt-g do the highlighting + Return (in regexp) do the highlighting + +" normal "To clipboard:" bold " Put the 'regexp' command with its arguments to the clipboard + +" normal "Tips:" bold " 1) To set the sample, either put a filename on the command line, + or just copy & paste it in the sample text window. + 2) You can change the default colors or windows size by editing the + first lines of the program file. + 3) when typing your regexp you can use Control-Z/Control-R + to undo/redo the last typing. + 4) When using the replace function, using Control-Z restore the value + of the sample before the replacement : you try, retry, reretry, ..." + # ok button + button .help.ok -text "Ok" -width 10 -default active -command "destroy .help" + pack .help.ok -side bottom -pady 10 +} + +proc regexp::regexp:help:toggle {} { +variable data + + if {$data(v:help) == 0} { + pack forget $data(w:help) + } else { + pack $data(w:help) -before $data(w:regexp) -fill x -padx 5 + } +} + +#---------------------------------------------------------------------------------------------- +# Undo/redo (quick and dirty UNDO/REDO support) +#---------------------------------------------------------------------------------------------- + +proc regexp::undo:sample {} { +variable data + + # display result + $data(w:sample) delete 1.0 end + $data(w:sample) insert 1.0 $data(v:undo:sample) + # colorize + go +} + +proc regexp::unredo:regexp {dir} { +variable data + + set index [expr ($data(v:undo:index)+$dir) % 100] + if {![info exists data(v:undo:r$index)]} { + return + } + set data(v:undo:index) $index + + set t $data(w:regexp) + $t delete 1.0 end + $t insert 1.0 [lindex $data(v:undo:r$index) 1] + $t mark set insert [lindex $data(v:undo:r$index) 0] +} + +proc regexp::undo:regexp:compute {w k a} { +variable data + + if {[string match -nocase "*control*" $k] + || [string match -nocase "*shift*" $k] + || [string match -nocase "*alt*" $k]} { + return + } + + set data(v:undo:r$data(v:undo:index)) [list [$w index insert] [$w get 1.0 end-1char]] + set data(v:undo:index) [expr ($data(v:undo:index)+1) % 100] +} + +#---------------------------------------------------------------------------------------------- +# Replace +#---------------------------------------------------------------------------------------------- + +proc regexp::replace {} { +variable data + + set exp [$data(w:regexp) get 1.0 end-1char] + set subst [$data(w:replace) get 1.0 end-1char] + if {$exp == ""} { + set regexp::data(v:nbreplace) "empty regexp" + return + } + + # get sample & store it for undo + set sample [$data(w:sample) get 1.0 end] + set data(v:undo:sample) $sample + set result [eval regsub $data(v:all) \ + $data(v:line) $data(v:lineanchor) $data(v:linestop) \ + $data(v:nocase) -- \ + [list $exp] [list $sample] [list [subst -nocommands -novariables $subst]] sample] + set regexp::data(v:nbreplace) "$result replaced" + # display result + $data(w:sample) delete 1.0 end + $data(w:sample) insert 1.0 $sample +} + +proc regexp::replace:toggle {} { +variable data + + if {$regexp::data(v:mode) == "replace"} { + bind $data(w:regexp) "focus $data(w:replace); break;" + bind $data(w:regexp) "focus $data(w:sample); break;" + catch { bind $data(w:regexp) "focus $data(w:sample); break;" } + + bind $data(w:replace) "focus $data(w:sample); break;" + bind $data(w:replace) "focus $data(w:regexp); break;" + catch { bind $data(w:replace) "focus $data(w:regexp); break;" } + + bind $data(w:sample) "focus $data(w:regexp); break;" + bind $data(w:sample) "focus $data(w:replace); break;" + catch { bind $data(w:sample) "focus $data(w:replace); break;" } + + pack $data(w:allreplace) -side top -fill both + + } else { + bind $data(w:regexp) "focus $data(w:sample); break;" + catch { bind $data(w:regexp) "focus $data(w:sample); break;" } + + bind $data(w:sample) "focus $data(w:regexp); break;" + catch { bind $data(w:sample) "focus $data(w:regexp); break;" } + + pack forget $data(w:allreplace) + } +} + +#---------------------------------------------------------------------------------------------- +# Manage REGEXP +#---------------------------------------------------------------------------------------------- + +proc regexp::regexp:set {text} { +variable data + + $data(w:regexp) delete 1.0 end + $data(w:regexp) insert 1.0 $text +} + +proc regexp::regexp:colorize {} { +variable data + + set exp [$data(w:regexp) get 1.0 end-1char] + set max [string length $exp] + set stack {} + # list format : min max min max ... + set indices [list "report" 0 [string length $exp]] + # search the groups in the regexp + set data(v:nblevels) 1 + for {set i 0} {$i < $max} {incr i} { + set c [string index $exp $i] + if {$c == "\\"} { + incr i + continue + } elseif {$c == "("} { + set c [string index $exp [expr $i+1]] + set what [string index $exp [expr $i+2]] + # test for escape with (?...) + if {$c == "?"} { + if {$what != ":"} { + lappend indices "lookahead" + } else { + lappend indices "noreport" + } + } else { + lappend indices "report" + incr data(v:nblevels) + } + lappend indices $i + set stack "[llength $indices] $stack" + lappend indices 0 + + } elseif {$c == ")"} { + set idx [lindex $stack 0] + if {$idx == ""} { + continue + } + set stack [lrange $stack 1 end] + set indices [lreplace $indices $idx $idx $i] + } + } + + # remove old colors + foreach level $data(v:levels) { + $data(w:regexp) tag remove $level 1.0 end + } + $data(w:regexp) tag remove "lookahead" 1.0 end + $data(w:regexp) tag remove "noreport" 1.0 end + # colorize the regexp + set i 0 + foreach {type min max} $indices { + if {$type != "report"} { + continue + } + $data(w:regexp) tag add [lindex $data(v:levels) $i] \ + [$data(w:regexp) index "1.0+${min}chars"] \ + [$data(w:regexp) index "1.0+[expr $max+1]chars"] + incr i + } + # apply special item + foreach {type min max} $indices { + if {$type == "report"} { + continue + } + $data(w:regexp) tag add $type \ + [$data(w:regexp) index "1.0+${min}chars"] \ + [$data(w:regexp) index "1.0+[expr $max+1]chars"] + } +} + +#---------------------------------------------------------------------------------------------- + +proc regexp::regexp:load {} { +variable data + + # get filename + set types [list [list "All" *]] + set file [tk_getOpenFile -filetypes $types -parent .] + if {$file == ""} { + return + } + # do it + set in [open $file "r"] + regexp:set [read $in [file size $file]] + close $in +} + +#---------------------------------------------------------------------------------------------- + +proc regexp::regexp:insert {what} { +variable data + + set w $data(w:regexp) + # prepare undo/redo + set data(v:undo:r$data(v:undo:index)) [list [$w index insert] [$w get 1.0 end-1char]] + set data(v:undo:index) [expr ($data(v:undo:index)+1) % 100] + # do it + $w insert insert $what + # prepare undo/redo + set data(v:undo:r$data(v:undo:index)) [list [$w index insert] [$w get 1.0 end-1char]] +} + +#---------------------------------------------------------------------------------------------- +# History window to memorize already typed regexp + +proc regexp::history:init {} { +variable data +global font + + set w [toplevel .history] + wm title $w "Visual REGEXP $::version -- REGEXP History" + wm geometry $w 640x480 + wm protocol $w WM_DELETE_WINDOW "set regexp::data(v:history) 0; wm withdraw $w" + + # text zone + set tf [frame $w.t] + pack $tf -side top -expand true -fill both + set t [text $tf.t -xscrollcommand "$tf.x set" -yscrollcommand "$tf.y set" \ + -bg white -font $::font_regexp -width 5 -height 1 \ + -selectbackground lightblue -selectborderwidth 0] + set data(w:history) $t + $t tag configure spacing -font {Helvetica 6} + set tx [scrollbar $tf.x -bd 1 -orient horizontal -command "$t xview"] + set ty [scrollbar $tf.y -bd 1 -orient vertical -command "$t yview"] + bindtags $t "$t all" + grid $t $ty -sticky news + grid $tx x -sticky news + grid columnconfigure $tf {0} -weight 1 + grid columnconfigure $tf {1} -weight 0 + grid rowconfigure $tf {0} -weight 1 + grid rowconfigure $tf {1} -weight 0 + + # buttons + set bf [frame $w.f] + pack $bf -side bottom -padx 5 -pady 5 + + set b1 [button $bf.1 -bd 1 -text "Hide" -command "wm withdraw $w; set ::regexp::data(v:history) 0"] + set b2 [button $bf.2 -bd 1 -text "Save ..." -command "regexp::history:save"] + pack $b2 $b1 -side left -anchor c + + wm withdraw $w +} + +set last "" +set counter 0 + +proc regexp::history:add {} { +variable data + + if {$::inReplay} { + # avoid to put the same expression again when replaying it + set ::inReplay 0 + return + } + + set exp [$data(w:regexp) get 1.0 end-1char] + if {$exp != "" && $exp != $::last} { + # memorize position + set start [$data(w:history) index insert] + # add text + $data(w:history) insert end "$exp\n" + set end [$data(w:history) index insert] + $data(w:history) insert end "\n" {spacing} + set ::last $exp + $data(w:history) yview moveto 1.0 + # do the binding + set tag "t$::counter" + incr ::counter + $data(w:history) tag bind $tag "$data(w:history) tag configure $tag -background lightblue" + $data(w:history) tag bind $tag "$data(w:history) tag configure $tag -background {}" + $data(w:history) tag bind $tag <1> "regexp::history:replay [list $exp]" + $data(w:history) tag add $tag $start $end + + # colorize the expression in history + scan $start "%d.%d" sl sc + incr sl -1 + foreach tag {e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 lookahead noreport} { + foreach {start end} [$data(w:regexp) tag ranges $tag] { + set start [$data(w:history) index "$start + $sc chars + $sl lines"] + set end [$data(w:history) index "$end + $sc chars + $sl lines"] + $data(w:history) tag add $tag $start $end + } + } + } +} + +set inReplay 0 + +proc regexp::history:replay {text} { +variable data + + set ::inReplay 1 + regexp:set $text + go +} + +proc regexp::history:save {} { +variable data + + set file [tk_getSaveFile -defaultextension .txt] + if {$file != ""} { + set out [open $file "w"] + puts -nonewline $out [$data(w:history) get 1.0 end] + close $out + } +} + + +#---------------------------------------------------------------------------------------------- +# Manage SAMPLE +#---------------------------------------------------------------------------------------------- + +proc regexp::sample:set {text} { +variable data + + $data(w:sample) delete 1.0 end + $data(w:sample) insert 1.0 $text + set data(v:undo:sample) $text +} + +proc regexp::sample:colorize {} { +variable data + + # remove old tags + foreach level $data(v:levels) { + $data(w:sample) tag remove $level 1.0 end + } + set data(v:position) 0 + set data(v:positions) [list ] + + # set new tags + set exp [$data(w:regexp) get 1.0 end-1char] + if {$exp == ""} { + set data(v:result) {} + return + } + set result [eval regexp -inline -indices $data(v:all) \ + $data(v:line) $data(v:lineanchor) $data(v:linestop) \ + $data(v:nocase) -- \ + [list $exp] [list [$data(w:sample) get 1.0 end]]] + set data(v:result) $result + set i 0 + foreach match $result { + set start [$data(w:sample) index "1.0+[lindex $match 0]chars"] + $data(w:sample) tag add e[expr $i % $data(v:nblevels)] \ + $start [$data(w:sample) index "1.0+[expr [lindex $match 1]+1]chars"] + lappend data(v:positions) $start + if {$i == 0} { + $data(w:sample) see $start + } + incr i + } + # set nb of matches + if {$data(v:nblevels)} { + set nb 0 + foreach item $result { + if {[lindex $item 0] <= [lindex $item 1]} { + incr nb + } + } + set regexp::data(v:nbmatches) "[expr $nb/$data(v:nblevels)] matches" + } else { + set regexp::data(v:nbmatches) "? matches" + } +} + +proc regexp::sample:background {} { +variable data + + foreach level $data(v:levels) color $::colors bgcolor $::bgcolors { + if {$data(v:background)} { + $data(w:sample) tag configure $level -foreground $color -background $bgcolor + } else { + $data(w:sample) tag configure $level -foreground $color -background {} + } + } +} + +proc regexp::sample:move {amount} { +variable data + + if {$amount == -1} { + if {$data(v:position) > 0} { + incr data(v:position) -1 + } + } else { + if {$data(v:position) < [llength $data(v:positions)]-1} { + incr data(v:position) +1 + } + } + set where [lindex $data(v:positions) $data(v:position)] + if {$where != ""} { + $data(w:sample) see $where + $data(w:sample) mark set insert $where + focus $data(w:sample) + } +} + +#---------------------------------------------------------------------------------------------- + +proc regexp::sample:load {} { +variable data + + # get filename + set types [list [list "All" *]] + set file [tk_getOpenFile -initialdir $data(v:dir) -filetypes $types -parent .] + if {$file == ""} { + return + } + # memorize location + set data(v:dir) [file dirname $file] + set data(v:file) [file tail $file] + # do it + set in [open $file "r"] + sample:set [read $in [file size $file]] + close $in +} + +proc regexp::sample:save {mode} { +variable data + + # get filename + set types [list [list "All" *]] + set file [tk_getSaveFile -initialdir $data(v:dir) -initialfile $data(v:file) \ + -filetypes $types -parent .] + if {$file == ""} { + return + } + # memorize location + set data(v:dir) [file dirname $file] + set data(v:file) [file tail $file] + # do it + set out [open $file "w"] + fconfigure $out -translation $mode + puts $out [$data(w:sample) get 1.0 end] + close $out +} + + +#---------------------------------------------------------------------------------------------- +# Main toplevel commands +#---------------------------------------------------------------------------------------------- + +proc regexp::make-regexp {} { +variable data + + # new dialog + catch { destroy .mkregexp } + set w [toplevel .mkregexp] + wm title $w "Make regexp" + wm geometry $w 640x480 + # widgets + set f [frame $w.top] + # area to input words + label $f.l1 -text "Words list:" + set list [text $f.list -wrap char -bg white -font $::font_regexp \ + -selectbackground lightblue -selectborderwidth 0 \ + -width 1 -height 10 -bd 1 -yscrollcommand "$f.sy1 set"] + scrollbar $f.sy1 -command "$list yview" -orient vertical -bd 1 + # button to compute the regexp + set doit [button $f.doit -text "Compute" -width 15 -bd 1 -command "regexp::make-regexp:compute"] + # display result + label $f.l2 -text "Regexp:" + set output [text $f.output -wrap char -bg white -font $::font_regexp \ + -selectbackground lightblue -selectborderwidth 0 \ + -width 1 -height 4 -bd 1 -yscrollcommand "$f.sy2 set"] + bindtags $output "$output all" + scrollbar $f.sy2 -command "$output yview" -orient vertical -bd 1 + # layout + grid $f.l1 $list $f.sy1 -sticky news + grid $doit - - -sticky ns -pady 2 + grid $f.l2 $output $f.sy2 -sticky news + grid columnconfigure $f {1} -weight 1 + grid rowconfigure $f {0 2} -weight 1 + # init + set data(w:make:list) $list + set data(w:make:output) $output + # button OK / CANCEL + set ff [frame $w.bottom] + set ok [button $ff.ok -text "Insert into regexp" -width 20 -bd 1 -command "regexp::make-regexp:ok $w"] + set cancel [button $ff.cancel -text "Cancel" -width 20 -bd 1 -command "destroy $w"] + pack $ok $cancel -side left -fill both -padx 10 -pady 10 + # layout + pack $f -side top -expand true -fill both + pack $ff -side bottom -anchor c +} + +proc regexp::make-regexp:compute {} { +variable data + + set words [$data(w:make:list) get 1.0 end-1c] + $data(w:make:output) delete 1.0 end + $data(w:make:output) insert 1.0 [make-regexp::make-regexp $words] +} + +proc regexp::make-regexp:ok {w} { +variable data + + set words [$data(w:make:list) get 1.0 end-1c] + + $data(w:regexp) insert insert "([make-regexp::make-regexp $words])" + destroy $w +} + + +#============================================================================================== +# Main entry point +#============================================================================================== + +# try to get customization from 'visual_regexp.ini' +puts "[file exists visual_regexp.ini]" +set filename [file dirname [info nameofexecutable]]/visual_regexp.ini +if {[file exists $filename]} { + source $filename +} elseif {[file exists visual_regexp.ini]} { + source visual_regexp.ini +} + +# try to auto user patterns +set filename [file dirname [info nameofexecutable]]/regexp.txt +if {[file exists $filename]} { + regexp::pattern:load $filename +} elseif {[file exists regexp.txt]} { + regexp::pattern:load regexp.txt +} + +# buld the GUI +regexp::history:init +regexp::gui +regexp::go + +if {$argc > 1} { + puts "Usage: $argv0 " +} elseif {$argc == 1} { + set filename [lindex $argv 0] + set file [open $filename] + set data [read $file [file size $filename]] + close $file + + # memorize location + set regexp::data(v:dir) [file dirname $filename] + set regexp::data(v:file) [file tail $filename] + + regexp::sample:set $data + unset data +} + + +#---------------------------------------------------------------------------------------------- + +image create photo logo -data {R0lGODlhLAFxAMYAAAICAhcXFzw8WFtbb4+Njq2ssioqNMfGxkJCSgYCtcYtJrjOuEpGVs3Y0FJOYr1JNb53Yt/g4BsXq+i9yspGHOjQ08adlebm5rm57unH0NwjGPY4EsJaIgYCwqOjp2hmet6+wurq6uTYvvcuE77Ovh4altZLE9C0uioqjrljT76OevtCDt7Hx7q5u8LC7tzZ2PsbFnJyhvsqEspWGvxaCgYC0+jh3cLSwh4akujY2Ll8Z5qZm8rK6tDQ6PxODNHQ0f///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAEKAEAALAAAAAAsAXAAAAf+gBEvBy2FBz8XiYqLixGEhT8vjJOUjD+PLZGVm5yCl4WghpEREZymlBE/hqWnio8HrbGngoUvrLKEP7eym4+SnS0HpaqEB8bHFyHKF57GycrQ0RcNhAWQsSEvl6O8lJ+Qv92TIY6hoIcvts/im9mfwrLlBYjs4uTF4uXq9YwRwfSbUmUKwYxUMVu7Uh2DF60hwXKgAJoiV5DfIlWgGoSzmA2UtQMaSVk8RW1VvIgjeQ06sDGWvxYiU3bUxYmcqgbP7mVKVCrVJWOacjpcBjEYw6HQeApCiFSaIJFJFYqK0LRqw0QYjeoqtayr1a/RbAyCZAPsQ1AvzKqtOo3mWlr+wtZWFUTiV9Wxkogay/twoUaCrSKQOAev1U+QLVEdtmuzUAGQuyxSO3QLsOWUi2w+kkgSVORZ2j6DxsmrceFJpERTUvb01E8bi14Ewwn4ZwPYOSf6PGcrGgsLDzQIF67gQYqPuppeSBfqRdm+r5JbtTBCgwIIz5M+TJ35qlyrWDcLVR5C1WOqase24AuWGY9gadUuxzdUYNyvzIxxRWpwYDKeGq3T2n8ETiRWA6HQdIEKCsDg4IMQOqiACjyolog2oTRAVTJFsWThMzrIIKIMDwA2zn8mEpgiZvkZQlorIbzy4SQIXiNLR4XMmNk0uaxmwyM6MiMbTJVAQ4xoSSn+QpBly0yk2TkRVKCCBhFW+eB1NZEy2F5LMjOYIc5lCQEMIo6gQAWrJdIli6eQ4Es8P3zUzVinxUJnkIsYs14lL8FyCjmy1clICDa46WeBO67JJH4cYnKABVTCoIEKLpzQoJVXcqZkQelEABtgHcZU5AUpiAjDCDLo0J2am7LZiYx/8vQICTdyuiGMioRUWoy1FCkIbhPxBOxqsgWlpqKINjkeUooI8kgKVGqQgiSpQYqphDmcyOEFZR0rlqNptcPtmCOSOGiKl7k6iQ0lBaOjiWh1ky42x644Cz7jMBnrvCfqZ293yC5LHoeqTAmDAh5kp0gPD1wraWSXmbikTob+HMLNaqWW+0C4TXb5r6sKYeJusDzFWyur7HxcZDaE0JqmvIiiNki4SiKLrsft/RdBDztcasFGrEVwgsMwWNBqoim+8KUhYBaZ8YgKZDtqqyqz026CVTNCjTWJrZz1yiknUqOmNX/NSwOX7LIizh3HHGsPDWrwQA8tbacD0Qqgh/KOzWZlTUT7pagCmWWeqTeKVE/8HbNDFtNCXQJLo+aQJKAHXuKM7m0Wq4Gy13a9zCbb1A8Sfa6iosrimkgKDj7Qggs9BM5qBJdem8LHqZcyiJu8U2YvoSeMQLgMZ5q9N4uCoE36PrGSEknXaRp/og4cqGC06qDiLj3MNXvN78n+cRfAww8vdn8B3ERf/zvVSz21j+SJ9DDiqRT8kLrEx0a+uLYossWqdpkD2OUUQQEa0MAEHDjAACcGuq40cCjrKJtD8vU97dSrNDyB1ANOMCgVNctSDlNAOCp4lVglQgFlgsEDhmWiH7AATUeTCQPtsTbV1eMhMzCgAU1gAam9LHWr2d6NbjYqr9zwApCyQA8QF0NFWCB9zzlXsnLzu441bEQPyB9BKnACCKQAAgcYFpuEWDaOuC1WIsihDmmQAguQ8YgRpJfxlLW/EPAgA/DTnIAadq1JHe9/q+KXvUI0Iggw4gQpQOEIFqkBDqqrQB4L277soSQb2GCNOpwBCGr+0sQOYkN6QPQgyha1FvO5DX+zqx2mNikx7SUpUawCAeE0YIEoTmmRuFzkxh7Jj1BikIzQyAEmMykCXnryjE1c05/YVkoJnlFREcjB4Bz2gM8oE5BTnMQPqCQDDdDDkhTIJS5lwAE89ZKSyOwgMLv3gmEacAbFfFk658k/eY7yRDiTICmZpbKAIasCqqySBkAARMVRMgcaQJUCCAWYB8hAnItU1RhzwzcnrZOe+FREO91pArWB8o3L5FYnsflKdOrLmYh7iAUCGqFqbqpq+lqfDVBIImmcQANlwuUDcrC40L20fwMbj/7yuE//zc6dBxSKUv4XDYjZIAc5+NQycCP+AkuqyZLLqCq3cqBVS1YVN7bQ0DqSZCJWkONd4krXNZNhAx5Eykq0BBoTK+rJJtFUoosIzkO7mQIxjiSSdK0JSFHRD60toHwvUCMmOXCDG7woAgsQVWYaEFnWVGACIJjABGB4gahySwQi8KFVO/tVrn7VBqHV6jR2ZiG99QZQK/KrWtEVx7l6inXXmtBc+XZSqv0HhY30YAVAYIEUqMCRPYXgjj411OVU4LnZAmBYKsBTaETgBgvIruUa4NhlUJYqEWiAeEnA3QYQ6gaKXWMKsnuD62I3u+IN3EPIy63LRvWyE0gEar1azC5VlVCpJch+vYpV1q42vAC60IYQDCD+Aeu3W0gbKW1TB4K3CrSaEavr1JiRDAWYaZOVYIGygGXJEpO4xBsGjA04y4kVswAELMiADbhCCRtkIANKomx2F5BjxyoCuzihbGMdS16CkCC9OkyBkKeBXceKV7wSuy5ObDwB2FwWx58NAWj/+4z/oha0/C3xV6fRA2XE7nylCFB4e8Kdh4i0lRb07U+RmQ3cXut64ipIakhhmeuS4AYzJZ5ZfQuYHGQATRG4MQgy8MLJZQAELG5HoiNdiafeeAIs4KkinoubUlQgA7cAstogSxruHpYrOm4vaxaAZANCAL7kaOxhQ0AC+IqVII3l1lO5pVmeghnAUUzGab8KYBH+EArCrCVI7HY2jRdoSCQa0ohYNdQxxZH1aDGZ8HbAywOWQkgBLbj1fxobk/eyFydrhuwCbrDNEWSxEuXLwQupMtwJ3DgDv6DyoheRgzAdbbiLGC2KWZUBe2+E0czNxo2fgV0aN2vWOoYvMxzbcP0e2Z0WWDdVqH3dh8h61hdobJdsYG8xG1vLXP6PiYn9ZYZ+6tnKjh+Cn71g8z6DFFJ9IG3/0wMXuMDhKbruAsIVARcQgGgPaG8j2Psf8WL3AIdl8rp37AHrGFJApr6ByguOm3ovsUnDVXQFcBPjRY8WMFzXL6NzcNlF+/B8+56cvRthAxawgBW1pi1ktX4B9vb+hDapecgCOOBOFWhcw1lPRK51XfKygNnx/dWvlvmrDAJT8dbpFq/YYrckzeeKrfpdlp47+AIMVGgc6tY6QXQcnD4afhGUPYBjbyH07qrpvSRwqALwKt4dr1u/l11iIi7twxDIuwIvuLLUPr1oTGfAs+ebgEhyoFlI1xvU+tUsjqOZfEw/l7MF70mu0bX3REj8RLVvNQ1aAPKXCn3d5g0BZWnDa2h8uSwtz8x/Wf54aXB+O/LHFWfGRNuha6DnED3AAzxwZk3VAxjgAnZBIKl3ewtAAh7gbQ4iNwUwbqnGXXrzXvE3ce+FQhRgNO+3AAfwZ81ScGhCDgWXaYqwYpv+1W+YBUOk0AMFh1mHlgjDJTU5kFmglmiZpSaJNndXhllIiGUXwAJVxgzZ9S+/p24vMkMgqH7zx1TTUGt/disNQF+65mUod2yg5S0DVgHGhn//lSLUthwbwnkcBlQP0RtY9UcXwAMYcIdlVjNFh4c74ndL8l4v0AMWFiFyIwk6BnU7xhW1Z3PcpXURACkkcgIfB388AQIgcAIqgEf/8WjYlwzUBwIb8oLhAlUvwAP2VnDJ8AJNGAEscAIYAEOMll+p+Gg5ECUZcEf2BgIYcAIHUAERoFkbN37p8ns1EgwsADkTU4GeYgLutHitQon5o13/8WkMNXlhZm0n93gDhj/+4hZBXjFBUGE6i+ACd/hzgGWHD5gXigd1Sic22fUCOTAmfbSBE8d+YrUItlaAj0gBIvIABcB01lUB0CIcI8BBD/FoTXgh8PgpOdADIKACKfAAD6AAFFAcEqkCvkh91KUDFUkBbfSLcbccJUeEj6YCFEABK0ABxmEBLJAMV9gPP0AAOpACHEABJmACPnCTM8ABOnAClcNeiTVMMyCN6SIaS8YtIfB89vdrYJYTWPUcT3lyNOJR+QOHFUFKlICOsFNGe4gBeah4v7cI79UTGCghiNaFkbUpqfcZeiUDIOF7PgYcudRInwKSoIY6QpNIG7ABI7CXe7kCGwCYKQkBiVb+ACkQmIK5ASlwAhPQA11nbxtCEBOgAiuwAj5QmT7gAxhZCtpFFD9gATOAk5npAzRAmjpkmqV5HO/VajPgjKvSHYtXefj3HI+3ZWcYFtCwZcGmJNkWSNbWSmNVCeT4gHRTnDxxAXfolQACX7cSckR5N33UAuSgY6MGZKRhXTglIuTzXmMZHHMJYsxQcDLWHTZwAhywl32Jnn65niuQAheQASmAkpU5nxugApuFdpAWeomWAplpmf2pAt0ijdxyABBAAaNZmqV5oKaJmhzwZzdAeJhkAuumTIIEWYNWeRi6Xyg3dmwVFmhoVRQqWadTRVgZOcl5oqaXFMPpAhySamb+FQKJqF98hCki9H6RoWPUZhmsIwMq9BzhRQK1RgDitAHFAxgT4AJY1iQrxZfF0UYn8KRlpwIPEJiLSXIQoAB/OZ+X+QAilghMWIuWwQMoeZmYqZk8kV08AQH+SZoHepqZaUCoyUbF1GockJbmg0q2x0xiNptYJZv256EFhTvH40CiMxQnygOwM4CJkJw/N3Hn13QCGiXQiSkpYKN6yHQ5UQE4VR2shCLhxQEQpQDAcmUsFgEQYCYbVF27ZkS/8QvMJ5/0WZnuyQyatZuUeZmjmZnXA1nkxZFvqqA0sAI3CQHWg4kQMAOoaQGlAKFrxFh65DZRpCjZ4XLSMDEldmz+1VqVO7dWFAU/SDGcGOA2EZCcPOBx57cMY+mpLMWjkpJxAporErckEeBQIgIBa6MMKQBRGjABS4JfLUgQIDACEMACyfcCL2asEZmwEHACb1cKFoCY81mZG9BDzNecIYCsuFqmbjQN2ZUCopmrmWkCbdRfKcKsNIAmNkCnx4RK12RtUGl/0bos+FdbdFiV3RGOARc5K7ofvMmoLSp75TOB/zNNmOKP8DV7ykANUacILMBNA1VDNpCv4qQABnkBYfd2wcOTOqACM5lIFYmlWKoBKtlDm/ICsBqxK/AAi2Z2vCmfuDqaboRrLcCMwJqTi1kJIkC3BkQbJksDMzCrUkT+R2UUR9VYQqNEKLslOq9JEUkBG5UxVR+zs6iXnMJno5GpbpUlMTPqIOwqKeC2Y3wnf1BHGo9Ir1hyRirwULkkA0ZDEPdGXeFithqAnovkl4kJmH/5AKrSJCcAsRG7ARhwaOxhAyrQn/3pn8h1AWoKsplJmFP0AuYJpwaECCk7TLfjS20TSnBGrSU1VzWkOQOyDK+lYpSgWqhAN0iilRJ4bg8XlgxEO4P4bZUjKkq7ITdFJo3UnC9FHRClAhzyaEDIYiGAiRE5kQ9gAhRJkRW5nhQgNQ/BkWgrq46kJBbAAYBpvLiKZxdQQL9qAvUTWxEAAr6KoAh6AsXUt3+rOQb+BUkxA1pMknIxWFHfW5UD0ixjJQI9oY1+FViTMJzCBxg4umAA+VIvMKk8yq48qgD0MGSJ6AgJxaO1lHNlEzw5tUgpoInR1G+1GETVliIsEJgY9j8PK7Fk7FLP8QIP4AMluAFv27ys8rE5uUm38gMnoAMQkMbSi0kqMKeLpQKvpA4dIwIwWGPPtQ5jiDoxo2K/wmadcgG2eXM4nBsvYGxa5SlaZk6N4IAYQH83F6NOyF4Vtyl2xrmkLDemdm4tAAGRQkt02BUHAFGLpAIOt4S7q63PmwEF8ABpqz5ImQhqiraX6Z6AAQFqvEQpYJmYmZIAAcc+wAFf5LE3yaYJKs3+qJkCwpACmDQD/msiL1YBkvNCEMYILwBpn/JribBlimCbXGab1DLJqOUpNQxgekMQkTxjkVyzNps05Fgh80Kdgud77bckFdZHMAAB5BVtJ9CWxFM34wBQqotLG1CCPIB8j5ZIQCev6QCPFdCKd4ylG6ADP5wivQvMKXkCBMECJzmrOjCaa3ooBpqrOCmaCLqgM32aNMAB4QYBfcwILxZPBPIDxqZrqKVfL8YC2YgbX9aUzCACQD2Gy4HD+xUBLmzJUq0iUl1dlRdNn1XP0zpBp6MIiKqcX117QOx092jV1oLEZAIh0tLRD9JNP9PFiZxIsMxIFJBQRDpjiZTAfA3+th6NmBvAAdWVswShAxFcmSbgRScpYjMGAsjM0hQQRiHAAcwLsgk60zMAARaAk5n0OCcglFubAjpQd3fHCHVXCoJsiTAWJZZo1I4cT1+21MW0ZeQwhlKdw0Ki1IIQQSIQgVl2C1VFsspxPC/gc2qDGiEYPaxiA8BRJUccIaYiNy05W54kTUOqnrlk0qTCl9z9l7YbmH4pyy/KwhAAsYiJqybAmEz4QirAxiA7A250AsxMzdRsAqOdCmpEmjOQCQ3Qt5gUwr74P8PlHHZnSQV+ASCACEkbT6C1YOfs07392jzh00vtKffMIUP9hjh8yU4dH0GlLKIijvdKRB6UA3z+9Nyd+9zSsrHemEc1AwIPIE4ysAEzLratmw0UwN2AWbvoSZELq1TPVKDJDJgUwAE6CF3h5QIm8NgroALmFQG3qqC/mpPabBMIwtkHpAIH0AMNcALqt5MDPigvVgrdzKHkkJ+1ncMUPg0uXNuWNMmy7ciOq1UN3iygNcn1bCK48ZtejT/dS4A8LEoScwCq9Nyca3WaJkqLWyAsEJEJlUsK0EYilQiW0t2B2ZcnObC8JUX61d7J/AAqkFkgIAm40Vgei6sP4M3K0OjRLOUmMAM64AFpgTZog6wHtN+zZwP+XT29CAJYzbQsUBYv9gOrrWUgEMlObQMK4sivTeq2Xc/+OCzVOOzUDQ6Vk0wKsK1yu3JB3ktXK0y4saVfdcy1x6UCxxV5FRTozQINFmA9TSJvz9dlmKgDoGiAO1dpBxgC7a6sjjuSHGJuLaACLbAapNPu1tNp7EYKDUA3ekYOXL4t+n5cCiTQnaozMOZgZljgP7ghTi3tW13boNUAyF7JG+4pfBF6F3SvcsZJh5tR2aRhLLxhnVRFhVVRzDV89qbqDjbpBqXRGyEWinZoUpVh1Id9UYG558oTpMNCDn9mPdADN+Bs5cYDf6TnMBZHAJ4Kwc6K81bUtsDU/6HOwB3toLLpWEhHhIpK2COOguW9wMlb4ssDr2VP/EMomqf2ryT+nswFVTcWYwFODsyngztoY+IZ9KbELQ6piWszXnbaLFz+SvK38LdygzdQZk9fPgFHVQluhgW7YqDIdqrt64kgb8Eu4c3Sm3zeW1UvVIJ+RC2bTB3Um0SoDdXgATtgAAGQ+7q/+7yf+wKgUd/gAR4wAL1f/MUvAK54Ao6xAwKAAMb//C5QADuwAwTw/Naf+y7QAsK/A8Z/XYRg+zvgAMVvAAdQAODv/NfP+wjgyDBmd5aIwwD3VHYHzssAVcK25lx8TNgkQPtERc30rIBwEXJBGDJoKDhIeMGDwROhGBnxc9BS4LFDgJDQkeD5CRqKYhAz+WO5k2nQwdrq2lHjGgv+wFCQSkAAgPIKy1rzCwwM4GKRueMQnKwcDFBpi2vw6wrws9DigUkQoCzBc529vSxegyIQUIH+kmMTEiH4jgj/fhEhUhi/WJg/v58fqejvkMBEhgoaPIiP3yKAAPXt64Eh4guGhCY5y4YilMaNCQw0oIQKmsZOrDi54hSgwLNcJHn1ipXMXKVbAsbBXBagEqZMAWoGQ+HsFoFoyQD0+MbTpk0ADOMdTLRwkQh3URc2rNqvn8CtBeUh/GrQH9amUK9GiIiBqqIXLlpguJTNAce5oAxQUomLAA5OfEl68tsSwUoBEly2ShDr8C9ab7MBkCatFTBYwTogIHHtEq7HyQz+XMokgDOzDwcW2MokWqkyA/MQXT0kz2HZfa+z6vun0DVXsLyv8lMUgeqFBjx68GggfHhEF1QjuHARUWU2nhpRILiOfZPGZtcyaQLVCYD48eTHh0QA4HDJEuzbuy8hQQCCFiemr0pcw0D5/eInWeuuCWWUAaDZUJQJ80IPF4GmzH4MLCOBWLc9JZtWirBjm4QZ3kOQU7r1hhAhPUQwYlURFNfDBS80EhGKikCEAXOEsLVcdN7lopEBAuzIo3zbWZPNUH158kEGRrrjjg02UDJAARZsJgAvAARAZZVWVnnCCS08iUuUkQEQwyA2EGIDCxmwEIEDYb5AgmkroZAMAuD+cBNABA3odIsEygTQ2A4M6LhMVb4FlCFw9GgFVWtcWVXhbLBtuA+NaBVXyIloPfccWjFCcgGMLizCIg8rHoCBB3kZEAoOALxwwGeb7QVKM6Z5B8CQAuSQwQQZYEgICFmiospfrQhQAQi6VhDCC0ZmUEGuIFQCIAF6+tJBAA6JyasgFoWUS2U1IEAAAz4xE8GoACKwTAynqITaMo8iGpyEg7Dww4UiiBCCCOzARlFChTol26CQXhBjpmg1sIimGPQwiHOX0gPjIyIWF8JHb90I6ycGIECiq5oIEAoAQHoH8l81ANAsCxNU8IINJP4aEgMuBZBBDsVWcIENzRppJg/+B7hw2lAw9eIAbbclUi5mAI4rjNA/AUDPD5i5mtovApzYwjfdKgNbBTmoRY8IIODsmw0g2DNIA/ZccK+F1/LbkGvXNjpwPi9UxGJaiEAXYwMAnbUcxMu50w6J0ElH8nZRe7xjKAFkHaQEfKEUXK4TqKxylkDvoAJLrwgwUUWJ0tOOgpBv9lIHKNSNyEd4MpjMgcBYG3VQ0DQYwQ2WYLN1MBE2PHYEY74TAc4z1uPODyAs7869Y+Zbb2zwCBybvxTV3Q+nIeSdIj0Pz+Pwwu2EisiKfKtUQF4BaGTtip/xVLLGkGeyCWCsdaryBJcv3xbVLcECNUQVxGUgCVp6boL+AN2IpSE5IMFFbqcUAxyCVQ8MVzIksCqfUU0ZJSBTBEBwt0go6W4qYsHyKlCm5bGAEG0bRNv+RT3aDORDIAIL4ba3HBICLiJqaQffeEAPvn2qUwfrweFopREHGO5iqAvFB3ZHnU90Aio5yMGIEnQAnZiKABlxhTkicQ98sCprg0kMALFXkRfozlXhGId8KkIcPBEAGZ1BQAGzwTSrvaNYa3uH2Vigs7O9oAKAFNsKWSicF2pokYvqEL8cWUMKMQItwrkUpwQXEYaFD4hEjAipSnUj7XwCBWhxyzMGkBFQCMAammFAeqS4ut+kLYuuQsArThYD28SjXNDKBrogU4P+AAzEaAx5gdR2hws4iUMCtDvRAmg5p6LYqYJ6KoogAimcQbxgbBcwYRWFdwE+zmgqi/hBH3PTlYEpMJKRnAff0pKwSSFnRZPCW4tEhBbp8I4AMciYJwTgFkt8xgG1ChkZ4deJv5SjRz1CQGgKVKuSsEIAvEOPBC6KUYyWAADI1MbQYsHQkArABl8j3hg3uAz9AMd1ISGoMhhw0mwQJU420NcBQECbYrEjAiwwYfBMuLYWshBRRJ3N9NIJN3aGCFSDq4jCFOaCHkykdDxcyzvdgkeNyCekJdgIQKn2FyneJHY7WskqXFECdu2gJ5C5ZVq7Q1DJyE4cAsgACDLAqaT+HXQoMwWGABhwiHLxYGrgyKMEfnBMAypDAM4zWw7A2M0V2iB0H1zhCYVnTqmc8zX+0uUMaahUg1zync25VN4yqb3xMQwqL4hjAQC0vrmcpDpTewaqworbsJIEAIIh2f8EwK5cTEsWrUBBzO7zkrGm7mTMekG8agdFB/R1MeBT0LocU02/vkAEe3WAMpmxDpJykyE9zRmaagqCHFxAhfZ4YT0a5ZthEqo1jEJjVl4UoxJ5L0aPKJdzBaWQRUwCcqYiKF3oEpqDZqIECR3SkBLaAY4WqDCSIdAW09MLlxDoGQAowUeplVxhFKIBCyABCRLL4V8y4x4NIA6QZLqaU1z+o0vT/cX9wple4YGTpz8I5PLORghC/qB5QUWbh4yGZPjSzb5RQURwhLPD7omOLIIql4x5FwBRHjgU17mLZkTZ4AS8hz0SKEE5XIWqV6SEw128JSs2rAq5wgI+Za4zncsh4BssgJXYQM1c9ThiE1NzsQ69DmHEwZRy/liF5q1Uy0h4tPfei3BI7ld8IXs9Jie5yeVajpQDTD07rdExGsGBP0GBg9DUKbHg0C0G39YOGUNUPZahxzRbdRpbZri3mdgFfiSAAEgua3h53nOQDJBdZSRQRAvo3zMepBpEBzsRIvCakpCqy36QExL4iO+GAEZfTcOwKp5imPXC+C5eCjT+WCEbD/t0FBzEzg9HqqyT0aYZ3VcexgENA0l31vqKDxQIMS8Z6btCYFe8RmXA0apaMqw1iB60CYoejTadQoAhJ2N70/W9r8cLhe5HhpY3TW6IpVZbIbI4xZgVvG1dtpjKT0A8WcfcCQGiZDIA8DsrIljXM3b0Cgmgw64gIONOHjOsAp31Jonuh13Vm4/cwSUTLl1KAk/kAm/0uXcWt5owwy3fgLxLeov8eFjWuZuRg6V6YPxQthVICNfB5eYakcA+C6oxTlHw39Jy3AKSo2NK4Bo1DA4MCDJ3AvQZI0q+INAtkP6SABA7H7mCND1wbXOkK4UpzjkAZmyeR6VgEEz+ZMeKoCBLEHVib+1JVbskR9fZAC9QEqyOoir7vNZUNYxN845fQgVwAwE3S3+/Cq6+fWGAnbLgBBbwGIVjkRLfZvhbWYmArohNYqS0qyihF4AgPvLiTCTbxoZmAALMzwDANpKocQtLk0Ete7ajvSygdX06kzz2oh4q6oiVI941lgqgoRHBti1spBEfgDCDkAM9dXhZMnV09wpQ40Po40v40REFUhPTFyaxYQO6IhwkNjJzFHoBIC3KkEtxtDTu8n50E3ZgR0z3dX8t+HEAtmTiZnpxI0v0FQI9ABEyYggshxRCgmoAsANBcmrD4DMVVFAlEUuDoD8ToF4rwnyD8T/+J1M8GZAlzbcTAZBhEmABvjR9qtN2M3J9M7JnWiM0BxIa20cuDUBYptJGwLBsl7Z68cdxOohp62eHcmODmpZ/8UdaiwCERshlAhCAIqFKBmAJFMdFIbMIFTABICQmECEduEBhrkAzFcADiaeFOxAa1AJcczJ9AXR/4UQVxrRXnxgMJeAZSRETk+ANimVN2faCHNd+8MeH06N68mJ6fchIs8chZiFElbJGQhE/n2BhmbcdpeIBeDFH4JEATBECOeACZRhvmPeMVcgUPQACGNCJuVB4bzZr1LJRR2NraSRr6TMAXsIMwMJFyuAApeGO3/ULCHBjMgRydyhAjCRfcFP+dpjmi0yWf+XCg8lxAUJEOBCBe5uhVZcwd8foCaOADQY4OQnAMe2gPyBkZZZgABVlEiYBQFdCJRg2NAEQJD7hC2/kZM4VHC+QIAKwIAZSFN4AIA7HHSlYFALjbX/Ij7h4cKPDfjfYiwGpIY+SIItgRJgCaTskIwfpkFtEb6qkEsgkF6EQYVTyARdmlfzBHz/3P75QAxnVHi7RW7gQjlbDlftBcQEwLcBQAggALWxWFISlCnvybSzIi5lWi54Ve/j3WfbHGyRiHCMCZeX2TmgxIj4UOILwForXJaKAPsz4mFaZAClhKvYoRcJSGeoRjbyTZn0hGbHDCyUwYzcHYhb+h0Hn4WvAYAB1cidQ5EoX9DMoFQzet1TmmH9bMTd2qH9CaT1d0XqAeRCH6QiUdVr9xQNC1F/1RAjJ2T95kSMRYXSowRFyYiq6UJFhBpIfeYECaBjf6UVshB+3JA4dIACtOEfThQBhsi2lWWOPs095hAI6ST3dVoO02Iul+Hb0J5wgwoPHOSMsElXgsxxAtEkj9oC4sIwegAF7xVtatXX/F2YlAZqcIAEC5xjhCJrg2QEb9XMHtFyyMJ4RNgCpgB5guRgFAYRv0hkUtUXjJwBfsUC4+TaJgno1GENGhY9e0Z9f4Q486GkV8UOA9zBRNiPR4THL2KDrpgn/909ollv+2RmlXwUOx0drxNULrfkZ9ghiYYgfk2GZQ6FiA1IIbGI7TuNXABAk9FgD3leHLUifHpeLtVFpKfdIRKlLL1CgP8g3nzYIQRo+KeI+BRAdW2QlU5Jlhap4a3UlDDA/DiCSkSqSMWCmwGIOkoqpd0QAAyCpiBqpAAWbkTptKtIAR6E1rSmSA4AJl2olBlA0u1ifckp2dGpp+fgbeLoh5WYIgVqYQaqnmaQimpIpz/FJ5oZ1WYcc//BcAWMoh7KsFTE8u4Ek/TA84MQoA5Ek08ohzzUoYJMzPNqtwYgbHfcvulh25CpDR3autQGQuJptMCI+wyFEAyopGBBC8Bo6DSD+rB/orcB5q0Z1PXD6fjMUlG5Tcv+Kn0C5elQme33Zm/C3j3dKq//gsODGm+7qKSRUr46QnJakTdDBHIrQAFnXAwhDPDM6g+HmKP6om/j4FGeno/Lir4dgM2SSL89DKHp5NDHIhwfnfgCbs+mqg/kJKRQrsPXXo5LkKSZrRJl0Wi5gsmtRLlaBg5kmsTk6tLMaMLc6htXDIbyJcSEAidenJBPwPBILcvZZlPcpN3T4r51VsX7YbSKXtGuHT46QkGjBki75rDrarruZsIOyKDAbe0dGsD97nzkTtjqjP0aCLCGgK00xTDtpripnoz+LuOgacjNKp7LaIQqbdnUro0j+A2k7SEkKq7mAq2RDOZSP4roqu7PnmhXXpiS1S7vXBrkiMAGNhXAT0LZsC3uAe6MuG3/ehrr6mbLfJrhHJbqSNHYdC087Sau8CLsJe7CHi7yoO7uLa7uGwA61azM6YyT60oG5kgH3gnG6uzb+qLVUZrkewrM4SIPo9oLs6rlnJ7hI27xVWwiecknZa6Mz2Ll8mbhMNibfmzO1671haxC4K7bV1rhGcn29+4T40rvZQr0Xm7gDbI7Uu3tTVbw/6bBj4bfuCqtlakTdw1kruGkJYbEZ3Ie1uys1hSzfy8Deq8BKIgKWc326uzK5UgH3Ern6ssO5Qr6Re5dfC4NUW7T+sSpgwiFvByBj3tqTimKu8CW/Jsw6VTuuFoK1q1ufw0tMB/y9SoIOumI5tItxMvyE51tT+iPEu6u+b3zERHy++mK2+bIyGByMLJy8RUtUxhQvlZBFwdECDdACQ3YKSjan2iu8lxtyo4uneYh/wZujpfjCucEPShJe31rG+7LANWU5bry7CNGBu8u456srFgzHkKgvRoxxqAyJ5ku+usvHRenEYuGSutS39NAC0BIBLXADhjxNNnDIFyDFd4qb/XjFDSu7WryjvblO6XqLf7ujsHHA+TJ04XXD3bsvb3wsHYhCtkvH+OI8uuvGkLu7rmwDsDzH6Lwy5gyJ+/K56Nr+tX9jst7wtYXDA6LCKxGQRRdACcF8N8E8WQcQzMGRzM9cvMAIyFvcn9FcuOuaeneom/yiw9UGzk84xDQswfjyze1szviCyg0Mx2scxOj8yteXK0piJGsM0vkyw+mbxwPbcTypDy0gIz9AQojsAghdCYglMZfXAuf4AkUt0EMmxcF8efvIjyPcwXLbo45MyYX7mwGhY8kxubFstmML0pAYxG0cxCi0xqFc1kZswzuMymrt0hwN0vqyuAu8uHCNw2Ebs7F3J1AWLz/wWgdw1C3QeQodzFnk15WSNSqSyMH8ywg9CWAD1axruX+sTnUrdjhKi2LsGhw9AaylP5zS1jP+7MbtrD/enMMDZNo0vStBrMMcnQEMXFOgbNplXNawTbsd/L5k4jLDcQCm2gJj9APDccinsC9IotBDhhwXoDQIPSGpJ4MQy8SALMYQPdUIu7VWnD0RAHUBptmRkMYDZL4KrMfni8M1dS/jfLs2bAjqq94YN8vi7cCzbcPfLNfgDcpoFG/IYRwXkDVSXAkfkcgC3QJLcgANMyJ+DdDO5dexdgDHTaNbi9N4+dj6CM0GK5S2MXQZsAiWEzoylMp+NMu2O8cDFOLiqysVnN4O/MnqG9cr/sm4K9/yveKxDWqtk0V3cye7bchKrdzeANCFPdCn0H88Tdh+o3K3+Kauy8H+zj2wIKLBfdi54asWuILGyHIBORDBxNPSe7QyOVNF5hvO7Ey7OxzmKM4OOwzXajxAORzfMX7abH4Q1+bJKyXFBe0zP6AgNnAUvz0IBv7fyI3QlOBcx8EOxOFc3nsBAEDPiCCBbTceCzEesNHo79DoYCQeLVgeiyAeBUwIAYSr86cQy9IVHz4PzBJONfO9XkMQzaJeO7wzZM0O42va6OvaaxzSnwzfb27WuI7epkzr871dXQHoAJ089bKrITDQM8LYWUQJPG3siHXPiSCN7cfpBXHpIVAehnDph04eB5HpLqzt5MHQ+5Dpnb656SS+qr4vuILhe1QzGMcsj6tAZj7+QM1iwek7wzaMDrve5nJt1u9N27wO27E90t5LAmPihrex7Dwt2HBkEXr358P8Xy/rwtgugd8u6aToD5Vu7VCj8ZVe6doO8gSh8a/R7R1f8ZH+7Rwf6SvP8gEE7pc9EDaDQsyiXmL70tfELMNTRVsrvuhN7yIu3mkOyucN3+gd8PON9DDewDesNm6owySAL1IcRqYA6MZU0DyNzCQAHHeDWNk08Ub18de+8dej8SAf9kxh8huf8aQInBu/7WM/9mlP7dLo8Wj/6HXv9tGem2GkM6iOK2T99xIPlP8QvmV9wwWR0gE/9LP+FfoOFrKu7+T91jdQuwU/CWxzAz/Q9Pj+Ag86NGTlcgNzfk2CovDGGyIULwjdfvHB+PGpr/KuP/baHvvQzvaPku1qn/d0/+hwf+0j3/t67+1tH07ogAgK7DVk475kUkWH0PcufvTabMHefPi8zu/8Tt46nM35gr71IAJqgy+IpSRqkzMkMAkuybfHQwiI1fVkcq1zQ2ksbOkSWO3jTvstX/LbnvLTnv8UPwh1r/v8DwghgoMAAIKFhoWDIYqHhoSPixeTlCGTkhchNpmcFzkVOZKCl5c2OZuDOaGai4s2rDavrbKCtK21rLMhIiKCDSIRvJYNv7sNIRG/wcovoyINERcRP83DEZatmdjblZSclt7e26OjjYz+jReF2pOI6IjriODnAN3p7Zbq55nv5vfzj/H+nVt0z9ytQesukdM2CFSOTvLGfYtlAxTDQbFg4TqYC9YrWbZyiZBVDFmEZA0u2FAW4UWvCy+SnXTZbNKLH9FaRvv2jRw2Ugwv9jzYCSi+bvIeKRwFMeg6bhfHgSPlUx7PcFizat26deFPnlMZnnoYFKHVTKYy2gp58OOiXh9twN0oVy2wUdUuiEAbQe6kk9F8tZzU4AXEwGGZhvP602dCUU4VPmXEmN7XiFWvnsXcc7HmqWG5ih7d9THVxrMexoLYuBLGjmozvt7FdtfIWnUFzc2N669vS4B3Ar50sihmTK1BA3WVjTqq88StxYlzvLks9KWMpYPVTrq79+kSkYJXSRE1t3G10bvCvR4uRdm6c8mmtIlSYPvQsyFlCnrh9M7nIZcNQq5RJRlU1zEWXXXWKbbUZPV8J+FoET31oDdu1WeafmZxxJFs8L2HGy0gukXKTsxJ0xSBB4Z2YIOsXXaZZ9Jhchp/LB5341D8YSUjdVFJ5eGQRBYpSCAAOy==} + + + + +#============================================================================================== +# Make Regexp +#============================================================================================== +namespace eval make-regexp { +} +# Takes a list of words, returns a list "prefix prefix ..." +# after grouping by first common letter. +proc make-regexp::prefix {words} { + # init + set result {} + lappend words "" ;# to force last completion + # group by first letter + set prefix [string range [lindex $words 0] 0 0] + set subwords [list [string range [lindex $words 0] 1 end]] + foreach word [lrange $words 1 end] { + set char [string range $word 0 0] + if {$char == $prefix} { + lappend subwords [string range $word 1 end] + } else { + # compute prefixes recursively + set recurse [prefix $subwords] + if {[llength $recurse] == 2} { + # only one prefix, so concat with previous prefix + append prefix [lindex $recurse 0] + set recurse [lindex $recurse 1] + } + append result " [verify [list $prefix $recurse]]" + set prefix $char + set subwords [list [string range $word 1 end]] + } + } + # return + set result +} +# Verification of regexp. +# After searching common suffixes, some patterns grouped by parenthesis or conditional exps +# may be broken. We need to fix them. +proc make-regexp::verify {exp} { + set orphans [isOrphans $exp] + set result {} + foreach {prefix recurse} $exp { + if {![isBalanced $prefix]} { + if {[llength $recurse]} { + foreach {pp rr} $recurse { + lappend result "$prefix$pp" $rr + } + if {![isBalanced $prefix] && $orphans} { + set result [verify $result] + } + } else { + lappend result "$prefix" "" + } + } else { + lappend result $prefix $recurse + } + } + # return result after fixing + set result +} +# Check for orphan grouping ('|' lost in lower level) +proc make-regexp::isOrphans {exp} { + set orphan 0 + foreach {prefix recurse} $exp { + if {[string index $prefix 0] == "|"} { + set orphan 1 + break + } + if {[isOrphans $recurse]} { + set orphan 1 + break + } + } + set orphan +} +#============================================================================================== +# Check if parenthesis in 'str' after balanced. +proc make-regexp::isBalanced {str} { + # if start with '?' skip it + if {[string index $str 0] == "?"} { + return 0 + } + # must start with a ')' + if {[string index $str 0] != ")"} { + return 1 + } + # try to balanced each ')' with an appropriate '(' + set depth 0 + foreach c [split $str {}] { + if {$c == "("} { + incr depth -1 + } elseif {$c == ")"} { + incr depth +1 + } + } + return [expr $depth == 0] +} +# Check if 'str' contains a first level grouping +proc make-regexp::firstLevelGroup {str} { + set depth 0 + foreach c [split $str {}] { + if {$c == "("} { + incr depth -1 + } elseif {$c == ")"} { + incr depth +1 + } elseif {$depth == 0 && $c == "|"} { + return 1 + } + } + return 0 +} +#============================================================================================== +# After having found common prefixes, try to find common suffixes in expression +proc make-regexp::suffix {list} { + # end of recursion if empty list + if {[llength $list] == 0} { + return "" + } + set newlist {} + foreach {prefix recurse} $list { + set result [suffix $recurse] + lappend newlist $prefix [lindex $result 0] + } + # compute longest common suffixes + set words {} + foreach {prefix tail} $newlist { + if {[firstLevelGroup $tail]} { + set tail "($tail)" + } + lappend words [reverse $prefix$tail] + } + set words [lsort -unique $words] + set reverse [prefix $words] + # compute regexp from precomputed reverse list + set regexp [build "" $reverse] + # returns computed regexp + set regexp +} +proc make-regexp::build {mainstem reverse} { + # flag to indicate need for '?' (optional group) + set addQuestionMark 0 + set regexp "" + foreach {prefix recurse} $reverse { + set stem "[reverse $prefix]$mainstem" + if {[llength $recurse]} { + set fromlower [build $stem $recurse] + } else { + set fromlower "" + } + # build regexp + if {$prefix == ""} { + set addQuestionMark 1 + } else { + if {[string length $fromlower] > 1 && [string index $fromlower end] != "?"} { + set fromlower "($fromlower)" + } + append regexp "$fromlower[reverse $prefix]|" + } + } + # remove last trailing '|' + set regexp "[string range $regexp 0 end-1]" + # add '?' if needed + if {$addQuestionMark} { + if {[string length $regexp] == 1} { + set regexp "$regexp?" + } else { + set regexp "($regexp)?" + } + } + # result + set regexp +} +#---------------------------------------------------------------------------------------------- +# Last pass for grouping '(x|y|z|...)' into char range '[xyz...]' +proc make-regexp::optimize:charset {regexp} { + set optimized "" + set memory "" + set ok 1 + set charset "" + # examine char one by one + set len [string length $regexp] + for {set i 0} {$i < $len} {incr i} { + set char [string index $regexp $i] + append memory $char + if {$char =="("} { + # start of group + if {$ok} { + append optimized [string range $memory 0 end-1] + } + incr i + set result [optimize:charset [string range $regexp $i end]] + append optimized "[lindex $result 2][lindex $result 0][lindex $result 3]" + set memory "" + set ok 0 + incr i [expr [lindex $result 1]] + continue + } elseif {$char ==")"} { + # end of group + if {$ok} { + set optimized "\[$charset\]" + return [list $optimized $i "" ""] + } else { + return [list $optimized $i "(" ")"] + } + } + if {$ok} { + if {$i & 1} { + if {$char != "|"} { + set ok 0 + append optimized $memory + } + } else { + append charset $char + } + } else { + append optimized $char + } + } + # return result + list $optimized $i "(" ")" +} +#============================================================================================== +# Compute string in reverse order +proc make-regexp::reverse {string} { + set result "" + for {set i [expr [string length $string]-1]} {$i >= 0} {incr i -1} { + append result [string index $string $i] + } + set result +} +#============================================================================================== +proc make-regexp::make-regexp {words} { + set words [lsort -unique $words] + # escape special chars used to form regexp + regsub -all -- {\|} $words "\x01" words + regsub -all -- {\(} $words "\x02" words + regsub -all -- {\)} $words "\x03" words + regsub -all -- {\?} $words "\x04" words + regsub -all -- {\[} $words "\x07" words + regsub -all -- {\]} $words "\x08" words + # do it + set list [prefix $words] + set regexp [suffix $list] + # returns regexp + set regexp [lindex [optimize:charset $regexp] 0] + # un-escape special chars used to form regexp + regsub -all -- "\x01" $regexp "\\|" regexp + regsub -all -- "\x02" $regexp "\\(" regexp + regsub -all -- "\x03" $regexp "\\)" regexp + regsub -all -- "\x04" $regexp "\\?" regexp + regsub -all -- "\x07" $regexp "\\\[" regexp + regsub -all -- "\x08" $regexp "\\\]" regexp + regsub -all -- "\\*" $regexp "\\*" regexp + regsub -all -- "\\+" $regexp "\\+" regexp + regsub -all -- "\\\$" $regexp "\$" regexp + regsub -all -- "\\\^" $regexp "\\\^" regexp + # returns result + set regexp +} +#==============================================================================================