console.tcl 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. # console.tcl --
  2. #
  3. # This code constructs the console window for an application. It
  4. # can be used by non-unix systems that do not have built-in support
  5. # for shells.
  6. #
  7. # Copyright (c) 1995-1997 Sun Microsystems, Inc.
  8. # Copyright (c) 1998-2000 Ajuba Solutions.
  9. # Copyright (c) 2007-2008 Daniel A. Steffen <das@users.sourceforge.net>
  10. #
  11. # See the file "license.terms" for information on usage and redistribution
  12. # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  13. #
  14. # TODO: history - remember partially written command
  15. namespace eval ::tk::console {
  16. variable blinkTime 500 ; # msecs to blink braced range for
  17. variable blinkRange 1 ; # enable blinking of the entire braced range
  18. variable magicKeys 1 ; # enable brace matching and proc/var recognition
  19. variable maxLines 600 ; # maximum # of lines buffered in console
  20. variable showMatches 1 ; # show multiple expand matches
  21. variable useFontchooser [llength [info command ::tk::fontchooser]]
  22. variable inPlugin [info exists embed_args]
  23. variable defaultPrompt ; # default prompt if tcl_prompt1 isn't used
  24. if {$inPlugin} {
  25. set defaultPrompt {subst {[history nextid] % }}
  26. } else {
  27. set defaultPrompt {subst {([file tail [pwd]]) [history nextid] % }}
  28. }
  29. }
  30. # simple compat function for tkcon code added for this console
  31. interp alias {} EvalAttached {} consoleinterp eval
  32. # ::tk::ConsoleInit --
  33. # This procedure constructs and configures the console windows.
  34. #
  35. # Arguments:
  36. # None.
  37. proc ::tk::ConsoleInit {} {
  38. if {![consoleinterp eval {set tcl_interactive}]} {
  39. wm withdraw .
  40. }
  41. if {[tk windowingsystem] eq "aqua"} {
  42. set mod "Cmd"
  43. } else {
  44. set mod "Ctrl"
  45. }
  46. if {[catch {menu .menubar} err]} {
  47. bgerror "INIT: $err"
  48. }
  49. AmpMenuArgs .menubar add cascade -label [mc &File] -menu .menubar.file
  50. AmpMenuArgs .menubar add cascade -label [mc &Edit] -menu .menubar.edit
  51. menu .menubar.file -tearoff 0
  52. AmpMenuArgs .menubar.file add command -label [mc "&Source..."] \
  53. -command {tk::ConsoleSource}
  54. AmpMenuArgs .menubar.file add command -label [mc "&Hide Console"] \
  55. -command {wm withdraw .}
  56. AmpMenuArgs .menubar.file add command -label [mc "&Clear Console"] \
  57. -command {.console delete 1.0 "promptEnd linestart"}
  58. if {[tk windowingsystem] ne "aqua"} {
  59. AmpMenuArgs .menubar.file add command -label [mc E&xit] -command {exit}
  60. }
  61. menu .menubar.edit -tearoff 0
  62. AmpMenuArgs .menubar.edit add command -label [mc Cu&t] -accel "$mod+X"\
  63. -command {event generate .console <<Cut>>}
  64. AmpMenuArgs .menubar.edit add command -label [mc &Copy] -accel "$mod+C"\
  65. -command {event generate .console <<Copy>>}
  66. AmpMenuArgs .menubar.edit add command -label [mc P&aste] -accel "$mod+V"\
  67. -command {event generate .console <<Paste>>}
  68. if {[tk windowingsystem] ne "win32"} {
  69. AmpMenuArgs .menubar.edit add command -label [mc Cl&ear] \
  70. -command {event generate .console <<Clear>>}
  71. } else {
  72. AmpMenuArgs .menubar.edit add command -label [mc &Delete] \
  73. -command {event generate .console <<Clear>>} -accel "Del"
  74. AmpMenuArgs .menubar add cascade -label [mc &Help] -menu .menubar.help
  75. menu .menubar.help -tearoff 0
  76. AmpMenuArgs .menubar.help add command -label [mc &About...] \
  77. -command tk::ConsoleAbout
  78. }
  79. AmpMenuArgs .menubar.edit add separator
  80. if {$::tk::console::useFontchooser} {
  81. if {[tk windowingsystem] eq "aqua"} {
  82. .menubar.edit add command -label tk_choose_font_marker
  83. set index [.menubar.edit index tk_choose_font_marker]
  84. .menubar.edit entryconfigure $index \
  85. -label [mc "Show Fonts"]\
  86. -accelerator "$mod-T"\
  87. -command [list ::tk::console::FontchooserToggle]
  88. bind Console <<TkFontchooserVisibility>> \
  89. [list ::tk::console::FontchooserVisibility $index]
  90. ::tk::console::FontchooserVisibility $index
  91. } else {
  92. AmpMenuArgs .menubar.edit add command -label [mc "&Font..."] \
  93. -command [list ::tk::console::FontchooserToggle]
  94. }
  95. bind Console <FocusIn> [list ::tk::console::FontchooserFocus %W 1]
  96. bind Console <FocusOut> [list ::tk::console::FontchooserFocus %W 0]
  97. }
  98. AmpMenuArgs .menubar.edit add command -label [mc "&Increase Font Size"] \
  99. -accel "$mod++" -command {event generate .console <<Console_FontSizeIncr>>}
  100. AmpMenuArgs .menubar.edit add command -label [mc "&Decrease Font Size"] \
  101. -accel "$mod+-" -command {event generate .console <<Console_FontSizeDecr>>}
  102. AmpMenuArgs .menubar.edit add command -label [mc "Fit To Screen Width"] \
  103. -command {event generate .console <<Console_FitScreenWidth>>}
  104. if {[tk windowingsystem] eq "aqua"} {
  105. .menubar add cascade -label [mc Window] -menu [menu .menubar.window]
  106. .menubar add cascade -label [mc Help] -menu [menu .menubar.help]
  107. }
  108. . configure -menu .menubar
  109. # See if we can find a better font than the TkFixedFont
  110. catch {font create TkConsoleFont {*}[font configure TkFixedFont]}
  111. set families [font families]
  112. switch -exact -- [tk windowingsystem] {
  113. aqua { set preferred {Monaco 10} }
  114. win32 { set preferred {ProFontWindows 8 Consolas 8} }
  115. default { set preferred {} }
  116. }
  117. foreach {family size} $preferred {
  118. if {[lsearch -exact $families $family] != -1} {
  119. font configure TkConsoleFont -family $family -size $size
  120. break
  121. }
  122. }
  123. # Provide the right border for the text widget (platform dependent).
  124. ::ttk::style layout ConsoleFrame {
  125. Entry.field -sticky news -border 1 -children {
  126. ConsoleFrame.padding -sticky news
  127. }
  128. }
  129. ::ttk::frame .consoleframe -style ConsoleFrame
  130. set con [text .console -yscrollcommand [list .sb set] -setgrid true \
  131. -borderwidth 0 -highlightthickness 0 -font TkConsoleFont]
  132. if {[tk windowingsystem] eq "aqua"} {
  133. scrollbar .sb -command [list $con yview]
  134. } else {
  135. ::ttk::scrollbar .sb -command [list $con yview]
  136. }
  137. pack .sb -in .consoleframe -fill both -side right -padx 1 -pady 1
  138. pack $con -in .consoleframe -fill both -expand 1 -side left -padx 1 -pady 1
  139. pack .consoleframe -fill both -expand 1 -side left
  140. ConsoleBind $con
  141. $con tag configure stderr -foreground red
  142. $con tag configure stdin -foreground blue
  143. $con tag configure prompt -foreground \#8F4433
  144. $con tag configure proc -foreground \#008800
  145. $con tag configure var -background \#FFC0D0
  146. $con tag raise sel
  147. $con tag configure blink -background \#FFFF00
  148. $con tag configure find -background \#FFFF00
  149. focus $con
  150. # Avoid listing this console in [winfo interps]
  151. if {[info command ::send] eq "::send"} {rename ::send {}}
  152. wm protocol . WM_DELETE_WINDOW { wm withdraw . }
  153. wm title . [mc "Console"]
  154. flush stdout
  155. $con mark set output [$con index "end - 1 char"]
  156. tk::TextSetCursor $con end
  157. $con mark set promptEnd insert
  158. $con mark gravity promptEnd left
  159. # A variant of ConsolePrompt to avoid a 'puts' call
  160. set w $con
  161. set temp [$w index "end - 1 char"]
  162. $w mark set output end
  163. if {![consoleinterp eval "info exists tcl_prompt1"]} {
  164. set string [EvalAttached $::tk::console::defaultPrompt]
  165. $w insert output $string stdout
  166. }
  167. $w mark set output $temp
  168. ::tk::TextSetCursor $w end
  169. $w mark set promptEnd insert
  170. $w mark gravity promptEnd left
  171. if {[tk windowingsystem] ne "aqua"} {
  172. # Subtle work-around to erase the '% ' that tclMain.c prints out
  173. after idle [subst -nocommand {
  174. if {[$con get 1.0 output] eq "% "} { $con delete 1.0 output }
  175. }]
  176. }
  177. }
  178. # ::tk::ConsoleSource --
  179. #
  180. # Prompts the user for a file to source in the main interpreter.
  181. #
  182. # Arguments:
  183. # None.
  184. proc ::tk::ConsoleSource {} {
  185. set filename [tk_getOpenFile -defaultextension .tcl -parent . \
  186. -title [mc "Select a file to source"] \
  187. -filetypes [list \
  188. [list [mc "Tcl Scripts"] .tcl] \
  189. [list [mc "All Files"] *]]]
  190. if {$filename ne ""} {
  191. set cmd [list source $filename]
  192. if {[catch {consoleinterp eval $cmd} result]} {
  193. ConsoleOutput stderr "$result\n"
  194. }
  195. }
  196. }
  197. # ::tk::ConsoleInvoke --
  198. # Processes the command line input. If the command is complete it
  199. # is evaled in the main interpreter. Otherwise, the continuation
  200. # prompt is added and more input may be added.
  201. #
  202. # Arguments:
  203. # None.
  204. proc ::tk::ConsoleInvoke {args} {
  205. set ranges [.console tag ranges input]
  206. set cmd ""
  207. if {[llength $ranges]} {
  208. set pos 0
  209. while {[lindex $ranges $pos] ne ""} {
  210. set start [lindex $ranges $pos]
  211. set end [lindex $ranges [incr pos]]
  212. append cmd [.console get $start $end]
  213. incr pos
  214. }
  215. }
  216. if {$cmd eq ""} {
  217. ConsolePrompt
  218. } elseif {[info complete $cmd]} {
  219. .console mark set output end
  220. .console tag delete input
  221. set result [consoleinterp record $cmd]
  222. if {$result ne ""} {
  223. puts $result
  224. }
  225. ConsoleHistory reset
  226. ConsolePrompt
  227. } else {
  228. ConsolePrompt partial
  229. }
  230. .console yview -pickplace insert
  231. }
  232. # ::tk::ConsoleHistory --
  233. # This procedure implements command line history for the
  234. # console. In general is evals the history command in the
  235. # main interpreter to obtain the history. The variable
  236. # ::tk::HistNum is used to store the current location in the history.
  237. #
  238. # Arguments:
  239. # cmd - Which action to take: prev, next, reset.
  240. set ::tk::HistNum 1
  241. proc ::tk::ConsoleHistory {cmd} {
  242. variable HistNum
  243. switch $cmd {
  244. prev {
  245. incr HistNum -1
  246. if {$HistNum == 0} {
  247. set cmd {history event [expr {[history nextid] -1}]}
  248. } else {
  249. set cmd "history event $HistNum"
  250. }
  251. if {[catch {consoleinterp eval $cmd} cmd]} {
  252. incr HistNum
  253. return
  254. }
  255. .console delete promptEnd end
  256. .console insert promptEnd $cmd {input stdin}
  257. }
  258. next {
  259. incr HistNum
  260. if {$HistNum == 0} {
  261. set cmd {history event [expr {[history nextid] -1}]}
  262. } elseif {$HistNum > 0} {
  263. set cmd ""
  264. set HistNum 1
  265. } else {
  266. set cmd "history event $HistNum"
  267. }
  268. if {$cmd ne ""} {
  269. catch {consoleinterp eval $cmd} cmd
  270. }
  271. .console delete promptEnd end
  272. .console insert promptEnd $cmd {input stdin}
  273. }
  274. reset {
  275. set HistNum 1
  276. }
  277. }
  278. }
  279. # ::tk::ConsolePrompt --
  280. # This procedure draws the prompt. If tcl_prompt1 or tcl_prompt2
  281. # exists in the main interpreter it will be called to generate the
  282. # prompt. Otherwise, a hard coded default prompt is printed.
  283. #
  284. # Arguments:
  285. # partial - Flag to specify which prompt to print.
  286. proc ::tk::ConsolePrompt {{partial normal}} {
  287. set w .console
  288. if {$partial eq "normal"} {
  289. set temp [$w index "end - 1 char"]
  290. $w mark set output end
  291. if {[consoleinterp eval "info exists tcl_prompt1"]} {
  292. consoleinterp eval "eval \[set tcl_prompt1\]"
  293. } else {
  294. puts -nonewline [EvalAttached $::tk::console::defaultPrompt]
  295. }
  296. } else {
  297. set temp [$w index output]
  298. $w mark set output end
  299. if {[consoleinterp eval "info exists tcl_prompt2"]} {
  300. consoleinterp eval "eval \[set tcl_prompt2\]"
  301. } else {
  302. puts -nonewline "> "
  303. }
  304. }
  305. flush stdout
  306. $w mark set output $temp
  307. ::tk::TextSetCursor $w end
  308. $w mark set promptEnd insert
  309. $w mark gravity promptEnd left
  310. ::tk::console::ConstrainBuffer $w $::tk::console::maxLines
  311. $w see end
  312. }
  313. # Copy selected text from the console
  314. proc ::tk::console::Copy {w} {
  315. if {![catch {set data [$w get sel.first sel.last]}]} {
  316. clipboard clear -displayof $w
  317. clipboard append -displayof $w $data
  318. }
  319. }
  320. # Copies selected text. If the selection is within the current active edit
  321. # region then it will be cut, if not it is only copied.
  322. proc ::tk::console::Cut {w} {
  323. if {![catch {set data [$w get sel.first sel.last]}]} {
  324. clipboard clear -displayof $w
  325. clipboard append -displayof $w $data
  326. if {[$w compare sel.first >= output]} {
  327. $w delete sel.first sel.last
  328. }
  329. }
  330. }
  331. # Paste text from the clipboard
  332. proc ::tk::console::Paste {w} {
  333. catch {
  334. set clip [::tk::GetSelection $w CLIPBOARD]
  335. set list [split $clip \n\r]
  336. tk::ConsoleInsert $w [lindex $list 0]
  337. foreach x [lrange $list 1 end] {
  338. $w mark set insert {end - 1c}
  339. tk::ConsoleInsert $w "\n"
  340. tk::ConsoleInvoke
  341. tk::ConsoleInsert $w $x
  342. }
  343. }
  344. }
  345. # Fit TkConsoleFont to window width
  346. proc ::tk::console::FitScreenWidth {w} {
  347. set width [winfo screenwidth $w]
  348. set cwidth [$w cget -width]
  349. set s -50
  350. set fit 0
  351. array set fi [font configure TkConsoleFont]
  352. while {$s < 0} {
  353. set fi(-size) $s
  354. set f [font create {*}[array get fi]]
  355. set c [font measure $f "eM"]
  356. font delete $f
  357. if {$c * $cwidth < 1.667 * $width} {
  358. font configure TkConsoleFont -size $s
  359. break
  360. }
  361. incr s 2
  362. }
  363. }
  364. # ::tk::ConsoleBind --
  365. # This procedure first ensures that the default bindings for the Text
  366. # class have been defined. Then certain bindings are overridden for
  367. # the class.
  368. #
  369. # Arguments:
  370. # None.
  371. proc ::tk::ConsoleBind {w} {
  372. bindtags $w [list $w Console PostConsole [winfo toplevel $w] all]
  373. ## Get all Text bindings into Console
  374. foreach ev [bind Text] {
  375. bind Console $ev [bind Text $ev]
  376. }
  377. ## We really didn't want the newline insertion...
  378. bind Console <Control-Key-o> {}
  379. ## ...or any Control-v binding (would block <<Paste>>)
  380. bind Console <Control-Key-v> {}
  381. # For the moment, transpose isn't enabled until the console
  382. # gets and overhaul of how it handles input -- hobbs
  383. bind Console <Control-Key-t> {}
  384. # Ignore all Alt, Meta, and Control keypresses unless explicitly bound.
  385. # Otherwise, if a widget binding for one of these is defined, the
  386. # <Keypress> class binding will also fire and insert the character
  387. # which is wrong.
  388. bind Console <Alt-KeyPress> {# nothing }
  389. bind Console <Meta-KeyPress> {# nothing}
  390. bind Console <Control-KeyPress> {# nothing}
  391. foreach {ev key} {
  392. <<Console_NextImmediate>> <Control-Key-n>
  393. <<Console_PrevImmediate>> <Control-Key-p>
  394. <<Console_PrevSearch>> <Control-Key-r>
  395. <<Console_NextSearch>> <Control-Key-s>
  396. <<Console_Expand>> <Key-Tab>
  397. <<Console_Expand>> <Key-Escape>
  398. <<Console_ExpandFile>> <Control-Shift-Key-F>
  399. <<Console_ExpandProc>> <Control-Shift-Key-P>
  400. <<Console_ExpandVar>> <Control-Shift-Key-V>
  401. <<Console_Tab>> <Control-Key-i>
  402. <<Console_Tab>> <Meta-Key-i>
  403. <<Console_Eval>> <Key-Return>
  404. <<Console_Eval>> <Key-KP_Enter>
  405. <<Console_Clear>> <Control-Key-l>
  406. <<Console_KillLine>> <Control-Key-k>
  407. <<Console_Transpose>> <Control-Key-t>
  408. <<Console_ClearLine>> <Control-Key-u>
  409. <<Console_SaveCommand>> <Control-Key-z>
  410. <<Console_FontSizeIncr>> <Control-Key-plus>
  411. <<Console_FontSizeDecr>> <Control-Key-minus>
  412. } {
  413. event add $ev $key
  414. bind Console $key {}
  415. }
  416. if {[tk windowingsystem] eq "aqua"} {
  417. foreach {ev key} {
  418. <<Console_FontSizeIncr>> <Command-Key-plus>
  419. <<Console_FontSizeDecr>> <Command-Key-minus>
  420. } {
  421. event add $ev $key
  422. bind Console $key {}
  423. }
  424. if {$::tk::console::useFontchooser} {
  425. bind Console <Command-Key-t> [list ::tk::console::FontchooserToggle]
  426. }
  427. }
  428. bind Console <<Console_Expand>> {
  429. if {[%W compare insert > promptEnd]} {
  430. ::tk::console::Expand %W
  431. }
  432. }
  433. bind Console <<Console_ExpandFile>> {
  434. if {[%W compare insert > promptEnd]} {
  435. ::tk::console::Expand %W path
  436. }
  437. }
  438. bind Console <<Console_ExpandProc>> {
  439. if {[%W compare insert > promptEnd]} {
  440. ::tk::console::Expand %W proc
  441. }
  442. }
  443. bind Console <<Console_ExpandVar>> {
  444. if {[%W compare insert > promptEnd]} {
  445. ::tk::console::Expand %W var
  446. }
  447. }
  448. bind Console <<Console_Eval>> {
  449. %W mark set insert {end - 1c}
  450. tk::ConsoleInsert %W "\n"
  451. tk::ConsoleInvoke
  452. break
  453. }
  454. bind Console <Delete> {
  455. if {{} ne [%W tag nextrange sel 1.0 end] \
  456. && [%W compare sel.first >= promptEnd]} {
  457. %W delete sel.first sel.last
  458. } elseif {[%W compare insert >= promptEnd]} {
  459. %W delete insert
  460. %W see insert
  461. }
  462. }
  463. bind Console <BackSpace> {
  464. if {{} ne [%W tag nextrange sel 1.0 end] \
  465. && [%W compare sel.first >= promptEnd]} {
  466. %W delete sel.first sel.last
  467. } elseif {[%W compare insert != 1.0] && \
  468. [%W compare insert > promptEnd]} {
  469. %W delete insert-1c
  470. %W see insert
  471. }
  472. }
  473. bind Console <Control-h> [bind Console <BackSpace>]
  474. bind Console <<LineStart>> {
  475. if {[%W compare insert < promptEnd]} {
  476. tk::TextSetCursor %W {insert linestart}
  477. } else {
  478. tk::TextSetCursor %W promptEnd
  479. }
  480. }
  481. bind Console <<LineEnd>> {
  482. tk::TextSetCursor %W {insert lineend}
  483. }
  484. bind Console <Control-d> {
  485. if {[%W compare insert < promptEnd]} {
  486. break
  487. }
  488. %W delete insert
  489. }
  490. bind Console <<Console_KillLine>> {
  491. if {[%W compare insert < promptEnd]} {
  492. break
  493. }
  494. if {[%W compare insert == {insert lineend}]} {
  495. %W delete insert
  496. } else {
  497. %W delete insert {insert lineend}
  498. }
  499. }
  500. bind Console <<Console_Clear>> {
  501. ## Clear console display
  502. %W delete 1.0 "promptEnd linestart"
  503. }
  504. bind Console <<Console_ClearLine>> {
  505. ## Clear command line (Unix shell staple)
  506. %W delete promptEnd end
  507. }
  508. bind Console <Meta-d> {
  509. if {[%W compare insert >= promptEnd]} {
  510. %W delete insert {insert wordend}
  511. }
  512. }
  513. bind Console <Meta-BackSpace> {
  514. if {[%W compare {insert -1c wordstart} >= promptEnd]} {
  515. %W delete {insert -1c wordstart} insert
  516. }
  517. }
  518. bind Console <Meta-d> {
  519. if {[%W compare insert >= promptEnd]} {
  520. %W delete insert {insert wordend}
  521. }
  522. }
  523. bind Console <Meta-BackSpace> {
  524. if {[%W compare {insert -1c wordstart} >= promptEnd]} {
  525. %W delete {insert -1c wordstart} insert
  526. }
  527. }
  528. bind Console <Meta-Delete> {
  529. if {[%W compare insert >= promptEnd]} {
  530. %W delete insert {insert wordend}
  531. }
  532. }
  533. bind Console <<PrevLine>> {
  534. tk::ConsoleHistory prev
  535. }
  536. bind Console <<NextLine>> {
  537. tk::ConsoleHistory next
  538. }
  539. bind Console <Insert> {
  540. catch {tk::ConsoleInsert %W [::tk::GetSelection %W PRIMARY]}
  541. }
  542. bind Console <KeyPress> {
  543. tk::ConsoleInsert %W %A
  544. }
  545. bind Console <F9> {
  546. eval destroy [winfo child .]
  547. source [file join $tk_library console.tcl]
  548. }
  549. if {[tk windowingsystem] eq "aqua"} {
  550. bind Console <Command-q> {
  551. exit
  552. }
  553. }
  554. bind Console <<Cut>> { ::tk::console::Cut %W }
  555. bind Console <<Copy>> { ::tk::console::Copy %W }
  556. bind Console <<Paste>> { ::tk::console::Paste %W }
  557. bind Console <<Console_FontSizeIncr>> {
  558. set size [font configure TkConsoleFont -size]
  559. if {$size < 0} {set sign -1} else {set sign 1}
  560. set size [expr {(abs($size) + 1) * $sign}]
  561. font configure TkConsoleFont -size $size
  562. if {$::tk::console::useFontchooser} {
  563. tk fontchooser configure -font TkConsoleFont
  564. }
  565. }
  566. bind Console <<Console_FontSizeDecr>> {
  567. set size [font configure TkConsoleFont -size]
  568. if {abs($size) < 2} { return }
  569. if {$size < 0} {set sign -1} else {set sign 1}
  570. set size [expr {(abs($size) - 1) * $sign}]
  571. font configure TkConsoleFont -size $size
  572. if {$::tk::console::useFontchooser} {
  573. tk fontchooser configure -font TkConsoleFont
  574. }
  575. }
  576. bind Console <<Console_FitScreenWidth>> {
  577. ::tk::console::FitScreenWidth %W
  578. }
  579. ##
  580. ## Bindings for doing special things based on certain keys
  581. ##
  582. bind PostConsole <Key-parenright> {
  583. if {"\\" ne [%W get insert-2c]} {
  584. ::tk::console::MatchPair %W \( \) promptEnd
  585. }
  586. }
  587. bind PostConsole <Key-bracketright> {
  588. if {"\\" ne [%W get insert-2c]} {
  589. ::tk::console::MatchPair %W \[ \] promptEnd
  590. }
  591. }
  592. bind PostConsole <Key-braceright> {
  593. if {"\\" ne [%W get insert-2c]} {
  594. ::tk::console::MatchPair %W \{ \} promptEnd
  595. }
  596. }
  597. bind PostConsole <Key-quotedbl> {
  598. if {"\\" ne [%W get insert-2c]} {
  599. ::tk::console::MatchQuote %W promptEnd
  600. }
  601. }
  602. bind PostConsole <KeyPress> {
  603. if {"%A" ne ""} {
  604. ::tk::console::TagProc %W
  605. }
  606. }
  607. }
  608. # ::tk::ConsoleInsert --
  609. # Insert a string into a text at the point of the insertion cursor.
  610. # If there is a selection in the text, and it covers the point of the
  611. # insertion cursor, then delete the selection before inserting. Insertion
  612. # is restricted to the prompt area.
  613. #
  614. # Arguments:
  615. # w - The text window in which to insert the string
  616. # s - The string to insert (usually just a single character)
  617. proc ::tk::ConsoleInsert {w s} {
  618. if {$s eq ""} {
  619. return
  620. }
  621. catch {
  622. if {[$w compare sel.first <= insert] \
  623. && [$w compare sel.last >= insert]} {
  624. $w tag remove sel sel.first promptEnd
  625. $w delete sel.first sel.last
  626. }
  627. }
  628. if {[$w compare insert < promptEnd]} {
  629. $w mark set insert end
  630. }
  631. $w insert insert $s {input stdin}
  632. $w see insert
  633. }
  634. # ::tk::ConsoleOutput --
  635. #
  636. # This routine is called directly by ConsolePutsCmd to cause a string
  637. # to be displayed in the console.
  638. #
  639. # Arguments:
  640. # dest - The output tag to be used: either "stderr" or "stdout".
  641. # string - The string to be displayed.
  642. proc ::tk::ConsoleOutput {dest string} {
  643. set w .console
  644. $w insert output $string $dest
  645. ::tk::console::ConstrainBuffer $w $::tk::console::maxLines
  646. $w see insert
  647. }
  648. # ::tk::ConsoleExit --
  649. #
  650. # This routine is called by ConsoleEventProc when the main window of
  651. # the application is destroyed. Don't call exit - that probably already
  652. # happened. Just delete our window.
  653. #
  654. # Arguments:
  655. # None.
  656. proc ::tk::ConsoleExit {} {
  657. destroy .
  658. }
  659. # ::tk::ConsoleAbout --
  660. #
  661. # This routine displays an About box to show Tcl/Tk version info.
  662. #
  663. # Arguments:
  664. # None.
  665. proc ::tk::ConsoleAbout {} {
  666. tk_messageBox -type ok -message "[mc {Tcl for Windows}]
  667. Tcl $::tcl_patchLevel
  668. Tk $::tk_patchLevel"
  669. }
  670. # ::tk::console::Fontchooser* --
  671. # Let the user select the console font (TIP 324).
  672. proc ::tk::console::FontchooserToggle {} {
  673. if {[tk fontchooser configure -visible]} {
  674. tk fontchooser hide
  675. } else {
  676. tk fontchooser show
  677. }
  678. }
  679. proc ::tk::console::FontchooserVisibility {index} {
  680. if {[tk fontchooser configure -visible]} {
  681. .menubar.edit entryconfigure $index -label [msgcat::mc "Hide Fonts"]
  682. } else {
  683. .menubar.edit entryconfigure $index -label [msgcat::mc "Show Fonts"]
  684. }
  685. }
  686. proc ::tk::console::FontchooserFocus {w isFocusIn} {
  687. if {$isFocusIn} {
  688. tk fontchooser configure -parent $w -font TkConsoleFont \
  689. -command [namespace code [list FontchooserApply]]
  690. } else {
  691. tk fontchooser configure -parent $w -font {} -command {}
  692. }
  693. }
  694. proc ::tk::console::FontchooserApply {font args} {
  695. catch {font configure TkConsoleFont {*}[font actual $font]}
  696. }
  697. # ::tk::console::TagProc --
  698. #
  699. # Tags a procedure in the console if it's recognized
  700. # This procedure is not perfect. However, making it perfect wastes
  701. # too much CPU time...
  702. #
  703. # Arguments:
  704. # w - console text widget
  705. proc ::tk::console::TagProc w {
  706. if {!$::tk::console::magicKeys} {
  707. return
  708. }
  709. set exp "\[^\\\\\]\[\[ \t\n\r\;{}\"\$\]"
  710. set i [$w search -backwards -regexp $exp insert-1c promptEnd-1c]
  711. if {$i eq ""} {
  712. set i promptEnd
  713. } else {
  714. append i +2c
  715. }
  716. regsub -all "\[\[\\\\\\?\\*\]" [$w get $i "insert-1c wordend"] {\\\0} c
  717. if {[llength [EvalAttached [list info commands $c]]]} {
  718. $w tag add proc $i "insert-1c wordend"
  719. } else {
  720. $w tag remove proc $i "insert-1c wordend"
  721. }
  722. if {[llength [EvalAttached [list info vars $c]]]} {
  723. $w tag add var $i "insert-1c wordend"
  724. } else {
  725. $w tag remove var $i "insert-1c wordend"
  726. }
  727. }
  728. # ::tk::console::MatchPair --
  729. #
  730. # Blinks a matching pair of characters
  731. # c2 is assumed to be at the text index 'insert'.
  732. # This proc is really loopy and took me an hour to figure out given
  733. # all possible combinations with escaping except for escaped \'s.
  734. # It doesn't take into account possible commenting... Oh well. If
  735. # anyone has something better, I'd like to see/use it. This is really
  736. # only efficient for small contexts.
  737. #
  738. # Arguments:
  739. # w - console text widget
  740. # c1 - first char of pair
  741. # c2 - second char of pair
  742. #
  743. # Calls: ::tk::console::Blink
  744. proc ::tk::console::MatchPair {w c1 c2 {lim 1.0}} {
  745. if {!$::tk::console::magicKeys} {
  746. return
  747. }
  748. if {{} ne [set ix [$w search -back $c1 insert $lim]]} {
  749. while {
  750. [string match {\\} [$w get $ix-1c]] &&
  751. [set ix [$w search -back $c1 $ix-1c $lim]] ne {}
  752. } {}
  753. set i1 insert-1c
  754. while {$ix ne {}} {
  755. set i0 $ix
  756. set j 0
  757. while {[set i0 [$w search $c2 $i0 $i1]] ne {}} {
  758. append i0 +1c
  759. if {[string match {\\} [$w get $i0-2c]]} {
  760. continue
  761. }
  762. incr j
  763. }
  764. if {!$j} {
  765. break
  766. }
  767. set i1 $ix
  768. while {$j && [set ix [$w search -back $c1 $ix $lim]] ne {}} {
  769. if {[string match {\\} [$w get $ix-1c]]} {
  770. continue
  771. }
  772. incr j -1
  773. }
  774. }
  775. if {[string match {} $ix]} {
  776. set ix [$w index $lim]
  777. }
  778. } else {
  779. set ix [$w index $lim]
  780. }
  781. if {$::tk::console::blinkRange} {
  782. Blink $w $ix [$w index insert]
  783. } else {
  784. Blink $w $ix $ix+1c [$w index insert-1c] [$w index insert]
  785. }
  786. }
  787. # ::tk::console::MatchQuote --
  788. #
  789. # Blinks between matching quotes.
  790. # Blinks just the quote if it's unmatched, otherwise blinks quoted string
  791. # The quote to match is assumed to be at the text index 'insert'.
  792. #
  793. # Arguments:
  794. # w - console text widget
  795. #
  796. # Calls: ::tk::console::Blink
  797. proc ::tk::console::MatchQuote {w {lim 1.0}} {
  798. if {!$::tk::console::magicKeys} {
  799. return
  800. }
  801. set i insert-1c
  802. set j 0
  803. while {[set i [$w search -back \" $i $lim]] ne {}} {
  804. if {[string match {\\} [$w get $i-1c]]} {
  805. continue
  806. }
  807. if {!$j} {
  808. set i0 $i
  809. }
  810. incr j
  811. }
  812. if {$j&1} {
  813. if {$::tk::console::blinkRange} {
  814. Blink $w $i0 [$w index insert]
  815. } else {
  816. Blink $w $i0 $i0+1c [$w index insert-1c] [$w index insert]
  817. }
  818. } else {
  819. Blink $w [$w index insert-1c] [$w index insert]
  820. }
  821. }
  822. # ::tk::console::Blink --
  823. #
  824. # Blinks between n index pairs for a specified duration.
  825. #
  826. # Arguments:
  827. # w - console text widget
  828. # i1 - start index to blink region
  829. # i2 - end index of blink region
  830. # dur - duration in usecs to blink for
  831. #
  832. # Outputs:
  833. # blinks selected characters in $w
  834. proc ::tk::console::Blink {w args} {
  835. eval [list $w tag add blink] $args
  836. after $::tk::console::blinkTime [list $w] tag remove blink $args
  837. }
  838. # ::tk::console::ConstrainBuffer --
  839. #
  840. # This limits the amount of data in the text widget
  841. # Called by Prompt and ConsoleOutput
  842. #
  843. # Arguments:
  844. # w - console text widget
  845. # size - # of lines to constrain to
  846. #
  847. # Outputs:
  848. # may delete data in console widget
  849. proc ::tk::console::ConstrainBuffer {w size} {
  850. if {[$w index end] > $size} {
  851. $w delete 1.0 [expr {int([$w index end])-$size}].0
  852. }
  853. }
  854. # ::tk::console::Expand --
  855. #
  856. # Arguments:
  857. # ARGS: w - text widget in which to expand str
  858. # type - type of expansion (path / proc / variable)
  859. #
  860. # Calls: ::tk::console::Expand(Pathname|Procname|Variable)
  861. #
  862. # Outputs: The string to match is expanded to the longest possible match.
  863. # If ::tk::console::showMatches is non-zero and the longest match
  864. # equaled the string to expand, then all possible matches are
  865. # output to stdout. Triggers bell if no matches are found.
  866. #
  867. # Returns: number of matches found
  868. proc ::tk::console::Expand {w {type ""}} {
  869. set exp "\[^\\\\\]\[\[ \t\n\r\\\{\"\\\\\$\]"
  870. set tmp [$w search -backwards -regexp $exp insert-1c promptEnd-1c]
  871. if {$tmp eq ""} {
  872. set tmp promptEnd
  873. } else {
  874. append tmp +2c
  875. }
  876. if {[$w compare $tmp >= insert]} {
  877. return
  878. }
  879. set str [$w get $tmp insert]
  880. switch -glob $type {
  881. path* {
  882. set res [ExpandPathname $str]
  883. }
  884. proc* {
  885. set res [ExpandProcname $str]
  886. }
  887. var* {
  888. set res [ExpandVariable $str]
  889. }
  890. default {
  891. set res {}
  892. foreach t {Pathname Procname Variable} {
  893. if {![catch {Expand$t $str} res] && ($res ne "")} {
  894. break
  895. }
  896. }
  897. }
  898. }
  899. set len [llength $res]
  900. if {$len} {
  901. set repl [lindex $res 0]
  902. $w delete $tmp insert
  903. $w insert $tmp $repl {input stdin}
  904. if {($len > 1) && ($::tk::console::showMatches) && ($repl eq $str)} {
  905. puts stdout [lsort [lreplace $res 0 0]]
  906. }
  907. } else {
  908. bell
  909. }
  910. return [incr len -1]
  911. }
  912. # ::tk::console::ExpandPathname --
  913. #
  914. # Expand a file pathname based on $str
  915. # This is based on UNIX file name conventions
  916. #
  917. # Arguments:
  918. # str - partial file pathname to expand
  919. #
  920. # Calls: ::tk::console::ExpandBestMatch
  921. #
  922. # Returns: list containing longest unique match followed by all the
  923. # possible further matches
  924. proc ::tk::console::ExpandPathname str {
  925. set pwd [EvalAttached pwd]
  926. if {[catch {EvalAttached [list cd [file dirname $str]]} err opt]} {
  927. return -options $opt $err
  928. }
  929. set dir [file tail $str]
  930. ## Check to see if it was known to be a directory and keep the trailing
  931. ## slash if so (file tail cuts it off)
  932. if {[string match */ $str]} {
  933. append dir /
  934. }
  935. if {[catch {lsort [EvalAttached [list glob $dir*]]} m]} {
  936. set match {}
  937. } else {
  938. if {[llength $m] > 1} {
  939. if { $::tcl_platform(platform) eq "windows" } {
  940. ## Windows is screwy because it's case insensitive
  941. set tmp [ExpandBestMatch [string tolower $m] \
  942. [string tolower $dir]]
  943. ## Don't change case if we haven't changed the word
  944. if {[string length $dir]==[string length $tmp]} {
  945. set tmp $dir
  946. }
  947. } else {
  948. set tmp [ExpandBestMatch $m $dir]
  949. }
  950. if {[string match ?*/* $str]} {
  951. set tmp [file dirname $str]/$tmp
  952. } elseif {[string match /* $str]} {
  953. set tmp /$tmp
  954. }
  955. regsub -all { } $tmp {\\ } tmp
  956. set match [linsert $m 0 $tmp]
  957. } else {
  958. ## This may look goofy, but it handles spaces in path names
  959. eval append match $m
  960. if {[file isdir $match]} {
  961. append match /
  962. }
  963. if {[string match ?*/* $str]} {
  964. set match [file dirname $str]/$match
  965. } elseif {[string match /* $str]} {
  966. set match /$match
  967. }
  968. regsub -all { } $match {\\ } match
  969. ## Why is this one needed and the ones below aren't!!
  970. set match [list $match]
  971. }
  972. }
  973. EvalAttached [list cd $pwd]
  974. return $match
  975. }
  976. # ::tk::console::ExpandProcname --
  977. #
  978. # Expand a tcl proc name based on $str
  979. #
  980. # Arguments:
  981. # str - partial proc name to expand
  982. #
  983. # Calls: ::tk::console::ExpandBestMatch
  984. #
  985. # Returns: list containing longest unique match followed by all the
  986. # possible further matches
  987. proc ::tk::console::ExpandProcname str {
  988. set match [EvalAttached [list info commands $str*]]
  989. if {[llength $match] == 0} {
  990. set ns [EvalAttached \
  991. "namespace children \[namespace current\] [list $str*]"]
  992. if {[llength $ns]==1} {
  993. set match [EvalAttached [list info commands ${ns}::*]]
  994. } else {
  995. set match $ns
  996. }
  997. }
  998. if {[llength $match] > 1} {
  999. regsub -all { } [ExpandBestMatch $match $str] {\\ } str
  1000. set match [linsert $match 0 $str]
  1001. } else {
  1002. regsub -all { } $match {\\ } match
  1003. }
  1004. return $match
  1005. }
  1006. # ::tk::console::ExpandVariable --
  1007. #
  1008. # Expand a tcl variable name based on $str
  1009. #
  1010. # Arguments:
  1011. # str - partial tcl var name to expand
  1012. #
  1013. # Calls: ::tk::console::ExpandBestMatch
  1014. #
  1015. # Returns: list containing longest unique match followed by all the
  1016. # possible further matches
  1017. proc ::tk::console::ExpandVariable str {
  1018. if {[regexp {([^\(]*)\((.*)} $str -> ary str]} {
  1019. ## Looks like they're trying to expand an array.
  1020. set match [EvalAttached [list array names $ary $str*]]
  1021. if {[llength $match] > 1} {
  1022. set vars $ary\([ExpandBestMatch $match $str]
  1023. foreach var $match {
  1024. lappend vars $ary\($var\)
  1025. }
  1026. return $vars
  1027. } elseif {[llength $match] == 1} {
  1028. set match $ary\($match\)
  1029. }
  1030. ## Space transformation avoided for array names.
  1031. } else {
  1032. set match [EvalAttached [list info vars $str*]]
  1033. if {[llength $match] > 1} {
  1034. regsub -all { } [ExpandBestMatch $match $str] {\\ } str
  1035. set match [linsert $match 0 $str]
  1036. } else {
  1037. regsub -all { } $match {\\ } match
  1038. }
  1039. }
  1040. return $match
  1041. }
  1042. # ::tk::console::ExpandBestMatch --
  1043. #
  1044. # Finds the best unique match in a list of names.
  1045. # The extra $e in this argument allows us to limit the innermost loop a little
  1046. # further. This improves speed as $l becomes large or $e becomes long.
  1047. #
  1048. # Arguments:
  1049. # l - list to find best unique match in
  1050. # e - currently best known unique match
  1051. #
  1052. # Returns: longest unique match in the list
  1053. proc ::tk::console::ExpandBestMatch {l {e {}}} {
  1054. set ec [lindex $l 0]
  1055. if {[llength $l]>1} {
  1056. set e [expr {[string length $e] - 1}]
  1057. set ei [expr {[string length $ec] - 1}]
  1058. foreach l $l {
  1059. while {$ei>=$e && [string first $ec $l]} {
  1060. set ec [string range $ec 0 [incr ei -1]]
  1061. }
  1062. }
  1063. }
  1064. return $ec
  1065. }
  1066. # now initialize the console
  1067. ::tk::ConsoleInit