console.tcl 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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 {$family in $families} {
  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. .console see end
  258. }
  259. next {
  260. incr HistNum
  261. if {$HistNum == 0} {
  262. set cmd {history event [expr {[history nextid] -1}]}
  263. } elseif {$HistNum > 0} {
  264. set cmd ""
  265. set HistNum 1
  266. } else {
  267. set cmd "history event $HistNum"
  268. }
  269. if {$cmd ne ""} {
  270. catch {consoleinterp eval $cmd} cmd
  271. }
  272. .console delete promptEnd end
  273. .console insert promptEnd $cmd {input stdin}
  274. .console see end
  275. }
  276. reset {
  277. set HistNum 1
  278. }
  279. }
  280. }
  281. # ::tk::ConsolePrompt --
  282. # This procedure draws the prompt. If tcl_prompt1 or tcl_prompt2
  283. # exists in the main interpreter it will be called to generate the
  284. # prompt. Otherwise, a hard coded default prompt is printed.
  285. #
  286. # Arguments:
  287. # partial - Flag to specify which prompt to print.
  288. proc ::tk::ConsolePrompt {{partial normal}} {
  289. set w .console
  290. if {$partial eq "normal"} {
  291. set temp [$w index "end - 1 char"]
  292. $w mark set output end
  293. if {[consoleinterp eval "info exists tcl_prompt1"]} {
  294. consoleinterp eval "eval \[set tcl_prompt1\]"
  295. } else {
  296. puts -nonewline [EvalAttached $::tk::console::defaultPrompt]
  297. }
  298. } else {
  299. set temp [$w index output]
  300. $w mark set output end
  301. if {[consoleinterp eval "info exists tcl_prompt2"]} {
  302. consoleinterp eval "eval \[set tcl_prompt2\]"
  303. } else {
  304. puts -nonewline "> "
  305. }
  306. }
  307. flush stdout
  308. $w mark set output $temp
  309. ::tk::TextSetCursor $w end
  310. $w mark set promptEnd insert
  311. $w mark gravity promptEnd left
  312. ::tk::console::ConstrainBuffer $w $::tk::console::maxLines
  313. $w see end
  314. }
  315. # Copy selected text from the console
  316. proc ::tk::console::Copy {w} {
  317. if {![catch {set data [$w get sel.first sel.last]}]} {
  318. clipboard clear -displayof $w
  319. clipboard append -displayof $w $data
  320. }
  321. }
  322. # Copies selected text. If the selection is within the current active edit
  323. # region then it will be cut, if not it is only copied.
  324. proc ::tk::console::Cut {w} {
  325. if {![catch {set data [$w get sel.first sel.last]}]} {
  326. clipboard clear -displayof $w
  327. clipboard append -displayof $w $data
  328. if {[$w compare sel.first >= output]} {
  329. $w delete sel.first sel.last
  330. }
  331. }
  332. }
  333. # Paste text from the clipboard
  334. proc ::tk::console::Paste {w} {
  335. catch {
  336. set clip [::tk::GetSelection $w CLIPBOARD]
  337. set list [split $clip \n\r]
  338. tk::ConsoleInsert $w [lindex $list 0]
  339. foreach x [lrange $list 1 end] {
  340. $w mark set insert {end - 1c}
  341. tk::ConsoleInsert $w "\n"
  342. tk::ConsoleInvoke
  343. tk::ConsoleInsert $w $x
  344. }
  345. }
  346. }
  347. # Fit TkConsoleFont to window width
  348. proc ::tk::console::FitScreenWidth {w} {
  349. set width [winfo screenwidth $w]
  350. set cwidth [$w cget -width]
  351. set s -50
  352. set fit 0
  353. array set fi [font configure TkConsoleFont]
  354. while {$s < 0} {
  355. set fi(-size) $s
  356. set f [font create {*}[array get fi]]
  357. set c [font measure $f "eM"]
  358. font delete $f
  359. if {$c * $cwidth < 1.667 * $width} {
  360. font configure TkConsoleFont -size $s
  361. break
  362. }
  363. incr s 2
  364. }
  365. }
  366. # ::tk::ConsoleBind --
  367. # This procedure first ensures that the default bindings for the Text
  368. # class have been defined. Then certain bindings are overridden for
  369. # the class.
  370. #
  371. # Arguments:
  372. # None.
  373. proc ::tk::ConsoleBind {w} {
  374. bindtags $w [list $w Console PostConsole [winfo toplevel $w] all]
  375. ## Get all Text bindings into Console
  376. foreach ev [bind Text] {
  377. bind Console $ev [bind Text $ev]
  378. }
  379. ## We really didn't want the newline insertion...
  380. bind Console <Control-Key-o> {}
  381. ## ...or any Control-v binding (would block <<Paste>>)
  382. bind Console <Control-Key-v> {}
  383. # For the moment, transpose isn't enabled until the console
  384. # gets and overhaul of how it handles input -- hobbs
  385. bind Console <Control-Key-t> {}
  386. # Ignore all Alt, Meta, and Control keypresses unless explicitly bound.
  387. # Otherwise, if a widget binding for one of these is defined, the
  388. # <Keypress> class binding will also fire and insert the character
  389. # which is wrong.
  390. bind Console <Alt-KeyPress> {# nothing }
  391. bind Console <Meta-KeyPress> {# nothing}
  392. bind Console <Control-KeyPress> {# nothing}
  393. foreach {ev key} {
  394. <<Console_NextImmediate>> <Control-Key-n>
  395. <<Console_PrevImmediate>> <Control-Key-p>
  396. <<Console_PrevSearch>> <Control-Key-r>
  397. <<Console_NextSearch>> <Control-Key-s>
  398. <<Console_Expand>> <Key-Tab>
  399. <<Console_Expand>> <Key-Escape>
  400. <<Console_ExpandFile>> <Control-Shift-Key-F>
  401. <<Console_ExpandProc>> <Control-Shift-Key-P>
  402. <<Console_ExpandVar>> <Control-Shift-Key-V>
  403. <<Console_Tab>> <Control-Key-i>
  404. <<Console_Tab>> <Meta-Key-i>
  405. <<Console_Eval>> <Key-Return>
  406. <<Console_Eval>> <Key-KP_Enter>
  407. <<Console_Clear>> <Control-Key-l>
  408. <<Console_KillLine>> <Control-Key-k>
  409. <<Console_Transpose>> <Control-Key-t>
  410. <<Console_ClearLine>> <Control-Key-u>
  411. <<Console_SaveCommand>> <Control-Key-z>
  412. <<Console_FontSizeIncr>> <Control-Key-plus>
  413. <<Console_FontSizeDecr>> <Control-Key-minus>
  414. } {
  415. event add $ev $key
  416. bind Console $key {}
  417. }
  418. if {[tk windowingsystem] eq "aqua"} {
  419. foreach {ev key} {
  420. <<Console_FontSizeIncr>> <Command-Key-plus>
  421. <<Console_FontSizeDecr>> <Command-Key-minus>
  422. } {
  423. event add $ev $key
  424. bind Console $key {}
  425. }
  426. if {$::tk::console::useFontchooser} {
  427. bind Console <Command-Key-t> [list ::tk::console::FontchooserToggle]
  428. }
  429. }
  430. bind Console <<Console_Expand>> {
  431. if {[%W compare insert > promptEnd]} {
  432. ::tk::console::Expand %W
  433. }
  434. }
  435. bind Console <<Console_ExpandFile>> {
  436. if {[%W compare insert > promptEnd]} {
  437. ::tk::console::Expand %W path
  438. }
  439. }
  440. bind Console <<Console_ExpandProc>> {
  441. if {[%W compare insert > promptEnd]} {
  442. ::tk::console::Expand %W proc
  443. }
  444. }
  445. bind Console <<Console_ExpandVar>> {
  446. if {[%W compare insert > promptEnd]} {
  447. ::tk::console::Expand %W var
  448. }
  449. }
  450. bind Console <<Console_Eval>> {
  451. %W mark set insert {end - 1c}
  452. tk::ConsoleInsert %W "\n"
  453. tk::ConsoleInvoke
  454. break
  455. }
  456. bind Console <Delete> {
  457. if {{} ne [%W tag nextrange sel 1.0 end] \
  458. && [%W compare sel.first >= promptEnd]} {
  459. %W delete sel.first sel.last
  460. } elseif {[%W compare insert >= promptEnd]} {
  461. %W delete insert
  462. %W see insert
  463. }
  464. }
  465. bind Console <BackSpace> {
  466. if {{} ne [%W tag nextrange sel 1.0 end] \
  467. && [%W compare sel.first >= promptEnd]} {
  468. %W delete sel.first sel.last
  469. } elseif {[%W compare insert != 1.0] && \
  470. [%W compare insert > promptEnd]} {
  471. %W delete insert-1c
  472. %W see insert
  473. }
  474. }
  475. bind Console <Control-h> [bind Console <BackSpace>]
  476. bind Console <<LineStart>> {
  477. if {[%W compare insert < promptEnd]} {
  478. tk::TextSetCursor %W {insert linestart}
  479. } else {
  480. tk::TextSetCursor %W promptEnd
  481. }
  482. }
  483. bind Console <<LineEnd>> {
  484. tk::TextSetCursor %W {insert lineend}
  485. }
  486. bind Console <Control-d> {
  487. if {[%W compare insert < promptEnd]} {
  488. break
  489. }
  490. %W delete insert
  491. }
  492. bind Console <<Console_KillLine>> {
  493. if {[%W compare insert < promptEnd]} {
  494. break
  495. }
  496. if {[%W compare insert == {insert lineend}]} {
  497. %W delete insert
  498. } else {
  499. %W delete insert {insert lineend}
  500. }
  501. }
  502. bind Console <<Console_Clear>> {
  503. ## Clear console display
  504. %W delete 1.0 "promptEnd linestart"
  505. }
  506. bind Console <<Console_ClearLine>> {
  507. ## Clear command line (Unix shell staple)
  508. %W delete promptEnd end
  509. }
  510. bind Console <Meta-d> {
  511. if {[%W compare insert >= promptEnd]} {
  512. %W delete insert {insert wordend}
  513. }
  514. }
  515. bind Console <Meta-BackSpace> {
  516. if {[%W compare {insert -1c wordstart} >= promptEnd]} {
  517. %W delete {insert -1c wordstart} insert
  518. }
  519. }
  520. bind Console <Meta-d> {
  521. if {[%W compare insert >= promptEnd]} {
  522. %W delete insert {insert wordend}
  523. }
  524. }
  525. bind Console <Meta-BackSpace> {
  526. if {[%W compare {insert -1c wordstart} >= promptEnd]} {
  527. %W delete {insert -1c wordstart} insert
  528. }
  529. }
  530. bind Console <Meta-Delete> {
  531. if {[%W compare insert >= promptEnd]} {
  532. %W delete insert {insert wordend}
  533. }
  534. }
  535. bind Console <<PrevLine>> {
  536. tk::ConsoleHistory prev
  537. }
  538. bind Console <<NextLine>> {
  539. tk::ConsoleHistory next
  540. }
  541. bind Console <Insert> {
  542. catch {tk::ConsoleInsert %W [::tk::GetSelection %W PRIMARY]}
  543. }
  544. bind Console <KeyPress> {
  545. tk::ConsoleInsert %W %A
  546. }
  547. bind Console <F9> {
  548. eval destroy [winfo child .]
  549. source -encoding utf-8 [file join $tk_library console.tcl]
  550. }
  551. if {[tk windowingsystem] eq "aqua"} {
  552. bind Console <Command-q> {
  553. exit
  554. }
  555. }
  556. bind Console <<Cut>> { ::tk::console::Cut %W }
  557. bind Console <<Copy>> { ::tk::console::Copy %W }
  558. bind Console <<Paste>> { ::tk::console::Paste %W }
  559. bind Console <<Console_FontSizeIncr>> {
  560. set size [font configure TkConsoleFont -size]
  561. if {$size < 0} {set sign -1} else {set sign 1}
  562. set size [expr {(abs($size) + 1) * $sign}]
  563. font configure TkConsoleFont -size $size
  564. if {$::tk::console::useFontchooser} {
  565. tk fontchooser configure -font TkConsoleFont
  566. }
  567. }
  568. bind Console <<Console_FontSizeDecr>> {
  569. set size [font configure TkConsoleFont -size]
  570. if {abs($size) < 2} { return }
  571. if {$size < 0} {set sign -1} else {set sign 1}
  572. set size [expr {(abs($size) - 1) * $sign}]
  573. font configure TkConsoleFont -size $size
  574. if {$::tk::console::useFontchooser} {
  575. tk fontchooser configure -font TkConsoleFont
  576. }
  577. }
  578. bind Console <<Console_FitScreenWidth>> {
  579. ::tk::console::FitScreenWidth %W
  580. }
  581. ##
  582. ## Bindings for doing special things based on certain keys
  583. ##
  584. bind PostConsole <Key-parenright> {
  585. if {"\\" ne [%W get insert-2c]} {
  586. ::tk::console::MatchPair %W \( \) promptEnd
  587. }
  588. }
  589. bind PostConsole <Key-bracketright> {
  590. if {"\\" ne [%W get insert-2c]} {
  591. ::tk::console::MatchPair %W \[ \] promptEnd
  592. }
  593. }
  594. bind PostConsole <Key-braceright> {
  595. if {"\\" ne [%W get insert-2c]} {
  596. ::tk::console::MatchPair %W \{ \} promptEnd
  597. }
  598. }
  599. bind PostConsole <Key-quotedbl> {
  600. if {"\\" ne [%W get insert-2c]} {
  601. ::tk::console::MatchQuote %W promptEnd
  602. }
  603. }
  604. bind PostConsole <KeyPress> {
  605. if {"%A" ne ""} {
  606. ::tk::console::TagProc %W
  607. }
  608. }
  609. }
  610. # ::tk::ConsoleInsert --
  611. # Insert a string into a text at the point of the insertion cursor.
  612. # If there is a selection in the text, and it covers the point of the
  613. # insertion cursor, then delete the selection before inserting. Insertion
  614. # is restricted to the prompt area.
  615. #
  616. # Arguments:
  617. # w - The text window in which to insert the string
  618. # s - The string to insert (usually just a single character)
  619. proc ::tk::ConsoleInsert {w s} {
  620. if {$s eq ""} {
  621. return
  622. }
  623. catch {
  624. if {[$w compare sel.first <= insert] \
  625. && [$w compare sel.last >= insert]} {
  626. $w tag remove sel sel.first promptEnd
  627. $w delete sel.first sel.last
  628. }
  629. }
  630. if {[$w compare insert < promptEnd]} {
  631. $w mark set insert end
  632. }
  633. $w insert insert $s {input stdin}
  634. $w see insert
  635. }
  636. # ::tk::ConsoleOutput --
  637. #
  638. # This routine is called directly by ConsolePutsCmd to cause a string
  639. # to be displayed in the console.
  640. #
  641. # Arguments:
  642. # dest - The output tag to be used: either "stderr" or "stdout".
  643. # string - The string to be displayed.
  644. proc ::tk::ConsoleOutput {dest string} {
  645. set w .console
  646. $w insert output $string $dest
  647. ::tk::console::ConstrainBuffer $w $::tk::console::maxLines
  648. $w see insert
  649. }
  650. # ::tk::ConsoleExit --
  651. #
  652. # This routine is called by ConsoleEventProc when the main window of
  653. # the application is destroyed. Don't call exit - that probably already
  654. # happened. Just delete our window.
  655. #
  656. # Arguments:
  657. # None.
  658. proc ::tk::ConsoleExit {} {
  659. destroy .
  660. }
  661. # ::tk::ConsoleAbout --
  662. #
  663. # This routine displays an About box to show Tcl/Tk version info.
  664. #
  665. # Arguments:
  666. # None.
  667. proc ::tk::ConsoleAbout {} {
  668. tk_messageBox -type ok -message "[mc {Tcl for Windows}]
  669. Tcl $::tcl_patchLevel
  670. Tk $::tk_patchLevel"
  671. }
  672. # ::tk::console::Fontchooser* --
  673. # Let the user select the console font (TIP 324).
  674. proc ::tk::console::FontchooserToggle {} {
  675. if {[tk fontchooser configure -visible]} {
  676. tk fontchooser hide
  677. } else {
  678. tk fontchooser show
  679. }
  680. }
  681. proc ::tk::console::FontchooserVisibility {index} {
  682. if {[tk fontchooser configure -visible]} {
  683. .menubar.edit entryconfigure $index -label [::tk::msgcat::mc "Hide Fonts"]
  684. } else {
  685. .menubar.edit entryconfigure $index -label [::tk::msgcat::mc "Show Fonts"]
  686. }
  687. }
  688. proc ::tk::console::FontchooserFocus {w isFocusIn} {
  689. if {$isFocusIn} {
  690. tk fontchooser configure -parent $w -font TkConsoleFont \
  691. -command [namespace code [list FontchooserApply]]
  692. } else {
  693. tk fontchooser configure -parent $w -font {} -command {}
  694. }
  695. }
  696. proc ::tk::console::FontchooserApply {font args} {
  697. catch {font configure TkConsoleFont {*}[font actual $font]}
  698. }
  699. # ::tk::console::TagProc --
  700. #
  701. # Tags a procedure in the console if it's recognized
  702. # This procedure is not perfect. However, making it perfect wastes
  703. # too much CPU time...
  704. #
  705. # Arguments:
  706. # w - console text widget
  707. proc ::tk::console::TagProc w {
  708. if {!$::tk::console::magicKeys} {
  709. return
  710. }
  711. set exp "\[^\\\\\]\[\[ \t\n\r\;{}\"\$\]"
  712. set i [$w search -backwards -regexp $exp insert-1c promptEnd-1c]
  713. if {$i eq ""} {
  714. set i promptEnd
  715. } else {
  716. append i +2c
  717. }
  718. regsub -all "\[\[\\\\\\?\\*\]" [$w get $i "insert-1c wordend"] {\\\0} c
  719. if {[llength [EvalAttached [list info commands $c]]]} {
  720. $w tag add proc $i "insert-1c wordend"
  721. } else {
  722. $w tag remove proc $i "insert-1c wordend"
  723. }
  724. if {[llength [EvalAttached [list info vars $c]]]} {
  725. $w tag add var $i "insert-1c wordend"
  726. } else {
  727. $w tag remove var $i "insert-1c wordend"
  728. }
  729. }
  730. # ::tk::console::MatchPair --
  731. #
  732. # Blinks a matching pair of characters
  733. # c2 is assumed to be at the text index 'insert'.
  734. # This proc is really loopy and took me an hour to figure out given
  735. # all possible combinations with escaping except for escaped \'s.
  736. # It doesn't take into account possible commenting... Oh well. If
  737. # anyone has something better, I'd like to see/use it. This is really
  738. # only efficient for small contexts.
  739. #
  740. # Arguments:
  741. # w - console text widget
  742. # c1 - first char of pair
  743. # c2 - second char of pair
  744. #
  745. # Calls: ::tk::console::Blink
  746. proc ::tk::console::MatchPair {w c1 c2 {lim 1.0}} {
  747. if {!$::tk::console::magicKeys} {
  748. return
  749. }
  750. if {{} ne [set ix [$w search -back $c1 insert $lim]]} {
  751. while {
  752. [string match {\\} [$w get $ix-1c]] &&
  753. [set ix [$w search -back $c1 $ix-1c $lim]] ne {}
  754. } {}
  755. set i1 insert-1c
  756. while {$ix ne {}} {
  757. set i0 $ix
  758. set j 0
  759. while {[set i0 [$w search $c2 $i0 $i1]] ne {}} {
  760. append i0 +1c
  761. if {[string match {\\} [$w get $i0-2c]]} {
  762. continue
  763. }
  764. incr j
  765. }
  766. if {!$j} {
  767. break
  768. }
  769. set i1 $ix
  770. while {$j && [set ix [$w search -back $c1 $ix $lim]] ne {}} {
  771. if {[string match {\\} [$w get $ix-1c]]} {
  772. continue
  773. }
  774. incr j -1
  775. }
  776. }
  777. if {[string match {} $ix]} {
  778. set ix [$w index $lim]
  779. }
  780. } else {
  781. set ix [$w index $lim]
  782. }
  783. if {$::tk::console::blinkRange} {
  784. Blink $w $ix [$w index insert]
  785. } else {
  786. Blink $w $ix $ix+1c [$w index insert-1c] [$w index insert]
  787. }
  788. }
  789. # ::tk::console::MatchQuote --
  790. #
  791. # Blinks between matching quotes.
  792. # Blinks just the quote if it's unmatched, otherwise blinks quoted string
  793. # The quote to match is assumed to be at the text index 'insert'.
  794. #
  795. # Arguments:
  796. # w - console text widget
  797. #
  798. # Calls: ::tk::console::Blink
  799. proc ::tk::console::MatchQuote {w {lim 1.0}} {
  800. if {!$::tk::console::magicKeys} {
  801. return
  802. }
  803. set i insert-1c
  804. set j 0
  805. while {[set i [$w search -back \" $i $lim]] ne {}} {
  806. if {[string match {\\} [$w get $i-1c]]} {
  807. continue
  808. }
  809. if {!$j} {
  810. set i0 $i
  811. }
  812. incr j
  813. }
  814. if {$j&1} {
  815. if {$::tk::console::blinkRange} {
  816. Blink $w $i0 [$w index insert]
  817. } else {
  818. Blink $w $i0 $i0+1c [$w index insert-1c] [$w index insert]
  819. }
  820. } else {
  821. Blink $w [$w index insert-1c] [$w index insert]
  822. }
  823. }
  824. # ::tk::console::Blink --
  825. #
  826. # Blinks between n index pairs for a specified duration.
  827. #
  828. # Arguments:
  829. # w - console text widget
  830. # i1 - start index to blink region
  831. # i2 - end index of blink region
  832. # dur - duration in usecs to blink for
  833. #
  834. # Outputs:
  835. # blinks selected characters in $w
  836. proc ::tk::console::Blink {w args} {
  837. eval [list $w tag add blink] $args
  838. after $::tk::console::blinkTime [list $w] tag remove blink $args
  839. }
  840. # ::tk::console::ConstrainBuffer --
  841. #
  842. # This limits the amount of data in the text widget
  843. # Called by Prompt and ConsoleOutput
  844. #
  845. # Arguments:
  846. # w - console text widget
  847. # size - # of lines to constrain to
  848. #
  849. # Outputs:
  850. # may delete data in console widget
  851. proc ::tk::console::ConstrainBuffer {w size} {
  852. if {[$w index end] > $size} {
  853. $w delete 1.0 [expr {int([$w index end])-$size}].0
  854. }
  855. }
  856. # ::tk::console::Expand --
  857. #
  858. # Arguments:
  859. # ARGS: w - text widget in which to expand str
  860. # type - type of expansion (path / proc / variable)
  861. #
  862. # Calls: ::tk::console::Expand(Pathname|Procname|Variable)
  863. #
  864. # Outputs: The string to match is expanded to the longest possible match.
  865. # If ::tk::console::showMatches is non-zero and the longest match
  866. # equaled the string to expand, then all possible matches are
  867. # output to stdout. Triggers bell if no matches are found.
  868. #
  869. # Returns: number of matches found
  870. proc ::tk::console::Expand {w {type ""}} {
  871. set exp "\[^\\\\\]\[\[ \t\n\r\\\{\"\\\\\$\]"
  872. set tmp [$w search -backwards -regexp $exp insert-1c promptEnd-1c]
  873. if {$tmp eq ""} {
  874. set tmp promptEnd
  875. } else {
  876. append tmp +2c
  877. }
  878. if {[$w compare $tmp >= insert]} {
  879. return
  880. }
  881. set str [$w get $tmp insert]
  882. switch -glob $type {
  883. path* {
  884. set res [ExpandPathname $str]
  885. }
  886. proc* {
  887. set res [ExpandProcname $str]
  888. }
  889. var* {
  890. set res [ExpandVariable $str]
  891. }
  892. default {
  893. set res {}
  894. foreach t {Pathname Procname Variable} {
  895. if {![catch {Expand$t $str} res] && ($res ne "")} {
  896. break
  897. }
  898. }
  899. }
  900. }
  901. set len [llength $res]
  902. if {$len} {
  903. set repl [lindex $res 0]
  904. $w delete $tmp insert
  905. $w insert $tmp $repl {input stdin}
  906. if {($len > 1) && ($::tk::console::showMatches) && ($repl eq $str)} {
  907. puts stdout [lsort [lreplace $res 0 0]]
  908. }
  909. } else {
  910. bell
  911. }
  912. return [incr len -1]
  913. }
  914. # ::tk::console::ExpandPathname --
  915. #
  916. # Expand a file pathname based on $str
  917. # This is based on UNIX file name conventions
  918. #
  919. # Arguments:
  920. # str - partial file pathname to expand
  921. #
  922. # Calls: ::tk::console::ExpandBestMatch
  923. #
  924. # Returns: list containing longest unique match followed by all the
  925. # possible further matches
  926. proc ::tk::console::ExpandPathname str {
  927. set pwd [EvalAttached pwd]
  928. if {[catch {EvalAttached [list cd [file dirname $str]]} err opt]} {
  929. return -options $opt $err
  930. }
  931. set dir [file tail $str]
  932. ## Check to see if it was known to be a directory and keep the trailing
  933. ## slash if so (file tail cuts it off)
  934. if {[string match */ $str]} {
  935. append dir /
  936. }
  937. if {[catch {lsort [EvalAttached [list glob $dir*]]} m]} {
  938. set match {}
  939. } else {
  940. if {[llength $m] > 1} {
  941. if { $::tcl_platform(platform) eq "windows" } {
  942. ## Windows is screwy because it's case insensitive
  943. set tmp [ExpandBestMatch [string tolower $m] \
  944. [string tolower $dir]]
  945. ## Don't change case if we haven't changed the word
  946. if {[string length $dir]==[string length $tmp]} {
  947. set tmp $dir
  948. }
  949. } else {
  950. set tmp [ExpandBestMatch $m $dir]
  951. }
  952. if {[string match ?*/* $str]} {
  953. set tmp [file dirname $str]/$tmp
  954. } elseif {[string match /* $str]} {
  955. set tmp /$tmp
  956. }
  957. regsub -all { } $tmp {\\ } tmp
  958. set match [linsert $m 0 $tmp]
  959. } else {
  960. ## This may look goofy, but it handles spaces in path names
  961. eval append match $m
  962. if {[file isdir $match]} {
  963. append match /
  964. }
  965. if {[string match ?*/* $str]} {
  966. set match [file dirname $str]/$match
  967. } elseif {[string match /* $str]} {
  968. set match /$match
  969. }
  970. regsub -all { } $match {\\ } match
  971. ## Why is this one needed and the ones below aren't!!
  972. set match [list $match]
  973. }
  974. }
  975. EvalAttached [list cd $pwd]
  976. return $match
  977. }
  978. # ::tk::console::ExpandProcname --
  979. #
  980. # Expand a tcl proc name based on $str
  981. #
  982. # Arguments:
  983. # str - partial proc name to expand
  984. #
  985. # Calls: ::tk::console::ExpandBestMatch
  986. #
  987. # Returns: list containing longest unique match followed by all the
  988. # possible further matches
  989. proc ::tk::console::ExpandProcname str {
  990. set match [EvalAttached [list info commands $str*]]
  991. if {[llength $match] == 0} {
  992. set ns [EvalAttached \
  993. "namespace children \[namespace current\] [list $str*]"]
  994. if {[llength $ns]==1} {
  995. set match [EvalAttached [list info commands ${ns}::*]]
  996. } else {
  997. set match $ns
  998. }
  999. }
  1000. if {[llength $match] > 1} {
  1001. regsub -all { } [ExpandBestMatch $match $str] {\\ } str
  1002. set match [linsert $match 0 $str]
  1003. } else {
  1004. regsub -all { } $match {\\ } match
  1005. }
  1006. return $match
  1007. }
  1008. # ::tk::console::ExpandVariable --
  1009. #
  1010. # Expand a tcl variable name based on $str
  1011. #
  1012. # Arguments:
  1013. # str - partial tcl var name to expand
  1014. #
  1015. # Calls: ::tk::console::ExpandBestMatch
  1016. #
  1017. # Returns: list containing longest unique match followed by all the
  1018. # possible further matches
  1019. proc ::tk::console::ExpandVariable str {
  1020. if {[regexp {([^\(]*)\((.*)} $str -> ary str]} {
  1021. ## Looks like they're trying to expand an array.
  1022. set match [EvalAttached [list array names $ary $str*]]
  1023. if {[llength $match] > 1} {
  1024. set vars $ary\([ExpandBestMatch $match $str]
  1025. foreach var $match {
  1026. lappend vars $ary\($var\)
  1027. }
  1028. return $vars
  1029. } elseif {[llength $match] == 1} {
  1030. set match $ary\($match\)
  1031. }
  1032. ## Space transformation avoided for array names.
  1033. } else {
  1034. set match [EvalAttached [list info vars $str*]]
  1035. if {[llength $match] > 1} {
  1036. regsub -all { } [ExpandBestMatch $match $str] {\\ } str
  1037. set match [linsert $match 0 $str]
  1038. } else {
  1039. regsub -all { } $match {\\ } match
  1040. }
  1041. }
  1042. return $match
  1043. }
  1044. # ::tk::console::ExpandBestMatch --
  1045. #
  1046. # Finds the best unique match in a list of names.
  1047. # The extra $e in this argument allows us to limit the innermost loop a little
  1048. # further. This improves speed as $l becomes large or $e becomes long.
  1049. #
  1050. # Arguments:
  1051. # l - list to find best unique match in
  1052. # e - currently best known unique match
  1053. #
  1054. # Returns: longest unique match in the list
  1055. proc ::tk::console::ExpandBestMatch {l {e {}}} {
  1056. set ec [lindex $l 0]
  1057. if {[llength $l]>1} {
  1058. set e [expr {[string length $e] - 1}]
  1059. set ei [expr {[string length $ec] - 1}]
  1060. foreach l $l {
  1061. while {$ei>=$e && [string first $ec $l]} {
  1062. set ec [string range $ec 0 [incr ei -1]]
  1063. }
  1064. }
  1065. }
  1066. return $ec
  1067. }
  1068. # now initialize the console
  1069. ::tk::ConsoleInit