TextView.cs 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150
  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. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public event Action LinesLoaded;
  35. public bool LoadFile (string file)
  36. {
  37. FilePath = file ?? throw new ArgumentNullException (nameof (file));
  38. var stream = File.OpenRead (file);
  39. LoadStream (stream);
  40. return true;
  41. }
  42. public bool CloseFile ()
  43. {
  44. if (FilePath == null)
  45. throw new ArgumentNullException (nameof (FilePath));
  46. FilePath = null;
  47. lines = new List<List<Rune>> ();
  48. return true;
  49. }
  50. // Turns the ustring into runes, this does not split the
  51. // contents on a newline if it is present.
  52. internal static List<Rune> ToRunes (ustring str)
  53. {
  54. List<Rune> runes = new List<Rune> ();
  55. foreach (var x in str.ToRunes ()) {
  56. runes.Add (x);
  57. }
  58. return runes;
  59. }
  60. // Splits a string into a List that contains a List<Rune> for each line
  61. public static List<List<Rune>> StringToRunes (ustring content)
  62. {
  63. var lines = new List<List<Rune>> ();
  64. int start = 0, i = 0;
  65. var hasCR = false;
  66. // ASCII code 13 = Carriage Return.
  67. // ASCII code 10 = Line Feed.
  68. for (; i < content.Length; i++) {
  69. if (content [i] == 13) {
  70. hasCR = true;
  71. continue;
  72. }
  73. if (content [i] == 10) {
  74. if (i - start > 0)
  75. lines.Add (ToRunes (content [start, hasCR ? i - 1 : i]));
  76. else
  77. lines.Add (ToRunes (ustring.Empty));
  78. start = i + 1;
  79. hasCR = false;
  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. var wasNewLine = false;
  100. while ((v = buff.ReadByte ()) != -1) {
  101. if (v == 13) {
  102. continue;
  103. }
  104. if (v == 10) {
  105. Append (line);
  106. line.Clear ();
  107. wasNewLine = true;
  108. continue;
  109. }
  110. line.Add ((byte)v);
  111. wasNewLine = false;
  112. }
  113. if (line.Count > 0 || wasNewLine)
  114. Append (line);
  115. buff.Dispose ();
  116. OnLinesLoaded ();
  117. }
  118. public void LoadString (ustring content)
  119. {
  120. lines = StringToRunes (content);
  121. OnLinesLoaded ();
  122. }
  123. void OnLinesLoaded ()
  124. {
  125. LinesLoaded?.Invoke ();
  126. }
  127. public override string ToString ()
  128. {
  129. var sb = new StringBuilder ();
  130. for (int i = 0; i < lines.Count; i++) {
  131. sb.Append (ustring.Make (lines [i]));
  132. if ((i + 1) < lines.Count) {
  133. sb.AppendLine ();
  134. }
  135. }
  136. return sb.ToString ();
  137. }
  138. public string FilePath { get; set; }
  139. /// <summary>
  140. /// The number of text lines in the model
  141. /// </summary>
  142. public int Count => lines.Count;
  143. /// <summary>
  144. /// Returns the specified line as a List of Rune
  145. /// </summary>
  146. /// <returns>The line.</returns>
  147. /// <param name="line">Line number to retrieve.</param>
  148. public List<Rune> GetLine (int line)
  149. {
  150. if (lines.Count > 0) {
  151. if (line < Count) {
  152. return lines [line];
  153. } else {
  154. return lines [Count - 1];
  155. }
  156. } else {
  157. lines.Add (new List<Rune> ());
  158. return lines [0];
  159. }
  160. }
  161. /// <summary>
  162. /// Adds a line to the model at the specified position.
  163. /// </summary>
  164. /// <param name="pos">Line number where the line will be inserted.</param>
  165. /// <param name="runes">The line of text, as a List of Rune.</param>
  166. public void AddLine (int pos, List<Rune> runes)
  167. {
  168. lines.Insert (pos, runes);
  169. }
  170. /// <summary>
  171. /// Removes the line at the specified position
  172. /// </summary>
  173. /// <param name="pos">Position.</param>
  174. public void RemoveLine (int pos)
  175. {
  176. if (lines.Count > 0) {
  177. if (lines.Count == 1 && lines [0].Count == 0) {
  178. return;
  179. }
  180. lines.RemoveAt (pos);
  181. }
  182. }
  183. public void ReplaceLine (int pos, List<Rune> runes)
  184. {
  185. if (lines.Count > 0 && pos < lines.Count) {
  186. lines [pos] = new List<Rune> (runes);
  187. } else if (lines.Count == 0 || (lines.Count > 0 && pos >= lines.Count)) {
  188. lines.Add (runes);
  189. }
  190. }
  191. /// <summary>
  192. /// Returns the maximum line length of the visible lines.
  193. /// </summary>
  194. /// <param name="first">The first line.</param>
  195. /// <param name="last">The last line.</param>
  196. /// <param name="tabWidth">The tab width.</param>
  197. public int GetMaxVisibleLine (int first, int last, int tabWidth)
  198. {
  199. int maxLength = 0;
  200. last = last < lines.Count ? last : lines.Count;
  201. for (int i = first; i < last; i++) {
  202. var line = GetLine (i);
  203. var tabSum = line.Sum (r => r == '\t' ? Math.Max (tabWidth - 1, 0) : 0);
  204. var l = line.Count + tabSum;
  205. if (l > maxLength) {
  206. maxLength = l;
  207. }
  208. }
  209. return maxLength;
  210. }
  211. internal static bool SetCol (ref int col, int width, int cols)
  212. {
  213. if (col + cols <= width) {
  214. col += cols;
  215. return true;
  216. }
  217. return false;
  218. }
  219. internal static int GetColFromX (List<Rune> t, int start, int x, int tabWidth = 0)
  220. {
  221. if (x < 0) {
  222. return x;
  223. }
  224. int size = start;
  225. var pX = x + start;
  226. for (int i = start; i < t.Count; i++) {
  227. var r = t [i];
  228. size += Rune.ColumnWidth (r);
  229. if (r == '\t') {
  230. size += tabWidth + 1;
  231. }
  232. if (i == pX || (size > pX)) {
  233. return i - start;
  234. }
  235. }
  236. return t.Count - start;
  237. }
  238. // Returns the size and length in a range of the string.
  239. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1,
  240. bool checkNextRune = true, int tabWidth = 0)
  241. {
  242. if (t == null || t.Count == 0) {
  243. return (0, 0);
  244. }
  245. int size = 0;
  246. int len = 0;
  247. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  248. int i = start == -1 ? 0 : start;
  249. for (; i < tcount; i++) {
  250. var rune = t [i];
  251. size += Rune.ColumnWidth (rune);
  252. len += Rune.RuneLen (rune);
  253. if (rune == '\t') {
  254. size += tabWidth + 1;
  255. len += tabWidth - 1;
  256. }
  257. if (checkNextRune && i == tcount - 1 && t.Count > tcount
  258. && IsWideRune (t [i + 1], tabWidth, out int s, out int l)) {
  259. size += s;
  260. len += l;
  261. }
  262. }
  263. bool IsWideRune (Rune r, int tWidth, out int s, out int l)
  264. {
  265. s = Rune.ColumnWidth (r);
  266. l = Rune.RuneLen (r);
  267. if (r == '\t') {
  268. s += tWidth + 1;
  269. l += tWidth - 1;
  270. }
  271. return s > 1;
  272. }
  273. return (size, len);
  274. }
  275. // Returns the left column in a range of the string.
  276. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int tabWidth = 0)
  277. {
  278. if (t == null || t.Count == 0) {
  279. return 0;
  280. }
  281. int size = 0;
  282. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  283. int col = 0;
  284. for (int i = tcount; i >= 0; i--) {
  285. var rune = t [i];
  286. size += Rune.ColumnWidth (rune);
  287. if (rune == '\t') {
  288. size += tabWidth + 1;
  289. }
  290. if (size > width) {
  291. if (col + width == end) {
  292. col++;
  293. }
  294. break;
  295. } else if ((end < t.Count && col > 0 && start < end && col == start) || (end - col == width - 1)) {
  296. break;
  297. }
  298. col = i;
  299. }
  300. return col;
  301. }
  302. (Point startPointToFind, Point currentPointToFind, bool found) toFind;
  303. internal (Point current, bool found) FindNextText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  304. {
  305. if (text == null || lines.Count == 0) {
  306. gaveFullTurn = false;
  307. return (Point.Empty, false);
  308. }
  309. if (toFind.found) {
  310. toFind.currentPointToFind.X++;
  311. }
  312. var foundPos = GetFoundNextTextPoint (text, lines.Count, matchCase, matchWholeWord, toFind.currentPointToFind);
  313. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  314. foundPos = GetFoundNextTextPoint (text, toFind.startPointToFind.Y + 1, matchCase, matchWholeWord, Point.Empty);
  315. }
  316. gaveFullTurn = ApplyToFind (foundPos);
  317. return foundPos;
  318. }
  319. internal (Point current, bool found) FindPreviousText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  320. {
  321. if (text == null || lines.Count == 0) {
  322. gaveFullTurn = false;
  323. return (Point.Empty, false);
  324. }
  325. if (toFind.found) {
  326. toFind.currentPointToFind.X++;
  327. }
  328. var linesCount = toFind.currentPointToFind.IsEmpty ? lines.Count - 1 : toFind.currentPointToFind.Y;
  329. var foundPos = GetFoundPreviousTextPoint (text, linesCount, matchCase, matchWholeWord, toFind.currentPointToFind);
  330. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  331. foundPos = GetFoundPreviousTextPoint (text, lines.Count - 1, matchCase, matchWholeWord,
  332. new Point (lines [lines.Count - 1].Count, lines.Count));
  333. }
  334. gaveFullTurn = ApplyToFind (foundPos);
  335. return foundPos;
  336. }
  337. internal (Point current, bool found) ReplaceAllText (ustring text, bool matchCase = false, bool matchWholeWord = false, ustring textToReplace = null)
  338. {
  339. bool found = false;
  340. Point pos = Point.Empty;
  341. for (int i = 0; i < lines.Count; i++) {
  342. var x = lines [i];
  343. var txt = GetText (x);
  344. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  345. var col = txt.IndexOf (matchText);
  346. while (col > -1) {
  347. if (matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  348. if (col + 1 > txt.Length) {
  349. break;
  350. }
  351. col = txt.IndexOf (matchText, col + 1);
  352. continue;
  353. }
  354. if (col > -1) {
  355. if (!found) {
  356. found = true;
  357. }
  358. lines [i] = ReplaceText (x, textToReplace, matchText, col).ToRuneList ();
  359. x = lines [i];
  360. txt = GetText (x);
  361. pos = new Point (col, i);
  362. col += (textToReplace.Length - matchText.Length);
  363. }
  364. if (col + 1 > txt.Length) {
  365. break;
  366. }
  367. col = txt.IndexOf (matchText, col + 1);
  368. }
  369. }
  370. string GetText (List<Rune> x)
  371. {
  372. var txt = ustring.Make (x).ToString ();
  373. if (!matchCase) {
  374. txt = txt.ToUpper ();
  375. }
  376. return txt;
  377. }
  378. return (pos, found);
  379. }
  380. ustring ReplaceText (List<Rune> source, ustring textToReplace, string matchText, int col)
  381. {
  382. var origTxt = ustring.Make (source);
  383. (int _, int len) = TextModel.DisplaySize (source, 0, col, false);
  384. (var _, var len2) = TextModel.DisplaySize (source, col, col + matchText.Length, false);
  385. (var _, var len3) = TextModel.DisplaySize (source, col + matchText.Length, origTxt.RuneCount, false);
  386. return origTxt [0, len] +
  387. textToReplace.ToString () +
  388. origTxt [len + len2, len + len2 + len3];
  389. }
  390. bool ApplyToFind ((Point current, bool found) foundPos)
  391. {
  392. bool gaveFullTurn = false;
  393. if (foundPos.found) {
  394. toFind.currentPointToFind = foundPos.current;
  395. if (toFind.found && toFind.currentPointToFind == toFind.startPointToFind) {
  396. gaveFullTurn = true;
  397. }
  398. if (!toFind.found) {
  399. toFind.startPointToFind = toFind.currentPointToFind = foundPos.current;
  400. toFind.found = foundPos.found;
  401. }
  402. }
  403. return gaveFullTurn;
  404. }
  405. (Point current, bool found) GetFoundNextTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  406. {
  407. for (int i = start.Y; i < linesCount; i++) {
  408. var x = lines [i];
  409. var txt = ustring.Make (x).ToString ();
  410. if (!matchCase) {
  411. txt = txt.ToUpper ();
  412. }
  413. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  414. var col = txt.IndexOf (matchText, Math.Min (start.X, txt.Length));
  415. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  416. continue;
  417. }
  418. if (col > -1 && ((i == start.Y && col >= start.X)
  419. || i > start.Y)
  420. && txt.Contains (matchText)) {
  421. return (new Point (col, i), true);
  422. } else if (col == -1 && start.X > 0) {
  423. start.X = 0;
  424. }
  425. }
  426. return (Point.Empty, false);
  427. }
  428. (Point current, bool found) GetFoundPreviousTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  429. {
  430. for (int i = linesCount; i >= 0; i--) {
  431. var x = lines [i];
  432. var txt = ustring.Make (x).ToString ();
  433. if (!matchCase) {
  434. txt = txt.ToUpper ();
  435. }
  436. if (start.Y != i) {
  437. start.X = Math.Max (x.Count - 1, 0);
  438. }
  439. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  440. var col = txt.LastIndexOf (matchText, toFind.found ? start.X - 1 : start.X);
  441. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  442. continue;
  443. }
  444. if (col > -1 && ((i <= linesCount && col <= start.X)
  445. || i < start.Y)
  446. && txt.Contains (matchText)) {
  447. return (new Point (col, i), true);
  448. }
  449. }
  450. return (Point.Empty, false);
  451. }
  452. bool MatchWholeWord (string source, string matchText, int index = 0)
  453. {
  454. if (string.IsNullOrEmpty (source) || string.IsNullOrEmpty (matchText)) {
  455. return false;
  456. }
  457. var txt = matchText.Trim ();
  458. var start = index > 0 ? index - 1 : 0;
  459. var end = index + txt.Length;
  460. if ((start == 0 || Rune.IsWhiteSpace (source [start]))
  461. && (end == source.Length || Rune.IsWhiteSpace (source [end]))) {
  462. return true;
  463. }
  464. return false;
  465. }
  466. /// <summary>
  467. /// Redefine column and line tracking.
  468. /// </summary>
  469. /// <param name="point">Contains the column and line.</param>
  470. internal void ResetContinuousFind (Point point)
  471. {
  472. toFind.startPointToFind = toFind.currentPointToFind = point;
  473. toFind.found = false;
  474. }
  475. }
  476. class HistoryText {
  477. public enum LineStatus {
  478. Original,
  479. Replaced,
  480. Removed,
  481. Added
  482. }
  483. public class HistoryTextItem {
  484. public List<List<Rune>> Lines;
  485. public Point CursorPosition;
  486. public LineStatus LineStatus;
  487. public bool IsUndoing;
  488. public Point FinalCursorPosition;
  489. public HistoryTextItem RemovedOnAdded;
  490. public HistoryTextItem (List<List<Rune>> lines, Point curPos, LineStatus linesStatus)
  491. {
  492. Lines = lines;
  493. CursorPosition = curPos;
  494. LineStatus = linesStatus;
  495. }
  496. public HistoryTextItem (HistoryTextItem historyTextItem)
  497. {
  498. Lines = new List<List<Rune>> (historyTextItem.Lines);
  499. CursorPosition = new Point (historyTextItem.CursorPosition.X, historyTextItem.CursorPosition.Y);
  500. LineStatus = historyTextItem.LineStatus;
  501. }
  502. public override string ToString ()
  503. {
  504. return $"(Count: {Lines.Count}, Cursor: {CursorPosition}, Status: {LineStatus})";
  505. }
  506. }
  507. List<HistoryTextItem> historyTextItems = new List<HistoryTextItem> ();
  508. int idxHistoryText = -1;
  509. ustring originalText;
  510. public bool IsFromHistory { get; private set; }
  511. public bool HasHistoryChanges => idxHistoryText > -1;
  512. public event Action<HistoryTextItem> ChangeText;
  513. public void Add (List<List<Rune>> lines, Point curPos, LineStatus lineStatus = LineStatus.Original)
  514. {
  515. if (lineStatus == LineStatus.Original && historyTextItems.Count > 0
  516. && historyTextItems.Last ().LineStatus == LineStatus.Original) {
  517. return;
  518. }
  519. if (lineStatus == LineStatus.Replaced && historyTextItems.Count > 0
  520. && historyTextItems.Last ().LineStatus == LineStatus.Replaced) {
  521. return;
  522. }
  523. if (historyTextItems.Count == 0 && lineStatus != LineStatus.Original)
  524. throw new ArgumentException ("The first item must be the original.");
  525. if (idxHistoryText >= 0 && idxHistoryText + 1 < historyTextItems.Count)
  526. historyTextItems.RemoveRange (idxHistoryText + 1, historyTextItems.Count - idxHistoryText - 1);
  527. historyTextItems.Add (new HistoryTextItem (lines, curPos, lineStatus));
  528. idxHistoryText++;
  529. }
  530. public void ReplaceLast (List<List<Rune>> lines, Point curPos, LineStatus lineStatus)
  531. {
  532. var found = historyTextItems.FindLast (x => x.LineStatus == lineStatus);
  533. if (found != null) {
  534. found.Lines = lines;
  535. found.CursorPosition = curPos;
  536. }
  537. }
  538. public void Undo ()
  539. {
  540. if (historyTextItems?.Count > 0 && idxHistoryText > 0) {
  541. IsFromHistory = true;
  542. idxHistoryText--;
  543. var historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]) {
  544. IsUndoing = true
  545. };
  546. ProcessChanges (ref historyTextItem);
  547. IsFromHistory = false;
  548. }
  549. }
  550. public void Redo ()
  551. {
  552. if (historyTextItems?.Count > 0 && idxHistoryText < historyTextItems.Count - 1) {
  553. IsFromHistory = true;
  554. idxHistoryText++;
  555. var historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]) {
  556. IsUndoing = false
  557. };
  558. ProcessChanges (ref historyTextItem);
  559. IsFromHistory = false;
  560. }
  561. }
  562. void ProcessChanges (ref HistoryTextItem historyTextItem)
  563. {
  564. if (historyTextItem.IsUndoing) {
  565. if (idxHistoryText - 1 > -1 && ((historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Added)
  566. || historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed
  567. || (historyTextItem.LineStatus == LineStatus.Replaced &&
  568. historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original))) {
  569. idxHistoryText--;
  570. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Added
  571. && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  572. idxHistoryText--;
  573. }
  574. historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]);
  575. historyTextItem.IsUndoing = true;
  576. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  577. }
  578. if (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Added) {
  579. historyTextItem.RemovedOnAdded = new HistoryTextItem (historyTextItems [idxHistoryText + 1]);
  580. }
  581. if ((historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original)
  582. || (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original)
  583. || (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed)) {
  584. if (!historyTextItem.Lines [0].SequenceEqual (historyTextItems [idxHistoryText - 1].Lines [0])
  585. && historyTextItem.CursorPosition == historyTextItems [idxHistoryText - 1].CursorPosition) {
  586. historyTextItem.Lines [0] = new List<Rune> (historyTextItems [idxHistoryText - 1].Lines [0]);
  587. }
  588. if (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  589. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText - 2].CursorPosition;
  590. } else {
  591. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText - 1].CursorPosition;
  592. }
  593. } else {
  594. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  595. }
  596. OnChangeText (historyTextItem);
  597. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Removed
  598. || historyTextItems [idxHistoryText].LineStatus == LineStatus.Added) {
  599. idxHistoryText--;
  600. }
  601. } else if (!historyTextItem.IsUndoing) {
  602. if (idxHistoryText + 1 < historyTextItems.Count && (historyTextItem.LineStatus == LineStatus.Original
  603. || historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Added
  604. || historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Removed)) {
  605. idxHistoryText++;
  606. historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]);
  607. historyTextItem.IsUndoing = false;
  608. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  609. }
  610. if (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  611. historyTextItem.RemovedOnAdded = new HistoryTextItem (historyTextItems [idxHistoryText - 1]);
  612. }
  613. if ((historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Replaced)
  614. || (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Original)
  615. || (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Replaced)) {
  616. if (historyTextItem.LineStatus == LineStatus.Removed
  617. && !historyTextItem.Lines [0].SequenceEqual (historyTextItems [idxHistoryText + 1].Lines [0])) {
  618. historyTextItem.Lines [0] = new List<Rune> (historyTextItems [idxHistoryText + 1].Lines [0]);
  619. }
  620. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText + 1].CursorPosition;
  621. } else {
  622. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  623. }
  624. OnChangeText (historyTextItem);
  625. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Removed
  626. || historyTextItems [idxHistoryText].LineStatus == LineStatus.Added) {
  627. idxHistoryText++;
  628. }
  629. }
  630. }
  631. void OnChangeText (HistoryTextItem lines)
  632. {
  633. ChangeText?.Invoke (lines);
  634. }
  635. public void Clear (ustring text)
  636. {
  637. historyTextItems.Clear ();
  638. idxHistoryText = -1;
  639. originalText = text;
  640. }
  641. public bool IsDirty (ustring text)
  642. {
  643. return originalText != text;
  644. }
  645. }
  646. class WordWrapManager {
  647. class WrappedLine {
  648. public int ModelLine;
  649. public int Row;
  650. public int RowIndex;
  651. public int ColWidth;
  652. }
  653. List<WrappedLine> wrappedModelLines = new List<WrappedLine> ();
  654. int frameWidth;
  655. bool isWrapModelRefreshing;
  656. public TextModel Model { get; private set; }
  657. public WordWrapManager (TextModel model)
  658. {
  659. Model = model;
  660. }
  661. public TextModel WrapModel (int width, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  662. int row = 0, int col = 0, int startRow = 0, int startCol = 0, int tabWidth = 0)
  663. {
  664. frameWidth = width;
  665. var modelRow = isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  666. var modelCol = isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  667. var modelStartRow = isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  668. var modelStartCol = isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  669. var wrappedModel = new TextModel ();
  670. int lines = 0;
  671. nRow = 0;
  672. nCol = 0;
  673. nStartRow = 0;
  674. nStartCol = 0;
  675. bool isRowAndColSetted = row == 0 && col == 0;
  676. bool isStartRowAndColSetted = startRow == 0 && startCol == 0;
  677. List<WrappedLine> wModelLines = new List<WrappedLine> ();
  678. for (int i = 0; i < Model.Count; i++) {
  679. var line = Model.GetLine (i);
  680. var wrappedLines = ToListRune (
  681. TextFormatter.Format (ustring.Make (line), width,
  682. TextAlignment.Left, true, true, tabWidth));
  683. int sumColWidth = 0;
  684. for (int j = 0; j < wrappedLines.Count; j++) {
  685. var wrapLine = wrappedLines [j];
  686. if (!isRowAndColSetted && modelRow == i) {
  687. if (nCol + wrapLine.Count <= modelCol) {
  688. nCol += wrapLine.Count;
  689. nRow = lines;
  690. if (nCol == modelCol) {
  691. nCol = wrapLine.Count;
  692. isRowAndColSetted = true;
  693. } else if (j == wrappedLines.Count - 1) {
  694. nCol = wrapLine.Count - j + modelCol - nCol;
  695. isRowAndColSetted = true;
  696. }
  697. } else {
  698. var offset = nCol + wrapLine.Count - modelCol;
  699. nCol = wrapLine.Count - offset;
  700. nRow = lines;
  701. isRowAndColSetted = true;
  702. }
  703. }
  704. if (!isStartRowAndColSetted && modelStartRow == i) {
  705. if (nStartCol + wrapLine.Count <= modelStartCol) {
  706. nStartCol += wrapLine.Count;
  707. nStartRow = lines;
  708. if (nStartCol == modelStartCol) {
  709. nStartCol = wrapLine.Count;
  710. isStartRowAndColSetted = true;
  711. } else if (j == wrappedLines.Count - 1) {
  712. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  713. isStartRowAndColSetted = true;
  714. }
  715. } else {
  716. var offset = nStartCol + wrapLine.Count - modelStartCol;
  717. nStartCol = wrapLine.Count - offset;
  718. nStartRow = lines;
  719. isStartRowAndColSetted = true;
  720. }
  721. }
  722. wrappedModel.AddLine (lines, wrapLine);
  723. sumColWidth += wrapLine.Count;
  724. var wrappedLine = new WrappedLine () {
  725. ModelLine = i,
  726. Row = lines,
  727. RowIndex = j,
  728. ColWidth = wrapLine.Count,
  729. };
  730. wModelLines.Add (wrappedLine);
  731. lines++;
  732. }
  733. }
  734. wrappedModelLines = wModelLines;
  735. return wrappedModel;
  736. }
  737. public List<List<Rune>> ToListRune (List<ustring> textList)
  738. {
  739. var runesList = new List<List<Rune>> ();
  740. foreach (var text in textList) {
  741. runesList.Add (text.ToRuneList ());
  742. }
  743. return runesList;
  744. }
  745. public int GetModelLineFromWrappedLines (int line) => wrappedModelLines.Count > 0
  746. ? wrappedModelLines [Math.Min (line, wrappedModelLines.Count - 1)].ModelLine
  747. : 0;
  748. public int GetModelColFromWrappedLines (int line, int col)
  749. {
  750. if (wrappedModelLines?.Count == 0) {
  751. return 0;
  752. }
  753. var modelLine = GetModelLineFromWrappedLines (line);
  754. var firstLine = wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  755. int modelCol = 0;
  756. for (int i = firstLine; i <= line; i++) {
  757. var wLine = wrappedModelLines [i];
  758. if (i < line) {
  759. modelCol += wLine.ColWidth;
  760. } else {
  761. modelCol += col;
  762. }
  763. }
  764. return modelCol;
  765. }
  766. List<Rune> GetCurrentLine (int row) => Model.GetLine (row);
  767. public void AddLine (int row, int col)
  768. {
  769. var modelRow = GetModelLineFromWrappedLines (row);
  770. var modelCol = GetModelColFromWrappedLines (row, col);
  771. var line = GetCurrentLine (modelRow);
  772. var restCount = line.Count - modelCol;
  773. var rest = line.GetRange (modelCol, restCount);
  774. line.RemoveRange (modelCol, restCount);
  775. Model.AddLine (modelRow + 1, rest);
  776. isWrapModelRefreshing = true;
  777. WrapModel (frameWidth, out _, out _, out _, out _, modelRow + 1, 0);
  778. isWrapModelRefreshing = false;
  779. }
  780. public bool Insert (int row, int col, Rune rune)
  781. {
  782. var line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  783. line.Insert (GetModelColFromWrappedLines (row, col), rune);
  784. if (line.Count > frameWidth) {
  785. return true;
  786. } else {
  787. return false;
  788. }
  789. }
  790. public bool RemoveAt (int row, int col)
  791. {
  792. var modelRow = GetModelLineFromWrappedLines (row);
  793. var line = GetCurrentLine (modelRow);
  794. var modelCol = GetModelColFromWrappedLines (row, col);
  795. if (modelCol >= line.Count) {
  796. Model.RemoveLine (modelRow);
  797. RemoveAt (row, 0);
  798. return false;
  799. }
  800. line.RemoveAt (modelCol);
  801. if (line.Count > frameWidth || (row + 1 < wrappedModelLines.Count
  802. && wrappedModelLines [row + 1].ModelLine == modelRow)) {
  803. return true;
  804. }
  805. return false;
  806. }
  807. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  808. {
  809. lineRemoved = false;
  810. var modelRow = GetModelLineFromWrappedLines (row);
  811. var line = GetCurrentLine (modelRow);
  812. var modelCol = GetModelColFromWrappedLines (row, col);
  813. if (modelCol == 0 && line.Count == 0) {
  814. Model.RemoveLine (modelRow);
  815. return false;
  816. } else if (modelCol < line.Count) {
  817. if (forward) {
  818. line.RemoveAt (modelCol);
  819. return true;
  820. } else if (modelCol - 1 > -1) {
  821. line.RemoveAt (modelCol - 1);
  822. return true;
  823. }
  824. }
  825. lineRemoved = true;
  826. if (forward) {
  827. if (modelRow + 1 == Model.Count) {
  828. return false;
  829. }
  830. var nextLine = Model.GetLine (modelRow + 1);
  831. line.AddRange (nextLine);
  832. Model.RemoveLine (modelRow + 1);
  833. if (line.Count > frameWidth) {
  834. return true;
  835. }
  836. } else {
  837. if (modelRow == 0) {
  838. return false;
  839. }
  840. var prevLine = Model.GetLine (modelRow - 1);
  841. prevLine.AddRange (line);
  842. Model.RemoveLine (modelRow);
  843. if (prevLine.Count > frameWidth) {
  844. return true;
  845. }
  846. }
  847. return false;
  848. }
  849. public bool RemoveRange (int row, int index, int count)
  850. {
  851. var modelRow = GetModelLineFromWrappedLines (row);
  852. var line = GetCurrentLine (modelRow);
  853. var modelCol = GetModelColFromWrappedLines (row, index);
  854. try {
  855. line.RemoveRange (modelCol, count);
  856. } catch (Exception) {
  857. return false;
  858. }
  859. return true;
  860. }
  861. public void UpdateModel (TextModel model, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  862. int row, int col, int startRow, int startCol)
  863. {
  864. isWrapModelRefreshing = true;
  865. Model = model;
  866. WrapModel (frameWidth, out nRow, out nCol, out nStartRow, out nStartCol, row, col, startRow, startCol);
  867. isWrapModelRefreshing = false;
  868. }
  869. }
  870. /// <summary>
  871. /// Multi-line text editing <see cref="View"/>
  872. /// </summary>
  873. /// <remarks>
  874. /// <para>
  875. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  876. /// with it with the standard Emacs commands for movement or the arrow
  877. /// keys.
  878. /// </para>
  879. /// <list type="table">
  880. /// <listheader>
  881. /// <term>Shortcut</term>
  882. /// <description>Action performed</description>
  883. /// </listheader>
  884. /// <item>
  885. /// <term>Left cursor, Control-b</term>
  886. /// <description>
  887. /// Moves the editing point left.
  888. /// </description>
  889. /// </item>
  890. /// <item>
  891. /// <term>Right cursor, Control-f</term>
  892. /// <description>
  893. /// Moves the editing point right.
  894. /// </description>
  895. /// </item>
  896. /// <item>
  897. /// <term>Alt-b</term>
  898. /// <description>
  899. /// Moves one word back.
  900. /// </description>
  901. /// </item>
  902. /// <item>
  903. /// <term>Alt-f</term>
  904. /// <description>
  905. /// Moves one word forward.
  906. /// </description>
  907. /// </item>
  908. /// <item>
  909. /// <term>Up cursor, Control-p</term>
  910. /// <description>
  911. /// Moves the editing point one line up.
  912. /// </description>
  913. /// </item>
  914. /// <item>
  915. /// <term>Down cursor, Control-n</term>
  916. /// <description>
  917. /// Moves the editing point one line down
  918. /// </description>
  919. /// </item>
  920. /// <item>
  921. /// <term>Home key, Control-a</term>
  922. /// <description>
  923. /// Moves the cursor to the beginning of the line.
  924. /// </description>
  925. /// </item>
  926. /// <item>
  927. /// <term>End key, Control-e</term>
  928. /// <description>
  929. /// Moves the cursor to the end of the line.
  930. /// </description>
  931. /// </item>
  932. /// <item>
  933. /// <term>Control-Home</term>
  934. /// <description>
  935. /// Scrolls to the first line and moves the cursor there.
  936. /// </description>
  937. /// </item>
  938. /// <item>
  939. /// <term>Control-End</term>
  940. /// <description>
  941. /// Scrolls to the last line and moves the cursor there.
  942. /// </description>
  943. /// </item>
  944. /// <item>
  945. /// <term>Delete, Control-d</term>
  946. /// <description>
  947. /// Deletes the character in front of the cursor.
  948. /// </description>
  949. /// </item>
  950. /// <item>
  951. /// <term>Backspace</term>
  952. /// <description>
  953. /// Deletes the character behind the cursor.
  954. /// </description>
  955. /// </item>
  956. /// <item>
  957. /// <term>Control-k</term>
  958. /// <description>
  959. /// Deletes the text until the end of the line and replaces the kill buffer
  960. /// with the deleted text. You can paste this text in a different place by
  961. /// using Control-y.
  962. /// </description>
  963. /// </item>
  964. /// <item>
  965. /// <term>Control-y</term>
  966. /// <description>
  967. /// Pastes the content of the kill ring into the current position.
  968. /// </description>
  969. /// </item>
  970. /// <item>
  971. /// <term>Alt-d</term>
  972. /// <description>
  973. /// Deletes the word above the cursor and adds it to the kill ring. You
  974. /// can paste the contents of the kill ring with Control-y.
  975. /// </description>
  976. /// </item>
  977. /// <item>
  978. /// <term>Control-q</term>
  979. /// <description>
  980. /// Quotes the next input character, to prevent the normal processing of
  981. /// key handling to take place.
  982. /// </description>
  983. /// </item>
  984. /// </list>
  985. /// </remarks>
  986. public class TextView : View {
  987. TextModel model = new TextModel ();
  988. int topRow;
  989. int leftColumn;
  990. int currentRow;
  991. int currentColumn;
  992. int selectionStartColumn, selectionStartRow;
  993. bool selecting;
  994. bool wordWrap;
  995. WordWrapManager wrapManager;
  996. bool continuousFind;
  997. int bottomOffset, rightOffset;
  998. int tabWidth = 4;
  999. bool allowsTab = true;
  1000. bool allowsReturn = true;
  1001. bool multiline = true;
  1002. HistoryText historyText = new HistoryText ();
  1003. /// <summary>
  1004. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  1005. /// </summary>
  1006. public event Action TextChanged;
  1007. /// <summary>
  1008. /// Provides autocomplete context menu based on suggestions at the current cursor
  1009. /// position. Populate <see cref="Autocomplete.AllSuggestions"/> to enable this feature
  1010. /// </summary>
  1011. public IAutocomplete Autocomplete { get; protected set; } = new TextViewAutocomplete ();
  1012. #if false
  1013. /// <summary>
  1014. /// Changed event, raised when the text has clicked.
  1015. /// </summary>
  1016. /// <remarks>
  1017. /// Client code can hook up to this event, it is
  1018. /// raised when the text in the entry changes.
  1019. /// </remarks>
  1020. public Action Changed;
  1021. #endif
  1022. /// <summary>
  1023. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  1024. /// </summary>
  1025. /// <remarks>
  1026. /// </remarks>
  1027. public TextView (Rect frame) : base (frame)
  1028. {
  1029. Initialize ();
  1030. }
  1031. /// <summary>
  1032. /// Initializes a <see cref="TextView"/> on the specified area,
  1033. /// with dimensions controlled with the X, Y, Width and Height properties.
  1034. /// </summary>
  1035. public TextView () : base ()
  1036. {
  1037. Initialize ();
  1038. }
  1039. void Initialize ()
  1040. {
  1041. CanFocus = true;
  1042. Used = true;
  1043. model.LinesLoaded += Model_LinesLoaded;
  1044. historyText.ChangeText += HistoryText_ChangeText;
  1045. Initialized += TextView_Initialized;
  1046. // Things this view knows how to do
  1047. AddCommand (Command.PageDown, () => { ProcessPageDown (); return true; });
  1048. AddCommand (Command.PageDownExtend, () => { ProcessPageDownExtend (); return true; });
  1049. AddCommand (Command.PageUp, () => { ProcessPageUp (); return true; });
  1050. AddCommand (Command.PageUpExtend, () => { ProcessPageUpExtend (); return true; });
  1051. AddCommand (Command.LineDown, () => { ProcessMoveDown (); return true; });
  1052. AddCommand (Command.LineDownExtend, () => { ProcessMoveDownExtend (); return true; });
  1053. AddCommand (Command.LineUp, () => { ProcessMoveUp (); return true; });
  1054. AddCommand (Command.LineUpExtend, () => { ProcessMoveUpExtend (); return true; });
  1055. AddCommand (Command.Right, () => ProcessMoveRight ());
  1056. AddCommand (Command.RightExtend, () => { ProcessMoveRightExtend (); return true; });
  1057. AddCommand (Command.Left, () => ProcessMoveLeft ());
  1058. AddCommand (Command.LeftExtend, () => { ProcessMoveLeftExtend (); return true; });
  1059. AddCommand (Command.DeleteCharLeft, () => { ProcessDeleteCharLeft (); return true; });
  1060. AddCommand (Command.StartOfLine, () => { ProcessMoveStartOfLine (); return true; });
  1061. AddCommand (Command.StartOfLineExtend, () => { ProcessMoveStartOfLineExtend (); return true; });
  1062. AddCommand (Command.DeleteCharRight, () => { ProcessDeleteCharRight (); return true; });
  1063. AddCommand (Command.EndOfLine, () => { ProcessMoveEndOfLine (); return true; });
  1064. AddCommand (Command.EndOfLineExtend, () => { ProcessMoveEndOfLineExtend (); return true; });
  1065. AddCommand (Command.CutToEndLine, () => { KillToEndOfLine (); return true; });
  1066. AddCommand (Command.CutToStartLine, () => { KillToStartOfLine (); return true; });
  1067. AddCommand (Command.Paste, () => { ProcessPaste (); return true; });
  1068. AddCommand (Command.ToggleExtend, () => { ToggleSelecting (); return true; });
  1069. AddCommand (Command.Copy, () => { ProcessCopy (); return true; });
  1070. AddCommand (Command.Cut, () => { ProcessCut (); return true; });
  1071. AddCommand (Command.WordLeft, () => { ProcessMoveWordBackward (); return true; });
  1072. AddCommand (Command.WordLeftExtend, () => { ProcessMoveWordBackwardExtend (); return true; });
  1073. AddCommand (Command.WordRight, () => { ProcessMoveWordForward (); return true; });
  1074. AddCommand (Command.WordRightExtend, () => { ProcessMoveWordForwardExtend (); return true; });
  1075. AddCommand (Command.KillWordForwards, () => { ProcessKillWordForward (); return true; });
  1076. AddCommand (Command.KillWordBackwards, () => { ProcessKillWordBackward (); return true; });
  1077. AddCommand (Command.NewLine, () => ProcessReturn ());
  1078. AddCommand (Command.BottomEnd, () => { MoveBottomEnd (); return true; });
  1079. AddCommand (Command.BottomEndExtend, () => { MoveBottomEndExtend (); return true; });
  1080. AddCommand (Command.TopHome, () => { MoveTopHome (); return true; });
  1081. AddCommand (Command.TopHomeExtend, () => { MoveTopHomeExtend (); return true; });
  1082. AddCommand (Command.SelectAll, () => { ProcessSelectAll (); return true; });
  1083. AddCommand (Command.ToggleOverwrite, () => { ProcessSetOverwrite (); return true; });
  1084. AddCommand (Command.EnableOverwrite, () => { SetOverwrite (true); return true; });
  1085. AddCommand (Command.DisableOverwrite, () => { SetOverwrite (false); return true; });
  1086. AddCommand (Command.Tab, () => ProcessTab ());
  1087. AddCommand (Command.BackTab, () => ProcessBackTab ());
  1088. AddCommand (Command.NextView, () => ProcessMoveNextView ());
  1089. AddCommand (Command.PreviousView, () => ProcessMovePreviousView ());
  1090. AddCommand (Command.Undo, () => { UndoChanges (); return true; });
  1091. AddCommand (Command.Redo, () => { RedoChanges (); return true; });
  1092. // Default keybindings for this view
  1093. AddKeyBinding (Key.PageDown, Command.PageDown);
  1094. AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
  1095. AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
  1096. AddKeyBinding (Key.PageUp, Command.PageUp);
  1097. AddKeyBinding (((int)'V' + Key.AltMask), Command.PageUp);
  1098. AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
  1099. AddKeyBinding (Key.N | Key.CtrlMask, Command.LineDown);
  1100. AddKeyBinding (Key.CursorDown, Command.LineDown);
  1101. AddKeyBinding (Key.CursorDown | Key.ShiftMask, Command.LineDownExtend);
  1102. AddKeyBinding (Key.P | Key.CtrlMask, Command.LineUp);
  1103. AddKeyBinding (Key.CursorUp, Command.LineUp);
  1104. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
  1105. AddKeyBinding (Key.F | Key.CtrlMask, Command.Right);
  1106. AddKeyBinding (Key.CursorRight, Command.Right);
  1107. AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
  1108. AddKeyBinding (Key.B | Key.CtrlMask, Command.Left);
  1109. AddKeyBinding (Key.CursorLeft, Command.Left);
  1110. AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
  1111. AddKeyBinding (Key.Delete, Command.DeleteCharLeft);
  1112. AddKeyBinding (Key.Backspace, Command.DeleteCharLeft);
  1113. AddKeyBinding (Key.Home, Command.StartOfLine);
  1114. AddKeyBinding (Key.A | Key.CtrlMask, Command.StartOfLine);
  1115. AddKeyBinding (Key.Home | Key.ShiftMask, Command.StartOfLineExtend);
  1116. AddKeyBinding (Key.DeleteChar, Command.DeleteCharRight);
  1117. AddKeyBinding (Key.D | Key.CtrlMask, Command.DeleteCharRight);
  1118. AddKeyBinding (Key.End, Command.EndOfLine);
  1119. AddKeyBinding (Key.E | Key.CtrlMask, Command.EndOfLine);
  1120. AddKeyBinding (Key.End | Key.ShiftMask, Command.EndOfLineExtend);
  1121. AddKeyBinding (Key.K | Key.CtrlMask, Command.CutToEndLine); // kill-to-end
  1122. AddKeyBinding (Key.DeleteChar | Key.CtrlMask | Key.ShiftMask, Command.CutToEndLine); // kill-to-end
  1123. AddKeyBinding (Key.K | Key.AltMask, Command.CutToStartLine); // kill-to-start
  1124. AddKeyBinding (Key.Backspace | Key.CtrlMask | Key.ShiftMask, Command.CutToStartLine); // kill-to-start
  1125. AddKeyBinding (Key.Y | Key.CtrlMask, Command.Paste); // Control-y, yank
  1126. AddKeyBinding (Key.Space | Key.CtrlMask, Command.ToggleExtend);
  1127. AddKeyBinding (((int)'C' + Key.AltMask), Command.Copy);
  1128. AddKeyBinding (Key.C | Key.CtrlMask, Command.Copy);
  1129. AddKeyBinding (((int)'W' + Key.AltMask), Command.Cut);
  1130. AddKeyBinding (Key.W | Key.CtrlMask, Command.Cut);
  1131. AddKeyBinding (Key.X | Key.CtrlMask, Command.Cut);
  1132. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.WordLeft);
  1133. AddKeyBinding ((Key)((int)'B' + Key.AltMask), Command.WordLeft);
  1134. AddKeyBinding (Key.CursorLeft | Key.CtrlMask | Key.ShiftMask, Command.WordLeftExtend);
  1135. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.WordRight);
  1136. AddKeyBinding ((Key)((int)'F' + Key.AltMask), Command.WordRight);
  1137. AddKeyBinding (Key.CursorRight | Key.CtrlMask | Key.ShiftMask, Command.WordRightExtend);
  1138. AddKeyBinding (Key.DeleteChar | Key.CtrlMask, Command.KillWordForwards); // kill-word-forwards
  1139. AddKeyBinding (Key.Backspace | Key.CtrlMask, Command.KillWordBackwards); // kill-word-backwards
  1140. AddKeyBinding (Key.Enter, Command.NewLine);
  1141. AddKeyBinding (Key.End | Key.CtrlMask, Command.BottomEnd);
  1142. AddKeyBinding (Key.End | Key.CtrlMask | Key.ShiftMask, Command.BottomEndExtend);
  1143. AddKeyBinding (Key.Home | Key.CtrlMask, Command.TopHome);
  1144. AddKeyBinding (Key.Home | Key.CtrlMask | Key.ShiftMask, Command.TopHomeExtend);
  1145. AddKeyBinding (Key.T | Key.CtrlMask, Command.SelectAll);
  1146. AddKeyBinding (Key.InsertChar, Command.ToggleOverwrite);
  1147. AddKeyBinding (Key.Tab, Command.Tab);
  1148. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.BackTab);
  1149. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextView);
  1150. AddKeyBinding (Application.AlternateForwardKey, Command.NextView);
  1151. AddKeyBinding (Key.Tab | Key.CtrlMask | Key.ShiftMask, Command.PreviousView);
  1152. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousView);
  1153. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Undo);
  1154. AddKeyBinding (Key.R | Key.CtrlMask, Command.Redo);
  1155. }
  1156. private void Model_LinesLoaded ()
  1157. {
  1158. historyText.Clear (Text);
  1159. }
  1160. private void HistoryText_ChangeText (HistoryText.HistoryTextItem obj)
  1161. {
  1162. var startLine = obj.CursorPosition.Y;
  1163. if (obj.RemovedOnAdded != null) {
  1164. int offset;
  1165. if (obj.IsUndoing) {
  1166. offset = Math.Max (obj.RemovedOnAdded.Lines.Count - obj.Lines.Count, 1);
  1167. } else {
  1168. offset = obj.RemovedOnAdded.Lines.Count - 1;
  1169. }
  1170. for (int i = 0; i < offset; i++) {
  1171. if (Lines > obj.RemovedOnAdded.CursorPosition.Y) {
  1172. model.RemoveLine (obj.RemovedOnAdded.CursorPosition.Y);
  1173. } else {
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. for (int i = 0; i < obj.Lines.Count; i++) {
  1179. if (i == 0) {
  1180. model.ReplaceLine (startLine, obj.Lines [i]);
  1181. } else if ((obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Removed)
  1182. || !obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Added) {
  1183. model.AddLine (startLine, obj.Lines [i]);
  1184. } else if (Lines > obj.CursorPosition.Y + 1) {
  1185. model.RemoveLine (obj.CursorPosition.Y + 1);
  1186. }
  1187. startLine++;
  1188. }
  1189. CursorPosition = obj.FinalCursorPosition;
  1190. Adjust ();
  1191. }
  1192. void TextView_Initialized (object sender, EventArgs e)
  1193. {
  1194. Autocomplete.HostControl = this;
  1195. Application.Top.AlternateForwardKeyChanged += Top_AlternateForwardKeyChanged;
  1196. Application.Top.AlternateBackwardKeyChanged += Top_AlternateBackwardKeyChanged;
  1197. }
  1198. void Top_AlternateBackwardKeyChanged (Key obj)
  1199. {
  1200. ReplaceKeyBinding (obj, Application.AlternateBackwardKey);
  1201. }
  1202. void Top_AlternateForwardKeyChanged (Key obj)
  1203. {
  1204. ReplaceKeyBinding (obj, Application.AlternateForwardKey);
  1205. }
  1206. /// <summary>
  1207. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  1208. /// so new input should be appended at the cursor position, rather than clearing the entry
  1209. /// </summary>
  1210. public bool Used { get; set; }
  1211. void ResetPosition ()
  1212. {
  1213. topRow = leftColumn = currentRow = currentColumn = 0;
  1214. selecting = false;
  1215. shiftSelecting = false;
  1216. ResetCursorVisibility ();
  1217. }
  1218. /// <summary>
  1219. /// Sets or gets the text in the <see cref="TextView"/>.
  1220. /// </summary>
  1221. /// <remarks>
  1222. /// </remarks>
  1223. public override ustring Text {
  1224. get {
  1225. if (wordWrap) {
  1226. return wrapManager.Model.ToString ();
  1227. } else {
  1228. return model.ToString ();
  1229. }
  1230. }
  1231. set {
  1232. ResetPosition ();
  1233. model.LoadString (value);
  1234. if (wordWrap) {
  1235. wrapManager = new WordWrapManager (model);
  1236. model = wrapManager.WrapModel (Frame.Width - 2, out _, out _, out _, out _);
  1237. }
  1238. TextChanged?.Invoke ();
  1239. SetNeedsDisplay ();
  1240. historyText.Clear (Text);
  1241. }
  1242. }
  1243. ///<inheritdoc/>
  1244. public override Rect Frame {
  1245. get => base.Frame;
  1246. set {
  1247. base.Frame = value;
  1248. WrapTextModel ();
  1249. Adjust ();
  1250. }
  1251. }
  1252. void WrapTextModel ()
  1253. {
  1254. if (wordWrap && wrapManager != null) {
  1255. model = wrapManager.WrapModel (Frame.Width - 2,
  1256. out int nRow, out int nCol,
  1257. out int nStartRow, out int nStartCol,
  1258. currentRow, currentColumn,
  1259. selectionStartRow, selectionStartColumn,
  1260. tabWidth);
  1261. currentRow = nRow;
  1262. currentColumn = nCol;
  1263. selectionStartRow = nStartRow;
  1264. selectionStartColumn = nStartCol;
  1265. SetNeedsDisplay ();
  1266. }
  1267. }
  1268. /// <summary>
  1269. /// Gets or sets the top row.
  1270. /// </summary>
  1271. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  1272. /// <summary>
  1273. /// Gets or sets the left column.
  1274. /// </summary>
  1275. public int LeftColumn { get => leftColumn; set => leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0); }
  1276. /// <summary>
  1277. /// Gets the maximum visible length line.
  1278. /// </summary>
  1279. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  1280. /// <summary>
  1281. /// Gets the number of lines.
  1282. /// </summary>
  1283. public int Lines => model.Count;
  1284. /// <summary>
  1285. /// Sets or gets the current cursor position.
  1286. /// </summary>
  1287. public Point CursorPosition {
  1288. get => new Point (currentColumn, currentRow);
  1289. set {
  1290. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  1291. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  1292. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  1293. ? Math.Max (model.Count - 1, 0) : value.Y;
  1294. SetNeedsDisplay ();
  1295. Adjust ();
  1296. }
  1297. }
  1298. /// <summary>
  1299. /// Start column position of the selected text.
  1300. /// </summary>
  1301. public int SelectionStartColumn {
  1302. get => selectionStartColumn;
  1303. set {
  1304. var line = model.GetLine (currentRow);
  1305. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  1306. selecting = true;
  1307. SetNeedsDisplay ();
  1308. Adjust ();
  1309. }
  1310. }
  1311. /// <summary>
  1312. /// Start row position of the selected text.
  1313. /// </summary>
  1314. public int SelectionStartRow {
  1315. get => selectionStartRow;
  1316. set {
  1317. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  1318. ? Math.Max (model.Count - 1, 0) : value;
  1319. selecting = true;
  1320. SetNeedsDisplay ();
  1321. Adjust ();
  1322. }
  1323. }
  1324. /// <summary>
  1325. /// The selected text.
  1326. /// </summary>
  1327. public ustring SelectedText {
  1328. get {
  1329. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  1330. return ustring.Empty;
  1331. }
  1332. SetWrapModel ();
  1333. var sel = GetRegion ();
  1334. UpdateWrapModel ();
  1335. Adjust ();
  1336. return sel;
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Length of the selected text.
  1341. /// </summary>
  1342. public int SelectedLength => GetSelectedLength ();
  1343. /// <summary>
  1344. /// Get or sets the selecting.
  1345. /// </summary>
  1346. public bool Selecting {
  1347. get => selecting;
  1348. set => selecting = value;
  1349. }
  1350. /// <summary>
  1351. /// Allows word wrap the to fit the available container width.
  1352. /// </summary>
  1353. public bool WordWrap {
  1354. get => wordWrap;
  1355. set {
  1356. if (value == wordWrap) {
  1357. return;
  1358. }
  1359. if (value && !multiline) {
  1360. return;
  1361. }
  1362. wordWrap = value;
  1363. ResetPosition ();
  1364. if (wordWrap) {
  1365. wrapManager = new WordWrapManager (model);
  1366. model = wrapManager.WrapModel (Math.Max (Frame.Width - 2, 0), out _, out _, out _, out _);
  1367. } else if (!wordWrap && wrapManager != null) {
  1368. model = wrapManager.Model;
  1369. }
  1370. SetNeedsDisplay ();
  1371. }
  1372. }
  1373. /// <summary>
  1374. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1375. /// This is only needed with the keyboard navigation.
  1376. /// </summary>
  1377. public int BottomOffset {
  1378. get => bottomOffset;
  1379. set {
  1380. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1381. topRow = Math.Max (topRow - bottomOffset, 0);
  1382. }
  1383. bottomOffset = value;
  1384. Adjust ();
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// The right offset needed to use a vertical scrollbar or for another reason.
  1389. /// This is only needed with the keyboard navigation.
  1390. /// </summary>
  1391. public int RightOffset {
  1392. get => rightOffset;
  1393. set {
  1394. if (currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1395. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1396. }
  1397. rightOffset = value;
  1398. Adjust ();
  1399. }
  1400. }
  1401. /// <summary>
  1402. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1403. /// creates a new line of text in the view or activates the default button for the toplevel.
  1404. /// </summary>
  1405. public bool AllowsReturn {
  1406. get => allowsReturn;
  1407. set {
  1408. allowsReturn = value;
  1409. if (allowsReturn && !multiline) {
  1410. Multiline = true;
  1411. }
  1412. if (!allowsReturn && multiline) {
  1413. Multiline = false;
  1414. AllowsTab = false;
  1415. }
  1416. SetNeedsDisplay ();
  1417. }
  1418. }
  1419. /// <summary>
  1420. /// Gets or sets a value indicating whether pressing the TAB key in a <see cref="TextView"/>
  1421. /// types a TAB character in the view instead of moving the focus to the next view in the tab order.
  1422. /// </summary>
  1423. public bool AllowsTab {
  1424. get => allowsTab;
  1425. set {
  1426. allowsTab = value;
  1427. if (allowsTab && tabWidth == 0) {
  1428. tabWidth = 4;
  1429. }
  1430. if (allowsTab && !multiline) {
  1431. Multiline = true;
  1432. }
  1433. if (!allowsTab && tabWidth > 0) {
  1434. tabWidth = 0;
  1435. }
  1436. SetNeedsDisplay ();
  1437. }
  1438. }
  1439. /// <summary>
  1440. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1441. /// </summary>
  1442. public int TabWidth {
  1443. get => tabWidth;
  1444. set {
  1445. tabWidth = Math.Max (value, 0);
  1446. if (tabWidth > 0 && !AllowsTab) {
  1447. AllowsTab = true;
  1448. }
  1449. SetNeedsDisplay ();
  1450. }
  1451. }
  1452. Dim savedHeight = null;
  1453. /// <summary>
  1454. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1455. /// </summary>
  1456. public bool Multiline {
  1457. get => multiline;
  1458. set {
  1459. multiline = value;
  1460. if (multiline && !allowsTab) {
  1461. AllowsTab = true;
  1462. }
  1463. if (multiline && !allowsReturn) {
  1464. AllowsReturn = true;
  1465. }
  1466. if (!multiline) {
  1467. AllowsReturn = false;
  1468. AllowsTab = false;
  1469. WordWrap = false;
  1470. currentColumn = 0;
  1471. currentRow = 0;
  1472. savedHeight = Height;
  1473. var lyout = LayoutStyle;
  1474. if (LayoutStyle == LayoutStyle.Computed) {
  1475. LayoutStyle = LayoutStyle.Absolute;
  1476. }
  1477. Height = 1;
  1478. LayoutStyle = lyout;
  1479. Autocomplete.PopupInsideContainer = false;
  1480. SetNeedsDisplay ();
  1481. } else if (multiline && savedHeight != null) {
  1482. var lyout = LayoutStyle;
  1483. if (LayoutStyle == LayoutStyle.Computed) {
  1484. LayoutStyle = LayoutStyle.Absolute;
  1485. }
  1486. Height = savedHeight;
  1487. LayoutStyle = lyout;
  1488. Autocomplete.PopupInsideContainer = true;
  1489. SetNeedsDisplay ();
  1490. }
  1491. }
  1492. }
  1493. /// <summary>
  1494. /// Indicates whatever the text was changed or not.
  1495. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  1496. /// </summary>
  1497. public bool IsDirty => historyText.IsDirty (Text);
  1498. /// <summary>
  1499. /// Indicates whatever the text has history changes or not.
  1500. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  1501. /// </summary>
  1502. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  1503. int GetSelectedLength ()
  1504. {
  1505. return SelectedText.Length;
  1506. }
  1507. CursorVisibility savedCursorVisibility;
  1508. void SaveCursorVisibility ()
  1509. {
  1510. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1511. if (savedCursorVisibility == 0) {
  1512. savedCursorVisibility = desiredCursorVisibility;
  1513. }
  1514. DesiredCursorVisibility = CursorVisibility.Invisible;
  1515. }
  1516. }
  1517. void ResetCursorVisibility ()
  1518. {
  1519. if (savedCursorVisibility != 0) {
  1520. DesiredCursorVisibility = savedCursorVisibility;
  1521. savedCursorVisibility = 0;
  1522. }
  1523. }
  1524. /// <summary>
  1525. /// Loads the contents of the file into the <see cref="TextView"/>.
  1526. /// </summary>
  1527. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1528. /// <param name="path">Path to the file to load.</param>
  1529. public bool LoadFile (string path)
  1530. {
  1531. var res = model.LoadFile (path);
  1532. ResetPosition ();
  1533. SetNeedsDisplay ();
  1534. return res;
  1535. }
  1536. /// <summary>
  1537. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1538. /// </summary>
  1539. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1540. /// <param name="stream">Stream to load the contents from.</param>
  1541. public void LoadStream (Stream stream)
  1542. {
  1543. model.LoadStream (stream);
  1544. ResetPosition ();
  1545. SetNeedsDisplay ();
  1546. }
  1547. /// <summary>
  1548. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1549. /// </summary>
  1550. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1551. public bool CloseFile ()
  1552. {
  1553. var res = model.CloseFile ();
  1554. ResetPosition ();
  1555. SetNeedsDisplay ();
  1556. return res;
  1557. }
  1558. /// <summary>
  1559. /// Gets the current cursor row.
  1560. /// </summary>
  1561. public int CurrentRow => currentRow;
  1562. /// <summary>
  1563. /// Gets the cursor column.
  1564. /// </summary>
  1565. /// <value>The cursor column.</value>
  1566. public int CurrentColumn => currentColumn;
  1567. /// <summary>
  1568. /// Positions the cursor on the current row and column
  1569. /// </summary>
  1570. public override void PositionCursor ()
  1571. {
  1572. if (!CanFocus || !Enabled) {
  1573. return;
  1574. }
  1575. if (selecting) {
  1576. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1577. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1578. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1579. }
  1580. var line = model.GetLine (currentRow);
  1581. var col = 0;
  1582. if (line.Count > 0) {
  1583. for (int idx = leftColumn; idx < line.Count; idx++) {
  1584. if (idx >= currentColumn)
  1585. break;
  1586. var cols = Rune.ColumnWidth (line [idx]);
  1587. if (line [idx] == '\t') {
  1588. cols += TabWidth + 1;
  1589. }
  1590. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1591. col = currentColumn;
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. var posX = currentColumn - leftColumn;
  1597. var posY = currentRow - topRow;
  1598. if (posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1599. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1600. ResetCursorVisibility ();
  1601. Move (col, currentRow - topRow);
  1602. } else {
  1603. SaveCursorVisibility ();
  1604. }
  1605. }
  1606. void ClearRegion (int left, int top, int right, int bottom)
  1607. {
  1608. for (int row = top; row < bottom; row++) {
  1609. Move (left, row);
  1610. for (int col = left; col < right; col++)
  1611. AddRune (col, row, ' ');
  1612. }
  1613. }
  1614. /// <summary>
  1615. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1616. /// </summary>
  1617. protected virtual void ColorNormal ()
  1618. {
  1619. Driver.SetAttribute (GetNormalColor ());
  1620. }
  1621. /// <summary>
  1622. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1623. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1624. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1625. /// </summary>
  1626. /// <param name="line"></param>
  1627. /// <param name="idx"></param>
  1628. protected virtual void ColorNormal (List<Rune> line, int idx)
  1629. {
  1630. Driver.SetAttribute (GetNormalColor ());
  1631. }
  1632. /// <summary>
  1633. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1634. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1635. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1636. /// </summary>
  1637. /// <param name="line"></param>
  1638. /// <param name="idx"></param>
  1639. protected virtual void ColorSelection (List<Rune> line, int idx)
  1640. {
  1641. Driver.SetAttribute (ColorScheme.Focus);
  1642. }
  1643. /// <summary>
  1644. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1645. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1646. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1647. /// </summary>
  1648. /// <param name="line"></param>
  1649. /// <param name="idx"></param>
  1650. protected virtual void ColorUsed (List<Rune> line, int idx)
  1651. {
  1652. Driver.SetAttribute (ColorScheme.HotFocus);
  1653. }
  1654. bool isReadOnly = false;
  1655. /// <summary>
  1656. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1657. /// </summary>
  1658. /// <value>Boolean value(Default false)</value>
  1659. public bool ReadOnly {
  1660. get => isReadOnly;
  1661. set {
  1662. isReadOnly = value;
  1663. SetNeedsDisplay ();
  1664. }
  1665. }
  1666. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1667. /// <summary>
  1668. /// Get / Set the wished cursor when the field is focused
  1669. /// </summary>
  1670. public CursorVisibility DesiredCursorVisibility {
  1671. get => desiredCursorVisibility;
  1672. set {
  1673. if (HasFocus) {
  1674. Application.Driver.SetCursorVisibility (value);
  1675. }
  1676. desiredCursorVisibility = value;
  1677. SetNeedsDisplay ();
  1678. }
  1679. }
  1680. ///<inheritdoc/>
  1681. public override bool OnEnter (View view)
  1682. {
  1683. //TODO: Improve it by handling read only mode of the text field
  1684. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1685. return base.OnEnter (view);
  1686. }
  1687. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1688. void GetEncodedRegionBounds (out long start, out long end)
  1689. {
  1690. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1691. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1692. if (selection > point) {
  1693. start = point;
  1694. end = selection;
  1695. } else {
  1696. start = selection;
  1697. end = point;
  1698. }
  1699. }
  1700. bool PointInSelection (int col, int row)
  1701. {
  1702. long start, end;
  1703. GetEncodedRegionBounds (out start, out end);
  1704. var q = ((long)(uint)row << 32) | (uint)col;
  1705. return q >= start && q <= end - 1;
  1706. }
  1707. //
  1708. // Returns a ustring with the text in the selected
  1709. // region.
  1710. //
  1711. ustring GetRegion ()
  1712. {
  1713. long start, end;
  1714. GetEncodedRegionBounds (out start, out end);
  1715. if (start == end) {
  1716. return ustring.Empty;
  1717. }
  1718. int startRow = (int)(start >> 32);
  1719. var maxrow = ((int)(end >> 32));
  1720. int startCol = (int)(start & 0xffffffff);
  1721. var endCol = (int)(end & 0xffffffff);
  1722. var line = model.GetLine (startRow);
  1723. if (startRow == maxrow)
  1724. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1725. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1726. for (int row = startRow + 1; row < maxrow; row++) {
  1727. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (model.GetLine (row));
  1728. }
  1729. line = model.GetLine (maxrow);
  1730. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (line.GetRange (0, endCol));
  1731. return res;
  1732. }
  1733. //
  1734. // Clears the contents of the selected region
  1735. //
  1736. void ClearRegion ()
  1737. {
  1738. long start, end;
  1739. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1740. GetEncodedRegionBounds (out start, out end);
  1741. int startRow = (int)(start >> 32);
  1742. var maxrow = ((int)(end >> 32));
  1743. int startCol = (int)(start & 0xffffffff);
  1744. var endCol = (int)(end & 0xffffffff);
  1745. var line = model.GetLine (startRow);
  1746. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, new Point (startCol, startRow));
  1747. List<List<Rune>> removedLines = new List<List<Rune>> ();
  1748. if (startRow == maxrow) {
  1749. removedLines.Add (new List<Rune> (line));
  1750. line.RemoveRange (startCol, endCol - startCol);
  1751. currentColumn = startCol;
  1752. if (wordWrap) {
  1753. SetNeedsDisplay ();
  1754. } else {
  1755. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1756. }
  1757. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition, HistoryText.LineStatus.Removed);
  1758. return;
  1759. }
  1760. removedLines.Add (new List<Rune> (line));
  1761. line.RemoveRange (startCol, line.Count - startCol);
  1762. var line2 = model.GetLine (maxrow);
  1763. line.AddRange (line2.Skip (endCol));
  1764. for (int row = startRow + 1; row <= maxrow; row++) {
  1765. removedLines.Add (new List<Rune> (model.GetLine (startRow + 1)));
  1766. model.RemoveLine (startRow + 1);
  1767. }
  1768. if (currentEncoded == end) {
  1769. currentRow -= maxrow - (startRow);
  1770. }
  1771. currentColumn = startCol;
  1772. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  1773. HistoryText.LineStatus.Removed);
  1774. SetNeedsDisplay ();
  1775. }
  1776. /// <summary>
  1777. /// Select all text.
  1778. /// </summary>
  1779. public void SelectAll ()
  1780. {
  1781. if (model.Count == 0) {
  1782. return;
  1783. }
  1784. StartSelecting ();
  1785. selectionStartColumn = 0;
  1786. selectionStartRow = 0;
  1787. currentColumn = model.GetLine (model.Count - 1).Count;
  1788. currentRow = model.Count - 1;
  1789. SetNeedsDisplay ();
  1790. }
  1791. /// <summary>
  1792. /// Find the next text based on the match case with the option to replace it.
  1793. /// </summary>
  1794. /// <param name="textToFind">The text to find.</param>
  1795. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1796. /// <param name="matchCase">The match case setting.</param>
  1797. /// <param name="matchWholeWord">The match whole word setting.</param>
  1798. /// <param name="textToReplace">The text to replace.</param>
  1799. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1800. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1801. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1802. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1803. {
  1804. if (model.Count == 0) {
  1805. gaveFullTurn = false;
  1806. return false;
  1807. }
  1808. SetWrapModel ();
  1809. ResetContinuousFind ();
  1810. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1811. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1812. }
  1813. /// <summary>
  1814. /// Find the previous text based on the match case with the option to replace it.
  1815. /// </summary>
  1816. /// <param name="textToFind">The text to find.</param>
  1817. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1818. /// <param name="matchCase">The match case setting.</param>
  1819. /// <param name="matchWholeWord">The match whole word setting.</param>
  1820. /// <param name="textToReplace">The text to replace.</param>
  1821. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1822. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1823. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1824. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1825. {
  1826. if (model.Count == 0) {
  1827. gaveFullTurn = false;
  1828. return false;
  1829. }
  1830. SetWrapModel ();
  1831. ResetContinuousFind ();
  1832. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1833. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1834. }
  1835. /// <summary>
  1836. /// Reset the flag to stop continuous find.
  1837. /// </summary>
  1838. public void FindTextChanged ()
  1839. {
  1840. continuousFind = false;
  1841. }
  1842. /// <summary>
  1843. /// Replaces all the text based on the match case.
  1844. /// </summary>
  1845. /// <param name="textToFind">The text to find.</param>
  1846. /// <param name="matchCase">The match case setting.</param>
  1847. /// <param name="matchWholeWord">The match whole word setting.</param>
  1848. /// <param name="textToReplace">The text to replace.</param>
  1849. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1850. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1851. ustring textToReplace = null)
  1852. {
  1853. if (isReadOnly || model.Count == 0) {
  1854. return false;
  1855. }
  1856. SetWrapModel ();
  1857. ResetContinuousFind ();
  1858. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1859. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1860. }
  1861. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1862. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1863. {
  1864. if (foundPos.found) {
  1865. StartSelecting ();
  1866. selectionStartColumn = foundPos.current.X;
  1867. selectionStartRow = foundPos.current.Y;
  1868. if (!replaceAll) {
  1869. currentColumn = selectionStartColumn + text.RuneCount;
  1870. } else {
  1871. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1872. }
  1873. currentRow = foundPos.current.Y;
  1874. if (!isReadOnly && replace) {
  1875. Adjust ();
  1876. ClearSelectedRegion ();
  1877. InsertText (textToReplace);
  1878. StartSelecting ();
  1879. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1880. } else {
  1881. UpdateWrapModel ();
  1882. SetNeedsDisplay ();
  1883. Adjust ();
  1884. }
  1885. continuousFind = true;
  1886. return foundPos.found;
  1887. }
  1888. UpdateWrapModel ();
  1889. continuousFind = false;
  1890. return foundPos.found;
  1891. }
  1892. void ResetContinuousFind ()
  1893. {
  1894. if (!continuousFind) {
  1895. var col = selecting ? selectionStartColumn : currentColumn;
  1896. var row = selecting ? selectionStartRow : currentRow;
  1897. model.ResetContinuousFind (new Point (col, row));
  1898. }
  1899. }
  1900. /// <summary>
  1901. /// Restore from original model.
  1902. /// </summary>
  1903. void SetWrapModel ()
  1904. {
  1905. if (wordWrap) {
  1906. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  1907. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  1908. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  1909. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  1910. model = wrapManager.Model;
  1911. }
  1912. }
  1913. /// <summary>
  1914. /// Update the original model.
  1915. /// </summary>
  1916. void UpdateWrapModel ()
  1917. {
  1918. if (wordWrap) {
  1919. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  1920. out int nStartRow, out int nStartCol,
  1921. currentRow, currentColumn,
  1922. selectionStartRow, selectionStartColumn);
  1923. currentRow = nRow;
  1924. currentColumn = nCol;
  1925. selectionStartRow = nStartRow;
  1926. selectionStartColumn = nStartCol;
  1927. wrapNeeded = true;
  1928. }
  1929. }
  1930. ///<inheritdoc/>
  1931. public override void Redraw (Rect bounds)
  1932. {
  1933. ColorNormal ();
  1934. var offB = OffSetBackground ();
  1935. int right = Frame.Width + offB.width + RightOffset;
  1936. int bottom = Frame.Height + offB.height + BottomOffset;
  1937. var row = 0;
  1938. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  1939. var line = model.GetLine (idxRow);
  1940. int lineRuneCount = line.Count;
  1941. var col = 0;
  1942. Move (0, row);
  1943. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  1944. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  1945. var cols = Rune.ColumnWidth (rune);
  1946. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  1947. ColorSelection (line, idxCol);
  1948. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  1949. && HasFocus && idxCol < lineRuneCount) {
  1950. ColorUsed (line, idxCol);
  1951. } else {
  1952. ColorNormal (line, idxCol);
  1953. }
  1954. if (rune == '\t') {
  1955. cols += TabWidth + 1;
  1956. if (col + cols > right) {
  1957. cols = right - col;
  1958. }
  1959. for (int i = 0; i < cols; i++) {
  1960. if (col + i < right) {
  1961. AddRune (col + i, row, ' ');
  1962. }
  1963. }
  1964. } else {
  1965. AddRune (col, row, rune);
  1966. }
  1967. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  1968. break;
  1969. }
  1970. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  1971. break;
  1972. }
  1973. }
  1974. if (col < right) {
  1975. ColorNormal ();
  1976. ClearRegion (col, row, right, row + 1);
  1977. }
  1978. row++;
  1979. }
  1980. if (row < bottom) {
  1981. ColorNormal ();
  1982. ClearRegion (bounds.Left, row, right, bottom);
  1983. }
  1984. PositionCursor ();
  1985. if (SelectedLength > 0)
  1986. return;
  1987. // draw autocomplete
  1988. Autocomplete.GenerateSuggestions ();
  1989. var renderAt = new Point (
  1990. CursorPosition.X - LeftColumn,
  1991. Autocomplete.PopupInsideContainer
  1992. ? (CursorPosition.Y + 1) - TopRow
  1993. : 0);
  1994. Autocomplete.RenderOverlay (renderAt);
  1995. }
  1996. ///<inheritdoc/>
  1997. public override bool CanFocus {
  1998. get => base.CanFocus;
  1999. set { base.CanFocus = value; }
  2000. }
  2001. void SetClipboard (ustring text)
  2002. {
  2003. if (text != null) {
  2004. Clipboard.Contents = text;
  2005. }
  2006. }
  2007. void AppendClipboard (ustring text)
  2008. {
  2009. Clipboard.Contents += text;
  2010. }
  2011. /// <summary>
  2012. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  2013. /// exactly as if the user had just typed it
  2014. /// </summary>
  2015. /// <param name="toAdd">Text to add</param>
  2016. public void InsertText (string toAdd)
  2017. {
  2018. foreach (var ch in toAdd) {
  2019. Key key;
  2020. try {
  2021. key = (Key)ch;
  2022. } catch (Exception) {
  2023. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  2024. }
  2025. InsertText (new KeyEvent () { Key = key });
  2026. }
  2027. }
  2028. void Insert (Rune rune)
  2029. {
  2030. var line = GetCurrentLine ();
  2031. if (Used) {
  2032. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2033. } else {
  2034. if (currentColumn < line.Count) {
  2035. line.RemoveAt (currentColumn);
  2036. }
  2037. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2038. }
  2039. if (wordWrap) {
  2040. if (Used) {
  2041. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  2042. } else {
  2043. wrapNeeded = wrapManager.RemoveAt (currentRow, currentColumn);
  2044. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  2045. }
  2046. if (wrapNeeded) {
  2047. SetNeedsDisplay ();
  2048. }
  2049. }
  2050. var prow = currentRow - topRow;
  2051. if (!wrapNeeded) {
  2052. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  2053. }
  2054. }
  2055. ustring StringFromRunes (List<Rune> runes)
  2056. {
  2057. if (runes == null)
  2058. throw new ArgumentNullException (nameof (runes));
  2059. int size = 0;
  2060. foreach (var rune in runes) {
  2061. size += Utf8.RuneLen (rune);
  2062. }
  2063. var encoded = new byte [size];
  2064. int offset = 0;
  2065. foreach (var rune in runes) {
  2066. offset += Utf8.EncodeRune (rune, encoded, offset);
  2067. }
  2068. return ustring.Make (encoded);
  2069. }
  2070. /// <summary>
  2071. /// Returns the characters on the current line (where the cursor is positioned).
  2072. /// Use <see cref="CurrentColumn"/> to determine the position of the cursor within
  2073. /// that line
  2074. /// </summary>
  2075. /// <returns></returns>
  2076. public List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  2077. void InsertText (ustring text)
  2078. {
  2079. if (ustring.IsNullOrEmpty (text)) {
  2080. return;
  2081. }
  2082. var lines = TextModel.StringToRunes (text);
  2083. if (lines.Count == 0) {
  2084. return;
  2085. }
  2086. var line = GetCurrentLine ();
  2087. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition);
  2088. // Optimize single line
  2089. if (lines.Count == 1) {
  2090. line.InsertRange (currentColumn, lines [0]);
  2091. currentColumn += lines [0].Count;
  2092. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2093. HistoryText.LineStatus.Replaced);
  2094. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  2095. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  2096. }
  2097. if (wordWrap) {
  2098. SetNeedsDisplay ();
  2099. } else {
  2100. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  2101. }
  2102. return;
  2103. }
  2104. List<Rune> rest = null;
  2105. int lastp = 0;
  2106. if (model.Count > 0 && line.Count > 0 && !copyWithoutSelection) {
  2107. // Keep a copy of the rest of the line
  2108. var restCount = line.Count - currentColumn;
  2109. rest = line.GetRange (currentColumn, restCount);
  2110. line.RemoveRange (currentColumn, restCount);
  2111. }
  2112. // First line is inserted at the current location, the rest is appended
  2113. line.InsertRange (currentColumn, lines [0]);
  2114. //model.AddLine (currentRow, lines [0]);
  2115. var addedLines = new List<List<Rune>> () { new List<Rune> (line) };
  2116. for (int i = 1; i < lines.Count; i++) {
  2117. model.AddLine (currentRow + i, lines [i]);
  2118. addedLines.Add (new List<Rune> (lines [i]));
  2119. }
  2120. if (rest != null) {
  2121. var last = model.GetLine (currentRow + lines.Count - 1);
  2122. lastp = last.Count;
  2123. last.InsertRange (last.Count, rest);
  2124. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  2125. }
  2126. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2127. // Now adjust column and row positions
  2128. currentRow += lines.Count - 1;
  2129. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  2130. Adjust ();
  2131. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2132. HistoryText.LineStatus.Replaced);
  2133. }
  2134. // The column we are tracking, or -1 if we are not tracking any column
  2135. int columnTrack = -1;
  2136. // Tries to snap the cursor to the tracking column
  2137. void TrackColumn ()
  2138. {
  2139. // Now track the column
  2140. var line = GetCurrentLine ();
  2141. if (line.Count < columnTrack)
  2142. currentColumn = line.Count;
  2143. else if (columnTrack != -1)
  2144. currentColumn = columnTrack;
  2145. else if (currentColumn > line.Count)
  2146. currentColumn = line.Count;
  2147. Adjust ();
  2148. }
  2149. void Adjust ()
  2150. {
  2151. var offB = OffSetBackground ();
  2152. var line = GetCurrentLine ();
  2153. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  2154. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  2155. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  2156. if (!wordWrap && currentColumn < leftColumn) {
  2157. leftColumn = currentColumn;
  2158. need = true;
  2159. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  2160. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  2161. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  2162. Frame.Width + offB.width - RightOffset, TabWidth);
  2163. need = true;
  2164. } else if (dSize.size + RightOffset < Frame.Width + offB.width
  2165. && tSize.size + RightOffset < Frame.Width + offB.width) {
  2166. leftColumn = 0;
  2167. need = true;
  2168. }
  2169. if (currentRow < topRow) {
  2170. topRow = currentRow;
  2171. need = true;
  2172. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  2173. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  2174. need = true;
  2175. } else if (topRow > 0 && currentRow == topRow) {
  2176. topRow = Math.Max (topRow - 1, 0);
  2177. }
  2178. if (need) {
  2179. if (wrapNeeded) {
  2180. WrapTextModel ();
  2181. wrapNeeded = false;
  2182. }
  2183. SetNeedsDisplay ();
  2184. } else {
  2185. PositionCursor ();
  2186. }
  2187. }
  2188. (int width, int height) OffSetBackground ()
  2189. {
  2190. int w = 0;
  2191. int h = 0;
  2192. if (SuperView?.Frame.Right - Frame.Right < 0) {
  2193. w = SuperView.Frame.Right - Frame.Right - 1;
  2194. }
  2195. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  2196. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  2197. }
  2198. return (w, h);
  2199. }
  2200. /// <summary>
  2201. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  2202. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  2203. /// </summary>
  2204. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  2205. /// if the value is negative it will be reset to zero</param>
  2206. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  2207. public void ScrollTo (int idx, bool isRow = true)
  2208. {
  2209. if (idx < 0) {
  2210. idx = 0;
  2211. }
  2212. if (isRow) {
  2213. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  2214. } else if (!wordWrap) {
  2215. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  2216. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  2217. }
  2218. SetNeedsDisplay ();
  2219. }
  2220. bool lastWasKill;
  2221. bool wrapNeeded;
  2222. bool shiftSelecting;
  2223. ///<inheritdoc/>
  2224. public override bool ProcessKey (KeyEvent kb)
  2225. {
  2226. if (!CanFocus) {
  2227. return true;
  2228. }
  2229. // Give autocomplete first opportunity to respond to key presses
  2230. if (SelectedLength == 0 && Autocomplete.ProcessKey (kb)) {
  2231. return true;
  2232. }
  2233. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (kb),
  2234. new KeyModifiers () { Alt = kb.IsAlt, Ctrl = kb.IsCtrl, Shift = kb.IsShift }));
  2235. if (result != null)
  2236. return (bool)result;
  2237. ResetColumnTrack ();
  2238. // Ignore control characters and other special keys
  2239. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2240. return false;
  2241. InsertText (kb);
  2242. DoNeededAction ();
  2243. return true;
  2244. }
  2245. void RedoChanges ()
  2246. {
  2247. if (ReadOnly || wordWrap)
  2248. return;
  2249. historyText.Redo ();
  2250. }
  2251. void UndoChanges ()
  2252. {
  2253. if (ReadOnly || wordWrap)
  2254. return;
  2255. historyText.Undo ();
  2256. }
  2257. bool ProcessMovePreviousView ()
  2258. {
  2259. ResetColumnTrack ();
  2260. return MovePreviousView ();
  2261. }
  2262. bool ProcessMoveNextView ()
  2263. {
  2264. ResetColumnTrack ();
  2265. return MoveNextView ();
  2266. }
  2267. void ProcessSetOverwrite ()
  2268. {
  2269. ResetColumnTrack ();
  2270. SetOverwrite (!Used);
  2271. }
  2272. void ProcessSelectAll ()
  2273. {
  2274. ResetColumnTrack ();
  2275. SelectAll ();
  2276. }
  2277. void MoveTopHomeExtend ()
  2278. {
  2279. ResetColumnTrack ();
  2280. StartSelecting ();
  2281. MoveHome ();
  2282. }
  2283. void MoveTopHome ()
  2284. {
  2285. ResetAllTrack ();
  2286. if (shiftSelecting && selecting) {
  2287. StopSelecting ();
  2288. }
  2289. MoveHome ();
  2290. }
  2291. void MoveBottomEndExtend ()
  2292. {
  2293. ResetAllTrack ();
  2294. StartSelecting ();
  2295. MoveEnd ();
  2296. }
  2297. void MoveBottomEnd ()
  2298. {
  2299. ResetAllTrack ();
  2300. if (shiftSelecting && selecting) {
  2301. StopSelecting ();
  2302. }
  2303. MoveEnd ();
  2304. }
  2305. void ProcessKillWordBackward ()
  2306. {
  2307. ResetColumnTrack ();
  2308. KillWordBackward ();
  2309. }
  2310. void ProcessKillWordForward ()
  2311. {
  2312. ResetColumnTrack ();
  2313. KillWordForward ();
  2314. }
  2315. void ProcessMoveWordForwardExtend ()
  2316. {
  2317. ResetAllTrack ();
  2318. StartSelecting ();
  2319. MoveWordForward ();
  2320. }
  2321. void ProcessMoveWordForward ()
  2322. {
  2323. ResetAllTrack ();
  2324. if (shiftSelecting && selecting) {
  2325. StopSelecting ();
  2326. }
  2327. MoveWordForward ();
  2328. }
  2329. void ProcessMoveWordBackwardExtend ()
  2330. {
  2331. ResetAllTrack ();
  2332. StartSelecting ();
  2333. MoveWordBackward ();
  2334. }
  2335. void ProcessMoveWordBackward ()
  2336. {
  2337. ResetAllTrack ();
  2338. if (shiftSelecting && selecting) {
  2339. StopSelecting ();
  2340. }
  2341. MoveWordBackward ();
  2342. }
  2343. void ProcessCut ()
  2344. {
  2345. ResetColumnTrack ();
  2346. Cut ();
  2347. }
  2348. void ProcessCopy ()
  2349. {
  2350. ResetColumnTrack ();
  2351. Copy ();
  2352. }
  2353. void ToggleSelecting ()
  2354. {
  2355. ResetColumnTrack ();
  2356. selecting = !selecting;
  2357. selectionStartColumn = currentColumn;
  2358. selectionStartRow = currentRow;
  2359. }
  2360. void ProcessPaste ()
  2361. {
  2362. ResetColumnTrack ();
  2363. if (isReadOnly)
  2364. return;
  2365. Paste ();
  2366. }
  2367. void ProcessMoveEndOfLineExtend ()
  2368. {
  2369. ResetAllTrack ();
  2370. StartSelecting ();
  2371. MoveEndOfLine ();
  2372. }
  2373. void ProcessMoveEndOfLine ()
  2374. {
  2375. ResetAllTrack ();
  2376. if (shiftSelecting && selecting) {
  2377. StopSelecting ();
  2378. }
  2379. MoveEndOfLine ();
  2380. }
  2381. void ProcessDeleteCharRight ()
  2382. {
  2383. ResetColumnTrack ();
  2384. DeleteCharRight ();
  2385. }
  2386. void ProcessMoveStartOfLineExtend ()
  2387. {
  2388. ResetAllTrack ();
  2389. StartSelecting ();
  2390. MoveStartOfLine ();
  2391. }
  2392. void ProcessMoveStartOfLine ()
  2393. {
  2394. ResetAllTrack ();
  2395. if (shiftSelecting && selecting) {
  2396. StopSelecting ();
  2397. }
  2398. MoveStartOfLine ();
  2399. }
  2400. void ProcessDeleteCharLeft ()
  2401. {
  2402. ResetColumnTrack ();
  2403. DeleteCharLeft ();
  2404. }
  2405. void ProcessMoveLeftExtend ()
  2406. {
  2407. ResetAllTrack ();
  2408. StartSelecting ();
  2409. MoveLeft ();
  2410. }
  2411. bool ProcessMoveLeft ()
  2412. {
  2413. // if the user presses Left (without any control keys) and they are at the start of the text
  2414. if (currentColumn == 0 && currentRow == 0) {
  2415. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  2416. return false;
  2417. }
  2418. ResetAllTrack ();
  2419. if (shiftSelecting && selecting) {
  2420. StopSelecting ();
  2421. }
  2422. MoveLeft ();
  2423. return true;
  2424. }
  2425. void ProcessMoveRightExtend ()
  2426. {
  2427. ResetAllTrack ();
  2428. StartSelecting ();
  2429. MoveRight ();
  2430. }
  2431. bool ProcessMoveRight ()
  2432. {
  2433. // if the user presses Right (without any control keys)
  2434. // determine where the last cursor position in the text is
  2435. var lastRow = model.Count - 1;
  2436. var lastCol = model.GetLine (lastRow).Count;
  2437. // if they are at the very end of all the text do not respond (this lets the key press fall through to navigation system - which usually changes focus forward)
  2438. if (currentColumn == lastCol && currentRow == lastRow) {
  2439. return false;
  2440. }
  2441. ResetAllTrack ();
  2442. if (shiftSelecting && selecting) {
  2443. StopSelecting ();
  2444. }
  2445. MoveRight ();
  2446. return true;
  2447. }
  2448. void ProcessMoveUpExtend ()
  2449. {
  2450. ResetColumnTrack ();
  2451. StartSelecting ();
  2452. MoveUp ();
  2453. }
  2454. void ProcessMoveUp ()
  2455. {
  2456. ResetContinuousFindTrack ();
  2457. if (shiftSelecting && selecting) {
  2458. StopSelecting ();
  2459. }
  2460. MoveUp ();
  2461. }
  2462. void ProcessMoveDownExtend ()
  2463. {
  2464. ResetColumnTrack ();
  2465. StartSelecting ();
  2466. MoveDown ();
  2467. }
  2468. void ProcessMoveDown ()
  2469. {
  2470. ResetContinuousFindTrack ();
  2471. if (shiftSelecting && selecting) {
  2472. StopSelecting ();
  2473. }
  2474. MoveDown ();
  2475. }
  2476. void ProcessPageUpExtend ()
  2477. {
  2478. ResetColumnTrack ();
  2479. StartSelecting ();
  2480. MovePageUp ();
  2481. }
  2482. void ProcessPageUp ()
  2483. {
  2484. ResetColumnTrack ();
  2485. if (shiftSelecting && selecting) {
  2486. StopSelecting ();
  2487. }
  2488. MovePageUp ();
  2489. }
  2490. void ProcessPageDownExtend ()
  2491. {
  2492. ResetColumnTrack ();
  2493. StartSelecting ();
  2494. MovePageDown ();
  2495. }
  2496. void ProcessPageDown ()
  2497. {
  2498. ResetColumnTrack ();
  2499. if (shiftSelecting && selecting) {
  2500. StopSelecting ();
  2501. }
  2502. MovePageDown ();
  2503. }
  2504. bool MovePreviousView ()
  2505. {
  2506. if (Application.MdiTop != null) {
  2507. return SuperView?.FocusPrev () == true;
  2508. }
  2509. return false;
  2510. }
  2511. bool MoveNextView ()
  2512. {
  2513. if (Application.MdiTop != null) {
  2514. return SuperView?.FocusNext () == true;
  2515. }
  2516. return false;
  2517. }
  2518. bool ProcessBackTab ()
  2519. {
  2520. ResetColumnTrack ();
  2521. if (!AllowsTab) {
  2522. return false;
  2523. }
  2524. if (currentColumn > 0) {
  2525. var currentLine = GetCurrentLine ();
  2526. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2527. currentLine.RemoveAt (currentColumn - 1);
  2528. currentColumn--;
  2529. }
  2530. }
  2531. DoNeededAction ();
  2532. return true;
  2533. }
  2534. bool ProcessTab ()
  2535. {
  2536. ResetColumnTrack ();
  2537. if (!AllowsTab) {
  2538. return false;
  2539. }
  2540. InsertText (new KeyEvent ((Key)'\t', null));
  2541. DoNeededAction ();
  2542. return true;
  2543. }
  2544. void SetOverwrite (bool overwrite)
  2545. {
  2546. Used = overwrite;
  2547. SetNeedsDisplay ();
  2548. DoNeededAction ();
  2549. }
  2550. bool ProcessReturn ()
  2551. {
  2552. ResetColumnTrack ();
  2553. if (!AllowsReturn) {
  2554. return false;
  2555. }
  2556. if (isReadOnly)
  2557. return true;
  2558. var currentLine = GetCurrentLine ();
  2559. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2560. if (selecting) {
  2561. ClearSelectedRegion ();
  2562. currentLine = GetCurrentLine ();
  2563. }
  2564. var restCount = currentLine.Count - currentColumn;
  2565. var rest = currentLine.GetRange (currentColumn, restCount);
  2566. currentLine.RemoveRange (currentColumn, restCount);
  2567. var addedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2568. model.AddLine (currentRow + 1, rest);
  2569. addedLines.Add (new List<Rune> (model.GetLine (currentRow + 1)));
  2570. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2571. if (wordWrap) {
  2572. wrapManager.AddLine (currentRow, currentColumn);
  2573. wrapNeeded = true;
  2574. }
  2575. currentRow++;
  2576. bool fullNeedsDisplay = false;
  2577. if (currentRow >= topRow + Frame.Height) {
  2578. topRow++;
  2579. fullNeedsDisplay = true;
  2580. }
  2581. currentColumn = 0;
  2582. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2583. HistoryText.LineStatus.Replaced);
  2584. if (!wordWrap && currentColumn < leftColumn) {
  2585. fullNeedsDisplay = true;
  2586. leftColumn = 0;
  2587. }
  2588. if (fullNeedsDisplay)
  2589. SetNeedsDisplay ();
  2590. else
  2591. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2592. DoNeededAction ();
  2593. return true;
  2594. }
  2595. void KillWordBackward ()
  2596. {
  2597. if (isReadOnly)
  2598. return;
  2599. var currentLine = GetCurrentLine ();
  2600. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2601. if (currentColumn == 0) {
  2602. DeleteTextBackwards ();
  2603. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2604. HistoryText.LineStatus.Replaced);
  2605. return;
  2606. }
  2607. var newPos = WordBackward (currentColumn, currentRow);
  2608. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2609. var restCount = currentColumn - newPos.Value.col;
  2610. currentLine.RemoveRange (newPos.Value.col, restCount);
  2611. if (wordWrap && wrapManager.RemoveRange (currentRow, newPos.Value.col, restCount)) {
  2612. wrapNeeded = true;
  2613. }
  2614. currentColumn = newPos.Value.col;
  2615. } else if (newPos.HasValue) {
  2616. var restCount = currentLine.Count - currentColumn;
  2617. currentLine.RemoveRange (currentColumn, restCount);
  2618. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2619. wrapNeeded = true;
  2620. }
  2621. currentColumn = newPos.Value.col;
  2622. currentRow = newPos.Value.row;
  2623. }
  2624. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2625. HistoryText.LineStatus.Replaced);
  2626. if (wrapNeeded) {
  2627. SetNeedsDisplay ();
  2628. } else {
  2629. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2630. }
  2631. DoNeededAction ();
  2632. }
  2633. void KillWordForward ()
  2634. {
  2635. if (isReadOnly)
  2636. return;
  2637. var currentLine = GetCurrentLine ();
  2638. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2639. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2640. DeleteTextForwards ();
  2641. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2642. HistoryText.LineStatus.Replaced);
  2643. return;
  2644. }
  2645. var newPos = WordForward (currentColumn, currentRow);
  2646. var restCount = 0;
  2647. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2648. restCount = newPos.Value.col - currentColumn;
  2649. currentLine.RemoveRange (currentColumn, restCount);
  2650. } else if (newPos.HasValue) {
  2651. restCount = currentLine.Count - currentColumn;
  2652. currentLine.RemoveRange (currentColumn, restCount);
  2653. }
  2654. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2655. wrapNeeded = true;
  2656. }
  2657. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2658. HistoryText.LineStatus.Replaced);
  2659. if (wrapNeeded) {
  2660. SetNeedsDisplay ();
  2661. } else {
  2662. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2663. }
  2664. DoNeededAction ();
  2665. }
  2666. void MoveWordForward ()
  2667. {
  2668. var newPos = WordForward (currentColumn, currentRow);
  2669. if (newPos.HasValue) {
  2670. currentColumn = newPos.Value.col;
  2671. currentRow = newPos.Value.row;
  2672. }
  2673. Adjust ();
  2674. DoNeededAction ();
  2675. }
  2676. void MoveWordBackward ()
  2677. {
  2678. var newPos = WordBackward (currentColumn, currentRow);
  2679. if (newPos.HasValue) {
  2680. currentColumn = newPos.Value.col;
  2681. currentRow = newPos.Value.row;
  2682. }
  2683. Adjust ();
  2684. DoNeededAction ();
  2685. }
  2686. void KillToStartOfLine ()
  2687. {
  2688. if (isReadOnly)
  2689. return;
  2690. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2691. // Prevents from adding line feeds if there is no more lines.
  2692. return;
  2693. }
  2694. var currentLine = GetCurrentLine ();
  2695. var setLastWasKill = true;
  2696. if (currentLine.Count > 0 && currentColumn == 0) {
  2697. DeleteTextBackwards ();
  2698. return;
  2699. }
  2700. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2701. if (currentLine.Count == 0) {
  2702. if (currentRow > 0) {
  2703. model.RemoveLine (currentRow);
  2704. if (model.Count > 0 || lastWasKill) {
  2705. var val = ustring.Make (Environment.NewLine);
  2706. if (lastWasKill) {
  2707. AppendClipboard (val);
  2708. } else {
  2709. SetClipboard (val);
  2710. }
  2711. }
  2712. if (model.Count == 0) {
  2713. // Prevents from adding line feeds if there is no more lines.
  2714. setLastWasKill = false;
  2715. }
  2716. currentRow--;
  2717. currentLine = model.GetLine (currentRow);
  2718. var removedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2719. removedLine.Add (new List<Rune> ());
  2720. historyText.Add (new List<List<Rune>> (removedLine), CursorPosition, HistoryText.LineStatus.Removed);
  2721. currentColumn = currentLine.Count;
  2722. }
  2723. } else {
  2724. var restCount = currentColumn;
  2725. var rest = currentLine.GetRange (0, restCount);
  2726. var val = ustring.Empty;
  2727. val += StringFromRunes (rest);
  2728. if (lastWasKill) {
  2729. AppendClipboard (val);
  2730. } else {
  2731. SetClipboard (val);
  2732. }
  2733. currentLine.RemoveRange (0, restCount);
  2734. currentColumn = 0;
  2735. }
  2736. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2737. HistoryText.LineStatus.Replaced);
  2738. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2739. lastWasKill = setLastWasKill;
  2740. DoNeededAction ();
  2741. }
  2742. void KillToEndOfLine ()
  2743. {
  2744. if (isReadOnly)
  2745. return;
  2746. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2747. // Prevents from adding line feeds if there is no more lines.
  2748. return;
  2749. }
  2750. var currentLine = GetCurrentLine ();
  2751. var setLastWasKill = true;
  2752. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2753. DeleteTextForwards ();
  2754. return;
  2755. }
  2756. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2757. if (currentLine.Count == 0) {
  2758. if (currentRow < model.Count - 1) {
  2759. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2760. model.RemoveLine (currentRow);
  2761. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  2762. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  2763. HistoryText.LineStatus.Removed);
  2764. }
  2765. if (model.Count > 0 || lastWasKill) {
  2766. var val = ustring.Make (Environment.NewLine);
  2767. if (lastWasKill) {
  2768. AppendClipboard (val);
  2769. } else {
  2770. SetClipboard (val);
  2771. }
  2772. }
  2773. if (model.Count == 0) {
  2774. // Prevents from adding line feeds if there is no more lines.
  2775. setLastWasKill = false;
  2776. }
  2777. } else {
  2778. var restCount = currentLine.Count - currentColumn;
  2779. var rest = currentLine.GetRange (currentColumn, restCount);
  2780. var val = ustring.Empty;
  2781. val += StringFromRunes (rest);
  2782. if (lastWasKill) {
  2783. AppendClipboard (val);
  2784. } else {
  2785. SetClipboard (val);
  2786. }
  2787. currentLine.RemoveRange (currentColumn, restCount);
  2788. }
  2789. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2790. HistoryText.LineStatus.Replaced);
  2791. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2792. lastWasKill = setLastWasKill;
  2793. DoNeededAction ();
  2794. }
  2795. void MoveEndOfLine ()
  2796. {
  2797. var currentLine = GetCurrentLine ();
  2798. currentColumn = currentLine.Count;
  2799. Adjust ();
  2800. DoNeededAction ();
  2801. }
  2802. void MoveStartOfLine ()
  2803. {
  2804. currentColumn = 0;
  2805. leftColumn = 0;
  2806. Adjust ();
  2807. DoNeededAction ();
  2808. }
  2809. /// <summary>
  2810. /// Deletes all the selected or a single character at right from the position of the cursor.
  2811. /// </summary>
  2812. public void DeleteCharRight ()
  2813. {
  2814. if (isReadOnly)
  2815. return;
  2816. if (selecting) {
  2817. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2818. HistoryText.LineStatus.Original);
  2819. ClearSelectedRegion ();
  2820. var currentLine = GetCurrentLine ();
  2821. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2822. HistoryText.LineStatus.Replaced);
  2823. return;
  2824. }
  2825. if (DeleteTextForwards ()) {
  2826. return;
  2827. }
  2828. DoNeededAction ();
  2829. }
  2830. /// <summary>
  2831. /// Deletes all the selected or a single character at left from the position of the cursor.
  2832. /// </summary>
  2833. public void DeleteCharLeft ()
  2834. {
  2835. if (isReadOnly)
  2836. return;
  2837. if (selecting) {
  2838. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2839. HistoryText.LineStatus.Original);
  2840. ClearSelectedRegion ();
  2841. var currentLine = GetCurrentLine ();
  2842. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2843. HistoryText.LineStatus.Replaced);
  2844. return;
  2845. }
  2846. if (DeleteTextBackwards ()) {
  2847. return;
  2848. }
  2849. DoNeededAction ();
  2850. }
  2851. void MoveLeft ()
  2852. {
  2853. if (currentColumn > 0) {
  2854. currentColumn--;
  2855. } else {
  2856. if (currentRow > 0) {
  2857. currentRow--;
  2858. if (currentRow < topRow) {
  2859. topRow--;
  2860. SetNeedsDisplay ();
  2861. }
  2862. var currentLine = GetCurrentLine ();
  2863. currentColumn = currentLine.Count;
  2864. }
  2865. }
  2866. Adjust ();
  2867. DoNeededAction ();
  2868. }
  2869. void MoveRight ()
  2870. {
  2871. var currentLine = GetCurrentLine ();
  2872. if (currentColumn < currentLine.Count) {
  2873. currentColumn++;
  2874. } else {
  2875. if (currentRow + 1 < model.Count) {
  2876. currentRow++;
  2877. currentColumn = 0;
  2878. if (currentRow >= topRow + Frame.Height) {
  2879. topRow++;
  2880. SetNeedsDisplay ();
  2881. }
  2882. }
  2883. }
  2884. Adjust ();
  2885. DoNeededAction ();
  2886. }
  2887. void MovePageUp ()
  2888. {
  2889. int nPageUpShift = Frame.Height - 1;
  2890. if (currentRow > 0) {
  2891. if (columnTrack == -1)
  2892. columnTrack = currentColumn;
  2893. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  2894. if (currentRow < topRow) {
  2895. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  2896. SetNeedsDisplay ();
  2897. }
  2898. TrackColumn ();
  2899. PositionCursor ();
  2900. }
  2901. DoNeededAction ();
  2902. }
  2903. void MovePageDown ()
  2904. {
  2905. int nPageDnShift = Frame.Height - 1;
  2906. if (currentRow >= 0 && currentRow < model.Count) {
  2907. if (columnTrack == -1)
  2908. columnTrack = currentColumn;
  2909. currentRow = (currentRow + nPageDnShift) > model.Count
  2910. ? model.Count > 0 ? model.Count - 1 : 0
  2911. : currentRow + nPageDnShift;
  2912. if (topRow < currentRow - nPageDnShift) {
  2913. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  2914. SetNeedsDisplay ();
  2915. }
  2916. TrackColumn ();
  2917. PositionCursor ();
  2918. }
  2919. DoNeededAction ();
  2920. }
  2921. void ResetContinuousFindTrack ()
  2922. {
  2923. // Handle some state here - whether the last command was a kill
  2924. // operation and the column tracking (up/down)
  2925. lastWasKill = false;
  2926. continuousFind = false;
  2927. }
  2928. void ResetColumnTrack ()
  2929. {
  2930. // Handle some state here - whether the last command was a kill
  2931. // operation and the column tracking (up/down)
  2932. lastWasKill = false;
  2933. columnTrack = -1;
  2934. }
  2935. void ResetAllTrack ()
  2936. {
  2937. // Handle some state here - whether the last command was a kill
  2938. // operation and the column tracking (up/down)
  2939. lastWasKill = false;
  2940. columnTrack = -1;
  2941. continuousFind = false;
  2942. }
  2943. bool InsertText (KeyEvent kb)
  2944. {
  2945. //So that special keys like tab can be processed
  2946. if (isReadOnly)
  2947. return true;
  2948. var curPos = CursorPosition;
  2949. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2950. if (selecting) {
  2951. ClearSelectedRegion ();
  2952. }
  2953. if (Used) {
  2954. Insert ((uint)kb.Key);
  2955. currentColumn++;
  2956. if (currentColumn >= leftColumn + Frame.Width) {
  2957. leftColumn++;
  2958. SetNeedsDisplay ();
  2959. }
  2960. } else {
  2961. Insert ((uint)kb.Key);
  2962. currentColumn++;
  2963. }
  2964. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2965. HistoryText.LineStatus.Replaced);
  2966. return true;
  2967. }
  2968. ///<inheritdoc/>
  2969. public override bool OnKeyUp (KeyEvent kb)
  2970. {
  2971. switch (kb.Key) {
  2972. case Key.Space | Key.CtrlMask:
  2973. return true;
  2974. }
  2975. return false;
  2976. }
  2977. void DoNeededAction ()
  2978. {
  2979. if (NeedDisplay.IsEmpty) {
  2980. PositionCursor ();
  2981. } else {
  2982. Adjust ();
  2983. }
  2984. }
  2985. bool DeleteTextForwards ()
  2986. {
  2987. var currentLine = GetCurrentLine ();
  2988. if (currentColumn == currentLine.Count) {
  2989. if (currentRow + 1 == model.Count)
  2990. return true;
  2991. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2992. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2993. var nextLine = model.GetLine (currentRow + 1);
  2994. removedLines.Add (new List<Rune> (nextLine));
  2995. historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  2996. currentLine.AddRange (nextLine);
  2997. model.RemoveLine (currentRow + 1);
  2998. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2999. HistoryText.LineStatus.Replaced);
  3000. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  3001. wrapNeeded = true;
  3002. }
  3003. var sr = currentRow - topRow;
  3004. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  3005. } else {
  3006. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3007. currentLine.RemoveAt (currentColumn);
  3008. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3009. HistoryText.LineStatus.Replaced);
  3010. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  3011. wrapNeeded = true;
  3012. }
  3013. var r = currentRow - topRow;
  3014. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  3015. }
  3016. return false;
  3017. }
  3018. bool DeleteTextBackwards ()
  3019. {
  3020. if (currentColumn > 0) {
  3021. // Delete backwards
  3022. var currentLine = GetCurrentLine ();
  3023. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3024. currentLine.RemoveAt (currentColumn - 1);
  3025. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  3026. wrapNeeded = true;
  3027. }
  3028. currentColumn--;
  3029. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3030. HistoryText.LineStatus.Replaced);
  3031. if (currentColumn < leftColumn) {
  3032. leftColumn--;
  3033. SetNeedsDisplay ();
  3034. } else
  3035. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  3036. } else {
  3037. // Merges the current line with the previous one.
  3038. if (currentRow == 0)
  3039. return true;
  3040. var prowIdx = currentRow - 1;
  3041. var prevRow = model.GetLine (prowIdx);
  3042. historyText.Add (new List<List<Rune>> () { new List<Rune> (prevRow) }, CursorPosition);
  3043. List<List<Rune>> removedLines = new List<List<Rune>> () { new List<Rune> (prevRow) };
  3044. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  3045. historyText.Add (removedLines, new Point (currentColumn, prowIdx),
  3046. HistoryText.LineStatus.Removed);
  3047. var prevCount = prevRow.Count;
  3048. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3049. model.RemoveLine (currentRow);
  3050. bool lineRemoved = false;
  3051. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  3052. wrapNeeded = true;
  3053. }
  3054. currentRow--;
  3055. historyText.Add (new List<List<Rune>> () { GetCurrentLine () }, new Point (currentColumn, prowIdx),
  3056. HistoryText.LineStatus.Replaced);
  3057. if (wrapNeeded && !lineRemoved) {
  3058. currentColumn = Math.Max (prevCount - 1, 0);
  3059. } else {
  3060. currentColumn = prevCount;
  3061. }
  3062. SetNeedsDisplay ();
  3063. }
  3064. return false;
  3065. }
  3066. bool copyWithoutSelection;
  3067. /// <summary>
  3068. /// Copy the selected text to the clipboard contents.
  3069. /// </summary>
  3070. public void Copy ()
  3071. {
  3072. SetWrapModel ();
  3073. if (selecting) {
  3074. SetClipboard (GetRegion ());
  3075. copyWithoutSelection = false;
  3076. } else {
  3077. var currentLine = GetCurrentLine ();
  3078. SetClipboard (ustring.Make (currentLine));
  3079. copyWithoutSelection = true;
  3080. }
  3081. UpdateWrapModel ();
  3082. DoNeededAction ();
  3083. }
  3084. /// <summary>
  3085. /// Cut the selected text to the clipboard contents.
  3086. /// </summary>
  3087. public void Cut ()
  3088. {
  3089. SetWrapModel ();
  3090. SetClipboard (GetRegion ());
  3091. if (!isReadOnly) {
  3092. ClearRegion ();
  3093. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3094. HistoryText.LineStatus.Replaced);
  3095. }
  3096. UpdateWrapModel ();
  3097. selecting = false;
  3098. DoNeededAction ();
  3099. }
  3100. /// <summary>
  3101. /// Paste the clipboard contents into the current selected position.
  3102. /// </summary>
  3103. public void Paste ()
  3104. {
  3105. if (isReadOnly) {
  3106. return;
  3107. }
  3108. SetWrapModel ();
  3109. var contents = Clipboard.Contents;
  3110. if (copyWithoutSelection && contents.FirstOrDefault (x => x == '\n' || x == '\r') == 0) {
  3111. var runeList = contents == null ? new List<Rune> () : contents.ToRuneList ();
  3112. var currentLine = GetCurrentLine ();
  3113. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3114. var addedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3115. addedLine.Add (runeList);
  3116. historyText.Add (new List<List<Rune>> (addedLine), CursorPosition, HistoryText.LineStatus.Added);
  3117. model.AddLine (currentRow, runeList);
  3118. currentRow++;
  3119. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3120. HistoryText.LineStatus.Replaced);
  3121. } else {
  3122. if (selecting) {
  3123. ClearRegion ();
  3124. }
  3125. copyWithoutSelection = false;
  3126. InsertText (contents);
  3127. if (selecting) {
  3128. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3129. HistoryText.LineStatus.Original);
  3130. }
  3131. }
  3132. UpdateWrapModel ();
  3133. selecting = false;
  3134. DoNeededAction ();
  3135. }
  3136. void StartSelecting ()
  3137. {
  3138. if (shiftSelecting && selecting) {
  3139. return;
  3140. }
  3141. shiftSelecting = true;
  3142. selecting = true;
  3143. selectionStartColumn = currentColumn;
  3144. selectionStartRow = currentRow;
  3145. }
  3146. void StopSelecting ()
  3147. {
  3148. shiftSelecting = false;
  3149. selecting = false;
  3150. }
  3151. void ClearSelectedRegion ()
  3152. {
  3153. SetWrapModel ();
  3154. if (!isReadOnly) {
  3155. ClearRegion ();
  3156. }
  3157. UpdateWrapModel ();
  3158. selecting = false;
  3159. DoNeededAction ();
  3160. }
  3161. void MoveUp ()
  3162. {
  3163. if (currentRow > 0) {
  3164. if (columnTrack == -1) {
  3165. columnTrack = currentColumn;
  3166. }
  3167. currentRow--;
  3168. if (currentRow < topRow) {
  3169. topRow--;
  3170. SetNeedsDisplay ();
  3171. }
  3172. TrackColumn ();
  3173. PositionCursor ();
  3174. }
  3175. DoNeededAction ();
  3176. }
  3177. void MoveDown ()
  3178. {
  3179. if (currentRow + 1 < model.Count) {
  3180. if (columnTrack == -1) {
  3181. columnTrack = currentColumn;
  3182. }
  3183. currentRow++;
  3184. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  3185. topRow++;
  3186. SetNeedsDisplay ();
  3187. }
  3188. TrackColumn ();
  3189. PositionCursor ();
  3190. } else if (currentRow > Frame.Height) {
  3191. Adjust ();
  3192. }
  3193. DoNeededAction ();
  3194. }
  3195. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  3196. {
  3197. if (col < 0 || row < 0)
  3198. yield break;
  3199. if (row >= model.Count)
  3200. yield break;
  3201. var line = GetCurrentLine ();
  3202. if (col >= line.Count)
  3203. yield break;
  3204. while (row < model.Count) {
  3205. for (int c = col; c < line.Count; c++) {
  3206. yield return (c, row, line [c]);
  3207. }
  3208. col = 0;
  3209. row++;
  3210. line = GetCurrentLine ();
  3211. }
  3212. }
  3213. Rune RuneAt (int col, int row)
  3214. {
  3215. var line = model.GetLine (row);
  3216. if (line.Count > 0) {
  3217. return line [col > line.Count - 1 ? line.Count - 1 : col];
  3218. } else {
  3219. return 0;
  3220. }
  3221. }
  3222. /// <summary>
  3223. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  3224. /// </summary>
  3225. public void MoveEnd ()
  3226. {
  3227. currentRow = model.Count - 1;
  3228. var line = GetCurrentLine ();
  3229. currentColumn = line.Count;
  3230. TrackColumn ();
  3231. PositionCursor ();
  3232. }
  3233. /// <summary>
  3234. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  3235. /// </summary>
  3236. public void MoveHome ()
  3237. {
  3238. currentRow = 0;
  3239. topRow = 0;
  3240. currentColumn = 0;
  3241. leftColumn = 0;
  3242. TrackColumn ();
  3243. PositionCursor ();
  3244. }
  3245. bool MoveNext (ref int col, ref int row, out Rune rune)
  3246. {
  3247. var line = model.GetLine (row);
  3248. if (col + 1 < line.Count) {
  3249. col++;
  3250. rune = line [col];
  3251. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune)
  3252. && !Rune.IsWhiteSpace (line [col - 1])) {
  3253. col++;
  3254. }
  3255. return true;
  3256. } else if (col + 1 == line.Count) {
  3257. col++;
  3258. }
  3259. while (row + 1 < model.Count) {
  3260. col = 0;
  3261. row++;
  3262. line = model.GetLine (row);
  3263. if (line.Count > 0) {
  3264. rune = line [0];
  3265. return true;
  3266. }
  3267. }
  3268. rune = 0;
  3269. return false;
  3270. }
  3271. bool MovePrev (ref int col, ref int row, out Rune rune)
  3272. {
  3273. var line = model.GetLine (row);
  3274. if (col > 0) {
  3275. col--;
  3276. rune = line [col];
  3277. return true;
  3278. }
  3279. if (row == 0) {
  3280. rune = 0;
  3281. return false;
  3282. }
  3283. while (row > 0) {
  3284. row--;
  3285. line = model.GetLine (row);
  3286. col = line.Count - 1;
  3287. if (col >= 0) {
  3288. rune = line [col];
  3289. return true;
  3290. }
  3291. }
  3292. rune = 0;
  3293. return false;
  3294. }
  3295. (int col, int row)? WordForward (int fromCol, int fromRow)
  3296. {
  3297. var col = fromCol;
  3298. var row = fromRow;
  3299. try {
  3300. var rune = RuneAt (col, row);
  3301. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  3302. {
  3303. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3304. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3305. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  3306. return;
  3307. }
  3308. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3309. return;
  3310. }
  3311. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3312. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3313. break;
  3314. }
  3315. } else {
  3316. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  3317. return;
  3318. }
  3319. var line = model.GetLine (fromRow);
  3320. if ((nRow != fromRow && fromCol < line.Count)
  3321. || (nRow == fromRow && nCol == line.Count - 1)) {
  3322. nCol = line.Count;
  3323. nRow = fromRow;
  3324. return;
  3325. } else if (nRow != fromRow && fromCol == line.Count) {
  3326. line = model.GetLine (nRow);
  3327. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  3328. return;
  3329. }
  3330. }
  3331. ProcMoveNext (ref nCol, ref nRow, nRune);
  3332. }
  3333. }
  3334. ProcMoveNext (ref col, ref row, rune);
  3335. if (fromCol != col || fromRow != row)
  3336. return (col, row);
  3337. return null;
  3338. } catch (Exception) {
  3339. return null;
  3340. }
  3341. }
  3342. (int col, int row)? WordBackward (int fromCol, int fromRow)
  3343. {
  3344. if (fromRow == 0 && fromCol == 0)
  3345. return null;
  3346. var col = Math.Max (fromCol - 1, 0);
  3347. var row = fromRow;
  3348. try {
  3349. var rune = RuneAt (col, row);
  3350. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  3351. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  3352. {
  3353. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3354. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3355. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  3356. lastValidCol = nCol;
  3357. break;
  3358. }
  3359. }
  3360. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3361. if (lastValidCol > -1) {
  3362. nCol = lastValidCol;
  3363. }
  3364. return;
  3365. }
  3366. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3367. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3368. break;
  3369. if (nRow != fromRow) {
  3370. break;
  3371. }
  3372. lastValidCol = nCol;
  3373. }
  3374. if (lastValidCol > -1) {
  3375. nCol = lastValidCol;
  3376. nRow = fromRow;
  3377. }
  3378. } else {
  3379. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  3380. return;
  3381. }
  3382. var line = model.GetLine (nRow);
  3383. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  3384. return;
  3385. }
  3386. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  3387. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  3388. nCol = lastValidCol;
  3389. return;
  3390. }
  3391. if (fromRow != nRow) {
  3392. nCol = line.Count;
  3393. return;
  3394. }
  3395. ProcMovePrev (ref nCol, ref nRow, nRune);
  3396. }
  3397. }
  3398. ProcMovePrev (ref col, ref row, rune);
  3399. if (fromCol != col || fromRow != row)
  3400. return (col, row);
  3401. return null;
  3402. } catch (Exception) {
  3403. return null;
  3404. }
  3405. }
  3406. ///<inheritdoc/>
  3407. public override bool MouseEvent (MouseEvent ev)
  3408. {
  3409. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  3410. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  3411. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  3412. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  3413. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  3414. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  3415. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  3416. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3417. return false;
  3418. }
  3419. if (!CanFocus) {
  3420. return true;
  3421. }
  3422. if (!HasFocus) {
  3423. SetFocus ();
  3424. }
  3425. continuousFind = false;
  3426. // Give autocomplete first opportunity to respond to mouse clicks
  3427. if (SelectedLength == 0 && Autocomplete.MouseEvent (ev, true)) {
  3428. return true;
  3429. }
  3430. if (ev.Flags == MouseFlags.Button1Clicked) {
  3431. if (shiftSelecting) {
  3432. shiftSelecting = false;
  3433. selecting = false;
  3434. }
  3435. ProcessMouseClick (ev, out _);
  3436. PositionCursor ();
  3437. lastWasKill = false;
  3438. columnTrack = currentColumn;
  3439. } else if (ev.Flags == MouseFlags.WheeledDown) {
  3440. lastWasKill = false;
  3441. columnTrack = currentColumn;
  3442. ScrollTo (topRow + 1);
  3443. } else if (ev.Flags == MouseFlags.WheeledUp) {
  3444. lastWasKill = false;
  3445. columnTrack = currentColumn;
  3446. ScrollTo (topRow - 1);
  3447. } else if (ev.Flags == MouseFlags.WheeledRight) {
  3448. lastWasKill = false;
  3449. columnTrack = currentColumn;
  3450. ScrollTo (leftColumn + 1, false);
  3451. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  3452. lastWasKill = false;
  3453. columnTrack = currentColumn;
  3454. ScrollTo (leftColumn - 1, false);
  3455. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  3456. ProcessMouseClick (ev, out List<Rune> line);
  3457. PositionCursor ();
  3458. if (model.Count > 0 && shiftSelecting && selecting) {
  3459. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  3460. && model.Count + BottomOffset > topRow + currentRow) {
  3461. ScrollTo (topRow + Frame.Height);
  3462. } else if (topRow > 0 && currentRow <= topRow) {
  3463. ScrollTo (topRow - Frame.Height);
  3464. } else if (ev.Y >= Frame.Height) {
  3465. ScrollTo (model.Count + BottomOffset);
  3466. } else if (ev.Y < 0 && topRow > 0) {
  3467. ScrollTo (0);
  3468. }
  3469. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  3470. && line.Count + RightOffset > leftColumn + currentColumn) {
  3471. ScrollTo (leftColumn + Frame.Width, false);
  3472. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  3473. ScrollTo (leftColumn - Frame.Width, false);
  3474. } else if (ev.X >= Frame.Width) {
  3475. ScrollTo (line.Count + RightOffset, false);
  3476. } else if (ev.X < 0 && leftColumn > 0) {
  3477. ScrollTo (0, false);
  3478. }
  3479. }
  3480. lastWasKill = false;
  3481. columnTrack = currentColumn;
  3482. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  3483. if (!shiftSelecting) {
  3484. StartSelecting ();
  3485. }
  3486. ProcessMouseClick (ev, out _);
  3487. PositionCursor ();
  3488. lastWasKill = false;
  3489. columnTrack = currentColumn;
  3490. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  3491. if (shiftSelecting) {
  3492. shiftSelecting = false;
  3493. selecting = false;
  3494. }
  3495. ProcessMouseClick (ev, out _);
  3496. PositionCursor ();
  3497. if (!selecting) {
  3498. StartSelecting ();
  3499. }
  3500. lastWasKill = false;
  3501. columnTrack = currentColumn;
  3502. if (Application.mouseGrabView == null) {
  3503. Application.GrabMouse (this);
  3504. }
  3505. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  3506. Application.UngrabMouse ();
  3507. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  3508. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  3509. if (!selecting) {
  3510. StartSelecting ();
  3511. }
  3512. } else if (selecting) {
  3513. StopSelecting ();
  3514. }
  3515. ProcessMouseClick (ev, out List<Rune> line);
  3516. (int col, int row)? newPos;
  3517. if (currentColumn == line.Count || (currentColumn > 0 && (line [currentColumn - 1] != ' '
  3518. || line [currentColumn] == ' '))) {
  3519. newPos = WordBackward (currentColumn, currentRow);
  3520. if (newPos.HasValue) {
  3521. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : 0;
  3522. }
  3523. }
  3524. if (!selecting) {
  3525. StartSelecting ();
  3526. }
  3527. newPos = WordForward (currentColumn, currentRow);
  3528. if (newPos != null && newPos.HasValue) {
  3529. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  3530. }
  3531. PositionCursor ();
  3532. lastWasKill = false;
  3533. columnTrack = currentColumn;
  3534. } else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3535. if (selecting) {
  3536. StopSelecting ();
  3537. }
  3538. ProcessMouseClick (ev, out List<Rune> line);
  3539. currentColumn = 0;
  3540. if (!selecting) {
  3541. StartSelecting ();
  3542. }
  3543. currentColumn = line.Count;
  3544. PositionCursor ();
  3545. lastWasKill = false;
  3546. columnTrack = currentColumn;
  3547. }
  3548. return true;
  3549. }
  3550. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  3551. {
  3552. List<Rune> r = null;
  3553. if (model.Count > 0) {
  3554. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  3555. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  3556. currentRow = maxCursorPositionableLine + topRow;
  3557. } else {
  3558. currentRow = Math.Max (ev.Y + topRow, 0);
  3559. }
  3560. r = GetCurrentLine ();
  3561. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  3562. if (idx - leftColumn >= r.Count + RightOffset) {
  3563. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  3564. } else {
  3565. currentColumn = idx + leftColumn;
  3566. }
  3567. }
  3568. line = r;
  3569. }
  3570. ///<inheritdoc/>
  3571. public override bool OnLeave (View view)
  3572. {
  3573. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  3574. Application.UngrabMouse ();
  3575. }
  3576. return base.OnLeave (view);
  3577. }
  3578. /// <summary>
  3579. /// Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.
  3580. /// </summary>
  3581. public void ClearHistoryChanges ()
  3582. {
  3583. historyText.Clear (Text);
  3584. }
  3585. }
  3586. /// <summary>
  3587. /// Renders an overlay on another view at a given point that allows selecting
  3588. /// from a range of 'autocomplete' options.
  3589. /// An implementation on a TextView.
  3590. /// </summary>
  3591. public class TextViewAutocomplete : Autocomplete {
  3592. ///<inheritdoc/>
  3593. protected override string GetCurrentWord ()
  3594. {
  3595. var host = (TextView)HostControl;
  3596. var currentLine = host.GetCurrentLine ();
  3597. var cursorPosition = Math.Min (host.CurrentColumn, currentLine.Count);
  3598. return IdxToWord (currentLine, cursorPosition);
  3599. }
  3600. /// <inheritdoc/>
  3601. protected override void DeleteTextBackwards ()
  3602. {
  3603. ((TextView)HostControl).DeleteCharLeft ();
  3604. }
  3605. /// <inheritdoc/>
  3606. protected override void InsertText (string accepted)
  3607. {
  3608. ((TextView)HostControl).InsertText (accepted);
  3609. }
  3610. }
  3611. }