TextView.cs 27 KB

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