TextView.cs 122 KB

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