TextView.cs 27 KB

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