TextView.cs 27 KB

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