bim.c 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. *
  3. * Copyright (C) 2012-2019 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. * bim - Text editor
  18. *
  19. * Bim is inspired by vim, and its name is short for "Bad IMitation".
  20. *
  21. * Bim supports syntax highlighting, extensive editing, line selection
  22. * and copy-paste, undo/redo stack, forward and backward search, and can
  23. * be built for ToaruOS, Sortix, Linux, macOS, and BSDs.
  24. */
  25. #define _XOPEN_SOURCE
  26. #define _DEFAULT_SOURCE
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <termios.h>
  34. #include <signal.h>
  35. #include <locale.h>
  36. #include <wchar.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <poll.h>
  40. #include <limits.h>
  41. #include <sys/types.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/stat.h>
  44. #define BIM_VERSION "1.5.1"
  45. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  46. #define BLOCK_SIZE 4096
  47. #define ENTER_KEY '\r'
  48. #define LINE_FEED '\n'
  49. #define BACKSPACE_KEY 0x08
  50. #define DELETE_KEY 0x7F
  51. /**
  52. * Theming data
  53. *
  54. * This is all overridden by a load_colorscheme_ method.
  55. * The default is to load_colorscheme_ansi, but config
  56. * files can be used to set a different default theme.
  57. */
  58. const char * COLOR_FG = "@17";
  59. const char * COLOR_BG = "@0";
  60. const char * COLOR_ALT_FG = "@17";
  61. const char * COLOR_ALT_BG = "@0";
  62. const char * COLOR_NUMBER_FG = "@17";
  63. const char * COLOR_NUMBER_BG = "@0";
  64. const char * COLOR_STATUS_FG = "@17";
  65. const char * COLOR_STATUS_BG = "@0";
  66. const char * COLOR_TABBAR_BG = "@0";
  67. const char * COLOR_TAB_BG = "@0";
  68. const char * COLOR_ERROR_FG = "@17";
  69. const char * COLOR_ERROR_BG = "@0";
  70. const char * COLOR_SEARCH_FG = "@17";
  71. const char * COLOR_SEARCH_BG = "@0";
  72. const char * COLOR_KEYWORD = "@17";
  73. const char * COLOR_STRING = "@17";
  74. const char * COLOR_COMMENT = "@17";
  75. const char * COLOR_TYPE = "@17";
  76. const char * COLOR_PRAGMA = "@17";
  77. const char * COLOR_NUMERAL = "@17";
  78. const char * COLOR_SELECTFG = "@0";
  79. const char * COLOR_SELECTBG = "@17";
  80. const char * COLOR_RED = "@1";
  81. const char * COLOR_GREEN = "@2";
  82. const char * COLOR_BOLD = "@17";
  83. const char * COLOR_LINK = "@17";
  84. const char * COLOR_ESCAPE = "@17";
  85. const char * current_theme = "none";
  86. /**
  87. * Syntax highlighting flags.
  88. */
  89. #define FLAG_NONE 0
  90. #define FLAG_KEYWORD 1
  91. #define FLAG_STRING 2
  92. #define FLAG_COMMENT 3
  93. #define FLAG_TYPE 4
  94. #define FLAG_PRAGMA 5
  95. #define FLAG_NUMERAL 6
  96. #define FLAG_STRING2 7
  97. #define FLAG_DIFFPLUS 8
  98. #define FLAG_DIFFMINUS 9
  99. #define FLAG_NOTICE 10
  100. #define FLAG_BOLD 11
  101. #define FLAG_LINK 12
  102. #define FLAG_ESCAPE 13
  103. #define FLAG_SELECT (1 << 5)
  104. #define FLAG_SEARCH (1 << 6)
  105. /**
  106. * Convert syntax hilighting flag to color code
  107. */
  108. const char * flag_to_color(int _flag) {
  109. int flag = _flag & 0xF;
  110. switch (flag) {
  111. case FLAG_KEYWORD:
  112. return COLOR_KEYWORD;
  113. case FLAG_STRING:
  114. case FLAG_STRING2: /* allows python to differentiate " and ' */
  115. return COLOR_STRING;
  116. case FLAG_COMMENT:
  117. return COLOR_COMMENT;
  118. case FLAG_TYPE:
  119. return COLOR_TYPE;
  120. case FLAG_NUMERAL:
  121. return COLOR_NUMERAL;
  122. case FLAG_PRAGMA:
  123. return COLOR_PRAGMA;
  124. case FLAG_DIFFPLUS:
  125. return COLOR_GREEN;
  126. case FLAG_DIFFMINUS:
  127. return COLOR_RED;
  128. case FLAG_SELECT:
  129. return COLOR_FG;
  130. case FLAG_BOLD:
  131. return COLOR_BOLD;
  132. case FLAG_LINK:
  133. return COLOR_LINK;
  134. case FLAG_ESCAPE:
  135. return COLOR_ESCAPE;
  136. default:
  137. return COLOR_FG;
  138. }
  139. }
  140. /**
  141. * Line buffer definitions
  142. *
  143. * Lines are essentially resizable vectors of char_t structs,
  144. * which represent single codepoints in the file.
  145. */
  146. typedef struct {
  147. uint32_t display_width:4;
  148. uint32_t flags:7;
  149. uint32_t codepoint:21;
  150. } __attribute__((packed)) char_t;
  151. /**
  152. * Lines have available and actual lengths, describing
  153. * how much space was allocated vs. how much is being
  154. * used at the moment.
  155. */
  156. typedef struct {
  157. int available;
  158. int actual;
  159. int istate;
  160. int is_current;
  161. int rev_status;
  162. char_t text[];
  163. } line_t;
  164. /**
  165. * Global configuration state
  166. */
  167. struct {
  168. /* Terminal size */
  169. int term_width, term_height;
  170. int bottom_size;
  171. line_t ** yanks;
  172. size_t yank_count;
  173. int yank_is_full_lines;
  174. int tty_in;
  175. const char * bimrc_path;
  176. unsigned int hilight_on_open:1;
  177. unsigned int initial_file_is_read_only:1;
  178. unsigned int can_scroll:1;
  179. unsigned int can_hideshow:1;
  180. unsigned int can_altscreen:1;
  181. unsigned int can_mouse:1;
  182. unsigned int can_unicode:1;
  183. unsigned int can_bright:1;
  184. unsigned int can_title:1;
  185. unsigned int can_bce:1;
  186. unsigned int history_enabled:1;
  187. unsigned int highlight_parens:1;
  188. unsigned int smart_case:1;
  189. unsigned int can_24bit:1;
  190. unsigned int can_256color:1;
  191. unsigned int can_italic:1;
  192. unsigned int go_to_line:1;
  193. unsigned int hilight_current_line:1;
  194. unsigned int shift_scrolling:1;
  195. unsigned int check_git:1;
  196. unsigned int color_gutter:1;
  197. int cursor_padding;
  198. int split_percent;
  199. int scroll_amount;
  200. } global_config = {
  201. 0, /* term_width */
  202. 0, /* term_height */
  203. 2, /* bottom_size */
  204. NULL, /* yanks */
  205. 0, /* yank_count */
  206. 0, /* yank is full lines */
  207. STDIN_FILENO, /* tty_in */
  208. "~/.bimrc", /* bimrc_path */
  209. 1, /* hilight_on_open */
  210. 0, /* initial_file_is_read_only */
  211. 1, /* can scroll */
  212. 1, /* can hide/show cursor */
  213. 1, /* can use alternate screen */
  214. 1, /* can mouse */
  215. 1, /* can unicode */
  216. 1, /* can use bright colors */
  217. 1, /* can set title */
  218. 1, /* can bce */
  219. 1, /* history enabled */
  220. 1, /* highlight parens/braces when cursor moves */
  221. 1, /* smart case */
  222. 1, /* can use 24-bit color */
  223. 1, /* can use 265 colors */
  224. 1, /* can use italics (without inverting) */
  225. 1, /* should go to line when opening file */
  226. 1, /* hilight the current line */
  227. 1, /* shift scrolling (shifts view rather than moving cursor) */
  228. 0, /* check git on open and on save */
  229. 1, /* color the gutter for modified lines */
  230. 4, /* cursor padding */
  231. 50, /* split percentage */
  232. 5, /* how many lines to scroll on mouse wheel */
  233. };
  234. void redraw_line(int j, int x);
  235. int git_examine(char * filename);
  236. void search_next(void);
  237. void set_preferred_column(void);
  238. /**
  239. * Special implementation of getch with a timeout
  240. */
  241. int _bim_unget = -1;
  242. void bim_unget(int c) {
  243. _bim_unget = c;
  244. }
  245. #define bim_getch() bim_getch_timeout(200)
  246. int bim_getch_timeout(int timeout) {
  247. if (_bim_unget != -1) {
  248. int out = _bim_unget;
  249. _bim_unget = -1;
  250. return out;
  251. }
  252. struct pollfd fds[1];
  253. fds[0].fd = global_config.tty_in;
  254. fds[0].events = POLLIN;
  255. int ret = poll(fds,1,timeout);
  256. if (ret > 0 && fds[0].revents & POLLIN) {
  257. unsigned char buf[1];
  258. read(global_config.tty_in, buf, 1);
  259. return buf[0];
  260. } else {
  261. return -1;
  262. }
  263. }
  264. #define HISTORY_SENTINEL 0
  265. #define HISTORY_INSERT 1
  266. #define HISTORY_DELETE 2
  267. #define HISTORY_REPLACE 3
  268. #define HISTORY_REMOVE_LINE 4
  269. #define HISTORY_ADD_LINE 5
  270. #define HISTORY_REPLACE_LINE 6
  271. #define HISTORY_MERGE_LINES 7
  272. #define HISTORY_SPLIT_LINE 8
  273. #define HISTORY_BREAK 10
  274. typedef struct history {
  275. struct history * previous;
  276. struct history * next;
  277. int type;
  278. union {
  279. struct {
  280. int lineno;
  281. int offset;
  282. int codepoint;
  283. int old_codepoint;
  284. } insert_delete_replace;
  285. struct {
  286. int lineno;
  287. line_t * contents;
  288. line_t * old_contents;
  289. } remove_replace_line;
  290. struct {
  291. int lineno;
  292. int split;
  293. } add_merge_split_lines;
  294. } contents;
  295. } history_t;
  296. /**
  297. * Buffer data
  298. *
  299. * A buffer describes a file, and stores
  300. * its name as well as the editor state
  301. * (cursor offsets, etc.) and the actual
  302. * line buffers.
  303. */
  304. typedef struct _env {
  305. unsigned short loading:1;
  306. unsigned short tabs:1;
  307. unsigned short modified:1;
  308. unsigned short readonly:1;
  309. unsigned short indent:1;
  310. unsigned short highlighting_paren:1;
  311. unsigned short checkgitstatusonwrite:1;
  312. short mode;
  313. short tabstop;
  314. char * file_name;
  315. int offset;
  316. int coffset;
  317. int line_no;
  318. int line_count;
  319. int line_avail;
  320. int col_no;
  321. int preferred_column;
  322. uint32_t * search;
  323. struct syntax_definition * syntax;
  324. line_t ** lines;
  325. history_t * history;
  326. history_t * last_save_history;
  327. int width;
  328. int left;
  329. int start_line;
  330. int sel_col;
  331. } buffer_t;
  332. /**
  333. * Pointer to current active buffer
  334. */
  335. buffer_t * env;
  336. buffer_t * left_buffer;
  337. buffer_t * right_buffer;
  338. /**
  339. * Editor modes (like in vim)
  340. */
  341. #define MODE_NORMAL 0
  342. #define MODE_INSERT 1
  343. #define MODE_LINE_SELECTION 2
  344. #define MODE_REPLACE 3
  345. #define MODE_CHAR_SELECTION 4
  346. #define MODE_COL_SELECTION 5
  347. #define MODE_COL_INSERT 6
  348. /**
  349. * Available buffers
  350. */
  351. int buffers_len;
  352. int buffers_avail;
  353. buffer_t ** buffers;
  354. /**
  355. * Create a new buffer
  356. */
  357. buffer_t * buffer_new(void) {
  358. if (buffers_len == buffers_avail) {
  359. /* If we are out of buffer space, expand the buffers vector */
  360. buffers_avail *= 2;
  361. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  362. }
  363. /* TODO: Support having split buffers with more than two buffers open */
  364. if (left_buffer) {
  365. left_buffer->left = 0;
  366. left_buffer->width = global_config.term_width;
  367. right_buffer->left = 0;
  368. right_buffer->width = global_config.term_width;
  369. left_buffer = NULL;
  370. right_buffer = NULL;
  371. }
  372. /* Allocate a new buffer */
  373. buffers[buffers_len] = malloc(sizeof(buffer_t));
  374. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  375. buffers[buffers_len]->left = 0;
  376. buffers[buffers_len]->width = global_config.term_width;
  377. buffers_len++;
  378. return buffers[buffers_len-1];
  379. }
  380. /**
  381. * Open the biminfo file.
  382. */
  383. FILE * open_biminfo(void) {
  384. /* TODO This should probably be configurable line bimrc */
  385. char * home = getenv("HOME");
  386. if (!home) {
  387. /* Since it's not, we need HOME */
  388. return NULL;
  389. }
  390. /* biminfo lives at ~/.biminfo */
  391. char biminfo_path[PATH_MAX+1] = {0};
  392. sprintf(biminfo_path,"%s/.biminfo",home);
  393. /* Try to open normally first... */
  394. FILE * biminfo = fopen(biminfo_path,"r+");
  395. if (!biminfo) {
  396. /* Otherwise, try to create it. */
  397. biminfo = fopen(biminfo_path,"w+");
  398. }
  399. return biminfo;
  400. }
  401. /**
  402. * Fetch the cursor position from a biminfo file
  403. */
  404. int fetch_from_biminfo(buffer_t * buf) {
  405. /* Can't fetch if we don't have a filename */
  406. if (!buf->file_name) return 1;
  407. /* Get the absolute name of the file */
  408. char tmp_path[PATH_MAX+2];
  409. if (!realpath(buf->file_name, tmp_path)) {
  410. return 1;
  411. }
  412. strcat(tmp_path," ");
  413. FILE * biminfo = open_biminfo();
  414. if (!biminfo) return 1;
  415. /* Scan */
  416. char line[PATH_MAX+64];
  417. while (!feof(biminfo)) {
  418. fpos_t start_of_line;
  419. fgetpos(biminfo, &start_of_line);
  420. fgets(line, PATH_MAX+63, biminfo);
  421. if (line[0] != '>') {
  422. continue;
  423. }
  424. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  425. /* Read */
  426. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  427. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  428. return 0;
  429. }
  430. }
  431. return 0;
  432. }
  433. /**
  434. * Write a file containing the last cursor position of a buffer.
  435. */
  436. int update_biminfo(buffer_t * buf) {
  437. if (!buf->file_name) return 1;
  438. /* Get the absolute name of the file */
  439. char tmp_path[PATH_MAX+1];
  440. if (!realpath(buf->file_name, tmp_path)) {
  441. return 1;
  442. }
  443. strcat(tmp_path," ");
  444. FILE * biminfo = open_biminfo();
  445. if (!biminfo) return 1;
  446. /* Scan */
  447. char line[PATH_MAX+64];
  448. while (!feof(biminfo)) {
  449. fpos_t start_of_line;
  450. fgetpos(biminfo, &start_of_line);
  451. fgets(line, PATH_MAX+63, biminfo);
  452. if (line[0] != '>') {
  453. continue;
  454. }
  455. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  456. /* Update */
  457. fsetpos(biminfo, &start_of_line);
  458. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  459. goto _done;
  460. }
  461. }
  462. if (ftell(biminfo) == 0) {
  463. /* New biminfo */
  464. fprintf(biminfo, "# This is a biminfo file.\n");
  465. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  466. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  467. }
  468. /* Haven't found what we're looking for, should be at end of file */
  469. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  470. _done:
  471. fclose(biminfo);
  472. return 0;
  473. }
  474. /**
  475. * Close a buffer
  476. */
  477. buffer_t * buffer_close(buffer_t * buf) {
  478. int i;
  479. /* Locate the buffer in the buffer pointer vector */
  480. for (i = 0; i < buffers_len; i++) {
  481. if (buf == buffers[i])
  482. break;
  483. }
  484. /* Invalid buffer? */
  485. if (i == buffers_len) {
  486. return env; /* wtf */
  487. }
  488. update_biminfo(buf);
  489. /* Clean up lines used by old buffer */
  490. for (int i = 0; i < buf->line_count; ++i) {
  491. free(buf->lines[i]);
  492. }
  493. free(buf->lines);
  494. if (buf->search) {
  495. free(buf->search);
  496. }
  497. if (buf->file_name) {
  498. free(buf->file_name);
  499. }
  500. history_t * h = buf->history;
  501. while (h->next) {
  502. h = h->next;
  503. }
  504. while (h) {
  505. history_t * x = h->previous;
  506. free(h);
  507. h = x;
  508. }
  509. /* Clean up the old buffer */
  510. free(buf);
  511. /* Remove the buffer from the vector, moving others up */
  512. if (i != buffers_len - 1) {
  513. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  514. }
  515. /* There is one less buffer */
  516. buffers_len--;
  517. if (!buffers_len) {
  518. /* There are no more buffers. */
  519. return NULL;
  520. }
  521. /* If this was the last buffer, return the previous last buffer */
  522. if (i == buffers_len) {
  523. return buffers[buffers_len-1];
  524. }
  525. /* Otherwise return the new last buffer */
  526. return buffers[i];
  527. }
  528. /**
  529. * Themes
  530. */
  531. /* 16-color theme, default */
  532. void load_colorscheme_ansi(void) {
  533. COLOR_FG = global_config.can_bright ? "@17" : "@7";
  534. COLOR_BG = global_config.can_bright ? "@9" : "@0";
  535. COLOR_ALT_FG = global_config.can_bright ? "@10" : "@5";
  536. COLOR_ALT_BG = "@9";
  537. COLOR_NUMBER_FG = "@3";
  538. COLOR_NUMBER_BG = "@9";
  539. COLOR_STATUS_FG = global_config.can_bright ? "@17" : "@7";
  540. COLOR_STATUS_BG = "@4";
  541. COLOR_TABBAR_BG = "@4";
  542. COLOR_TAB_BG = "@4";
  543. COLOR_KEYWORD = global_config.can_bright ? "@14" : "@4";
  544. COLOR_STRING = "@2";
  545. COLOR_COMMENT = global_config.can_bright ? "@10" : "@5";
  546. COLOR_TYPE = "@3";
  547. COLOR_PRAGMA = "@1";
  548. COLOR_NUMERAL = "@1";
  549. COLOR_ERROR_FG = global_config.can_bright ? "@17" : "@7";
  550. COLOR_ERROR_BG = "@1";
  551. COLOR_SEARCH_FG = "@0";
  552. COLOR_SEARCH_BG = global_config.can_bright ? "@13" : "@3";
  553. COLOR_SELECTBG = global_config.can_bright ? "@17" : "@7";
  554. COLOR_SELECTFG = "@0";
  555. COLOR_RED = "@1";
  556. COLOR_GREEN = "@2";
  557. COLOR_BOLD = COLOR_FG; /* @ doesn't support extra args; FIXME */
  558. COLOR_LINK = global_config.can_bright ? "@14" : "@4";
  559. COLOR_ESCAPE = global_config.can_bright ? "@12" : "@2";
  560. current_theme = "ansi";
  561. }
  562. /* Based on the wombat256 theme for vim */
  563. void load_colorscheme_wombat(void) {
  564. if (!global_config.can_256color) return;
  565. COLOR_FG = "5;230";
  566. COLOR_BG = "5;235";
  567. COLOR_ALT_FG = "5;244";
  568. COLOR_ALT_BG = "5;236";
  569. COLOR_NUMBER_BG = "5;232";
  570. COLOR_NUMBER_FG = "5;101";
  571. COLOR_STATUS_FG = "5;230";
  572. COLOR_STATUS_BG = "5;238";
  573. COLOR_TABBAR_BG = "5;230";
  574. COLOR_TAB_BG = "5;248";
  575. COLOR_KEYWORD = "5;117";
  576. COLOR_STRING = "5;113";
  577. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  578. COLOR_TYPE = "5;186";
  579. COLOR_PRAGMA = "5;173";
  580. COLOR_NUMERAL = COLOR_PRAGMA;
  581. COLOR_ERROR_FG = "5;15";
  582. COLOR_ERROR_BG = "5;196";
  583. COLOR_SEARCH_FG = "5;234";
  584. COLOR_SEARCH_BG = "5;226";
  585. COLOR_SELECTFG = "5;235";
  586. COLOR_SELECTBG = "5;230";
  587. COLOR_RED = "@1";
  588. COLOR_GREEN = "@2";
  589. COLOR_BOLD = "5;230;1";
  590. COLOR_LINK = "5;117;4";
  591. COLOR_ESCAPE = "5;194";
  592. current_theme = "wombat";
  593. }
  594. /* "City Lights" based on citylights.xyz */
  595. void load_colorscheme_citylights(void) {
  596. if (!global_config.can_24bit) return;
  597. COLOR_FG = "2;151;178;198";
  598. COLOR_BG = "2;29;37;44";
  599. COLOR_ALT_FG = "2;45;55;65";
  600. COLOR_ALT_BG = "2;33;42;50";
  601. COLOR_NUMBER_FG = "2;71;89;103";
  602. COLOR_NUMBER_BG = "2;37;47;56";
  603. COLOR_STATUS_FG = "2;116;144;166";
  604. COLOR_STATUS_BG = "2;53;67;78";
  605. COLOR_TABBAR_BG = "2;37;47;56";
  606. COLOR_TAB_BG = "2;29;37;44";
  607. COLOR_KEYWORD = "2;94;196;255";
  608. COLOR_STRING = "2;83;154;252";
  609. COLOR_COMMENT = "2;107;133;153;3";
  610. COLOR_TYPE = "2;139;212;156";
  611. COLOR_PRAGMA = "2;0;139;148";
  612. COLOR_NUMERAL = "2;207;118;132";
  613. COLOR_ERROR_FG = "5;15";
  614. COLOR_ERROR_BG = "5;196";
  615. COLOR_SEARCH_FG = "5;234";
  616. COLOR_SEARCH_BG = "5;226";
  617. COLOR_SELECTFG = "2;29;37;44";
  618. COLOR_SELECTBG = "2;151;178;198";
  619. COLOR_RED = "2;222;53;53";
  620. COLOR_GREEN = "2;55;167;0";
  621. COLOR_BOLD = "2;151;178;198;1";
  622. COLOR_LINK = "2;94;196;255;4";
  623. COLOR_ESCAPE = "2;133;182;249";
  624. current_theme = "citylights";
  625. }
  626. /* Solarized Dark, popular theme */
  627. void load_colorscheme_solarized_dark(void) {
  628. if (!global_config.can_24bit) return;
  629. COLOR_FG = "2;147;161;161";
  630. COLOR_BG = "2;0;43;54";
  631. COLOR_ALT_FG = "2;147;161;161";
  632. COLOR_ALT_BG = "2;7;54;66";
  633. COLOR_NUMBER_FG = "2;131;148;149";
  634. COLOR_NUMBER_BG = "2;7;54;66";
  635. COLOR_STATUS_FG = "2;131;148;150";
  636. COLOR_STATUS_BG = "2;7;54;66";
  637. COLOR_TABBAR_BG = "2;7;54;66";
  638. COLOR_TAB_BG = "2;131;148;150";
  639. COLOR_KEYWORD = "2;133;153;0";
  640. COLOR_STRING = "2;42;161;152";
  641. COLOR_COMMENT = "2;101;123;131";
  642. COLOR_TYPE = "2;181;137;0";
  643. COLOR_PRAGMA = "2;203;75;22";
  644. COLOR_NUMERAL = "2;220;50;47";
  645. COLOR_ERROR_FG = "5;15";
  646. COLOR_ERROR_BG = "5;196";
  647. COLOR_SEARCH_FG = "5;234";
  648. COLOR_SEARCH_BG = "5;226";
  649. COLOR_SELECTFG = "2;0;43;54";
  650. COLOR_SELECTBG = "2;147;161;161";
  651. COLOR_RED = "2;222;53;53";
  652. COLOR_GREEN = "2;55;167;0";
  653. COLOR_BOLD = "2;147;161;161;1";
  654. COLOR_LINK = "2;42;161;152;4";
  655. COLOR_ESCAPE = "2;133;153;0";
  656. current_theme = "solarized-dark";
  657. }
  658. void load_colorscheme_sunsmoke256(void) {
  659. if (!global_config.can_256color) return;
  660. COLOR_FG = "5;188";
  661. COLOR_BG = "5;234";
  662. COLOR_ALT_FG = "5;244";
  663. COLOR_ALT_BG = "5;236";
  664. COLOR_NUMBER_FG = "5;101";
  665. COLOR_NUMBER_BG = "5;232";
  666. COLOR_STATUS_FG = "5;188";
  667. COLOR_STATUS_BG = "5;59";
  668. COLOR_TABBAR_BG = "5;59";
  669. COLOR_TAB_BG = "5;59";
  670. COLOR_KEYWORD = "5;74";
  671. COLOR_STRING = "5;71";
  672. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  673. COLOR_TYPE = "5;221";
  674. COLOR_PRAGMA = "5;160";
  675. COLOR_NUMERAL = "5;161";
  676. COLOR_ERROR_FG = "5;15";
  677. COLOR_ERROR_BG = "5;196";
  678. COLOR_SEARCH_FG = "5;234";
  679. COLOR_SEARCH_BG = "5;226";
  680. COLOR_SELECTFG = "5;17";
  681. COLOR_SELECTBG = "5;109";
  682. COLOR_RED = "@1";
  683. COLOR_GREEN = "@2";
  684. COLOR_BOLD = "5;188;1";
  685. COLOR_LINK = "5;74;4";
  686. COLOR_ESCAPE = "5;79";
  687. current_theme = "sunsmoke256";
  688. }
  689. /* Custom theme */
  690. void load_colorscheme_sunsmoke(void) {
  691. if (!global_config.can_24bit) {
  692. load_colorscheme_sunsmoke256();
  693. return;
  694. }
  695. COLOR_FG = "2;230;230;230";
  696. COLOR_BG = "2;31;31;31";
  697. COLOR_ALT_FG = "2;122;122;122";
  698. COLOR_ALT_BG = "2;46;43;46";
  699. COLOR_NUMBER_FG = "2;150;139;57";
  700. COLOR_NUMBER_BG = "2;0;0;0";
  701. COLOR_STATUS_FG = "2;230;230;230";
  702. COLOR_STATUS_BG = "2;71;64;58";
  703. COLOR_TABBAR_BG = "2;71;64;58";
  704. COLOR_TAB_BG = "2;71;64;58";
  705. COLOR_KEYWORD = "2;51;162;230";
  706. COLOR_STRING = "2;72;176;72";
  707. COLOR_COMMENT = "2;158;153;129;3";
  708. COLOR_TYPE = "2;230;206;110";
  709. COLOR_PRAGMA = "2;194;70;54";
  710. COLOR_NUMERAL = "2;230;43;127";
  711. COLOR_ERROR_FG = "5;15";
  712. COLOR_ERROR_BG = "5;196";
  713. COLOR_SEARCH_FG = "5;234";
  714. COLOR_SEARCH_BG = "5;226";
  715. COLOR_SELECTFG = "2;0;43;54";
  716. COLOR_SELECTBG = "2;147;161;161";
  717. COLOR_RED = "2;222;53;53";
  718. COLOR_GREEN = "2;55;167;0";
  719. COLOR_BOLD = "2;230;230;230;1";
  720. COLOR_LINK = "2;51;162;230;4";
  721. COLOR_ESCAPE = "2;113;203;173";
  722. current_theme = "sunsmoke";
  723. }
  724. struct theme_def {
  725. const char * name;
  726. void (*load)(void);
  727. } themes[] = {
  728. {"wombat", load_colorscheme_wombat},
  729. {"citylights", load_colorscheme_citylights},
  730. {"solarized-dark", load_colorscheme_solarized_dark},
  731. {"ansi", load_colorscheme_ansi},
  732. {"sunsmoke", load_colorscheme_sunsmoke},
  733. {"sunsmoke256", load_colorscheme_sunsmoke256},
  734. {NULL, NULL}
  735. };
  736. struct syntax_state {
  737. line_t * line;
  738. int line_no;
  739. int state;
  740. int i;
  741. };
  742. #define paint(length, flag) do { for (int i = 0; i < (length) && state->i < state->line->actual; i++, state->i++) { state->line->text[state->i].flags = (flag); } } while (0)
  743. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  744. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  745. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  746. #define skip() (state->i++)
  747. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  748. /**
  749. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  750. * Returns 1 if a keyword from the last was found, otherwise 0.
  751. */
  752. static int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  753. if (keyword_qualifier(lastchar())) return 0;
  754. if (!keyword_qualifier(charat())) return 0;
  755. for (char ** keyword = keywords; *keyword; ++keyword) {
  756. int d = 0;
  757. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  758. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  759. paint((int)strlen(*keyword), flag);
  760. return 1;
  761. }
  762. }
  763. return 0;
  764. }
  765. /**
  766. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  767. * so it can be used for prefix checking for things that need further special handling.
  768. */
  769. static int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  770. if (keyword_qualifier(lastchar())) return 0;
  771. if (!keyword_qualifier(charat())) return 0;
  772. int i = state->i;
  773. int slen = 0;
  774. while (i < state->line->actual || *keyword == '\0') {
  775. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  776. for (int j = 0; j < slen; ++j) {
  777. paint(1, flag);
  778. }
  779. return 1;
  780. }
  781. if (*keyword != state->line->text[i].codepoint) return 0;
  782. i++;
  783. keyword++;
  784. slen++;
  785. }
  786. return 0;
  787. }
  788. /**
  789. * Syntax definition for C
  790. */
  791. static char * syn_c_keywords[] = {
  792. "while","if","for","continue","return","break","switch","case","sizeof",
  793. "struct","union","typedef","do","default","else","goto",
  794. "alignas","alignof","offsetof","asm","__asm__",
  795. /* C++ stuff */
  796. "public","private","class","using","namespace","virtual","override","protected",
  797. "template","typename","static_cast","throw",
  798. NULL
  799. };
  800. static char * syn_c_types[] = {
  801. "static","int","char","short","float","double","void","unsigned","volatile","const",
  802. "register","long","inline","restrict","enum","auto","extern","bool","complex",
  803. "uint8_t","uint16_t","uint32_t","uint64_t",
  804. "int8_t","int16_t","int32_t","int64_t","FILE",
  805. "ssize_t","size_t","uintptr_t","intptr_t","__volatile__",
  806. "constexpr",
  807. NULL
  808. };
  809. static char * syn_c_special[] = {
  810. "NULL",
  811. "stdin","stdout","stderr",
  812. "STDIN_FILENO","STDOUT_FILENO","STDERR_FILENO",
  813. NULL
  814. };
  815. static int c_keyword_qualifier(int c) {
  816. return isalnum(c) || (c == '_');
  817. }
  818. /**
  819. * Paints a basic C-style quoted string.
  820. */
  821. static void paint_c_string(struct syntax_state * state) {
  822. /* Assumes you came in from a check of charat() == '"' */
  823. paint(1, FLAG_STRING);
  824. int last = -1;
  825. while (charat() != -1) {
  826. if (last != '\\' && charat() == '"') {
  827. paint(1, FLAG_STRING);
  828. return;
  829. } else if (charat() == '\\' && (nextchar() == '\\' || nextchar() == 'n' || nextchar() == 'r')) {
  830. paint(2, FLAG_ESCAPE);
  831. last = -1;
  832. } else if (charat() == '\\' && nextchar() >= '0' && nextchar() <= '7') {
  833. paint(2, FLAG_ESCAPE);
  834. if (charat() >= '0' && charat() <= '7') {
  835. paint(1, FLAG_ESCAPE);
  836. if (charat() >= '0' && charat() <= '7') {
  837. paint(1, FLAG_ESCAPE);
  838. }
  839. }
  840. last = -1;
  841. } else if (charat() == '\\' && nextchar() == 'x') {
  842. paint(2, FLAG_ESCAPE);
  843. while (isxdigit(charat())) paint(1, FLAG_ESCAPE);
  844. } else {
  845. last = charat();
  846. paint(1, FLAG_STRING);
  847. }
  848. }
  849. }
  850. static void paint_simple_string(struct syntax_state * state) {
  851. /* Assumes you came in from a check of charat() == '"' */
  852. paint(1, FLAG_STRING);
  853. int last = -1;
  854. while (charat() != -1) {
  855. if (last != '\\' && charat() == '"') {
  856. paint(1, FLAG_STRING);
  857. return;
  858. } else if (last == '\\' && charat() == '\\') {
  859. paint(1, FLAG_STRING);
  860. last = -1;
  861. } else {
  862. last = charat();
  863. paint(1, FLAG_STRING);
  864. }
  865. }
  866. }
  867. /**
  868. * Paint a C character numeral. Can be arbitrarily large, so
  869. * it supports multibyte chars for things like defining weird
  870. * ASCII multibyte integer constants.
  871. */
  872. static void paint_c_char(struct syntax_state * state) {
  873. /* Assumes you came in from a check of charat() == '\'' */
  874. paint(1, FLAG_NUMERAL);
  875. int last = -1;
  876. while (charat() != -1) {
  877. if (last != '\\' && charat() == '\'') {
  878. paint(1, FLAG_NUMERAL);
  879. return;
  880. } else if (last == '\\' && charat() == '\\') {
  881. paint(1, FLAG_NUMERAL);
  882. last = -1;
  883. } else {
  884. last = charat();
  885. paint(1, FLAG_NUMERAL);
  886. }
  887. }
  888. }
  889. /**
  890. * Paint a generic C pragma, eg. a #define statement.
  891. */
  892. static int paint_c_pragma(struct syntax_state * state) {
  893. while (state->i < state->line->actual) {
  894. if (charat() == '"') {
  895. /* Paint C string */
  896. paint_c_string(state);
  897. } else if (charat() == '\'') {
  898. paint_c_char(state);
  899. } else if (charat() == '\\' && state->i == state->line->actual - 1) {
  900. paint(1, FLAG_PRAGMA);
  901. return 2;
  902. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  903. continue;
  904. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  905. continue;
  906. } else {
  907. paint(1, FLAG_PRAGMA);
  908. }
  909. }
  910. return 0;
  911. }
  912. /**
  913. * Paint a comment until end of line, assumes this comment can not continue.
  914. * (Some languages have comments that can continue with a \ - don't use this!)
  915. * Assumes you've already painted your comment start characters.
  916. */
  917. static int paint_comment(struct syntax_state * state) {
  918. while (charat() != -1) {
  919. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  920. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  921. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  922. else { paint(1, FLAG_COMMENT); }
  923. }
  924. return -1;
  925. }
  926. /**
  927. * Paint a classic C comment which continues until terminated.
  928. * Assumes you've already painted the starting / and *.
  929. */
  930. static int paint_c_comment(struct syntax_state * state) {
  931. int last = -1;
  932. while (charat() != -1) {
  933. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  934. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  935. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  936. else if (last == '*' && charat() == '/') {
  937. paint(1, FLAG_COMMENT);
  938. return 0;
  939. } else {
  940. last = charat();
  941. paint(1, FLAG_COMMENT);
  942. }
  943. }
  944. return 1;
  945. }
  946. /**
  947. * Paint integers and floating point values with some handling for suffixes.
  948. */
  949. static int paint_c_numeral(struct syntax_state * state) {
  950. if (charat() == '0' && (nextchar() == 'x' || nextchar() == 'X')) {
  951. paint(2, FLAG_NUMERAL);
  952. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  953. } else if (charat() == '0' && nextchar() == '.') {
  954. paint(2, FLAG_NUMERAL);
  955. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  956. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  957. return 0;
  958. } else if (charat() == '0') {
  959. paint(1, FLAG_NUMERAL);
  960. while (charat() >= '0' && charat() <= '7') paint(1, FLAG_NUMERAL);
  961. } else {
  962. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  963. if (charat() == '.') {
  964. paint(1, FLAG_NUMERAL);
  965. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  966. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  967. return 0;
  968. }
  969. }
  970. while (charat() == 'u' || charat() == 'U' || charat() == 'l' || charat() == 'L') paint(1, FLAG_NUMERAL);
  971. return 0;
  972. }
  973. static int syn_c_calculate(struct syntax_state * state) {
  974. switch (state->state) {
  975. case -1:
  976. case 0:
  977. if (charat() == '#') {
  978. /* Must be first thing on line, but can have spaces before */
  979. for (int i = 0; i < state->i; ++i) {
  980. if (state->line->text[i].codepoint != ' ' && state->line->text[i].codepoint != '\t') {
  981. skip();
  982. return 0;
  983. }
  984. }
  985. /* Handle preprocessor functions */
  986. paint(1, FLAG_PRAGMA);
  987. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  988. if (match_and_paint(state, "include", FLAG_PRAGMA, c_keyword_qualifier)) {
  989. /* Put quotes around <includes> */
  990. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  991. if (charat() == '<') {
  992. paint(1, FLAG_STRING);
  993. while (charat() != '>' && state->i < state->line->actual) {
  994. paint(1, FLAG_STRING);
  995. }
  996. if (charat() != -1) {
  997. paint(1, FLAG_STRING);
  998. }
  999. }
  1000. /* (for "includes", normal pragma highlighting covers that. */
  1001. } else if (match_and_paint(state, "if", FLAG_PRAGMA, c_keyword_qualifier)) {
  1002. /* These are to prevent #if and #else from being highlighted as keywords */
  1003. } else if (match_and_paint(state, "else", FLAG_PRAGMA, c_keyword_qualifier)) {
  1004. /* ... */
  1005. }
  1006. return paint_c_pragma(state);
  1007. } else if (charat() == '/' && nextchar() == '/') {
  1008. /* C++-style comments */
  1009. paint_comment(state);
  1010. } else if (charat() == '/' && nextchar() == '*') {
  1011. /* C-style comments */
  1012. if (paint_c_comment(state) == 1) return 1;
  1013. return 0;
  1014. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1015. return 0;
  1016. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  1017. return 0;
  1018. } else if (find_keywords(state, syn_c_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1019. return 0;
  1020. } else if (charat() == '\"') {
  1021. paint_c_string(state);
  1022. return 0;
  1023. } else if (charat() == '\'') {
  1024. paint_c_char(state);
  1025. return 0;
  1026. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1027. paint_c_numeral(state);
  1028. return 0;
  1029. } else if (charat() != -1) {
  1030. skip();
  1031. return 0;
  1032. }
  1033. break;
  1034. case 1:
  1035. /* In a block comment */
  1036. if (paint_c_comment(state) == 1) return 1;
  1037. return 0;
  1038. case 2:
  1039. /* In an unclosed preprocessor statement */
  1040. return paint_c_pragma(state);
  1041. }
  1042. return -1;
  1043. }
  1044. static char * c_ext[] = {".c",".h",".cpp",".hpp",".c++",".h++",".cc",".hh",NULL};
  1045. static char * syn_py_keywords[] = {
  1046. "class","def","return","del","if","else","elif","for","while","continue",
  1047. "break","assert","as","and","or","except","finally","from","global",
  1048. "import","in","is","lambda","with","nonlocal","not","pass","raise","try","yield",
  1049. NULL
  1050. };
  1051. static char * syn_py_types[] = {
  1052. "object","set","dict","int","str","bytes",
  1053. NULL
  1054. };
  1055. static char * syn_py_special[] = {
  1056. "True","False","None",
  1057. NULL
  1058. };
  1059. static int paint_py_triple_double(struct syntax_state * state) {
  1060. while (charat() != -1) {
  1061. if (charat() == '"') {
  1062. paint(1, FLAG_STRING);
  1063. if (charat() == '"' && nextchar() == '"') {
  1064. paint(2, FLAG_STRING);
  1065. return 0;
  1066. }
  1067. } else {
  1068. paint(1, FLAG_STRING);
  1069. }
  1070. }
  1071. return 1; /* continues */
  1072. }
  1073. static int paint_py_triple_single(struct syntax_state * state) {
  1074. while (charat() != -1) {
  1075. if (charat() == '\'') {
  1076. paint(1, FLAG_STRING);
  1077. if (charat() == '\'' && nextchar() == '\'') {
  1078. paint(2, FLAG_STRING);
  1079. return 0;
  1080. }
  1081. } else {
  1082. paint(1, FLAG_STRING);
  1083. }
  1084. }
  1085. return 2; /* continues */
  1086. }
  1087. static int paint_py_single_string(struct syntax_state * state) {
  1088. paint(1, FLAG_STRING);
  1089. int last = -1;
  1090. while (charat() != -1) {
  1091. if (last != '\\' && charat() == '\'') {
  1092. paint(1, FLAG_STRING);
  1093. return 0;
  1094. } else if (last == '\\' && charat() == '\\') {
  1095. paint(1, FLAG_STRING);
  1096. last = -1;
  1097. /* TODO check for \0, \r, \n, \0xxx, etc. */
  1098. } else {
  1099. last = charat();
  1100. paint(1, FLAG_STRING);
  1101. }
  1102. }
  1103. return 0;
  1104. }
  1105. static int paint_py_numeral(struct syntax_state * state) {
  1106. if (charat() == '0' && (nextchar() == 'x' || nextchar() == 'X')) {
  1107. paint(2, FLAG_NUMERAL);
  1108. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  1109. } else if (charat() == '0' && nextchar() == '.') {
  1110. paint(2, FLAG_NUMERAL);
  1111. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1112. if ((charat() == '+' || charat() == '-') && (nextchar() == 'e' || nextchar() == 'E')) {
  1113. paint(2, FLAG_NUMERAL);
  1114. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1115. } else if (charat() == 'e' || charat() == 'E') {
  1116. paint(1, FLAG_NUMERAL);
  1117. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1118. }
  1119. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1120. return 0;
  1121. } else {
  1122. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1123. if (charat() == '.') {
  1124. paint(1, FLAG_NUMERAL);
  1125. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1126. if ((charat() == '+' || charat() == '-') && (nextchar() == 'e' || nextchar() == 'E')) {
  1127. paint(2, FLAG_NUMERAL);
  1128. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1129. } else if (charat() == 'e' || charat() == 'E') {
  1130. paint(1, FLAG_NUMERAL);
  1131. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1132. }
  1133. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1134. return 0;
  1135. }
  1136. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1137. }
  1138. while (charat() == 'l' || charat() == 'L') paint(1, FLAG_NUMERAL);
  1139. return 0;
  1140. }
  1141. static int syn_py_calculate(struct syntax_state * state) {
  1142. switch (state->state) {
  1143. case -1:
  1144. case 0:
  1145. if (charat() == '#') {
  1146. paint_comment(state);
  1147. } else if (state->i == 0 && match_and_paint(state, "import", FLAG_PRAGMA, c_keyword_qualifier)) {
  1148. return 0;
  1149. } else if (charat() == '@') {
  1150. paint(1, FLAG_PRAGMA);
  1151. while (c_keyword_qualifier(charat())) paint(1, FLAG_PRAGMA);
  1152. return 0;
  1153. } else if (charat() == '"') {
  1154. if (nextchar() == '"' && charrel(2) == '"') {
  1155. paint(3, FLAG_STRING);
  1156. return paint_py_triple_double(state);
  1157. } else {
  1158. paint_simple_string(state);
  1159. return 0;
  1160. }
  1161. } else if (find_keywords(state, syn_py_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1162. return 0;
  1163. } else if (find_keywords(state, syn_py_types, FLAG_TYPE, c_keyword_qualifier)) {
  1164. return 0;
  1165. } else if (find_keywords(state, syn_py_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1166. return 0;
  1167. } else if (charat() == '\'') {
  1168. if (nextchar() == '\'' && charrel(2) == '\'') {
  1169. paint(3, FLAG_STRING);
  1170. return paint_py_triple_single(state);
  1171. } else {
  1172. paint_py_single_string(state);
  1173. return 0;
  1174. }
  1175. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1176. paint_py_numeral(state);
  1177. return 0;
  1178. } else if (charat() != -1) {
  1179. skip();
  1180. return 0;
  1181. }
  1182. break;
  1183. case 1: /* multiline """ string */
  1184. return paint_py_triple_double(state);
  1185. case 2: /* multiline ''' string */
  1186. return paint_py_triple_single(state);
  1187. }
  1188. return -1;
  1189. }
  1190. static char * py_ext[] = {".py",NULL};
  1191. static char * syn_java_keywords[] = {
  1192. "assert","break","case","catch","class","continue",
  1193. "default","do","else","enum","exports","extends","finally",
  1194. "for","if","implements","instanceof","interface","module","native",
  1195. "new","requires","return","throws",
  1196. "strictfp","super","switch","synchronized","this","throw","try","while",
  1197. NULL
  1198. };
  1199. static char * syn_java_types[] = {
  1200. "var","boolean","void","short","long","int","double","float","enum","char",
  1201. "private","protected","public","static","final","transient","volatile","abstract",
  1202. NULL
  1203. };
  1204. static char * syn_java_special[] = {
  1205. "true","false","import","package","null",
  1206. NULL
  1207. };
  1208. static char * syn_java_at_comments[] = {
  1209. "@author","@see","@since","@param","@return","@throws",
  1210. "@version","@exception","@deprecated",
  1211. NULL
  1212. };
  1213. static int at_keyword_qualifier(int c) {
  1214. return isalnum(c) || (c == '_') || (c == '@');
  1215. }
  1216. static char * syn_java_brace_comments[] = {
  1217. "{@docRoot","{@inheritDoc","{@link","{@linkplain",
  1218. "{@value","{@code","{@literal","{@serial",
  1219. "{@serialData","{@serialField",
  1220. NULL
  1221. };
  1222. static int brace_keyword_qualifier(int c) {
  1223. return isalnum(c) || (c == '{') || (c == '@');
  1224. }
  1225. static int paint_java_comment(struct syntax_state * state) {
  1226. int last = -1;
  1227. while (charat() != -1) {
  1228. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1229. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1230. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1231. else if (charat() == '@') {
  1232. if (!find_keywords(state, syn_java_at_comments, FLAG_ESCAPE, at_keyword_qualifier)) {
  1233. /* Paint the @ */
  1234. paint(1, FLAG_COMMENT);
  1235. }
  1236. } else if (charat() == '{') {
  1237. /* see if this terminates */
  1238. if (find_keywords(state, syn_java_brace_comments, FLAG_ESCAPE, brace_keyword_qualifier)) {
  1239. while (charat() != '}' && charat() != -1) {
  1240. paint(1, FLAG_ESCAPE);
  1241. }
  1242. if (charat() == '}') paint(1, FLAG_ESCAPE);
  1243. } else {
  1244. paint(1, FLAG_COMMENT);
  1245. }
  1246. } else if (charat() == '<') {
  1247. int is_tag = 0;
  1248. for (int i = 1; charrel(i) != -1; ++i) {
  1249. if (charrel(i) == '>') {
  1250. is_tag = 1;
  1251. break;
  1252. }
  1253. if (!isalnum(charrel(i)) && charrel(i) != '/') {
  1254. is_tag = 0;
  1255. break;
  1256. }
  1257. }
  1258. if (is_tag) {
  1259. paint(1, FLAG_TYPE);
  1260. while (charat() != -1 && charat() != '>') {
  1261. if (charat() == '/') paint(1, FLAG_TYPE);
  1262. else paint(1, FLAG_KEYWORD);
  1263. }
  1264. if (charat() == '>') paint(1, FLAG_TYPE);
  1265. } else {
  1266. /* Paint the < */
  1267. paint(1, FLAG_COMMENT);
  1268. }
  1269. } else if (last == '*' && charat() == '/') {
  1270. paint(1, FLAG_COMMENT);
  1271. return 0;
  1272. } else {
  1273. last = charat();
  1274. paint(1, FLAG_COMMENT);
  1275. }
  1276. }
  1277. return 1;
  1278. }
  1279. static int syn_java_calculate(struct syntax_state * state) {
  1280. switch (state->state) {
  1281. case -1:
  1282. case 0:
  1283. if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1284. paint_c_numeral(state);
  1285. return 0;
  1286. } else if (charat() == '/' && nextchar() == '/') {
  1287. /* C++-style comments */
  1288. paint_comment(state);
  1289. } else if (charat() == '/' && nextchar() == '*') {
  1290. /* C-style comments; TODO: Needs special stuff for @author; <html>; etc. */
  1291. if (paint_java_comment(state) == 1) return 1;
  1292. } else if (find_keywords(state, syn_java_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1293. return 0;
  1294. } else if (find_keywords(state, syn_java_types, FLAG_TYPE, c_keyword_qualifier)) {
  1295. return 0;
  1296. } else if (find_keywords(state, syn_java_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1297. return 0;
  1298. } else if (charat() == '\"') {
  1299. paint_simple_string(state);
  1300. return 0;
  1301. } else if (charat() == '\'') {
  1302. paint_c_char(state);
  1303. return 0;
  1304. } else if (charat() == '@') {
  1305. paint(1, FLAG_PRAGMA);
  1306. while (c_keyword_qualifier(charat())) paint(1, FLAG_PRAGMA);
  1307. } else if (charat() != -1) {
  1308. skip();
  1309. return 0;
  1310. }
  1311. break;
  1312. case 1:
  1313. if (paint_java_comment(state) == 1) return 1;
  1314. return 0;
  1315. }
  1316. return -1;
  1317. }
  1318. static char * java_ext[] = {".java",NULL};
  1319. static int syn_diff_calculate(struct syntax_state * state) {
  1320. /* No states to worry about */
  1321. if (state->i == 0) {
  1322. int flag = 0;
  1323. if (charat() == '+') {
  1324. flag = FLAG_DIFFPLUS;
  1325. } else if (charat() == '-') {
  1326. flag = FLAG_DIFFMINUS;
  1327. } else if (charat() == '@') {
  1328. flag = FLAG_TYPE;
  1329. } else if (charat() != ' ') {
  1330. flag = FLAG_KEYWORD;
  1331. } else {
  1332. return -1;
  1333. }
  1334. while (charat() != -1) paint(1, flag);
  1335. }
  1336. return -1;
  1337. }
  1338. static char * diff_ext[] = {".patch",".diff",NULL};
  1339. static int syn_conf_calculate(struct syntax_state * state) {
  1340. if (state->i == 0) {
  1341. if (charat() == ';') {
  1342. while (charat() != -1) paint(1, FLAG_COMMENT);
  1343. } else if (charat() == '#') {
  1344. while (charat() != -1) paint(1, FLAG_COMMENT);
  1345. } else if (charat() == '[') {
  1346. paint(1, FLAG_KEYWORD);
  1347. while (charat() != ']' && charat() != -1) paint(1, FLAG_KEYWORD);
  1348. if (charat() == ']') paint(1, FLAG_KEYWORD);
  1349. } else {
  1350. while (charat() != '=' && charat() != -1) paint(1, FLAG_TYPE);
  1351. }
  1352. }
  1353. return -1;
  1354. }
  1355. static char * conf_ext[] = {".conf",".ini",".git/config",NULL};
  1356. static char * syn_rust_keywords[] = {
  1357. "as","break","const","continue","crate","else","enum","extern",
  1358. "false","fn","for","if","impl","in","let","loop","match","mod",
  1359. "move","mut","pub","ref","return","Self","self","static","struct",
  1360. "super","trait","true","type","unsafe","use","where","while",
  1361. NULL,
  1362. };
  1363. static char * syn_rust_types[] = {
  1364. "bool","char","str",
  1365. "i8","i16","i32","i64",
  1366. "u8","u16","u32","u64",
  1367. "isize","usize",
  1368. "f32","f64",
  1369. NULL,
  1370. };
  1371. static int paint_rs_comment(struct syntax_state * state) {
  1372. while (charat() != -1) {
  1373. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1374. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1375. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1376. else if (charat() == '*' && nextchar() == '/') {
  1377. paint(2, FLAG_COMMENT);
  1378. state->state--;
  1379. if (state->state == 0) return 0;
  1380. } else if (charat() == '/' && nextchar() == '*') {
  1381. state->state++;
  1382. paint(2, FLAG_COMMENT);
  1383. } else {
  1384. paint(1, FLAG_COMMENT);
  1385. }
  1386. }
  1387. return state->state;
  1388. }
  1389. static int paint_rust_numeral(struct syntax_state * state) {
  1390. if (charat() == '0' && nextchar() == 'b') {
  1391. paint(2, FLAG_NUMERAL);
  1392. while (charat() == '0' || charat() == '1' || charat() == '_') paint(1, FLAG_NUMERAL);
  1393. } else if (charat() == '0' && nextchar() == 'o') {
  1394. paint(2, FLAG_NUMERAL);
  1395. while ((charat() >= '0' && charat() <= '7') || charat() == '_') paint(1, FLAG_NUMERAL);
  1396. } else if (charat() == '0' && nextchar() == 'x') {
  1397. paint(2, FLAG_NUMERAL);
  1398. while (isxdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1399. } else if (charat() == '0' && nextchar() == '.') {
  1400. paint(2, FLAG_NUMERAL);
  1401. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1402. } else {
  1403. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1404. if (charat() == '.') {
  1405. paint(1, FLAG_NUMERAL);
  1406. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1407. }
  1408. }
  1409. return 0;
  1410. }
  1411. static int syn_rust_calculate(struct syntax_state * state) {
  1412. switch (state->state) {
  1413. case -1:
  1414. case 0:
  1415. if (charat() == '/' && nextchar() == '/') {
  1416. /* C++-style comments */
  1417. paint_comment(state);
  1418. } else if (charat() == '/' && nextchar() == '*') {
  1419. paint(2, FLAG_COMMENT);
  1420. state->state = 1;
  1421. return paint_rs_comment(state);
  1422. } else if (find_keywords(state, syn_rust_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1423. return 0;
  1424. } else if (find_keywords(state, syn_rust_types, FLAG_TYPE, c_keyword_qualifier)) {
  1425. return 0;
  1426. } else if (charat() == '\"') {
  1427. paint_simple_string(state);
  1428. return 0;
  1429. } else if (charat() == '\'') {
  1430. paint_c_char(state);
  1431. return 0;
  1432. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1433. paint_rust_numeral(state);
  1434. return 0;
  1435. } else if (charat() != -1) {
  1436. skip();
  1437. return 0;
  1438. }
  1439. break;
  1440. default: /* Nested comments */
  1441. return paint_rs_comment(state);
  1442. }
  1443. return -1;
  1444. }
  1445. static char * rust_ext[] = {".rs",NULL};
  1446. static char * syn_bimrc_keywords[] = {
  1447. "history","padding","hlparen","hlcurrent","splitpercent",
  1448. "shiftscrolling","scrollamount","git","colorgutter",
  1449. NULL
  1450. };
  1451. static int syn_bimrc_calculate(struct syntax_state * state) {
  1452. /* No states */
  1453. if (state->i == 0) {
  1454. if (charat() == '#') {
  1455. while (charat() != -1) paint(1, FLAG_COMMENT);
  1456. } else if (match_and_paint(state, "theme", FLAG_KEYWORD, c_keyword_qualifier)) {
  1457. if (charat() == '=') {
  1458. skip();
  1459. for (struct theme_def * s = themes; s->name; ++s) {
  1460. if (match_and_paint(state, s->name, FLAG_TYPE, c_keyword_qualifier)) break;
  1461. }
  1462. }
  1463. } else if (find_keywords(state, syn_bimrc_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1464. return -1;
  1465. }
  1466. }
  1467. return -1;
  1468. }
  1469. static char * bimrc_ext[] = {".bimrc",NULL};
  1470. static int syn_gitcommit_calculate(struct syntax_state * state) {
  1471. if (state->i == 0 && charat() == '#') {
  1472. while (charat() != -1) paint(1, FLAG_COMMENT);
  1473. } else if (state->line_no == 0) {
  1474. /* First line is special */
  1475. while (charat() != -1 && state->i < 50) paint(1, FLAG_KEYWORD);
  1476. while (charat() != -1) paint(1, FLAG_DIFFMINUS);
  1477. } else if (state->line_no == 1) {
  1478. /* No text on second line */
  1479. while (charat() != -1) paint(1, FLAG_DIFFMINUS);
  1480. } else if (charat() != -1) {
  1481. skip();
  1482. return 0;
  1483. }
  1484. return -1;
  1485. }
  1486. static char * gitcommit_ext[] = {"COMMIT_EDITMSG", NULL};
  1487. static char * syn_gitrebase_commands[] = {
  1488. "p","r","e","s","f","x","d",
  1489. "pick","reword","edit","squash","fixup",
  1490. "exec","drop",
  1491. NULL
  1492. };
  1493. static int syn_gitrebase_calculate(struct syntax_state * state) {
  1494. if (state->i == 0 && charat() == '#') {
  1495. while (charat() != -1) paint(1, FLAG_COMMENT);
  1496. } else if (state->i == 0 && find_keywords(state, syn_gitrebase_commands, FLAG_KEYWORD, c_keyword_qualifier)) {
  1497. while (charat() == ' ') skip();
  1498. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  1499. return -1;
  1500. }
  1501. return -1;
  1502. }
  1503. static char * gitrebase_ext[] = {"git-rebase-todo",NULL};
  1504. static int make_command_qualifier(int c) {
  1505. return isalnum(c) || c == '_' || c == '-' || c == '.';
  1506. }
  1507. static char * syn_make_commands[] = {
  1508. "define","endef","undefine","ifdef","ifndef","ifeq","ifneq","else","endif",
  1509. "include","sinclude","override","export","unexport","private","vpath",
  1510. "-include",
  1511. NULL
  1512. };
  1513. static char * syn_make_functions[] = {
  1514. "subst","patsubst","findstring","filter","filter-out",
  1515. "sort","word","words","wordlist","firstword","lastword",
  1516. "dir","notdir","suffix","basename","addsuffix","addprefix",
  1517. "join","wildcard","realpath","abspath","error","warning",
  1518. "shell","origin","flavor","foreach","if","or","and",
  1519. "call","eval","file","value",
  1520. NULL
  1521. };
  1522. static char * syn_make_special_targets[] = {
  1523. "all", /* Not really special, but highlight it 'cause I feel like it. */
  1524. ".PHONY", ".SUFFIXES", ".DEFAULT", ".PRECIOUS", ".INTERMEDIATE",
  1525. ".SECONDARY", ".SECONDEXPANSION", ".DELETE_ON_ERROR", ".IGNORE",
  1526. ".LOW_RESOLUTION_TIME", ".SILENT", ".EXPORT_ALL_VARIABLES",
  1527. ".NOTPARALLEL", ".ONESHELL", ".POSIX",
  1528. NULL
  1529. };
  1530. static int make_close_paren(struct syntax_state * state) {
  1531. paint(2, FLAG_TYPE);
  1532. find_keywords(state, syn_make_functions, FLAG_KEYWORD, c_keyword_qualifier);
  1533. int i = 1;
  1534. while (charat() != -1) {
  1535. if (charat() == '(') {
  1536. i++;
  1537. } else if (charat() == ')') {
  1538. i--;
  1539. if (i == 0) {
  1540. paint(1,FLAG_TYPE);
  1541. return 0;
  1542. }
  1543. } else if (charat() == '"') {
  1544. paint_simple_string(state);
  1545. }
  1546. paint(1,FLAG_TYPE);
  1547. }
  1548. return 0;
  1549. }
  1550. static int make_close_brace(struct syntax_state * state) {
  1551. paint(2, FLAG_TYPE);
  1552. while (charat() != -1) {
  1553. if (charat() == '}') {
  1554. paint(1, FLAG_TYPE);
  1555. return 0;
  1556. }
  1557. paint(1, FLAG_TYPE);
  1558. }
  1559. return 0;
  1560. }
  1561. static int make_variable_or_comment(struct syntax_state * state, int flag) {
  1562. while (charat() != -1) {
  1563. if (charat() == '$') {
  1564. switch (nextchar()) {
  1565. case '(':
  1566. make_close_paren(state);
  1567. break;
  1568. case '{':
  1569. make_close_brace(state);
  1570. break;
  1571. default:
  1572. paint(2, FLAG_TYPE);
  1573. break;
  1574. }
  1575. } else if (charat() == '#') {
  1576. while (charat() != -1) paint(1, FLAG_COMMENT);
  1577. } else {
  1578. paint(1, flag);
  1579. }
  1580. }
  1581. return 0;
  1582. }
  1583. static int syn_make_calculate(struct syntax_state * state) {
  1584. if (state->i == 0 && charat() == '\t') {
  1585. make_variable_or_comment(state, FLAG_NUMERAL);
  1586. } else {
  1587. while (charat() == ' ') { skip(); }
  1588. /* Peek forward to see if this is a rule or a variable */
  1589. int whatisit = 0;
  1590. for (int i = 0; charrel(i) != -1; ++i) {
  1591. if (charrel(i) == ':' && charrel(i+1) != '=') {
  1592. whatisit = 1;
  1593. break;
  1594. } else if (charrel(i) == '=') {
  1595. whatisit = 2;
  1596. break;
  1597. } else if (charrel(i) == '#') {
  1598. break;
  1599. }
  1600. }
  1601. if (!whatisit) {
  1602. /* Check for functions */
  1603. while (charat() != -1) {
  1604. if (charat() == '#') {
  1605. while (charat() != -1) paint(1, FLAG_COMMENT);
  1606. } else if (find_keywords(state, syn_make_commands, FLAG_KEYWORD, make_command_qualifier)) {
  1607. continue;
  1608. } else if (charat() == '$') {
  1609. make_variable_or_comment(state, FLAG_NONE);
  1610. } else {
  1611. skip();
  1612. }
  1613. }
  1614. } else if (whatisit == 1) {
  1615. /* It's a rule */
  1616. while (charat() != -1) {
  1617. if (charat() == '#') {
  1618. while (charat() != -1) paint(1, FLAG_COMMENT);
  1619. } else if (charat() == ':') {
  1620. paint(1, FLAG_TYPE);
  1621. make_variable_or_comment(state, FLAG_NONE);
  1622. } else if (find_keywords(state, syn_make_special_targets, FLAG_KEYWORD, make_command_qualifier)) {
  1623. continue;
  1624. } else {
  1625. paint(1, FLAG_TYPE);
  1626. }
  1627. }
  1628. } else if (whatisit == 2) {
  1629. /* It's a variable definition */
  1630. match_and_paint(state, "export", FLAG_KEYWORD, c_keyword_qualifier);
  1631. while (charat() != -1 && charat() != '+' && charat() != '=' && charat() != ':' && charat() != '?') {
  1632. paint(1, FLAG_TYPE);
  1633. }
  1634. while (charat() != -1 && charat() != '=') skip();
  1635. /* Highlight variable expansions */
  1636. make_variable_or_comment(state, FLAG_NONE);
  1637. }
  1638. }
  1639. return -1;
  1640. }
  1641. static char * make_ext[] = {"Makefile","makefile","GNUmakefile",".mak",NULL};
  1642. #define nest(lang, low) \
  1643. do { \
  1644. state->state = (state->state < 1 ? 0 : state->state - low); \
  1645. do { state->state = lang(state); } while (state->state == 0); \
  1646. if (state->state == -1) return low; \
  1647. return state->state + low; \
  1648. } while (0)
  1649. static int match_forward(struct syntax_state * state, char * c) {
  1650. int i = 0;
  1651. while (1) {
  1652. if (charrel(i) == -1 && !*c) return 1;
  1653. if (charrel(i) != *c) return 0;
  1654. c++;
  1655. i++;
  1656. }
  1657. return 0;
  1658. }
  1659. static int syn_json_calculate(struct syntax_state * state);
  1660. static int syn_xml_calculate(struct syntax_state * state);
  1661. static int syn_markdown_calculate(struct syntax_state * state) {
  1662. if (state->state < 1) {
  1663. while (charat() != -1) {
  1664. if (state->i == 0 && charat() == '#') {
  1665. while (charat() == '#') paint(1, FLAG_KEYWORD);
  1666. while (charat() != -1) paint(1, FLAG_BOLD);
  1667. return -1;
  1668. } else if (state->i == 0) {
  1669. while (charat() == ' ') skip();
  1670. if (charat() == '`' && nextchar() == '`' && charrel(2) == '`') {
  1671. paint(3, FLAG_STRING);
  1672. if (match_forward(state, "c")) {
  1673. nest(syn_c_calculate, 2);
  1674. } else if (match_forward(state,"c++")) {
  1675. nest(syn_c_calculate, 2);
  1676. } else if (match_forward(state,"py") || match_forward(state,"python")) {
  1677. nest(syn_py_calculate, 5);
  1678. } else if (match_forward(state, "java")) {
  1679. nest(syn_java_calculate, 8);
  1680. } else if (match_forward(state,"json")) {
  1681. nest(syn_json_calculate, 10);
  1682. } else if (match_forward(state,"xml")) {
  1683. nest(syn_xml_calculate, 11);
  1684. } else if (match_forward(state,"html")) {
  1685. nest(syn_xml_calculate, 11); // TODO this will be a different highlighter later
  1686. } else if (match_forward(state,"make")) {
  1687. nest(syn_make_calculate, 16);
  1688. } else if (match_forward(state, "diff")) {
  1689. nest(syn_diff_calculate, 17);
  1690. } else if (match_forward(state, "rust")) {
  1691. nest(syn_rust_calculate, 18); /* Keep this at the end for now */
  1692. }
  1693. return 1;
  1694. }
  1695. }
  1696. if (charat() == ' ' && charrel(1) == ' ' && charrel(2) == ' ' && charrel(3) == ' ') {
  1697. return -1;
  1698. } else if (charat() == '`') {
  1699. paint(1, FLAG_STRING);
  1700. while (charat() != -1) {
  1701. if (charat() == '`') {
  1702. paint(1, FLAG_STRING);
  1703. return 0;
  1704. }
  1705. paint(1, FLAG_STRING);
  1706. }
  1707. } else if (charat() == '[') {
  1708. skip();
  1709. while (charat() != -1 && charat() != ']') {
  1710. paint(1, FLAG_LINK);
  1711. }
  1712. if (charat() == ']') skip();
  1713. if (charat() == '(') {
  1714. skip();
  1715. while (charat() != -1 && charat() != ')') {
  1716. paint(1, FLAG_NUMERAL);
  1717. }
  1718. }
  1719. } else {
  1720. skip();
  1721. return 0;
  1722. }
  1723. }
  1724. return -1;
  1725. } else if (state->state >= 1) {
  1726. /* Continuing generic triple-` */
  1727. if (state->i == 0) {
  1728. /* Go backwards until we find the source ``` */
  1729. int count = 0;
  1730. for (int i = state->line_no; i > 0; i--) {
  1731. if (env->lines[i]->istate < 1) {
  1732. while (env->lines[i]->text[count].codepoint == ' ') {
  1733. if (charrel(count) != ' ') goto _nope;
  1734. count++;
  1735. }
  1736. break;
  1737. }
  1738. }
  1739. if (charrel(count) == '`' && charrel(count+1) == '`' && charrel(count+2) == '`' && charrel(count+3) == -1) {
  1740. paint(count+3,FLAG_STRING);
  1741. return -1;
  1742. }
  1743. }
  1744. _nope:
  1745. if (state->state == 1) {
  1746. while (charat() != -1) paint(1, FLAG_STRING);
  1747. return 1;
  1748. } else if (state->state < 5) {
  1749. nest(syn_c_calculate, 2);
  1750. } else if (state->state < 8) {
  1751. nest(syn_py_calculate, 5);
  1752. } else if (state->state < 10) {
  1753. nest(syn_java_calculate, 8);
  1754. } else if (state->state < 11) {
  1755. nest(syn_json_calculate, 10);
  1756. } else if (state->state < 16) {
  1757. nest(syn_xml_calculate, 11);
  1758. } else if (state->state < 17) {
  1759. nest(syn_make_calculate, 16);
  1760. } else if (state->state < 18) {
  1761. nest(syn_diff_calculate, 17);
  1762. } else {
  1763. nest(syn_rust_calculate, 18);
  1764. }
  1765. }
  1766. return -1;
  1767. }
  1768. static char * markdown_ext[] = {".md",".markdown",NULL};
  1769. static char * syn_json_keywords[] = {
  1770. "true","false","null",
  1771. NULL
  1772. };
  1773. static int syn_json_calculate(struct syntax_state * state) {
  1774. while (charat() != -1) {
  1775. if (charat() == '"') {
  1776. int backtrack = state->i;
  1777. paint_simple_string(state);
  1778. int backtrack_end = state->i;
  1779. while (charat() == ' ') skip();
  1780. if (charat() == ':') {
  1781. /* This is dumb. */
  1782. state->i = backtrack;
  1783. paint(1, FLAG_ESCAPE);
  1784. while (state->i < backtrack_end-1) {
  1785. paint(1, FLAG_KEYWORD);
  1786. }
  1787. if (charat() == '"') {
  1788. paint(1, FLAG_ESCAPE);
  1789. }
  1790. }
  1791. return 0;
  1792. } else if (charat() == '-' || isdigit(charat())) {
  1793. if (charat() == '-') paint(1, FLAG_NUMERAL);
  1794. if (charat() == '0') {
  1795. paint(1, FLAG_NUMERAL);
  1796. } else {
  1797. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1798. }
  1799. if (charat() == '.') {
  1800. paint(1, FLAG_NUMERAL);
  1801. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1802. }
  1803. if (charat() == 'e' || charat() == 'E') {
  1804. paint(1, FLAG_NUMERAL);
  1805. if (charat() == '+' || charat() == '-') {
  1806. paint(1, FLAG_NUMERAL);
  1807. }
  1808. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1809. }
  1810. } else if (find_keywords(state,syn_json_keywords,FLAG_NUMERAL,c_keyword_qualifier)) {
  1811. /* ... */
  1812. } else {
  1813. skip();
  1814. return 0;
  1815. }
  1816. }
  1817. return -1;
  1818. }
  1819. static char * json_ext[] = {".json",NULL}; // TODO other stuff that uses json
  1820. static int syn_xml_calculate(struct syntax_state * state) {
  1821. switch (state->state) {
  1822. case -1:
  1823. case 0:
  1824. if (charat() == -1) return -1;
  1825. if (charat() != '<') {
  1826. skip();
  1827. return 0;
  1828. }
  1829. /* Opening brace */
  1830. if (charat() == '<' && nextchar() == '!' && charrel(2) == '-' && charrel(3) == '-') {
  1831. paint(4, FLAG_COMMENT);
  1832. goto _comment;
  1833. }
  1834. paint(1, FLAG_TYPE);
  1835. /* Fall through */
  1836. case 1:
  1837. /* State 1: We saw an opening brace. */
  1838. while (charat() != -1) {
  1839. if (charat() == '/') paint(1, FLAG_TYPE);
  1840. if (charat() == '?') paint(1, FLAG_TYPE);
  1841. if (charat() == ' ' || charat() == '\t') skip();
  1842. if (isalnum(charat())) {
  1843. while (isalnum(charat()) || charat() == '-') paint(1, FLAG_KEYWORD);
  1844. if (charat() == -1) return 2;
  1845. goto _in_tag;
  1846. } else {
  1847. paint(1, FLAG_TYPE);
  1848. }
  1849. }
  1850. return -1;
  1851. _in_tag:
  1852. case 2:
  1853. while (charat() != -1) {
  1854. if (charat() == '>') {
  1855. paint(1, FLAG_TYPE);
  1856. return 0;
  1857. } else if (charat() == '"') {
  1858. paint_simple_string(state);
  1859. if (charat() == -1 && lastchar() != '"') {
  1860. return 3;
  1861. }
  1862. } else {
  1863. paint(1, FLAG_TYPE);
  1864. }
  1865. }
  1866. return 2;
  1867. case 3:
  1868. /* In a string in tag */
  1869. if (charat() == '"') {
  1870. paint(1, FLAG_STRING);
  1871. return 2;
  1872. } else {
  1873. paint_simple_string(state);
  1874. if (charat() == -1 && lastchar() != '"') {
  1875. return 3;
  1876. }
  1877. }
  1878. break;
  1879. _comment:
  1880. case 4:
  1881. while (charat() != -1) {
  1882. if (charat() == '-' && nextchar() == '-' && charrel(2) == '>') {
  1883. paint(3, FLAG_COMMENT);
  1884. return 0;
  1885. } else {
  1886. paint(1, FLAG_COMMENT);
  1887. }
  1888. }
  1889. return 4;
  1890. }
  1891. return -1;
  1892. }
  1893. static char * xml_ext[] = {".xml",".htm",".html",NULL}; // TODO other stuff that uses xml (it's a lot!); FIXME htm/html are temporary; make dedicated SGML ones for this
  1894. static char * syn_proto_keywords[] = {
  1895. "syntax","import","option","package","message","group","oneof",
  1896. "optional","required","repeated","default","extend","extensions","to","max","reserved",
  1897. "service","rpc","returns","stream",
  1898. NULL
  1899. };
  1900. static char * syn_proto_types[] = {
  1901. "int32","int64","uint32","uint64","sint32","sint64",
  1902. "fixed32","fixed64","sfixed32","sfixed64",
  1903. "float","double","bool","string","bytes",
  1904. "enum",
  1905. NULL
  1906. };
  1907. static char * syn_proto_special[] = {
  1908. "true","false",
  1909. NULL
  1910. };
  1911. static int syn_proto_calculate(struct syntax_state * state) {
  1912. if (state->state < 1) {
  1913. if (charat() == '/' && nextchar() == '/') {
  1914. paint_comment(state);
  1915. } else if (charat() == '/' && nextchar() == '*') {
  1916. if (paint_c_comment(state) == 1) return 1;
  1917. return 0;
  1918. } else if (find_keywords(state, syn_proto_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1919. return 0;
  1920. } else if (find_keywords(state, syn_proto_types, FLAG_TYPE, c_keyword_qualifier)) {
  1921. return 0;
  1922. } else if (find_keywords(state, syn_proto_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1923. return 0;
  1924. } else if (charat() == '"') {
  1925. paint_simple_string(state);
  1926. return 0;
  1927. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1928. paint_c_numeral(state);
  1929. return 0;
  1930. } else if (charat() != -1) {
  1931. skip();
  1932. return 0;
  1933. }
  1934. return -1;
  1935. } else {
  1936. if (paint_c_comment(state) == 1) return 1;
  1937. return 0;
  1938. }
  1939. }
  1940. static char * proto_ext[] = {".proto",NULL};
  1941. static int esh_variable_qualifier(int c) {
  1942. return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_');
  1943. }
  1944. static int paint_esh_variable(struct syntax_state * state) {
  1945. if (charat() == '{') {
  1946. paint(1, FLAG_TYPE);
  1947. while (charat() != '}') paint(1, FLAG_TYPE);
  1948. if (charat() == '}') paint(1, FLAG_TYPE);
  1949. } else {
  1950. if (charat() == '?' || charat() == '$' || charat() == '#') {
  1951. paint(1, FLAG_TYPE);
  1952. } else {
  1953. while (esh_variable_qualifier(charat())) paint(1, FLAG_TYPE);
  1954. }
  1955. }
  1956. return 0;
  1957. }
  1958. static int paint_esh_string(struct syntax_state * state) {
  1959. int last = -1;
  1960. while (charat() != -1) {
  1961. if (last != '\\' && charat() == '"') {
  1962. paint(1, FLAG_STRING);
  1963. return 0;
  1964. } else if (charat() == '$') {
  1965. paint(1, FLAG_TYPE);
  1966. paint_esh_variable(state);
  1967. last = -1;
  1968. } else if (charat() != -1) {
  1969. last = charat();
  1970. paint(1, FLAG_STRING);
  1971. }
  1972. }
  1973. return 2;
  1974. }
  1975. static int paint_esh_single_string(struct syntax_state * state) {
  1976. int last = -1;
  1977. while (charat() != -1) {
  1978. if (last != '\\' && charat() == '\'') {
  1979. paint(1, FLAG_STRING);
  1980. return 0;
  1981. } else if (charat() != -1) {
  1982. last = charat();
  1983. paint(1, FLAG_STRING);
  1984. }
  1985. }
  1986. return 1;
  1987. }
  1988. static int esh_keyword_qualifier(int c) {
  1989. return (isalnum(c) || c == '?' || c == '_' || c == '-'); /* technically anything that isn't a space should qualify... */
  1990. }
  1991. static char * esh_keywords[] = {
  1992. "cd","exit","export","help","history","if","empty?",
  1993. "equals?","return","export-cmd","source","exec","not","while",
  1994. "then","else","echo",
  1995. NULL
  1996. };
  1997. static int syn_esh_calculate(struct syntax_state * state) {
  1998. if (state->state == 1) {
  1999. return paint_esh_single_string(state);
  2000. } else if (state->state == 2) {
  2001. return paint_esh_string(state);
  2002. }
  2003. if (charat() == '#') {
  2004. while (charat() != -1) paint(1, FLAG_COMMENT);
  2005. return -1;
  2006. } else if (charat() == '$') {
  2007. paint(1, FLAG_TYPE);
  2008. paint_esh_variable(state);
  2009. return 0;
  2010. } else if (charat() == '\'') {
  2011. paint(1, FLAG_STRING);
  2012. return paint_esh_single_string(state);
  2013. } else if (charat() == '"') {
  2014. paint(1, FLAG_STRING);
  2015. return paint_esh_string(state);
  2016. } else if (match_and_paint(state, "export", FLAG_KEYWORD, esh_keyword_qualifier)) {
  2017. while (charat() == ' ') skip();
  2018. while (esh_keyword_qualifier(charat())) paint(1, FLAG_TYPE);
  2019. return 0;
  2020. } else if (match_and_paint(state, "export-cmd", FLAG_KEYWORD, esh_keyword_qualifier)) {
  2021. while (charat() == ' ') skip();
  2022. while (esh_keyword_qualifier(charat())) paint(1, FLAG_TYPE);
  2023. return 0;
  2024. } else if (find_keywords(state, esh_keywords, FLAG_KEYWORD, esh_keyword_qualifier)) {
  2025. return 0;
  2026. } else if (isdigit(charat())) {
  2027. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  2028. return 0;
  2029. } else if (charat() != -1) {
  2030. skip();
  2031. return 0;
  2032. }
  2033. return -1;
  2034. }
  2035. /* Only enable esh highlighting by default on ToaruOS */
  2036. static char * esh_ext[] = {
  2037. #ifdef __toaru__
  2038. ".sh",
  2039. #endif
  2040. NULL
  2041. };
  2042. struct syntax_definition {
  2043. char * name;
  2044. char ** ext;
  2045. int (*calculate)(struct syntax_state *);
  2046. int prefers_spaces;
  2047. } syntaxes[] = {
  2048. {"c",c_ext,syn_c_calculate,0},
  2049. {"python",py_ext,syn_py_calculate,1},
  2050. {"java",java_ext,syn_java_calculate,1},
  2051. {"diff",diff_ext,syn_diff_calculate,0},
  2052. {"conf",conf_ext,syn_conf_calculate,0},
  2053. {"rust",rust_ext,syn_rust_calculate,1},
  2054. {"bimrc",bimrc_ext,syn_bimrc_calculate,0},
  2055. {"gitcommit",gitcommit_ext,syn_gitcommit_calculate,0},
  2056. {"gitrebase",gitrebase_ext,syn_gitrebase_calculate,0},
  2057. {"make",make_ext,syn_make_calculate,0}, /* Definitely don't use spaces for Make */
  2058. {"markdown",markdown_ext,syn_markdown_calculate,1},
  2059. {"json",json_ext,syn_json_calculate,1},
  2060. {"xml",xml_ext,syn_xml_calculate,1},
  2061. {"protobuf",proto_ext,syn_proto_calculate,1},
  2062. {"toarush",esh_ext,syn_esh_calculate,0},
  2063. {NULL,NULL,NULL,0},
  2064. };
  2065. /**
  2066. * Calculate syntax hilighting for the given line.
  2067. */
  2068. void recalculate_syntax(line_t * line, int line_no) {
  2069. /* Clear syntax for this line first */
  2070. for (int i = 0; i < line->actual; ++i) {
  2071. line->text[i].flags = 0;
  2072. }
  2073. if (!env->syntax) return;
  2074. /* Start from the line's stored in initial state */
  2075. struct syntax_state state;
  2076. state.line = line;
  2077. state.line_no = line_no;
  2078. state.state = line->istate;
  2079. state.i = 0;
  2080. while (1) {
  2081. state.state = env->syntax->calculate(&state);
  2082. if (state.state != 0) {
  2083. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  2084. env->lines[line_no+1]->istate = state.state;
  2085. if (env->loading) return;
  2086. recalculate_syntax(env->lines[line_no+1], line_no+1);
  2087. if (line_no + 1 >= env->offset && line_no + 1 < env->offset + global_config.term_height - global_config.bottom_size - 1) {
  2088. redraw_line(line_no + 1 - env->offset, line_no + 1);
  2089. }
  2090. }
  2091. break;
  2092. }
  2093. }
  2094. }
  2095. /**
  2096. * Recalculate tab widths.
  2097. */
  2098. void recalculate_tabs(line_t * line) {
  2099. if (env->loading) return;
  2100. int j = 0;
  2101. for (int i = 0; i < line->actual; ++i) {
  2102. if (line->text[i].codepoint == '\t') {
  2103. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  2104. }
  2105. j += line->text[i].display_width;
  2106. }
  2107. }
  2108. /**
  2109. * TODO:
  2110. *
  2111. * The line editing functions should probably take a buffer_t *
  2112. * so that they can act on buffers other than the active one.
  2113. */
  2114. void recursive_history_free(history_t * root) {
  2115. if (!root->next) return;
  2116. history_t * n = root->next;
  2117. recursive_history_free(n);
  2118. switch (n->type) {
  2119. case HISTORY_REPLACE_LINE:
  2120. free(n->contents.remove_replace_line.contents);
  2121. /* fall-through */
  2122. case HISTORY_REMOVE_LINE:
  2123. free(n->contents.remove_replace_line.old_contents);
  2124. break;
  2125. default:
  2126. /* Nothing extra to free */
  2127. break;
  2128. }
  2129. free(n);
  2130. root->next = NULL;
  2131. }
  2132. #define HIST_APPEND(e) do { \
  2133. if (env->history) { \
  2134. e->previous = env->history; \
  2135. recursive_history_free(env->history); \
  2136. env->history->next = e; \
  2137. e->next = NULL; \
  2138. } \
  2139. env->history = e; \
  2140. } while (0)
  2141. /**
  2142. * Mark a point where a complete set of actions has ended.
  2143. */
  2144. void set_history_break(void) {
  2145. if (!global_config.history_enabled) return;
  2146. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  2147. history_t * e = malloc(sizeof(history_t));
  2148. e->type = HISTORY_BREAK;
  2149. HIST_APPEND(e);
  2150. }
  2151. }
  2152. /**
  2153. * Insert a character into an existing line.
  2154. */
  2155. line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  2156. if (!env->loading && global_config.history_enabled) {
  2157. history_t * e = malloc(sizeof(history_t));
  2158. e->type = HISTORY_INSERT;
  2159. e->contents.insert_delete_replace.lineno = lineno;
  2160. e->contents.insert_delete_replace.offset = offset;
  2161. e->contents.insert_delete_replace.codepoint = c.codepoint;
  2162. HIST_APPEND(e);
  2163. }
  2164. /* If there is not enough space... */
  2165. if (line->actual == line->available) {
  2166. /* Expand the line buffer */
  2167. if (line->available == 0) {
  2168. line->available = 8;
  2169. } else {
  2170. line->available *= 2;
  2171. }
  2172. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  2173. }
  2174. /* If this was not the last character, then shift remaining characters forward. */
  2175. if (offset < line->actual) {
  2176. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  2177. }
  2178. /* Insert the new character */
  2179. line->text[offset] = c;
  2180. /* There is one new character in the line */
  2181. line->actual += 1;
  2182. if (!env->loading) {
  2183. line->rev_status = 2; /* Modified */
  2184. recalculate_tabs(line);
  2185. recalculate_syntax(line, lineno);
  2186. }
  2187. return line;
  2188. }
  2189. /**
  2190. * Delete a character from a line
  2191. */
  2192. void line_delete(line_t * line, int offset, int lineno) {
  2193. /* Can't delete character before start of line. */
  2194. if (offset == 0) return;
  2195. if (!env->loading && global_config.history_enabled) {
  2196. history_t * e = malloc(sizeof(history_t));
  2197. e->type = HISTORY_DELETE;
  2198. e->contents.insert_delete_replace.lineno = lineno;
  2199. e->contents.insert_delete_replace.offset = offset;
  2200. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  2201. HIST_APPEND(e);
  2202. }
  2203. /* If this isn't the last character, we need to move all subsequent characters backwards */
  2204. if (offset < line->actual) {
  2205. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  2206. }
  2207. /* The line is one character shorter */
  2208. line->actual -= 1;
  2209. line->rev_status = 2;
  2210. recalculate_tabs(line);
  2211. recalculate_syntax(line, lineno);
  2212. }
  2213. /**
  2214. * Replace a character in a line
  2215. */
  2216. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  2217. if (!env->loading && global_config.history_enabled) {
  2218. history_t * e = malloc(sizeof(history_t));
  2219. e->type = HISTORY_REPLACE;
  2220. e->contents.insert_delete_replace.lineno = lineno;
  2221. e->contents.insert_delete_replace.offset = offset;
  2222. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  2223. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  2224. HIST_APPEND(e);
  2225. }
  2226. line->text[offset] = _c;
  2227. if (!env->loading) {
  2228. line->rev_status = 2; /* Modified */
  2229. recalculate_tabs(line);
  2230. recalculate_syntax(line, lineno);
  2231. }
  2232. }
  2233. /**
  2234. * Remove a line from the active buffer
  2235. */
  2236. line_t ** remove_line(line_t ** lines, int offset) {
  2237. /* If there is only one line, clear it instead of removing it. */
  2238. if (env->line_count == 1) {
  2239. while (lines[offset]->actual > 0) {
  2240. line_delete(lines[offset], lines[offset]->actual, offset);
  2241. }
  2242. return lines;
  2243. }
  2244. if (!env->loading && global_config.history_enabled) {
  2245. history_t * e = malloc(sizeof(history_t));
  2246. e->type = HISTORY_REMOVE_LINE;
  2247. e->contents.remove_replace_line.lineno = offset;
  2248. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2249. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2250. HIST_APPEND(e);
  2251. }
  2252. /* Otherwise, free the data used by the line */
  2253. free(lines[offset]);
  2254. /* Move other lines up */
  2255. if (offset < env->line_count-1) {
  2256. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  2257. lines[env->line_count-1] = NULL;
  2258. }
  2259. /* There is one less line */
  2260. env->line_count -= 1;
  2261. return lines;
  2262. }
  2263. /**
  2264. * Add a new line to the active buffer.
  2265. */
  2266. line_t ** add_line(line_t ** lines, int offset) {
  2267. /* Invalid offset? */
  2268. if (offset > env->line_count) return lines;
  2269. if (!env->loading && global_config.history_enabled) {
  2270. history_t * e = malloc(sizeof(history_t));
  2271. e->type = HISTORY_ADD_LINE;
  2272. e->contents.add_merge_split_lines.lineno = offset;
  2273. HIST_APPEND(e);
  2274. }
  2275. /* Not enough space */
  2276. if (env->line_count == env->line_avail) {
  2277. /* Allocate more space */
  2278. env->line_avail *= 2;
  2279. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  2280. }
  2281. /* If this isn't the last line, move other lines down */
  2282. if (offset < env->line_count) {
  2283. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  2284. }
  2285. /* Allocate the new line */
  2286. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  2287. lines[offset]->available = 32;
  2288. /* There is one new line */
  2289. env->line_count += 1;
  2290. env->lines = lines;
  2291. if (!env->loading) {
  2292. lines[offset]->rev_status = 2; /* Modified */
  2293. }
  2294. if (offset > 0 && !env->loading) {
  2295. recalculate_syntax(lines[offset-1],offset-1);
  2296. }
  2297. return lines;
  2298. }
  2299. /**
  2300. * Replace a line with data from another line (used by paste to paste yanked lines)
  2301. */
  2302. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  2303. if (!env->loading && global_config.history_enabled) {
  2304. history_t * e = malloc(sizeof(history_t));
  2305. e->type = HISTORY_REPLACE_LINE;
  2306. e->contents.remove_replace_line.lineno = offset;
  2307. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2308. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2309. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  2310. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  2311. HIST_APPEND(e);
  2312. }
  2313. if (lines[offset]->available < replacement->actual) {
  2314. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  2315. lines[offset]->available = replacement->available;
  2316. }
  2317. lines[offset]->actual = replacement->actual;
  2318. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  2319. if (!env->loading) {
  2320. lines[offset]->rev_status = 2;
  2321. recalculate_syntax(lines[offset],offset);
  2322. }
  2323. }
  2324. /**
  2325. * Merge two consecutive lines.
  2326. * lineb is the offset of the second line.
  2327. */
  2328. line_t ** merge_lines(line_t ** lines, int lineb) {
  2329. /* linea is the line immediately before lineb */
  2330. int linea = lineb - 1;
  2331. if (!env->loading && global_config.history_enabled) {
  2332. history_t * e = malloc(sizeof(history_t));
  2333. e->type = HISTORY_MERGE_LINES;
  2334. e->contents.add_merge_split_lines.lineno = lineb;
  2335. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  2336. HIST_APPEND(e);
  2337. }
  2338. /* If there isn't enough space in linea hold both... */
  2339. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  2340. /* ... allocate more space until it fits */
  2341. if (lines[linea]->available == 0) {
  2342. lines[linea]->available = 8;
  2343. } else {
  2344. lines[linea]->available *= 2;
  2345. }
  2346. /* XXX why not just do this once after calculating appropriate size */
  2347. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  2348. }
  2349. /* Copy the second line into the first line */
  2350. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  2351. /* The first line is now longer */
  2352. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  2353. if (!env->loading) {
  2354. lines[linea]->rev_status = 2;
  2355. recalculate_tabs(lines[linea]);
  2356. recalculate_syntax(lines[linea], linea);
  2357. }
  2358. /* Remove the second line */
  2359. free(lines[lineb]);
  2360. /* Move other lines up */
  2361. if (lineb < env->line_count) {
  2362. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  2363. lines[env->line_count-1] = NULL;
  2364. }
  2365. /* There is one less line */
  2366. env->line_count -= 1;
  2367. return lines;
  2368. }
  2369. /**
  2370. * Split a line into two lines at the given column
  2371. */
  2372. line_t ** split_line(line_t ** lines, int line, int split) {
  2373. /* If we're trying to split from the start, just add a new blank line before */
  2374. if (split == 0) {
  2375. return add_line(lines, line);
  2376. }
  2377. if (!env->loading && global_config.history_enabled) {
  2378. history_t * e = malloc(sizeof(history_t));
  2379. e->type = HISTORY_SPLIT_LINE;
  2380. e->contents.add_merge_split_lines.lineno = line;
  2381. e->contents.add_merge_split_lines.split = split;
  2382. HIST_APPEND(e);
  2383. }
  2384. /* Allocate more space as needed */
  2385. if (env->line_count == env->line_avail) {
  2386. env->line_avail *= 2;
  2387. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  2388. }
  2389. /* Shift later lines down */
  2390. if (line < env->line_count) {
  2391. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  2392. }
  2393. /* I have no idea what this is doing */
  2394. int remaining = lines[line]->actual - split;
  2395. int v = remaining;
  2396. v--;
  2397. v |= v >> 1;
  2398. v |= v >> 2;
  2399. v |= v >> 4;
  2400. v |= v >> 8;
  2401. v |= v >> 16;
  2402. v++;
  2403. /* Allocate space for the new line */
  2404. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  2405. lines[line+1]->available = v;
  2406. lines[line+1]->actual = remaining;
  2407. /* Move the data from the old line into the new line */
  2408. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  2409. lines[line]->actual = split;
  2410. if (!env->loading) {
  2411. lines[line]->rev_status = 2;
  2412. lines[line+1]->rev_status = 2;
  2413. recalculate_tabs(lines[line]);
  2414. recalculate_tabs(lines[line+1]);
  2415. recalculate_syntax(lines[line], line);
  2416. recalculate_syntax(lines[line+1], line+1);
  2417. }
  2418. /* There is one new line */
  2419. env->line_count += 1;
  2420. /* We may have reallocated lines */
  2421. return lines;
  2422. }
  2423. /**
  2424. * Understand spaces and comments and check if the previous line
  2425. * ended with a brace or a colon.
  2426. */
  2427. int line_ends_with_brace(line_t * line) {
  2428. int i = line->actual-1;
  2429. while (i >= 0) {
  2430. if ((line->text[i].flags & 0xF) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  2431. i--;
  2432. } else {
  2433. break;
  2434. }
  2435. }
  2436. if (i < 0) return 0;
  2437. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':');
  2438. }
  2439. int line_is_comment(line_t * line) {
  2440. if (!env->syntax) return 0;
  2441. if (!strcmp(env->syntax->name,"c")) {
  2442. if (line->istate == 1) return 1;
  2443. } else if (!strcmp(env->syntax->name,"java")) {
  2444. if (line->istate == 1) return 1;
  2445. } else if (!strcmp(env->syntax->name,"rust")) {
  2446. if (line->istate > 0) return 1;
  2447. }
  2448. return 0;
  2449. }
  2450. /**
  2451. * Add indentation from the previous (temporally) line
  2452. */
  2453. void add_indent(int new_line, int old_line, int ignore_brace) {
  2454. if (env->indent) {
  2455. int changed = 0;
  2456. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  2457. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2458. if (env->lines[old_line]->text[i].codepoint == '/') {
  2459. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  2460. /* Insert ' * ' */
  2461. char_t space = {1,FLAG_COMMENT,' '};
  2462. char_t asterisk = {1,FLAG_COMMENT,'*'};
  2463. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  2464. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  2465. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  2466. env->col_no += 3;
  2467. }
  2468. break;
  2469. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  2470. /* Insert ' * ' */
  2471. char_t space = {1,FLAG_COMMENT,' '};
  2472. char_t asterisk = {1,FLAG_COMMENT,'*'};
  2473. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  2474. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  2475. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  2476. env->col_no += 3;
  2477. break;
  2478. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  2479. env->lines[old_line]->text[i].codepoint == '\t' ||
  2480. env->lines[old_line]->text[i].codepoint == '*') {
  2481. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  2482. env->col_no++;
  2483. changed = 1;
  2484. } else {
  2485. break;
  2486. }
  2487. }
  2488. } else {
  2489. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2490. if (old_line < new_line && i == env->lines[old_line]->actual - 3 &&
  2491. env->lines[old_line]->text[i].codepoint == ' ' &&
  2492. env->lines[old_line]->text[i+1].codepoint == '*' &&
  2493. env->lines[old_line]->text[i+2].codepoint == '/') {
  2494. break;
  2495. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  2496. env->lines[old_line]->text[i].codepoint == '\t') {
  2497. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  2498. env->col_no++;
  2499. changed = 1;
  2500. } else {
  2501. break;
  2502. }
  2503. }
  2504. }
  2505. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  2506. if (env->tabs) {
  2507. char_t c;
  2508. c.codepoint = '\t';
  2509. c.display_width = env->tabstop;
  2510. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  2511. env->col_no++;
  2512. changed = 1;
  2513. } else {
  2514. for (int j = 0; j < env->tabstop; ++j) {
  2515. char_t c;
  2516. c.codepoint = ' ';
  2517. c.display_width = 1;
  2518. c.flags = FLAG_SELECT;
  2519. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  2520. env->col_no++;
  2521. }
  2522. changed = 1;
  2523. }
  2524. }
  2525. int was_whitespace = 1;
  2526. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2527. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  2528. env->lines[old_line]->text[i].codepoint != '\t') {
  2529. was_whitespace = 0;
  2530. break;
  2531. }
  2532. }
  2533. if (was_whitespace) {
  2534. while (env->lines[old_line]->actual) {
  2535. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  2536. }
  2537. }
  2538. if (changed) {
  2539. recalculate_syntax(env->lines[new_line],new_line);
  2540. }
  2541. }
  2542. }
  2543. /**
  2544. * Initialize a buffer with default values
  2545. */
  2546. void setup_buffer(buffer_t * env) {
  2547. /* If this buffer was already initialized, clear out its line data */
  2548. if (env->lines) {
  2549. for (int i = 0; i < env->line_count; ++i) {
  2550. free(env->lines[i]);
  2551. }
  2552. free(env->lines);
  2553. }
  2554. /* Default state parameters */
  2555. env->line_no = 1; /* Default cursor position */
  2556. env->col_no = 1;
  2557. env->line_count = 1; /* Buffers always have at least one line */
  2558. env->modified = 0;
  2559. env->readonly = 0;
  2560. env->offset = 0;
  2561. env->line_avail = 8; /* Default line buffer capacity */
  2562. env->tabs = 1; /* Tabs by default */
  2563. env->tabstop = 4; /* Tab stop width */
  2564. env->indent = 1; /* Auto-indent by default */
  2565. env->history = malloc(sizeof(struct history));
  2566. memset(env->history, 0, sizeof(struct history));
  2567. env->last_save_history = env->history;
  2568. /* Allocate line buffer */
  2569. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  2570. /* Initialize the first line */
  2571. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  2572. env->lines[0]->available = 32;
  2573. }
  2574. /**
  2575. * Toggle buffered / unbuffered modes
  2576. */
  2577. struct termios old;
  2578. void get_initial_termios(void) {
  2579. tcgetattr(STDOUT_FILENO, &old);
  2580. }
  2581. void set_unbuffered(void) {
  2582. struct termios new = old;
  2583. new.c_iflag &= (~ICRNL);
  2584. new.c_lflag &= (~ICANON) & (~ECHO);
  2585. new.c_cc[VINTR] = 0;
  2586. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  2587. }
  2588. void set_buffered(void) {
  2589. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  2590. }
  2591. /**
  2592. * Convert codepoint to utf-8 string
  2593. */
  2594. int to_eight(uint32_t codepoint, char * out) {
  2595. memset(out, 0x00, 7);
  2596. if (codepoint < 0x0080) {
  2597. out[0] = (char)codepoint;
  2598. } else if (codepoint < 0x0800) {
  2599. out[0] = 0xC0 | (codepoint >> 6);
  2600. out[1] = 0x80 | (codepoint & 0x3F);
  2601. } else if (codepoint < 0x10000) {
  2602. out[0] = 0xE0 | (codepoint >> 12);
  2603. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  2604. out[2] = 0x80 | (codepoint & 0x3F);
  2605. } else if (codepoint < 0x200000) {
  2606. out[0] = 0xF0 | (codepoint >> 18);
  2607. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  2608. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  2609. out[3] = 0x80 | ((codepoint) & 0x3F);
  2610. } else if (codepoint < 0x4000000) {
  2611. out[0] = 0xF8 | (codepoint >> 24);
  2612. out[1] = 0x80 | (codepoint >> 18);
  2613. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  2614. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  2615. out[4] = 0x80 | ((codepoint) & 0x3F);
  2616. } else {
  2617. out[0] = 0xF8 | (codepoint >> 30);
  2618. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  2619. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  2620. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  2621. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  2622. out[5] = 0x80 | ((codepoint) & 0x3F);
  2623. }
  2624. return strlen(out);
  2625. }
  2626. /**
  2627. * Get the presentation width of a codepoint
  2628. */
  2629. int codepoint_width(wchar_t codepoint) {
  2630. if (codepoint == '\t') {
  2631. return 1; /* Recalculate later */
  2632. }
  2633. if (codepoint < 32) {
  2634. /* We render these as ^@ */
  2635. return 2;
  2636. }
  2637. if (codepoint == 0x7F) {
  2638. /* Renders as ^? */
  2639. return 2;
  2640. }
  2641. if (codepoint > 0x7f && codepoint < 0xa0) {
  2642. /* Upper control bytes <xx> */
  2643. return 4;
  2644. }
  2645. if (codepoint == 0xa0) {
  2646. /* Non-breaking space _ */
  2647. return 1;
  2648. }
  2649. /* Skip wcwidth for anything under 256 */
  2650. if (codepoint > 256) {
  2651. if (global_config.can_unicode) {
  2652. /* Higher codepoints may be wider (eg. Japanese) */
  2653. int out = wcwidth(codepoint);
  2654. if (out >= 1) return out;
  2655. }
  2656. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  2657. return (codepoint < 0x10000) ? 8 : 10;
  2658. }
  2659. return 1;
  2660. }
  2661. /**
  2662. * Move the terminal cursor
  2663. */
  2664. void place_cursor(int x, int y) {
  2665. printf("\033[%d;%dH", y, x);
  2666. fflush(stdout);
  2667. }
  2668. /**
  2669. * Set text colors
  2670. *
  2671. * Normally, text colors are just strings, but if they
  2672. * start with @ they will be parsed as integers
  2673. * representing one of the 16 standard colors, suitable
  2674. * for terminals without support for the 256- or 24-bit
  2675. * color modes.
  2676. */
  2677. void set_colors(const char * fg, const char * bg) {
  2678. printf("\033[22;23;24;");
  2679. if (*bg == '@') {
  2680. int _bg = atoi(bg+1);
  2681. if (_bg < 10) {
  2682. printf("4%d;", _bg);
  2683. } else {
  2684. printf("10%d;", _bg-10);
  2685. }
  2686. } else {
  2687. printf("48;%s;", bg);
  2688. }
  2689. if (*fg == '@') {
  2690. int _fg = atoi(fg+1);
  2691. if (_fg < 10) {
  2692. printf("3%dm", _fg);
  2693. } else {
  2694. printf("9%dm", _fg-10);
  2695. }
  2696. } else {
  2697. printf("38;%sm", fg);
  2698. }
  2699. fflush(stdout);
  2700. }
  2701. /**
  2702. * Set just the foreground color
  2703. *
  2704. * (See set_colors above)
  2705. */
  2706. void set_fg_color(const char * fg) {
  2707. printf("\033[22;23;24;");
  2708. if (*fg == '@') {
  2709. int _fg = atoi(fg+1);
  2710. if (_fg < 10) {
  2711. printf("3%dm", _fg);
  2712. } else {
  2713. printf("9%dm", _fg-10);
  2714. }
  2715. } else {
  2716. printf("38;%sm", fg);
  2717. }
  2718. fflush(stdout);
  2719. }
  2720. /**
  2721. * Clear the rest of this line
  2722. */
  2723. void clear_to_end(void) {
  2724. if (global_config.can_bce) {
  2725. printf("\033[K");
  2726. fflush(stdout);
  2727. }
  2728. }
  2729. /**
  2730. * For terminals without bce,
  2731. * prepaint the whole line, so we don't have to track
  2732. * where the cursor is for everything. Inefficient,
  2733. * but effective.
  2734. */
  2735. void paint_line(const char * bg) {
  2736. if (!global_config.can_bce) {
  2737. set_colors(COLOR_FG, bg);
  2738. for (int i = 0; i < global_config.term_width; ++i) {
  2739. printf(" ");
  2740. }
  2741. printf("\r");
  2742. }
  2743. }
  2744. /**
  2745. * Enable bold text display
  2746. */
  2747. void set_bold(void) {
  2748. printf("\033[1m");
  2749. fflush(stdout);
  2750. }
  2751. /**
  2752. * Disable bold
  2753. */
  2754. void unset_bold(void) {
  2755. printf("\033[22m");
  2756. fflush(stdout);
  2757. }
  2758. /**
  2759. * Enable underlined text display
  2760. */
  2761. void set_underline(void) {
  2762. printf("\033[4m");
  2763. fflush(stdout);
  2764. }
  2765. /**
  2766. * Disable underlined text display
  2767. */
  2768. void unset_underline(void) {
  2769. printf("\033[24m");
  2770. fflush(stdout);
  2771. }
  2772. /**
  2773. * Reset text display attributes
  2774. */
  2775. void reset(void) {
  2776. printf("\033[0m");
  2777. fflush(stdout);
  2778. }
  2779. /**
  2780. * Clear the entire screen
  2781. */
  2782. void clear_screen(void) {
  2783. printf("\033[H\033[2J");
  2784. fflush(stdout);
  2785. }
  2786. /**
  2787. * Hide the cursor
  2788. */
  2789. void hide_cursor(void) {
  2790. if (global_config.can_hideshow) {
  2791. printf("\033[?25l");
  2792. }
  2793. fflush(stdout);
  2794. }
  2795. /**
  2796. * Show the cursor
  2797. */
  2798. void show_cursor(void) {
  2799. if (global_config.can_hideshow) {
  2800. printf("\033[?25h");
  2801. }
  2802. fflush(stdout);
  2803. }
  2804. /**
  2805. * Request mouse events
  2806. */
  2807. void mouse_enable(void) {
  2808. if (global_config.can_mouse) {
  2809. printf("\033[?1000h");
  2810. }
  2811. fflush(stdout);
  2812. }
  2813. /**
  2814. * Stop mouse events
  2815. */
  2816. void mouse_disable(void) {
  2817. if (global_config.can_mouse) {
  2818. printf("\033[?1000l");
  2819. }
  2820. fflush(stdout);
  2821. }
  2822. /**
  2823. * Shift the screen up one line
  2824. */
  2825. void shift_up(void) {
  2826. printf("\033[1S");
  2827. }
  2828. /**
  2829. * Shift the screen down one line.
  2830. */
  2831. void shift_down(void) {
  2832. printf("\033[1T");
  2833. }
  2834. /**
  2835. * Switch to the alternate terminal screen.
  2836. */
  2837. void set_alternate_screen(void) {
  2838. if (global_config.can_altscreen) {
  2839. printf("\033[?1049h");
  2840. }
  2841. }
  2842. /**
  2843. * Restore the standard terminal screen.
  2844. */
  2845. void unset_alternate_screen(void) {
  2846. if (global_config.can_altscreen) {
  2847. printf("\033[?1049l");
  2848. }
  2849. }
  2850. char * file_basename(char * file) {
  2851. char * c = strrchr(file, '/');
  2852. if (!c) return file;
  2853. return (c+1);
  2854. }
  2855. int draw_tab_name(buffer_t * _env, char * out) {
  2856. return sprintf(out, "%s %.40s ",
  2857. _env->modified ? " +" : "",
  2858. _env->file_name ? file_basename(_env->file_name) : "[No Name]");
  2859. }
  2860. /**
  2861. * Redaw the tabbar, with a tab for each buffer.
  2862. *
  2863. * The active buffer is highlighted.
  2864. */
  2865. void redraw_tabbar(void) {
  2866. /* Hide cursor while rendering UI */
  2867. hide_cursor();
  2868. /* Move to upper left */
  2869. place_cursor(1,1);
  2870. paint_line(COLOR_TABBAR_BG);
  2871. /* For each buffer... */
  2872. int offset = 0;
  2873. for (int i = 0; i < buffers_len; i++) {
  2874. buffer_t * _env = buffers[i];
  2875. if (_env == env) {
  2876. /* If this is the active buffer, hilight it */
  2877. reset();
  2878. set_colors(COLOR_FG, COLOR_BG);
  2879. set_bold();
  2880. } else {
  2881. /* Otherwise use default tab color */
  2882. reset();
  2883. set_colors(COLOR_FG, COLOR_TAB_BG);
  2884. set_underline();
  2885. }
  2886. char title[64];
  2887. int size = draw_tab_name(_env, title);
  2888. if (offset + size >= global_config.term_width) {
  2889. if (global_config.term_width - offset - 1 > 0) {
  2890. printf("%*s", global_config.term_width - offset - 1, title);
  2891. }
  2892. break;
  2893. } else {
  2894. printf("%s", title);
  2895. }
  2896. offset += size;
  2897. }
  2898. /* Reset bold/underline */
  2899. reset();
  2900. /* Fill the rest of the tab bar */
  2901. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2902. clear_to_end();
  2903. }
  2904. /**
  2905. * Braindead log10 implementation for the line numbers
  2906. */
  2907. int log_base_10(unsigned int v) {
  2908. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2909. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2910. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2911. return r;
  2912. }
  2913. /**
  2914. * Render a line of text
  2915. *
  2916. * This handles rendering the actual text content. A full line of text
  2917. * also includes a line number and some padding.
  2918. *
  2919. * width: width of the text display region (term width - line number width)
  2920. * offset: how many cells into the line to start rendering at
  2921. */
  2922. void render_line(line_t * line, int width, int offset, int line_no) {
  2923. int i = 0; /* Offset in char_t line data entries */
  2924. int j = 0; /* Offset in terminal cells */
  2925. const char * last_color = NULL;
  2926. int was_selecting = 0, was_searching = 0;
  2927. /* Set default text colors */
  2928. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2929. /*
  2930. * When we are rendering in the middle of a wide character,
  2931. * we render -'s to fill the remaining amount of the
  2932. * charater's width
  2933. */
  2934. int remainder = 0;
  2935. /* For each character in the line ... */
  2936. while (i < line->actual) {
  2937. /* If there is remaining text... */
  2938. if (remainder) {
  2939. /* If we should be drawing by now... */
  2940. if (j >= offset) {
  2941. /* Fill remainder with -'s */
  2942. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2943. printf("-");
  2944. set_colors(COLOR_FG, COLOR_BG);
  2945. }
  2946. /* One less remaining width cell to fill */
  2947. remainder--;
  2948. /* Terminal offset moves forward */
  2949. j++;
  2950. /*
  2951. * If this was the last remaining character, move to
  2952. * the next codepoint in the line
  2953. */
  2954. if (remainder == 0) {
  2955. i++;
  2956. }
  2957. continue;
  2958. }
  2959. /* Get the next character to draw */
  2960. char_t c = line->text[i];
  2961. /* If we should be drawing by now... */
  2962. if (j >= offset) {
  2963. /* If this character is going to fall off the edge of the screen... */
  2964. if (j - offset + c.display_width >= width) {
  2965. /* We draw this with special colors so it isn't ambiguous */
  2966. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2967. /* If it's wide, draw ---> as needed */
  2968. while (j - offset < width - 1) {
  2969. printf("-");
  2970. j++;
  2971. }
  2972. /* End the line with a > to show it overflows */
  2973. printf(">");
  2974. set_colors(COLOR_FG, COLOR_BG);
  2975. return;
  2976. }
  2977. /* Syntax hilighting */
  2978. const char * color = flag_to_color(c.flags);
  2979. if (c.flags & FLAG_SELECT) {
  2980. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2981. was_selecting = 1;
  2982. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2983. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2984. was_searching = 1;
  2985. } else {
  2986. if (was_selecting || was_searching) {
  2987. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2988. last_color = color;
  2989. } else if (!last_color || strcmp(color, last_color)) {
  2990. set_fg_color(color);
  2991. last_color = color;
  2992. }
  2993. }
  2994. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2995. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2996. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2997. ((j == env->sel_col) ||
  2998. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2999. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3000. was_selecting = 1;
  3001. }
  3002. #define _set_colors(fg,bg) \
  3003. if (!(c.flags & FLAG_SELECT) && !(was_selecting)) { \
  3004. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  3005. }
  3006. /* Render special characters */
  3007. if (c.codepoint == '\t') {
  3008. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3009. if (global_config.can_unicode) {
  3010. printf("»");
  3011. for (int i = 1; i < c.display_width; ++i) {
  3012. printf("·");
  3013. }
  3014. } else {
  3015. printf(">");
  3016. for (int i = 1; i < c.display_width; ++i) {
  3017. printf("-");
  3018. }
  3019. }
  3020. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3021. } else if (c.codepoint < 32) {
  3022. /* Codepoints under 32 to get converted to ^@ escapes */
  3023. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3024. printf("^%c", '@' + c.codepoint);
  3025. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3026. } else if (c.codepoint == 0x7f) {
  3027. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3028. printf("^?");
  3029. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3030. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  3031. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3032. printf("<%2x>", c.codepoint);
  3033. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3034. } else if (c.codepoint == 0xa0) {
  3035. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3036. printf("_");
  3037. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3038. } else if (c.display_width == 8) {
  3039. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3040. printf("[U+%04x]", c.codepoint);
  3041. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3042. } else if (c.display_width == 10) {
  3043. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3044. printf("[U+%06x]", c.codepoint);
  3045. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3046. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  3047. /* Special case: space at end of line */
  3048. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3049. printf("·");
  3050. _set_colors(COLOR_FG, COLOR_BG);
  3051. } else {
  3052. /* Normal characters get output */
  3053. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  3054. to_eight(c.codepoint, tmp);
  3055. printf("%s", tmp);
  3056. }
  3057. /* Advance the terminal cell offset by the render width of this character */
  3058. j += c.display_width;
  3059. /* Advance to the next character */
  3060. i++;
  3061. } else if (c.display_width > 1) {
  3062. /*
  3063. * If this is a wide character but we aren't ready to render yet,
  3064. * we may need to draw some filler text for the remainder of its
  3065. * width to ensure we don't jump around when horizontally scrolling
  3066. * past wide characters.
  3067. */
  3068. remainder = c.display_width - 1;
  3069. j++;
  3070. } else {
  3071. /* Regular character, not ready to draw, advance without doing anything */
  3072. j++;
  3073. i++;
  3074. }
  3075. }
  3076. if (env->mode != MODE_LINE_SELECTION) {
  3077. if (line->is_current) {
  3078. set_colors(COLOR_FG, COLOR_ALT_BG);
  3079. } else {
  3080. set_colors(COLOR_FG, COLOR_BG);
  3081. }
  3082. } else {
  3083. if (!line->actual) {
  3084. if (env->line_no == line_no ||
  3085. (env->start_line > env->line_no &&
  3086. (line_no >= env->line_no && line_no <= env->start_line)) ||
  3087. (env->start_line < env->line_no &&
  3088. (line_no >= env->start_line && line_no <= env->line_no))) {
  3089. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3090. }
  3091. }
  3092. }
  3093. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  3094. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  3095. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  3096. j <= env->sel_col &&
  3097. env->sel_col < width) {
  3098. set_colors(COLOR_FG, COLOR_BG);
  3099. while (j < env->sel_col) {
  3100. printf(" ");
  3101. j++;
  3102. }
  3103. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3104. printf(" ");
  3105. j++;
  3106. set_colors(COLOR_FG, COLOR_BG);
  3107. }
  3108. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  3109. clear_to_end();
  3110. } else {
  3111. /* Paint the rest of the line */
  3112. for (; j - offset < width; ++j) {
  3113. printf(" ");
  3114. }
  3115. }
  3116. }
  3117. /**
  3118. * Get the width of the line number region
  3119. */
  3120. int num_width(void) {
  3121. int w = log_base_10(env->line_count) + 1;
  3122. if (w < 2) return 2;
  3123. return w;
  3124. }
  3125. /**
  3126. * Draw the gutter and line numbers.
  3127. */
  3128. void draw_line_number(int x) {
  3129. /* Draw the line number */
  3130. if (env->lines[x]->is_current) {
  3131. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  3132. } else {
  3133. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  3134. }
  3135. int num_size = num_width();
  3136. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  3137. printf(" ");
  3138. }
  3139. printf("%d%c", x + 1, (x+1 == env->line_no && env->coffset > 0) ? '<' : ' ');
  3140. }
  3141. /**
  3142. * Used to highlight the current line after moving the cursor.
  3143. */
  3144. void recalculate_current_line(void) {
  3145. if (!global_config.hilight_current_line) return;
  3146. for (int i = 0; i < env->line_count; ++i) {
  3147. if (env->lines[i]->is_current && i != env->line_no-1) {
  3148. env->lines[i]->is_current = 0;
  3149. if ((i) - env->offset > -1 &&
  3150. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3151. redraw_line((i) - env->offset, i);
  3152. }
  3153. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  3154. env->lines[i]->is_current = 1;
  3155. if ((i) - env->offset > -1 &&
  3156. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3157. redraw_line((i) - env->offset, i);
  3158. }
  3159. }
  3160. }
  3161. }
  3162. /**
  3163. * Redraw line.
  3164. *
  3165. * This draws the line number as well as the actual text.
  3166. * j = screen-relative line offset.
  3167. */
  3168. void redraw_line(int j, int x) {
  3169. if (env->loading) return;
  3170. /* Hide cursor when drawing */
  3171. hide_cursor();
  3172. /* Move cursor to upper left most cell of this line */
  3173. place_cursor(1 + env->left,2 + j);
  3174. /* Draw a gutter on the left. */
  3175. switch (env->lines[x]->rev_status) {
  3176. case 1:
  3177. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  3178. break;
  3179. case 2:
  3180. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  3181. break;
  3182. case 3:
  3183. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  3184. break;
  3185. case 4:
  3186. set_colors(COLOR_NUMBER_FG, COLOR_RED);
  3187. break;
  3188. default:
  3189. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  3190. break;
  3191. }
  3192. printf(" ");
  3193. draw_line_number(x);
  3194. /*
  3195. * Draw the line text
  3196. * If this is the active line, the current character cell offset should be used.
  3197. * (Non-active lines are not shifted and always render from the start of the line)
  3198. */
  3199. render_line(env->lines[x], env->width - 3 - num_width(), (x + 1 == env->line_no) ? env->coffset : 0, x+1);
  3200. }
  3201. /**
  3202. * Draw a ~ line where there is no buffer text.
  3203. */
  3204. void draw_excess_line(int j) {
  3205. place_cursor(1+env->left,2 + j);
  3206. paint_line(COLOR_ALT_BG);
  3207. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3208. printf("~");
  3209. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  3210. clear_to_end();
  3211. } else {
  3212. /* Paint the rest of the line */
  3213. for (int x = 1; x < env->width; ++x) {
  3214. printf(" ");
  3215. }
  3216. }
  3217. }
  3218. /**
  3219. * Redraw the entire text area
  3220. */
  3221. void redraw_text(void) {
  3222. /* Hide cursor while rendering */
  3223. hide_cursor();
  3224. /* Figure out the available size of the text region */
  3225. int l = global_config.term_height - global_config.bottom_size - 1;
  3226. int j = 0;
  3227. /* Draw each line */
  3228. for (int x = env->offset; j < l && x < env->line_count; x++) {
  3229. redraw_line(j,x);
  3230. j++;
  3231. }
  3232. /* Draw the rest of the text region as ~ lines */
  3233. for (; j < l; ++j) {
  3234. draw_excess_line(j);
  3235. }
  3236. }
  3237. static int view_left_offset = 0;
  3238. static int view_right_offset = 0;
  3239. void redraw_alt_buffer(buffer_t * buf) {
  3240. if (left_buffer == right_buffer) {
  3241. /* draw the opposite view */
  3242. int left, width, offset;
  3243. left = env->left;
  3244. width = env->width;
  3245. offset = env->offset;
  3246. if (left == 0) {
  3247. /* Draw the right side */
  3248. env->left = width;
  3249. env->width = global_config.term_width - width;
  3250. env->offset = view_right_offset;
  3251. view_left_offset = offset;
  3252. } else {
  3253. env->left = 0;
  3254. env->width = global_config.term_width * global_config.split_percent / 100;
  3255. env->offset = view_left_offset;
  3256. view_right_offset = offset;
  3257. }
  3258. redraw_text();
  3259. env->left = left;
  3260. env->width = width;
  3261. env->offset = offset;
  3262. }
  3263. /* Swap out active buffer */
  3264. buffer_t * tmp = env;
  3265. env = buf;
  3266. /* Redraw text */
  3267. redraw_text();
  3268. /* Return original active buffer */
  3269. env = tmp;
  3270. }
  3271. /**
  3272. * Draw the status bar
  3273. *
  3274. * The status bar shows the name of the file, whether it has modifications,
  3275. * and (in the future) what syntax highlighting mode is enabled.
  3276. *
  3277. * The right side of the tatus bar shows the line number and column.
  3278. */
  3279. void redraw_statusbar(void) {
  3280. /* Hide cursor while rendering */
  3281. hide_cursor();
  3282. /* Move cursor to the status bar line (second from bottom */
  3283. place_cursor(1, global_config.term_height - 1);
  3284. /* Set background colors for status line */
  3285. paint_line(COLOR_STATUS_BG);
  3286. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3287. /* Print the file name */
  3288. char status_bits[1024] = {0}; /* Sane maximum */
  3289. char * s = status_bits;
  3290. if (env->syntax) {
  3291. s += snprintf(s, 100, "[%s]", env->syntax->name);
  3292. }
  3293. /* Print file status indicators */
  3294. if (env->modified) {
  3295. s += snprintf(s, 5, "[+]");
  3296. }
  3297. if (env->readonly) {
  3298. s += snprintf(s, 6, "[ro]");
  3299. }
  3300. s += snprintf(s, 2, " ");
  3301. if (env->tabs) {
  3302. s += snprintf(s, 20, "[tabs]");
  3303. } else {
  3304. s += snprintf(s, 20, "[spaces=%d]", env->tabstop);
  3305. }
  3306. if (global_config.yanks) {
  3307. s += snprintf(s, 20, "[y:%ld]", global_config.yank_count);
  3308. }
  3309. if (env->indent) {
  3310. s += snprintf(s, 20, "[indent]");
  3311. }
  3312. /* Pre-render the right hand side of the status bar */
  3313. char right_hand[1024];
  3314. snprintf(right_hand, 1024, "Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  3315. if (env->file_name) {
  3316. int len = strlen(env->file_name);
  3317. int i = 0;
  3318. while (len > 5 && len > (int)global_config.term_width - (int)strlen(right_hand) - (int)strlen(status_bits) - 5) {
  3319. len--;
  3320. i += 1;
  3321. }
  3322. printf("%s%s", i > 0 ? "<" : "", env->file_name + i);
  3323. } else {
  3324. printf("[No Name]");
  3325. }
  3326. printf(" ");
  3327. printf("%s", status_bits);
  3328. /* Clear the rest of the status bar */
  3329. clear_to_end();
  3330. /* Move the cursor appropriately to draw it */
  3331. place_cursor(global_config.term_width - strlen(right_hand), global_config.term_height - 1);
  3332. /* TODO: What if we're localized and this has wide chars? */
  3333. printf("%s",right_hand);
  3334. fflush(stdout);
  3335. }
  3336. /**
  3337. * Draw the command line
  3338. *
  3339. * The command line either has input from the user (:quit, :!make, etc.)
  3340. * or shows the INSERT (or VISUAL in the future) mode name.
  3341. */
  3342. void redraw_commandline(void) {
  3343. /* Hide cursor while rendering */
  3344. hide_cursor();
  3345. /* Move cursor to the last line */
  3346. place_cursor(1, global_config.term_height);
  3347. /* Set background color */
  3348. paint_line(COLOR_BG);
  3349. set_colors(COLOR_FG, COLOR_BG);
  3350. /* If we are in an edit mode, note that. */
  3351. if (env->mode == MODE_INSERT) {
  3352. set_bold();
  3353. printf("-- INSERT --");
  3354. clear_to_end();
  3355. unset_bold();
  3356. } else if (env->mode == MODE_LINE_SELECTION) {
  3357. set_bold();
  3358. printf("-- LINE SELECTION -- (%d:%d)",
  3359. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3360. (env->start_line < env->line_no) ? env->line_no : env->start_line
  3361. );
  3362. clear_to_end();
  3363. unset_bold();
  3364. } else if (env->mode == MODE_COL_SELECTION) {
  3365. set_bold();
  3366. printf("-- COL SELECTION -- (%d:%d %d)",
  3367. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3368. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  3369. (env->sel_col)
  3370. );
  3371. clear_to_end();
  3372. unset_bold();
  3373. } else if (env->mode == MODE_COL_INSERT) {
  3374. set_bold();
  3375. printf("-- COL INSERT -- (%d:%d %d)",
  3376. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3377. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  3378. (env->sel_col)
  3379. );
  3380. clear_to_end();
  3381. unset_bold();
  3382. } else if (env->mode == MODE_REPLACE) {
  3383. set_bold();
  3384. printf("-- REPLACE --");
  3385. clear_to_end();
  3386. unset_bold();
  3387. } else if (env->mode == MODE_CHAR_SELECTION) {
  3388. set_bold();
  3389. printf("-- CHAR SELECTION -- ");
  3390. clear_to_end();
  3391. reset();
  3392. } else {
  3393. clear_to_end();
  3394. }
  3395. }
  3396. /**
  3397. * Draw a message on the command line.
  3398. */
  3399. void render_commandline_message(char * message, ...) {
  3400. /* varargs setup */
  3401. va_list args;
  3402. va_start(args, message);
  3403. char buf[1024];
  3404. /* Process format string */
  3405. vsnprintf(buf, 1024, message, args);
  3406. va_end(args);
  3407. /* Hide cursor while rendering */
  3408. hide_cursor();
  3409. /* Move cursor to the last line */
  3410. place_cursor(1, global_config.term_height);
  3411. /* Set background color */
  3412. paint_line(COLOR_BG);
  3413. set_colors(COLOR_FG, COLOR_BG);
  3414. printf("%s", buf);
  3415. /* Clear the rest of the status bar */
  3416. clear_to_end();
  3417. }
  3418. /**
  3419. * Draw all screen elements
  3420. */
  3421. void redraw_all(void) {
  3422. redraw_tabbar();
  3423. redraw_text();
  3424. if (left_buffer) {
  3425. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  3426. }
  3427. redraw_statusbar();
  3428. redraw_commandline();
  3429. }
  3430. void redraw_most(void) {
  3431. redraw_tabbar();
  3432. redraw_text();
  3433. redraw_statusbar();
  3434. redraw_commandline();
  3435. }
  3436. void unsplit(void) {
  3437. if (left_buffer) {
  3438. left_buffer->left = 0;
  3439. left_buffer->width = global_config.term_width;
  3440. }
  3441. if (right_buffer) {
  3442. right_buffer->left = 0;
  3443. right_buffer->width = global_config.term_width;
  3444. }
  3445. left_buffer = NULL;
  3446. right_buffer = NULL;
  3447. redraw_all();
  3448. }
  3449. /**
  3450. * Update the terminal title bar
  3451. */
  3452. void update_title(void) {
  3453. if (!global_config.can_title) return;
  3454. char cwd[1024] = {'/',0};
  3455. getcwd(cwd, 1024);
  3456. for (int i = 1; i < 3; ++i) {
  3457. printf("\033]%d;%s%s (%s) - BIM\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  3458. }
  3459. }
  3460. /**
  3461. * Mark this buffer as modified and
  3462. * redraw the status and tabbar if needed.
  3463. */
  3464. void set_modified(void) {
  3465. /* If it was already marked modified, no need to do anything */
  3466. if (env->modified) return;
  3467. /* Mark as modified */
  3468. env->modified = 1;
  3469. /* Redraw some things */
  3470. update_title();
  3471. redraw_tabbar();
  3472. redraw_statusbar();
  3473. }
  3474. /**
  3475. * Draw a message on the status line
  3476. */
  3477. void render_status_message(char * message, ...) {
  3478. /* varargs setup */
  3479. va_list args;
  3480. va_start(args, message);
  3481. char buf[1024];
  3482. /* Process format string */
  3483. vsnprintf(buf, 1024, message, args);
  3484. va_end(args);
  3485. /* Hide cursor while rendering */
  3486. hide_cursor();
  3487. /* Move cursor to the status bar line (second from bottom */
  3488. place_cursor(1, global_config.term_height - 1);
  3489. /* Set background colors for status line */
  3490. paint_line(COLOR_STATUS_BG);
  3491. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3492. printf("%s", buf);
  3493. /* Clear the rest of the status bar */
  3494. clear_to_end();
  3495. }
  3496. /**
  3497. * Draw an errormessage to the command line.
  3498. */
  3499. void render_error(char * message, ...) {
  3500. /* varargs setup */
  3501. va_list args;
  3502. va_start(args, message);
  3503. char buf[1024];
  3504. /* Process format string */
  3505. vsnprintf(buf, 1024, message, args);
  3506. va_end(args);
  3507. /* Hide cursor while rendering */
  3508. hide_cursor();
  3509. /* Move cursor to the command line */
  3510. place_cursor(1, global_config.term_height);
  3511. /* Set appropriate error message colors */
  3512. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  3513. /* Draw the message */
  3514. printf("%s", buf);
  3515. fflush(stdout);
  3516. }
  3517. char * paren_pairs = "()[]{}<>";
  3518. void find_matching_paren(int * out_line, int * out_col, int in_col);
  3519. int is_paren(int c) {
  3520. char * p = paren_pairs;
  3521. while (*p) {
  3522. if (c == *p) return 1;
  3523. p++;
  3524. }
  3525. return 0;
  3526. }
  3527. /**
  3528. * If the config option is enabled, find the matching
  3529. * paren character and highlight it with the SELECT
  3530. * colors, clearing out other SELECT values. As we
  3531. * co-opt the SELECT flag, don't do this in selection
  3532. * modes - only in normal and insert modes.
  3533. */
  3534. void highlight_matching_paren(void) {
  3535. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  3536. if (!global_config.highlight_parens) return;
  3537. int line = -1, col = -1;
  3538. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  3539. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  3540. find_matching_paren(&line, &col, 1);
  3541. if (line != -1) env->highlighting_paren = 1;
  3542. } else if (env->line_no <= env->line_count && env->col_no > 1 && is_paren(env->lines[env->line_no-1]->text[env->col_no-2].codepoint)) {
  3543. find_matching_paren(&line, &col, 2);
  3544. if (line != -1) env->highlighting_paren = 1;
  3545. }
  3546. if (!env->highlighting_paren) return;
  3547. for (int i = 0; i < env->line_count; ++i) {
  3548. int redraw = 0;
  3549. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3550. if (i == line-1 && j == col-1) {
  3551. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT;
  3552. redraw = 1;
  3553. continue;
  3554. }
  3555. if (env->lines[i]->text[j].flags & FLAG_SELECT) {
  3556. redraw = 1;
  3557. }
  3558. env->lines[i]->text[j].flags &= (~FLAG_SELECT);
  3559. }
  3560. if (redraw) {
  3561. if ((i) - env->offset > -1 &&
  3562. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3563. redraw_line((i) - env->offset, i);
  3564. }
  3565. }
  3566. }
  3567. if (line == -1) env->highlighting_paren = 0;
  3568. }
  3569. /**
  3570. * Move the cursor to the appropriate location based
  3571. * on where it is in the text region.
  3572. *
  3573. * This does some additional math to set the text
  3574. * region horizontal offset.
  3575. */
  3576. void place_cursor_actual(void) {
  3577. /* Invalid positions */
  3578. if (env->line_no < 1) env->line_no = 1;
  3579. if (env->col_no < 1) env->col_no = 1;
  3580. /* Account for the left hand gutter */
  3581. int num_size = num_width() + 3;
  3582. int x = num_size + 1 - env->coffset;
  3583. /* Determine where the cursor is physically */
  3584. for (int i = 0; i < env->col_no - 1; ++i) {
  3585. char_t * c = &env->lines[env->line_no-1]->text[i];
  3586. x += c->display_width;
  3587. }
  3588. /* y is a bit easier to calculate */
  3589. int y = env->line_no - env->offset + 1;
  3590. int needs_redraw = 0;
  3591. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  3592. y++;
  3593. env->offset--;
  3594. needs_redraw = 1;
  3595. }
  3596. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  3597. y--;
  3598. env->offset++;
  3599. needs_redraw = 1;
  3600. }
  3601. if (needs_redraw) {
  3602. redraw_text();
  3603. redraw_tabbar();
  3604. redraw_statusbar();
  3605. redraw_commandline();
  3606. }
  3607. /* If the cursor has gone off screen to the right... */
  3608. if (x > env->width - 1) {
  3609. /* Adjust the offset appropriately to scroll horizontally */
  3610. int diff = x - (env->width - 1);
  3611. env->coffset += diff;
  3612. x -= diff;
  3613. redraw_text();
  3614. }
  3615. /* Same for scrolling horizontally to the left */
  3616. if (x < num_size + 1) {
  3617. int diff = (num_size + 1) - x;
  3618. env->coffset -= diff;
  3619. x += diff;
  3620. redraw_text();
  3621. }
  3622. highlight_matching_paren();
  3623. recalculate_current_line();
  3624. /* Move the actual terminal cursor */
  3625. place_cursor(x+env->left,y);
  3626. /* Show the cursor */
  3627. show_cursor();
  3628. }
  3629. void update_split_size(void) {
  3630. if (!left_buffer) return;
  3631. if (left_buffer == right_buffer) {
  3632. if (left_buffer->left == 0) {
  3633. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3634. } else {
  3635. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  3636. right_buffer->width = global_config.term_width - right_buffer->left;
  3637. }
  3638. return;
  3639. }
  3640. left_buffer->left = 0;
  3641. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3642. right_buffer->left = left_buffer->width;
  3643. right_buffer->width = global_config.term_width - left_buffer->width;
  3644. }
  3645. /**
  3646. * Update screen size
  3647. */
  3648. void update_screen_size(void) {
  3649. struct winsize w;
  3650. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  3651. global_config.term_width = w.ws_col;
  3652. global_config.term_height = w.ws_row;
  3653. if (env) {
  3654. if (left_buffer) {
  3655. update_split_size();
  3656. } else if (env != left_buffer && env != right_buffer) {
  3657. env->width = w.ws_col;
  3658. }
  3659. }
  3660. }
  3661. /**
  3662. * Handle terminal size changes
  3663. */
  3664. void SIGWINCH_handler(int sig) {
  3665. (void)sig;
  3666. update_screen_size();
  3667. redraw_all();
  3668. signal(SIGWINCH, SIGWINCH_handler);
  3669. }
  3670. /**
  3671. * Handle suspend
  3672. */
  3673. void SIGTSTP_handler(int sig) {
  3674. (void)sig;
  3675. mouse_disable();
  3676. set_buffered();
  3677. reset();
  3678. clear_screen();
  3679. show_cursor();
  3680. unset_alternate_screen();
  3681. fflush(stdout);
  3682. signal(SIGTSTP, SIG_DFL);
  3683. raise(SIGTSTP);
  3684. }
  3685. void SIGCONT_handler(int sig) {
  3686. (void)sig;
  3687. set_alternate_screen();
  3688. set_unbuffered();
  3689. mouse_enable();
  3690. redraw_all();
  3691. signal(SIGCONT, SIGCONT_handler);
  3692. signal(SIGTSTP, SIGTSTP_handler);
  3693. }
  3694. /**
  3695. * Move the cursor to a specific line.
  3696. */
  3697. void goto_line(int line) {
  3698. /* Respect file bounds */
  3699. if (line < 1) line = 1;
  3700. if (line > env->line_count) line = env->line_count;
  3701. /* Move the cursor / text region offsets */
  3702. env->coffset = 0;
  3703. env->offset = line - 1;
  3704. env->line_no = line;
  3705. env->col_no = 1;
  3706. redraw_most();
  3707. }
  3708. /**
  3709. * UTF-8 parser state
  3710. */
  3711. static uint32_t codepoint_r;
  3712. static uint32_t state = 0;
  3713. #define UTF8_ACCEPT 0
  3714. #define UTF8_REJECT 1
  3715. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  3716. static int state_table[32] = {
  3717. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  3718. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  3719. 2,2,2,2, /* 110xxxxx */
  3720. 3,3, /* 1110xxxx */
  3721. 4, /* 11110xxx */
  3722. 1 /* 11111xxx */
  3723. };
  3724. static int mask_bytes[32] = {
  3725. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  3726. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  3727. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  3728. 0x1F,0x1F,0x1F,0x1F,
  3729. 0x0F,0x0F,
  3730. 0x07,
  3731. 0x00
  3732. };
  3733. static int next[5] = {
  3734. 0,
  3735. 1,
  3736. 0,
  3737. 2,
  3738. 3
  3739. };
  3740. if (*state == UTF8_ACCEPT) {
  3741. *codep = byte & mask_bytes[byte >> 3];
  3742. *state = state_table[byte >> 3];
  3743. } else if (*state > 0) {
  3744. *codep = (byte & 0x3F) | (*codep << 6);
  3745. *state = next[*state];
  3746. }
  3747. return *state;
  3748. }
  3749. /**
  3750. * Processs (part of) a file and add it to a buffer.
  3751. */
  3752. void add_buffer(uint8_t * buf, int size) {
  3753. for (int i = 0; i < size; ++i) {
  3754. if (!decode(&state, &codepoint_r, buf[i])) {
  3755. uint32_t c = codepoint_r;
  3756. if (c == '\n') {
  3757. env->lines = add_line(env->lines, env->line_no);
  3758. env->col_no = 1;
  3759. env->line_no += 1;
  3760. } else {
  3761. char_t _c;
  3762. _c.codepoint = (uint32_t)c;
  3763. _c.flags = 0;
  3764. _c.display_width = codepoint_width((wchar_t)c);
  3765. line_t * line = env->lines[env->line_no - 1];
  3766. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3767. if (line != nline) {
  3768. env->lines[env->line_no - 1] = nline;
  3769. }
  3770. env->col_no += 1;
  3771. }
  3772. } else if (state == UTF8_REJECT) {
  3773. state = 0;
  3774. }
  3775. }
  3776. }
  3777. struct syntax_definition * match_syntax(char * file) {
  3778. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3779. for (char ** ext = s->ext; *ext; ++ext) {
  3780. int i = strlen(file);
  3781. int j = strlen(*ext);
  3782. do {
  3783. if (file[i] != (*ext)[j]) break;
  3784. if (j == 0) return s;
  3785. if (i == 0) break;
  3786. i--;
  3787. j--;
  3788. } while (1);
  3789. }
  3790. }
  3791. return NULL;
  3792. }
  3793. /**
  3794. * Check if a string is all numbers.
  3795. */
  3796. int is_all_numbers(const char * c) {
  3797. while (*c) {
  3798. if (!isdigit(*c)) return 0;
  3799. c++;
  3800. }
  3801. return 1;
  3802. }
  3803. /**
  3804. * Create a new buffer from a file.
  3805. */
  3806. void open_file(char * file) {
  3807. env = buffer_new();
  3808. env->width = global_config.term_width;
  3809. env->left = 0;
  3810. env->loading = 1;
  3811. setup_buffer(env);
  3812. FILE * f;
  3813. int init_line = -1;
  3814. if (!strcmp(file,"-")) {
  3815. /**
  3816. * Read file from stdin. stderr provides terminal input.
  3817. */
  3818. f = stdin;
  3819. global_config.tty_in = STDERR_FILENO;
  3820. env->modified = 1;
  3821. } else {
  3822. char * l = strrchr(file, ':');
  3823. if (l && is_all_numbers(l+1)) {
  3824. *l = '\0';
  3825. l++;
  3826. init_line = atoi(l);
  3827. }
  3828. struct stat statbuf;
  3829. if (!stat(file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3830. DIR * dirp = opendir(file);
  3831. if (!dirp) {
  3832. env->loading = 0;
  3833. return;
  3834. }
  3835. struct dirent * ent = readdir(dirp);
  3836. while (ent) {
  3837. add_buffer((unsigned char*)ent->d_name, strlen(ent->d_name));
  3838. add_buffer((unsigned char*)"\n",1);
  3839. ent = readdir(dirp);
  3840. }
  3841. closedir(dirp);
  3842. env->file_name = strdup(file);
  3843. env->readonly = 1;
  3844. env->loading = 0;
  3845. return;
  3846. }
  3847. f = fopen(file, "r");
  3848. env->file_name = strdup(file);
  3849. }
  3850. if (!f) {
  3851. if (global_config.hilight_on_open) {
  3852. env->syntax = match_syntax(file);
  3853. }
  3854. env->loading = 0;
  3855. if (global_config.go_to_line) {
  3856. goto_line(1);
  3857. }
  3858. if (env->syntax && env->syntax->prefers_spaces) {
  3859. env->tabs = 0;
  3860. }
  3861. return;
  3862. }
  3863. uint8_t buf[BLOCK_SIZE];
  3864. state = 0;
  3865. while (!feof(f) && !ferror(f)) {
  3866. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3867. add_buffer(buf, r);
  3868. }
  3869. if (ferror(f)) {
  3870. env->loading = 0;
  3871. return;
  3872. }
  3873. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3874. /* Remove blank line from end */
  3875. remove_line(env->lines, env->line_no-1);
  3876. }
  3877. if (global_config.hilight_on_open) {
  3878. env->syntax = match_syntax(file);
  3879. for (int i = 0; i < env->line_count; ++i) {
  3880. recalculate_syntax(env->lines[i],i);
  3881. }
  3882. }
  3883. /* Try to automatically figure out tabs vs. spaces */
  3884. int tabs = 0, spaces = 0;
  3885. for (int i = 0; i < env->line_count; ++i) {
  3886. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3887. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3888. if (env->lines[i]->text[0].codepoint == ' ' &&
  3889. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3890. spaces++;
  3891. }
  3892. }
  3893. if (spaces > tabs) {
  3894. env->tabs = 0;
  3895. }
  3896. /* TODO figure out tabstop for spaces? */
  3897. env->loading = 0;
  3898. if (global_config.check_git) {
  3899. env->checkgitstatusonwrite = 1;
  3900. git_examine(file);
  3901. }
  3902. for (int i = 0; i < env->line_count; ++i) {
  3903. recalculate_tabs(env->lines[i]);
  3904. }
  3905. if (global_config.go_to_line) {
  3906. if (init_line != -1) {
  3907. goto_line(init_line);
  3908. } else {
  3909. env->line_no = 1;
  3910. env->col_no = 1;
  3911. fetch_from_biminfo(env);
  3912. redraw_all();
  3913. place_cursor_actual();
  3914. set_preferred_column();
  3915. }
  3916. }
  3917. fclose(f);
  3918. }
  3919. /**
  3920. * Clean up the terminal and exit the editor.
  3921. */
  3922. void quit(void) {
  3923. mouse_disable();
  3924. set_buffered();
  3925. reset();
  3926. clear_screen();
  3927. show_cursor();
  3928. unset_alternate_screen();
  3929. exit(0);
  3930. }
  3931. /**
  3932. * Try to quit, but don't continue if there are
  3933. * modified buffers open.
  3934. */
  3935. void try_quit(void) {
  3936. for (int i = 0; i < buffers_len; i++ ) {
  3937. buffer_t * _env = buffers[i];
  3938. if (_env->modified) {
  3939. if (_env->file_name) {
  3940. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3941. } else {
  3942. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3943. }
  3944. return;
  3945. }
  3946. }
  3947. /* Close all buffers */
  3948. while (buffers_len) {
  3949. buffer_close(buffers[0]);
  3950. }
  3951. quit();
  3952. }
  3953. /**
  3954. * Switch to the previous buffer
  3955. */
  3956. void previous_tab(void) {
  3957. buffer_t * last = NULL;
  3958. for (int i = 0; i < buffers_len; i++) {
  3959. buffer_t * _env = buffers[i];
  3960. if (_env == env) {
  3961. if (last) {
  3962. /* Wrap around */
  3963. env = last;
  3964. redraw_all();
  3965. return;
  3966. } else {
  3967. env = buffers[buffers_len-1];
  3968. redraw_all();
  3969. return;
  3970. }
  3971. }
  3972. last = _env;
  3973. }
  3974. }
  3975. /**
  3976. * Switch to the next buffer
  3977. */
  3978. void next_tab(void) {
  3979. for (int i = 0; i < buffers_len; i++) {
  3980. buffer_t * _env = buffers[i];
  3981. if (_env == env) {
  3982. if (i != buffers_len - 1) {
  3983. env = buffers[i+1];
  3984. redraw_all();
  3985. return;
  3986. } else {
  3987. /* Wrap around */
  3988. env = buffers[0];
  3989. redraw_all();
  3990. return;
  3991. }
  3992. }
  3993. }
  3994. }
  3995. /**
  3996. * Check for modified lines in a file by examining `git diff` output.
  3997. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3998. */
  3999. int git_examine(char * filename) {
  4000. if (env->modified) return 1;
  4001. #ifndef __toaru__
  4002. int fds[2];
  4003. pipe(fds);
  4004. int child = fork();
  4005. if (child == 0) {
  4006. FILE * dev_null = fopen("/dev/null","w");
  4007. close(fds[0]);
  4008. dup2(fds[1], STDOUT_FILENO);
  4009. dup2(fileno(dev_null), STDERR_FILENO);
  4010. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  4011. exit(execvp("git",args));
  4012. } else if (child < 0) {
  4013. return 1;
  4014. }
  4015. close(fds[1]);
  4016. FILE * f = fdopen(fds[0],"r");
  4017. int line_offset = 0;
  4018. int line_count = 0;
  4019. int lines_to_pull = 0;
  4020. int line_no = 0;
  4021. int pre_count = 0;
  4022. while (!feof(f)) {
  4023. int c = fgetc(f);
  4024. if (c < 0) break;
  4025. if (lines_to_pull > 0 && line_offset == 0) {
  4026. if (c != '-') {
  4027. if (c == '+') {
  4028. if (pre_count == lines_to_pull) {
  4029. env->lines[line_no-1]->rev_status = 3;
  4030. } else {
  4031. env->lines[line_no-1]->rev_status = 1;
  4032. }
  4033. }
  4034. lines_to_pull--;
  4035. pre_count--;
  4036. line_no++;
  4037. }
  4038. } else if (c == '@' && line_offset == 0) {
  4039. /* Read line offset, count */
  4040. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  4041. while (isdigit(c = fgetc(f)));
  4042. if (c != ',') {
  4043. fscanf(f,"%d",&line_no);
  4044. pre_count = 1;
  4045. } else {
  4046. while ((c = fgetc(f)) == ',');
  4047. ungetc(c,f);
  4048. fscanf(f,"%d",&pre_count);
  4049. }
  4050. while ((c = fgetc(f)) == ' ');
  4051. ungetc(c,f);
  4052. /* Read one integer */
  4053. fscanf(f,"%d",&line_no);
  4054. lines_to_pull = 1;
  4055. if (fgetc(f) == ',') {
  4056. fscanf(f,"%d",&lines_to_pull);
  4057. }
  4058. }
  4059. }
  4060. if (c == '\n') {
  4061. line_offset = 0;
  4062. line_count++;
  4063. continue;
  4064. }
  4065. line_offset++;
  4066. }
  4067. fclose(f);
  4068. #endif
  4069. return 0;
  4070. }
  4071. /**
  4072. * Write active buffer to file
  4073. */
  4074. void write_file(char * file) {
  4075. if (!file) {
  4076. render_error("Need a file to write to.");
  4077. return;
  4078. }
  4079. FILE * f = fopen(file, "w+");
  4080. if (!f) {
  4081. render_error("Failed to open file for writing.");
  4082. return;
  4083. }
  4084. /* Go through each line and convert it back to UTF-8 */
  4085. int i, j;
  4086. for (i = 0; i < env->line_count; ++i) {
  4087. line_t * line = env->lines[i];
  4088. line->rev_status = 0;
  4089. for (j = 0; j < line->actual; j++) {
  4090. char_t c = line->text[j];
  4091. if (c.codepoint == 0) {
  4092. char buf[1] = {0};
  4093. fwrite(buf, 1, 1, f);
  4094. } else {
  4095. char tmp[8] = {0};
  4096. int i = to_eight(c.codepoint, tmp);
  4097. fwrite(tmp, i, 1, f);
  4098. }
  4099. }
  4100. fputc('\n', f);
  4101. }
  4102. fclose(f);
  4103. /* Mark it no longer modified */
  4104. env->modified = 0;
  4105. env->last_save_history = env->history;
  4106. /* If there was no file name set, set one */
  4107. if (!env->file_name) {
  4108. env->file_name = malloc(strlen(file) + 1);
  4109. memcpy(env->file_name, file, strlen(file) + 1);
  4110. }
  4111. if (env->checkgitstatusonwrite) {
  4112. git_examine(file);
  4113. }
  4114. update_title();
  4115. redraw_all();
  4116. }
  4117. /**
  4118. * Close the active buffer
  4119. */
  4120. void close_buffer(void) {
  4121. buffer_t * previous_env = env;
  4122. buffer_t * new_env = buffer_close(env);
  4123. if (new_env == previous_env) {
  4124. /* ?? Failed to close buffer */
  4125. render_error("lolwat");
  4126. }
  4127. if (left_buffer && env == left_buffer) {
  4128. left_buffer = NULL;
  4129. right_buffer->left = 0;
  4130. right_buffer->width = global_config.term_width;
  4131. right_buffer = NULL;
  4132. } else if (left_buffer && env == right_buffer) {
  4133. right_buffer = NULL;
  4134. left_buffer->left = 0;
  4135. left_buffer->width = global_config.term_width;
  4136. left_buffer = NULL;
  4137. }
  4138. /* No more buffers, exit */
  4139. if (!new_env) {
  4140. quit();
  4141. }
  4142. /* Set the new active buffer */
  4143. env = new_env;
  4144. /* Redraw the screen */
  4145. redraw_all();
  4146. }
  4147. void set_preferred_column(void) {
  4148. int c = 0;
  4149. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  4150. c += env->lines[env->line_no-1]->text[i].display_width;
  4151. }
  4152. env->preferred_column = c;
  4153. }
  4154. /**
  4155. * Move the cursor down one line in the text region
  4156. */
  4157. void cursor_down(void) {
  4158. /* If this isn't already the last line... */
  4159. if (env->line_no < env->line_count) {
  4160. /* Move the cursor down */
  4161. env->line_no += 1;
  4162. /* Try to place the cursor horizontally at the preferred column */
  4163. int _x = 0;
  4164. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4165. char_t * c = &env->lines[env->line_no-1]->text[i];
  4166. _x += c->display_width;
  4167. env->col_no = i+1;
  4168. if (_x > env->preferred_column) {
  4169. break;
  4170. }
  4171. }
  4172. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4173. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4174. }
  4175. /*
  4176. * If the horizontal cursor position exceeds the width the new line,
  4177. * then move the cursor left to the extent of the new line.
  4178. *
  4179. * If we're in insert mode, we can go one cell beyond the end of the line
  4180. */
  4181. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4182. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4183. if (env->col_no == 0) env->col_no = 1;
  4184. }
  4185. /*
  4186. * If the screen was scrolled horizontally, unscroll it;
  4187. * if it will be scrolled on this line as well, that will
  4188. * be handled by place_cursor_actual
  4189. */
  4190. int redraw = 0;
  4191. if (env->coffset != 0) {
  4192. env->coffset = 0;
  4193. redraw = 1;
  4194. }
  4195. /* If we've scrolled past the bottom of the screen, scroll the screen */
  4196. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  4197. env->offset += 1;
  4198. /* Tell terminal to scroll */
  4199. if (global_config.can_scroll && !left_buffer) {
  4200. shift_up();
  4201. /* A new line appears on screen at the bottom, draw it */
  4202. int l = global_config.term_height - global_config.bottom_size - 1;
  4203. if (env->offset + l < env->line_count + 1) {
  4204. redraw_line(l-1, env->offset + l-1);
  4205. } else {
  4206. draw_excess_line(l - 1);
  4207. }
  4208. } else {
  4209. redraw_text();
  4210. }
  4211. redraw_tabbar();
  4212. redraw_statusbar();
  4213. redraw_commandline();
  4214. place_cursor_actual();
  4215. return;
  4216. } else if (redraw) {
  4217. /* Otherwise, if we need to redraw because of coffset change, do that */
  4218. redraw_text();
  4219. }
  4220. /* Update the status bar */
  4221. redraw_statusbar();
  4222. /* Place the terminal cursor again */
  4223. place_cursor_actual();
  4224. }
  4225. }
  4226. /**
  4227. * Move the cursor up one line in the text region
  4228. */
  4229. void cursor_up(void) {
  4230. /* If this isn't the first line already */
  4231. if (env->line_no > 1) {
  4232. /* Move the cursor down */
  4233. env->line_no -= 1;
  4234. /* Try to place the cursor horizontally at the preferred column */
  4235. int _x = 0;
  4236. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4237. char_t * c = &env->lines[env->line_no-1]->text[i];
  4238. _x += c->display_width;
  4239. env->col_no = i+1;
  4240. if (_x > env->preferred_column) {
  4241. break;
  4242. }
  4243. }
  4244. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4245. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4246. }
  4247. /*
  4248. * If the horizontal cursor position exceeds the width the new line,
  4249. * then move the cursor left to the extent of the new line.
  4250. *
  4251. * If we're in insert mode, we can go one cell beyond the end of the line
  4252. */
  4253. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4254. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4255. if (env->col_no == 0) env->col_no = 1;
  4256. }
  4257. /*
  4258. * If the screen was scrolled horizontally, unscroll it;
  4259. * if it will be scrolled on this line as well, that will
  4260. * be handled by place_cursor_actual
  4261. */
  4262. int redraw = 0;
  4263. if (env->coffset != 0) {
  4264. env->coffset = 0;
  4265. redraw = 1;
  4266. }
  4267. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  4268. if (env->line_no <= e) {
  4269. env->offset -= 1;
  4270. /* Tell terminal to scroll */
  4271. if (global_config.can_scroll && !left_buffer) {
  4272. shift_down();
  4273. /*
  4274. * The line at the top of the screen should always be real
  4275. * so we can just call redraw_line here
  4276. */
  4277. redraw_line(0,env->offset);
  4278. } else {
  4279. redraw_text();
  4280. }
  4281. redraw_tabbar();
  4282. redraw_statusbar();
  4283. redraw_commandline();
  4284. place_cursor_actual();
  4285. return;
  4286. } else if (redraw) {
  4287. /* Otherwise, if we need to redraw because of coffset change, do that */
  4288. redraw_text();
  4289. }
  4290. /* Update the status bar */
  4291. redraw_statusbar();
  4292. /* Place the terminal cursor again */
  4293. place_cursor_actual();
  4294. }
  4295. }
  4296. /**
  4297. * Move the cursor one column left.
  4298. */
  4299. void cursor_left(void) {
  4300. if (env->col_no > 1) {
  4301. env->col_no -= 1;
  4302. /* Update the status bar */
  4303. redraw_statusbar();
  4304. /* Place the terminal cursor again */
  4305. place_cursor_actual();
  4306. }
  4307. set_preferred_column();
  4308. }
  4309. /**
  4310. * Move the cursor one column right.
  4311. */
  4312. void cursor_right(void) {
  4313. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  4314. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  4315. env->col_no += 1;
  4316. /* Update the status bar */
  4317. redraw_statusbar();
  4318. /* Place the terminal cursor again */
  4319. place_cursor_actual();
  4320. }
  4321. set_preferred_column();
  4322. }
  4323. /**
  4324. * Move the cursor to the fron the of the line
  4325. */
  4326. void cursor_home(void) {
  4327. env->col_no = 1;
  4328. set_preferred_column();
  4329. /* Update the status bar */
  4330. redraw_statusbar();
  4331. /* Place the terminal cursor again */
  4332. place_cursor_actual();
  4333. }
  4334. /**
  4335. * Move the cursor to the end of the line.
  4336. *
  4337. * In INSERT mode, moves one cell right of the end of the line.
  4338. * In NORMAL mode, moves the cursor to the last occupied cell.
  4339. */
  4340. void cursor_end(void) {
  4341. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4342. set_preferred_column();
  4343. /* Update the status bar */
  4344. redraw_statusbar();
  4345. /* Place the terminal cursor again */
  4346. place_cursor_actual();
  4347. }
  4348. /**
  4349. * Leave INSERT mode
  4350. *
  4351. * If the cursor is too far right, adjust it.
  4352. * Redraw the command line.
  4353. */
  4354. void leave_insert(void) {
  4355. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4356. env->col_no = env->lines[env->line_no-1]->actual;
  4357. if (env->col_no == 0) env->col_no = 1;
  4358. set_preferred_column();
  4359. }
  4360. set_history_break();
  4361. env->mode = MODE_NORMAL;
  4362. redraw_commandline();
  4363. }
  4364. int search_matches(uint32_t a, uint32_t b, int mode) {
  4365. if (mode == 0) {
  4366. return a == b;
  4367. } else if (mode == 1) {
  4368. return tolower(a) == tolower(b);
  4369. }
  4370. return 0;
  4371. }
  4372. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4373. line_t * line = env->lines[line_no-1];
  4374. int j = col;
  4375. while (j < line->actual + 1) {
  4376. int k = j;
  4377. uint32_t * match = needle;
  4378. while (k < line->actual + 1) {
  4379. if (*match == '\0') {
  4380. /* Perform replacement */
  4381. for (uint32_t * n = needle; *n; ++n) {
  4382. line_delete(line, j+1, line_no-1);
  4383. }
  4384. int t = 0;
  4385. for (uint32_t * r = replacement; *r; ++r) {
  4386. char_t _c;
  4387. _c.codepoint = *r;
  4388. _c.flags = 0;
  4389. _c.display_width = codepoint_width(*r);
  4390. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4391. if (line != nline) {
  4392. env->lines[line_no-1] = nline;
  4393. line = nline;
  4394. }
  4395. t++;
  4396. }
  4397. *out_col = j + t;
  4398. set_modified();
  4399. return;
  4400. }
  4401. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  4402. match++;
  4403. k++;
  4404. }
  4405. j++;
  4406. }
  4407. *out_col = -1;
  4408. }
  4409. #define COMMAND_HISTORY_MAX 255
  4410. char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4411. void insert_command_history(char * cmd) {
  4412. /* See if this is already in the history. */
  4413. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4414. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4415. if (!strcmp(command_history[i], cmd)) {
  4416. free(command_history[i]);
  4417. amount_to_shift = i;
  4418. break;
  4419. }
  4420. }
  4421. /* Remove last entry that will roll off the stack */
  4422. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4423. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4424. }
  4425. /* Roll the history */
  4426. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4427. command_history[0] = strdup(cmd);
  4428. }
  4429. /**
  4430. * Process a user command.
  4431. */
  4432. void process_command(char * cmd) {
  4433. /* Special case ! to run shell commands without parsing tokens */
  4434. int c;
  4435. /* Add command to history */
  4436. insert_command_history(cmd);
  4437. if (*cmd == '!') {
  4438. /* Reset and draw some line feeds */
  4439. reset();
  4440. printf("\n\n");
  4441. /* Set buffered for shell application */
  4442. set_buffered();
  4443. /* Call the shell and wait for completion */
  4444. system(&cmd[1]);
  4445. /* Return to the editor, wait for user to press enter. */
  4446. set_unbuffered();
  4447. printf("\n\nPress ENTER to continue.");
  4448. fflush(stdout);
  4449. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4450. /* Redraw the screen */
  4451. redraw_all();
  4452. /* Done processing command */
  4453. return;
  4454. }
  4455. /* Arguments aren't really tokenized, but the first command before a space is extracted */
  4456. char *argv[512]; /* If a specific command wants to tokenize further, it can do that later. */
  4457. int argc = 0;
  4458. argv[0] = cmd;
  4459. if (*cmd) argc++;
  4460. /* Collect up until first space for argv[0] */
  4461. for (char * c = cmd; *c; ++c) {
  4462. if (*c == ' ') {
  4463. *c = '\0';
  4464. argv[1] = c+1;
  4465. if (*argv[1]) argc++;
  4466. break;
  4467. }
  4468. }
  4469. argv[argc] = NULL;
  4470. if (argc < 1) {
  4471. /* no op */
  4472. return;
  4473. }
  4474. int all_lines = 0;
  4475. if (argv[0][0] == '%') {
  4476. all_lines = 1;
  4477. argv[0]++;
  4478. }
  4479. if (!strcmp(argv[0], "e")) {
  4480. /* e: edit file */
  4481. if (argc > 1) {
  4482. /* This actually opens a new tab */
  4483. open_file(argv[1]);
  4484. update_title();
  4485. } else {
  4486. if (env->modified) {
  4487. render_error("File is modified, can not reload.");
  4488. return;
  4489. }
  4490. buffer_t * old_env = env;
  4491. open_file(env->file_name);
  4492. buffer_t * new_env = env;
  4493. env = old_env;
  4494. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4495. SWAP(line_t **, env->lines, new_env->lines);
  4496. SWAP(int, env->line_count, new_env->line_count);
  4497. SWAP(int, env->line_avail, new_env->line_avail);
  4498. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4499. redraw_all();
  4500. }
  4501. } else if (!strcmp(argv[0], "s")) {
  4502. if (argc < 2) {
  4503. render_error("expected substitution argument");
  4504. return;
  4505. }
  4506. /* Substitution */
  4507. int range_top, range_bot;
  4508. if (env->mode == MODE_LINE_SELECTION) {
  4509. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4510. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4511. } else if (all_lines) {
  4512. range_top = 1;
  4513. range_bot = env->line_count;
  4514. } else {
  4515. range_top = env->line_no;
  4516. range_bot = env->line_no;
  4517. }
  4518. /* Determine replacement parameters */
  4519. char divider = argv[1][0];
  4520. char * needle = &argv[1][1];
  4521. char * c = needle;
  4522. char * replacement = NULL;
  4523. char * options = "";
  4524. while (*c) {
  4525. if (*c == divider) {
  4526. *c = '\0';
  4527. replacement = c + 1;
  4528. break;
  4529. }
  4530. c++;
  4531. }
  4532. if (!replacement) {
  4533. render_error("nothing to replace with");
  4534. return;
  4535. }
  4536. c = replacement;
  4537. while (*c) {
  4538. if (*c == divider) {
  4539. *c = '\0';
  4540. options = c + 1;
  4541. break;
  4542. }
  4543. c++;
  4544. }
  4545. int global = 0;
  4546. int case_insensitive = 0;
  4547. /* Parse options */
  4548. while (*options) {
  4549. switch (*options) {
  4550. case 'g':
  4551. global = 1;
  4552. break;
  4553. case 'i':
  4554. case_insensitive = 1;
  4555. break;
  4556. }
  4557. options++;
  4558. }
  4559. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4560. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4561. {
  4562. int i = 0;
  4563. uint32_t c, state = 0;
  4564. for (char * cin = needle; *cin; cin++) {
  4565. if (!decode(&state, &c, *cin)) {
  4566. needle_c[i] = c;
  4567. i++;
  4568. } else if (state == UTF8_REJECT) {
  4569. state = 0;
  4570. }
  4571. }
  4572. needle_c[i] = 0;
  4573. i = 0;
  4574. c = 0;
  4575. state = 0;
  4576. for (char * cin = replacement; *cin; cin++) {
  4577. if (!decode(&state, &c, *cin)) {
  4578. replacement_c[i] = c;
  4579. i++;
  4580. } else if (state == UTF8_REJECT) {
  4581. state = 0;
  4582. }
  4583. }
  4584. replacement_c[i] = 0;
  4585. }
  4586. int replacements = 0;
  4587. for (int line = range_top; line <= range_bot; ++line) {
  4588. int col = 0;
  4589. while (col != -1) {
  4590. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4591. if (col != -1) replacements++;
  4592. if (!global) break;
  4593. }
  4594. }
  4595. free(needle_c);
  4596. free(replacement_c);
  4597. if (replacements) {
  4598. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4599. set_history_break();
  4600. redraw_text();
  4601. } else {
  4602. render_error("Pattern not found: %s", needle);
  4603. }
  4604. } else if (!strcmp(argv[0], "tabnew")) {
  4605. if (argc > 1) {
  4606. open_file(argv[1]);
  4607. update_title();
  4608. } else {
  4609. env = buffer_new();
  4610. setup_buffer(env);
  4611. redraw_all();
  4612. update_title();
  4613. }
  4614. } else if (!strcmp(argv[0], "w")) {
  4615. /* w: write file */
  4616. if (argc > 1) {
  4617. write_file(argv[1]);
  4618. } else {
  4619. write_file(env->file_name);
  4620. }
  4621. } else if (!strcmp(argv[0], "history")) {
  4622. render_commandline_message(""); /* To clear command line */
  4623. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4624. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4625. }
  4626. render_commandline_message("\n");
  4627. redraw_tabbar();
  4628. redraw_commandline();
  4629. fflush(stdout);
  4630. int c;
  4631. while ((c = bim_getch())== -1);
  4632. bim_unget(c);
  4633. redraw_all();
  4634. } else if (!strcmp(argv[0], "wq")) {
  4635. /* wq: write file and close buffer; if there's no file to write to, may do weird things */
  4636. write_file(env->file_name);
  4637. close_buffer();
  4638. } else if (!strcmp(argv[0], "q")) {
  4639. /* close buffer if unmodified */
  4640. if (left_buffer && left_buffer == right_buffer) {
  4641. unsplit();
  4642. return;
  4643. }
  4644. if (env->modified) {
  4645. render_error("No write since last change. Use :q! to force exit.");
  4646. } else {
  4647. close_buffer();
  4648. }
  4649. } else if (!strcmp(argv[0], "q!")) {
  4650. /* close buffer without warning if unmodified */
  4651. close_buffer();
  4652. } else if (!strcmp(argv[0], "qa") || !strcmp(argv[0], "qall")) {
  4653. /* Close all */
  4654. try_quit();
  4655. } else if (!strcmp(argv[0], "qa!")) {
  4656. /* Forcefully exit editor */
  4657. while (buffers_len) {
  4658. buffer_close(buffers[0]);
  4659. }
  4660. quit();
  4661. } else if (!strcmp(argv[0], "tabp")) {
  4662. /* Next tab */
  4663. previous_tab();
  4664. update_title();
  4665. } else if (!strcmp(argv[0], "tabn")) {
  4666. /* Previous tab */
  4667. next_tab();
  4668. update_title();
  4669. } else if (!strcmp(argv[0], "git")) {
  4670. if (argc < 2) {
  4671. render_status_message("git=%d", env->checkgitstatusonwrite);
  4672. } else {
  4673. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4674. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4675. git_examine(env->file_name);
  4676. redraw_text();
  4677. }
  4678. }
  4679. } else if (!strcmp(argv[0], "colorgutter")) {
  4680. if (argc < 2) {
  4681. render_status_message("colorgutter=%d", global_config.color_gutter);
  4682. } else {
  4683. global_config.color_gutter = !!atoi(argv[1]);
  4684. redraw_text();
  4685. }
  4686. } else if (!strcmp(argv[0], "indent")) {
  4687. env->indent = 1;
  4688. redraw_statusbar();
  4689. } else if (!strcmp(argv[0], "noindent")) {
  4690. env->indent = 0;
  4691. redraw_statusbar();
  4692. } else if (!strcmp(argv[0], "cursorcolumn")) {
  4693. render_status_message("cursorcolumn=%d", env->preferred_column);
  4694. } else if (!strcmp(argv[0], "noh")) {
  4695. if (env->search) {
  4696. free(env->search);
  4697. env->search = NULL;
  4698. for (int i = 0; i < env->line_count; ++i) {
  4699. recalculate_syntax(env->lines[i],i);
  4700. }
  4701. redraw_text();
  4702. }
  4703. } else if (!strcmp(argv[0], "help")) {
  4704. /*
  4705. * The repeated calls to redraw_commandline here make use
  4706. * of scrolling to draw this multiline help message on
  4707. * the same background as the command line.
  4708. */
  4709. render_commandline_message(""); /* To clear command line */
  4710. render_commandline_message("\n");
  4711. render_commandline_message(" \033[1mbim - The standard ToaruOS Text Editor\033[22m\n");
  4712. render_commandline_message("\n");
  4713. render_commandline_message(" Available commands:\n");
  4714. render_commandline_message(" Quit with \033[3m:q\033[23m, \033[3m:qa\033[23m, \033[3m:q!\033[23m, \033[3m:qa!\033[23m\n");
  4715. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4716. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4717. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4718. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4719. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4720. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4721. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4722. render_commandline_message("\n");
  4723. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4724. render_commandline_message("\n");
  4725. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4726. redraw_tabbar();
  4727. redraw_commandline();
  4728. fflush(stdout);
  4729. /* Wait for a character so we can redraw the screen before continuing */
  4730. int c;
  4731. while ((c = bim_getch())== -1);
  4732. /* Make sure that key press actually gets used */
  4733. bim_unget(c);
  4734. /*
  4735. * Redraw everything to hide the help message and get the
  4736. * upper few lines of text on screen again
  4737. */
  4738. redraw_all();
  4739. } else if (!strcmp(argv[0], "theme")) {
  4740. if (argc < 2) {
  4741. render_status_message("theme=%s", current_theme);
  4742. return;
  4743. }
  4744. for (struct theme_def * d = themes; d->name; ++d) {
  4745. if (!strcmp(argv[1], d->name)) {
  4746. d->load();
  4747. redraw_all();
  4748. return;
  4749. }
  4750. }
  4751. } else if (!strcmp(argv[0], "splitpercent")) {
  4752. if (argc < 2) {
  4753. render_status_message("splitpercent=%d", global_config.split_percent);
  4754. return;
  4755. } else {
  4756. global_config.split_percent = atoi(argv[1]);
  4757. if (left_buffer) {
  4758. update_split_size();
  4759. redraw_all();
  4760. }
  4761. }
  4762. } else if (!strcmp(argv[0], "split")) {
  4763. if (argc < 2 && buffers_len == 1) {
  4764. left_buffer = buffers[0];
  4765. right_buffer = buffers[0];
  4766. update_split_size();
  4767. redraw_all();
  4768. } else if ((argc < 2 && buffers_len != 2) || (argc == 2 && buffers_len != 1)) {
  4769. render_error("(splits are experimental and only work with two buffers; sorry!)");
  4770. return;
  4771. } else {
  4772. if (argc == 2) {
  4773. open_file(argv[1]);
  4774. }
  4775. left_buffer = buffers[0];
  4776. right_buffer = buffers[1];
  4777. update_split_size();
  4778. redraw_alt_buffer(left_buffer);
  4779. redraw_alt_buffer(right_buffer);
  4780. }
  4781. } else if (!strcmp(argv[0], "unsplit")) {
  4782. unsplit();
  4783. } else if (!strcmp(argv[0], "syntax")) {
  4784. if (argc < 2) {
  4785. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  4786. return;
  4787. }
  4788. if (!strcmp(argv[1],"none")) {
  4789. for (int i = 0; i < env->line_count; ++i) {
  4790. env->lines[i]->istate = 0;
  4791. for (int j = 0; j < env->lines[i]->actual; ++j) {
  4792. env->lines[i]->text[j].flags = 0;
  4793. }
  4794. }
  4795. redraw_all();
  4796. return;
  4797. }
  4798. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  4799. if (!strcmp(argv[1],s->name)) {
  4800. env->syntax = s;
  4801. for (int i = 0; i < env->line_count; ++i) {
  4802. env->lines[i]->istate = 0;
  4803. }
  4804. for (int i = 0; i < env->line_count; ++i) {
  4805. recalculate_syntax(env->lines[i],i);
  4806. }
  4807. redraw_all();
  4808. return;
  4809. }
  4810. }
  4811. render_error("unrecognized syntax type");
  4812. } else if (!strcmp(argv[0], "recalc")) {
  4813. for (int i = 0; i < env->line_count; ++i) {
  4814. env->lines[i]->istate = 0;
  4815. }
  4816. env->loading = 1;
  4817. for (int i = 0; i < env->line_count; ++i) {
  4818. recalculate_syntax(env->lines[i],i);
  4819. }
  4820. env->loading = 0;
  4821. redraw_all();
  4822. } else if (!strcmp(argv[0], "tabs")) {
  4823. env->tabs = 1;
  4824. redraw_statusbar();
  4825. } else if (!strcmp(argv[0], "spaces")) {
  4826. env->tabs = 0;
  4827. redraw_statusbar();
  4828. } else if (!strcmp(argv[0], "tabstop")) {
  4829. if (argc < 2) {
  4830. render_status_message("tabstop=%d", env->tabstop);
  4831. } else {
  4832. int t = atoi(argv[1]);
  4833. if (t > 0 && t < 32) {
  4834. env->tabstop = t;
  4835. for (int i = 0; i < env->line_count; ++i) {
  4836. recalculate_tabs(env->lines[i]);
  4837. }
  4838. redraw_all();
  4839. } else {
  4840. render_error("Invalid tabstop: %s", argv[1]);
  4841. }
  4842. }
  4843. } else if (!strcmp(argv[0], "clearyank")) {
  4844. if (global_config.yanks) {
  4845. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4846. free(global_config.yanks[i]);
  4847. }
  4848. free(global_config.yanks);
  4849. global_config.yanks = NULL;
  4850. global_config.yank_count = 0;
  4851. redraw_statusbar();
  4852. }
  4853. } else if (!strcmp(argv[0], "padding")) {
  4854. if (argc < 2) {
  4855. render_status_message("padding=%d", global_config.cursor_padding);
  4856. } else {
  4857. global_config.cursor_padding = atoi(argv[1]);
  4858. place_cursor_actual();
  4859. }
  4860. } else if (!strcmp(argv[0], "smartcase")) {
  4861. if (argc < 2) {
  4862. render_status_message("smartcase=%d", global_config.smart_case);
  4863. } else {
  4864. global_config.smart_case = atoi(argv[1]);
  4865. place_cursor_actual();
  4866. }
  4867. } else if (!strcmp(argv[0], "hlparen")) {
  4868. if (argc < 2) {
  4869. render_status_message("hlparen=%d", global_config.highlight_parens);
  4870. } else {
  4871. global_config.highlight_parens = atoi(argv[1]);
  4872. for (int i = 0; i < env->line_count; ++i) {
  4873. recalculate_syntax(env->lines[i],i);
  4874. }
  4875. redraw_text();
  4876. place_cursor_actual();
  4877. }
  4878. } else if (!strcmp(argv[0], "hlcurrent")) {
  4879. if (argc < 2) {
  4880. render_status_message("hlcurrent=%d", global_config.hilight_current_line);
  4881. } else {
  4882. global_config.hilight_current_line = atoi(argv[1]);
  4883. if (!global_config.hilight_current_line) {
  4884. for (int i = 0; i < env->line_count; ++i) {
  4885. env->lines[i]->is_current = 0;
  4886. }
  4887. }
  4888. redraw_text();
  4889. place_cursor_actual();
  4890. }
  4891. } else if (isdigit(*argv[0])) {
  4892. /* Go to line number */
  4893. goto_line(atoi(argv[0]));
  4894. } else {
  4895. /* Unrecognized command */
  4896. render_error("Not an editor command: %s", argv[0]);
  4897. }
  4898. }
  4899. /**
  4900. * Tab completion for command mode.
  4901. */
  4902. void command_tab_complete(char * buffer) {
  4903. /* Figure out which argument this is and where it starts */
  4904. int arg = 0;
  4905. char * buf = strdup(buffer);
  4906. char * b = buf;
  4907. char * args[32];
  4908. int candidate_count= 0;
  4909. int candidate_space = 4;
  4910. char ** candidates = malloc(sizeof(char*)*candidate_space);
  4911. /* Accept whitespace before first argument */
  4912. while (*b == ' ') b++;
  4913. char * start = b;
  4914. args[0] = start;
  4915. while (*b && *b != ' ') b++;
  4916. while (*b) {
  4917. while (*b == ' ') {
  4918. *b = '\0';
  4919. b++;
  4920. }
  4921. start = b;
  4922. arg++;
  4923. if (arg < 32) {
  4924. args[arg] = start;
  4925. }
  4926. while (*b && *b != ' ') b++;
  4927. }
  4928. /**
  4929. * Check a possible candidate and add it to the
  4930. * candidates list, expanding as necessary,
  4931. * if it matches for the current argument.
  4932. */
  4933. #define add_candidate(candidate) \
  4934. do { \
  4935. char * _arg = args[arg]; \
  4936. int r = strncmp(_arg, candidate, strlen(_arg)); \
  4937. if (!r) { \
  4938. if (candidate_count == candidate_space) { \
  4939. candidate_space *= 2; \
  4940. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  4941. } \
  4942. candidates[candidate_count] = strdup(candidate); \
  4943. candidate_count++; \
  4944. } \
  4945. } while (0)
  4946. if (arg == 0) {
  4947. /* Complete command names */
  4948. add_candidate("help");
  4949. add_candidate("recalc");
  4950. add_candidate("syntax");
  4951. add_candidate("tabn");
  4952. add_candidate("tabp");
  4953. add_candidate("tabnew");
  4954. add_candidate("theme");
  4955. add_candidate("tabs");
  4956. add_candidate("tabstop");
  4957. add_candidate("spaces");
  4958. add_candidate("noh");
  4959. add_candidate("clearyank");
  4960. add_candidate("indent");
  4961. add_candidate("noindent");
  4962. add_candidate("padding");
  4963. add_candidate("hlparen");
  4964. add_candidate("hlcurrent");
  4965. add_candidate("cursorcolumn");
  4966. add_candidate("smartcase");
  4967. add_candidate("split");
  4968. add_candidate("splitpercent");
  4969. add_candidate("unsplit");
  4970. add_candidate("git");
  4971. add_candidate("colorgutter");
  4972. goto _accept_candidate;
  4973. }
  4974. if (arg == 1 && !strcmp(args[0], "syntax")) {
  4975. /* Complete syntax options */
  4976. add_candidate("none");
  4977. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  4978. add_candidate(s->name);
  4979. }
  4980. goto _accept_candidate;
  4981. }
  4982. if (arg == 1 && !strcmp(args[0], "theme")) {
  4983. /* Complete color theme names */
  4984. for (struct theme_def * s = themes; s->name; ++s) {
  4985. add_candidate(s->name);
  4986. }
  4987. goto _accept_candidate;
  4988. }
  4989. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") || !strcmp(args[0],"split"))) {
  4990. /* Complete file paths */
  4991. /* First, find the deepest directory match */
  4992. char * tmp = strdup(args[arg]);
  4993. char * last_slash = strrchr(tmp, '/');
  4994. DIR * dirp;
  4995. if (last_slash) {
  4996. *last_slash = '\0';
  4997. if (last_slash == tmp) {
  4998. /* Started with slash, and it was the only slash */
  4999. dirp = opendir("/");
  5000. } else {
  5001. dirp = opendir(tmp);
  5002. }
  5003. } else {
  5004. /* No directory match, completing from current directory */
  5005. dirp = opendir(".");
  5006. tmp[0] = '\0';
  5007. }
  5008. if (!dirp) {
  5009. /* Directory match doesn't exist, no candidates to populate */
  5010. free(tmp);
  5011. goto done;
  5012. }
  5013. struct dirent * ent = readdir(dirp);
  5014. while (ent != NULL) {
  5015. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5016. struct stat statbuf;
  5017. /* Figure out if this file is a directory */
  5018. if (last_slash) {
  5019. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5020. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5021. stat(x, &statbuf);
  5022. free(x);
  5023. } else {
  5024. stat(ent->d_name, &statbuf);
  5025. }
  5026. /* Build the complete argument name to tab complete */
  5027. char s[1024] = {0};
  5028. if (last_slash == tmp) {
  5029. strcat(s,"/");
  5030. } else if (*tmp) {
  5031. strcat(s,tmp);
  5032. strcat(s,"/");
  5033. }
  5034. strcat(s,ent->d_name);
  5035. /*
  5036. * If it is a directory, add a / to the end so the next completion
  5037. * attempt will complete the directory's contents.
  5038. */
  5039. if (S_ISDIR(statbuf.st_mode)) {
  5040. strcat(s,"/");
  5041. }
  5042. add_candidate(s);
  5043. }
  5044. ent = readdir(dirp);
  5045. }
  5046. closedir(dirp);
  5047. free(tmp);
  5048. goto _accept_candidate;
  5049. }
  5050. _accept_candidate:
  5051. if (candidate_count == 0) {
  5052. redraw_statusbar();
  5053. goto done;
  5054. }
  5055. if (candidate_count == 1) {
  5056. /* Only one completion possibility */
  5057. redraw_statusbar();
  5058. /* Fill out the rest of the command */
  5059. char * cstart = (buffer) + (start - buf);
  5060. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5061. *cstart = candidates[0][i];
  5062. cstart++;
  5063. }
  5064. *cstart = '\0';
  5065. } else {
  5066. /* Print candidates in status bar */
  5067. char * tmp = malloc(global_config.term_width+1);
  5068. memset(tmp, 0, global_config.term_width+1);
  5069. int offset = 0;
  5070. for (int i = 0; i < candidate_count; ++i) {
  5071. if (offset + 1 + (signed)strlen(candidates[i]) > global_config.term_width - 5) {
  5072. strcat(tmp, "...");
  5073. break;
  5074. }
  5075. if (offset > 0) {
  5076. strcat(tmp, " ");
  5077. offset++;
  5078. }
  5079. strcat(tmp, candidates[i]);
  5080. offset += strlen(candidates[i]);
  5081. }
  5082. render_status_message("%s", tmp);
  5083. free(tmp);
  5084. /* Complete to longest common substring */
  5085. char * cstart = (buffer) + (start - buf);
  5086. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5087. for (int j = 1; j < candidate_count; ++j) {
  5088. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5089. }
  5090. *cstart = candidates[0][i];
  5091. cstart++;
  5092. }
  5093. /* End of longest common substring */
  5094. _reject:
  5095. *cstart = '\0';
  5096. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5097. if (start > buf) { /* Start point needs to be something other than first byte */
  5098. char * tmp = cstart - 1;
  5099. if ((*tmp & 0xC0) == 0x80) {
  5100. /* Count back until we find the start byte and make sure we have the right number */
  5101. int count = 1;
  5102. int x = 0;
  5103. while (tmp >= start) {
  5104. x++;
  5105. tmp--;
  5106. if ((*tmp & 0xC0) == 0x80) {
  5107. count++;
  5108. } else if ((*tmp & 0xC0) == 0xC0) {
  5109. /* How many should we have? */
  5110. int i = 1;
  5111. int j = *tmp;
  5112. while (j & 0x20) {
  5113. i += 1;
  5114. j <<= 1;
  5115. }
  5116. if (count != i) {
  5117. *tmp = '\0';
  5118. break;
  5119. }
  5120. break;
  5121. } else {
  5122. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5123. tmp++;
  5124. *tmp = '\0';
  5125. break;
  5126. }
  5127. }
  5128. } else if ((*tmp & 0xC0) == 0xC0) {
  5129. *tmp = '\0';
  5130. }
  5131. }
  5132. }
  5133. /* Free candidates */
  5134. for (int i = 0; i < candidate_count; ++i) {
  5135. free(candidates[i]);
  5136. }
  5137. /* Redraw command line */
  5138. done:
  5139. redraw_commandline();
  5140. printf(":%s", buffer);
  5141. free(candidates);
  5142. free(buf);
  5143. }
  5144. int handle_command_escape(int * this_buf, int * timeout, int c) {
  5145. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  5146. this_buf[*timeout] = c;
  5147. (*timeout)++;
  5148. return 1;
  5149. }
  5150. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  5151. *timeout = 0;
  5152. bim_unget(c);
  5153. return 1;
  5154. }
  5155. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  5156. *timeout = 1;
  5157. this_buf[*timeout] = c;
  5158. (*timeout)++;
  5159. return 0;
  5160. }
  5161. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  5162. (isdigit(c) || c == ';')) {
  5163. this_buf[*timeout] = c;
  5164. (*timeout)++;
  5165. return 0;
  5166. }
  5167. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  5168. int out = 0;
  5169. switch (c) {
  5170. case 'M':
  5171. out = 2;
  5172. break;
  5173. case 'A': // up
  5174. case 'B': // down
  5175. case 'C': // right
  5176. case 'D': // left
  5177. case 'H': // home
  5178. case 'F': // end
  5179. out = c;
  5180. break;
  5181. }
  5182. *timeout = 0;
  5183. return out;
  5184. }
  5185. *timeout = 0;
  5186. return 0;
  5187. }
  5188. /**
  5189. * Command mode
  5190. *
  5191. * Accept a user command and then process it and
  5192. * return to normal mode.
  5193. *
  5194. * TODO: We only have basic line editing here; it might be
  5195. * nice to add more advanced line editing, like cursor
  5196. * movement, tab completion, etc. This is easier than
  5197. * with the shell since we have a lot more control over
  5198. * where the command input bar is rendered.
  5199. */
  5200. void command_mode(void) {
  5201. int c;
  5202. char buffer[1024] = {0};
  5203. int buffer_len = 0;
  5204. int _redraw_on_byte = 0;
  5205. int timeout = 0;
  5206. int this_buf[20];
  5207. redraw_commandline();
  5208. printf(":");
  5209. show_cursor();
  5210. int history_point = -1;
  5211. while ((c = bim_getch())) {
  5212. if (c == -1) {
  5213. if (timeout && this_buf[timeout-1] == '\033') {
  5214. return;
  5215. }
  5216. timeout = 0;
  5217. continue;
  5218. } else {
  5219. if (timeout == 0) {
  5220. switch (c) {
  5221. case '\033':
  5222. /* Escape, cancel command */
  5223. if (timeout == 0) {
  5224. this_buf[timeout] = c;
  5225. timeout++;
  5226. }
  5227. break;
  5228. case ENTER_KEY:
  5229. case LINE_FEED:
  5230. /* Enter, run command */
  5231. process_command(buffer);
  5232. return;
  5233. case '\t':
  5234. /* Handle tab completion */
  5235. command_tab_complete(buffer);
  5236. buffer_len = strlen(buffer);
  5237. break;
  5238. case BACKSPACE_KEY:
  5239. case DELETE_KEY:
  5240. /* Backspace, delete last character in command buffer */
  5241. if (buffer_len > 0) {
  5242. do {
  5243. buffer_len--;
  5244. if ((buffer[buffer_len] & 0xC0) != 0x80) {
  5245. buffer[buffer_len] = '\0';
  5246. break;
  5247. }
  5248. } while (1);
  5249. goto _redraw_buffer;
  5250. } else {
  5251. /* If backspaced through entire command, cancel command mode */
  5252. redraw_commandline();
  5253. return;
  5254. }
  5255. break;
  5256. case 23:
  5257. while (buffer_len >0 &&
  5258. (buffer[buffer_len-1] == ' ' ||
  5259. buffer[buffer_len-1] == '/')) {
  5260. buffer_len--;
  5261. buffer[buffer_len] = '\0';
  5262. }
  5263. while (buffer_len > 0 &&
  5264. buffer[buffer_len-1] != ' ' &&
  5265. buffer[buffer_len-1] != '/') {
  5266. buffer_len--;
  5267. buffer[buffer_len] = '\0';
  5268. }
  5269. goto _redraw_buffer;
  5270. default:
  5271. /* Regular character */
  5272. buffer[buffer_len] = c;
  5273. buffer_len++;
  5274. if ((c & 0xC0) == 0xC0) {
  5275. /* This is the start of a UTF-8 character; how many bytes do we need? */
  5276. int i = 1;
  5277. int j = c;
  5278. while (j & 0x20) {
  5279. i += 1;
  5280. j <<= 1;
  5281. }
  5282. _redraw_on_byte = i;
  5283. } else if ((c & 0xC0) == 0x80 && _redraw_on_byte) {
  5284. _redraw_on_byte--;
  5285. if (_redraw_on_byte == 0) {
  5286. goto _redraw_buffer;
  5287. }
  5288. } else {
  5289. printf("%c", c);
  5290. }
  5291. break;
  5292. }
  5293. } else {
  5294. switch (handle_command_escape(this_buf,&timeout,c)) {
  5295. case 1:
  5296. bim_unget(c);
  5297. return;
  5298. case 'A':
  5299. /* Load from history */
  5300. if (command_history[history_point+1]) {
  5301. memcpy(buffer, command_history[history_point+1], strlen(command_history[history_point+1])+1);
  5302. history_point++;
  5303. buffer_len = strlen(buffer);
  5304. }
  5305. goto _redraw_buffer;
  5306. case 'B':
  5307. if (history_point > 0) {
  5308. history_point--;
  5309. memcpy(buffer, command_history[history_point], strlen(command_history[history_point])+1);
  5310. } else {
  5311. history_point = -1;
  5312. memset(buffer, 0, 1000);
  5313. }
  5314. buffer_len = strlen(buffer);
  5315. goto _redraw_buffer;
  5316. case 'C':
  5317. case 'D':
  5318. case 'H':
  5319. case 'F':
  5320. render_status_message("line editing not supported in command mode (sorry)");
  5321. goto _redraw_buffer;
  5322. }
  5323. }
  5324. show_cursor();
  5325. continue;
  5326. _redraw_buffer:
  5327. redraw_commandline();
  5328. printf(":%s", buffer);
  5329. show_cursor();
  5330. }
  5331. }
  5332. }
  5333. int smart_case(uint32_t * str) {
  5334. if (!global_config.smart_case) return 0;
  5335. for (uint32_t * s = str; *s; ++s) {
  5336. if (tolower(*s) != (int)*s) {
  5337. return 0;
  5338. }
  5339. }
  5340. return 1;
  5341. }
  5342. /**
  5343. * Search forward from the given cursor position
  5344. * to find a basic search match.
  5345. *
  5346. * This could be more complicated...
  5347. */
  5348. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5349. int col = from_col;
  5350. int ignorecase = smart_case(str);
  5351. for (int i = from_line; i <= env->line_count; ++i) {
  5352. line_t * line = env->lines[i - 1];
  5353. int j = col - 1;
  5354. while (j < line->actual + 1) {
  5355. int k = j;
  5356. uint32_t * match = str;
  5357. while (k < line->actual + 1) {
  5358. if (*match == '\0') {
  5359. *out_line = i;
  5360. *out_col = j + 1;
  5361. return;
  5362. }
  5363. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  5364. match++;
  5365. k++;
  5366. }
  5367. j++;
  5368. }
  5369. col = 0;
  5370. }
  5371. }
  5372. /**
  5373. * Search backwards for matching string.
  5374. */
  5375. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5376. int col = from_col;
  5377. int ignorecase = smart_case(str);
  5378. for (int i = from_line; i >= 1; --i) {
  5379. line_t * line = env->lines[i-1];
  5380. int j = col - 1;
  5381. while (j > -1) {
  5382. int k = j;
  5383. uint32_t * match = str;
  5384. while (k < line->actual + 1) {
  5385. if (*match == '\0') {
  5386. *out_line = i;
  5387. *out_col = j + 1;
  5388. return;
  5389. }
  5390. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  5391. match++;
  5392. k++;
  5393. }
  5394. j--;
  5395. }
  5396. col = (i > 1) ? (env->lines[i-2]->actual) : -1;
  5397. }
  5398. }
  5399. /**
  5400. * Draw the matched search result.
  5401. */
  5402. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  5403. for (int i = 0; i < env->line_count; ++i) {
  5404. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5405. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5406. }
  5407. }
  5408. int line = -1, col = -1, _line = 1, _col = 1;
  5409. do {
  5410. find_match(_line, _col, &line, &col, buffer);
  5411. if (line != -1) {
  5412. line_t * l = env->lines[line-1];
  5413. uint32_t * t = buffer;
  5414. for (int i = col; *t; ++i, ++t) {
  5415. l->text[i-1].flags |= FLAG_SEARCH;
  5416. }
  5417. }
  5418. _line = line;
  5419. _col = col+1;
  5420. line = -1;
  5421. col = -1;
  5422. } while (_line != -1);
  5423. redraw_text();
  5424. place_cursor_actual();
  5425. redraw_statusbar();
  5426. redraw_commandline();
  5427. if (redraw_buffer != -1) {
  5428. printf(redraw_buffer == 1 ? "/" : "?");
  5429. uint32_t * c = buffer;
  5430. while (*c) {
  5431. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5432. to_eight(*c, tmp);
  5433. printf("%s", tmp);
  5434. c++;
  5435. }
  5436. }
  5437. }
  5438. /**
  5439. * Search mode
  5440. *
  5441. * Search text for substring match.
  5442. */
  5443. void search_mode(int direction) {
  5444. uint32_t c;
  5445. uint32_t buffer[1024] = {0};
  5446. int buffer_len = 0;
  5447. /* utf-8 decoding */
  5448. /* Remember where the cursor is so we can cancel */
  5449. int prev_line = env->line_no;
  5450. int prev_col = env->col_no;
  5451. int prev_coffset = env->coffset;
  5452. int prev_offset = env->offset;
  5453. redraw_commandline();
  5454. printf(direction == 1 ? "/" : "?");
  5455. if (env->search) {
  5456. printf("\0337");
  5457. set_colors(COLOR_ALT_FG, COLOR_BG);
  5458. uint32_t * c = env->search;
  5459. while (*c) {
  5460. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5461. to_eight(*c, tmp);
  5462. printf("%s", tmp);
  5463. c++;
  5464. }
  5465. printf("\0338");
  5466. set_colors(COLOR_FG, COLOR_BG);
  5467. }
  5468. show_cursor();
  5469. uint32_t state = 0;
  5470. int cin;
  5471. while ((cin = bim_getch())) {
  5472. if (cin == -1) {
  5473. /* Time out */
  5474. continue;
  5475. }
  5476. if (!decode(&state, &c, cin)) {
  5477. if (c == '\033') {
  5478. /* Cancel search */
  5479. env->line_no = prev_line;
  5480. env->col_no = prev_col;
  5481. /* Unhighlight search matches */
  5482. for (int i = 0; i < env->line_count; ++i) {
  5483. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5484. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5485. }
  5486. }
  5487. redraw_all();
  5488. break;
  5489. } else if (c == ENTER_KEY || c == LINE_FEED) {
  5490. /* Exit search */
  5491. if (!buffer_len) {
  5492. if (env->search) {
  5493. search_next();
  5494. }
  5495. break;
  5496. }
  5497. if (env->search) {
  5498. free(env->search);
  5499. }
  5500. env->search = malloc((buffer_len + 1) * sizeof(uint32_t));
  5501. memcpy(env->search, buffer, (buffer_len + 1) * sizeof(uint32_t));
  5502. break;
  5503. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  5504. /* Backspace, delete last character in search buffer */
  5505. if (buffer_len > 0) {
  5506. buffer_len -= 1;
  5507. buffer[buffer_len] = '\0';
  5508. /* Search from beginning to find first match */
  5509. int line = -1, col = -1;
  5510. if (direction == 1) {
  5511. find_match(prev_line, prev_col, &line, &col, buffer);
  5512. } else {
  5513. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  5514. }
  5515. if (line != -1) {
  5516. env->col_no = col;
  5517. env->line_no = line;
  5518. set_preferred_column();
  5519. }
  5520. draw_search_match(buffer, direction);
  5521. } else {
  5522. /* If backspaced through entire search term, cancel search */
  5523. redraw_commandline();
  5524. env->coffset = prev_coffset;
  5525. env->offset = prev_offset;
  5526. env->col_no = prev_col;
  5527. set_preferred_column();
  5528. env->line_no = prev_line;
  5529. redraw_all();
  5530. break;
  5531. }
  5532. } else {
  5533. /* Regular character */
  5534. buffer[buffer_len] = c;
  5535. buffer_len++;
  5536. buffer[buffer_len] = '\0';
  5537. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5538. to_eight(c, tmp);
  5539. printf("%s", tmp);
  5540. /* Find the next search match */
  5541. int line = -1, col = -1;
  5542. if (direction == 1) {
  5543. find_match(prev_line, prev_col, &line, &col, buffer);
  5544. } else {
  5545. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  5546. }
  5547. if (line != -1) {
  5548. env->col_no = col;
  5549. env->line_no = line;
  5550. set_preferred_column();
  5551. } else {
  5552. env->coffset = prev_coffset;
  5553. env->offset = prev_offset;
  5554. env->col_no = prev_col;
  5555. set_preferred_column();
  5556. env->line_no = prev_line;
  5557. }
  5558. draw_search_match(buffer, direction);
  5559. }
  5560. show_cursor();
  5561. } else if (state == UTF8_REJECT) {
  5562. state = 0;
  5563. }
  5564. }
  5565. }
  5566. /**
  5567. * Find the next search result, or loop back around if at the end.
  5568. */
  5569. void search_next(void) {
  5570. if (!env->search) return;
  5571. if (env->coffset) env->coffset = 0;
  5572. int line = -1, col = -1;
  5573. find_match(env->line_no, env->col_no+1, &line, &col, env->search);
  5574. if (line == -1) {
  5575. find_match(1,1, &line, &col, env->search);
  5576. if (line == -1) return;
  5577. }
  5578. env->col_no = col;
  5579. env->line_no = line;
  5580. set_preferred_column();
  5581. draw_search_match(env->search, -1);
  5582. }
  5583. /**
  5584. * Find the previous search result, or loop to the end of the file.
  5585. */
  5586. void search_prev(void) {
  5587. if (!env->search) return;
  5588. if (env->coffset) env->coffset = 0;
  5589. int line = -1, col = -1;
  5590. find_match_backwards(env->line_no, env->col_no-1, &line, &col, env->search);
  5591. if (line == -1) {
  5592. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, env->search);
  5593. if (line == -1) return;
  5594. }
  5595. env->col_no = col;
  5596. env->line_no = line;
  5597. set_preferred_column();
  5598. draw_search_match(env->search, -1);
  5599. }
  5600. /**
  5601. * Find the matching paren for this one.
  5602. *
  5603. * This approach skips having to do its own syntax parsing
  5604. * to deal with, eg., erroneous parens in comments. It does
  5605. * this by finding the matching paren with the same flag
  5606. * value, thus parens in strings will match, parens outside
  5607. * of strings will match, but parens in strings won't
  5608. * match parens outside of strings and so on.
  5609. */
  5610. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  5611. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  5612. return; /* Invalid cursor position */
  5613. }
  5614. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  5615. int paren_match = 0;
  5616. int direction = 0;
  5617. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  5618. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0xF;
  5619. int count = 0;
  5620. /* TODO what about unicode parens? */
  5621. for (int i = 0; paren_pairs[i]; ++i) {
  5622. if (start == paren_pairs[i]) {
  5623. direction = (i % 2 == 0) ? 1 : -1;
  5624. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  5625. break;
  5626. }
  5627. }
  5628. if (!paren_match) return;
  5629. /* Scan for match */
  5630. int line = env->line_no;
  5631. int col = env->col_no - in_col + 1;
  5632. do {
  5633. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  5634. /* Only match on same syntax */
  5635. if ((env->lines[line-1]->text[col-1].flags & 0xF) == flags) {
  5636. /* Count up on same direction */
  5637. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  5638. /* Count down on opposite direction */
  5639. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  5640. count--;
  5641. /* When count == 0 we have a match */
  5642. if (count == 0) goto _match_found;
  5643. }
  5644. }
  5645. col += direction;
  5646. }
  5647. line += direction;
  5648. /* Reached first/last line with no match */
  5649. if (line == 0 || line == env->line_count + 1) {
  5650. return;
  5651. }
  5652. /* Reset column to start/end of line, depending on direction */
  5653. if (direction > 0) {
  5654. col = 1;
  5655. } else {
  5656. col = env->lines[line-1]->actual;
  5657. }
  5658. } while (1);
  5659. _match_found:
  5660. *out_line = line;
  5661. *out_col = col;
  5662. }
  5663. void use_left_buffer(void) {
  5664. if (left_buffer == right_buffer && env->left != 0) {
  5665. view_right_offset = env->offset;
  5666. env->width = env->left;
  5667. env->left = 0;
  5668. env->offset = view_left_offset;
  5669. }
  5670. env = left_buffer;
  5671. }
  5672. void use_right_buffer(void) {
  5673. if (left_buffer == right_buffer && env->left == 0) {
  5674. view_left_offset = env->offset;
  5675. env->left = env->width;
  5676. env->width = global_config.term_width - env->width;
  5677. env->offset = view_right_offset;
  5678. }
  5679. env = right_buffer;
  5680. }
  5681. /**
  5682. * Handle mouse event
  5683. */
  5684. void handle_mouse(void) {
  5685. int buttons = bim_getch() - 32;
  5686. int x = bim_getch() - 32;
  5687. int y = bim_getch() - 32;
  5688. if (buttons == 64) {
  5689. /* Scroll up */
  5690. if (global_config.shift_scrolling) {
  5691. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5692. if (env->offset > 0) env->offset--;
  5693. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  5694. cursor_up();
  5695. }
  5696. }
  5697. redraw_most();
  5698. } else {
  5699. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5700. cursor_up();
  5701. }
  5702. }
  5703. return;
  5704. } else if (buttons == 65) {
  5705. /* Scroll down */
  5706. if (global_config.shift_scrolling) {
  5707. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5708. if (env->offset < env->line_count-1) env->offset++;
  5709. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  5710. if (env->line_no <= e) {
  5711. cursor_down();
  5712. }
  5713. }
  5714. redraw_most();
  5715. } else {
  5716. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5717. cursor_down();
  5718. }
  5719. }
  5720. return;
  5721. } else if (buttons == 3) {
  5722. /* Move cursor to position */
  5723. if (x < 0) return;
  5724. if (y < 0) return;
  5725. if (y == 1) {
  5726. /* Pick from tabs */
  5727. int _x = 0;
  5728. for (int i = 0; i < buffers_len; i++) {
  5729. buffer_t * _env = buffers[i];
  5730. char tmp[64];
  5731. _x += draw_tab_name(_env, tmp);
  5732. if (_x >= x) {
  5733. env = buffers[i];
  5734. redraw_all();
  5735. return;
  5736. }
  5737. }
  5738. return;
  5739. }
  5740. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  5741. int current_mode = env->mode;
  5742. if (x < env->left && env == right_buffer) {
  5743. use_left_buffer();
  5744. } else if (x > env->width && env == left_buffer) {
  5745. use_right_buffer();
  5746. }
  5747. env->mode = current_mode;
  5748. redraw_all();
  5749. }
  5750. if (env->left) {
  5751. x -= env->left;
  5752. }
  5753. /* Figure out y coordinate */
  5754. int line_no = y + env->offset - 1;
  5755. int col_no = -1;
  5756. if (line_no > env->line_count) {
  5757. line_no = env->line_count;
  5758. }
  5759. /* Account for the left hand gutter */
  5760. int num_size = num_width() + 3;
  5761. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  5762. /* Determine where the cursor is physically */
  5763. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  5764. char_t * c = &env->lines[line_no-1]->text[i];
  5765. _x += c->display_width;
  5766. if (_x > x-1) {
  5767. col_no = i+1;
  5768. break;
  5769. }
  5770. }
  5771. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  5772. col_no = env->lines[line_no-1]->actual;
  5773. }
  5774. env->line_no = line_no;
  5775. env->col_no = col_no;
  5776. set_preferred_column();
  5777. place_cursor_actual();
  5778. }
  5779. return;
  5780. }
  5781. /**
  5782. * Append a character at the current cursor point.
  5783. */
  5784. void insert_char(unsigned int c) {
  5785. if (!c) {
  5786. render_error("Inserted nil byte?");
  5787. return;
  5788. }
  5789. char_t _c;
  5790. _c.codepoint = c;
  5791. _c.flags = 0;
  5792. _c.display_width = codepoint_width(c);
  5793. line_t * line = env->lines[env->line_no - 1];
  5794. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  5795. if (line != nline) {
  5796. env->lines[env->line_no - 1] = nline;
  5797. }
  5798. env->col_no += 1;
  5799. set_modified();
  5800. }
  5801. /**
  5802. * Replace a single character at the current cursor point
  5803. */
  5804. void replace_char(unsigned int c) {
  5805. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  5806. char_t _c;
  5807. _c.codepoint = c;
  5808. _c.flags = 0;
  5809. _c.display_width = codepoint_width(c);
  5810. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  5811. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  5812. set_modified();
  5813. }
  5814. /**
  5815. * Undo a history entry.
  5816. */
  5817. void undo_history(void) {
  5818. if (!global_config.history_enabled) return;
  5819. env->loading = 1;
  5820. history_t * e = env->history;
  5821. if (e->type == HISTORY_SENTINEL) {
  5822. env->loading = 0;
  5823. render_commandline_message("Already at oldest change");
  5824. return;
  5825. }
  5826. int count_chars = 0;
  5827. int count_lines = 0;
  5828. do {
  5829. if (e->type == HISTORY_SENTINEL) break;
  5830. switch (e->type) {
  5831. case HISTORY_INSERT:
  5832. /* Delete */
  5833. line_delete(
  5834. env->lines[e->contents.insert_delete_replace.lineno],
  5835. e->contents.insert_delete_replace.offset+1,
  5836. e->contents.insert_delete_replace.lineno
  5837. );
  5838. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5839. env->col_no = e->contents.insert_delete_replace.offset + 1;
  5840. count_chars++;
  5841. break;
  5842. case HISTORY_DELETE:
  5843. {
  5844. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  5845. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  5846. env->lines[e->contents.insert_delete_replace.lineno],
  5847. _c,
  5848. e->contents.insert_delete_replace.offset-1,
  5849. e->contents.insert_delete_replace.lineno
  5850. );
  5851. }
  5852. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5853. env->col_no = e->contents.insert_delete_replace.offset + 2;
  5854. count_chars++;
  5855. break;
  5856. case HISTORY_REPLACE:
  5857. {
  5858. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  5859. line_replace(
  5860. env->lines[e->contents.insert_delete_replace.lineno],
  5861. _o,
  5862. e->contents.insert_delete_replace.offset,
  5863. e->contents.insert_delete_replace.lineno
  5864. );
  5865. }
  5866. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5867. env->col_no = e->contents.insert_delete_replace.offset + 1;
  5868. count_chars++;
  5869. break;
  5870. case HISTORY_REMOVE_LINE:
  5871. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  5872. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  5873. env->line_no = e->contents.remove_replace_line.lineno + 2;
  5874. env->col_no = 1;
  5875. count_lines++;
  5876. break;
  5877. case HISTORY_ADD_LINE:
  5878. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  5879. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  5880. env->col_no = 1;
  5881. count_lines++;
  5882. break;
  5883. case HISTORY_REPLACE_LINE:
  5884. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  5885. env->line_no = e->contents.remove_replace_line.lineno + 1;
  5886. env->col_no = 1;
  5887. count_lines++;
  5888. break;
  5889. case HISTORY_SPLIT_LINE:
  5890. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  5891. env->line_no = e->contents.add_merge_split_lines.lineno + 2;
  5892. env->col_no = 1;
  5893. count_lines++;
  5894. break;
  5895. case HISTORY_MERGE_LINES:
  5896. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  5897. env->line_no = e->contents.add_merge_split_lines.lineno;
  5898. env->col_no = 1;
  5899. count_lines++;
  5900. break;
  5901. case HISTORY_BREAK:
  5902. /* Ignore break */
  5903. break;
  5904. default:
  5905. render_error("Unknown type %d!\n", e->type);
  5906. break;
  5907. }
  5908. env->history = e->previous;
  5909. e = env->history;
  5910. } while (e->type != HISTORY_BREAK);
  5911. if (env->line_no > env->line_count) env->line_no = env->line_count;
  5912. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  5913. env->modified = (env->history != env->last_save_history);
  5914. env->loading = 0;
  5915. for (int i = 0; i < env->line_count; ++i) {
  5916. env->lines[i]->istate = 0;
  5917. recalculate_tabs(env->lines[i]);
  5918. }
  5919. for (int i = 0; i < env->line_count; ++i) {
  5920. recalculate_syntax(env->lines[i],i);
  5921. }
  5922. place_cursor_actual();
  5923. update_title();
  5924. redraw_all();
  5925. render_commandline_message("%d character%s, %d line%s changed",
  5926. count_chars, (count_chars == 1) ? "" : "s",
  5927. count_lines, (count_lines == 1) ? "" : "s");
  5928. }
  5929. /**
  5930. * Replay a history entry.
  5931. */
  5932. void redo_history(void) {
  5933. if (!global_config.history_enabled) return;
  5934. env->loading = 1;
  5935. history_t * e = env->history->next;
  5936. if (!e) {
  5937. env->loading = 0;
  5938. render_commandline_message("Already at newest change");
  5939. return;
  5940. }
  5941. int count_chars = 0;
  5942. int count_lines = 0;
  5943. while (e) {
  5944. if (e->type == HISTORY_BREAK) {
  5945. env->history = e;
  5946. break;
  5947. }
  5948. switch (e->type) {
  5949. case HISTORY_INSERT:
  5950. {
  5951. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  5952. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  5953. env->lines[e->contents.insert_delete_replace.lineno],
  5954. _c,
  5955. e->contents.insert_delete_replace.offset,
  5956. e->contents.insert_delete_replace.lineno
  5957. );
  5958. }
  5959. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5960. env->col_no = e->contents.insert_delete_replace.offset + 2;
  5961. count_chars++;
  5962. break;
  5963. case HISTORY_DELETE:
  5964. /* Delete */
  5965. line_delete(
  5966. env->lines[e->contents.insert_delete_replace.lineno],
  5967. e->contents.insert_delete_replace.offset,
  5968. e->contents.insert_delete_replace.lineno
  5969. );
  5970. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5971. env->col_no = e->contents.insert_delete_replace.offset + 1;
  5972. count_chars++;
  5973. break;
  5974. case HISTORY_REPLACE:
  5975. {
  5976. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  5977. line_replace(
  5978. env->lines[e->contents.insert_delete_replace.lineno],
  5979. _o,
  5980. e->contents.insert_delete_replace.offset,
  5981. e->contents.insert_delete_replace.lineno
  5982. );
  5983. }
  5984. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  5985. env->col_no = e->contents.insert_delete_replace.offset + 2;
  5986. count_chars++;
  5987. break;
  5988. case HISTORY_ADD_LINE:
  5989. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  5990. env->line_no = e->contents.remove_replace_line.lineno + 2;
  5991. env->col_no = 1;
  5992. count_lines++;
  5993. break;
  5994. case HISTORY_REMOVE_LINE:
  5995. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  5996. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  5997. env->col_no = 1;
  5998. count_lines++;
  5999. break;
  6000. case HISTORY_REPLACE_LINE:
  6001. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6002. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6003. env->col_no = 1;
  6004. count_lines++;
  6005. break;
  6006. case HISTORY_MERGE_LINES:
  6007. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6008. env->line_no = e->contents.remove_replace_line.lineno + 1;
  6009. env->col_no = 1;
  6010. count_lines++;
  6011. break;
  6012. case HISTORY_SPLIT_LINE:
  6013. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6014. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6015. env->col_no = 1;
  6016. count_lines++;
  6017. break;
  6018. case HISTORY_BREAK:
  6019. /* Ignore break */
  6020. break;
  6021. default:
  6022. render_error("Unknown type %d!\n", e->type);
  6023. break;
  6024. }
  6025. env->history = e;
  6026. e = e->next;
  6027. }
  6028. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6029. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6030. env->modified = (env->history != env->last_save_history);
  6031. env->loading = 0;
  6032. for (int i = 0; i < env->line_count; ++i) {
  6033. env->lines[i]->istate = 0;
  6034. recalculate_tabs(env->lines[i]);
  6035. }
  6036. for (int i = 0; i < env->line_count; ++i) {
  6037. recalculate_syntax(env->lines[i],i);
  6038. }
  6039. place_cursor_actual();
  6040. update_title();
  6041. redraw_all();
  6042. render_commandline_message("%d character%s, %d line%s changed",
  6043. count_chars, (count_chars == 1) ? "" : "s",
  6044. count_lines, (count_lines == 1) ? "" : "s");
  6045. }
  6046. /**
  6047. * Move the cursor the start of the previous word.
  6048. */
  6049. void word_left(void) {
  6050. int line_no = env->line_no;
  6051. int col_no = env->col_no;
  6052. do {
  6053. col_no--;
  6054. while (col_no == 0) {
  6055. line_no--;
  6056. if (line_no == 0) {
  6057. goto_line(1);
  6058. set_preferred_column();
  6059. return;
  6060. }
  6061. col_no = env->lines[line_no-1]->actual;
  6062. }
  6063. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6064. do {
  6065. col_no--;
  6066. if (col_no == 0) {
  6067. col_no = 1;
  6068. break;
  6069. }
  6070. if (col_no == 1) {
  6071. env->col_no = 1;
  6072. env->line_no = line_no;
  6073. set_preferred_column();
  6074. redraw_statusbar();
  6075. place_cursor_actual();
  6076. return;
  6077. }
  6078. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6079. env->col_no = col_no;
  6080. env->line_no = line_no;
  6081. set_preferred_column();
  6082. cursor_right();
  6083. }
  6084. /**
  6085. * Word right
  6086. */
  6087. void word_right(void) {
  6088. int line_no = env->line_no;
  6089. int col_no = env->col_no;
  6090. do {
  6091. col_no++;
  6092. if (col_no > env->lines[line_no-1]->actual) {
  6093. line_no++;
  6094. if (line_no > env->line_count) {
  6095. env->line_no = env->line_count;
  6096. env->col_no = env->lines[env->line_no-1]->actual;
  6097. set_preferred_column();
  6098. redraw_statusbar();
  6099. place_cursor_actual();
  6100. return;
  6101. }
  6102. col_no = 0;
  6103. break;
  6104. }
  6105. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6106. do {
  6107. col_no++;
  6108. while (col_no > env->lines[line_no-1]->actual) {
  6109. line_no++;
  6110. if (line_no >= env->line_count) {
  6111. env->col_no = env->lines[env->line_count-1]->actual;
  6112. env->line_no = env->line_count;
  6113. set_preferred_column();
  6114. redraw_statusbar();
  6115. place_cursor_actual();
  6116. return;
  6117. }
  6118. col_no = 1;
  6119. }
  6120. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6121. env->col_no = col_no;
  6122. env->line_no = line_no;
  6123. set_preferred_column();
  6124. redraw_statusbar();
  6125. place_cursor_actual();
  6126. return;
  6127. }
  6128. /**
  6129. * Backspace from the current cursor position.
  6130. */
  6131. void delete_at_cursor(void) {
  6132. if (env->col_no > 1) {
  6133. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6134. env->col_no -= 1;
  6135. if (env->coffset > 0) env->coffset--;
  6136. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6137. set_modified();
  6138. redraw_statusbar();
  6139. place_cursor_actual();
  6140. } else if (env->line_no > 1) {
  6141. int tmp = env->lines[env->line_no - 2]->actual;
  6142. merge_lines(env->lines, env->line_no - 1);
  6143. env->line_no -= 1;
  6144. env->col_no = tmp+1;
  6145. set_preferred_column();
  6146. redraw_text();
  6147. set_modified();
  6148. redraw_statusbar();
  6149. place_cursor_actual();
  6150. }
  6151. }
  6152. int is_whitespace(int codepoint) {
  6153. return codepoint == ' ' || codepoint == '\t';
  6154. }
  6155. int is_normal(int codepoint) {
  6156. return isalnum(codepoint) || codepoint == '_';
  6157. }
  6158. int is_special(int codepoint) {
  6159. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6160. }
  6161. void delete_word(void) {
  6162. if (!env->lines[env->line_no-1]) return;
  6163. if (env->col_no > 1) {
  6164. /* Start by deleting whitespace */
  6165. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6166. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6167. env->col_no -= 1;
  6168. if (env->coffset > 0) env->coffset--;
  6169. }
  6170. int (*inverse_comparator)(int) = is_special;
  6171. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6172. inverse_comparator = is_normal;
  6173. }
  6174. do {
  6175. if (env->col_no > 1) {
  6176. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6177. env->col_no -= 1;
  6178. if (env->coffset > 0) env->coffset--;
  6179. }
  6180. } while (env->col_no > 1 && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint));
  6181. set_preferred_column();
  6182. redraw_text();
  6183. set_modified();
  6184. redraw_statusbar();
  6185. place_cursor_actual();
  6186. }
  6187. }
  6188. /**
  6189. * Break the current line in two at the current cursor position.
  6190. */
  6191. void insert_line_feed(void) {
  6192. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6193. env->lines = add_line(env->lines, env->line_no);
  6194. } else {
  6195. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6196. }
  6197. env->col_no = 1;
  6198. env->line_no += 1;
  6199. set_preferred_column();
  6200. add_indent(env->line_no-1,env->line_no-2,0);
  6201. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  6202. env->offset += 1;
  6203. }
  6204. set_modified();
  6205. }
  6206. /**
  6207. * Yank lines between line start and line end (which may be in either order)
  6208. */
  6209. void yank_lines(int start, int end) {
  6210. if (global_config.yanks) {
  6211. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6212. free(global_config.yanks[i]);
  6213. }
  6214. free(global_config.yanks);
  6215. }
  6216. int lines_to_yank;
  6217. int start_point;
  6218. if (start <= end) {
  6219. lines_to_yank = end - start + 1;
  6220. start_point = start - 1;
  6221. } else {
  6222. lines_to_yank = start - end + 1;
  6223. start_point = end - 1;
  6224. }
  6225. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6226. global_config.yank_count = lines_to_yank;
  6227. global_config.yank_is_full_lines = 1;
  6228. for (int i = 0; i < lines_to_yank; ++i) {
  6229. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6230. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6231. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6232. global_config.yanks[i]->istate = 0;
  6233. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6234. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6235. global_config.yanks[i]->text[j].flags = 0;
  6236. }
  6237. }
  6238. }
  6239. /**
  6240. * Helper to yank part of a line into a new yank line.
  6241. */
  6242. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  6243. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  6244. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  6245. global_config.yanks[yank_no]->actual = count;
  6246. global_config.yanks[yank_no]->istate = 0;
  6247. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  6248. for (int i = 0; i < count; ++i) {
  6249. global_config.yanks[yank_no]->text[i].flags = 0;
  6250. }
  6251. }
  6252. /**
  6253. * Yank text...
  6254. */
  6255. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  6256. if (global_config.yanks) {
  6257. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6258. free(global_config.yanks[i]);
  6259. }
  6260. free(global_config.yanks);
  6261. }
  6262. int lines_to_yank = end_line - start_line + 1;
  6263. int start_point = start_line - 1;
  6264. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6265. global_config.yank_count = lines_to_yank;
  6266. global_config.yank_is_full_lines = 0;
  6267. if (lines_to_yank == 1) {
  6268. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  6269. } else {
  6270. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  6271. /* Yank middle lines */
  6272. for (int i = 1; i < lines_to_yank - 1; ++i) {
  6273. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6274. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6275. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6276. global_config.yanks[i]->istate = 0;
  6277. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6278. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6279. global_config.yanks[i]->text[j].flags = 0;
  6280. }
  6281. }
  6282. /* Yank end line */
  6283. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  6284. }
  6285. }
  6286. /**
  6287. * Handle shared escape keys (mostly navigation)
  6288. */
  6289. int handle_escape(int * this_buf, int * timeout, int c) {
  6290. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  6291. this_buf[*timeout] = c;
  6292. (*timeout)++;
  6293. return 1;
  6294. }
  6295. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  6296. *timeout = 0;
  6297. bim_unget(c);
  6298. return 1;
  6299. }
  6300. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  6301. *timeout = 1;
  6302. this_buf[*timeout] = c;
  6303. (*timeout)++;
  6304. return 0;
  6305. }
  6306. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  6307. (isdigit(c) || c == ';')) {
  6308. this_buf[*timeout] = c;
  6309. (*timeout)++;
  6310. return 0;
  6311. }
  6312. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  6313. switch (c) {
  6314. case 'M':
  6315. handle_mouse();
  6316. break;
  6317. case 'A': // up
  6318. cursor_up();
  6319. break;
  6320. case 'B': // down
  6321. cursor_down();
  6322. break;
  6323. case 'C': // right
  6324. if (this_buf[*timeout-1] == '5') {
  6325. word_right();
  6326. } else if (this_buf[*timeout-1] == '3') {
  6327. global_config.split_percent += 1;
  6328. update_split_size();
  6329. redraw_all();
  6330. } else if (this_buf[*timeout-1] == '4') {
  6331. use_right_buffer();
  6332. redraw_all();
  6333. } else {
  6334. cursor_right();
  6335. }
  6336. break;
  6337. case 'D': // left
  6338. if (this_buf[*timeout-1] == '5') {
  6339. word_left();
  6340. } else if (this_buf[*timeout-1] == '3') {
  6341. global_config.split_percent -= 1;
  6342. update_split_size();
  6343. redraw_all();
  6344. } else if (this_buf[*timeout-1] == '4') {
  6345. use_left_buffer();
  6346. redraw_all();
  6347. } else {
  6348. cursor_left();
  6349. }
  6350. break;
  6351. case 'H': // home
  6352. cursor_home();
  6353. break;
  6354. case 'F': // end
  6355. cursor_end();
  6356. break;
  6357. case 'I':
  6358. goto_line(env->line_no - (global_config.term_height - 6));
  6359. break;
  6360. case 'G':
  6361. goto_line(env->line_no + global_config.term_height - 6);
  6362. break;
  6363. case 'Z':
  6364. /* Shift tab */
  6365. if (env->mode == MODE_LINE_SELECTION) {
  6366. *timeout = 0;
  6367. return 'Z';
  6368. }
  6369. break;
  6370. case '~':
  6371. switch (this_buf[*timeout-1]) {
  6372. case '1':
  6373. cursor_home();
  6374. break;
  6375. case '3':
  6376. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) {
  6377. if (env->col_no < env->lines[env->line_no - 1]->actual + 1) {
  6378. line_delete(env->lines[env->line_no - 1], env->col_no, env->line_no - 1);
  6379. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6380. set_modified();
  6381. redraw_statusbar();
  6382. place_cursor_actual();
  6383. } else if (env->line_no < env->line_count) {
  6384. merge_lines(env->lines, env->line_no);
  6385. redraw_text();
  6386. set_modified();
  6387. redraw_statusbar();
  6388. place_cursor_actual();
  6389. }
  6390. }
  6391. break;
  6392. case '4':
  6393. cursor_end();
  6394. break;
  6395. case '5':
  6396. goto_line(env->line_no - (global_config.term_height - 6));
  6397. break;
  6398. case '6':
  6399. goto_line(env->line_no + global_config.term_height - 6);
  6400. break;
  6401. }
  6402. break;
  6403. default:
  6404. render_error("Unrecognized escape sequence identifier: %c", c);
  6405. break;
  6406. }
  6407. *timeout = 0;
  6408. return 0;
  6409. }
  6410. *timeout = 0;
  6411. return 0;
  6412. }
  6413. /**
  6414. * Search for the word under the cursor
  6415. */
  6416. void search_under_cursor(void) {
  6417. /* Figure out size */
  6418. int c_before = 0;
  6419. int c_after = 0;
  6420. int i = env->col_no;
  6421. while (i > 0) {
  6422. if (!c_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6423. c_before++;
  6424. i--;
  6425. }
  6426. i = env->col_no+1;
  6427. while (i < env->lines[env->line_no-1]->actual+1) {
  6428. if (!c_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6429. c_after++;
  6430. i++;
  6431. }
  6432. if (!c_before && !c_after) return;
  6433. /* Populate with characters */
  6434. if (env->search) free(env->search);
  6435. env->search = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  6436. int j = 0;
  6437. while (c_before) {
  6438. env->search[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  6439. c_before--;
  6440. j++;
  6441. }
  6442. int x = 0;
  6443. while (c_after) {
  6444. env->search[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  6445. j++;
  6446. x++;
  6447. c_after--;
  6448. }
  6449. env->search[j] = 0;
  6450. /* Find it */
  6451. search_next();
  6452. }
  6453. /**
  6454. * Standard navigation shared by normal, line, and char selection.
  6455. */
  6456. void handle_navigation(int c) {
  6457. switch (c) {
  6458. case 2: /* ctrl-b = page up */
  6459. goto_line(env->line_no - (global_config.term_height - 6));
  6460. break;
  6461. case 6: /* ctrl-f = page down */
  6462. goto_line(env->line_no + global_config.term_height - 6);
  6463. break;
  6464. case ':': /* Switch to command mode */
  6465. command_mode();
  6466. break;
  6467. case '/': /* Switch to search mode */
  6468. search_mode(1);
  6469. break;
  6470. case '?': /* Switch to search mode */
  6471. search_mode(0);
  6472. break;
  6473. case 'n': /* Jump to next search result */
  6474. search_next();
  6475. break;
  6476. case 'N': /* Jump backwards to previous search result */
  6477. search_prev();
  6478. break;
  6479. case 'j': /* Move cursor down */
  6480. cursor_down();
  6481. break;
  6482. case 'k': /* Move cursor up */
  6483. cursor_up();
  6484. break;
  6485. case 'h': /* Move cursor left */
  6486. cursor_left();
  6487. break;
  6488. case 'l': /* Move cursor right*/
  6489. cursor_right();
  6490. break;
  6491. case 'w': /* Move cursor one word right */
  6492. word_right();
  6493. break;
  6494. case 'G': /* Go to end of file */
  6495. goto_line(env->line_count);
  6496. break;
  6497. case '*': /* Search for word under cursor */
  6498. search_under_cursor();
  6499. break;
  6500. case ' ': /* Jump forward several lines */
  6501. goto_line(env->line_no + global_config.term_height - 6);
  6502. break;
  6503. case '%': /* Jump to matching brace/bracket */
  6504. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) {
  6505. /* These modes need to recalculate syntax as find_matching_brace uses it to find appropriate match */
  6506. for (int i = 0; i < env->line_count; ++i) {
  6507. recalculate_syntax(env->lines[i],i);
  6508. }
  6509. }
  6510. {
  6511. int paren_line = -1, paren_col = -1;
  6512. find_matching_paren(&paren_line, &paren_col, 1);
  6513. if (paren_line != -1) {
  6514. env->line_no = paren_line;
  6515. env->col_no = paren_col;
  6516. set_preferred_column();
  6517. place_cursor_actual();
  6518. redraw_statusbar();
  6519. }
  6520. }
  6521. break;
  6522. case '{': /* Jump to previous blank line */
  6523. env->col_no = 1;
  6524. if (env->line_no == 1) break;
  6525. do {
  6526. env->line_no--;
  6527. if (env->lines[env->line_no-1]->actual == 0) break;
  6528. } while (env->line_no > 1);
  6529. set_preferred_column();
  6530. redraw_statusbar();
  6531. break;
  6532. case '}': /* Jump to next blank line */
  6533. env->col_no = 1;
  6534. if (env->line_no == env->line_count) break;
  6535. do {
  6536. env->line_no++;
  6537. if (env->lines[env->line_no-1]->actual == 0) break;
  6538. } while (env->line_no < env->line_count);
  6539. set_preferred_column();
  6540. redraw_statusbar();
  6541. break;
  6542. case '$': /* Move cursor to end of line */
  6543. cursor_end();
  6544. break;
  6545. case '^':
  6546. case '0': /* Move cursor to beginning of line */
  6547. cursor_home();
  6548. break;
  6549. }
  6550. }
  6551. /**
  6552. * Macro for redrawing selected lines with appropriate highlighting.
  6553. */
  6554. #define _redraw_line(line, force_start_line) \
  6555. do { \
  6556. if (!(force_start_line) && (line) == env->start_line) break; \
  6557. if ((line) > env->line_count + 1) { \
  6558. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6559. draw_excess_line((line) - env->offset - 1); \
  6560. } \
  6561. break; \
  6562. } \
  6563. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  6564. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  6565. (env->line_no == env->start_line && (line) != env->start_line)) { \
  6566. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  6567. } else { \
  6568. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  6569. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  6570. } \
  6571. } \
  6572. if ((line) - env->offset + 1 > 1 && \
  6573. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  6574. redraw_line((line) - env->offset - 1, (line)-1); \
  6575. } \
  6576. } while (0)
  6577. /**
  6578. * Adjust indentation on selected lines.
  6579. */
  6580. void adjust_indent(int start_line, int direction) {
  6581. int lines_to_cover = 0;
  6582. int start_point = 0;
  6583. if (start_line <= env->line_no) {
  6584. start_point = start_line - 1;
  6585. lines_to_cover = env->line_no - start_line + 1;
  6586. } else {
  6587. start_point = env->line_no - 1;
  6588. lines_to_cover = start_line - env->line_no + 1;
  6589. }
  6590. for (int i = 0; i < lines_to_cover; ++i) {
  6591. if ((direction == -1) && env->lines[start_point + i]->actual < 1) continue;
  6592. if (direction == -1) {
  6593. if (env->tabs) {
  6594. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  6595. line_delete(env->lines[start_point + i],1,start_point+i);
  6596. _redraw_line(start_point+i+1,1);
  6597. }
  6598. } else {
  6599. for (int j = 0; j < env->tabstop; ++j) {
  6600. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  6601. line_delete(env->lines[start_point + i],1,start_point+i);
  6602. }
  6603. }
  6604. _redraw_line(start_point+i+1,1);
  6605. }
  6606. } else if (direction == 1) {
  6607. if (env->tabs) {
  6608. char_t c;
  6609. c.codepoint = '\t';
  6610. c.display_width = env->tabstop;
  6611. c.flags = FLAG_SELECT;
  6612. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6613. } else {
  6614. for (int j = 0; j < env->tabstop; ++j) {
  6615. char_t c;
  6616. c.codepoint = ' ';
  6617. c.display_width = 1;
  6618. c.flags = FLAG_SELECT;
  6619. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6620. }
  6621. }
  6622. _redraw_line(start_point+i+1,1);
  6623. }
  6624. }
  6625. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6626. env->col_no = env->lines[env->line_no-1]->actual;
  6627. }
  6628. set_preferred_column();
  6629. set_modified();
  6630. }
  6631. /**
  6632. * LINE SELECTION mode
  6633. *
  6634. * Equivalent to visual line in vim; selects lines of texts.
  6635. */
  6636. void line_selection_mode(void) {
  6637. env->start_line = env->line_no;
  6638. int prev_line = env->start_line;
  6639. env->mode = MODE_LINE_SELECTION;
  6640. redraw_commandline();
  6641. int c;
  6642. int timeout = 0;
  6643. int this_buf[20];
  6644. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  6645. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  6646. }
  6647. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6648. while ((c = bim_getch())) {
  6649. if (c == -1) {
  6650. if (timeout && this_buf[timeout-1] == '\033') {
  6651. goto _leave_select_line;
  6652. }
  6653. timeout = 0;
  6654. continue;
  6655. } else {
  6656. if (timeout == 0) {
  6657. switch (c) {
  6658. case '\033':
  6659. if (timeout == 0) {
  6660. this_buf[timeout] = c;
  6661. timeout++;
  6662. }
  6663. break;
  6664. case DELETE_KEY:
  6665. case BACKSPACE_KEY:
  6666. cursor_left();
  6667. break;
  6668. case '\t':
  6669. if (env->readonly) goto _readonly;
  6670. adjust_indent(env->start_line, 1);
  6671. break;
  6672. case 'V':
  6673. goto _leave_select_line;
  6674. case 'y':
  6675. yank_lines(env->start_line, env->line_no);
  6676. goto _leave_select_line;
  6677. case 'D':
  6678. case 'd':
  6679. if (env->readonly) goto _readonly;
  6680. yank_lines(env->start_line, env->line_no);
  6681. if (env->start_line <= env->line_no) {
  6682. int lines_to_delete = env->line_no - env->start_line + 1;
  6683. for (int i = 0; i < lines_to_delete; ++i) {
  6684. remove_line(env->lines, env->start_line-1);
  6685. }
  6686. env->line_no = env->start_line;
  6687. } else {
  6688. int lines_to_delete = env->start_line - env->line_no + 1;
  6689. for (int i = 0; i < lines_to_delete; ++i) {
  6690. remove_line(env->lines, env->line_no-1);
  6691. }
  6692. }
  6693. if (env->line_no > env->line_count) {
  6694. env->line_no = env->line_count;
  6695. }
  6696. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6697. env->col_no = env->lines[env->line_no-1]->actual;
  6698. }
  6699. set_preferred_column();
  6700. set_modified();
  6701. goto _leave_select_line;
  6702. case ':': /* Handle command mode specially for redraw */
  6703. command_mode();
  6704. goto _leave_select_line;
  6705. default:
  6706. handle_navigation(c);
  6707. break;
  6708. }
  6709. } else {
  6710. switch (handle_escape(this_buf,&timeout,c)) {
  6711. case 1:
  6712. bim_unget(c);
  6713. goto _leave_select_line;
  6714. case 'Z':
  6715. /* Unindent */
  6716. if (env->readonly) goto _readonly;
  6717. adjust_indent(env->start_line, -1);
  6718. break;
  6719. }
  6720. }
  6721. /* Mark current line */
  6722. _redraw_line(env->line_no,0);
  6723. /* Properly mark everything in the span we just moved through */
  6724. if (prev_line < env->line_no) {
  6725. for (int i = prev_line; i < env->line_no; ++i) {
  6726. _redraw_line(i,0);
  6727. }
  6728. prev_line = env->line_no;
  6729. } else if (prev_line > env->line_no) {
  6730. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  6731. _redraw_line(i,0);
  6732. }
  6733. prev_line = env->line_no;
  6734. }
  6735. redraw_commandline();
  6736. place_cursor_actual();
  6737. continue;
  6738. _readonly:
  6739. render_error("Buffer is read-only");
  6740. }
  6741. }
  6742. _leave_select_line:
  6743. set_history_break();
  6744. env->mode = MODE_NORMAL;
  6745. for (int i = 0; i < env->line_count; ++i) {
  6746. recalculate_syntax(env->lines[i],i);
  6747. }
  6748. redraw_all();
  6749. }
  6750. #define _redraw_line_col(line, force_start_line) \
  6751. do {\
  6752. if (!(force_start_line) && (line) == env->start_line) break; \
  6753. if ((line) > env->line_count + 1) { \
  6754. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6755. draw_excess_line((line) - env->offset - 1); \
  6756. } \
  6757. break; \
  6758. } \
  6759. if ((line) - env->offset + 1 > 1 && \
  6760. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  6761. redraw_line((line) - env->offset - 1, (line)-1); \
  6762. } \
  6763. } while (0)
  6764. void col_insert_mode(void) {
  6765. if (env->start_line < env->line_no) {
  6766. /* swap */
  6767. int tmp = env->line_no;
  6768. env->line_no = env->start_line;
  6769. env->start_line = tmp;
  6770. }
  6771. /* Set column to preferred_column */
  6772. env->mode = MODE_COL_INSERT;
  6773. redraw_commandline();
  6774. place_cursor_actual();
  6775. int cin;
  6776. uint32_t c;
  6777. int timeout = 0;
  6778. int this_buf[20];
  6779. uint32_t istate = 0;
  6780. int redraw = 0;
  6781. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  6782. if (cin == -1) {
  6783. if (redraw) {
  6784. if (redraw & 2) {
  6785. redraw_text();
  6786. } else {
  6787. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6788. }
  6789. redraw_statusbar();
  6790. place_cursor_actual();
  6791. redraw = 0;
  6792. }
  6793. if (timeout && this_buf[timeout-1] == '\033') {
  6794. return;
  6795. }
  6796. timeout = 0;
  6797. continue;
  6798. }
  6799. if (!decode(&istate, &c, cin)) {
  6800. if (timeout == 0) {
  6801. switch (c) {
  6802. case '\033':
  6803. if (timeout == 0) {
  6804. this_buf[timeout] = c;
  6805. timeout++;
  6806. }
  6807. break;
  6808. case DELETE_KEY:
  6809. case BACKSPACE_KEY:
  6810. if (env->sel_col > 0) {
  6811. int prev_width = 0;
  6812. for (int i = env->line_no; i <= env->start_line; i++) {
  6813. line_t * line = env->lines[i - 1];
  6814. int _x = 0;
  6815. int col = 1;
  6816. int j = 0;
  6817. for (; j < line->actual; ++j) {
  6818. char_t * c = &line->text[j];
  6819. _x += c->display_width;
  6820. col = j+1;
  6821. prev_width = c->display_width;
  6822. if (_x > env->sel_col) break;
  6823. }
  6824. if ((_x == env->sel_col && j == line->actual)) {
  6825. line_delete(line, line->actual, i - 1);
  6826. set_modified();
  6827. } else if (_x > env->sel_col) {
  6828. line_delete(line, col - 1, i - 1);
  6829. set_modified();
  6830. }
  6831. }
  6832. env->sel_col -= prev_width;
  6833. redraw_text();
  6834. }
  6835. break;
  6836. case ENTER_KEY:
  6837. case LINE_FEED:
  6838. /* do nothing in these cases */
  6839. break;
  6840. case 23: /* ^W */
  6841. break;
  6842. case 22: /* ^V */
  6843. render_commandline_message("^V");
  6844. while ((cin = bim_getch()) == -1);
  6845. c = cin;
  6846. redraw_commandline();
  6847. /* fallthrough */
  6848. default:
  6849. /* Okay, this is going to duplicate a lot of insert_char */
  6850. if (c) {
  6851. char_t _c;
  6852. _c.codepoint = c;
  6853. _c.flags = 0;
  6854. _c.display_width = codepoint_width(c);
  6855. /* For each line */
  6856. for (int i = env->line_no; i <= env->start_line; i++) {
  6857. line_t * line = env->lines[i - 1];
  6858. int _x = 0;
  6859. int col = 1;
  6860. int j = 0;
  6861. for (; j < line->actual; ++j) {
  6862. char_t * c = &line->text[j];
  6863. _x += c->display_width;
  6864. col = j+1;
  6865. if (_x > env->sel_col) break;
  6866. }
  6867. if ((_x == env->sel_col && j == line->actual)) {
  6868. _x = env->sel_col + 1;
  6869. col = line->actual + 1;
  6870. }
  6871. if (_x > env->sel_col) {
  6872. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  6873. if (line != nline) {
  6874. env->lines[i - 1] = nline;
  6875. }
  6876. set_modified();
  6877. }
  6878. }
  6879. env->sel_col += _c.display_width;
  6880. redraw_text();
  6881. }
  6882. }
  6883. } else {
  6884. /* Don't handle escapes */
  6885. }
  6886. } else if (istate == UTF8_REJECT) {
  6887. istate = 0;
  6888. }
  6889. }
  6890. }
  6891. /**
  6892. * COL SELECTION mode
  6893. *
  6894. * Limited selection mode for doing inserts on multiple lines.
  6895. * Experimental. Based on how I usually use vim's VISUAL BLOCK mode.
  6896. */
  6897. void col_selection_mode(void) {
  6898. env->start_line = env->line_no;
  6899. env->sel_col = env->preferred_column;
  6900. int prev_line = env->start_line;
  6901. env->mode = MODE_COL_SELECTION;
  6902. redraw_commandline();
  6903. int c;
  6904. int timeout = 0;
  6905. int this_buf[20];
  6906. while ((c = bim_getch())) {
  6907. if (c == -1) {
  6908. if (timeout && this_buf[timeout-1] == '\033') {
  6909. goto _leave_select_col;
  6910. }
  6911. timeout = 0;
  6912. continue;
  6913. } else {
  6914. if (timeout == 0) {
  6915. switch (c) {
  6916. case '\033':
  6917. if (timeout == 0) {
  6918. this_buf[timeout] = c;
  6919. timeout++;
  6920. }
  6921. break;
  6922. case 'I':
  6923. if (env->readonly) goto _readonly;
  6924. col_insert_mode();
  6925. goto _leave_select_col;
  6926. case 'a':
  6927. if (env->readonly) goto _readonly;
  6928. env->sel_col += 1;
  6929. redraw_text();
  6930. col_insert_mode();
  6931. goto _leave_select_col;
  6932. case ':':
  6933. command_mode();
  6934. goto _leave_select_col;
  6935. default:
  6936. handle_navigation(c);
  6937. break;
  6938. }
  6939. } else {
  6940. switch (handle_escape(this_buf,&timeout,c)) {
  6941. case 1:
  6942. bim_unget(c);
  6943. goto _leave_select_col;
  6944. /* Doesn't support anything else. */
  6945. }
  6946. }
  6947. }
  6948. _redraw_line_col(env->line_no, 0);
  6949. /* Properly mark everything in the span we just moved through */
  6950. if (prev_line < env->line_no) {
  6951. for (int i = prev_line; i < env->line_no; ++i) {
  6952. _redraw_line_col(i,0);
  6953. }
  6954. prev_line = env->line_no;
  6955. } else if (prev_line > env->line_no) {
  6956. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  6957. _redraw_line_col(i,0);
  6958. }
  6959. prev_line = env->line_no;
  6960. }
  6961. /* prev_line... */
  6962. redraw_commandline();
  6963. place_cursor_actual();
  6964. continue;
  6965. _readonly:
  6966. render_error("Buffer is read-only.");
  6967. }
  6968. _leave_select_col:
  6969. set_history_break();
  6970. env->mode = MODE_NORMAL;
  6971. redraw_all();
  6972. }
  6973. /**
  6974. * Determine if a column + line number are within range of the
  6975. * current character selection specified by start_line, etc.
  6976. *
  6977. * Used to determine how syntax flags should be set when redrawing
  6978. * selected text in CHAR SELECTION mode.
  6979. */
  6980. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  6981. if (start_line == end_line) {
  6982. if ( end_col < start_col) {
  6983. int tmp = end_col;
  6984. end_col = start_col;
  6985. start_col = tmp;
  6986. }
  6987. return (col >= start_col && col <= end_col);
  6988. }
  6989. if (start_line > end_line) {
  6990. int tmp = end_line;
  6991. end_line = start_line;
  6992. start_line = tmp;
  6993. tmp = end_col;
  6994. end_col = start_col;
  6995. start_col = tmp;
  6996. }
  6997. if (line < start_line || line > end_line) return 0;
  6998. if (line == start_line) {
  6999. return col >= start_col;
  7000. }
  7001. if (line == end_line) {
  7002. return col <= end_col;
  7003. }
  7004. return 1;
  7005. }
  7006. #define _redraw_line_char(line, force_start_line) \
  7007. do { \
  7008. if (!(force_start_line) && (line) == start_line) break; \
  7009. if ((line) > env->line_count + 1) { \
  7010. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7011. draw_excess_line((line) - env->offset - 1); \
  7012. } \
  7013. break; \
  7014. } \
  7015. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  7016. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  7017. (env->line_no == start_line && (line) != start_line)) { \
  7018. /* Line is completely outside selection */ \
  7019. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7020. } else { \
  7021. if ((line) == start_line || (line) == env->line_no) { \
  7022. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7023. } \
  7024. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7025. if (point_in_range(start_line, env->line_no,start_col, env->col_no, (line), j+1)) { \
  7026. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7027. } \
  7028. } \
  7029. } \
  7030. if ((line) - env->offset + 1 > 1 && \
  7031. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  7032. redraw_line((line) - env->offset - 1, (line)-1); \
  7033. } \
  7034. } while (0)
  7035. /**
  7036. * CHAR SELECTION mode.
  7037. */
  7038. void char_selection_mode(void) {
  7039. int start_line = env->line_no;
  7040. int start_col = env->col_no;
  7041. int prev_line = start_line;
  7042. env->mode = MODE_CHAR_SELECTION;
  7043. redraw_commandline();
  7044. int c;
  7045. int timeout = 0;
  7046. int this_buf[20];
  7047. /* Select single character */
  7048. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7049. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7050. while ((c = bim_getch())) {
  7051. if (c == -1) {
  7052. if (timeout && this_buf[timeout-1] == '\033') {
  7053. goto _leave_select_char;
  7054. }
  7055. timeout = 0;
  7056. continue;
  7057. } else {
  7058. if (timeout == 0) {
  7059. switch (c) {
  7060. case '\033':
  7061. if (timeout == 0) {
  7062. this_buf[timeout] = c;
  7063. timeout++;
  7064. }
  7065. break;
  7066. case DELETE_KEY:
  7067. case BACKSPACE_KEY:
  7068. cursor_left();
  7069. break;
  7070. case 'v':
  7071. goto _leave_select_char;
  7072. case 'y':
  7073. {
  7074. int end_line = env->line_no;
  7075. int end_col = env->col_no;
  7076. if (start_line == end_line) {
  7077. if (start_col > end_col) {
  7078. int tmp = start_col;
  7079. start_col = end_col;
  7080. end_col = tmp;
  7081. }
  7082. } else if (start_line > end_line) {
  7083. int tmp = start_line;
  7084. start_line = end_line;
  7085. end_line = tmp;
  7086. tmp = start_col;
  7087. start_col = end_col;
  7088. end_col = tmp;
  7089. }
  7090. yank_text(start_line, start_col, end_line, end_col);
  7091. }
  7092. goto _leave_select_char;
  7093. case 'D':
  7094. case 'd':
  7095. if (env->readonly) goto _readonly;
  7096. {
  7097. int end_line = env->line_no;
  7098. int end_col = env->col_no;
  7099. if (start_line == end_line) {
  7100. if (start_col > end_col) {
  7101. int tmp = start_col;
  7102. start_col = end_col;
  7103. end_col = tmp;
  7104. }
  7105. yank_text(start_line, start_col, end_line, end_col);
  7106. for (int i = start_col; i <= end_col; ++i) {
  7107. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  7108. }
  7109. env->col_no = start_col;
  7110. } else {
  7111. if (start_line > end_line) {
  7112. int tmp = start_line;
  7113. start_line = end_line;
  7114. end_line = tmp;
  7115. tmp = start_col;
  7116. start_col = end_col;
  7117. end_col = tmp;
  7118. }
  7119. /* Copy lines */
  7120. yank_text(start_line, start_col, end_line, end_col);
  7121. /* Delete lines */
  7122. for (int i = start_line+1; i < end_line; ++i) {
  7123. remove_line(env->lines, start_line);
  7124. } /* end_line is no longer valid; should be start_line+1*/
  7125. /* Delete from start_col forward */
  7126. int tmp = env->lines[start_line-1]->actual;
  7127. for (int i = start_col; i <= tmp; ++i) {
  7128. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  7129. }
  7130. for (int i = 1; i <= end_col; ++i) {
  7131. line_delete(env->lines[start_line], 1, start_line);
  7132. }
  7133. /* Merge start and end lines */
  7134. merge_lines(env->lines, start_line);
  7135. env->line_no = start_line;
  7136. env->col_no = start_col;
  7137. }
  7138. }
  7139. if (env->line_no > env->line_count) {
  7140. env->line_no = env->line_count;
  7141. }
  7142. set_preferred_column();
  7143. set_modified();
  7144. goto _leave_select_char;
  7145. case ':':
  7146. command_mode();
  7147. goto _leave_select_char;
  7148. default:
  7149. handle_navigation(c);
  7150. break;
  7151. }
  7152. } else {
  7153. switch (handle_escape(this_buf,&timeout,c)) {
  7154. case 1:
  7155. bim_unget(c);
  7156. goto _leave_select_char;
  7157. }
  7158. }
  7159. /* Mark current line */
  7160. _redraw_line_char(env->line_no,1);
  7161. /* Properly mark everything in the span we just moved through */
  7162. if (prev_line < env->line_no) {
  7163. for (int i = prev_line; i < env->line_no; ++i) {
  7164. _redraw_line_char(i,1);
  7165. }
  7166. prev_line = env->line_no;
  7167. } else if (prev_line > env->line_no) {
  7168. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  7169. _redraw_line_char(i,1);
  7170. }
  7171. prev_line = env->line_no;
  7172. }
  7173. place_cursor_actual();
  7174. continue;
  7175. _readonly:
  7176. render_error("Buffer is read-only");
  7177. }
  7178. }
  7179. _leave_select_char:
  7180. set_history_break();
  7181. env->mode = MODE_NORMAL;
  7182. for (int i = 0; i < env->line_count; ++i) {
  7183. recalculate_syntax(env->lines[i],i);
  7184. }
  7185. redraw_all();
  7186. }
  7187. /**
  7188. * INSERT mode
  7189. *
  7190. * Accept input into the text buffer.
  7191. */
  7192. void insert_mode(void) {
  7193. int cin;
  7194. uint32_t c;
  7195. /* Set mode line */
  7196. env->mode = MODE_INSERT;
  7197. redraw_commandline();
  7198. /* Place the cursor in the text area */
  7199. place_cursor_actual();
  7200. int timeout = 0;
  7201. int this_buf[20];
  7202. uint32_t istate = 0;
  7203. int redraw = 0;
  7204. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  7205. if (cin == -1) {
  7206. if (redraw) {
  7207. if (redraw & 2) {
  7208. redraw_text();
  7209. } else {
  7210. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7211. }
  7212. redraw_statusbar();
  7213. place_cursor_actual();
  7214. redraw = 0;
  7215. }
  7216. if (timeout && this_buf[timeout-1] == '\033') {
  7217. leave_insert();
  7218. return;
  7219. }
  7220. timeout = 0;
  7221. continue;
  7222. }
  7223. if (!decode(&istate, &c, cin)) {
  7224. if (timeout == 0) {
  7225. switch (c) {
  7226. case '\033':
  7227. if (timeout == 0) {
  7228. this_buf[timeout] = c;
  7229. timeout++;
  7230. }
  7231. break;
  7232. case DELETE_KEY:
  7233. case BACKSPACE_KEY:
  7234. delete_at_cursor();
  7235. break;
  7236. case ENTER_KEY:
  7237. case LINE_FEED:
  7238. if (env->indent) {
  7239. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0xF) == FLAG_COMMENT &&
  7240. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7241. (env->col_no > 3) &&
  7242. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7243. delete_at_cursor();
  7244. }
  7245. }
  7246. insert_line_feed();
  7247. redraw |= 2;
  7248. break;
  7249. case 22: /* ^V */
  7250. /* Insert next byte raw */
  7251. {
  7252. /* Indicate we're in literal mode */
  7253. render_commandline_message("^V");
  7254. /* Put the cursor back into the text field */
  7255. place_cursor_actual();
  7256. /* Get next character */
  7257. while ((cin = bim_getch()) == -1);
  7258. /* Insert literal */
  7259. insert_char(cin);
  7260. /* Redraw INSERT */
  7261. redraw_commandline();
  7262. /* Draw text */
  7263. redraw |= 1;
  7264. }
  7265. break;
  7266. case 23: /* ^W */
  7267. delete_word();
  7268. set_preferred_column();
  7269. break;
  7270. case '\t':
  7271. if (env->tabs) {
  7272. insert_char('\t');
  7273. } else {
  7274. for (int i = 0; i < env->tabstop; ++i) {
  7275. insert_char(' ');
  7276. }
  7277. }
  7278. redraw |= 1;
  7279. set_preferred_column();
  7280. break;
  7281. case '/':
  7282. if (env->indent) {
  7283. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0xF) == FLAG_COMMENT &&
  7284. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7285. (env->col_no > 3) &&
  7286. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7287. env->col_no--;
  7288. replace_char('/');
  7289. env->col_no++;
  7290. place_cursor_actual();
  7291. break;
  7292. }
  7293. }
  7294. goto _just_insert;
  7295. case '}':
  7296. if (env->indent) {
  7297. int was_whitespace = 1;
  7298. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7299. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  7300. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  7301. was_whitespace = 0;
  7302. break;
  7303. }
  7304. }
  7305. insert_char('}');
  7306. if (was_whitespace) {
  7307. int line = -1, col = -1;
  7308. env->col_no--;
  7309. find_matching_paren(&line,&col, 1);
  7310. if (line != -1) {
  7311. while (env->lines[env->line_no-1]->actual) {
  7312. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  7313. }
  7314. add_indent(env->line_no-1,line-1,1);
  7315. env->col_no = env->lines[env->line_no-1]->actual + 1;
  7316. insert_char('}');
  7317. }
  7318. }
  7319. set_preferred_column();
  7320. redraw |= 1;
  7321. break;
  7322. }
  7323. /* fallthrough */
  7324. default:
  7325. _just_insert:
  7326. insert_char(c);
  7327. set_preferred_column();
  7328. redraw |= 1;
  7329. break;
  7330. }
  7331. } else {
  7332. if (handle_escape(this_buf,&timeout,c)) {
  7333. bim_unget(c);
  7334. leave_insert();
  7335. return;
  7336. }
  7337. }
  7338. } else if (istate == UTF8_REJECT) {
  7339. istate = 0;
  7340. }
  7341. }
  7342. }
  7343. /**
  7344. * REPLACE mode
  7345. *
  7346. * Like insert, but replaces characters.
  7347. */
  7348. void replace_mode(void) {
  7349. int cin;
  7350. uint32_t c;
  7351. /* Set mode line */
  7352. env->mode = MODE_REPLACE;
  7353. redraw_commandline();
  7354. /* Place the cursor in the text area */
  7355. place_cursor_actual();
  7356. int timeout = 0;
  7357. int this_buf[20];
  7358. uint32_t istate = 0;
  7359. while ((cin = bim_getch())) {
  7360. if (cin == -1) {
  7361. if (timeout && this_buf[timeout-1] == '\033') {
  7362. leave_insert();
  7363. return;
  7364. }
  7365. timeout = 0;
  7366. continue;
  7367. }
  7368. if (!decode(&istate, &c, cin)) {
  7369. if (timeout == 0) {
  7370. switch (c) {
  7371. case '\033':
  7372. if (timeout == 0) {
  7373. this_buf[timeout] = c;
  7374. timeout++;
  7375. }
  7376. break;
  7377. case DELETE_KEY:
  7378. case BACKSPACE_KEY:
  7379. if (env->line_no > 1 && env->col_no == 1) {
  7380. env->line_no--;
  7381. env->col_no = env->lines[env->line_no-1]->actual;
  7382. set_preferred_column();
  7383. place_cursor_actual();
  7384. } else {
  7385. cursor_left();
  7386. }
  7387. break;
  7388. case ENTER_KEY:
  7389. case LINE_FEED:
  7390. insert_line_feed();
  7391. redraw_text();
  7392. set_modified();
  7393. redraw_statusbar();
  7394. place_cursor_actual();
  7395. break;
  7396. default:
  7397. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  7398. replace_char(c);
  7399. env->col_no += 1;
  7400. } else {
  7401. insert_char(c);
  7402. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7403. }
  7404. redraw_statusbar();
  7405. place_cursor_actual();
  7406. break;
  7407. }
  7408. } else {
  7409. if (handle_escape(this_buf,&timeout,c)) {
  7410. bim_unget(c);
  7411. leave_insert();
  7412. return;
  7413. }
  7414. }
  7415. } else if (istate == UTF8_REJECT) {
  7416. istate = 0;
  7417. }
  7418. }
  7419. }
  7420. void replace_one(void) {
  7421. /* Read one character and replace */
  7422. render_commandline_message("r");
  7423. uint32_t state = 0;
  7424. int cin;
  7425. uint32_t c;
  7426. while ((cin = bim_getch())) {
  7427. if (cin == -1) continue;
  7428. if (!decode(&state, &c, cin)) {
  7429. if (c == '\033') {
  7430. return;
  7431. } else if (c == 22) { /* ctrl-v */
  7432. render_commandline_message("r ^V");
  7433. while ((cin = bim_getch()) == -1);
  7434. replace_char(cin);
  7435. return;
  7436. } else {
  7437. replace_char(c);
  7438. return;
  7439. }
  7440. }
  7441. }
  7442. return;
  7443. }
  7444. /**
  7445. * NORMAL mode
  7446. *
  7447. * Default editor mode - just cursor navigation and keybinds
  7448. * to enter the other modes.
  7449. */
  7450. void normal_mode(void) {
  7451. while (1) {
  7452. place_cursor_actual();
  7453. int c;
  7454. int timeout = 0;
  7455. int this_buf[20];
  7456. while ((c = bim_getch())) {
  7457. if (c == -1) {
  7458. /* getch timed out, nothing to do in normal mode */
  7459. continue;
  7460. }
  7461. if (timeout == 0) {
  7462. switch (c) {
  7463. case '\033':
  7464. if (timeout == 0) {
  7465. this_buf[timeout] = c;
  7466. timeout++;
  7467. }
  7468. break;
  7469. case DELETE_KEY:
  7470. case BACKSPACE_KEY:
  7471. if (env->line_no > 1 && env->col_no == 1) {
  7472. env->line_no--;
  7473. env->col_no = env->lines[env->line_no-1]->actual;
  7474. set_preferred_column();
  7475. place_cursor_actual();
  7476. } else {
  7477. cursor_left();
  7478. }
  7479. break;
  7480. case 'V': /* Enter LINE SELECTION mode */
  7481. line_selection_mode();
  7482. break;
  7483. case 'v': /* Enter CHAR SELECTION mode */
  7484. char_selection_mode();
  7485. break;
  7486. case 22: /* ctrl-v, enter COL SELECTION mode */
  7487. col_selection_mode();
  7488. break;
  7489. case 'O': /* Append line before and enter INSERT mode */
  7490. {
  7491. if (env->readonly) goto _readonly;
  7492. env->lines = add_line(env->lines, env->line_no-1);
  7493. env->col_no = 1;
  7494. add_indent(env->line_no-1,env->line_no,0);
  7495. redraw_text();
  7496. set_preferred_column();
  7497. set_modified();
  7498. place_cursor_actual();
  7499. goto _insert;
  7500. }
  7501. case 'o': /* Append line after and enter INSERT mode */
  7502. {
  7503. if (env->readonly) goto _readonly;
  7504. env->lines = add_line(env->lines, env->line_no);
  7505. env->col_no = 1;
  7506. env->line_no += 1;
  7507. add_indent(env->line_no-1,env->line_no-2,0);
  7508. set_preferred_column();
  7509. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7510. env->offset += 1;
  7511. }
  7512. redraw_text();
  7513. set_modified();
  7514. place_cursor_actual();
  7515. goto _insert;
  7516. }
  7517. case 'a': /* Enter INSERT mode with cursor after current position */
  7518. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  7519. env->col_no += 1;
  7520. }
  7521. goto _insert;
  7522. case 'P': /* Paste before */
  7523. case 'p': /* Paste after */
  7524. if (env->readonly) goto _readonly;
  7525. if (global_config.yanks) {
  7526. if (!global_config.yank_is_full_lines) {
  7527. /* Handle P for paste before, p for past after */
  7528. int target_column = (c == 'P' ? (env->col_no) : (env->col_no+1));
  7529. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  7530. target_column = env->lines[env->line_no-1]->actual + 1;
  7531. }
  7532. if (global_config.yank_count > 1) {
  7533. /* Spit the current line at the current position */
  7534. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  7535. }
  7536. /* Insert first line at current position */
  7537. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  7538. env->lines[env->line_no - 1] = line_insert(env->lines[env->line_no - 1], global_config.yanks[0]->text[i], target_column + i - 1, env->line_no - 1);
  7539. }
  7540. if (global_config.yank_count > 1) {
  7541. /* Insert full lines */
  7542. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7543. env->lines = add_line(env->lines, env->line_no);
  7544. }
  7545. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7546. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  7547. }
  7548. /* Insert characters from last line into (what was) the next line */
  7549. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  7550. env->lines[env->line_no + global_config.yank_count - 2] = line_insert(env->lines[env->line_no + global_config.yank_count - 2], global_config.yanks[global_config.yank_count-1]->text[i], i, env->line_no + global_config.yank_count - 2);
  7551. }
  7552. }
  7553. } else {
  7554. /* Insert full lines */
  7555. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7556. env->lines = add_line(env->lines, env->line_no - (c == 'P' ? 1 : 0));
  7557. }
  7558. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7559. replace_line(env->lines, env->line_no - (c == 'P' ? 1 : 0) + i, global_config.yanks[i]);
  7560. }
  7561. }
  7562. /* Recalculate whole document syntax */
  7563. for (int i = 0; i < env->line_count; ++i) {
  7564. env->lines[i]->istate = 0;
  7565. }
  7566. for (int i = 0; i < env->line_count; ++i) {
  7567. recalculate_syntax(env->lines[i],i);
  7568. }
  7569. if (c == 'p') {
  7570. if (global_config.yank_is_full_lines) {
  7571. env->line_no += 1;
  7572. } else {
  7573. if (global_config.yank_count == 1) {
  7574. env->col_no = env->col_no + global_config.yanks[0]->actual;
  7575. } else {
  7576. env->line_no = env->line_no + global_config.yank_count - 1;
  7577. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  7578. }
  7579. }
  7580. }
  7581. set_history_break();
  7582. set_modified();
  7583. redraw_all();
  7584. }
  7585. break;
  7586. case 'r': /* Replace with next */
  7587. replace_one();
  7588. redraw_commandline();
  7589. break;
  7590. case 'u': /* Undo one block of history */
  7591. undo_history();
  7592. break;
  7593. case 18: /* ^R - Redo one block of history */
  7594. redo_history();
  7595. break;
  7596. case 12: /* ^L - Repaint the whole screen */
  7597. redraw_all();
  7598. break;
  7599. case 'i': /* Enter INSERT mode */
  7600. _insert:
  7601. if (env->readonly) goto _readonly;
  7602. insert_mode();
  7603. redraw_statusbar();
  7604. redraw_commandline();
  7605. timeout = 0;
  7606. break;
  7607. case 'R': /* Enter REPLACE mode */
  7608. if (env->readonly) goto _readonly;
  7609. replace_mode();
  7610. redraw_statusbar();
  7611. redraw_commandline();
  7612. timeout = 0;
  7613. break;
  7614. _readonly:
  7615. render_error("Buffer is read-only");
  7616. break;
  7617. default:
  7618. handle_navigation(c);
  7619. break;
  7620. }
  7621. } else {
  7622. handle_escape(this_buf,&timeout,c);
  7623. }
  7624. place_cursor_actual();
  7625. }
  7626. }
  7627. }
  7628. /**
  7629. * Show help text for -?
  7630. */
  7631. static void show_usage(char * argv[]) {
  7632. #define _s "\033[3m"
  7633. #define _e "\033[0m\n"
  7634. printf(
  7635. "bim - Text editor\n"
  7636. "\n"
  7637. "usage: %s [options] [file]\n"
  7638. " %s [options] -- -\n"
  7639. "\n"
  7640. " -R " _s "open initial buffer read-only" _e
  7641. " -O " _s "set various options:" _e
  7642. " noscroll " _s "disable terminal scrolling" _e
  7643. " noaltscreen " _s "disable alternate screen buffer" _e
  7644. " nomouse " _s "disable mouse support" _e
  7645. " nounicode " _s "disable unicode display" _e
  7646. " nobright " _s "disable bright next" _e
  7647. " nohideshow " _s "disable togglging cursor visibility" _e
  7648. " nosyntax " _s "disable syntax highlighting on load" _e
  7649. " notitle " _s "disable title-setting escapes" _e
  7650. " history " _s "enable experimental undo/redo" _e
  7651. " -c,-C " _s "print file to stdout with syntax hilighting" _e
  7652. " " _s "-C includes line numbers, -c does not" _e
  7653. " -u " _s "override bimrc file" _e
  7654. " -? " _s "show this help text" _e
  7655. " --version " _s "show version information and available plugins" _e
  7656. "\n", argv[0], argv[0]);
  7657. #undef _e
  7658. #undef _s
  7659. }
  7660. /**
  7661. * Load bimrc configuration file.
  7662. *
  7663. * At the moment, this a simple key=value list.
  7664. */
  7665. void load_bimrc(void) {
  7666. if (!global_config.bimrc_path) return;
  7667. /* Default is ~/.bimrc */
  7668. char * tmp = strdup(global_config.bimrc_path);
  7669. if (!*tmp) {
  7670. free(tmp);
  7671. return;
  7672. }
  7673. /* Parse ~ at the front of the path. */
  7674. if (*tmp == '~') {
  7675. char path[1024] = {0};
  7676. char * home = getenv("HOME");
  7677. if (!home) {
  7678. /* $HOME is unset? */
  7679. free(tmp);
  7680. return;
  7681. }
  7682. /* New path is $HOME/.bimrc */
  7683. snprintf(path, 1024, "%s%s", home, tmp+1);
  7684. free(tmp);
  7685. tmp = strdup(path);
  7686. }
  7687. /* Try to open the file */
  7688. FILE * bimrc = fopen(tmp, "r");
  7689. free(tmp);
  7690. if (!bimrc) {
  7691. /* No bimrc, or bad permissions */
  7692. return;
  7693. }
  7694. /* Parse through lines */
  7695. char line[1024];
  7696. while (!feof(bimrc)) {
  7697. char * l = fgets(line, 1023, bimrc);
  7698. /* Ignore bad lines */
  7699. if (!l) break;
  7700. if (!*l) continue;
  7701. if (*l == '\n') continue;
  7702. /* Ignore comment lines */
  7703. if (*l == '#') continue;
  7704. /* Remove linefeed at the end */
  7705. char *nl = strstr(l,"\n");
  7706. if (nl) *nl = '\0';
  7707. /* Extract value from keypair, if available
  7708. * (I foresee options without values in the future) */
  7709. char *value= strstr(l,"=");
  7710. if (value) {
  7711. *value = '\0';
  7712. value++;
  7713. }
  7714. /* theme=... */
  7715. if (!strcmp(l,"theme") && value) {
  7716. /* Examine available themes for a match. */
  7717. for (struct theme_def * d = themes; d->name; ++d) {
  7718. if (!strcmp(value, d->name)) {
  7719. d->load();
  7720. break;
  7721. }
  7722. }
  7723. }
  7724. /* enable history (experimental) */
  7725. if (!strcmp(l,"history")) {
  7726. global_config.history_enabled = (value ? atoi(value) : 1);
  7727. }
  7728. /* padding= */
  7729. if (!strcmp(l,"padding") && value) {
  7730. global_config.cursor_padding = atoi(value);
  7731. }
  7732. if (!strcmp(l,"hlparen") && value) {
  7733. global_config.highlight_parens = atoi(value);
  7734. }
  7735. /* Disable hilighting of current line */
  7736. if (!strcmp(l,"hlcurrent") && value) {
  7737. global_config.hilight_current_line = atoi(value);
  7738. }
  7739. if (!strcmp(l,"splitpercent") && value) {
  7740. global_config.split_percent = atoi(value);
  7741. }
  7742. if (!strcmp(l,"shiftscrolling")) {
  7743. global_config.shift_scrolling = (value ? atoi(value) : 1);
  7744. }
  7745. if (!strcmp(l,"scrollamount") && value) {
  7746. global_config.scroll_amount = atoi(value);
  7747. }
  7748. if (!strcmp(l,"git") && value) {
  7749. global_config.check_git = !!atoi(value);
  7750. }
  7751. if (!strcmp(l,"colorgutter") && value) {
  7752. global_config.color_gutter = !!atoi(value);
  7753. }
  7754. }
  7755. fclose(bimrc);
  7756. }
  7757. /**
  7758. * Set some default values when certain terminals are detected.
  7759. */
  7760. void detect_weird_terminals(void) {
  7761. char * term = getenv("TERM");
  7762. if (term && !strcmp(term,"linux")) {
  7763. /* Linux VTs can't scroll. */
  7764. global_config.can_scroll = 0;
  7765. }
  7766. if (term && !strcmp(term,"cons25")) {
  7767. /* Dragonfly BSD console */
  7768. global_config.can_hideshow = 0;
  7769. global_config.can_altscreen = 0;
  7770. global_config.can_mouse = 0;
  7771. global_config.can_unicode = 0;
  7772. global_config.can_bright = 0;
  7773. }
  7774. if (term && !strcmp(term,"sortix")) {
  7775. /* sortix will spew title escapes to the screen, no good */
  7776. global_config.can_title = 0;
  7777. }
  7778. if (term && strstr(term,"tmux") == term) {
  7779. global_config.can_scroll = 0;
  7780. global_config.can_bce = 0;
  7781. }
  7782. if (term && strstr(term,"screen") == term) {
  7783. /* unfortunately */
  7784. global_config.can_24bit = 0;
  7785. global_config.can_italic = 0;
  7786. }
  7787. if (term && strstr(term,"toaru-vga") == term) {
  7788. global_config.can_24bit = 0; /* Also not strictly true */
  7789. global_config.can_256color = 0; /* Not strictly true */
  7790. }
  7791. }
  7792. /**
  7793. * Run global initialization tasks
  7794. */
  7795. void initialize(void) {
  7796. setlocale(LC_ALL, "");
  7797. detect_weird_terminals();
  7798. load_colorscheme_ansi();
  7799. load_bimrc();
  7800. buffers_avail = 4;
  7801. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  7802. }
  7803. /**
  7804. * Initialize terminal for editor display.
  7805. */
  7806. void init_terminal(void) {
  7807. set_alternate_screen();
  7808. update_screen_size();
  7809. get_initial_termios();
  7810. set_unbuffered();
  7811. mouse_enable();
  7812. signal(SIGWINCH, SIGWINCH_handler);
  7813. signal(SIGCONT, SIGCONT_handler);
  7814. signal(SIGTSTP, SIGTSTP_handler);
  7815. }
  7816. int main(int argc, char * argv[]) {
  7817. int opt;
  7818. while ((opt = getopt(argc, argv, "?c:C:u:RO:-:")) != -1) {
  7819. switch (opt) {
  7820. case 'R':
  7821. global_config.initial_file_is_read_only = 1;
  7822. break;
  7823. case 'c':
  7824. case 'C':
  7825. /* Print file to stdout using our syntax highlighting and color theme */
  7826. initialize();
  7827. global_config.go_to_line = 0;
  7828. open_file(optarg);
  7829. for (int i = 0; i < env->line_count; ++i) {
  7830. if (opt == 'C') {
  7831. draw_line_number(i);
  7832. }
  7833. render_line(env->lines[i], 6 * (env->lines[i]->actual + 1), 0, i + 1);
  7834. reset();
  7835. fprintf(stdout, "\n");
  7836. }
  7837. return 0;
  7838. case 'u':
  7839. global_config.bimrc_path = optarg;
  7840. break;
  7841. case 'O':
  7842. /* Set various display options */
  7843. if (!strcmp(optarg,"noaltscreen")) global_config.can_altscreen = 0;
  7844. else if (!strcmp(optarg,"noscroll")) global_config.can_scroll = 0;
  7845. else if (!strcmp(optarg,"nomouse")) global_config.can_mouse = 0;
  7846. else if (!strcmp(optarg,"nounicode")) global_config.can_unicode = 0;
  7847. else if (!strcmp(optarg,"nobright")) global_config.can_bright = 0;
  7848. else if (!strcmp(optarg,"nohideshow")) global_config.can_hideshow = 0;
  7849. else if (!strcmp(optarg,"nosyntax")) global_config.hilight_on_open = 0;
  7850. else if (!strcmp(optarg,"nohistory")) global_config.history_enabled = 0;
  7851. else if (!strcmp(optarg,"notitle")) global_config.can_title = 0;
  7852. else if (!strcmp(optarg,"nobce")) global_config.can_bce = 0;
  7853. else {
  7854. fprintf(stderr, "%s: unrecognized -O option: %s\n", argv[0], optarg);
  7855. return 1;
  7856. }
  7857. break;
  7858. case '-':
  7859. if (!strcmp(optarg,"version")) {
  7860. fprintf(stderr, "bim %s %s\n", BIM_VERSION, BIM_COPYRIGHT);
  7861. fprintf(stderr, " Available syntax highlighters:");
  7862. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  7863. fprintf(stderr, " %s", s->name);
  7864. }
  7865. fprintf(stderr, "\n");
  7866. fprintf(stderr, " Available color themes:");
  7867. for (struct theme_def * d = themes; d->name; ++d) {
  7868. fprintf(stderr, " %s", d->name);
  7869. }
  7870. fprintf(stderr, "\n");
  7871. return 0;
  7872. } else if (!strcmp(optarg,"help")) {
  7873. show_usage(argv);
  7874. return 0;
  7875. }
  7876. break;
  7877. case '?':
  7878. show_usage(argv);
  7879. return 0;
  7880. }
  7881. }
  7882. /* Set up terminal */
  7883. initialize();
  7884. init_terminal();
  7885. /* Open file */
  7886. if (argc > optind) {
  7887. open_file(argv[optind]);
  7888. update_title();
  7889. if (global_config.initial_file_is_read_only) {
  7890. env->readonly = 1;
  7891. }
  7892. } else {
  7893. env = buffer_new();
  7894. update_title();
  7895. setup_buffer(env);
  7896. }
  7897. /* Draw the screen once */
  7898. redraw_all();
  7899. /* Start accepting key commands */
  7900. normal_mode();
  7901. return 0;
  7902. }