TextView.cs 26 KB

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