TextView.cs 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. model.RemoveLine (currentRow);
  710. currentRow--;
  711. currentColumn = prevCount;
  712. leftColumn = currentColumn - Frame.Width + 1;
  713. if (leftColumn < 0)
  714. leftColumn = 0;
  715. SetNeedsDisplay ();
  716. }
  717. break;
  718. // Home, C-A
  719. case Key.Home:
  720. case Key.ControlA:
  721. currentColumn = 0;
  722. if (currentColumn < leftColumn) {
  723. leftColumn = 0;
  724. SetNeedsDisplay ();
  725. } else
  726. PositionCursor ();
  727. break;
  728. case Key.ControlD: // Delete
  729. currentLine = GetCurrentLine ();
  730. if (currentColumn == currentLine.Count) {
  731. if (currentRow + 1 == model.Count)
  732. break;
  733. var nextLine = model.GetLine (currentRow + 1);
  734. currentLine.AddRange (nextLine);
  735. model.RemoveLine (currentRow + 1);
  736. var sr = currentRow - topRow;
  737. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  738. } else {
  739. currentLine.RemoveAt (currentColumn);
  740. var r = currentRow - topRow;
  741. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  742. }
  743. break;
  744. case Key.End:
  745. case Key.ControlE: // End
  746. currentLine = GetCurrentLine ();
  747. currentColumn = currentLine.Count;
  748. int pcol = leftColumn;
  749. leftColumn = currentColumn - Frame.Width + 1;
  750. if (leftColumn < 0)
  751. leftColumn = 0;
  752. if (pcol != leftColumn)
  753. SetNeedsDisplay ();
  754. PositionCursor ();
  755. break;
  756. case Key.ControlK: // kill-to-end
  757. currentLine = GetCurrentLine ();
  758. if (currentLine.Count == 0) {
  759. model.RemoveLine (currentRow);
  760. var val = ustring.Make ((Rune)'\n');
  761. if (lastWasKill)
  762. AppendClipboard (val);
  763. else
  764. SetClipboard (val);
  765. } else {
  766. restCount = currentLine.Count - currentColumn;
  767. rest = currentLine.GetRange (currentColumn, restCount);
  768. var val = StringFromRunes (rest);
  769. if (lastWasKill)
  770. AppendClipboard (val);
  771. else
  772. SetClipboard (val);
  773. currentLine.RemoveRange (currentColumn, restCount);
  774. }
  775. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  776. lastWasKill = true;
  777. break;
  778. case Key.ControlY: // Control-y, yank
  779. InsertText (Clipboard.Contents);
  780. selecting = false;
  781. break;
  782. case Key.ControlSpace:
  783. selecting = true;
  784. selectionStartColumn = currentColumn;
  785. selectionStartRow = currentRow;
  786. break;
  787. case ((int)'w' + Key.AltMask):
  788. SetClipboard (GetRegion ());
  789. selecting = false;
  790. break;
  791. case Key.ControlW:
  792. SetClipboard (GetRegion ());
  793. ClearRegion ();
  794. selecting = false;
  795. break;
  796. case (Key)((int)'b' + Key.AltMask):
  797. var newPos = WordBackward (currentColumn, currentRow);
  798. if (newPos.HasValue) {
  799. currentColumn = newPos.Value.col;
  800. currentRow = newPos.Value.row;
  801. }
  802. Adjust ();
  803. break;
  804. case (Key)((int)'f' + Key.AltMask):
  805. newPos = WordForward (currentColumn, currentRow);
  806. if (newPos.HasValue) {
  807. currentColumn = newPos.Value.col;
  808. currentRow = newPos.Value.row;
  809. }
  810. Adjust ();
  811. break;
  812. case Key.Enter:
  813. var orow = currentRow;
  814. currentLine = GetCurrentLine ();
  815. restCount = currentLine.Count - currentColumn;
  816. rest = currentLine.GetRange (currentColumn, restCount);
  817. currentLine.RemoveRange (currentColumn, restCount);
  818. model.AddLine (currentRow + 1, rest);
  819. currentRow++;
  820. bool fullNeedsDisplay = false;
  821. if (currentRow >= topRow + Frame.Height) {
  822. topRow++;
  823. fullNeedsDisplay = true;
  824. }
  825. currentColumn = 0;
  826. if (currentColumn < leftColumn) {
  827. fullNeedsDisplay = true;
  828. leftColumn = 0;
  829. }
  830. if (fullNeedsDisplay)
  831. SetNeedsDisplay ();
  832. else
  833. SetNeedsDisplay (new Rect (0, currentRow - topRow, 0, Frame.Height));
  834. break;
  835. default:
  836. // Ignore control characters and other special keys
  837. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  838. return false;
  839. Insert ((uint)kb.Key);
  840. currentColumn++;
  841. if (currentColumn >= leftColumn + Frame.Width) {
  842. leftColumn++;
  843. SetNeedsDisplay ();
  844. }
  845. PositionCursor ();
  846. return true;
  847. }
  848. return true;
  849. }
  850. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  851. {
  852. if (col < 0 || row < 0)
  853. yield break;
  854. if (row >= model.Count)
  855. yield break;
  856. var line = GetCurrentLine ();
  857. if (col >= line.Count)
  858. yield break;
  859. while (row < model.Count) {
  860. for (int c = col; c < line.Count; c++) {
  861. yield return (c, row, line [c]);
  862. }
  863. col = 0;
  864. row++;
  865. line = GetCurrentLine ();
  866. }
  867. }
  868. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  869. bool MoveNext (ref int col, ref int row, out Rune rune)
  870. {
  871. var line = model.GetLine (row);
  872. if (col + 1 < line.Count) {
  873. col++;
  874. rune = line [col];
  875. return true;
  876. }
  877. while (row + 1 < model.Count){
  878. col = 0;
  879. row++;
  880. line = model.GetLine (row);
  881. if (line.Count > 0) {
  882. rune = line [0];
  883. return true;
  884. }
  885. }
  886. rune = 0;
  887. return false;
  888. }
  889. bool MovePrev (ref int col, ref int row, out Rune rune)
  890. {
  891. var line = model.GetLine (row);
  892. if (col > 0) {
  893. col--;
  894. rune = line [col];
  895. return true;
  896. }
  897. if (row == 0) {
  898. rune = 0;
  899. return false;
  900. }
  901. while (row > 0) {
  902. row--;
  903. line = model.GetLine (row);
  904. col = line.Count - 1;
  905. if (col >= 0) {
  906. rune = line [col];
  907. return true;
  908. }
  909. }
  910. rune = 0;
  911. return false;
  912. }
  913. (int col, int row)? WordForward (int fromCol, int fromRow)
  914. {
  915. var col = fromCol;
  916. var row = fromRow;
  917. var line = GetCurrentLine ();
  918. var rune = RuneAt (col, row);
  919. var srow = row;
  920. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  921. while (MoveNext (ref col, ref row, out rune)){
  922. if (Rune.IsLetterOrDigit (rune))
  923. break;
  924. }
  925. while (MoveNext (ref col, ref row, out rune)) {
  926. if (!Rune.IsLetterOrDigit (rune))
  927. break;
  928. }
  929. } else {
  930. while (MoveNext (ref col, ref row, out rune)) {
  931. if (!Rune.IsLetterOrDigit (rune))
  932. break;
  933. }
  934. }
  935. if (fromCol != col || fromRow != row)
  936. return (col, row);
  937. return null;
  938. }
  939. (int col, int row)? WordBackward (int fromCol, int fromRow)
  940. {
  941. if (fromRow == 0 && fromCol == 0)
  942. return null;
  943. var col = fromCol;
  944. var row = fromRow;
  945. var line = GetCurrentLine ();
  946. var rune = RuneAt (col, row);
  947. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  948. while (MovePrev (ref col, ref row, out rune)){
  949. if (Rune.IsLetterOrDigit (rune))
  950. break;
  951. }
  952. while (MovePrev (ref col, ref row, out rune)){
  953. if (!Rune.IsLetterOrDigit (rune))
  954. break;
  955. }
  956. } else {
  957. while (MovePrev (ref col, ref row, out rune)) {
  958. if (!Rune.IsLetterOrDigit (rune))
  959. break;
  960. }
  961. }
  962. if (fromCol != col || fromRow != row)
  963. return (col, row);
  964. return null;
  965. }
  966. public override bool MouseEvent (MouseEvent ev)
  967. {
  968. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  969. return false;
  970. }
  971. if (!HasFocus)
  972. SuperView.SetFocus (this);
  973. if (ev.Y + topRow >= model.Count) {
  974. currentRow = model.Count - topRow;
  975. } else {
  976. currentRow = ev.Y + topRow;
  977. }
  978. var r = GetCurrentLine ();
  979. if (ev.X - leftColumn >= r.Count)
  980. currentColumn = r.Count - leftColumn;
  981. else
  982. currentColumn = ev.X - leftColumn;
  983. PositionCursor ();
  984. return true;
  985. }
  986. }
  987. }