2
0

TextView.cs 135 KB

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