console.tcl 31 KB

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