TextView.cs 27 KB

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