bim.c 330 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119
  1. /**
  2. * This is a baked, single-file version of bim.
  3. * It was built Thu Oct 31 12:34:51 2019
  4. * It is based on git commit 50936d4d1f47720fc0ef1151b0102d3d53a3f5f3
  5. */
  6. #define GIT_TAG "50936d4-baked"
  7. /* Bim - A Text Editor
  8. *
  9. * Copyright (C) 2012-2019 K. Lange
  10. *
  11. * Permission to use, copy, modify, and/or distribute this software for any
  12. * purpose with or without fee is hereby granted, provided that the above
  13. * copyright notice and this permission notice appear in all copies.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  16. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  17. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  18. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  21. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22. */
  23. /* Included from bim-core.h */
  24. #define _XOPEN_SOURCE 700
  25. #define _DARWIN_C_SOURCE
  26. #define _DEFAULT_SOURCE
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <termios.h>
  34. #include <signal.h>
  35. #include <locale.h>
  36. #include <wchar.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <poll.h>
  40. #include <limits.h>
  41. #include <sys/types.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/stat.h>
  44. #ifdef __TIMESTAMP__
  45. # define BIM_BUILD_DATE " built " __TIMESTAMP__
  46. #else
  47. # define BIM_BUILD_DATE DATE ""
  48. #endif
  49. #ifdef GIT_TAG
  50. # define TAG "-" GIT_TAG
  51. #else
  52. # define TAG ""
  53. #endif
  54. #define BIM_VERSION "2.1.3" TAG
  55. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  56. #define BLOCK_SIZE 4096
  57. #define ENTER_KEY '\r'
  58. #define LINE_FEED '\n'
  59. #define BACKSPACE_KEY 0x08
  60. #define DELETE_KEY 0x7F
  61. enum Key {
  62. KEY_TIMEOUT = -1,
  63. KEY_CTRL_AT = 0, /* Base */
  64. KEY_CTRL_A, KEY_CTRL_B, KEY_CTRL_C, KEY_CTRL_D, KEY_CTRL_E, KEY_CTRL_F, KEY_CTRL_G, KEY_CTRL_H,
  65. KEY_CTRL_I, KEY_CTRL_J, KEY_CTRL_K, KEY_CTRL_L, KEY_CTRL_M, KEY_CTRL_N, KEY_CTRL_O, KEY_CTRL_P,
  66. KEY_CTRL_Q, KEY_CTRL_R, KEY_CTRL_S, KEY_CTRL_T, KEY_CTRL_U, KEY_CTRL_V, KEY_CTRL_W, KEY_CTRL_X,
  67. KEY_CTRL_Y, KEY_CTRL_Z, /* Note we keep ctrl-z mapped in termios as suspend */
  68. KEY_CTRL_OPEN, KEY_CTRL_BACKSLASH, KEY_CTRL_CLOSE, KEY_CTRL_CARAT, KEY_CTRL_UNDERSCORE,
  69. /* Space... */
  70. /* Some of these are equivalent to things above */
  71. KEY_BACKSPACE = 0x08,
  72. KEY_LINEFEED = '\n',
  73. KEY_ENTER = '\r',
  74. KEY_TAB = '\t',
  75. /* Basic printable characters go here. */
  76. /* Delete is special */
  77. KEY_DELETE = 0x7F,
  78. /* Unicode codepoints go here */
  79. KEY_ESCAPE = 0x400000, /* Escape would normally be 27, but is special because reasons */
  80. KEY_F1, KEY_F2, KEY_F3, KEY_F4, /* TODO other F keys */
  81. KEY_MOUSE, /* Must be followed with a 3-byte mouse read */
  82. KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN,
  83. KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT,
  84. KEY_SHIFT_UP, KEY_SHIFT_DOWN, KEY_SHIFT_RIGHT, KEY_SHIFT_LEFT,
  85. KEY_CTRL_UP, KEY_CTRL_DOWN, KEY_CTRL_RIGHT, KEY_CTRL_LEFT,
  86. KEY_ALT_UP, KEY_ALT_DOWN, KEY_ALT_RIGHT, KEY_ALT_LEFT,
  87. KEY_ALT_SHIFT_UP, KEY_ALT_SHIFT_DOWN, KEY_ALT_SHIFT_RIGHT, KEY_ALT_SHIFT_LEFT,
  88. KEY_SHIFT_TAB,
  89. };
  90. struct key_name_map {
  91. enum Key keycode;
  92. char * name;
  93. };
  94. extern struct key_name_map KeyNames[];
  95. /**
  96. * Syntax highlighting flags.
  97. */
  98. #define FLAG_NONE 0
  99. #define FLAG_KEYWORD 1
  100. #define FLAG_STRING 2
  101. #define FLAG_COMMENT 3
  102. #define FLAG_TYPE 4
  103. #define FLAG_PRAGMA 5
  104. #define FLAG_NUMERAL 6
  105. #define FLAG_ERROR 7
  106. #define FLAG_DIFFPLUS 8
  107. #define FLAG_DIFFMINUS 9
  108. #define FLAG_NOTICE 10
  109. #define FLAG_BOLD 11
  110. #define FLAG_LINK 12
  111. #define FLAG_ESCAPE 13
  112. #define FLAG_SELECT (1 << 5)
  113. #define FLAG_SEARCH (1 << 6)
  114. /**
  115. * Line buffer definitions
  116. *
  117. * Lines are essentially resizable vectors of char_t structs,
  118. * which represent single codepoints in the file.
  119. */
  120. typedef struct {
  121. uint32_t display_width:4;
  122. uint32_t flags:7;
  123. uint32_t codepoint:21;
  124. } __attribute__((packed)) char_t;
  125. /**
  126. * Lines have available and actual lengths, describing
  127. * how much space was allocated vs. how much is being
  128. * used at the moment.
  129. */
  130. typedef struct {
  131. int available;
  132. int actual;
  133. int istate;
  134. int is_current;
  135. int rev_status;
  136. char_t text[];
  137. } line_t;
  138. /**
  139. * Global configuration state
  140. *
  141. * At the moment, this is all in a global, but in the future
  142. * this should be passed around to various functions.
  143. */
  144. typedef struct {
  145. /* Terminal size */
  146. int term_width, term_height;
  147. int bottom_size;
  148. line_t ** yanks;
  149. size_t yank_count;
  150. int yank_is_full_lines;
  151. int tty_in;
  152. const char * bimrc_path;
  153. const char * syntax_fallback;
  154. uint32_t * search;
  155. int overlay_mode;
  156. line_t * command_buffer;
  157. int command_offset, command_col_no;
  158. struct syntax_definition * command_syn, * command_syn_back;
  159. int history_point;
  160. int search_direction;
  161. int prev_line, prev_col, prev_coffset, prev_offset;
  162. unsigned int highlight_on_open:1;
  163. unsigned int initial_file_is_read_only:1;
  164. unsigned int go_to_line:1;
  165. unsigned int break_from_selection:1;
  166. unsigned int can_scroll:1;
  167. unsigned int can_hideshow:1;
  168. unsigned int can_altscreen:1;
  169. unsigned int can_mouse:1;
  170. unsigned int can_unicode:1;
  171. unsigned int can_bright:1;
  172. unsigned int can_title:1;
  173. unsigned int can_bce:1;
  174. unsigned int can_24bit:1;
  175. unsigned int can_256color:1;
  176. unsigned int can_italic:1;
  177. unsigned int history_enabled:1;
  178. unsigned int highlight_parens:1;
  179. unsigned int smart_case:1;
  180. unsigned int highlight_current_line:1;
  181. unsigned int shift_scrolling:1;
  182. unsigned int check_git:1;
  183. unsigned int color_gutter:1;
  184. unsigned int relative_lines:1;
  185. unsigned int numbers:1;
  186. unsigned int horizontal_shift_scrolling:1;
  187. int cursor_padding;
  188. int split_percent;
  189. int scroll_amount;
  190. } global_config_t;
  191. #define OVERLAY_MODE_NONE 0
  192. #define OVERLAY_MODE_READ_ONE 1
  193. #define OVERLAY_MODE_COMMAND 2
  194. #define OVERLAY_MODE_SEARCH 3
  195. #define OVERLAY_MODE_COMPLETE 4
  196. #define HISTORY_SENTINEL 0
  197. #define HISTORY_INSERT 1
  198. #define HISTORY_DELETE 2
  199. #define HISTORY_REPLACE 3
  200. #define HISTORY_REMOVE_LINE 4
  201. #define HISTORY_ADD_LINE 5
  202. #define HISTORY_REPLACE_LINE 6
  203. #define HISTORY_MERGE_LINES 7
  204. #define HISTORY_SPLIT_LINE 8
  205. #define HISTORY_BREAK 10
  206. typedef struct history {
  207. struct history * previous;
  208. struct history * next;
  209. int type;
  210. int line;
  211. int col;
  212. union {
  213. struct {
  214. int lineno;
  215. int offset;
  216. int codepoint;
  217. int old_codepoint;
  218. } insert_delete_replace;
  219. struct {
  220. int lineno;
  221. line_t * contents;
  222. line_t * old_contents;
  223. } remove_replace_line;
  224. struct {
  225. int lineno;
  226. int split;
  227. } add_merge_split_lines;
  228. } contents;
  229. } history_t;
  230. /**
  231. * Buffer data
  232. *
  233. * A buffer describes a file, and stores
  234. * its name as well as the editor state
  235. * (cursor offsets, etc.) and the actual
  236. * line buffers.
  237. */
  238. typedef struct _env {
  239. unsigned int loading:1;
  240. unsigned int tabs:1;
  241. unsigned int modified:1;
  242. unsigned int readonly:1;
  243. unsigned int indent:1;
  244. unsigned int checkgitstatusonwrite:1;
  245. unsigned int crnl:1;
  246. int highlighting_paren;
  247. short mode;
  248. short tabstop;
  249. char * file_name;
  250. int offset;
  251. int coffset;
  252. int line_no;
  253. int line_count;
  254. int line_avail;
  255. int col_no;
  256. int preferred_column;
  257. struct syntax_definition * syntax;
  258. line_t ** lines;
  259. history_t * history;
  260. history_t * last_save_history;
  261. int width;
  262. int left;
  263. int start_line;
  264. int sel_col;
  265. int start_col;
  266. int prev_line;
  267. } buffer_t;
  268. struct theme_def {
  269. const char * name;
  270. void (*load)(void);
  271. };
  272. extern struct theme_def * themes;
  273. extern void add_colorscheme(struct theme_def theme);
  274. struct syntax_state {
  275. line_t * line;
  276. int line_no;
  277. int state;
  278. int i;
  279. };
  280. struct syntax_definition {
  281. char * name;
  282. char ** ext;
  283. int (*calculate)(struct syntax_state *);
  284. int prefers_spaces;
  285. };
  286. extern struct syntax_definition * syntaxes;
  287. /**
  288. * Editor mode states
  289. */
  290. #define MODE_NORMAL 0
  291. #define MODE_INSERT 1
  292. #define MODE_LINE_SELECTION 2
  293. #define MODE_REPLACE 3
  294. #define MODE_CHAR_SELECTION 4
  295. #define MODE_COL_SELECTION 5
  296. #define MODE_COL_INSERT 6
  297. #define MODE_DIRECTORY_BROWSE 7
  298. extern global_config_t global_config;
  299. extern const char * COLOR_FG;
  300. extern const char * COLOR_BG;
  301. extern const char * COLOR_ALT_FG;
  302. extern const char * COLOR_ALT_BG;
  303. extern const char * COLOR_NUMBER_FG;
  304. extern const char * COLOR_NUMBER_BG;
  305. extern const char * COLOR_STATUS_FG;
  306. extern const char * COLOR_STATUS_BG;
  307. extern const char * COLOR_TABBAR_BG;
  308. extern const char * COLOR_TAB_BG;
  309. extern const char * COLOR_ERROR_FG;
  310. extern const char * COLOR_ERROR_BG;
  311. extern const char * COLOR_SEARCH_FG;
  312. extern const char * COLOR_SEARCH_BG;
  313. extern const char * COLOR_KEYWORD;
  314. extern const char * COLOR_STRING;
  315. extern const char * COLOR_COMMENT;
  316. extern const char * COLOR_TYPE;
  317. extern const char * COLOR_PRAGMA;
  318. extern const char * COLOR_NUMERAL;
  319. extern const char * COLOR_SELECTFG;
  320. extern const char * COLOR_SELECTBG;
  321. extern const char * COLOR_RED;
  322. extern const char * COLOR_GREEN;
  323. extern const char * COLOR_BOLD;
  324. extern const char * COLOR_LINK;
  325. extern const char * COLOR_ESCAPE;
  326. extern const char * current_theme;
  327. struct action_def {
  328. char * name;
  329. void (*action)();
  330. int options;
  331. const char * description;
  332. };
  333. extern struct action_def * mappable_actions;
  334. #define ARG_IS_INPUT 0x01 /* Takes the key that triggered it as the first argument */
  335. #define ARG_IS_CUSTOM 0x02 /* Takes a custom argument which is specific to the method */
  336. #define ARG_IS_PROMPT 0x04 /* Prompts for an argument. */
  337. #define ACTION_IS_RW 0x08 /* Needs to be able to write. */
  338. #define BIM_ACTION(name, options, description) \
  339. void name (); /* Define the action with unknown arguments */ \
  340. void __attribute__((constructor)) _install_ ## name (void) { \
  341. add_action((struct action_def){#name, name, options, description}); \
  342. } \
  343. void name
  344. struct command_def {
  345. char * name;
  346. int (*command)(char *, int, char * arg[]);
  347. const char * description;
  348. };
  349. #define BIM_COMMAND(cmd_name, cmd_str, description) \
  350. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  351. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  352. add_command((struct command_def){cmd_str, bim_command_ ## cmd_name, description}); \
  353. } \
  354. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  355. #define BIM_ALIAS(alias, alias_name, cmd_name) \
  356. void __attribute__((constructor)) _install_alias_ ## alias_name (void) { \
  357. add_command((struct command_def){alias, bim_command_ ## cmd_name, "Alias for " #cmd_name}); \
  358. }
  359. #define BIM_PREFIX_COMMAND(cmd_name, cmd_prefix, description) \
  360. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  361. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  362. add_prefix_command((struct command_def){cmd_prefix, bim_command_ ## cmd_name, description}); \
  363. } \
  364. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  365. extern buffer_t * env;
  366. extern buffer_t * left_buffer;
  367. extern buffer_t * right_buffer;
  368. #define NAV_BUFFER_MAX 10
  369. extern char nav_buf[NAV_BUFFER_MAX+1];
  370. extern int nav_buffer;
  371. extern int buffers_len;
  372. extern int buffers_avail;
  373. extern buffer_t ** buffers;
  374. extern const char * flag_to_color(int _flag);
  375. extern void redraw_line(int x);
  376. extern int git_examine(char * filename);
  377. extern void search_next(void);
  378. extern void set_preferred_column(void);
  379. extern void quit(const char * message);
  380. extern void close_buffer(void);
  381. extern void set_syntax_by_name(const char * name);
  382. extern void rehighlight_search(line_t * line);
  383. extern void try_to_center();
  384. extern int read_one_character(char * message);
  385. extern void bim_unget(int c);
  386. #define bim_getch() bim_getch_timeout(200)
  387. extern int bim_getch_timeout(int timeout);
  388. extern buffer_t * buffer_new(void);
  389. extern FILE * open_biminfo(void);
  390. extern int fetch_from_biminfo(buffer_t * buf);
  391. extern int update_biminfo(buffer_t * buf);
  392. extern buffer_t * buffer_close(buffer_t * buf);
  393. extern int to_eight(uint32_t codepoint, char * out);
  394. extern char * name_from_key(enum Key keycode);
  395. extern void add_action(struct action_def action);
  396. extern void open_file(char * file);
  397. extern void recalculate_selected_lines(void);
  398. extern void add_command(struct command_def command);
  399. extern void add_prefix_command(struct command_def command);
  400. extern void render_command_input_buffer(void);
  401. extern void unhighlight_matching_paren(void);
  402. extern void add_syntax(struct syntax_definition def);
  403. struct ColorName {
  404. const char * name;
  405. const char ** value;
  406. };
  407. extern struct ColorName color_names[];
  408. /* End of bim-core.h */
  409. /* Included from bim-theme.h */
  410. #define BIM_THEME(name) \
  411. static void load_colorscheme_ ## name (void); \
  412. __attribute__((constructor)) static void _load_ ## name (void) { \
  413. add_colorscheme((struct theme_def){#name, load_colorscheme_ ## name}); \
  414. } \
  415. static void load_colorscheme_ ## name (void)
  416. /* End of bim-theme.h */
  417. /* Included from bim-syntax.h */
  418. #define BIM_SYNTAX(name, spaces) \
  419. __attribute__((constructor)) static void _load_ ## name (void) { \
  420. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces}); \
  421. } \
  422. #define paint(length, flag) do { for (int i = 0; i < (length) && state->i < state->line->actual; i++, state->i++) { state->line->text[state->i].flags = (flag); } } while (0)
  423. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  424. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  425. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  426. #define skip() (state->i++)
  427. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  428. extern int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c));
  429. extern int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c));
  430. extern void paint_single_string(struct syntax_state * state);
  431. extern void paint_simple_string(struct syntax_state * state);
  432. extern int common_comment_buzzwords(struct syntax_state * state);
  433. extern int paint_comment(struct syntax_state * state);
  434. extern int match_forward(struct syntax_state * state, char * c);
  435. extern struct syntax_definition * find_syntax_calculator(const char * name);
  436. #define nest(lang, low) \
  437. do { \
  438. state->state = (state->state < 1 ? 0 : state->state - low); \
  439. do { state->state = lang(state); } while (state->state == 0); \
  440. if (state->state == -1) return low; \
  441. return state->state + low; \
  442. } while (0)
  443. /* Some of the C stuff is widely used */
  444. extern int c_keyword_qualifier(int c);
  445. extern int paint_c_numeral(struct syntax_state * state);
  446. extern int paint_c_comment(struct syntax_state * state);
  447. extern void paint_c_char(struct syntax_state * state);
  448. /* Hacky workaround for isdigit not really accepting Unicode stuff */
  449. static __attribute__((used)) int _isdigit(int c) { if (c > 128) return 0; return isdigit(c); }
  450. static __attribute__((used)) int _isxdigit(int c) { if (c > 128) return 0; return isxdigit(c); }
  451. #undef isdigit
  452. #undef isxdigit
  453. #define isdigit(c) _isdigit(c)
  454. #define isxdigit(c) _isxdigit(c)
  455. /* End of bim-syntax.h */
  456. global_config_t global_config = {
  457. /* State */
  458. .term_width = 0,
  459. .term_height = 0,
  460. .bottom_size = 2,
  461. .yanks = NULL,
  462. .yank_count = 0,
  463. .yank_is_full_lines = 0,
  464. .tty_in = STDIN_FILENO,
  465. .bimrc_path = "~/.bimrc",
  466. .syntax_fallback = NULL, /* syntax to fall back to if none other match applies */
  467. .search = NULL,
  468. .overlay_mode = OVERLAY_MODE_NONE,
  469. .command_buffer = NULL,
  470. .command_offset = 0,
  471. .command_col_no = 0,
  472. .history_point = -1,
  473. /* Bitset starts here */
  474. .highlight_on_open = 1,
  475. .initial_file_is_read_only = 0,
  476. .go_to_line = 1,
  477. .break_from_selection = 1,
  478. /* Terminal capabilities */
  479. .can_scroll = 1,
  480. .can_hideshow = 1,
  481. .can_altscreen = 1,
  482. .can_mouse = 1,
  483. .can_unicode = 1,
  484. .can_bright = 1,
  485. .can_title = 1,
  486. .can_bce = 1,
  487. .can_24bit = 1, /* can use 24-bit color */
  488. .can_256color = 1, /* can use 265 colors */
  489. .can_italic = 1, /* can use italics (without inverting) */
  490. /* Configuration options */
  491. .history_enabled = 1,
  492. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  493. .smart_case = 1, /* smart case-sensitivity while searching */
  494. .highlight_current_line = 1,
  495. .shift_scrolling = 1, /* shift rather than moving cursor*/
  496. .check_git = 0,
  497. .color_gutter = 1, /* shows modified lines */
  498. .relative_lines = 0,
  499. .numbers = 1,
  500. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  501. /* Integer config values */
  502. .cursor_padding = 4,
  503. .split_percent = 50,
  504. .scroll_amount = 5,
  505. };
  506. struct key_name_map KeyNames[] = {
  507. {KEY_TIMEOUT, "[timeout]"},
  508. {KEY_BACKSPACE, "<backspace>"},
  509. {KEY_ENTER, "<enter>"},
  510. {KEY_ESCAPE, "<escape>"},
  511. {KEY_TAB, "<tab>"},
  512. {' ', "<space>"},
  513. /* These are mostly here for markdown output. */
  514. {'`', "<backtick>"},
  515. {'|', "<pipe>"},
  516. {KEY_DELETE, "<del>"},
  517. {KEY_MOUSE, "<mouse>"},
  518. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  519. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  520. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  521. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  522. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  523. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  524. {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>"},
  525. {KEY_SHIFT_TAB,"<shift-tab>"},
  526. };
  527. char * name_from_key(enum Key keycode) {
  528. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  529. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  530. }
  531. static char keyNameTmp[8] = {0};
  532. if (keycode <= KEY_CTRL_UNDERSCORE) {
  533. keyNameTmp[0] = '^';
  534. keyNameTmp[1] = '@' + keycode;
  535. keyNameTmp[2] = 0;
  536. return keyNameTmp;
  537. }
  538. to_eight(keycode, keyNameTmp);
  539. return keyNameTmp;
  540. }
  541. struct ColorName color_names[] = {
  542. {"text-fg", &COLOR_FG},
  543. {"text-bg", &COLOR_BG},
  544. {"alternate-fg", &COLOR_ALT_FG},
  545. {"alternate-bg", &COLOR_ALT_BG},
  546. {"number-fg", &COLOR_NUMBER_FG},
  547. {"number-bg", &COLOR_NUMBER_BG},
  548. {"status-fg", &COLOR_STATUS_FG},
  549. {"status-bg", &COLOR_STATUS_BG},
  550. {"tabbar-bg", &COLOR_TABBAR_BG},
  551. {"tab-bg", &COLOR_TAB_BG},
  552. {"error-fg", &COLOR_ERROR_FG},
  553. {"error-bg", &COLOR_ERROR_BG},
  554. {"search-fg", &COLOR_SEARCH_FG},
  555. {"search-bg", &COLOR_SEARCH_BG},
  556. {"keyword", &COLOR_KEYWORD},
  557. {"string", &COLOR_STRING},
  558. {"comment", &COLOR_COMMENT},
  559. {"type", &COLOR_TYPE},
  560. {"pragma", &COLOR_PRAGMA},
  561. {"numeral", &COLOR_NUMERAL},
  562. {"select-fg", &COLOR_SELECTFG},
  563. {"select-bg", &COLOR_SELECTBG},
  564. {"red", &COLOR_RED},
  565. {"green", &COLOR_GREEN},
  566. {"bold", &COLOR_BOLD},
  567. {"link", &COLOR_LINK},
  568. {"escape", &COLOR_ESCAPE},
  569. {NULL,NULL},
  570. };
  571. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  572. int flex_ ## name ## _count = 0; \
  573. int flex_ ## name ## _space = 0; \
  574. type * name = NULL; \
  575. void add_name (type input) { \
  576. if (flex_ ## name ## _space == 0) { \
  577. flex_ ## name ## _space = 4; \
  578. name = calloc(sizeof(type), flex_ ## name ## _space); \
  579. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  580. flex_ ## name ## _space *= 2; \
  581. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  582. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  583. } \
  584. name[flex_ ## name ## _count] = input; \
  585. flex_ ## name ## _count ++; \
  586. }
  587. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  588. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  589. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  590. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  591. /**
  592. * Special implementation of getch with a timeout
  593. */
  594. int _bim_unget = -1;
  595. void bim_unget(int c) {
  596. _bim_unget = c;
  597. }
  598. int bim_getch_timeout(int timeout) {
  599. fflush(stdout);
  600. if (_bim_unget != -1) {
  601. int out = _bim_unget;
  602. _bim_unget = -1;
  603. return out;
  604. }
  605. struct pollfd fds[1];
  606. fds[0].fd = global_config.tty_in;
  607. fds[0].events = POLLIN;
  608. int ret = poll(fds,1,timeout);
  609. if (ret > 0 && fds[0].revents & POLLIN) {
  610. unsigned char buf[1];
  611. read(global_config.tty_in, buf, 1);
  612. return buf[0];
  613. } else {
  614. return -1;
  615. }
  616. }
  617. /**
  618. * UTF-8 parser state
  619. */
  620. static uint32_t codepoint_r;
  621. static uint32_t state = 0;
  622. #define UTF8_ACCEPT 0
  623. #define UTF8_REJECT 1
  624. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  625. static int state_table[32] = {
  626. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  627. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  628. 2,2,2,2, /* 110xxxxx */
  629. 3,3, /* 1110xxxx */
  630. 4, /* 11110xxx */
  631. 1 /* 11111xxx */
  632. };
  633. static int mask_bytes[32] = {
  634. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  635. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  636. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  637. 0x1F,0x1F,0x1F,0x1F,
  638. 0x0F,0x0F,
  639. 0x07,
  640. 0x00
  641. };
  642. static int next[5] = {
  643. 0,
  644. 1,
  645. 0,
  646. 2,
  647. 3
  648. };
  649. if (*state == UTF8_ACCEPT) {
  650. *codep = byte & mask_bytes[byte >> 3];
  651. *state = state_table[byte >> 3];
  652. } else if (*state > 0) {
  653. *codep = (byte & 0x3F) | (*codep << 6);
  654. *state = next[*state];
  655. }
  656. return *state;
  657. }
  658. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  659. int _shift_key(int i, int this_buf[20], int *timeout) {
  660. int thing = this_buf[*timeout-1];
  661. (*timeout) = 0;
  662. switch (thing) {
  663. /* There are other combinations we can handle... */
  664. case '2': return i + 4;
  665. case '5': return i + 8;
  666. case '3': return i + 12;
  667. case '4': return i + 16;
  668. default: return i;
  669. }
  670. }
  671. int bim_getkey(int read_timeout) {
  672. int timeout = 0;
  673. int this_buf[20];
  674. int cin;
  675. uint32_t c;
  676. uint32_t istate = 0;
  677. while ((cin = bim_getch_timeout(read_timeout))) {
  678. if (cin == -1) {
  679. if (timeout && this_buf[timeout-1] == '\033')
  680. return KEY_ESCAPE;
  681. return KEY_TIMEOUT;
  682. }
  683. if (!decode(&istate, &c, cin)) {
  684. if (timeout == 0) {
  685. switch (c) {
  686. case '\033':
  687. if (timeout == 0) {
  688. this_buf[timeout] = c;
  689. timeout++;
  690. }
  691. continue;
  692. case KEY_LINEFEED: return KEY_ENTER;
  693. case KEY_DELETE: return KEY_BACKSPACE;
  694. }
  695. return c;
  696. } else {
  697. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  698. bim_unget(c);
  699. timeout = 0;
  700. return KEY_ESCAPE;
  701. }
  702. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  703. this_buf[timeout] = c;
  704. timeout++;
  705. continue;
  706. }
  707. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  708. switch (c) {
  709. case 'P': timeout = 0; return KEY_F1;
  710. case 'Q': timeout = 0; return KEY_F2;
  711. case 'R': timeout = 0; return KEY_F3;
  712. case 'S': timeout = 0; return KEY_F4;
  713. }
  714. timeout = 0;
  715. continue;
  716. }
  717. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  718. timeout = 0;
  719. bim_unget(c);
  720. return KEY_ESCAPE;
  721. }
  722. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  723. timeout = 1;
  724. this_buf[timeout] = c;
  725. timeout++;
  726. continue;
  727. }
  728. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  729. (isdigit(c) || (c == ';'))) {
  730. this_buf[timeout] = c;
  731. timeout++;
  732. continue;
  733. }
  734. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  735. switch (c) {
  736. case 'M': timeout = 0; return KEY_MOUSE;
  737. case 'A': return shift_key(KEY_UP);
  738. case 'B': return shift_key(KEY_DOWN);
  739. case 'C': return shift_key(KEY_RIGHT);
  740. case 'D': return shift_key(KEY_LEFT);
  741. case 'H': timeout = 0; return KEY_HOME;
  742. case 'F': timeout = 0; return KEY_END;
  743. case 'I': timeout = 0; return KEY_PAGE_UP;
  744. case 'G': timeout = 0; return KEY_PAGE_DOWN;
  745. case 'Z': timeout = 0; return KEY_SHIFT_TAB;
  746. case '~':
  747. switch (this_buf[timeout-1]) {
  748. case '1': timeout = 0; return KEY_HOME;
  749. case '3': timeout = 0; return KEY_DELETE;
  750. case '4': timeout = 0; return KEY_END;
  751. case '5': timeout = 0; return KEY_PAGE_UP;
  752. case '6': timeout = 0; return KEY_PAGE_DOWN;
  753. }
  754. break;
  755. }
  756. }
  757. timeout = 0;
  758. continue;
  759. }
  760. } else if (istate == UTF8_REJECT) {
  761. istate = 0;
  762. }
  763. }
  764. return KEY_TIMEOUT;
  765. }
  766. /**
  767. * Pointer to current active buffer
  768. */
  769. buffer_t * env = NULL;
  770. buffer_t * left_buffer = NULL;
  771. buffer_t * right_buffer = NULL;
  772. /**
  773. * A buffer for holding a number (line, repetition count)
  774. */
  775. char nav_buf[NAV_BUFFER_MAX+1];
  776. int nav_buffer = 0;
  777. /**
  778. * Available buffers
  779. */
  780. int buffers_len = 0;
  781. int buffers_avail = 0;
  782. buffer_t ** buffers = NULL;
  783. /**
  784. * Create a new buffer
  785. */
  786. buffer_t * buffer_new(void) {
  787. if (buffers_len == buffers_avail) {
  788. /* If we are out of buffer space, expand the buffers vector */
  789. buffers_avail *= 2;
  790. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  791. }
  792. /* TODO: Support having split buffers with more than two buffers open */
  793. if (left_buffer) {
  794. left_buffer->left = 0;
  795. left_buffer->width = global_config.term_width;
  796. right_buffer->left = 0;
  797. right_buffer->width = global_config.term_width;
  798. left_buffer = NULL;
  799. right_buffer = NULL;
  800. }
  801. /* Allocate a new buffer */
  802. buffers[buffers_len] = malloc(sizeof(buffer_t));
  803. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  804. buffers[buffers_len]->left = 0;
  805. buffers[buffers_len]->width = global_config.term_width;
  806. buffers[buffers_len]->highlighting_paren = -1;
  807. buffers_len++;
  808. return buffers[buffers_len-1];
  809. }
  810. /**
  811. * Open the biminfo file.
  812. */
  813. FILE * open_biminfo(void) {
  814. /* TODO This should probably be configurable line bimrc */
  815. char * home = getenv("HOME");
  816. if (!home) {
  817. /* Since it's not, we need HOME */
  818. return NULL;
  819. }
  820. /* biminfo lives at ~/.biminfo */
  821. char biminfo_path[PATH_MAX+1] = {0};
  822. sprintf(biminfo_path,"%s/.biminfo",home);
  823. /* Try to open normally first... */
  824. FILE * biminfo = fopen(biminfo_path,"r+");
  825. if (!biminfo) {
  826. /* Otherwise, try to create it. */
  827. biminfo = fopen(biminfo_path,"w+");
  828. }
  829. return biminfo;
  830. }
  831. /**
  832. * Fetch the cursor position from a biminfo file
  833. */
  834. int fetch_from_biminfo(buffer_t * buf) {
  835. /* Can't fetch if we don't have a filename */
  836. if (!buf->file_name) return 1;
  837. /* Get the absolute name of the file */
  838. char tmp_path[PATH_MAX+2];
  839. if (!realpath(buf->file_name, tmp_path)) {
  840. return 1;
  841. }
  842. strcat(tmp_path," ");
  843. FILE * biminfo = open_biminfo();
  844. if (!biminfo) return 1;
  845. /* Scan */
  846. char line[PATH_MAX+64];
  847. while (!feof(biminfo)) {
  848. fpos_t start_of_line;
  849. fgetpos(biminfo, &start_of_line);
  850. fgets(line, PATH_MAX+63, biminfo);
  851. if (line[0] != '>') {
  852. continue;
  853. }
  854. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  855. /* Read */
  856. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  857. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  858. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  859. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  860. try_to_center();
  861. return 0;
  862. }
  863. }
  864. return 0;
  865. }
  866. /**
  867. * Write a file containing the last cursor position of a buffer.
  868. */
  869. int update_biminfo(buffer_t * buf) {
  870. if (!buf->file_name) return 1;
  871. /* Get the absolute name of the file */
  872. char tmp_path[PATH_MAX+1];
  873. if (!realpath(buf->file_name, tmp_path)) {
  874. return 1;
  875. }
  876. strcat(tmp_path," ");
  877. FILE * biminfo = open_biminfo();
  878. if (!biminfo) return 1;
  879. /* Scan */
  880. char line[PATH_MAX+64];
  881. while (!feof(biminfo)) {
  882. fpos_t start_of_line;
  883. fgetpos(biminfo, &start_of_line);
  884. fgets(line, PATH_MAX+63, biminfo);
  885. if (line[0] != '>') {
  886. continue;
  887. }
  888. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  889. /* Update */
  890. fsetpos(biminfo, &start_of_line);
  891. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  892. goto _done;
  893. }
  894. }
  895. if (ftell(biminfo) == 0) {
  896. /* New biminfo */
  897. fprintf(biminfo, "# This is a biminfo file.\n");
  898. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  899. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  900. }
  901. /* Haven't found what we're looking for, should be at end of file */
  902. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  903. _done:
  904. fclose(biminfo);
  905. return 0;
  906. }
  907. /**
  908. * Close a buffer
  909. */
  910. buffer_t * buffer_close(buffer_t * buf) {
  911. int i;
  912. /* Locate the buffer in the buffer pointer vector */
  913. for (i = 0; i < buffers_len; i++) {
  914. if (buf == buffers[i])
  915. break;
  916. }
  917. /* Invalid buffer? */
  918. if (i == buffers_len) {
  919. return env; /* wtf */
  920. }
  921. update_biminfo(buf);
  922. /* Clean up lines used by old buffer */
  923. for (int i = 0; i < buf->line_count; ++i) {
  924. free(buf->lines[i]);
  925. }
  926. free(buf->lines);
  927. if (buf->file_name) {
  928. free(buf->file_name);
  929. }
  930. history_t * h = buf->history;
  931. while (h->next) {
  932. h = h->next;
  933. }
  934. while (h) {
  935. history_t * x = h->previous;
  936. free(h);
  937. h = x;
  938. }
  939. /* Clean up the old buffer */
  940. free(buf);
  941. /* Remove the buffer from the vector, moving others up */
  942. if (i != buffers_len - 1) {
  943. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  944. }
  945. /* There is one less buffer */
  946. buffers_len--;
  947. if (!buffers_len) {
  948. /* There are no more buffers. */
  949. return NULL;
  950. }
  951. /* If this was the last buffer, return the previous last buffer */
  952. if (i == buffers_len) {
  953. return buffers[buffers_len-1];
  954. }
  955. /* Otherwise return the new last buffer */
  956. return buffers[i];
  957. }
  958. /**
  959. * Theming data
  960. *
  961. * This default set is pretty simple "default foreground on default background"
  962. * except for search and selections which are black-on-white specifically.
  963. *
  964. * The theme colors get set by separate configurable themes.
  965. */
  966. const char * COLOR_FG = "@9";
  967. const char * COLOR_BG = "@9";
  968. const char * COLOR_ALT_FG = "@9";
  969. const char * COLOR_ALT_BG = "@9";
  970. const char * COLOR_NUMBER_FG = "@9";
  971. const char * COLOR_NUMBER_BG = "@9";
  972. const char * COLOR_STATUS_FG = "@9";
  973. const char * COLOR_STATUS_BG = "@9";
  974. const char * COLOR_TABBAR_BG = "@9";
  975. const char * COLOR_TAB_BG = "@9";
  976. const char * COLOR_ERROR_FG = "@9";
  977. const char * COLOR_ERROR_BG = "@9";
  978. const char * COLOR_SEARCH_FG = "@0";
  979. const char * COLOR_SEARCH_BG = "@17";
  980. const char * COLOR_KEYWORD = "@9";
  981. const char * COLOR_STRING = "@9";
  982. const char * COLOR_COMMENT = "@9";
  983. const char * COLOR_TYPE = "@9";
  984. const char * COLOR_PRAGMA = "@9";
  985. const char * COLOR_NUMERAL = "@9";
  986. const char * COLOR_SELECTFG = "@0";
  987. const char * COLOR_SELECTBG = "@17";
  988. const char * COLOR_RED = "@1";
  989. const char * COLOR_GREEN = "@2";
  990. const char * COLOR_BOLD = "@9";
  991. const char * COLOR_LINK = "@9";
  992. const char * COLOR_ESCAPE = "@9";
  993. const char * current_theme = "none";
  994. /**
  995. * Convert syntax highlighting flag to color code
  996. */
  997. const char * flag_to_color(int _flag) {
  998. int flag = _flag & 0xF;
  999. switch (flag) {
  1000. case FLAG_KEYWORD:
  1001. return COLOR_KEYWORD;
  1002. case FLAG_STRING:
  1003. return COLOR_STRING;
  1004. case FLAG_COMMENT:
  1005. return COLOR_COMMENT;
  1006. case FLAG_TYPE:
  1007. return COLOR_TYPE;
  1008. case FLAG_NUMERAL:
  1009. return COLOR_NUMERAL;
  1010. case FLAG_PRAGMA:
  1011. return COLOR_PRAGMA;
  1012. case FLAG_DIFFPLUS:
  1013. return COLOR_GREEN;
  1014. case FLAG_DIFFMINUS:
  1015. return COLOR_RED;
  1016. case FLAG_SELECT:
  1017. return COLOR_FG;
  1018. case FLAG_BOLD:
  1019. return COLOR_BOLD;
  1020. case FLAG_LINK:
  1021. return COLOR_LINK;
  1022. case FLAG_ESCAPE:
  1023. return COLOR_ESCAPE;
  1024. default:
  1025. return COLOR_FG;
  1026. }
  1027. }
  1028. /**
  1029. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  1030. * Returns 1 if a keyword from the last was found, otherwise 0.
  1031. */
  1032. int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  1033. if (keyword_qualifier(lastchar())) return 0;
  1034. if (!keyword_qualifier(charat())) return 0;
  1035. for (char ** keyword = keywords; *keyword; ++keyword) {
  1036. int d = 0;
  1037. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  1038. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  1039. paint((int)strlen(*keyword), flag);
  1040. return 1;
  1041. }
  1042. }
  1043. return 0;
  1044. }
  1045. /**
  1046. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  1047. * so it can be used for prefix checking for things that need further special handling.
  1048. */
  1049. int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  1050. if (keyword_qualifier(lastchar())) return 0;
  1051. if (!keyword_qualifier(charat())) return 0;
  1052. int i = state->i;
  1053. int slen = 0;
  1054. while (i < state->line->actual || *keyword == '\0') {
  1055. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  1056. for (int j = 0; j < slen; ++j) {
  1057. paint(1, flag);
  1058. }
  1059. return 1;
  1060. }
  1061. if (*keyword != state->line->text[i].codepoint) return 0;
  1062. i++;
  1063. keyword++;
  1064. slen++;
  1065. }
  1066. return 0;
  1067. }
  1068. void paint_single_string(struct syntax_state * state) {
  1069. paint(1, FLAG_STRING);
  1070. while (charat() != -1) {
  1071. if (charat() == '\\' && nextchar() == '\'') {
  1072. paint(2, FLAG_ESCAPE);
  1073. } else if (charat() == '\'') {
  1074. paint(1, FLAG_STRING);
  1075. return;
  1076. } else if (charat() == '\\') {
  1077. paint(2, FLAG_ESCAPE);
  1078. } else {
  1079. paint(1, FLAG_STRING);
  1080. }
  1081. }
  1082. }
  1083. void paint_simple_string(struct syntax_state * state) {
  1084. /* Assumes you came in from a check of charat() == '"' */
  1085. paint(1, FLAG_STRING);
  1086. while (charat() != -1) {
  1087. if (charat() == '\\' && nextchar() == '"') {
  1088. paint(2, FLAG_ESCAPE);
  1089. } else if (charat() == '"') {
  1090. paint(1, FLAG_STRING);
  1091. return;
  1092. } else if (charat() == '\\') {
  1093. paint(2, FLAG_ESCAPE);
  1094. } else {
  1095. paint(1, FLAG_STRING);
  1096. }
  1097. }
  1098. }
  1099. /**
  1100. * This is a basic character matcher for "keyword" characters.
  1101. */
  1102. int simple_keyword_qualifier(int c) {
  1103. return isalnum(c) || (c == '_');
  1104. }
  1105. /**
  1106. * These words can appear in comments and should be highlighted.
  1107. * Since there are a lot of comment highlighters, let's break them out.
  1108. */
  1109. int common_comment_buzzwords(struct syntax_state * state) {
  1110. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1111. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1112. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  1113. return 0;
  1114. }
  1115. /**
  1116. * Paint a comment until end of line, assumes this comment can not continue.
  1117. * (Some languages have comments that can continue with a \ - don't use this!)
  1118. * Assumes you've already painted your comment start characters.
  1119. */
  1120. int paint_comment(struct syntax_state * state) {
  1121. while (charat() != -1) {
  1122. if (common_comment_buzzwords(state)) continue;
  1123. else { paint(1, FLAG_COMMENT); }
  1124. }
  1125. return -1;
  1126. }
  1127. /**
  1128. * Match a word forward and return whether it was matched.
  1129. */
  1130. int match_forward(struct syntax_state * state, char * c) {
  1131. int i = 0;
  1132. while (1) {
  1133. if (charrel(i) == -1 && !*c) return 1;
  1134. if (charrel(i) != *c) return 0;
  1135. c++;
  1136. i++;
  1137. }
  1138. return 0;
  1139. }
  1140. /**
  1141. * Find and return a highlighter by name, or NULL
  1142. */
  1143. struct syntax_definition * find_syntax_calculator(const char * name) {
  1144. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  1145. if (!strcmp(s->name, name)) {
  1146. return s;
  1147. }
  1148. }
  1149. return NULL;
  1150. }
  1151. int syntax_count = 0;
  1152. int syntax_space = 0;
  1153. struct syntax_definition * syntaxes = NULL;
  1154. void add_syntax(struct syntax_definition def) {
  1155. if (syntax_space == 0) {
  1156. syntax_space = 4;
  1157. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  1158. } else if (syntax_count +1 == syntax_space) {
  1159. syntax_space *= 2;
  1160. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  1161. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  1162. }
  1163. syntaxes[syntax_count] = def;
  1164. syntax_count++;
  1165. }
  1166. /**
  1167. * Calculate syntax highlighting for the given line.
  1168. */
  1169. void recalculate_syntax(line_t * line, int line_no) {
  1170. /* Clear syntax for this line first */
  1171. int is_original = 1;
  1172. while (1) {
  1173. for (int i = 0; i < line->actual; ++i) {
  1174. line->text[i].flags = 0;
  1175. }
  1176. if (!env->syntax) {
  1177. if (line_no != -1) rehighlight_search(line);
  1178. return;
  1179. }
  1180. /* Start from the line's stored in initial state */
  1181. struct syntax_state state;
  1182. state.line = line;
  1183. state.line_no = line_no;
  1184. state.state = line->istate;
  1185. state.i = 0;
  1186. while (1) {
  1187. state.state = env->syntax->calculate(&state);
  1188. if (state.state != 0) {
  1189. if (line_no == -1) return;
  1190. rehighlight_search(line);
  1191. if (!is_original) {
  1192. redraw_line(line_no);
  1193. }
  1194. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  1195. line_no++;
  1196. line = env->lines[line_no];
  1197. line->istate = state.state;
  1198. if (env->loading) return;
  1199. is_original = 0;
  1200. goto _next;
  1201. }
  1202. return;
  1203. }
  1204. }
  1205. _next:
  1206. (void)0;
  1207. }
  1208. }
  1209. /**
  1210. * Recalculate tab widths.
  1211. */
  1212. void recalculate_tabs(line_t * line) {
  1213. if (env->loading) return;
  1214. int j = 0;
  1215. for (int i = 0; i < line->actual; ++i) {
  1216. if (line->text[i].codepoint == '\t') {
  1217. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1218. }
  1219. j += line->text[i].display_width;
  1220. }
  1221. }
  1222. /**
  1223. * TODO:
  1224. *
  1225. * The line editing functions should probably take a buffer_t *
  1226. * so that they can act on buffers other than the active one.
  1227. */
  1228. void recursive_history_free(history_t * root) {
  1229. if (!root->next) return;
  1230. history_t * n = root->next;
  1231. recursive_history_free(n);
  1232. switch (n->type) {
  1233. case HISTORY_REPLACE_LINE:
  1234. free(n->contents.remove_replace_line.contents);
  1235. /* fall-through */
  1236. case HISTORY_REMOVE_LINE:
  1237. free(n->contents.remove_replace_line.old_contents);
  1238. break;
  1239. default:
  1240. /* Nothing extra to free */
  1241. break;
  1242. }
  1243. free(n);
  1244. root->next = NULL;
  1245. }
  1246. #define HIST_APPEND(e) do { \
  1247. e->col = env->col_no; \
  1248. e->line = env->line_no; \
  1249. if (env->history) { \
  1250. e->previous = env->history; \
  1251. recursive_history_free(env->history); \
  1252. env->history->next = e; \
  1253. e->next = NULL; \
  1254. } \
  1255. env->history = e; \
  1256. } while (0)
  1257. /**
  1258. * Mark a point where a complete set of actions has ended.
  1259. */
  1260. void set_history_break(void) {
  1261. if (!global_config.history_enabled) return;
  1262. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1263. history_t * e = malloc(sizeof(history_t));
  1264. e->type = HISTORY_BREAK;
  1265. HIST_APPEND(e);
  1266. }
  1267. }
  1268. /**
  1269. * Insert a character into an existing line.
  1270. */
  1271. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1272. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1273. history_t * e = malloc(sizeof(history_t));
  1274. e->type = HISTORY_INSERT;
  1275. e->contents.insert_delete_replace.lineno = lineno;
  1276. e->contents.insert_delete_replace.offset = offset;
  1277. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1278. HIST_APPEND(e);
  1279. }
  1280. /* If there is not enough space... */
  1281. if (line->actual == line->available) {
  1282. /* Expand the line buffer */
  1283. if (line->available == 0) {
  1284. line->available = 8;
  1285. } else {
  1286. line->available *= 2;
  1287. }
  1288. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1289. }
  1290. /* If this was not the last character, then shift remaining characters forward. */
  1291. if (offset < line->actual) {
  1292. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1293. }
  1294. /* Insert the new character */
  1295. line->text[offset] = c;
  1296. /* There is one new character in the line */
  1297. line->actual += 1;
  1298. if (!env->loading) {
  1299. line->rev_status = 2; /* Modified */
  1300. recalculate_tabs(line);
  1301. recalculate_syntax(line, lineno);
  1302. }
  1303. return line;
  1304. }
  1305. /**
  1306. * Delete a character from a line
  1307. */
  1308. void line_delete(line_t * line, int offset, int lineno) {
  1309. /* Can't delete character before start of line. */
  1310. if (offset == 0) return;
  1311. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1312. history_t * e = malloc(sizeof(history_t));
  1313. e->type = HISTORY_DELETE;
  1314. e->contents.insert_delete_replace.lineno = lineno;
  1315. e->contents.insert_delete_replace.offset = offset;
  1316. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1317. HIST_APPEND(e);
  1318. }
  1319. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1320. if (offset < line->actual) {
  1321. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1322. }
  1323. /* The line is one character shorter */
  1324. line->actual -= 1;
  1325. line->rev_status = 2;
  1326. recalculate_tabs(line);
  1327. recalculate_syntax(line, lineno);
  1328. }
  1329. /**
  1330. * Replace a character in a line
  1331. */
  1332. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1333. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1334. history_t * e = malloc(sizeof(history_t));
  1335. e->type = HISTORY_REPLACE;
  1336. e->contents.insert_delete_replace.lineno = lineno;
  1337. e->contents.insert_delete_replace.offset = offset;
  1338. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1339. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1340. HIST_APPEND(e);
  1341. }
  1342. line->text[offset] = _c;
  1343. if (!env->loading) {
  1344. line->rev_status = 2; /* Modified */
  1345. recalculate_tabs(line);
  1346. recalculate_syntax(line, lineno);
  1347. }
  1348. }
  1349. /**
  1350. * Remove a line from the active buffer
  1351. */
  1352. line_t ** remove_line(line_t ** lines, int offset) {
  1353. /* If there is only one line, clear it instead of removing it. */
  1354. if (env->line_count == 1) {
  1355. while (lines[offset]->actual > 0) {
  1356. line_delete(lines[offset], lines[offset]->actual, offset);
  1357. }
  1358. return lines;
  1359. }
  1360. if (!env->loading && global_config.history_enabled) {
  1361. history_t * e = malloc(sizeof(history_t));
  1362. e->type = HISTORY_REMOVE_LINE;
  1363. e->contents.remove_replace_line.lineno = offset;
  1364. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1365. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1366. HIST_APPEND(e);
  1367. }
  1368. /* Otherwise, free the data used by the line */
  1369. free(lines[offset]);
  1370. /* Move other lines up */
  1371. if (offset < env->line_count-1) {
  1372. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1373. lines[env->line_count-1] = NULL;
  1374. }
  1375. /* There is one less line */
  1376. env->line_count -= 1;
  1377. return lines;
  1378. }
  1379. /**
  1380. * Add a new line to the active buffer.
  1381. */
  1382. line_t ** add_line(line_t ** lines, int offset) {
  1383. /* Invalid offset? */
  1384. if (offset > env->line_count) return lines;
  1385. if (!env->loading && global_config.history_enabled) {
  1386. history_t * e = malloc(sizeof(history_t));
  1387. e->type = HISTORY_ADD_LINE;
  1388. e->contents.add_merge_split_lines.lineno = offset;
  1389. HIST_APPEND(e);
  1390. }
  1391. /* Not enough space */
  1392. if (env->line_count == env->line_avail) {
  1393. /* Allocate more space */
  1394. env->line_avail *= 2;
  1395. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1396. }
  1397. /* If this isn't the last line, move other lines down */
  1398. if (offset < env->line_count) {
  1399. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1400. }
  1401. /* Allocate the new line */
  1402. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1403. lines[offset]->available = 32;
  1404. /* There is one new line */
  1405. env->line_count += 1;
  1406. env->lines = lines;
  1407. if (!env->loading) {
  1408. lines[offset]->rev_status = 2; /* Modified */
  1409. }
  1410. if (offset > 0 && !env->loading) {
  1411. recalculate_syntax(lines[offset-1],offset-1);
  1412. }
  1413. return lines;
  1414. }
  1415. /**
  1416. * Replace a line with data from another line (used by paste to paste yanked lines)
  1417. */
  1418. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1419. if (!env->loading && global_config.history_enabled) {
  1420. history_t * e = malloc(sizeof(history_t));
  1421. e->type = HISTORY_REPLACE_LINE;
  1422. e->contents.remove_replace_line.lineno = offset;
  1423. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1424. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1425. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1426. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1427. HIST_APPEND(e);
  1428. }
  1429. if (lines[offset]->available < replacement->actual) {
  1430. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1431. lines[offset]->available = replacement->available;
  1432. }
  1433. lines[offset]->actual = replacement->actual;
  1434. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1435. if (!env->loading) {
  1436. lines[offset]->rev_status = 2;
  1437. recalculate_syntax(lines[offset],offset);
  1438. }
  1439. }
  1440. /**
  1441. * Merge two consecutive lines.
  1442. * lineb is the offset of the second line.
  1443. */
  1444. line_t ** merge_lines(line_t ** lines, int lineb) {
  1445. /* linea is the line immediately before lineb */
  1446. int linea = lineb - 1;
  1447. if (!env->loading && global_config.history_enabled) {
  1448. history_t * e = malloc(sizeof(history_t));
  1449. e->type = HISTORY_MERGE_LINES;
  1450. e->contents.add_merge_split_lines.lineno = lineb;
  1451. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1452. HIST_APPEND(e);
  1453. }
  1454. /* If there isn't enough space in linea hold both... */
  1455. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1456. /* ... allocate more space until it fits */
  1457. if (lines[linea]->available == 0) {
  1458. lines[linea]->available = 8;
  1459. } else {
  1460. lines[linea]->available *= 2;
  1461. }
  1462. /* XXX why not just do this once after calculating appropriate size */
  1463. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1464. }
  1465. /* Copy the second line into the first line */
  1466. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1467. /* The first line is now longer */
  1468. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1469. if (!env->loading) {
  1470. lines[linea]->rev_status = 2;
  1471. recalculate_tabs(lines[linea]);
  1472. recalculate_syntax(lines[linea], linea);
  1473. }
  1474. /* Remove the second line */
  1475. free(lines[lineb]);
  1476. /* Move other lines up */
  1477. if (lineb < env->line_count) {
  1478. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1479. lines[env->line_count-1] = NULL;
  1480. }
  1481. /* There is one less line */
  1482. env->line_count -= 1;
  1483. return lines;
  1484. }
  1485. /**
  1486. * Split a line into two lines at the given column
  1487. */
  1488. line_t ** split_line(line_t ** lines, int line, int split) {
  1489. /* If we're trying to split from the start, just add a new blank line before */
  1490. if (split == 0) {
  1491. return add_line(lines, line);
  1492. }
  1493. if (!env->loading && global_config.history_enabled) {
  1494. history_t * e = malloc(sizeof(history_t));
  1495. e->type = HISTORY_SPLIT_LINE;
  1496. e->contents.add_merge_split_lines.lineno = line;
  1497. e->contents.add_merge_split_lines.split = split;
  1498. HIST_APPEND(e);
  1499. }
  1500. /* Allocate more space as needed */
  1501. if (env->line_count == env->line_avail) {
  1502. env->line_avail *= 2;
  1503. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1504. }
  1505. if (!env->loading) {
  1506. unhighlight_matching_paren();
  1507. }
  1508. /* Shift later lines down */
  1509. if (line < env->line_count) {
  1510. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1511. }
  1512. /* I have no idea what this is doing */
  1513. int remaining = lines[line]->actual - split;
  1514. int v = remaining;
  1515. v--;
  1516. v |= v >> 1;
  1517. v |= v >> 2;
  1518. v |= v >> 4;
  1519. v |= v >> 8;
  1520. v |= v >> 16;
  1521. v++;
  1522. /* Allocate space for the new line */
  1523. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1524. lines[line+1]->available = v;
  1525. lines[line+1]->actual = remaining;
  1526. /* Move the data from the old line into the new line */
  1527. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1528. lines[line]->actual = split;
  1529. if (!env->loading) {
  1530. lines[line]->rev_status = 2;
  1531. lines[line+1]->rev_status = 2;
  1532. recalculate_tabs(lines[line]);
  1533. recalculate_tabs(lines[line+1]);
  1534. recalculate_syntax(lines[line], line);
  1535. recalculate_syntax(lines[line+1], line+1);
  1536. }
  1537. /* There is one new line */
  1538. env->line_count += 1;
  1539. /* We may have reallocated lines */
  1540. return lines;
  1541. }
  1542. /**
  1543. * Understand spaces and comments and check if the previous line
  1544. * ended with a brace or a colon.
  1545. */
  1546. int line_ends_with_brace(line_t * line) {
  1547. int i = line->actual-1;
  1548. while (i >= 0) {
  1549. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1550. i--;
  1551. } else {
  1552. break;
  1553. }
  1554. }
  1555. if (i < 0) return 0;
  1556. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':');
  1557. }
  1558. int line_is_comment(line_t * line) {
  1559. if (!env->syntax) return 0;
  1560. if (!strcmp(env->syntax->name,"c")) {
  1561. if (line->istate == 1) return 1;
  1562. } else if (!strcmp(env->syntax->name,"java")) {
  1563. if (line->istate == 1) return 1;
  1564. } else if (!strcmp(env->syntax->name,"rust")) {
  1565. if (line->istate > 0) return 1;
  1566. }
  1567. return 0;
  1568. }
  1569. /**
  1570. * Add indentation from the previous (temporally) line
  1571. */
  1572. void add_indent(int new_line, int old_line, int ignore_brace) {
  1573. if (env->indent) {
  1574. int changed = 0;
  1575. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1576. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1577. if (env->lines[old_line]->text[i].codepoint == '/') {
  1578. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1579. /* Insert ' * ' */
  1580. char_t space = {1,FLAG_COMMENT,' '};
  1581. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1582. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1583. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1584. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1585. env->col_no += 3;
  1586. }
  1587. break;
  1588. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1589. /* Insert ' * ' */
  1590. char_t space = {1,FLAG_COMMENT,' '};
  1591. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1592. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1593. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1594. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1595. env->col_no += 3;
  1596. break;
  1597. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1598. env->lines[old_line]->text[i].codepoint == '\t' ||
  1599. env->lines[old_line]->text[i].codepoint == '*') {
  1600. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1601. env->col_no++;
  1602. changed = 1;
  1603. } else {
  1604. break;
  1605. }
  1606. }
  1607. } else {
  1608. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1609. if (old_line < new_line && i == env->lines[old_line]->actual - 3 &&
  1610. env->lines[old_line]->text[i].codepoint == ' ' &&
  1611. env->lines[old_line]->text[i+1].codepoint == '*' &&
  1612. env->lines[old_line]->text[i+2].codepoint == '/') {
  1613. break;
  1614. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1615. env->lines[old_line]->text[i].codepoint == '\t') {
  1616. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1617. env->col_no++;
  1618. changed = 1;
  1619. } else {
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1625. if (env->tabs) {
  1626. char_t c;
  1627. c.codepoint = '\t';
  1628. c.display_width = env->tabstop;
  1629. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1630. env->col_no++;
  1631. changed = 1;
  1632. } else {
  1633. for (int j = 0; j < env->tabstop; ++j) {
  1634. char_t c;
  1635. c.codepoint = ' ';
  1636. c.display_width = 1;
  1637. c.flags = FLAG_SELECT;
  1638. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1639. env->col_no++;
  1640. }
  1641. changed = 1;
  1642. }
  1643. }
  1644. int was_whitespace = 1;
  1645. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1646. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1647. env->lines[old_line]->text[i].codepoint != '\t') {
  1648. was_whitespace = 0;
  1649. break;
  1650. }
  1651. }
  1652. if (was_whitespace) {
  1653. while (env->lines[old_line]->actual) {
  1654. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1655. }
  1656. }
  1657. if (changed) {
  1658. recalculate_syntax(env->lines[new_line],new_line);
  1659. }
  1660. }
  1661. }
  1662. /**
  1663. * Initialize a buffer with default values
  1664. */
  1665. void setup_buffer(buffer_t * env) {
  1666. /* If this buffer was already initialized, clear out its line data */
  1667. if (env->lines) {
  1668. for (int i = 0; i < env->line_count; ++i) {
  1669. free(env->lines[i]);
  1670. }
  1671. free(env->lines);
  1672. }
  1673. /* Default state parameters */
  1674. env->line_no = 1; /* Default cursor position */
  1675. env->col_no = 1;
  1676. env->line_count = 1; /* Buffers always have at least one line */
  1677. env->modified = 0;
  1678. env->readonly = 0;
  1679. env->offset = 0;
  1680. env->line_avail = 8; /* Default line buffer capacity */
  1681. env->tabs = 1; /* Tabs by default */
  1682. env->tabstop = 4; /* Tab stop width */
  1683. env->indent = 1; /* Auto-indent by default */
  1684. env->history = malloc(sizeof(struct history));
  1685. memset(env->history, 0, sizeof(struct history));
  1686. env->last_save_history = env->history;
  1687. /* Allocate line buffer */
  1688. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1689. /* Initialize the first line */
  1690. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1691. env->lines[0]->available = 32;
  1692. }
  1693. /**
  1694. * Toggle buffered / unbuffered modes
  1695. */
  1696. struct termios old;
  1697. void get_initial_termios(void) {
  1698. tcgetattr(STDOUT_FILENO, &old);
  1699. }
  1700. void set_unbuffered(void) {
  1701. struct termios new = old;
  1702. new.c_iflag &= (~ICRNL) & (~IXON);
  1703. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1704. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1705. }
  1706. void set_buffered(void) {
  1707. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1708. }
  1709. /**
  1710. * Convert codepoint to utf-8 string
  1711. */
  1712. int to_eight(uint32_t codepoint, char * out) {
  1713. memset(out, 0x00, 7);
  1714. if (codepoint < 0x0080) {
  1715. out[0] = (char)codepoint;
  1716. } else if (codepoint < 0x0800) {
  1717. out[0] = 0xC0 | (codepoint >> 6);
  1718. out[1] = 0x80 | (codepoint & 0x3F);
  1719. } else if (codepoint < 0x10000) {
  1720. out[0] = 0xE0 | (codepoint >> 12);
  1721. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1722. out[2] = 0x80 | (codepoint & 0x3F);
  1723. } else if (codepoint < 0x200000) {
  1724. out[0] = 0xF0 | (codepoint >> 18);
  1725. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1726. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1727. out[3] = 0x80 | ((codepoint) & 0x3F);
  1728. } else if (codepoint < 0x4000000) {
  1729. out[0] = 0xF8 | (codepoint >> 24);
  1730. out[1] = 0x80 | (codepoint >> 18);
  1731. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1732. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1733. out[4] = 0x80 | ((codepoint) & 0x3F);
  1734. } else {
  1735. out[0] = 0xF8 | (codepoint >> 30);
  1736. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1737. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1738. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1739. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1740. out[5] = 0x80 | ((codepoint) & 0x3F);
  1741. }
  1742. return strlen(out);
  1743. }
  1744. /**
  1745. * Get the presentation width of a codepoint
  1746. */
  1747. int codepoint_width(wchar_t codepoint) {
  1748. if (codepoint == '\t') {
  1749. return 1; /* Recalculate later */
  1750. }
  1751. if (codepoint < 32) {
  1752. /* We render these as ^@ */
  1753. return 2;
  1754. }
  1755. if (codepoint == 0x7F) {
  1756. /* Renders as ^? */
  1757. return 2;
  1758. }
  1759. if (codepoint > 0x7f && codepoint < 0xa0) {
  1760. /* Upper control bytes <xx> */
  1761. return 4;
  1762. }
  1763. if (codepoint == 0xa0) {
  1764. /* Non-breaking space _ */
  1765. return 1;
  1766. }
  1767. /* Skip wcwidth for anything under 256 */
  1768. if (codepoint > 256) {
  1769. if (global_config.can_unicode) {
  1770. /* Higher codepoints may be wider (eg. Japanese) */
  1771. int out = wcwidth(codepoint);
  1772. if (out >= 1) return out;
  1773. }
  1774. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1775. return (codepoint < 0x10000) ? 8 : 10;
  1776. }
  1777. return 1;
  1778. }
  1779. /**
  1780. * Move the terminal cursor
  1781. */
  1782. void place_cursor(int x, int y) {
  1783. printf("\033[%d;%dH", y, x);
  1784. }
  1785. /**
  1786. * Set text colors
  1787. *
  1788. * Normally, text colors are just strings, but if they
  1789. * start with @ they will be parsed as integers
  1790. * representing one of the 16 standard colors, suitable
  1791. * for terminals without support for the 256- or 24-bit
  1792. * color modes.
  1793. */
  1794. void set_colors(const char * fg, const char * bg) {
  1795. printf("\033[22;23;24;");
  1796. if (*bg == '@') {
  1797. int _bg = atoi(bg+1);
  1798. if (_bg < 10) {
  1799. printf("4%d;", _bg);
  1800. } else {
  1801. printf("10%d;", _bg-10);
  1802. }
  1803. } else {
  1804. printf("48;%s;", bg);
  1805. }
  1806. if (*fg == '@') {
  1807. int _fg = atoi(fg+1);
  1808. if (_fg < 10) {
  1809. printf("3%dm", _fg);
  1810. } else {
  1811. printf("9%dm", _fg-10);
  1812. }
  1813. } else {
  1814. printf("38;%sm", fg);
  1815. }
  1816. }
  1817. /**
  1818. * Set just the foreground color
  1819. *
  1820. * (See set_colors above)
  1821. */
  1822. void set_fg_color(const char * fg) {
  1823. printf("\033[22;23;24;");
  1824. if (*fg == '@') {
  1825. int _fg = atoi(fg+1);
  1826. if (_fg < 10) {
  1827. printf("3%dm", _fg);
  1828. } else {
  1829. printf("9%dm", _fg-10);
  1830. }
  1831. } else {
  1832. printf("38;%sm", fg);
  1833. }
  1834. }
  1835. /**
  1836. * Clear the rest of this line
  1837. */
  1838. void clear_to_end(void) {
  1839. if (global_config.can_bce) {
  1840. printf("\033[K");
  1841. }
  1842. }
  1843. /**
  1844. * For terminals without bce,
  1845. * prepaint the whole line, so we don't have to track
  1846. * where the cursor is for everything. Inefficient,
  1847. * but effective.
  1848. */
  1849. void paint_line(const char * bg) {
  1850. if (!global_config.can_bce) {
  1851. set_colors(COLOR_FG, bg);
  1852. for (int i = 0; i < global_config.term_width; ++i) {
  1853. printf(" ");
  1854. }
  1855. printf("\r");
  1856. }
  1857. }
  1858. /**
  1859. * Enable bold text display
  1860. */
  1861. void set_bold(void) {
  1862. printf("\033[1m");
  1863. }
  1864. /**
  1865. * Disable bold
  1866. */
  1867. void unset_bold(void) {
  1868. printf("\033[22m");
  1869. }
  1870. /**
  1871. * Enable underlined text display
  1872. */
  1873. void set_underline(void) {
  1874. printf("\033[4m");
  1875. }
  1876. /**
  1877. * Disable underlined text display
  1878. */
  1879. void unset_underline(void) {
  1880. printf("\033[24m");
  1881. }
  1882. /**
  1883. * Reset text display attributes
  1884. */
  1885. void reset(void) {
  1886. printf("\033[0m");
  1887. }
  1888. /**
  1889. * Clear the entire screen
  1890. */
  1891. void clear_screen(void) {
  1892. printf("\033[H\033[2J");
  1893. }
  1894. /**
  1895. * Hide the cursor
  1896. */
  1897. void hide_cursor(void) {
  1898. if (global_config.can_hideshow) {
  1899. printf("\033[?25l");
  1900. }
  1901. }
  1902. /**
  1903. * Show the cursor
  1904. */
  1905. void show_cursor(void) {
  1906. if (global_config.can_hideshow) {
  1907. printf("\033[?25h");
  1908. }
  1909. }
  1910. /**
  1911. * Store the cursor position
  1912. */
  1913. void store_cursor(void) {
  1914. printf("\0337");
  1915. }
  1916. /**
  1917. * Restore the cursor position.
  1918. */
  1919. void restore_cursor(void) {
  1920. printf("\0338");
  1921. }
  1922. /**
  1923. * Request mouse events
  1924. */
  1925. void mouse_enable(void) {
  1926. if (global_config.can_mouse) {
  1927. printf("\033[?1000h");
  1928. }
  1929. }
  1930. /**
  1931. * Stop mouse events
  1932. */
  1933. void mouse_disable(void) {
  1934. if (global_config.can_mouse) {
  1935. printf("\033[?1000l");
  1936. }
  1937. }
  1938. /**
  1939. * Shift the screen up one line
  1940. */
  1941. void shift_up(int amount) {
  1942. printf("\033[%dS", amount);
  1943. }
  1944. /**
  1945. * Shift the screen down one line.
  1946. */
  1947. void shift_down(int amount) {
  1948. printf("\033[%dT", amount);
  1949. }
  1950. /**
  1951. * Switch to the alternate terminal screen.
  1952. */
  1953. void set_alternate_screen(void) {
  1954. if (global_config.can_altscreen) {
  1955. printf("\033[?1049h");
  1956. }
  1957. }
  1958. /**
  1959. * Restore the standard terminal screen.
  1960. */
  1961. void unset_alternate_screen(void) {
  1962. if (global_config.can_altscreen) {
  1963. printf("\033[?1049l");
  1964. }
  1965. }
  1966. /**
  1967. * Get the name of just a file from a full path.
  1968. * Returns a pointer within the original string.
  1969. */
  1970. char * file_basename(char * file) {
  1971. char * c = strrchr(file, '/');
  1972. if (!c) return file;
  1973. return (c+1);
  1974. }
  1975. /**
  1976. * Print a tab name with fixed width and modifiers
  1977. * into an output buffer and return the written width.
  1978. *
  1979. * TODO this isn't unicode/display-width aware, so it returns
  1980. * byte lengths and doesn't limit the width of the file
  1981. * properly if it has wide characters. FIXME
  1982. */
  1983. int draw_tab_name(buffer_t * _env, char * out) {
  1984. return sprintf(out, "%s %.40s ",
  1985. _env->modified ? " +" : "",
  1986. _env->file_name ? file_basename(_env->file_name) : "[No Name]");
  1987. }
  1988. /**
  1989. * Redaw the tabbar, with a tab for each buffer.
  1990. *
  1991. * The active buffer is highlighted.
  1992. */
  1993. void redraw_tabbar(void) {
  1994. /* Hide cursor while rendering UI */
  1995. hide_cursor();
  1996. /* Move to upper left */
  1997. place_cursor(1,1);
  1998. paint_line(COLOR_TABBAR_BG);
  1999. /* For each buffer... */
  2000. int offset = 0;
  2001. for (int i = 0; i < buffers_len; i++) {
  2002. buffer_t * _env = buffers[i];
  2003. if (_env == env) {
  2004. /* If this is the active buffer, highlight it */
  2005. reset();
  2006. set_colors(COLOR_FG, COLOR_BG);
  2007. set_bold();
  2008. } else {
  2009. /* Otherwise use default tab color */
  2010. reset();
  2011. set_colors(COLOR_FG, COLOR_TAB_BG);
  2012. set_underline();
  2013. }
  2014. char title[64];
  2015. int size = draw_tab_name(_env, title);
  2016. if (offset + size >= global_config.term_width) {
  2017. if (global_config.term_width - offset - 1 > 0) {
  2018. title[global_config.term_width - offset - 1] = '\0';
  2019. }
  2020. printf("%s", title);
  2021. break;
  2022. }
  2023. printf("%s", title);
  2024. offset += size;
  2025. }
  2026. /* Reset bold/underline */
  2027. reset();
  2028. /* Fill the rest of the tab bar */
  2029. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2030. clear_to_end();
  2031. }
  2032. /**
  2033. * Braindead log10 implementation for the line numbers
  2034. */
  2035. int log_base_10(unsigned int v) {
  2036. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2037. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2038. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2039. return r;
  2040. }
  2041. /**
  2042. * Render a line of text
  2043. *
  2044. * This handles rendering the actual text content. A full line of text
  2045. * also includes a line number and some padding.
  2046. *
  2047. * width: width of the text display region (term width - line number width)
  2048. * offset: how many cells into the line to start rendering at
  2049. */
  2050. void render_line(line_t * line, int width, int offset, int line_no) {
  2051. int i = 0; /* Offset in char_t line data entries */
  2052. int j = 0; /* Offset in terminal cells */
  2053. const char * last_color = NULL;
  2054. int was_selecting = 0, was_searching = 0;
  2055. /* Set default text colors */
  2056. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2057. /*
  2058. * When we are rendering in the middle of a wide character,
  2059. * we render -'s to fill the remaining amount of the
  2060. * charater's width
  2061. */
  2062. int remainder = 0;
  2063. int is_spaces = 1;
  2064. /* For each character in the line ... */
  2065. while (i < line->actual) {
  2066. /* If there is remaining text... */
  2067. if (remainder) {
  2068. /* If we should be drawing by now... */
  2069. if (j >= offset) {
  2070. /* Fill remainder with -'s */
  2071. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2072. printf("-");
  2073. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2074. }
  2075. /* One less remaining width cell to fill */
  2076. remainder--;
  2077. /* Terminal offset moves forward */
  2078. j++;
  2079. /*
  2080. * If this was the last remaining character, move to
  2081. * the next codepoint in the line
  2082. */
  2083. if (remainder == 0) {
  2084. i++;
  2085. }
  2086. continue;
  2087. }
  2088. /* Get the next character to draw */
  2089. char_t c = line->text[i];
  2090. if (c.codepoint != ' ') is_spaces = 0;
  2091. /* If we should be drawing by now... */
  2092. if (j >= offset) {
  2093. /* If this character is going to fall off the edge of the screen... */
  2094. if (j - offset + c.display_width >= width) {
  2095. /* We draw this with special colors so it isn't ambiguous */
  2096. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2097. /* If it's wide, draw ---> as needed */
  2098. while (j - offset < width - 1) {
  2099. printf("-");
  2100. j++;
  2101. }
  2102. /* End the line with a > to show it overflows */
  2103. printf(">");
  2104. set_colors(COLOR_FG, COLOR_BG);
  2105. return;
  2106. }
  2107. /* Syntax highlighting */
  2108. const char * color = flag_to_color(c.flags);
  2109. if (c.flags & FLAG_SELECT) {
  2110. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2111. was_selecting = 1;
  2112. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2113. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2114. was_searching = 1;
  2115. } else if (c.flags == FLAG_ERROR) {
  2116. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2117. was_searching = 1; /* co-opting this should work... */
  2118. } else {
  2119. if (was_selecting || was_searching) {
  2120. was_selecting = 0;
  2121. was_searching = 0;
  2122. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2123. last_color = color;
  2124. } else if (!last_color || strcmp(color, last_color)) {
  2125. set_fg_color(color);
  2126. last_color = color;
  2127. }
  2128. }
  2129. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2130. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2131. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2132. ((j == env->sel_col) ||
  2133. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2134. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2135. was_selecting = 1;
  2136. }
  2137. #define _set_colors(fg,bg) \
  2138. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2139. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2140. }
  2141. /* Render special characters */
  2142. if (c.codepoint == '\t') {
  2143. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2144. if (global_config.can_unicode) {
  2145. printf("»");
  2146. for (int i = 1; i < c.display_width; ++i) {
  2147. printf("·");
  2148. }
  2149. } else {
  2150. printf(">");
  2151. for (int i = 1; i < c.display_width; ++i) {
  2152. printf("-");
  2153. }
  2154. }
  2155. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2156. } else if (c.codepoint < 32) {
  2157. /* Codepoints under 32 to get converted to ^@ escapes */
  2158. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2159. printf("^%c", '@' + c.codepoint);
  2160. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2161. } else if (c.codepoint == 0x7f) {
  2162. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2163. printf("^?");
  2164. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2165. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2166. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2167. printf("<%2x>", c.codepoint);
  2168. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2169. } else if (c.codepoint == 0xa0) {
  2170. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2171. printf("_");
  2172. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2173. } else if (c.display_width == 8) {
  2174. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2175. printf("[U+%04x]", c.codepoint);
  2176. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2177. } else if (c.display_width == 10) {
  2178. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2179. printf("[U+%06x]", c.codepoint);
  2180. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2181. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2182. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2183. if (global_config.can_unicode) {
  2184. printf("▏");
  2185. } else {
  2186. printf("|");
  2187. }
  2188. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2189. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2190. /* Special case: space at end of line */
  2191. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2192. if (global_config.can_unicode) {
  2193. printf("·");
  2194. } else {
  2195. printf("-");
  2196. }
  2197. _set_colors(COLOR_FG, COLOR_BG);
  2198. } else {
  2199. /* Normal characters get output */
  2200. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2201. to_eight(c.codepoint, tmp);
  2202. printf("%s", tmp);
  2203. }
  2204. /* Advance the terminal cell offset by the render width of this character */
  2205. j += c.display_width;
  2206. /* Advance to the next character */
  2207. i++;
  2208. } else if (c.display_width > 1) {
  2209. /*
  2210. * If this is a wide character but we aren't ready to render yet,
  2211. * we may need to draw some filler text for the remainder of its
  2212. * width to ensure we don't jump around when horizontally scrolling
  2213. * past wide characters.
  2214. */
  2215. remainder = c.display_width - 1;
  2216. j++;
  2217. } else {
  2218. /* Regular character, not ready to draw, advance without doing anything */
  2219. j++;
  2220. i++;
  2221. }
  2222. }
  2223. if (env->mode != MODE_LINE_SELECTION) {
  2224. if (line->is_current) {
  2225. set_colors(COLOR_FG, COLOR_ALT_BG);
  2226. } else {
  2227. set_colors(COLOR_FG, COLOR_BG);
  2228. }
  2229. } else {
  2230. if (!line->actual) {
  2231. if (env->line_no == line_no ||
  2232. (env->start_line > env->line_no &&
  2233. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2234. (env->start_line < env->line_no &&
  2235. (line_no >= env->start_line && line_no <= env->line_no))) {
  2236. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2237. }
  2238. }
  2239. }
  2240. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2241. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2242. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2243. j <= env->sel_col &&
  2244. env->sel_col < width) {
  2245. set_colors(COLOR_FG, COLOR_BG);
  2246. while (j < env->sel_col) {
  2247. printf(" ");
  2248. j++;
  2249. }
  2250. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2251. printf(" ");
  2252. j++;
  2253. set_colors(COLOR_FG, COLOR_BG);
  2254. }
  2255. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2256. clear_to_end();
  2257. } else {
  2258. /* Paint the rest of the line */
  2259. if (j < offset) j = offset;
  2260. for (; j < width + offset; ++j) {
  2261. printf(" ");
  2262. }
  2263. }
  2264. }
  2265. /**
  2266. * Get the width of the line number region
  2267. */
  2268. int num_width(void) {
  2269. if (!global_config.numbers) return -2; /* Accounts for the padding */
  2270. int w = log_base_10(env->line_count) + 1;
  2271. if (w < 2) return 2;
  2272. return w;
  2273. }
  2274. /**
  2275. * Draw the gutter and line numbers.
  2276. */
  2277. void draw_line_number(int x) {
  2278. if (!global_config.numbers) return;
  2279. /* Draw the line number */
  2280. if (env->lines[x]->is_current) {
  2281. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2282. } else {
  2283. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2284. }
  2285. if (global_config.relative_lines && x+1 != env->line_no) {
  2286. x = x+1 - env->line_no;
  2287. x = ((x < 0) ? -x : x)-1;
  2288. }
  2289. int num_size = num_width();
  2290. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2291. printf(" ");
  2292. }
  2293. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2294. }
  2295. /**
  2296. * Used to highlight the current line after moving the cursor.
  2297. */
  2298. void recalculate_current_line(void) {
  2299. int something_changed = 0;
  2300. if (global_config.highlight_current_line) {
  2301. for (int i = 0; i < env->line_count; ++i) {
  2302. if (env->lines[i]->is_current && i != env->line_no-1) {
  2303. env->lines[i]->is_current = 0;
  2304. something_changed = 1;
  2305. redraw_line(i);
  2306. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2307. env->lines[i]->is_current = 1;
  2308. something_changed = 1;
  2309. redraw_line(i);
  2310. }
  2311. }
  2312. } else {
  2313. something_changed = 1;
  2314. }
  2315. if (something_changed && global_config.relative_lines) {
  2316. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2317. /* Place cursor for line number */
  2318. place_cursor(2 + env->left, (i)-env->offset+2);
  2319. draw_line_number(i);
  2320. }
  2321. }
  2322. }
  2323. /**
  2324. * Redraw line.
  2325. *
  2326. * This draws the line number as well as the actual text.
  2327. */
  2328. void redraw_line(int x) {
  2329. if (env->loading) return;
  2330. /* Determine if this line is visible. */
  2331. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 2) {
  2332. return;
  2333. }
  2334. /* Calculate offset in screen */
  2335. int j = x - env->offset;
  2336. /* Hide cursor when drawing */
  2337. hide_cursor();
  2338. /* Move cursor to upper left most cell of this line */
  2339. place_cursor(1 + env->left,2 + j);
  2340. /* Draw a gutter on the left. */
  2341. switch (env->lines[x]->rev_status) {
  2342. case 1:
  2343. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2344. printf(" ");
  2345. break;
  2346. case 2:
  2347. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2348. printf(" ");
  2349. break;
  2350. case 3:
  2351. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2352. printf(" ");
  2353. break;
  2354. case 4:
  2355. set_colors(COLOR_ALT_FG, COLOR_RED);
  2356. printf("▆");
  2357. break;
  2358. case 5:
  2359. set_colors(COLOR_KEYWORD, COLOR_RED);
  2360. printf("▆");
  2361. break;
  2362. default:
  2363. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2364. printf(" ");
  2365. break;
  2366. }
  2367. draw_line_number(x);
  2368. /*
  2369. * Draw the line text
  2370. * If this is the active line, the current character cell offset should be used.
  2371. * (Non-active lines are not shifted and always render from the start of the line)
  2372. */
  2373. render_line(env->lines[x], env->width - 3 - num_width(), (x + 1 == env->line_no || global_config.horizontal_shift_scrolling) ? env->coffset : 0, x+1);
  2374. }
  2375. /**
  2376. * Draw a ~ line where there is no buffer text.
  2377. */
  2378. void draw_excess_line(int j) {
  2379. place_cursor(1+env->left,2 + j);
  2380. paint_line(COLOR_ALT_BG);
  2381. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2382. printf("~");
  2383. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2384. clear_to_end();
  2385. } else {
  2386. /* Paint the rest of the line */
  2387. for (int x = 1; x < env->width; ++x) {
  2388. printf(" ");
  2389. }
  2390. }
  2391. }
  2392. /**
  2393. * Redraw the entire text area
  2394. */
  2395. void redraw_text(void) {
  2396. /* Hide cursor while rendering */
  2397. hide_cursor();
  2398. /* Figure out the available size of the text region */
  2399. int l = global_config.term_height - global_config.bottom_size - 1;
  2400. int j = 0;
  2401. /* Draw each line */
  2402. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2403. redraw_line(x);
  2404. j++;
  2405. }
  2406. /* Draw the rest of the text region as ~ lines */
  2407. for (; j < l; ++j) {
  2408. draw_excess_line(j);
  2409. }
  2410. }
  2411. static int view_left_offset = 0;
  2412. static int view_right_offset = 0;
  2413. /**
  2414. * When in split view, draw the other buffer.
  2415. * Has special handling for when the split is
  2416. * on a single buffer.
  2417. */
  2418. void redraw_alt_buffer(buffer_t * buf) {
  2419. if (left_buffer == right_buffer) {
  2420. /* draw the opposite view */
  2421. int left, width, offset;
  2422. left = env->left;
  2423. width = env->width;
  2424. offset = env->offset;
  2425. if (left == 0) {
  2426. /* Draw the right side */
  2427. env->left = width;
  2428. env->width = global_config.term_width - width;
  2429. env->offset = view_right_offset;
  2430. view_left_offset = offset;
  2431. } else {
  2432. env->left = 0;
  2433. env->width = global_config.term_width * global_config.split_percent / 100;
  2434. env->offset = view_left_offset;
  2435. view_right_offset = offset;
  2436. }
  2437. redraw_text();
  2438. env->left = left;
  2439. env->width = width;
  2440. env->offset = offset;
  2441. }
  2442. /* Swap out active buffer */
  2443. buffer_t * tmp = env;
  2444. env = buf;
  2445. /* Redraw text */
  2446. redraw_text();
  2447. /* Return original active buffer */
  2448. env = tmp;
  2449. }
  2450. /**
  2451. * Draw the status bar
  2452. *
  2453. * The status bar shows the name of the file, whether it has modifications,
  2454. * and (in the future) what syntax highlighting mode is enabled.
  2455. *
  2456. * The right side of the tatus bar shows the line number and column.
  2457. */
  2458. void redraw_statusbar(void) {
  2459. /* Hide cursor while rendering */
  2460. hide_cursor();
  2461. /* Move cursor to the status bar line (second from bottom */
  2462. place_cursor(1, global_config.term_height - 1);
  2463. /* Set background colors for status line */
  2464. paint_line(COLOR_STATUS_BG);
  2465. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2466. /* Print the file name */
  2467. char status_bits[1024] = {0}; /* Sane maximum */
  2468. char * s = status_bits;
  2469. if (env->syntax) {
  2470. s += snprintf(s, 100, "[%s]", env->syntax->name);
  2471. }
  2472. /* Print file status indicators */
  2473. if (env->modified) {
  2474. s += snprintf(s, 5, "[+]");
  2475. }
  2476. if (env->readonly) {
  2477. s += snprintf(s, 6, "[ro]");
  2478. }
  2479. if (env->crnl) {
  2480. s += snprintf(s, 7, "[crnl]");
  2481. }
  2482. if (env->tabs) {
  2483. s += snprintf(s, 20, "[tabs]");
  2484. } else {
  2485. s += snprintf(s, 20, "[spaces=%d]", env->tabstop);
  2486. }
  2487. if (global_config.yanks) {
  2488. s += snprintf(s, 20, "[y:%ld]", global_config.yank_count);
  2489. }
  2490. if (env->indent) {
  2491. s += snprintf(s, 20, "[indent]");
  2492. }
  2493. /* Pre-render the right hand side of the status bar */
  2494. char right_hand[1024];
  2495. snprintf(right_hand, 1024, "Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2496. if (env->file_name) {
  2497. int len = strlen(env->file_name);
  2498. int i = 0;
  2499. while (len > 5 && len > (int)global_config.term_width - (int)strlen(right_hand) - (int)strlen(status_bits) - 5) {
  2500. len--;
  2501. i += 1;
  2502. }
  2503. printf("%s%s", i > 0 ? "<" : "", env->file_name + i);
  2504. } else {
  2505. printf("[No Name]");
  2506. }
  2507. printf(" ");
  2508. printf("%s", status_bits);
  2509. /* Clear the rest of the status bar */
  2510. clear_to_end();
  2511. /* Move the cursor appropriately to draw it */
  2512. place_cursor(global_config.term_width - strlen(right_hand), global_config.term_height - 1);
  2513. /* TODO: What if we're localized and this has wide chars? */
  2514. printf("%s",right_hand);
  2515. }
  2516. /**
  2517. * Redraw the navigation numbers on the right side of the command line
  2518. */
  2519. void redraw_nav_buffer() {
  2520. if (nav_buffer) {
  2521. store_cursor();
  2522. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2523. printf("%s", nav_buf);
  2524. clear_to_end();
  2525. restore_cursor();
  2526. }
  2527. }
  2528. /**
  2529. * Draw the command line
  2530. *
  2531. * The command line either has input from the user (:quit, :!make, etc.)
  2532. * or shows the INSERT (or VISUAL in the future) mode name.
  2533. */
  2534. void redraw_commandline(void) {
  2535. /* Hide cursor while rendering */
  2536. hide_cursor();
  2537. /* Move cursor to the last line */
  2538. place_cursor(1, global_config.term_height);
  2539. /* Set background color */
  2540. paint_line(COLOR_BG);
  2541. set_colors(COLOR_FG, COLOR_BG);
  2542. /* If we are in an edit mode, note that. */
  2543. if (env->mode == MODE_INSERT) {
  2544. set_bold();
  2545. printf("-- INSERT --");
  2546. clear_to_end();
  2547. unset_bold();
  2548. } else if (env->mode == MODE_LINE_SELECTION) {
  2549. set_bold();
  2550. printf("-- LINE SELECTION -- (%d:%d)",
  2551. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2552. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2553. );
  2554. clear_to_end();
  2555. unset_bold();
  2556. } else if (env->mode == MODE_COL_SELECTION) {
  2557. set_bold();
  2558. printf("-- COL SELECTION -- (%d:%d %d)",
  2559. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2560. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2561. (env->sel_col)
  2562. );
  2563. clear_to_end();
  2564. unset_bold();
  2565. } else if (env->mode == MODE_COL_INSERT) {
  2566. set_bold();
  2567. printf("-- COL INSERT -- (%d:%d %d)",
  2568. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2569. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2570. (env->sel_col)
  2571. );
  2572. clear_to_end();
  2573. unset_bold();
  2574. } else if (env->mode == MODE_REPLACE) {
  2575. set_bold();
  2576. printf("-- REPLACE --");
  2577. clear_to_end();
  2578. unset_bold();
  2579. } else if (env->mode == MODE_CHAR_SELECTION) {
  2580. set_bold();
  2581. printf("-- CHAR SELECTION -- ");
  2582. clear_to_end();
  2583. unset_bold();
  2584. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2585. set_bold();
  2586. printf("-- DIRECTORY BROWSE --");
  2587. clear_to_end();
  2588. unset_bold();
  2589. } else {
  2590. clear_to_end();
  2591. }
  2592. redraw_nav_buffer();
  2593. }
  2594. /**
  2595. * Draw a message on the command line.
  2596. */
  2597. void render_commandline_message(char * message, ...) {
  2598. /* varargs setup */
  2599. va_list args;
  2600. va_start(args, message);
  2601. char buf[1024];
  2602. /* Process format string */
  2603. vsnprintf(buf, 1024, message, args);
  2604. va_end(args);
  2605. /* Hide cursor while rendering */
  2606. hide_cursor();
  2607. /* Move cursor to the last line */
  2608. place_cursor(1, global_config.term_height);
  2609. /* Set background color */
  2610. paint_line(COLOR_BG);
  2611. set_colors(COLOR_FG, COLOR_BG);
  2612. printf("%s", buf);
  2613. /* Clear the rest of the status bar */
  2614. clear_to_end();
  2615. redraw_nav_buffer();
  2616. }
  2617. BIM_ACTION(redraw_all, 0,
  2618. "Repaint the screen."
  2619. )(void) {
  2620. redraw_tabbar();
  2621. redraw_text();
  2622. if (left_buffer) {
  2623. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2624. }
  2625. redraw_statusbar();
  2626. redraw_commandline();
  2627. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND || global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  2628. render_command_input_buffer();
  2629. }
  2630. }
  2631. void pause_for_key(void) {
  2632. int c;
  2633. while ((c = bim_getch())== -1);
  2634. bim_unget(c);
  2635. redraw_all();
  2636. }
  2637. /**
  2638. * Redraw all screen elements except the other split view.
  2639. */
  2640. void redraw_most(void) {
  2641. redraw_tabbar();
  2642. redraw_text();
  2643. redraw_statusbar();
  2644. redraw_commandline();
  2645. }
  2646. /**
  2647. * Disable screen splitting.
  2648. */
  2649. void unsplit(void) {
  2650. if (left_buffer) {
  2651. left_buffer->left = 0;
  2652. left_buffer->width = global_config.term_width;
  2653. }
  2654. if (right_buffer) {
  2655. right_buffer->left = 0;
  2656. right_buffer->width = global_config.term_width;
  2657. }
  2658. left_buffer = NULL;
  2659. right_buffer = NULL;
  2660. redraw_all();
  2661. }
  2662. /**
  2663. * Update the terminal title bar
  2664. */
  2665. void update_title(void) {
  2666. if (!global_config.can_title) return;
  2667. char cwd[1024] = {'/',0};
  2668. getcwd(cwd, 1024);
  2669. for (int i = 1; i < 3; ++i) {
  2670. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2671. }
  2672. }
  2673. /**
  2674. * Mark this buffer as modified and
  2675. * redraw the status and tabbar if needed.
  2676. */
  2677. void set_modified(void) {
  2678. /* If it was already marked modified, no need to do anything */
  2679. if (env->modified) return;
  2680. /* Mark as modified */
  2681. env->modified = 1;
  2682. /* Redraw some things */
  2683. update_title();
  2684. redraw_tabbar();
  2685. redraw_statusbar();
  2686. }
  2687. /**
  2688. * Draw a message on the status line
  2689. */
  2690. void render_status_message(char * message, ...) {
  2691. /* varargs setup */
  2692. va_list args;
  2693. va_start(args, message);
  2694. char buf[1024];
  2695. /* Process format string */
  2696. vsnprintf(buf, 1024, message, args);
  2697. va_end(args);
  2698. /* Hide cursor while rendering */
  2699. hide_cursor();
  2700. /* Move cursor to the status bar line (second from bottom */
  2701. place_cursor(1, global_config.term_height - 1);
  2702. /* Set background colors for status line */
  2703. paint_line(COLOR_STATUS_BG);
  2704. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2705. printf("%s", buf);
  2706. /* Clear the rest of the status bar */
  2707. clear_to_end();
  2708. }
  2709. /**
  2710. * Draw an errormessage to the command line.
  2711. */
  2712. void render_error(char * message, ...) {
  2713. /* varargs setup */
  2714. va_list args;
  2715. va_start(args, message);
  2716. char buf[1024];
  2717. /* Process format string */
  2718. vsnprintf(buf, 1024, message, args);
  2719. va_end(args);
  2720. /* Hide cursor while rendering */
  2721. hide_cursor();
  2722. /* Move cursor to the command line */
  2723. place_cursor(1, global_config.term_height);
  2724. /* Set appropriate error message colors */
  2725. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2726. /* Draw the message */
  2727. printf("%s", buf);
  2728. }
  2729. char * paren_pairs = "()[]{}<>";
  2730. void find_matching_paren(int * out_line, int * out_col, int in_col);
  2731. int is_paren(int c) {
  2732. char * p = paren_pairs;
  2733. while (*p) {
  2734. if (c == *p) return 1;
  2735. p++;
  2736. }
  2737. return 0;
  2738. }
  2739. #define _rehighlight_parens() do { \
  2740. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  2741. if (i == line-1 && j == col-1) { \
  2742. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  2743. continue; \
  2744. } else { \
  2745. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  2746. } \
  2747. } \
  2748. redraw_line(i); \
  2749. } while (0)
  2750. /**
  2751. * If the config option is enabled, find the matching
  2752. * paren character and highlight it with the SELECT
  2753. * colors, clearing out other SELECT values. As we
  2754. * co-opt the SELECT flag, don't do this in selection
  2755. * modes - only in normal and insert modes.
  2756. */
  2757. void highlight_matching_paren(void) {
  2758. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  2759. if (!global_config.highlight_parens) return;
  2760. int line = -1, col = -1;
  2761. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  2762. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  2763. find_matching_paren(&line, &col, 1);
  2764. } 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)) {
  2765. find_matching_paren(&line, &col, 2);
  2766. }
  2767. if (env->highlighting_paren == -1 && line == -1) return;
  2768. if (env->highlighting_paren > 0) {
  2769. int i = env->highlighting_paren - 1;
  2770. _rehighlight_parens();
  2771. }
  2772. if (env->highlighting_paren != line && line != -1) {
  2773. int i = line - 1;
  2774. _rehighlight_parens();
  2775. }
  2776. env->highlighting_paren = line;
  2777. }
  2778. /**
  2779. * Recalculate syntax for the matched paren.
  2780. * Useful when entering selection modes.
  2781. */
  2782. void unhighlight_matching_paren(void) {
  2783. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  2784. for (int i = env->highlighting_paren - 1; i <= env->highlighting_paren + 1; ++i) {
  2785. if (i >= 1 && i <= env->line_count) {
  2786. recalculate_syntax(env->lines[i-1], i-1);
  2787. redraw_line(i-1);
  2788. }
  2789. }
  2790. env->highlighting_paren = -1;
  2791. }
  2792. }
  2793. /**
  2794. * Move the cursor to the appropriate location based
  2795. * on where it is in the text region.
  2796. *
  2797. * This does some additional math to set the text
  2798. * region horizontal offset.
  2799. */
  2800. void place_cursor_actual(void) {
  2801. /* Invalid positions */
  2802. if (env->line_no < 1) env->line_no = 1;
  2803. if (env->col_no < 1) env->col_no = 1;
  2804. /* Account for the left hand gutter */
  2805. int num_size = num_width() + 3;
  2806. int x = num_size + 1 - env->coffset;
  2807. /* Determine where the cursor is physically */
  2808. for (int i = 0; i < env->col_no - 1; ++i) {
  2809. char_t * c = &env->lines[env->line_no-1]->text[i];
  2810. x += c->display_width;
  2811. }
  2812. /* y is a bit easier to calculate */
  2813. int y = env->line_no - env->offset + 1;
  2814. int needs_redraw = 0;
  2815. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  2816. y++;
  2817. env->offset--;
  2818. needs_redraw = 1;
  2819. }
  2820. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  2821. y--;
  2822. env->offset++;
  2823. needs_redraw = 1;
  2824. }
  2825. if (needs_redraw) {
  2826. redraw_text();
  2827. redraw_tabbar();
  2828. redraw_statusbar();
  2829. redraw_commandline();
  2830. }
  2831. /* If the cursor has gone off screen to the right... */
  2832. if (x > env->width - 1) {
  2833. /* Adjust the offset appropriately to scroll horizontally */
  2834. int diff = x - (env->width - 1);
  2835. env->coffset += diff;
  2836. x -= diff;
  2837. redraw_text();
  2838. }
  2839. /* Same for scrolling horizontally to the left */
  2840. if (x < num_size + 1) {
  2841. int diff = (num_size + 1) - x;
  2842. env->coffset -= diff;
  2843. x += diff;
  2844. redraw_text();
  2845. }
  2846. highlight_matching_paren();
  2847. recalculate_current_line();
  2848. /* Move the actual terminal cursor */
  2849. place_cursor(x+env->left,y);
  2850. /* Show the cursor */
  2851. show_cursor();
  2852. }
  2853. /**
  2854. * If the screen is split, update the split sizes based
  2855. * on the new terminal width and the user's split_percent setting.
  2856. */
  2857. void update_split_size(void) {
  2858. if (!left_buffer) return;
  2859. if (left_buffer == right_buffer) {
  2860. if (left_buffer->left == 0) {
  2861. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2862. } else {
  2863. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  2864. right_buffer->width = global_config.term_width - right_buffer->left;
  2865. }
  2866. return;
  2867. }
  2868. left_buffer->left = 0;
  2869. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2870. right_buffer->left = left_buffer->width;
  2871. right_buffer->width = global_config.term_width - left_buffer->width;
  2872. }
  2873. /**
  2874. * Update screen size
  2875. */
  2876. void update_screen_size(void) {
  2877. struct winsize w;
  2878. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  2879. global_config.term_width = w.ws_col;
  2880. global_config.term_height = w.ws_row;
  2881. if (env) {
  2882. if (left_buffer) {
  2883. update_split_size();
  2884. } else if (env != left_buffer && env != right_buffer) {
  2885. env->width = w.ws_col;
  2886. }
  2887. }
  2888. for (int i = 0; i < buffers_len; ++i) {
  2889. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  2890. buffers[i]->width = w.ws_col;
  2891. }
  2892. }
  2893. }
  2894. /**
  2895. * Handle terminal size changes
  2896. */
  2897. void SIGWINCH_handler(int sig) {
  2898. (void)sig;
  2899. update_screen_size();
  2900. redraw_all();
  2901. signal(SIGWINCH, SIGWINCH_handler);
  2902. }
  2903. /**
  2904. * Handle suspend
  2905. */
  2906. void SIGTSTP_handler(int sig) {
  2907. (void)sig;
  2908. mouse_disable();
  2909. set_buffered();
  2910. reset();
  2911. clear_screen();
  2912. show_cursor();
  2913. unset_alternate_screen();
  2914. fflush(stdout);
  2915. signal(SIGTSTP, SIG_DFL);
  2916. raise(SIGTSTP);
  2917. }
  2918. void SIGCONT_handler(int sig) {
  2919. (void)sig;
  2920. set_alternate_screen();
  2921. set_unbuffered();
  2922. update_screen_size();
  2923. mouse_enable();
  2924. redraw_all();
  2925. update_title();
  2926. signal(SIGCONT, SIGCONT_handler);
  2927. signal(SIGTSTP, SIGTSTP_handler);
  2928. }
  2929. void try_to_center() {
  2930. int half_a_screen = (global_config.term_height - 3) / 2;
  2931. if (half_a_screen < env->line_no) {
  2932. env->offset = env->line_no - half_a_screen;
  2933. } else {
  2934. env->offset = 0;
  2935. }
  2936. }
  2937. BIM_ACTION(suspend, 0,
  2938. "Suspend bim and the rest of the job it was run in."
  2939. )(void) {
  2940. kill(0, SIGTSTP);
  2941. }
  2942. /**
  2943. * Move the cursor to a specific line.
  2944. */
  2945. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  2946. "Jump to the requested line."
  2947. )(int line) {
  2948. if (line == -1) line = env->line_count;
  2949. /* Respect file bounds */
  2950. if (line < 1) line = 1;
  2951. if (line > env->line_count) line = env->line_count;
  2952. /* Move the cursor / text region offsets */
  2953. env->coffset = 0;
  2954. env->line_no = line;
  2955. env->col_no = 1;
  2956. if (!env->loading) {
  2957. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  2958. place_cursor_actual();
  2959. } else {
  2960. try_to_center();
  2961. }
  2962. redraw_most();
  2963. } else {
  2964. try_to_center();
  2965. }
  2966. }
  2967. /**
  2968. * Processs (part of) a file and add it to a buffer.
  2969. */
  2970. void add_buffer(uint8_t * buf, int size) {
  2971. for (int i = 0; i < size; ++i) {
  2972. if (!decode(&state, &codepoint_r, buf[i])) {
  2973. uint32_t c = codepoint_r;
  2974. if (c == '\n') {
  2975. 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') {
  2976. env->lines[env->line_no-1]->actual--;
  2977. env->crnl = 1;
  2978. }
  2979. env->lines = add_line(env->lines, env->line_no);
  2980. env->col_no = 1;
  2981. env->line_no += 1;
  2982. } else if (env->crnl && c == '\r') {
  2983. continue;
  2984. } else {
  2985. char_t _c;
  2986. _c.codepoint = (uint32_t)c;
  2987. _c.flags = 0;
  2988. _c.display_width = codepoint_width((wchar_t)c);
  2989. line_t * line = env->lines[env->line_no - 1];
  2990. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  2991. if (line != nline) {
  2992. env->lines[env->line_no - 1] = nline;
  2993. }
  2994. env->col_no += 1;
  2995. }
  2996. } else if (state == UTF8_REJECT) {
  2997. state = 0;
  2998. }
  2999. }
  3000. }
  3001. /**
  3002. * Add a raw string to a buffer. Convenience wrapper
  3003. * for add_buffer for nil-terminated strings.
  3004. */
  3005. void add_string(char * string) {
  3006. add_buffer((uint8_t*)string,strlen(string));
  3007. }
  3008. int str_ends_with(const char * haystack, const char * needle) {
  3009. int i = strlen(haystack);
  3010. int j = strlen(needle);
  3011. do {
  3012. if (haystack[i] != needle[j]) return 0;
  3013. if (j == 0) return 1;
  3014. if (i == 0) return 0;
  3015. i--;
  3016. j--;
  3017. } while (1);
  3018. }
  3019. /**
  3020. * Find a syntax highlighter for the given filename.
  3021. */
  3022. struct syntax_definition * match_syntax(char * file) {
  3023. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3024. for (char ** ext = s->ext; *ext; ++ext) {
  3025. if (str_ends_with(file, *ext)) return s;
  3026. }
  3027. }
  3028. return NULL;
  3029. }
  3030. /**
  3031. * Set the syntax configuration by the name of the syntax highlighter.
  3032. */
  3033. void set_syntax_by_name(const char * name) {
  3034. if (!strcmp(name,"none")) {
  3035. for (int i = 0; i < env->line_count; ++i) {
  3036. env->lines[i]->istate = -1;
  3037. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3038. env->lines[i]->text[j].flags = 0;
  3039. }
  3040. }
  3041. redraw_all();
  3042. return;
  3043. }
  3044. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3045. if (!strcmp(name,s->name)) {
  3046. env->syntax = s;
  3047. for (int i = 0; i < env->line_count; ++i) {
  3048. env->lines[i]->istate = -1;
  3049. }
  3050. for (int i = 0; i < env->line_count; ++i) {
  3051. recalculate_syntax(env->lines[i],i);
  3052. }
  3053. redraw_all();
  3054. return;
  3055. }
  3056. }
  3057. render_error("unrecognized syntax type");
  3058. }
  3059. /**
  3060. * Check if a string is all numbers.
  3061. */
  3062. int is_all_numbers(const char * c) {
  3063. while (*c) {
  3064. if (!isdigit(*c)) return 0;
  3065. c++;
  3066. }
  3067. return 1;
  3068. }
  3069. struct file_listing {
  3070. int type;
  3071. char * filename;
  3072. };
  3073. int sort_files(const void * a, const void * b) {
  3074. struct file_listing * _a = (struct file_listing *)a;
  3075. struct file_listing * _b = (struct file_listing *)b;
  3076. if (_a->type == _b->type) {
  3077. return strcmp(_a->filename, _b->filename);
  3078. } else {
  3079. return _a->type - _b->type;
  3080. }
  3081. }
  3082. void read_directory_into_buffer(char * file) {
  3083. DIR * dirp = opendir(file);
  3084. if (!dirp) {
  3085. env->loading = 0;
  3086. return;
  3087. }
  3088. add_string("# Directory listing for `");
  3089. add_string(file);
  3090. add_string("`\n");
  3091. /* Flexible array to hold directory contents */
  3092. int available = 32;
  3093. int count = 0;
  3094. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3095. /* Read directory */
  3096. struct dirent * ent = readdir(dirp);
  3097. while (ent) {
  3098. struct stat statbuf;
  3099. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3100. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3101. stat(tmp, &statbuf);
  3102. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3103. if (count + 1 == available) {
  3104. available *= 2; \
  3105. files = realloc(files, sizeof(struct file_listing) * available); \
  3106. } \
  3107. files[count].type = type;
  3108. files[count].filename = strdup(ent->d_name);
  3109. count++;
  3110. ent = readdir(dirp);
  3111. }
  3112. closedir(dirp);
  3113. /* Sort directory entries */
  3114. qsort(files, count, sizeof(struct file_listing), sort_files);
  3115. for (int i = 0; i < count; ++i) {
  3116. add_string(files[i].type == 'd' ? "d" : "f");
  3117. add_string(" ");
  3118. add_string(files[i].filename);
  3119. add_string("\n");
  3120. free(files[i].filename);
  3121. }
  3122. free(files);
  3123. env->file_name = strdup(file);
  3124. env->syntax = find_syntax_calculator("dirent");
  3125. for (int i = 0; i < env->line_count; ++i) {
  3126. recalculate_syntax(env->lines[i],i);
  3127. }
  3128. env->readonly = 1;
  3129. env->loading = 0;
  3130. env->mode = MODE_DIRECTORY_BROWSE;
  3131. env->line_no = 1;
  3132. redraw_all();
  3133. }
  3134. BIM_ACTION(open_file_from_line, 0,
  3135. "When browsing a directory, open the file under the cursor."
  3136. )(void) {
  3137. if (env->lines[env->line_no-1]->actual < 1) return;
  3138. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3139. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3140. /* Collect file name */
  3141. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3142. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3143. char * t = tmp;
  3144. /* Start by copying the filename */
  3145. t += sprintf(t, "%s/", env->file_name);
  3146. /* Start from character 2 to skip d/f and space */
  3147. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3148. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3149. }
  3150. *t = '\0';
  3151. /* Normalize */
  3152. char tmp_path[PATH_MAX+1];
  3153. if (!realpath(tmp, tmp_path)) {
  3154. free(tmp);
  3155. return;
  3156. }
  3157. free(tmp);
  3158. /* Open file */
  3159. buffer_t * old_buffer = env;
  3160. open_file(tmp_path);
  3161. buffer_close(old_buffer);
  3162. update_title();
  3163. redraw_all();
  3164. }
  3165. int line_matches(line_t * line, char * string) {
  3166. uint32_t c, state = 0;
  3167. int i = 0;
  3168. while (*string) {
  3169. if (!decode(&state, &c, *string)) {
  3170. if (i >= line->actual) return 0;
  3171. if (line->text[i].codepoint != c) return 0;
  3172. string++;
  3173. i++;
  3174. } else if (state == UTF8_REJECT) {
  3175. state = 0;
  3176. }
  3177. }
  3178. return 1;
  3179. }
  3180. /**
  3181. * Create a new buffer from a file.
  3182. */
  3183. void open_file(char * file) {
  3184. env = buffer_new();
  3185. env->width = global_config.term_width;
  3186. env->left = 0;
  3187. env->loading = 1;
  3188. setup_buffer(env);
  3189. FILE * f;
  3190. int init_line = -1;
  3191. if (!strcmp(file,"-")) {
  3192. /**
  3193. * Read file from stdin. stderr provides terminal input.
  3194. */
  3195. if (isatty(STDIN_FILENO)) {
  3196. if (buffers_len == 1) {
  3197. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3198. }
  3199. close_buffer();
  3200. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3201. return;
  3202. }
  3203. f = stdin;
  3204. env->modified = 1;
  3205. } else {
  3206. char * l = strrchr(file, ':');
  3207. if (l && is_all_numbers(l+1)) {
  3208. *l = '\0';
  3209. l++;
  3210. init_line = atoi(l);
  3211. }
  3212. struct stat statbuf;
  3213. if (!stat(file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3214. read_directory_into_buffer(file);
  3215. return;
  3216. }
  3217. f = fopen(file, "r");
  3218. env->file_name = strdup(file);
  3219. }
  3220. if (!f) {
  3221. if (global_config.highlight_on_open) {
  3222. env->syntax = match_syntax(file);
  3223. }
  3224. env->loading = 0;
  3225. if (global_config.go_to_line) {
  3226. goto_line(1);
  3227. }
  3228. if (env->syntax && env->syntax->prefers_spaces) {
  3229. env->tabs = 0;
  3230. }
  3231. return;
  3232. }
  3233. uint8_t buf[BLOCK_SIZE];
  3234. state = 0;
  3235. while (!feof(f) && !ferror(f)) {
  3236. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3237. add_buffer(buf, r);
  3238. }
  3239. if (ferror(f)) {
  3240. env->loading = 0;
  3241. return;
  3242. }
  3243. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3244. /* Remove blank line from end */
  3245. env->lines = remove_line(env->lines, env->line_no-1);
  3246. }
  3247. if (global_config.highlight_on_open) {
  3248. env->syntax = match_syntax(file);
  3249. if (!env->syntax) {
  3250. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3251. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3252. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3253. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3254. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3255. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3256. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3257. }
  3258. if (!env->syntax && global_config.syntax_fallback) {
  3259. set_syntax_by_name(global_config.syntax_fallback);
  3260. }
  3261. for (int i = 0; i < env->line_count; ++i) {
  3262. recalculate_syntax(env->lines[i],i);
  3263. }
  3264. }
  3265. /* Try to automatically figure out tabs vs. spaces */
  3266. int tabs = 0, spaces = 0;
  3267. for (int i = 0; i < env->line_count; ++i) {
  3268. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3269. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3270. if (env->lines[i]->text[0].codepoint == ' ' &&
  3271. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3272. spaces++;
  3273. }
  3274. }
  3275. if (spaces > tabs) {
  3276. env->tabs = 0;
  3277. }
  3278. /* TODO figure out tabstop for spaces? */
  3279. env->loading = 0;
  3280. if (global_config.check_git) {
  3281. env->checkgitstatusonwrite = 1;
  3282. git_examine(file);
  3283. }
  3284. for (int i = 0; i < env->line_count; ++i) {
  3285. recalculate_tabs(env->lines[i]);
  3286. }
  3287. if (global_config.go_to_line) {
  3288. if (init_line != -1) {
  3289. goto_line(init_line);
  3290. } else {
  3291. env->line_no = 1;
  3292. env->col_no = 1;
  3293. fetch_from_biminfo(env);
  3294. place_cursor_actual();
  3295. redraw_all();
  3296. set_preferred_column();
  3297. }
  3298. }
  3299. fclose(f);
  3300. }
  3301. /**
  3302. * Clean up the terminal and exit the editor.
  3303. */
  3304. void quit(const char * message) {
  3305. mouse_disable();
  3306. set_buffered();
  3307. reset();
  3308. clear_screen();
  3309. show_cursor();
  3310. unset_alternate_screen();
  3311. if (message) {
  3312. fprintf(stdout, "%s\n", message);
  3313. }
  3314. exit(0);
  3315. }
  3316. /**
  3317. * Try to quit, but don't continue if there are
  3318. * modified buffers open.
  3319. */
  3320. void try_quit(void) {
  3321. for (int i = 0; i < buffers_len; i++ ) {
  3322. buffer_t * _env = buffers[i];
  3323. if (_env->modified) {
  3324. if (_env->file_name) {
  3325. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3326. } else {
  3327. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3328. }
  3329. return;
  3330. }
  3331. }
  3332. /* Close all buffers */
  3333. while (buffers_len) {
  3334. buffer_close(buffers[0]);
  3335. }
  3336. quit(NULL);
  3337. }
  3338. /**
  3339. * Switch to the previous buffer
  3340. */
  3341. BIM_ACTION(previous_tab, 0,
  3342. "Switch the previoius tab"
  3343. )(void) {
  3344. buffer_t * last = NULL;
  3345. for (int i = 0; i < buffers_len; i++) {
  3346. buffer_t * _env = buffers[i];
  3347. if (_env == env) {
  3348. if (last) {
  3349. /* Wrap around */
  3350. env = last;
  3351. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3352. redraw_all();
  3353. update_title();
  3354. return;
  3355. } else {
  3356. env = buffers[buffers_len-1];
  3357. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3358. redraw_all();
  3359. update_title();
  3360. return;
  3361. }
  3362. }
  3363. last = _env;
  3364. }
  3365. }
  3366. /**
  3367. * Switch to the next buffer
  3368. */
  3369. BIM_ACTION(next_tab, 0,
  3370. "Switch to the next tab"
  3371. )(void) {
  3372. for (int i = 0; i < buffers_len; i++) {
  3373. buffer_t * _env = buffers[i];
  3374. if (_env == env) {
  3375. if (i != buffers_len - 1) {
  3376. env = buffers[i+1];
  3377. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3378. redraw_all();
  3379. update_title();
  3380. return;
  3381. } else {
  3382. /* Wrap around */
  3383. env = buffers[0];
  3384. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3385. redraw_all();
  3386. update_title();
  3387. return;
  3388. }
  3389. }
  3390. }
  3391. }
  3392. /**
  3393. * Check for modified lines in a file by examining `git diff` output.
  3394. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3395. */
  3396. int git_examine(char * filename) {
  3397. if (env->modified) return 1;
  3398. int fds[2];
  3399. pipe(fds);
  3400. int child = fork();
  3401. if (child == 0) {
  3402. FILE * dev_null = fopen("/dev/null","w");
  3403. close(fds[0]);
  3404. dup2(fds[1], STDOUT_FILENO);
  3405. dup2(fileno(dev_null), STDERR_FILENO);
  3406. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3407. exit(execvp("git",args));
  3408. } else if (child < 0) {
  3409. return 1;
  3410. }
  3411. close(fds[1]);
  3412. FILE * f = fdopen(fds[0],"r");
  3413. int line_offset = 0;
  3414. while (!feof(f)) {
  3415. int c = fgetc(f);
  3416. if (c < 0) break;
  3417. if (c == '@' && line_offset == 0) {
  3418. /* Read line offset, count */
  3419. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3420. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3421. int from_line = 0;
  3422. int from_count = 0;
  3423. int to_line = 0;
  3424. int to_count = 0;
  3425. fscanf(f,"%d",&from_line);
  3426. if (fgetc(f) == ',') {
  3427. fscanf(f,"%d",&from_count);
  3428. } else {
  3429. from_count = 1;
  3430. }
  3431. fscanf(f,"%d",&to_line);
  3432. if (fgetc(f) == ',') {
  3433. fscanf(f,"%d",&to_count);
  3434. } else {
  3435. to_count = 1;
  3436. }
  3437. if (to_line > env->line_count) continue;
  3438. if (from_count == 0 && to_count > 0) {
  3439. /* No -, all + means all of to_count is green */
  3440. for (int i = 0; i < to_count; ++i) {
  3441. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3442. }
  3443. } else if (from_count > 0 && to_count == 0) {
  3444. /*
  3445. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3446. * Note that to_line is one lower than the affacted line, so we don't need to mes with indexes.
  3447. */
  3448. if (to_line >= env->line_count) continue;
  3449. env->lines[to_line]->rev_status = 4; /* Red */
  3450. } else if (from_count > 0 && from_count == to_count) {
  3451. /* from = to, all modified */
  3452. for (int i = 0; i < to_count; ++i) {
  3453. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3454. }
  3455. } else if (from_count > 0 && from_count < to_count) {
  3456. /* from < to, some modified, some added */
  3457. for (int i = 0; i < from_count; ++i) {
  3458. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3459. }
  3460. for (int i = from_count; i < to_count; ++i) {
  3461. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3462. }
  3463. } else if (to_count > 0 && from_count > to_count) {
  3464. /* from > to, we deleted but also modified some lines */
  3465. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3466. for (int i = 1; i < to_count; ++i) {
  3467. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3468. }
  3469. }
  3470. }
  3471. }
  3472. if (c == '\n') {
  3473. line_offset = 0;
  3474. continue;
  3475. }
  3476. line_offset++;
  3477. }
  3478. fclose(f);
  3479. return 0;
  3480. }
  3481. /**
  3482. * Write active buffer to file
  3483. */
  3484. void write_file(char * file) {
  3485. if (!file) {
  3486. render_error("Need a file to write to.");
  3487. return;
  3488. }
  3489. FILE * f = fopen(file, "w+");
  3490. if (!f) {
  3491. render_error("Failed to open file for writing.");
  3492. return;
  3493. }
  3494. /* Go through each line and convert it back to UTF-8 */
  3495. int i, j;
  3496. for (i = 0; i < env->line_count; ++i) {
  3497. line_t * line = env->lines[i];
  3498. line->rev_status = 0;
  3499. for (j = 0; j < line->actual; j++) {
  3500. char_t c = line->text[j];
  3501. if (c.codepoint == 0) {
  3502. char buf[1] = {0};
  3503. fwrite(buf, 1, 1, f);
  3504. } else {
  3505. char tmp[8] = {0};
  3506. int i = to_eight(c.codepoint, tmp);
  3507. fwrite(tmp, i, 1, f);
  3508. }
  3509. }
  3510. if (env->crnl) fputc('\r', f);
  3511. fputc('\n', f);
  3512. }
  3513. fclose(f);
  3514. /* Mark it no longer modified */
  3515. env->modified = 0;
  3516. env->last_save_history = env->history;
  3517. /* If there was no file name set, set one */
  3518. if (!env->file_name) {
  3519. env->file_name = malloc(strlen(file) + 1);
  3520. memcpy(env->file_name, file, strlen(file) + 1);
  3521. }
  3522. if (env->checkgitstatusonwrite) {
  3523. git_examine(file);
  3524. }
  3525. update_title();
  3526. redraw_all();
  3527. }
  3528. /**
  3529. * Close the active buffer
  3530. */
  3531. void close_buffer(void) {
  3532. buffer_t * previous_env = env;
  3533. buffer_t * new_env = buffer_close(env);
  3534. if (new_env == previous_env) {
  3535. /* ?? Failed to close buffer */
  3536. render_error("lolwat");
  3537. }
  3538. if (left_buffer && env == left_buffer) {
  3539. left_buffer = NULL;
  3540. right_buffer->left = 0;
  3541. right_buffer->width = global_config.term_width;
  3542. right_buffer = NULL;
  3543. } else if (left_buffer && env == right_buffer) {
  3544. right_buffer = NULL;
  3545. left_buffer->left = 0;
  3546. left_buffer->width = global_config.term_width;
  3547. left_buffer = NULL;
  3548. }
  3549. /* No more buffers, exit */
  3550. if (!new_env) {
  3551. quit(NULL);
  3552. }
  3553. /* Set the new active buffer */
  3554. env = new_env;
  3555. /* Redraw the screen */
  3556. redraw_all();
  3557. update_title();
  3558. }
  3559. /**
  3560. * Set the visual column the cursor should attempt to keep
  3561. * when moving up and down based on where the cursor currently is.
  3562. * This should happen whenever the user intentionally changes
  3563. * the cursor's horizontal positioning, such as with left/right
  3564. * arrow keys, word-move, search, mouse, etc.
  3565. */
  3566. void set_preferred_column(void) {
  3567. int c = 0;
  3568. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3569. c += env->lines[env->line_no-1]->text[i].display_width;
  3570. }
  3571. env->preferred_column = c;
  3572. }
  3573. BIM_ACTION(cursor_down, 0,
  3574. "Move the cursor one line down."
  3575. )(void) {
  3576. /* If this isn't already the last line... */
  3577. if (env->line_no < env->line_count) {
  3578. /* Move the cursor down */
  3579. env->line_no += 1;
  3580. /* Try to place the cursor horizontally at the preferred column */
  3581. int _x = 0;
  3582. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3583. char_t * c = &env->lines[env->line_no-1]->text[i];
  3584. _x += c->display_width;
  3585. env->col_no = i+1;
  3586. if (_x > env->preferred_column) {
  3587. break;
  3588. }
  3589. }
  3590. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3591. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3592. }
  3593. /*
  3594. * If the horizontal cursor position exceeds the width the new line,
  3595. * then move the cursor left to the extent of the new line.
  3596. *
  3597. * If we're in insert mode, we can go one cell beyond the end of the line
  3598. */
  3599. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3600. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3601. if (env->col_no == 0) env->col_no = 1;
  3602. }
  3603. if (env->loading) return;
  3604. /*
  3605. * If the screen was scrolled horizontally, unscroll it;
  3606. * if it will be scrolled on this line as well, that will
  3607. * be handled by place_cursor_actual
  3608. */
  3609. int redraw = 0;
  3610. if (env->coffset != 0) {
  3611. env->coffset = 0;
  3612. redraw = 1;
  3613. }
  3614. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3615. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  3616. env->offset += 1;
  3617. /* Tell terminal to scroll */
  3618. if (global_config.can_scroll && !left_buffer) {
  3619. shift_up(1);
  3620. /* A new line appears on screen at the bottom, draw it */
  3621. int l = global_config.term_height - global_config.bottom_size - 1;
  3622. if (env->offset + l < env->line_count + 1) {
  3623. redraw_line(env->offset + l-1);
  3624. } else {
  3625. draw_excess_line(l - 1);
  3626. }
  3627. } else {
  3628. redraw_text();
  3629. }
  3630. redraw_tabbar();
  3631. redraw_statusbar();
  3632. redraw_commandline();
  3633. place_cursor_actual();
  3634. return;
  3635. } else if (redraw) {
  3636. /* Otherwise, if we need to redraw because of coffset change, do that */
  3637. redraw_text();
  3638. }
  3639. set_history_break();
  3640. /* Update the status bar */
  3641. redraw_statusbar();
  3642. /* Place the terminal cursor again */
  3643. place_cursor_actual();
  3644. }
  3645. }
  3646. BIM_ACTION(cursor_up, 0,
  3647. "Move the cursor up one line."
  3648. )(void) {
  3649. /* If this isn't the first line already */
  3650. if (env->line_no > 1) {
  3651. /* Move the cursor down */
  3652. env->line_no -= 1;
  3653. /* Try to place the cursor horizontally at the preferred column */
  3654. int _x = 0;
  3655. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3656. char_t * c = &env->lines[env->line_no-1]->text[i];
  3657. _x += c->display_width;
  3658. env->col_no = i+1;
  3659. if (_x > env->preferred_column) {
  3660. break;
  3661. }
  3662. }
  3663. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3664. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3665. }
  3666. /*
  3667. * If the horizontal cursor position exceeds the width the new line,
  3668. * then move the cursor left to the extent of the new line.
  3669. *
  3670. * If we're in insert mode, we can go one cell beyond the end of the line
  3671. */
  3672. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3673. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3674. if (env->col_no == 0) env->col_no = 1;
  3675. }
  3676. if (env->loading) return;
  3677. /*
  3678. * If the screen was scrolled horizontally, unscroll it;
  3679. * if it will be scrolled on this line as well, that will
  3680. * be handled by place_cursor_actual
  3681. */
  3682. int redraw = 0;
  3683. if (env->coffset != 0) {
  3684. env->coffset = 0;
  3685. redraw = 1;
  3686. }
  3687. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  3688. if (env->line_no <= e) {
  3689. env->offset -= 1;
  3690. /* Tell terminal to scroll */
  3691. if (global_config.can_scroll && !left_buffer) {
  3692. shift_down(1);
  3693. /*
  3694. * The line at the top of the screen should always be real
  3695. * so we can just call redraw_line here
  3696. */
  3697. redraw_line(env->offset);
  3698. } else {
  3699. redraw_text();
  3700. }
  3701. redraw_tabbar();
  3702. redraw_statusbar();
  3703. redraw_commandline();
  3704. place_cursor_actual();
  3705. return;
  3706. } else if (redraw) {
  3707. /* Otherwise, if we need to redraw because of coffset change, do that */
  3708. redraw_text();
  3709. }
  3710. set_history_break();
  3711. /* Update the status bar */
  3712. redraw_statusbar();
  3713. /* Place the terminal cursor again */
  3714. place_cursor_actual();
  3715. }
  3716. }
  3717. BIM_ACTION(cursor_left, 0,
  3718. "Move the cursor one character to the left."
  3719. )(void) {
  3720. if (env->col_no > 1) {
  3721. env->col_no -= 1;
  3722. /* Update the status bar */
  3723. redraw_statusbar();
  3724. /* Place the terminal cursor again */
  3725. place_cursor_actual();
  3726. }
  3727. set_history_break();
  3728. set_preferred_column();
  3729. }
  3730. BIM_ACTION(cursor_right, 0,
  3731. "Move the cursor one character to the right."
  3732. )(void) {
  3733. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  3734. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  3735. env->col_no += 1;
  3736. /* Update the status bar */
  3737. redraw_statusbar();
  3738. /* Place the terminal cursor again */
  3739. place_cursor_actual();
  3740. }
  3741. set_history_break();
  3742. set_preferred_column();
  3743. }
  3744. BIM_ACTION(cursor_home, 0,
  3745. "Move the cursor to the beginning of the line."
  3746. )(void) {
  3747. env->col_no = 1;
  3748. set_history_break();
  3749. set_preferred_column();
  3750. /* Update the status bar */
  3751. redraw_statusbar();
  3752. /* Place the terminal cursor again */
  3753. place_cursor_actual();
  3754. }
  3755. BIM_ACTION(cursor_end, 0,
  3756. "Move the cursor to the end of the line, or past the end in insert mode."
  3757. )(void) {
  3758. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  3759. set_history_break();
  3760. set_preferred_column();
  3761. /* Update the status bar */
  3762. redraw_statusbar();
  3763. /* Place the terminal cursor again */
  3764. place_cursor_actual();
  3765. }
  3766. BIM_ACTION(leave_insert, 0,
  3767. "Leave insert modes and return to normal mode."
  3768. )(void) {
  3769. if (env->col_no > env->lines[env->line_no-1]->actual) {
  3770. env->col_no = env->lines[env->line_no-1]->actual;
  3771. if (env->col_no == 0) env->col_no = 1;
  3772. set_preferred_column();
  3773. }
  3774. set_history_break();
  3775. env->mode = MODE_NORMAL;
  3776. redraw_commandline();
  3777. }
  3778. /**
  3779. * Helper for handling smart case sensitivity.
  3780. */
  3781. int search_matches(uint32_t a, uint32_t b, int mode) {
  3782. if (mode == 0) {
  3783. return a == b;
  3784. } else if (mode == 1) {
  3785. return tolower(a) == tolower(b);
  3786. }
  3787. return 0;
  3788. }
  3789. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  3790. int k = j;
  3791. uint32_t * match = needle;
  3792. if (*match == '^') {
  3793. if (j != 0) return 0;
  3794. match++;
  3795. }
  3796. while (k < line->actual + 1) {
  3797. if (*match == '\0') {
  3798. if (len) *len = k - j;
  3799. return 1;
  3800. }
  3801. if (*match == '$') {
  3802. if (k != line->actual) return 0;
  3803. match++;
  3804. continue;
  3805. }
  3806. if (*match == '.') {
  3807. if (match[1] == '*') {
  3808. int greedy = !(match[2] == '?');
  3809. /* Short-circuit chained .*'s */
  3810. if (match[greedy ? 2 : 3] == '.' && match[greedy ? 3 : 4] == '*') {
  3811. int _len;
  3812. if (subsearch_matches(line, k, &match[greedy ? 2 : 3], ignorecase, &_len)) {
  3813. if (len) *len = _len + k - j;
  3814. return 1;
  3815. }
  3816. return 0;
  3817. }
  3818. int _j = greedy ? line->actual : k;
  3819. int _break = -1;
  3820. int _len = -1;
  3821. if (!match[greedy ? 2 : 3]) {
  3822. _len = greedy ? (line->actual - _j) : 0;
  3823. _break = _j;
  3824. } else {
  3825. while (_j < line->actual + 1 && _j >= k) {
  3826. int len;
  3827. if (subsearch_matches(line, _j, &match[greedy ? 2 : 3], ignorecase, &len)) {
  3828. _break = _j;
  3829. _len = len;
  3830. break;
  3831. }
  3832. _j += (greedy ? -1 : 1);
  3833. }
  3834. }
  3835. if (_break != -1) {
  3836. if (len) *len = (_break - j) + _len;
  3837. return 1;
  3838. }
  3839. return 0;
  3840. } else {
  3841. if (k >= line->actual) return 0;
  3842. match++;
  3843. k++;
  3844. continue;
  3845. }
  3846. }
  3847. if (*match == '\\' && (match[1] == '$' || match[1] == '^' || match[1] == '/' || match[1] == '\\' || match[1] == '.')) {
  3848. match++;
  3849. } else if (*match == '\\' && match[1] == 't') {
  3850. if (line->text[k].codepoint != '\t') break;
  3851. match += 2;
  3852. k++;
  3853. continue;
  3854. }
  3855. if (k == line->actual) break;
  3856. if (!search_matches(*match, line->text[k].codepoint, ignorecase)) break;
  3857. match++;
  3858. k++;
  3859. }
  3860. return 0;
  3861. }
  3862. /**
  3863. * Replace text on a given line with other text.
  3864. */
  3865. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  3866. line_t * line = env->lines[line_no-1];
  3867. int j = col;
  3868. while (j < line->actual + 1) {
  3869. int match_len;
  3870. if (subsearch_matches(line,j,needle,ignorecase,&match_len)) {
  3871. /* Perform replacement */
  3872. for (int i = 0; i < match_len; ++i) {
  3873. line_delete(line, j+1, line_no-1);
  3874. }
  3875. int t = 0;
  3876. for (uint32_t * r = replacement; *r; ++r) {
  3877. char_t _c;
  3878. _c.codepoint = *r;
  3879. _c.flags = 0;
  3880. _c.display_width = codepoint_width(*r);
  3881. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  3882. if (line != nline) {
  3883. env->lines[line_no-1] = nline;
  3884. line = nline;
  3885. }
  3886. t++;
  3887. }
  3888. *out_col = j + t;
  3889. set_modified();
  3890. return;
  3891. }
  3892. j++;
  3893. }
  3894. *out_col = -1;
  3895. }
  3896. #define COMMAND_HISTORY_MAX 255
  3897. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  3898. /**
  3899. * Add a command to the history. If that command was
  3900. * already in history, it is moved to the front of the list;
  3901. * otherwise, the whole list is shifted backwards and
  3902. * overflow is freed up.
  3903. */
  3904. void insert_command_history(char * cmd) {
  3905. /* See if this is already in the history. */
  3906. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  3907. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  3908. if (!strcmp((char*)command_history[i], cmd)) {
  3909. free(command_history[i]);
  3910. amount_to_shift = i;
  3911. break;
  3912. }
  3913. }
  3914. /* Remove last entry that will roll off the stack */
  3915. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  3916. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  3917. }
  3918. /* Roll the history */
  3919. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  3920. command_history[0] = (unsigned char*)strdup(cmd);
  3921. }
  3922. static uint32_t term_colors[] = {
  3923. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  3924. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  3925. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  3926. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  3927. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  3928. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  3929. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  3930. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  3931. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  3932. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  3933. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  3934. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  3935. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  3936. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  3937. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  3938. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  3939. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  3940. 0xeeeeee,
  3941. };
  3942. /**
  3943. * Convert a color setting from terminal format
  3944. * to a hexadecimal color code and add it to the current
  3945. * buffer. This is used for HTML conversion, but could
  3946. * possibly be used for other purposes.
  3947. */
  3948. static void html_convert_color(const char * color_string) {
  3949. char tmp[100];
  3950. if (!strncmp(color_string,"2;",2)) {
  3951. /* 24-bit color */
  3952. int red, green, blue;
  3953. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  3954. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  3955. } else if (!strncmp(color_string,"5;",2)) {
  3956. /* 256 colors; needs lookup table */
  3957. int index;
  3958. sscanf(color_string+2,"%d",&index);
  3959. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  3960. } else {
  3961. /* 16 colors; needs lookup table */
  3962. int index;
  3963. uint32_t color;
  3964. sscanf(color_string+1,"%d",&index);
  3965. if (index >= 10) {
  3966. index -= 10;
  3967. color = term_colors[index+8];
  3968. } else if (index == 9) {
  3969. color = term_colors[0];
  3970. } else {
  3971. color = term_colors[index];
  3972. }
  3973. sprintf(tmp,"#%06x;", (unsigned int)color);
  3974. }
  3975. add_string(tmp);
  3976. char * italic = strstr(color_string,";3");
  3977. if (italic && italic[2] == '\0') {
  3978. add_string(" font-style: oblique;");
  3979. }
  3980. char * bold = strstr(color_string,";1");
  3981. if (bold && bold[2] == '\0') {
  3982. add_string(" font-weight: bold;");
  3983. }
  3984. char * underline = strstr(color_string,";4");
  3985. if (underline && underline[2] == '\0') {
  3986. add_string(" font-decoration: underline;");
  3987. }
  3988. }
  3989. /**
  3990. * Based on vim's :TOhtml
  3991. * Convert syntax-highlighted buffer contents to HTML.
  3992. */
  3993. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  3994. buffer_t * old = env;
  3995. env = buffer_new();
  3996. setup_buffer(env);
  3997. env->loading = 1;
  3998. add_string("<!doctype html>\n");
  3999. add_string("<html>\n");
  4000. add_string(" <head>\n");
  4001. add_string(" <meta charset=\"UTF-8\">\n");
  4002. if (old->file_name) {
  4003. add_string(" <title>");
  4004. add_string(file_basename(old->file_name));
  4005. add_string("</title>\n");
  4006. }
  4007. add_string(" <style>\n");
  4008. add_string(" body {\n");
  4009. add_string(" margin: 0;\n");
  4010. add_string(" -webkit-text-size-adjust: none;\n");
  4011. add_string(" counter-reset: line-no;\n");
  4012. add_string(" background-color: ");
  4013. /* Convert color */
  4014. html_convert_color(COLOR_BG);
  4015. add_string("\n");
  4016. add_string(" }\n");
  4017. for (int i = 0; i < 15; ++i) {
  4018. /* For each of the relevant flags... */
  4019. char tmp[20];
  4020. sprintf(tmp," .s%d { color: ", i);
  4021. add_string(tmp);
  4022. /* These are special */
  4023. if (i == FLAG_NOTICE) {
  4024. html_convert_color(COLOR_SEARCH_FG);
  4025. add_string(" background-color: ");
  4026. html_convert_color(COLOR_SEARCH_BG);
  4027. } else if (i == FLAG_ERROR) {
  4028. html_convert_color(COLOR_ERROR_FG);
  4029. add_string(" background-color: ");
  4030. html_convert_color(COLOR_ERROR_BG);
  4031. } else {
  4032. html_convert_color(flag_to_color(i));
  4033. }
  4034. add_string("}\n");
  4035. }
  4036. add_string(" pre {\n");
  4037. add_string(" margin: 0;\n");
  4038. add_string(" white-space: pre-wrap;\n");
  4039. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4040. add_string(" font-size: 10pt;\n");
  4041. add_string(" }\n");
  4042. add_string(" pre>span {\n");
  4043. add_string(" display: inline-block;\n");
  4044. add_string(" width: 100%;\n");
  4045. add_string(" }\n");
  4046. add_string(" pre>span>a::before {\n");
  4047. add_string(" counter-increment: line-no;\n");
  4048. add_string(" content: counter(line-no);\n");
  4049. add_string(" padding-right: 1em;\n");
  4050. add_string(" width: 3em;\n");
  4051. add_string(" display: inline-block;\n");
  4052. add_string(" text-align: right;\n");
  4053. add_string(" background-color: ");
  4054. html_convert_color(COLOR_NUMBER_BG);
  4055. add_string("\n");
  4056. add_string(" color: ");
  4057. html_convert_color(COLOR_NUMBER_FG);
  4058. add_string("\n");
  4059. add_string(" }\n");
  4060. add_string(" pre>span:target {\n");
  4061. add_string(" background-color: ");
  4062. html_convert_color(COLOR_ALT_BG);
  4063. add_string("\n");
  4064. add_string(" }\n");
  4065. add_string(" pre>span:target>a::before {\n");
  4066. add_string(" background-color: ");
  4067. html_convert_color(COLOR_NUMBER_FG);
  4068. add_string("\n");
  4069. add_string(" color: ");
  4070. html_convert_color(COLOR_NUMBER_BG);
  4071. add_string("\n");
  4072. add_string(" }\n");
  4073. for (int i = 1; i <= env->tabstop; ++i) {
  4074. char tmp[10];
  4075. sprintf(tmp, ".tab%d", i);
  4076. add_string(" ");
  4077. add_string(tmp);
  4078. add_string(">span {\n");
  4079. add_string(" display: inline-block;\n");
  4080. add_string(" overflow: hidden;\n");
  4081. add_string(" width: 0;\n");
  4082. add_string(" height: 0;\n");
  4083. add_string(" }\n");
  4084. add_string(" ");
  4085. add_string(tmp);
  4086. add_string("::after {\n");
  4087. add_string(" content: '»");
  4088. for (int j = 1; j < i; ++j) {
  4089. add_string("·");
  4090. }
  4091. add_string("';\n");
  4092. add_string(" background-color: ");
  4093. html_convert_color(COLOR_ALT_BG);
  4094. add_string("\n");
  4095. add_string(" color: ");
  4096. html_convert_color(COLOR_ALT_FG);
  4097. add_string("\n");
  4098. add_string(" }\n");
  4099. }
  4100. add_string(" .space {\n");
  4101. add_string(" border-left: 1px solid ");
  4102. html_convert_color(COLOR_ALT_FG);
  4103. add_string("\n");
  4104. add_string(" margin-left: -1px;\n");
  4105. add_string(" }\n");
  4106. add_string(" </style>\n");
  4107. add_string(" </head>\n");
  4108. add_string(" <body><pre>\n");
  4109. for (int i = 0; i < old->line_count; ++i) {
  4110. char tmp[100];
  4111. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4112. add_string(tmp);
  4113. int last_flag = -1;
  4114. int opened = 0;
  4115. int all_spaces = 1;
  4116. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4117. char_t c = old->lines[i]->text[j];
  4118. if (c.codepoint != ' ') all_spaces = 0;
  4119. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4120. if (opened) add_string("</span>");
  4121. opened = 1;
  4122. char tmp[100];
  4123. sprintf(tmp, "<span class=\"s%d\">", c.flags & 0x1F);
  4124. add_string(tmp);
  4125. last_flag = (c.flags & 0x1F);
  4126. }
  4127. if (c.codepoint == '<') {
  4128. add_string("&lt;");
  4129. } else if (c.codepoint == '>') {
  4130. add_string("&gt;");
  4131. } else if (c.codepoint == '&') {
  4132. add_string("&amp;");
  4133. } else if (c.codepoint == '\t') {
  4134. char tmp[100];
  4135. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4136. add_string(tmp);
  4137. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4138. add_string("<span class=\"space\"> </span>");
  4139. } else {
  4140. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4141. to_eight(c.codepoint, tmp);
  4142. add_string(tmp);
  4143. }
  4144. }
  4145. if (opened) {
  4146. add_string("</span>");
  4147. } else {
  4148. add_string("<wbr>");
  4149. }
  4150. add_string("</span>\n");
  4151. }
  4152. add_string("</pre></body>\n");
  4153. add_string("</html>\n");
  4154. env->loading = 0;
  4155. env->modified = 1;
  4156. if (old->file_name) {
  4157. char * base = file_basename(old->file_name);
  4158. char * tmp = malloc(strlen(base) + 5);
  4159. *tmp = '\0';
  4160. strcat(tmp, base);
  4161. strcat(tmp, ".htm");
  4162. env->file_name = tmp;
  4163. }
  4164. for (int i = 0; i < env->line_count; ++i) {
  4165. recalculate_tabs(env->lines[i]);
  4166. }
  4167. env->syntax = match_syntax(".htm");
  4168. for (int i = 0; i < env->line_count; ++i) {
  4169. recalculate_syntax(env->lines[i],i);
  4170. }
  4171. redraw_all();
  4172. return 0;
  4173. }
  4174. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4175. int _prefix_command_run_script(char * cmd) {
  4176. if (env->mode == MODE_LINE_SELECTION) {
  4177. int range_top, range_bot;
  4178. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4179. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4180. int in[2];
  4181. pipe(in);
  4182. int out[2];
  4183. pipe(out);
  4184. int child = fork();
  4185. /* Open child process and set up pipes */
  4186. if (child == 0) {
  4187. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4188. close(out[0]);
  4189. close(in[1]);
  4190. dup2(out[1], STDOUT_FILENO);
  4191. dup2(in[0], STDIN_FILENO);
  4192. dup2(fileno(dev_null), STDERR_FILENO);
  4193. if (*cmd == '!') {
  4194. system(&cmd[1]); /* Yes we can just do this */
  4195. } else {
  4196. char * const args[] = {"python3","-c",&cmd[1],NULL};
  4197. execvp("python3",args);
  4198. }
  4199. exit(1);
  4200. } else if (child < 0) {
  4201. render_error("Failed to fork");
  4202. return 1;
  4203. }
  4204. close(out[1]);
  4205. close(in[0]);
  4206. /* Write lines to child process */
  4207. FILE * f = fdopen(in[1],"w");
  4208. for (int i = range_top; i <= range_bot; ++i) {
  4209. line_t * line = env->lines[i-1];
  4210. for (int j = 0; j < line->actual; j++) {
  4211. char_t c = line->text[j];
  4212. if (c.codepoint == 0) {
  4213. char buf[1] = {0};
  4214. fwrite(buf, 1, 1, f);
  4215. } else {
  4216. char tmp[8] = {0};
  4217. int i = to_eight(c.codepoint, tmp);
  4218. fwrite(tmp, i, 1, f);
  4219. }
  4220. }
  4221. fputc('\n', f);
  4222. }
  4223. fclose(f);
  4224. close(in[1]);
  4225. /* Read results from child process into a new buffer */
  4226. FILE * result = fdopen(out[0],"r");
  4227. buffer_t * old = env;
  4228. env = buffer_new();
  4229. setup_buffer(env);
  4230. env->loading = 1;
  4231. uint8_t buf[BLOCK_SIZE];
  4232. state = 0;
  4233. while (!feof(result) && !ferror(result)) {
  4234. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4235. add_buffer(buf, r);
  4236. }
  4237. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4238. env->lines = remove_line(env->lines, env->line_no-1);
  4239. }
  4240. fclose(result);
  4241. env->loading = 0;
  4242. /* Return to the original buffer and replace the selected lines with the output */
  4243. buffer_t * new = env;
  4244. env = old;
  4245. for (int i = range_top; i <= range_bot; ++i) {
  4246. /* Remove the existing lines */
  4247. env->lines = remove_line(env->lines, range_top-1);
  4248. }
  4249. for (int i = 0; i < new->line_count; ++i) {
  4250. /* Add the new lines */
  4251. env->lines = add_line(env->lines, range_top + i - 1);
  4252. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4253. recalculate_tabs(env->lines[range_top+i-1]);
  4254. }
  4255. env->modified = 1;
  4256. /* Close the temporary buffer */
  4257. buffer_close(new);
  4258. } else {
  4259. /* Reset and draw some line feeds */
  4260. reset();
  4261. printf("\n\n");
  4262. /* Set buffered for shell application */
  4263. set_buffered();
  4264. /* Call the shell and wait for completion */
  4265. if (*cmd == '!') {
  4266. system(&cmd[1]);
  4267. } else {
  4268. setenv("PYCMD",&cmd[1],1);
  4269. system("python3 -c \"$PYCMD\"");
  4270. }
  4271. /* Return to the editor, wait for user to press enter. */
  4272. set_unbuffered();
  4273. printf("\n\nPress ENTER to continue.");
  4274. int c;
  4275. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4276. /* Redraw the screen */
  4277. redraw_all();
  4278. }
  4279. /* Done processing command */
  4280. return 0;
  4281. }
  4282. BIM_PREFIX_COMMAND(bang,"!","Executes shell commands.") {
  4283. (void)argc, (void)argv;
  4284. return _prefix_command_run_script(cmd);
  4285. }
  4286. BIM_PREFIX_COMMAND(tick,"`","Executes Python commands.") {
  4287. (void)argc, (void)argv;
  4288. return _prefix_command_run_script(cmd);
  4289. }
  4290. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4291. char * c = needle;
  4292. char * replacement = NULL;
  4293. char * options = "";
  4294. while (*c) {
  4295. if (*c == divider) {
  4296. *c = '\0';
  4297. replacement = c + 1;
  4298. break;
  4299. }
  4300. c++;
  4301. }
  4302. if (!replacement) {
  4303. render_error("nothing to replace with");
  4304. return 1;
  4305. }
  4306. c = replacement;
  4307. while (*c) {
  4308. if (*c == divider) {
  4309. *c = '\0';
  4310. options = c + 1;
  4311. break;
  4312. }
  4313. c++;
  4314. }
  4315. int global = 0;
  4316. int case_insensitive = 0;
  4317. /* Parse options */
  4318. while (*options) {
  4319. switch (*options) {
  4320. case 'g':
  4321. global = 1;
  4322. break;
  4323. case 'i':
  4324. case_insensitive = 1;
  4325. break;
  4326. }
  4327. options++;
  4328. }
  4329. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4330. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4331. {
  4332. int i = 0;
  4333. uint32_t c, state = 0;
  4334. for (char * cin = needle; *cin; cin++) {
  4335. if (!decode(&state, &c, *cin)) {
  4336. needle_c[i] = c;
  4337. i++;
  4338. } else if (state == UTF8_REJECT) {
  4339. state = 0;
  4340. }
  4341. }
  4342. needle_c[i] = 0;
  4343. i = 0;
  4344. c = 0;
  4345. state = 0;
  4346. for (char * cin = replacement; *cin; cin++) {
  4347. if (!decode(&state, &c, *cin)) {
  4348. replacement_c[i] = c;
  4349. i++;
  4350. } else if (state == UTF8_REJECT) {
  4351. state = 0;
  4352. }
  4353. }
  4354. replacement_c[i] = 0;
  4355. }
  4356. int replacements = 0;
  4357. for (int line = range_top; line <= range_bot; ++line) {
  4358. int col = 0;
  4359. while (col != -1) {
  4360. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4361. if (col != -1) replacements++;
  4362. if (!global) break;
  4363. }
  4364. }
  4365. free(needle_c);
  4366. free(replacement_c);
  4367. if (replacements) {
  4368. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4369. set_history_break();
  4370. redraw_text();
  4371. } else {
  4372. render_error("Pattern not found: %s", needle);
  4373. }
  4374. return 0;
  4375. }
  4376. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4377. int range_top, range_bot;
  4378. if (env->mode == MODE_LINE_SELECTION) {
  4379. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4380. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4381. } else {
  4382. range_top = env->line_no;
  4383. range_bot = env->line_no;
  4384. }
  4385. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4386. }
  4387. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4388. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4389. }
  4390. BIM_COMMAND(e,"e","Open a file") {
  4391. if (argc > 1) {
  4392. /* This actually opens a new tab */
  4393. open_file(argv[1]);
  4394. update_title();
  4395. } else {
  4396. if (env->modified) {
  4397. render_error("File is modified, can not reload.");
  4398. return 1;
  4399. }
  4400. buffer_t * old_env = env;
  4401. open_file(env->file_name);
  4402. buffer_t * new_env = env;
  4403. env = old_env;
  4404. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4405. SWAP(line_t **, env->lines, new_env->lines);
  4406. SWAP(int, env->line_count, new_env->line_count);
  4407. SWAP(int, env->line_avail, new_env->line_avail);
  4408. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4409. redraw_all();
  4410. }
  4411. return 0;
  4412. }
  4413. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4414. if (argc > 1) {
  4415. open_file(argv[1]);
  4416. update_title();
  4417. } else {
  4418. env = buffer_new();
  4419. setup_buffer(env);
  4420. redraw_all();
  4421. update_title();
  4422. }
  4423. return 0;
  4424. }
  4425. BIM_COMMAND(w,"w","Write a file") {
  4426. /* w: write file */
  4427. if (argc > 1) {
  4428. write_file(argv[1]);
  4429. } else {
  4430. write_file(env->file_name);
  4431. }
  4432. return 0;
  4433. }
  4434. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4435. write_file(env->file_name);
  4436. close_buffer();
  4437. return 0;
  4438. }
  4439. BIM_COMMAND(history,"history","Display command history") {
  4440. render_commandline_message(""); /* To clear command line */
  4441. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4442. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4443. }
  4444. render_commandline_message("\n");
  4445. redraw_tabbar();
  4446. redraw_commandline();
  4447. pause_for_key();
  4448. return 0;
  4449. }
  4450. BIM_COMMAND(q,"q","Close buffer") {
  4451. if (left_buffer && left_buffer == right_buffer) {
  4452. unsplit();
  4453. return 0;
  4454. }
  4455. if (env->modified) {
  4456. render_error("No write since last change. Use :q! to force exit.");
  4457. } else {
  4458. close_buffer();
  4459. }
  4460. update_title();
  4461. return 0;
  4462. }
  4463. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4464. close_buffer();
  4465. update_title();
  4466. return 0;
  4467. }
  4468. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4469. try_quit();
  4470. return 0;
  4471. }
  4472. BIM_ALIAS("qall",qall,qa)
  4473. BIM_COMMAND(qabang,"qa!","Force exit") {
  4474. /* Forcefully exit editor */
  4475. while (buffers_len) {
  4476. buffer_close(buffers[0]);
  4477. }
  4478. quit(NULL);
  4479. return 1; /* doesn't return */
  4480. }
  4481. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4482. previous_tab();
  4483. update_title();
  4484. return 0;
  4485. }
  4486. BIM_COMMAND(tabn,"tabn","Next tab") {
  4487. next_tab();
  4488. update_title();
  4489. return 0;
  4490. }
  4491. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4492. if (argc < 2) {
  4493. render_status_message("git=%d", env->checkgitstatusonwrite);
  4494. } else {
  4495. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4496. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4497. git_examine(env->file_name);
  4498. redraw_text();
  4499. }
  4500. }
  4501. return 0;
  4502. }
  4503. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4504. if (argc < 2) {
  4505. render_status_message("colorgutter=%d", global_config.color_gutter);
  4506. } else {
  4507. global_config.color_gutter = !!atoi(argv[1]);
  4508. redraw_text();
  4509. }
  4510. return 0;
  4511. }
  4512. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4513. env->indent = 1;
  4514. redraw_statusbar();
  4515. return 0;
  4516. }
  4517. BIM_COMMAND(noindent,"noindent","Disable smrat indentation") {
  4518. env->indent = 0;
  4519. redraw_statusbar();
  4520. return 0;
  4521. }
  4522. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  4523. render_status_message("cursorcolumn=%d", env->preferred_column);
  4524. return 0;
  4525. }
  4526. BIM_COMMAND(noh,"noh","Clear search term") {
  4527. if (global_config.search) {
  4528. free(global_config.search);
  4529. global_config.search = NULL;
  4530. for (int i = 0; i < env->line_count; ++i) {
  4531. recalculate_syntax(env->lines[i],i);
  4532. }
  4533. redraw_text();
  4534. }
  4535. return 0;
  4536. }
  4537. BIM_COMMAND(help,"help","Show help text.") {
  4538. if (argc < 2) {
  4539. render_commandline_message(""); /* To clear command line */
  4540. render_commandline_message("\n");
  4541. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  4542. render_commandline_message("\n");
  4543. render_commandline_message(" Available commands:\n");
  4544. 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");
  4545. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4546. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4547. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4548. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4549. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4550. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4551. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4552. render_commandline_message("\n");
  4553. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  4554. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4555. render_commandline_message("\n");
  4556. } else {
  4557. int found = 0;
  4558. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  4559. if (!strcmp(c->name, argv[1])) {
  4560. render_commandline_message(""); /* To clear command line */
  4561. render_commandline_message("Help description for `%s`:\n", c->name);
  4562. render_commandline_message(" %s\n", c->description);
  4563. found = 1;
  4564. break;
  4565. }
  4566. }
  4567. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  4568. if (!strcmp(c->name, argv[1])) {
  4569. render_commandline_message(""); /* To clear command line */
  4570. render_commandline_message("Help description for `%s`:\n", c->name);
  4571. render_commandline_message(" %s\n", c->description);
  4572. found = 1;
  4573. break;
  4574. }
  4575. }
  4576. if (!found) {
  4577. render_error("Unknown command: %s", argv[1]);
  4578. return 1;
  4579. }
  4580. }
  4581. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4582. redraw_tabbar();
  4583. redraw_commandline();
  4584. /* Wait for a character so we can redraw the screen before continuing */
  4585. pause_for_key();
  4586. return 0;
  4587. }
  4588. BIM_COMMAND(version,"version","Show version information.") {
  4589. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  4590. return 0;
  4591. }
  4592. BIM_COMMAND(theme,"theme","Set color theme") {
  4593. if (argc < 2) {
  4594. render_status_message("theme=%s", current_theme);
  4595. } else {
  4596. for (struct theme_def * d = themes; themes && d->name; ++d) {
  4597. if (!strcmp(argv[1], d->name)) {
  4598. d->load();
  4599. redraw_all();
  4600. return 0;
  4601. }
  4602. }
  4603. }
  4604. return 0;
  4605. }
  4606. BIM_ALIAS("colorscheme",colorscheme,theme)
  4607. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  4608. if (argc < 2) {
  4609. render_status_message("splitpercent=%d", global_config.split_percent);
  4610. return 0;
  4611. } else {
  4612. global_config.split_percent = atoi(argv[1]);
  4613. if (left_buffer) {
  4614. update_split_size();
  4615. redraw_all();
  4616. }
  4617. }
  4618. return 0;
  4619. }
  4620. BIM_COMMAND(split,"split","Split the current view.") {
  4621. buffer_t * original = env;
  4622. if (argc > 1) {
  4623. int is_not_number = 0;
  4624. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  4625. if (is_not_number) {
  4626. /* Open a file for the new split */
  4627. open_file(argv[1]);
  4628. right_buffer = buffers[buffers_len-1];
  4629. } else {
  4630. /* Use an existing buffer for the new split */
  4631. int other = atoi(argv[1]);
  4632. if (other >= buffers_len || other < 0) {
  4633. render_error("Invalid buffer number: %d", other);
  4634. return 1;
  4635. }
  4636. right_buffer = buffers[other];
  4637. }
  4638. } else {
  4639. /* Use the current buffer for the new split */
  4640. right_buffer = original;
  4641. }
  4642. left_buffer = original;
  4643. update_split_size();
  4644. redraw_all();
  4645. return 0;
  4646. }
  4647. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  4648. unsplit();
  4649. return 0;
  4650. }
  4651. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  4652. if (argc < 2) {
  4653. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  4654. return 0;
  4655. } else {
  4656. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  4657. redraw_all();
  4658. }
  4659. return 0;
  4660. }
  4661. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  4662. if (argc < 2) {
  4663. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  4664. } else {
  4665. set_syntax_by_name(argv[1]);
  4666. }
  4667. return 0;
  4668. }
  4669. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  4670. for (int i = 0; i < env->line_count; ++i) {
  4671. env->lines[i]->istate = -1;
  4672. }
  4673. env->loading = 1;
  4674. for (int i = 0; i < env->line_count; ++i) {
  4675. recalculate_syntax(env->lines[i],i);
  4676. }
  4677. env->loading = 0;
  4678. redraw_all();
  4679. return 0;
  4680. }
  4681. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  4682. env->tabs = 1;
  4683. redraw_statusbar();
  4684. return 0;
  4685. }
  4686. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  4687. env->tabs = 0;
  4688. redraw_statusbar();
  4689. return 0;
  4690. }
  4691. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  4692. if (argc < 2) {
  4693. render_status_message("tabstop=%d", env->tabstop);
  4694. } else {
  4695. int t = atoi(argv[1]);
  4696. if (t > 0 && t < 32) {
  4697. env->tabstop = t;
  4698. for (int i = 0; i < env->line_count; ++i) {
  4699. recalculate_tabs(env->lines[i]);
  4700. }
  4701. redraw_all();
  4702. } else {
  4703. render_error("Invalid tabstop: %s", argv[1]);
  4704. }
  4705. }
  4706. return 0;
  4707. }
  4708. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  4709. if (global_config.yanks) {
  4710. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4711. free(global_config.yanks[i]);
  4712. }
  4713. free(global_config.yanks);
  4714. global_config.yanks = NULL;
  4715. global_config.yank_count = 0;
  4716. redraw_statusbar();
  4717. }
  4718. return 0;
  4719. }
  4720. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  4721. if (argc < 2) {
  4722. render_status_message("padding=%d", global_config.cursor_padding);
  4723. } else {
  4724. global_config.cursor_padding = atoi(argv[1]);
  4725. place_cursor_actual();
  4726. }
  4727. return 0;
  4728. }
  4729. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  4730. if (argc < 2) {
  4731. render_status_message("smartcase=%d", global_config.smart_case);
  4732. } else {
  4733. global_config.smart_case = atoi(argv[1]);
  4734. place_cursor_actual();
  4735. }
  4736. return 0;
  4737. }
  4738. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  4739. if (argc < 2) {
  4740. render_status_message("hlparen=%d", global_config.highlight_parens);
  4741. } else {
  4742. global_config.highlight_parens = atoi(argv[1]);
  4743. for (int i = 0; i < env->line_count; ++i) {
  4744. recalculate_syntax(env->lines[i],i);
  4745. }
  4746. redraw_text();
  4747. place_cursor_actual();
  4748. }
  4749. return 0;
  4750. }
  4751. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  4752. if (argc < 2) {
  4753. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  4754. } else {
  4755. global_config.highlight_current_line = atoi(argv[1]);
  4756. if (!global_config.highlight_current_line) {
  4757. for (int i = 0; i < env->line_count; ++i) {
  4758. env->lines[i]->is_current = 0;
  4759. }
  4760. }
  4761. redraw_text();
  4762. place_cursor_actual();
  4763. }
  4764. return 0;
  4765. }
  4766. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  4767. if (argc < 2) {
  4768. render_status_message("crnl=%d", env->crnl);
  4769. } else {
  4770. env->crnl = !!atoi(argv[1]);
  4771. redraw_statusbar();
  4772. }
  4773. return 0;
  4774. }
  4775. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  4776. if (argc < 2) {
  4777. render_status_message("numbers=%d", global_config.numbers);
  4778. } else {
  4779. global_config.numbers = !!atoi(argv[1]);
  4780. redraw_all();
  4781. }
  4782. return 0;
  4783. }
  4784. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  4785. if (argc < 2) {
  4786. render_status_message("relativenumber=%d", global_config.relative_lines);
  4787. } else {
  4788. global_config.relative_lines = atoi(argv[1]);
  4789. if (!global_config.relative_lines) {
  4790. for (int i = 0; i < env->line_count; ++i) {
  4791. env->lines[i]->is_current = 0;
  4792. }
  4793. }
  4794. redraw_text();
  4795. place_cursor_actual();
  4796. }
  4797. return 0;
  4798. }
  4799. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  4800. for (int i = 0; i < buffers_len; ++i) {
  4801. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  4802. }
  4803. redraw_tabbar();
  4804. redraw_commandline();
  4805. pause_for_key();
  4806. return 0;
  4807. }
  4808. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  4809. int c;
  4810. render_commandline_message("(press a key)");
  4811. while ((c = bim_getkey(200)) == KEY_TIMEOUT);
  4812. render_commandline_message("%d = %s", c, name_from_key(c));
  4813. return 0;
  4814. }
  4815. /**
  4816. * Process a user command.
  4817. */
  4818. int process_command(char * cmd) {
  4819. if (*cmd == '#') return 0;
  4820. /* First, check prefix commands */
  4821. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  4822. if (strstr(cmd, c->name) == cmd &&
  4823. (!isalpha(cmd[strlen(c->name)]) || !isalpha(cmd[0]))) {
  4824. return c->command(cmd, 0, NULL);
  4825. }
  4826. }
  4827. char * argv[3] = {NULL, NULL, NULL};
  4828. int argc = !!(*cmd);
  4829. char cmd_name[512] = {0};
  4830. for (char * c = cmd; *c; ++c) {
  4831. if (c-cmd == 511) break;
  4832. if (*c == ' ') {
  4833. cmd_name[c-cmd] = '\0';
  4834. argv[1] = c+1;
  4835. if (*argv[1]) argc++;
  4836. break;
  4837. }
  4838. cmd_name[c-cmd] = *c;
  4839. }
  4840. argv[0] = cmd_name;
  4841. argv[argc] = NULL;
  4842. if (argc < 1) {
  4843. /* no op */
  4844. return 0;
  4845. }
  4846. /* Now check regular commands */
  4847. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  4848. if (!strcmp(argv[0], c->name)) {
  4849. return c->command(cmd, argc, argv);
  4850. }
  4851. }
  4852. global_config.break_from_selection = 1;
  4853. if (argv[0][0] == '-' && isdigit(argv[0][1])) {
  4854. goto_line(env->line_no-atoi(&argv[0][1]));
  4855. return 0;
  4856. } else if (argv[0][0] == '+' && isdigit(argv[0][1])) {
  4857. goto_line(env->line_no+atoi(&argv[0][1]));
  4858. return 0;
  4859. } else if (isdigit(*argv[0])) {
  4860. goto_line(atoi(argv[0]));
  4861. return 0;
  4862. } else {
  4863. render_error("Not an editor command: %s", argv[0]);
  4864. return 1;
  4865. }
  4866. }
  4867. /**
  4868. * Wrap strcmp for use with qsort.
  4869. */
  4870. int compare_str(const void * a, const void * b) {
  4871. return strcmp(*(const char **)a, *(const char **)b);
  4872. }
  4873. /**
  4874. * List of file extensions to ignore when tab completing.
  4875. */
  4876. const char * tab_complete_ignore[] = {".o",NULL};
  4877. /**
  4878. * Tab completion for command mode.
  4879. */
  4880. void command_tab_complete(char * buffer) {
  4881. /* Figure out which argument this is and where it starts */
  4882. int arg = 0;
  4883. char * buf = strdup(buffer);
  4884. char * b = buf;
  4885. char * args[32];
  4886. int candidate_count= 0;
  4887. int candidate_space = 4;
  4888. char ** candidates = malloc(sizeof(char*)*candidate_space);
  4889. /* Accept whitespace before first argument */
  4890. while (*b == ' ') b++;
  4891. char * start = b;
  4892. args[0] = start;
  4893. while (*b && *b != ' ') b++;
  4894. while (*b) {
  4895. while (*b == ' ') {
  4896. *b = '\0';
  4897. b++;
  4898. }
  4899. start = b;
  4900. arg++;
  4901. args[arg] = start;
  4902. break;
  4903. }
  4904. /**
  4905. * Check a possible candidate and add it to the
  4906. * candidates list, expanding as necessary,
  4907. * if it matches for the current argument.
  4908. */
  4909. #define add_candidate(candidate) \
  4910. do { \
  4911. char * _arg = args[arg]; \
  4912. int r = strncmp(_arg, candidate, strlen(_arg)); \
  4913. if (!r) { \
  4914. if (candidate_count == candidate_space) { \
  4915. candidate_space *= 2; \
  4916. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  4917. } \
  4918. candidates[candidate_count] = strdup(candidate); \
  4919. candidate_count++; \
  4920. } \
  4921. } while (0)
  4922. int _candidates_are_files = 0;
  4923. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  4924. /* Complete command names */
  4925. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  4926. add_candidate(c->name);
  4927. }
  4928. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  4929. add_candidate(c->name);
  4930. }
  4931. goto _accept_candidate;
  4932. }
  4933. if (arg == 1 && !strcmp(args[0], "syntax")) {
  4934. /* Complete syntax options */
  4935. add_candidate("none");
  4936. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  4937. add_candidate(s->name);
  4938. }
  4939. goto _accept_candidate;
  4940. }
  4941. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  4942. /* Complete color theme names */
  4943. for (struct theme_def * s = themes; themes && s->name; ++s) {
  4944. add_candidate(s->name);
  4945. }
  4946. goto _accept_candidate;
  4947. }
  4948. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  4949. for (struct ColorName * c = color_names; c->name; ++c) {
  4950. add_candidate(c->name);
  4951. }
  4952. goto _accept_candidate;
  4953. }
  4954. if (arg == 1 && (!strcmp(args[0], "action"))) {
  4955. for (struct action_def * a = mappable_actions; a->name; ++a) {
  4956. add_candidate(a->name);
  4957. }
  4958. goto _accept_candidate;
  4959. }
  4960. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") || !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") || args[0][0] == '!')) {
  4961. /* Complete file paths */
  4962. /* First, find the deepest directory match */
  4963. char * tmp = strdup(args[arg]);
  4964. char * last_slash = strrchr(tmp, '/');
  4965. DIR * dirp;
  4966. if (last_slash) {
  4967. *last_slash = '\0';
  4968. if (last_slash == tmp) {
  4969. /* Started with slash, and it was the only slash */
  4970. dirp = opendir("/");
  4971. } else {
  4972. dirp = opendir(tmp);
  4973. }
  4974. } else {
  4975. /* No directory match, completing from current directory */
  4976. dirp = opendir(".");
  4977. tmp[0] = '\0';
  4978. }
  4979. if (!dirp) {
  4980. /* Directory match doesn't exist, no candidates to populate */
  4981. free(tmp);
  4982. goto done;
  4983. }
  4984. _candidates_are_files = 1;
  4985. struct dirent * ent = readdir(dirp);
  4986. while (ent != NULL) {
  4987. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  4988. struct stat statbuf;
  4989. /* Figure out if this file is a directory */
  4990. if (last_slash) {
  4991. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  4992. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  4993. stat(x, &statbuf);
  4994. free(x);
  4995. } else {
  4996. stat(ent->d_name, &statbuf);
  4997. }
  4998. /* Build the complete argument name to tab complete */
  4999. char s[1024] = {0};
  5000. if (last_slash == tmp) {
  5001. strcat(s,"/");
  5002. } else if (*tmp) {
  5003. strcat(s,tmp);
  5004. strcat(s,"/");
  5005. }
  5006. strcat(s,ent->d_name);
  5007. /*
  5008. * If it is a directory, add a / to the end so the next completion
  5009. * attempt will complete the directory's contents.
  5010. */
  5011. if (S_ISDIR(statbuf.st_mode)) {
  5012. strcat(s,"/");
  5013. }
  5014. int skip = 0;
  5015. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5016. if (str_ends_with(s, *c)) {
  5017. skip = 1;
  5018. break;
  5019. }
  5020. }
  5021. if (!skip) {
  5022. add_candidate(s);
  5023. }
  5024. }
  5025. ent = readdir(dirp);
  5026. }
  5027. closedir(dirp);
  5028. free(tmp);
  5029. goto _accept_candidate;
  5030. }
  5031. _accept_candidate:
  5032. if (candidate_count == 0) {
  5033. redraw_statusbar();
  5034. goto done;
  5035. }
  5036. if (candidate_count == 1) {
  5037. /* Only one completion possibility */
  5038. redraw_statusbar();
  5039. /* Fill out the rest of the command */
  5040. char * cstart = (buffer) + (start - buf);
  5041. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5042. *cstart = candidates[0][i];
  5043. cstart++;
  5044. }
  5045. *cstart = '\0';
  5046. } else {
  5047. /* Sort candidates */
  5048. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_str);
  5049. /* Print candidates in status bar */
  5050. char * tmp = malloc(global_config.term_width+1);
  5051. memset(tmp, 0, global_config.term_width+1);
  5052. int offset = 0;
  5053. for (int i = 0; i < candidate_count; ++i) {
  5054. char * printed_candidate = candidates[i];
  5055. if (_candidates_are_files) {
  5056. for (char * c = printed_candidate; *c; ++c) {
  5057. if (c[0] == '/' && c[1] != '\0') {
  5058. printed_candidate = c+1;
  5059. }
  5060. }
  5061. }
  5062. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5063. strcat(tmp, "...");
  5064. break;
  5065. }
  5066. if (offset > 0) {
  5067. strcat(tmp, " ");
  5068. offset++;
  5069. }
  5070. strcat(tmp, printed_candidate);
  5071. offset += strlen(printed_candidate);
  5072. }
  5073. render_status_message("%s", tmp);
  5074. free(tmp);
  5075. /* Complete to longest common substring */
  5076. char * cstart = (buffer) + (start - buf);
  5077. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5078. for (int j = 1; j < candidate_count; ++j) {
  5079. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5080. }
  5081. *cstart = candidates[0][i];
  5082. cstart++;
  5083. }
  5084. /* End of longest common substring */
  5085. _reject:
  5086. *cstart = '\0';
  5087. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5088. if (start > buf) { /* Start point needs to be something other than first byte */
  5089. char * tmp = cstart - 1;
  5090. if ((*tmp & 0xC0) == 0x80) {
  5091. /* Count back until we find the start byte and make sure we have the right number */
  5092. int count = 1;
  5093. int x = 0;
  5094. while (tmp >= start) {
  5095. x++;
  5096. tmp--;
  5097. if ((*tmp & 0xC0) == 0x80) {
  5098. count++;
  5099. } else if ((*tmp & 0xC0) == 0xC0) {
  5100. /* How many should we have? */
  5101. int i = 1;
  5102. int j = *tmp;
  5103. while (j & 0x20) {
  5104. i += 1;
  5105. j <<= 1;
  5106. }
  5107. if (count != i) {
  5108. *tmp = '\0';
  5109. break;
  5110. }
  5111. break;
  5112. } else {
  5113. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5114. tmp++;
  5115. *tmp = '\0';
  5116. break;
  5117. }
  5118. }
  5119. } else if ((*tmp & 0xC0) == 0xC0) {
  5120. *tmp = '\0';
  5121. }
  5122. }
  5123. }
  5124. /* Free candidates */
  5125. for (int i = 0; i < candidate_count; ++i) {
  5126. free(candidates[i]);
  5127. }
  5128. done:
  5129. free(candidates);
  5130. free(buf);
  5131. }
  5132. /**
  5133. * Macros for use in command mode.
  5134. */
  5135. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5136. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5137. #define _restore_history(point) do { \
  5138. unsigned char * t = command_history[point]; \
  5139. global_config.command_col_no = 1; \
  5140. global_config.command_buffer->actual = 0; \
  5141. _syn_command(); \
  5142. uint32_t state = 0; \
  5143. uint32_t c = 0; \
  5144. while (*t) { \
  5145. if (!decode(&state, &c, *t)) { \
  5146. char_t _c = {codepoint_width(c), 0, c}; \
  5147. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1); \
  5148. global_config.command_col_no++; \
  5149. } else if (state == UTF8_REJECT) state = 0; \
  5150. t++; \
  5151. } \
  5152. _syn_restore(); \
  5153. } while (0)
  5154. /**
  5155. * Draw the command buffer and any prefix.
  5156. */
  5157. void render_command_input_buffer(void) {
  5158. if (!global_config.command_buffer) return;
  5159. /* Place the cursor at the bottom of the screen */
  5160. place_cursor(1, global_config.term_height);
  5161. paint_line(COLOR_BG);
  5162. set_colors(COLOR_ALT_FG, COLOR_BG);
  5163. /* If there's a mode name to render, draw it first */
  5164. int _left_gutter = 0;
  5165. if (env->mode == MODE_LINE_SELECTION) {
  5166. _left_gutter = printf("(LINE %d:%d)",
  5167. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5168. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5169. } else if (env->mode == MODE_COL_SELECTION) {
  5170. _left_gutter = printf("(COL %d:%d %d)",
  5171. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5172. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5173. (env->sel_col));
  5174. } else if (env->mode == MODE_CHAR_SELECTION) {
  5175. _left_gutter = printf("(CHAR)");
  5176. }
  5177. /* Figure out the cursor position and adjust the offset if necessary */
  5178. int x = 2 + _left_gutter - global_config.command_offset;
  5179. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5180. char_t * c = &global_config.command_buffer->text[i];
  5181. x += c->display_width;
  5182. }
  5183. if (x > global_config.term_width - 1) {
  5184. int diff = x - (global_config.term_width - 1);
  5185. global_config.command_offset += diff;
  5186. x -= diff;
  5187. }
  5188. if (x < 2 + _left_gutter) {
  5189. int diff = (2 + _left_gutter) - x;
  5190. global_config.command_offset -= diff;
  5191. x += diff;
  5192. }
  5193. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5194. if (global_config.command_offset) {
  5195. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5196. printf("<");
  5197. } else {
  5198. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5199. set_colors(COLOR_FG, COLOR_BG);
  5200. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5201. printf(global_config.search_direction == 0 ? "?" : "/");
  5202. } else {
  5203. printf(":");
  5204. }
  5205. }
  5206. /* Render the buffer */
  5207. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5208. /* Place and display the cursor */
  5209. place_cursor(x, global_config.term_height);
  5210. show_cursor();
  5211. }
  5212. BIM_ACTION(command_discard, 0,
  5213. "Discard the input buffer and cancel command or search."
  5214. )(void) {
  5215. free(global_config.command_buffer);
  5216. global_config.command_buffer = NULL;
  5217. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5218. env->line_no = global_config.prev_line;
  5219. env->col_no = global_config.prev_col;
  5220. /* Unhighlight search matches */
  5221. for (int i = 0; i < env->line_count; ++i) {
  5222. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5223. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5224. }
  5225. rehighlight_search(env->lines[i]);
  5226. }
  5227. }
  5228. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5229. redraw_all();
  5230. /* TODO exit some other modes? */
  5231. }
  5232. BIM_ACTION(enter_command, 0,
  5233. "Enter command input mode."
  5234. )(void) {
  5235. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  5236. global_config.command_offset = 0;
  5237. global_config.command_col_no = 1;
  5238. if (global_config.command_buffer) {
  5239. free(global_config.command_buffer);
  5240. }
  5241. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5242. global_config.command_buffer->available = 32;
  5243. global_config.command_syn_back = env->syntax;
  5244. global_config.command_syn = find_syntax_calculator("bimcmd");
  5245. global_config.history_point = -1;
  5246. render_command_input_buffer();
  5247. }
  5248. BIM_ACTION(command_accept, 0,
  5249. "Accept the command input and run the requested command."
  5250. )(void) {
  5251. /* Convert command buffer to UTF-8 char-array string */
  5252. size_t size = 0;
  5253. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5254. char tmp[8] = {0};
  5255. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  5256. }
  5257. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  5258. char * t = tmp;
  5259. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5260. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5261. }
  5262. *t = '\0';
  5263. /* Free the original editing buffer */
  5264. free(global_config.command_buffer);
  5265. global_config.command_buffer = NULL;
  5266. /* Run the converted command */
  5267. global_config.break_from_selection = 0;
  5268. insert_command_history(tmp);
  5269. process_command(tmp);
  5270. free(tmp);
  5271. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  5272. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  5273. recalculate_selected_lines();
  5274. }
  5275. env->mode = MODE_NORMAL;
  5276. }
  5277. /* Leave command mode */
  5278. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5279. }
  5280. BIM_ACTION(command_word_delete, 0,
  5281. "Delete the previous word from the input buffer."
  5282. )(void) {
  5283. _syn_command();
  5284. while (global_config.command_col_no > 1 &&
  5285. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  5286. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  5287. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5288. global_config.command_col_no--;
  5289. }
  5290. while (global_config.command_col_no > 1 &&
  5291. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  5292. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  5293. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5294. global_config.command_col_no--;
  5295. }
  5296. _syn_restore();
  5297. }
  5298. BIM_ACTION(command_tab_complete_buffer, 0,
  5299. "Complete command names and arguments in the input buffer."
  5300. )(void) {
  5301. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  5302. char * tmp = calloc(1024,1);
  5303. char * t = tmp;
  5304. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  5305. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5306. }
  5307. *t = '\0';
  5308. _syn_command();
  5309. while (global_config.command_col_no > 1) {
  5310. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5311. global_config.command_col_no--;
  5312. }
  5313. _syn_restore();
  5314. command_tab_complete(tmp);
  5315. _syn_command();
  5316. uint32_t state = 0, c= 0;
  5317. t = tmp;
  5318. while (*t) {
  5319. if (!decode(&state, &c, *t)) {
  5320. char_t _c = {codepoint_width(c), 0, c};
  5321. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5322. global_config.command_col_no++;
  5323. }
  5324. t++;
  5325. }
  5326. _syn_restore();
  5327. free(tmp);
  5328. }
  5329. BIM_ACTION(command_backspace, 0,
  5330. "Erase the character before the cursor in the input buffer."
  5331. )(void) {
  5332. if (global_config.command_col_no <= 1) {
  5333. if (global_config.command_buffer->actual == 0) {
  5334. command_discard();
  5335. }
  5336. return;
  5337. }
  5338. _syn_command();
  5339. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5340. _syn_restore();
  5341. global_config.command_col_no--;
  5342. global_config.command_offset = 0;
  5343. }
  5344. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  5345. "Scroll through command input history."
  5346. )(int direction) {
  5347. if (direction == -1) {
  5348. if (command_history[global_config.history_point+1]) {
  5349. _restore_history(global_config.history_point+1);
  5350. global_config.history_point++;
  5351. }
  5352. } else {
  5353. if (global_config.history_point > 0) {
  5354. global_config.history_point--;
  5355. _restore_history(global_config.history_point);
  5356. } else {
  5357. global_config.history_point = -1;
  5358. global_config.command_col_no = 1;
  5359. global_config.command_buffer->actual = 0;
  5360. }
  5361. }
  5362. }
  5363. BIM_ACTION(command_word_left, 0,
  5364. "Move to the start of the previous word in the input buffer."
  5365. )(void) {
  5366. if (global_config.command_col_no > 1) {
  5367. do {
  5368. global_config.command_col_no--;
  5369. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5370. if (global_config.command_col_no == 1) return;
  5371. do {
  5372. global_config.command_col_no--;
  5373. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5374. 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++;
  5375. }
  5376. }
  5377. BIM_ACTION(command_word_right, 0,
  5378. "Move to the start of the next word in the input buffer."
  5379. )(void) {
  5380. if (global_config.command_col_no < global_config.command_buffer->actual) {
  5381. do {
  5382. global_config.command_col_no++;
  5383. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5384. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5385. do {
  5386. global_config.command_col_no++;
  5387. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5388. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5389. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  5390. }
  5391. }
  5392. BIM_ACTION(command_cursor_left, 0,
  5393. "Move the cursor one character left in the input buffer."
  5394. )(void) {
  5395. if (global_config.command_col_no > 1) global_config.command_col_no--;
  5396. }
  5397. BIM_ACTION(command_cursor_right, 0,
  5398. "Move the cursor one character right in the input buffer."
  5399. )(void) {
  5400. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  5401. }
  5402. BIM_ACTION(command_cursor_home, 0,
  5403. "Move the cursor to the start of the input buffer."
  5404. )(void) {
  5405. global_config.command_col_no = 1;
  5406. }
  5407. BIM_ACTION(command_cursor_end, 0,
  5408. "Move the cursor to the end of the input buffer."
  5409. )(void) {
  5410. global_config.command_col_no = global_config.command_buffer->actual + 1;
  5411. }
  5412. BIM_ACTION(eat_mouse, 0,
  5413. "(temporary) Read, but ignore mouse input."
  5414. )(void) {
  5415. bim_getch();
  5416. bim_getch();
  5417. bim_getch();
  5418. }
  5419. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  5420. "Insert one character into the input buffer."
  5421. )(int c) {
  5422. char_t _c = {codepoint_width(c), 0, c};
  5423. _syn_command();
  5424. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5425. _syn_restore();
  5426. global_config.command_col_no++;
  5427. }
  5428. /**
  5429. * Determine whether a string should be searched
  5430. * case-sensitive or not based on whether it contains
  5431. * any upper-case letters.
  5432. */
  5433. int smart_case(uint32_t * str) {
  5434. if (!global_config.smart_case) return 0;
  5435. for (uint32_t * s = str; *s; ++s) {
  5436. if (tolower(*s) != (int)*s) {
  5437. return 0;
  5438. }
  5439. }
  5440. return 1;
  5441. }
  5442. /**
  5443. * Search forward from the given cursor position
  5444. * to find a basic search match.
  5445. *
  5446. * This could be more complicated...
  5447. */
  5448. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  5449. int col = from_col;
  5450. int ignorecase = smart_case(str);
  5451. for (int i = from_line; i <= env->line_count; ++i) {
  5452. line_t * line = env->lines[i - 1];
  5453. int j = col - 1;
  5454. while (j < line->actual + 1) {
  5455. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  5456. *out_line = i;
  5457. *out_col = j + 1;
  5458. return;
  5459. }
  5460. j++;
  5461. }
  5462. col = 0;
  5463. }
  5464. }
  5465. /**
  5466. * Search backwards for matching string.
  5467. */
  5468. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5469. int col = from_col;
  5470. int ignorecase = smart_case(str);
  5471. for (int i = from_line; i >= 1; --i) {
  5472. line_t * line = env->lines[i-1];
  5473. int j = col - 1;
  5474. while (j > -1) {
  5475. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  5476. *out_line = i;
  5477. *out_col = j + 1;
  5478. return;
  5479. }
  5480. j--;
  5481. }
  5482. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  5483. }
  5484. }
  5485. /**
  5486. * Re-mark search matches while editing text.
  5487. * This gets called after recalculate_syntax, so it works as we're typing or
  5488. * whenever syntax calculation would redraw other lines.
  5489. * XXX There's a bunch of code duplication between the (now three) search match functions.
  5490. * and search should be improved to support regex anyway, so this needs to be fixed.
  5491. */
  5492. void rehighlight_search(line_t * line) {
  5493. if (!global_config.search) return;
  5494. int j = 0;
  5495. int ignorecase = smart_case(global_config.search);
  5496. while (j < line->actual) {
  5497. int matchlen = 0;
  5498. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  5499. for (int i = j; matchlen > 0; ++i, matchlen--) {
  5500. line->text[i].flags |= FLAG_SEARCH;
  5501. }
  5502. }
  5503. j++;
  5504. }
  5505. }
  5506. /**
  5507. * Draw the matched search result.
  5508. */
  5509. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  5510. for (int i = 0; i < env->line_count; ++i) {
  5511. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5512. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5513. }
  5514. }
  5515. int line = -1, col = -1, _line = 1, _col = 1;
  5516. do {
  5517. int matchlen;
  5518. find_match(_line, _col, &line, &col, buffer, &matchlen);
  5519. if (line != -1) {
  5520. line_t * l = env->lines[line-1];
  5521. for (int i = col; matchlen > 0; ++i, --matchlen) {
  5522. l->text[i-1].flags |= FLAG_SEARCH;
  5523. }
  5524. }
  5525. _line = line;
  5526. _col = col+1;
  5527. line = -1;
  5528. col = -1;
  5529. } while (_line != -1);
  5530. redraw_text();
  5531. place_cursor_actual();
  5532. redraw_statusbar();
  5533. redraw_commandline();
  5534. if (redraw_buffer != -1) {
  5535. printf(redraw_buffer == 1 ? "/" : "?");
  5536. uint32_t * c = buffer;
  5537. while (*c) {
  5538. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5539. to_eight(*c, tmp);
  5540. printf("%s", tmp);
  5541. c++;
  5542. }
  5543. }
  5544. }
  5545. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  5546. "Enter search mode."
  5547. )(int direction) {
  5548. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  5549. global_config.command_offset = 0;
  5550. global_config.command_col_no = 1;
  5551. global_config.prev_line = env->line_no;
  5552. global_config.prev_col = env->col_no;
  5553. global_config.prev_coffset = env->coffset;
  5554. global_config.prev_offset = env->offset;
  5555. global_config.search_direction = direction;
  5556. if (global_config.command_buffer) {
  5557. free(global_config.command_buffer);
  5558. }
  5559. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5560. global_config.command_buffer->available = 32;
  5561. global_config.command_syn_back = env->syntax;
  5562. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  5563. render_command_input_buffer();
  5564. }
  5565. BIM_ACTION(search_accept, 0,
  5566. "Accept the search term and return to the previous mode."
  5567. )(void) {
  5568. /* Store the accepted search */
  5569. if (!global_config.command_buffer->actual) {
  5570. if (global_config.search) {
  5571. search_next();
  5572. }
  5573. goto _finish;
  5574. }
  5575. if (global_config.search) {
  5576. free(global_config.search);
  5577. }
  5578. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  5579. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5580. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  5581. }
  5582. global_config.search[global_config.command_buffer->actual] = 0;
  5583. _finish:
  5584. /* Free the original editing buffer */
  5585. free(global_config.command_buffer);
  5586. global_config.command_buffer = NULL;
  5587. /* Leave command mode */
  5588. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5589. }
  5590. /**
  5591. * Find the next search result, or loop back around if at the end.
  5592. */
  5593. BIM_ACTION(search_next, 0,
  5594. "Jump to the next search match."
  5595. )(void) {
  5596. if (!global_config.search) return;
  5597. if (env->coffset) env->coffset = 0;
  5598. int line = -1, col = -1;
  5599. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  5600. if (line == -1) {
  5601. find_match(1,1, &line, &col, global_config.search, NULL);
  5602. if (line == -1) return;
  5603. }
  5604. env->col_no = col;
  5605. env->line_no = line;
  5606. set_preferred_column();
  5607. draw_search_match(global_config.search, -1);
  5608. }
  5609. /**
  5610. * Find the previous search result, or loop to the end of the file.
  5611. */
  5612. BIM_ACTION(search_prev, 0,
  5613. "Jump to the preceding search match."
  5614. )(void) {
  5615. if (!global_config.search) return;
  5616. if (env->coffset) env->coffset = 0;
  5617. int line = -1, col = -1;
  5618. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  5619. if (line == -1) {
  5620. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  5621. if (line == -1) return;
  5622. }
  5623. env->col_no = col;
  5624. env->line_no = line;
  5625. set_preferred_column();
  5626. draw_search_match(global_config.search, -1);
  5627. }
  5628. /**
  5629. * Find the matching paren for this one.
  5630. *
  5631. * This approach skips having to do its own syntax parsing
  5632. * to deal with, eg., erroneous parens in comments. It does
  5633. * this by finding the matching paren with the same flag
  5634. * value, thus parens in strings will match, parens outside
  5635. * of strings will match, but parens in strings won't
  5636. * match parens outside of strings and so on.
  5637. */
  5638. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  5639. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  5640. return; /* Invalid cursor position */
  5641. }
  5642. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  5643. int paren_match = 0;
  5644. int direction = 0;
  5645. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  5646. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  5647. int count = 0;
  5648. /* TODO what about unicode parens? */
  5649. for (int i = 0; paren_pairs[i]; ++i) {
  5650. if (start == paren_pairs[i]) {
  5651. direction = (i % 2 == 0) ? 1 : -1;
  5652. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  5653. break;
  5654. }
  5655. }
  5656. if (!paren_match) return;
  5657. /* Scan for match */
  5658. int line = env->line_no;
  5659. int col = env->col_no - in_col + 1;
  5660. do {
  5661. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  5662. /* Only match on same syntax */
  5663. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  5664. /* Count up on same direction */
  5665. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  5666. /* Count down on opposite direction */
  5667. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  5668. count--;
  5669. /* When count == 0 we have a match */
  5670. if (count == 0) goto _match_found;
  5671. }
  5672. }
  5673. col += direction;
  5674. }
  5675. line += direction;
  5676. /* Reached first/last line with no match */
  5677. if (line == 0 || line == env->line_count + 1) {
  5678. return;
  5679. }
  5680. /* Reset column to start/end of line, depending on direction */
  5681. if (direction > 0) {
  5682. col = 1;
  5683. } else {
  5684. col = env->lines[line-1]->actual;
  5685. }
  5686. } while (1);
  5687. _match_found:
  5688. *out_line = line;
  5689. *out_col = col;
  5690. }
  5691. /**
  5692. * Switch to the left split view
  5693. * (Primarily to handle cases where the left and right are the same buffer)
  5694. */
  5695. BIM_ACTION(use_left_buffer, 0,
  5696. "Switch to the left split view."
  5697. )(void) {
  5698. if (left_buffer == right_buffer && env->left != 0) {
  5699. view_right_offset = env->offset;
  5700. env->width = env->left;
  5701. env->left = 0;
  5702. env->offset = view_left_offset;
  5703. }
  5704. env = left_buffer;
  5705. update_title();
  5706. }
  5707. /**
  5708. * Switch to the right split view
  5709. * (Primarily to handle cases where the left and right are the same buffer)
  5710. */
  5711. BIM_ACTION(use_right_buffer, 0,
  5712. "Switch to the right split view."
  5713. )(void) {
  5714. if (left_buffer == right_buffer && env->left == 0) {
  5715. view_left_offset = env->offset;
  5716. env->left = env->width;
  5717. env->width = global_config.term_width - env->width;
  5718. env->offset = view_right_offset;
  5719. }
  5720. env = right_buffer;
  5721. update_title();
  5722. }
  5723. /**
  5724. * Handle mouse event
  5725. */
  5726. BIM_ACTION(handle_mouse, 0,
  5727. "Process mouse actions."
  5728. )(void) {
  5729. int buttons = bim_getch() - 32;
  5730. int x = bim_getch() - 32;
  5731. int y = bim_getch() - 32;
  5732. if (buttons == 64) {
  5733. /* Scroll up */
  5734. if (global_config.shift_scrolling) {
  5735. env->loading = 1;
  5736. int shifted = 0;
  5737. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5738. if (env->offset > 0) {
  5739. env->offset--;
  5740. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  5741. cursor_up();
  5742. }
  5743. shifted++;
  5744. }
  5745. }
  5746. env->loading = 0;
  5747. if (!shifted) return;
  5748. if (global_config.can_scroll && !left_buffer) {
  5749. shift_down(shifted);
  5750. for (int i = 0; i < shifted; ++i) {
  5751. redraw_line(env->offset+i);
  5752. }
  5753. } else {
  5754. redraw_text();
  5755. }
  5756. redraw_tabbar();
  5757. redraw_statusbar();
  5758. redraw_commandline();
  5759. place_cursor_actual();
  5760. } else {
  5761. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5762. cursor_up();
  5763. }
  5764. }
  5765. return;
  5766. } else if (buttons == 65) {
  5767. /* Scroll down */
  5768. if (global_config.shift_scrolling) {
  5769. env->loading = 1;
  5770. int shifted = 0;
  5771. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5772. if (env->offset < env->line_count-1) {
  5773. env->offset++;
  5774. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  5775. if (env->line_no <= e) {
  5776. cursor_down();
  5777. }
  5778. shifted++;
  5779. }
  5780. }
  5781. env->loading = 0;
  5782. if (!shifted) return;
  5783. if (global_config.can_scroll && !left_buffer) {
  5784. shift_up(shifted);
  5785. int l = global_config.term_height - global_config.bottom_size - 1;
  5786. for (int i = 0; i < shifted; ++i) {
  5787. if (env->offset + l - i < env->line_count + 1) {
  5788. redraw_line(env->offset + l-1-i);
  5789. } else {
  5790. draw_excess_line(l - 1 - i);
  5791. }
  5792. }
  5793. } else {
  5794. redraw_text();
  5795. }
  5796. redraw_tabbar();
  5797. redraw_statusbar();
  5798. redraw_commandline();
  5799. place_cursor_actual();
  5800. } else {
  5801. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5802. cursor_down();
  5803. }
  5804. }
  5805. return;
  5806. } else if (buttons == 3) {
  5807. /* Move cursor to position */
  5808. if (x < 0) return;
  5809. if (y < 0) return;
  5810. if (y == 1) {
  5811. /* Pick from tabs */
  5812. int _x = 0;
  5813. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  5814. for (int i = 0; i < buffers_len; i++) {
  5815. buffer_t * _env = buffers[i];
  5816. char tmp[64];
  5817. _x += draw_tab_name(_env, tmp);
  5818. if (_x >= x) {
  5819. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  5820. env = buffers[i];
  5821. redraw_all();
  5822. update_title();
  5823. return;
  5824. }
  5825. }
  5826. return;
  5827. }
  5828. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  5829. int current_mode = env->mode;
  5830. if (x < env->left && env == right_buffer) {
  5831. use_left_buffer();
  5832. } else if (x > env->width && env == left_buffer) {
  5833. use_right_buffer();
  5834. }
  5835. env->mode = current_mode;
  5836. redraw_all();
  5837. }
  5838. if (env->left) {
  5839. x -= env->left;
  5840. }
  5841. /* Figure out y coordinate */
  5842. int line_no = y + env->offset - 1;
  5843. int col_no = -1;
  5844. if (line_no > env->line_count) {
  5845. line_no = env->line_count;
  5846. }
  5847. if (line_no != env->line_no) {
  5848. env->coffset = 0;
  5849. }
  5850. /* Account for the left hand gutter */
  5851. int num_size = num_width() + 3;
  5852. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  5853. /* Determine where the cursor is physically */
  5854. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  5855. char_t * c = &env->lines[line_no-1]->text[i];
  5856. _x += c->display_width;
  5857. if (_x > x-1) {
  5858. col_no = i+1;
  5859. break;
  5860. }
  5861. }
  5862. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  5863. col_no = env->lines[line_no-1]->actual;
  5864. }
  5865. env->line_no = line_no;
  5866. env->col_no = col_no;
  5867. set_history_break();
  5868. set_preferred_column();
  5869. redraw_statusbar();
  5870. place_cursor_actual();
  5871. }
  5872. return;
  5873. }
  5874. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  5875. "Insert one character."
  5876. )(unsigned int c) {
  5877. if (!c) {
  5878. render_error("Inserted nil byte?");
  5879. return;
  5880. }
  5881. char_t _c;
  5882. _c.codepoint = c;
  5883. _c.flags = 0;
  5884. _c.display_width = codepoint_width(c);
  5885. line_t * line = env->lines[env->line_no - 1];
  5886. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  5887. if (line != nline) {
  5888. env->lines[env->line_no - 1] = nline;
  5889. }
  5890. env->col_no += 1;
  5891. set_preferred_column();
  5892. set_modified();
  5893. }
  5894. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  5895. "Replace a single character."
  5896. )(unsigned int c) {
  5897. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  5898. if (c >= KEY_ESCAPE) {
  5899. render_error("Invalid key for replacement");
  5900. return;
  5901. }
  5902. char_t _c;
  5903. _c.codepoint = c;
  5904. _c.flags = 0;
  5905. _c.display_width = codepoint_width(c);
  5906. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  5907. redraw_line(env->line_no-1);
  5908. set_modified();
  5909. }
  5910. BIM_ACTION(undo_history, ACTION_IS_RW,
  5911. "Undo history until the last breakpoint."
  5912. )(void) {
  5913. if (!global_config.history_enabled) return;
  5914. env->loading = 1;
  5915. history_t * e = env->history;
  5916. if (e->type == HISTORY_SENTINEL) {
  5917. env->loading = 0;
  5918. render_commandline_message("Already at oldest change");
  5919. return;
  5920. }
  5921. int count_chars = 0;
  5922. int count_lines = 0;
  5923. do {
  5924. if (e->type == HISTORY_SENTINEL) break;
  5925. switch (e->type) {
  5926. case HISTORY_INSERT:
  5927. /* Delete */
  5928. line_delete(
  5929. env->lines[e->contents.insert_delete_replace.lineno],
  5930. e->contents.insert_delete_replace.offset+1,
  5931. e->contents.insert_delete_replace.lineno
  5932. );
  5933. count_chars++;
  5934. break;
  5935. case HISTORY_DELETE:
  5936. {
  5937. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  5938. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  5939. env->lines[e->contents.insert_delete_replace.lineno],
  5940. _c,
  5941. e->contents.insert_delete_replace.offset-1,
  5942. e->contents.insert_delete_replace.lineno
  5943. );
  5944. }
  5945. count_chars++;
  5946. break;
  5947. case HISTORY_REPLACE:
  5948. {
  5949. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  5950. line_replace(
  5951. env->lines[e->contents.insert_delete_replace.lineno],
  5952. _o,
  5953. e->contents.insert_delete_replace.offset,
  5954. e->contents.insert_delete_replace.lineno
  5955. );
  5956. }
  5957. count_chars++;
  5958. break;
  5959. case HISTORY_REMOVE_LINE:
  5960. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  5961. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  5962. count_lines++;
  5963. break;
  5964. case HISTORY_ADD_LINE:
  5965. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  5966. count_lines++;
  5967. break;
  5968. case HISTORY_REPLACE_LINE:
  5969. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  5970. count_lines++;
  5971. break;
  5972. case HISTORY_SPLIT_LINE:
  5973. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  5974. count_lines++;
  5975. break;
  5976. case HISTORY_MERGE_LINES:
  5977. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  5978. count_lines++;
  5979. break;
  5980. case HISTORY_BREAK:
  5981. /* Ignore break */
  5982. break;
  5983. default:
  5984. render_error("Unknown type %d!\n", e->type);
  5985. break;
  5986. }
  5987. env->line_no = env->history->line;
  5988. env->col_no = env->history->col;
  5989. env->history = e->previous;
  5990. e = env->history;
  5991. } while (e->type != HISTORY_BREAK);
  5992. if (env->line_no > env->line_count) env->line_no = env->line_count;
  5993. if (env->line_no < 1) env->line_no = 1;
  5994. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  5995. if (env->col_no < 1) env->col_no = 1;
  5996. env->modified = (env->history != env->last_save_history);
  5997. env->loading = 0;
  5998. for (int i = 0; i < env->line_count; ++i) {
  5999. env->lines[i]->istate = 0;
  6000. recalculate_tabs(env->lines[i]);
  6001. }
  6002. for (int i = 0; i < env->line_count; ++i) {
  6003. recalculate_syntax(env->lines[i],i);
  6004. }
  6005. place_cursor_actual();
  6006. update_title();
  6007. redraw_all();
  6008. render_commandline_message("%d character%s, %d line%s changed",
  6009. count_chars, (count_chars == 1) ? "" : "s",
  6010. count_lines, (count_lines == 1) ? "" : "s");
  6011. }
  6012. BIM_ACTION(redo_history, ACTION_IS_RW,
  6013. "Redo history until the next breakpoint."
  6014. )(void) {
  6015. if (!global_config.history_enabled) return;
  6016. env->loading = 1;
  6017. history_t * e = env->history->next;
  6018. if (!e) {
  6019. env->loading = 0;
  6020. render_commandline_message("Already at newest change");
  6021. return;
  6022. }
  6023. int count_chars = 0;
  6024. int count_lines = 0;
  6025. while (e) {
  6026. if (e->type == HISTORY_BREAK) {
  6027. env->history = e;
  6028. break;
  6029. }
  6030. switch (e->type) {
  6031. case HISTORY_INSERT:
  6032. {
  6033. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6034. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6035. env->lines[e->contents.insert_delete_replace.lineno],
  6036. _c,
  6037. e->contents.insert_delete_replace.offset,
  6038. e->contents.insert_delete_replace.lineno
  6039. );
  6040. }
  6041. count_chars++;
  6042. break;
  6043. case HISTORY_DELETE:
  6044. /* Delete */
  6045. line_delete(
  6046. env->lines[e->contents.insert_delete_replace.lineno],
  6047. e->contents.insert_delete_replace.offset,
  6048. e->contents.insert_delete_replace.lineno
  6049. );
  6050. count_chars++;
  6051. break;
  6052. case HISTORY_REPLACE:
  6053. {
  6054. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6055. line_replace(
  6056. env->lines[e->contents.insert_delete_replace.lineno],
  6057. _o,
  6058. e->contents.insert_delete_replace.offset,
  6059. e->contents.insert_delete_replace.lineno
  6060. );
  6061. }
  6062. count_chars++;
  6063. break;
  6064. case HISTORY_ADD_LINE:
  6065. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6066. count_lines++;
  6067. break;
  6068. case HISTORY_REMOVE_LINE:
  6069. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6070. count_lines++;
  6071. break;
  6072. case HISTORY_REPLACE_LINE:
  6073. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6074. count_lines++;
  6075. break;
  6076. case HISTORY_MERGE_LINES:
  6077. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6078. count_lines++;
  6079. break;
  6080. case HISTORY_SPLIT_LINE:
  6081. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6082. count_lines++;
  6083. break;
  6084. case HISTORY_BREAK:
  6085. /* Ignore break */
  6086. break;
  6087. default:
  6088. render_error("Unknown type %d!\n", e->type);
  6089. break;
  6090. }
  6091. env->history = e;
  6092. e = e->next;
  6093. }
  6094. env->line_no = env->history->line;
  6095. env->col_no = env->history->col;
  6096. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6097. if (env->line_no < 1) env->line_no = 1;
  6098. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6099. if (env->col_no < 1) env->col_no = 1;
  6100. env->modified = (env->history != env->last_save_history);
  6101. env->loading = 0;
  6102. for (int i = 0; i < env->line_count; ++i) {
  6103. env->lines[i]->istate = 0;
  6104. recalculate_tabs(env->lines[i]);
  6105. }
  6106. for (int i = 0; i < env->line_count; ++i) {
  6107. recalculate_syntax(env->lines[i],i);
  6108. }
  6109. place_cursor_actual();
  6110. update_title();
  6111. redraw_all();
  6112. render_commandline_message("%d character%s, %d line%s changed",
  6113. count_chars, (count_chars == 1) ? "" : "s",
  6114. count_lines, (count_lines == 1) ? "" : "s");
  6115. }
  6116. int is_whitespace(int codepoint) {
  6117. return codepoint == ' ' || codepoint == '\t';
  6118. }
  6119. int is_normal(int codepoint) {
  6120. return isalnum(codepoint) || codepoint == '_';
  6121. }
  6122. int is_special(int codepoint) {
  6123. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6124. }
  6125. BIM_ACTION(word_left, 0,
  6126. "Move the cursor left to the previous word."
  6127. )(void) {
  6128. if (!env->lines[env->line_no-1]) return;
  6129. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6130. env->col_no -= 1;
  6131. }
  6132. if (env->col_no == 1) {
  6133. if (env->line_no == 1) goto _place;
  6134. env->line_no--;
  6135. env->col_no = env->lines[env->line_no-1]->actual;
  6136. goto _place;
  6137. }
  6138. int (*inverse_comparator)(int) = is_special;
  6139. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6140. inverse_comparator = is_normal;
  6141. }
  6142. do {
  6143. if (env->col_no > 1) {
  6144. env->col_no -= 1;
  6145. }
  6146. } 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));
  6147. _place:
  6148. set_preferred_column();
  6149. place_cursor_actual();
  6150. }
  6151. BIM_ACTION(big_word_left, 0,
  6152. "Move the cursor left to the previous WORD."
  6153. )(void) {
  6154. int line_no = env->line_no;
  6155. int col_no = env->col_no;
  6156. do {
  6157. col_no--;
  6158. while (col_no == 0) {
  6159. line_no--;
  6160. if (line_no == 0) {
  6161. goto_line(1);
  6162. set_preferred_column();
  6163. return;
  6164. }
  6165. col_no = env->lines[line_no-1]->actual;
  6166. }
  6167. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6168. do {
  6169. col_no--;
  6170. if (col_no == 0) {
  6171. env->col_no = 1;
  6172. env->line_no = line_no;
  6173. set_preferred_column();
  6174. redraw_statusbar();
  6175. place_cursor_actual();
  6176. return;
  6177. }
  6178. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6179. env->col_no = col_no;
  6180. env->line_no = line_no;
  6181. set_preferred_column();
  6182. cursor_right();
  6183. }
  6184. BIM_ACTION(word_right, 0,
  6185. "Move the cursor right to the start of the next word."
  6186. )(void) {
  6187. if (!env->lines[env->line_no-1]) return;
  6188. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6189. /* next line */
  6190. if (env->line_no == env->line_count) return;
  6191. env->line_no++;
  6192. env->col_no = 0;
  6193. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6194. goto _place;
  6195. }
  6196. }
  6197. 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)) {
  6198. 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)) {
  6199. env->col_no++;
  6200. }
  6201. goto _place;
  6202. }
  6203. int (*inverse_comparator)(int) = is_special;
  6204. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6205. inverse_comparator = is_normal;
  6206. }
  6207. 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)) {
  6208. env->col_no++;
  6209. }
  6210. 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)) {
  6211. env->col_no++;
  6212. }
  6213. _place:
  6214. set_preferred_column();
  6215. place_cursor_actual();
  6216. }
  6217. BIM_ACTION(big_word_right, 0,
  6218. "Move the cursor right to the start of the next WORD."
  6219. )(void) {
  6220. int line_no = env->line_no;
  6221. int col_no = env->col_no;
  6222. do {
  6223. col_no++;
  6224. if (col_no > env->lines[line_no-1]->actual) {
  6225. line_no++;
  6226. if (line_no > env->line_count) {
  6227. env->line_no = env->line_count;
  6228. env->col_no = env->lines[env->line_no-1]->actual;
  6229. set_preferred_column();
  6230. redraw_statusbar();
  6231. place_cursor_actual();
  6232. return;
  6233. }
  6234. col_no = 0;
  6235. break;
  6236. }
  6237. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6238. do {
  6239. col_no++;
  6240. while (col_no > env->lines[line_no-1]->actual) {
  6241. line_no++;
  6242. if (line_no >= env->line_count) {
  6243. env->col_no = env->lines[env->line_count-1]->actual;
  6244. env->line_no = env->line_count;
  6245. set_preferred_column();
  6246. redraw_statusbar();
  6247. place_cursor_actual();
  6248. return;
  6249. }
  6250. col_no = 1;
  6251. }
  6252. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6253. env->col_no = col_no;
  6254. env->line_no = line_no;
  6255. set_preferred_column();
  6256. redraw_statusbar();
  6257. place_cursor_actual();
  6258. return;
  6259. }
  6260. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  6261. "Delete the character at the cursor, or merge with previous line."
  6262. )(void) {
  6263. if (env->col_no > 1) {
  6264. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6265. env->col_no -= 1;
  6266. if (env->coffset > 0) env->coffset--;
  6267. redraw_line(env->line_no-1);
  6268. set_modified();
  6269. redraw_statusbar();
  6270. place_cursor_actual();
  6271. } else if (env->line_no > 1) {
  6272. int tmp = env->lines[env->line_no - 2]->actual;
  6273. merge_lines(env->lines, env->line_no - 1);
  6274. env->line_no -= 1;
  6275. env->col_no = tmp+1;
  6276. set_preferred_column();
  6277. redraw_text();
  6278. set_modified();
  6279. redraw_statusbar();
  6280. place_cursor_actual();
  6281. }
  6282. }
  6283. BIM_ACTION(delete_word, ACTION_IS_RW,
  6284. "Delete the previous word."
  6285. )(void) {
  6286. if (!env->lines[env->line_no-1]) return;
  6287. if (env->col_no > 1) {
  6288. /* Start by deleting whitespace */
  6289. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6290. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6291. env->col_no -= 1;
  6292. if (env->coffset > 0) env->coffset--;
  6293. }
  6294. int (*inverse_comparator)(int) = is_special;
  6295. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6296. inverse_comparator = is_normal;
  6297. }
  6298. do {
  6299. if (env->col_no > 1) {
  6300. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6301. env->col_no -= 1;
  6302. if (env->coffset > 0) env->coffset--;
  6303. }
  6304. } 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));
  6305. set_preferred_column();
  6306. redraw_text();
  6307. set_modified();
  6308. redraw_statusbar();
  6309. place_cursor_actual();
  6310. }
  6311. }
  6312. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  6313. "Insert a line break, splitting the current line into two."
  6314. )(void) {
  6315. if (env->indent) {
  6316. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  6317. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  6318. (env->col_no > 3) &&
  6319. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  6320. delete_at_cursor();
  6321. }
  6322. }
  6323. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6324. env->lines = add_line(env->lines, env->line_no);
  6325. } else {
  6326. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6327. }
  6328. env->coffset = 0;
  6329. env->col_no = 1;
  6330. env->line_no += 1;
  6331. set_preferred_column();
  6332. add_indent(env->line_no-1,env->line_no-2,0);
  6333. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  6334. env->offset += 1;
  6335. }
  6336. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  6337. set_modified();
  6338. }
  6339. BIM_ACTION(yank_lines, 0,
  6340. "Copy lines into the paste buffer."
  6341. )(void) {
  6342. int start = env->start_line;
  6343. int end = env->line_no;
  6344. if (global_config.yanks) {
  6345. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6346. free(global_config.yanks[i]);
  6347. }
  6348. free(global_config.yanks);
  6349. }
  6350. int lines_to_yank;
  6351. int start_point;
  6352. if (start <= end) {
  6353. lines_to_yank = end - start + 1;
  6354. start_point = start - 1;
  6355. } else {
  6356. lines_to_yank = start - end + 1;
  6357. start_point = end - 1;
  6358. }
  6359. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6360. global_config.yank_count = lines_to_yank;
  6361. global_config.yank_is_full_lines = 1;
  6362. for (int i = 0; i < lines_to_yank; ++i) {
  6363. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6364. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6365. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6366. global_config.yanks[i]->istate = 0;
  6367. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6368. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6369. global_config.yanks[i]->text[j].flags = 0;
  6370. }
  6371. }
  6372. }
  6373. /**
  6374. * Helper to yank part of a line into a new yank line.
  6375. */
  6376. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  6377. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  6378. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  6379. global_config.yanks[yank_no]->actual = count;
  6380. global_config.yanks[yank_no]->istate = 0;
  6381. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  6382. for (int i = 0; i < count; ++i) {
  6383. global_config.yanks[yank_no]->text[i].flags = 0;
  6384. }
  6385. }
  6386. /**
  6387. * Yank text...
  6388. */
  6389. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  6390. if (global_config.yanks) {
  6391. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6392. free(global_config.yanks[i]);
  6393. }
  6394. free(global_config.yanks);
  6395. }
  6396. int lines_to_yank = end_line - start_line + 1;
  6397. int start_point = start_line - 1;
  6398. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6399. global_config.yank_count = lines_to_yank;
  6400. global_config.yank_is_full_lines = 0;
  6401. if (lines_to_yank == 1) {
  6402. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  6403. } else {
  6404. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  6405. /* Yank middle lines */
  6406. for (int i = 1; i < lines_to_yank - 1; ++i) {
  6407. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6408. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6409. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6410. global_config.yanks[i]->istate = 0;
  6411. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6412. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6413. global_config.yanks[i]->text[j].flags = 0;
  6414. }
  6415. }
  6416. /* Yank end line */
  6417. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  6418. }
  6419. }
  6420. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  6421. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  6422. )(int direction) {
  6423. if (direction == -1 && env->sel_col <= 0) return;
  6424. int prev_width = 0;
  6425. for (int i = env->line_no; i <= env->start_line; i++) {
  6426. line_t * line = env->lines[i - 1];
  6427. int _x = 0;
  6428. int col = 1;
  6429. int j = 0;
  6430. for (; j < line->actual; ++j) {
  6431. char_t * c = &line->text[j];
  6432. _x += c->display_width;
  6433. col = j+1;
  6434. if (_x > env->sel_col) break;
  6435. prev_width = c->display_width;
  6436. }
  6437. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  6438. line_delete(line, line->actual, i - 1);
  6439. set_modified();
  6440. } else if (_x > env->sel_col) {
  6441. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  6442. set_modified();
  6443. }
  6444. }
  6445. if (direction == -1) {
  6446. env->sel_col -= prev_width;
  6447. env->col_no--;
  6448. }
  6449. redraw_text();
  6450. }
  6451. uint32_t * get_word_under_cursor(void) {
  6452. /* Figure out size */
  6453. int c_before = 0;
  6454. int c_after = 0;
  6455. int i = env->col_no;
  6456. while (i > 0) {
  6457. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6458. c_before++;
  6459. i--;
  6460. }
  6461. i = env->col_no+1;
  6462. while (i < env->lines[env->line_no-1]->actual+1) {
  6463. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6464. c_after++;
  6465. i++;
  6466. }
  6467. if (!c_before && !c_after) return NULL;
  6468. /* Populate with characters */
  6469. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  6470. int j = 0;
  6471. while (c_before) {
  6472. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  6473. c_before--;
  6474. j++;
  6475. }
  6476. int x = 0;
  6477. while (c_after) {
  6478. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  6479. j++;
  6480. x++;
  6481. c_after--;
  6482. }
  6483. out[j] = 0;
  6484. return out;
  6485. }
  6486. BIM_ACTION(search_under_cursor, 0,
  6487. "Search for the word currently under the cursor."
  6488. )(void) {
  6489. if (global_config.search) free(global_config.search);
  6490. global_config.search = get_word_under_cursor();
  6491. /* Find it */
  6492. search_next();
  6493. }
  6494. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  6495. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  6496. )(int type, int c) {
  6497. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  6498. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  6499. env->col_no = i - !!(type == 't');
  6500. place_cursor_actual();
  6501. set_preferred_column();
  6502. return;
  6503. }
  6504. }
  6505. }
  6506. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  6507. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  6508. )(int type, int c) {
  6509. for (int i = env->col_no-1; i >= 1; --i) {
  6510. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  6511. env->col_no = i + !!(type == 'T');
  6512. place_cursor_actual();
  6513. set_preferred_column();
  6514. return;
  6515. }
  6516. }
  6517. }
  6518. /**
  6519. * Clear the navigation number buffer
  6520. */
  6521. void reset_nav_buffer(int c) {
  6522. if (c == KEY_TIMEOUT) return;
  6523. if (nav_buffer && (c < '0' || c > '9')) {
  6524. nav_buffer = 0;
  6525. redraw_commandline();
  6526. }
  6527. }
  6528. /**
  6529. * Determine if a column + line number are within range of the
  6530. * current character selection specified by start_line, etc.
  6531. *
  6532. * Used to determine how syntax flags should be set when redrawing
  6533. * selected text in CHAR SELECTION mode.
  6534. */
  6535. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  6536. if (start_line == end_line) {
  6537. if ( end_col < start_col) {
  6538. int tmp = end_col;
  6539. end_col = start_col;
  6540. start_col = tmp;
  6541. }
  6542. return (col >= start_col && col <= end_col);
  6543. }
  6544. if (start_line > end_line) {
  6545. int tmp = end_line;
  6546. end_line = start_line;
  6547. start_line = tmp;
  6548. tmp = end_col;
  6549. end_col = start_col;
  6550. start_col = tmp;
  6551. }
  6552. if (line < start_line || line > end_line) return 0;
  6553. if (line == start_line) {
  6554. return col >= start_col;
  6555. }
  6556. if (line == end_line) {
  6557. return col <= end_col;
  6558. }
  6559. return 1;
  6560. }
  6561. /**
  6562. * Macro for redrawing selected lines with appropriate highlighting.
  6563. */
  6564. #define _redraw_line(line, force_start_line) \
  6565. do { \
  6566. if (!(force_start_line) && (line) == env->start_line) break; \
  6567. if ((line) > env->line_count + 1) { \
  6568. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6569. draw_excess_line((line) - env->offset - 1); \
  6570. } \
  6571. break; \
  6572. } \
  6573. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  6574. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  6575. (env->line_no == env->start_line && (line) != env->start_line)) { \
  6576. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  6577. } else { \
  6578. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  6579. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  6580. } \
  6581. } \
  6582. redraw_line((line)-1); \
  6583. } while (0)
  6584. #define _redraw_line_char(line, force_start_line) \
  6585. do { \
  6586. if (!(force_start_line) && (line) == env->start_line) break; \
  6587. if ((line) > env->line_count + 1) { \
  6588. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6589. draw_excess_line((line) - env->offset - 1); \
  6590. } \
  6591. break; \
  6592. } \
  6593. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  6594. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  6595. (env->line_no == env->start_line && (line) != env->start_line)) { \
  6596. /* Line is completely outside selection */ \
  6597. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  6598. } else { \
  6599. if ((line) == env->start_line || (line) == env->line_no) { \
  6600. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  6601. } \
  6602. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  6603. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  6604. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  6605. } \
  6606. } \
  6607. } \
  6608. redraw_line((line)-1); \
  6609. } while (0)
  6610. #define _redraw_line_col(line, force_start_line) \
  6611. do {\
  6612. if (!(force_start_line) && (line) == env->start_line) break; \
  6613. if ((line) > env->line_count + 1) { \
  6614. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6615. draw_excess_line((line) - env->offset - 1); \
  6616. } \
  6617. break; \
  6618. } \
  6619. redraw_line((line)-1); \
  6620. } while (0)
  6621. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  6622. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  6623. )(int direction) {
  6624. int lines_to_cover = 0;
  6625. int start_point = 0;
  6626. if (env->start_line <= env->line_no) {
  6627. start_point = env->start_line - 1;
  6628. lines_to_cover = env->line_no - env->start_line + 1;
  6629. } else {
  6630. start_point = env->line_no - 1;
  6631. lines_to_cover = env->start_line - env->line_no + 1;
  6632. }
  6633. for (int i = 0; i < lines_to_cover; ++i) {
  6634. if (env->lines[start_point + i]->actual < 1) continue;
  6635. if (direction == -1) {
  6636. if (env->tabs) {
  6637. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  6638. line_delete(env->lines[start_point + i],1,start_point+i);
  6639. _redraw_line(start_point+i+1,1);
  6640. }
  6641. } else {
  6642. for (int j = 0; j < env->tabstop; ++j) {
  6643. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  6644. line_delete(env->lines[start_point + i],1,start_point+i);
  6645. }
  6646. }
  6647. _redraw_line(start_point+i+1,1);
  6648. }
  6649. } else if (direction == 1) {
  6650. if (env->tabs) {
  6651. char_t c;
  6652. c.codepoint = '\t';
  6653. c.display_width = env->tabstop;
  6654. c.flags = FLAG_SELECT;
  6655. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6656. } else {
  6657. for (int j = 0; j < env->tabstop; ++j) {
  6658. char_t c;
  6659. c.codepoint = ' ';
  6660. c.display_width = 1;
  6661. c.flags = FLAG_SELECT;
  6662. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6663. }
  6664. }
  6665. _redraw_line(start_point+i+1,1);
  6666. }
  6667. }
  6668. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6669. env->col_no = env->lines[env->line_no-1]->actual;
  6670. }
  6671. set_preferred_column();
  6672. set_modified();
  6673. }
  6674. void recalculate_selected_lines(void) {
  6675. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  6676. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  6677. if (start < 1) start = 1;
  6678. if (start > env->line_count) start = env->line_count;
  6679. if (end < 1) end = 1;
  6680. if (end > env->line_count) end = env->line_count;
  6681. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  6682. recalculate_syntax(env->lines[i-1],i-1);
  6683. }
  6684. redraw_all();
  6685. }
  6686. BIM_ACTION(enter_line_selection, 0,
  6687. "Enter line selection mode."
  6688. )(void) {
  6689. /* Set mode */
  6690. env->mode = MODE_LINE_SELECTION;
  6691. /* Store start position */
  6692. env->start_line = env->line_no;
  6693. env->prev_line = env->start_line;
  6694. env->start_col = env->col_no;
  6695. /* Redraw commandline to get -- LINE SELECTION -- text */
  6696. redraw_commandline();
  6697. unhighlight_matching_paren();
  6698. /* Set this line as selected for syntax highlighting */
  6699. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  6700. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  6701. }
  6702. /* And redraw it */
  6703. redraw_line(env->line_no-1);
  6704. }
  6705. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  6706. "Swap between LINE and CHAR selection modes."
  6707. )(int mode) {
  6708. env->mode = mode;
  6709. if (mode == MODE_LINE_SELECTION) {
  6710. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  6711. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  6712. for (int i = start; i <= end; ++i) {
  6713. _redraw_line(i, 1);
  6714. }
  6715. } else if (mode == MODE_CHAR_SELECTION) {
  6716. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  6717. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  6718. for (int i = start; i <= end; ++i) {
  6719. _redraw_line_char(i, 1);
  6720. }
  6721. }
  6722. }
  6723. BIM_ACTION(delete_and_yank_lines, 0,
  6724. "Delete and yank the selected lines."
  6725. )(void) {
  6726. yank_lines();
  6727. if (env->start_line <= env->line_no) {
  6728. int lines_to_delete = env->line_no - env->start_line + 1;
  6729. for (int i = 0; i < lines_to_delete; ++i) {
  6730. env->lines = remove_line(env->lines, env->start_line-1);
  6731. }
  6732. env->line_no = env->start_line;
  6733. } else {
  6734. int lines_to_delete = env->start_line - env->line_no + 1;
  6735. for (int i = 0; i < lines_to_delete; ++i) {
  6736. env->lines = remove_line(env->lines, env->line_no-1);
  6737. }
  6738. }
  6739. if (env->line_no > env->line_count) {
  6740. env->line_no = env->line_count;
  6741. }
  6742. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6743. env->col_no = env->lines[env->line_no-1]->actual;
  6744. }
  6745. set_preferred_column();
  6746. set_modified();
  6747. }
  6748. BIM_ACTION(enter_insert, ACTION_IS_RW,
  6749. "Enter insert mode."
  6750. )(void) {
  6751. env->mode = MODE_INSERT;
  6752. set_history_break();
  6753. }
  6754. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  6755. "Delete and yank the selected lines and then enter insert mode."
  6756. )(void) {
  6757. delete_and_yank_lines();
  6758. env->lines = add_line(env->lines, env->line_no-1);
  6759. redraw_text();
  6760. env->mode = MODE_INSERT;
  6761. }
  6762. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  6763. "Replace characters in the selected lines."
  6764. )(int c) {
  6765. if (c >= KEY_ESCAPE) {
  6766. render_error("Invalid key for replacement");
  6767. return;
  6768. }
  6769. char_t _c = {codepoint_width(c), 0, c};
  6770. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  6771. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  6772. for (int line = start_point; line <= end_point; ++line) {
  6773. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  6774. line_replace(env->lines[line-1], _c, i, line-1);
  6775. }
  6776. }
  6777. }
  6778. BIM_ACTION(leave_selection, 0,
  6779. "Leave selection modes and return to normal mode."
  6780. )(void) {
  6781. set_history_break();
  6782. env->mode = MODE_NORMAL;
  6783. recalculate_selected_lines();
  6784. }
  6785. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  6786. "Insert a character on all lines at the current column."
  6787. )(int c) {
  6788. char_t _c;
  6789. _c.codepoint = c;
  6790. _c.flags = 0;
  6791. _c.display_width = codepoint_width(c);
  6792. int inserted_width = 0;
  6793. /* For each line */
  6794. for (int i = env->line_no; i <= env->start_line; i++) {
  6795. line_t * line = env->lines[i - 1];
  6796. int _x = 0;
  6797. int col = 1;
  6798. int j = 0;
  6799. for (; j < line->actual; ++j) {
  6800. char_t * c = &line->text[j];
  6801. _x += c->display_width;
  6802. col = j+1;
  6803. if (_x > env->sel_col) break;
  6804. }
  6805. if ((_x == env->sel_col && j == line->actual)) {
  6806. _x = env->sel_col + 1;
  6807. col = line->actual + 1;
  6808. }
  6809. if (_x > env->sel_col) {
  6810. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  6811. if (line != nline) {
  6812. env->lines[i - 1] = nline;
  6813. line = nline;
  6814. }
  6815. set_modified();
  6816. }
  6817. recalculate_tabs(line);
  6818. inserted_width = line->text[col-1].display_width;
  6819. }
  6820. env->sel_col += inserted_width;
  6821. env->col_no++;
  6822. }
  6823. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  6824. "Enter column insert mode."
  6825. )(void) {
  6826. if (env->start_line < env->line_no) {
  6827. /* swap */
  6828. int tmp = env->line_no;
  6829. env->line_no = env->start_line;
  6830. env->start_line = tmp;
  6831. }
  6832. env->mode = MODE_COL_INSERT;
  6833. }
  6834. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  6835. "Enter column insert mode after the selected column."
  6836. )(void) {
  6837. env->sel_col += 1;
  6838. enter_col_insert();
  6839. }
  6840. BIM_ACTION(delete_column, ACTION_IS_RW,
  6841. "(temporary) Delete the selected column."
  6842. )(void) {
  6843. /* TODO maybe a flag to do this so we can just call delete_at_column with arg = 1? */
  6844. if (env->start_line < env->line_no) {
  6845. int tmp = env->line_no;
  6846. env->line_no = env->start_line;
  6847. env->start_line = tmp;
  6848. }
  6849. delete_at_column(1);
  6850. }
  6851. BIM_ACTION(enter_col_selection, 0,
  6852. "Enter column selection mode."
  6853. )(void) {
  6854. /* Set mode */
  6855. env->mode = MODE_COL_SELECTION;
  6856. /* Store cursor */
  6857. env->start_line = env->line_no;
  6858. env->sel_col = env->preferred_column;
  6859. env->prev_line = env->start_line;
  6860. /* Redraw commandline */
  6861. redraw_commandline();
  6862. /* Nothing else to do here; rely on cursor */
  6863. }
  6864. BIM_ACTION(yank_characters, 0,
  6865. "Yank the selected characters to the paste buffer."
  6866. )(void) {
  6867. int end_line = env->line_no;
  6868. int end_col = env->col_no;
  6869. if (env->start_line == end_line) {
  6870. if (env->start_col > end_col) {
  6871. int tmp = env->start_col;
  6872. env->start_col = end_col;
  6873. end_col = tmp;
  6874. }
  6875. } else if (env->start_line > end_line) {
  6876. int tmp = env->start_line;
  6877. env->start_line = end_line;
  6878. end_line = tmp;
  6879. tmp = env->start_col;
  6880. env->start_col = end_col;
  6881. end_col = tmp;
  6882. }
  6883. yank_text(env->start_line, env->start_col, end_line, end_col);
  6884. }
  6885. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  6886. "Delete and yank the selected characters."
  6887. )(void) {
  6888. int end_line = env->line_no;
  6889. int end_col = env->col_no;
  6890. if (env->start_line == end_line) {
  6891. if (env->start_col > end_col) {
  6892. int tmp = env->start_col;
  6893. env->start_col = end_col;
  6894. end_col = tmp;
  6895. }
  6896. yank_text(env->start_line, env->start_col, end_line, end_col);
  6897. for (int i = env->start_col; i <= end_col; ++i) {
  6898. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  6899. }
  6900. env->col_no = env->start_col;
  6901. } else {
  6902. if (env->start_line > end_line) {
  6903. int tmp = env->start_line;
  6904. env->start_line = end_line;
  6905. end_line = tmp;
  6906. tmp = env->start_col;
  6907. env->start_col = end_col;
  6908. end_col = tmp;
  6909. }
  6910. /* Copy lines */
  6911. yank_text(env->start_line, env->start_col, end_line, end_col);
  6912. /* Delete lines */
  6913. for (int i = env->start_line+1; i < end_line; ++i) {
  6914. env->lines = remove_line(env->lines, env->start_line);
  6915. } /* end_line is no longer valid; should be start_line+1*/
  6916. /* Delete from env->start_col forward */
  6917. int tmp = env->lines[env->start_line-1]->actual;
  6918. for (int i = env->start_col; i <= tmp; ++i) {
  6919. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  6920. }
  6921. for (int i = 1; i <= end_col; ++i) {
  6922. line_delete(env->lines[env->start_line], 1, env->start_line);
  6923. }
  6924. /* Merge start and end lines */
  6925. merge_lines(env->lines, env->start_line);
  6926. env->line_no = env->start_line;
  6927. env->col_no = env->start_col;
  6928. }
  6929. if (env->line_no > env->line_count) {
  6930. env->line_no = env->line_count;
  6931. }
  6932. set_preferred_column();
  6933. set_modified();
  6934. }
  6935. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  6936. "Delete and yank the selected characters and then enter insert mode."
  6937. )(void) {
  6938. delete_and_yank_chars();
  6939. redraw_text();
  6940. enter_insert();
  6941. }
  6942. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  6943. "Replace the selected characters."
  6944. )(int c) {
  6945. if (c >= KEY_ESCAPE) {
  6946. render_error("Invalid key for replacement");
  6947. return;
  6948. }
  6949. char_t _c = {codepoint_width(c), 0, c};
  6950. /* This should probably be a function line "do_over_range" or something */
  6951. if (env->start_line == env->line_no) {
  6952. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  6953. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  6954. for (int i = s; i <= e; ++i) {
  6955. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  6956. }
  6957. redraw_text();
  6958. } else {
  6959. if (env->start_line < env->line_no) {
  6960. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  6961. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  6962. }
  6963. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  6964. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  6965. line_replace(env->lines[line-1], _c, i, line-1);
  6966. }
  6967. }
  6968. for (int s = 0; s < env->col_no; ++s) {
  6969. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  6970. }
  6971. } else {
  6972. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  6973. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  6974. }
  6975. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  6976. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  6977. line_replace(env->lines[line-1], _c, i, line-1);
  6978. }
  6979. }
  6980. for (int s = 0; s < env->start_col; ++s) {
  6981. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  6982. }
  6983. }
  6984. }
  6985. }
  6986. BIM_ACTION(enter_char_selection, 0,
  6987. "Enter character selection mode."
  6988. )(void) {
  6989. /* Set mode */
  6990. env->mode = MODE_CHAR_SELECTION;
  6991. /* Set cursor positions */
  6992. env->start_line = env->line_no;
  6993. env->start_col = env->col_no;
  6994. env->prev_line = env->start_line;
  6995. /* Redraw commandline for -- CHAR SELECTION -- */
  6996. redraw_commandline();
  6997. unhighlight_matching_paren();
  6998. /* Select single character */
  6999. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7000. redraw_line(env->line_no-1);
  7001. }
  7002. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  7003. "Move the cursor to the end of the selection and enter insert mode."
  7004. )(void) {
  7005. recalculate_selected_lines();
  7006. if (env->line_no == env->start_line) {
  7007. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  7008. } else if (env->line_no < env->start_line) {
  7009. env->col_no = env->start_col + 1;
  7010. env->line_no = env->start_line;
  7011. } else {
  7012. env->col_no += 1;
  7013. }
  7014. env->mode = MODE_INSERT;
  7015. }
  7016. struct completion_match {
  7017. char * string;
  7018. char * file;
  7019. char * search;
  7020. };
  7021. void free_completion_match(struct completion_match * match) {
  7022. if (match->string) free(match->string);
  7023. if (match->file) free(match->file);
  7024. if (match->search) free(match->search);
  7025. }
  7026. /**
  7027. * Read ctags file to find matches for a symbol
  7028. */
  7029. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  7030. int matches_len = 4;
  7031. *matches_count = 0;
  7032. *matches = malloc(sizeof(struct completion_match) * (matches_len));
  7033. FILE * tags = fopen("tags","r");
  7034. if (!tags) return 1;
  7035. char tmp[4096]; /* max line */
  7036. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  7037. if (tmp[0] == '!') continue;
  7038. int i = 0;
  7039. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  7040. if (comp[i] == '\0') {
  7041. if (complete_match && tmp[i] != '\t') continue;
  7042. int j = i;
  7043. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7044. tmp[j] = '\0'; j++;
  7045. char * file = &tmp[j];
  7046. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7047. tmp[j] = '\0'; j++;
  7048. char * search = &tmp[j];
  7049. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  7050. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  7051. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  7052. tmp[j] = '\0'; j++;
  7053. /* Dedup */
  7054. #if 0
  7055. int match_found = 0;
  7056. for (int i = 0; i < *matches_count; ++i) {
  7057. if (!strcmp((*matches)[i].string, tmp)) {
  7058. match_found = 1;
  7059. break;
  7060. }
  7061. }
  7062. if (match_found) continue;
  7063. #endif
  7064. if (*matches_count == matches_len) {
  7065. matches_len *= 2;
  7066. *matches = realloc(*matches, sizeof(struct completion_match) * (matches_len));
  7067. }
  7068. (*matches)[*matches_count].string = strdup(tmp);
  7069. (*matches)[*matches_count].file = strdup(file);
  7070. (*matches)[*matches_count].search = strdup(search);
  7071. (*matches_count)++;
  7072. }
  7073. }
  7074. fclose(tags);
  7075. return 0;
  7076. }
  7077. /**
  7078. * Draw an autocomplete popover with matches.
  7079. */
  7080. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  7081. int original_length = 0;
  7082. while (tmp[original_length]) original_length++;
  7083. int max_width = 0;
  7084. for (int i = 0; i < matches_count; ++i) {
  7085. /* TODO unicode width */
  7086. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  7087. if (my_width > (unsigned int)max_width) {
  7088. max_width = my_width;
  7089. }
  7090. }
  7091. /* Figure out how much space we have to display the window */
  7092. int cursor_y = env->line_no - env->offset + 1;
  7093. int max_y = global_config.term_height - 2 - cursor_y;
  7094. /* Find a good place to put the box horizontally */
  7095. int num_size = num_width() + 3;
  7096. int x = num_size + 1 - env->coffset;
  7097. /* Determine where the cursor is physically */
  7098. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  7099. char_t * c = &env->lines[env->line_no-1]->text[i];
  7100. x += c->display_width;
  7101. }
  7102. int box_width = max_width;
  7103. int box_x = x;
  7104. int box_y = cursor_y+1;
  7105. if (max_width > env->width - num_width()) {
  7106. box_width = env->width - num_width();
  7107. box_x = 1;
  7108. } else if (env->width - x < max_width) {
  7109. box_width = max_width;
  7110. box_x = env->width - max_width;
  7111. }
  7112. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  7113. for (int x = index; x < max_count+index; ++x) {
  7114. int i = x % matches_count;
  7115. place_cursor(box_x, box_y+x-index);
  7116. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  7117. /* TODO wide characters */
  7118. int match_width = strlen(matches[i].string);
  7119. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  7120. for (int j = 0; j < box_width; ++j) {
  7121. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  7122. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  7123. if (j < match_width) printf("%c", matches[i].string[j]);
  7124. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  7125. else printf(" ");
  7126. }
  7127. }
  7128. if (max_count == 0) {
  7129. place_cursor(box_x, box_y);
  7130. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7131. printf(" (no matches) ");
  7132. } else if (max_count != matches_count) {
  7133. place_cursor(box_x, box_y+max_count);
  7134. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7135. printf(" (%d more) ", matches_count-max_count);
  7136. }
  7137. }
  7138. /**
  7139. * Autocomplete words (function/variable names, etc.) in input mode.
  7140. */
  7141. int omni_complete(void) {
  7142. int c;
  7143. /* Pull the word from before the cursor */
  7144. int c_before = 0;
  7145. int i = env->col_no-1;
  7146. while (i > 0) {
  7147. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7148. c_before++;
  7149. i--;
  7150. }
  7151. /* Populate with characters */
  7152. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  7153. int j = 0;
  7154. while (c_before) {
  7155. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  7156. c_before--;
  7157. j++;
  7158. }
  7159. tmp[j] = 0;
  7160. /*
  7161. * TODO matches should probably be a struct with more data than just
  7162. * the matching string; maybe offset where the needle was found,
  7163. * class information, source file information - anything we can extract
  7164. * from ctags, but also other information for other sources of completion.
  7165. */
  7166. struct completion_match *matches;
  7167. int matches_count;
  7168. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  7169. if (read_tags(tmp, &matches, &matches_count, 0)) goto _completion_done;
  7170. /* Draw box with matches at cursor-width(tmp) */
  7171. draw_completion_matches(tmp, matches, matches_count, 0);
  7172. int retval = 0;
  7173. int index = 0;
  7174. _completion_done:
  7175. place_cursor_actual();
  7176. while (1) {
  7177. c = bim_getch();
  7178. if (c == -1) continue;
  7179. if (matches_count < 1) {
  7180. redraw_all();
  7181. break;
  7182. }
  7183. if (c == 15) {
  7184. index = (index + 1) % matches_count;
  7185. draw_completion_matches(tmp, matches, matches_count, index);
  7186. place_cursor_actual();
  7187. continue;
  7188. } else if (c == '\t') {
  7189. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  7190. insert_char(matches[index].string[i]);
  7191. }
  7192. set_preferred_column();
  7193. redraw_text();
  7194. place_cursor_actual();
  7195. goto _finish_completion;
  7196. } else if (isgraph(c) && c != '}') {
  7197. /* insert and continue matching */
  7198. insert_char(c);
  7199. set_preferred_column();
  7200. redraw_text();
  7201. place_cursor_actual();
  7202. retval = 1;
  7203. goto _finish_completion;
  7204. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  7205. delete_at_cursor();
  7206. set_preferred_column();
  7207. redraw_text();
  7208. place_cursor_actual();
  7209. retval = 1;
  7210. goto _finish_completion;
  7211. }
  7212. /* TODO: Keyboard navigation of the matches list would be nice */
  7213. redraw_all();
  7214. break;
  7215. }
  7216. bim_unget(c);
  7217. _finish_completion:
  7218. for (int i = 0; i < matches_count; ++i) {
  7219. free_completion_match(&matches[i]);
  7220. }
  7221. free(matches);
  7222. free(tmp);
  7223. return retval;
  7224. }
  7225. /**
  7226. * Set the search string from a UTF-8 sequence.
  7227. * Since the search string is normally a series of codepoints, this saves
  7228. * some effort when trying to search for things we pulled from the outside world.
  7229. * (eg., ctags search terms)
  7230. */
  7231. void set_search_from_bytes(char * bytes) {
  7232. if (global_config.search) free(global_config.search);
  7233. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) + 1));
  7234. uint32_t * s = global_config.search;
  7235. char * tmp = bytes;
  7236. uint32_t c, istate = 0;
  7237. while (*tmp) {
  7238. if (!decode(&istate, &c, *tmp)) {
  7239. *s = c;
  7240. s++;
  7241. *s = 0;
  7242. } else if (istate == UTF8_REJECT) {
  7243. istate = 0;
  7244. }
  7245. tmp++;
  7246. }
  7247. }
  7248. BIM_ACTION(goto_definition, 0,
  7249. "Jump to the definition of the word under under cursor."
  7250. )(void) {
  7251. uint32_t * word = get_word_under_cursor();
  7252. if (!word) {
  7253. render_error("No match");
  7254. return;
  7255. }
  7256. struct completion_match *matches;
  7257. int matches_count;
  7258. if (read_tags(word, &matches, &matches_count, 1)) {
  7259. render_error("No tags file");
  7260. goto _done;
  7261. }
  7262. if (!matches_count) {
  7263. render_error("No match");
  7264. goto _done;
  7265. }
  7266. #define _perform_correct_search(i) do { \
  7267. if (matches[i].search[0] == '/') { \
  7268. set_search_from_bytes(&matches[i].search[1]); \
  7269. search_next(); \
  7270. } else { \
  7271. goto_line(atoi(matches[i].search)); \
  7272. } \
  7273. } while (0)
  7274. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  7275. _perform_correct_search(0);
  7276. } else {
  7277. /* Check if there were other matches that are in this file */
  7278. for (int i =1; env->file_name && i < matches_count; ++i) {
  7279. if (!strcmp(matches[i].file, env->file_name)) {
  7280. _perform_correct_search(i);
  7281. goto _done;
  7282. }
  7283. }
  7284. /* Check buffers */
  7285. for (int i = 0; i < buffers_len; ++i) {
  7286. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  7287. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  7288. env = buffers[i];
  7289. redraw_tabbar();
  7290. _perform_correct_search(i);
  7291. goto _done;
  7292. }
  7293. }
  7294. /* Okay, let's try opening */
  7295. buffer_t * old_buf = env;
  7296. open_file(matches[0].file);
  7297. if (env != old_buf) {
  7298. _perform_correct_search(0);
  7299. } else {
  7300. render_error("Could not locate file containing definition");
  7301. }
  7302. }
  7303. _done:
  7304. for (int i = 0; i < matches_count; ++i) {
  7305. free_completion_match(&matches[i]);
  7306. }
  7307. free(matches);
  7308. free(word);
  7309. }
  7310. /**
  7311. * Read one codepoint, with verbatim support.
  7312. */
  7313. int read_one_character(char * message) {
  7314. /* Read one character and replace */
  7315. if (!global_config.overlay_mode) {
  7316. render_commandline_message(message);
  7317. place_cursor_actual();
  7318. }
  7319. int c;
  7320. while ((c = bim_getkey(200))) {
  7321. if (c == KEY_TIMEOUT) continue;
  7322. if (c == KEY_CTRL_V) {
  7323. if (!global_config.overlay_mode) {
  7324. render_commandline_message(message);
  7325. printf(" ^V");
  7326. place_cursor_actual();
  7327. }
  7328. while ((c = bim_getch()) == -1);
  7329. break;
  7330. }
  7331. break;
  7332. }
  7333. redraw_commandline();
  7334. return c;
  7335. }
  7336. int read_one_byte(char * message) {
  7337. if (!global_config.overlay_mode) {
  7338. render_commandline_message(message);
  7339. place_cursor_actual();
  7340. }
  7341. int c;
  7342. while ((c = bim_getch())) {
  7343. if (c == -1) continue;
  7344. break;
  7345. }
  7346. redraw_commandline();
  7347. return c;
  7348. }
  7349. BIM_ACTION(cursor_left_with_wrap, 0,
  7350. "Move the cursor one position left, wrapping to the previous line."
  7351. )(void) {
  7352. if (env->line_no > 1 && env->col_no == 1) {
  7353. env->line_no--;
  7354. env->col_no = env->lines[env->line_no-1]->actual;
  7355. set_preferred_column();
  7356. place_cursor_actual();
  7357. } else {
  7358. cursor_left();
  7359. }
  7360. }
  7361. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  7362. "Insert a new line before the current line and enter insert mode."
  7363. )(void) {
  7364. set_history_break();
  7365. env->lines = add_line(env->lines, env->line_no-1);
  7366. env->col_no = 1;
  7367. add_indent(env->line_no-1,env->line_no,0);
  7368. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7369. redraw_text();
  7370. set_preferred_column();
  7371. set_modified();
  7372. place_cursor_actual();
  7373. env->mode = MODE_INSERT;
  7374. }
  7375. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  7376. "Insert a new line after the current line and enter insert mode."
  7377. )(void) {
  7378. set_history_break();
  7379. env->lines = add_line(env->lines, env->line_no);
  7380. env->col_no = 1;
  7381. env->line_no += 1;
  7382. add_indent(env->line_no-1,env->line_no-2,0);
  7383. set_preferred_column();
  7384. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7385. env->offset += 1;
  7386. }
  7387. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7388. redraw_text();
  7389. set_modified();
  7390. place_cursor_actual();
  7391. env->mode = MODE_INSERT;
  7392. }
  7393. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  7394. "Place the cursor after the selected character and enter insert mode."
  7395. )(void) {
  7396. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  7397. env->col_no += 1;
  7398. }
  7399. enter_insert();
  7400. }
  7401. BIM_ACTION(delete_forward, ACTION_IS_RW,
  7402. "Delete the character under the cursor."
  7403. )(void) {
  7404. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  7405. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  7406. redraw_text();
  7407. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1) {
  7408. merge_lines(env->lines, env->line_no);
  7409. redraw_text();
  7410. }
  7411. set_modified();
  7412. redraw_statusbar();
  7413. place_cursor_actual();
  7414. }
  7415. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  7416. "Delete the character under the cursor and enter insert mode."
  7417. )(void) {
  7418. set_history_break();
  7419. delete_forward();
  7420. env->mode = MODE_INSERT;
  7421. }
  7422. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  7423. "Paste yanked text before (`P`) or after (`p`) the cursor."
  7424. )(int direction) {
  7425. if (global_config.yanks) {
  7426. if (!global_config.yank_is_full_lines) {
  7427. /* Handle P for paste before, p for past after */
  7428. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  7429. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  7430. target_column = env->lines[env->line_no-1]->actual + 1;
  7431. }
  7432. if (global_config.yank_count > 1) {
  7433. /* Spit the current line at the current position */
  7434. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  7435. }
  7436. /* Insert first line at current position */
  7437. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  7438. 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);
  7439. }
  7440. if (global_config.yank_count > 1) {
  7441. /* Insert full lines */
  7442. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7443. env->lines = add_line(env->lines, env->line_no);
  7444. }
  7445. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7446. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  7447. }
  7448. /* Insert characters from last line into (what was) the next line */
  7449. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  7450. 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);
  7451. }
  7452. }
  7453. } else {
  7454. /* Insert full lines */
  7455. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7456. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  7457. }
  7458. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7459. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  7460. }
  7461. }
  7462. /* Recalculate whole document syntax */
  7463. for (int i = 0; i < env->line_count; ++i) {
  7464. env->lines[i]->istate = 0;
  7465. }
  7466. for (int i = 0; i < env->line_count; ++i) {
  7467. recalculate_syntax(env->lines[i],i);
  7468. }
  7469. if (direction == 1) {
  7470. if (global_config.yank_is_full_lines) {
  7471. env->line_no += 1;
  7472. } else {
  7473. if (global_config.yank_count == 1) {
  7474. env->col_no = env->col_no + global_config.yanks[0]->actual;
  7475. } else {
  7476. env->line_no = env->line_no + global_config.yank_count - 1;
  7477. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  7478. }
  7479. }
  7480. }
  7481. if (global_config.yank_is_full_lines) {
  7482. env->col_no = 1;
  7483. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7484. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  7485. env->col_no = i + 1;
  7486. break;
  7487. }
  7488. }
  7489. }
  7490. set_history_break();
  7491. set_modified();
  7492. redraw_all();
  7493. }
  7494. }
  7495. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  7496. "Move the cursor to the end of the current line and enter insert mode."
  7497. )(void) {
  7498. env->col_no = env->lines[env->line_no-1]->actual+1;
  7499. env->mode = MODE_INSERT;
  7500. set_history_break();
  7501. }
  7502. BIM_ACTION(enter_replace, ACTION_IS_RW,
  7503. "Enter replace mode."
  7504. )(void) {
  7505. env->mode = MODE_REPLACE;
  7506. set_history_break();
  7507. }
  7508. BIM_ACTION(toggle_numbers, 0,
  7509. "Toggle the display of line numbers."
  7510. )(void) {
  7511. global_config.numbers = !global_config.numbers;
  7512. redraw_all();
  7513. place_cursor_actual();
  7514. }
  7515. BIM_ACTION(toggle_indent, 0,
  7516. "Toggle smart indentation."
  7517. )(void) {
  7518. env->indent = !env->indent;
  7519. redraw_statusbar();
  7520. place_cursor_actual();
  7521. }
  7522. BIM_ACTION(expand_split_right, 0,
  7523. "Move the view split divider to the right."
  7524. )(void) {
  7525. global_config.split_percent += 1;
  7526. update_split_size();
  7527. redraw_all();
  7528. }
  7529. BIM_ACTION(expand_split_left, 0,
  7530. "Move the view split divider to the left."
  7531. )(void) {
  7532. global_config.split_percent -= 1;
  7533. update_split_size();
  7534. redraw_all();
  7535. }
  7536. BIM_ACTION(go_page_up, 0,
  7537. "Jump up a screenful."
  7538. )(void) {
  7539. goto_line(env->line_no - (global_config.term_height - 6));
  7540. }
  7541. BIM_ACTION(go_page_down, 0,
  7542. "Jump down a screenful."
  7543. )(void) {
  7544. goto_line(env->line_no + (global_config.term_height - 6));
  7545. }
  7546. BIM_ACTION(jump_to_matching_bracket, 0,
  7547. "Find and jump to the matching bracket for the character under the cursor."
  7548. )(void) {
  7549. recalculate_selected_lines();
  7550. int paren_line = -1, paren_col = -1;
  7551. find_matching_paren(&paren_line, &paren_col, 1);
  7552. if (paren_line != -1) {
  7553. env->line_no = paren_line;
  7554. env->col_no = paren_col;
  7555. set_preferred_column();
  7556. place_cursor_actual();
  7557. redraw_statusbar();
  7558. }
  7559. }
  7560. BIM_ACTION(jump_to_previous_blank, 0,
  7561. "Jump to the preceding blank line before the cursor."
  7562. )(void) {
  7563. env->col_no = 1;
  7564. if (env->line_no == 1) return;
  7565. do {
  7566. env->line_no--;
  7567. if (env->lines[env->line_no-1]->actual == 0) break;
  7568. } while (env->line_no > 1);
  7569. set_preferred_column();
  7570. redraw_statusbar();
  7571. }
  7572. BIM_ACTION(jump_to_next_blank, 0,
  7573. "Jump to the next blank line after the cursor."
  7574. )(void) {
  7575. env->col_no = 1;
  7576. if (env->line_no == env->line_count) return;
  7577. do {
  7578. env->line_no++;
  7579. if (env->lines[env->line_no-1]->actual == 0) break;
  7580. } while (env->line_no < env->line_count);
  7581. set_preferred_column();
  7582. redraw_statusbar();
  7583. }
  7584. BIM_ACTION(first_non_whitespace, 0,
  7585. "Jump to the first non-whitespace character in the current line."
  7586. )(void) {
  7587. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7588. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  7589. env->col_no = i + 1;
  7590. break;
  7591. }
  7592. }
  7593. set_preferred_column();
  7594. redraw_statusbar();
  7595. }
  7596. BIM_ACTION(next_line_non_whitespace, 0,
  7597. "Jump to the first non-whitespace character in the next next line."
  7598. )(void) {
  7599. if (env->line_no < env->line_count) {
  7600. env->line_no++;
  7601. env->col_no = 1;
  7602. } else {
  7603. return;
  7604. }
  7605. first_non_whitespace();
  7606. }
  7607. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  7608. "Delete the preceding character, with special handling for indentation."
  7609. )(void) {
  7610. if (!env->tabs && env->col_no > 1) {
  7611. int i;
  7612. for (i = 0; i < env->col_no-1; ++i) {
  7613. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  7614. }
  7615. if (i == env->col_no-1) {
  7616. /* Backspace until aligned */
  7617. delete_at_cursor();
  7618. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  7619. delete_at_cursor();
  7620. }
  7621. return;
  7622. }
  7623. }
  7624. delete_at_cursor();
  7625. }
  7626. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  7627. "(temporary) Perform smart symbol competion from ctags."
  7628. )(void) {
  7629. /* This should probably be a submode */
  7630. while (omni_complete() == 1);
  7631. }
  7632. BIM_ACTION(smart_tab, ACTION_IS_RW,
  7633. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  7634. )(void) {
  7635. if (env->tabs) {
  7636. insert_char('\t');
  7637. } else {
  7638. for (int i = 0; i < env->tabstop; ++i) {
  7639. insert_char(' ');
  7640. }
  7641. }
  7642. }
  7643. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  7644. "Insert a `/` ending a C-style comment."
  7645. )(int c) {
  7646. /* smart *end* of comment anyway */
  7647. if (env->indent) {
  7648. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  7649. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7650. (env->col_no > 3) &&
  7651. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7652. env->col_no--;
  7653. replace_char('/');
  7654. env->col_no++;
  7655. place_cursor_actual();
  7656. return;
  7657. }
  7658. }
  7659. insert_char(c);
  7660. }
  7661. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  7662. "Insert a closing brace and smartly position it if it is the first character on a line."
  7663. )(int c) {
  7664. if (env->indent) {
  7665. int was_whitespace = 1;
  7666. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7667. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  7668. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  7669. was_whitespace = 0;
  7670. break;
  7671. }
  7672. }
  7673. insert_char(c);
  7674. if (was_whitespace) {
  7675. int line = -1, col = -1;
  7676. env->col_no--;
  7677. find_matching_paren(&line,&col, 1);
  7678. if (line != -1) {
  7679. while (env->lines[env->line_no-1]->actual) {
  7680. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  7681. }
  7682. add_indent(env->line_no-1,line-1,1);
  7683. env->col_no = env->lines[env->line_no-1]->actual + 1;
  7684. insert_char(c);
  7685. }
  7686. }
  7687. set_preferred_column();
  7688. return;
  7689. }
  7690. insert_char(c);
  7691. }
  7692. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  7693. "Enter line selection and move the cursor up one line."
  7694. )(void) {
  7695. enter_line_selection();
  7696. cursor_up();
  7697. }
  7698. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  7699. "Enter line selection and move the cursor down one line."
  7700. )(void) {
  7701. enter_line_selection();
  7702. cursor_down();
  7703. }
  7704. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  7705. "Shift the current line or screen view horiztonally, depending on settings."
  7706. )(int amount) {
  7707. env->coffset += amount;
  7708. if (env->coffset < 0) env->coffset = 0;
  7709. redraw_text();
  7710. }
  7711. struct action_map {
  7712. int key;
  7713. void (*method)();
  7714. int options;
  7715. int arg;
  7716. };
  7717. #define opt_rep 0x1 /* This action will be repeated */
  7718. #define opt_arg 0x2 /* This action will take a specified argument */
  7719. #define opt_char 0x4 /* This action will read a character to pass as an argument */
  7720. #define opt_nav 0x8 /* This action will consume the nav buffer as its argument */
  7721. #define opt_rw 0x10 /* Must not be read-only */
  7722. #define opt_norm 0x20 /* Returns to normal mode */
  7723. #define opt_byte 0x40 /* Same as opt_char but forces a byte */
  7724. struct action_map NORMAL_MAP[] = {
  7725. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  7726. {'V', enter_line_selection, 0, 0},
  7727. {'v', enter_char_selection, 0, 0},
  7728. {KEY_CTRL_V, enter_col_selection, 0, 0},
  7729. {'O', prepend_and_insert, opt_rw, 0},
  7730. {'o', append_and_insert, opt_rw, 0},
  7731. {'a', insert_after_cursor, opt_rw, 0},
  7732. {'s', delete_forward_and_insert, opt_rw, 0},
  7733. {'x', delete_forward, opt_rep | opt_rw, 0},
  7734. {'P', paste, opt_arg | opt_rw, -1},
  7735. {'p', paste, opt_arg | opt_rw, 1},
  7736. {'r', replace_char, opt_char | opt_rw, 0},
  7737. {'A', insert_at_end, opt_rw, 0},
  7738. {'u', undo_history, opt_rw, 0},
  7739. {KEY_CTRL_R, redo_history, opt_rw, 0},
  7740. {KEY_CTRL_L, redraw_all, 0, 0},
  7741. {KEY_CTRL_G, goto_definition, 0, 0},
  7742. {'i', enter_insert, opt_rw, 0},
  7743. {'R', enter_replace, opt_rw, 0},
  7744. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  7745. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  7746. {KEY_ALT_UP, previous_tab, 0, 0},
  7747. {KEY_ALT_DOWN, next_tab, 0, 0},
  7748. {-1, NULL, 0, 0},
  7749. };
  7750. struct action_map INSERT_MAP[] = {
  7751. {KEY_ESCAPE, leave_insert, 0, 0},
  7752. {KEY_DELETE, delete_forward, 0, 0},
  7753. {KEY_CTRL_C, leave_insert, 0, 0},
  7754. {KEY_BACKSPACE, smart_backspace, 0, 0},
  7755. {KEY_ENTER, insert_line_feed, 0, 0},
  7756. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  7757. {KEY_CTRL_V, insert_char, opt_byte, 0},
  7758. {KEY_CTRL_W, delete_word, 0, 0},
  7759. {'\t', smart_tab, 0, 0},
  7760. {'/', smart_comment_end, opt_arg, '/'},
  7761. {'}', smart_brace_end, opt_arg, '}'},
  7762. {-1, NULL, 0, 0},
  7763. };
  7764. struct action_map REPLACE_MAP[] = {
  7765. {KEY_ESCAPE, leave_insert, 0, 0},
  7766. {KEY_DELETE, delete_forward, 0, 0},
  7767. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  7768. {KEY_ENTER, insert_line_feed, 0, 0},
  7769. {-1, NULL, 0, 0},
  7770. };
  7771. struct action_map LINE_SELECTION_MAP[] = {
  7772. {KEY_ESCAPE, leave_selection, 0, 0},
  7773. {KEY_CTRL_C, leave_selection, 0, 0},
  7774. {'V', leave_selection, 0, 0},
  7775. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  7776. {'y', yank_lines, opt_norm, 0},
  7777. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  7778. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  7779. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  7780. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  7781. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  7782. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  7783. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  7784. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  7785. {KEY_SHIFT_UP, cursor_up, 0, 0},
  7786. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  7787. {-1, NULL, 0, 0},
  7788. };
  7789. struct action_map CHAR_SELECTION_MAP[] = {
  7790. {KEY_ESCAPE, leave_selection, 0, 0},
  7791. {KEY_CTRL_C, leave_selection, 0, 0},
  7792. {'v', leave_selection, 0, 0},
  7793. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  7794. {'y', yank_characters, opt_norm, 0},
  7795. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  7796. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  7797. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  7798. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  7799. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  7800. {'r', replace_chars, opt_char | opt_rw, 0},
  7801. {'A', insert_at_end_of_selection, opt_rw, 0},
  7802. {-1, NULL, 0, 0},
  7803. };
  7804. struct action_map COL_SELECTION_MAP[] = {
  7805. {KEY_ESCAPE, leave_selection, 0, 0},
  7806. {KEY_CTRL_C, leave_selection, 0, 0},
  7807. {KEY_CTRL_V, leave_selection, 0, 0},
  7808. {'I', enter_col_insert, opt_rw, 0},
  7809. {'a', enter_col_insert_after, opt_rw, 0},
  7810. {'d', delete_column, opt_norm | opt_rw, 0},
  7811. {-1, NULL, 0, 0},
  7812. };
  7813. struct action_map COL_INSERT_MAP[] = {
  7814. {KEY_ESCAPE, leave_selection, 0, 0},
  7815. {KEY_CTRL_C, leave_selection, 0, 0},
  7816. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  7817. {KEY_DELETE, delete_at_column, opt_arg, 1},
  7818. {KEY_ENTER, NULL, 0, 0},
  7819. {KEY_CTRL_W, NULL, 0, 0},
  7820. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  7821. {-1, NULL, 0, 0},
  7822. };
  7823. struct action_map NAVIGATION_MAP[] = {
  7824. /* Common navigation */
  7825. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  7826. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  7827. {':', enter_command, 0, 0},
  7828. {'/', enter_search, opt_arg, 1},
  7829. {'?', enter_search, opt_arg, 0},
  7830. {'n', search_next, opt_rep, 0},
  7831. {'N', search_prev, opt_rep, 0},
  7832. {'j', cursor_down, opt_rep, 0},
  7833. {'k', cursor_up, opt_rep, 0},
  7834. {'h', cursor_left, opt_rep, 0},
  7835. {'l', cursor_right, opt_rep, 0},
  7836. {'b', word_left, opt_rep, 0},
  7837. {'w', word_right, opt_rep, 0},
  7838. {'B', big_word_left, opt_rep, 0},
  7839. {'W', big_word_right, opt_rep, 0},
  7840. {'<', shift_horizontally, opt_arg, -1},
  7841. {'>', shift_horizontally, opt_arg, 1},
  7842. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  7843. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  7844. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  7845. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  7846. {'G', goto_line, opt_nav, 0},
  7847. {'*', search_under_cursor, 0, 0},
  7848. {' ', go_page_down, opt_rep, 0},
  7849. {'%', jump_to_matching_bracket, 0, 0},
  7850. {'{', jump_to_previous_blank, opt_rep, 0},
  7851. {'}', jump_to_next_blank, opt_rep, 0},
  7852. {'$', cursor_end, 0, 0},
  7853. {'|', cursor_home, 0, 0},
  7854. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  7855. {'^', first_non_whitespace, 0, 0},
  7856. {'0', cursor_home, 0, 0},
  7857. {-1, NULL, 0, 0},
  7858. };
  7859. struct action_map ESCAPE_MAP[] = {
  7860. {KEY_F1, toggle_numbers, 0, 0},
  7861. {KEY_F2, toggle_indent, 0, 0},
  7862. {KEY_MOUSE, handle_mouse, 0, 0},
  7863. {KEY_UP, cursor_up, opt_rep, 0},
  7864. {KEY_DOWN, cursor_down, opt_rep, 0},
  7865. {KEY_RIGHT, cursor_right, opt_rep, 0},
  7866. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  7867. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  7868. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  7869. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  7870. {KEY_LEFT, cursor_left, opt_rep, 0},
  7871. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  7872. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  7873. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  7874. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  7875. {KEY_HOME, cursor_home, 0, 0},
  7876. {KEY_END, cursor_end, 0, 0},
  7877. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  7878. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  7879. {KEY_CTRL_Z, suspend, 0, 0},
  7880. {-1, NULL, 0, 0}
  7881. };
  7882. struct action_map COMMAND_MAP[] = {
  7883. {KEY_ENTER, command_accept, 0, 0},
  7884. {'\t', command_tab_complete_buffer, 0, 0},
  7885. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  7886. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  7887. {-1, NULL, 0, 0}
  7888. };
  7889. struct action_map SEARCH_MAP[] = {
  7890. {KEY_ENTER, search_accept, 0, 0},
  7891. {KEY_UP, NULL, 0, 0},
  7892. {KEY_DOWN, NULL, 0, 0},
  7893. {-1, NULL, 0, 0}
  7894. };
  7895. struct action_map INPUT_BUFFER_MAP[] = {
  7896. /* These are generic and shared with search */
  7897. {KEY_ESCAPE, command_discard, 0, 0},
  7898. {KEY_CTRL_C, command_discard, 0, 0},
  7899. {KEY_BACKSPACE, command_backspace, 0, 0},
  7900. {KEY_CTRL_W, command_word_delete, 0, 0},
  7901. {KEY_MOUSE, eat_mouse, 0, 0},
  7902. {KEY_LEFT, command_cursor_left, 0, 0},
  7903. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  7904. {KEY_RIGHT, command_cursor_right, 0, 0},
  7905. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  7906. {KEY_HOME, command_cursor_home, 0, 0},
  7907. {KEY_END, command_cursor_end, 0, 0},
  7908. {-1, NULL, 0, 0}
  7909. };
  7910. struct action_map DIRECTORY_BROWSE_MAP[] = {
  7911. {KEY_ENTER, open_file_from_line, 0, 0},
  7912. {-1, NULL, 0, 0}
  7913. };
  7914. int handle_action(struct action_map * basemap, int key) {
  7915. for (struct action_map * map = basemap; map->key != -1; map++) {
  7916. if (map->key == key) {
  7917. if (!map->method) return 1;
  7918. if ((map->options & opt_rw) && (env->readonly)) {
  7919. render_error("Buffer is read-only");
  7920. return 2;
  7921. }
  7922. /* Determine how to format this request */
  7923. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  7924. int c = 0;
  7925. if (map->options & opt_char) {
  7926. c = read_one_character(name_from_key(key));
  7927. }
  7928. if (map->options & opt_byte) {
  7929. c = read_one_byte(name_from_key(key));
  7930. }
  7931. for (int i = 0; i < reps; ++i) {
  7932. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  7933. map->method(map->arg, c);
  7934. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  7935. map->method(c);
  7936. } else if (map->options & opt_arg) {
  7937. map->method(map->arg);
  7938. } else if (map->options & opt_nav) {
  7939. if (nav_buffer) {
  7940. map->method(atoi(nav_buf));
  7941. reset_nav_buffer(0);
  7942. } else {
  7943. map->method(-1);
  7944. }
  7945. } else {
  7946. map->method();
  7947. }
  7948. }
  7949. if (map->options & opt_norm) {
  7950. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  7951. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  7952. else {
  7953. env->mode = MODE_NORMAL;
  7954. redraw_all();
  7955. }
  7956. }
  7957. return 1;
  7958. }
  7959. }
  7960. return 0;
  7961. }
  7962. int handle_nav_buffer(int key) {
  7963. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  7964. if (nav_buffer < NAV_BUFFER_MAX) {
  7965. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  7966. nav_buf[nav_buffer] = key;
  7967. nav_buf[nav_buffer+1] = 0;
  7968. nav_buffer++;
  7969. /* Print the number buffer */
  7970. redraw_commandline();
  7971. }
  7972. return 0;
  7973. }
  7974. return 1;
  7975. }
  7976. /**
  7977. * NORMAL mode
  7978. *
  7979. * Default editor mode - just cursor navigation and keybinds
  7980. * to enter the other modes.
  7981. */
  7982. void normal_mode(void) {
  7983. int last_mode = MODE_NORMAL;
  7984. int refresh = 0;
  7985. while (1) {
  7986. if (global_config.overlay_mode) {
  7987. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  7988. if (refresh) {
  7989. render_command_input_buffer();
  7990. refresh = 0;
  7991. }
  7992. int key = bim_getkey(200);
  7993. if (key != KEY_TIMEOUT) {
  7994. refresh = 1;
  7995. if (!handle_action(COMMAND_MAP, key))
  7996. if (!handle_action(INPUT_BUFFER_MAP, key))
  7997. if (key < KEY_ESCAPE) command_insert_char(key);
  7998. }
  7999. continue;
  8000. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8001. if (refresh) {
  8002. render_command_input_buffer();
  8003. refresh = 0;
  8004. }
  8005. int key = bim_getkey(200);
  8006. if (key != KEY_TIMEOUT) {
  8007. refresh = 1;
  8008. if (!handle_action(SEARCH_MAP, key)) {
  8009. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  8010. if (key < KEY_ESCAPE) command_insert_char(key);
  8011. }
  8012. }
  8013. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8014. /* Find the next search match */
  8015. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  8016. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  8017. buffer[i] = global_config.command_buffer->text[i].codepoint;
  8018. }
  8019. buffer[global_config.command_buffer->actual] = 0;
  8020. int line = -1, col = -1;
  8021. if (global_config.search_direction == 1) {
  8022. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  8023. if (line == -1) {
  8024. find_match(1, global_config.prev_col, &line, &col, buffer, NULL);
  8025. }
  8026. } else {
  8027. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  8028. if (line == -1) {
  8029. find_match_backwards(env->line_count, global_config.prev_col, &line, &col, buffer);
  8030. }
  8031. }
  8032. if (line != -1) {
  8033. env->col_no = col;
  8034. env->line_no = line;
  8035. set_preferred_column();
  8036. } else {
  8037. env->coffset = global_config.prev_coffset;
  8038. env->offset = global_config.prev_offset;
  8039. env->col_no = global_config.prev_col;
  8040. set_preferred_column();
  8041. env->line_no = global_config.prev_line;
  8042. }
  8043. draw_search_match(buffer, 0);
  8044. free(buffer);
  8045. }
  8046. }
  8047. continue;
  8048. }
  8049. }
  8050. if (env->mode != last_mode) {
  8051. redraw_statusbar();
  8052. redraw_commandline();
  8053. last_mode = env->mode;
  8054. }
  8055. if (env->mode == MODE_NORMAL) {
  8056. place_cursor_actual();
  8057. int key = bim_getkey(200);
  8058. if (handle_nav_buffer(key)) {
  8059. if (!handle_action(NORMAL_MAP, key))
  8060. if (!handle_action(NAVIGATION_MAP, key))
  8061. handle_action(ESCAPE_MAP, key);
  8062. }
  8063. reset_nav_buffer(key);
  8064. } else if (env->mode == MODE_INSERT) {
  8065. place_cursor_actual();
  8066. int key = bim_getkey(refresh ? 10 : 200);
  8067. if (key == KEY_TIMEOUT) {
  8068. if (refresh > 1) {
  8069. redraw_text();
  8070. } else if (refresh) {
  8071. redraw_line(env->line_no-1);
  8072. }
  8073. refresh = 0;
  8074. } else if (handle_action(INSERT_MAP, key)) {
  8075. refresh = 2;
  8076. } else if (handle_action(ESCAPE_MAP, key)) {
  8077. /* Do nothing */
  8078. } else if (key < KEY_ESCAPE) {
  8079. insert_char(key);
  8080. refresh |= 1;
  8081. }
  8082. } else if (env->mode == MODE_REPLACE) {
  8083. place_cursor_actual();
  8084. int key = bim_getkey(200);
  8085. if (key != KEY_TIMEOUT) {
  8086. if (handle_action(REPLACE_MAP, key)) {
  8087. redraw_text();
  8088. } else if (!handle_action(ESCAPE_MAP, key)) {
  8089. /* Perform replacement */
  8090. if (key < KEY_ESCAPE) {
  8091. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  8092. replace_char(key);
  8093. env->col_no += 1;
  8094. } else {
  8095. insert_char(key);
  8096. redraw_line(env->line_no-1);
  8097. }
  8098. set_preferred_column();
  8099. }
  8100. }
  8101. }
  8102. } else if (env->mode == MODE_LINE_SELECTION) {
  8103. place_cursor_actual();
  8104. int key = bim_getkey(200);
  8105. if (key == KEY_TIMEOUT) continue;
  8106. if (handle_nav_buffer(key)) {
  8107. if (!handle_action(LINE_SELECTION_MAP, key))
  8108. if (!handle_action(NAVIGATION_MAP, key))
  8109. handle_action(ESCAPE_MAP, key);
  8110. }
  8111. reset_nav_buffer(key);
  8112. if (env->mode == MODE_LINE_SELECTION) {
  8113. /* Mark current line */
  8114. _redraw_line(env->line_no,0);
  8115. _redraw_line(env->start_line,1);
  8116. /* Properly mark everything in the span we just moved through */
  8117. if (env->prev_line < env->line_no) {
  8118. for (int i = env->prev_line; i < env->line_no; ++i) {
  8119. _redraw_line(i,0);
  8120. }
  8121. env->prev_line = env->line_no;
  8122. } else if (env->prev_line > env->line_no) {
  8123. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8124. _redraw_line(i,0);
  8125. }
  8126. env->prev_line = env->line_no;
  8127. }
  8128. redraw_commandline();
  8129. }
  8130. } else if (env->mode == MODE_CHAR_SELECTION) {
  8131. place_cursor_actual();
  8132. int key = bim_getkey(200);
  8133. if (key == KEY_TIMEOUT) continue;
  8134. if (handle_nav_buffer(key)) {
  8135. if (!handle_action(CHAR_SELECTION_MAP, key))
  8136. if (!handle_action(NAVIGATION_MAP, key))
  8137. handle_action(ESCAPE_MAP, key);
  8138. }
  8139. reset_nav_buffer(key);
  8140. if (env->mode == MODE_CHAR_SELECTION) {
  8141. /* Mark current line */
  8142. _redraw_line_char(env->line_no,1);
  8143. /* Properly mark everything in the span we just moved through */
  8144. if (env->prev_line < env->line_no) {
  8145. for (int i = env->prev_line; i < env->line_no; ++i) {
  8146. _redraw_line_char(i,1);
  8147. }
  8148. env->prev_line = env->line_no;
  8149. } else if (env->prev_line > env->line_no) {
  8150. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8151. _redraw_line_char(i,1);
  8152. }
  8153. env->prev_line = env->line_no;
  8154. }
  8155. }
  8156. } else if (env->mode == MODE_COL_SELECTION) {
  8157. place_cursor_actual();
  8158. int key = bim_getkey(200);
  8159. if (key == KEY_TIMEOUT) continue;
  8160. if (handle_nav_buffer(key)) {
  8161. if (!handle_action(COL_SELECTION_MAP, key))
  8162. if (!handle_action(NAVIGATION_MAP, key))
  8163. handle_action(ESCAPE_MAP, key);
  8164. }
  8165. reset_nav_buffer(key);
  8166. if (env->mode == MODE_COL_SELECTION) {
  8167. _redraw_line_col(env->line_no, 0);
  8168. /* Properly mark everything in the span we just moved through */
  8169. if (env->prev_line < env->line_no) {
  8170. for (int i = env->prev_line; i < env->line_no; ++i) {
  8171. _redraw_line_col(i,0);
  8172. }
  8173. env->prev_line = env->line_no;
  8174. } else if (env->prev_line > env->line_no) {
  8175. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8176. _redraw_line_col(i,0);
  8177. }
  8178. env->prev_line = env->line_no;
  8179. }
  8180. redraw_commandline();
  8181. }
  8182. } else if (env->mode == MODE_COL_INSERT) {
  8183. int key = bim_getkey(refresh ? 10 : 200);
  8184. if (key == KEY_TIMEOUT) {
  8185. if (refresh) {
  8186. redraw_commandline();
  8187. redraw_text();
  8188. }
  8189. refresh = 0;
  8190. } else if (handle_action(COL_INSERT_MAP, key)) {
  8191. /* pass */
  8192. } else if (key < KEY_ESCAPE) {
  8193. insert_char_at_column(key);
  8194. refresh = 1;
  8195. }
  8196. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  8197. place_cursor_actual();
  8198. int key = bim_getkey(200);
  8199. if (handle_nav_buffer(key)) {
  8200. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  8201. if (!handle_action(NAVIGATION_MAP, key))
  8202. handle_action(ESCAPE_MAP, key);
  8203. }
  8204. reset_nav_buffer(key);
  8205. }
  8206. }
  8207. }
  8208. /**
  8209. * Show help text for -?
  8210. */
  8211. static void show_usage(char * argv[]) {
  8212. #define _s "\033[3m"
  8213. #define _e "\033[0m\n"
  8214. printf(
  8215. "bim - Text editor\n"
  8216. "\n"
  8217. "usage: %s [options] [file]\n"
  8218. " %s [options] -- -\n"
  8219. "\n"
  8220. " -R " _s "open initial buffer read-only" _e
  8221. " -O " _s "set various options:" _e
  8222. " noscroll " _s "disable terminal scrolling" _e
  8223. " noaltscreen " _s "disable alternate screen buffer" _e
  8224. " nomouse " _s "disable mouse support" _e
  8225. " nounicode " _s "disable unicode display" _e
  8226. " nobright " _s "disable bright next" _e
  8227. " nohideshow " _s "disable togglging cursor visibility" _e
  8228. " nosyntax " _s "disable syntax highlighting on load" _e
  8229. " notitle " _s "disable title-setting escapes" _e
  8230. " history " _s "enable experimental undo/redo" _e
  8231. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  8232. " " _s "-C includes line numbers, -c does not" _e
  8233. " -u " _s "override bimrc file" _e
  8234. " -? " _s "show this help text" _e
  8235. "\n"
  8236. "Long options:\n"
  8237. " --help " _s "show this help text" _e
  8238. " --version " _s "show version information and available plugins" _e
  8239. " --dump-mappings " _s "dump markdown description of key mappings" _e
  8240. "\n", argv[0], argv[0]);
  8241. #undef _e
  8242. #undef _s
  8243. }
  8244. /**
  8245. * Load bimrc configuration file.
  8246. *
  8247. * At the moment, this a simple key=value list.
  8248. */
  8249. void load_bimrc(void) {
  8250. if (!global_config.bimrc_path) return;
  8251. /* Default is ~/.bimrc */
  8252. char * tmp = strdup(global_config.bimrc_path);
  8253. if (!*tmp) {
  8254. free(tmp);
  8255. return;
  8256. }
  8257. /* Parse ~ at the front of the path. */
  8258. if (*tmp == '~') {
  8259. char path[1024] = {0};
  8260. char * home = getenv("HOME");
  8261. if (!home) {
  8262. /* $HOME is unset? */
  8263. free(tmp);
  8264. return;
  8265. }
  8266. /* New path is $HOME/.bimrc */
  8267. snprintf(path, 1024, "%s%s", home, tmp+1);
  8268. free(tmp);
  8269. tmp = strdup(path);
  8270. }
  8271. /* Try to open the file */
  8272. FILE * bimrc = fopen(tmp, "r");
  8273. free(tmp);
  8274. if (!bimrc) {
  8275. /* No bimrc, or bad permissions */
  8276. return;
  8277. }
  8278. /* Parse through lines */
  8279. char line[1024];
  8280. while (!feof(bimrc)) {
  8281. char * l = fgets(line, 1023, bimrc);
  8282. /* Ignore bad lines */
  8283. if (!l) break;
  8284. if (!*l) continue;
  8285. if (*l == '\n') continue;
  8286. /* Ignore comment lines */
  8287. if (*l == '#') continue;
  8288. /* Remove linefeed at the end */
  8289. char *nl = strstr(l,"\n");
  8290. if (nl) *nl = '\0';
  8291. /* Extract value from keypair, if available
  8292. * (I foresee options without values in the future) */
  8293. char *value= strstr(l,"=");
  8294. if (value) {
  8295. *value = '\0';
  8296. value++;
  8297. }
  8298. /* theme=... */
  8299. if (!strcmp(l,"theme") && value) {
  8300. /* Examine available themes for a match. */
  8301. for (struct theme_def * d = themes; themes && d->name; ++d) {
  8302. if (!strcmp(value, d->name)) {
  8303. d->load();
  8304. break;
  8305. }
  8306. }
  8307. }
  8308. /* enable history (experimental) */
  8309. if (!strcmp(l,"history")) {
  8310. global_config.history_enabled = (value ? atoi(value) : 1);
  8311. }
  8312. /* padding= */
  8313. if (!strcmp(l,"padding") && value) {
  8314. global_config.cursor_padding = atoi(value);
  8315. }
  8316. if (!strcmp(l,"hlparen") && value) {
  8317. global_config.highlight_parens = atoi(value);
  8318. }
  8319. /* Disable highlighting of current line */
  8320. if (!strcmp(l,"hlcurrent") && value) {
  8321. global_config.highlight_current_line = atoi(value);
  8322. }
  8323. /* Relative line numbers */
  8324. if (!strcmp(l,"relativenumber") && value) {
  8325. global_config.relative_lines = atoi(value);
  8326. }
  8327. if (!strcmp(l,"splitpercent") && value) {
  8328. global_config.split_percent = atoi(value);
  8329. }
  8330. if (!strcmp(l,"shiftscrolling")) {
  8331. global_config.shift_scrolling = (value ? atoi(value) : 1);
  8332. }
  8333. if (!strcmp(l,"scrollamount") && value) {
  8334. global_config.scroll_amount = atoi(value);
  8335. }
  8336. if (!strcmp(l,"git") && value) {
  8337. global_config.check_git = !!atoi(value);
  8338. }
  8339. if (!strcmp(l,"colorgutter") && value) {
  8340. global_config.color_gutter = !!atoi(value);
  8341. }
  8342. if (!strcmp(l,"numbers") && value) {
  8343. global_config.numbers = !!atoi(value);
  8344. }
  8345. }
  8346. fclose(bimrc);
  8347. }
  8348. /**
  8349. * Set some default values when certain terminals are detected.
  8350. */
  8351. void detect_weird_terminals(void) {
  8352. char * term = getenv("TERM");
  8353. if (term && !strcmp(term,"linux")) {
  8354. /* Linux VTs can't scroll. */
  8355. global_config.can_scroll = 0;
  8356. }
  8357. if (term && !strcmp(term,"cons25")) {
  8358. /* Dragonfly BSD console */
  8359. global_config.can_hideshow = 0;
  8360. global_config.can_altscreen = 0;
  8361. global_config.can_mouse = 0;
  8362. global_config.can_unicode = 0;
  8363. global_config.can_bright = 0;
  8364. }
  8365. if (term && !strcmp(term,"sortix")) {
  8366. /* sortix will spew title escapes to the screen, no good */
  8367. global_config.can_title = 0;
  8368. }
  8369. if (term && strstr(term,"tmux") == term) {
  8370. global_config.can_scroll = 0;
  8371. global_config.can_bce = 0;
  8372. }
  8373. if (term && strstr(term,"screen") == term) {
  8374. /* unfortunately */
  8375. global_config.can_24bit = 0;
  8376. global_config.can_italic = 0;
  8377. }
  8378. if (term && strstr(term,"toaru-vga") == term) {
  8379. global_config.can_24bit = 0; /* Also not strictly true */
  8380. global_config.can_256color = 0; /* Not strictly true */
  8381. }
  8382. }
  8383. /**
  8384. * Run global initialization tasks
  8385. */
  8386. void initialize(void) {
  8387. setlocale(LC_ALL, "");
  8388. detect_weird_terminals();
  8389. load_bimrc();
  8390. buffers_avail = 4;
  8391. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  8392. }
  8393. /**
  8394. * Initialize terminal for editor display.
  8395. */
  8396. void init_terminal(void) {
  8397. if (!isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  8398. global_config.tty_in = STDERR_FILENO;
  8399. }
  8400. set_alternate_screen();
  8401. update_screen_size();
  8402. get_initial_termios();
  8403. set_unbuffered();
  8404. mouse_enable();
  8405. signal(SIGWINCH, SIGWINCH_handler);
  8406. signal(SIGCONT, SIGCONT_handler);
  8407. signal(SIGTSTP, SIGTSTP_handler);
  8408. }
  8409. struct action_def * find_action(void (*action)()) {
  8410. if (!action) return NULL;
  8411. for (int i = 0; i < flex_mappable_actions_count; ++i) {
  8412. if (action == mappable_actions[i].action) return &mappable_actions[i];
  8413. }
  8414. return NULL;
  8415. }
  8416. void dump_mapping(const char * description, struct action_map * map) {
  8417. printf("## %s\n", description);
  8418. printf("\n");
  8419. printf("| **Key** | **Action** | **Description** |\n");
  8420. printf("|---------|------------|-----------------|\n");
  8421. struct action_map * m = map;
  8422. while (m->key != -1) {
  8423. /* Find the name of this action */
  8424. struct action_def * action = find_action(m->method);
  8425. printf("| `%s` | `%s` | %s |\n", name_from_key(m->key),
  8426. action ? action->name : "(unbound)",
  8427. action ? action->description : "(unbound)");
  8428. m++;
  8429. }
  8430. printf("\n");
  8431. }
  8432. BIM_COMMAND(whatis,"whatis","Describe actions bound to a key in different modes.") {
  8433. int key = 0;
  8434. if (argc < 2) {
  8435. render_commandline_message("(press a key)");
  8436. while ((key = bim_getkey(200)) == KEY_TIMEOUT);
  8437. } else if (strlen(argv[1]) > 1 && argv[1][0] == '^') {
  8438. /* See if it's a valid ctrl key */
  8439. if (argv[1][2] != '\0') {
  8440. goto _invalid_key_name;
  8441. }
  8442. if ((unsigned char)argv[1][1] < '@' || (unsigned char)argv[1][1] > '@' + '_') {
  8443. goto _invalid_key_name;
  8444. }
  8445. key = argv[1][1] - '@';
  8446. } else if (argv[1][1] != '\0') {
  8447. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  8448. if (!strcmp(KeyNames[i].name,argv[1])) {
  8449. key = KeyNames[i].keycode;
  8450. }
  8451. }
  8452. if (!key) goto _invalid_key_name;
  8453. } else {
  8454. key = (unsigned char)argv[1][0];
  8455. }
  8456. struct MappingNames {
  8457. char * name;
  8458. struct action_map * map;
  8459. } maps[] = {
  8460. {"Normal", NORMAL_MAP},
  8461. {"Insert", INSERT_MAP},
  8462. {"Replace", REPLACE_MAP},
  8463. {"Line Selection", LINE_SELECTION_MAP},
  8464. {"Char Selection", CHAR_SELECTION_MAP},
  8465. {"Col Selection", COL_SELECTION_MAP},
  8466. {"Col Insert", COL_INSERT_MAP},
  8467. {"Navigation (Select)", NAVIGATION_MAP},
  8468. {"Escape (Select, Insert)", ESCAPE_MAP},
  8469. {"Command", COMMAND_MAP},
  8470. {"Search", SEARCH_MAP},
  8471. {"Input (Command, Search)", INPUT_BUFFER_MAP},
  8472. {NULL, NULL},
  8473. };
  8474. render_commandline_message("");
  8475. int found_something = 0;
  8476. for (struct MappingNames * map = maps; map->name; ++map) {
  8477. /* See if this key is mapped */
  8478. struct action_map * m = map->map;
  8479. while (m->key != -1) {
  8480. if (m->key == key) {
  8481. struct action_def * action = find_action(m->method);
  8482. render_commandline_message("%s: %s\n", map->name, action ? action->description : "(unmapped)");
  8483. found_something = 1;
  8484. break;
  8485. }
  8486. m++;
  8487. }
  8488. }
  8489. if (!found_something) {
  8490. render_commandline_message("Nothing bound for this key");
  8491. }
  8492. pause_for_key();
  8493. return 0;
  8494. _invalid_key_name:
  8495. render_error("Invalid key name");
  8496. return 1;
  8497. }
  8498. BIM_COMMAND(setcolor, "setcolor", "Set colorscheme colors") {
  8499. if (argc < 2) {
  8500. /* Print colors */
  8501. struct ColorName * c = color_names;
  8502. while (c->name) {
  8503. render_commandline_message("%20s = ", c->name);
  8504. set_colors(*c->value, *c->value);
  8505. printf(" ");
  8506. set_colors(COLOR_FG, COLOR_BG);
  8507. printf(" %s\n", *c->value);
  8508. c++;
  8509. }
  8510. pause_for_key();
  8511. } else {
  8512. char * colorname = argv[1];
  8513. char * space = strstr(colorname, " ");
  8514. if (!space) {
  8515. render_error(":setcolor <colorname> <colorvalue>");
  8516. return 1;
  8517. }
  8518. char * colorvalue = space + 1;
  8519. *space = '\0';
  8520. struct ColorName * c = color_names;
  8521. while (c->name) {
  8522. if (!strcmp(c->name, colorname)) {
  8523. *(c->value) = strdup(colorvalue);
  8524. return 0;
  8525. }
  8526. c++;
  8527. }
  8528. render_error("Unknown color: %s", colorname);
  8529. return 1;
  8530. }
  8531. return 0;
  8532. }
  8533. BIM_COMMAND(runscript,"runscript","Run a script file") {
  8534. if (argc < 2) {
  8535. render_error("Expected a script to run");
  8536. return 1;
  8537. }
  8538. /* Run commands */
  8539. FILE * f = fopen(argv[1],"r");
  8540. if (!f) {
  8541. render_error("Failed to open script");
  8542. return 1;
  8543. }
  8544. int retval = 0;
  8545. char linebuf[4096];
  8546. while (!feof(f)) {
  8547. memset(linebuf, 0, 4096);
  8548. fgets(linebuf, 4095, f);
  8549. /* Remove linefeed */
  8550. char * s = strstr(linebuf, "\n");
  8551. if (s) *s = '\0';
  8552. int result = process_command(linebuf);
  8553. if (result != 0) {
  8554. retval = result;
  8555. break;
  8556. }
  8557. }
  8558. fclose(f);
  8559. return retval;
  8560. }
  8561. BIM_COMMAND(checkprop,"checkprop","Check a property value; returns the inverse of the property") {
  8562. if (argc < 2) {
  8563. return 1;
  8564. }
  8565. if (!strcmp(argv[1],"can_scroll")) return !global_config.can_scroll;
  8566. else if (!strcmp(argv[1],"can_hideshow")) return !global_config.can_hideshow;
  8567. else if (!strcmp(argv[1],"can_altscreen")) return !global_config.can_altscreen;
  8568. else if (!strcmp(argv[1],"can_mouse")) return !global_config.can_mouse;
  8569. else if (!strcmp(argv[1],"can_unicode")) return !global_config.can_unicode;
  8570. else if (!strcmp(argv[1],"can_bright")) return !global_config.can_bright;
  8571. else if (!strcmp(argv[1],"can_title")) return !global_config.can_title;
  8572. else if (!strcmp(argv[1],"can_bce")) return !global_config.can_bce;
  8573. else if (!strcmp(argv[1],"can_24bit")) return !global_config.can_24bit;
  8574. else if (!strcmp(argv[1],"can_256color")) return !global_config.can_256color;
  8575. else if (!strcmp(argv[1],"can_italic")) return !global_config.can_italic;
  8576. render_error("Unknown property '%s'", argv[1]);
  8577. return 1;
  8578. }
  8579. BIM_COMMAND(action,"action","Execute a bim action") {
  8580. if (argc < 2) {
  8581. render_error("Expected :action <action-name> [arg [arg [arg...]]]");
  8582. return 1;
  8583. }
  8584. /* Split argument on spaces */
  8585. char * action = argv[1];
  8586. char * arg1 = NULL, * arg2 = NULL, * arg3 = NULL;
  8587. arg1 = strstr(argv[1]," ");
  8588. if (arg1) {
  8589. *arg1 = '\0';
  8590. arg1++;
  8591. arg2 = strstr(arg1," ");
  8592. if (arg2) {
  8593. *arg2 = '\0';
  8594. arg2++;
  8595. arg3 = strstr(arg1," ");
  8596. if (arg3) {
  8597. *arg3 = '\0';
  8598. arg3++;
  8599. }
  8600. }
  8601. }
  8602. /* Find the action */
  8603. for (int i = 0; i < flex_mappable_actions_count; ++i) {
  8604. if (!strcmp(mappable_actions[i].name, action)) {
  8605. /* Count arguments */
  8606. int args = 0;
  8607. if (mappable_actions[i].options & ARG_IS_CUSTOM) args++;
  8608. if (mappable_actions[i].options & ARG_IS_INPUT) args++;
  8609. if (mappable_actions[i].options & ARG_IS_PROMPT) args++;
  8610. if (args == 0) {
  8611. mappable_actions[i].action();
  8612. } else if (args == 1) {
  8613. if (!arg1) { render_error("Expected one argument"); return 1; }
  8614. mappable_actions[i].action(atoi(arg1));
  8615. } else if (args == 2) {
  8616. if (!arg2) { render_error("Expected two arguments"); return 1; }
  8617. mappable_actions[i].action(atoi(arg1), atoi(arg2));
  8618. } else if (args == 3) {
  8619. if (!arg3) { render_error("Expected three arguments"); return 1; }
  8620. mappable_actions[i].action(atoi(arg1), atoi(arg2), atoi(arg3));
  8621. }
  8622. return 0;
  8623. }
  8624. }
  8625. render_error("Unknown action: %s", action);
  8626. return 1;
  8627. }
  8628. int main(int argc, char * argv[]) {
  8629. int opt;
  8630. while ((opt = getopt(argc, argv, "?c:C:u:RS:O:-:")) != -1) {
  8631. switch (opt) {
  8632. case 'R':
  8633. global_config.initial_file_is_read_only = 1;
  8634. break;
  8635. case 'c':
  8636. case 'C':
  8637. /* Print file to stdout using our syntax highlighting and color theme */
  8638. initialize();
  8639. global_config.go_to_line = 0;
  8640. open_file(optarg);
  8641. for (int i = 0; i < env->line_count; ++i) {
  8642. if (opt == 'C') {
  8643. draw_line_number(i);
  8644. }
  8645. render_line(env->lines[i], 6 * (env->lines[i]->actual + 1), 0, i + 1);
  8646. reset();
  8647. fprintf(stdout, "\n");
  8648. }
  8649. return 0;
  8650. case 'u':
  8651. global_config.bimrc_path = optarg;
  8652. break;
  8653. case 'S':
  8654. global_config.syntax_fallback = optarg;
  8655. break;
  8656. case 'O':
  8657. /* Set various display options */
  8658. if (!strcmp(optarg,"noaltscreen")) global_config.can_altscreen = 0;
  8659. else if (!strcmp(optarg,"noscroll")) global_config.can_scroll = 0;
  8660. else if (!strcmp(optarg,"nomouse")) global_config.can_mouse = 0;
  8661. else if (!strcmp(optarg,"nounicode")) global_config.can_unicode = 0;
  8662. else if (!strcmp(optarg,"nobright")) global_config.can_bright = 0;
  8663. else if (!strcmp(optarg,"nohideshow")) global_config.can_hideshow = 0;
  8664. else if (!strcmp(optarg,"nosyntax")) global_config.highlight_on_open = 0;
  8665. else if (!strcmp(optarg,"nohistory")) global_config.history_enabled = 0;
  8666. else if (!strcmp(optarg,"notitle")) global_config.can_title = 0;
  8667. else if (!strcmp(optarg,"nobce")) global_config.can_bce = 0;
  8668. else {
  8669. fprintf(stderr, "%s: unrecognized -O option: %s\n", argv[0], optarg);
  8670. return 1;
  8671. }
  8672. break;
  8673. case '-':
  8674. if (!strcmp(optarg,"version")) {
  8675. fprintf(stderr, "bim %s%s - %s\n", BIM_VERSION, BIM_BUILD_DATE, BIM_COPYRIGHT);
  8676. fprintf(stderr, " Available syntax highlighters:");
  8677. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  8678. fprintf(stderr, " %s", s->name);
  8679. }
  8680. fprintf(stderr, "\n");
  8681. fprintf(stderr, " Available color themes:");
  8682. for (struct theme_def * d = themes; themes && d->name; ++d) {
  8683. fprintf(stderr, " %s", d->name);
  8684. }
  8685. fprintf(stderr, "\n");
  8686. return 0;
  8687. } else if (!strcmp(optarg,"help")) {
  8688. show_usage(argv);
  8689. return 0;
  8690. } else if (!strcmp(optarg,"dump-mappings")) {
  8691. dump_mapping("Normal", NORMAL_MAP);
  8692. dump_mapping("Insert", INSERT_MAP);
  8693. dump_mapping("Replace", REPLACE_MAP);
  8694. dump_mapping("Line Selection", LINE_SELECTION_MAP);
  8695. dump_mapping("Char Selection", CHAR_SELECTION_MAP);
  8696. dump_mapping("Col Selection", COL_SELECTION_MAP);
  8697. dump_mapping("Col Insert", COL_INSERT_MAP);
  8698. dump_mapping("Navigation (Select)", NAVIGATION_MAP);
  8699. dump_mapping("Escape (Select, Insert)", ESCAPE_MAP);
  8700. dump_mapping("Command", COMMAND_MAP);
  8701. dump_mapping("Search", SEARCH_MAP);
  8702. dump_mapping("Input (Command, Search)", INPUT_BUFFER_MAP);
  8703. return 0;
  8704. } else if (strlen(optarg)) {
  8705. fprintf(stderr, "bim: unrecognized option `%s'\n", optarg);
  8706. return 1;
  8707. } /* Else, this is -- to indicate end of arguments */
  8708. break;
  8709. case '?':
  8710. show_usage(argv);
  8711. return 0;
  8712. }
  8713. }
  8714. /* Set up terminal */
  8715. initialize();
  8716. init_terminal();
  8717. /* Open file */
  8718. if (argc > optind) {
  8719. while (argc > optind) {
  8720. open_file(argv[optind]);
  8721. update_title();
  8722. if (global_config.initial_file_is_read_only) {
  8723. env->readonly = 1;
  8724. }
  8725. optind++;
  8726. }
  8727. env = buffers[0];
  8728. } else {
  8729. env = buffer_new();
  8730. setup_buffer(env);
  8731. }
  8732. update_title();
  8733. /* Draw the screen once */
  8734. redraw_all();
  8735. /* Start accepting key commands */
  8736. normal_mode();
  8737. return 0;
  8738. }
  8739. /* 16-color theme, default */
  8740. BIM_THEME(ansi) {
  8741. COLOR_FG = global_config.can_bright ? "@17" : "@7";
  8742. COLOR_BG = global_config.can_bright ? "@9" : "@0";
  8743. COLOR_ALT_FG = global_config.can_bright ? "@10" : "@5";
  8744. COLOR_ALT_BG = "@9";
  8745. COLOR_NUMBER_FG = "@3";
  8746. COLOR_NUMBER_BG = "@9";
  8747. COLOR_STATUS_FG = global_config.can_bright ? "@17" : "@7";
  8748. COLOR_STATUS_BG = "@4";
  8749. COLOR_TABBAR_BG = "@4";
  8750. COLOR_TAB_BG = "@4";
  8751. COLOR_KEYWORD = global_config.can_bright ? "@14" : "@4";
  8752. COLOR_STRING = "@2";
  8753. COLOR_COMMENT = global_config.can_bright ? "@10" : "@5";
  8754. COLOR_TYPE = "@3";
  8755. COLOR_PRAGMA = "@1";
  8756. COLOR_NUMERAL = "@1";
  8757. COLOR_ERROR_FG = global_config.can_bright ? "@17" : "@7";
  8758. COLOR_ERROR_BG = "@1";
  8759. COLOR_SEARCH_FG = "@0";
  8760. COLOR_SEARCH_BG = global_config.can_bright ? "@13" : "@3";
  8761. COLOR_SELECTBG = global_config.can_bright ? "@17" : "@7";
  8762. COLOR_SELECTFG = "@0";
  8763. COLOR_RED = "@1";
  8764. COLOR_GREEN = "@2";
  8765. COLOR_BOLD = COLOR_FG; /* @ doesn't support extra args; FIXME */
  8766. COLOR_LINK = global_config.can_bright ? "@14" : "@4";
  8767. COLOR_ESCAPE = global_config.can_bright ? "@12" : "@2";
  8768. current_theme = "ansi";
  8769. }
  8770. /* "City Lights" based on citylights.xyz */
  8771. BIM_THEME(citylights) {
  8772. if (!global_config.can_24bit) return;
  8773. COLOR_FG = "2;151;178;198";
  8774. COLOR_BG = "2;29;37;44";
  8775. COLOR_ALT_FG = "2;45;55;65";
  8776. COLOR_ALT_BG = "2;33;42;50";
  8777. COLOR_NUMBER_FG = "2;71;89;103";
  8778. COLOR_NUMBER_BG = "2;37;47;56";
  8779. COLOR_STATUS_FG = "2;116;144;166";
  8780. COLOR_STATUS_BG = "2;53;67;78";
  8781. COLOR_TABBAR_BG = "2;37;47;56";
  8782. COLOR_TAB_BG = "2;29;37;44";
  8783. COLOR_KEYWORD = "2;94;196;255";
  8784. COLOR_STRING = "2;83;154;252";
  8785. COLOR_COMMENT = "2;107;133;153;3";
  8786. COLOR_TYPE = "2;139;212;156";
  8787. COLOR_PRAGMA = "2;0;139;148";
  8788. COLOR_NUMERAL = "2;207;118;132";
  8789. COLOR_ERROR_FG = "5;15";
  8790. COLOR_ERROR_BG = "5;196";
  8791. COLOR_SEARCH_FG = "5;234";
  8792. COLOR_SEARCH_BG = "5;226";
  8793. COLOR_SELECTFG = "2;29;37;44";
  8794. COLOR_SELECTBG = "2;151;178;198";
  8795. COLOR_RED = "2;222;53;53";
  8796. COLOR_GREEN = "2;55;167;0";
  8797. COLOR_BOLD = "2;151;178;198;1";
  8798. COLOR_LINK = "2;94;196;255;4";
  8799. COLOR_ESCAPE = "2;133;182;249";
  8800. current_theme = "citylights";
  8801. }
  8802. /* Solarized Dark, popular theme */
  8803. BIM_THEME(solarized_dark) {
  8804. if (!global_config.can_24bit) return;
  8805. COLOR_FG = "2;147;161;161";
  8806. COLOR_BG = "2;0;43;54";
  8807. COLOR_ALT_FG = "2;147;161;161";
  8808. COLOR_ALT_BG = "2;7;54;66";
  8809. COLOR_NUMBER_FG = "2;131;148;149";
  8810. COLOR_NUMBER_BG = "2;7;54;66";
  8811. COLOR_STATUS_FG = "2;131;148;150";
  8812. COLOR_STATUS_BG = "2;7;54;66";
  8813. COLOR_TABBAR_BG = "2;7;54;66";
  8814. COLOR_TAB_BG = "2;131;148;150";
  8815. COLOR_KEYWORD = "2;133;153;0";
  8816. COLOR_STRING = "2;42;161;152";
  8817. COLOR_COMMENT = "2;101;123;131";
  8818. COLOR_TYPE = "2;181;137;0";
  8819. COLOR_PRAGMA = "2;203;75;22";
  8820. COLOR_NUMERAL = "2;220;50;47";
  8821. COLOR_ERROR_FG = "5;15";
  8822. COLOR_ERROR_BG = "5;196";
  8823. COLOR_SEARCH_FG = "5;234";
  8824. COLOR_SEARCH_BG = "5;226";
  8825. COLOR_SELECTFG = "2;0;43;54";
  8826. COLOR_SELECTBG = "2;147;161;161";
  8827. COLOR_RED = "2;222;53;53";
  8828. COLOR_GREEN = "2;55;167;0";
  8829. COLOR_BOLD = "2;147;161;161;1";
  8830. COLOR_LINK = "2;42;161;152;4";
  8831. COLOR_ESCAPE = "2;133;153;0";
  8832. current_theme = "solarized-dark";
  8833. }
  8834. BIM_THEME(sunsmoke256) {
  8835. if (!global_config.can_256color) return;
  8836. COLOR_FG = "5;188";
  8837. COLOR_BG = "5;234";
  8838. COLOR_ALT_FG = "5;244";
  8839. COLOR_ALT_BG = "5;236";
  8840. COLOR_NUMBER_FG = "5;101";
  8841. COLOR_NUMBER_BG = "5;232";
  8842. COLOR_STATUS_FG = "5;188";
  8843. COLOR_STATUS_BG = "5;59";
  8844. COLOR_TABBAR_BG = "5;59";
  8845. COLOR_TAB_BG = "5;59";
  8846. COLOR_KEYWORD = "5;74";
  8847. COLOR_STRING = "5;71";
  8848. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  8849. COLOR_TYPE = "5;221";
  8850. COLOR_PRAGMA = "5;160";
  8851. COLOR_NUMERAL = "5;161";
  8852. COLOR_ERROR_FG = "5;15";
  8853. COLOR_ERROR_BG = "5;196";
  8854. COLOR_SEARCH_FG = "5;234";
  8855. COLOR_SEARCH_BG = "5;226";
  8856. COLOR_SELECTFG = "5;17";
  8857. COLOR_SELECTBG = "5;109";
  8858. COLOR_RED = "@1";
  8859. COLOR_GREEN = "@2";
  8860. COLOR_BOLD = "5;188;1";
  8861. COLOR_LINK = "5;74;4";
  8862. COLOR_ESCAPE = "5;79";
  8863. current_theme = "sunsmoke256";
  8864. }
  8865. /* Custom theme */
  8866. BIM_THEME(sunsmoke) {
  8867. if (!global_config.can_24bit) {
  8868. load_colorscheme_sunsmoke256();
  8869. return;
  8870. }
  8871. COLOR_FG = "2;230;230;230";
  8872. COLOR_BG = "2;31;31;31";
  8873. COLOR_ALT_FG = "2;122;122;122";
  8874. COLOR_ALT_BG = "2;46;43;46";
  8875. COLOR_NUMBER_FG = "2;150;139;57";
  8876. COLOR_NUMBER_BG = "2;0;0;0";
  8877. COLOR_STATUS_FG = "2;230;230;230";
  8878. COLOR_STATUS_BG = "2;71;64;58";
  8879. COLOR_TABBAR_BG = "2;71;64;58";
  8880. COLOR_TAB_BG = "2;71;64;58";
  8881. COLOR_KEYWORD = "2;51;162;230";
  8882. COLOR_STRING = "2;72;176;72";
  8883. COLOR_COMMENT = "2;158;153;129;3";
  8884. COLOR_TYPE = "2;230;206;110";
  8885. COLOR_PRAGMA = "2;194;70;54";
  8886. COLOR_NUMERAL = "2;230;43;127";
  8887. COLOR_ERROR_FG = "5;15";
  8888. COLOR_ERROR_BG = "5;196";
  8889. COLOR_SEARCH_FG = "5;234";
  8890. COLOR_SEARCH_BG = "5;226";
  8891. COLOR_SELECTFG = "2;0;43;54";
  8892. COLOR_SELECTBG = "2;147;161;161";
  8893. COLOR_RED = "2;222;53;53";
  8894. COLOR_GREEN = "2;55;167;0";
  8895. COLOR_BOLD = "2;230;230;230;1";
  8896. COLOR_LINK = "2;51;162;230;4";
  8897. COLOR_ESCAPE = "2;113;203;173";
  8898. current_theme = "sunsmoke";
  8899. }
  8900. /* Based on the wombat256 theme for vim */
  8901. BIM_THEME(wombat) {
  8902. if (!global_config.can_256color) return;
  8903. COLOR_FG = "5;230";
  8904. COLOR_BG = "5;235";
  8905. COLOR_ALT_FG = "5;244";
  8906. COLOR_ALT_BG = "5;236";
  8907. COLOR_NUMBER_BG = "5;232";
  8908. COLOR_NUMBER_FG = "5;101";
  8909. COLOR_STATUS_FG = "5;230";
  8910. COLOR_STATUS_BG = "5;238";
  8911. COLOR_TABBAR_BG = "5;230";
  8912. COLOR_TAB_BG = "5;248";
  8913. COLOR_KEYWORD = "5;117";
  8914. COLOR_STRING = "5;113";
  8915. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  8916. COLOR_TYPE = "5;186";
  8917. COLOR_PRAGMA = "5;173";
  8918. COLOR_NUMERAL = COLOR_PRAGMA;
  8919. COLOR_ERROR_FG = "5;15";
  8920. COLOR_ERROR_BG = "5;196";
  8921. COLOR_SEARCH_FG = "5;234";
  8922. COLOR_SEARCH_BG = "5;226";
  8923. COLOR_SELECTFG = "5;235";
  8924. COLOR_SELECTBG = "5;230";
  8925. COLOR_RED = "@1";
  8926. COLOR_GREEN = "@2";
  8927. COLOR_BOLD = "5;230;1";
  8928. COLOR_LINK = "5;117;4";
  8929. COLOR_ESCAPE = "5;194";
  8930. current_theme = "wombat";
  8931. }
  8932. char * syn_bash_keywords[] = {
  8933. /* Actual bash keywords */
  8934. "if","then","else","elif","fi","case","esac","for","coproc",
  8935. "select","while","until","do","done","in","function","time",
  8936. /* Other keywords */
  8937. "exit","return","source","function","export","alias","complete","shopt","local","eval",
  8938. /* Common Unix utilities */
  8939. "echo","cd","pushd","popd","printf","sed","rm","mv",
  8940. NULL
  8941. };
  8942. int bash_pop_state(int state) {
  8943. int new_state = state / 100;
  8944. return new_state * 10;
  8945. }
  8946. int bash_push_state(int state, int new) {
  8947. return state * 10 + new;
  8948. }
  8949. int bash_paint_tick(struct syntax_state * state, int out_state) {
  8950. int last = -1;
  8951. while (charat() != -1) {
  8952. if (last != '\\' && charat() == '\'') {
  8953. paint(1, FLAG_STRING);
  8954. return bash_pop_state(out_state);
  8955. } else if (last == '\\') {
  8956. paint(1, FLAG_STRING);
  8957. last = -1;
  8958. } else if (charat() != -1) {
  8959. last = charat();
  8960. paint(1, FLAG_STRING);
  8961. }
  8962. }
  8963. return out_state;
  8964. }
  8965. int bash_paint_braced_variable(struct syntax_state * state) {
  8966. while (charat() != -1) {
  8967. if (charat() == '}') {
  8968. paint(1, FLAG_NUMERAL);
  8969. return 0;
  8970. }
  8971. paint(1, FLAG_NUMERAL);
  8972. }
  8973. return 0;
  8974. }
  8975. int bash_special_variable(int c) {
  8976. return (c == '@' || c == '?');
  8977. }
  8978. int bash_paint_string(struct syntax_state * state, char terminator, int out_state, int color) {
  8979. int last = -1;
  8980. state->state = out_state;
  8981. while (charat() != -1) {
  8982. if (last != '\\' && charat() == terminator) {
  8983. paint(1, color);
  8984. return bash_pop_state(state->state);
  8985. } else if (last == '\\') {
  8986. paint(1, color);
  8987. last = -1;
  8988. } else if (terminator != '`' && charat() == '`') {
  8989. paint(1, FLAG_ESCAPE);
  8990. state->state = bash_paint_string(state,'`',bash_push_state(out_state, 20),FLAG_ESCAPE);
  8991. } else if (terminator != ')' && charat() == '$' && nextchar() == '(') {
  8992. paint(2, FLAG_TYPE);
  8993. state->state = bash_paint_string(state,')',bash_push_state(out_state, 30),FLAG_TYPE);
  8994. } else if (charat() == '$' && nextchar() == '{') {
  8995. paint(2, FLAG_NUMERAL);
  8996. bash_paint_braced_variable(state);
  8997. } else if (charat() == '$') {
  8998. paint(1, FLAG_NUMERAL);
  8999. if (bash_special_variable(charat())) { paint(1, FLAG_NUMERAL); continue; }
  9000. while (c_keyword_qualifier(charat())) paint(1, FLAG_NUMERAL);
  9001. } else if (terminator != '"' && charat() == '"') {
  9002. paint(1, FLAG_STRING);
  9003. state->state = bash_paint_string(state,'"',bash_push_state(out_state, 40),FLAG_STRING);
  9004. } else if (terminator != '"' && charat() == '\'') { /* No single quotes in regular quotes */
  9005. paint(1, FLAG_STRING);
  9006. state->state = bash_paint_tick(state, out_state);
  9007. } else if (charat() != -1) {
  9008. last = charat();
  9009. paint(1, color);
  9010. }
  9011. }
  9012. return state->state;
  9013. }
  9014. int syn_bash_calculate(struct syntax_state * state) {
  9015. if (state->state < 1) {
  9016. if (charat() == '#') {
  9017. while (charat() != -1) {
  9018. if (common_comment_buzzwords(state)) continue;
  9019. else paint(1, FLAG_COMMENT);
  9020. }
  9021. return -1;
  9022. } else if (charat() == '\'') {
  9023. paint(1, FLAG_STRING);
  9024. return bash_paint_tick(state, 10);
  9025. } else if (charat() == '`') {
  9026. paint(1, FLAG_ESCAPE);
  9027. return bash_paint_string(state,'`',20,FLAG_ESCAPE);
  9028. } else if (charat() == '$' && nextchar() == '(') {
  9029. paint(2, FLAG_TYPE);
  9030. return bash_paint_string(state,')',30,FLAG_TYPE);
  9031. } else if (charat() == '"') {
  9032. paint(1, FLAG_STRING);
  9033. return bash_paint_string(state,'"',40,FLAG_STRING);
  9034. } else if (charat() == '$' && nextchar() == '{') {
  9035. paint(2, FLAG_NUMERAL);
  9036. bash_paint_braced_variable(state);
  9037. return 0;
  9038. } else if (charat() == '$') {
  9039. paint(1, FLAG_NUMERAL);
  9040. if (bash_special_variable(charat())) { paint(1, FLAG_NUMERAL); return 0; }
  9041. while (c_keyword_qualifier(charat())) paint(1, FLAG_NUMERAL);
  9042. return 0;
  9043. } else if (find_keywords(state, syn_bash_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  9044. return 0;
  9045. } else if (charat() == ';') {
  9046. paint(1, FLAG_KEYWORD);
  9047. return 0;
  9048. } else if (c_keyword_qualifier(charat())) {
  9049. for (int i = 0; charrel(i) != -1; ++i) {
  9050. if (charrel(i) == ' ') break;
  9051. if (charrel(i) == '=') {
  9052. for (int j = 0; j < i; ++j) {
  9053. paint(1, FLAG_TYPE);
  9054. }
  9055. skip(); /* equals sign */
  9056. return 0;
  9057. }
  9058. }
  9059. for (int i = 0; charrel(i) != -1; ++i) {
  9060. if (charrel(i) == '(') {
  9061. for (int j = 0; j < i; ++j) {
  9062. paint(1, FLAG_TYPE);
  9063. }
  9064. return 0;
  9065. }
  9066. if (!c_keyword_qualifier(charrel(i)) && charrel(i) != '-' && charrel(i) != ' ') break;
  9067. }
  9068. skip();
  9069. return 0;
  9070. } else if (charat() != -1) {
  9071. skip();
  9072. return 0;
  9073. }
  9074. } else if (state->state < 10) {
  9075. /*
  9076. * TODO: I have an idea of how to do up to `n` (here... 8?) heredocs
  9077. * by storing them in a static table and using the index into that table
  9078. * for the state, but it's iffy. It would work well in situations where
  9079. * someoen used the same heredoc repeatedly throughout their document.
  9080. */
  9081. } else if (state->state >= 10) {
  9082. /* Nested string states */
  9083. while (charat() != -1) {
  9084. int s = (state->state / 10) % 10;
  9085. if (s == 1) {
  9086. state->state = bash_paint_string(state,'\'',state->state,FLAG_STRING);
  9087. } else if (s == 2) {
  9088. state->state = bash_paint_string(state,'`',state->state,FLAG_ESCAPE);
  9089. } else if (s == 3) {
  9090. state->state = bash_paint_string(state,')',state->state,FLAG_TYPE);
  9091. } else if (s == 4) {
  9092. state->state = bash_paint_string(state,'"',state->state,FLAG_STRING);
  9093. } else if (!s) {
  9094. return -1;
  9095. }
  9096. }
  9097. return state->state;
  9098. }
  9099. return -1;
  9100. }
  9101. char * syn_bash_ext[] = {
  9102. #ifndef __toaru__
  9103. ".sh",
  9104. #endif
  9105. ".bash",".bashrc",
  9106. NULL
  9107. };
  9108. BIM_SYNTAX(bash, 0)
  9109. int cmd_qualifier(int c) { return c != -1 && c != ' '; }
  9110. extern int syn_bash_calculate(struct syntax_state * state);
  9111. extern int syn_py_calculate(struct syntax_state * state);
  9112. static int bimcmd_paint_replacement(struct syntax_state * state) {
  9113. paint(1, FLAG_KEYWORD);
  9114. char special = charat();
  9115. paint(1, FLAG_TYPE);
  9116. while (charat() != -1 && charat() != special) {
  9117. paint(1, FLAG_DIFFMINUS);
  9118. }
  9119. if (charat() == special) paint(1, FLAG_TYPE);
  9120. while (charat() != -1 && charat() != special) {
  9121. paint(1, FLAG_DIFFPLUS);
  9122. }
  9123. if (charat() == special) paint(1, FLAG_TYPE);
  9124. while (charat() != -1) paint(1, FLAG_NUMERAL);
  9125. return -1;
  9126. }
  9127. extern struct command_def * regular_commands;
  9128. extern struct command_def * prefix_commands;
  9129. static int bimcmd_find_commands(struct syntax_state * state) {
  9130. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  9131. if (match_and_paint(state, c->name, FLAG_KEYWORD, cmd_qualifier)) return 1;
  9132. }
  9133. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  9134. if (match_and_paint(state, c->name, FLAG_KEYWORD, cmd_qualifier)) return 1;
  9135. }
  9136. return 0;
  9137. }
  9138. static char * bimscript_comments[] = {
  9139. "@author","@version","@url","@description",
  9140. NULL
  9141. };
  9142. static int bcmd_at_keyword_qualifier(int c) {
  9143. return isalnum(c) || (c == '_') || (c == '@');
  9144. }
  9145. int syn_bimcmd_calculate(struct syntax_state * state) {
  9146. if (state->i == 0) {
  9147. while (charat() == ' ') skip();
  9148. if (charat() == '#') {
  9149. while (charat() != -1) {
  9150. if (charat() == '@') {
  9151. if (!find_keywords(state, bimscript_comments, FLAG_ESCAPE, bcmd_at_keyword_qualifier)) {
  9152. paint(1, FLAG_COMMENT);
  9153. }
  9154. } else {
  9155. paint(1, FLAG_COMMENT);
  9156. }
  9157. }
  9158. return -1;
  9159. } else if (match_and_paint(state, "theme", FLAG_KEYWORD, cmd_qualifier) ||
  9160. match_and_paint(state, "colorscheme", FLAG_KEYWORD, cmd_qualifier)) {
  9161. while (charat() == ' ') skip();
  9162. for (struct theme_def * s = themes; themes && s->name; ++s) {
  9163. if (match_and_paint(state, s->name, FLAG_TYPE, cmd_qualifier)) break;
  9164. }
  9165. } else if (match_and_paint(state, "syntax", FLAG_KEYWORD, cmd_qualifier)) {
  9166. while (charat() == ' ') skip();
  9167. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  9168. if (match_and_paint(state, s->name, FLAG_TYPE, cmd_qualifier)) return -1;
  9169. }
  9170. if (match_and_paint(state, "none", FLAG_TYPE, cmd_qualifier)) return -1;
  9171. } else if (match_and_paint(state, "setcolor", FLAG_KEYWORD, cmd_qualifier)) {
  9172. while (charat() == ' ') skip();
  9173. for (struct ColorName * c = color_names; c->name; ++c) {
  9174. if (match_and_paint(state, c->name, FLAG_TYPE, cmd_qualifier)) {
  9175. while (charat() != -1) paint(1, FLAG_STRING);
  9176. return -1;
  9177. }
  9178. }
  9179. return -1;
  9180. } else if (match_and_paint(state, "action", FLAG_KEYWORD, cmd_qualifier)) {
  9181. while (charat() == ' ') skip();
  9182. for (struct action_def * a = mappable_actions; a->name; ++a) {
  9183. if (match_and_paint(state, a->name, FLAG_TYPE, cmd_qualifier)) return -1;
  9184. }
  9185. } else if (charat() == '%' && nextchar() == 's') {
  9186. paint(1, FLAG_KEYWORD);
  9187. return bimcmd_paint_replacement(state);
  9188. } else if (charat() == 's' && !isalpha(nextchar())) {
  9189. return bimcmd_paint_replacement(state);
  9190. } else if (bimcmd_find_commands(state)) {
  9191. return -1;
  9192. } else if (charat() == '!') {
  9193. paint(1, FLAG_NUMERAL);
  9194. nest(syn_bash_calculate, 1);
  9195. } else if (charat() == '`') {
  9196. paint(1, FLAG_NUMERAL);
  9197. nest(syn_py_calculate, 1);
  9198. } else if (isdigit(charat()) || charat() == '-' || charat() == '+') {
  9199. paint(1, FLAG_NUMERAL);
  9200. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  9201. return -1;
  9202. }
  9203. }
  9204. return -1;
  9205. }
  9206. char * syn_bimcmd_ext[] = {".bimscript",NULL}; /* no files */
  9207. BIM_SYNTAX(bimcmd, 1)
  9208. int syn_biminfo_calculate(struct syntax_state * state) {
  9209. if (state->i == 0) {
  9210. if (charat() == '#') {
  9211. while (charat() != -1) paint(1, FLAG_COMMENT);
  9212. } else if (charat() == '>') {
  9213. paint(1, FLAG_KEYWORD);
  9214. while (charat() != ' ') paint(1, FLAG_TYPE);
  9215. skip();
  9216. while (charat() != -1) paint(1, FLAG_NUMERAL);
  9217. } else {
  9218. while (charat() != -1) paint(1, FLAG_ERROR);
  9219. }
  9220. }
  9221. return -1;
  9222. }
  9223. char * syn_biminfo_ext[] = {".biminfo",NULL};
  9224. BIM_SYNTAX(biminfo, 0)
  9225. char * syn_bimrc_keywords[] = {
  9226. "history","padding","hlparen","hlcurrent","splitpercent","numbers",
  9227. "shiftscrolling","scrollamount","git","colorgutter","relativenumber",
  9228. NULL
  9229. };
  9230. int syn_bimrc_calculate(struct syntax_state * state) {
  9231. /* No states */
  9232. if (state->i == 0) {
  9233. if (charat() == '#') {
  9234. while (charat() != -1) {
  9235. if (common_comment_buzzwords(state)) continue;
  9236. else paint(1, FLAG_COMMENT);
  9237. }
  9238. } else if (match_and_paint(state, "theme", FLAG_KEYWORD, c_keyword_qualifier)) {
  9239. if (charat() == '=') {
  9240. skip();
  9241. for (struct theme_def * s = themes; themes && s->name; ++s) {
  9242. if (match_and_paint(state, s->name, FLAG_TYPE, c_keyword_qualifier)) break;
  9243. }
  9244. }
  9245. } else if (find_keywords(state, syn_bimrc_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  9246. return -1;
  9247. }
  9248. }
  9249. return -1;
  9250. }
  9251. char * syn_bimrc_ext[] = {".bimrc",NULL};
  9252. BIM_SYNTAX(bimrc, 0)
  9253. /**
  9254. * Syntax definition for C
  9255. */
  9256. char * syn_c_keywords[] = {
  9257. "while","if","for","continue","return","break","switch","case","sizeof",
  9258. "struct","union","typedef","do","default","else","goto",
  9259. "alignas","alignof","offsetof","asm","__asm__",
  9260. /* C++ stuff */
  9261. "public","private","class","using","namespace","virtual","override","protected",
  9262. "template","typename","static_cast","throw",
  9263. NULL
  9264. };
  9265. char * syn_c_types[] = {
  9266. "static","int","char","short","float","double","void","unsigned","volatile","const",
  9267. "register","long","inline","restrict","enum","auto","extern","bool","complex",
  9268. "uint8_t","uint16_t","uint32_t","uint64_t",
  9269. "int8_t","int16_t","int32_t","int64_t","FILE",
  9270. "ssize_t","size_t","uintptr_t","intptr_t","__volatile__",
  9271. "constexpr",
  9272. NULL
  9273. };
  9274. char * syn_c_special[] = {
  9275. "NULL",
  9276. "stdin","stdout","stderr",
  9277. "STDIN_FILENO","STDOUT_FILENO","STDERR_FILENO",
  9278. NULL
  9279. };
  9280. int c_keyword_qualifier(int c) {
  9281. return isalnum(c) || (c == '_');
  9282. }
  9283. /**
  9284. * Paints a basic C-style quoted string.
  9285. */
  9286. void paint_c_string(struct syntax_state * state) {
  9287. /* Assumes you came in from a check of charat() == '"' */
  9288. paint(1, FLAG_STRING);
  9289. int last = -1;
  9290. while (charat() != -1) {
  9291. if (last != '\\' && charat() == '"') {
  9292. paint(1, FLAG_STRING);
  9293. return;
  9294. } else if (charat() == '\\' && (nextchar() == '\\' || nextchar() == 'n' || nextchar() == 'r')) {
  9295. paint(2, FLAG_ESCAPE);
  9296. last = -1;
  9297. } else if (charat() == '\\' && nextchar() >= '0' && nextchar() <= '7') {
  9298. paint(2, FLAG_ESCAPE);
  9299. if (charat() >= '0' && charat() <= '7') {
  9300. paint(1, FLAG_ESCAPE);
  9301. if (charat() >= '0' && charat() <= '7') {
  9302. paint(1, FLAG_ESCAPE);
  9303. }
  9304. }
  9305. last = -1;
  9306. } else if (charat() == '%') {
  9307. paint(1, FLAG_ESCAPE);
  9308. if (charat() == '%') {
  9309. paint(1, FLAG_ESCAPE);
  9310. } else {
  9311. while (charat() == '-' || charat() == '#' || charat() == '*' || charat() == '0' || charat() == '+') paint(1, FLAG_ESCAPE);
  9312. while (isdigit(charat())) paint(1, FLAG_ESCAPE);
  9313. if (charat() == '.') {
  9314. paint(1, FLAG_ESCAPE);
  9315. if (charat() == '*') paint(1, FLAG_ESCAPE);
  9316. else while (isdigit(charat())) paint(1, FLAG_ESCAPE);
  9317. }
  9318. while (charat() == 'l' || charat() == 'z') paint(1, FLAG_ESCAPE);
  9319. paint(1, FLAG_ESCAPE);
  9320. }
  9321. } else if (charat() == '\\' && nextchar() == 'x') {
  9322. paint(2, FLAG_ESCAPE);
  9323. while (isxdigit(charat())) paint(1, FLAG_ESCAPE);
  9324. } else {
  9325. last = charat();
  9326. paint(1, FLAG_STRING);
  9327. }
  9328. }
  9329. }
  9330. /**
  9331. * Paint a C character numeral. Can be arbitrarily large, so
  9332. * it supports multibyte chars for things like defining weird
  9333. * ASCII multibyte integer constants.
  9334. */
  9335. void paint_c_char(struct syntax_state * state) {
  9336. /* Assumes you came in from a check of charat() == '\'' */
  9337. paint(1, FLAG_NUMERAL);
  9338. int last = -1;
  9339. while (charat() != -1) {
  9340. if (last != '\\' && charat() == '\'') {
  9341. paint(1, FLAG_NUMERAL);
  9342. return;
  9343. } else if (last == '\\' && charat() == '\\') {
  9344. paint(1, FLAG_NUMERAL);
  9345. last = -1;
  9346. } else {
  9347. last = charat();
  9348. paint(1, FLAG_NUMERAL);
  9349. }
  9350. }
  9351. }
  9352. /**
  9353. * Paint a classic C comment which continues until terminated.
  9354. * Assumes you've already painted the starting / and *.
  9355. */
  9356. int paint_c_comment(struct syntax_state * state) {
  9357. int last = -1;
  9358. while (charat() != -1) {
  9359. if (common_comment_buzzwords(state)) continue;
  9360. else if (last == '*' && charat() == '/') {
  9361. paint(1, FLAG_COMMENT);
  9362. return 0;
  9363. } else {
  9364. last = charat();
  9365. paint(1, FLAG_COMMENT);
  9366. }
  9367. }
  9368. return 1;
  9369. }
  9370. /**
  9371. * Paint a generic C pragma, eg. a #define statement.
  9372. */
  9373. int paint_c_pragma(struct syntax_state * state) {
  9374. while (state->i < state->line->actual) {
  9375. if (charat() == '"') {
  9376. /* Paint C string */
  9377. paint_c_string(state);
  9378. } else if (charat() == '\'') {
  9379. paint_c_char(state);
  9380. } else if (charat() == '\\' && state->i == state->line->actual - 1) {
  9381. paint(1, FLAG_PRAGMA);
  9382. return 2;
  9383. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  9384. continue;
  9385. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  9386. continue;
  9387. } else if (charat() == '/' && nextchar() == '/') {
  9388. /* C++-style comments */
  9389. paint_comment(state);
  9390. return -1;
  9391. } else if (charat() == '/' && nextchar() == '*') {
  9392. /* C-style comments */
  9393. if (paint_c_comment(state) == 1) return 3;
  9394. continue;
  9395. } else {
  9396. paint(1, FLAG_PRAGMA);
  9397. }
  9398. }
  9399. return 0;
  9400. }
  9401. /**
  9402. * Paint integers and floating point values with some handling for suffixes.
  9403. */
  9404. int paint_c_numeral(struct syntax_state * state) {
  9405. if (charat() == '0' && (nextchar() == 'x' || nextchar() == 'X')) {
  9406. paint(2, FLAG_NUMERAL);
  9407. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  9408. } else if (charat() == '0' && nextchar() == '.') {
  9409. paint(2, FLAG_NUMERAL);
  9410. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  9411. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  9412. return 0;
  9413. } else if (charat() == '0') {
  9414. paint(1, FLAG_NUMERAL);
  9415. while (charat() >= '0' && charat() <= '7') paint(1, FLAG_NUMERAL);
  9416. } else {
  9417. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  9418. if (charat() == '.') {
  9419. paint(1, FLAG_NUMERAL);
  9420. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  9421. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  9422. return 0;
  9423. }
  9424. }
  9425. while (charat() == 'u' || charat() == 'U' || charat() == 'l' || charat() == 'L') paint(1, FLAG_NUMERAL);
  9426. return 0;
  9427. }
  9428. int syn_c_calculate(struct syntax_state * state) {
  9429. switch (state->state) {
  9430. case -1:
  9431. case 0:
  9432. if (charat() == '#') {
  9433. /* Must be first thing on line, but can have spaces before */
  9434. for (int i = 0; i < state->i; ++i) {
  9435. if (state->line->text[i].codepoint != ' ' && state->line->text[i].codepoint != '\t') {
  9436. skip();
  9437. return 0;
  9438. }
  9439. }
  9440. /* Handle preprocessor functions */
  9441. paint(1, FLAG_PRAGMA);
  9442. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  9443. if (match_and_paint(state, "include", FLAG_PRAGMA, c_keyword_qualifier)) {
  9444. /* Put quotes around <includes> */
  9445. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  9446. if (charat() == '<') {
  9447. paint(1, FLAG_STRING);
  9448. while (charat() != '>' && state->i < state->line->actual) {
  9449. paint(1, FLAG_STRING);
  9450. }
  9451. if (charat() != -1) {
  9452. paint(1, FLAG_STRING);
  9453. }
  9454. }
  9455. /* (for "includes", normal pragma highlighting covers that. */
  9456. } else if (match_and_paint(state, "if", FLAG_PRAGMA, c_keyword_qualifier)) {
  9457. /* These are to prevent #if and #else from being highlighted as keywords */
  9458. } else if (match_and_paint(state, "else", FLAG_PRAGMA, c_keyword_qualifier)) {
  9459. /* ... */
  9460. }
  9461. return paint_c_pragma(state);
  9462. } else if (charat() == '/' && nextchar() == '/') {
  9463. /* C++-style comments */
  9464. paint_comment(state);
  9465. } else if (charat() == '/' && nextchar() == '*') {
  9466. /* C-style comments */
  9467. if (paint_c_comment(state) == 1) return 1;
  9468. return 0;
  9469. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  9470. return 0;
  9471. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  9472. return 0;
  9473. } else if (find_keywords(state, syn_c_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  9474. return 0;
  9475. } else if (charat() == '\"') {
  9476. paint_c_string(state);
  9477. return 0;
  9478. } else if (charat() == '\'') {
  9479. paint_c_char(state);
  9480. return 0;
  9481. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  9482. paint_c_numeral(state);
  9483. return 0;
  9484. } else if (charat() != -1) {
  9485. skip();
  9486. return 0;
  9487. }
  9488. break;
  9489. case 1:
  9490. /* In a block comment */
  9491. if (paint_c_comment(state) == 1) return 1;
  9492. return 0;
  9493. case 2:
  9494. /* In an unclosed preprocessor statement */
  9495. return paint_c_pragma(