TextView.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // In ReadOnly mode backspace/space behave like pageup/pagedown
  10. // Attributed text on spans
  11. // Replace insertion with Insert method
  12. // String accumulation (Control-k, control-k is not preserving the last new line, see StringToRunes
  13. // Alt-D, Alt-Backspace
  14. // API to set the cursor position
  15. // API to scroll to a particular place
  16. // keybindings to go to top/bottom
  17. // public API to insert, remove ranges
  18. // Add word forward/word backwards commands
  19. // Save buffer API
  20. // Mouse
  21. //
  22. // Desirable:
  23. // Move all the text manipulation into the TextModel
  24. using System;
  25. using System.Collections.Generic;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Text;
  29. using NStack;
  30. namespace Terminal.Gui {
  31. class TextModel {
  32. List<List<Rune>> lines = new List<List<Rune>> ();
  33. public bool LoadFile (string file)
  34. {
  35. if (file == null)
  36. throw new ArgumentNullException (nameof (file));
  37. try {
  38. var stream = File.OpenRead (file);
  39. } catch {
  40. return false;
  41. }
  42. LoadStream (File.OpenRead (file));
  43. return true;
  44. }
  45. // Turns the ustring into runes, this does not split the
  46. // contents on a newline if it is present.
  47. internal static List<Rune> ToRunes (ustring str)
  48. {
  49. List<Rune> runes = new List<Rune> ();
  50. foreach (var x in str.ToRunes ()) {
  51. runes.Add (x);
  52. }
  53. return runes;
  54. }
  55. // Splits a string into a List that contains a List<Rune> for each line
  56. public static List<List<Rune>> StringToRunes (ustring content)
  57. {
  58. var lines = new List<List<Rune>> ();
  59. int start = 0, i = 0;
  60. for (; i < content.Length; i++) {
  61. if (content [i] == 10) {
  62. if (i - start > 0)
  63. lines.Add (ToRunes (content [start, i]));
  64. else
  65. lines.Add (ToRunes (ustring.Empty));
  66. start = i + 1;
  67. }
  68. }
  69. if (i - start >= 0)
  70. lines.Add (ToRunes (content [start, null]));
  71. return lines;
  72. }
  73. void Append (List<byte> line)
  74. {
  75. var str = ustring.Make (line.ToArray ());
  76. lines.Add (ToRunes (str));
  77. }
  78. public void LoadStream (Stream input)
  79. {
  80. if (input == null)
  81. throw new ArgumentNullException (nameof (input));
  82. lines = new List<List<Rune>> ();
  83. var buff = new BufferedStream (input);
  84. int v;
  85. var line = new List<byte> ();
  86. while ((v = buff.ReadByte ()) != -1) {
  87. if (v == 10) {
  88. Append (line);
  89. line.Clear ();
  90. continue;
  91. }
  92. line.Add ((byte)v);
  93. }
  94. if (line.Count > 0)
  95. Append (line);
  96. }
  97. public void LoadString (ustring content)
  98. {
  99. lines = StringToRunes (content);
  100. }
  101. public override string ToString ()
  102. {
  103. var sb = new StringBuilder ();
  104. foreach (var line in lines)
  105. {
  106. sb.Append (ustring.Make(line));
  107. sb.AppendLine ();
  108. }
  109. return sb.ToString ();
  110. }
  111. /// <summary>
  112. /// The number of text lines in the model
  113. /// </summary>
  114. public int Count => lines.Count;
  115. /// <summary>
  116. /// Returns the specified line as a List of Rune
  117. /// </summary>
  118. /// <returns>The line.</returns>
  119. /// <param name="line">Line number to retrieve.</param>
  120. public List<Rune> GetLine (int line) => line < Count ? lines [line]: lines[Count-1];
  121. /// <summary>
  122. /// Adds a line to the model at the specified position.
  123. /// </summary>
  124. /// <param name="pos">Line number where the line will be inserted.</param>
  125. /// <param name="runes">The line of text, as a List of Rune.</param>
  126. public void AddLine (int pos, List<Rune> runes)
  127. {
  128. lines.Insert (pos, runes);
  129. }
  130. /// <summary>
  131. /// Removes the line at the specified position
  132. /// </summary>
  133. /// <param name="pos">Position.</param>
  134. public void RemoveLine (int pos)
  135. {
  136. lines.RemoveAt (pos);
  137. }
  138. }
  139. /// <summary>
  140. /// Multi-line text editing view
  141. /// </summary>
  142. /// <remarks>
  143. /// <para>
  144. /// The text view provides a multi-line text view. Users interact
  145. /// with it with the standard Emacs commands for movement or the arrow
  146. /// keys.
  147. /// </para>
  148. /// <list type="table">
  149. /// <listheader>
  150. /// <term>Shortcut</term>
  151. /// <description>Action performed</description>
  152. /// </listheader>
  153. /// <item>
  154. /// <term>Left cursor, Control-b</term>
  155. /// <description>
  156. /// Moves the editing point left.
  157. /// </description>
  158. /// </item>
  159. /// <item>
  160. /// <term>Right cursor, Control-f</term>
  161. /// <description>
  162. /// Moves the editing point right.
  163. /// </description>
  164. /// </item>
  165. /// <item>
  166. /// <term>Alt-b</term>
  167. /// <description>
  168. /// Moves one word back.
  169. /// </description>
  170. /// </item>
  171. /// <item>
  172. /// <term>Alt-f</term>
  173. /// <description>
  174. /// Moves one word forward.
  175. /// </description>
  176. /// </item>
  177. /// <item>
  178. /// <term>Up cursor, Control-p</term>
  179. /// <description>
  180. /// Moves the editing point one line up.
  181. /// </description>
  182. /// </item>
  183. /// <item>
  184. /// <term>Down cursor, Control-n</term>
  185. /// <description>
  186. /// Moves the editing point one line down
  187. /// </description>
  188. /// </item>
  189. /// <item>
  190. /// <term>Home key, Control-a</term>
  191. /// <description>
  192. /// Moves the cursor to the beginning of the line.
  193. /// </description>
  194. /// </item>
  195. /// <item>
  196. /// <term>End key, Control-e</term>
  197. /// <description>
  198. /// Moves the cursor to the end of the line.
  199. /// </description>
  200. /// </item>
  201. /// <item>
  202. /// <term>Delete, Control-d</term>
  203. /// <description>
  204. /// Deletes the character in front of the cursor.
  205. /// </description>
  206. /// </item>
  207. /// <item>
  208. /// <term>Backspace</term>
  209. /// <description>
  210. /// Deletes the character behind the cursor.
  211. /// </description>
  212. /// </item>
  213. /// <item>
  214. /// <term>Control-k</term>
  215. /// <description>
  216. /// Deletes the text until the end of the line and replaces the kill buffer
  217. /// with the deleted text. You can paste this text in a different place by
  218. /// using Control-y.
  219. /// </description>
  220. /// </item>
  221. /// <item>
  222. /// <term>Control-y</term>
  223. /// <description>
  224. /// Pastes the content of the kill ring into the current position.
  225. /// </description>
  226. /// </item>
  227. /// <item>
  228. /// <term>Alt-d</term>
  229. /// <description>
  230. /// Deletes the word above the cursor and adds it to the kill ring. You
  231. /// can paste the contents of the kill ring with Control-y.
  232. /// </description>
  233. /// </item>
  234. /// <item>
  235. /// <term>Control-q</term>
  236. /// <description>
  237. /// Quotes the next input character, to prevent the normal processing of
  238. /// key handling to take place.
  239. /// </description>
  240. /// </item>
  241. /// </list>
  242. /// </remarks>
  243. public class TextView : View {
  244. TextModel model = new TextModel ();
  245. int topRow;
  246. int leftColumn;
  247. int currentRow;
  248. int currentColumn;
  249. int selectionStartColumn, selectionStartRow;
  250. bool selecting;
  251. //bool used;
  252. /// <summary>
  253. /// Raised when the Text of the TextView changes.
  254. /// </summary>
  255. public event EventHandler TextChanged;
  256. #if false
  257. /// <summary>
  258. /// Changed event, raised when the text has clicked.
  259. /// </summary>
  260. /// <remarks>
  261. /// Client code can hook up to this event, it is
  262. /// raised when the text in the entry changes.
  263. /// </remarks>
  264. public event EventHandler Changed;
  265. #endif
  266. /// <summary>
  267. /// Public constructor, creates a view on the specified area, with absolute position and size.
  268. /// </summary>
  269. /// <remarks>
  270. /// </remarks>
  271. public TextView (Rect frame) : base (frame)
  272. {
  273. CanFocus = true;
  274. }
  275. /// <summary>
  276. /// Public constructor, creates a view on the specified area, with dimensions controlled with the X, Y, Width and Height properties.
  277. /// </summary>
  278. public TextView () : base ()
  279. {
  280. CanFocus = true;
  281. }
  282. void ResetPosition ()
  283. {
  284. topRow = leftColumn = currentRow = currentColumn = 0;
  285. }
  286. /// <summary>
  287. /// Sets or gets the text in the entry.
  288. /// </summary>
  289. /// <remarks>
  290. /// </remarks>
  291. public ustring Text {
  292. get {
  293. return model.ToString ();
  294. }
  295. set {
  296. ResetPosition ();
  297. model.LoadString (value);
  298. TextChanged?.Invoke(this, new EventArgs());
  299. SetNeedsDisplay ();
  300. }
  301. }
  302. /// <summary>
  303. /// Loads the contents of the file into the TextView.
  304. /// </summary>
  305. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  306. /// <param name="path">Path to the file to load.</param>
  307. public bool LoadFile (string path)
  308. {
  309. if (path == null)
  310. throw new ArgumentNullException (nameof (path));
  311. ResetPosition ();
  312. var res = model.LoadFile (path);
  313. SetNeedsDisplay ();
  314. return res;
  315. }
  316. /// <summary>
  317. /// Loads the contents of the stream into the TextView.
  318. /// </summary>
  319. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  320. /// <param name="stream">Stream to load the contents from.</param>
  321. public void LoadStream (Stream stream)
  322. {
  323. if (stream == null)
  324. throw new ArgumentNullException (nameof (stream));
  325. ResetPosition ();
  326. model.LoadStream(stream);
  327. SetNeedsDisplay ();
  328. }
  329. /// <summary>
  330. /// The current cursor row.
  331. /// </summary>
  332. public int CurrentRow => currentRow;
  333. /// <summary>
  334. /// Gets the cursor column.
  335. /// </summary>
  336. /// <value>The cursor column.</value>
  337. public int CurrentColumn => currentColumn;
  338. /// <summary>
  339. /// Positions the cursor on the current row and column
  340. /// </summary>
  341. public override void PositionCursor ()
  342. {
  343. if (selecting) {
  344. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow)-topRow, 0), Frame.Height);
  345. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  346. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  347. }
  348. Move (CurrentColumn - leftColumn, CurrentRow - topRow);
  349. }
  350. void ClearRegion (int left, int top, int right, int bottom)
  351. {
  352. for (int row = top; row < bottom; row++) {
  353. Move (left, row);
  354. for (int col = left; col < right; col++)
  355. AddRune (col, row, ' ');
  356. }
  357. }
  358. void ColorNormal ()
  359. {
  360. Driver.SetAttribute (ColorScheme.Normal);
  361. }
  362. void ColorSelection ()
  363. {
  364. if (HasFocus)
  365. Driver.SetAttribute (ColorScheme.Focus);
  366. else
  367. Driver.SetAttribute (ColorScheme.Normal);
  368. }
  369. bool isReadOnly = false;
  370. /// <summary>
  371. /// Indicates readonly attribute of TextView
  372. /// </summary>
  373. /// <value>Boolean value(Default false)</value>
  374. public bool ReadOnly {
  375. get => isReadOnly;
  376. set {
  377. isReadOnly = value;
  378. }
  379. }
  380. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  381. void GetEncodedRegionBounds (out long start, out long end)
  382. {
  383. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  384. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  385. if (selection > point) {
  386. start = point;
  387. end = selection;
  388. } else {
  389. start = selection;
  390. end = point;
  391. }
  392. }
  393. bool PointInSelection (int col, int row)
  394. {
  395. long start, end;
  396. GetEncodedRegionBounds (out start, out end);
  397. var q = ((long)(uint)row << 32) | (uint)col;
  398. return q >= start && q <= end;
  399. }
  400. //
  401. // Returns a ustring with the text in the selected
  402. // region.
  403. //
  404. ustring GetRegion ()
  405. {
  406. long start, end;
  407. GetEncodedRegionBounds (out start, out end);
  408. int startRow = (int)(start >> 32);
  409. var maxrow = ((int)(end >> 32));
  410. int startCol = (int)(start & 0xffffffff);
  411. var endCol = (int)(end & 0xffffffff);
  412. var line = model.GetLine (startRow);
  413. if (startRow == maxrow)
  414. return StringFromRunes (line.GetRange (startCol, endCol));
  415. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  416. for (int row = startRow+1; row < maxrow; row++) {
  417. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  418. }
  419. line = model.GetLine (maxrow);
  420. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  421. return res;
  422. }
  423. //
  424. // Clears the contents of the selected region
  425. //
  426. void ClearRegion ()
  427. {
  428. long start, end;
  429. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  430. GetEncodedRegionBounds (out start, out end);
  431. int startRow = (int)(start >> 32);
  432. var maxrow = ((int)(end >> 32));
  433. int startCol = (int)(start & 0xffffffff);
  434. var endCol = (int)(end & 0xffffffff);
  435. var line = model.GetLine (startRow);
  436. if (startRow == maxrow) {
  437. line.RemoveRange (startCol, endCol - startCol);
  438. currentColumn = startCol;
  439. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  440. return;
  441. }
  442. line.RemoveRange (startCol, line.Count - startCol);
  443. var line2 = model.GetLine (maxrow);
  444. line.AddRange (line2.Skip (endCol));
  445. for (int row = startRow + 1; row <= maxrow; row++) {
  446. model.RemoveLine (startRow+1);
  447. }
  448. if (currentEncoded == end) {
  449. currentRow -= maxrow - (startRow);
  450. }
  451. currentColumn = startCol;
  452. SetNeedsDisplay ();
  453. }
  454. /// <summary>
  455. /// Redraw the text editor region
  456. /// </summary>
  457. /// <param name="region">The region to redraw.</param>
  458. public override void Redraw (Rect region)
  459. {
  460. ColorNormal ();
  461. int bottom = region.Bottom;
  462. int right = region.Right;
  463. for (int row = region.Top; row < bottom; row++)
  464. {
  465. int textLine = topRow + row;
  466. if (textLine >= model.Count)
  467. {
  468. ColorNormal ();
  469. ClearRegion (region.Left, row, region.Right, row + 1);
  470. continue;
  471. }
  472. var line = model.GetLine (textLine);
  473. int lineRuneCount = line.Count;
  474. if (line.Count < region.Left)
  475. {
  476. ClearRegion (region.Left, row, region.Right, row + 1);
  477. continue;
  478. }
  479. Move (region.Left, row);
  480. for (int col = region.Left; col < right; col++)
  481. {
  482. var lineCol = leftColumn + col;
  483. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  484. if (selecting && PointInSelection (col, row))
  485. ColorSelection ();
  486. else
  487. ColorNormal ();
  488. AddRune (col, row, rune);
  489. }
  490. }
  491. PositionCursor ();
  492. }
  493. ///<inheritdoc cref="CanFocus"/>
  494. public override bool CanFocus {
  495. get => true;
  496. set { base.CanFocus = value; }
  497. }
  498. void SetClipboard (ustring text)
  499. {
  500. Clipboard.Contents = text;
  501. }
  502. void AppendClipboard (ustring text)
  503. {
  504. Clipboard.Contents = Clipboard.Contents + text;
  505. }
  506. void Insert (Rune rune)
  507. {
  508. var line = GetCurrentLine ();
  509. line.Insert (currentColumn, rune);
  510. var prow = currentRow - topRow;
  511. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  512. }
  513. ustring StringFromRunes (List<Rune> runes)
  514. {
  515. if (runes == null)
  516. throw new ArgumentNullException (nameof (runes));
  517. int size = 0;
  518. foreach (var rune in runes) {
  519. size += Utf8.RuneLen (rune);
  520. }
  521. var encoded = new byte [size];
  522. int offset = 0;
  523. foreach (var rune in runes) {
  524. offset += Utf8.EncodeRune (rune, encoded, offset);
  525. }
  526. return ustring.Make (encoded);
  527. }
  528. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  529. void InsertText (ustring text)
  530. {
  531. var lines = TextModel.StringToRunes (text);
  532. if (lines.Count == 0)
  533. return;
  534. var line = GetCurrentLine ();
  535. // Optmize single line
  536. if (lines.Count == 1) {
  537. line.InsertRange (currentColumn, lines [0]);
  538. currentColumn += lines [0].Count;
  539. if (currentColumn - leftColumn > Frame.Width)
  540. leftColumn = currentColumn - Frame.Width + 1;
  541. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  542. return;
  543. }
  544. // Keep a copy of the rest of the line
  545. var restCount = line.Count - currentColumn;
  546. var rest = line.GetRange (currentColumn, restCount);
  547. line.RemoveRange (currentColumn, restCount);
  548. // First line is inserted at the current location, the rest is appended
  549. line.InsertRange (currentColumn, lines [0]);
  550. for (int i = 1; i < lines.Count; i++)
  551. model.AddLine (currentRow + i, lines [i]);
  552. var last = model.GetLine (currentRow + lines.Count-1);
  553. var lastp = last.Count;
  554. last.InsertRange (last.Count, rest);
  555. // Now adjjust column and row positions
  556. currentRow += lines.Count-1;
  557. currentColumn = lastp;
  558. if (currentRow - topRow > Frame.Height) {
  559. topRow = currentRow - Frame.Height + 1;
  560. if (topRow < 0)
  561. topRow = 0;
  562. }
  563. if (currentColumn < leftColumn)
  564. leftColumn = currentColumn;
  565. if (currentColumn-leftColumn >= Frame.Width)
  566. leftColumn = currentColumn - Frame.Width + 1;
  567. SetNeedsDisplay ();
  568. }
  569. // The column we are tracking, or -1 if we are not tracking any column
  570. int columnTrack = -1;
  571. // Tries to snap the cursor to the tracking column
  572. void TrackColumn ()
  573. {
  574. // Now track the column
  575. var line = GetCurrentLine ();
  576. if (line.Count < columnTrack)
  577. currentColumn = line.Count;
  578. else if (columnTrack != -1)
  579. currentColumn = columnTrack;
  580. else if (currentColumn > line.Count)
  581. currentColumn = line.Count;
  582. Adjust ();
  583. }
  584. void Adjust ()
  585. {
  586. bool need = false;
  587. if (currentColumn < leftColumn) {
  588. currentColumn = leftColumn;
  589. need = true;
  590. }
  591. if (currentColumn - leftColumn > Frame.Width) {
  592. leftColumn = currentColumn - Frame.Width + 1;
  593. need = true;
  594. }
  595. if (currentRow < topRow) {
  596. topRow = currentRow;
  597. need = true;
  598. }
  599. if (currentRow - topRow > Frame.Height) {
  600. topRow = currentRow - Frame.Height + 1;
  601. need = true;
  602. }
  603. if (need)
  604. SetNeedsDisplay ();
  605. else
  606. PositionCursor ();
  607. }
  608. /// <summary>
  609. /// Will scroll the view to display the specified row at the top
  610. /// </summary>
  611. /// <param name="row">Row that should be displayed at the top, if the value is negative it will be reset to zero</param>
  612. public void ScrollTo (int row)
  613. {
  614. if (row < 0)
  615. row = 0;
  616. topRow = row > model.Count ? model.Count - 1 : row;
  617. SetNeedsDisplay ();
  618. }
  619. bool lastWasKill;
  620. ///<inheritdoc cref="ProcessKey"/>
  621. public override bool ProcessKey (KeyEvent kb)
  622. {
  623. int restCount;
  624. List<Rune> rest;
  625. // Handle some state here - whether the last command was a kill
  626. // operation and the column tracking (up/down)
  627. switch (kb.Key) {
  628. case Key.ControlN:
  629. case Key.CursorDown:
  630. case Key.ControlP:
  631. case Key.CursorUp:
  632. lastWasKill = false;
  633. break;
  634. case Key.ControlK:
  635. break;
  636. default:
  637. lastWasKill = false;
  638. columnTrack = -1;
  639. break;
  640. }
  641. // Dispatch the command.
  642. switch (kb.Key) {
  643. case Key.PageDown:
  644. case Key.ControlV:
  645. int nPageDnShift = Frame.Height - 1;
  646. if (currentRow < model.Count) {
  647. if (columnTrack == -1)
  648. columnTrack = currentColumn;
  649. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  650. if (topRow < currentRow - nPageDnShift) {
  651. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  652. SetNeedsDisplay ();
  653. }
  654. TrackColumn ();
  655. PositionCursor ();
  656. }
  657. break;
  658. case Key.PageUp:
  659. case ((int)'v' + Key.AltMask):
  660. int nPageUpShift = Frame.Height - 1;
  661. if (currentRow > 0) {
  662. if (columnTrack == -1)
  663. columnTrack = currentColumn;
  664. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  665. if (currentRow < topRow) {
  666. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  667. SetNeedsDisplay ();
  668. }
  669. TrackColumn ();
  670. PositionCursor ();
  671. }
  672. break;
  673. case Key.ControlN:
  674. case Key.CursorDown:
  675. if (currentRow + 1 < model.Count) {
  676. if (columnTrack == -1)
  677. columnTrack = currentColumn;
  678. currentRow++;
  679. if (currentRow >= topRow + Frame.Height) {
  680. topRow++;
  681. SetNeedsDisplay ();
  682. }
  683. TrackColumn ();
  684. PositionCursor ();
  685. }
  686. break;
  687. case Key.ControlP:
  688. case Key.CursorUp:
  689. if (currentRow > 0) {
  690. if (columnTrack == -1)
  691. columnTrack = currentColumn;
  692. currentRow--;
  693. if (currentRow < topRow) {
  694. topRow--;
  695. SetNeedsDisplay ();
  696. }
  697. TrackColumn ();
  698. PositionCursor ();
  699. }
  700. break;
  701. case Key.ControlF:
  702. case Key.CursorRight:
  703. var currentLine = GetCurrentLine ();
  704. if (currentColumn < currentLine.Count) {
  705. currentColumn++;
  706. if (currentColumn >= leftColumn + Frame.Width) {
  707. leftColumn++;
  708. SetNeedsDisplay ();
  709. }
  710. PositionCursor ();
  711. } else {
  712. if (currentRow + 1 < model.Count) {
  713. currentRow++;
  714. currentColumn = 0;
  715. leftColumn = 0;
  716. if (currentRow >= topRow + Frame.Height) {
  717. topRow++;
  718. }
  719. SetNeedsDisplay ();
  720. PositionCursor ();
  721. }
  722. break;
  723. }
  724. break;
  725. case Key.ControlB:
  726. case Key.CursorLeft:
  727. if (currentColumn > 0) {
  728. currentColumn--;
  729. if (currentColumn < leftColumn) {
  730. leftColumn--;
  731. SetNeedsDisplay ();
  732. }
  733. PositionCursor ();
  734. } else {
  735. if (currentRow > 0) {
  736. currentRow--;
  737. if (currentRow < topRow) {
  738. topRow--;
  739. SetNeedsDisplay ();
  740. }
  741. currentLine = GetCurrentLine ();
  742. currentColumn = currentLine.Count;
  743. int prev = leftColumn;
  744. leftColumn = currentColumn - Frame.Width + 1;
  745. if (leftColumn < 0)
  746. leftColumn = 0;
  747. if (prev != leftColumn)
  748. SetNeedsDisplay ();
  749. PositionCursor ();
  750. }
  751. }
  752. break;
  753. case Key.Delete:
  754. case Key.Backspace:
  755. if (isReadOnly)
  756. break;
  757. if (currentColumn > 0) {
  758. // Delete backwards
  759. currentLine = GetCurrentLine ();
  760. currentLine.RemoveAt (currentColumn - 1);
  761. currentColumn--;
  762. if (currentColumn < leftColumn) {
  763. leftColumn--;
  764. SetNeedsDisplay ();
  765. } else
  766. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  767. } else {
  768. // Merges the current line with the previous one.
  769. if (currentRow == 0)
  770. return true;
  771. var prowIdx = currentRow - 1;
  772. var prevRow = model.GetLine (prowIdx);
  773. var prevCount = prevRow.Count;
  774. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  775. model.RemoveLine (currentRow);
  776. currentRow--;
  777. currentColumn = prevCount;
  778. leftColumn = currentColumn - Frame.Width + 1;
  779. if (leftColumn < 0)
  780. leftColumn = 0;
  781. SetNeedsDisplay ();
  782. }
  783. break;
  784. // Home, C-A
  785. case Key.Home:
  786. case Key.ControlA:
  787. currentColumn = 0;
  788. if (currentColumn < leftColumn) {
  789. leftColumn = 0;
  790. SetNeedsDisplay ();
  791. } else
  792. PositionCursor ();
  793. break;
  794. case Key.DeleteChar:
  795. case Key.ControlD: // Delete
  796. if (isReadOnly)
  797. break;
  798. currentLine = GetCurrentLine ();
  799. if (currentColumn == currentLine.Count) {
  800. if (currentRow + 1 == model.Count)
  801. break;
  802. var nextLine = model.GetLine (currentRow + 1);
  803. currentLine.AddRange (nextLine);
  804. model.RemoveLine (currentRow + 1);
  805. var sr = currentRow - topRow;
  806. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  807. } else {
  808. currentLine.RemoveAt (currentColumn);
  809. var r = currentRow - topRow;
  810. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  811. }
  812. break;
  813. case Key.End:
  814. case Key.ControlE: // End
  815. currentLine = GetCurrentLine ();
  816. currentColumn = currentLine.Count;
  817. int pcol = leftColumn;
  818. leftColumn = currentColumn - Frame.Width + 1;
  819. if (leftColumn < 0)
  820. leftColumn = 0;
  821. if (pcol != leftColumn)
  822. SetNeedsDisplay ();
  823. PositionCursor ();
  824. break;
  825. case Key.ControlK: // kill-to-end
  826. if (isReadOnly)
  827. break;
  828. currentLine = GetCurrentLine ();
  829. if (currentLine.Count == 0) {
  830. model.RemoveLine (currentRow);
  831. var val = ustring.Make ((Rune)'\n');
  832. if (lastWasKill)
  833. AppendClipboard (val);
  834. else
  835. SetClipboard (val);
  836. } else {
  837. restCount = currentLine.Count - currentColumn;
  838. rest = currentLine.GetRange (currentColumn, restCount);
  839. var val = StringFromRunes (rest);
  840. if (lastWasKill)
  841. AppendClipboard (val);
  842. else
  843. SetClipboard (val);
  844. currentLine.RemoveRange (currentColumn, restCount);
  845. }
  846. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  847. lastWasKill = true;
  848. break;
  849. case Key.ControlY: // Control-y, yank
  850. if (isReadOnly)
  851. break;
  852. InsertText (Clipboard.Contents);
  853. selecting = false;
  854. break;
  855. case Key.ControlSpace:
  856. selecting = true;
  857. selectionStartColumn = currentColumn;
  858. selectionStartRow = currentRow;
  859. break;
  860. case ((int)'w' + Key.AltMask):
  861. SetClipboard (GetRegion ());
  862. selecting = false;
  863. break;
  864. case Key.ControlW:
  865. SetClipboard (GetRegion ());
  866. if (!isReadOnly)
  867. ClearRegion ();
  868. selecting = false;
  869. break;
  870. case (Key)((int)'b' + Key.AltMask):
  871. var newPos = WordBackward (currentColumn, currentRow);
  872. if (newPos.HasValue) {
  873. currentColumn = newPos.Value.col;
  874. currentRow = newPos.Value.row;
  875. }
  876. Adjust ();
  877. break;
  878. case (Key)((int)'f' + Key.AltMask):
  879. newPos = WordForward (currentColumn, currentRow);
  880. if (newPos.HasValue) {
  881. currentColumn = newPos.Value.col;
  882. currentRow = newPos.Value.row;
  883. }
  884. Adjust ();
  885. break;
  886. case Key.Enter:
  887. if (isReadOnly)
  888. break;
  889. var orow = currentRow;
  890. currentLine = GetCurrentLine ();
  891. restCount = currentLine.Count - currentColumn;
  892. rest = currentLine.GetRange (currentColumn, restCount);
  893. currentLine.RemoveRange (currentColumn, restCount);
  894. model.AddLine (currentRow + 1, rest);
  895. currentRow++;
  896. bool fullNeedsDisplay = false;
  897. if (currentRow >= topRow + Frame.Height) {
  898. topRow++;
  899. fullNeedsDisplay = true;
  900. }
  901. currentColumn = 0;
  902. if (currentColumn < leftColumn) {
  903. fullNeedsDisplay = true;
  904. leftColumn = 0;
  905. }
  906. if (fullNeedsDisplay)
  907. SetNeedsDisplay ();
  908. else
  909. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  910. break;
  911. default:
  912. // Ignore control characters and other special keys
  913. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  914. return false;
  915. //So that special keys like tab can be processed
  916. if (isReadOnly)
  917. return true;
  918. Insert ((uint)kb.Key);
  919. currentColumn++;
  920. if (currentColumn >= leftColumn + Frame.Width) {
  921. leftColumn++;
  922. SetNeedsDisplay ();
  923. }
  924. PositionCursor ();
  925. return true;
  926. }
  927. return true;
  928. }
  929. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  930. {
  931. if (col < 0 || row < 0)
  932. yield break;
  933. if (row >= model.Count)
  934. yield break;
  935. var line = GetCurrentLine ();
  936. if (col >= line.Count)
  937. yield break;
  938. while (row < model.Count) {
  939. for (int c = col; c < line.Count; c++) {
  940. yield return (c, row, line [c]);
  941. }
  942. col = 0;
  943. row++;
  944. line = GetCurrentLine ();
  945. }
  946. }
  947. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  948. bool MoveNext (ref int col, ref int row, out Rune rune)
  949. {
  950. var line = model.GetLine (row);
  951. if (col + 1 < line.Count) {
  952. col++;
  953. rune = line [col];
  954. return true;
  955. }
  956. while (row + 1 < model.Count){
  957. col = 0;
  958. row++;
  959. line = model.GetLine (row);
  960. if (line.Count > 0) {
  961. rune = line [0];
  962. return true;
  963. }
  964. }
  965. rune = 0;
  966. return false;
  967. }
  968. bool MovePrev (ref int col, ref int row, out Rune rune)
  969. {
  970. var line = model.GetLine (row);
  971. if (col > 0) {
  972. col--;
  973. rune = line [col];
  974. return true;
  975. }
  976. if (row == 0) {
  977. rune = 0;
  978. return false;
  979. }
  980. while (row > 0) {
  981. row--;
  982. line = model.GetLine (row);
  983. col = line.Count - 1;
  984. if (col >= 0) {
  985. rune = line [col];
  986. return true;
  987. }
  988. }
  989. rune = 0;
  990. return false;
  991. }
  992. (int col, int row)? WordForward (int fromCol, int fromRow)
  993. {
  994. var col = fromCol;
  995. var row = fromRow;
  996. var line = GetCurrentLine ();
  997. var rune = RuneAt (col, row);
  998. var srow = row;
  999. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1000. while (MoveNext (ref col, ref row, out rune)){
  1001. if (Rune.IsLetterOrDigit (rune))
  1002. break;
  1003. }
  1004. while (MoveNext (ref col, ref row, out rune)) {
  1005. if (!Rune.IsLetterOrDigit (rune))
  1006. break;
  1007. }
  1008. } else {
  1009. while (MoveNext (ref col, ref row, out rune)) {
  1010. if (!Rune.IsLetterOrDigit (rune))
  1011. break;
  1012. }
  1013. }
  1014. if (fromCol != col || fromRow != row)
  1015. return (col, row);
  1016. return null;
  1017. }
  1018. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1019. {
  1020. if (fromRow == 0 && fromCol == 0)
  1021. return null;
  1022. var col = fromCol;
  1023. var row = fromRow;
  1024. var line = GetCurrentLine ();
  1025. var rune = RuneAt (col, row);
  1026. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1027. while (MovePrev (ref col, ref row, out rune)){
  1028. if (Rune.IsLetterOrDigit (rune))
  1029. break;
  1030. }
  1031. while (MovePrev (ref col, ref row, out rune)){
  1032. if (!Rune.IsLetterOrDigit (rune))
  1033. break;
  1034. }
  1035. } else {
  1036. while (MovePrev (ref col, ref row, out rune)) {
  1037. if (!Rune.IsLetterOrDigit (rune))
  1038. break;
  1039. }
  1040. }
  1041. if (fromCol != col || fromRow != row)
  1042. return (col, row);
  1043. return null;
  1044. }
  1045. ///<inheritdoc cref="MouseEvent"/>
  1046. public override bool MouseEvent (MouseEvent ev)
  1047. {
  1048. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1049. return false;
  1050. }
  1051. if (!HasFocus)
  1052. SuperView.SetFocus (this);
  1053. if (model.Count > 0) {
  1054. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1055. if (ev.Y > maxCursorPositionableLine) {
  1056. currentRow = maxCursorPositionableLine;
  1057. } else {
  1058. currentRow = ev.Y + topRow;
  1059. }
  1060. var r = GetCurrentLine ();
  1061. if (ev.X - leftColumn >= r.Count)
  1062. currentColumn = r.Count - leftColumn;
  1063. else
  1064. currentColumn = ev.X - leftColumn;
  1065. }
  1066. PositionCursor ();
  1067. return true;
  1068. }
  1069. }
  1070. }