bim.c 369 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468
  1. /**
  2. * This is a baked, single-file version of bim.
  3. * It was built Fri Nov 20 14:06:22 2020
  4. * It is based on git commit 496849bab42290f42e9928f510a1d91534fe2a51
  5. */
  6. #define GIT_TAG "496849b-baked"
  7. /* Bim - A Text Editor
  8. *
  9. * Copyright (C) 2012-2020 K. Lange
  10. *
  11. * Permission to use, copy, modify, and/or distribute this software for any
  12. * purpose with or without fee is hereby granted, provided that the above
  13. * copyright notice and this permission notice appear in all copies.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  16. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  17. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  18. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  21. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22. */
  23. /* Included from bim-core.h */
  24. #define _XOPEN_SOURCE 700
  25. #define _DARWIN_C_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. #ifdef __DATE__
  45. # define BIM_BUILD_DATE " built " __DATE__ " at " __TIME__
  46. #else
  47. # define BIM_BUILD_DATE DATE ""
  48. #endif
  49. #ifdef GIT_TAG
  50. # define TAG "-" GIT_TAG
  51. #else
  52. # define TAG ""
  53. #endif
  54. #define BIM_VERSION "2.6.2" TAG
  55. #define BIM_COPYRIGHT "Copyright 2012-2020 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  56. #define BLOCK_SIZE 4096
  57. #define ENTER_KEY '\r'
  58. #define LINE_FEED '\n'
  59. #define BACKSPACE_KEY 0x08
  60. #define DELETE_KEY 0x7F
  61. enum Key {
  62. KEY_TIMEOUT = -1,
  63. KEY_CTRL_AT = 0, /* Base */
  64. KEY_CTRL_A, KEY_CTRL_B, KEY_CTRL_C, KEY_CTRL_D, KEY_CTRL_E, KEY_CTRL_F, KEY_CTRL_G, KEY_CTRL_H,
  65. KEY_CTRL_I, KEY_CTRL_J, KEY_CTRL_K, KEY_CTRL_L, KEY_CTRL_M, KEY_CTRL_N, KEY_CTRL_O, KEY_CTRL_P,
  66. KEY_CTRL_Q, KEY_CTRL_R, KEY_CTRL_S, KEY_CTRL_T, KEY_CTRL_U, KEY_CTRL_V, KEY_CTRL_W, KEY_CTRL_X,
  67. KEY_CTRL_Y, KEY_CTRL_Z, /* Note we keep ctrl-z mapped in termios as suspend */
  68. KEY_CTRL_OPEN, KEY_CTRL_BACKSLASH, KEY_CTRL_CLOSE, KEY_CTRL_CARAT, KEY_CTRL_UNDERSCORE,
  69. /* Space... */
  70. /* Some of these are equivalent to things above */
  71. KEY_BACKSPACE = 0x08,
  72. KEY_LINEFEED = '\n',
  73. KEY_ENTER = '\r',
  74. KEY_TAB = '\t',
  75. /* Basic printable characters go here. */
  76. /* Delete is special */
  77. KEY_DELETE = 0x7F,
  78. /* Unicode codepoints go here */
  79. KEY_ESCAPE = 0x400000, /* Escape would normally be 27, but is special because reasons */
  80. KEY_F1, KEY_F2, KEY_F3, KEY_F4,
  81. KEY_F5, KEY_F6, KEY_F7, KEY_F8,
  82. KEY_F9, KEY_F10, KEY_F11, KEY_F12,
  83. /* TODO ALT, SHIFT, etc., for F keys */
  84. KEY_MOUSE, /* Must be followed with a 3-byte mouse read */
  85. KEY_MOUSE_SGR, /* Followed by an SGR-style sequence of mouse data */
  86. KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN,
  87. KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT,
  88. KEY_SHIFT_UP, KEY_SHIFT_DOWN, KEY_SHIFT_RIGHT, KEY_SHIFT_LEFT,
  89. KEY_CTRL_UP, KEY_CTRL_DOWN, KEY_CTRL_RIGHT, KEY_CTRL_LEFT,
  90. KEY_ALT_UP, KEY_ALT_DOWN, KEY_ALT_RIGHT, KEY_ALT_LEFT,
  91. KEY_ALT_SHIFT_UP, KEY_ALT_SHIFT_DOWN, KEY_ALT_SHIFT_RIGHT, KEY_ALT_SHIFT_LEFT,
  92. KEY_SHIFT_TAB,
  93. /* Special signals for paste start, paste end */
  94. KEY_PASTE_BEGIN, KEY_PASTE_END,
  95. };
  96. struct key_name_map {
  97. enum Key keycode;
  98. char * name;
  99. };
  100. extern struct key_name_map KeyNames[];
  101. /**
  102. * Syntax highlighting flags.
  103. */
  104. #define FLAG_NONE 0
  105. #define FLAG_KEYWORD 1
  106. #define FLAG_STRING 2
  107. #define FLAG_COMMENT 3
  108. #define FLAG_TYPE 4
  109. #define FLAG_PRAGMA 5
  110. #define FLAG_NUMERAL 6
  111. #define FLAG_ERROR 7
  112. #define FLAG_DIFFPLUS 8
  113. #define FLAG_DIFFMINUS 9
  114. #define FLAG_NOTICE 10
  115. #define FLAG_BOLD 11
  116. #define FLAG_LINK 12
  117. #define FLAG_ESCAPE 13
  118. #define FLAG_SELECT (1 << 5)
  119. #define FLAG_SEARCH (1 << 6)
  120. /**
  121. * Line buffer definitions
  122. *
  123. * Lines are essentially resizable vectors of char_t structs,
  124. * which represent single codepoints in the file.
  125. */
  126. typedef struct {
  127. uint32_t display_width:4;
  128. uint32_t flags:7;
  129. uint32_t codepoint:21;
  130. } __attribute__((packed)) char_t;
  131. /**
  132. * Lines have available and actual lengths, describing
  133. * how much space was allocated vs. how much is being
  134. * used at the moment.
  135. */
  136. typedef struct {
  137. int available;
  138. int actual;
  139. int istate;
  140. int is_current;
  141. int rev_status;
  142. char_t text[];
  143. } line_t;
  144. /**
  145. * Global configuration state
  146. *
  147. * At the moment, this is all in a global, but in the future
  148. * this should be passed around to various functions.
  149. */
  150. typedef struct {
  151. /* Terminal size */
  152. int term_width, term_height;
  153. int bottom_size;
  154. line_t ** yanks;
  155. size_t yank_count;
  156. int yank_is_full_lines;
  157. int tty_in;
  158. const char * bimrc_path;
  159. const char * syntax_fallback;
  160. uint32_t * search;
  161. int overlay_mode;
  162. line_t * command_buffer;
  163. int command_offset, command_col_no;
  164. struct syntax_definition * command_syn, * command_syn_back;
  165. int history_point;
  166. int search_direction;
  167. int prev_line, prev_col, prev_coffset, prev_offset;
  168. unsigned int highlight_on_open:1;
  169. unsigned int initial_file_is_read_only:1;
  170. unsigned int go_to_line:1;
  171. unsigned int break_from_selection:1;
  172. unsigned int can_scroll:1;
  173. unsigned int can_hideshow:1;
  174. unsigned int can_altscreen:1;
  175. unsigned int can_mouse:1;
  176. unsigned int can_unicode:1;
  177. unsigned int can_bright:1;
  178. unsigned int can_title:1;
  179. unsigned int can_bce:1;
  180. unsigned int can_24bit:1;
  181. unsigned int can_256color:1;
  182. unsigned int can_italic:1;
  183. unsigned int can_insert:1;
  184. unsigned int can_bracketedpaste:1;
  185. unsigned int history_enabled:1;
  186. unsigned int highlight_parens:1;
  187. unsigned int smart_case:1;
  188. unsigned int highlight_current_line:1;
  189. unsigned int shift_scrolling:1;
  190. unsigned int check_git:1;
  191. unsigned int color_gutter:1;
  192. unsigned int relative_lines:1;
  193. unsigned int numbers:1;
  194. unsigned int horizontal_shift_scrolling:1;
  195. unsigned int hide_statusbar:1;
  196. unsigned int tabs_visible:1;
  197. unsigned int autohide_tabs:1;
  198. unsigned int smart_complete:1;
  199. unsigned int has_terminal:1;
  200. unsigned int use_sgr_mouse:1;
  201. unsigned int search_wraps:1;
  202. int cursor_padding;
  203. int split_percent;
  204. int scroll_amount;
  205. int tab_offset;
  206. char * tab_indicator;
  207. char * space_indicator;
  208. } global_config_t;
  209. #define OVERLAY_MODE_NONE 0
  210. #define OVERLAY_MODE_READ_ONE 1
  211. #define OVERLAY_MODE_COMMAND 2
  212. #define OVERLAY_MODE_SEARCH 3
  213. #define OVERLAY_MODE_COMPLETE 4
  214. #define HISTORY_SENTINEL 0
  215. #define HISTORY_INSERT 1
  216. #define HISTORY_DELETE 2
  217. #define HISTORY_REPLACE 3
  218. #define HISTORY_REMOVE_LINE 4
  219. #define HISTORY_ADD_LINE 5
  220. #define HISTORY_REPLACE_LINE 6
  221. #define HISTORY_MERGE_LINES 7
  222. #define HISTORY_SPLIT_LINE 8
  223. #define HISTORY_BREAK 10
  224. typedef struct history {
  225. struct history * previous;
  226. struct history * next;
  227. int type;
  228. int line;
  229. int col;
  230. union {
  231. struct {
  232. int lineno;
  233. int offset;
  234. int codepoint;
  235. int old_codepoint;
  236. } insert_delete_replace;
  237. struct {
  238. int lineno;
  239. line_t * contents;
  240. line_t * old_contents;
  241. } remove_replace_line;
  242. struct {
  243. int lineno;
  244. int split;
  245. } add_merge_split_lines;
  246. } contents;
  247. } history_t;
  248. /**
  249. * Buffer data
  250. *
  251. * A buffer describes a file, and stores
  252. * its name as well as the editor state
  253. * (cursor offsets, etc.) and the actual
  254. * line buffers.
  255. */
  256. typedef struct _env {
  257. unsigned int loading:1;
  258. unsigned int tabs:1;
  259. unsigned int modified:1;
  260. unsigned int readonly:1;
  261. unsigned int indent:1;
  262. unsigned int checkgitstatusonwrite:1;
  263. unsigned int crnl:1;
  264. unsigned int numbers:1;
  265. unsigned int gutter:1;
  266. int highlighting_paren;
  267. int maxcolumn;
  268. short mode;
  269. short tabstop;
  270. char * file_name;
  271. int offset;
  272. int coffset;
  273. int line_no;
  274. int line_count;
  275. int line_avail;
  276. int col_no;
  277. int preferred_column;
  278. struct syntax_definition * syntax;
  279. line_t ** lines;
  280. history_t * history;
  281. history_t * last_save_history;
  282. int width;
  283. int left;
  284. int start_line;
  285. int sel_col;
  286. int start_col;
  287. int prev_line;
  288. } buffer_t;
  289. struct theme_def {
  290. const char * name;
  291. void (*load)(const char * name);
  292. };
  293. extern struct theme_def * themes;
  294. extern void add_colorscheme(struct theme_def theme);
  295. struct syntax_state {
  296. line_t * line;
  297. int line_no;
  298. int state;
  299. int i;
  300. };
  301. struct completion_match {
  302. char * string;
  303. char * file;
  304. char * search;
  305. };
  306. struct syntax_definition {
  307. char * name;
  308. char ** ext;
  309. int (*calculate)(struct syntax_state *);
  310. int prefers_spaces;
  311. int (*completion_qualifier)(int c);
  312. int (*completion_matcher)(uint32_t * comp, struct completion_match ** matches, int * matches_count, int complete_match, int * matches_len);
  313. };
  314. extern struct syntax_definition * syntaxes;
  315. /**
  316. * Editor mode states
  317. */
  318. #define MODE_NORMAL 0
  319. #define MODE_INSERT 1
  320. #define MODE_LINE_SELECTION 2
  321. #define MODE_REPLACE 3
  322. #define MODE_CHAR_SELECTION 4
  323. #define MODE_COL_SELECTION 5
  324. #define MODE_COL_INSERT 6
  325. #define MODE_DIRECTORY_BROWSE 7
  326. extern global_config_t global_config;
  327. extern const char * COLOR_FG;
  328. extern const char * COLOR_BG;
  329. extern const char * COLOR_ALT_FG;
  330. extern const char * COLOR_ALT_BG;
  331. extern const char * COLOR_NUMBER_FG;
  332. extern const char * COLOR_NUMBER_BG;
  333. extern const char * COLOR_STATUS_FG;
  334. extern const char * COLOR_STATUS_BG;
  335. extern const char * COLOR_STATUS_ALT;
  336. extern const char * COLOR_TABBAR_BG;
  337. extern const char * COLOR_TAB_BG;
  338. extern const char * COLOR_ERROR_FG;
  339. extern const char * COLOR_ERROR_BG;
  340. extern const char * COLOR_SEARCH_FG;
  341. extern const char * COLOR_SEARCH_BG;
  342. extern const char * COLOR_KEYWORD;
  343. extern const char * COLOR_STRING;
  344. extern const char * COLOR_COMMENT;
  345. extern const char * COLOR_TYPE;
  346. extern const char * COLOR_PRAGMA;
  347. extern const char * COLOR_NUMERAL;
  348. extern const char * COLOR_SELECTFG;
  349. extern const char * COLOR_SELECTBG;
  350. extern const char * COLOR_RED;
  351. extern const char * COLOR_GREEN;
  352. extern const char * COLOR_BOLD;
  353. extern const char * COLOR_LINK;
  354. extern const char * COLOR_ESCAPE;
  355. extern const char * current_theme;
  356. struct action_def {
  357. char * name;
  358. void (*action)();
  359. int options;
  360. const char * description;
  361. };
  362. extern struct action_def * mappable_actions;
  363. #define ARG_IS_INPUT 0x01 /* Takes the key that triggered it as the first argument */
  364. #define ARG_IS_CUSTOM 0x02 /* Takes a custom argument which is specific to the method */
  365. #define ARG_IS_PROMPT 0x04 /* Prompts for an argument. */
  366. #define ACTION_IS_RW 0x08 /* Needs to be able to write. */
  367. #define BIM_ACTION(name, options, description) \
  368. void name (); /* Define the action with unknown arguments */ \
  369. void __attribute__((constructor)) _install_ ## name (void) { \
  370. add_action((struct action_def){#name, name, options, description}); \
  371. } \
  372. void name
  373. struct command_def {
  374. char * name;
  375. int (*command)(char *, int, char * arg[]);
  376. const char * description;
  377. };
  378. #define BIM_COMMAND(cmd_name, cmd_str, description) \
  379. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  380. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  381. add_command((struct command_def){cmd_str, bim_command_ ## cmd_name, description}); \
  382. } \
  383. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  384. #define BIM_ALIAS(alias, alias_name, cmd_name) \
  385. void __attribute__((constructor)) _install_alias_ ## alias_name (void) { \
  386. add_command((struct command_def){alias, bim_command_ ## cmd_name, "Alias for " #cmd_name}); \
  387. }
  388. #define BIM_PREFIX_COMMAND(cmd_name, cmd_prefix, description) \
  389. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  390. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  391. add_prefix_command((struct command_def){cmd_prefix, bim_command_ ## cmd_name, description}); \
  392. } \
  393. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  394. extern buffer_t * env;
  395. extern buffer_t * left_buffer;
  396. extern buffer_t * right_buffer;
  397. #define NAV_BUFFER_MAX 10
  398. extern char nav_buf[NAV_BUFFER_MAX+1];
  399. extern int nav_buffer;
  400. extern int buffers_len;
  401. extern int buffers_avail;
  402. extern buffer_t ** buffers;
  403. extern const char * flag_to_color(int _flag);
  404. extern void redraw_line(int x);
  405. extern int git_examine(char * filename);
  406. extern void search_next(void);
  407. extern void set_preferred_column(void);
  408. extern void quit(const char * message);
  409. extern void close_buffer(void);
  410. extern void set_syntax_by_name(const char * name);
  411. extern void rehighlight_search(line_t * line);
  412. extern void try_to_center();
  413. extern int read_one_character(char * message);
  414. extern void bim_unget(int c);
  415. #define bim_getch() bim_getch_timeout(200)
  416. extern int bim_getch_timeout(int timeout);
  417. extern buffer_t * buffer_new(void);
  418. extern FILE * open_biminfo(void);
  419. extern int fetch_from_biminfo(buffer_t * buf);
  420. extern int update_biminfo(buffer_t * buf);
  421. extern buffer_t * buffer_close(buffer_t * buf);
  422. extern int to_eight(uint32_t codepoint, char * out);
  423. extern char * name_from_key(enum Key keycode);
  424. extern void add_action(struct action_def action);
  425. extern void open_file(char * file);
  426. extern void recalculate_selected_lines(void);
  427. extern void add_command(struct command_def command);
  428. extern void add_prefix_command(struct command_def command);
  429. extern void render_command_input_buffer(void);
  430. extern void unhighlight_matching_paren(void);
  431. extern void add_syntax(struct syntax_definition def);
  432. struct ColorName {
  433. const char * name;
  434. const char ** value;
  435. };
  436. extern struct ColorName color_names[];
  437. struct bim_function {
  438. char * command;
  439. struct bim_function * next;
  440. };
  441. extern struct bim_function ** user_functions;
  442. extern int run_function(char * name);
  443. extern int has_function(char * name);
  444. extern void find_matching_paren(int * out_line, int * out_col, int in_col);
  445. extern void render_error(char * message, ...);
  446. extern void pause_for_key(void);
  447. #define add_match(match_string, match_file, match_search) do { \
  448. if (*matches_count == *matches_len) { \
  449. (*matches_len) *= 2; \
  450. *matches = realloc(*matches, sizeof(struct completion_match) * (*matches_len)); \
  451. } \
  452. (*matches)[*matches_count].string = strdup(match_string); \
  453. (*matches)[*matches_count].file = strdup(match_file); \
  454. (*matches)[*matches_count].search = strdup(match_search); \
  455. (*matches_count)++; \
  456. } while (0)
  457. #define add_if_match(name,desc) do { \
  458. int i = 0; \
  459. while (comp[i] && comp[i] == (unsigned char)name[i]) i++; \
  460. if (comp[i] == '\0') { \
  461. add_match(name,desc,""); \
  462. } \
  463. } while (0)
  464. struct action_map {
  465. int key;
  466. void (*method)();
  467. int options;
  468. int arg;
  469. };
  470. #define opt_rep 0x1 /* This action will be repeated */
  471. #define opt_arg 0x2 /* This action will take a specified argument */
  472. #define opt_char 0x4 /* This action will read a character to pass as an argument */
  473. #define opt_nav 0x8 /* This action will consume the nav buffer as its argument */
  474. #define opt_rw 0x10 /* Must not be read-only */
  475. #define opt_norm 0x20 /* Returns to normal mode */
  476. #define opt_byte 0x40 /* Same as opt_char but forces a byte */
  477. struct mode_names {
  478. const char * description;
  479. const char * name;
  480. struct action_map ** mode;
  481. };
  482. extern struct mode_names mode_names[];
  483. /* End of bim-core.h */
  484. /* Included from bim-syntax.h */
  485. #define BIM_SYNTAX(name, spaces) \
  486. __attribute__((constructor)) static void _load_ ## name (void) { \
  487. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, NULL, NULL}); \
  488. } \
  489. #define BIM_SYNTAX_EXT(name, spaces, matcher) \
  490. __attribute__((constructor)) static void _load_ ## name (void) { \
  491. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, matcher, _match_completions_ ## name}); \
  492. } \
  493. #define BIM_SYNTAX_COMPLETER(name) \
  494. static int _match_completions_ ## name ( \
  495. uint32_t * comp __attribute__((unused)), \
  496. struct completion_match **matches __attribute__((unused)), \
  497. int * matches_count __attribute__((unused)), \
  498. int complete_match __attribute__((unused)), \
  499. int *matches_len __attribute__((unused)))
  500. #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)
  501. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  502. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  503. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  504. #define skip() (state->i++)
  505. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  506. extern int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c));
  507. extern int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c));
  508. extern void paint_single_string(struct syntax_state * state);
  509. extern void paint_simple_string(struct syntax_state * state);
  510. extern int common_comment_buzzwords(struct syntax_state * state);
  511. extern int paint_comment(struct syntax_state * state);
  512. extern int match_forward(struct syntax_state * state, char * c);
  513. extern struct syntax_definition * find_syntax_calculator(const char * name);
  514. #define nest(lang, low) \
  515. do { \
  516. state->state = (state->state < 1 ? 0 : state->state - low); \
  517. do { state->state = lang(state); } while (state->state == 0); \
  518. if (state->state == -1) return low; \
  519. return state->state + low; \
  520. } while (0)
  521. /* Some of the C stuff is widely used */
  522. extern int c_keyword_qualifier(int c);
  523. extern int paint_c_numeral(struct syntax_state * state);
  524. extern int paint_c_comment(struct syntax_state * state);
  525. extern void paint_c_char(struct syntax_state * state);
  526. /* Hacky workaround for isdigit not really accepting Unicode stuff */
  527. static __attribute__((used)) int _isdigit(int c) { if (c > 128) return 0; return isdigit(c); }
  528. static __attribute__((used)) int _isxdigit(int c) { if (c > 128) return 0; return isxdigit(c); }
  529. #undef isdigit
  530. #undef isxdigit
  531. #define isdigit(c) _isdigit(c)
  532. #define isxdigit(c) _isxdigit(c)
  533. /* End of bim-syntax.h */
  534. global_config_t global_config = {
  535. /* State */
  536. .term_width = 0,
  537. .term_height = 0,
  538. .bottom_size = 2,
  539. .yanks = NULL,
  540. .yank_count = 0,
  541. .yank_is_full_lines = 0,
  542. .tty_in = STDIN_FILENO,
  543. .bimrc_path = "~/.bimrc",
  544. .syntax_fallback = NULL, /* syntax to fall back to if none other match applies */
  545. .search = NULL,
  546. .overlay_mode = OVERLAY_MODE_NONE,
  547. .command_buffer = NULL,
  548. .command_offset = 0,
  549. .command_col_no = 0,
  550. .history_point = -1,
  551. /* Bitset starts here */
  552. .highlight_on_open = 1,
  553. .initial_file_is_read_only = 0,
  554. .go_to_line = 1,
  555. .break_from_selection = 1,
  556. /* Terminal capabilities */
  557. .can_scroll = 1,
  558. .can_hideshow = 1,
  559. .can_altscreen = 1,
  560. .can_mouse = 1,
  561. .can_unicode = 1,
  562. .can_bright = 1,
  563. .can_title = 1,
  564. .can_bce = 1,
  565. .can_24bit = 1, /* can use 24-bit color */
  566. .can_256color = 1, /* can use 265 colors */
  567. .can_italic = 1, /* can use italics (without inverting) */
  568. .can_insert = 0, /* ^[[L */
  569. .can_bracketedpaste = 0, /* puts escapes before and after pasted stuff */
  570. /* Configuration options */
  571. .history_enabled = 1,
  572. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  573. .smart_case = 1, /* smart case-sensitivity while searching */
  574. .highlight_current_line = 1,
  575. .shift_scrolling = 1, /* shift rather than moving cursor*/
  576. .check_git = 0,
  577. .color_gutter = 1, /* shows modified lines */
  578. .relative_lines = 0,
  579. .numbers = 1,
  580. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  581. .hide_statusbar = 0,
  582. .tabs_visible = 1,
  583. .autohide_tabs = 0,
  584. .smart_complete = 0,
  585. .has_terminal = 0,
  586. .use_sgr_mouse = 0,
  587. .search_wraps = 1,
  588. /* Integer config values */
  589. .cursor_padding = 4,
  590. .split_percent = 50,
  591. .scroll_amount = 5,
  592. .tab_offset = 0,
  593. };
  594. struct key_name_map KeyNames[] = {
  595. {KEY_TIMEOUT, "[timeout]"},
  596. {KEY_BACKSPACE, "<backspace>"},
  597. {KEY_ENTER, "<enter>"},
  598. {KEY_ESCAPE, "<escape>"},
  599. {KEY_TAB, "<tab>"},
  600. {' ', "<space>"},
  601. /* These are mostly here for markdown output. */
  602. {'`', "<backtick>"},
  603. {'|', "<pipe>"},
  604. {KEY_DELETE, "<del>"},
  605. {KEY_MOUSE, "<mouse>"},
  606. {KEY_MOUSE_SGR, "<mouse-sgr>"},
  607. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  608. {KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
  609. {KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
  610. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  611. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  612. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  613. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  614. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  615. {KEY_ALT_SHIFT_UP, "<alt-shift-up>"},{KEY_ALT_SHIFT_DOWN, "<alt-shift-down>"},{KEY_ALT_SHIFT_RIGHT, "<alt-shift-right>"},{KEY_ALT_SHIFT_LEFT, "<alt-shift-left>"},
  616. {KEY_SHIFT_TAB,"<shift-tab>"},
  617. {KEY_PASTE_BEGIN,"<paste-begin>"},{KEY_PASTE_END,"<paste-end>"},
  618. };
  619. char * name_from_key(enum Key keycode) {
  620. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  621. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  622. }
  623. static char keyNameTmp[8] = {0};
  624. if (keycode <= KEY_CTRL_UNDERSCORE) {
  625. keyNameTmp[0] = '^';
  626. keyNameTmp[1] = '@' + keycode;
  627. keyNameTmp[2] = 0;
  628. return keyNameTmp;
  629. }
  630. to_eight(keycode, keyNameTmp);
  631. return keyNameTmp;
  632. }
  633. struct ColorName color_names[] = {
  634. {"text-fg", &COLOR_FG},
  635. {"text-bg", &COLOR_BG},
  636. {"alternate-fg", &COLOR_ALT_FG},
  637. {"alternate-bg", &COLOR_ALT_BG},
  638. {"number-fg", &COLOR_NUMBER_FG},
  639. {"number-bg", &COLOR_NUMBER_BG},
  640. {"status-fg", &COLOR_STATUS_FG},
  641. {"status-bg", &COLOR_STATUS_BG},
  642. {"status-alt", &COLOR_STATUS_ALT},
  643. {"tabbar-bg", &COLOR_TABBAR_BG},
  644. {"tab-bg", &COLOR_TAB_BG},
  645. {"error-fg", &COLOR_ERROR_FG},
  646. {"error-bg", &COLOR_ERROR_BG},
  647. {"search-fg", &COLOR_SEARCH_FG},
  648. {"search-bg", &COLOR_SEARCH_BG},
  649. {"keyword", &COLOR_KEYWORD},
  650. {"string", &COLOR_STRING},
  651. {"comment", &COLOR_COMMENT},
  652. {"type", &COLOR_TYPE},
  653. {"pragma", &COLOR_PRAGMA},
  654. {"numeral", &COLOR_NUMERAL},
  655. {"select-fg", &COLOR_SELECTFG},
  656. {"select-bg", &COLOR_SELECTBG},
  657. {"red", &COLOR_RED},
  658. {"green", &COLOR_GREEN},
  659. {"bold", &COLOR_BOLD},
  660. {"link", &COLOR_LINK},
  661. {"escape", &COLOR_ESCAPE},
  662. {NULL,NULL},
  663. };
  664. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  665. int flex_ ## name ## _count = 0; \
  666. int flex_ ## name ## _space = 0; \
  667. type * name = NULL; \
  668. void add_name (type input) { \
  669. if (flex_ ## name ## _space == 0) { \
  670. flex_ ## name ## _space = 4; \
  671. name = calloc(sizeof(type), flex_ ## name ## _space); \
  672. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  673. flex_ ## name ## _space *= 2; \
  674. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  675. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  676. } \
  677. name[flex_ ## name ## _count] = input; \
  678. flex_ ## name ## _count ++; \
  679. }
  680. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  681. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  682. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  683. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  684. FLEXIBLE_ARRAY(user_functions, add_user_function, struct bim_function *, NULL)
  685. /**
  686. * Special implementation of getch with a timeout
  687. */
  688. int _bim_unget = -1;
  689. void bim_unget(int c) {
  690. _bim_unget = c;
  691. }
  692. int bim_getch_timeout(int timeout) {
  693. fflush(stdout);
  694. if (_bim_unget != -1) {
  695. int out = _bim_unget;
  696. _bim_unget = -1;
  697. return out;
  698. }
  699. struct pollfd fds[1];
  700. fds[0].fd = global_config.tty_in;
  701. fds[0].events = POLLIN;
  702. int ret = poll(fds,1,timeout);
  703. if (ret > 0 && fds[0].revents & POLLIN) {
  704. unsigned char buf[1];
  705. read(global_config.tty_in, buf, 1);
  706. return buf[0];
  707. } else {
  708. return -1;
  709. }
  710. }
  711. /**
  712. * UTF-8 parser state
  713. */
  714. static uint32_t codepoint_r;
  715. static uint32_t state = 0;
  716. #define UTF8_ACCEPT 0
  717. #define UTF8_REJECT 1
  718. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  719. static int state_table[32] = {
  720. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  721. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  722. 2,2,2,2, /* 110xxxxx */
  723. 3,3, /* 1110xxxx */
  724. 4, /* 11110xxx */
  725. 1 /* 11111xxx */
  726. };
  727. static int mask_bytes[32] = {
  728. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  729. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  730. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  731. 0x1F,0x1F,0x1F,0x1F,
  732. 0x0F,0x0F,
  733. 0x07,
  734. 0x00
  735. };
  736. static int next[5] = {
  737. 0,
  738. 1,
  739. 0,
  740. 2,
  741. 3
  742. };
  743. if (*state == UTF8_ACCEPT) {
  744. *codep = byte & mask_bytes[byte >> 3];
  745. *state = state_table[byte >> 3];
  746. } else if (*state > 0) {
  747. *codep = (byte & 0x3F) | (*codep << 6);
  748. *state = next[*state];
  749. }
  750. return *state;
  751. }
  752. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  753. int _shift_key(int i, int this_buf[20], int *timeout) {
  754. int thing = this_buf[*timeout-1];
  755. (*timeout) = 0;
  756. switch (thing) {
  757. /* There are other combinations we can handle... */
  758. case '2': return i + 4;
  759. case '5': return i + 8;
  760. case '3': return i + 12;
  761. case '4': return i + 16;
  762. default: return i;
  763. }
  764. }
  765. int bim_getkey(int read_timeout) {
  766. int timeout = 0;
  767. int this_buf[20];
  768. int cin;
  769. uint32_t c;
  770. uint32_t istate = 0;
  771. while ((cin = bim_getch_timeout(read_timeout))) {
  772. if (cin == -1) {
  773. if (timeout && this_buf[timeout-1] == '\033')
  774. return KEY_ESCAPE;
  775. return KEY_TIMEOUT;
  776. }
  777. if (!decode(&istate, &c, cin)) {
  778. if (timeout == 0) {
  779. switch (c) {
  780. case '\033':
  781. if (timeout == 0) {
  782. this_buf[timeout] = c;
  783. timeout++;
  784. }
  785. continue;
  786. case KEY_LINEFEED: return KEY_ENTER;
  787. case KEY_DELETE: return KEY_BACKSPACE;
  788. }
  789. return c;
  790. } else {
  791. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  792. bim_unget(c);
  793. timeout = 0;
  794. return KEY_ESCAPE;
  795. }
  796. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  797. this_buf[timeout] = c;
  798. timeout++;
  799. continue;
  800. }
  801. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  802. switch (c) {
  803. case 'P': timeout = 0; return KEY_F1;
  804. case 'Q': timeout = 0; return KEY_F2;
  805. case 'R': timeout = 0; return KEY_F3;
  806. case 'S': timeout = 0; return KEY_F4;
  807. }
  808. timeout = 0;
  809. continue;
  810. }
  811. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  812. timeout = 0;
  813. bim_unget(c);
  814. return KEY_ESCAPE;
  815. }
  816. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  817. timeout = 1;
  818. this_buf[timeout] = c;
  819. timeout++;
  820. continue;
  821. }
  822. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  823. (isdigit(c) || (c == ';'))) {
  824. this_buf[timeout] = c;
  825. timeout++;
  826. continue;
  827. }
  828. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  829. switch (c) {
  830. case 'M': timeout = 0; return KEY_MOUSE;
  831. case '<': timeout = 0; return KEY_MOUSE_SGR;
  832. case 'A': return shift_key(KEY_UP);
  833. case 'B': return shift_key(KEY_DOWN);
  834. case 'C': return shift_key(KEY_RIGHT);
  835. case 'D': return shift_key(KEY_LEFT);
  836. case 'H': timeout = 0; return KEY_HOME;
  837. case 'F': timeout = 0; return KEY_END;
  838. case 'I': timeout = 0; return KEY_PAGE_UP;
  839. case 'G': timeout = 0; return KEY_PAGE_DOWN;
  840. case 'Z': timeout = 0; return KEY_SHIFT_TAB;
  841. case '~':
  842. if (timeout == 3) {
  843. switch (this_buf[2]) {
  844. case '1': timeout = 0; return KEY_HOME;
  845. case '3': timeout = 0; return KEY_DELETE;
  846. case '4': timeout = 0; return KEY_END;
  847. case '5': timeout = 0; return KEY_PAGE_UP;
  848. case '6': timeout = 0; return KEY_PAGE_DOWN;
  849. }
  850. } else if (timeout == 5) {
  851. if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '0') {
  852. return KEY_PASTE_BEGIN;
  853. } else if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '1') {
  854. return KEY_PASTE_END;
  855. }
  856. } else if (this_buf[2] == '1') {
  857. switch (this_buf[3]) {
  858. case '5': return KEY_F5;
  859. case '7': return KEY_F6;
  860. case '8': return KEY_F7;
  861. case '9': return KEY_F8;
  862. }
  863. } else if (this_buf[2] == '2') {
  864. switch (this_buf[3]) {
  865. case '0': return KEY_F9;
  866. case '1': return KEY_F10;
  867. case '3': return KEY_F11;
  868. case '4': return KEY_F12;
  869. }
  870. }
  871. break;
  872. }
  873. }
  874. timeout = 0;
  875. continue;
  876. }
  877. } else if (istate == UTF8_REJECT) {
  878. istate = 0;
  879. }
  880. }
  881. return KEY_TIMEOUT;
  882. }
  883. enum Key key_from_name(char * name) {
  884. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  885. if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
  886. }
  887. if (name[0] == '^' && name[1] && !name[2]) {
  888. return name[1] - '@';
  889. }
  890. if (!name[1]) return name[0];
  891. /* Try decoding */
  892. uint32_t c, state = 0;
  893. int candidate = -1;
  894. while (*name) {
  895. if (!decode(&state, &c, (unsigned char)*name)) {
  896. if (candidate == -1) candidate = c;
  897. else return -1; /* Multiple characters */
  898. } else if (state == UTF8_REJECT) {
  899. return -1;
  900. }
  901. }
  902. return candidate;
  903. }
  904. /**
  905. * Pointer to current active buffer
  906. */
  907. buffer_t * env = NULL;
  908. buffer_t * left_buffer = NULL;
  909. buffer_t * right_buffer = NULL;
  910. /**
  911. * A buffer for holding a number (line, repetition count)
  912. */
  913. char nav_buf[NAV_BUFFER_MAX+1];
  914. int nav_buffer = 0;
  915. /**
  916. * Available buffers
  917. */
  918. int buffers_len = 0;
  919. int buffers_avail = 0;
  920. buffer_t ** buffers = NULL;
  921. /**
  922. * Create a new buffer
  923. */
  924. buffer_t * buffer_new(void) {
  925. if (buffers_len == buffers_avail) {
  926. /* If we are out of buffer space, expand the buffers vector */
  927. buffers_avail *= 2;
  928. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  929. }
  930. /* TODO: Support having split buffers with more than two buffers open */
  931. if (left_buffer) {
  932. left_buffer->left = 0;
  933. left_buffer->width = global_config.term_width;
  934. right_buffer->left = 0;
  935. right_buffer->width = global_config.term_width;
  936. left_buffer = NULL;
  937. right_buffer = NULL;
  938. }
  939. /* Allocate a new buffer */
  940. buffers[buffers_len] = malloc(sizeof(buffer_t));
  941. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  942. buffers[buffers_len]->left = 0;
  943. buffers[buffers_len]->width = global_config.term_width;
  944. buffers[buffers_len]->highlighting_paren = -1;
  945. buffers[buffers_len]->numbers = global_config.numbers;
  946. buffers[buffers_len]->gutter = 1;
  947. buffers_len++;
  948. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  949. return buffers[buffers_len-1];
  950. }
  951. /**
  952. * Open the biminfo file.
  953. */
  954. FILE * open_biminfo(void) {
  955. /* TODO This should probably be configurable line bimrc */
  956. char * home = getenv("HOME");
  957. if (!home) {
  958. /* Since it's not, we need HOME */
  959. return NULL;
  960. }
  961. /* biminfo lives at ~/.biminfo */
  962. char biminfo_path[PATH_MAX+1] = {0};
  963. sprintf(biminfo_path,"%s/.biminfo",home);
  964. /* Try to open normally first... */
  965. FILE * biminfo = fopen(biminfo_path,"r+");
  966. if (!biminfo) {
  967. /* Otherwise, try to create it. */
  968. biminfo = fopen(biminfo_path,"w+");
  969. }
  970. return biminfo;
  971. }
  972. /**
  973. * Fetch the cursor position from a biminfo file
  974. */
  975. int fetch_from_biminfo(buffer_t * buf) {
  976. /* Can't fetch if we don't have a filename */
  977. if (!buf->file_name) return 1;
  978. /* Get the absolute name of the file */
  979. char tmp_path[PATH_MAX+2];
  980. if (!realpath(buf->file_name, tmp_path)) {
  981. return 1;
  982. }
  983. strcat(tmp_path," ");
  984. FILE * biminfo = open_biminfo();
  985. if (!biminfo) return 1;
  986. /* Scan */
  987. char line[PATH_MAX+64];
  988. while (!feof(biminfo)) {
  989. fpos_t start_of_line;
  990. fgetpos(biminfo, &start_of_line);
  991. fgets(line, PATH_MAX+63, biminfo);
  992. if (line[0] != '>') {
  993. continue;
  994. }
  995. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  996. /* Read */
  997. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  998. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  999. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  1000. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  1001. try_to_center();
  1002. return 0;
  1003. }
  1004. }
  1005. return 0;
  1006. }
  1007. /**
  1008. * Write a file containing the last cursor position of a buffer.
  1009. */
  1010. int update_biminfo(buffer_t * buf) {
  1011. if (!buf->file_name) return 1;
  1012. /* Get the absolute name of the file */
  1013. char tmp_path[PATH_MAX+1];
  1014. if (!realpath(buf->file_name, tmp_path)) {
  1015. return 1;
  1016. }
  1017. strcat(tmp_path," ");
  1018. FILE * biminfo = open_biminfo();
  1019. if (!biminfo) return 1;
  1020. /* Scan */
  1021. char line[PATH_MAX+64];
  1022. while (!feof(biminfo)) {
  1023. fpos_t start_of_line;
  1024. fgetpos(biminfo, &start_of_line);
  1025. fgets(line, PATH_MAX+63, biminfo);
  1026. if (line[0] != '>') {
  1027. continue;
  1028. }
  1029. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  1030. /* Update */
  1031. fsetpos(biminfo, &start_of_line);
  1032. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1033. goto _done;
  1034. }
  1035. }
  1036. if (ftell(biminfo) == 0) {
  1037. /* New biminfo */
  1038. fprintf(biminfo, "# This is a biminfo file.\n");
  1039. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  1040. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  1041. }
  1042. /* Haven't found what we're looking for, should be at end of file */
  1043. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1044. _done:
  1045. fclose(biminfo);
  1046. return 0;
  1047. }
  1048. /**
  1049. * Close a buffer
  1050. */
  1051. buffer_t * buffer_close(buffer_t * buf) {
  1052. int i;
  1053. /* Locate the buffer in the buffer pointer vector */
  1054. for (i = 0; i < buffers_len; i++) {
  1055. if (buf == buffers[i])
  1056. break;
  1057. }
  1058. /* Invalid buffer? */
  1059. if (i == buffers_len) {
  1060. return env; /* wtf */
  1061. }
  1062. update_biminfo(buf);
  1063. /* Clean up lines used by old buffer */
  1064. for (int i = 0; i < buf->line_count; ++i) {
  1065. free(buf->lines[i]);
  1066. }
  1067. free(buf->lines);
  1068. if (buf->file_name) {
  1069. free(buf->file_name);
  1070. }
  1071. history_t * h = buf->history;
  1072. while (h->next) {
  1073. h = h->next;
  1074. }
  1075. while (h) {
  1076. history_t * x = h->previous;
  1077. free(h);
  1078. h = x;
  1079. }
  1080. /* Clean up the old buffer */
  1081. free(buf);
  1082. /* Remove the buffer from the vector, moving others up */
  1083. if (i != buffers_len - 1) {
  1084. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  1085. }
  1086. /* There is one less buffer */
  1087. buffers_len--;
  1088. if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
  1089. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  1090. if (!buffers_len) {
  1091. /* There are no more buffers. */
  1092. return NULL;
  1093. }
  1094. /* If this was the last buffer, return the previous last buffer */
  1095. if (i == buffers_len) {
  1096. return buffers[buffers_len-1];
  1097. }
  1098. /* Otherwise return the new last buffer */
  1099. return buffers[i];
  1100. }
  1101. /**
  1102. * Theming data
  1103. *
  1104. * This default set is pretty simple "default foreground on default background"
  1105. * except for search and selections which are black-on-white specifically.
  1106. *
  1107. * The theme colors get set by separate configurable themes.
  1108. */
  1109. const char * COLOR_FG = "@9";
  1110. const char * COLOR_BG = "@9";
  1111. const char * COLOR_ALT_FG = "@9";
  1112. const char * COLOR_ALT_BG = "@9";
  1113. const char * COLOR_NUMBER_FG = "@9";
  1114. const char * COLOR_NUMBER_BG = "@9";
  1115. const char * COLOR_STATUS_FG = "@9";
  1116. const char * COLOR_STATUS_BG = "@9";
  1117. const char * COLOR_STATUS_ALT= "@9";
  1118. const char * COLOR_TABBAR_BG = "@9";
  1119. const char * COLOR_TAB_BG = "@9";
  1120. const char * COLOR_ERROR_FG = "@9";
  1121. const char * COLOR_ERROR_BG = "@9";
  1122. const char * COLOR_SEARCH_FG = "@0";
  1123. const char * COLOR_SEARCH_BG = "@17";
  1124. const char * COLOR_KEYWORD = "@9";
  1125. const char * COLOR_STRING = "@9";
  1126. const char * COLOR_COMMENT = "@9";
  1127. const char * COLOR_TYPE = "@9";
  1128. const char * COLOR_PRAGMA = "@9";
  1129. const char * COLOR_NUMERAL = "@9";
  1130. const char * COLOR_SELECTFG = "@0";
  1131. const char * COLOR_SELECTBG = "@17";
  1132. const char * COLOR_RED = "@1";
  1133. const char * COLOR_GREEN = "@2";
  1134. const char * COLOR_BOLD = "@9";
  1135. const char * COLOR_LINK = "@9";
  1136. const char * COLOR_ESCAPE = "@9";
  1137. const char * current_theme = "none";
  1138. /**
  1139. * Convert syntax highlighting flag to color code
  1140. */
  1141. const char * flag_to_color(int _flag) {
  1142. int flag = _flag & 0xF;
  1143. switch (flag) {
  1144. case FLAG_KEYWORD:
  1145. return COLOR_KEYWORD;
  1146. case FLAG_STRING:
  1147. return COLOR_STRING;
  1148. case FLAG_COMMENT:
  1149. return COLOR_COMMENT;
  1150. case FLAG_TYPE:
  1151. return COLOR_TYPE;
  1152. case FLAG_NUMERAL:
  1153. return COLOR_NUMERAL;
  1154. case FLAG_PRAGMA:
  1155. return COLOR_PRAGMA;
  1156. case FLAG_DIFFPLUS:
  1157. return COLOR_GREEN;
  1158. case FLAG_DIFFMINUS:
  1159. return COLOR_RED;
  1160. case FLAG_SELECT:
  1161. return COLOR_FG;
  1162. case FLAG_BOLD:
  1163. return COLOR_BOLD;
  1164. case FLAG_LINK:
  1165. return COLOR_LINK;
  1166. case FLAG_ESCAPE:
  1167. return COLOR_ESCAPE;
  1168. default:
  1169. return COLOR_FG;
  1170. }
  1171. }
  1172. /**
  1173. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  1174. * Returns 1 if a keyword from the last was found, otherwise 0.
  1175. */
  1176. int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  1177. if (keyword_qualifier(lastchar())) return 0;
  1178. if (!keyword_qualifier(charat())) return 0;
  1179. for (char ** keyword = keywords; *keyword; ++keyword) {
  1180. int d = 0;
  1181. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  1182. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  1183. paint((int)strlen(*keyword), flag);
  1184. return 1;
  1185. }
  1186. }
  1187. return 0;
  1188. }
  1189. /**
  1190. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  1191. * so it can be used for prefix checking for things that need further special handling.
  1192. */
  1193. int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  1194. if (keyword_qualifier(lastchar())) return 0;
  1195. if (!keyword_qualifier(charat())) return 0;
  1196. int i = state->i;
  1197. int slen = 0;
  1198. while (i < state->line->actual || *keyword == '\0') {
  1199. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  1200. for (int j = 0; j < slen; ++j) {
  1201. paint(1, flag);
  1202. }
  1203. return 1;
  1204. }
  1205. if (*keyword != state->line->text[i].codepoint) return 0;
  1206. i++;
  1207. keyword++;
  1208. slen++;
  1209. }
  1210. return 0;
  1211. }
  1212. void paint_single_string(struct syntax_state * state) {
  1213. paint(1, FLAG_STRING);
  1214. while (charat() != -1) {
  1215. if (charat() == '\\' && nextchar() == '\'') {
  1216. paint(2, FLAG_ESCAPE);
  1217. } else if (charat() == '\'') {
  1218. paint(1, FLAG_STRING);
  1219. return;
  1220. } else if (charat() == '\\') {
  1221. paint(2, FLAG_ESCAPE);
  1222. } else {
  1223. paint(1, FLAG_STRING);
  1224. }
  1225. }
  1226. }
  1227. void paint_simple_string(struct syntax_state * state) {
  1228. /* Assumes you came in from a check of charat() == '"' */
  1229. paint(1, FLAG_STRING);
  1230. while (charat() != -1) {
  1231. if (charat() == '\\' && nextchar() == '"') {
  1232. paint(2, FLAG_ESCAPE);
  1233. } else if (charat() == '"') {
  1234. paint(1, FLAG_STRING);
  1235. return;
  1236. } else if (charat() == '\\') {
  1237. paint(2, FLAG_ESCAPE);
  1238. } else {
  1239. paint(1, FLAG_STRING);
  1240. }
  1241. }
  1242. }
  1243. /**
  1244. * This is a basic character matcher for "keyword" characters.
  1245. */
  1246. int simple_keyword_qualifier(int c) {
  1247. return isalnum(c) || (c == '_');
  1248. }
  1249. /**
  1250. * These words can appear in comments and should be highlighted.
  1251. * Since there are a lot of comment highlighters, let's break them out.
  1252. */
  1253. int common_comment_buzzwords(struct syntax_state * state) {
  1254. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1255. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1256. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  1257. return 0;
  1258. }
  1259. /**
  1260. * Paint a comment until end of line, assumes this comment can not continue.
  1261. * (Some languages have comments that can continue with a \ - don't use this!)
  1262. * Assumes you've already painted your comment start characters.
  1263. */
  1264. int paint_comment(struct syntax_state * state) {
  1265. while (charat() != -1) {
  1266. if (common_comment_buzzwords(state)) continue;
  1267. else { paint(1, FLAG_COMMENT); }
  1268. }
  1269. return -1;
  1270. }
  1271. /**
  1272. * Match a word forward and return whether it was matched.
  1273. */
  1274. int match_forward(struct syntax_state * state, char * c) {
  1275. int i = 0;
  1276. while (1) {
  1277. if (charrel(i) == -1 && !*c) return 1;
  1278. if (charrel(i) != *c) return 0;
  1279. c++;
  1280. i++;
  1281. }
  1282. return 0;
  1283. }
  1284. /**
  1285. * Find and return a highlighter by name, or NULL
  1286. */
  1287. struct syntax_definition * find_syntax_calculator(const char * name) {
  1288. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  1289. if (!strcmp(s->name, name)) {
  1290. return s;
  1291. }
  1292. }
  1293. return NULL;
  1294. }
  1295. int syntax_count = 0;
  1296. int syntax_space = 0;
  1297. struct syntax_definition * syntaxes = NULL;
  1298. void add_syntax(struct syntax_definition def) {
  1299. if (syntax_space == 0) {
  1300. syntax_space = 4;
  1301. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  1302. } else if (syntax_count +1 == syntax_space) {
  1303. syntax_space *= 2;
  1304. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  1305. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  1306. }
  1307. syntaxes[syntax_count] = def;
  1308. syntax_count++;
  1309. }
  1310. /**
  1311. * Calculate syntax highlighting for the given line.
  1312. */
  1313. void recalculate_syntax(line_t * line, int line_no) {
  1314. /* Clear syntax for this line first */
  1315. int is_original = 1;
  1316. while (1) {
  1317. for (int i = 0; i < line->actual; ++i) {
  1318. line->text[i].flags = 0;
  1319. }
  1320. if (!env->syntax) {
  1321. if (line_no != -1) rehighlight_search(line);
  1322. return;
  1323. }
  1324. /* Start from the line's stored in initial state */
  1325. struct syntax_state state;
  1326. state.line = line;
  1327. state.line_no = line_no;
  1328. state.state = line->istate;
  1329. state.i = 0;
  1330. while (1) {
  1331. state.state = env->syntax->calculate(&state);
  1332. if (state.state != 0) {
  1333. if (line_no == -1) return;
  1334. rehighlight_search(line);
  1335. if (!is_original) {
  1336. redraw_line(line_no);
  1337. }
  1338. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  1339. line_no++;
  1340. line = env->lines[line_no];
  1341. line->istate = state.state;
  1342. if (env->loading) return;
  1343. is_original = 0;
  1344. goto _next;
  1345. }
  1346. return;
  1347. }
  1348. }
  1349. _next:
  1350. (void)0;
  1351. }
  1352. }
  1353. /**
  1354. * Recalculate tab widths.
  1355. */
  1356. void recalculate_tabs(line_t * line) {
  1357. if (env->loading) return;
  1358. int j = 0;
  1359. for (int i = 0; i < line->actual; ++i) {
  1360. if (line->text[i].codepoint == '\t') {
  1361. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1362. }
  1363. j += line->text[i].display_width;
  1364. }
  1365. }
  1366. /**
  1367. * TODO:
  1368. *
  1369. * The line editing functions should probably take a buffer_t *
  1370. * so that they can act on buffers other than the active one.
  1371. */
  1372. void recursive_history_free(history_t * root) {
  1373. if (!root->next) return;
  1374. history_t * n = root->next;
  1375. recursive_history_free(n);
  1376. switch (n->type) {
  1377. case HISTORY_REPLACE_LINE:
  1378. free(n->contents.remove_replace_line.contents);
  1379. /* fall-through */
  1380. case HISTORY_REMOVE_LINE:
  1381. free(n->contents.remove_replace_line.old_contents);
  1382. break;
  1383. default:
  1384. /* Nothing extra to free */
  1385. break;
  1386. }
  1387. free(n);
  1388. root->next = NULL;
  1389. }
  1390. #define HIST_APPEND(e) do { \
  1391. e->col = env->col_no; \
  1392. e->line = env->line_no; \
  1393. if (env->history) { \
  1394. e->previous = env->history; \
  1395. recursive_history_free(env->history); \
  1396. env->history->next = e; \
  1397. e->next = NULL; \
  1398. } \
  1399. env->history = e; \
  1400. } while (0)
  1401. /**
  1402. * Mark a point where a complete set of actions has ended.
  1403. */
  1404. void set_history_break(void) {
  1405. if (!global_config.history_enabled) return;
  1406. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1407. history_t * e = malloc(sizeof(history_t));
  1408. e->type = HISTORY_BREAK;
  1409. HIST_APPEND(e);
  1410. }
  1411. }
  1412. /**
  1413. * Insert a character into an existing line.
  1414. */
  1415. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1416. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1417. history_t * e = malloc(sizeof(history_t));
  1418. e->type = HISTORY_INSERT;
  1419. e->contents.insert_delete_replace.lineno = lineno;
  1420. e->contents.insert_delete_replace.offset = offset;
  1421. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1422. HIST_APPEND(e);
  1423. }
  1424. /* If there is not enough space... */
  1425. if (line->actual == line->available) {
  1426. /* Expand the line buffer */
  1427. if (line->available == 0) {
  1428. line->available = 8;
  1429. } else {
  1430. line->available *= 2;
  1431. }
  1432. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1433. }
  1434. /* If this was not the last character, then shift remaining characters forward. */
  1435. if (offset < line->actual) {
  1436. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1437. }
  1438. /* Insert the new character */
  1439. line->text[offset] = c;
  1440. /* There is one new character in the line */
  1441. line->actual += 1;
  1442. if (!env->loading) {
  1443. line->rev_status = 2; /* Modified */
  1444. recalculate_tabs(line);
  1445. recalculate_syntax(line, lineno);
  1446. }
  1447. return line;
  1448. }
  1449. /**
  1450. * Delete a character from a line
  1451. */
  1452. void line_delete(line_t * line, int offset, int lineno) {
  1453. /* Can't delete character before start of line. */
  1454. if (offset == 0) return;
  1455. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1456. history_t * e = malloc(sizeof(history_t));
  1457. e->type = HISTORY_DELETE;
  1458. e->contents.insert_delete_replace.lineno = lineno;
  1459. e->contents.insert_delete_replace.offset = offset;
  1460. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1461. HIST_APPEND(e);
  1462. }
  1463. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1464. if (offset < line->actual) {
  1465. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1466. }
  1467. /* The line is one character shorter */
  1468. line->actual -= 1;
  1469. line->rev_status = 2;
  1470. recalculate_tabs(line);
  1471. recalculate_syntax(line, lineno);
  1472. }
  1473. /**
  1474. * Replace a character in a line
  1475. */
  1476. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1477. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1478. history_t * e = malloc(sizeof(history_t));
  1479. e->type = HISTORY_REPLACE;
  1480. e->contents.insert_delete_replace.lineno = lineno;
  1481. e->contents.insert_delete_replace.offset = offset;
  1482. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1483. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1484. HIST_APPEND(e);
  1485. }
  1486. line->text[offset] = _c;
  1487. if (!env->loading) {
  1488. line->rev_status = 2; /* Modified */
  1489. recalculate_tabs(line);
  1490. recalculate_syntax(line, lineno);
  1491. }
  1492. }
  1493. /**
  1494. * Remove a line from the active buffer
  1495. */
  1496. line_t ** remove_line(line_t ** lines, int offset) {
  1497. /* If there is only one line, clear it instead of removing it. */
  1498. if (env->line_count == 1) {
  1499. while (lines[offset]->actual > 0) {
  1500. line_delete(lines[offset], lines[offset]->actual, offset);
  1501. }
  1502. return lines;
  1503. }
  1504. if (!env->loading && global_config.history_enabled) {
  1505. history_t * e = malloc(sizeof(history_t));
  1506. e->type = HISTORY_REMOVE_LINE;
  1507. e->contents.remove_replace_line.lineno = offset;
  1508. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1509. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1510. HIST_APPEND(e);
  1511. }
  1512. /* Otherwise, free the data used by the line */
  1513. free(lines[offset]);
  1514. /* Move other lines up */
  1515. if (offset < env->line_count-1) {
  1516. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1517. lines[env->line_count-1] = NULL;
  1518. }
  1519. /* There is one less line */
  1520. env->line_count -= 1;
  1521. return lines;
  1522. }
  1523. /**
  1524. * Add a new line to the active buffer.
  1525. */
  1526. line_t ** add_line(line_t ** lines, int offset) {
  1527. /* Invalid offset? */
  1528. if (offset > env->line_count) return lines;
  1529. if (!env->loading && global_config.history_enabled) {
  1530. history_t * e = malloc(sizeof(history_t));
  1531. e->type = HISTORY_ADD_LINE;
  1532. e->contents.add_merge_split_lines.lineno = offset;
  1533. HIST_APPEND(e);
  1534. }
  1535. /* Not enough space */
  1536. if (env->line_count == env->line_avail) {
  1537. /* Allocate more space */
  1538. env->line_avail *= 2;
  1539. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1540. }
  1541. /* If this isn't the last line, move other lines down */
  1542. if (offset < env->line_count) {
  1543. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1544. }
  1545. /* Allocate the new line */
  1546. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1547. lines[offset]->available = 32;
  1548. /* There is one new line */
  1549. env->line_count += 1;
  1550. env->lines = lines;
  1551. if (!env->loading) {
  1552. lines[offset]->rev_status = 2; /* Modified */
  1553. }
  1554. if (offset > 0 && !env->loading) {
  1555. recalculate_syntax(lines[offset-1],offset-1);
  1556. }
  1557. return lines;
  1558. }
  1559. /**
  1560. * Replace a line with data from another line (used by paste to paste yanked lines)
  1561. */
  1562. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1563. if (!env->loading && global_config.history_enabled) {
  1564. history_t * e = malloc(sizeof(history_t));
  1565. e->type = HISTORY_REPLACE_LINE;
  1566. e->contents.remove_replace_line.lineno = offset;
  1567. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1568. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1569. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1570. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1571. HIST_APPEND(e);
  1572. }
  1573. if (lines[offset]->available < replacement->actual) {
  1574. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1575. lines[offset]->available = replacement->available;
  1576. }
  1577. lines[offset]->actual = replacement->actual;
  1578. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1579. if (!env->loading) {
  1580. lines[offset]->rev_status = 2;
  1581. recalculate_syntax(lines[offset],offset);
  1582. }
  1583. }
  1584. /**
  1585. * Merge two consecutive lines.
  1586. * lineb is the offset of the second line.
  1587. */
  1588. line_t ** merge_lines(line_t ** lines, int lineb) {
  1589. /* linea is the line immediately before lineb */
  1590. int linea = lineb - 1;
  1591. if (!env->loading && global_config.history_enabled) {
  1592. history_t * e = malloc(sizeof(history_t));
  1593. e->type = HISTORY_MERGE_LINES;
  1594. e->contents.add_merge_split_lines.lineno = lineb;
  1595. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1596. HIST_APPEND(e);
  1597. }
  1598. /* If there isn't enough space in linea hold both... */
  1599. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1600. /* ... allocate more space until it fits */
  1601. if (lines[linea]->available == 0) {
  1602. lines[linea]->available = 8;
  1603. } else {
  1604. lines[linea]->available *= 2;
  1605. }
  1606. /* XXX why not just do this once after calculating appropriate size */
  1607. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1608. }
  1609. /* Copy the second line into the first line */
  1610. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1611. /* The first line is now longer */
  1612. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1613. if (!env->loading) {
  1614. lines[linea]->rev_status = 2;
  1615. recalculate_tabs(lines[linea]);
  1616. recalculate_syntax(lines[linea], linea);
  1617. }
  1618. /* Remove the second line */
  1619. free(lines[lineb]);
  1620. /* Move other lines up */
  1621. if (lineb < env->line_count) {
  1622. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1623. lines[env->line_count-1] = NULL;
  1624. }
  1625. /* There is one less line */
  1626. env->line_count -= 1;
  1627. return lines;
  1628. }
  1629. /**
  1630. * Split a line into two lines at the given column
  1631. */
  1632. line_t ** split_line(line_t ** lines, int line, int split) {
  1633. /* If we're trying to split from the start, just add a new blank line before */
  1634. if (split == 0) {
  1635. return add_line(lines, line);
  1636. }
  1637. if (!env->loading && global_config.history_enabled) {
  1638. history_t * e = malloc(sizeof(history_t));
  1639. e->type = HISTORY_SPLIT_LINE;
  1640. e->contents.add_merge_split_lines.lineno = line;
  1641. e->contents.add_merge_split_lines.split = split;
  1642. HIST_APPEND(e);
  1643. }
  1644. /* Allocate more space as needed */
  1645. if (env->line_count == env->line_avail) {
  1646. env->line_avail *= 2;
  1647. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1648. }
  1649. if (!env->loading) {
  1650. unhighlight_matching_paren();
  1651. }
  1652. /* Shift later lines down */
  1653. if (line < env->line_count) {
  1654. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1655. }
  1656. /* I have no idea what this is doing */
  1657. int remaining = lines[line]->actual - split;
  1658. int v = remaining;
  1659. v--;
  1660. v |= v >> 1;
  1661. v |= v >> 2;
  1662. v |= v >> 4;
  1663. v |= v >> 8;
  1664. v |= v >> 16;
  1665. v++;
  1666. /* Allocate space for the new line */
  1667. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1668. lines[line+1]->available = v;
  1669. lines[line+1]->actual = remaining;
  1670. /* Move the data from the old line into the new line */
  1671. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1672. lines[line]->actual = split;
  1673. if (!env->loading) {
  1674. lines[line]->rev_status = 2;
  1675. lines[line+1]->rev_status = 2;
  1676. recalculate_tabs(lines[line]);
  1677. recalculate_tabs(lines[line+1]);
  1678. recalculate_syntax(lines[line], line);
  1679. recalculate_syntax(lines[line+1], line+1);
  1680. }
  1681. /* There is one new line */
  1682. env->line_count += 1;
  1683. /* We may have reallocated lines */
  1684. return lines;
  1685. }
  1686. /**
  1687. * Understand spaces and comments and check if the previous line
  1688. * ended with a brace or a colon.
  1689. */
  1690. int line_ends_with_brace(line_t * line) {
  1691. int i = line->actual-1;
  1692. while (i >= 0) {
  1693. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1694. i--;
  1695. } else {
  1696. break;
  1697. }
  1698. }
  1699. if (i < 0) return 0;
  1700. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':') ? i+1 : 0;
  1701. }
  1702. int line_is_comment(line_t * line) {
  1703. if (!env->syntax) return 0;
  1704. if (!strcmp(env->syntax->name,"c")) {
  1705. if (line->istate == 1) return 1;
  1706. } else if (!strcmp(env->syntax->name,"java")) {
  1707. if (line->istate == 1) return 1;
  1708. } else if (!strcmp(env->syntax->name,"kotlin")) {
  1709. if (line->istate == 1) return 1;
  1710. } else if (!strcmp(env->syntax->name,"rust")) {
  1711. if (line->istate > 0) return 1;
  1712. }
  1713. return 0;
  1714. }
  1715. int find_brace_line_start(int line, int col) {
  1716. int ncol = col - 1;
  1717. while (ncol > 0) {
  1718. if (env->lines[line-1]->text[ncol-1].codepoint == ')') {
  1719. int t_line_no = env->line_no;
  1720. int t_col_no = env->col_no;
  1721. env->line_no = line;
  1722. env->col_no = ncol;
  1723. int paren_match_line = -1, paren_match_col = -1;
  1724. find_matching_paren(&paren_match_line, &paren_match_col, 1);
  1725. if (paren_match_line != -1) {
  1726. line = paren_match_line;
  1727. }
  1728. env->line_no = t_line_no;
  1729. env->col_no = t_col_no;
  1730. break;
  1731. } else if (env->lines[line-1]->text[ncol-1].codepoint == ' ') {
  1732. ncol--;
  1733. } else {
  1734. break;
  1735. }
  1736. }
  1737. return line;
  1738. }
  1739. /**
  1740. * Add indentation from the previous (temporally) line
  1741. */
  1742. void add_indent(int new_line, int old_line, int ignore_brace) {
  1743. if (env->indent) {
  1744. int changed = 0;
  1745. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1746. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1747. if (env->lines[old_line]->text[i].codepoint == '/') {
  1748. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1749. /* Insert ' * ' */
  1750. char_t space = {1,FLAG_COMMENT,' '};
  1751. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1752. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1753. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1754. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1755. env->col_no += 3;
  1756. }
  1757. break;
  1758. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1759. /* Insert ' * ' */
  1760. char_t space = {1,FLAG_COMMENT,' '};
  1761. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1762. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1763. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1764. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1765. env->col_no += 3;
  1766. break;
  1767. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1768. env->lines[old_line]->text[i].codepoint == '\t' ||
  1769. env->lines[old_line]->text[i].codepoint == '*') {
  1770. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1771. env->col_no++;
  1772. changed = 1;
  1773. } else {
  1774. break;
  1775. }
  1776. }
  1777. } else {
  1778. int line_to_copy_from = old_line;
  1779. int col;
  1780. if (old_line < new_line &&
  1781. !ignore_brace &&
  1782. (col = line_ends_with_brace(env->lines[old_line])) &&
  1783. env->lines[old_line]->text[col-1].codepoint == '{') {
  1784. line_to_copy_from = find_brace_line_start(old_line+1, col)-1;
  1785. }
  1786. for (int i = 0; i < env->lines[line_to_copy_from]->actual; ++i) {
  1787. if (line_to_copy_from < new_line && i == env->lines[line_to_copy_from]->actual - 3 &&
  1788. env->lines[line_to_copy_from]->text[i].codepoint == ' ' &&
  1789. env->lines[line_to_copy_from]->text[i+1].codepoint == '*' &&
  1790. env->lines[line_to_copy_from]->text[i+2].codepoint == '/') {
  1791. break;
  1792. } else if (env->lines[line_to_copy_from]->text[i].codepoint == ' ' ||
  1793. env->lines[line_to_copy_from]->text[i].codepoint == '\t') {
  1794. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[line_to_copy_from]->text[i],i,new_line);
  1795. env->col_no++;
  1796. changed = 1;
  1797. } else {
  1798. break;
  1799. }
  1800. }
  1801. }
  1802. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1803. if (env->tabs) {
  1804. char_t c;
  1805. c.codepoint = '\t';
  1806. c.display_width = env->tabstop;
  1807. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1808. env->col_no++;
  1809. changed = 1;
  1810. } else {
  1811. for (int j = 0; j < env->tabstop; ++j) {
  1812. char_t c;
  1813. c.codepoint = ' ';
  1814. c.display_width = 1;
  1815. c.flags = FLAG_SELECT;
  1816. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1817. env->col_no++;
  1818. }
  1819. changed = 1;
  1820. }
  1821. }
  1822. int was_whitespace = 1;
  1823. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1824. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1825. env->lines[old_line]->text[i].codepoint != '\t') {
  1826. was_whitespace = 0;
  1827. break;
  1828. }
  1829. }
  1830. if (was_whitespace) {
  1831. while (env->lines[old_line]->actual) {
  1832. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1833. }
  1834. }
  1835. if (changed) {
  1836. recalculate_syntax(env->lines[new_line],new_line);
  1837. }
  1838. }
  1839. }
  1840. /**
  1841. * Initialize a buffer with default values
  1842. */
  1843. void setup_buffer(buffer_t * env) {
  1844. /* If this buffer was already initialized, clear out its line data */
  1845. if (env->lines) {
  1846. for (int i = 0; i < env->line_count; ++i) {
  1847. free(env->lines[i]);
  1848. }
  1849. free(env->lines);
  1850. }
  1851. /* Default state parameters */
  1852. env->line_no = 1; /* Default cursor position */
  1853. env->col_no = 1;
  1854. env->line_count = 1; /* Buffers always have at least one line */
  1855. env->modified = 0;
  1856. env->readonly = 0;
  1857. env->offset = 0;
  1858. env->line_avail = 8; /* Default line buffer capacity */
  1859. env->tabs = 1; /* Tabs by default */
  1860. env->tabstop = 4; /* Tab stop width */
  1861. env->indent = 1; /* Auto-indent by default */
  1862. env->history = malloc(sizeof(struct history));
  1863. memset(env->history, 0, sizeof(struct history));
  1864. env->last_save_history = env->history;
  1865. /* Allocate line buffer */
  1866. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1867. /* Initialize the first line */
  1868. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1869. env->lines[0]->available = 32;
  1870. }
  1871. /**
  1872. * Toggle buffered / unbuffered modes
  1873. */
  1874. struct termios old;
  1875. void get_initial_termios(void) {
  1876. tcgetattr(STDOUT_FILENO, &old);
  1877. }
  1878. void set_unbuffered(void) {
  1879. struct termios new = old;
  1880. new.c_iflag &= (~ICRNL) & (~IXON);
  1881. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1882. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1883. }
  1884. void set_buffered(void) {
  1885. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1886. }
  1887. /**
  1888. * Convert codepoint to utf-8 string
  1889. */
  1890. int to_eight(uint32_t codepoint, char * out) {
  1891. memset(out, 0x00, 7);
  1892. if (codepoint < 0x0080) {
  1893. out[0] = (char)codepoint;
  1894. } else if (codepoint < 0x0800) {
  1895. out[0] = 0xC0 | (codepoint >> 6);
  1896. out[1] = 0x80 | (codepoint & 0x3F);
  1897. } else if (codepoint < 0x10000) {
  1898. out[0] = 0xE0 | (codepoint >> 12);
  1899. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1900. out[2] = 0x80 | (codepoint & 0x3F);
  1901. } else if (codepoint < 0x200000) {
  1902. out[0] = 0xF0 | (codepoint >> 18);
  1903. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1904. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1905. out[3] = 0x80 | ((codepoint) & 0x3F);
  1906. } else if (codepoint < 0x4000000) {
  1907. out[0] = 0xF8 | (codepoint >> 24);
  1908. out[1] = 0x80 | (codepoint >> 18);
  1909. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1910. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1911. out[4] = 0x80 | ((codepoint) & 0x3F);
  1912. } else {
  1913. out[0] = 0xF8 | (codepoint >> 30);
  1914. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1915. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1916. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1917. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1918. out[5] = 0x80 | ((codepoint) & 0x3F);
  1919. }
  1920. return strlen(out);
  1921. }
  1922. /**
  1923. * Get the presentation width of a codepoint
  1924. */
  1925. int codepoint_width(wchar_t codepoint) {
  1926. if (codepoint == '\t') {
  1927. return 1; /* Recalculate later */
  1928. }
  1929. if (codepoint < 32) {
  1930. /* We render these as ^@ */
  1931. return 2;
  1932. }
  1933. if (codepoint == 0x7F) {
  1934. /* Renders as ^? */
  1935. return 2;
  1936. }
  1937. if (codepoint > 0x7f && codepoint < 0xa0) {
  1938. /* Upper control bytes <xx> */
  1939. return 4;
  1940. }
  1941. if (codepoint == 0xa0) {
  1942. /* Non-breaking space _ */
  1943. return 1;
  1944. }
  1945. /* Skip wcwidth for anything under 256 */
  1946. if (codepoint > 256) {
  1947. if (global_config.can_unicode) {
  1948. /* Higher codepoints may be wider (eg. Japanese) */
  1949. int out = wcwidth(codepoint);
  1950. if (out >= 1) return out;
  1951. }
  1952. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1953. return (codepoint < 0x10000) ? 8 : 10;
  1954. }
  1955. return 1;
  1956. }
  1957. /**
  1958. * Move the terminal cursor
  1959. */
  1960. void place_cursor(int x, int y) {
  1961. printf("\033[%d;%dH", y, x);
  1962. }
  1963. char * color_string(const char * fg, const char * bg) {
  1964. static char output[100];
  1965. char * t = output;
  1966. t += sprintf(t,"\033[22;23;24;");
  1967. if (*bg == '@') {
  1968. int _bg = atoi(bg+1);
  1969. if (_bg < 10) {
  1970. t += sprintf(t, "4%d;", _bg);
  1971. } else {
  1972. t += sprintf(t, "10%d;", _bg-10);
  1973. }
  1974. } else {
  1975. t += sprintf(t, "48;%s;", bg);
  1976. }
  1977. if (*fg == '@') {
  1978. int _fg = atoi(fg+1);
  1979. if (_fg < 10) {
  1980. t += sprintf(t, "3%dm", _fg);
  1981. } else {
  1982. t += sprintf(t, "9%dm", _fg-10);
  1983. }
  1984. } else {
  1985. t += sprintf(t, "38;%sm", fg);
  1986. }
  1987. return output;
  1988. }
  1989. /**
  1990. * Set text colors
  1991. *
  1992. * Normally, text colors are just strings, but if they
  1993. * start with @ they will be parsed as integers
  1994. * representing one of the 16 standard colors, suitable
  1995. * for terminals without support for the 256- or 24-bit
  1996. * color modes.
  1997. */
  1998. void set_colors(const char * fg, const char * bg) {
  1999. printf("%s", color_string(fg, bg));
  2000. }
  2001. /**
  2002. * Set just the foreground color
  2003. *
  2004. * (See set_colors above)
  2005. */
  2006. void set_fg_color(const char * fg) {
  2007. printf("\033[22;23;24;");
  2008. if (*fg == '@') {
  2009. int _fg = atoi(fg+1);
  2010. if (_fg < 10) {
  2011. printf("3%dm", _fg);
  2012. } else {
  2013. printf("9%dm", _fg-10);
  2014. }
  2015. } else {
  2016. printf("38;%sm", fg);
  2017. }
  2018. }
  2019. /**
  2020. * Clear the rest of this line
  2021. */
  2022. void clear_to_end(void) {
  2023. if (global_config.can_bce) {
  2024. printf("\033[K");
  2025. }
  2026. }
  2027. /**
  2028. * For terminals without bce,
  2029. * prepaint the whole line, so we don't have to track
  2030. * where the cursor is for everything. Inefficient,
  2031. * but effective.
  2032. */
  2033. void paint_line(const char * bg) {
  2034. if (!global_config.can_bce) {
  2035. set_colors(COLOR_FG, bg);
  2036. for (int i = 0; i < global_config.term_width; ++i) {
  2037. printf(" ");
  2038. }
  2039. printf("\r");
  2040. }
  2041. }
  2042. /**
  2043. * Enable bold text display
  2044. */
  2045. void set_bold(void) {
  2046. printf("\033[1m");
  2047. }
  2048. /**
  2049. * Disable bold
  2050. */
  2051. void unset_bold(void) {
  2052. printf("\033[22m");
  2053. }
  2054. /**
  2055. * Enable underlined text display
  2056. */
  2057. void set_underline(void) {
  2058. printf("\033[4m");
  2059. }
  2060. /**
  2061. * Disable underlined text display
  2062. */
  2063. void unset_underline(void) {
  2064. printf("\033[24m");
  2065. }
  2066. /**
  2067. * Reset text display attributes
  2068. */
  2069. void reset(void) {
  2070. printf("\033[0m");
  2071. }
  2072. /**
  2073. * Clear the entire screen
  2074. */
  2075. void clear_screen(void) {
  2076. printf("\033[H\033[2J");
  2077. }
  2078. /**
  2079. * Hide the cursor
  2080. */
  2081. void hide_cursor(void) {
  2082. if (global_config.can_hideshow) {
  2083. printf("\033[?25l");
  2084. }
  2085. }
  2086. /**
  2087. * Show the cursor
  2088. */
  2089. void show_cursor(void) {
  2090. if (global_config.can_hideshow) {
  2091. printf("\033[?25h");
  2092. }
  2093. }
  2094. /**
  2095. * Store the cursor position
  2096. */
  2097. void store_cursor(void) {
  2098. printf("\0337");
  2099. }
  2100. /**
  2101. * Restore the cursor position.
  2102. */
  2103. void restore_cursor(void) {
  2104. printf("\0338");
  2105. }
  2106. /**
  2107. * Request mouse events
  2108. */
  2109. void mouse_enable(void) {
  2110. if (global_config.can_mouse) {
  2111. printf("\033[?1000h");
  2112. if (global_config.use_sgr_mouse) {
  2113. printf("\033[?1006h");
  2114. }
  2115. }
  2116. }
  2117. /**
  2118. * Stop mouse events
  2119. */
  2120. void mouse_disable(void) {
  2121. if (global_config.can_mouse) {
  2122. if (global_config.use_sgr_mouse) {
  2123. printf("\033[?1006l");
  2124. }
  2125. printf("\033[?1000l");
  2126. }
  2127. }
  2128. /**
  2129. * Shift the screen up one line
  2130. */
  2131. void shift_up(int amount) {
  2132. printf("\033[%dS", amount);
  2133. }
  2134. /**
  2135. * Shift the screen down one line.
  2136. */
  2137. void shift_down(int amount) {
  2138. printf("\033[%dT", amount);
  2139. }
  2140. void insert_lines_at(int line, int count) {
  2141. place_cursor(1, line);
  2142. printf("\033[%dL", count);
  2143. }
  2144. void delete_lines_at(int line, int count) {
  2145. place_cursor(1, line);
  2146. printf("\033[%dM", count);
  2147. }
  2148. /**
  2149. * Switch to the alternate terminal screen.
  2150. */
  2151. void set_alternate_screen(void) {
  2152. if (global_config.can_altscreen) {
  2153. printf("\033[?1049h");
  2154. }
  2155. }
  2156. /**
  2157. * Restore the standard terminal screen.
  2158. */
  2159. void unset_alternate_screen(void) {
  2160. if (global_config.can_altscreen) {
  2161. printf("\033[?1049l");
  2162. }
  2163. }
  2164. /**
  2165. * Enable bracketed paste mode.
  2166. */
  2167. void set_bracketed_paste(void) {
  2168. if (global_config.can_bracketedpaste) {
  2169. printf("\033[?2004h");
  2170. }
  2171. }
  2172. /**
  2173. * Disable bracketed paste mode.
  2174. */
  2175. void unset_bracketed_paste(void) {
  2176. if (global_config.can_bracketedpaste) {
  2177. printf("\033[?2004l");
  2178. }
  2179. }
  2180. /**
  2181. * Get the name of just a file from a full path.
  2182. * Returns a pointer within the original string.
  2183. */
  2184. char * file_basename(char * file) {
  2185. char * c = strrchr(file, '/');
  2186. if (!c) return file;
  2187. return (c+1);
  2188. }
  2189. /**
  2190. * Print a tab name with fixed width and modifiers
  2191. * into an output buffer and return the written width.
  2192. */
  2193. int draw_tab_name(buffer_t * _env, char * out, int max_width, int * width) {
  2194. uint32_t c, state = 0;
  2195. char * t = _env->file_name ? file_basename(_env->file_name) : "[No Name]";
  2196. #define ADD(c) do { \
  2197. *o = c; \
  2198. o++; \
  2199. *o = '\0'; \
  2200. bytes++; \
  2201. } while (0)
  2202. char * o = out;
  2203. *o = '\0';
  2204. int bytes = 0;
  2205. if (max_width < 2) return 1;
  2206. ADD(' ');
  2207. (*width)++;
  2208. if (_env->modified) {
  2209. if (max_width < 4) return 1;
  2210. ADD('+');
  2211. (*width)++;
  2212. ADD(' ');
  2213. (*width)++;
  2214. }
  2215. while (*t) {
  2216. if (!decode(&state, &c, (unsigned char)*t)) {
  2217. char tmp[7];
  2218. int size = to_eight(c, tmp);
  2219. if (bytes + size > 62) break;
  2220. if (*width + size >= max_width) return 1;
  2221. for (int i = 0; i < size; ++i) {
  2222. ADD(tmp[i]);
  2223. }
  2224. (*width) += codepoint_width(c);
  2225. } else if (state == UTF8_REJECT) {
  2226. state = 0;
  2227. }
  2228. t++;
  2229. }
  2230. if (max_width == *width + 1) return 1;
  2231. ADD(' ');
  2232. (*width)++;
  2233. #undef ADD
  2234. return 0;
  2235. }
  2236. /**
  2237. * Redaw the tabbar, with a tab for each buffer.
  2238. *
  2239. * The active buffer is highlighted.
  2240. */
  2241. void redraw_tabbar(void) {
  2242. if (!global_config.tabs_visible) return;
  2243. /* Hide cursor while rendering UI */
  2244. hide_cursor();
  2245. /* Move to upper left */
  2246. place_cursor(1,1);
  2247. paint_line(COLOR_TABBAR_BG);
  2248. /* For each buffer... */
  2249. int offset = 0;
  2250. if (global_config.tab_offset) {
  2251. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2252. printf("<");
  2253. offset++;
  2254. }
  2255. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  2256. buffer_t * _env = buffers[i];
  2257. if (_env == env) {
  2258. /* If this is the active buffer, highlight it */
  2259. reset();
  2260. set_colors(COLOR_FG, COLOR_BG);
  2261. set_bold();
  2262. } else {
  2263. /* Otherwise use default tab color */
  2264. reset();
  2265. set_colors(COLOR_FG, COLOR_TAB_BG);
  2266. set_underline();
  2267. }
  2268. char title[64];
  2269. int size = 0;
  2270. int filled = draw_tab_name(_env, title, global_config.term_width - offset, &size);
  2271. if (filled) {
  2272. offset += size;
  2273. printf("%s", title);
  2274. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2275. while (offset != global_config.term_width - 1) {
  2276. printf(" ");
  2277. offset++;
  2278. }
  2279. printf(">");
  2280. break;
  2281. }
  2282. printf("%s", title);
  2283. offset += size;
  2284. }
  2285. /* Reset bold/underline */
  2286. reset();
  2287. /* Fill the rest of the tab bar */
  2288. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2289. clear_to_end();
  2290. }
  2291. /**
  2292. * Braindead log10 implementation for the line numbers
  2293. */
  2294. int log_base_10(unsigned int v) {
  2295. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2296. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2297. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2298. return r;
  2299. }
  2300. /**
  2301. * Render a line of text
  2302. *
  2303. * This handles rendering the actual text content. A full line of text
  2304. * also includes a line number and some padding.
  2305. *
  2306. * width: width of the text display region (term width - line number width)
  2307. * offset: how many cells into the line to start rendering at
  2308. */
  2309. void render_line(line_t * line, int width, int offset, int line_no) {
  2310. int i = 0; /* Offset in char_t line data entries */
  2311. int j = 0; /* Offset in terminal cells */
  2312. const char * last_color = NULL;
  2313. int was_selecting = 0, was_searching = 0;
  2314. /* Set default text colors */
  2315. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2316. /*
  2317. * When we are rendering in the middle of a wide character,
  2318. * we render -'s to fill the remaining amount of the
  2319. * charater's width
  2320. */
  2321. int remainder = 0;
  2322. int is_spaces = 1;
  2323. /* For each character in the line ... */
  2324. while (i < line->actual) {
  2325. /* If there is remaining text... */
  2326. if (remainder) {
  2327. /* If we should be drawing by now... */
  2328. if (j >= offset) {
  2329. /* Fill remainder with -'s */
  2330. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2331. printf("-");
  2332. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2333. }
  2334. /* One less remaining width cell to fill */
  2335. remainder--;
  2336. /* Terminal offset moves forward */
  2337. j++;
  2338. /*
  2339. * If this was the last remaining character, move to
  2340. * the next codepoint in the line
  2341. */
  2342. if (remainder == 0) {
  2343. i++;
  2344. }
  2345. continue;
  2346. }
  2347. /* Get the next character to draw */
  2348. char_t c = line->text[i];
  2349. if (c.codepoint != ' ') is_spaces = 0;
  2350. /* If we should be drawing by now... */
  2351. if (j >= offset) {
  2352. /* If this character is going to fall off the edge of the screen... */
  2353. if (j - offset + c.display_width >= width) {
  2354. /* We draw this with special colors so it isn't ambiguous */
  2355. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2356. /* If it's wide, draw ---> as needed */
  2357. while (j - offset < width - 1) {
  2358. printf("-");
  2359. j++;
  2360. }
  2361. /* End the line with a > to show it overflows */
  2362. printf(">");
  2363. set_colors(COLOR_FG, COLOR_BG);
  2364. return;
  2365. }
  2366. /* Syntax highlighting */
  2367. const char * color = flag_to_color(c.flags);
  2368. if (c.flags & FLAG_SELECT) {
  2369. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2370. was_selecting = 1;
  2371. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2372. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2373. was_searching = 1;
  2374. } else if (c.flags == FLAG_ERROR) {
  2375. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2376. was_searching = 1; /* co-opting this should work... */
  2377. } else {
  2378. if (was_selecting || was_searching) {
  2379. was_selecting = 0;
  2380. was_searching = 0;
  2381. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2382. last_color = color;
  2383. } else if (!last_color || strcmp(color, last_color)) {
  2384. set_fg_color(color);
  2385. last_color = color;
  2386. }
  2387. }
  2388. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2389. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2390. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2391. ((j == env->sel_col) ||
  2392. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2393. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2394. was_selecting = 1;
  2395. }
  2396. #define _set_colors(fg,bg) \
  2397. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2398. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2399. }
  2400. /* Render special characters */
  2401. if (c.codepoint == '\t') {
  2402. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2403. printf("%s", global_config.tab_indicator);
  2404. for (int i = 1; i < c.display_width; ++i) {
  2405. printf("%s" ,global_config.space_indicator);
  2406. }
  2407. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2408. } else if (c.codepoint < 32) {
  2409. /* Codepoints under 32 to get converted to ^@ escapes */
  2410. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2411. printf("^%c", '@' + c.codepoint);
  2412. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2413. } else if (c.codepoint == 0x7f) {
  2414. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2415. printf("^?");
  2416. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2417. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2418. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2419. printf("<%2x>", c.codepoint);
  2420. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2421. } else if (c.codepoint == 0xa0) {
  2422. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2423. printf("_");
  2424. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2425. } else if (c.display_width == 8) {
  2426. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2427. printf("[U+%04x]", c.codepoint);
  2428. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2429. } else if (c.display_width == 10) {
  2430. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2431. printf("[U+%06x]", c.codepoint);
  2432. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2433. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2434. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2435. if (global_config.can_unicode) {
  2436. printf("▏");
  2437. } else {
  2438. printf("|");
  2439. }
  2440. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2441. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2442. /* Special case: space at end of line */
  2443. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2444. printf("%s",global_config.space_indicator);
  2445. _set_colors(COLOR_FG, COLOR_BG);
  2446. } else {
  2447. /* Normal characters get output */
  2448. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2449. to_eight(c.codepoint, tmp);
  2450. printf("%s", tmp);
  2451. }
  2452. /* Advance the terminal cell offset by the render width of this character */
  2453. j += c.display_width;
  2454. /* Advance to the next character */
  2455. i++;
  2456. } else if (c.display_width > 1) {
  2457. /*
  2458. * If this is a wide character but we aren't ready to render yet,
  2459. * we may need to draw some filler text for the remainder of its
  2460. * width to ensure we don't jump around when horizontally scrolling
  2461. * past wide characters.
  2462. */
  2463. remainder = c.display_width - 1;
  2464. j++;
  2465. } else {
  2466. /* Regular character, not ready to draw, advance without doing anything */
  2467. j++;
  2468. i++;
  2469. }
  2470. }
  2471. if (env->mode != MODE_LINE_SELECTION) {
  2472. if (line->is_current) {
  2473. set_colors(COLOR_FG, COLOR_ALT_BG);
  2474. } else {
  2475. set_colors(COLOR_FG, COLOR_BG);
  2476. }
  2477. } else {
  2478. if (!line->actual) {
  2479. if (env->line_no == line_no ||
  2480. (env->start_line > env->line_no &&
  2481. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2482. (env->start_line < env->line_no &&
  2483. (line_no >= env->start_line && line_no <= env->line_no))) {
  2484. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2485. }
  2486. }
  2487. }
  2488. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2489. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2490. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2491. j <= env->sel_col &&
  2492. env->sel_col < width) {
  2493. set_colors(COLOR_FG, COLOR_BG);
  2494. while (j < env->sel_col) {
  2495. printf(" ");
  2496. j++;
  2497. }
  2498. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2499. printf(" ");
  2500. j++;
  2501. set_colors(COLOR_FG, COLOR_BG);
  2502. }
  2503. if (env->maxcolumn && line_no > -1 /* ensures we don't do this for command line */) {
  2504. /* Fill out the normal background */
  2505. if (j < offset) j = offset;
  2506. for (; j < width + offset && j < env->maxcolumn; ++j) {
  2507. printf(" ");
  2508. }
  2509. /* Draw the line */
  2510. if (j < width + offset && j == env->maxcolumn) {
  2511. j++;
  2512. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2513. if (global_config.can_unicode) {
  2514. printf("▏");
  2515. } else {
  2516. printf("|");
  2517. }
  2518. }
  2519. /* Fill the rest with the alternate background color */
  2520. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2521. }
  2522. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2523. clear_to_end();
  2524. } else {
  2525. /* Paint the rest of the line */
  2526. if (j < offset) j = offset;
  2527. for (; j < width + offset; ++j) {
  2528. printf(" ");
  2529. }
  2530. }
  2531. }
  2532. /**
  2533. * Get the width of the line number region
  2534. */
  2535. int num_width(void) {
  2536. if (!env->numbers) return 0;
  2537. int w = log_base_10(env->line_count) + 3;
  2538. if (w < 4) return 4;
  2539. return w;
  2540. }
  2541. /**
  2542. * Display width of the revision status gutter.
  2543. */
  2544. int gutter_width(void) {
  2545. return env->gutter;
  2546. }
  2547. /**
  2548. * Draw the gutter and line numbers.
  2549. */
  2550. void draw_line_number(int x) {
  2551. if (!env->numbers) return;
  2552. /* Draw the line number */
  2553. if (env->lines[x]->is_current) {
  2554. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2555. } else {
  2556. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2557. }
  2558. if (global_config.relative_lines && x+1 != env->line_no) {
  2559. x = x+1 - env->line_no;
  2560. x = ((x < 0) ? -x : x)-1;
  2561. }
  2562. int num_size = num_width() - 2; /* Padding */
  2563. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2564. printf(" ");
  2565. }
  2566. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2567. }
  2568. /**
  2569. * Used to highlight the current line after moving the cursor.
  2570. */
  2571. void recalculate_current_line(void) {
  2572. int something_changed = 0;
  2573. if (global_config.highlight_current_line) {
  2574. for (int i = 0; i < env->line_count; ++i) {
  2575. if (env->lines[i]->is_current && i != env->line_no-1) {
  2576. env->lines[i]->is_current = 0;
  2577. something_changed = 1;
  2578. redraw_line(i);
  2579. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2580. env->lines[i]->is_current = 1;
  2581. something_changed = 1;
  2582. redraw_line(i);
  2583. }
  2584. }
  2585. } else {
  2586. something_changed = 1;
  2587. }
  2588. if (something_changed && global_config.relative_lines) {
  2589. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2590. /* Place cursor for line number */
  2591. place_cursor(1 + gutter_width() + env->left, (i)-env->offset + 1 + global_config.tabs_visible);
  2592. draw_line_number(i);
  2593. }
  2594. }
  2595. }
  2596. /**
  2597. * Redraw line.
  2598. *
  2599. * This draws the line number as well as the actual text.
  2600. */
  2601. void redraw_line(int x) {
  2602. if (env->loading) return;
  2603. /* Determine if this line is visible. */
  2604. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 1 - global_config.tabs_visible) {
  2605. return;
  2606. }
  2607. /* Calculate offset in screen */
  2608. int j = x - env->offset;
  2609. /* Hide cursor when drawing */
  2610. hide_cursor();
  2611. /* Move cursor to upper left most cell of this line */
  2612. place_cursor(1 + env->left,1 + global_config.tabs_visible + j);
  2613. /* Draw a gutter on the left. */
  2614. if (env->gutter) {
  2615. switch (env->lines[x]->rev_status) {
  2616. case 1:
  2617. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2618. printf(" ");
  2619. break;
  2620. case 2:
  2621. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2622. printf(" ");
  2623. break;
  2624. case 3:
  2625. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2626. printf(" ");
  2627. break;
  2628. case 4:
  2629. set_colors(COLOR_ALT_FG, COLOR_RED);
  2630. printf("▆");
  2631. break;
  2632. case 5:
  2633. set_colors(COLOR_KEYWORD, COLOR_RED);
  2634. printf("▆");
  2635. break;
  2636. default:
  2637. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2638. printf(" ");
  2639. break;
  2640. }
  2641. }
  2642. draw_line_number(x);
  2643. /*
  2644. * Draw the line text
  2645. * If this is the active line, the current character cell offset should be used.
  2646. * (Non-active lines are not shifted and always render from the start of the line)
  2647. */
  2648. render_line(env->lines[x], env->width - gutter_width() - num_width(), (x + 1 == env->line_no || global_config.horizontal_shift_scrolling) ? env->coffset : 0, x+1);
  2649. }
  2650. /**
  2651. * Draw a ~ line where there is no buffer text.
  2652. */
  2653. void draw_excess_line(int j) {
  2654. place_cursor(1+env->left,1 + global_config.tabs_visible + j);
  2655. paint_line(COLOR_ALT_BG);
  2656. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2657. printf("~");
  2658. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2659. clear_to_end();
  2660. } else {
  2661. /* Paint the rest of the line */
  2662. for (int x = 1; x < env->width; ++x) {
  2663. printf(" ");
  2664. }
  2665. }
  2666. }
  2667. /**
  2668. * Redraw the entire text area
  2669. */
  2670. void redraw_text(void) {
  2671. if (!env) return;
  2672. if (!global_config.has_terminal) return;
  2673. /* Hide cursor while rendering */
  2674. hide_cursor();
  2675. /* Figure out the available size of the text region */
  2676. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  2677. int j = 0;
  2678. /* Draw each line */
  2679. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2680. redraw_line(x);
  2681. j++;
  2682. }
  2683. /* Draw the rest of the text region as ~ lines */
  2684. for (; j < l; ++j) {
  2685. draw_excess_line(j);
  2686. }
  2687. }
  2688. static int view_left_offset = 0;
  2689. static int view_right_offset = 0;
  2690. /**
  2691. * When in split view, draw the other buffer.
  2692. * Has special handling for when the split is
  2693. * on a single buffer.
  2694. */
  2695. void redraw_alt_buffer(buffer_t * buf) {
  2696. if (left_buffer == right_buffer) {
  2697. /* draw the opposite view */
  2698. int left, width, offset;
  2699. left = env->left;
  2700. width = env->width;
  2701. offset = env->offset;
  2702. if (left == 0) {
  2703. /* Draw the right side */
  2704. env->left = width;
  2705. env->width = global_config.term_width - width;
  2706. env->offset = view_right_offset;
  2707. view_left_offset = offset;
  2708. } else {
  2709. env->left = 0;
  2710. env->width = global_config.term_width * global_config.split_percent / 100;
  2711. env->offset = view_left_offset;
  2712. view_right_offset = offset;
  2713. }
  2714. redraw_text();
  2715. env->left = left;
  2716. env->width = width;
  2717. env->offset = offset;
  2718. }
  2719. /* Swap out active buffer */
  2720. buffer_t * tmp = env;
  2721. env = buf;
  2722. /* Redraw text */
  2723. redraw_text();
  2724. /* Return original active buffer */
  2725. env = tmp;
  2726. }
  2727. /**
  2728. * Basically wcswidth() but implemented internally using our
  2729. * own utf-8 decoder to ensure it works properly.
  2730. */
  2731. int display_width_of_string(char * str) {
  2732. uint8_t * s = (uint8_t *)str;
  2733. int out = 0;
  2734. uint32_t c, state = 0;
  2735. while (*s) {
  2736. if (!decode(&state, &c, *s)) {
  2737. out += codepoint_width(c);
  2738. } else if (state == UTF8_REJECT) {
  2739. state = 0;
  2740. }
  2741. s++;
  2742. }
  2743. return out;
  2744. }
  2745. int statusbar_append_status(int *remaining_width, char * output, char * base, ...) {
  2746. va_list args;
  2747. va_start(args, base);
  2748. char tmp[100]; /* should be big enough */
  2749. vsnprintf(tmp, 100, base, args);
  2750. va_end(args);
  2751. int width = display_width_of_string(tmp) + 2;
  2752. if (width < *remaining_width) {
  2753. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2754. strcat(output,"[");
  2755. strcat(output,color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2756. strcat(output, tmp);
  2757. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2758. strcat(output,"]");
  2759. (*remaining_width) -= width;
  2760. return width;
  2761. } else {
  2762. return 0;
  2763. }
  2764. }
  2765. int statusbar_build_right(char * right_hand) {
  2766. char tmp[1024];
  2767. sprintf(tmp, " Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2768. int out = display_width_of_string(tmp);
  2769. char * s = right_hand;
  2770. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2771. s += sprintf(s, " Line ");
  2772. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2773. s += sprintf(s, "%d/%d ", env->line_no, env->line_count);
  2774. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2775. s += sprintf(s, " Col: ");
  2776. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2777. s += sprintf(s, "%d ", env->col_no);
  2778. return out;
  2779. }
  2780. /**
  2781. * Draw the status bar
  2782. *
  2783. * The status bar shows the name of the file, whether it has modifications,
  2784. * and (in the future) what syntax highlighting mode is enabled.
  2785. *
  2786. * The right side of the tatus bar shows the line number and column.
  2787. */
  2788. void redraw_statusbar(void) {
  2789. if (global_config.hide_statusbar) return;
  2790. if (!global_config.has_terminal) return;
  2791. if (!env) return;
  2792. /* Hide cursor while rendering */
  2793. hide_cursor();
  2794. /* Move cursor to the status bar line (second from bottom */
  2795. place_cursor(1, global_config.term_height - 1);
  2796. /* Set background colors for status line */
  2797. paint_line(COLOR_STATUS_BG);
  2798. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2799. /* Pre-render the right hand side of the status bar */
  2800. char right_hand[1024];
  2801. int right_width = statusbar_build_right(right_hand);
  2802. char status_bits[1024] = {0}; /* Sane maximum */
  2803. int status_bits_width = 0;
  2804. int remaining_width = global_config.term_width - right_width;
  2805. #define ADD(...) do { status_bits_width += statusbar_append_status(&remaining_width, status_bits, __VA_ARGS__); } while (0)
  2806. if (env->syntax) {
  2807. ADD("%s",env->syntax->name);
  2808. }
  2809. /* Print file status indicators */
  2810. if (env->modified) {
  2811. ADD("+");
  2812. }
  2813. if (env->readonly) {
  2814. ADD("ro");
  2815. }
  2816. if (env->crnl) {
  2817. ADD("crnl");
  2818. }
  2819. if (env->tabs) {
  2820. ADD("tabs");
  2821. } else {
  2822. ADD("spaces=%d", env->tabstop);
  2823. }
  2824. if (global_config.yanks) {
  2825. ADD("y:%ld", global_config.yank_count);
  2826. }
  2827. if (env->indent) {
  2828. ADD("indent");
  2829. }
  2830. if (global_config.smart_complete) {
  2831. ADD("complete");
  2832. }
  2833. #undef ADD
  2834. uint8_t * file_name = (uint8_t *)(env->file_name ? env->file_name : "[No Name]");
  2835. int file_name_width = display_width_of_string((char*)file_name);
  2836. if (remaining_width > 3) {
  2837. int is_chopped = 0;
  2838. while (remaining_width < file_name_width + 3) {
  2839. is_chopped = 1;
  2840. if ((*file_name & 0xc0) == 0xc0) { /* First byte of a multibyte character */
  2841. file_name++;
  2842. while ((*file_name & 0xc0) == 0x80) file_name++;
  2843. } else {
  2844. file_name++;
  2845. }
  2846. file_name_width = display_width_of_string((char*)file_name);
  2847. }
  2848. if (is_chopped) {
  2849. set_colors(COLOR_ALT_FG, COLOR_STATUS_BG);
  2850. printf("<");
  2851. }
  2852. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2853. printf("%s ", file_name);
  2854. }
  2855. printf("%s", status_bits);
  2856. /* Clear the rest of the status bar */
  2857. clear_to_end();
  2858. /* Move the cursor appropriately to draw it */
  2859. place_cursor(global_config.term_width - right_width, global_config.term_height - 1);
  2860. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2861. printf("%s",right_hand);
  2862. }
  2863. /**
  2864. * Redraw the navigation numbers on the right side of the command line
  2865. */
  2866. void redraw_nav_buffer() {
  2867. if (!global_config.has_terminal) return;
  2868. if (nav_buffer) {
  2869. store_cursor();
  2870. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2871. printf("%s", nav_buf);
  2872. clear_to_end();
  2873. restore_cursor();
  2874. }
  2875. }
  2876. /**
  2877. * Draw the command line
  2878. *
  2879. * The command line either has input from the user (:quit, :!make, etc.)
  2880. * or shows the INSERT (or VISUAL in the future) mode name.
  2881. */
  2882. void redraw_commandline(void) {
  2883. if (!global_config.has_terminal) return;
  2884. if (!env) return;
  2885. /* Hide cursor while rendering */
  2886. hide_cursor();
  2887. /* Move cursor to the last line */
  2888. place_cursor(1, global_config.term_height);
  2889. /* Set background color */
  2890. paint_line(COLOR_BG);
  2891. set_colors(COLOR_FG, COLOR_BG);
  2892. /* If we are in an edit mode, note that. */
  2893. if (env->mode == MODE_INSERT) {
  2894. set_bold();
  2895. printf("-- INSERT --");
  2896. clear_to_end();
  2897. unset_bold();
  2898. } else if (env->mode == MODE_LINE_SELECTION) {
  2899. set_bold();
  2900. printf("-- LINE SELECTION -- (%d:%d)",
  2901. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2902. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2903. );
  2904. clear_to_end();
  2905. unset_bold();
  2906. } else if (env->mode == MODE_COL_SELECTION) {
  2907. set_bold();
  2908. printf("-- COL SELECTION -- (%d:%d %d)",
  2909. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2910. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2911. (env->sel_col)
  2912. );
  2913. clear_to_end();
  2914. unset_bold();
  2915. } else if (env->mode == MODE_COL_INSERT) {
  2916. set_bold();
  2917. printf("-- COL INSERT -- (%d:%d %d)",
  2918. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2919. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2920. (env->sel_col)
  2921. );
  2922. clear_to_end();
  2923. unset_bold();
  2924. } else if (env->mode == MODE_REPLACE) {
  2925. set_bold();
  2926. printf("-- REPLACE --");
  2927. clear_to_end();
  2928. unset_bold();
  2929. } else if (env->mode == MODE_CHAR_SELECTION) {
  2930. set_bold();
  2931. printf("-- CHAR SELECTION -- ");
  2932. clear_to_end();
  2933. unset_bold();
  2934. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2935. set_bold();
  2936. printf("-- DIRECTORY BROWSE --");
  2937. clear_to_end();
  2938. unset_bold();
  2939. } else {
  2940. clear_to_end();
  2941. }
  2942. redraw_nav_buffer();
  2943. }
  2944. /**
  2945. * Draw a message on the command line.
  2946. */
  2947. void render_commandline_message(char * message, ...) {
  2948. /* varargs setup */
  2949. va_list args;
  2950. va_start(args, message);
  2951. char buf[1024];
  2952. /* Process format string */
  2953. vsnprintf(buf, 1024, message, args);
  2954. va_end(args);
  2955. /* Hide cursor while rendering */
  2956. hide_cursor();
  2957. /* Move cursor to the last line */
  2958. place_cursor(1, global_config.term_height);
  2959. /* Set background color */
  2960. paint_line(COLOR_BG);
  2961. set_colors(COLOR_FG, COLOR_BG);
  2962. printf("%s", buf);
  2963. /* Clear the rest of the status bar */
  2964. clear_to_end();
  2965. redraw_nav_buffer();
  2966. }
  2967. BIM_ACTION(redraw_all, 0,
  2968. "Repaint the screen."
  2969. )(void) {
  2970. if (!env) return;
  2971. redraw_tabbar();
  2972. redraw_text();
  2973. if (left_buffer) {
  2974. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2975. }
  2976. redraw_statusbar();
  2977. redraw_commandline();
  2978. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND || global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  2979. render_command_input_buffer();
  2980. }
  2981. }
  2982. void pause_for_key(void) {
  2983. int c;
  2984. while ((c = bim_getch())== -1);
  2985. bim_unget(c);
  2986. redraw_all();
  2987. }
  2988. /**
  2989. * Redraw all screen elements except the other split view.
  2990. */
  2991. void redraw_most(void) {
  2992. redraw_tabbar();
  2993. redraw_text();
  2994. redraw_statusbar();
  2995. redraw_commandline();
  2996. }
  2997. /**
  2998. * Disable screen splitting.
  2999. */
  3000. void unsplit(void) {
  3001. if (left_buffer) {
  3002. left_buffer->left = 0;
  3003. left_buffer->width = global_config.term_width;
  3004. }
  3005. if (right_buffer) {
  3006. right_buffer->left = 0;
  3007. right_buffer->width = global_config.term_width;
  3008. }
  3009. left_buffer = NULL;
  3010. right_buffer = NULL;
  3011. redraw_all();
  3012. }
  3013. /**
  3014. * Update the terminal title bar
  3015. */
  3016. void update_title(void) {
  3017. if (!global_config.can_title) return;
  3018. char cwd[1024] = {'/',0};
  3019. getcwd(cwd, 1024);
  3020. for (int i = 1; i < 3; ++i) {
  3021. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  3022. }
  3023. }
  3024. /**
  3025. * Mark this buffer as modified and
  3026. * redraw the status and tabbar if needed.
  3027. */
  3028. void set_modified(void) {
  3029. /* If it was already marked modified, no need to do anything */
  3030. if (env->modified) return;
  3031. /* Mark as modified */
  3032. env->modified = 1;
  3033. /* Redraw some things */
  3034. update_title();
  3035. redraw_tabbar();
  3036. redraw_statusbar();
  3037. }
  3038. /**
  3039. * Draw a message on the status line
  3040. */
  3041. void render_status_message(char * message, ...) {
  3042. if (!env) return; /* Don't print when there's no active environment; this usually means a bimrc command tried to print something */
  3043. /* varargs setup */
  3044. va_list args;
  3045. va_start(args, message);
  3046. char buf[1024];
  3047. /* Process format string */
  3048. vsnprintf(buf, 1024, message, args);
  3049. va_end(args);
  3050. /* Hide cursor while rendering */
  3051. hide_cursor();
  3052. /* Move cursor to the status bar line (second from bottom */
  3053. place_cursor(1, global_config.term_height - 1);
  3054. /* Set background colors for status line */
  3055. paint_line(COLOR_STATUS_BG);
  3056. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3057. printf("%s", buf);
  3058. /* Clear the rest of the status bar */
  3059. clear_to_end();
  3060. }
  3061. /**
  3062. * Draw an errormessage to the command line.
  3063. */
  3064. void render_error(char * message, ...) {
  3065. /* varargs setup */
  3066. va_list args;
  3067. va_start(args, message);
  3068. char buf[1024];
  3069. /* Process format string */
  3070. vsnprintf(buf, 1024, message, args);
  3071. va_end(args);
  3072. if (env) {
  3073. /* Hide cursor while rendering */
  3074. hide_cursor();
  3075. /* Move cursor to the command line */
  3076. place_cursor(1, global_config.term_height);
  3077. /* Set appropriate error message colors */
  3078. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  3079. /* Draw the message */
  3080. printf("%s", buf);
  3081. } else {
  3082. printf("bim: error during startup: %s\n", buf);
  3083. }
  3084. }
  3085. char * paren_pairs = "()[]{}<>";
  3086. int is_paren(int c) {
  3087. char * p = paren_pairs;
  3088. while (*p) {
  3089. if (c == *p) return 1;
  3090. p++;
  3091. }
  3092. return 0;
  3093. }
  3094. #define _rehighlight_parens() do { \
  3095. if (i < 0 || i >= env->line_count) break; \
  3096. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  3097. if (i == line-1 && j == col-1) { \
  3098. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  3099. continue; \
  3100. } else { \
  3101. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  3102. } \
  3103. } \
  3104. redraw_line(i); \
  3105. } while (0)
  3106. /**
  3107. * If the config option is enabled, find the matching
  3108. * paren character and highlight it with the SELECT
  3109. * colors, clearing out other SELECT values. As we
  3110. * co-opt the SELECT flag, don't do this in selection
  3111. * modes - only in normal and insert modes.
  3112. */
  3113. void highlight_matching_paren(void) {
  3114. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  3115. if (!global_config.highlight_parens) return;
  3116. int line = -1, col = -1;
  3117. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  3118. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  3119. find_matching_paren(&line, &col, 1);
  3120. } 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)) {
  3121. find_matching_paren(&line, &col, 2);
  3122. }
  3123. if (env->highlighting_paren == -1 && line == -1) return;
  3124. if (env->highlighting_paren > 0) {
  3125. int i = env->highlighting_paren - 1;
  3126. _rehighlight_parens();
  3127. }
  3128. if (env->highlighting_paren != line && line != -1) {
  3129. int i = line - 1;
  3130. _rehighlight_parens();
  3131. }
  3132. env->highlighting_paren = line;
  3133. }
  3134. /**
  3135. * Recalculate syntax for the matched paren.
  3136. * Useful when entering selection modes.
  3137. */
  3138. void unhighlight_matching_paren(void) {
  3139. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  3140. for (int i = env->highlighting_paren - 1; i <= env->highlighting_paren + 1; ++i) {
  3141. if (i >= 1 && i <= env->line_count) {
  3142. recalculate_syntax(env->lines[i-1], i-1);
  3143. redraw_line(i-1);
  3144. }
  3145. }
  3146. env->highlighting_paren = -1;
  3147. }
  3148. }
  3149. /**
  3150. * Move the cursor to the appropriate location based
  3151. * on where it is in the text region.
  3152. *
  3153. * This does some additional math to set the text
  3154. * region horizontal offset.
  3155. */
  3156. void place_cursor_actual(void) {
  3157. /* Invalid positions */
  3158. if (env->line_no < 1) env->line_no = 1;
  3159. if (env->col_no < 1) env->col_no = 1;
  3160. /* Account for the left hand gutter */
  3161. int num_size = num_width() + gutter_width();
  3162. int x = num_size + 1 - env->coffset;
  3163. /* Determine where the cursor is physically */
  3164. for (int i = 0; i < env->col_no - 1; ++i) {
  3165. char_t * c = &env->lines[env->line_no-1]->text[i];
  3166. x += c->display_width;
  3167. }
  3168. /* y is a bit easier to calculate */
  3169. int y = env->line_no - env->offset + 1;
  3170. int needs_redraw = 0;
  3171. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  3172. y++;
  3173. env->offset--;
  3174. needs_redraw = 1;
  3175. }
  3176. while (y > 1 + global_config.term_height - global_config.bottom_size - global_config.cursor_padding - global_config.tabs_visible) {
  3177. y--;
  3178. env->offset++;
  3179. needs_redraw = 1;
  3180. }
  3181. if (needs_redraw) {
  3182. redraw_text();
  3183. redraw_tabbar();
  3184. redraw_statusbar();
  3185. redraw_commandline();
  3186. }
  3187. /* If the cursor has gone off screen to the right... */
  3188. if (x > env->width - 1) {
  3189. /* Adjust the offset appropriately to scroll horizontally */
  3190. int diff = x - (env->width - 1);
  3191. env->coffset += diff;
  3192. x -= diff;
  3193. redraw_text();
  3194. }
  3195. /* Same for scrolling horizontally to the left */
  3196. if (x < num_size + 1) {
  3197. int diff = (num_size + 1) - x;
  3198. env->coffset -= diff;
  3199. x += diff;
  3200. redraw_text();
  3201. }
  3202. highlight_matching_paren();
  3203. recalculate_current_line();
  3204. /* Move the actual terminal cursor */
  3205. place_cursor(x+env->left,y - !global_config.tabs_visible);
  3206. /* Show the cursor */
  3207. show_cursor();
  3208. }
  3209. /**
  3210. * If the screen is split, update the split sizes based
  3211. * on the new terminal width and the user's split_percent setting.
  3212. */
  3213. void update_split_size(void) {
  3214. if (!left_buffer) return;
  3215. if (left_buffer == right_buffer) {
  3216. if (left_buffer->left == 0) {
  3217. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3218. } else {
  3219. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  3220. right_buffer->width = global_config.term_width - right_buffer->left;
  3221. }
  3222. return;
  3223. }
  3224. left_buffer->left = 0;
  3225. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3226. right_buffer->left = left_buffer->width;
  3227. right_buffer->width = global_config.term_width - left_buffer->width;
  3228. }
  3229. /**
  3230. * Update screen size
  3231. */
  3232. void update_screen_size(void) {
  3233. struct winsize w;
  3234. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  3235. global_config.term_width = w.ws_col;
  3236. global_config.term_height = w.ws_row;
  3237. if (env) {
  3238. if (left_buffer) {
  3239. update_split_size();
  3240. } else if (env != left_buffer && env != right_buffer) {
  3241. env->width = w.ws_col;
  3242. }
  3243. }
  3244. for (int i = 0; i < buffers_len; ++i) {
  3245. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  3246. buffers[i]->width = w.ws_col;
  3247. }
  3248. }
  3249. }
  3250. /**
  3251. * Handle terminal size changes
  3252. */
  3253. void SIGWINCH_handler(int sig) {
  3254. (void)sig;
  3255. update_screen_size();
  3256. redraw_all();
  3257. signal(SIGWINCH, SIGWINCH_handler);
  3258. }
  3259. /**
  3260. * Handle suspend
  3261. */
  3262. void SIGTSTP_handler(int sig) {
  3263. (void)sig;
  3264. mouse_disable();
  3265. set_buffered();
  3266. reset();
  3267. clear_screen();
  3268. show_cursor();
  3269. unset_bracketed_paste();
  3270. unset_alternate_screen();
  3271. fflush(stdout);
  3272. signal(SIGTSTP, SIG_DFL);
  3273. raise(SIGTSTP);
  3274. }
  3275. void SIGCONT_handler(int sig) {
  3276. (void)sig;
  3277. set_alternate_screen();
  3278. set_bracketed_paste();
  3279. set_unbuffered();
  3280. update_screen_size();
  3281. mouse_enable();
  3282. redraw_all();
  3283. update_title();
  3284. signal(SIGCONT, SIGCONT_handler);
  3285. signal(SIGTSTP, SIGTSTP_handler);
  3286. }
  3287. void try_to_center() {
  3288. int half_a_screen = (global_config.term_height - 3) / 2;
  3289. if (half_a_screen < env->line_no) {
  3290. env->offset = env->line_no - half_a_screen;
  3291. } else {
  3292. env->offset = 0;
  3293. }
  3294. }
  3295. BIM_ACTION(suspend, 0,
  3296. "Suspend bim and the rest of the job it was run in."
  3297. )(void) {
  3298. kill(0, SIGTSTP);
  3299. }
  3300. /**
  3301. * Move the cursor to a specific line.
  3302. */
  3303. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  3304. "Jump to the requested line."
  3305. )(int line) {
  3306. if (line == -1) line = env->line_count;
  3307. /* Respect file bounds */
  3308. if (line < 1) line = 1;
  3309. if (line > env->line_count) line = env->line_count;
  3310. /* Move the cursor / text region offsets */
  3311. env->coffset = 0;
  3312. env->line_no = line;
  3313. env->col_no = 1;
  3314. if (!env->loading) {
  3315. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  3316. place_cursor_actual();
  3317. } else {
  3318. try_to_center();
  3319. }
  3320. redraw_most();
  3321. } else {
  3322. try_to_center();
  3323. }
  3324. }
  3325. /**
  3326. * Processs (part of) a file and add it to a buffer.
  3327. */
  3328. void add_buffer(uint8_t * buf, int size) {
  3329. for (int i = 0; i < size; ++i) {
  3330. if (!decode(&state, &codepoint_r, buf[i])) {
  3331. uint32_t c = codepoint_r;
  3332. if (c == '\n') {
  3333. if (!env->crnl && env->lines[env->line_no-1]->actual && env->lines[env->line_no-1]->text[env->lines[env->line_no-1]->actual-1].codepoint == '\r') {
  3334. env->lines[env->line_no-1]->actual--;
  3335. env->crnl = 1;
  3336. }
  3337. env->lines = add_line(env->lines, env->line_no);
  3338. env->col_no = 1;
  3339. env->line_no += 1;
  3340. } else if (env->crnl && c == '\r') {
  3341. continue;
  3342. } else {
  3343. char_t _c;
  3344. _c.codepoint = (uint32_t)c;
  3345. _c.flags = 0;
  3346. _c.display_width = codepoint_width((wchar_t)c);
  3347. line_t * line = env->lines[env->line_no - 1];
  3348. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3349. if (line != nline) {
  3350. env->lines[env->line_no - 1] = nline;
  3351. }
  3352. env->col_no += 1;
  3353. }
  3354. } else if (state == UTF8_REJECT) {
  3355. state = 0;
  3356. }
  3357. }
  3358. }
  3359. /**
  3360. * Add a raw string to a buffer. Convenience wrapper
  3361. * for add_buffer for nil-terminated strings.
  3362. */
  3363. void add_string(char * string) {
  3364. add_buffer((uint8_t*)string,strlen(string));
  3365. }
  3366. int str_ends_with(const char * haystack, const char * needle) {
  3367. int i = strlen(haystack);
  3368. int j = strlen(needle);
  3369. do {
  3370. if (haystack[i] != needle[j]) return 0;
  3371. if (j == 0) return 1;
  3372. if (i == 0) return 0;
  3373. i--;
  3374. j--;
  3375. } while (1);
  3376. }
  3377. /**
  3378. * Find a syntax highlighter for the given filename.
  3379. */
  3380. struct syntax_definition * match_syntax(char * file) {
  3381. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3382. for (char ** ext = s->ext; *ext; ++ext) {
  3383. if (str_ends_with(file, *ext)) return s;
  3384. }
  3385. }
  3386. return NULL;
  3387. }
  3388. /**
  3389. * Set the syntax configuration by the name of the syntax highlighter.
  3390. */
  3391. void set_syntax_by_name(const char * name) {
  3392. if (!strcmp(name,"none")) {
  3393. for (int i = 0; i < env->line_count; ++i) {
  3394. env->lines[i]->istate = -1;
  3395. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3396. env->lines[i]->text[j].flags = 0;
  3397. }
  3398. }
  3399. env->syntax = NULL;
  3400. redraw_all();
  3401. return;
  3402. }
  3403. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3404. if (!strcmp(name,s->name)) {
  3405. env->syntax = s;
  3406. for (int i = 0; i < env->line_count; ++i) {
  3407. env->lines[i]->istate = -1;
  3408. }
  3409. for (int i = 0; i < env->line_count; ++i) {
  3410. recalculate_syntax(env->lines[i],i);
  3411. }
  3412. redraw_all();
  3413. return;
  3414. }
  3415. }
  3416. render_error("unrecognized syntax type");
  3417. }
  3418. /**
  3419. * Check if a string is all numbers.
  3420. */
  3421. int is_all_numbers(const char * c) {
  3422. while (*c) {
  3423. if (!isdigit(*c)) return 0;
  3424. c++;
  3425. }
  3426. return 1;
  3427. }
  3428. struct file_listing {
  3429. int type;
  3430. char * filename;
  3431. };
  3432. int sort_files(const void * a, const void * b) {
  3433. struct file_listing * _a = (struct file_listing *)a;
  3434. struct file_listing * _b = (struct file_listing *)b;
  3435. if (_a->type == _b->type) {
  3436. return strcmp(_a->filename, _b->filename);
  3437. } else {
  3438. return _a->type - _b->type;
  3439. }
  3440. }
  3441. void read_directory_into_buffer(char * file) {
  3442. DIR * dirp = opendir(file);
  3443. if (!dirp) {
  3444. env->loading = 0;
  3445. return;
  3446. }
  3447. add_string("# Directory listing for `");
  3448. add_string(file);
  3449. add_string("`\n");
  3450. /* Flexible array to hold directory contents */
  3451. int available = 32;
  3452. int count = 0;
  3453. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3454. /* Read directory */
  3455. struct dirent * ent = readdir(dirp);
  3456. while (ent) {
  3457. struct stat statbuf;
  3458. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3459. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3460. stat(tmp, &statbuf);
  3461. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3462. if (count + 1 == available) {
  3463. available *= 2; \
  3464. files = realloc(files, sizeof(struct file_listing) * available); \
  3465. } \
  3466. files[count].type = type;
  3467. files[count].filename = strdup(ent->d_name);
  3468. count++;
  3469. ent = readdir(dirp);
  3470. }
  3471. closedir(dirp);
  3472. /* Sort directory entries */
  3473. qsort(files, count, sizeof(struct file_listing), sort_files);
  3474. for (int i = 0; i < count; ++i) {
  3475. add_string(files[i].type == 'd' ? "d" : "f");
  3476. add_string(" ");
  3477. add_string(files[i].filename);
  3478. add_string("\n");
  3479. free(files[i].filename);
  3480. }
  3481. free(files);
  3482. env->file_name = strdup(file);
  3483. env->syntax = find_syntax_calculator("dirent");
  3484. for (int i = 0; i < env->line_count; ++i) {
  3485. recalculate_syntax(env->lines[i],i);
  3486. }
  3487. env->readonly = 1;
  3488. env->loading = 0;
  3489. env->mode = MODE_DIRECTORY_BROWSE;
  3490. env->line_no = 1;
  3491. redraw_all();
  3492. }
  3493. BIM_ACTION(open_file_from_line, 0,
  3494. "When browsing a directory, open the file under the cursor."
  3495. )(void) {
  3496. if (env->lines[env->line_no-1]->actual < 1) return;
  3497. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3498. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3499. /* Collect file name */
  3500. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3501. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3502. char * t = tmp;
  3503. /* Start by copying the filename */
  3504. t += sprintf(t, "%s/", env->file_name);
  3505. /* Start from character 2 to skip d/f and space */
  3506. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3507. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3508. }
  3509. *t = '\0';
  3510. /* Normalize */
  3511. char tmp_path[PATH_MAX+1];
  3512. if (!realpath(tmp, tmp_path)) {
  3513. free(tmp);
  3514. return;
  3515. }
  3516. free(tmp);
  3517. /* Open file */
  3518. buffer_t * old_buffer = env;
  3519. open_file(tmp_path);
  3520. buffer_close(old_buffer);
  3521. update_title();
  3522. redraw_all();
  3523. }
  3524. int line_matches(line_t * line, char * string) {
  3525. uint32_t c, state = 0;
  3526. int i = 0;
  3527. while (*string) {
  3528. if (!decode(&state, &c, *string)) {
  3529. if (i >= line->actual) return 0;
  3530. if (line->text[i].codepoint != c) return 0;
  3531. string++;
  3532. i++;
  3533. } else if (state == UTF8_REJECT) {
  3534. state = 0;
  3535. }
  3536. }
  3537. return 1;
  3538. }
  3539. void run_onload(buffer_t * env) {
  3540. if (has_function("onload:*")) {
  3541. run_function("onload:*");
  3542. }
  3543. if (env->syntax) {
  3544. char tmp[512];
  3545. sprintf(tmp, "onload:%s", env->syntax->name);
  3546. if (has_function(tmp)) {
  3547. run_function(tmp);
  3548. }
  3549. }
  3550. }
  3551. /**
  3552. * Create a new buffer from a file.
  3553. */
  3554. void open_file(char * file) {
  3555. env = buffer_new();
  3556. env->width = global_config.term_width;
  3557. env->left = 0;
  3558. env->loading = 1;
  3559. setup_buffer(env);
  3560. FILE * f;
  3561. int init_line = -1;
  3562. if (!strcmp(file,"-")) {
  3563. /**
  3564. * Read file from stdin. stderr provides terminal input.
  3565. */
  3566. if (isatty(STDIN_FILENO)) {
  3567. if (buffers_len == 1) {
  3568. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3569. }
  3570. close_buffer();
  3571. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3572. return;
  3573. }
  3574. f = stdin;
  3575. env->modified = 1;
  3576. } else {
  3577. char * l = strrchr(file, ':');
  3578. if (l && is_all_numbers(l+1)) {
  3579. *l = '\0';
  3580. l++;
  3581. init_line = atoi(l);
  3582. }
  3583. char * _file = file;
  3584. if (file[0] == '~') {
  3585. char * home = getenv("HOME");
  3586. if (home) {
  3587. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3588. sprintf(_file, "%s%s", home, file+1);
  3589. }
  3590. }
  3591. struct stat statbuf;
  3592. if (!stat(_file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3593. read_directory_into_buffer(_file);
  3594. if (file != _file) free(_file);
  3595. return;
  3596. }
  3597. f = fopen(_file, "r");
  3598. if (file != _file) free(_file);
  3599. env->file_name = strdup(file);
  3600. }
  3601. if (!f) {
  3602. if (global_config.highlight_on_open) {
  3603. env->syntax = match_syntax(file);
  3604. }
  3605. env->loading = 0;
  3606. if (global_config.go_to_line) {
  3607. goto_line(1);
  3608. }
  3609. if (env->syntax && env->syntax->prefers_spaces) {
  3610. env->tabs = 0;
  3611. }
  3612. run_onload(env);
  3613. return;
  3614. }
  3615. uint8_t buf[BLOCK_SIZE];
  3616. state = 0;
  3617. while (!feof(f) && !ferror(f)) {
  3618. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3619. add_buffer(buf, r);
  3620. }
  3621. if (ferror(f)) {
  3622. env->loading = 0;
  3623. return;
  3624. }
  3625. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3626. /* Remove blank line from end */
  3627. env->lines = remove_line(env->lines, env->line_no-1);
  3628. }
  3629. if (global_config.highlight_on_open) {
  3630. env->syntax = match_syntax(file);
  3631. if (!env->syntax) {
  3632. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3633. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3634. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3635. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3636. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3637. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3638. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3639. }
  3640. if (!env->syntax && global_config.syntax_fallback) {
  3641. set_syntax_by_name(global_config.syntax_fallback);
  3642. }
  3643. for (int i = 0; i < env->line_count; ++i) {
  3644. recalculate_syntax(env->lines[i],i);
  3645. }
  3646. }
  3647. /* Try to automatically figure out tabs vs. spaces */
  3648. int tabs = 0, spaces = 0;
  3649. for (int i = 0; i < env->line_count; ++i) {
  3650. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3651. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3652. if (env->lines[i]->text[0].codepoint == ' ' &&
  3653. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3654. spaces++;
  3655. }
  3656. }
  3657. if (spaces > tabs) {
  3658. env->tabs = 0;
  3659. } else if (spaces == tabs && env->syntax) {
  3660. env->tabs = env->syntax->prefers_spaces;
  3661. }
  3662. /* TODO figure out tabstop for spaces? */
  3663. env->loading = 0;
  3664. if (global_config.check_git) {
  3665. env->checkgitstatusonwrite = 1;
  3666. git_examine(file);
  3667. }
  3668. for (int i = 0; i < env->line_count; ++i) {
  3669. recalculate_tabs(env->lines[i]);
  3670. }
  3671. if (global_config.go_to_line) {
  3672. if (init_line != -1) {
  3673. goto_line(init_line);
  3674. } else {
  3675. env->line_no = 1;
  3676. env->col_no = 1;
  3677. fetch_from_biminfo(env);
  3678. place_cursor_actual();
  3679. redraw_all();
  3680. set_preferred_column();
  3681. }
  3682. }
  3683. fclose(f);
  3684. run_onload(env);
  3685. }
  3686. /**
  3687. * Clean up the terminal and exit the editor.
  3688. */
  3689. void quit(const char * message) {
  3690. mouse_disable();
  3691. set_buffered();
  3692. reset();
  3693. clear_screen();
  3694. show_cursor();
  3695. unset_bracketed_paste();
  3696. unset_alternate_screen();
  3697. if (message) {
  3698. fprintf(stdout, "%s\n", message);
  3699. }
  3700. exit(0);
  3701. }
  3702. /**
  3703. * Try to quit, but don't continue if there are
  3704. * modified buffers open.
  3705. */
  3706. void try_quit(void) {
  3707. for (int i = 0; i < buffers_len; i++ ) {
  3708. buffer_t * _env = buffers[i];
  3709. if (_env->modified) {
  3710. if (_env->file_name) {
  3711. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3712. } else {
  3713. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3714. }
  3715. return;
  3716. }
  3717. }
  3718. /* Close all buffers */
  3719. while (buffers_len) {
  3720. buffer_close(buffers[0]);
  3721. }
  3722. quit(NULL);
  3723. }
  3724. /**
  3725. * Switch to the previous buffer
  3726. */
  3727. BIM_ACTION(previous_tab, 0,
  3728. "Switch the previoius tab"
  3729. )(void) {
  3730. buffer_t * last = NULL;
  3731. for (int i = 0; i < buffers_len; i++) {
  3732. buffer_t * _env = buffers[i];
  3733. if (_env == env) {
  3734. if (last) {
  3735. /* Wrap around */
  3736. env = last;
  3737. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3738. redraw_all();
  3739. update_title();
  3740. return;
  3741. } else {
  3742. env = buffers[buffers_len-1];
  3743. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3744. redraw_all();
  3745. update_title();
  3746. return;
  3747. }
  3748. }
  3749. last = _env;
  3750. }
  3751. }
  3752. /**
  3753. * Switch to the next buffer
  3754. */
  3755. BIM_ACTION(next_tab, 0,
  3756. "Switch to the next tab"
  3757. )(void) {
  3758. for (int i = 0; i < buffers_len; i++) {
  3759. buffer_t * _env = buffers[i];
  3760. if (_env == env) {
  3761. if (i != buffers_len - 1) {
  3762. env = buffers[i+1];
  3763. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3764. redraw_all();
  3765. update_title();
  3766. return;
  3767. } else {
  3768. /* Wrap around */
  3769. env = buffers[0];
  3770. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3771. redraw_all();
  3772. update_title();
  3773. return;
  3774. }
  3775. }
  3776. }
  3777. }
  3778. /**
  3779. * Check for modified lines in a file by examining `git diff` output.
  3780. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3781. */
  3782. int git_examine(char * filename) {
  3783. if (env->modified) return 1;
  3784. int fds[2];
  3785. pipe(fds);
  3786. int child = fork();
  3787. if (child == 0) {
  3788. FILE * dev_null = fopen("/dev/null","w");
  3789. close(fds[0]);
  3790. dup2(fds[1], STDOUT_FILENO);
  3791. dup2(fileno(dev_null), STDERR_FILENO);
  3792. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3793. exit(execvp("git",args));
  3794. } else if (child < 0) {
  3795. return 1;
  3796. }
  3797. close(fds[1]);
  3798. FILE * f = fdopen(fds[0],"r");
  3799. int line_offset = 0;
  3800. while (!feof(f)) {
  3801. int c = fgetc(f);
  3802. if (c < 0) break;
  3803. if (c == '@' && line_offset == 0) {
  3804. /* Read line offset, count */
  3805. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3806. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3807. int from_line = 0;
  3808. int from_count = 0;
  3809. int to_line = 0;
  3810. int to_count = 0;
  3811. fscanf(f,"%d",&from_line);
  3812. if (fgetc(f) == ',') {
  3813. fscanf(f,"%d",&from_count);
  3814. } else {
  3815. from_count = 1;
  3816. }
  3817. fscanf(f,"%d",&to_line);
  3818. if (fgetc(f) == ',') {
  3819. fscanf(f,"%d",&to_count);
  3820. } else {
  3821. to_count = 1;
  3822. }
  3823. if (to_line > env->line_count) continue;
  3824. if (from_count == 0 && to_count > 0) {
  3825. /* No -, all + means all of to_count is green */
  3826. for (int i = 0; i < to_count; ++i) {
  3827. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3828. }
  3829. } else if (from_count > 0 && to_count == 0) {
  3830. /*
  3831. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3832. * Note that to_line is one lower than the affacted line, so we don't need to mes with indexes.
  3833. */
  3834. if (to_line >= env->line_count) continue;
  3835. env->lines[to_line]->rev_status = 4; /* Red */
  3836. } else if (from_count > 0 && from_count == to_count) {
  3837. /* from = to, all modified */
  3838. for (int i = 0; i < to_count; ++i) {
  3839. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3840. }
  3841. } else if (from_count > 0 && from_count < to_count) {
  3842. /* from < to, some modified, some added */
  3843. for (int i = 0; i < from_count; ++i) {
  3844. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3845. }
  3846. for (int i = from_count; i < to_count; ++i) {
  3847. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3848. }
  3849. } else if (to_count > 0 && from_count > to_count) {
  3850. /* from > to, we deleted but also modified some lines */
  3851. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3852. for (int i = 1; i < to_count; ++i) {
  3853. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3854. }
  3855. }
  3856. }
  3857. }
  3858. if (c == '\n') {
  3859. line_offset = 0;
  3860. continue;
  3861. }
  3862. line_offset++;
  3863. }
  3864. fclose(f);
  3865. return 0;
  3866. }
  3867. /**
  3868. * Write file contents to FILE
  3869. */
  3870. void output_file(buffer_t * env, FILE * f) {
  3871. int i, j;
  3872. for (i = 0; i < env->line_count; ++i) {
  3873. line_t * line = env->lines[i];
  3874. line->rev_status = 0;
  3875. for (j = 0; j < line->actual; j++) {
  3876. char_t c = line->text[j];
  3877. if (c.codepoint == 0) {
  3878. char buf[1] = {0};
  3879. fwrite(buf, 1, 1, f);
  3880. } else {
  3881. char tmp[8] = {0};
  3882. int i = to_eight(c.codepoint, tmp);
  3883. fwrite(tmp, i, 1, f);
  3884. }
  3885. }
  3886. if (env->crnl) fputc('\r', f);
  3887. fputc('\n', f);
  3888. }
  3889. }
  3890. /**
  3891. * Write active buffer to file
  3892. */
  3893. void write_file(char * file) {
  3894. if (!file) {
  3895. render_error("Need a file to write to.");
  3896. return;
  3897. }
  3898. char * _file = file;
  3899. if (file[0] == '~') {
  3900. char * home = getenv("HOME");
  3901. if (home) {
  3902. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3903. sprintf(_file, "%s%s", home, file+1);
  3904. }
  3905. }
  3906. FILE * f = fopen(_file, "w+");
  3907. if (file != _file) free(_file);
  3908. if (!f) {
  3909. render_error("Failed to open file for writing.");
  3910. return;
  3911. }
  3912. /* Go through each line and convert it back to UTF-8 */
  3913. output_file(env, f);
  3914. fclose(f);
  3915. /* Mark it no longer modified */
  3916. env->modified = 0;
  3917. env->last_save_history = env->history;
  3918. /* If there was no file name set, set one */
  3919. if (!env->file_name) {
  3920. env->file_name = malloc(strlen(file) + 1);
  3921. memcpy(env->file_name, file, strlen(file) + 1);
  3922. }
  3923. if (env->checkgitstatusonwrite) {
  3924. git_examine(file);
  3925. }
  3926. update_title();
  3927. redraw_all();
  3928. }
  3929. /**
  3930. * Close the active buffer
  3931. */
  3932. void close_buffer(void) {
  3933. buffer_t * previous_env = env;
  3934. buffer_t * new_env = buffer_close(env);
  3935. if (new_env == previous_env) {
  3936. /* ?? Failed to close buffer */
  3937. render_error("lolwat");
  3938. }
  3939. if (left_buffer && env == left_buffer) {
  3940. left_buffer = NULL;
  3941. right_buffer->left = 0;
  3942. right_buffer->width = global_config.term_width;
  3943. right_buffer = NULL;
  3944. } else if (left_buffer && env == right_buffer) {
  3945. right_buffer = NULL;
  3946. left_buffer->left = 0;
  3947. left_buffer->width = global_config.term_width;
  3948. left_buffer = NULL;
  3949. }
  3950. /* No more buffers, exit */
  3951. if (!new_env) {
  3952. quit(NULL);
  3953. }
  3954. /* Set the new active buffer */
  3955. env = new_env;
  3956. /* Redraw the screen */
  3957. redraw_all();
  3958. update_title();
  3959. }
  3960. /**
  3961. * Set the visual column the cursor should attempt to keep
  3962. * when moving up and down based on where the cursor currently is.
  3963. * This should happen whenever the user intentionally changes
  3964. * the cursor's horizontal positioning, such as with left/right
  3965. * arrow keys, word-move, search, mouse, etc.
  3966. */
  3967. void set_preferred_column(void) {
  3968. int c = 0;
  3969. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3970. c += env->lines[env->line_no-1]->text[i].display_width;
  3971. }
  3972. env->preferred_column = c;
  3973. }
  3974. BIM_ACTION(cursor_down, 0,
  3975. "Move the cursor one line down."
  3976. )(void) {
  3977. /* If this isn't already the last line... */
  3978. if (env->line_no < env->line_count) {
  3979. /* Move the cursor down */
  3980. env->line_no += 1;
  3981. /* Try to place the cursor horizontally at the preferred column */
  3982. int _x = 0;
  3983. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3984. char_t * c = &env->lines[env->line_no-1]->text[i];
  3985. _x += c->display_width;
  3986. env->col_no = i+1;
  3987. if (_x > env->preferred_column) {
  3988. break;
  3989. }
  3990. }
  3991. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3992. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3993. }
  3994. /*
  3995. * If the horizontal cursor position exceeds the width the new line,
  3996. * then move the cursor left to the extent of the new line.
  3997. *
  3998. * If we're in insert mode, we can go one cell beyond the end of the line
  3999. */
  4000. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4001. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4002. if (env->col_no == 0) env->col_no = 1;
  4003. }
  4004. if (env->loading) return;
  4005. /*
  4006. * If the screen was scrolled horizontally, unscroll it;
  4007. * if it will be scrolled on this line as well, that will
  4008. * be handled by place_cursor_actual
  4009. */
  4010. int redraw = 0;
  4011. if (env->coffset != 0) {
  4012. env->coffset = 0;
  4013. redraw = 1;
  4014. }
  4015. /* If we've scrolled past the bottom of the screen, scroll the screen */
  4016. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  4017. env->offset += 1;
  4018. /* Tell terminal to scroll */
  4019. if (global_config.can_scroll && !left_buffer) {
  4020. if (!global_config.can_insert) {
  4021. shift_up(1);
  4022. redraw_tabbar();
  4023. } else {
  4024. delete_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  4025. }
  4026. /* A new line appears on screen at the bottom, draw it */
  4027. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  4028. if (env->offset + l < env->line_count + 1) {
  4029. redraw_line(env->offset + l-1);
  4030. } else {
  4031. draw_excess_line(l - 1);
  4032. }
  4033. } else {
  4034. redraw_text();
  4035. }
  4036. redraw_statusbar();
  4037. redraw_commandline();
  4038. place_cursor_actual();
  4039. return;
  4040. } else if (redraw) {
  4041. /* Otherwise, if we need to redraw because of coffset change, do that */
  4042. redraw_text();
  4043. }
  4044. set_history_break();
  4045. /* Update the status bar */
  4046. redraw_statusbar();
  4047. /* Place the terminal cursor again */
  4048. place_cursor_actual();
  4049. }
  4050. }
  4051. BIM_ACTION(cursor_up, 0,
  4052. "Move the cursor up one line."
  4053. )(void) {
  4054. /* If this isn't the first line already */
  4055. if (env->line_no > 1) {
  4056. /* Move the cursor down */
  4057. env->line_no -= 1;
  4058. /* Try to place the cursor horizontally at the preferred column */
  4059. int _x = 0;
  4060. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4061. char_t * c = &env->lines[env->line_no-1]->text[i];
  4062. _x += c->display_width;
  4063. env->col_no = i+1;
  4064. if (_x > env->preferred_column) {
  4065. break;
  4066. }
  4067. }
  4068. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4069. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4070. }
  4071. /*
  4072. * If the horizontal cursor position exceeds the width the new line,
  4073. * then move the cursor left to the extent of the new line.
  4074. *
  4075. * If we're in insert mode, we can go one cell beyond the end of the line
  4076. */
  4077. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4078. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4079. if (env->col_no == 0) env->col_no = 1;
  4080. }
  4081. if (env->loading) return;
  4082. /*
  4083. * If the screen was scrolled horizontally, unscroll it;
  4084. * if it will be scrolled on this line as well, that will
  4085. * be handled by place_cursor_actual
  4086. */
  4087. int redraw = 0;
  4088. if (env->coffset != 0) {
  4089. env->coffset = 0;
  4090. redraw = 1;
  4091. }
  4092. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  4093. if (env->line_no <= e) {
  4094. env->offset -= 1;
  4095. /* Tell terminal to scroll */
  4096. if (global_config.can_scroll && !left_buffer) {
  4097. if (!global_config.can_insert) {
  4098. shift_down(1);
  4099. redraw_tabbar();
  4100. } else {
  4101. insert_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  4102. }
  4103. /*
  4104. * The line at the top of the screen should always be real
  4105. * so we can just call redraw_line here
  4106. */
  4107. redraw_line(env->offset);
  4108. } else {
  4109. redraw_tabbar();
  4110. redraw_text();
  4111. }
  4112. redraw_statusbar();
  4113. redraw_commandline();
  4114. place_cursor_actual();
  4115. return;
  4116. } else if (redraw) {
  4117. /* Otherwise, if we need to redraw because of coffset change, do that */
  4118. redraw_text();
  4119. }
  4120. set_history_break();
  4121. /* Update the status bar */
  4122. redraw_statusbar();
  4123. /* Place the terminal cursor again */
  4124. place_cursor_actual();
  4125. }
  4126. }
  4127. BIM_ACTION(cursor_left, 0,
  4128. "Move the cursor one character to the left."
  4129. )(void) {
  4130. if (env->col_no > 1) {
  4131. env->col_no -= 1;
  4132. /* Update the status bar */
  4133. redraw_statusbar();
  4134. /* Place the terminal cursor again */
  4135. place_cursor_actual();
  4136. }
  4137. set_history_break();
  4138. set_preferred_column();
  4139. }
  4140. BIM_ACTION(cursor_right, 0,
  4141. "Move the cursor one character to the right."
  4142. )(void) {
  4143. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  4144. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  4145. env->col_no += 1;
  4146. /* Update the status bar */
  4147. redraw_statusbar();
  4148. /* Place the terminal cursor again */
  4149. place_cursor_actual();
  4150. }
  4151. set_history_break();
  4152. set_preferred_column();
  4153. }
  4154. BIM_ACTION(cursor_home, 0,
  4155. "Move the cursor to the beginning of the line."
  4156. )(void) {
  4157. env->col_no = 1;
  4158. set_history_break();
  4159. set_preferred_column();
  4160. /* Update the status bar */
  4161. redraw_statusbar();
  4162. /* Place the terminal cursor again */
  4163. place_cursor_actual();
  4164. }
  4165. BIM_ACTION(cursor_end, 0,
  4166. "Move the cursor to the end of the line, or past the end in insert mode."
  4167. )(void) {
  4168. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4169. set_history_break();
  4170. set_preferred_column();
  4171. /* Update the status bar */
  4172. redraw_statusbar();
  4173. /* Place the terminal cursor again */
  4174. place_cursor_actual();
  4175. }
  4176. BIM_ACTION(leave_insert, 0,
  4177. "Leave insert modes and return to normal mode."
  4178. )(void) {
  4179. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4180. env->col_no = env->lines[env->line_no-1]->actual;
  4181. if (env->col_no == 0) env->col_no = 1;
  4182. set_preferred_column();
  4183. }
  4184. set_history_break();
  4185. env->mode = MODE_NORMAL;
  4186. redraw_commandline();
  4187. }
  4188. /**
  4189. * Helper for handling smart case sensitivity.
  4190. */
  4191. int search_matches(uint32_t a, uint32_t b, int mode) {
  4192. if (mode == 0) {
  4193. return a == b;
  4194. } else if (mode == 1) {
  4195. return tolower(a) == tolower(b);
  4196. }
  4197. return 0;
  4198. }
  4199. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  4200. int k = j;
  4201. uint32_t * match = needle;
  4202. if (*match == '^') {
  4203. if (j != 0) return 0;
  4204. match++;
  4205. }
  4206. while (k < line->actual + 1) {
  4207. if (*match == '\0') {
  4208. if (len) *len = k - j;
  4209. return 1;
  4210. }
  4211. if (*match == '$') {
  4212. if (k != line->actual) return 0;
  4213. match++;
  4214. continue;
  4215. }
  4216. if (*match == '.') {
  4217. if (match[1] == '*') {
  4218. int greedy = !(match[2] == '?');
  4219. /* Short-circuit chained .*'s */
  4220. if (match[greedy ? 2 : 3] == '.' && match[greedy ? 3 : 4] == '*') {
  4221. int _len;
  4222. if (subsearch_matches(line, k, &match[greedy ? 2 : 3], ignorecase, &_len)) {
  4223. if (len) *len = _len + k - j;
  4224. return 1;
  4225. }
  4226. return 0;
  4227. }
  4228. int _j = greedy ? line->actual : k;
  4229. int _break = -1;
  4230. int _len = -1;
  4231. if (!match[greedy ? 2 : 3]) {
  4232. _len = greedy ? (line->actual - _j) : 0;
  4233. _break = _j;
  4234. } else {
  4235. while (_j < line->actual + 1 && _j >= k) {
  4236. int len;
  4237. if (subsearch_matches(line, _j, &match[greedy ? 2 : 3], ignorecase, &len)) {
  4238. _break = _j;
  4239. _len = len;
  4240. break;
  4241. }
  4242. _j += (greedy ? -1 : 1);
  4243. }
  4244. }
  4245. if (_break != -1) {
  4246. if (len) *len = (_break - j) + _len;
  4247. return 1;
  4248. }
  4249. return 0;
  4250. } else {
  4251. if (k >= line->actual) return 0;
  4252. match++;
  4253. k++;
  4254. continue;
  4255. }
  4256. }
  4257. if (*match == '\\' && (match[1] == '$' || match[1] == '^' || match[1] == '/' || match[1] == '\\' || match[1] == '.')) {
  4258. match++;
  4259. } else if (*match == '\\' && match[1] == 't') {
  4260. if (line->text[k].codepoint != '\t') break;
  4261. match += 2;
  4262. k++;
  4263. continue;
  4264. }
  4265. if (k == line->actual) break;
  4266. if (!search_matches(*match, line->text[k].codepoint, ignorecase)) break;
  4267. match++;
  4268. k++;
  4269. }
  4270. return 0;
  4271. }
  4272. /**
  4273. * Replace text on a given line with other text.
  4274. */
  4275. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4276. line_t * line = env->lines[line_no-1];
  4277. int j = col;
  4278. while (j < line->actual + 1) {
  4279. int match_len;
  4280. if (subsearch_matches(line,j,needle,ignorecase,&match_len)) {
  4281. /* Perform replacement */
  4282. for (int i = 0; i < match_len; ++i) {
  4283. line_delete(line, j+1, line_no-1);
  4284. }
  4285. int t = 0;
  4286. for (uint32_t * r = replacement; *r; ++r) {
  4287. char_t _c;
  4288. _c.codepoint = *r;
  4289. _c.flags = 0;
  4290. _c.display_width = codepoint_width(*r);
  4291. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4292. if (line != nline) {
  4293. env->lines[line_no-1] = nline;
  4294. line = nline;
  4295. }
  4296. t++;
  4297. }
  4298. *out_col = j + t;
  4299. set_modified();
  4300. return;
  4301. }
  4302. j++;
  4303. }
  4304. *out_col = -1;
  4305. }
  4306. #define COMMAND_HISTORY_MAX 255
  4307. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4308. /**
  4309. * Add a command to the history. If that command was
  4310. * already in history, it is moved to the front of the list;
  4311. * otherwise, the whole list is shifted backwards and
  4312. * overflow is freed up.
  4313. */
  4314. void insert_command_history(char * cmd) {
  4315. /* See if this is already in the history. */
  4316. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4317. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4318. if (!strcmp((char*)command_history[i], cmd)) {
  4319. free(command_history[i]);
  4320. amount_to_shift = i;
  4321. break;
  4322. }
  4323. }
  4324. /* Remove last entry that will roll off the stack */
  4325. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4326. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4327. }
  4328. /* Roll the history */
  4329. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4330. command_history[0] = (unsigned char*)strdup(cmd);
  4331. }
  4332. static uint32_t term_colors[] = {
  4333. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  4334. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  4335. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  4336. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  4337. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  4338. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  4339. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  4340. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  4341. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  4342. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  4343. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  4344. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  4345. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  4346. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  4347. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  4348. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  4349. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  4350. 0xeeeeee,
  4351. };
  4352. /**
  4353. * Convert a color setting from terminal format
  4354. * to a hexadecimal color code and add it to the current
  4355. * buffer. This is used for HTML conversion, but could
  4356. * possibly be used for other purposes.
  4357. */
  4358. static void html_convert_color(const char * color_string) {
  4359. char tmp[100];
  4360. if (!strncmp(color_string,"2;",2)) {
  4361. /* 24-bit color */
  4362. int red, green, blue;
  4363. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  4364. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  4365. } else if (!strncmp(color_string,"5;",2)) {
  4366. /* 256 colors; needs lookup table */
  4367. int index;
  4368. sscanf(color_string+2,"%d",&index);
  4369. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  4370. } else {
  4371. /* 16 colors; needs lookup table */
  4372. int index;
  4373. uint32_t color;
  4374. sscanf(color_string+1,"%d",&index);
  4375. if (index >= 10) {
  4376. index -= 10;
  4377. color = term_colors[index+8];
  4378. } else if (index == 9) {
  4379. color = term_colors[0];
  4380. } else {
  4381. color = term_colors[index];
  4382. }
  4383. sprintf(tmp,"#%06x;", (unsigned int)color);
  4384. }
  4385. add_string(tmp);
  4386. char * italic = strstr(color_string,";3");
  4387. if (italic && italic[2] == '\0') {
  4388. add_string(" font-style: oblique;");
  4389. }
  4390. char * bold = strstr(color_string,";1");
  4391. if (bold && bold[2] == '\0') {
  4392. add_string(" font-weight: bold;");
  4393. }
  4394. char * underline = strstr(color_string,";4");
  4395. if (underline && underline[2] == '\0') {
  4396. add_string(" font-decoration: underline;");
  4397. }
  4398. }
  4399. int convert_to_html(void) {
  4400. buffer_t * old = env;
  4401. env = buffer_new();
  4402. setup_buffer(env);
  4403. env->loading = 1;
  4404. add_string("<!doctype html>\n");
  4405. add_string("<html>\n");
  4406. add_string(" <head>\n");
  4407. add_string(" <meta charset=\"UTF-8\">\n");
  4408. if (old->file_name) {
  4409. add_string(" <title>");
  4410. add_string(file_basename(old->file_name));
  4411. add_string("</title>\n");
  4412. }
  4413. add_string(" <style>\n");
  4414. add_string(" body {\n");
  4415. add_string(" margin: 0;\n");
  4416. add_string(" -webkit-text-size-adjust: none;\n");
  4417. add_string(" counter-reset: line-no;\n");
  4418. add_string(" background-color: ");
  4419. /* Convert color */
  4420. html_convert_color(COLOR_BG);
  4421. add_string("\n");
  4422. add_string(" }\n");
  4423. for (int i = 0; i < 15; ++i) {
  4424. /* For each of the relevant flags... */
  4425. char tmp[20];
  4426. sprintf(tmp," .s%d { color: ", i);
  4427. add_string(tmp);
  4428. /* These are special */
  4429. if (i == FLAG_NOTICE) {
  4430. html_convert_color(COLOR_SEARCH_FG);
  4431. add_string(" background-color: ");
  4432. html_convert_color(COLOR_SEARCH_BG);
  4433. } else if (i == FLAG_ERROR) {
  4434. html_convert_color(COLOR_ERROR_FG);
  4435. add_string(" background-color: ");
  4436. html_convert_color(COLOR_ERROR_BG);
  4437. } else {
  4438. html_convert_color(flag_to_color(i));
  4439. }
  4440. add_string("}\n");
  4441. }
  4442. add_string(" pre {\n");
  4443. add_string(" margin: 0;\n");
  4444. add_string(" white-space: pre-wrap;\n");
  4445. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4446. add_string(" font-size: 10pt;\n");
  4447. add_string(" }\n");
  4448. add_string(" pre>span {\n");
  4449. add_string(" display: inline-block;\n");
  4450. add_string(" width: 100%;\n");
  4451. add_string(" }\n");
  4452. add_string(" pre>span>a::before {\n");
  4453. add_string(" counter-increment: line-no;\n");
  4454. add_string(" content: counter(line-no);\n");
  4455. add_string(" padding-right: 1em;\n");
  4456. add_string(" width: 3em;\n");
  4457. add_string(" display: inline-block;\n");
  4458. add_string(" text-align: right;\n");
  4459. add_string(" background-color: ");
  4460. html_convert_color(COLOR_NUMBER_BG);
  4461. add_string("\n");
  4462. add_string(" color: ");
  4463. html_convert_color(COLOR_NUMBER_FG);
  4464. add_string("\n");
  4465. add_string(" }\n");
  4466. add_string(" pre>span:target {\n");
  4467. add_string(" background-color: ");
  4468. html_convert_color(COLOR_ALT_BG);
  4469. add_string("\n");
  4470. add_string(" }\n");
  4471. add_string(" pre>span:target>a::before {\n");
  4472. add_string(" background-color: ");
  4473. html_convert_color(COLOR_NUMBER_FG);
  4474. add_string("\n");
  4475. add_string(" color: ");
  4476. html_convert_color(COLOR_NUMBER_BG);
  4477. add_string("\n");
  4478. add_string(" }\n");
  4479. for (int i = 1; i <= env->tabstop; ++i) {
  4480. char tmp[10];
  4481. sprintf(tmp, ".tab%d", i);
  4482. add_string(" ");
  4483. add_string(tmp);
  4484. add_string(">span {\n");
  4485. add_string(" display: inline-block;\n");
  4486. add_string(" overflow: hidden;\n");
  4487. add_string(" width: 0;\n");
  4488. add_string(" height: 0;\n");
  4489. add_string(" }\n");
  4490. add_string(" ");
  4491. add_string(tmp);
  4492. add_string("::after {\n");
  4493. add_string(" content: '»");
  4494. for (int j = 1; j < i; ++j) {
  4495. add_string("·");
  4496. }
  4497. add_string("';\n");
  4498. add_string(" background-color: ");
  4499. html_convert_color(COLOR_ALT_BG);
  4500. add_string("\n");
  4501. add_string(" color: ");
  4502. html_convert_color(COLOR_ALT_FG);
  4503. add_string("\n");
  4504. add_string(" }\n");
  4505. }
  4506. add_string(" .space {\n");
  4507. add_string(" border-left: 1px solid ");
  4508. html_convert_color(COLOR_ALT_FG);
  4509. add_string("\n");
  4510. add_string(" margin-left: -1px;\n");
  4511. add_string(" }\n");
  4512. add_string(" </style>\n");
  4513. add_string(" </head>\n");
  4514. add_string(" <body><pre>\n");
  4515. for (int i = 0; i < old->line_count; ++i) {
  4516. char tmp[100];
  4517. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4518. add_string(tmp);
  4519. int last_flag = -1;
  4520. int opened = 0;
  4521. int all_spaces = 1;
  4522. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4523. char_t c = old->lines[i]->text[j];
  4524. if (c.codepoint != ' ') all_spaces = 0;
  4525. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4526. if (opened) add_string("</span>");
  4527. opened = 1;
  4528. char tmp[100];
  4529. sprintf(tmp, "<span class=\"s%d\">", c.flags & 0x1F);
  4530. add_string(tmp);
  4531. last_flag = (c.flags & 0x1F);
  4532. }
  4533. if (c.codepoint == '<') {
  4534. add_string("&lt;");
  4535. } else if (c.codepoint == '>') {
  4536. add_string("&gt;");
  4537. } else if (c.codepoint == '&') {
  4538. add_string("&amp;");
  4539. } else if (c.codepoint == '\t') {
  4540. char tmp[100];
  4541. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4542. add_string(tmp);
  4543. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4544. add_string("<span class=\"space\"> </span>");
  4545. } else {
  4546. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4547. to_eight(c.codepoint, tmp);
  4548. add_string(tmp);
  4549. }
  4550. }
  4551. if (opened) {
  4552. add_string("</span>");
  4553. } else {
  4554. add_string("<wbr>");
  4555. }
  4556. add_string("</span>\n");
  4557. }
  4558. add_string("</pre></body>\n");
  4559. add_string("</html>\n");
  4560. env->loading = 0;
  4561. env->modified = 1;
  4562. if (old->file_name) {
  4563. char * base = file_basename(old->file_name);
  4564. char * tmp = malloc(strlen(base) + 5);
  4565. *tmp = '\0';
  4566. strcat(tmp, base);
  4567. strcat(tmp, ".htm");
  4568. env->file_name = tmp;
  4569. }
  4570. for (int i = 0; i < env->line_count; ++i) {
  4571. recalculate_tabs(env->lines[i]);
  4572. }
  4573. env->syntax = match_syntax(".htm");
  4574. for (int i = 0; i < env->line_count; ++i) {
  4575. recalculate_syntax(env->lines[i],i);
  4576. }
  4577. return 0;
  4578. }
  4579. /**
  4580. * Based on vim's :TOhtml
  4581. * Convert syntax-highlighted buffer contents to HTML.
  4582. */
  4583. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  4584. convert_to_html();
  4585. redraw_all();
  4586. return 0;
  4587. }
  4588. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4589. int _prefix_command_run_script(char * cmd) {
  4590. if (env->mode == MODE_LINE_SELECTION) {
  4591. int range_top, range_bot;
  4592. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4593. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4594. int in[2];
  4595. pipe(in);
  4596. int out[2];
  4597. pipe(out);
  4598. int child = fork();
  4599. /* Open child process and set up pipes */
  4600. if (child == 0) {
  4601. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4602. close(out[0]);
  4603. close(in[1]);
  4604. dup2(out[1], STDOUT_FILENO);
  4605. dup2(in[0], STDIN_FILENO);
  4606. dup2(fileno(dev_null), STDERR_FILENO);
  4607. if (*cmd == '!') {
  4608. system(&cmd[1]); /* Yes we can just do this */
  4609. } else {
  4610. char * const args[] = {"python3","-c",&cmd[1],NULL};
  4611. execvp("python3",args);
  4612. }
  4613. exit(1);
  4614. } else if (child < 0) {
  4615. render_error("Failed to fork");
  4616. return 1;
  4617. }
  4618. close(out[1]);
  4619. close(in[0]);
  4620. /* Write lines to child process */
  4621. FILE * f = fdopen(in[1],"w");
  4622. for (int i = range_top; i <= range_bot; ++i) {
  4623. line_t * line = env->lines[i-1];
  4624. for (int j = 0; j < line->actual; j++) {
  4625. char_t c = line->text[j];
  4626. if (c.codepoint == 0) {
  4627. char buf[1] = {0};
  4628. fwrite(buf, 1, 1, f);
  4629. } else {
  4630. char tmp[8] = {0};
  4631. int i = to_eight(c.codepoint, tmp);
  4632. fwrite(tmp, i, 1, f);
  4633. }
  4634. }
  4635. fputc('\n', f);
  4636. }
  4637. fclose(f);
  4638. close(in[1]);
  4639. /* Read results from child process into a new buffer */
  4640. FILE * result = fdopen(out[0],"r");
  4641. buffer_t * old = env;
  4642. env = buffer_new();
  4643. setup_buffer(env);
  4644. env->loading = 1;
  4645. uint8_t buf[BLOCK_SIZE];
  4646. state = 0;
  4647. while (!feof(result) && !ferror(result)) {
  4648. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4649. add_buffer(buf, r);
  4650. }
  4651. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4652. env->lines = remove_line(env->lines, env->line_no-1);
  4653. }
  4654. fclose(result);
  4655. env->loading = 0;
  4656. /* Return to the original buffer and replace the selected lines with the output */
  4657. buffer_t * new = env;
  4658. env = old;
  4659. for (int i = range_top; i <= range_bot; ++i) {
  4660. /* Remove the existing lines */
  4661. env->lines = remove_line(env->lines, range_top-1);
  4662. }
  4663. for (int i = 0; i < new->line_count; ++i) {
  4664. /* Add the new lines */
  4665. env->lines = add_line(env->lines, range_top + i - 1);
  4666. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4667. recalculate_tabs(env->lines[range_top+i-1]);
  4668. }
  4669. env->modified = 1;
  4670. /* Close the temporary buffer */
  4671. buffer_close(new);
  4672. } else {
  4673. /* Reset and draw some line feeds */
  4674. reset();
  4675. printf("\n\n");
  4676. /* Set buffered for shell application */
  4677. set_buffered();
  4678. /* Call the shell and wait for completion */
  4679. if (*cmd == '!') {
  4680. system(&cmd[1]);
  4681. } else {
  4682. setenv("PYCMD",&cmd[1],1);
  4683. system("python3 -c \"$PYCMD\"");
  4684. }
  4685. /* Return to the editor, wait for user to press enter. */
  4686. set_unbuffered();
  4687. printf("\n\nPress ENTER to continue.");
  4688. int c;
  4689. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4690. /* Redraw the screen */
  4691. redraw_all();
  4692. }
  4693. /* Done processing command */
  4694. return 0;
  4695. }
  4696. BIM_PREFIX_COMMAND(bang,"!","Executes shell commands.") {
  4697. (void)argc, (void)argv;
  4698. return _prefix_command_run_script(cmd);
  4699. }
  4700. BIM_PREFIX_COMMAND(tick,"`","Executes Python commands.") {
  4701. (void)argc, (void)argv;
  4702. return _prefix_command_run_script(cmd);
  4703. }
  4704. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4705. char * c = needle;
  4706. char * replacement = NULL;
  4707. char * options = "";
  4708. while (*c) {
  4709. if (*c == divider) {
  4710. *c = '\0';
  4711. replacement = c + 1;
  4712. break;
  4713. }
  4714. c++;
  4715. }
  4716. if (!replacement) {
  4717. render_error("nothing to replace with");
  4718. return 1;
  4719. }
  4720. c = replacement;
  4721. while (*c) {
  4722. if (*c == divider) {
  4723. *c = '\0';
  4724. options = c + 1;
  4725. break;
  4726. }
  4727. c++;
  4728. }
  4729. int global = 0;
  4730. int case_insensitive = 0;
  4731. /* Parse options */
  4732. while (*options) {
  4733. switch (*options) {
  4734. case 'g':
  4735. global = 1;
  4736. break;
  4737. case 'i':
  4738. case_insensitive = 1;
  4739. break;
  4740. }
  4741. options++;
  4742. }
  4743. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4744. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4745. {
  4746. int i = 0;
  4747. uint32_t c, state = 0;
  4748. for (char * cin = needle; *cin; cin++) {
  4749. if (!decode(&state, &c, *cin)) {
  4750. needle_c[i] = c;
  4751. i++;
  4752. } else if (state == UTF8_REJECT) {
  4753. state = 0;
  4754. }
  4755. }
  4756. needle_c[i] = 0;
  4757. i = 0;
  4758. c = 0;
  4759. state = 0;
  4760. for (char * cin = replacement; *cin; cin++) {
  4761. if (!decode(&state, &c, *cin)) {
  4762. replacement_c[i] = c;
  4763. i++;
  4764. } else if (state == UTF8_REJECT) {
  4765. state = 0;
  4766. }
  4767. }
  4768. replacement_c[i] = 0;
  4769. }
  4770. int replacements = 0;
  4771. for (int line = range_top; line <= range_bot; ++line) {
  4772. int col = 0;
  4773. while (col != -1) {
  4774. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4775. if (col != -1) replacements++;
  4776. if (!global) break;
  4777. }
  4778. }
  4779. free(needle_c);
  4780. free(replacement_c);
  4781. if (replacements) {
  4782. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4783. set_history_break();
  4784. redraw_text();
  4785. } else {
  4786. render_error("Pattern not found: %s", needle);
  4787. }
  4788. return 0;
  4789. }
  4790. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4791. int range_top, range_bot;
  4792. if (env->mode == MODE_LINE_SELECTION) {
  4793. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4794. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4795. } else {
  4796. range_top = env->line_no;
  4797. range_bot = env->line_no;
  4798. }
  4799. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4800. }
  4801. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4802. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4803. }
  4804. BIM_COMMAND(e,"e","Open a file") {
  4805. if (argc > 1) {
  4806. /* This actually opens a new tab */
  4807. open_file(argv[1]);
  4808. update_title();
  4809. } else {
  4810. if (env->modified) {
  4811. render_error("File is modified, can not reload.");
  4812. return 1;
  4813. }
  4814. buffer_t * old_env = env;
  4815. open_file(env->file_name);
  4816. buffer_t * new_env = env;
  4817. env = old_env;
  4818. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4819. SWAP(line_t **, env->lines, new_env->lines);
  4820. SWAP(int, env->line_count, new_env->line_count);
  4821. SWAP(int, env->line_avail, new_env->line_avail);
  4822. SWAP(history_t *, env->history, new_env->history);
  4823. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4824. redraw_all();
  4825. }
  4826. return 0;
  4827. }
  4828. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4829. if (argc > 1) {
  4830. open_file(argv[1]);
  4831. update_title();
  4832. } else {
  4833. env = buffer_new();
  4834. setup_buffer(env);
  4835. redraw_all();
  4836. update_title();
  4837. }
  4838. return 0;
  4839. }
  4840. BIM_COMMAND(w,"w","Write a file") {
  4841. /* w: write file */
  4842. if (argc > 1) {
  4843. write_file(argv[1]);
  4844. } else {
  4845. write_file(env->file_name);
  4846. }
  4847. return 0;
  4848. }
  4849. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4850. write_file(env->file_name);
  4851. close_buffer();
  4852. return 0;
  4853. }
  4854. BIM_COMMAND(history,"history","Display command history") {
  4855. render_commandline_message(""); /* To clear command line */
  4856. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4857. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4858. }
  4859. render_commandline_message("\n");
  4860. redraw_tabbar();
  4861. redraw_commandline();
  4862. pause_for_key();
  4863. return 0;
  4864. }
  4865. BIM_COMMAND(q,"q","Close buffer") {
  4866. if (left_buffer && left_buffer == right_buffer) {
  4867. unsplit();
  4868. return 0;
  4869. }
  4870. if (env->modified) {
  4871. render_error("No write since last change. Use :q! to force exit.");
  4872. } else {
  4873. close_buffer();
  4874. }
  4875. update_title();
  4876. return 0;
  4877. }
  4878. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4879. close_buffer();
  4880. update_title();
  4881. return 0;
  4882. }
  4883. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4884. try_quit();
  4885. return 0;
  4886. }
  4887. BIM_ALIAS("qall",qall,qa)
  4888. BIM_COMMAND(qabang,"qa!","Force exit") {
  4889. /* Forcefully exit editor */
  4890. while (buffers_len) {
  4891. buffer_close(buffers[0]);
  4892. }
  4893. quit(NULL);
  4894. return 1; /* doesn't return */
  4895. }
  4896. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4897. previous_tab();
  4898. update_title();
  4899. return 0;
  4900. }
  4901. BIM_COMMAND(tabn,"tabn","Next tab") {
  4902. next_tab();
  4903. update_title();
  4904. return 0;
  4905. }
  4906. BIM_COMMAND(tabindicator,"tabindicator","Set the tab indicator") {
  4907. if (argc < 2) {
  4908. render_status_message("tabindicator=%s", global_config.tab_indicator);
  4909. return 0;
  4910. }
  4911. if (display_width_of_string(argv[1]) != 1) {
  4912. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4913. return 1;
  4914. }
  4915. if (global_config.tab_indicator) free(global_config.tab_indicator);
  4916. global_config.tab_indicator = strdup(argv[1]);
  4917. return 0;
  4918. }
  4919. BIM_COMMAND(spaceindicator,"spaceindicator","Set the space indicator") {
  4920. if (argc < 2) {
  4921. render_status_message("spaceindicator=%s", global_config.space_indicator);
  4922. return 0;
  4923. }
  4924. if (display_width_of_string(argv[1]) != 1) {
  4925. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4926. return 1;
  4927. }
  4928. if (global_config.space_indicator) free(global_config.space_indicator);
  4929. global_config.space_indicator = strdup(argv[1]);
  4930. return 0;
  4931. }
  4932. BIM_COMMAND(global_sgr,"global.sgr_mouse","Enable SGR mouse escapes") {
  4933. if (argc < 2) {
  4934. render_status_message("global.sgr_mouse=%d", global_config.use_sgr_mouse);
  4935. } else {
  4936. if (global_config.has_terminal) mouse_disable();
  4937. global_config.use_sgr_mouse = !!atoi(argv[1]);
  4938. if (global_config.has_terminal) mouse_enable();
  4939. }
  4940. return 0;
  4941. }
  4942. BIM_COMMAND(global_git,"global.git","Show or change the default status of git integration") {
  4943. if (argc < 2) {
  4944. render_status_message("global.git=%d", global_config.check_git);
  4945. } else {
  4946. global_config.check_git = !!atoi(argv[1]);
  4947. }
  4948. return 0;
  4949. }
  4950. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4951. if (!env) {
  4952. render_error("requires environment (did you mean global.git?)");
  4953. return 1;
  4954. }
  4955. if (argc < 2) {
  4956. render_status_message("git=%d", env->checkgitstatusonwrite);
  4957. } else {
  4958. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4959. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4960. git_examine(env->file_name);
  4961. redraw_text();
  4962. }
  4963. }
  4964. return 0;
  4965. }
  4966. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4967. if (argc < 2) {
  4968. render_status_message("colorgutter=%d", global_config.color_gutter);
  4969. } else {
  4970. global_config.color_gutter = !!atoi(argv[1]);
  4971. redraw_text();
  4972. }
  4973. return 0;
  4974. }
  4975. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4976. env->indent = 1;
  4977. redraw_statusbar();
  4978. return 0;
  4979. }
  4980. BIM_COMMAND(noindent,"noindent","Disable smrat indentation") {
  4981. env->indent = 0;
  4982. redraw_statusbar();
  4983. return 0;
  4984. }
  4985. /* TODO: global.maxcolumn */
  4986. BIM_COMMAND(maxcolumn,"maxcolumn","Highlight past the given column to indicate maximum desired line length") {
  4987. if (argc < 2) {
  4988. render_status_message("maxcolumn=%d",env->maxcolumn);
  4989. return 0;
  4990. }
  4991. env->maxcolumn = atoi(argv[1]);
  4992. redraw_text();
  4993. return 0;
  4994. }
  4995. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  4996. render_status_message("cursorcolumn=%d", env->preferred_column);
  4997. return 0;
  4998. }
  4999. BIM_COMMAND(noh,"noh","Clear search term") {
  5000. if (global_config.search) {
  5001. free(global_config.search);
  5002. global_config.search = NULL;
  5003. for (int i = 0; i < env->line_count; ++i) {
  5004. recalculate_syntax(env->lines[i],i);
  5005. }
  5006. redraw_text();
  5007. }
  5008. return 0;
  5009. }
  5010. BIM_COMMAND(help,"help","Show help text.") {
  5011. if (argc < 2) {
  5012. render_commandline_message(""); /* To clear command line */
  5013. render_commandline_message("\n");
  5014. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  5015. render_commandline_message("\n");
  5016. render_commandline_message(" Available commands:\n");
  5017. 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");
  5018. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  5019. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  5020. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  5021. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  5022. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  5023. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  5024. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  5025. render_commandline_message("\n");
  5026. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  5027. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  5028. render_commandline_message("\n");
  5029. } else {
  5030. int found = 0;
  5031. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  5032. if (!strcmp(c->name, argv[1])) {
  5033. render_commandline_message(""); /* To clear command line */
  5034. render_commandline_message("Help description for `%s`:\n", c->name);
  5035. render_commandline_message(" %s\n", c->description);
  5036. found = 1;
  5037. break;
  5038. }
  5039. }
  5040. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  5041. if (!strcmp(c->name, argv[1])) {
  5042. render_commandline_message(""); /* To clear command line */
  5043. render_commandline_message("Help description for `%s`:\n", c->name);
  5044. render_commandline_message(" %s\n", c->description);
  5045. found = 1;
  5046. break;
  5047. }
  5048. }
  5049. if (!found) {
  5050. render_error("Unknown command: %s", argv[1]);
  5051. return 1;
  5052. }
  5053. }
  5054. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  5055. redraw_tabbar();
  5056. redraw_commandline();
  5057. /* Wait for a character so we can redraw the screen before continuing */
  5058. pause_for_key();
  5059. return 0;
  5060. }
  5061. BIM_COMMAND(version,"version","Show version information.") {
  5062. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  5063. return 0;
  5064. }
  5065. void load_colorscheme_script(const char * name) {
  5066. static char name_copy[512];
  5067. char tmp[1024];
  5068. snprintf(tmp, 1023, "theme:%s", name);
  5069. if (!run_function(tmp)) {
  5070. sprintf(name_copy, "%s", name);
  5071. current_theme = name_copy;
  5072. }
  5073. }
  5074. BIM_COMMAND(theme,"theme","Set color theme") {
  5075. if (argc < 2) {
  5076. render_status_message("theme=%s", current_theme);
  5077. } else {
  5078. for (struct theme_def * d = themes; themes && d->name; ++d) {
  5079. if (!strcmp(argv[1], d->name)) {
  5080. d->load(d->name);
  5081. redraw_all();
  5082. return 0;
  5083. }
  5084. }
  5085. }
  5086. return 0;
  5087. }
  5088. BIM_ALIAS("colorscheme",colorscheme,theme)
  5089. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  5090. if (argc < 2) {
  5091. render_status_message("splitpercent=%d", global_config.split_percent);
  5092. return 0;
  5093. } else {
  5094. global_config.split_percent = atoi(argv[1]);
  5095. if (left_buffer) {
  5096. update_split_size();
  5097. redraw_all();
  5098. }
  5099. }
  5100. return 0;
  5101. }
  5102. BIM_COMMAND(split,"split","Split the current view.") {
  5103. buffer_t * original = env;
  5104. if (argc > 1) {
  5105. int is_not_number = 0;
  5106. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  5107. if (is_not_number) {
  5108. /* Open a file for the new split */
  5109. open_file(argv[1]);
  5110. right_buffer = buffers[buffers_len-1];
  5111. } else {
  5112. /* Use an existing buffer for the new split */
  5113. int other = atoi(argv[1]);
  5114. if (other >= buffers_len || other < 0) {
  5115. render_error("Invalid buffer number: %d", other);
  5116. return 1;
  5117. }
  5118. right_buffer = buffers[other];
  5119. }
  5120. } else {
  5121. /* Use the current buffer for the new split */
  5122. right_buffer = original;
  5123. }
  5124. left_buffer = original;
  5125. update_split_size();
  5126. redraw_all();
  5127. return 0;
  5128. }
  5129. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  5130. unsplit();
  5131. return 0;
  5132. }
  5133. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  5134. if (argc < 2) {
  5135. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  5136. return 0;
  5137. } else {
  5138. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  5139. redraw_all();
  5140. }
  5141. return 0;
  5142. }
  5143. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  5144. if (argc < 2) {
  5145. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  5146. } else {
  5147. set_syntax_by_name(argv[1]);
  5148. }
  5149. return 0;
  5150. }
  5151. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  5152. for (int i = 0; i < env->line_count; ++i) {
  5153. env->lines[i]->istate = -1;
  5154. }
  5155. env->loading = 1;
  5156. for (int i = 0; i < env->line_count; ++i) {
  5157. recalculate_syntax(env->lines[i],i);
  5158. }
  5159. env->loading = 0;
  5160. redraw_all();
  5161. return 0;
  5162. }
  5163. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  5164. env->tabs = 1;
  5165. redraw_statusbar();
  5166. return 0;
  5167. }
  5168. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  5169. env->tabs = 0;
  5170. redraw_statusbar();
  5171. return 0;
  5172. }
  5173. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  5174. if (argc < 2) {
  5175. render_status_message("tabstop=%d", env->tabstop);
  5176. } else {
  5177. int t = atoi(argv[1]);
  5178. if (t > 0 && t < 32) {
  5179. env->tabstop = t;
  5180. for (int i = 0; i < env->line_count; ++i) {
  5181. recalculate_tabs(env->lines[i]);
  5182. }
  5183. redraw_all();
  5184. } else {
  5185. render_error("Invalid tabstop: %s", argv[1]);
  5186. }
  5187. }
  5188. return 0;
  5189. }
  5190. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  5191. if (global_config.yanks) {
  5192. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5193. free(global_config.yanks[i]);
  5194. }
  5195. free(global_config.yanks);
  5196. global_config.yanks = NULL;
  5197. global_config.yank_count = 0;
  5198. redraw_statusbar();
  5199. }
  5200. return 0;
  5201. }
  5202. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  5203. if (argc < 2) {
  5204. render_status_message("padding=%d", global_config.cursor_padding);
  5205. } else {
  5206. global_config.cursor_padding = atoi(argv[1]);
  5207. if (env) {
  5208. place_cursor_actual();
  5209. }
  5210. }
  5211. return 0;
  5212. }
  5213. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  5214. if (argc < 2) {
  5215. render_status_message("smartcase=%d", global_config.smart_case);
  5216. } else {
  5217. global_config.smart_case = atoi(argv[1]);
  5218. if (env) place_cursor_actual();
  5219. }
  5220. return 0;
  5221. }
  5222. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  5223. if (argc < 2) {
  5224. render_status_message("hlparen=%d", global_config.highlight_parens);
  5225. } else {
  5226. global_config.highlight_parens = atoi(argv[1]);
  5227. if (env) {
  5228. for (int i = 0; i < env->line_count; ++i) {
  5229. recalculate_syntax(env->lines[i],i);
  5230. }
  5231. redraw_text();
  5232. place_cursor_actual();
  5233. }
  5234. }
  5235. return 0;
  5236. }
  5237. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  5238. if (argc < 2) {
  5239. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  5240. } else {
  5241. global_config.highlight_current_line = atoi(argv[1]);
  5242. if (env) {
  5243. if (!global_config.highlight_current_line) {
  5244. for (int i = 0; i < env->line_count; ++i) {
  5245. env->lines[i]->is_current = 0;
  5246. }
  5247. }
  5248. redraw_text();
  5249. place_cursor_actual();
  5250. }
  5251. }
  5252. return 0;
  5253. }
  5254. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  5255. if (argc < 2) {
  5256. render_status_message("crnl=%d", env->crnl);
  5257. } else {
  5258. env->crnl = !!atoi(argv[1]);
  5259. redraw_statusbar();
  5260. }
  5261. return 0;
  5262. }
  5263. BIM_COMMAND(global_numbers,"global.numbers","Set whether numbers are displayed by default") {
  5264. if (argc < 2) {
  5265. render_status_message("global.numbers=%d", global_config.numbers);
  5266. } else {
  5267. global_config.numbers = !!atoi(argv[1]);
  5268. redraw_all();
  5269. }
  5270. return 0;
  5271. }
  5272. BIM_COMMAND(global_statusbar,"global.statusbar","Show or set whether to display the statusbar") {
  5273. if (argc < 2) {
  5274. render_status_message("global.statusbar=%d",!global_config.hide_statusbar);
  5275. } else {
  5276. global_config.hide_statusbar = !atoi(argv[1]);
  5277. global_config.bottom_size = global_config.hide_statusbar ? 1 : 2;
  5278. redraw_all();
  5279. }
  5280. return 0;
  5281. }
  5282. BIM_COMMAND(global_search_wraps,"wrapsearch","Enable search wrapping around from top or bottom") {
  5283. if (argc < 2) {
  5284. render_status_message("wrapsearch=%d",global_config.search_wraps);
  5285. } else {
  5286. global_config.search_wraps = !!atoi(argv[1]);
  5287. }
  5288. return 0;
  5289. }
  5290. BIM_COMMAND(smartcomplete,"smartcomplete","Enable autocompletion while typing") {
  5291. if (argc < 2) {
  5292. render_status_message("smartcomplete=%d",global_config.smart_complete);
  5293. } else {
  5294. global_config.smart_complete = !!atoi(argv[1]);
  5295. }
  5296. return 0;
  5297. }
  5298. BIM_COMMAND(global_autohide_tabs,"global.autohidetabs","Whether to show the tab bar when there is only one tab") {
  5299. if (argc < 2) {
  5300. render_status_message("global.autohidetabs=%d", global_config.autohide_tabs);
  5301. } else {
  5302. global_config.autohide_tabs = !!atoi(argv[1]);
  5303. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  5304. redraw_all();
  5305. }
  5306. return 0;
  5307. }
  5308. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  5309. if (argc < 2) {
  5310. render_status_message("numbers=%d", env->numbers);
  5311. } else {
  5312. env->numbers = !!atoi(argv[1]);
  5313. redraw_all();
  5314. }
  5315. return 0;
  5316. }
  5317. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  5318. if (argc < 2) {
  5319. render_status_message("relativenumber=%d", global_config.relative_lines);
  5320. } else {
  5321. global_config.relative_lines = atoi(argv[1]);
  5322. if (env) {
  5323. if (!global_config.relative_lines) {
  5324. for (int i = 0; i < env->line_count; ++i) {
  5325. env->lines[i]->is_current = 0;
  5326. }
  5327. }
  5328. redraw_text();
  5329. place_cursor_actual();
  5330. }
  5331. }
  5332. return 0;
  5333. }
  5334. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  5335. for (int i = 0; i < buffers_len; ++i) {
  5336. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  5337. }
  5338. redraw_tabbar();
  5339. redraw_commandline();
  5340. pause_for_key();
  5341. return 0;
  5342. }
  5343. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  5344. int c;
  5345. render_commandline_message("(press a key)");
  5346. while ((c = bim_getkey(200)) == KEY_TIMEOUT);
  5347. render_commandline_message("%d = %s", c, name_from_key(c));
  5348. return 0;
  5349. }
  5350. /**
  5351. * Process a user command.
  5352. */
  5353. int process_command(char * cmd) {
  5354. if (*cmd == '#') return 0;
  5355. /* First, check prefix commands */
  5356. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5357. if (strstr(cmd, c->name) == cmd &&
  5358. (!isalpha(cmd[strlen(c->name)]) || !isalpha(cmd[0]))) {
  5359. return c->command(cmd, 0, NULL);
  5360. }
  5361. }
  5362. char * argv[3] = {NULL, NULL, NULL};
  5363. int argc = !!(*cmd);
  5364. char cmd_name[512] = {0};
  5365. for (char * c = cmd; *c; ++c) {
  5366. if (c-cmd == 511) break;
  5367. if (*c == ' ') {
  5368. cmd_name[c-cmd] = '\0';
  5369. argv[1] = c+1;
  5370. if (*argv[1]) argc++;
  5371. break;
  5372. }
  5373. cmd_name[c-cmd] = *c;
  5374. }
  5375. argv[0] = cmd_name;
  5376. argv[argc] = NULL;
  5377. if (argc < 1) {
  5378. /* no op */
  5379. return 0;
  5380. }
  5381. /* Now check regular commands */
  5382. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5383. if (!strcmp(argv[0], c->name)) {
  5384. return c->command(cmd, argc, argv);
  5385. }
  5386. }
  5387. global_config.break_from_selection = 1;
  5388. if (argv[0][0] == '-' && isdigit(argv[0][1])) {
  5389. goto_line(env->line_no-atoi(&argv[0][1]));
  5390. return 0;
  5391. } else if (argv[0][0] == '+' && isdigit(argv[0][1])) {
  5392. goto_line(env->line_no+atoi(&argv[0][1]));
  5393. return 0;
  5394. } else if (isdigit(*argv[0])) {
  5395. goto_line(atoi(argv[0]));
  5396. return 0;
  5397. } else {
  5398. render_error("Not an editor command: %s", argv[0]);
  5399. return 1;
  5400. }
  5401. }
  5402. /**
  5403. * Wrap strcmp for use with qsort.
  5404. */
  5405. int compare_str(const void * a, const void * b) {
  5406. return strcmp(*(const char **)a, *(const char **)b);
  5407. }
  5408. /**
  5409. * List of file extensions to ignore when tab completing.
  5410. */
  5411. const char * tab_complete_ignore[] = {".o",NULL};
  5412. /**
  5413. * Tab completion for command mode.
  5414. */
  5415. void command_tab_complete(char * buffer) {
  5416. /* Figure out which argument this is and where it starts */
  5417. int arg = 0;
  5418. char * buf = strdup(buffer);
  5419. char * b = buf;
  5420. char * args[32];
  5421. int candidate_count= 0;
  5422. int candidate_space = 4;
  5423. char ** candidates = malloc(sizeof(char*)*candidate_space);
  5424. /* Accept whitespace before first argument */
  5425. while (*b == ' ') b++;
  5426. char * start = b;
  5427. args[0] = start;
  5428. while (*b && *b != ' ') b++;
  5429. while (*b) {
  5430. while (*b == ' ') {
  5431. *b = '\0';
  5432. b++;
  5433. }
  5434. start = b;
  5435. arg++;
  5436. args[arg] = start;
  5437. break;
  5438. }
  5439. /**
  5440. * Check a possible candidate and add it to the
  5441. * candidates list, expanding as necessary,
  5442. * if it matches for the current argument.
  5443. */
  5444. #define add_candidate(candidate) \
  5445. do { \
  5446. char * _arg = args[arg]; \
  5447. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5448. if (!r) { \
  5449. if (candidate_count == candidate_space) { \
  5450. candidate_space *= 2; \
  5451. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  5452. } \
  5453. candidates[candidate_count] = strdup(candidate); \
  5454. candidate_count++; \
  5455. } \
  5456. } while (0)
  5457. int _candidates_are_files = 0;
  5458. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  5459. /* Complete command names */
  5460. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5461. add_candidate(c->name);
  5462. }
  5463. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5464. add_candidate(c->name);
  5465. }
  5466. goto _accept_candidate;
  5467. }
  5468. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5469. /* Complete syntax options */
  5470. add_candidate("none");
  5471. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  5472. add_candidate(s->name);
  5473. }
  5474. goto _accept_candidate;
  5475. }
  5476. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  5477. /* Complete color theme names */
  5478. for (struct theme_def * s = themes; themes && s->name; ++s) {
  5479. add_candidate(s->name);
  5480. }
  5481. goto _accept_candidate;
  5482. }
  5483. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  5484. for (struct ColorName * c = color_names; c->name; ++c) {
  5485. add_candidate(c->name);
  5486. }
  5487. goto _accept_candidate;
  5488. }
  5489. if (arg == 1 && (!strcmp(args[0], "action"))) {
  5490. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5491. add_candidate(a->name);
  5492. }
  5493. goto _accept_candidate;
  5494. }
  5495. if (arg == 1 && (!strcmp(args[0], "call") || !strcmp(args[0], "trycall") || !strcmp(args[0], "showfunction"))) {
  5496. for (int i = 0; i < flex_user_functions_count; ++i) {
  5497. add_candidate(user_functions[i]->command);
  5498. }
  5499. goto _accept_candidate;
  5500. }
  5501. if (arg == 1 && (!strcmp(args[0], "mapkey"))) {
  5502. for (int i = 0; args[arg][i]; ++i) {
  5503. if (args[arg][i] == ' ') {
  5504. while (args[arg][i] == ' ') {
  5505. args[arg][i] = '\0';
  5506. i++;
  5507. }
  5508. start = &args[arg][i];
  5509. arg++;
  5510. args[arg] = start;
  5511. i = 0;
  5512. if (arg == 32) {
  5513. arg = 31;
  5514. break;
  5515. }
  5516. }
  5517. }
  5518. if (arg == 1) {
  5519. for (struct mode_names * m = mode_names; m->name; ++m) {
  5520. add_candidate(m->name);
  5521. }
  5522. } else if (arg == 2) {
  5523. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  5524. add_candidate(KeyNames[i].name);
  5525. }
  5526. } else if (arg == 3) {
  5527. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5528. add_candidate(a->name);
  5529. }
  5530. add_candidate("none");
  5531. } else if (arg == 4) {
  5532. for (char * c = "racnwmb"; *c; ++c) {
  5533. char tmp[] = {*c,'\0'};
  5534. add_candidate(tmp);
  5535. }
  5536. }
  5537. goto _accept_candidate;
  5538. }
  5539. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") ||
  5540. !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") ||
  5541. !strcmp(args[0],"rundir") || args[0][0] == '!')) {
  5542. /* Complete file paths */
  5543. /* First, find the deepest directory match */
  5544. char * tmp = strdup(args[arg]);
  5545. char * last_slash = strrchr(tmp, '/');
  5546. DIR * dirp;
  5547. if (last_slash) {
  5548. *last_slash = '\0';
  5549. if (last_slash == tmp) {
  5550. /* Started with slash, and it was the only slash */
  5551. dirp = opendir("/");
  5552. } else {
  5553. char * home;
  5554. if (*tmp == '~' && (home = getenv("HOME"))) {
  5555. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  5556. sprintf(t, "%s%s",home,tmp+1);
  5557. dirp = opendir(t);
  5558. free(t);
  5559. } else {
  5560. dirp = opendir(tmp);
  5561. }
  5562. }
  5563. } else {
  5564. /* No directory match, completing from current directory */
  5565. dirp = opendir(".");
  5566. tmp[0] = '\0';
  5567. }
  5568. if (!dirp) {
  5569. /* Directory match doesn't exist, no candidates to populate */
  5570. free(tmp);
  5571. goto done;
  5572. }
  5573. _candidates_are_files = 1;
  5574. struct dirent * ent = readdir(dirp);
  5575. while (ent != NULL) {
  5576. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5577. struct stat statbuf;
  5578. /* Figure out if this file is a directory */
  5579. if (last_slash) {
  5580. char * x;
  5581. char * home;
  5582. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  5583. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  5584. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  5585. } else {
  5586. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5587. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5588. }
  5589. stat(x, &statbuf);
  5590. free(x);
  5591. } else {
  5592. stat(ent->d_name, &statbuf);
  5593. }
  5594. /* Build the complete argument name to tab complete */
  5595. char s[1024] = {0};
  5596. if (last_slash == tmp) {
  5597. strcat(s,"/");
  5598. } else if (*tmp) {
  5599. strcat(s,tmp);
  5600. strcat(s,"/");
  5601. }
  5602. strcat(s,ent->d_name);
  5603. /*
  5604. * If it is a directory, add a / to the end so the next completion
  5605. * attempt will complete the directory's contents.
  5606. */
  5607. if (S_ISDIR(statbuf.st_mode)) {
  5608. strcat(s,"/");
  5609. }
  5610. int skip = 0;
  5611. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5612. if (str_ends_with(s, *c)) {
  5613. skip = 1;
  5614. break;
  5615. }
  5616. }
  5617. if (!skip) {
  5618. add_candidate(s);
  5619. }
  5620. }
  5621. ent = readdir(dirp);
  5622. }
  5623. closedir(dirp);
  5624. free(tmp);
  5625. goto _accept_candidate;
  5626. }
  5627. _accept_candidate:
  5628. if (candidate_count == 0) {
  5629. redraw_statusbar();
  5630. goto done;
  5631. }
  5632. if (candidate_count == 1) {
  5633. /* Only one completion possibility */
  5634. redraw_statusbar();
  5635. /* Fill out the rest of the command */
  5636. char * cstart = (buffer) + (start - buf);
  5637. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5638. *cstart = candidates[0][i];
  5639. cstart++;
  5640. }
  5641. *cstart = '\0';
  5642. } else {
  5643. /* Sort candidates */
  5644. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_str);
  5645. /* Print candidates in status bar */
  5646. char * tmp = malloc(global_config.term_width+1);
  5647. memset(tmp, 0, global_config.term_width+1);
  5648. int offset = 0;
  5649. for (int i = 0; i < candidate_count; ++i) {
  5650. char * printed_candidate = candidates[i];
  5651. if (_candidates_are_files) {
  5652. for (char * c = printed_candidate; *c; ++c) {
  5653. if (c[0] == '/' && c[1] != '\0') {
  5654. printed_candidate = c+1;
  5655. }
  5656. }
  5657. }
  5658. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5659. strcat(tmp, "...");
  5660. break;
  5661. }
  5662. if (offset > 0) {
  5663. strcat(tmp, " ");
  5664. offset++;
  5665. }
  5666. strcat(tmp, printed_candidate);
  5667. offset += strlen(printed_candidate);
  5668. }
  5669. render_status_message("%s", tmp);
  5670. free(tmp);
  5671. /* Complete to longest common substring */
  5672. char * cstart = (buffer) + (start - buf);
  5673. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5674. for (int j = 1; j < candidate_count; ++j) {
  5675. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5676. }
  5677. *cstart = candidates[0][i];
  5678. cstart++;
  5679. }
  5680. /* End of longest common substring */
  5681. _reject:
  5682. *cstart = '\0';
  5683. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5684. if (start > buf) { /* Start point needs to be something other than first byte */
  5685. char * tmp = cstart - 1;
  5686. if ((*tmp & 0xC0) == 0x80) {
  5687. /* Count back until we find the start byte and make sure we have the right number */
  5688. int count = 1;
  5689. int x = 0;
  5690. while (tmp >= start) {
  5691. x++;
  5692. tmp--;
  5693. if ((*tmp & 0xC0) == 0x80) {
  5694. count++;
  5695. } else if ((*tmp & 0xC0) == 0xC0) {
  5696. /* How many should we have? */
  5697. int i = 1;
  5698. int j = *tmp;
  5699. while (j & 0x20) {
  5700. i += 1;
  5701. j <<= 1;
  5702. }
  5703. if (count != i) {
  5704. *tmp = '\0';
  5705. break;
  5706. }
  5707. break;
  5708. } else {
  5709. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5710. tmp++;
  5711. *tmp = '\0';
  5712. break;
  5713. }
  5714. }
  5715. } else if ((*tmp & 0xC0) == 0xC0) {
  5716. *tmp = '\0';
  5717. }
  5718. }
  5719. }
  5720. /* Free candidates */
  5721. for (int i = 0; i < candidate_count; ++i) {
  5722. free(candidates[i]);
  5723. }
  5724. done:
  5725. free(candidates);
  5726. free(buf);
  5727. }
  5728. /**
  5729. * Macros for use in command mode.
  5730. */
  5731. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5732. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5733. #define _restore_history(point) do { \
  5734. unsigned char * t = command_history[point]; \
  5735. global_config.command_col_no = 1; \
  5736. global_config.command_buffer->actual = 0; \
  5737. _syn_command(); \
  5738. uint32_t state = 0; \
  5739. uint32_t c = 0; \
  5740. while (*t) { \
  5741. if (!decode(&state, &c, *t)) { \
  5742. char_t _c = {codepoint_width(c), 0, c}; \
  5743. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1); \
  5744. global_config.command_col_no++; \
  5745. } else if (state == UTF8_REJECT) state = 0; \
  5746. t++; \
  5747. } \
  5748. _syn_restore(); \
  5749. } while (0)
  5750. /**
  5751. * Draw the command buffer and any prefix.
  5752. */
  5753. void render_command_input_buffer(void) {
  5754. if (!global_config.command_buffer) return;
  5755. /* Place the cursor at the bottom of the screen */
  5756. place_cursor(1, global_config.term_height);
  5757. paint_line(COLOR_BG);
  5758. set_colors(COLOR_ALT_FG, COLOR_BG);
  5759. /* If there's a mode name to render, draw it first */
  5760. int _left_gutter = 0;
  5761. if (env->mode == MODE_LINE_SELECTION) {
  5762. _left_gutter = printf("(LINE %d:%d)",
  5763. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5764. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5765. } else if (env->mode == MODE_COL_SELECTION) {
  5766. _left_gutter = printf("(COL %d:%d %d)",
  5767. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5768. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5769. (env->sel_col));
  5770. } else if (env->mode == MODE_CHAR_SELECTION) {
  5771. _left_gutter = printf("(CHAR)");
  5772. }
  5773. /* Figure out the cursor position and adjust the offset if necessary */
  5774. int x = 2 + _left_gutter - global_config.command_offset;
  5775. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5776. char_t * c = &global_config.command_buffer->text[i];
  5777. x += c->display_width;
  5778. }
  5779. if (x > global_config.term_width - 1) {
  5780. int diff = x - (global_config.term_width - 1);
  5781. global_config.command_offset += diff;
  5782. x -= diff;
  5783. }
  5784. if (x < 2 + _left_gutter) {
  5785. int diff = (2 + _left_gutter) - x;
  5786. global_config.command_offset -= diff;
  5787. x += diff;
  5788. }
  5789. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5790. if (global_config.command_offset) {
  5791. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5792. printf("<");
  5793. } else {
  5794. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5795. set_colors(COLOR_FG, COLOR_BG);
  5796. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5797. printf(global_config.search_direction == 0 ? "?" : "/");
  5798. } else {
  5799. printf(":");
  5800. }
  5801. }
  5802. /* Render the buffer */
  5803. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5804. /* Place and display the cursor */
  5805. place_cursor(x, global_config.term_height);
  5806. show_cursor();
  5807. }
  5808. BIM_ACTION(command_discard, 0,
  5809. "Discard the input buffer and cancel command or search."
  5810. )(void) {
  5811. free(global_config.command_buffer);
  5812. global_config.command_buffer = NULL;
  5813. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5814. env->line_no = global_config.prev_line;
  5815. env->col_no = global_config.prev_col;
  5816. /* Unhighlight search matches */
  5817. for (int i = 0; i < env->line_count; ++i) {
  5818. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5819. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5820. }
  5821. rehighlight_search(env->lines[i]);
  5822. }
  5823. }
  5824. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5825. redraw_all();
  5826. /* TODO exit some other modes? */
  5827. }
  5828. BIM_ACTION(enter_command, 0,
  5829. "Enter command input mode."
  5830. )(void) {
  5831. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  5832. global_config.command_offset = 0;
  5833. global_config.command_col_no = 1;
  5834. if (global_config.command_buffer) {
  5835. free(global_config.command_buffer);
  5836. }
  5837. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5838. global_config.command_buffer->available = 32;
  5839. global_config.command_syn_back = env->syntax;
  5840. global_config.command_syn = find_syntax_calculator("bimcmd");
  5841. global_config.history_point = -1;
  5842. render_command_input_buffer();
  5843. }
  5844. BIM_ACTION(command_accept, 0,
  5845. "Accept the command input and run the requested command."
  5846. )(void) {
  5847. /* Convert command buffer to UTF-8 char-array string */
  5848. size_t size = 0;
  5849. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5850. char tmp[8] = {0};
  5851. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  5852. }
  5853. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  5854. char * t = tmp;
  5855. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5856. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5857. }
  5858. *t = '\0';
  5859. /* Free the original editing buffer */
  5860. free(global_config.command_buffer);
  5861. global_config.command_buffer = NULL;
  5862. /* Run the converted command */
  5863. global_config.break_from_selection = 0;
  5864. insert_command_history(tmp);
  5865. process_command(tmp);
  5866. free(tmp);
  5867. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  5868. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  5869. recalculate_selected_lines();
  5870. }
  5871. env->mode = MODE_NORMAL;
  5872. }
  5873. /* Leave command mode */
  5874. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5875. }
  5876. BIM_ACTION(command_word_delete, 0,
  5877. "Delete the previous word from the input buffer."
  5878. )(void) {
  5879. _syn_command();
  5880. while (global_config.command_col_no > 1 &&
  5881. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  5882. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  5883. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5884. global_config.command_col_no--;
  5885. }
  5886. while (global_config.command_col_no > 1 &&
  5887. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  5888. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  5889. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5890. global_config.command_col_no--;
  5891. }
  5892. _syn_restore();
  5893. }
  5894. BIM_ACTION(command_tab_complete_buffer, 0,
  5895. "Complete command names and arguments in the input buffer."
  5896. )(void) {
  5897. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  5898. char * tmp = calloc(1024,1);
  5899. char * t = tmp;
  5900. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  5901. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5902. }
  5903. *t = '\0';
  5904. _syn_command();
  5905. while (global_config.command_col_no > 1) {
  5906. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5907. global_config.command_col_no--;
  5908. }
  5909. _syn_restore();
  5910. command_tab_complete(tmp);
  5911. _syn_command();
  5912. uint32_t state = 0, c= 0;
  5913. t = tmp;
  5914. while (*t) {
  5915. if (!decode(&state, &c, *t)) {
  5916. char_t _c = {codepoint_width(c), 0, c};
  5917. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5918. global_config.command_col_no++;
  5919. }
  5920. t++;
  5921. }
  5922. _syn_restore();
  5923. free(tmp);
  5924. }
  5925. BIM_ACTION(command_backspace, 0,
  5926. "Erase the character before the cursor in the input buffer."
  5927. )(void) {
  5928. if (global_config.command_col_no <= 1) {
  5929. if (global_config.command_buffer->actual == 0) {
  5930. command_discard();
  5931. }
  5932. return;
  5933. }
  5934. _syn_command();
  5935. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5936. _syn_restore();
  5937. global_config.command_col_no--;
  5938. global_config.command_offset = 0;
  5939. }
  5940. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  5941. "Scroll through command input history."
  5942. )(int direction) {
  5943. if (direction == -1) {
  5944. if (command_history[global_config.history_point+1]) {
  5945. _restore_history(global_config.history_point+1);
  5946. global_config.history_point++;
  5947. }
  5948. } else {
  5949. if (global_config.history_point > 0) {
  5950. global_config.history_point--;
  5951. _restore_history(global_config.history_point);
  5952. } else {
  5953. global_config.history_point = -1;
  5954. global_config.command_col_no = 1;
  5955. global_config.command_buffer->actual = 0;
  5956. }
  5957. }
  5958. }
  5959. BIM_ACTION(command_word_left, 0,
  5960. "Move to the start of the previous word in the input buffer."
  5961. )(void) {
  5962. if (global_config.command_col_no > 1) {
  5963. do {
  5964. global_config.command_col_no--;
  5965. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5966. if (global_config.command_col_no == 1) return;
  5967. do {
  5968. global_config.command_col_no--;
  5969. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5970. if (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no < global_config.command_buffer->actual) global_config.command_col_no++;
  5971. }
  5972. }
  5973. BIM_ACTION(command_word_right, 0,
  5974. "Move to the start of the next word in the input buffer."
  5975. )(void) {
  5976. if (global_config.command_col_no < global_config.command_buffer->actual) {
  5977. do {
  5978. global_config.command_col_no++;
  5979. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5980. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5981. do {
  5982. global_config.command_col_no++;
  5983. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5984. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5985. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  5986. }
  5987. }
  5988. BIM_ACTION(command_cursor_left, 0,
  5989. "Move the cursor one character left in the input buffer."
  5990. )(void) {
  5991. if (global_config.command_col_no > 1) global_config.command_col_no--;
  5992. }
  5993. BIM_ACTION(command_cursor_right, 0,
  5994. "Move the cursor one character right in the input buffer."
  5995. )(void) {
  5996. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  5997. }
  5998. BIM_ACTION(command_cursor_home, 0,
  5999. "Move the cursor to the start of the input buffer."
  6000. )(void) {
  6001. global_config.command_col_no = 1;
  6002. }
  6003. BIM_ACTION(command_cursor_end, 0,
  6004. "Move the cursor to the end of the input buffer."
  6005. )(void) {
  6006. global_config.command_col_no = global_config.command_buffer->actual + 1;
  6007. }
  6008. BIM_ACTION(eat_mouse, 0,
  6009. "(temporary) Read, but ignore mouse input."
  6010. )(void) {
  6011. bim_getch();
  6012. bim_getch();
  6013. bim_getch();
  6014. }
  6015. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  6016. "Insert one character into the input buffer."
  6017. )(int c) {
  6018. char_t _c = {codepoint_width(c), 0, c};
  6019. _syn_command();
  6020. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  6021. _syn_restore();
  6022. global_config.command_col_no++;
  6023. }
  6024. /**
  6025. * Determine whether a string should be searched
  6026. * case-sensitive or not based on whether it contains
  6027. * any upper-case letters.
  6028. */
  6029. int smart_case(uint32_t * str) {
  6030. if (!global_config.smart_case) return 0;
  6031. for (uint32_t * s = str; *s; ++s) {
  6032. if (tolower(*s) != (int)*s) {
  6033. return 0;
  6034. }
  6035. }
  6036. return 1;
  6037. }
  6038. /**
  6039. * Search forward from the given cursor position
  6040. * to find a basic search match.
  6041. *
  6042. * This could be more complicated...
  6043. */
  6044. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  6045. int col = from_col;
  6046. int ignorecase = smart_case(str);
  6047. for (int i = from_line; i <= env->line_count; ++i) {
  6048. line_t * line = env->lines[i - 1];
  6049. int j = col - 1;
  6050. while (j < line->actual + 1) {
  6051. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  6052. *out_line = i;
  6053. *out_col = j + 1;
  6054. return;
  6055. }
  6056. j++;
  6057. }
  6058. col = 0;
  6059. }
  6060. }
  6061. /**
  6062. * Search backwards for matching string.
  6063. */
  6064. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  6065. int col = from_col;
  6066. int ignorecase = smart_case(str);
  6067. for (int i = from_line; i >= 1; --i) {
  6068. line_t * line = env->lines[i-1];
  6069. int j = col - 1;
  6070. while (j > -1) {
  6071. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  6072. *out_line = i;
  6073. *out_col = j + 1;
  6074. return;
  6075. }
  6076. j--;
  6077. }
  6078. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  6079. }
  6080. }
  6081. /**
  6082. * Re-mark search matches while editing text.
  6083. * This gets called after recalculate_syntax, so it works as we're typing or
  6084. * whenever syntax calculation would redraw other lines.
  6085. * XXX There's a bunch of code duplication between the (now three) search match functions.
  6086. * and search should be improved to support regex anyway, so this needs to be fixed.
  6087. */
  6088. void rehighlight_search(line_t * line) {
  6089. if (!global_config.search) return;
  6090. int j = 0;
  6091. int ignorecase = smart_case(global_config.search);
  6092. while (j < line->actual) {
  6093. int matchlen = 0;
  6094. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  6095. for (int i = j; matchlen > 0; ++i, matchlen--) {
  6096. line->text[i].flags |= FLAG_SEARCH;
  6097. }
  6098. }
  6099. j++;
  6100. }
  6101. }
  6102. /**
  6103. * Draw the matched search result.
  6104. */
  6105. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  6106. for (int i = 0; i < env->line_count; ++i) {
  6107. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6108. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6109. }
  6110. }
  6111. int line = -1, col = -1, _line = 1, _col = 1;
  6112. do {
  6113. int matchlen;
  6114. find_match(_line, _col, &line, &col, buffer, &matchlen);
  6115. if (line != -1) {
  6116. line_t * l = env->lines[line-1];
  6117. for (int i = col; matchlen > 0; ++i, --matchlen) {
  6118. l->text[i-1].flags |= FLAG_SEARCH;
  6119. }
  6120. }
  6121. _line = line;
  6122. _col = col+1;
  6123. line = -1;
  6124. col = -1;
  6125. } while (_line != -1);
  6126. redraw_text();
  6127. place_cursor_actual();
  6128. redraw_statusbar();
  6129. redraw_commandline();
  6130. if (redraw_buffer != -1) {
  6131. printf(redraw_buffer == 1 ? "/" : "?");
  6132. uint32_t * c = buffer;
  6133. while (*c) {
  6134. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  6135. to_eight(*c, tmp);
  6136. printf("%s", tmp);
  6137. c++;
  6138. }
  6139. }
  6140. }
  6141. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  6142. "Enter search mode."
  6143. )(int direction) {
  6144. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  6145. global_config.command_offset = 0;
  6146. global_config.command_col_no = 1;
  6147. global_config.prev_line = env->line_no;
  6148. global_config.prev_col = env->col_no;
  6149. global_config.prev_coffset = env->coffset;
  6150. global_config.prev_offset = env->offset;
  6151. global_config.search_direction = direction;
  6152. if (global_config.command_buffer) {
  6153. free(global_config.command_buffer);
  6154. }
  6155. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6156. global_config.command_buffer->available = 32;
  6157. global_config.command_syn_back = env->syntax;
  6158. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  6159. render_command_input_buffer();
  6160. }
  6161. BIM_ACTION(search_accept, 0,
  6162. "Accept the search term and return to the previous mode."
  6163. )(void) {
  6164. /* Store the accepted search */
  6165. if (!global_config.command_buffer->actual) {
  6166. if (global_config.search) {
  6167. search_next();
  6168. }
  6169. goto _finish;
  6170. }
  6171. if (global_config.search) {
  6172. free(global_config.search);
  6173. }
  6174. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  6175. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6176. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  6177. }
  6178. global_config.search[global_config.command_buffer->actual] = 0;
  6179. _finish:
  6180. /* Free the original editing buffer */
  6181. free(global_config.command_buffer);
  6182. global_config.command_buffer = NULL;
  6183. /* Leave command mode */
  6184. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6185. }
  6186. /**
  6187. * Find the next search result, or loop back around if at the end.
  6188. */
  6189. BIM_ACTION(search_next, 0,
  6190. "Jump to the next search match."
  6191. )(void) {
  6192. if (!global_config.search) return;
  6193. if (env->coffset) env->coffset = 0;
  6194. int line = -1, col = -1;
  6195. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  6196. if (line == -1) {
  6197. if (!global_config.search_wraps) return;
  6198. find_match(1,1, &line, &col, global_config.search, NULL);
  6199. if (line == -1) return;
  6200. }
  6201. env->col_no = col;
  6202. env->line_no = line;
  6203. set_preferred_column();
  6204. draw_search_match(global_config.search, -1);
  6205. }
  6206. /**
  6207. * Find the previous search result, or loop to the end of the file.
  6208. */
  6209. BIM_ACTION(search_prev, 0,
  6210. "Jump to the preceding search match."
  6211. )(void) {
  6212. if (!global_config.search) return;
  6213. if (env->coffset) env->coffset = 0;
  6214. int line = -1, col = -1;
  6215. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  6216. if (line == -1) {
  6217. if (!global_config.search_wraps) return;
  6218. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  6219. if (line == -1) return;
  6220. }
  6221. env->col_no = col;
  6222. env->line_no = line;
  6223. set_preferred_column();
  6224. draw_search_match(global_config.search, -1);
  6225. }
  6226. /**
  6227. * Find the matching paren for this one.
  6228. *
  6229. * This approach skips having to do its own syntax parsing
  6230. * to deal with, eg., erroneous parens in comments. It does
  6231. * this by finding the matching paren with the same flag
  6232. * value, thus parens in strings will match, parens outside
  6233. * of strings will match, but parens in strings won't
  6234. * match parens outside of strings and so on.
  6235. */
  6236. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  6237. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  6238. return; /* Invalid cursor position */
  6239. }
  6240. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  6241. int paren_match = 0;
  6242. int direction = 0;
  6243. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  6244. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  6245. int count = 0;
  6246. /* TODO what about unicode parens? */
  6247. for (int i = 0; paren_pairs[i]; ++i) {
  6248. if (start == paren_pairs[i]) {
  6249. direction = (i % 2 == 0) ? 1 : -1;
  6250. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  6251. break;
  6252. }
  6253. }
  6254. if (!paren_match) return;
  6255. /* Scan for match */
  6256. int line = env->line_no;
  6257. int col = env->col_no - in_col + 1;
  6258. do {
  6259. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  6260. /* Only match on same syntax */
  6261. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  6262. /* Count up on same direction */
  6263. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  6264. /* Count down on opposite direction */
  6265. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  6266. count--;
  6267. /* When count == 0 we have a match */
  6268. if (count == 0) goto _match_found;
  6269. }
  6270. }
  6271. col += direction;
  6272. }
  6273. line += direction;
  6274. /* Reached first/last line with no match */
  6275. if (line == 0 || line == env->line_count + 1) {
  6276. return;
  6277. }
  6278. /* Reset column to start/end of line, depending on direction */
  6279. if (direction > 0) {
  6280. col = 1;
  6281. } else {
  6282. col = env->lines[line-1]->actual;
  6283. }
  6284. } while (1);
  6285. _match_found:
  6286. *out_line = line;
  6287. *out_col = col;
  6288. }
  6289. /**
  6290. * Switch to the left split view
  6291. * (Primarily to handle cases where the left and right are the same buffer)
  6292. */
  6293. BIM_ACTION(use_left_buffer, 0,
  6294. "Switch to the left split view."
  6295. )(void) {
  6296. if (left_buffer == right_buffer && env->left != 0) {
  6297. view_right_offset = env->offset;
  6298. env->width = env->left;
  6299. env->left = 0;
  6300. env->offset = view_left_offset;
  6301. }
  6302. env = left_buffer;
  6303. update_title();
  6304. }
  6305. /**
  6306. * Switch to the right split view
  6307. * (Primarily to handle cases where the left and right are the same buffer)
  6308. */
  6309. BIM_ACTION(use_right_buffer, 0,
  6310. "Switch to the right split view."
  6311. )(void) {
  6312. if (left_buffer == right_buffer && env->left == 0) {
  6313. view_left_offset = env->offset;
  6314. env->left = env->width;
  6315. env->width = global_config.term_width - env->width;
  6316. env->offset = view_right_offset;
  6317. }
  6318. env = right_buffer;
  6319. update_title();
  6320. }
  6321. void handle_common_mouse(int buttons, int x, int y) {
  6322. if (buttons == 64) {
  6323. /* Scroll up */
  6324. if (global_config.shift_scrolling) {
  6325. env->loading = 1;
  6326. int shifted = 0;
  6327. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6328. if (env->offset > 0) {
  6329. env->offset--;
  6330. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  6331. cursor_up();
  6332. }
  6333. shifted++;
  6334. }
  6335. }
  6336. env->loading = 0;
  6337. if (!shifted) return;
  6338. if (global_config.can_scroll && !left_buffer) {
  6339. if (!global_config.can_insert) {
  6340. shift_down(shifted);
  6341. redraw_tabbar();
  6342. } else {
  6343. insert_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6344. }
  6345. for (int i = 0; i < shifted; ++i) {
  6346. redraw_line(env->offset+i);
  6347. }
  6348. } else {
  6349. redraw_tabbar();
  6350. redraw_text();
  6351. }
  6352. redraw_statusbar();
  6353. redraw_commandline();
  6354. place_cursor_actual();
  6355. } else {
  6356. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6357. cursor_up();
  6358. }
  6359. }
  6360. return;
  6361. } else if (buttons == 65) {
  6362. /* Scroll down */
  6363. if (global_config.shift_scrolling) {
  6364. env->loading = 1;
  6365. int shifted = 0;
  6366. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6367. if (env->offset < env->line_count-1) {
  6368. env->offset++;
  6369. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  6370. if (env->line_no <= e) {
  6371. cursor_down();
  6372. }
  6373. shifted++;
  6374. }
  6375. }
  6376. env->loading = 0;
  6377. if (!shifted) return;
  6378. if (global_config.can_scroll && !left_buffer) {
  6379. if (!global_config.can_insert) {
  6380. shift_up(shifted);
  6381. redraw_tabbar();
  6382. } else {
  6383. delete_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6384. }
  6385. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  6386. for (int i = 0; i < shifted; ++i) {
  6387. if (env->offset + l - i < env->line_count + 1) {
  6388. redraw_line(env->offset + l-1-i);
  6389. } else {
  6390. draw_excess_line(l - 1 - i);
  6391. }
  6392. }
  6393. } else {
  6394. redraw_tabbar();
  6395. redraw_text();
  6396. }
  6397. redraw_statusbar();
  6398. redraw_commandline();
  6399. place_cursor_actual();
  6400. } else {
  6401. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6402. cursor_down();
  6403. }
  6404. }
  6405. return;
  6406. } else if (buttons == 3) {
  6407. /* Move cursor to position */
  6408. if (x < 0) return;
  6409. if (y < 0) return;
  6410. if (y == 1 && global_config.tabs_visible) {
  6411. /* Pick from tabs */
  6412. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  6413. int _x = 0;
  6414. if (global_config.tab_offset) _x = 1;
  6415. if (global_config.tab_offset && _x >= x) {
  6416. global_config.tab_offset--;
  6417. redraw_tabbar();
  6418. return;
  6419. }
  6420. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6421. buffer_t * _env = buffers[i];
  6422. char tmp[64];
  6423. int size = 0;
  6424. int filled = draw_tab_name(_env, tmp, global_config.term_width - _x, &size);
  6425. _x += size;
  6426. if (_x >= x) {
  6427. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  6428. env = buffers[i];
  6429. redraw_all();
  6430. update_title();
  6431. return;
  6432. }
  6433. if (filled) break;
  6434. }
  6435. if (x > _x && global_config.tab_offset < buffers_len - 1) {
  6436. global_config.tab_offset++;
  6437. redraw_tabbar();
  6438. }
  6439. return;
  6440. }
  6441. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  6442. int current_mode = env->mode;
  6443. if (x < env->left && env == right_buffer) {
  6444. use_left_buffer();
  6445. } else if (x > env->width && env == left_buffer) {
  6446. use_right_buffer();
  6447. }
  6448. env->mode = current_mode;
  6449. redraw_all();
  6450. }
  6451. if (env->left) {
  6452. x -= env->left;
  6453. }
  6454. /* Figure out y coordinate */
  6455. int line_no = y + env->offset - global_config.tabs_visible;
  6456. int col_no = -1;
  6457. if (line_no > env->line_count) {
  6458. line_no = env->line_count;
  6459. }
  6460. if (line_no != env->line_no) {
  6461. env->coffset = 0;
  6462. }
  6463. /* Account for the left hand gutter */
  6464. int num_size = num_width() + gutter_width();
  6465. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  6466. /* Determine where the cursor is physically */
  6467. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  6468. char_t * c = &env->lines[line_no-1]->text[i];
  6469. _x += c->display_width;
  6470. if (_x > x-1) {
  6471. col_no = i+1;
  6472. break;
  6473. }
  6474. }
  6475. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  6476. col_no = env->lines[line_no-1]->actual;
  6477. }
  6478. env->line_no = line_no;
  6479. env->col_no = col_no;
  6480. set_history_break();
  6481. set_preferred_column();
  6482. redraw_statusbar();
  6483. place_cursor_actual();
  6484. }
  6485. return;
  6486. }
  6487. /**
  6488. * Handle mouse event
  6489. */
  6490. BIM_ACTION(handle_mouse, 0,
  6491. "Process mouse actions."
  6492. )(void) {
  6493. int buttons = bim_getch() - 32;
  6494. int x = bim_getch() - 32;
  6495. int y = bim_getch() - 32;
  6496. handle_common_mouse(buttons, x, y);
  6497. }
  6498. BIM_ACTION(handle_mouse_sgr, 0,
  6499. "Process SGR-style mouse actions."
  6500. )(void) {
  6501. int values[3] = {0};
  6502. char tmp[512] = {0};
  6503. char * c = tmp;
  6504. int buttons = 0;
  6505. do {
  6506. int _c = bim_getch();
  6507. if (_c == -1) {
  6508. break;
  6509. }
  6510. if (_c == 'm') {
  6511. buttons = 3;
  6512. break;
  6513. } else if (_c == 'M') {
  6514. buttons = 0;
  6515. break;
  6516. }
  6517. *c = _c;
  6518. ++c;
  6519. } while (1);
  6520. char * j = tmp;
  6521. char * last = tmp;
  6522. int i = 0;
  6523. while (*j) {
  6524. if (*j == ';') {
  6525. *j = '\0';
  6526. values[i] = atoi(last);
  6527. last = j+1;
  6528. i++;
  6529. if (i == 3) break;
  6530. }
  6531. j++;
  6532. }
  6533. if (last && i < 3) values[i] = atoi(last);
  6534. if (buttons != 3) {
  6535. buttons = values[0];
  6536. }
  6537. int x = values[1];
  6538. int y = values[2];
  6539. handle_common_mouse(buttons, x, y);
  6540. }
  6541. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  6542. "Insert one character."
  6543. )(unsigned int c) {
  6544. if (!c) {
  6545. render_error("Inserted nil byte?");
  6546. return;
  6547. }
  6548. char_t _c;
  6549. _c.codepoint = c;
  6550. _c.flags = 0;
  6551. _c.display_width = codepoint_width(c);
  6552. line_t * line = env->lines[env->line_no - 1];
  6553. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6554. if (line != nline) {
  6555. env->lines[env->line_no - 1] = nline;
  6556. }
  6557. env->col_no += 1;
  6558. set_preferred_column();
  6559. set_modified();
  6560. }
  6561. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  6562. "Replace a single character."
  6563. )(unsigned int c) {
  6564. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6565. if (c >= KEY_ESCAPE) {
  6566. render_error("Invalid key for replacement");
  6567. return;
  6568. }
  6569. char_t _c;
  6570. _c.codepoint = c;
  6571. _c.flags = 0;
  6572. _c.display_width = codepoint_width(c);
  6573. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6574. redraw_line(env->line_no-1);
  6575. set_modified();
  6576. }
  6577. BIM_ACTION(undo_history, ACTION_IS_RW,
  6578. "Undo history until the last breakpoint."
  6579. )(void) {
  6580. if (!global_config.history_enabled) return;
  6581. env->loading = 1;
  6582. history_t * e = env->history;
  6583. if (e->type == HISTORY_SENTINEL) {
  6584. env->loading = 0;
  6585. render_commandline_message("Already at oldest change");
  6586. return;
  6587. }
  6588. int count_chars = 0;
  6589. int count_lines = 0;
  6590. do {
  6591. if (e->type == HISTORY_SENTINEL) break;
  6592. switch (e->type) {
  6593. case HISTORY_INSERT:
  6594. /* Delete */
  6595. line_delete(
  6596. env->lines[e->contents.insert_delete_replace.lineno],
  6597. e->contents.insert_delete_replace.offset+1,
  6598. e->contents.insert_delete_replace.lineno
  6599. );
  6600. count_chars++;
  6601. break;
  6602. case HISTORY_DELETE:
  6603. {
  6604. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6605. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6606. env->lines[e->contents.insert_delete_replace.lineno],
  6607. _c,
  6608. e->contents.insert_delete_replace.offset-1,
  6609. e->contents.insert_delete_replace.lineno
  6610. );
  6611. }
  6612. count_chars++;
  6613. break;
  6614. case HISTORY_REPLACE:
  6615. {
  6616. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6617. line_replace(
  6618. env->lines[e->contents.insert_delete_replace.lineno],
  6619. _o,
  6620. e->contents.insert_delete_replace.offset,
  6621. e->contents.insert_delete_replace.lineno
  6622. );
  6623. }
  6624. count_chars++;
  6625. break;
  6626. case HISTORY_REMOVE_LINE:
  6627. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6628. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6629. count_lines++;
  6630. break;
  6631. case HISTORY_ADD_LINE:
  6632. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6633. count_lines++;
  6634. break;
  6635. case HISTORY_REPLACE_LINE:
  6636. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6637. count_lines++;
  6638. break;
  6639. case HISTORY_SPLIT_LINE:
  6640. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6641. count_lines++;
  6642. break;
  6643. case HISTORY_MERGE_LINES:
  6644. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6645. count_lines++;
  6646. break;
  6647. case HISTORY_BREAK:
  6648. /* Ignore break */
  6649. break;
  6650. default:
  6651. render_error("Unknown type %d!\n", e->type);
  6652. break;
  6653. }
  6654. env->line_no = env->history->line;
  6655. env->col_no = env->history->col;
  6656. env->history = e->previous;
  6657. e = env->history;
  6658. } while (e->type != HISTORY_BREAK);
  6659. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6660. if (env->line_no < 1) env->line_no = 1;
  6661. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6662. if (env->col_no < 1) env->col_no = 1;
  6663. env->modified = (env->history != env->last_save_history);
  6664. env->loading = 0;
  6665. for (int i = 0; i < env->line_count; ++i) {
  6666. env->lines[i]->istate = 0;
  6667. recalculate_tabs(env->lines[i]);
  6668. }
  6669. for (int i = 0; i < env->line_count; ++i) {
  6670. recalculate_syntax(env->lines[i],i);
  6671. }
  6672. place_cursor_actual();
  6673. update_title();
  6674. redraw_all();
  6675. render_commandline_message("%d character%s, %d line%s changed",
  6676. count_chars, (count_chars == 1) ? "" : "s",
  6677. count_lines, (count_lines == 1) ? "" : "s");
  6678. }
  6679. BIM_ACTION(redo_history, ACTION_IS_RW,
  6680. "Redo history until the next breakpoint."
  6681. )(void) {
  6682. if (!global_config.history_enabled) return;
  6683. env->loading = 1;
  6684. history_t * e = env->history->next;
  6685. if (!e) {
  6686. env->loading = 0;
  6687. render_commandline_message("Already at newest change");
  6688. return;
  6689. }
  6690. int count_chars = 0;
  6691. int count_lines = 0;
  6692. while (e) {
  6693. if (e->type == HISTORY_BREAK) {
  6694. env->history = e;
  6695. break;
  6696. }
  6697. switch (e->type) {
  6698. case HISTORY_INSERT:
  6699. {
  6700. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6701. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6702. env->lines[e->contents.insert_delete_replace.lineno],
  6703. _c,
  6704. e->contents.insert_delete_replace.offset,
  6705. e->contents.insert_delete_replace.lineno
  6706. );
  6707. }
  6708. count_chars++;
  6709. break;
  6710. case HISTORY_DELETE:
  6711. /* Delete */
  6712. line_delete(
  6713. env->lines[e->contents.insert_delete_replace.lineno],
  6714. e->contents.insert_delete_replace.offset,
  6715. e->contents.insert_delete_replace.lineno
  6716. );
  6717. count_chars++;
  6718. break;
  6719. case HISTORY_REPLACE:
  6720. {
  6721. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6722. line_replace(
  6723. env->lines[e->contents.insert_delete_replace.lineno],
  6724. _o,
  6725. e->contents.insert_delete_replace.offset,
  6726. e->contents.insert_delete_replace.lineno
  6727. );
  6728. }
  6729. count_chars++;
  6730. break;
  6731. case HISTORY_ADD_LINE:
  6732. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6733. count_lines++;
  6734. break;
  6735. case HISTORY_REMOVE_LINE:
  6736. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6737. count_lines++;
  6738. break;
  6739. case HISTORY_REPLACE_LINE:
  6740. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6741. count_lines++;
  6742. break;
  6743. case HISTORY_MERGE_LINES:
  6744. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6745. count_lines++;
  6746. break;
  6747. case HISTORY_SPLIT_LINE:
  6748. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6749. count_lines++;
  6750. break;
  6751. case HISTORY_BREAK:
  6752. /* Ignore break */
  6753. break;
  6754. default:
  6755. render_error("Unknown type %d!\n", e->type);
  6756. break;
  6757. }
  6758. env->history = e;
  6759. e = e->next;
  6760. }
  6761. env->line_no = env->history->line;
  6762. env->col_no = env->history->col;
  6763. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6764. if (env->line_no < 1) env->line_no = 1;
  6765. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6766. if (env->col_no < 1) env->col_no = 1;
  6767. env->modified = (env->history != env->last_save_history);
  6768. env->loading = 0;
  6769. for (int i = 0; i < env->line_count; ++i) {
  6770. env->lines[i]->istate = 0;
  6771. recalculate_tabs(env->lines[i]);
  6772. }
  6773. for (int i = 0; i < env->line_count; ++i) {
  6774. recalculate_syntax(env->lines[i],i);
  6775. }
  6776. place_cursor_actual();
  6777. update_title();
  6778. redraw_all();
  6779. render_commandline_message("%d character%s, %d line%s changed",
  6780. count_chars, (count_chars == 1) ? "" : "s",
  6781. count_lines, (count_lines == 1) ? "" : "s");
  6782. }
  6783. int is_whitespace(int codepoint) {
  6784. return codepoint == ' ' || codepoint == '\t';
  6785. }
  6786. int is_normal(int codepoint) {
  6787. return isalnum(codepoint) || codepoint == '_';
  6788. }
  6789. int is_special(int codepoint) {
  6790. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6791. }
  6792. BIM_ACTION(word_left, 0,
  6793. "Move the cursor left to the previous word."
  6794. )(void) {
  6795. if (!env->lines[env->line_no-1]) return;
  6796. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6797. env->col_no -= 1;
  6798. }
  6799. if (env->col_no == 1) {
  6800. if (env->line_no == 1) goto _place;
  6801. env->line_no--;
  6802. env->col_no = env->lines[env->line_no-1]->actual;
  6803. goto _place;
  6804. }
  6805. int (*inverse_comparator)(int) = is_special;
  6806. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6807. inverse_comparator = is_normal;
  6808. }
  6809. do {
  6810. if (env->col_no > 1) {
  6811. env->col_no -= 1;
  6812. }
  6813. } 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));
  6814. _place:
  6815. set_preferred_column();
  6816. place_cursor_actual();
  6817. }
  6818. BIM_ACTION(big_word_left, 0,
  6819. "Move the cursor left to the previous WORD."
  6820. )(void) {
  6821. int line_no = env->line_no;
  6822. int col_no = env->col_no;
  6823. do {
  6824. col_no--;
  6825. while (col_no == 0) {
  6826. line_no--;
  6827. if (line_no == 0) {
  6828. goto_line(1);
  6829. set_preferred_column();
  6830. return;
  6831. }
  6832. col_no = env->lines[line_no-1]->actual;
  6833. }
  6834. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6835. do {
  6836. col_no--;
  6837. if (col_no == 0) {
  6838. env->col_no = 1;
  6839. env->line_no = line_no;
  6840. set_preferred_column();
  6841. redraw_statusbar();
  6842. place_cursor_actual();
  6843. return;
  6844. }
  6845. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6846. env->col_no = col_no;
  6847. env->line_no = line_no;
  6848. set_preferred_column();
  6849. cursor_right();
  6850. }
  6851. BIM_ACTION(word_right, 0,
  6852. "Move the cursor right to the start of the next word."
  6853. )(void) {
  6854. if (!env->lines[env->line_no-1]) return;
  6855. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6856. /* next line */
  6857. if (env->line_no == env->line_count) return;
  6858. env->line_no++;
  6859. env->col_no = 0;
  6860. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6861. goto _place;
  6862. }
  6863. }
  6864. if (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  6865. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  6866. env->col_no++;
  6867. }
  6868. goto _place;
  6869. }
  6870. int (*inverse_comparator)(int) = is_special;
  6871. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6872. inverse_comparator = is_normal;
  6873. }
  6874. while (env->col_no < env->lines[env->line_no-1]->actual && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6875. env->col_no++;
  6876. }
  6877. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6878. env->col_no++;
  6879. }
  6880. _place:
  6881. set_preferred_column();
  6882. place_cursor_actual();
  6883. }
  6884. BIM_ACTION(big_word_right, 0,
  6885. "Move the cursor right to the start of the next WORD."
  6886. )(void) {
  6887. int line_no = env->line_no;
  6888. int col_no = env->col_no;
  6889. do {
  6890. col_no++;
  6891. if (col_no > env->lines[line_no-1]->actual) {
  6892. line_no++;
  6893. if (line_no > env->line_count) {
  6894. env->line_no = env->line_count;
  6895. env->col_no = env->lines[env->line_no-1]->actual;
  6896. set_preferred_column();
  6897. redraw_statusbar();
  6898. place_cursor_actual();
  6899. return;
  6900. }
  6901. col_no = 0;
  6902. break;
  6903. }
  6904. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6905. do {
  6906. col_no++;
  6907. while (col_no > env->lines[line_no-1]->actual) {
  6908. line_no++;
  6909. if (line_no >= env->line_count) {
  6910. env->col_no = env->lines[env->line_count-1]->actual;
  6911. env->line_no = env->line_count;
  6912. set_preferred_column();
  6913. redraw_statusbar();
  6914. place_cursor_actual();
  6915. return;
  6916. }
  6917. col_no = 1;
  6918. }
  6919. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6920. env->col_no = col_no;
  6921. env->line_no = line_no;
  6922. set_preferred_column();
  6923. redraw_statusbar();
  6924. place_cursor_actual();
  6925. return;
  6926. }
  6927. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  6928. "Delete the character at the cursor, or merge with previous line."
  6929. )(void) {
  6930. if (env->col_no > 1) {
  6931. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6932. env->col_no -= 1;
  6933. if (env->coffset > 0) env->coffset--;
  6934. redraw_line(env->line_no-1);
  6935. set_modified();
  6936. redraw_statusbar();
  6937. place_cursor_actual();
  6938. } else if (env->line_no > 1) {
  6939. int tmp = env->lines[env->line_no - 2]->actual;
  6940. merge_lines(env->lines, env->line_no - 1);
  6941. env->line_no -= 1;
  6942. env->col_no = tmp+1;
  6943. set_preferred_column();
  6944. redraw_text();
  6945. set_modified();
  6946. redraw_statusbar();
  6947. place_cursor_actual();
  6948. }
  6949. }
  6950. BIM_ACTION(delete_word, ACTION_IS_RW,
  6951. "Delete the previous word."
  6952. )(void) {
  6953. if (!env->lines[env->line_no-1]) return;
  6954. if (env->col_no > 1) {
  6955. /* Start by deleting whitespace */
  6956. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6957. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6958. env->col_no -= 1;
  6959. if (env->coffset > 0) env->coffset--;
  6960. }
  6961. int (*inverse_comparator)(int) = is_special;
  6962. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6963. inverse_comparator = is_normal;
  6964. }
  6965. do {
  6966. if (env->col_no > 1) {
  6967. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6968. env->col_no -= 1;
  6969. if (env->coffset > 0) env->coffset--;
  6970. }
  6971. } 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));
  6972. set_preferred_column();
  6973. redraw_text();
  6974. set_modified();
  6975. redraw_statusbar();
  6976. place_cursor_actual();
  6977. }
  6978. }
  6979. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  6980. "Insert a line break, splitting the current line into two."
  6981. )(void) {
  6982. if (env->indent) {
  6983. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  6984. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  6985. (env->col_no > 3) &&
  6986. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  6987. delete_at_cursor();
  6988. }
  6989. }
  6990. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6991. env->lines = add_line(env->lines, env->line_no);
  6992. } else {
  6993. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6994. }
  6995. env->coffset = 0;
  6996. env->col_no = 1;
  6997. env->line_no += 1;
  6998. set_preferred_column();
  6999. add_indent(env->line_no-1,env->line_no-2,0);
  7000. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7001. env->offset += 1;
  7002. }
  7003. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7004. set_modified();
  7005. }
  7006. BIM_ACTION(yank_lines, 0,
  7007. "Copy lines into the paste buffer."
  7008. )(void) {
  7009. int start = env->start_line;
  7010. int end = env->line_no;
  7011. if (global_config.yanks) {
  7012. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7013. free(global_config.yanks[i]);
  7014. }
  7015. free(global_config.yanks);
  7016. }
  7017. int lines_to_yank;
  7018. int start_point;
  7019. if (start <= end) {
  7020. lines_to_yank = end - start + 1;
  7021. start_point = start - 1;
  7022. } else {
  7023. lines_to_yank = start - end + 1;
  7024. start_point = end - 1;
  7025. }
  7026. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7027. global_config.yank_count = lines_to_yank;
  7028. global_config.yank_is_full_lines = 1;
  7029. for (int i = 0; i < lines_to_yank; ++i) {
  7030. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7031. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7032. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7033. global_config.yanks[i]->istate = 0;
  7034. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7035. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7036. global_config.yanks[i]->text[j].flags = 0;
  7037. }
  7038. }
  7039. }
  7040. /**
  7041. * Helper to yank part of a line into a new yank line.
  7042. */
  7043. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  7044. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  7045. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  7046. global_config.yanks[yank_no]->actual = count;
  7047. global_config.yanks[yank_no]->istate = 0;
  7048. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  7049. for (int i = 0; i < count; ++i) {
  7050. global_config.yanks[yank_no]->text[i].flags = 0;
  7051. }
  7052. }
  7053. /**
  7054. * Yank text...
  7055. */
  7056. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  7057. if (global_config.yanks) {
  7058. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7059. free(global_config.yanks[i]);
  7060. }
  7061. free(global_config.yanks);
  7062. }
  7063. int lines_to_yank = end_line - start_line + 1;
  7064. int start_point = start_line - 1;
  7065. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7066. global_config.yank_count = lines_to_yank;
  7067. global_config.yank_is_full_lines = 0;
  7068. if (lines_to_yank == 1) {
  7069. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  7070. } else {
  7071. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  7072. /* Yank middle lines */
  7073. for (int i = 1; i < lines_to_yank - 1; ++i) {
  7074. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7075. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7076. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7077. global_config.yanks[i]->istate = 0;
  7078. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7079. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7080. global_config.yanks[i]->text[j].flags = 0;
  7081. }
  7082. }
  7083. /* Yank end line */
  7084. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  7085. }
  7086. }
  7087. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  7088. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  7089. )(int direction) {
  7090. if (direction == -1 && env->sel_col <= 0) return;
  7091. int prev_width = 0;
  7092. for (int i = env->line_no; i <= env->start_line; i++) {
  7093. line_t * line = env->lines[i - 1];
  7094. int _x = 0;
  7095. int col = 1;
  7096. int j = 0;
  7097. for (; j < line->actual; ++j) {
  7098. char_t * c = &line->text[j];
  7099. _x += c->display_width;
  7100. col = j+1;
  7101. if (_x > env->sel_col) break;
  7102. prev_width = c->display_width;
  7103. }
  7104. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  7105. line_delete(line, line->actual, i - 1);
  7106. set_modified();
  7107. } else if (_x > env->sel_col) {
  7108. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  7109. set_modified();
  7110. }
  7111. }
  7112. if (direction == -1) {
  7113. env->sel_col -= prev_width;
  7114. env->col_no--;
  7115. }
  7116. redraw_text();
  7117. }
  7118. uint32_t * get_word_under_cursor(void) {
  7119. /* Figure out size */
  7120. int c_before = 0;
  7121. int c_after = 0;
  7122. int i = env->col_no;
  7123. while (i > 0) {
  7124. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7125. c_before++;
  7126. i--;
  7127. }
  7128. i = env->col_no+1;
  7129. while (i < env->lines[env->line_no-1]->actual+1) {
  7130. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7131. c_after++;
  7132. i++;
  7133. }
  7134. if (!c_before && !c_after) return NULL;
  7135. /* Populate with characters */
  7136. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  7137. int j = 0;
  7138. while (c_before) {
  7139. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  7140. c_before--;
  7141. j++;
  7142. }
  7143. int x = 0;
  7144. while (c_after) {
  7145. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  7146. j++;
  7147. x++;
  7148. c_after--;
  7149. }
  7150. out[j] = 0;
  7151. return out;
  7152. }
  7153. BIM_ACTION(search_under_cursor, 0,
  7154. "Search for the word currently under the cursor."
  7155. )(void) {
  7156. if (global_config.search) free(global_config.search);
  7157. global_config.search = get_word_under_cursor();
  7158. /* Find it */
  7159. search_next();
  7160. }
  7161. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7162. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  7163. )(int type, int c) {
  7164. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  7165. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7166. env->col_no = i - !!(type == 't');
  7167. place_cursor_actual();
  7168. set_preferred_column();
  7169. return;
  7170. }
  7171. }
  7172. }
  7173. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7174. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  7175. )(int type, int c) {
  7176. for (int i = env->col_no-1; i >= 1; --i) {
  7177. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7178. env->col_no = i + !!(type == 'T');
  7179. place_cursor_actual();
  7180. set_preferred_column();
  7181. return;
  7182. }
  7183. }
  7184. }
  7185. /**
  7186. * Clear the navigation number buffer
  7187. */
  7188. void reset_nav_buffer(int c) {
  7189. if (c == KEY_TIMEOUT) return;
  7190. if (nav_buffer && (c < '0' || c > '9')) {
  7191. nav_buffer = 0;
  7192. redraw_commandline();
  7193. }
  7194. }
  7195. /**
  7196. * Determine if a column + line number are within range of the
  7197. * current character selection specified by start_line, etc.
  7198. *
  7199. * Used to determine how syntax flags should be set when redrawing
  7200. * selected text in CHAR SELECTION mode.
  7201. */
  7202. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7203. if (start_line == end_line) {
  7204. if ( end_col < start_col) {
  7205. int tmp = end_col;
  7206. end_col = start_col;
  7207. start_col = tmp;
  7208. }
  7209. return (col >= start_col && col <= end_col);
  7210. }
  7211. if (start_line > end_line) {
  7212. int tmp = end_line;
  7213. end_line = start_line;
  7214. start_line = tmp;
  7215. tmp = end_col;
  7216. end_col = start_col;
  7217. start_col = tmp;
  7218. }
  7219. if (line < start_line || line > end_line) return 0;
  7220. if (line == start_line) {
  7221. return col >= start_col;
  7222. }
  7223. if (line == end_line) {
  7224. return col <= end_col;
  7225. }
  7226. return 1;
  7227. }
  7228. /**
  7229. * Macro for redrawing selected lines with appropriate highlighting.
  7230. */
  7231. #define _redraw_line(line, force_start_line) \
  7232. do { \
  7233. if (!(force_start_line) && (line) == env->start_line) break; \
  7234. if ((line) > env->line_count + 1) { \
  7235. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7236. draw_excess_line((line) - env->offset - 1); \
  7237. } \
  7238. break; \
  7239. } \
  7240. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7241. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7242. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7243. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7244. } else { \
  7245. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7246. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7247. } \
  7248. } \
  7249. redraw_line((line)-1); \
  7250. } while (0)
  7251. #define _redraw_line_char(line, force_start_line) \
  7252. do { \
  7253. if (!(force_start_line) && (line) == env->start_line) break; \
  7254. if ((line) > env->line_count + 1) { \
  7255. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7256. draw_excess_line((line) - env->offset - 1); \
  7257. } \
  7258. break; \
  7259. } \
  7260. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7261. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7262. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7263. /* Line is completely outside selection */ \
  7264. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7265. } else { \
  7266. if ((line) == env->start_line || (line) == env->line_no) { \
  7267. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7268. } \
  7269. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7270. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  7271. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7272. } \
  7273. } \
  7274. } \
  7275. redraw_line((line)-1); \
  7276. } while (0)
  7277. #define _redraw_line_col(line, force_start_line) \
  7278. do {\
  7279. if (!(force_start_line) && (line) == env->start_line) break; \
  7280. if ((line) > env->line_count + 1) { \
  7281. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7282. draw_excess_line((line) - env->offset - 1); \
  7283. } \
  7284. break; \
  7285. } \
  7286. redraw_line((line)-1); \
  7287. } while (0)
  7288. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  7289. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  7290. )(int direction) {
  7291. int lines_to_cover = 0;
  7292. int start_point = 0;
  7293. if (env->start_line <= env->line_no) {
  7294. start_point = env->start_line - 1;
  7295. lines_to_cover = env->line_no - env->start_line + 1;
  7296. } else {
  7297. start_point = env->line_no - 1;
  7298. lines_to_cover = env->start_line - env->line_no + 1;
  7299. }
  7300. for (int i = 0; i < lines_to_cover; ++i) {
  7301. if (env->lines[start_point + i]->actual < 1) continue;
  7302. if (direction == -1) {
  7303. if (env->tabs) {
  7304. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7305. line_delete(env->lines[start_point + i],1,start_point+i);
  7306. _redraw_line(start_point+i+1,1);
  7307. }
  7308. } else {
  7309. for (int j = 0; j < env->tabstop; ++j) {
  7310. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  7311. line_delete(env->lines[start_point + i],1,start_point+i);
  7312. }
  7313. }
  7314. _redraw_line(start_point+i+1,1);
  7315. }
  7316. } else if (direction == 1) {
  7317. if (env->tabs) {
  7318. char_t c;
  7319. c.codepoint = '\t';
  7320. c.display_width = env->tabstop;
  7321. c.flags = FLAG_SELECT;
  7322. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7323. } else {
  7324. for (int j = 0; j < env->tabstop; ++j) {
  7325. char_t c;
  7326. c.codepoint = ' ';
  7327. c.display_width = 1;
  7328. c.flags = FLAG_SELECT;
  7329. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7330. }
  7331. }
  7332. _redraw_line(start_point+i+1,1);
  7333. }
  7334. }
  7335. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7336. env->col_no = env->lines[env->line_no-1]->actual;
  7337. }
  7338. set_preferred_column();
  7339. set_modified();
  7340. }
  7341. void recalculate_selected_lines(void) {
  7342. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7343. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7344. if (start < 1) start = 1;
  7345. if (start > env->line_count) start = env->line_count;
  7346. if (end < 1) end = 1;
  7347. if (end > env->line_count) end = env->line_count;
  7348. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  7349. recalculate_syntax(env->lines[i-1],i-1);
  7350. }
  7351. redraw_all();
  7352. }
  7353. BIM_ACTION(enter_line_selection, 0,
  7354. "Enter line selection mode."
  7355. )(void) {
  7356. /* Set mode */
  7357. env->mode = MODE_LINE_SELECTION;
  7358. /* Store start position */
  7359. env->start_line = env->line_no;
  7360. env->prev_line = env->start_line;
  7361. env->start_col = env->col_no;
  7362. /* Redraw commandline to get -- LINE SELECTION -- text */
  7363. redraw_commandline();
  7364. unhighlight_matching_paren();
  7365. /* Set this line as selected for syntax highlighting */
  7366. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  7367. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  7368. }
  7369. /* And redraw it */
  7370. redraw_line(env->line_no-1);
  7371. }
  7372. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  7373. "Swap between LINE and CHAR selection modes."
  7374. )(int mode) {
  7375. env->mode = mode;
  7376. if (mode == MODE_LINE_SELECTION) {
  7377. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7378. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7379. for (int i = start; i <= end; ++i) {
  7380. _redraw_line(i, 1);
  7381. }
  7382. } else if (mode == MODE_CHAR_SELECTION) {
  7383. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7384. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7385. for (int i = start; i <= end; ++i) {
  7386. _redraw_line_char(i, 1);
  7387. }
  7388. }
  7389. }
  7390. BIM_ACTION(delete_and_yank_lines, 0,
  7391. "Delete and yank the selected lines."
  7392. )(void) {
  7393. yank_lines();
  7394. if (env->start_line <= env->line_no) {
  7395. int lines_to_delete = env->line_no - env->start_line + 1;
  7396. for (int i = 0; i < lines_to_delete; ++i) {
  7397. env->lines = remove_line(env->lines, env->start_line-1);
  7398. }
  7399. env->line_no = env->start_line;
  7400. } else {
  7401. int lines_to_delete = env->start_line - env->line_no + 1;
  7402. for (int i = 0; i < lines_to_delete; ++i) {
  7403. env->lines = remove_line(env->lines, env->line_no-1);
  7404. }
  7405. }
  7406. if (env->line_no > env->line_count) {
  7407. env->line_no = env->line_count;
  7408. }
  7409. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7410. env->col_no = env->lines[env->line_no-1]->actual;
  7411. }
  7412. set_preferred_column();
  7413. set_modified();
  7414. }
  7415. BIM_ACTION(enter_insert, ACTION_IS_RW,
  7416. "Enter insert mode."
  7417. )(void) {
  7418. env->mode = MODE_INSERT;
  7419. set_history_break();
  7420. }
  7421. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  7422. "Delete and yank the selected lines and then enter insert mode."
  7423. )(void) {
  7424. delete_and_yank_lines();
  7425. env->lines = add_line(env->lines, env->line_no-1);
  7426. redraw_text();
  7427. env->mode = MODE_INSERT;
  7428. }
  7429. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  7430. "Replace characters in the selected lines."
  7431. )(int c) {
  7432. if (c >= KEY_ESCAPE) {
  7433. render_error("Invalid key for replacement");
  7434. return;
  7435. }
  7436. char_t _c = {codepoint_width(c), 0, c};
  7437. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  7438. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  7439. for (int line = start_point; line <= end_point; ++line) {
  7440. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7441. line_replace(env->lines[line-1], _c, i, line-1);
  7442. }
  7443. }
  7444. }
  7445. BIM_ACTION(leave_selection, 0,
  7446. "Leave selection modes and return to normal mode."
  7447. )(void) {
  7448. set_history_break();
  7449. env->mode = MODE_NORMAL;
  7450. recalculate_selected_lines();
  7451. }
  7452. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  7453. "Insert a character on all lines at the current column."
  7454. )(int c) {
  7455. char_t _c;
  7456. _c.codepoint = c;
  7457. _c.flags = 0;
  7458. _c.display_width = codepoint_width(c);
  7459. int inserted_width = 0;
  7460. /* For each line */
  7461. for (int i = env->line_no; i <= env->start_line; i++) {
  7462. line_t * line = env->lines[i - 1];
  7463. int _x = 0;
  7464. int col = 1;
  7465. int j = 0;
  7466. for (; j < line->actual; ++j) {
  7467. char_t * c = &line->text[j];
  7468. _x += c->display_width;
  7469. col = j+1;
  7470. if (_x > env->sel_col) break;
  7471. }
  7472. if ((_x == env->sel_col && j == line->actual)) {
  7473. _x = env->sel_col + 1;
  7474. col = line->actual + 1;
  7475. }
  7476. if (_x > env->sel_col) {
  7477. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7478. if (line != nline) {
  7479. env->lines[i - 1] = nline;
  7480. line = nline;
  7481. }
  7482. set_modified();
  7483. }
  7484. recalculate_tabs(line);
  7485. inserted_width = line->text[col-1].display_width;
  7486. }
  7487. env->sel_col += inserted_width;
  7488. env->col_no++;
  7489. }
  7490. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  7491. "Enter column insert mode."
  7492. )(void) {
  7493. if (env->start_line < env->line_no) {
  7494. /* swap */
  7495. int tmp = env->line_no;
  7496. env->line_no = env->start_line;
  7497. env->start_line = tmp;
  7498. }
  7499. env->mode = MODE_COL_INSERT;
  7500. }
  7501. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  7502. "Enter column insert mode after the selected column."
  7503. )(void) {
  7504. env->sel_col += 1;
  7505. enter_col_insert();
  7506. }
  7507. BIM_ACTION(delete_column, ACTION_IS_RW,
  7508. "(temporary) Delete the selected column."
  7509. )(void) {
  7510. /* TODO maybe a flag to do this so we can just call delete_at_column with arg = 1? */
  7511. if (env->start_line < env->line_no) {
  7512. int tmp = env->line_no;
  7513. env->line_no = env->start_line;
  7514. env->start_line = tmp;
  7515. }
  7516. delete_at_column(1);
  7517. }
  7518. BIM_ACTION(enter_col_selection, 0,
  7519. "Enter column selection mode."
  7520. )(void) {
  7521. /* Set mode */
  7522. env->mode = MODE_COL_SELECTION;
  7523. /* Store cursor */
  7524. env->start_line = env->line_no;
  7525. env->sel_col = env->preferred_column;
  7526. env->prev_line = env->start_line;
  7527. /* Redraw commandline */
  7528. redraw_commandline();
  7529. /* Nothing else to do here; rely on cursor */
  7530. }
  7531. BIM_ACTION(yank_characters, 0,
  7532. "Yank the selected characters to the paste buffer."
  7533. )(void) {
  7534. int end_line = env->line_no;
  7535. int end_col = env->col_no;
  7536. if (env->start_line == end_line) {
  7537. if (env->start_col > end_col) {
  7538. int tmp = env->start_col;
  7539. env->start_col = end_col;
  7540. end_col = tmp;
  7541. }
  7542. } else if (env->start_line > end_line) {
  7543. int tmp = env->start_line;
  7544. env->start_line = end_line;
  7545. end_line = tmp;
  7546. tmp = env->start_col;
  7547. env->start_col = end_col;
  7548. end_col = tmp;
  7549. }
  7550. yank_text(env->start_line, env->start_col, end_line, end_col);
  7551. }
  7552. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  7553. "Delete and yank the selected characters."
  7554. )(void) {
  7555. int end_line = env->line_no;
  7556. int end_col = env->col_no;
  7557. if (env->start_line == end_line) {
  7558. if (env->start_col > end_col) {
  7559. int tmp = env->start_col;
  7560. env->start_col = end_col;
  7561. end_col = tmp;
  7562. }
  7563. yank_text(env->start_line, env->start_col, end_line, end_col);
  7564. for (int i = env->start_col; i <= end_col; ++i) {
  7565. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7566. }
  7567. env->col_no = env->start_col;
  7568. } else {
  7569. if (env->start_line > end_line) {
  7570. int tmp = env->start_line;
  7571. env->start_line = end_line;
  7572. end_line = tmp;
  7573. tmp = env->start_col;
  7574. env->start_col = end_col;
  7575. end_col = tmp;
  7576. }
  7577. /* Copy lines */
  7578. yank_text(env->start_line, env->start_col, end_line, end_col);
  7579. /* Delete lines */
  7580. for (int i = env->start_line+1; i < end_line; ++i) {
  7581. env->lines = remove_line(env->lines, env->start_line);
  7582. } /* end_line is no longer valid; should be start_line+1*/
  7583. /* Delete from env->start_col forward */
  7584. int tmp = env->lines[env->start_line-1]->actual;
  7585. for (int i = env->start_col; i <= tmp; ++i) {
  7586. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7587. }
  7588. for (int i = 1; i <= end_col; ++i) {
  7589. line_delete(env->lines[env->start_line], 1, env->start_line);
  7590. }
  7591. /* Merge start and end lines */
  7592. merge_lines(env->lines, env->start_line);
  7593. env->line_no = env->start_line;
  7594. env->col_no = env->start_col;
  7595. }
  7596. if (env->line_no > env->line_count) {
  7597. env->line_no = env->line_count;
  7598. }
  7599. set_preferred_column();
  7600. set_modified();
  7601. }
  7602. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  7603. "Delete and yank the selected characters and then enter insert mode."
  7604. )(void) {
  7605. delete_and_yank_chars();
  7606. redraw_text();
  7607. enter_insert();
  7608. }
  7609. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  7610. "Replace the selected characters."
  7611. )(int c) {
  7612. if (c >= KEY_ESCAPE) {
  7613. render_error("Invalid key for replacement");
  7614. return;
  7615. }
  7616. char_t _c = {codepoint_width(c), 0, c};
  7617. /* This should probably be a function line "do_over_range" or something */
  7618. if (env->start_line == env->line_no) {
  7619. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  7620. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  7621. for (int i = s; i <= e; ++i) {
  7622. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  7623. }
  7624. redraw_text();
  7625. } else {
  7626. if (env->start_line < env->line_no) {
  7627. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  7628. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7629. }
  7630. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  7631. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7632. line_replace(env->lines[line-1], _c, i, line-1);
  7633. }
  7634. }
  7635. for (int s = 0; s < env->col_no; ++s) {
  7636. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7637. }
  7638. } else {
  7639. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  7640. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7641. }
  7642. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  7643. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7644. line_replace(env->lines[line-1], _c, i, line-1);
  7645. }
  7646. }
  7647. for (int s = 0; s < env->start_col; ++s) {
  7648. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7649. }
  7650. }
  7651. }
  7652. }
  7653. BIM_ACTION(enter_char_selection, 0,
  7654. "Enter character selection mode."
  7655. )(void) {
  7656. /* Set mode */
  7657. env->mode = MODE_CHAR_SELECTION;
  7658. /* Set cursor positions */
  7659. env->start_line = env->line_no;
  7660. env->start_col = env->col_no;
  7661. env->prev_line = env->start_line;
  7662. /* Redraw commandline for -- CHAR SELECTION -- */
  7663. redraw_commandline();
  7664. unhighlight_matching_paren();
  7665. /* Select single character */
  7666. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7667. redraw_line(env->line_no-1);
  7668. }
  7669. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  7670. "Move the cursor to the end of the selection and enter insert mode."
  7671. )(void) {
  7672. recalculate_selected_lines();
  7673. if (env->line_no == env->start_line) {
  7674. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  7675. } else if (env->line_no < env->start_line) {
  7676. env->col_no = env->start_col + 1;
  7677. env->line_no = env->start_line;
  7678. } else {
  7679. env->col_no += 1;
  7680. }
  7681. env->mode = MODE_INSERT;
  7682. }
  7683. void free_completion_match(struct completion_match * match) {
  7684. if (match->string) free(match->string);
  7685. if (match->file) free(match->file);
  7686. if (match->search) free(match->search);
  7687. }
  7688. /**
  7689. * Read ctags file to find matches for a symbol
  7690. */
  7691. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  7692. int _matches_len = 4;
  7693. int *matches_len = &_matches_len;
  7694. *matches_count = 0;
  7695. *matches = malloc(sizeof(struct completion_match) * (*matches_len));
  7696. FILE * tags = fopen("tags","r");
  7697. if (tags) {
  7698. char tmp[4096]; /* max line */
  7699. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  7700. if (tmp[0] == '!') continue;
  7701. int i = 0;
  7702. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  7703. if (comp[i] == '\0') {
  7704. if (complete_match && tmp[i] != '\t') continue;
  7705. int j = i;
  7706. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7707. tmp[j] = '\0'; j++;
  7708. char * file = &tmp[j];
  7709. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7710. tmp[j] = '\0'; j++;
  7711. char * search = &tmp[j];
  7712. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  7713. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  7714. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  7715. tmp[j] = '\0'; j++;
  7716. add_match(tmp,file,search);
  7717. }
  7718. }
  7719. fclose(tags);
  7720. }
  7721. /* TODO: Get these from syntax files with a dynamic callback */
  7722. if (env->syntax && env->syntax->completion_matcher) {
  7723. env->syntax->completion_matcher(comp,matches,matches_count,complete_match,matches_len);
  7724. }
  7725. return 0;
  7726. }
  7727. /**
  7728. * Draw an autocomplete popover with matches.
  7729. */
  7730. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  7731. int original_length = 0;
  7732. while (tmp[original_length]) original_length++;
  7733. int max_width = 0;
  7734. for (int i = 0; i < matches_count; ++i) {
  7735. /* TODO unicode width */
  7736. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  7737. if (my_width > (unsigned int)max_width) {
  7738. max_width = my_width;
  7739. }
  7740. }
  7741. /* Figure out how much space we have to display the window */
  7742. int cursor_y = env->line_no - env->offset + global_config.tabs_visible;
  7743. int max_y = global_config.term_height - global_config.bottom_size - cursor_y;
  7744. /* Find a good place to put the box horizontally */
  7745. int num_size = num_width() + gutter_width();
  7746. int x = num_size + 1 - env->coffset;
  7747. /* Determine where the cursor is physically */
  7748. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  7749. char_t * c = &env->lines[env->line_no-1]->text[i];
  7750. x += c->display_width;
  7751. }
  7752. int box_width = max_width;
  7753. int box_x = x;
  7754. int box_y = cursor_y + 1;
  7755. if (max_width > env->width - num_width() - gutter_width()) {
  7756. box_width = env->width - num_width() - gutter_width();
  7757. box_x = num_width() + gutter_width() + 1;
  7758. } else if (env->width - x < max_width) {
  7759. box_width = max_width;
  7760. box_x = env->width - max_width;
  7761. }
  7762. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  7763. for (int x = index; x < max_count+index; ++x) {
  7764. int i = x % matches_count;
  7765. place_cursor(box_x + env->left, box_y+x-index);
  7766. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  7767. /* TODO wide characters */
  7768. int match_width = strlen(matches[i].string);
  7769. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  7770. for (int j = 0; j < box_width; ++j) {
  7771. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  7772. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  7773. if (j < match_width) printf("%c", matches[i].string[j]);
  7774. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  7775. else printf(" ");
  7776. }
  7777. }
  7778. if (max_count == 0) {
  7779. place_cursor(box_x + env->left, box_y);
  7780. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7781. printf(" (no matches) ");
  7782. } else if (max_count != matches_count) {
  7783. place_cursor(box_x + env->left, box_y+max_count);
  7784. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7785. printf(" (%d more) ", matches_count-max_count);
  7786. }
  7787. }
  7788. /**
  7789. * Autocomplete words (function/variable names, etc.) in input mode.
  7790. */
  7791. int omni_complete(int quit_quietly_on_none) {
  7792. int c;
  7793. int (*qualifier)(int c) = simple_keyword_qualifier;
  7794. if (env->syntax && env->syntax->completion_qualifier) {
  7795. qualifier = env->syntax->completion_qualifier;
  7796. }
  7797. /* Pull the word from before the cursor */
  7798. int c_before = 0;
  7799. int i = env->col_no-1;
  7800. while (i > 0) {
  7801. int c = env->lines[env->line_no-1]->text[i-1].codepoint;
  7802. if (!qualifier(c)) break;
  7803. c_before++;
  7804. i--;
  7805. }
  7806. if (!c_before && quit_quietly_on_none) return 0;
  7807. /* Populate with characters */
  7808. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  7809. int j = 0;
  7810. while (c_before) {
  7811. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  7812. c_before--;
  7813. j++;
  7814. }
  7815. tmp[j] = 0;
  7816. /*
  7817. * TODO matches should probably be a struct with more data than just
  7818. * the matching string; maybe offset where the needle was found,
  7819. * class information, source file information - anything we can extract
  7820. * from ctags, but also other information for other sources of completion.
  7821. */
  7822. struct completion_match *matches;
  7823. int matches_count;
  7824. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  7825. if (read_tags(tmp, &matches, &matches_count, 0)) goto _completion_done;
  7826. /* Draw box with matches at cursor-width(tmp) */
  7827. if (quit_quietly_on_none && matches_count == 0) return 0;
  7828. draw_completion_matches(tmp, matches, matches_count, 0);
  7829. int retval = 0;
  7830. int index = 0;
  7831. _completion_done:
  7832. place_cursor_actual();
  7833. while (1) {
  7834. c = bim_getch();
  7835. if (c == -1) continue;
  7836. if (matches_count < 1) {
  7837. redraw_all();
  7838. break;
  7839. }
  7840. if (c == 15) {
  7841. index = (index + 1) % matches_count;
  7842. draw_completion_matches(tmp, matches, matches_count, index);
  7843. place_cursor_actual();
  7844. continue;
  7845. } else if (c == '\t') {
  7846. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  7847. insert_char(matches[index].string[i]);
  7848. }
  7849. set_preferred_column();
  7850. redraw_text();
  7851. place_cursor_actual();
  7852. goto _finish_completion;
  7853. } else if (isgraph(c) && c != '}') {
  7854. /* insert and continue matching */
  7855. insert_char(c);
  7856. set_preferred_column();
  7857. redraw_text();
  7858. place_cursor_actual();
  7859. retval = 1;
  7860. goto _finish_completion;
  7861. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  7862. delete_at_cursor();
  7863. set_preferred_column();
  7864. redraw_text();
  7865. place_cursor_actual();
  7866. retval = 1;
  7867. goto _finish_completion;
  7868. }
  7869. /* TODO: Keyboard navigation of the matches list would be nice */
  7870. redraw_all();
  7871. break;
  7872. }
  7873. bim_unget(c);
  7874. _finish_completion:
  7875. for (int i = 0; i < matches_count; ++i) {
  7876. free_completion_match(&matches[i]);
  7877. }
  7878. free(matches);
  7879. free(tmp);
  7880. return retval;
  7881. }
  7882. /**
  7883. * Set the search string from a UTF-8 sequence.
  7884. * Since the search string is normally a series of codepoints, this saves
  7885. * some effort when trying to search for things we pulled from the outside world.
  7886. * (eg., ctags search terms)
  7887. */
  7888. void set_search_from_bytes(char * bytes) {
  7889. if (global_config.search) free(global_config.search);
  7890. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) + 1));
  7891. uint32_t * s = global_config.search;
  7892. char * tmp = bytes;
  7893. uint32_t c, istate = 0;
  7894. while (*tmp) {
  7895. if (!decode(&istate, &c, *tmp)) {
  7896. *s = c;
  7897. s++;
  7898. *s = 0;
  7899. } else if (istate == UTF8_REJECT) {
  7900. istate = 0;
  7901. }
  7902. tmp++;
  7903. }
  7904. }
  7905. BIM_ACTION(goto_definition, 0,
  7906. "Jump to the definition of the word under under cursor."
  7907. )(void) {
  7908. uint32_t * word = get_word_under_cursor();
  7909. if (!word) {
  7910. render_error("No match");
  7911. return;
  7912. }
  7913. struct completion_match *matches;
  7914. int matches_count;
  7915. if (read_tags(word, &matches, &matches_count, 1)) {
  7916. render_error("No tags file");
  7917. goto _done;
  7918. }
  7919. if (!matches_count) {
  7920. render_error("No match");
  7921. goto _done;
  7922. }
  7923. #define _perform_correct_search(i) do { \
  7924. if (matches[i].search[0] == '/') { \
  7925. set_search_from_bytes(&matches[i].search[1]); \
  7926. search_next(); \
  7927. } else { \
  7928. goto_line(atoi(matches[i].search)); \
  7929. } \
  7930. } while (0)
  7931. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  7932. _perform_correct_search(0);
  7933. } else {
  7934. /* Check if there were other matches that are in this file */
  7935. for (int i =1; env->file_name && i < matches_count; ++i) {
  7936. if (!strcmp(matches[i].file, env->file_name)) {
  7937. _perform_correct_search(i);
  7938. goto _done;
  7939. }
  7940. }
  7941. /* Check buffers */
  7942. for (int i = 0; i < buffers_len; ++i) {
  7943. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  7944. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  7945. env = buffers[i];
  7946. redraw_tabbar();
  7947. _perform_correct_search(i);
  7948. goto _done;
  7949. }
  7950. }
  7951. /* Okay, let's try opening */
  7952. buffer_t * old_buf = env;
  7953. open_file(matches[0].file);
  7954. if (env != old_buf) {
  7955. _perform_correct_search(0);
  7956. } else {
  7957. render_error("Could not locate file containing definition");
  7958. }
  7959. }
  7960. _done:
  7961. for (int i = 0; i < matches_count; ++i) {
  7962. free_completion_match(&matches[i]);
  7963. }
  7964. free(matches);
  7965. free(word);
  7966. }
  7967. /**
  7968. * Read one codepoint, with verbatim support.
  7969. */
  7970. int read_one_character(char * message) {
  7971. /* Read one character and replace */
  7972. if (!global_config.overlay_mode) {
  7973. render_commandline_message(message);
  7974. place_cursor_actual();
  7975. }
  7976. int c;
  7977. while ((c = bim_getkey(200))) {
  7978. if (c == KEY_TIMEOUT) continue;
  7979. if (c == KEY_CTRL_V) {
  7980. if (!global_config.overlay_mode) {
  7981. render_commandline_message(message);
  7982. printf(" ^V");
  7983. place_cursor_actual();
  7984. }
  7985. while ((c = bim_getch()) == -1);
  7986. break;
  7987. }
  7988. break;
  7989. }
  7990. redraw_commandline();
  7991. return c;
  7992. }
  7993. int read_one_byte(char * message) {
  7994. if (!global_config.overlay_mode) {
  7995. render_commandline_message(message);
  7996. place_cursor_actual();
  7997. }
  7998. int c;
  7999. while ((c = bim_getch())) {
  8000. if (c == -1) continue;
  8001. break;
  8002. }
  8003. redraw_commandline();
  8004. return c;
  8005. }
  8006. BIM_ACTION(cursor_left_with_wrap, 0,
  8007. "Move the cursor one position left, wrapping to the previous line."
  8008. )(void) {
  8009. if (env->line_no > 1 && env->col_no == 1) {
  8010. env->line_no--;
  8011. env->col_no = env->lines[env->line_no-1]->actual;
  8012. set_preferred_column();
  8013. place_cursor_actual();
  8014. } else {
  8015. cursor_left();
  8016. }
  8017. }
  8018. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  8019. "Insert a new line before the current line and enter insert mode."
  8020. )(void) {
  8021. set_history_break();
  8022. env->lines = add_line(env->lines, env->line_no-1);
  8023. env->col_no = 1;
  8024. add_indent(env->line_no-1,env->line_no,0);
  8025. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8026. redraw_text();
  8027. set_preferred_column();
  8028. set_modified();
  8029. place_cursor_actual();
  8030. env->mode = MODE_INSERT;
  8031. }
  8032. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  8033. "Insert a new line after the current line and enter insert mode."
  8034. )(void) {
  8035. set_history_break();
  8036. unhighlight_matching_paren();
  8037. env->lines = add_line(env->lines, env->line_no);
  8038. env->col_no = 1;
  8039. env->line_no += 1;
  8040. add_indent(env->line_no-1,env->line_no-2,0);
  8041. set_preferred_column();
  8042. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  8043. env->offset += 1;
  8044. }
  8045. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8046. redraw_text();
  8047. set_modified();
  8048. place_cursor_actual();
  8049. env->mode = MODE_INSERT;
  8050. }
  8051. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  8052. "Place the cursor after the selected character and enter insert mode."
  8053. )(void) {
  8054. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  8055. env->col_no += 1;
  8056. }
  8057. enter_insert();
  8058. }
  8059. BIM_ACTION(delete_forward, ACTION_IS_RW,
  8060. "Delete the character under the cursor."
  8061. )(void) {
  8062. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  8063. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  8064. redraw_text();
  8065. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1 && env->line_count > env->line_no) {
  8066. merge_lines(env->lines, env->line_no);
  8067. redraw_text();
  8068. }
  8069. set_modified();
  8070. redraw_statusbar();
  8071. place_cursor_actual();
  8072. }
  8073. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  8074. "Delete the character under the cursor and enter insert mode."
  8075. )(void) {
  8076. set_history_break();
  8077. delete_forward();
  8078. env->mode = MODE_INSERT;
  8079. }
  8080. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  8081. "Paste yanked text before (`P`) or after (`p`) the cursor."
  8082. )(int direction) {
  8083. if (global_config.yanks) {
  8084. if (!global_config.yank_is_full_lines) {
  8085. /* Handle P for paste before, p for past after */
  8086. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  8087. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  8088. target_column = env->lines[env->line_no-1]->actual + 1;
  8089. }
  8090. if (global_config.yank_count > 1) {
  8091. /* Spit the current line at the current position */
  8092. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  8093. }
  8094. /* Insert first line at current position */
  8095. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  8096. 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);
  8097. }
  8098. if (global_config.yank_count > 1) {
  8099. /* Insert full lines */
  8100. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8101. env->lines = add_line(env->lines, env->line_no);
  8102. }
  8103. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8104. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  8105. }
  8106. /* Insert characters from last line into (what was) the next line */
  8107. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  8108. 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);
  8109. }
  8110. }
  8111. } else {
  8112. /* Insert full lines */
  8113. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8114. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  8115. }
  8116. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8117. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  8118. }
  8119. }
  8120. /* Recalculate whole document syntax */
  8121. for (int i = 0; i < env->line_count; ++i) {
  8122. env->lines[i]->istate = 0;
  8123. }
  8124. for (int i = 0; i < env->line_count; ++i) {
  8125. recalculate_syntax(env->lines[i],i);
  8126. }
  8127. if (direction == 1) {
  8128. if (global_config.yank_is_full_lines) {
  8129. env->line_no += 1;
  8130. } else {
  8131. if (global_config.yank_count == 1) {
  8132. env->col_no = env->col_no + global_config.yanks[0]->actual;
  8133. } else {
  8134. env->line_no = env->line_no + global_config.yank_count - 1;
  8135. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  8136. }
  8137. }
  8138. }
  8139. if (global_config.yank_is_full_lines) {
  8140. env->col_no = 1;
  8141. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8142. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8143. env->col_no = i + 1;
  8144. break;
  8145. }
  8146. }
  8147. }
  8148. set_history_break();
  8149. set_modified();
  8150. redraw_all();
  8151. }
  8152. }
  8153. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  8154. "Move the cursor to the end of the current line and enter insert mode."
  8155. )(void) {
  8156. env->col_no = env->lines[env->line_no-1]->actual+1;
  8157. env->mode = MODE_INSERT;
  8158. set_history_break();
  8159. }
  8160. BIM_ACTION(enter_replace, ACTION_IS_RW,
  8161. "Enter replace mode."
  8162. )(void) {
  8163. env->mode = MODE_REPLACE;
  8164. set_history_break();
  8165. }
  8166. BIM_ACTION(toggle_numbers, 0,
  8167. "Toggle the display of line numbers."
  8168. )(void) {
  8169. env->numbers = !env->numbers;
  8170. redraw_all();
  8171. place_cursor_actual();
  8172. }
  8173. BIM_ACTION(toggle_gutter, 0,
  8174. "Toggle the display of the revision status gutter."
  8175. )(void) {
  8176. env->gutter = !env->gutter;
  8177. redraw_all();
  8178. place_cursor_actual();
  8179. }
  8180. BIM_ACTION(toggle_indent, 0,
  8181. "Toggle smart indentation."
  8182. )(void) {
  8183. env->indent = !env->indent;
  8184. redraw_statusbar();
  8185. place_cursor_actual();
  8186. }
  8187. BIM_ACTION(toggle_smartcomplete, 0,
  8188. "Toggle smart completion."
  8189. )(void) {
  8190. global_config.smart_complete = !global_config.smart_complete;
  8191. redraw_statusbar();
  8192. place_cursor_actual();
  8193. }
  8194. BIM_ACTION(expand_split_right, 0,
  8195. "Move the view split divider to the right."
  8196. )(void) {
  8197. global_config.split_percent += 1;
  8198. update_split_size();
  8199. redraw_all();
  8200. }
  8201. BIM_ACTION(expand_split_left, 0,
  8202. "Move the view split divider to the left."
  8203. )(void) {
  8204. global_config.split_percent -= 1;
  8205. update_split_size();
  8206. redraw_all();
  8207. }
  8208. BIM_ACTION(go_page_up, 0,
  8209. "Jump up a screenful."
  8210. )(void) {
  8211. goto_line(env->line_no - (global_config.term_height - 6));
  8212. }
  8213. BIM_ACTION(go_page_down, 0,
  8214. "Jump down a screenful."
  8215. )(void) {
  8216. goto_line(env->line_no + (global_config.term_height - 6));
  8217. }
  8218. BIM_ACTION(jump_to_matching_bracket, 0,
  8219. "Find and jump to the matching bracket for the character under the cursor."
  8220. )(void) {
  8221. recalculate_selected_lines();
  8222. int paren_line = -1, paren_col = -1;
  8223. find_matching_paren(&paren_line, &paren_col, 1);
  8224. if (paren_line != -1) {
  8225. env->line_no = paren_line;
  8226. env->col_no = paren_col;
  8227. set_preferred_column();
  8228. place_cursor_actual();
  8229. redraw_statusbar();
  8230. }
  8231. }
  8232. BIM_ACTION(jump_to_previous_blank, 0,
  8233. "Jump to the preceding blank line before the cursor."
  8234. )(void) {
  8235. env->col_no = 1;
  8236. if (env->line_no == 1) return;
  8237. do {
  8238. env->line_no--;
  8239. if (env->lines[env->line_no-1]->actual == 0) break;
  8240. } while (env->line_no > 1);
  8241. set_preferred_column();
  8242. redraw_statusbar();
  8243. }
  8244. BIM_ACTION(jump_to_next_blank, 0,
  8245. "Jump to the next blank line after the cursor."
  8246. )(void) {
  8247. env->col_no = 1;
  8248. if (env->line_no == env->line_count) return;
  8249. do {
  8250. env->line_no++;
  8251. if (env->lines[env->line_no-1]->actual == 0) break;
  8252. } while (env->line_no < env->line_count);
  8253. set_preferred_column();
  8254. redraw_statusbar();
  8255. }
  8256. BIM_ACTION(first_non_whitespace, 0,
  8257. "Jump to the first non-whitespace character in the current line."
  8258. )(void) {
  8259. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8260. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8261. env->col_no = i + 1;
  8262. break;
  8263. }
  8264. }
  8265. set_preferred_column();
  8266. redraw_statusbar();
  8267. }
  8268. BIM_ACTION(next_line_non_whitespace, 0,
  8269. "Jump to the first non-whitespace character in the next next line."
  8270. )(void) {
  8271. if (env->line_no < env->line_count) {
  8272. env->line_no++;
  8273. env->col_no = 1;
  8274. } else {
  8275. return;
  8276. }
  8277. first_non_whitespace();
  8278. }
  8279. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  8280. "Delete the preceding character, with special handling for indentation."
  8281. )(void) {
  8282. if (!env->tabs && env->col_no > 1) {
  8283. int i;
  8284. for (i = 0; i < env->col_no-1; ++i) {
  8285. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  8286. }
  8287. if (i == env->col_no-1) {
  8288. /* Backspace until aligned */
  8289. delete_at_cursor();
  8290. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  8291. delete_at_cursor();
  8292. }
  8293. return;
  8294. }
  8295. }
  8296. delete_at_cursor();
  8297. }
  8298. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  8299. "(temporary) Perform smart symbol competion from ctags."
  8300. )(void) {
  8301. /* This should probably be a submode */
  8302. while (omni_complete(0) == 1);
  8303. }
  8304. BIM_ACTION(smart_tab, ACTION_IS_RW,
  8305. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  8306. )(void) {
  8307. if (env->tabs) {
  8308. insert_char('\t');
  8309. } else {
  8310. for (int i = 0; i < env->tabstop; ++i) {
  8311. insert_char(' ');
  8312. }
  8313. }
  8314. }
  8315. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  8316. "Insert a `/` ending a C-style comment."
  8317. )(int c) {
  8318. /* smart *end* of comment anyway */
  8319. if (env->indent) {
  8320. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  8321. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  8322. (env->col_no > 3) &&
  8323. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  8324. env->col_no--;
  8325. replace_char('/');
  8326. env->col_no++;
  8327. place_cursor_actual();
  8328. return;
  8329. }
  8330. }
  8331. insert_char(c);
  8332. }
  8333. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  8334. "Insert a closing brace and smartly position it if it is the first character on a line."
  8335. )(int c) {
  8336. if (env->indent) {
  8337. int was_whitespace = 1;
  8338. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8339. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  8340. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  8341. was_whitespace = 0;
  8342. break;
  8343. }
  8344. }
  8345. insert_char(c);
  8346. if (was_whitespace) {
  8347. int line = -1, col = -1;
  8348. env->col_no--;
  8349. find_matching_paren(&line,&col, 1);
  8350. if (line != -1) {
  8351. line = find_brace_line_start(line, col);
  8352. while (env->lines[env->line_no-1]->actual) {
  8353. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  8354. }
  8355. add_indent(env->line_no-1,line-1,1);
  8356. env->col_no = env->lines[env->line_no-1]->actual + 1;
  8357. insert_char(c);
  8358. }
  8359. }
  8360. set_preferred_column();
  8361. return;
  8362. }
  8363. insert_char(c);
  8364. }
  8365. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  8366. "Enter line selection and move the cursor up one line."
  8367. )(void) {
  8368. enter_line_selection();
  8369. cursor_up();
  8370. }
  8371. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  8372. "Enter line selection and move the cursor down one line."
  8373. )(void) {
  8374. enter_line_selection();
  8375. cursor_down();
  8376. }
  8377. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  8378. "Shift the current line or screen view horiztonally, depending on settings."
  8379. )(int amount) {
  8380. env->coffset += amount;
  8381. if (env->coffset < 0) env->coffset = 0;
  8382. redraw_text();
  8383. }
  8384. static int state_before_paste = 0;
  8385. BIM_ACTION(paste_begin, 0, "Begin bracketed paste; disable indentation, completion, etc.")(void) {
  8386. if (global_config.smart_complete) state_before_paste |= 0x01;
  8387. if (env->indent) state_before_paste |= 0x02;
  8388. global_config.smart_complete = 0;
  8389. env->indent = 0;
  8390. /* TODO: We need env->loading == 1, but with history (manual breaks, though) */
  8391. }
  8392. BIM_ACTION(paste_end, 0, "End bracketed paste; restore indentation, completion, etc.")(void) {
  8393. if (state_before_paste & 0x01) global_config.smart_complete = 1;
  8394. if (state_before_paste & 0x02) env->indent = 1;
  8395. redraw_statusbar();
  8396. }
  8397. struct action_map _NORMAL_MAP[] = {
  8398. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  8399. {'V', enter_line_selection, 0, 0},
  8400. {'v', enter_char_selection, 0, 0},
  8401. {KEY_CTRL_V, enter_col_selection, 0, 0},
  8402. {'O', prepend_and_insert, opt_rw, 0},
  8403. {'o', append_and_insert, opt_rw, 0},
  8404. {'a', insert_after_cursor, opt_rw, 0},
  8405. {'s', delete_forward_and_insert, opt_rw, 0},
  8406. {'x', delete_forward, opt_rep | opt_rw, 0},
  8407. {'P', paste, opt_arg | opt_rw, -1},
  8408. {'p', paste, opt_arg | opt_rw, 1},
  8409. {'r', replace_char, opt_char | opt_rw, 0},
  8410. {'A', insert_at_end, opt_rw, 0},
  8411. {'u', undo_history, opt_rw, 0},
  8412. {KEY_CTRL_R, redo_history, opt_rw, 0},
  8413. {KEY_CTRL_L, redraw_all, 0, 0},
  8414. {KEY_CTRL_G, goto_definition, 0, 0},
  8415. {'i', enter_insert, opt_rw, 0},
  8416. {'R', enter_replace, opt_rw, 0},
  8417. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  8418. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  8419. {KEY_ALT_UP, previous_tab, 0, 0},
  8420. {KEY_ALT_DOWN, next_tab, 0, 0},
  8421. {-1, NULL, 0, 0},
  8422. };
  8423. struct action_map _INSERT_MAP[] = {
  8424. {KEY_ESCAPE, leave_insert, 0, 0},
  8425. {KEY_DELETE, delete_forward, 0, 0},
  8426. {KEY_CTRL_C, leave_insert, 0, 0},
  8427. {KEY_BACKSPACE, smart_backspace, 0, 0},
  8428. {KEY_ENTER, insert_line_feed, 0, 0},
  8429. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  8430. {KEY_CTRL_V, insert_char, opt_byte, 0},
  8431. {KEY_CTRL_W, delete_word, 0, 0},
  8432. {'\t', smart_tab, 0, 0},
  8433. {'/', smart_comment_end, opt_arg, '/'},
  8434. {'}', smart_brace_end, opt_arg, '}'},
  8435. {KEY_PASTE_BEGIN, paste_begin, 0, 0},
  8436. {KEY_PASTE_END, paste_end, 0, 0},
  8437. {-1, NULL, 0, 0},
  8438. };
  8439. struct action_map _REPLACE_MAP[] = {
  8440. {KEY_ESCAPE, leave_insert, 0, 0},
  8441. {KEY_DELETE, delete_forward, 0, 0},
  8442. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8443. {KEY_ENTER, insert_line_feed, 0, 0},
  8444. {-1, NULL, 0, 0},
  8445. };
  8446. struct action_map _LINE_SELECTION_MAP[] = {
  8447. {KEY_ESCAPE, leave_selection, 0, 0},
  8448. {KEY_CTRL_C, leave_selection, 0, 0},
  8449. {'V', leave_selection, 0, 0},
  8450. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  8451. {'y', yank_lines, opt_norm, 0},
  8452. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8453. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  8454. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  8455. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8456. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8457. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8458. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  8459. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  8460. {KEY_SHIFT_UP, cursor_up, 0, 0},
  8461. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  8462. {-1, NULL, 0, 0},
  8463. };
  8464. struct action_map _CHAR_SELECTION_MAP[] = {
  8465. {KEY_ESCAPE, leave_selection, 0, 0},
  8466. {KEY_CTRL_C, leave_selection, 0, 0},
  8467. {'v', leave_selection, 0, 0},
  8468. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  8469. {'y', yank_characters, opt_norm, 0},
  8470. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8471. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8472. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8473. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8474. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  8475. {'r', replace_chars, opt_char | opt_rw, 0},
  8476. {'A', insert_at_end_of_selection, opt_rw, 0},
  8477. {-1, NULL, 0, 0},
  8478. };
  8479. struct action_map _COL_SELECTION_MAP[] = {
  8480. {KEY_ESCAPE, leave_selection, 0, 0},
  8481. {KEY_CTRL_C, leave_selection, 0, 0},
  8482. {KEY_CTRL_V, leave_selection, 0, 0},
  8483. {'I', enter_col_insert, opt_rw, 0},
  8484. {'a', enter_col_insert_after, opt_rw, 0},
  8485. {'d', delete_column, opt_norm | opt_rw, 0},
  8486. {-1, NULL, 0, 0},
  8487. };
  8488. struct action_map _COL_INSERT_MAP[] = {
  8489. {KEY_ESCAPE, leave_selection, 0, 0},
  8490. {KEY_CTRL_C, leave_selection, 0, 0},
  8491. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  8492. {KEY_DELETE, delete_at_column, opt_arg, 1},
  8493. {KEY_ENTER, NULL, 0, 0},
  8494. {KEY_CTRL_W, NULL, 0, 0},
  8495. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  8496. {-1, NULL, 0, 0},
  8497. };
  8498. struct action_map _NAVIGATION_MAP[] = {
  8499. /* Common navigation */
  8500. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  8501. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  8502. {':', enter_command, 0, 0},
  8503. {'/', enter_search, opt_arg, 1},
  8504. {'?', enter_search, opt_arg, 0},
  8505. {'n', search_next, opt_rep, 0},
  8506. {'N', search_prev, opt_rep, 0},
  8507. {'j', cursor_down, opt_rep, 0},
  8508. {'k', cursor_up, opt_rep, 0},
  8509. {'h', cursor_left, opt_rep, 0},
  8510. {'l', cursor_right, opt_rep, 0},
  8511. {'b', word_left, opt_rep, 0},
  8512. {'w', word_right, opt_rep, 0},
  8513. {'B', big_word_left, opt_rep, 0},
  8514. {'W', big_word_right, opt_rep, 0},
  8515. {'<', shift_horizontally, opt_arg, -1},
  8516. {'>', shift_horizontally, opt_arg, 1},
  8517. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  8518. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  8519. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  8520. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  8521. {'G', goto_line, opt_nav, 0},
  8522. {'*', search_under_cursor, 0, 0},
  8523. {' ', go_page_down, opt_rep, 0},
  8524. {'%', jump_to_matching_bracket, 0, 0},
  8525. {'{', jump_to_previous_blank, opt_rep, 0},
  8526. {'}', jump_to_next_blank, opt_rep, 0},
  8527. {'$', cursor_end, 0, 0},
  8528. {'|', cursor_home, 0, 0},
  8529. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  8530. {'^', first_non_whitespace, 0, 0},
  8531. {'0', cursor_home, 0, 0},
  8532. {-1, NULL, 0, 0},
  8533. };
  8534. struct action_map _ESCAPE_MAP[] = {
  8535. {KEY_F1, toggle_numbers, 0, 0},
  8536. {KEY_F2, toggle_indent, 0, 0},
  8537. {KEY_F3, toggle_gutter, 0, 0},
  8538. {KEY_F4, toggle_smartcomplete, 0, 0},
  8539. {KEY_MOUSE, handle_mouse, 0, 0},
  8540. {KEY_MOUSE_SGR, handle_mouse_sgr, 0, 0},
  8541. {KEY_UP, cursor_up, opt_rep, 0},
  8542. {KEY_DOWN, cursor_down, opt_rep, 0},
  8543. {KEY_RIGHT, cursor_right, opt_rep, 0},
  8544. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  8545. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  8546. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  8547. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  8548. {KEY_LEFT, cursor_left, opt_rep, 0},
  8549. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  8550. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  8551. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  8552. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  8553. {KEY_HOME, cursor_home, 0, 0},
  8554. {KEY_END, cursor_end, 0, 0},
  8555. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  8556. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  8557. {KEY_CTRL_Z, suspend, 0, 0},
  8558. {-1, NULL, 0, 0}
  8559. };
  8560. struct action_map _COMMAND_MAP[] = {
  8561. {KEY_ENTER, command_accept, 0, 0},
  8562. {'\t', command_tab_complete_buffer, 0, 0},
  8563. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  8564. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  8565. {-1, NULL, 0, 0}
  8566. };
  8567. struct action_map _SEARCH_MAP[] = {
  8568. {KEY_ENTER, search_accept, 0, 0},
  8569. {KEY_UP, NULL, 0, 0},
  8570. {KEY_DOWN, NULL, 0, 0},
  8571. {-1, NULL, 0, 0}
  8572. };
  8573. struct action_map _INPUT_BUFFER_MAP[] = {
  8574. /* These are generic and shared with search */
  8575. {KEY_ESCAPE, command_discard, 0, 0},
  8576. {KEY_CTRL_C, command_discard, 0, 0},
  8577. {KEY_BACKSPACE, command_backspace, 0, 0},
  8578. {KEY_CTRL_W, command_word_delete, 0, 0},
  8579. {KEY_MOUSE, eat_mouse, 0, 0},
  8580. {KEY_LEFT, command_cursor_left, 0, 0},
  8581. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  8582. {KEY_RIGHT, command_cursor_right, 0, 0},
  8583. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  8584. {KEY_HOME, command_cursor_home, 0, 0},
  8585. {KEY_END, command_cursor_end, 0, 0},
  8586. {-1, NULL, 0, 0}
  8587. };
  8588. /* DIRECTORY_BROWSE_MAP is only to override KEY_ENTER and should not be remapped,
  8589. * so unlike the others it is not going to be redefined as a pointer. */
  8590. struct action_map DIRECTORY_BROWSE_MAP[] = {
  8591. {KEY_ENTER, open_file_from_line, 0, 0},
  8592. {-1, NULL, 0, 0}
  8593. };
  8594. struct action_map * NORMAL_MAP = NULL;
  8595. struct action_map * INSERT_MAP = NULL;
  8596. struct action_map * REPLACE_MAP = NULL;
  8597. struct action_map * LINE_SELECTION_MAP = NULL;
  8598. struct action_map * CHAR_SELECTION_MAP = NULL;
  8599. struct action_map * COL_SELECTION_MAP = NULL;
  8600. struct action_map * COL_INSERT_MAP = NULL;
  8601. struct action_map * NAVIGATION_MAP = NULL;
  8602. struct action_map * ESCAPE_MAP = NULL;
  8603. struct action_map * COMMAND_MAP = NULL;
  8604. struct action_map * SEARCH_MAP = NULL;
  8605. struct action_map * INPUT_BUFFER_MAP = NULL;
  8606. struct mode_names mode_names[] = {
  8607. {"Normal","norm",&NORMAL_MAP},
  8608. {"Insert","insert",&INSERT_MAP},
  8609. {"Replace","replace",&REPLACE_MAP},
  8610. {"Line Selection","line",&LINE_SELECTION_MAP},
  8611. {"Char Selection","char",&CHAR_SELECTION_MAP},
  8612. {"Col Selection","col",&COL_SELECTION_MAP},
  8613. {"Col Insert","colinsert",&COL_INSERT_MAP},
  8614. {"Navigation (Select)","nav",&NAVIGATION_MAP},
  8615. {"Escape (Select, Insert)","esc",&ESCAPE_MAP},
  8616. {"Command","command",&COMMAND_MAP},
  8617. {"Search","search",&SEARCH_MAP},
  8618. {"Input (Command, Search)","input",&INPUT_BUFFER_MAP},
  8619. {NULL,NULL,NULL},
  8620. };
  8621. int handle_action(struct action_map * basemap, int key) {
  8622. for (struct action_map * map = basemap; map->key != -1; map++) {
  8623. if (map->key == key) {
  8624. if (!map->method) return 1;
  8625. if ((map->options & opt_rw) && (env->readonly)) {
  8626. render_error("Buffer is read-only");
  8627. return 2;
  8628. }
  8629. /* Determine how to format this request */
  8630. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  8631. int c = 0;
  8632. if (map->options & opt_char) {
  8633. c = read_one_character(name_from_key(key));
  8634. }
  8635. if (map->options & opt_byte) {
  8636. c = read_one_byte(name_from_key(key));
  8637. }
  8638. for (int i = 0; i < reps; ++i) {
  8639. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  8640. map->method(map->arg, c);
  8641. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  8642. map->method(c);
  8643. } else if (map->options & opt_arg) {
  8644. map->method(map->arg);
  8645. } else if (map->options & opt_nav) {
  8646. if (nav_buffer) {
  8647. map->method(atoi(nav_buf));
  8648. reset_nav_buffer(0);
  8649. } else {
  8650. map->method(-1);
  8651. }
  8652. } else {
  8653. map->method();
  8654. }
  8655. }
  8656. if (map->options & opt_norm) {
  8657. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  8658. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  8659. else {
  8660. env->mode = MODE_NORMAL;
  8661. redraw_all();
  8662. }
  8663. }
  8664. return 1;
  8665. }
  8666. }
  8667. return 0;
  8668. }
  8669. int handle_nav_buffer(int key) {
  8670. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  8671. if (nav_buffer < NAV_BUFFER_MAX) {
  8672. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  8673. nav_buf[nav_buffer] = key;
  8674. nav_buf[nav_buffer+1] = 0;
  8675. nav_buffer++;
  8676. /* Print the number buffer */
  8677. redraw_commandline();
  8678. }
  8679. return 0;
  8680. }
  8681. return 1;
  8682. }
  8683. /**
  8684. * NORMAL mode
  8685. *
  8686. * Default editor mode - just cursor navigation and keybinds
  8687. * to enter the other modes.
  8688. */
  8689. void normal_mode(void) {
  8690. int last_mode = MODE_NORMAL;
  8691. int refresh = 0;
  8692. while (1) {
  8693. if (global_config.overlay_mode) {
  8694. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  8695. if (refresh) {
  8696. render_command_input_buffer();
  8697. refresh = 0;
  8698. }
  8699. int key = bim_getkey(200);
  8700. if (key != KEY_TIMEOUT) {
  8701. refresh = 1;
  8702. if (!handle_action(COMMAND_MAP, key))
  8703. if (!handle_action(INPUT_BUFFER_MAP, key))
  8704. if (key < KEY_ESCAPE) command_insert_char(key);
  8705. }
  8706. continue;
  8707. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8708. if (refresh) {
  8709. render_command_input_buffer();
  8710. refresh = 0;
  8711. }
  8712. int key = bim_getkey(200);
  8713. if (key != KEY_TIMEOUT) {
  8714. refresh = 1;
  8715. if (!handle_action(SEARCH_MAP, key)) {
  8716. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  8717. if (key < KEY_ESCAPE) command_insert_char(key);
  8718. }
  8719. }
  8720. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8721. /* Find the next search match */
  8722. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  8723. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  8724. buffer[i] = global_config.command_buffer->text[i].codepoint;
  8725. }
  8726. buffer[global_config.command_buffer->actual] = 0;
  8727. int line = -1, col = -1;
  8728. if (global_config.search_direction == 1) {
  8729. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  8730. if (line == -1 && global_config.search_wraps) {
  8731. find_match(1, 1, &line, &col, buffer, NULL);
  8732. }
  8733. } else {
  8734. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  8735. if (line == -1 && global_config.search_wraps) {
  8736. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, buffer);
  8737. }
  8738. }
  8739. if (line != -1) {
  8740. env->col_no = col;
  8741. env->line_no = line;
  8742. set_preferred_column();
  8743. } else {
  8744. env->coffset = global_config.prev_coffset;
  8745. env->offset = global_config.prev_offset;
  8746. env->col_no = global_config.prev_col;
  8747. set_preferred_column();
  8748. env->line_no = global_config.prev_line;
  8749. }
  8750. draw_search_match(buffer, 0);
  8751. free(buffer);
  8752. }
  8753. }
  8754. continue;
  8755. }
  8756. }
  8757. if (env->mode != last_mode) {
  8758. redraw_statusbar();
  8759. redraw_commandline();
  8760. last_mode = env->mode;
  8761. }
  8762. if (env->mode == MODE_NORMAL) {
  8763. place_cursor_actual();
  8764. int key = bim_getkey(200);
  8765. if (handle_nav_buffer(key)) {
  8766. if (!handle_action(NORMAL_MAP, key))
  8767. if (!handle_action(NAVIGATION_MAP, key))
  8768. handle_action(ESCAPE_MAP, key);
  8769. }
  8770. reset_nav_buffer(key);
  8771. } else if (env->mode == MODE_INSERT) {
  8772. place_cursor_actual();
  8773. int key = bim_getkey(refresh ? 10 : 200);
  8774. if (key == KEY_TIMEOUT) {
  8775. if (refresh > 1) {
  8776. redraw_text();
  8777. } else if (refresh) {
  8778. redraw_line(env->line_no-1);
  8779. }
  8780. refresh = 0;
  8781. } else if (handle_action(INSERT_MAP, key)) {
  8782. refresh = 2;
  8783. } else if (handle_action(ESCAPE_MAP, key)) {
  8784. /* Do nothing */
  8785. } else if (key < KEY_ESCAPE) {
  8786. insert_char(key);
  8787. if (global_config.smart_complete) {
  8788. redraw_line(env->line_no-1);
  8789. while (omni_complete(1) == 1);
  8790. }
  8791. refresh |= 1;
  8792. }
  8793. } else if (env->mode == MODE_REPLACE) {
  8794. place_cursor_actual();
  8795. int key = bim_getkey(200);
  8796. if (key != KEY_TIMEOUT) {
  8797. if (handle_action(REPLACE_MAP, key)) {
  8798. redraw_text();
  8799. } else if (!handle_action(ESCAPE_MAP, key)) {
  8800. /* Perform replacement */
  8801. if (key < KEY_ESCAPE) {
  8802. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  8803. replace_char(key);
  8804. env->col_no += 1;
  8805. } else {
  8806. insert_char(key);
  8807. redraw_line(env->line_no-1);
  8808. }
  8809. set_preferred_column();
  8810. }
  8811. }
  8812. }
  8813. } else if (env->mode == MODE_LINE_SELECTION) {
  8814. place_cursor_actual();
  8815. int key = bim_getkey(200);
  8816. if (key == KEY_TIMEOUT) continue;
  8817. if (handle_nav_buffer(key)) {
  8818. if (!handle_action(LINE_SELECTION_MAP, key))
  8819. if (!handle_action(NAVIGATION_MAP, key))
  8820. handle_action(ESCAPE_MAP, key);
  8821. }
  8822. reset_nav_buffer(key);
  8823. if (env->mode == MODE_LINE_SELECTION) {
  8824. /* Mark current line */
  8825. _redraw_line(env->line_no,0);
  8826. _redraw_line(env->start_line,1);
  8827. /* Properly mark everything in the span we just moved through */
  8828. if (env->prev_line < env->line_no) {
  8829. for (int i = env->prev_line; i < env->line_no; ++i) {
  8830. _redraw_line(i,0);
  8831. }
  8832. env->prev_line = env->line_no;
  8833. } else if (env->prev_line > env->line_no) {
  8834. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8835. _redraw_line(i,0);
  8836. }
  8837. env->prev_line = env->line_no;
  8838. }
  8839. redraw_commandline();
  8840. }
  8841. } else if (env->mode == MODE_CHAR_SELECTION) {
  8842. place_cursor_actual();
  8843. int key = bim_getkey(200);
  8844. if (key == KEY_TIMEOUT) continue;
  8845. if (handle_nav_buffer(key)) {
  8846. if (!handle_action(CHAR_SELECTION_MAP, key))
  8847. if (!handle_action(NAVIGATION_MAP, key))
  8848. handle_action(ESCAPE_MAP, key);
  8849. }
  8850. reset_nav_buffer(key);
  8851. if (env->mode == MODE_CHAR_SELECTION) {
  8852. /* Mark current line */
  8853. _redraw_line_char(env->line_no,1);
  8854. /* Properly mark everything in the span we just moved through */
  8855. if (env->prev_line < env->line_no) {
  8856. for (int i = env->prev_line; i < env->line_no; ++i) {
  8857. _redraw_line_char(i,1);
  8858. }
  8859. env->prev_line = env->line_no;
  8860. } else if (env->prev_line > env->line_no) {
  8861. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8862. _redraw_line_char(i,1);
  8863. }
  8864. env->prev_line = env->line_no;
  8865. }
  8866. }
  8867. } else if (env->mode == MODE_COL_SELECTION) {
  8868. place_cursor_actual();
  8869. int key = bim_getkey(200);
  8870. if (key == KEY_TIMEOUT) continue;
  8871. if (handle_nav_buffer(key)) {
  8872. if (!handle_action(COL_SELECTION_MAP, key))
  8873. if (!handle_action(NAVIGATION_MAP, key))
  8874. handle_action(ESCAPE_MAP, key);
  8875. }
  8876. reset_nav_buffer(key);
  8877. if (env->mode == MODE_COL_SELECTION) {
  8878. _redraw_line_col(env->line_no, 0);
  8879. /* Properly mark everything in the span we just moved through */
  8880. if (env->prev_line < env->line_no) {
  8881. for (int i = env->prev_line; i < env->line_no; ++i) {
  8882. _redraw_line_col(i,0);
  8883. }
  8884. env->prev_line = env->line_no;
  8885. } else if (env->prev_line > env->line_no) {
  8886. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8887. _redraw_line_col(i,0);
  8888. }
  8889. env->prev_line = env->line_no;
  8890. }
  8891. redraw_commandline();
  8892. }
  8893. } else if (env->mode == MODE_COL_INSERT) {
  8894. int key = bim_getkey(refresh ? 10 : 200);
  8895. if (key == KEY_TIMEOUT) {
  8896. if (refresh) {
  8897. redraw_commandline();
  8898. redraw_text();
  8899. }
  8900. refresh = 0;
  8901. } else if (handle_action(COL_INSERT_MAP, key)) {
  8902. /* pass */
  8903. } else if (key < KEY_ESCAPE) {
  8904. insert_char_at_column(key);
  8905. refresh = 1;
  8906. }
  8907. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  8908. place_cursor_actual();
  8909. int key = bim_getkey(200);
  8910. if (handle_nav_buffer(key)) {
  8911. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  8912. if (!handle_action(NAVIGATION_MAP, key))
  8913. handle_action(ESCAPE_MAP, key);
  8914. }
  8915. reset_nav_buffer(key);
  8916. }
  8917. }
  8918. }
  8919. /**
  8920. * Show help text for -?
  8921. */
  8922. static void show_usage(char * argv[]) {
  8923. #define _s "\033[3m"
  8924. #define _e "\033[0m\n"
  8925. printf(
  8926. "bim - Text editor\n"
  8927. "\n"
  8928. "usage: %s [options] [file]\n"
  8929. " %s [options] -- -\n"
  8930. "\n"
  8931. " -R " _s "open initial buffer read-only" _e
  8932. " -O " _s "set various options:" _e
  8933. " noscroll " _s "disable terminal scrolling" _e
  8934. " noaltscreen " _s "disable alternate screen buffer" _e
  8935. " nomouse " _s "disable mouse support" _e
  8936. " nounicode " _s "disable unicode display" _e
  8937. " nobright " _s "disable bright next" _e
  8938. " nohideshow " _s "disable togglging cursor visibility" _e
  8939. " nosyntax " _s "disable syntax highlighting on load" _e
  8940. " notitle " _s "disable title-setting escapes" _e
  8941. " history " _s "enable experimental undo/redo" _e
  8942. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  8943. " " _s "-C includes line numbers, -c does not" _e
  8944. " -u " _s "override bimrc file" _e
  8945. " -? " _s "show this help text" _e
  8946. "\n"
  8947. "Long options:\n"
  8948. " --help " _s "show this help text" _e
  8949. " --version " _s "show version information and available plugins" _e
  8950. " --dump-mappings " _s "dump markdown description of key mappings" _e
  8951. " --dump-commands " _s "dump markdown description of all commands" _e
  8952. " --dump-config " _s "dump key mappings as a bimscript" _e
  8953. " --html FILE " _s "convert FILE to syntax-highlighted HTML" _e
  8954. "\n", argv[0], argv[0]);
  8955. #undef _e
  8956. #undef _s
  8957. }
  8958. void free_function(struct bim_function * func) {
  8959. do {
  8960. struct bim_function * next = func->next;
  8961. free(func->command);
  8962. free(func);
  8963. func = next;
  8964. } while (func);
  8965. }
  8966. int run_function(char * name) {
  8967. for (int i = 0; i < flex_user_functions_count; ++i) {
  8968. if (user_functions[i] && !strcmp(user_functions[i]->command, name)) {
  8969. /* Execute function */
  8970. struct bim_function * this = user_functions[i]->next;
  8971. while (this) {
  8972. char * tmp = strdup(this->command);
  8973. int result = process_command(tmp);
  8974. free(tmp);
  8975. if (result != 0) {
  8976. return result;
  8977. }
  8978. this = this->next;
  8979. }