TextView.cs 30 KB

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