TextView.cs 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // Attributed text on spans
  10. // Replace insertion with Insert method
  11. // String accumulation (Control-k, control-k is not preserving the last new line, see StringToRunes
  12. // Alt-D, Alt-Backspace
  13. // API to set the cursor position
  14. // API to scroll to a particular place
  15. // keybindings to go to top/bottom
  16. // public API to insert, remove ranges
  17. // Add word forward/word backwards commands
  18. // Save buffer API
  19. // Mouse
  20. //
  21. // Desirable:
  22. // Move all the text manipulation into the TextModel
  23. using System;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Text;
  28. using NStack;
  29. namespace Terminal.Gui {
  30. class TextModel {
  31. List<List<Rune>> lines;
  32. public bool LoadFile (string file)
  33. {
  34. if (file == null)
  35. throw new ArgumentNullException (nameof (file));
  36. try {
  37. var stream = File.OpenRead (file);
  38. } catch {
  39. return false;
  40. }
  41. LoadStream (File.OpenRead (file));
  42. return true;
  43. }
  44. // Turns the ustring into runes, this does not split the
  45. // contents on a newline if it is present.
  46. static List<Rune> ToRunes (ustring str)
  47. {
  48. List<Rune> runes = new List<Rune> ();
  49. foreach (var x in str.ToRunes ()) {
  50. runes.Add (x);
  51. }
  52. return runes;
  53. }
  54. // Splits a string into a List that contains a List<Rune> for each line
  55. public static List<List<Rune>> StringToRunes (ustring content)
  56. {
  57. var lines = new List<List<Rune>> ();
  58. int start = 0, i = 0;
  59. for (; i < content.Length; i++) {
  60. if (content [i] == 10) {
  61. if (i - start > 0)
  62. lines.Add (ToRunes (content [start, i]));
  63. else
  64. lines.Add (ToRunes (ustring.Empty));
  65. start = i + 1;
  66. }
  67. }
  68. if (i - start >= 0)
  69. lines.Add (ToRunes (content [start, null]));
  70. return lines;
  71. }
  72. void Append (List<byte> line)
  73. {
  74. var str = ustring.Make (line.ToArray ());
  75. lines.Add (ToRunes (str));
  76. }
  77. public void LoadStream (Stream input)
  78. {
  79. if (input == null)
  80. throw new ArgumentNullException (nameof (input));
  81. lines = new List<List<Rune>> ();
  82. var buff = new BufferedStream (input);
  83. int v;
  84. var line = new List<byte> ();
  85. while ((v = buff.ReadByte ()) != -1) {
  86. if (v == 10) {
  87. Append (line);
  88. line.Clear ();
  89. continue;
  90. }
  91. line.Add ((byte)v);
  92. }
  93. if (line.Count > 0)
  94. Append (line);
  95. }
  96. public void LoadString (ustring content)
  97. {
  98. lines = StringToRunes (content);
  99. }
  100. public override string ToString ()
  101. {
  102. var sb = new StringBuilder ();
  103. foreach (var line in lines) {
  104. sb.Append (line);
  105. sb.AppendLine ();
  106. }
  107. return sb.ToString ();
  108. }
  109. /// <summary>
  110. /// The number of text lines in the model
  111. /// </summary>
  112. public int Count => lines.Count;
  113. /// <summary>
  114. /// Returns the specified line as a List of Rune
  115. /// </summary>
  116. /// <returns>The line.</returns>
  117. /// <param name="line">Line number to retrieve.</param>
  118. public List<Rune> GetLine (int line) => lines [line];
  119. /// <summary>
  120. /// Adds a line to the model at the specified position.
  121. /// </summary>
  122. /// <param name="pos">Line number where the line will be inserted.</param>
  123. /// <param name="runes">The line of text, as a List of Rune.</param>
  124. public void AddLine (int pos, List<Rune> runes)
  125. {
  126. lines.Insert (pos, runes);
  127. }
  128. /// <summary>
  129. /// Removes the line at the specified position
  130. /// </summary>
  131. /// <param name="pos">Position.</param>
  132. public void RemoveLine (int pos)
  133. {
  134. lines.RemoveAt (pos);
  135. }
  136. }
  137. /// <summary>
  138. /// Multi-line text editing view
  139. /// </summary>
  140. /// <remarks>
  141. /// <para>
  142. /// The text view provides a multi-line text view. Users interact
  143. /// with it with the standard Emacs commands for movement or the arrow
  144. /// keys.
  145. /// </para>
  146. /// <list type="table">
  147. /// <listheader>
  148. /// <term>Shortcut</term>
  149. /// <description>Action performed</description>
  150. /// </listheader>
  151. /// <item>
  152. /// <term>Left cursor, Control-b</term>
  153. /// <description>
  154. /// Moves the editing point left.
  155. /// </description>
  156. /// </item>
  157. /// <item>
  158. /// <term>Right cursor, Control-f</term>
  159. /// <description>
  160. /// Moves the editing point right.
  161. /// </description>
  162. /// </item>
  163. /// <item>
  164. /// <term>Alt-b</term>
  165. /// <description>
  166. /// Moves one word back.
  167. /// </description>
  168. /// </item>
  169. /// <item>
  170. /// <term>Alt-f</term>
  171. /// <description>
  172. /// Moves one word forward.
  173. /// </description>
  174. /// </item>
  175. /// <item>
  176. /// <term>Up cursor, Control-p</term>
  177. /// <description>
  178. /// Moves the editing point one line up.
  179. /// </description>
  180. /// </item>
  181. /// <item>
  182. /// <term>Down cursor, Control-n</term>
  183. /// <description>
  184. /// Moves the editing point one line down
  185. /// </description>
  186. /// </item>
  187. /// <item>
  188. /// <term>Home key, Control-a</term>
  189. /// <description>
  190. /// Moves the cursor to the beginning of the line.
  191. /// </description>
  192. /// </item>
  193. /// <item>
  194. /// <term>End key, Control-e</term>
  195. /// <description>
  196. /// Moves the cursor to the end of the line.
  197. /// </description>
  198. /// </item>
  199. /// <item>
  200. /// <term>Delete, Control-d</term>
  201. /// <description>
  202. /// Deletes the character in front of the cursor.
  203. /// </description>
  204. /// </item>
  205. /// <item>
  206. /// <term>Backspace</term>
  207. /// <description>
  208. /// Deletes the character behind the cursor.
  209. /// </description>
  210. /// </item>
  211. /// <item>
  212. /// <term>Control-k</term>
  213. /// <description>
  214. /// Deletes the text until the end of the line and replaces the kill buffer
  215. /// with the deleted text. You can paste this text in a different place by
  216. /// using Control-y.
  217. /// </description>
  218. /// </item>
  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. currentRow--;
  709. currentColumn = prevCount;
  710. leftColumn = currentColumn - Frame.Width + 1;
  711. if (leftColumn < 0)
  712. leftColumn = 0;
  713. SetNeedsDisplay ();
  714. }
  715. break;
  716. // Home, C-A
  717. case Key.Home:
  718. case Key.ControlA:
  719. currentColumn = 0;
  720. if (currentColumn < leftColumn) {
  721. leftColumn = 0;
  722. SetNeedsDisplay ();
  723. } else
  724. PositionCursor ();
  725. break;
  726. case Key.ControlD: // Delete
  727. currentLine = GetCurrentLine ();
  728. if (currentColumn == currentLine.Count) {
  729. if (currentRow + 1 == model.Count)
  730. break;
  731. var nextLine = model.GetLine (currentRow + 1);
  732. currentLine.AddRange (nextLine);
  733. model.RemoveLine (currentRow + 1);
  734. var sr = currentRow - topRow;
  735. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  736. } else {
  737. currentLine.RemoveAt (currentColumn);
  738. var r = currentRow - topRow;
  739. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  740. }
  741. break;
  742. case Key.ControlE: // End
  743. currentLine = GetCurrentLine ();
  744. currentColumn = currentLine.Count;
  745. int pcol = leftColumn;
  746. leftColumn = currentColumn - Frame.Width + 1;
  747. if (leftColumn < 0)
  748. leftColumn = 0;
  749. if (pcol != leftColumn)
  750. SetNeedsDisplay ();
  751. PositionCursor ();
  752. break;
  753. case Key.ControlK: // kill-to-end
  754. currentLine = GetCurrentLine ();
  755. if (currentLine.Count == 0) {
  756. model.RemoveLine (currentRow);
  757. var val = ustring.Make ((Rune)'\n');
  758. if (lastWasKill)
  759. AppendClipboard (val);
  760. else
  761. SetClipboard (val);
  762. } else {
  763. restCount = currentLine.Count - currentColumn;
  764. rest = currentLine.GetRange (currentColumn, restCount);
  765. var val = StringFromRunes (rest);
  766. if (lastWasKill)
  767. AppendClipboard (val);
  768. else
  769. SetClipboard (val);
  770. currentLine.RemoveRange (currentColumn, restCount);
  771. }
  772. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  773. lastWasKill = true;
  774. break;
  775. case Key.ControlY: // Control-y, yank
  776. InsertText (Clipboard.Contents);
  777. selecting = false;
  778. break;
  779. case Key.ControlSpace:
  780. selecting = true;
  781. selectionStartColumn = currentColumn;
  782. selectionStartRow = currentRow;
  783. break;
  784. case ((int)'w' + Key.AltMask):
  785. SetClipboard (GetRegion ());
  786. selecting = false;
  787. break;
  788. case Key.ControlW:
  789. SetClipboard (GetRegion ());
  790. ClearRegion ();
  791. selecting = false;
  792. break;
  793. case (Key)((int)'b' + Key.AltMask):
  794. var newPos = WordBackward (currentColumn, currentRow);
  795. if (newPos.HasValue) {
  796. currentColumn = newPos.Value.col;
  797. currentRow = newPos.Value.row;
  798. }
  799. Adjust ();
  800. break;
  801. case (Key)((int)'f' + Key.AltMask):
  802. newPos = WordForward (currentColumn, currentRow);
  803. if (newPos.HasValue) {
  804. currentColumn = newPos.Value.col;
  805. currentRow = newPos.Value.row;
  806. }
  807. Adjust ();
  808. break;
  809. case Key.Enter:
  810. var orow = currentRow;
  811. currentLine = GetCurrentLine ();
  812. restCount = currentLine.Count - currentColumn;
  813. rest = currentLine.GetRange (currentColumn, restCount);
  814. currentLine.RemoveRange (currentColumn, restCount);
  815. model.AddLine (currentRow + 1, rest);
  816. currentRow++;
  817. bool fullNeedsDisplay = false;
  818. if (currentRow >= topRow + Frame.Height) {
  819. topRow++;
  820. fullNeedsDisplay = true;
  821. }
  822. currentColumn = 0;
  823. if (currentColumn < leftColumn) {
  824. fullNeedsDisplay = true;
  825. leftColumn = 0;
  826. }
  827. if (fullNeedsDisplay)
  828. SetNeedsDisplay ();
  829. else
  830. SetNeedsDisplay (new Rect (0, currentRow - topRow, 0, Frame.Height));
  831. break;
  832. default:
  833. // Ignore control characters and other special keys
  834. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  835. return false;
  836. Insert ((uint)kb.Key);
  837. currentColumn++;
  838. if (currentColumn >= leftColumn + Frame.Width) {
  839. leftColumn++;
  840. SetNeedsDisplay ();
  841. }
  842. PositionCursor ();
  843. return true;
  844. }
  845. return true;
  846. }
  847. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  848. {
  849. if (col < 0 || row < 0)
  850. yield break;
  851. if (row >= model.Count)
  852. yield break;
  853. var line = GetCurrentLine ();
  854. if (col >= line.Count)
  855. yield break;
  856. while (row < model.Count) {
  857. for (int c = col; c < line.Count; c++) {
  858. yield return (c, row, line [c]);
  859. }
  860. col = 0;
  861. row++;
  862. line = GetCurrentLine ();
  863. }
  864. }
  865. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  866. bool MoveNext (ref int col, ref int row, out Rune rune)
  867. {
  868. var line = model.GetLine (row);
  869. if (col + 1 < line.Count) {
  870. col++;
  871. rune = line [col];
  872. return true;
  873. }
  874. while (row + 1 < model.Count){
  875. col = 0;
  876. row++;
  877. line = model.GetLine (row);
  878. if (line.Count > 0) {
  879. rune = line [0];
  880. return true;
  881. }
  882. }
  883. rune = 0;
  884. return false;
  885. }
  886. bool MovePrev (ref int col, ref int row, out Rune rune)
  887. {
  888. var line = model.GetLine (row);
  889. if (col > 0) {
  890. col--;
  891. rune = line [col];
  892. return true;
  893. }
  894. if (row == 0) {
  895. rune = 0;
  896. return false;
  897. }
  898. while (row > 0) {
  899. row--;
  900. line = model.GetLine (row);
  901. col = line.Count - 1;
  902. if (col >= 0) {
  903. rune = line [col];
  904. return true;
  905. }
  906. }
  907. rune = 0;
  908. return false;
  909. }
  910. (int col, int row)? WordForward (int fromCol, int fromRow)
  911. {
  912. var col = fromCol;
  913. var row = fromRow;
  914. var line = GetCurrentLine ();
  915. var rune = RuneAt (col, row);
  916. var srow = row;
  917. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  918. while (MoveNext (ref col, ref row, out rune)){
  919. if (Rune.IsLetterOrDigit (rune))
  920. break;
  921. }
  922. while (MoveNext (ref col, ref row, out rune)) {
  923. if (!Rune.IsLetterOrDigit (rune))
  924. break;
  925. }
  926. } else {
  927. while (MoveNext (ref col, ref row, out rune)) {
  928. if (!Rune.IsLetterOrDigit (rune))
  929. break;
  930. }
  931. }
  932. if (fromCol != col || fromRow != row)
  933. return (col, row);
  934. return null;
  935. }
  936. (int col, int row)? WordBackward (int fromCol, int fromRow)
  937. {
  938. if (fromRow == 0 && fromCol == 0)
  939. return null;
  940. var col = fromCol;
  941. var row = fromRow;
  942. var line = GetCurrentLine ();
  943. var rune = RuneAt (col, row);
  944. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  945. while (MovePrev (ref col, ref row, out rune)){
  946. if (Rune.IsLetterOrDigit (rune))
  947. break;
  948. }
  949. while (MovePrev (ref col, ref row, out rune)){
  950. if (!Rune.IsLetterOrDigit (rune))
  951. break;
  952. }
  953. } else {
  954. while (MovePrev (ref col, ref row, out rune)) {
  955. if (!Rune.IsLetterOrDigit (rune))
  956. break;
  957. }
  958. }
  959. if (fromCol != col || fromRow != row)
  960. return (col, row);
  961. return null;
  962. }
  963. public override bool MouseEvent (MouseEvent ev)
  964. {
  965. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  966. return false;
  967. }
  968. if (!HasFocus)
  969. SuperView.SetFocus (this);
  970. if (ev.Y + topRow >= model.Count) {
  971. currentRow = model.Count - topRow;
  972. } else {
  973. currentRow = ev.Y + topRow;
  974. }
  975. var r = GetCurrentLine ();
  976. if (ev.X - leftColumn >= r.Count)
  977. currentColumn = r.Count - leftColumn;
  978. else
  979. currentColumn = ev.X - leftColumn;
  980. PositionCursor ();
  981. return true;
  982. }
  983. }
  984. }