bim.c 276 KB

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