TextView.cs 125 KB

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