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. /// <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. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  365. void GetEncodedRegionBounds (out long start, out long end)
  366. {
  367. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  368. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  369. if (selection > point) {
  370. start = point;
  371. end = selection;
  372. } else {
  373. start = selection;
  374. end = point;
  375. }
  376. }
  377. bool PointInSelection (int col, int row)
  378. {
  379. long start, end;
  380. GetEncodedRegionBounds (out start, out end);
  381. var q = ((long)(uint)row << 32) | (uint)col;
  382. return q >= start && q <= end;
  383. }
  384. //
  385. // Returns a ustring with the text in the selected
  386. // region.
  387. //
  388. ustring GetRegion ()
  389. {
  390. long start, end;
  391. GetEncodedRegionBounds (out start, out end);
  392. int startRow = (int)(start >> 32);
  393. var maxrow = ((int)(end >> 32));
  394. int startCol = (int)(start & 0xffffffff);
  395. var endCol = (int)(end & 0xffffffff);
  396. var line = model.GetLine (startRow);
  397. if (startRow == maxrow)
  398. return StringFromRunes (line.GetRange (startCol, endCol));
  399. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  400. for (int row = startRow+1; row < maxrow; row++) {
  401. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  402. }
  403. line = model.GetLine (maxrow);
  404. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  405. return res;
  406. }
  407. //
  408. // Clears the contents of the selected region
  409. //
  410. void ClearRegion ()
  411. {
  412. long start, end;
  413. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  414. GetEncodedRegionBounds (out start, out end);
  415. int startRow = (int)(start >> 32);
  416. var maxrow = ((int)(end >> 32));
  417. int startCol = (int)(start & 0xffffffff);
  418. var endCol = (int)(end & 0xffffffff);
  419. var line = model.GetLine (startRow);
  420. if (startRow == maxrow) {
  421. line.RemoveRange (startCol, endCol - startCol);
  422. currentColumn = startCol;
  423. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  424. return;
  425. }
  426. line.RemoveRange (startCol, line.Count - startCol);
  427. var line2 = model.GetLine (maxrow);
  428. line.AddRange (line2.Skip (endCol));
  429. for (int row = startRow + 1; row <= maxrow; row++) {
  430. model.RemoveLine (startRow+1);
  431. }
  432. if (currentEncoded == end) {
  433. currentRow -= maxrow - (startRow);
  434. }
  435. currentColumn = startCol;
  436. SetNeedsDisplay ();
  437. }
  438. /// <summary>
  439. /// Redraw the text editor region
  440. /// </summary>
  441. /// <param name="region">The region to redraw.</param>
  442. public override void Redraw (Rect region)
  443. {
  444. ColorNormal ();
  445. int bottom = region.Bottom;
  446. int right = region.Right;
  447. for (int row = region.Top; row < bottom; row++) {
  448. int textLine = topRow + row;
  449. if (textLine >= model.Count) {
  450. ColorNormal ();
  451. ClearRegion (region.Left, row, region.Right, row + 1);
  452. continue;
  453. }
  454. var line = model.GetLine (textLine);
  455. int lineRuneCount = line.Count;
  456. if (line.Count < region.Left){
  457. ClearRegion (region.Left, row, region.Right, row + 1);
  458. continue;
  459. }
  460. Move (region.Left, row);
  461. for (int col = region.Left; col < right; col++) {
  462. var lineCol = leftColumn + col;
  463. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  464. if (selecting && PointInSelection (col, row))
  465. ColorSelection ();
  466. else
  467. ColorNormal ();
  468. AddRune (col, row, rune);
  469. }
  470. }
  471. PositionCursor ();
  472. }
  473. public override bool CanFocus {
  474. get => true;
  475. set { base.CanFocus = value; }
  476. }
  477. void SetClipboard (ustring text)
  478. {
  479. Clipboard.Contents = text;
  480. }
  481. void AppendClipboard (ustring text)
  482. {
  483. Clipboard.Contents = Clipboard.Contents + text;
  484. }
  485. void Insert (Rune rune)
  486. {
  487. var line = GetCurrentLine ();
  488. line.Insert (currentColumn, rune);
  489. var prow = currentRow - topRow;
  490. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  491. }
  492. ustring StringFromRunes (List<Rune> runes)
  493. {
  494. if (runes == null)
  495. throw new ArgumentNullException (nameof (runes));
  496. int size = 0;
  497. foreach (var rune in runes) {
  498. size += Utf8.RuneLen (rune);
  499. }
  500. var encoded = new byte [size];
  501. int offset = 0;
  502. foreach (var rune in runes) {
  503. offset += Utf8.EncodeRune (rune, encoded, offset);
  504. }
  505. return ustring.Make (encoded);
  506. }
  507. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  508. void InsertText (ustring text)
  509. {
  510. var lines = TextModel.StringToRunes (text);
  511. if (lines.Count == 0)
  512. return;
  513. var line = GetCurrentLine ();
  514. // Optmize single line
  515. if (lines.Count == 1) {
  516. line.InsertRange (currentColumn, lines [0]);
  517. currentColumn += lines [0].Count;
  518. if (currentColumn - leftColumn > Frame.Width)
  519. leftColumn = currentColumn - Frame.Width + 1;
  520. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  521. return;
  522. }
  523. // Keep a copy of the rest of the line
  524. var restCount = line.Count - currentColumn;
  525. var rest = line.GetRange (currentColumn, restCount);
  526. line.RemoveRange (currentColumn, restCount);
  527. // First line is inserted at the current location, the rest is appended
  528. line.InsertRange (currentColumn, lines [0]);
  529. for (int i = 1; i < lines.Count; i++)
  530. model.AddLine (currentRow + i, lines [i]);
  531. var last = model.GetLine (currentRow + lines.Count-1);
  532. var lastp = last.Count;
  533. last.InsertRange (last.Count, rest);
  534. // Now adjjust column and row positions
  535. currentRow += lines.Count-1;
  536. currentColumn = lastp;
  537. if (currentRow - topRow > Frame.Height) {
  538. topRow = currentRow - Frame.Height + 1;
  539. if (topRow < 0)
  540. topRow = 0;
  541. }
  542. if (currentColumn < leftColumn)
  543. leftColumn = currentColumn;
  544. if (currentColumn-leftColumn >= Frame.Width)
  545. leftColumn = currentColumn - Frame.Width + 1;
  546. SetNeedsDisplay ();
  547. }
  548. // The column we are tracking, or -1 if we are not tracking any column
  549. int columnTrack = -1;
  550. // Tries to snap the cursor to the tracking column
  551. void TrackColumn ()
  552. {
  553. // Now track the column
  554. var line = GetCurrentLine ();
  555. if (line.Count < columnTrack)
  556. currentColumn = line.Count;
  557. else if (columnTrack != -1)
  558. currentColumn = columnTrack;
  559. else if (currentColumn > line.Count)
  560. currentColumn = line.Count;
  561. Adjust ();
  562. }
  563. void Adjust ()
  564. {
  565. bool need = false;
  566. if (currentColumn < leftColumn) {
  567. currentColumn = leftColumn;
  568. need = true;
  569. }
  570. if (currentColumn - leftColumn > Frame.Width) {
  571. leftColumn = currentColumn - Frame.Width + 1;
  572. need = true;
  573. }
  574. if (currentRow < topRow) {
  575. topRow = currentRow;
  576. need = true;
  577. }
  578. if (currentRow - topRow > Frame.Height) {
  579. topRow = currentRow - Frame.Height + 1;
  580. need = true;
  581. }
  582. if (need)
  583. SetNeedsDisplay ();
  584. else
  585. PositionCursor ();
  586. }
  587. bool lastWasKill;
  588. public override bool ProcessKey (KeyEvent kb)
  589. {
  590. int restCount;
  591. List<Rune> rest;
  592. // Handle some state here - whether the last command was a kill
  593. // operation and the column tracking (up/down)
  594. switch (kb.Key) {
  595. case Key.ControlN:
  596. case Key.CursorDown:
  597. case Key.ControlP:
  598. case Key.CursorUp:
  599. lastWasKill = false;
  600. break;
  601. case Key.ControlK:
  602. break;
  603. default:
  604. lastWasKill = false;
  605. columnTrack = -1;
  606. break;
  607. }
  608. // Dispatch the command.
  609. switch (kb.Key) {
  610. case Key.ControlN:
  611. case Key.CursorDown:
  612. if (currentRow + 1 < model.Count) {
  613. if (columnTrack == -1)
  614. columnTrack = currentColumn;
  615. currentRow++;
  616. if (currentRow >= topRow + Frame.Height) {
  617. topRow++;
  618. SetNeedsDisplay ();
  619. }
  620. TrackColumn ();
  621. PositionCursor ();
  622. }
  623. break;
  624. case Key.ControlP:
  625. case Key.CursorUp:
  626. if (currentRow > 0) {
  627. if (columnTrack == -1)
  628. columnTrack = currentColumn;
  629. currentRow--;
  630. if (currentRow < topRow) {
  631. topRow--;
  632. SetNeedsDisplay ();
  633. }
  634. TrackColumn ();
  635. PositionCursor ();
  636. }
  637. break;
  638. case Key.ControlF:
  639. case Key.CursorRight:
  640. var currentLine = GetCurrentLine ();
  641. if (currentColumn < currentLine.Count) {
  642. currentColumn++;
  643. if (currentColumn >= leftColumn + Frame.Width) {
  644. leftColumn++;
  645. SetNeedsDisplay ();
  646. }
  647. PositionCursor ();
  648. } else {
  649. if (currentRow + 1 < model.Count) {
  650. currentRow++;
  651. currentColumn = 0;
  652. leftColumn = 0;
  653. if (currentRow >= topRow + Frame.Height) {
  654. topRow++;
  655. }
  656. SetNeedsDisplay ();
  657. PositionCursor ();
  658. }
  659. break;
  660. }
  661. break;
  662. case Key.ControlB:
  663. case Key.CursorLeft:
  664. if (currentColumn > 0) {
  665. currentColumn--;
  666. if (currentColumn < leftColumn) {
  667. leftColumn--;
  668. SetNeedsDisplay ();
  669. }
  670. PositionCursor ();
  671. } else {
  672. if (currentRow > 0) {
  673. currentRow--;
  674. if (currentRow < topRow) {
  675. topRow--;
  676. }
  677. currentLine = GetCurrentLine ();
  678. currentColumn = currentLine.Count;
  679. int prev = leftColumn;
  680. leftColumn = currentColumn - Frame.Width + 1;
  681. if (leftColumn < 0)
  682. leftColumn = 0;
  683. if (prev != leftColumn)
  684. SetNeedsDisplay ();
  685. PositionCursor ();
  686. }
  687. }
  688. break;
  689. case Key.Delete:
  690. case Key.Backspace:
  691. if (currentColumn > 0) {
  692. // Delete backwards
  693. currentLine = GetCurrentLine ();
  694. currentLine.RemoveAt (currentColumn - 1);
  695. currentColumn--;
  696. if (currentColumn < leftColumn) {
  697. leftColumn--;
  698. SetNeedsDisplay ();
  699. } else
  700. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  701. } else {
  702. // Merges the current line with the previous one.
  703. if (currentRow == 0)
  704. return true;
  705. var prowIdx = currentRow - 1;
  706. var prevRow = model.GetLine (prowIdx);
  707. var prevCount = prevRow.Count;
  708. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  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. }