TextView.cs 121 KB

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