TextView.cs 124 KB

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