TextView.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // In ReadOnly mode backspace/space behave like 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 = new List<List<Rune>> ();
  33. public bool LoadFile (string file)
  34. {
  35. if (file == null)
  36. throw new ArgumentNullException (nameof (file));
  37. try {
  38. var stream = File.OpenRead (file);
  39. } catch {
  40. return false;
  41. }
  42. LoadStream (File.OpenRead (file));
  43. return true;
  44. }
  45. // Turns the ustring into runes, this does not split the
  46. // contents on a newline if it is present.
  47. internal static List<Rune> ToRunes (ustring str)
  48. {
  49. List<Rune> runes = new List<Rune> ();
  50. foreach (var x in str.ToRunes ()) {
  51. runes.Add (x);
  52. }
  53. return runes;
  54. }
  55. // Splits a string into a List that contains a List<Rune> for each line
  56. public static List<List<Rune>> StringToRunes (ustring content)
  57. {
  58. var lines = new List<List<Rune>> ();
  59. int start = 0, i = 0;
  60. for (; i < content.Length; i++) {
  61. if (content [i] == 10) {
  62. if (i - start > 0)
  63. lines.Add (ToRunes (content [start, i]));
  64. else
  65. lines.Add (ToRunes (ustring.Empty));
  66. start = i + 1;
  67. }
  68. }
  69. if (i - start >= 0)
  70. lines.Add (ToRunes (content [start, null]));
  71. return lines;
  72. }
  73. void Append (List<byte> line)
  74. {
  75. var str = ustring.Make (line.ToArray ());
  76. lines.Add (ToRunes (str));
  77. }
  78. public void LoadStream (Stream input)
  79. {
  80. if (input == null)
  81. throw new ArgumentNullException (nameof (input));
  82. lines = new List<List<Rune>> ();
  83. var buff = new BufferedStream (input);
  84. int v;
  85. var line = new List<byte> ();
  86. while ((v = buff.ReadByte ()) != -1) {
  87. if (v == 10) {
  88. Append (line);
  89. line.Clear ();
  90. continue;
  91. }
  92. line.Add ((byte)v);
  93. }
  94. if (line.Count > 0)
  95. Append (line);
  96. }
  97. public void LoadString (ustring content)
  98. {
  99. lines = StringToRunes (content);
  100. }
  101. public override string ToString ()
  102. {
  103. var sb = new StringBuilder ();
  104. foreach (var line in lines)
  105. {
  106. sb.Append (ustring.Make(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) => line < Count ? lines [line]: lines[Count-1];
  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 = false;
  365. /// <summary>
  366. /// Indicates readonly attribute of TextView
  367. /// </summary>
  368. /// <value>Boolean value(Default false)</value>
  369. public bool ReadOnly {
  370. get => isReadOnly;
  371. set {
  372. isReadOnly = value;
  373. }
  374. }
  375. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  376. void GetEncodedRegionBounds (out long start, out long end)
  377. {
  378. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  379. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  380. if (selection > point) {
  381. start = point;
  382. end = selection;
  383. } else {
  384. start = selection;
  385. end = point;
  386. }
  387. }
  388. bool PointInSelection (int col, int row)
  389. {
  390. long start, end;
  391. GetEncodedRegionBounds (out start, out end);
  392. var q = ((long)(uint)row << 32) | (uint)col;
  393. return q >= start && q <= end;
  394. }
  395. //
  396. // Returns a ustring with the text in the selected
  397. // region.
  398. //
  399. ustring GetRegion ()
  400. {
  401. long start, end;
  402. GetEncodedRegionBounds (out start, out end);
  403. int startRow = (int)(start >> 32);
  404. var maxrow = ((int)(end >> 32));
  405. int startCol = (int)(start & 0xffffffff);
  406. var endCol = (int)(end & 0xffffffff);
  407. var line = model.GetLine (startRow);
  408. if (startRow == maxrow)
  409. return StringFromRunes (line.GetRange (startCol, endCol));
  410. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  411. for (int row = startRow+1; row < maxrow; row++) {
  412. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  413. }
  414. line = model.GetLine (maxrow);
  415. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  416. return res;
  417. }
  418. //
  419. // Clears the contents of the selected region
  420. //
  421. void ClearRegion ()
  422. {
  423. long start, end;
  424. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  425. GetEncodedRegionBounds (out start, out end);
  426. int startRow = (int)(start >> 32);
  427. var maxrow = ((int)(end >> 32));
  428. int startCol = (int)(start & 0xffffffff);
  429. var endCol = (int)(end & 0xffffffff);
  430. var line = model.GetLine (startRow);
  431. if (startRow == maxrow) {
  432. line.RemoveRange (startCol, endCol - startCol);
  433. currentColumn = startCol;
  434. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  435. return;
  436. }
  437. line.RemoveRange (startCol, line.Count - startCol);
  438. var line2 = model.GetLine (maxrow);
  439. line.AddRange (line2.Skip (endCol));
  440. for (int row = startRow + 1; row <= maxrow; row++) {
  441. model.RemoveLine (startRow+1);
  442. }
  443. if (currentEncoded == end) {
  444. currentRow -= maxrow - (startRow);
  445. }
  446. currentColumn = startCol;
  447. SetNeedsDisplay ();
  448. }
  449. /// <summary>
  450. /// Redraw the text editor region
  451. /// </summary>
  452. /// <param name="region">The region to redraw.</param>
  453. public override void Redraw (Rect region)
  454. {
  455. ColorNormal ();
  456. int bottom = region.Bottom;
  457. int right = region.Right;
  458. for (int row = region.Top; row < bottom; row++)
  459. {
  460. int textLine = topRow + row;
  461. if (textLine >= model.Count)
  462. {
  463. ColorNormal ();
  464. ClearRegion (region.Left, row, region.Right, row + 1);
  465. continue;
  466. }
  467. var line = model.GetLine (textLine);
  468. int lineRuneCount = line.Count;
  469. if (line.Count < region.Left)
  470. {
  471. ClearRegion (region.Left, row, region.Right, row + 1);
  472. continue;
  473. }
  474. Move (region.Left, row);
  475. for (int col = region.Left; col < right; col++)
  476. {
  477. var lineCol = leftColumn + col;
  478. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  479. if (selecting && PointInSelection (col, row))
  480. ColorSelection ();
  481. else
  482. ColorNormal ();
  483. AddRune (col, row, rune);
  484. }
  485. }
  486. PositionCursor ();
  487. }
  488. public override bool CanFocus {
  489. get => true;
  490. set { base.CanFocus = value; }
  491. }
  492. void SetClipboard (ustring text)
  493. {
  494. Clipboard.Contents = text;
  495. }
  496. void AppendClipboard (ustring text)
  497. {
  498. Clipboard.Contents = Clipboard.Contents + text;
  499. }
  500. void Insert (Rune rune)
  501. {
  502. var line = GetCurrentLine ();
  503. line.Insert (currentColumn, rune);
  504. var prow = currentRow - topRow;
  505. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  506. }
  507. ustring StringFromRunes (List<Rune> runes)
  508. {
  509. if (runes == null)
  510. throw new ArgumentNullException (nameof (runes));
  511. int size = 0;
  512. foreach (var rune in runes) {
  513. size += Utf8.RuneLen (rune);
  514. }
  515. var encoded = new byte [size];
  516. int offset = 0;
  517. foreach (var rune in runes) {
  518. offset += Utf8.EncodeRune (rune, encoded, offset);
  519. }
  520. return ustring.Make (encoded);
  521. }
  522. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  523. void InsertText (ustring text)
  524. {
  525. var lines = TextModel.StringToRunes (text);
  526. if (lines.Count == 0)
  527. return;
  528. var line = GetCurrentLine ();
  529. // Optmize single line
  530. if (lines.Count == 1) {
  531. line.InsertRange (currentColumn, lines [0]);
  532. currentColumn += lines [0].Count;
  533. if (currentColumn - leftColumn > Frame.Width)
  534. leftColumn = currentColumn - Frame.Width + 1;
  535. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  536. return;
  537. }
  538. // Keep a copy of the rest of the line
  539. var restCount = line.Count - currentColumn;
  540. var rest = line.GetRange (currentColumn, restCount);
  541. line.RemoveRange (currentColumn, restCount);
  542. // First line is inserted at the current location, the rest is appended
  543. line.InsertRange (currentColumn, lines [0]);
  544. for (int i = 1; i < lines.Count; i++)
  545. model.AddLine (currentRow + i, lines [i]);
  546. var last = model.GetLine (currentRow + lines.Count-1);
  547. var lastp = last.Count;
  548. last.InsertRange (last.Count, rest);
  549. // Now adjjust column and row positions
  550. currentRow += lines.Count-1;
  551. currentColumn = lastp;
  552. if (currentRow - topRow > Frame.Height) {
  553. topRow = currentRow - Frame.Height + 1;
  554. if (topRow < 0)
  555. topRow = 0;
  556. }
  557. if (currentColumn < leftColumn)
  558. leftColumn = currentColumn;
  559. if (currentColumn-leftColumn >= Frame.Width)
  560. leftColumn = currentColumn - Frame.Width + 1;
  561. SetNeedsDisplay ();
  562. }
  563. // The column we are tracking, or -1 if we are not tracking any column
  564. int columnTrack = -1;
  565. // Tries to snap the cursor to the tracking column
  566. void TrackColumn ()
  567. {
  568. // Now track the column
  569. var line = GetCurrentLine ();
  570. if (line.Count < columnTrack)
  571. currentColumn = line.Count;
  572. else if (columnTrack != -1)
  573. currentColumn = columnTrack;
  574. else if (currentColumn > line.Count)
  575. currentColumn = line.Count;
  576. Adjust ();
  577. }
  578. void Adjust ()
  579. {
  580. bool need = false;
  581. if (currentColumn < leftColumn) {
  582. currentColumn = leftColumn;
  583. need = true;
  584. }
  585. if (currentColumn - leftColumn > Frame.Width) {
  586. leftColumn = currentColumn - Frame.Width + 1;
  587. need = true;
  588. }
  589. if (currentRow < topRow) {
  590. topRow = currentRow;
  591. need = true;
  592. }
  593. if (currentRow - topRow > Frame.Height) {
  594. topRow = currentRow - Frame.Height + 1;
  595. need = true;
  596. }
  597. if (need)
  598. SetNeedsDisplay ();
  599. else
  600. PositionCursor ();
  601. }
  602. bool lastWasKill;
  603. public override bool ProcessKey (KeyEvent kb)
  604. {
  605. int restCount;
  606. List<Rune> rest;
  607. // Handle some state here - whether the last command was a kill
  608. // operation and the column tracking (up/down)
  609. switch (kb.Key) {
  610. case Key.ControlN:
  611. case Key.CursorDown:
  612. case Key.ControlP:
  613. case Key.CursorUp:
  614. lastWasKill = false;
  615. break;
  616. case Key.ControlK:
  617. break;
  618. default:
  619. lastWasKill = false;
  620. columnTrack = -1;
  621. break;
  622. }
  623. // Dispatch the command.
  624. switch (kb.Key) {
  625. case Key.PageDown:
  626. case Key.ControlV:
  627. int nPageDnShift = Frame.Height - 1;
  628. if (currentRow < model.Count) {
  629. if (columnTrack == -1)
  630. columnTrack = currentColumn;
  631. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  632. if (topRow < currentRow - nPageDnShift) {
  633. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  634. SetNeedsDisplay ();
  635. }
  636. TrackColumn ();
  637. PositionCursor ();
  638. }
  639. break;
  640. case Key.PageUp:
  641. case ((int)'v' + Key.AltMask):
  642. int nPageUpShift = Frame.Height - 1;
  643. if (currentRow > 0) {
  644. if (columnTrack == -1)
  645. columnTrack = currentColumn;
  646. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  647. if (currentRow < topRow) {
  648. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  649. SetNeedsDisplay ();
  650. }
  651. TrackColumn ();
  652. PositionCursor ();
  653. }
  654. break;
  655. case Key.ControlN:
  656. case Key.CursorDown:
  657. if (currentRow + 1 < model.Count) {
  658. if (columnTrack == -1)
  659. columnTrack = currentColumn;
  660. currentRow++;
  661. if (currentRow >= topRow + Frame.Height) {
  662. topRow++;
  663. SetNeedsDisplay ();
  664. }
  665. TrackColumn ();
  666. PositionCursor ();
  667. }
  668. break;
  669. case Key.ControlP:
  670. case Key.CursorUp:
  671. if (currentRow > 0) {
  672. if (columnTrack == -1)
  673. columnTrack = currentColumn;
  674. currentRow--;
  675. if (currentRow < topRow) {
  676. topRow--;
  677. SetNeedsDisplay ();
  678. }
  679. TrackColumn ();
  680. PositionCursor ();
  681. }
  682. break;
  683. case Key.ControlF:
  684. case Key.CursorRight:
  685. var currentLine = GetCurrentLine ();
  686. if (currentColumn < currentLine.Count) {
  687. currentColumn++;
  688. if (currentColumn >= leftColumn + Frame.Width) {
  689. leftColumn++;
  690. SetNeedsDisplay ();
  691. }
  692. PositionCursor ();
  693. } else {
  694. if (currentRow + 1 < model.Count) {
  695. currentRow++;
  696. currentColumn = 0;
  697. leftColumn = 0;
  698. if (currentRow >= topRow + Frame.Height) {
  699. topRow++;
  700. }
  701. SetNeedsDisplay ();
  702. PositionCursor ();
  703. }
  704. break;
  705. }
  706. break;
  707. case Key.ControlB:
  708. case Key.CursorLeft:
  709. if (currentColumn > 0) {
  710. currentColumn--;
  711. if (currentColumn < leftColumn) {
  712. leftColumn--;
  713. SetNeedsDisplay ();
  714. }
  715. PositionCursor ();
  716. } else {
  717. if (currentRow > 0) {
  718. currentRow--;
  719. if (currentRow < topRow) {
  720. topRow--;
  721. }
  722. currentLine = GetCurrentLine ();
  723. currentColumn = currentLine.Count;
  724. int prev = leftColumn;
  725. leftColumn = currentColumn - Frame.Width + 1;
  726. if (leftColumn < 0)
  727. leftColumn = 0;
  728. if (prev != leftColumn)
  729. SetNeedsDisplay ();
  730. PositionCursor ();
  731. }
  732. }
  733. break;
  734. case Key.Delete:
  735. case Key.Backspace:
  736. if (isReadOnly)
  737. break;
  738. if (currentColumn > 0) {
  739. // Delete backwards
  740. currentLine = GetCurrentLine ();
  741. currentLine.RemoveAt (currentColumn - 1);
  742. currentColumn--;
  743. if (currentColumn < leftColumn) {
  744. leftColumn--;
  745. SetNeedsDisplay ();
  746. } else
  747. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  748. } else {
  749. // Merges the current line with the previous one.
  750. if (currentRow == 0)
  751. return true;
  752. var prowIdx = currentRow - 1;
  753. var prevRow = model.GetLine (prowIdx);
  754. var prevCount = prevRow.Count;
  755. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  756. model.RemoveLine (currentRow);
  757. currentRow--;
  758. currentColumn = prevCount;
  759. leftColumn = currentColumn - Frame.Width + 1;
  760. if (leftColumn < 0)
  761. leftColumn = 0;
  762. SetNeedsDisplay ();
  763. }
  764. break;
  765. // Home, C-A
  766. case Key.Home:
  767. case Key.ControlA:
  768. currentColumn = 0;
  769. if (currentColumn < leftColumn) {
  770. leftColumn = 0;
  771. SetNeedsDisplay ();
  772. } else
  773. PositionCursor ();
  774. break;
  775. case Key.DeleteChar:
  776. case Key.ControlD: // Delete
  777. if (isReadOnly)
  778. break;
  779. currentLine = GetCurrentLine ();
  780. if (currentColumn == currentLine.Count) {
  781. if (currentRow + 1 == model.Count)
  782. break;
  783. var nextLine = model.GetLine (currentRow + 1);
  784. currentLine.AddRange (nextLine);
  785. model.RemoveLine (currentRow + 1);
  786. var sr = currentRow - topRow;
  787. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  788. } else {
  789. currentLine.RemoveAt (currentColumn);
  790. var r = currentRow - topRow;
  791. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  792. }
  793. break;
  794. case Key.End:
  795. case Key.ControlE: // End
  796. currentLine = GetCurrentLine ();
  797. currentColumn = currentLine.Count;
  798. int pcol = leftColumn;
  799. leftColumn = currentColumn - Frame.Width + 1;
  800. if (leftColumn < 0)
  801. leftColumn = 0;
  802. if (pcol != leftColumn)
  803. SetNeedsDisplay ();
  804. PositionCursor ();
  805. break;
  806. case Key.ControlK: // kill-to-end
  807. if (isReadOnly)
  808. break;
  809. currentLine = GetCurrentLine ();
  810. if (currentLine.Count == 0) {
  811. model.RemoveLine (currentRow);
  812. var val = ustring.Make ((Rune)'\n');
  813. if (lastWasKill)
  814. AppendClipboard (val);
  815. else
  816. SetClipboard (val);
  817. } else {
  818. restCount = currentLine.Count - currentColumn;
  819. rest = currentLine.GetRange (currentColumn, restCount);
  820. var val = StringFromRunes (rest);
  821. if (lastWasKill)
  822. AppendClipboard (val);
  823. else
  824. SetClipboard (val);
  825. currentLine.RemoveRange (currentColumn, restCount);
  826. }
  827. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  828. lastWasKill = true;
  829. break;
  830. case Key.ControlY: // Control-y, yank
  831. if (isReadOnly)
  832. break;
  833. InsertText (Clipboard.Contents);
  834. selecting = false;
  835. break;
  836. case Key.ControlSpace:
  837. selecting = true;
  838. selectionStartColumn = currentColumn;
  839. selectionStartRow = currentRow;
  840. break;
  841. case ((int)'w' + Key.AltMask):
  842. SetClipboard (GetRegion ());
  843. selecting = false;
  844. break;
  845. case Key.ControlW:
  846. SetClipboard (GetRegion ());
  847. if (!isReadOnly)
  848. ClearRegion ();
  849. selecting = false;
  850. break;
  851. case (Key)((int)'b' + Key.AltMask):
  852. var newPos = WordBackward (currentColumn, currentRow);
  853. if (newPos.HasValue) {
  854. currentColumn = newPos.Value.col;
  855. currentRow = newPos.Value.row;
  856. }
  857. Adjust ();
  858. break;
  859. case (Key)((int)'f' + Key.AltMask):
  860. newPos = WordForward (currentColumn, currentRow);
  861. if (newPos.HasValue) {
  862. currentColumn = newPos.Value.col;
  863. currentRow = newPos.Value.row;
  864. }
  865. Adjust ();
  866. break;
  867. case Key.Enter:
  868. if (isReadOnly)
  869. break;
  870. var orow = currentRow;
  871. currentLine = GetCurrentLine ();
  872. restCount = currentLine.Count - currentColumn;
  873. rest = currentLine.GetRange (currentColumn, restCount);
  874. currentLine.RemoveRange (currentColumn, restCount);
  875. model.AddLine (currentRow + 1, rest);
  876. currentRow++;
  877. bool fullNeedsDisplay = false;
  878. if (currentRow >= topRow + Frame.Height) {
  879. topRow++;
  880. fullNeedsDisplay = true;
  881. }
  882. currentColumn = 0;
  883. if (currentColumn < leftColumn) {
  884. fullNeedsDisplay = true;
  885. leftColumn = 0;
  886. }
  887. if (fullNeedsDisplay)
  888. SetNeedsDisplay ();
  889. else
  890. SetNeedsDisplay (new Rect (0, currentRow - topRow, 0, Frame.Height));
  891. break;
  892. default:
  893. // Ignore control characters and other special keys
  894. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  895. return false;
  896. //So that special keys like tab can be processed
  897. if (isReadOnly)
  898. return true;
  899. Insert ((uint)kb.Key);
  900. currentColumn++;
  901. if (currentColumn >= leftColumn + Frame.Width) {
  902. leftColumn++;
  903. SetNeedsDisplay ();
  904. }
  905. PositionCursor ();
  906. return true;
  907. }
  908. return true;
  909. }
  910. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  911. {
  912. if (col < 0 || row < 0)
  913. yield break;
  914. if (row >= model.Count)
  915. yield break;
  916. var line = GetCurrentLine ();
  917. if (col >= line.Count)
  918. yield break;
  919. while (row < model.Count) {
  920. for (int c = col; c < line.Count; c++) {
  921. yield return (c, row, line [c]);
  922. }
  923. col = 0;
  924. row++;
  925. line = GetCurrentLine ();
  926. }
  927. }
  928. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  929. bool MoveNext (ref int col, ref int row, out Rune rune)
  930. {
  931. var line = model.GetLine (row);
  932. if (col + 1 < line.Count) {
  933. col++;
  934. rune = line [col];
  935. return true;
  936. }
  937. while (row + 1 < model.Count){
  938. col = 0;
  939. row++;
  940. line = model.GetLine (row);
  941. if (line.Count > 0) {
  942. rune = line [0];
  943. return true;
  944. }
  945. }
  946. rune = 0;
  947. return false;
  948. }
  949. bool MovePrev (ref int col, ref int row, out Rune rune)
  950. {
  951. var line = model.GetLine (row);
  952. if (col > 0) {
  953. col--;
  954. rune = line [col];
  955. return true;
  956. }
  957. if (row == 0) {
  958. rune = 0;
  959. return false;
  960. }
  961. while (row > 0) {
  962. row--;
  963. line = model.GetLine (row);
  964. col = line.Count - 1;
  965. if (col >= 0) {
  966. rune = line [col];
  967. return true;
  968. }
  969. }
  970. rune = 0;
  971. return false;
  972. }
  973. (int col, int row)? WordForward (int fromCol, int fromRow)
  974. {
  975. var col = fromCol;
  976. var row = fromRow;
  977. var line = GetCurrentLine ();
  978. var rune = RuneAt (col, row);
  979. var srow = row;
  980. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  981. while (MoveNext (ref col, ref row, out rune)){
  982. if (Rune.IsLetterOrDigit (rune))
  983. break;
  984. }
  985. while (MoveNext (ref col, ref row, out rune)) {
  986. if (!Rune.IsLetterOrDigit (rune))
  987. break;
  988. }
  989. } else {
  990. while (MoveNext (ref col, ref row, out rune)) {
  991. if (!Rune.IsLetterOrDigit (rune))
  992. break;
  993. }
  994. }
  995. if (fromCol != col || fromRow != row)
  996. return (col, row);
  997. return null;
  998. }
  999. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1000. {
  1001. if (fromRow == 0 && fromCol == 0)
  1002. return null;
  1003. var col = fromCol;
  1004. var row = fromRow;
  1005. var line = GetCurrentLine ();
  1006. var rune = RuneAt (col, row);
  1007. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1008. while (MovePrev (ref col, ref row, out rune)){
  1009. if (Rune.IsLetterOrDigit (rune))
  1010. break;
  1011. }
  1012. while (MovePrev (ref col, ref row, out rune)){
  1013. if (!Rune.IsLetterOrDigit (rune))
  1014. break;
  1015. }
  1016. } else {
  1017. while (MovePrev (ref col, ref row, out rune)) {
  1018. if (!Rune.IsLetterOrDigit (rune))
  1019. break;
  1020. }
  1021. }
  1022. if (fromCol != col || fromRow != row)
  1023. return (col, row);
  1024. return null;
  1025. }
  1026. public override bool MouseEvent (MouseEvent ev)
  1027. {
  1028. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1029. return false;
  1030. }
  1031. if (!HasFocus)
  1032. SuperView.SetFocus (this);
  1033. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1034. if (ev.Y > maxCursorPositionableLine) {
  1035. currentRow = maxCursorPositionableLine;
  1036. } else {
  1037. currentRow = ev.Y + topRow;
  1038. }
  1039. var r = GetCurrentLine ();
  1040. if (ev.X - leftColumn >= r.Count)
  1041. currentColumn = r.Count - leftColumn;
  1042. else
  1043. currentColumn = ev.X - leftColumn;
  1044. PositionCursor ();
  1045. return true;
  1046. }
  1047. }
  1048. }