TextView.cs 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454
  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="Autocomplete.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. if (Application.Top != null) {
  1225. Application.Top.AlternateForwardKeyChanged += Top_AlternateForwardKeyChanged;
  1226. Application.Top.AlternateBackwardKeyChanged += Top_AlternateBackwardKeyChanged;
  1227. }
  1228. OnContentsChanged ();
  1229. }
  1230. void Top_AlternateBackwardKeyChanged (object sender, KeyChangedEventArgs e)
  1231. {
  1232. ReplaceKeyBinding (e.OldKey, e.NewKey);
  1233. }
  1234. void Top_AlternateForwardKeyChanged (object sender, KeyChangedEventArgs e)
  1235. {
  1236. ReplaceKeyBinding (e.OldKey, e.NewKey);
  1237. }
  1238. /// <summary>
  1239. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  1240. /// so new input should be appended at the cursor position, rather than clearing the entry
  1241. /// </summary>
  1242. public bool Used { get; set; }
  1243. void ResetPosition ()
  1244. {
  1245. topRow = leftColumn = currentRow = currentColumn = 0;
  1246. StopSelecting ();
  1247. ResetCursorVisibility ();
  1248. }
  1249. /// <summary>
  1250. /// Sets or gets the text in the <see cref="TextView"/>.
  1251. /// </summary>
  1252. /// <remarks>
  1253. /// The <see cref="TextChanged"/> event is fired whenever this property is set. Note, however,
  1254. /// that Text is not set by <see cref="TextView"/> as the user types.
  1255. /// </remarks>
  1256. public override ustring Text {
  1257. get {
  1258. if (wordWrap) {
  1259. return wrapManager.Model.ToString ();
  1260. } else {
  1261. return model.ToString ();
  1262. }
  1263. }
  1264. set {
  1265. ResetPosition ();
  1266. model.LoadString (value);
  1267. if (wordWrap) {
  1268. wrapManager = new WordWrapManager (model);
  1269. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1270. }
  1271. TextChanged?.Invoke (this, EventArgs.Empty);
  1272. SetNeedsDisplay ();
  1273. historyText.Clear (Text);
  1274. }
  1275. }
  1276. ///<inheritdoc/>
  1277. public override Rect Frame {
  1278. get => base.Frame;
  1279. set {
  1280. base.Frame = value;
  1281. if (IsInitialized) {
  1282. WrapTextModel ();
  1283. Adjust ();
  1284. }
  1285. }
  1286. }
  1287. void WrapTextModel ()
  1288. {
  1289. if (wordWrap && wrapManager != null) {
  1290. model = wrapManager.WrapModel (frameWidth,
  1291. out int nRow, out int nCol,
  1292. out int nStartRow, out int nStartCol,
  1293. currentRow, currentColumn,
  1294. selectionStartRow, selectionStartColumn,
  1295. tabWidth, preserveTrailingSpaces: true);
  1296. currentRow = nRow;
  1297. currentColumn = nCol;
  1298. selectionStartRow = nStartRow;
  1299. selectionStartColumn = nStartCol;
  1300. SetNeedsDisplay ();
  1301. }
  1302. }
  1303. int frameWidth => Math.Max (Frame.Width - (RightOffset != 0 ? 2 : 1), 0);
  1304. /// <summary>
  1305. /// Gets or sets the top row.
  1306. /// </summary>
  1307. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  1308. /// <summary>
  1309. /// Gets or sets the left column.
  1310. /// </summary>
  1311. public int LeftColumn {
  1312. get => leftColumn;
  1313. set {
  1314. if (value > 0 && wordWrap)
  1315. return;
  1316. leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0);
  1317. }
  1318. }
  1319. /// <summary>
  1320. /// Gets the maximum visible length line.
  1321. /// </summary>
  1322. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  1323. /// <summary>
  1324. /// Gets the number of lines.
  1325. /// </summary>
  1326. public int Lines => model.Count;
  1327. /// <summary>
  1328. /// Sets or gets the current cursor position.
  1329. /// </summary>
  1330. public Point CursorPosition {
  1331. get => new Point (currentColumn, currentRow);
  1332. set {
  1333. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  1334. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  1335. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  1336. ? Math.Max (model.Count - 1, 0) : value.Y;
  1337. SetNeedsDisplay ();
  1338. Adjust ();
  1339. }
  1340. }
  1341. /// <summary>
  1342. /// Start column position of the selected text.
  1343. /// </summary>
  1344. public int SelectionStartColumn {
  1345. get => selectionStartColumn;
  1346. set {
  1347. var line = model.GetLine (currentRow);
  1348. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  1349. selecting = true;
  1350. SetNeedsDisplay ();
  1351. Adjust ();
  1352. }
  1353. }
  1354. /// <summary>
  1355. /// Start row position of the selected text.
  1356. /// </summary>
  1357. public int SelectionStartRow {
  1358. get => selectionStartRow;
  1359. set {
  1360. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  1361. ? Math.Max (model.Count - 1, 0) : value;
  1362. selecting = true;
  1363. SetNeedsDisplay ();
  1364. Adjust ();
  1365. }
  1366. }
  1367. /// <summary>
  1368. /// The selected text.
  1369. /// </summary>
  1370. public ustring SelectedText {
  1371. get {
  1372. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  1373. return ustring.Empty;
  1374. }
  1375. return GetSelectedRegion ();
  1376. }
  1377. }
  1378. /// <summary>
  1379. /// Length of the selected text.
  1380. /// </summary>
  1381. public int SelectedLength => GetSelectedLength ();
  1382. /// <summary>
  1383. /// Get or sets the selecting.
  1384. /// </summary>
  1385. public bool Selecting {
  1386. get => selecting;
  1387. set => selecting = value;
  1388. }
  1389. /// <summary>
  1390. /// Allows word wrap the to fit the available container width.
  1391. /// </summary>
  1392. public bool WordWrap {
  1393. get => wordWrap;
  1394. set {
  1395. if (value == wordWrap) {
  1396. return;
  1397. }
  1398. if (value && !multiline) {
  1399. return;
  1400. }
  1401. wordWrap = value;
  1402. ResetPosition ();
  1403. if (wordWrap) {
  1404. wrapManager = new WordWrapManager (model);
  1405. model = wrapManager.WrapModel (frameWidth, out _, out _, out _, out _);
  1406. } else if (!wordWrap && wrapManager != null) {
  1407. model = wrapManager.Model;
  1408. }
  1409. SetNeedsDisplay ();
  1410. }
  1411. }
  1412. /// <summary>
  1413. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1414. /// This is only needed with the keyboard navigation.
  1415. /// </summary>
  1416. public int BottomOffset {
  1417. get => bottomOffset;
  1418. set {
  1419. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1420. topRow = Math.Max (topRow - bottomOffset, 0);
  1421. }
  1422. bottomOffset = value;
  1423. Adjust ();
  1424. }
  1425. }
  1426. /// <summary>
  1427. /// The right offset needed to use a vertical scrollbar or for another reason.
  1428. /// This is only needed with the keyboard navigation.
  1429. /// </summary>
  1430. public int RightOffset {
  1431. get => rightOffset;
  1432. set {
  1433. if (!wordWrap && currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1434. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1435. }
  1436. rightOffset = value;
  1437. Adjust ();
  1438. }
  1439. }
  1440. /// <summary>
  1441. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1442. /// creates a new line of text in the view or activates the default button for the toplevel.
  1443. /// </summary>
  1444. public bool AllowsReturn {
  1445. get => allowsReturn;
  1446. set {
  1447. allowsReturn = value;
  1448. if (allowsReturn && !multiline) {
  1449. Multiline = true;
  1450. }
  1451. if (!allowsReturn && multiline) {
  1452. Multiline = false;
  1453. AllowsTab = false;
  1454. }
  1455. SetNeedsDisplay ();
  1456. }
  1457. }
  1458. /// <summary>
  1459. /// Gets or sets whether the <see cref="TextView"/> inserts a tab character into the text or ignores
  1460. /// tab input. If set to `false` and the user presses the tab key (or shift-tab) the focus will move to the
  1461. /// next view (or previous with shift-tab). The default is `true`; if the user presses the tab key, a tab
  1462. /// character will be inserted into the text.
  1463. /// </summary>
  1464. public bool AllowsTab {
  1465. get => allowsTab;
  1466. set {
  1467. allowsTab = value;
  1468. if (allowsTab && tabWidth == 0) {
  1469. tabWidth = 4;
  1470. }
  1471. if (allowsTab && !multiline) {
  1472. Multiline = true;
  1473. }
  1474. if (!allowsTab && tabWidth > 0) {
  1475. tabWidth = 0;
  1476. }
  1477. SetNeedsDisplay ();
  1478. }
  1479. }
  1480. /// <summary>
  1481. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1482. /// </summary>
  1483. public int TabWidth {
  1484. get => tabWidth;
  1485. set {
  1486. tabWidth = Math.Max (value, 0);
  1487. if (tabWidth > 0 && !AllowsTab) {
  1488. AllowsTab = true;
  1489. }
  1490. SetNeedsDisplay ();
  1491. }
  1492. }
  1493. Dim savedHeight = null;
  1494. /// <summary>
  1495. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1496. /// </summary>
  1497. public bool Multiline {
  1498. get => multiline;
  1499. set {
  1500. multiline = value;
  1501. if (multiline && !allowsTab) {
  1502. AllowsTab = true;
  1503. }
  1504. if (multiline && !allowsReturn) {
  1505. AllowsReturn = true;
  1506. }
  1507. if (!multiline) {
  1508. AllowsReturn = false;
  1509. AllowsTab = false;
  1510. WordWrap = false;
  1511. currentColumn = 0;
  1512. currentRow = 0;
  1513. savedHeight = Height;
  1514. var lyout = LayoutStyle;
  1515. if (LayoutStyle == LayoutStyle.Computed) {
  1516. LayoutStyle = LayoutStyle.Absolute;
  1517. }
  1518. Height = 1;
  1519. LayoutStyle = lyout;
  1520. Autocomplete.PopupInsideContainer = false;
  1521. SetNeedsDisplay ();
  1522. } else if (multiline && savedHeight != null) {
  1523. var lyout = LayoutStyle;
  1524. if (LayoutStyle == LayoutStyle.Computed) {
  1525. LayoutStyle = LayoutStyle.Absolute;
  1526. }
  1527. Height = savedHeight;
  1528. LayoutStyle = lyout;
  1529. Autocomplete.PopupInsideContainer = true;
  1530. SetNeedsDisplay ();
  1531. }
  1532. }
  1533. }
  1534. /// <summary>
  1535. /// Indicates whatever the text was changed or not.
  1536. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  1537. /// </summary>
  1538. public bool IsDirty => historyText.IsDirty (Text);
  1539. /// <summary>
  1540. /// Indicates whatever the text has history changes or not.
  1541. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  1542. /// </summary>
  1543. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  1544. /// <summary>
  1545. /// Get the <see cref="ContextMenu"/> for this view.
  1546. /// </summary>
  1547. public ContextMenu ContextMenu { get; private set; }
  1548. int GetSelectedLength ()
  1549. {
  1550. return SelectedText.Length;
  1551. }
  1552. CursorVisibility savedCursorVisibility;
  1553. void SaveCursorVisibility ()
  1554. {
  1555. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1556. if (savedCursorVisibility == 0) {
  1557. savedCursorVisibility = desiredCursorVisibility;
  1558. }
  1559. DesiredCursorVisibility = CursorVisibility.Invisible;
  1560. }
  1561. }
  1562. void ResetCursorVisibility ()
  1563. {
  1564. if (savedCursorVisibility != 0) {
  1565. DesiredCursorVisibility = savedCursorVisibility;
  1566. savedCursorVisibility = 0;
  1567. }
  1568. }
  1569. /// <summary>
  1570. /// Loads the contents of the file into the <see cref="TextView"/>.
  1571. /// </summary>
  1572. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1573. /// <param name="path">Path to the file to load.</param>
  1574. public bool LoadFile (string path)
  1575. {
  1576. bool res;
  1577. try {
  1578. SetWrapModel ();
  1579. res = model.LoadFile (path);
  1580. historyText.Clear (Text);
  1581. ResetPosition ();
  1582. } catch (Exception) {
  1583. throw;
  1584. } finally {
  1585. UpdateWrapModel ();
  1586. SetNeedsDisplay ();
  1587. Adjust ();
  1588. }
  1589. return res;
  1590. }
  1591. /// <summary>
  1592. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1593. /// </summary>
  1594. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1595. /// <param name="stream">Stream to load the contents from.</param>
  1596. public void LoadStream (Stream stream)
  1597. {
  1598. model.LoadStream (stream);
  1599. historyText.Clear (Text);
  1600. ResetPosition ();
  1601. SetNeedsDisplay ();
  1602. }
  1603. /// <summary>
  1604. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1605. /// </summary>
  1606. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1607. public bool CloseFile ()
  1608. {
  1609. var res = model.CloseFile ();
  1610. ResetPosition ();
  1611. SetNeedsDisplay ();
  1612. return res;
  1613. }
  1614. /// <summary>
  1615. /// Gets the current cursor row.
  1616. /// </summary>
  1617. public int CurrentRow => currentRow;
  1618. /// <summary>
  1619. /// Gets the cursor column.
  1620. /// </summary>
  1621. /// <value>The cursor column.</value>
  1622. public int CurrentColumn => currentColumn;
  1623. /// <summary>
  1624. /// Positions the cursor on the current row and column
  1625. /// </summary>
  1626. public override void PositionCursor ()
  1627. {
  1628. if (!CanFocus || !Enabled || Application.Driver == null) {
  1629. return;
  1630. }
  1631. if (selecting) {
  1632. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1633. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1634. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1635. }
  1636. var line = model.GetLine (currentRow);
  1637. var col = 0;
  1638. if (line.Count > 0) {
  1639. for (int idx = leftColumn; idx < line.Count; idx++) {
  1640. if (idx >= currentColumn)
  1641. break;
  1642. var cols = Rune.ColumnWidth (line [idx]);
  1643. if (line [idx] == '\t') {
  1644. cols += TabWidth + 1;
  1645. }
  1646. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1647. col = currentColumn;
  1648. break;
  1649. }
  1650. }
  1651. }
  1652. var posX = currentColumn - leftColumn;
  1653. var posY = currentRow - topRow;
  1654. if (posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1655. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1656. ResetCursorVisibility ();
  1657. Move (col, currentRow - topRow);
  1658. } else {
  1659. SaveCursorVisibility ();
  1660. }
  1661. }
  1662. void ClearRegion (int left, int top, int right, int bottom)
  1663. {
  1664. for (int row = top; row < bottom; row++) {
  1665. Move (left, row);
  1666. for (int col = left; col < right; col++)
  1667. AddRune (col, row, ' ');
  1668. }
  1669. }
  1670. /// <summary>
  1671. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1672. /// </summary>
  1673. protected virtual void SetNormalColor ()
  1674. {
  1675. Driver.SetAttribute (GetNormalColor ());
  1676. }
  1677. /// <summary>
  1678. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1679. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1680. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1681. /// </summary>
  1682. /// <param name="line"></param>
  1683. /// <param name="idx"></param>
  1684. protected virtual void SetNormalColor (List<Rune> line, int idx)
  1685. {
  1686. Driver.SetAttribute (GetNormalColor ());
  1687. }
  1688. /// <summary>
  1689. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1690. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1691. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1692. /// </summary>
  1693. /// <param name="line"></param>
  1694. /// <param name="idx"></param>
  1695. protected virtual void SetSelectionColor (List<Rune> line, int idx)
  1696. {
  1697. Driver.SetAttribute (new Attribute (ColorScheme.Focus.Background, ColorScheme.Focus.Foreground));
  1698. }
  1699. /// <summary>
  1700. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1701. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1702. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1703. /// </summary>
  1704. /// <param name="line"></param>
  1705. /// <param name="idx"></param>
  1706. protected virtual void SetReadOnlyColor (List<Rune> line, int idx)
  1707. {
  1708. Attribute attribute;
  1709. if (ColorScheme.Disabled.Foreground == ColorScheme.Focus.Background) {
  1710. attribute = new Attribute (ColorScheme.Focus.Foreground, ColorScheme.Focus.Background);
  1711. } else {
  1712. attribute = new Attribute (ColorScheme.Disabled.Foreground, ColorScheme.Focus.Background);
  1713. }
  1714. Driver.SetAttribute (attribute);
  1715. }
  1716. /// <summary>
  1717. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1718. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1719. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1720. /// </summary>
  1721. /// <param name="line"></param>
  1722. /// <param name="idx"></param>
  1723. protected virtual void SetUsedColor (List<Rune> line, int idx)
  1724. {
  1725. Driver.SetAttribute (ColorScheme.HotFocus);
  1726. }
  1727. bool isReadOnly = false;
  1728. /// <summary>
  1729. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1730. /// </summary>
  1731. /// <value>Boolean value(Default false)</value>
  1732. public bool ReadOnly {
  1733. get => isReadOnly;
  1734. set {
  1735. if (value != isReadOnly) {
  1736. isReadOnly = value;
  1737. SetNeedsDisplay ();
  1738. Adjust ();
  1739. }
  1740. }
  1741. }
  1742. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1743. /// <summary>
  1744. /// Get / Set the wished cursor when the field is focused
  1745. /// </summary>
  1746. public CursorVisibility DesiredCursorVisibility {
  1747. get => desiredCursorVisibility;
  1748. set {
  1749. if (HasFocus) {
  1750. Application.Driver.SetCursorVisibility (value);
  1751. }
  1752. desiredCursorVisibility = value;
  1753. SetNeedsDisplay ();
  1754. }
  1755. }
  1756. ///<inheritdoc/>
  1757. public override bool OnEnter (View view)
  1758. {
  1759. //TODO: Improve it by handling read only mode of the text field
  1760. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1761. return base.OnEnter (view);
  1762. }
  1763. ///<inheritdoc/>
  1764. public override bool OnLeave (View view)
  1765. {
  1766. if (Application.MouseGrabView != null && Application.MouseGrabView == this) {
  1767. Application.UngrabMouse ();
  1768. }
  1769. return base.OnLeave (view);
  1770. }
  1771. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1772. void GetEncodedRegionBounds (out long start, out long end,
  1773. int? startRow = null, int? startCol = null, int? cRow = null, int? cCol = null)
  1774. {
  1775. long selection;
  1776. long point;
  1777. if (startRow == null || startCol == null || cRow == null || cCol == null) {
  1778. selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1779. point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1780. } else {
  1781. selection = ((long)(uint)startRow << 32) | (uint)startCol;
  1782. point = ((long)(uint)cRow << 32) | (uint)cCol;
  1783. }
  1784. if (selection > point) {
  1785. start = point;
  1786. end = selection;
  1787. } else {
  1788. start = selection;
  1789. end = point;
  1790. }
  1791. }
  1792. bool PointInSelection (int col, int row)
  1793. {
  1794. long start, end;
  1795. GetEncodedRegionBounds (out start, out end);
  1796. var q = ((long)(uint)row << 32) | (uint)col;
  1797. return q >= start && q <= end - 1;
  1798. }
  1799. //
  1800. // Returns a ustring with the text in the selected
  1801. // region.
  1802. //
  1803. ustring GetRegion (int? sRow = null, int? sCol = null, int? cRow = null, int? cCol = null, TextModel model = null)
  1804. {
  1805. long start, end;
  1806. GetEncodedRegionBounds (out start, out end, sRow, sCol, cRow, cCol);
  1807. if (start == end) {
  1808. return ustring.Empty;
  1809. }
  1810. int startRow = (int)(start >> 32);
  1811. var maxrow = ((int)(end >> 32));
  1812. int startCol = (int)(start & 0xffffffff);
  1813. var endCol = (int)(end & 0xffffffff);
  1814. var line = model == null ? this.model.GetLine (startRow) : model.GetLine (startRow);
  1815. if (startRow == maxrow)
  1816. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1817. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1818. for (int row = startRow + 1; row < maxrow; row++) {
  1819. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (model == null
  1820. ? this.model.GetLine (row) : model.GetLine (row));
  1821. }
  1822. line = model == null ? this.model.GetLine (maxrow) : model.GetLine (maxrow);
  1823. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (line.GetRange (0, endCol));
  1824. return res;
  1825. }
  1826. //
  1827. // Clears the contents of the selected region
  1828. //
  1829. void ClearRegion ()
  1830. {
  1831. SetWrapModel ();
  1832. long start, end;
  1833. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1834. GetEncodedRegionBounds (out start, out end);
  1835. int startRow = (int)(start >> 32);
  1836. var maxrow = ((int)(end >> 32));
  1837. int startCol = (int)(start & 0xffffffff);
  1838. var endCol = (int)(end & 0xffffffff);
  1839. var line = model.GetLine (startRow);
  1840. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, new Point (startCol, startRow));
  1841. List<List<Rune>> removedLines = new List<List<Rune>> ();
  1842. if (startRow == maxrow) {
  1843. removedLines.Add (new List<Rune> (line));
  1844. line.RemoveRange (startCol, endCol - startCol);
  1845. currentColumn = startCol;
  1846. if (wordWrap) {
  1847. SetNeedsDisplay ();
  1848. } else {
  1849. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1850. }
  1851. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition, HistoryText.LineStatus.Removed);
  1852. UpdateWrapModel ();
  1853. return;
  1854. }
  1855. removedLines.Add (new List<Rune> (line));
  1856. line.RemoveRange (startCol, line.Count - startCol);
  1857. var line2 = model.GetLine (maxrow);
  1858. line.AddRange (line2.Skip (endCol));
  1859. for (int row = startRow + 1; row <= maxrow; row++) {
  1860. removedLines.Add (new List<Rune> (model.GetLine (startRow + 1)));
  1861. model.RemoveLine (startRow + 1);
  1862. }
  1863. if (currentEncoded == end) {
  1864. currentRow -= maxrow - (startRow);
  1865. }
  1866. currentColumn = startCol;
  1867. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  1868. HistoryText.LineStatus.Removed);
  1869. UpdateWrapModel ();
  1870. SetNeedsDisplay ();
  1871. }
  1872. /// <summary>
  1873. /// Select all text.
  1874. /// </summary>
  1875. public void SelectAll ()
  1876. {
  1877. if (model.Count == 0) {
  1878. return;
  1879. }
  1880. StartSelecting ();
  1881. selectionStartColumn = 0;
  1882. selectionStartRow = 0;
  1883. currentColumn = model.GetLine (model.Count - 1).Count;
  1884. currentRow = model.Count - 1;
  1885. SetNeedsDisplay ();
  1886. }
  1887. /// <summary>
  1888. /// Find the next text based on the match case with the option to replace it.
  1889. /// </summary>
  1890. /// <param name="textToFind">The text to find.</param>
  1891. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1892. /// <param name="matchCase">The match case setting.</param>
  1893. /// <param name="matchWholeWord">The match whole word setting.</param>
  1894. /// <param name="textToReplace">The text to replace.</param>
  1895. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1896. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1897. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1898. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1899. {
  1900. if (model.Count == 0) {
  1901. gaveFullTurn = false;
  1902. return false;
  1903. }
  1904. SetWrapModel ();
  1905. ResetContinuousFind ();
  1906. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1907. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1908. }
  1909. /// <summary>
  1910. /// Find the previous text based on the match case with the option to replace it.
  1911. /// </summary>
  1912. /// <param name="textToFind">The text to find.</param>
  1913. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1914. /// <param name="matchCase">The match case setting.</param>
  1915. /// <param name="matchWholeWord">The match whole word setting.</param>
  1916. /// <param name="textToReplace">The text to replace.</param>
  1917. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1918. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1919. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1920. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1921. {
  1922. if (model.Count == 0) {
  1923. gaveFullTurn = false;
  1924. return false;
  1925. }
  1926. SetWrapModel ();
  1927. ResetContinuousFind ();
  1928. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1929. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1930. }
  1931. /// <summary>
  1932. /// Reset the flag to stop continuous find.
  1933. /// </summary>
  1934. public void FindTextChanged ()
  1935. {
  1936. continuousFind = false;
  1937. }
  1938. /// <summary>
  1939. /// Replaces all the text based on the match case.
  1940. /// </summary>
  1941. /// <param name="textToFind">The text to find.</param>
  1942. /// <param name="matchCase">The match case setting.</param>
  1943. /// <param name="matchWholeWord">The match whole word setting.</param>
  1944. /// <param name="textToReplace">The text to replace.</param>
  1945. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1946. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1947. ustring textToReplace = null)
  1948. {
  1949. if (isReadOnly || model.Count == 0) {
  1950. return false;
  1951. }
  1952. SetWrapModel ();
  1953. ResetContinuousFind ();
  1954. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1955. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1956. }
  1957. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1958. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1959. {
  1960. if (foundPos.found) {
  1961. StartSelecting ();
  1962. selectionStartColumn = foundPos.current.X;
  1963. selectionStartRow = foundPos.current.Y;
  1964. if (!replaceAll) {
  1965. currentColumn = selectionStartColumn + text.RuneCount;
  1966. } else {
  1967. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1968. }
  1969. currentRow = foundPos.current.Y;
  1970. if (!isReadOnly && replace) {
  1971. Adjust ();
  1972. ClearSelectedRegion ();
  1973. InsertText (textToReplace);
  1974. StartSelecting ();
  1975. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1976. } else {
  1977. UpdateWrapModel ();
  1978. SetNeedsDisplay ();
  1979. Adjust ();
  1980. }
  1981. continuousFind = true;
  1982. return foundPos.found;
  1983. }
  1984. UpdateWrapModel ();
  1985. continuousFind = false;
  1986. return foundPos.found;
  1987. }
  1988. void ResetContinuousFind ()
  1989. {
  1990. if (!continuousFind) {
  1991. var col = selecting ? selectionStartColumn : currentColumn;
  1992. var row = selecting ? selectionStartRow : currentRow;
  1993. model.ResetContinuousFind (new Point (col, row));
  1994. }
  1995. }
  1996. string currentCaller;
  1997. /// <summary>
  1998. /// Restore from original model.
  1999. /// </summary>
  2000. void SetWrapModel ([CallerMemberName] string caller = null)
  2001. {
  2002. if (currentCaller != null)
  2003. return;
  2004. if (wordWrap) {
  2005. currentCaller = caller;
  2006. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2007. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2008. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2009. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2010. model = wrapManager.Model;
  2011. }
  2012. }
  2013. /// <summary>
  2014. /// Update the original model.
  2015. /// </summary>
  2016. void UpdateWrapModel ([CallerMemberName] string caller = null)
  2017. {
  2018. if (currentCaller != null && currentCaller != caller)
  2019. return;
  2020. if (wordWrap) {
  2021. currentCaller = null;
  2022. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  2023. out int nStartRow, out int nStartCol,
  2024. currentRow, currentColumn,
  2025. selectionStartRow, selectionStartColumn, preserveTrailingSpaces: true);
  2026. currentRow = nRow;
  2027. currentColumn = nCol;
  2028. selectionStartRow = nStartRow;
  2029. selectionStartColumn = nStartCol;
  2030. wrapNeeded = true;
  2031. }
  2032. if (currentCaller != null)
  2033. throw new InvalidOperationException ($"WordWrap settings was changed after the {currentCaller} call.");
  2034. }
  2035. /// <summary>
  2036. /// Invoke the <see cref="UnwrappedCursorPosition"/> event with the unwrapped <see cref="CursorPosition"/>.
  2037. /// </summary>
  2038. public virtual void OnUnwrappedCursorPosition (int? cRow = null, int? cCol = null)
  2039. {
  2040. var row = cRow == null ? currentRow : cRow;
  2041. var col = cCol == null ? currentColumn : cCol;
  2042. if (cRow == null && cCol == null && wordWrap) {
  2043. row = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2044. col = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2045. }
  2046. UnwrappedCursorPosition?.Invoke (this, new PointEventArgs (new Point ((int)col, (int)row)));
  2047. }
  2048. ustring GetSelectedRegion ()
  2049. {
  2050. var cRow = currentRow;
  2051. var cCol = currentColumn;
  2052. var startRow = selectionStartRow;
  2053. var startCol = selectionStartColumn;
  2054. var model = this.model;
  2055. if (wordWrap) {
  2056. cRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  2057. cCol = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  2058. startRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  2059. startCol = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  2060. model = wrapManager.Model;
  2061. }
  2062. OnUnwrappedCursorPosition (cRow, cCol);
  2063. return GetRegion (startRow, startCol, cRow, cCol, model);
  2064. }
  2065. ///<inheritdoc/>
  2066. public override void OnDrawContent (Rect contentArea)
  2067. {
  2068. SetNormalColor ();
  2069. var offB = OffSetBackground ();
  2070. int right = Frame.Width + offB.width + RightOffset;
  2071. int bottom = Frame.Height + offB.height + BottomOffset;
  2072. var row = 0;
  2073. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  2074. var line = model.GetLine (idxRow);
  2075. int lineRuneCount = line.Count;
  2076. var col = 0;
  2077. Move (0, row);
  2078. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  2079. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  2080. var cols = Rune.ColumnWidth (rune);
  2081. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  2082. SetSelectionColor (line, idxCol);
  2083. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  2084. && HasFocus && idxCol < lineRuneCount) {
  2085. SetSelectionColor (line, idxCol);
  2086. } else if (ReadOnly) {
  2087. SetReadOnlyColor (line, idxCol);
  2088. } else {
  2089. SetNormalColor (line, idxCol);
  2090. }
  2091. if (rune == '\t') {
  2092. cols += TabWidth + 1;
  2093. if (col + cols > right) {
  2094. cols = right - col;
  2095. }
  2096. for (int i = 0; i < cols; i++) {
  2097. if (col + i < right) {
  2098. AddRune (col + i, row, ' ');
  2099. }
  2100. }
  2101. } else {
  2102. AddRune (col, row, rune);
  2103. }
  2104. if (!TextModel.SetCol (ref col, contentArea.Right, cols)) {
  2105. break;
  2106. }
  2107. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  2108. break;
  2109. }
  2110. }
  2111. if (col < right) {
  2112. SetNormalColor ();
  2113. ClearRegion (col, row, right, row + 1);
  2114. }
  2115. row++;
  2116. }
  2117. if (row < bottom) {
  2118. SetNormalColor ();
  2119. ClearRegion (contentArea.Left, row, right, bottom);
  2120. }
  2121. PositionCursor ();
  2122. if (clickWithSelecting) {
  2123. clickWithSelecting = false;
  2124. return;
  2125. }
  2126. if (SelectedLength > 0)
  2127. return;
  2128. // draw autocomplete
  2129. Autocomplete.GenerateSuggestions ();
  2130. var renderAt = new Point (
  2131. CursorPosition.X - LeftColumn,
  2132. Autocomplete.PopupInsideContainer
  2133. ? (CursorPosition.Y + 1) - TopRow
  2134. : 0);
  2135. Autocomplete.RenderOverlay (renderAt);
  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 (_needsDisplay.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 = !_needsDisplay.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.Suggestions.Count > 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 (_needsDisplay.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 : Autocomplete {
  3817. ///<inheritdoc/>
  3818. protected override string GetCurrentWord (int columnOffset = 0)
  3819. {
  3820. var host = (TextView)HostControl;
  3821. var currentLine = host.GetCurrentLine ();
  3822. var cursorPosition = Math.Min (host.CurrentColumn + columnOffset, currentLine.Count);
  3823. return IdxToWord (currentLine, cursorPosition, columnOffset);
  3824. }
  3825. /// <inheritdoc/>
  3826. protected override void DeleteTextBackwards ()
  3827. {
  3828. ((TextView)HostControl).DeleteCharLeft ();
  3829. }
  3830. /// <inheritdoc/>
  3831. protected override void InsertText (string accepted)
  3832. {
  3833. ((TextView)HostControl).InsertText (accepted);
  3834. }
  3835. }
  3836. }