bim.c 324 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690
  1. /* Bim - A Text Editor
  2. *
  3. * Copyright (C) 2012-2021 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "bim.h"
  18. #include <kuroko/kuroko.h>
  19. #include <kuroko/vm.h>
  20. #include <kuroko/debug.h>
  21. #include <kuroko/util.h>
  22. #include <kuroko/scanner.h>
  23. global_config_t global_config = {
  24. /* State */
  25. .term_width = 0,
  26. .term_height = 0,
  27. .bottom_size = 2,
  28. .yanks = NULL,
  29. .yank_count = 0,
  30. .yank_is_full_lines = 0,
  31. .tty_in = STDIN_FILENO,
  32. .bimrc_path = "~/.bim3rc",
  33. .syntax_fallback = NULL, /* Syntax to fall back to if no other match applies */
  34. .search = NULL,
  35. .overlay_mode = OVERLAY_MODE_NONE,
  36. .command_buffer = NULL,
  37. .command_offset = 0,
  38. .command_col_no = 0,
  39. .history_point = -1,
  40. /* Bitset starts here */
  41. .highlight_on_open = 1,
  42. .initial_file_is_read_only = 0,
  43. .go_to_line = 1,
  44. .break_from_selection = 1,
  45. /* Terminal capabilities */
  46. .can_scroll = 1,
  47. .can_hideshow = 1,
  48. .can_altscreen = 1,
  49. .can_mouse = 1,
  50. .can_unicode = 1,
  51. .can_bright = 1,
  52. .can_title = 1,
  53. .can_bce = 1,
  54. .can_24bit = 1, /* can use 24-bit color */
  55. .can_256color = 1, /* can use 265 colors */
  56. .can_italic = 1, /* can use italics (without inverting) */
  57. .can_insert = 0, /* ^[[L */
  58. .can_bracketedpaste = 0, /* puts escapes before and after pasted stuff */
  59. .can_sgrmouse = 0, /* Whether SGR mouse mode is availabe (large coordinates) */
  60. /* Configuration options */
  61. .history_enabled = 1,
  62. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  63. .smart_case = 1, /* smart case-sensitivity while searching */
  64. .highlight_current_line = 1,
  65. .shift_scrolling = 1, /* shift rather than moving cursor*/
  66. .check_git = 0,
  67. .color_gutter = 1, /* shows modified lines */
  68. .relative_lines = 0,
  69. .numbers = 1,
  70. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  71. .hide_statusbar = 0,
  72. .tabs_visible = 1,
  73. .autohide_tabs = 0,
  74. .smart_complete = 0,
  75. .has_terminal = 0,
  76. .search_wraps = 1,
  77. .had_error = 0,
  78. .use_biminfo = 1,
  79. /* Integer config values */
  80. .cursor_padding = 4,
  81. .split_percent = 50,
  82. .scroll_amount = 5,
  83. .tab_offset = 0,
  84. .background_task = NULL,
  85. .tail_task = NULL,
  86. };
  87. struct key_name_map KeyNames[] = {
  88. {KEY_TIMEOUT, "[timeout]"},
  89. {KEY_BACKSPACE, "<backspace>"},
  90. {KEY_ENTER, "<enter>"},
  91. {KEY_ESCAPE, "<escape>"},
  92. {KEY_TAB, "<tab>"},
  93. {' ', "<space>"},
  94. /* These are mostly here for markdown output. */
  95. {'`', "<backtick>"},
  96. {'|', "<pipe>"},
  97. {KEY_DELETE, "<del>"},
  98. {KEY_MOUSE, "<mouse>"},
  99. {KEY_MOUSE_SGR, "<mouse-sgr>"},
  100. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  101. {KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
  102. {KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
  103. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  104. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  105. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  106. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  107. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  108. {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>"},
  109. {KEY_SHIFT_TAB,"<shift-tab>"},
  110. {KEY_PASTE_BEGIN,"<paste-begin>"},{KEY_PASTE_END,"<paste-end>"},
  111. };
  112. char * name_from_key(enum Key keycode) {
  113. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  114. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  115. }
  116. static char keyNameTmp[8] = {0};
  117. if (keycode <= KEY_CTRL_UNDERSCORE) {
  118. keyNameTmp[0] = '^';
  119. keyNameTmp[1] = '@' + keycode;
  120. keyNameTmp[2] = 0;
  121. return keyNameTmp;
  122. }
  123. to_eight(keycode, keyNameTmp);
  124. return keyNameTmp;
  125. }
  126. #define S(c) (krk_copyString(c,sizeof(c)-1))
  127. static KrkClass * syntaxStateClass = NULL;
  128. struct SyntaxState {
  129. KrkInstance inst;
  130. struct syntax_state state;
  131. };
  132. static void schedule_complete_recalc(void);
  133. /**
  134. * Theming data
  135. *
  136. * This default set is pretty simple "default foreground on default background"
  137. * except for search and selections which are black-on-white specifically.
  138. *
  139. * The theme colors get set by separate configurable theme scripts.
  140. */
  141. const char * COLOR_FG = "@9";
  142. const char * COLOR_BG = "@9";
  143. const char * COLOR_ALT_FG = "@9";
  144. const char * COLOR_ALT_BG = "@9";
  145. const char * COLOR_NUMBER_FG = "@9";
  146. const char * COLOR_NUMBER_BG = "@9";
  147. const char * COLOR_STATUS_FG = "@9";
  148. const char * COLOR_STATUS_BG = "@9";
  149. const char * COLOR_STATUS_ALT= "@9";
  150. const char * COLOR_TABBAR_BG = "@9";
  151. const char * COLOR_TAB_BG = "@9";
  152. const char * COLOR_ERROR_FG = "@9";
  153. const char * COLOR_ERROR_BG = "@9";
  154. const char * COLOR_SEARCH_FG = "@0";
  155. const char * COLOR_SEARCH_BG = "@17";
  156. const char * COLOR_KEYWORD = "@9";
  157. const char * COLOR_STRING = "@9";
  158. const char * COLOR_COMMENT = "@9";
  159. const char * COLOR_TYPE = "@9";
  160. const char * COLOR_PRAGMA = "@9";
  161. const char * COLOR_NUMERAL = "@9";
  162. const char * COLOR_SELECTFG = "@0";
  163. const char * COLOR_SELECTBG = "@17";
  164. const char * COLOR_RED = "@1";
  165. const char * COLOR_GREEN = "@2";
  166. const char * COLOR_BOLD = "@9";
  167. const char * COLOR_LINK = "@9";
  168. const char * COLOR_ESCAPE = "@9";
  169. const char * current_theme = "none";
  170. struct ColorName color_names[] = {
  171. {"text-fg", &COLOR_FG},
  172. {"text-bg", &COLOR_BG},
  173. {"alternate-fg", &COLOR_ALT_FG},
  174. {"alternate-bg", &COLOR_ALT_BG},
  175. {"number-fg", &COLOR_NUMBER_FG},
  176. {"number-bg", &COLOR_NUMBER_BG},
  177. {"status-fg", &COLOR_STATUS_FG},
  178. {"status-bg", &COLOR_STATUS_BG},
  179. {"status-alt", &COLOR_STATUS_ALT},
  180. {"tabbar-bg", &COLOR_TABBAR_BG},
  181. {"tab-bg", &COLOR_TAB_BG},
  182. {"error-fg", &COLOR_ERROR_FG},
  183. {"error-bg", &COLOR_ERROR_BG},
  184. {"search-fg", &COLOR_SEARCH_FG},
  185. {"search-bg", &COLOR_SEARCH_BG},
  186. {"keyword", &COLOR_KEYWORD},
  187. {"string", &COLOR_STRING},
  188. {"comment", &COLOR_COMMENT},
  189. {"type", &COLOR_TYPE},
  190. {"pragma", &COLOR_PRAGMA},
  191. {"numeral", &COLOR_NUMERAL},
  192. {"select-fg", &COLOR_SELECTFG},
  193. {"select-bg", &COLOR_SELECTBG},
  194. {"red", &COLOR_RED},
  195. {"green", &COLOR_GREEN},
  196. {"bold", &COLOR_BOLD},
  197. {"link", &COLOR_LINK},
  198. {"escape", &COLOR_ESCAPE},
  199. {NULL,NULL},
  200. };
  201. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  202. int flex_ ## name ## _count = 0; \
  203. int flex_ ## name ## _space = 0; \
  204. type * name = NULL; \
  205. void add_name (type input) { \
  206. if (flex_ ## name ## _space == 0) { \
  207. flex_ ## name ## _space = 4; \
  208. name = calloc(sizeof(type), flex_ ## name ## _space); \
  209. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  210. flex_ ## name ## _space *= 2; \
  211. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  212. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  213. } \
  214. name[flex_ ## name ## _count] = input; \
  215. flex_ ## name ## _count ++; \
  216. }
  217. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  218. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  219. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  220. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  221. /**
  222. * Special implementation of getch with a timeout
  223. */
  224. int _bim_unget = -1;
  225. void bim_unget(int c) {
  226. _bim_unget = c;
  227. }
  228. void redraw_statusbar(void);
  229. int bim_getch_timeout(int timeout) {
  230. fflush(stdout);
  231. if (_bim_unget != -1) {
  232. int out = _bim_unget;
  233. _bim_unget = -1;
  234. return out;
  235. }
  236. struct pollfd fds[1];
  237. fds[0].fd = global_config.tty_in;
  238. fds[0].events = POLLIN;
  239. int ret = poll(fds,1,timeout);
  240. if (ret > 0 && fds[0].revents & POLLIN) {
  241. unsigned char buf[1];
  242. read(global_config.tty_in, buf, 1);
  243. return buf[0];
  244. } else {
  245. background_task_t * task = global_config.background_task;
  246. if (task) {
  247. global_config.background_task = task->next;
  248. task->func(task);
  249. free(task);
  250. if (!global_config.background_task) {
  251. global_config.tail_task = NULL;
  252. redraw_statusbar();
  253. }
  254. }
  255. return -1;
  256. }
  257. }
  258. /**
  259. * UTF-8 parser state
  260. */
  261. static uint32_t codepoint_r;
  262. static uint32_t state = 0;
  263. #define UTF8_ACCEPT 0
  264. #define UTF8_REJECT 1
  265. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  266. static int state_table[32] = {
  267. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  268. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  269. 2,2,2,2, /* 110xxxxx */
  270. 3,3, /* 1110xxxx */
  271. 4, /* 11110xxx */
  272. 1 /* 11111xxx */
  273. };
  274. static int mask_bytes[32] = {
  275. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  276. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  277. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  278. 0x1F,0x1F,0x1F,0x1F,
  279. 0x0F,0x0F,
  280. 0x07,
  281. 0x00
  282. };
  283. static int next[5] = {
  284. 0,
  285. 1,
  286. 0,
  287. 2,
  288. 3
  289. };
  290. if (*state == UTF8_ACCEPT) {
  291. *codep = byte & mask_bytes[byte >> 3];
  292. *state = state_table[byte >> 3];
  293. } else if (*state > 0) {
  294. *codep = (byte & 0x3F) | (*codep << 6);
  295. *state = next[*state];
  296. }
  297. return *state;
  298. }
  299. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  300. int _shift_key(int i, int this_buf[20], int *timeout) {
  301. int thing = this_buf[*timeout-1];
  302. (*timeout) = 0;
  303. switch (thing) {
  304. /* There are other combinations we can handle... */
  305. case '2': return i + 4;
  306. case '5': return i + 8;
  307. case '3': return i + 12;
  308. case '4': return i + 16;
  309. default: return i;
  310. }
  311. }
  312. int bim_getkey(int read_timeout) {
  313. int timeout = 0;
  314. int this_buf[20];
  315. int cin;
  316. uint32_t c;
  317. uint32_t istate = 0;
  318. while ((cin = bim_getch_timeout((timeout == 1) ? 50 : read_timeout))) {
  319. if (cin == -1) {
  320. if (timeout && this_buf[timeout-1] == '\033')
  321. return KEY_ESCAPE;
  322. return KEY_TIMEOUT;
  323. }
  324. if (!decode(&istate, &c, cin)) {
  325. if (timeout == 0) {
  326. switch (c) {
  327. case '\033':
  328. if (timeout == 0) {
  329. this_buf[timeout] = c;
  330. timeout++;
  331. }
  332. continue;
  333. case KEY_LINEFEED: return KEY_ENTER;
  334. case KEY_DELETE: return KEY_BACKSPACE;
  335. }
  336. return c;
  337. } else {
  338. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  339. bim_unget(c);
  340. timeout = 0;
  341. return KEY_ESCAPE;
  342. }
  343. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  344. this_buf[timeout] = c;
  345. timeout++;
  346. continue;
  347. }
  348. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  349. switch (c) {
  350. case 'P': return KEY_F1;
  351. case 'Q': return KEY_F2;
  352. case 'R': return KEY_F3;
  353. case 'S': return KEY_F4;
  354. }
  355. timeout = 0;
  356. continue;
  357. }
  358. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  359. timeout = 0;
  360. bim_unget(c);
  361. return KEY_ESCAPE;
  362. }
  363. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  364. timeout = 1;
  365. this_buf[timeout] = c;
  366. timeout++;
  367. continue;
  368. }
  369. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  370. (isdigit(c) || (c == ';'))) {
  371. this_buf[timeout] = c;
  372. timeout++;
  373. continue;
  374. }
  375. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  376. switch (c) {
  377. case 'M': return KEY_MOUSE;
  378. case '<': return KEY_MOUSE_SGR;
  379. case 'A': return shift_key(KEY_UP);
  380. case 'B': return shift_key(KEY_DOWN);
  381. case 'C': return shift_key(KEY_RIGHT);
  382. case 'D': return shift_key(KEY_LEFT);
  383. case 'H': return KEY_HOME;
  384. case 'F': return KEY_END;
  385. case 'I': return KEY_PAGE_UP;
  386. case 'G': return KEY_PAGE_DOWN;
  387. case 'Z': return KEY_SHIFT_TAB;
  388. case '~':
  389. if (timeout == 3) {
  390. switch (this_buf[2]) {
  391. case '1': return KEY_HOME;
  392. case '3': return KEY_DELETE;
  393. case '4': return KEY_END;
  394. case '5': return KEY_PAGE_UP;
  395. case '6': return KEY_PAGE_DOWN;
  396. }
  397. } else if (timeout == 5) {
  398. if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '0') {
  399. return KEY_PASTE_BEGIN;
  400. } else if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '1') {
  401. return KEY_PASTE_END;
  402. }
  403. } else if (this_buf[2] == '1') {
  404. switch (this_buf[3]) {
  405. case '5': return KEY_F5;
  406. case '7': return KEY_F6;
  407. case '8': return KEY_F7;
  408. case '9': return KEY_F8;
  409. }
  410. } else if (this_buf[2] == '2') {
  411. switch (this_buf[3]) {
  412. case '0': return KEY_F9;
  413. case '1': return KEY_F10;
  414. case '3': return KEY_F11;
  415. case '4': return KEY_F12;
  416. }
  417. }
  418. break;
  419. }
  420. }
  421. timeout = 0;
  422. continue;
  423. }
  424. } else if (istate == UTF8_REJECT) {
  425. istate = 0;
  426. }
  427. }
  428. return KEY_TIMEOUT;
  429. }
  430. enum Key key_from_name(char * name) {
  431. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  432. if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
  433. }
  434. if (name[0] == '^' && name[1] && !name[2]) {
  435. return name[1] - '@';
  436. }
  437. if (!name[1]) return name[0];
  438. /* Try decoding */
  439. uint32_t c, state = 0;
  440. int candidate = -1;
  441. while (*name) {
  442. if (!decode(&state, &c, (unsigned char)*name)) {
  443. if (candidate == -1) candidate = c;
  444. else return -1; /* Reject `name` if it is multiple codepoints */
  445. } else if (state == UTF8_REJECT) {
  446. return -1;
  447. }
  448. }
  449. return candidate;
  450. }
  451. /**
  452. * Pointer to current active buffer
  453. */
  454. buffer_t * env = NULL;
  455. buffer_t * left_buffer = NULL;
  456. buffer_t * right_buffer = NULL;
  457. /**
  458. * A buffer for holding a number (line, repetition count)
  459. */
  460. #define NAV_BUFFER_MAX 10
  461. char nav_buf[NAV_BUFFER_MAX+1];
  462. int nav_buffer = 0;
  463. /**
  464. * Available buffers
  465. */
  466. int buffers_len = 0;
  467. int buffers_avail = 0;
  468. buffer_t ** buffers = NULL;
  469. /**
  470. * Create a new buffer
  471. */
  472. buffer_t * buffer_new(void) {
  473. if (buffers_len == buffers_avail) {
  474. /* If we are out of buffer space, expand the buffers vector */
  475. buffers_avail *= 2;
  476. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  477. }
  478. /* TODO: Clean up split support and support multiple splits... */
  479. if (left_buffer) {
  480. left_buffer->left = 0;
  481. left_buffer->width = global_config.term_width;
  482. right_buffer->left = 0;
  483. right_buffer->width = global_config.term_width;
  484. left_buffer = NULL;
  485. right_buffer = NULL;
  486. }
  487. /* Allocate a new buffer */
  488. buffers[buffers_len] = malloc(sizeof(buffer_t));
  489. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  490. buffers[buffers_len]->left = 0;
  491. buffers[buffers_len]->width = global_config.term_width;
  492. buffers[buffers_len]->highlighting_paren = -1;
  493. buffers[buffers_len]->numbers = global_config.numbers;
  494. buffers[buffers_len]->gutter = 1;
  495. buffers_len++;
  496. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  497. return buffers[buffers_len-1];
  498. }
  499. /**
  500. * Open the biminfo file.
  501. */
  502. FILE * open_biminfo(void) {
  503. if (!global_config.use_biminfo) return NULL;
  504. char * home = getenv("HOME");
  505. if (!home) {
  506. /* ... but since it's not, we need $HOME, so fail if it isn't set. */
  507. return NULL;
  508. }
  509. /* biminfo lives at ~/.biminfo */
  510. char biminfo_path[PATH_MAX+1] = {0};
  511. sprintf(biminfo_path,"%s/.biminfo",home);
  512. /* Try to open normally first... */
  513. FILE * biminfo = fopen(biminfo_path,"r+");
  514. if (!biminfo) {
  515. /* Otherwise, try to create it. */
  516. biminfo = fopen(biminfo_path,"w+");
  517. }
  518. return biminfo;
  519. }
  520. /**
  521. * Check if a file is open by examining the biminfo file
  522. */
  523. int file_is_open(char * file_name) {
  524. /* Get the absolute path of the file to normalize for lookup */
  525. char tmp_path[PATH_MAX+2];
  526. if (!realpath(file_name, tmp_path)) {
  527. return 0; /* Assume not */
  528. }
  529. strcat(tmp_path," ");
  530. FILE * biminfo = open_biminfo();
  531. if (!biminfo) return 0; /* Assume not */
  532. /* Scan */
  533. char line[PATH_MAX+64];
  534. while (!feof(biminfo)) {
  535. fpos_t start_of_line;
  536. fgetpos(biminfo, &start_of_line);
  537. fgets(line, PATH_MAX+63, biminfo);
  538. if (line[0] != '%') {
  539. continue;
  540. }
  541. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  542. /* File is currently open */
  543. int pid = -1;
  544. sscanf(line+1+strlen(tmp_path)+1,"%d",&pid);
  545. if (pid != -1 && pid != getpid()) {
  546. if (!kill(pid, 0)) {
  547. int key = 0;
  548. render_error("biminfo indicates another instance may already be editing this file");
  549. render_commandline_message("\n");
  550. render_commandline_message("file path = %s\n", tmp_path);
  551. render_commandline_message("pid = %d (still running)\n", pid);
  552. render_commandline_message("Open file anyway? (y/N)");
  553. while ((key = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  554. if (key != 'y') {
  555. fclose(biminfo);
  556. return 1;
  557. }
  558. }
  559. }
  560. fclose(biminfo);
  561. return 0;
  562. }
  563. }
  564. fclose(biminfo);
  565. return 0;
  566. }
  567. /**
  568. * Fetch the cursor position from a biminfo file
  569. */
  570. int fetch_from_biminfo(buffer_t * buf) {
  571. /* Can't fetch if we don't have a filename */
  572. if (!buf->file_name) return 1;
  573. /* Get the absolute path of the file to normalize for lookup */
  574. char tmp_path[PATH_MAX+2];
  575. if (!realpath(buf->file_name, tmp_path)) {
  576. return 1;
  577. }
  578. strcat(tmp_path," ");
  579. FILE * biminfo = open_biminfo();
  580. if (!biminfo) return 1;
  581. /* Scan */
  582. char line[PATH_MAX+64];
  583. while (!feof(biminfo)) {
  584. fpos_t start_of_line;
  585. fgetpos(biminfo, &start_of_line);
  586. fgets(line, PATH_MAX+63, biminfo);
  587. if (line[0] != '>') {
  588. continue;
  589. }
  590. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  591. /* Read */
  592. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  593. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  594. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  595. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  596. try_to_center();
  597. fclose(biminfo);
  598. return 0;
  599. }
  600. }
  601. fclose(biminfo);
  602. return 0;
  603. }
  604. /**
  605. * Write a file containing the last cursor position of a buffer.
  606. */
  607. int update_biminfo(buffer_t * buf, int is_open) {
  608. if (!buf->file_name) return 1;
  609. /* Get the absolute path of the file to normalize for lookup */
  610. char tmp_path[PATH_MAX+1];
  611. if (!realpath(buf->file_name, tmp_path)) {
  612. return 1;
  613. }
  614. strcat(tmp_path," ");
  615. FILE * biminfo = open_biminfo();
  616. if (!biminfo) return 1;
  617. /* Scan */
  618. char line[PATH_MAX+64];
  619. while (!feof(biminfo)) {
  620. fpos_t start_of_line;
  621. fgetpos(biminfo, &start_of_line);
  622. fgets(line, PATH_MAX+63, biminfo);
  623. if (line[0] != '>' && line[0] != '%') {
  624. continue;
  625. }
  626. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  627. /* Update */
  628. fsetpos(biminfo, &start_of_line);
  629. fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
  630. is_open ? getpid() : buf->line_no, buf->col_no);
  631. goto _done;
  632. }
  633. }
  634. if (ftell(biminfo) == 0) {
  635. /* New biminfo */
  636. fprintf(biminfo, "# This is a biminfo file.\n");
  637. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  638. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  639. }
  640. /* If we reach this point, we didn't find a record for this file
  641. * and the write cursor should be at the end, so just add a new line */
  642. fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
  643. is_open ? getpid() : buf->line_no, buf->col_no);
  644. _done:
  645. fclose(biminfo);
  646. return 0;
  647. }
  648. void cancel_background_tasks(buffer_t * buf) {
  649. background_task_t * t = global_config.background_task;
  650. background_task_t * last = NULL;
  651. while (t) {
  652. if (t->env == buf) {
  653. if (last) {
  654. last->next = t->next;
  655. } else {
  656. global_config.background_task = t->next;
  657. }
  658. if (!t->next) {
  659. global_config.tail_task = last;
  660. }
  661. background_task_t * tmp = t->next;
  662. free(t);
  663. t = tmp;
  664. } else {
  665. last = t;
  666. t = t->next;
  667. }
  668. }
  669. }
  670. /**
  671. * Close a buffer
  672. */
  673. buffer_t * buffer_close(buffer_t * buf) {
  674. int i;
  675. /* Locate the buffer in the buffer list */
  676. for (i = 0; i < buffers_len; i++) {
  677. if (buf == buffers[i])
  678. break;
  679. }
  680. /* This buffer doesn't exist? */
  681. if (i == buffers_len) {
  682. return NULL;
  683. }
  684. /* Cancel any background tasks for this env */
  685. cancel_background_tasks(buf);
  686. update_biminfo(buf, 0);
  687. /* Clean up lines used by old buffer */
  688. for (int i = 0; i < buf->line_count; ++i) {
  689. free(buf->lines[i]);
  690. }
  691. free(buf->lines);
  692. if (buf->file_name) {
  693. free(buf->file_name);
  694. }
  695. history_t * h = buf->history;
  696. while (h->next) {
  697. h = h->next;
  698. }
  699. while (h) {
  700. history_t * x = h->previous;
  701. free(h);
  702. h = x;
  703. }
  704. /* Clean up the old buffer */
  705. free(buf);
  706. /* Remove the buffer from the vector, moving others up */
  707. if (i != buffers_len - 1) {
  708. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i - 1));
  709. }
  710. /* There is one less buffer */
  711. buffers_len--;
  712. if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
  713. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  714. if (!buffers_len) {
  715. /* There are no more buffers. */
  716. return NULL;
  717. }
  718. /* If this was the last buffer in the list, return the previous last buffer */
  719. if (i == buffers_len) {
  720. return buffers[buffers_len-1];
  721. }
  722. /* Otherwise return the buffer in the same location */
  723. return buffers[i];
  724. }
  725. /**
  726. * Convert syntax highlighting flag to color code
  727. */
  728. const char * flag_to_color(int _flag) {
  729. int flag = _flag & FLAG_MASK_COLORS;
  730. switch (flag) {
  731. case FLAG_KEYWORD:
  732. return COLOR_KEYWORD;
  733. case FLAG_STRING:
  734. return COLOR_STRING;
  735. case FLAG_COMMENT:
  736. return COLOR_COMMENT;
  737. case FLAG_TYPE:
  738. return COLOR_TYPE;
  739. case FLAG_NUMERAL:
  740. return COLOR_NUMERAL;
  741. case FLAG_PRAGMA:
  742. return COLOR_PRAGMA;
  743. case FLAG_DIFFPLUS:
  744. return COLOR_GREEN;
  745. case FLAG_DIFFMINUS:
  746. return COLOR_RED;
  747. case FLAG_SELECT:
  748. return COLOR_FG;
  749. case FLAG_BOLD:
  750. return COLOR_BOLD;
  751. case FLAG_LINK_COLOR:
  752. return COLOR_LINK;
  753. case FLAG_ESCAPE:
  754. return COLOR_ESCAPE;
  755. default:
  756. return COLOR_FG;
  757. }
  758. }
  759. /**
  760. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  761. * so it can be used for prefix checking for things that need further special handling.
  762. */
  763. int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  764. if (keyword_qualifier(lastchar())) return 0;
  765. if (!keyword_qualifier(charat())) return 0;
  766. int i = state->i;
  767. int slen = 0;
  768. while (i < state->line->actual || *keyword == '\0') {
  769. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  770. for (int j = 0; j < slen; ++j) {
  771. paint(1, flag);
  772. }
  773. return 1;
  774. }
  775. if (*keyword != state->line->text[i].codepoint) return 0;
  776. i++;
  777. keyword++;
  778. slen++;
  779. }
  780. return 0;
  781. }
  782. /**
  783. * This is a basic character matcher for "keyword" characters.
  784. */
  785. int simple_keyword_qualifier(int c) {
  786. return isalnum(c) || (c == '_');
  787. }
  788. /**
  789. * These words can appear in comments and should be highlighted.
  790. * Since there are a lot of comment highlighters, this is provided
  791. * as a common function that can be used by multiple highlighters.
  792. */
  793. int common_comment_buzzwords(struct syntax_state * state) {
  794. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  795. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  796. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  797. return 0;
  798. }
  799. /**
  800. * Paint a comment until end of line; assumes this comment can not continue.
  801. * (Some languages have comments that can continue with a \ - don't use this!)
  802. * Assumes you've already painted your comment start characters.
  803. */
  804. int paint_comment(struct syntax_state * state) {
  805. while (charat() != -1) {
  806. if (common_comment_buzzwords(state)) continue;
  807. else { paint(1, FLAG_COMMENT); }
  808. }
  809. return -1;
  810. }
  811. /**
  812. * Find and return a highlighter by name, or return NULL if none was found.
  813. */
  814. struct syntax_definition * find_syntax_calculator(const char * name) {
  815. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  816. if (!strcmp(s->name, name)) {
  817. return s;
  818. }
  819. }
  820. return NULL;
  821. }
  822. int syntax_count = 0;
  823. int syntax_space = 0;
  824. struct syntax_definition * syntaxes = NULL;
  825. void add_syntax(struct syntax_definition def) {
  826. /* See if a name match already exists for this def. */
  827. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  828. if (!strcmp(def.name,s->name)) {
  829. *s = def;
  830. return;
  831. }
  832. }
  833. if (syntax_space == 0) {
  834. syntax_space = 4;
  835. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  836. } else if (syntax_count +1 == syntax_space) {
  837. syntax_space *= 2;
  838. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  839. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  840. }
  841. syntaxes[syntax_count] = def;
  842. syntax_count++;
  843. }
  844. void redraw_all(void);
  845. /**
  846. * Calculate syntax highlighting for the given line, and lines after
  847. * if their initial syntax state has changed by this recalculation.
  848. *
  849. * If `line_no` is -1, this line is taken to be a special line and not
  850. * part of a buffer; search highlighting will not be processed and syntax
  851. * highlighting will halt after the line is finished.
  852. *
  853. * If `env->slowop` is currently enabled, recalculation is skipped.
  854. */
  855. void recalculate_syntax(line_t * line, int line_no) {
  856. if (env->slowop) return;
  857. /* Clear syntax for this line first */
  858. int is_original = 1;
  859. while (1) {
  860. for (int i = 0; i < line->actual; ++i) {
  861. line->text[i].flags = line->text[i].flags & (3 << 5);
  862. }
  863. if (!env->syntax) {
  864. if (line_no != -1) rehighlight_search(line);
  865. return;
  866. }
  867. /* Start from the line's stored in initial state */
  868. struct SyntaxState * s = (void*)krk_newInstance(env->syntax->krkClass);
  869. s->state.env = env;
  870. s->state.line = line;
  871. s->state.line_no = line_no;
  872. s->state.state = line->istate;
  873. s->state.i = 0;
  874. while (1) {
  875. ptrdiff_t before = krk_currentThread.stackTop - krk_currentThread.stack;
  876. krk_push(OBJECT_VAL(env->syntax->krkFunc));
  877. krk_push(OBJECT_VAL(s));
  878. KrkValue result = krk_callStack(1);
  879. krk_currentThread.stackTop = krk_currentThread.stack + before;
  880. if (IS_NONE(result) && (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION)) {
  881. render_error("Exception occurred in plugin: %s", AS_INSTANCE(krk_currentThread.currentException)->_class->name->chars);
  882. render_commandline_message("\n");
  883. krk_dumpTraceback();
  884. goto _syntaxError;
  885. } else if (!IS_NONE(result) && !IS_INTEGER(result)) {
  886. render_error("Instead of an integer, got %s", krk_typeName(result));
  887. render_commandline_message("\n");
  888. goto _syntaxError;
  889. }
  890. s->state.state = IS_NONE(result) ? -1 : AS_INTEGER(result);
  891. if (s->state.state != 0) {
  892. if (line_no == -1) return;
  893. rehighlight_search(line);
  894. if (!is_original) {
  895. redraw_line(line_no);
  896. }
  897. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != s->state.state) {
  898. line_no++;
  899. line = env->lines[line_no];
  900. line->istate = s->state.state;
  901. if (env->loading) return;
  902. is_original = 0;
  903. goto _next;
  904. }
  905. return;
  906. }
  907. }
  908. _next:
  909. (void)0;
  910. }
  911. _syntaxError:
  912. krk_resetStack();
  913. fprintf(stderr,"This syntax highlighter will be disabled in this environment.");
  914. env->syntax = NULL;
  915. cancel_background_tasks(env);
  916. pause_for_key();
  917. redraw_all();
  918. }
  919. /**
  920. * Recalculate tab widths.
  921. */
  922. void recalculate_tabs(line_t * line) {
  923. if (env->loading) return;
  924. int j = 0;
  925. for (int i = 0; i < line->actual; ++i) {
  926. if (line->text[i].codepoint == '\t') {
  927. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  928. }
  929. j += line->text[i].display_width;
  930. }
  931. }
  932. /**
  933. * The next section contains the basic editing primitives. All other
  934. * actions are built out of these primitives, and they are the basic
  935. * instructions that get stored in history to be undone (or redone).
  936. *
  937. * Primitives may recalculate syntax or redraw lines, if needed, but only
  938. * when conditions for redrawing are met (such as not being in `slowop`,
  939. * or loading the file; also replaying history, or when loading files).
  940. *
  941. * At the moment, primitives and most other functions do not take the current
  942. * buffer (environment) as an argument and instead rely on a global variable;
  943. * this should definitely be fixed at some point...
  944. */
  945. /**
  946. * When a new action that produces history happens and there is forward
  947. * history that can be redone, we need to erase it as our tree has branched.
  948. * If we wanted, we could actually story things in a tree structure so that
  949. * the new branch and the old branch can both stick around, and that should
  950. * probably be explored in the future...
  951. */
  952. void history_free(history_t * root) {
  953. if (!root->next) return;
  954. /* Find the last entry so we can free backwards */
  955. history_t * n = root->next;
  956. while (n->next) {
  957. n = n->next;
  958. }
  959. /* Free everything after the root, including stored content. */
  960. while (n != root) {
  961. history_t * p = n->previous;
  962. switch (n->type) {
  963. case HISTORY_REPLACE_LINE:
  964. free(n->contents.remove_replace_line.contents);
  965. /* fall-through */
  966. case HISTORY_REMOVE_LINE:
  967. free(n->contents.remove_replace_line.old_contents);
  968. break;
  969. default:
  970. /* Nothing extra to free */
  971. break;
  972. }
  973. free(n);
  974. n = p;
  975. }
  976. root->next = NULL;
  977. }
  978. /**
  979. * This macro is called by primitives to insert history elements for each
  980. * primitive action when performing in edit modes.
  981. */
  982. #define HIST_APPEND(e) do { \
  983. e->col = env->col_no; \
  984. e->line = env->line_no; \
  985. if (env->history) { \
  986. e->previous = env->history; \
  987. history_free(env->history); \
  988. env->history->next = e; \
  989. e->next = NULL; \
  990. } \
  991. env->history = e; \
  992. } while (0)
  993. /**
  994. * Mark a point where a complete set of actions has ended.
  995. * Individual history entries include things like "insert one character"
  996. * but a user action that should be undone is "insert several characters";
  997. * breaks should be inserted after a series of primitives when there is
  998. * a clear "end", such as when switching out of insert mode after typing.
  999. */
  1000. void set_history_break(void) {
  1001. if (!global_config.history_enabled) return;
  1002. /* Do not produce duplicate breaks, or add breaks if we are at a sentinel. */
  1003. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1004. history_t * e = malloc(sizeof(history_t));
  1005. e->type = HISTORY_BREAK;
  1006. HIST_APPEND(e);
  1007. }
  1008. }
  1009. /**
  1010. * (Primitive) Insert a character into an existing line.
  1011. *
  1012. * This is the most basic primitive action: Take a line, and insert a codepoint
  1013. * into it at a given offset. If `lineno` is not -1, the line is assumed to
  1014. * be part of the active buffer. If inserting a character means the line needs
  1015. * to grow, then it will be reallocated, so the return value of the new line
  1016. * must ALWAYS be used. This primitive will NOT automatically update the
  1017. * buffer with the new pointer, so if you are calling insert on a buffer you
  1018. * MUST update env->lines[lineno-1] yourself.
  1019. */
  1020. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1021. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1022. history_t * e = malloc(sizeof(history_t));
  1023. e->type = HISTORY_INSERT;
  1024. e->contents.insert_delete_replace.lineno = lineno;
  1025. e->contents.insert_delete_replace.offset = offset;
  1026. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1027. HIST_APPEND(e);
  1028. }
  1029. /* If there is not enough space... */
  1030. if (line->actual == line->available) {
  1031. /* Expand the line buffer */
  1032. if (line->available == 0) {
  1033. line->available = 8;
  1034. } else {
  1035. line->available *= 2;
  1036. }
  1037. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1038. }
  1039. /* If this was not the last character, then shift remaining characters forward. */
  1040. if (offset < line->actual) {
  1041. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1042. }
  1043. /* Insert the new character */
  1044. line->text[offset] = c;
  1045. /* There is one new character in the line */
  1046. line->actual += 1;
  1047. if (!env->loading) {
  1048. line->rev_status = 2; /* Modified */
  1049. recalculate_tabs(line);
  1050. recalculate_syntax(line, lineno);
  1051. }
  1052. return line;
  1053. }
  1054. /**
  1055. * (Primitive) Delete a character from a line.
  1056. *
  1057. * Remove the character at the given offset. We never shrink lines, so this
  1058. * does not have a return value, and delete should never be called during
  1059. * a loading operation (though it may be called during a history replay).
  1060. */
  1061. void line_delete(line_t * line, int offset, int lineno) {
  1062. /* Can't delete character before start of line. */
  1063. if (offset == 0) return;
  1064. /* Can't delete past end of line either */
  1065. if (offset > line->actual) return;
  1066. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1067. history_t * e = malloc(sizeof(history_t));
  1068. e->type = HISTORY_DELETE;
  1069. e->contents.insert_delete_replace.lineno = lineno;
  1070. e->contents.insert_delete_replace.offset = offset;
  1071. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1072. HIST_APPEND(e);
  1073. }
  1074. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1075. if (offset < line->actual) {
  1076. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1077. }
  1078. /* The line is one character shorter */
  1079. line->actual -= 1;
  1080. line->rev_status = 2;
  1081. recalculate_tabs(line);
  1082. recalculate_syntax(line, lineno);
  1083. }
  1084. /**
  1085. * (Primitive) Replace a character in a line.
  1086. *
  1087. * Replaces the codepoint at the given offset with a new character. Since this
  1088. * does not involve any size changes, it does not have a return value.
  1089. * Since a replacement character may be a tab, we do still need to recalculate
  1090. * character widths for tabs as they may change.
  1091. */
  1092. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1093. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1094. history_t * e = malloc(sizeof(history_t));
  1095. e->type = HISTORY_REPLACE;
  1096. e->contents.insert_delete_replace.lineno = lineno;
  1097. e->contents.insert_delete_replace.offset = offset;
  1098. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1099. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1100. HIST_APPEND(e);
  1101. }
  1102. line->text[offset] = _c;
  1103. if (!env->loading) {
  1104. line->rev_status = 2; /* Modified */
  1105. recalculate_tabs(line);
  1106. recalculate_syntax(line, lineno);
  1107. }
  1108. }
  1109. /**
  1110. * (Primitive) Remove a line from the active buffer
  1111. *
  1112. * This primitive is only valid for a buffer. Delete a line, or if this is the
  1113. * only line in the buffer, clear it but keep the line around with no
  1114. * characters. We use the `line_delete` primitive to clear that line,
  1115. * otherwise we are our own primitive and produce history entries.
  1116. *
  1117. * While we do not shrink the `lines` array, it is returned here anyway.
  1118. */
  1119. line_t ** remove_line(line_t ** lines, int offset) {
  1120. /* If there is only one line, clear it instead of removing it. */
  1121. if (env->line_count == 1) {
  1122. while (lines[offset]->actual > 0) {
  1123. line_delete(lines[offset], lines[offset]->actual, offset);
  1124. }
  1125. return lines;
  1126. }
  1127. /* When a line is removed, we need to keep its contents so we
  1128. * can un-remove it on redo... */
  1129. if (!env->loading && global_config.history_enabled) {
  1130. history_t * e = malloc(sizeof(history_t));
  1131. e->type = HISTORY_REMOVE_LINE;
  1132. e->contents.remove_replace_line.lineno = offset;
  1133. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1134. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1135. HIST_APPEND(e);
  1136. }
  1137. /* Otherwise, free the data used by the line */
  1138. free(lines[offset]);
  1139. /* Move other lines up */
  1140. if (offset < env->line_count-1) {
  1141. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1142. lines[env->line_count-1] = NULL;
  1143. }
  1144. /* There is one less line */
  1145. env->line_count -= 1;
  1146. return lines;
  1147. }
  1148. /**
  1149. * (Primitive) Add a new line to the active buffer.
  1150. *
  1151. * Inserts a new line into a buffer at the given line offset.
  1152. * Since this grows the buffer, it will return the new line array
  1153. * after reallocation if needed.
  1154. */
  1155. line_t ** add_line(line_t ** lines, int offset) {
  1156. /* Invalid offset? */
  1157. if (offset > env->line_count) return lines;
  1158. if (!env->loading && global_config.history_enabled) {
  1159. history_t * e = malloc(sizeof(history_t));
  1160. e->type = HISTORY_ADD_LINE;
  1161. e->contents.add_merge_split_lines.lineno = offset;
  1162. HIST_APPEND(e);
  1163. }
  1164. /* Not enough space */
  1165. if (env->line_count == env->line_avail) {
  1166. /* Allocate more space */
  1167. env->line_avail *= 2;
  1168. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1169. }
  1170. /* If this isn't the last line, move other lines down */
  1171. if (offset < env->line_count) {
  1172. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1173. }
  1174. /* Allocate the new line */
  1175. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1176. lines[offset]->available = 32;
  1177. /* There is one new line */
  1178. env->line_count += 1;
  1179. env->lines = lines;
  1180. if (!env->loading) {
  1181. lines[offset]->rev_status = 2; /* Modified */
  1182. }
  1183. if (offset > 0 && !env->loading) {
  1184. recalculate_syntax(lines[offset-1],offset-1);
  1185. }
  1186. return lines;
  1187. }
  1188. /**
  1189. * (Primitive) Replace a line with data from another line.
  1190. *
  1191. * This is only called when pasting yanks after calling `add_line`,
  1192. * but it allows us to have simpler history for that action.
  1193. */
  1194. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1195. if (!env->loading && global_config.history_enabled) {
  1196. history_t * e = malloc(sizeof(history_t));
  1197. e->type = HISTORY_REPLACE_LINE;
  1198. e->contents.remove_replace_line.lineno = offset;
  1199. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1200. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1201. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1202. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1203. HIST_APPEND(e);
  1204. }
  1205. if (lines[offset]->available < replacement->actual) {
  1206. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1207. lines[offset]->available = replacement->available;
  1208. }
  1209. lines[offset]->actual = replacement->actual;
  1210. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1211. if (!env->loading) {
  1212. lines[offset]->rev_status = 2;
  1213. recalculate_syntax(lines[offset],offset);
  1214. }
  1215. }
  1216. /**
  1217. * (Primitive) Merge two consecutive lines.
  1218. *
  1219. * Take two lines in a buffer and turn them into one line.
  1220. * `lineb` is the offset of the second line... or the
  1221. * line number of the first line, depending on which indexing
  1222. * system you prefer to think about. This won't grow `lines`,
  1223. * but it will likely modify it and can reallocate individual
  1224. * lines as well.
  1225. */
  1226. line_t ** merge_lines(line_t ** lines, int lineb) {
  1227. /* linea is the line immediately before lineb */
  1228. int linea = lineb - 1;
  1229. if (!env->loading && global_config.history_enabled) {
  1230. history_t * e = malloc(sizeof(history_t));
  1231. e->type = HISTORY_MERGE_LINES;
  1232. e->contents.add_merge_split_lines.lineno = lineb;
  1233. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1234. HIST_APPEND(e);
  1235. }
  1236. /* If there isn't enough space in linea hold both... */
  1237. if (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1238. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1239. /* ... allocate more space until it fits */
  1240. if (lines[linea]->available == 0) {
  1241. lines[linea]->available = 8;
  1242. } else {
  1243. lines[linea]->available *= 2;
  1244. }
  1245. }
  1246. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1247. }
  1248. /* Copy the second line into the first line */
  1249. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1250. /* The first line is now longer */
  1251. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1252. if (!env->loading) {
  1253. lines[linea]->rev_status = 2;
  1254. recalculate_tabs(lines[linea]);
  1255. recalculate_syntax(lines[linea], linea);
  1256. }
  1257. /* Remove the second line */
  1258. free(lines[lineb]);
  1259. /* Move other lines up */
  1260. if (lineb < env->line_count) {
  1261. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1262. lines[env->line_count-1] = NULL;
  1263. }
  1264. /* There is one less line */
  1265. env->line_count -= 1;
  1266. return lines;
  1267. }
  1268. /**
  1269. * (Primitive) Split a line into two lines at the given column.
  1270. *
  1271. * Takes one line and makes it two lines. There are some optimizations
  1272. * if you are trying to "split" at the first or last column, which
  1273. * are both just treated as add_line.
  1274. */
  1275. line_t ** split_line(line_t ** lines, int line, int split) {
  1276. /* If we're trying to split from the start, just add a new blank line before */
  1277. if (split == 0) {
  1278. return add_line(lines, line);
  1279. }
  1280. if (!env->loading && global_config.history_enabled) {
  1281. history_t * e = malloc(sizeof(history_t));
  1282. e->type = HISTORY_SPLIT_LINE;
  1283. e->contents.add_merge_split_lines.lineno = line;
  1284. e->contents.add_merge_split_lines.split = split;
  1285. HIST_APPEND(e);
  1286. }
  1287. if (!env->loading) {
  1288. unhighlight_matching_paren();
  1289. }
  1290. /* Allocate more space as needed */
  1291. if (env->line_count == env->line_avail) {
  1292. env->line_avail *= 2;
  1293. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1294. }
  1295. /* Shift later lines down */
  1296. if (line < env->line_count) {
  1297. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1298. }
  1299. int remaining = lines[line]->actual - split;
  1300. /* This is some wacky math to get a good power-of-two */
  1301. int v = remaining;
  1302. v--;
  1303. v |= v >> 1;
  1304. v |= v >> 2;
  1305. v |= v >> 4;
  1306. v |= v >> 8;
  1307. v |= v >> 16;
  1308. v++;
  1309. /* Allocate space for the new line */
  1310. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1311. lines[line+1]->available = v;
  1312. lines[line+1]->actual = remaining;
  1313. /* Move the data from the old line into the new line */
  1314. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1315. lines[line]->actual = split;
  1316. if (!env->loading) {
  1317. lines[line]->rev_status = 2;
  1318. lines[line+1]->rev_status = 2;
  1319. recalculate_tabs(lines[line]);
  1320. recalculate_tabs(lines[line+1]);
  1321. recalculate_syntax(lines[line], line);
  1322. recalculate_syntax(lines[line+1], line+1);
  1323. }
  1324. /* There is one new line */
  1325. env->line_count += 1;
  1326. /* We may have reallocated lines */
  1327. return lines;
  1328. }
  1329. /**
  1330. * Primitives end here. Everything after this point that wants to
  1331. * perform modifications must be built on these primitives and
  1332. * should never directly modify env->lines or the contents thereof,
  1333. * outside of syntax highlighting flag changes.
  1334. */
  1335. /**
  1336. * The following section is where we implement "smart" automatic
  1337. * indentation. A lot of this is hacked-together nonsense and "smart"
  1338. * is a bit of an overstatement.
  1339. */
  1340. /**
  1341. * Understand spaces and comments and check if the previous line
  1342. * ended with a brace or a colon.
  1343. */
  1344. int line_ends_with_brace(line_t * line) {
  1345. int i = line->actual-1;
  1346. while (i >= 0) {
  1347. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1348. i--;
  1349. } else {
  1350. break;
  1351. }
  1352. }
  1353. if (i < 0) return 0;
  1354. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':') ? i+1 : 0;
  1355. }
  1356. /**
  1357. * Determine if a given line is a comment by checking its initial
  1358. * syntax highlighting state value. This is used by automatic indentation
  1359. * to continue block comments in languages like C.
  1360. *
  1361. * TODO: Why isn't this a syntax-> method?
  1362. */
  1363. int line_is_comment(line_t * line) {
  1364. if (!env->syntax) return 0;
  1365. if (!strcmp(env->syntax->name,"c")) {
  1366. if (line->istate == 1) return 1;
  1367. } else if (!strcmp(env->syntax->name,"java")) {
  1368. if (line->istate == 1) return 1;
  1369. } else if (!strcmp(env->syntax->name,"kotlin")) {
  1370. if (line->istate == 1) return 1;
  1371. } else if (!strcmp(env->syntax->name,"rust")) {
  1372. if (line->istate > 0) return 1;
  1373. }
  1374. return 0;
  1375. }
  1376. /**
  1377. * Figure out where the indentation for a brace belongs by finding
  1378. * where the start of the line is after whitespace. This is called
  1379. * by default when we insert } and tries to align it with the indentation
  1380. * of the matching opening {.
  1381. */
  1382. int find_brace_line_start(int line, int col) {
  1383. int ncol = col - 1;
  1384. while (ncol > 0) {
  1385. if (env->lines[line-1]->text[ncol-1].codepoint == ')') {
  1386. int t_line_no = env->line_no;
  1387. int t_col_no = env->col_no;
  1388. env->line_no = line;
  1389. env->col_no = ncol;
  1390. int paren_match_line = -1, paren_match_col = -1;
  1391. find_matching_paren(&paren_match_line, &paren_match_col, 1);
  1392. if (paren_match_line != -1) {
  1393. line = paren_match_line;
  1394. }
  1395. env->line_no = t_line_no;
  1396. env->col_no = t_col_no;
  1397. break;
  1398. } else if (env->lines[line-1]->text[ncol-1].codepoint == ' ') {
  1399. ncol--;
  1400. } else {
  1401. break;
  1402. }
  1403. }
  1404. return line;
  1405. }
  1406. /**
  1407. * Add indentation from the previous (temporally) line.
  1408. *
  1409. * By "temporally", we mean not necessarily the line above, but
  1410. * potentially the line below if we are inserting a line above
  1411. * the cursor.
  1412. */
  1413. void add_indent(int new_line, int old_line, int ignore_brace) {
  1414. if (env->indent) {
  1415. int changed = 0;
  1416. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1417. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1418. if (env->lines[old_line]->text[i].codepoint == '/') {
  1419. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1420. /* Insert ' * ' */
  1421. char_t space = {1,FLAG_COMMENT,' '};
  1422. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1423. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1424. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1425. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1426. env->col_no += 3;
  1427. }
  1428. break;
  1429. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1430. /* Insert ' * ' */
  1431. char_t space = {1,FLAG_COMMENT,' '};
  1432. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1433. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1434. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1435. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1436. env->col_no += 3;
  1437. break;
  1438. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1439. env->lines[old_line]->text[i].codepoint == '\t' ||
  1440. env->lines[old_line]->text[i].codepoint == '*') {
  1441. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1442. env->col_no++;
  1443. changed = 1;
  1444. } else {
  1445. break;
  1446. }
  1447. }
  1448. } else {
  1449. int line_to_copy_from = old_line;
  1450. int col;
  1451. if (old_line < new_line &&
  1452. !ignore_brace &&
  1453. (col = line_ends_with_brace(env->lines[old_line])) &&
  1454. env->lines[old_line]->text[col-1].codepoint == '{') {
  1455. line_to_copy_from = find_brace_line_start(old_line+1, col)-1;
  1456. }
  1457. for (int i = 0; i < env->lines[line_to_copy_from]->actual; ++i) {
  1458. if (line_to_copy_from < new_line && i == env->lines[line_to_copy_from]->actual - 3 &&
  1459. env->lines[line_to_copy_from]->text[i].codepoint == ' ' &&
  1460. env->lines[line_to_copy_from]->text[i+1].codepoint == '*' &&
  1461. env->lines[line_to_copy_from]->text[i+2].codepoint == '/') {
  1462. break;
  1463. } else if (env->lines[line_to_copy_from]->text[i].codepoint == ' ' ||
  1464. env->lines[line_to_copy_from]->text[i].codepoint == '\t') {
  1465. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[line_to_copy_from]->text[i],i,new_line);
  1466. env->col_no++;
  1467. changed = 1;
  1468. } else {
  1469. break;
  1470. }
  1471. }
  1472. }
  1473. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1474. if (env->tabs) {
  1475. char_t c = {0};
  1476. c.codepoint = '\t';
  1477. c.display_width = env->tabstop;
  1478. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1479. env->col_no++;
  1480. changed = 1;
  1481. } else {
  1482. for (int j = 0; j < env->tabstop; ++j) {
  1483. char_t c = {0};
  1484. c.codepoint = ' ';
  1485. c.display_width = 1;
  1486. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1487. env->col_no++;
  1488. }
  1489. changed = 1;
  1490. }
  1491. }
  1492. int was_whitespace = 1;
  1493. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1494. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1495. env->lines[old_line]->text[i].codepoint != '\t') {
  1496. was_whitespace = 0;
  1497. break;
  1498. }
  1499. }
  1500. if (was_whitespace) {
  1501. while (env->lines[old_line]->actual) {
  1502. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1503. }
  1504. }
  1505. if (changed) {
  1506. recalculate_syntax(env->lines[new_line],new_line);
  1507. }
  1508. }
  1509. }
  1510. /**
  1511. * Initialize a buffer with default values.
  1512. *
  1513. * Should be called after creating a buffer.
  1514. */
  1515. void setup_buffer(buffer_t * env) {
  1516. /* If this buffer was already initialized, clear out its line data */
  1517. if (env->lines) {
  1518. for (int i = 0; i < env->line_count; ++i) {
  1519. free(env->lines[i]);
  1520. }
  1521. free(env->lines);
  1522. }
  1523. /* Default state parameters */
  1524. env->line_no = 1; /* Default cursor position */
  1525. env->col_no = 1;
  1526. env->line_count = 1; /* Buffers always have at least one line */
  1527. env->modified = 0;
  1528. env->readonly = 0;
  1529. env->offset = 0;
  1530. env->line_avail = 8; /* Default line buffer capacity */
  1531. env->tabs = 1; /* Tabs by default */
  1532. env->tabstop = 4; /* Tab stop width */
  1533. env->indent = 1; /* Auto-indent by default */
  1534. env->history = malloc(sizeof(struct history));
  1535. memset(env->history, 0, sizeof(struct history));
  1536. env->last_save_history = env->history;
  1537. /* Allocate line buffer */
  1538. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1539. /* Initialize the first line */
  1540. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1541. env->lines[0]->available = 32;
  1542. }
  1543. /**
  1544. * Toggle buffered / unbuffered modes
  1545. */
  1546. struct termios old;
  1547. void get_initial_termios(void) {
  1548. tcgetattr(STDOUT_FILENO, &old);
  1549. }
  1550. void set_unbuffered(void) {
  1551. struct termios new = old;
  1552. new.c_iflag &= (~ICRNL) & (~IXON);
  1553. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1554. #ifdef VLNEXT
  1555. new.c_cc[VLNEXT] = 0;
  1556. #endif
  1557. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1558. }
  1559. void set_buffered(void) {
  1560. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1561. }
  1562. /**
  1563. * Convert codepoint to utf-8 string
  1564. */
  1565. int to_eight(uint32_t codepoint, char * out) {
  1566. memset(out, 0x00, 7);
  1567. if (codepoint < 0x0080) {
  1568. out[0] = (char)codepoint;
  1569. } else if (codepoint < 0x0800) {
  1570. out[0] = 0xC0 | (codepoint >> 6);
  1571. out[1] = 0x80 | (codepoint & 0x3F);
  1572. } else if (codepoint < 0x10000) {
  1573. out[0] = 0xE0 | (codepoint >> 12);
  1574. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1575. out[2] = 0x80 | (codepoint & 0x3F);
  1576. } else if (codepoint < 0x200000) {
  1577. out[0] = 0xF0 | (codepoint >> 18);
  1578. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1579. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1580. out[3] = 0x80 | ((codepoint) & 0x3F);
  1581. } else if (codepoint < 0x4000000) {
  1582. out[0] = 0xF8 | (codepoint >> 24);
  1583. out[1] = 0x80 | (codepoint >> 18);
  1584. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1585. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1586. out[4] = 0x80 | ((codepoint) & 0x3F);
  1587. } else {
  1588. out[0] = 0xF8 | (codepoint >> 30);
  1589. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1590. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1591. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1592. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1593. out[5] = 0x80 | ((codepoint) & 0x3F);
  1594. }
  1595. return strlen(out);
  1596. }
  1597. /**
  1598. * Get the presentation width of a codepoint
  1599. */
  1600. int codepoint_width(wchar_t codepoint) {
  1601. if (codepoint == '\t') {
  1602. return 1; /* Recalculate later */
  1603. }
  1604. if (codepoint < 32) {
  1605. /* We render these as ^@ */
  1606. return 2;
  1607. }
  1608. if (codepoint == 0x7F) {
  1609. /* Renders as ^? */
  1610. return 2;
  1611. }
  1612. if (codepoint > 0x7f && codepoint < 0xa0) {
  1613. /* Upper control bytes <xx> */
  1614. return 4;
  1615. }
  1616. if (codepoint == 0xa0) {
  1617. /* Non-breaking space _ */
  1618. return 1;
  1619. }
  1620. /* Skip wcwidth for anything under 256 */
  1621. if (codepoint > 127) {
  1622. if (global_config.can_unicode) {
  1623. /* Higher codepoints may be wider (eg. Japanese) */
  1624. int out = wcwidth(codepoint);
  1625. if (out >= 1) return out;
  1626. }
  1627. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1628. return (codepoint < 0x10000) ? 8 : 10;
  1629. }
  1630. return 1;
  1631. }
  1632. /**
  1633. * The following section contains methods for crafting terminal escapes
  1634. * for rendering the display. We do not use curses or any similar
  1635. * library, so we have to generate these sequences ourself based on
  1636. * some assumptions about the target terminal.
  1637. */
  1638. /**
  1639. * Move the terminal cursor
  1640. */
  1641. void place_cursor(int x, int y) {
  1642. printf("\033[%d;%dH", y, x);
  1643. }
  1644. /**
  1645. * Given two color codes from a theme, convert them to an escape
  1646. * sequence to set the foreground and background color. This allows
  1647. * us to support basic 16, xterm 256, and true color in themes.
  1648. */
  1649. char * color_string(const char * fg, const char * bg) {
  1650. static char output[100];
  1651. char * t = output;
  1652. t += sprintf(t,"\033[22;23;");
  1653. if (*bg == '@') {
  1654. int _bg = atoi(bg+1);
  1655. if (_bg < 10) {
  1656. t += sprintf(t, "4%d;", _bg);
  1657. } else {
  1658. t += sprintf(t, "10%d;", _bg-10);
  1659. }
  1660. } else {
  1661. t += sprintf(t, "48;%s;", bg);
  1662. }
  1663. if (*fg == '@') {
  1664. int _fg = atoi(fg+1);
  1665. if (_fg < 10) {
  1666. t += sprintf(t, "3%dm", _fg);
  1667. } else {
  1668. t += sprintf(t, "9%dm", _fg-10);
  1669. }
  1670. } else {
  1671. t += sprintf(t, "38;%sm", fg);
  1672. }
  1673. return output;
  1674. }
  1675. /**
  1676. * Set text colors
  1677. *
  1678. * Normally, text colors are just strings, but if they
  1679. * start with @ they will be parsed as integers
  1680. * representing one of the 16 standard colors, suitable
  1681. * for terminals without support for the 256- or 24-bit
  1682. * color modes.
  1683. */
  1684. void set_colors(const char * fg, const char * bg) {
  1685. printf("%s", color_string(fg, bg));
  1686. }
  1687. /**
  1688. * Set just the foreground color
  1689. *
  1690. * (See set_colors above)
  1691. */
  1692. void set_fg_color(const char * fg) {
  1693. printf("\033[22;23;");
  1694. if (*fg == '@') {
  1695. int _fg = atoi(fg+1);
  1696. if (_fg < 10) {
  1697. printf("3%dm", _fg);
  1698. } else {
  1699. printf("9%dm", _fg-10);
  1700. }
  1701. } else {
  1702. printf("38;%sm", fg);
  1703. }
  1704. }
  1705. /**
  1706. * Clear the rest of this line
  1707. */
  1708. void clear_to_end(void) {
  1709. if (global_config.can_bce) {
  1710. printf("\033[K");
  1711. }
  1712. }
  1713. /**
  1714. * For terminals without bce, prepaint the whole line, so we don't have to track
  1715. * where the cursor is for everything. Inefficient, but effective.
  1716. */
  1717. void paint_line(const char * bg) {
  1718. if (!global_config.can_bce) {
  1719. set_colors(COLOR_FG, bg);
  1720. for (int i = 0; i < global_config.term_width; ++i) {
  1721. printf(" ");
  1722. }
  1723. printf("\r");
  1724. }
  1725. }
  1726. /**
  1727. * Enable bold text display
  1728. */
  1729. void set_bold(void) {
  1730. printf("\033[1m");
  1731. }
  1732. /**
  1733. * Disable bold
  1734. */
  1735. void unset_bold(void) {
  1736. printf("\033[22m");
  1737. }
  1738. /**
  1739. * Enable underlined text display
  1740. */
  1741. void set_underline(void) {
  1742. printf("\033[4m");
  1743. }
  1744. /**
  1745. * Disable underlined text display
  1746. */
  1747. void unset_underline(void) {
  1748. printf("\033[24m");
  1749. }
  1750. /**
  1751. * Reset text display attributes
  1752. */
  1753. void reset(void) {
  1754. printf("\033[0m");
  1755. }
  1756. /**
  1757. * Clear the entire screen
  1758. */
  1759. void clear_screen(void) {
  1760. printf("\033[H\033[2J");
  1761. }
  1762. /**
  1763. * Hide the cursor
  1764. */
  1765. void hide_cursor(void) {
  1766. if (global_config.can_hideshow) {
  1767. printf("\033[?25l");
  1768. }
  1769. }
  1770. /**
  1771. * Show the cursor
  1772. */
  1773. void show_cursor(void) {
  1774. if (global_config.can_hideshow) {
  1775. printf("\033[?25h");
  1776. }
  1777. }
  1778. /**
  1779. * Store the cursor position
  1780. */
  1781. void store_cursor(void) {
  1782. printf("\0337");
  1783. }
  1784. /**
  1785. * Restore the cursor position.
  1786. */
  1787. void restore_cursor(void) {
  1788. printf("\0338");
  1789. }
  1790. /**
  1791. * Request mouse events
  1792. */
  1793. void mouse_enable(void) {
  1794. if (global_config.can_mouse) {
  1795. printf("\033[?1000h");
  1796. if (global_config.can_sgrmouse) {
  1797. printf("\033[?1006h");
  1798. }
  1799. }
  1800. }
  1801. /**
  1802. * Stop mouse events
  1803. */
  1804. void mouse_disable(void) {
  1805. if (global_config.can_mouse) {
  1806. if (global_config.can_sgrmouse) {
  1807. printf("\033[?1006l");
  1808. }
  1809. printf("\033[?1000l");
  1810. }
  1811. }
  1812. /**
  1813. * Shift the screen up one line
  1814. */
  1815. void shift_up(int amount) {
  1816. printf("\033[%dS", amount);
  1817. }
  1818. /**
  1819. * Shift the screen down one line.
  1820. */
  1821. void shift_down(int amount) {
  1822. printf("\033[%dT", amount);
  1823. }
  1824. void insert_lines_at(int line, int count) {
  1825. place_cursor(1, line);
  1826. printf("\033[%dL", count);
  1827. }
  1828. void delete_lines_at(int line, int count) {
  1829. place_cursor(1, line);
  1830. printf("\033[%dM", count);
  1831. }
  1832. /**
  1833. * Switch to the alternate terminal screen.
  1834. */
  1835. void set_alternate_screen(void) {
  1836. if (global_config.can_altscreen) {
  1837. printf("\033[?1049h");
  1838. }
  1839. }
  1840. /**
  1841. * Restore the standard terminal screen.
  1842. */
  1843. void unset_alternate_screen(void) {
  1844. if (global_config.can_altscreen) {
  1845. printf("\033[?1049l");
  1846. }
  1847. }
  1848. /**
  1849. * Enable bracketed paste mode.
  1850. */
  1851. void set_bracketed_paste(void) {
  1852. if (global_config.can_bracketedpaste) {
  1853. printf("\033[?2004h");
  1854. }
  1855. }
  1856. /**
  1857. * Disable bracketed paste mode.
  1858. */
  1859. void unset_bracketed_paste(void) {
  1860. if (global_config.can_bracketedpaste) {
  1861. printf("\033[?2004l");
  1862. }
  1863. }
  1864. /**
  1865. * Get the name of just a file from a full path.
  1866. * Returns a pointer within the original string.
  1867. *
  1868. * Called in a few different places where the name of a file
  1869. * is needed from its full path, such as drawing tab names or
  1870. * building HTML files.
  1871. */
  1872. char * file_basename(char * file) {
  1873. char * c = strrchr(file, '/');
  1874. if (!c) return file;
  1875. return (c+1);
  1876. }
  1877. /**
  1878. * Print a tab name with fixed width and modifiers
  1879. * into an output buffer and return the written width.
  1880. */
  1881. int draw_tab_name(buffer_t * _env, char * out, int max_width, int * width) {
  1882. uint32_t c, state = 0;
  1883. char * t = _env->file_name ? file_basename(_env->file_name) : "[No Name]";
  1884. #define ADD(c) do { \
  1885. *o = c; \
  1886. o++; \
  1887. *o = '\0'; \
  1888. bytes++; \
  1889. } while (0)
  1890. char * o = out;
  1891. *o = '\0';
  1892. int bytes = 0;
  1893. if (max_width < 2) return 1;
  1894. ADD(' ');
  1895. (*width)++;
  1896. if (_env->modified) {
  1897. if (max_width < 4) return 1;
  1898. ADD('+');
  1899. (*width)++;
  1900. ADD(' ');
  1901. (*width)++;
  1902. }
  1903. while (*t) {
  1904. /* File names can definitely by UTF-8, and we need to
  1905. * understand their display width... */
  1906. if (!decode(&state, &c, (unsigned char)*t)) {
  1907. /* But our displayed tab name is also just stored
  1908. * as UTF-8 again, so we essentially rebuild it... */
  1909. char tmp[7];
  1910. int size = to_eight(c, tmp);
  1911. if (bytes + size > 62) break;
  1912. if (*width + size >= max_width) return 1;
  1913. for (int i = 0; i < size; ++i) {
  1914. ADD(tmp[i]);
  1915. }
  1916. (*width) += codepoint_width(c);
  1917. } else if (state == UTF8_REJECT) {
  1918. state = 0;
  1919. }
  1920. t++;
  1921. }
  1922. if (max_width == *width + 1) return 1;
  1923. ADD(' ');
  1924. (*width)++;
  1925. #undef ADD
  1926. return 0;
  1927. }
  1928. /**
  1929. * Redraw the tabbar, with a tab for each buffer.
  1930. *
  1931. * The active buffer is highlighted.
  1932. */
  1933. void redraw_tabbar(void) {
  1934. if (!global_config.tabs_visible) return;
  1935. /* Hide cursor while rendering UI */
  1936. hide_cursor();
  1937. /* Move to upper left */
  1938. place_cursor(1,1);
  1939. paint_line(COLOR_TABBAR_BG);
  1940. /* For each buffer... */
  1941. int offset = 0;
  1942. if (global_config.tab_offset) {
  1943. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  1944. printf("<");
  1945. offset++;
  1946. }
  1947. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  1948. buffer_t * _env = buffers[i];
  1949. if (_env == env) {
  1950. /* If this is the active buffer, highlight it */
  1951. reset();
  1952. set_colors(COLOR_FG, COLOR_BG);
  1953. set_bold();
  1954. } else {
  1955. /* Otherwise use default tab color */
  1956. reset();
  1957. set_colors(COLOR_FG, COLOR_TAB_BG);
  1958. set_underline();
  1959. }
  1960. if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  1961. if (global_config.command_buffer->actual) {
  1962. char * f = _env->file_name ? file_basename(_env->file_name) : "";
  1963. /* TODO: Support unicode input here; needs conversion */
  1964. int i = 0;
  1965. for (; i < global_config.command_buffer->actual &&
  1966. f[i] == global_config.command_buffer->text[i].codepoint; ++i);
  1967. if (global_config.command_buffer->actual == i) {
  1968. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  1969. }
  1970. }
  1971. }
  1972. char title[64];
  1973. int size = 0;
  1974. int filled = draw_tab_name(_env, title, global_config.term_width - offset, &size);
  1975. if (filled) {
  1976. offset += size;
  1977. printf("%s", title);
  1978. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  1979. while (offset != global_config.term_width - 1) {
  1980. printf(" ");
  1981. offset++;
  1982. }
  1983. printf(">");
  1984. break;
  1985. }
  1986. printf("%s", title);
  1987. offset += size;
  1988. }
  1989. /* Reset bold/underline */
  1990. reset();
  1991. /* Fill the rest of the tab bar */
  1992. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  1993. clear_to_end();
  1994. }
  1995. /**
  1996. * Braindead log10 implementation for figuring out the width of the
  1997. * line number column.
  1998. */
  1999. int log_base_10(unsigned int v) {
  2000. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2001. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2002. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2003. return r;
  2004. }
  2005. /**
  2006. * Render a line of text.
  2007. *
  2008. * This handles rendering the actual text content. A full line of text
  2009. * also includes a line number and some padding, but those elements
  2010. * are rendered elsewhere; this method can be used for lines that are
  2011. * not attached to a buffer such as command input lines.
  2012. *
  2013. * width: width of the text display region (term width - line number width)
  2014. * offset: how many cells into the line to start rendering at
  2015. */
  2016. void render_line(line_t * line, int width, int offset, int line_no) {
  2017. int i = 0; /* Offset in char_t line data entries */
  2018. int j = 0; /* Offset in terminal cells */
  2019. const char * last_color = NULL;
  2020. int was_selecting = 0, was_searching = 0, was_underlining = 0;
  2021. /* Set default text colors */
  2022. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2023. /*
  2024. * When we are rendering in the middle of a wide character,
  2025. * we render -'s to fill the remaining amount of the character's width.
  2026. */
  2027. int remainder = 0;
  2028. int is_spaces = 1;
  2029. /* For each character in the line ... */
  2030. while (i < line->actual) {
  2031. /* If there is remaining text... */
  2032. if (remainder) {
  2033. /* If we should be drawing by now... */
  2034. if (j >= offset) {
  2035. if (was_underlining) printf("\033[24m");
  2036. /* Fill remainder with -'s */
  2037. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2038. printf("-");
  2039. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2040. }
  2041. /* One less remaining width cell to fill */
  2042. remainder--;
  2043. /* Terminal offset moves forward */
  2044. j++;
  2045. /*
  2046. * If this was the last remaining character, move to
  2047. * the next codepoint in the line
  2048. */
  2049. if (remainder == 0) {
  2050. i++;
  2051. }
  2052. continue;
  2053. }
  2054. /* Get the next character to draw */
  2055. char_t c = line->text[i];
  2056. if (c.codepoint != ' ') is_spaces = 0;
  2057. /* If we should be drawing by now... */
  2058. if (j >= offset) {
  2059. /* If this character is going to fall off the edge of the screen... */
  2060. if (j - offset + c.display_width >= width) {
  2061. /* We draw this with special colors so it isn't ambiguous */
  2062. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2063. if (was_underlining) printf("\033[24m");
  2064. /* If it's wide, draw ---> as needed */
  2065. while (j - offset < width - 1) {
  2066. printf("-");
  2067. j++;
  2068. }
  2069. /* End the line with a > to show it overflows */
  2070. printf(">");
  2071. set_colors(COLOR_FG, COLOR_BG);
  2072. return;
  2073. }
  2074. /* Syntax highlighting */
  2075. const char * color = flag_to_color(c.flags);
  2076. if (c.flags & FLAG_SELECT) {
  2077. if ((c.flags & FLAG_MASK_COLORS) == FLAG_NONE) color = COLOR_SELECTFG;
  2078. set_colors(color, COLOR_SELECTBG);
  2079. was_selecting = 1;
  2080. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2081. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2082. was_searching = 1;
  2083. } else if (c.flags == FLAG_ERROR) {
  2084. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2085. was_searching = 1; /* co-opting this should work... */
  2086. } else {
  2087. if (was_selecting || was_searching) {
  2088. was_selecting = 0;
  2089. was_searching = 0;
  2090. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2091. last_color = color;
  2092. } else if (!last_color || strcmp(color, last_color)) {
  2093. set_fg_color(color);
  2094. last_color = color;
  2095. }
  2096. }
  2097. if ((c.flags & FLAG_UNDERLINE) && !was_underlining) {
  2098. printf("\033[4m");
  2099. was_underlining = 1;
  2100. } else if (!(c.flags & FLAG_UNDERLINE) && was_underlining) {
  2101. printf("\033[24m");
  2102. was_underlining = 0;
  2103. }
  2104. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2105. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2106. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2107. ((j == env->sel_col) ||
  2108. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2109. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2110. was_selecting = 1;
  2111. }
  2112. #define _set_colors(fg,bg) \
  2113. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2114. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2115. }
  2116. /* Render special characters */
  2117. if (c.codepoint == '\t') {
  2118. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2119. printf("%s", global_config.tab_indicator);
  2120. for (int i = 1; i < c.display_width; ++i) {
  2121. printf("%s" ,global_config.space_indicator);
  2122. }
  2123. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2124. } else if (c.codepoint < 32) {
  2125. /* Codepoints under 32 to get converted to ^@ escapes */
  2126. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2127. printf("^%c", '@' + c.codepoint);
  2128. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2129. } else if (c.codepoint == 0x7f) {
  2130. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2131. printf("^?");
  2132. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2133. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2134. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2135. printf("<%2x>", c.codepoint);
  2136. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2137. } else if (c.codepoint == 0xa0) {
  2138. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2139. printf("_");
  2140. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2141. } else if (c.display_width == 8) {
  2142. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2143. printf("[U+%04x]", c.codepoint);
  2144. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2145. } else if (c.display_width == 10) {
  2146. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2147. printf("[U+%06x]", c.codepoint);
  2148. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2149. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2150. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2151. if (global_config.can_unicode) {
  2152. printf("▏");
  2153. } else {
  2154. printf("|");
  2155. }
  2156. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2157. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2158. /* Special case: space at end of line */
  2159. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2160. printf("%s",global_config.space_indicator);
  2161. _set_colors(COLOR_FG, COLOR_BG);
  2162. } else {
  2163. /* Normal characters get output */
  2164. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2165. to_eight(c.codepoint, tmp);
  2166. printf("%s", tmp);
  2167. }
  2168. /* Advance the terminal cell offset by the render width of this character */
  2169. j += c.display_width;
  2170. /* Advance to the next character */
  2171. i++;
  2172. } else if (c.display_width > 1) {
  2173. /*
  2174. * If this is a wide character but we aren't ready to render yet,
  2175. * we may need to draw some filler text for the remainder of its
  2176. * width to ensure we don't jump around when horizontally scrolling
  2177. * past wide characters.
  2178. */
  2179. remainder = c.display_width - 1;
  2180. j++;
  2181. } else {
  2182. /* Regular character, not ready to draw, advance without doing anything */
  2183. j++;
  2184. i++;
  2185. }
  2186. }
  2187. if (was_underlining) printf("\033[24m");
  2188. /**
  2189. * Determine what color the rest of the line should be.
  2190. */
  2191. if (env->mode != MODE_LINE_SELECTION) {
  2192. /* If we are not selecting, then use the normal background or highlight
  2193. * the current line if that feature is enabled. */
  2194. if (line->is_current) {
  2195. set_colors(COLOR_FG, COLOR_ALT_BG);
  2196. } else {
  2197. set_colors(COLOR_FG, COLOR_BG);
  2198. }
  2199. } else {
  2200. /* If this line was empty but was part of the selection, we didn't
  2201. * set the selection color already, so we need to do that here. */
  2202. if (!line->actual) {
  2203. if (env->line_no == line_no ||
  2204. (env->start_line > env->line_no &&
  2205. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2206. (env->start_line < env->line_no &&
  2207. (line_no >= env->start_line && line_no <= env->line_no))) {
  2208. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2209. }
  2210. }
  2211. }
  2212. /**
  2213. * In column modes, we may need to draw a column select beyond the end
  2214. * of a given line, so we need to draw up to that point first.
  2215. */
  2216. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2217. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2218. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2219. j <= env->sel_col &&
  2220. env->sel_col < width) {
  2221. set_colors(COLOR_FG, COLOR_BG);
  2222. while (j < env->sel_col) {
  2223. printf(" ");
  2224. j++;
  2225. }
  2226. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2227. printf(" ");
  2228. j++;
  2229. set_colors(COLOR_FG, COLOR_BG);
  2230. }
  2231. /*
  2232. * `maxcolumn` renders the background outside of the requested line length
  2233. * in a different color, with a line at the border between the two.
  2234. */
  2235. if (env->maxcolumn && line_no > -1 /* ensures we don't do this for command line */) {
  2236. /* Fill out the normal background */
  2237. if (j < offset) j = offset;
  2238. for (; j < width + offset && j < env->maxcolumn; ++j) {
  2239. printf(" ");
  2240. }
  2241. /* Draw the line */
  2242. if (j < width + offset && j == env->maxcolumn) {
  2243. j++;
  2244. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2245. if (global_config.can_unicode) {
  2246. printf("▏"); /* Should this be configurable? */
  2247. } else {
  2248. printf("|");
  2249. }
  2250. }
  2251. /* Fill the rest with the alternate background color */
  2252. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2253. }
  2254. /**
  2255. * Clear out the rest of the line. If we are the only buffer or the right split,
  2256. * and our terminal supports `bce`, we can just bce; otherwise write spaces
  2257. * until we reach the right side of the screen.
  2258. */
  2259. if (global_config.can_bce && (line_no == -1 || env->left + env->width == global_config.term_width)) {
  2260. clear_to_end();
  2261. } else {
  2262. /* Paint the rest of the line */
  2263. if (j < offset) j = offset;
  2264. for (; j < width + offset; ++j) {
  2265. printf(" ");
  2266. }
  2267. }
  2268. }
  2269. /**
  2270. * Get the width of the line number region
  2271. */
  2272. int num_width(void) {
  2273. if (!env->numbers) return 0;
  2274. int w = log_base_10(env->line_count) + 3;
  2275. if (w < 4) return 4;
  2276. return w;
  2277. }
  2278. /**
  2279. * Display width of the revision status gutter.
  2280. */
  2281. int gutter_width(void) {
  2282. return env->gutter;
  2283. }
  2284. /**
  2285. * Draw the gutter and line numbers.
  2286. */
  2287. void draw_line_number(int x) {
  2288. if (!env->numbers) return;
  2289. /* Draw the line number */
  2290. if (env->lines[x]->is_current) {
  2291. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2292. } else {
  2293. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2294. }
  2295. if (global_config.relative_lines && x+1 != env->line_no) {
  2296. x = x+1 - env->line_no;
  2297. x = ((x < 0) ? -x : x)-1;
  2298. }
  2299. int num_size = num_width() - 2; /* Padding */
  2300. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2301. printf(" ");
  2302. }
  2303. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2304. }
  2305. /**
  2306. * Used to highlight the current line after moving the cursor.
  2307. */
  2308. void recalculate_current_line(void) {
  2309. int something_changed = 0;
  2310. if (global_config.highlight_current_line) {
  2311. for (int i = 0; i < env->line_count; ++i) {
  2312. if (env->lines[i]->is_current && i != env->line_no-1) {
  2313. env->lines[i]->is_current = 0;
  2314. something_changed = 1;
  2315. redraw_line(i);
  2316. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2317. env->lines[i]->is_current = 1;
  2318. something_changed = 1;
  2319. redraw_line(i);
  2320. }
  2321. }
  2322. } else {
  2323. something_changed = 1;
  2324. }
  2325. if (something_changed && global_config.relative_lines) {
  2326. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2327. /* Place cursor for line number */
  2328. place_cursor(1 + gutter_width() + env->left, (i)-env->offset + 1 + global_config.tabs_visible);
  2329. draw_line_number(i);
  2330. }
  2331. }
  2332. }
  2333. /**
  2334. * Redraw line.
  2335. *
  2336. * This draws the line number as well as the actual text.
  2337. */
  2338. void redraw_line(int x) {
  2339. if (env->loading) return;
  2340. /* Determine if this line is visible. */
  2341. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 1 - global_config.tabs_visible) {
  2342. return;
  2343. }
  2344. /* Calculate offset in screen */
  2345. int j = x - env->offset;
  2346. /* Hide cursor when drawing */
  2347. hide_cursor();
  2348. /* Move cursor to upper left most cell of this line */
  2349. place_cursor(1 + env->left,1 + global_config.tabs_visible + j);
  2350. /* Draw a gutter on the left. */
  2351. if (env->gutter) {
  2352. switch (env->lines[x]->rev_status) {
  2353. case 1:
  2354. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2355. printf(" ");
  2356. break;
  2357. case 2:
  2358. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2359. printf(" ");
  2360. break;
  2361. case 3:
  2362. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2363. printf(" ");
  2364. break;
  2365. case 4:
  2366. set_colors(COLOR_ALT_FG, COLOR_RED);
  2367. printf("▆");
  2368. break;
  2369. case 5:
  2370. set_colors(COLOR_KEYWORD, COLOR_RED);
  2371. printf("▆");
  2372. break;
  2373. default:
  2374. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2375. printf(" ");
  2376. break;
  2377. }
  2378. }
  2379. draw_line_number(x);
  2380. int should_shift = x + 1 == env->line_no || global_config.horizontal_shift_scrolling ||
  2381. ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2382. x + 1 >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2383. x + 1 <= ((env->start_line < env->line_no) ? env->line_no : env->start_line));
  2384. /*
  2385. * Draw the line text
  2386. * If this is the active line, the current character cell offset should be used.
  2387. * (Non-active lines are not shifted and always render from the start of the line)
  2388. */
  2389. render_line(env->lines[x], env->width - gutter_width() - num_width(), should_shift ? env->coffset : 0, x+1);
  2390. }
  2391. /**
  2392. * Draw a ~ line where there is no buffer text.
  2393. */
  2394. void draw_excess_line(int j) {
  2395. place_cursor(1+env->left,1 + global_config.tabs_visible + j);
  2396. paint_line(COLOR_ALT_BG);
  2397. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2398. printf("~");
  2399. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2400. clear_to_end();
  2401. } else {
  2402. /* Paint the rest of the line */
  2403. for (int x = 1; x < env->width; ++x) {
  2404. printf(" ");
  2405. }
  2406. }
  2407. }
  2408. /**
  2409. * Redraw the entire text area
  2410. */
  2411. void redraw_text(void) {
  2412. if (!env) return;
  2413. if (!global_config.has_terminal) return;
  2414. /* Hide cursor while rendering */
  2415. hide_cursor();
  2416. /* Figure out the available size of the text region */
  2417. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  2418. int j = 0;
  2419. /* Draw each line */
  2420. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2421. redraw_line(x);
  2422. j++;
  2423. }
  2424. /* Draw the rest of the text region as ~ lines */
  2425. for (; j < l; ++j) {
  2426. draw_excess_line(j);
  2427. }
  2428. }
  2429. static int view_left_offset = 0;
  2430. static int view_right_offset = 0;
  2431. /**
  2432. * When in split view, draw the other buffer.
  2433. * Has special handling for when the split is
  2434. * on a single buffer.
  2435. */
  2436. void redraw_alt_buffer(buffer_t * buf) {
  2437. if (left_buffer == right_buffer) {
  2438. /* draw the opposite view */
  2439. int left, width, offset;
  2440. left = env->left;
  2441. width = env->width;
  2442. offset = env->offset;
  2443. if (left == 0) {
  2444. /* Draw the right side */
  2445. env->left = width;
  2446. env->width = global_config.term_width - width;
  2447. env->offset = view_right_offset;
  2448. view_left_offset = offset;
  2449. } else {
  2450. env->left = 0;
  2451. env->width = global_config.term_width * global_config.split_percent / 100;
  2452. env->offset = view_left_offset;
  2453. view_right_offset = offset;
  2454. }
  2455. redraw_text();
  2456. env->left = left;
  2457. env->width = width;
  2458. env->offset = offset;
  2459. }
  2460. /* Swap out active buffer */
  2461. buffer_t * tmp = env;
  2462. env = buf;
  2463. /* Redraw text */
  2464. redraw_text();
  2465. /* Return original active buffer */
  2466. env = tmp;
  2467. }
  2468. /**
  2469. * Basically wcswidth() but implemented internally using our
  2470. * own utf-8 decoder to ensure it works properly.
  2471. */
  2472. int display_width_of_string(const char * str) {
  2473. uint8_t * s = (uint8_t *)str;
  2474. int out = 0;
  2475. uint32_t c, state = 0;
  2476. while (*s) {
  2477. if (!decode(&state, &c, *s)) {
  2478. out += codepoint_width(c);
  2479. } else if (state == UTF8_REJECT) {
  2480. state = 0;
  2481. }
  2482. s++;
  2483. }
  2484. return out;
  2485. }
  2486. int statusbar_append_status(int *remaining_width, size_t *filled, char * output, char * base, ...) {
  2487. va_list args;
  2488. va_start(args, base);
  2489. char tmp[100] = {0}; /* should be big enough */
  2490. vsnprintf(tmp, 100, base, args);
  2491. va_end(args);
  2492. int width = display_width_of_string(tmp) + 2;
  2493. size_t totalWidth = strlen(tmp);
  2494. totalWidth += strlen(color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2495. totalWidth += strlen(color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2496. totalWidth += strlen(color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2497. totalWidth += 3;
  2498. if (totalWidth + *filled >= 2047) {
  2499. return 0;
  2500. }
  2501. if (width < *remaining_width) {
  2502. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2503. strcat(output,"[");
  2504. strcat(output,color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2505. strcat(output, tmp);
  2506. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2507. strcat(output,"]");
  2508. (*remaining_width) -= width;
  2509. (*filled) += totalWidth;
  2510. return width;
  2511. } else {
  2512. return 0;
  2513. }
  2514. }
  2515. int statusbar_build_right(char * right_hand) {
  2516. char tmp[1024] = {0};
  2517. sprintf(tmp, " Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2518. int out = display_width_of_string(tmp);
  2519. char * s = right_hand;
  2520. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2521. s += sprintf(s, " Line ");
  2522. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2523. s += sprintf(s, "%d/%d ", env->line_no, env->line_count);
  2524. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2525. s += sprintf(s, " Col: ");
  2526. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2527. s += sprintf(s, "%d ", env->col_no);
  2528. return out;
  2529. }
  2530. /**
  2531. * Draw the status bar
  2532. *
  2533. * The status bar shows the name of the file, whether it has modifications,
  2534. * and (in the future) what syntax highlighting mode is enabled.
  2535. *
  2536. * The right side of the status bar shows the line number and column.
  2537. */
  2538. void redraw_statusbar(void) {
  2539. if (global_config.hide_statusbar) return;
  2540. if (!global_config.has_terminal) return;
  2541. if (!env) return;
  2542. /* Hide cursor while rendering */
  2543. hide_cursor();
  2544. /* Move cursor to the status bar line (second from bottom */
  2545. place_cursor(1, global_config.term_height - 1);
  2546. /* Set background colors for status line */
  2547. paint_line(COLOR_STATUS_BG);
  2548. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2549. /* Pre-render the right hand side of the status bar */
  2550. char right_hand[1024] = {0};
  2551. int right_width = statusbar_build_right(right_hand);
  2552. char status_bits[2048] = {0}; /* Sane maximum */
  2553. size_t filled = 0;
  2554. int status_bits_width = 0;
  2555. int remaining_width = global_config.term_width - right_width;
  2556. #define ADD(...) do { status_bits_width += statusbar_append_status(&remaining_width, &filled, status_bits, __VA_ARGS__); } while (0)
  2557. if (env->syntax) {
  2558. ADD("%s",env->syntax->name);
  2559. }
  2560. /* Print file status indicators */
  2561. if (env->modified) {
  2562. ADD("+");
  2563. }
  2564. if (env->readonly) {
  2565. ADD("ro");
  2566. }
  2567. if (env->crnl) {
  2568. ADD("crnl");
  2569. }
  2570. if (env->tabs) {
  2571. ADD("tabs");
  2572. } else {
  2573. ADD("spaces=%d", env->tabstop);
  2574. }
  2575. if (global_config.yanks) {
  2576. ADD("y:%ld", global_config.yank_count);
  2577. }
  2578. if (env->indent) {
  2579. ADD("indent");
  2580. }
  2581. if (global_config.smart_complete) {
  2582. ADD("complete");
  2583. }
  2584. if (global_config.background_task) {
  2585. ADD("working");
  2586. }
  2587. #undef ADD
  2588. uint8_t * file_name = (uint8_t *)(env->file_name ? env->file_name : "[No Name]");
  2589. int file_name_width = display_width_of_string((char*)file_name);
  2590. if (remaining_width > 3) {
  2591. int is_chopped = 0;
  2592. while (remaining_width < file_name_width + 3) {
  2593. is_chopped = 1;
  2594. if ((*file_name & 0xc0) == 0xc0) { /* First byte of a multibyte character */
  2595. file_name++;
  2596. while ((*file_name & 0xc0) == 0x80) file_name++;
  2597. } else {
  2598. file_name++;
  2599. }
  2600. file_name_width = display_width_of_string((char*)file_name);
  2601. }
  2602. if (is_chopped) {
  2603. set_colors(COLOR_ALT_FG, COLOR_STATUS_BG);
  2604. printf("<");
  2605. }
  2606. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2607. printf("%s ", file_name);
  2608. }
  2609. printf("%s", status_bits);
  2610. /* Clear the rest of the status bar */
  2611. clear_to_end();
  2612. /* Move the cursor appropriately to draw it */
  2613. place_cursor(global_config.term_width - right_width, global_config.term_height - 1);
  2614. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2615. printf("%s",right_hand);
  2616. }
  2617. /**
  2618. * Redraw the navigation numbers on the right side of the command line
  2619. */
  2620. void redraw_nav_buffer() {
  2621. if (!global_config.has_terminal) return;
  2622. if (nav_buffer) {
  2623. store_cursor();
  2624. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2625. printf("%s", nav_buf);
  2626. clear_to_end();
  2627. restore_cursor();
  2628. }
  2629. }
  2630. /**
  2631. * Draw the command line
  2632. *
  2633. * The command line either has input from the user (:quit, :!make, etc.)
  2634. * or shows the INSERT (or VISUAL in the future) mode name.
  2635. */
  2636. void redraw_commandline(void) {
  2637. if (!global_config.has_terminal) return;
  2638. if (!env) return;
  2639. /* Hide cursor while rendering */
  2640. hide_cursor();
  2641. /* Move cursor to the last line */
  2642. place_cursor(1, global_config.term_height);
  2643. /* Set background color */
  2644. paint_line(COLOR_BG);
  2645. set_colors(COLOR_FG, COLOR_BG);
  2646. /* If we are in an edit mode, note that. */
  2647. if (env->mode == MODE_INSERT) {
  2648. set_bold();
  2649. printf("-- INSERT --");
  2650. clear_to_end();
  2651. unset_bold();
  2652. } else if (env->mode == MODE_LINE_SELECTION) {
  2653. set_bold();
  2654. printf("-- LINE SELECTION -- (%d:%d)",
  2655. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2656. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2657. );
  2658. clear_to_end();
  2659. unset_bold();
  2660. } else if (env->mode == MODE_COL_SELECTION) {
  2661. set_bold();
  2662. printf("-- COL SELECTION -- (%d:%d %d)",
  2663. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2664. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2665. (env->sel_col)
  2666. );
  2667. clear_to_end();
  2668. unset_bold();
  2669. } else if (env->mode == MODE_COL_INSERT) {
  2670. set_bold();
  2671. printf("-- COL INSERT -- (%d:%d %d)",
  2672. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2673. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2674. (env->sel_col)
  2675. );
  2676. clear_to_end();
  2677. unset_bold();
  2678. } else if (env->mode == MODE_REPLACE) {
  2679. set_bold();
  2680. printf("-- REPLACE --");
  2681. clear_to_end();
  2682. unset_bold();
  2683. } else if (env->mode == MODE_CHAR_SELECTION) {
  2684. set_bold();
  2685. printf("-- CHAR SELECTION -- ");
  2686. clear_to_end();
  2687. unset_bold();
  2688. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2689. set_bold();
  2690. printf("-- DIRECTORY BROWSE --");
  2691. clear_to_end();
  2692. unset_bold();
  2693. } else {
  2694. clear_to_end();
  2695. }
  2696. redraw_nav_buffer();
  2697. }
  2698. /**
  2699. * Draw a message on the command line.
  2700. */
  2701. void render_commandline_message(char * message, ...) {
  2702. /* varargs setup */
  2703. va_list args;
  2704. va_start(args, message);
  2705. /* Hide cursor while rendering */
  2706. hide_cursor();
  2707. /* Move cursor to the last line */
  2708. place_cursor(1, global_config.term_height);
  2709. /* Set background color */
  2710. paint_line(COLOR_BG);
  2711. set_colors(COLOR_FG, COLOR_BG);
  2712. vprintf(message, args);
  2713. va_end(args);
  2714. /* Clear the rest of the status bar */
  2715. clear_to_end();
  2716. redraw_nav_buffer();
  2717. }
  2718. BIM_ACTION(redraw_all, 0,
  2719. "Repaint the screen."
  2720. )(void) {
  2721. if (!env) return;
  2722. redraw_tabbar();
  2723. redraw_text();
  2724. if (left_buffer) {
  2725. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2726. }
  2727. redraw_statusbar();
  2728. redraw_commandline();
  2729. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND ||
  2730. global_config.overlay_mode == OVERLAY_MODE_SEARCH ||
  2731. global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  2732. render_command_input_buffer();
  2733. }
  2734. }
  2735. void pause_for_key(void) {
  2736. int c;
  2737. while ((c = bim_getch())== -1);
  2738. bim_unget(c);
  2739. redraw_all();
  2740. }
  2741. /**
  2742. * Redraw all screen elements except the other split view.
  2743. */
  2744. void redraw_most(void) {
  2745. redraw_tabbar();
  2746. redraw_text();
  2747. redraw_statusbar();
  2748. redraw_commandline();
  2749. }
  2750. /**
  2751. * Disable screen splitting.
  2752. */
  2753. void unsplit(void) {
  2754. if (left_buffer) {
  2755. left_buffer->left = 0;
  2756. left_buffer->width = global_config.term_width;
  2757. }
  2758. if (right_buffer) {
  2759. right_buffer->left = 0;
  2760. right_buffer->width = global_config.term_width;
  2761. }
  2762. left_buffer = NULL;
  2763. right_buffer = NULL;
  2764. redraw_all();
  2765. }
  2766. /**
  2767. * Update the terminal title bar
  2768. */
  2769. void update_title(void) {
  2770. if (!global_config.can_title) return;
  2771. char cwd[1024] = {'/',0};
  2772. getcwd(cwd, 1024);
  2773. for (int i = 1; i < 3; ++i) {
  2774. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2775. }
  2776. }
  2777. /**
  2778. * Mark this buffer as modified and
  2779. * redraw the status and tabbar if needed.
  2780. */
  2781. void set_modified(void) {
  2782. /* If it was already marked modified, no need to do anything */
  2783. if (env->modified) return;
  2784. /* Mark as modified */
  2785. env->modified = 1;
  2786. /* Redraw some things */
  2787. update_title();
  2788. redraw_tabbar();
  2789. redraw_statusbar();
  2790. }
  2791. /**
  2792. * Draw a message on the status line
  2793. */
  2794. void render_status_message(char * message, ...) {
  2795. if (!env) return; /* Don't print when there's no active environment; this usually means a bimrc command tried to print something */
  2796. /* varargs setup */
  2797. va_list args;
  2798. va_start(args, message);
  2799. /* Hide cursor while rendering */
  2800. hide_cursor();
  2801. /* Move cursor to the status bar line (second from bottom */
  2802. place_cursor(1, global_config.term_height - 1);
  2803. /* Set background colors for status line */
  2804. paint_line(COLOR_STATUS_BG);
  2805. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2806. /* Process format string */
  2807. vprintf(message, args);
  2808. va_end(args);
  2809. /* Clear the rest of the status bar */
  2810. clear_to_end();
  2811. }
  2812. /**
  2813. * Draw an error message to the command line.
  2814. */
  2815. void render_error(char * message, ...) {
  2816. /* varargs setup */
  2817. va_list args;
  2818. va_start(args, message);
  2819. if (env) {
  2820. /* Hide cursor while rendering */
  2821. hide_cursor();
  2822. /* Move cursor to the command line */
  2823. place_cursor(1, global_config.term_height);
  2824. /* Set appropriate error message colors */
  2825. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2826. /* Draw the message */
  2827. vprintf(message, args);
  2828. va_end(args);
  2829. global_config.had_error = 1;
  2830. } else {
  2831. printf("bim: error during startup: ");
  2832. vprintf(message, args);
  2833. va_end(args);
  2834. printf("\n");
  2835. }
  2836. }
  2837. char * paren_pairs = "()[]{}<>";
  2838. int is_paren(int c) {
  2839. char * p = paren_pairs;
  2840. while (*p) {
  2841. if (c == *p) return 1;
  2842. p++;
  2843. }
  2844. return 0;
  2845. }
  2846. #define _rehighlight_parens() do { \
  2847. if (i < 0 || i >= env->line_count) break; \
  2848. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  2849. if (i == line-1 && j == col-1) { \
  2850. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  2851. continue; \
  2852. } else { \
  2853. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  2854. } \
  2855. } \
  2856. redraw_line(i); \
  2857. } while (0)
  2858. /**
  2859. * If the config option is enabled, find the matching
  2860. * paren character and highlight it with the SELECT
  2861. * colors, clearing out other SELECT values. As we
  2862. * co-opt the SELECT flag, don't do this in selection
  2863. * modes - only in normal and insert modes.
  2864. */
  2865. void highlight_matching_paren(void) {
  2866. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  2867. if (!global_config.highlight_parens) return;
  2868. int line = -1, col = -1;
  2869. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  2870. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  2871. find_matching_paren(&line, &col, 1);
  2872. } 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)) {
  2873. find_matching_paren(&line, &col, 2);
  2874. }
  2875. if (env->highlighting_paren == -1 && line == -1) return;
  2876. if (env->highlighting_paren > 0) {
  2877. int i = env->highlighting_paren - 1;
  2878. _rehighlight_parens();
  2879. }
  2880. if (env->highlighting_paren != line && line != -1) {
  2881. int i = line - 1;
  2882. _rehighlight_parens();
  2883. }
  2884. env->highlighting_paren = line;
  2885. }
  2886. /**
  2887. * Recalculate syntax for the matched paren.
  2888. * Useful when entering selection modes.
  2889. */
  2890. void unhighlight_matching_paren(void) {
  2891. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  2892. for (int i = 0; i < env->line_count; i++) {
  2893. for (int j = 0; j < env->lines[i]->actual; ++j) {
  2894. env->lines[i]->text[j].flags &= ~(FLAG_SELECT);
  2895. }
  2896. }
  2897. env->highlighting_paren = -1;
  2898. }
  2899. }
  2900. /**
  2901. * Move the cursor to the appropriate location based
  2902. * on where it is in the text region.
  2903. *
  2904. * This does some additional math to set the text
  2905. * region horizontal offset.
  2906. */
  2907. void place_cursor_actual(void) {
  2908. /* Invalid positions */
  2909. if (env->line_no < 1) env->line_no = 1;
  2910. if (env->col_no < 1) env->col_no = 1;
  2911. /* Account for the left hand gutter */
  2912. int num_size = num_width() + gutter_width();
  2913. int x = num_size + 1 - env->coffset;
  2914. /* Determine where the cursor is physically */
  2915. for (int i = 0; i < env->col_no - 1; ++i) {
  2916. char_t * c = &env->lines[env->line_no-1]->text[i];
  2917. x += c->display_width;
  2918. }
  2919. /* y is a bit easier to calculate */
  2920. int y = env->line_no - env->offset + 1;
  2921. int needs_redraw = 0;
  2922. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  2923. y++;
  2924. env->offset--;
  2925. needs_redraw = 1;
  2926. }
  2927. while (y > 1 + global_config.term_height - global_config.bottom_size - global_config.cursor_padding - global_config.tabs_visible) {
  2928. y--;
  2929. env->offset++;
  2930. needs_redraw = 1;
  2931. }
  2932. if (needs_redraw) {
  2933. redraw_text();
  2934. redraw_tabbar();
  2935. redraw_statusbar();
  2936. redraw_commandline();
  2937. }
  2938. /* If the cursor has gone off screen to the right... */
  2939. if (x > env->width - 1) {
  2940. /* Adjust the offset appropriately to scroll horizontally */
  2941. int diff = x - (env->width - 1);
  2942. env->coffset += diff;
  2943. x -= diff;
  2944. redraw_text();
  2945. }
  2946. /* Same for scrolling horizontally to the left */
  2947. if (x < num_size + 1) {
  2948. int diff = (num_size + 1) - x;
  2949. env->coffset -= diff;
  2950. x += diff;
  2951. redraw_text();
  2952. }
  2953. highlight_matching_paren();
  2954. recalculate_current_line();
  2955. /* Move the actual terminal cursor */
  2956. place_cursor(x+env->left,y - !global_config.tabs_visible);
  2957. /* Show the cursor */
  2958. show_cursor();
  2959. }
  2960. /**
  2961. * If the screen is split, update the split sizes based
  2962. * on the new terminal width and the user's split_percent setting.
  2963. */
  2964. void update_split_size(void) {
  2965. if (!left_buffer) return;
  2966. if (left_buffer == right_buffer) {
  2967. if (left_buffer->left == 0) {
  2968. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2969. } else {
  2970. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  2971. right_buffer->width = global_config.term_width - right_buffer->left;
  2972. }
  2973. return;
  2974. }
  2975. left_buffer->left = 0;
  2976. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  2977. right_buffer->left = left_buffer->width;
  2978. right_buffer->width = global_config.term_width - left_buffer->width;
  2979. }
  2980. /**
  2981. * Update screen size
  2982. */
  2983. void update_screen_size(void) {
  2984. struct winsize w;
  2985. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  2986. global_config.term_width = w.ws_col;
  2987. global_config.term_height = w.ws_row;
  2988. if (env) {
  2989. if (left_buffer) {
  2990. update_split_size();
  2991. } else if (env != left_buffer && env != right_buffer) {
  2992. env->width = w.ws_col;
  2993. }
  2994. }
  2995. for (int i = 0; i < buffers_len; ++i) {
  2996. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  2997. buffers[i]->width = w.ws_col;
  2998. }
  2999. }
  3000. }
  3001. /**
  3002. * Handle terminal size changes
  3003. */
  3004. void SIGWINCH_handler(int sig) {
  3005. (void)sig;
  3006. update_screen_size();
  3007. redraw_all();
  3008. signal(SIGWINCH, SIGWINCH_handler);
  3009. }
  3010. /**
  3011. * Handle suspend
  3012. */
  3013. void SIGTSTP_handler(int sig) {
  3014. (void)sig;
  3015. mouse_disable();
  3016. set_buffered();
  3017. reset();
  3018. clear_screen();
  3019. show_cursor();
  3020. unset_bracketed_paste();
  3021. unset_alternate_screen();
  3022. fflush(stdout);
  3023. signal(SIGTSTP, SIG_DFL);
  3024. raise(SIGTSTP);
  3025. }
  3026. void SIGCONT_handler(int sig) {
  3027. (void)sig;
  3028. set_alternate_screen();
  3029. set_bracketed_paste();
  3030. set_unbuffered();
  3031. update_screen_size();
  3032. mouse_enable();
  3033. redraw_all();
  3034. update_title();
  3035. signal(SIGCONT, SIGCONT_handler);
  3036. signal(SIGTSTP, SIGTSTP_handler);
  3037. }
  3038. void try_to_center() {
  3039. int half_a_screen = (global_config.term_height - 3) / 2;
  3040. if (half_a_screen < env->line_no) {
  3041. env->offset = env->line_no - half_a_screen;
  3042. } else {
  3043. env->offset = 0;
  3044. }
  3045. }
  3046. BIM_ACTION(suspend, 0,
  3047. "Suspend bim and the rest of the job it was run in."
  3048. )(void) {
  3049. kill(0, SIGTSTP);
  3050. }
  3051. /**
  3052. * Move the cursor to a specific line.
  3053. */
  3054. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  3055. "Jump to the requested line."
  3056. )(int line) {
  3057. if (line == -1) line = env->line_count;
  3058. /* Respect file bounds */
  3059. if (line < 1) line = 1;
  3060. if (line > env->line_count) line = env->line_count;
  3061. /* Move the cursor / text region offsets */
  3062. env->coffset = 0;
  3063. env->line_no = line;
  3064. env->col_no = 1;
  3065. if (!env->loading) {
  3066. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  3067. place_cursor_actual();
  3068. } else {
  3069. try_to_center();
  3070. }
  3071. redraw_most();
  3072. } else {
  3073. try_to_center();
  3074. }
  3075. }
  3076. /**
  3077. * Process (part of) a file and add it to a buffer.
  3078. */
  3079. void add_buffer(uint8_t * buf, int size) {
  3080. for (int i = 0; i < size; ++i) {
  3081. if (!decode(&state, &codepoint_r, buf[i])) {
  3082. uint32_t c = codepoint_r;
  3083. if (c == '\n') {
  3084. 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') {
  3085. env->lines[env->line_no-1]->actual--;
  3086. env->crnl = 1;
  3087. }
  3088. env->lines = add_line(env->lines, env->line_no);
  3089. env->col_no = 1;
  3090. env->line_no += 1;
  3091. } else if (env->crnl && c == '\r') {
  3092. continue;
  3093. } else {
  3094. char_t _c;
  3095. _c.codepoint = (uint32_t)c;
  3096. _c.flags = 0;
  3097. _c.display_width = codepoint_width((wchar_t)c);
  3098. line_t * line = env->lines[env->line_no - 1];
  3099. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3100. if (line != nline) {
  3101. env->lines[env->line_no - 1] = nline;
  3102. }
  3103. env->col_no += 1;
  3104. }
  3105. } else if (state == UTF8_REJECT) {
  3106. state = 0;
  3107. }
  3108. }
  3109. }
  3110. /**
  3111. * Add a raw string to a buffer. Convenience wrapper
  3112. * for add_buffer for nil-terminated strings.
  3113. */
  3114. void add_string(char * string) {
  3115. add_buffer((uint8_t*)string,strlen(string));
  3116. }
  3117. int str_ends_with(const char * haystack, const char * needle) {
  3118. int i = strlen(haystack);
  3119. int j = strlen(needle);
  3120. do {
  3121. if (haystack[i] != needle[j]) return 0;
  3122. if (j == 0) return 1;
  3123. if (i == 0) return 0;
  3124. i--;
  3125. j--;
  3126. } while (1);
  3127. }
  3128. /**
  3129. * Find a syntax highlighter for the given filename.
  3130. */
  3131. struct syntax_definition * match_syntax(char * file) {
  3132. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3133. for (char ** ext = s->ext; *ext; ++ext) {
  3134. if (str_ends_with(file, *ext)) return s;
  3135. }
  3136. }
  3137. return NULL;
  3138. }
  3139. /**
  3140. * Set the syntax configuration by the name of the syntax highlighter.
  3141. */
  3142. void set_syntax_by_name(const char * name) {
  3143. if (!strcmp(name,"none")) {
  3144. for (int i = 0; i < env->line_count; ++i) {
  3145. env->lines[i]->istate = -1;
  3146. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3147. env->lines[i]->text[j].flags &= (3 << 5);
  3148. }
  3149. }
  3150. env->syntax = NULL;
  3151. redraw_all();
  3152. return;
  3153. }
  3154. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3155. if (!strcmp(name,s->name)) {
  3156. env->syntax = s;
  3157. for (int i = 0; i < env->line_count; ++i) {
  3158. env->lines[i]->istate = -1;
  3159. }
  3160. schedule_complete_recalc();
  3161. redraw_all();
  3162. return;
  3163. }
  3164. }
  3165. render_error("unrecognized syntax type");
  3166. }
  3167. /**
  3168. * Check if a string is all numbers.
  3169. */
  3170. int is_all_numbers(const char * c) {
  3171. while (*c) {
  3172. if (!isdigit(*c)) return 0;
  3173. c++;
  3174. }
  3175. return 1;
  3176. }
  3177. struct file_listing {
  3178. int type;
  3179. char * filename;
  3180. };
  3181. int sort_files(const void * a, const void * b) {
  3182. struct file_listing * _a = (struct file_listing *)a;
  3183. struct file_listing * _b = (struct file_listing *)b;
  3184. if (_a->type == _b->type) {
  3185. return strcmp(_a->filename, _b->filename);
  3186. } else {
  3187. return _a->type - _b->type;
  3188. }
  3189. }
  3190. void read_directory_into_buffer(char * file) {
  3191. DIR * dirp = opendir(file);
  3192. if (!dirp) {
  3193. env->loading = 0;
  3194. return;
  3195. }
  3196. add_string("# Directory listing for `");
  3197. add_string(file);
  3198. add_string("`\n");
  3199. /* Flexible array to hold directory contents */
  3200. int available = 32;
  3201. int count = 0;
  3202. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3203. /* Read directory */
  3204. struct dirent * ent = readdir(dirp);
  3205. while (ent) {
  3206. struct stat statbuf;
  3207. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3208. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3209. stat(tmp, &statbuf);
  3210. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3211. if (count + 1 == available) {
  3212. available *= 2; \
  3213. files = realloc(files, sizeof(struct file_listing) * available); \
  3214. } \
  3215. files[count].type = type;
  3216. files[count].filename = strdup(ent->d_name);
  3217. count++;
  3218. ent = readdir(dirp);
  3219. free(tmp);
  3220. }
  3221. closedir(dirp);
  3222. /* Sort directory entries */
  3223. qsort(files, count, sizeof(struct file_listing), sort_files);
  3224. for (int i = 0; i < count; ++i) {
  3225. add_string(files[i].type == 'd' ? "d" : "f");
  3226. add_string(" ");
  3227. add_string(files[i].filename);
  3228. add_string("\n");
  3229. free(files[i].filename);
  3230. }
  3231. free(files);
  3232. env->file_name = strdup(file);
  3233. env->syntax = find_syntax_calculator("dirent");
  3234. schedule_complete_recalc();
  3235. env->readonly = 1;
  3236. env->loading = 0;
  3237. env->mode = MODE_DIRECTORY_BROWSE;
  3238. env->line_no = 1;
  3239. redraw_all();
  3240. }
  3241. BIM_ACTION(open_file_from_line, 0,
  3242. "When browsing a directory, open the file under the cursor."
  3243. )(void) {
  3244. if (env->lines[env->line_no-1]->actual < 1) return;
  3245. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3246. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3247. /* Collect file name */
  3248. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3249. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3250. char * t = tmp;
  3251. /* Start by copying the filename */
  3252. t += sprintf(t, "%s/", env->file_name);
  3253. /* Start from character 2 to skip d/f and space */
  3254. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3255. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3256. }
  3257. *t = '\0';
  3258. /* Normalize */
  3259. char tmp_path[PATH_MAX+1];
  3260. if (!realpath(tmp, tmp_path)) {
  3261. free(tmp);
  3262. return;
  3263. }
  3264. free(tmp);
  3265. /* Open file */
  3266. buffer_t * old_buffer = env;
  3267. open_file(tmp_path);
  3268. buffer_close(old_buffer);
  3269. update_title();
  3270. redraw_all();
  3271. }
  3272. int line_matches(line_t * line, char * string) {
  3273. uint32_t c = 0, state = 0;
  3274. int i = 0;
  3275. while (*string) {
  3276. if (!decode(&state, &c, *string)) {
  3277. if (i >= line->actual) return 0;
  3278. if (line->text[i].codepoint != c) return 0;
  3279. string++;
  3280. i++;
  3281. } else if (state == UTF8_REJECT) {
  3282. state = 0;
  3283. }
  3284. }
  3285. return 1;
  3286. }
  3287. void run_onload(buffer_t * env) {
  3288. /* TODO */
  3289. KrkValue onLoad;
  3290. if (krk_tableGet_fast(&krk_currentThread.module->fields, S("onload"), &onLoad)) {
  3291. krk_push(onLoad);
  3292. krk_push(krk_dict_of(0,NULL,0));
  3293. if (env->file_name) {
  3294. krk_attachNamedObject(AS_DICT(krk_peek(0)), "filename",
  3295. (KrkObj*)krk_copyString(env->file_name,strlen(env->file_name)));
  3296. }
  3297. if (env->syntax && env->syntax->krkClass) {
  3298. krk_attachNamedObject(AS_DICT(krk_peek(0)), "highlighter",
  3299. (KrkObj*)env->syntax->krkClass);
  3300. }
  3301. krk_callStack(1);
  3302. krk_resetStack();
  3303. }
  3304. }
  3305. static void render_syntax_async(background_task_t * task) {
  3306. buffer_t * old_env = env;
  3307. env = task->env;
  3308. int line_no = task->_private_i;
  3309. if (env->line_count && line_no < env->line_count) {
  3310. int tmp = env->loading;
  3311. env->loading = 1;
  3312. recalculate_syntax(env->lines[line_no], line_no);
  3313. env->loading = tmp;
  3314. if (env == old_env) {
  3315. redraw_line(line_no);
  3316. }
  3317. }
  3318. env = old_env;
  3319. }
  3320. static void schedule_complete_recalc(void) {
  3321. if (env->line_count < 1000) {
  3322. for (int i = 0; i < env->line_count; ++i) {
  3323. recalculate_syntax(env->lines[i], i);
  3324. }
  3325. return;
  3326. }
  3327. /* TODO see if there's already a redraw scheduled */
  3328. for (int i = 0; i < env->line_count; ++i) {
  3329. background_task_t * task = malloc(sizeof(background_task_t));
  3330. task->env = env;
  3331. task->_private_i = i;
  3332. task->func = render_syntax_async;
  3333. task->next = NULL;
  3334. if (global_config.tail_task) {
  3335. global_config.tail_task->next = task;
  3336. }
  3337. global_config.tail_task = task;
  3338. if (!global_config.background_task) {
  3339. global_config.background_task = task;
  3340. }
  3341. }
  3342. redraw_statusbar();
  3343. }
  3344. /**
  3345. * Create a new buffer from a file.
  3346. */
  3347. void open_file(char * file) {
  3348. env = buffer_new();
  3349. env->width = global_config.term_width;
  3350. env->left = 0;
  3351. env->loading = 1;
  3352. setup_buffer(env);
  3353. FILE * f;
  3354. int init_line = -1;
  3355. if (!strcmp(file,"-")) {
  3356. /**
  3357. * Read file from stdin. stderr provides terminal input.
  3358. */
  3359. if (isatty(STDIN_FILENO)) {
  3360. if (buffers_len == 1) {
  3361. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3362. }
  3363. close_buffer();
  3364. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3365. return;
  3366. }
  3367. f = stdin;
  3368. env->modified = 1;
  3369. } else {
  3370. char * l = strrchr(file, ':');
  3371. if (l && is_all_numbers(l+1)) {
  3372. *l = '\0';
  3373. l++;
  3374. init_line = atoi(l);
  3375. }
  3376. char * _file = file;
  3377. if (file[0] == '~') {
  3378. char * home = getenv("HOME");
  3379. if (home) {
  3380. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3381. sprintf(_file, "%s%s", home, file+1);
  3382. }
  3383. }
  3384. if (file_is_open(_file)) {
  3385. if (file != _file) free(_file);
  3386. close_buffer();
  3387. return;
  3388. }
  3389. struct stat statbuf;
  3390. if (!stat(_file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3391. read_directory_into_buffer(_file);
  3392. if (file != _file) free(_file);
  3393. return;
  3394. }
  3395. f = fopen(_file, "r");
  3396. if (file != _file) free(_file);
  3397. if (!f && errno != ENOENT) {
  3398. render_error("%s: %s", file, strerror(errno));
  3399. pause_for_key();
  3400. close_buffer();
  3401. return;
  3402. }
  3403. env->file_name = strdup(file);
  3404. }
  3405. if (!f) {
  3406. if (global_config.highlight_on_open) {
  3407. env->syntax = match_syntax(file);
  3408. }
  3409. env->loading = 0;
  3410. if (global_config.go_to_line) {
  3411. goto_line(1);
  3412. }
  3413. if (env->syntax && env->syntax->prefers_spaces) {
  3414. env->tabs = 0;
  3415. }
  3416. update_biminfo(env, 1);
  3417. run_onload(env);
  3418. return;
  3419. }
  3420. uint8_t buf[BLOCK_SIZE];
  3421. state = 0;
  3422. while (!feof(f) && !ferror(f)) {
  3423. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3424. add_buffer(buf, r);
  3425. }
  3426. if (ferror(f)) {
  3427. env->loading = 0;
  3428. return;
  3429. }
  3430. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3431. /* Remove blank line from end */
  3432. env->lines = remove_line(env->lines, env->line_no-1);
  3433. }
  3434. if (global_config.highlight_on_open) {
  3435. env->syntax = match_syntax(file);
  3436. if (!env->syntax) {
  3437. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3438. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3439. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3440. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3441. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3442. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3443. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3444. }
  3445. if (!env->syntax && global_config.syntax_fallback) {
  3446. set_syntax_by_name(global_config.syntax_fallback);
  3447. }
  3448. schedule_complete_recalc();
  3449. }
  3450. /* Try to automatically figure out tabs vs. spaces */
  3451. int tabs = 0, spaces = 0;
  3452. for (int i = 0; i < env->line_count; ++i) {
  3453. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3454. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3455. if (env->lines[i]->text[0].codepoint == ' ' &&
  3456. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3457. spaces++;
  3458. }
  3459. }
  3460. if (spaces > tabs) {
  3461. env->tabs = 0;
  3462. } else if (spaces == tabs && env->syntax) {
  3463. env->tabs = env->syntax->prefers_spaces;
  3464. }
  3465. if (spaces > tabs) {
  3466. int one = 0, two = 0, three = 0, four = 0; /* If you use more than that, I don't like you. */
  3467. int lastCount = 0;
  3468. for (int i = 0; i < env->line_count; ++i) {
  3469. if (env->lines[i]->actual > 1 && !line_is_comment(env->lines[i])) {
  3470. /* Count spaces at beginning */
  3471. int c = 0, diff = 0;
  3472. while (c < env->lines[i]->actual && env->lines[i]->text[c].codepoint == ' ') c++;
  3473. if (c > lastCount) {
  3474. diff = c - lastCount;
  3475. } else if (c < lastCount) {
  3476. diff = lastCount - c;
  3477. }
  3478. if (diff == 1) one++;
  3479. if (diff == 2) two++;
  3480. if (diff == 3) three++;
  3481. if (diff == 4) four++;
  3482. lastCount = c;
  3483. }
  3484. }
  3485. if (four > three && four > two && four > one) {
  3486. env->tabstop = 4;
  3487. } else if (three > two && three > one) {
  3488. env->tabstop = 3;
  3489. } else if (two > one) {
  3490. env->tabstop = 2;
  3491. } else {
  3492. env->tabstop = 1;
  3493. }
  3494. }
  3495. env->loading = 0;
  3496. if (global_config.check_git) {
  3497. env->checkgitstatusonwrite = 1;
  3498. git_examine(file);
  3499. }
  3500. for (int i = 0; i < env->line_count; ++i) {
  3501. recalculate_tabs(env->lines[i]);
  3502. }
  3503. if (global_config.go_to_line) {
  3504. if (init_line != -1) {
  3505. goto_line(init_line);
  3506. } else {
  3507. env->line_no = 1;
  3508. env->col_no = 1;
  3509. fetch_from_biminfo(env);
  3510. place_cursor_actual();
  3511. redraw_all();
  3512. set_preferred_column();
  3513. }
  3514. }
  3515. update_biminfo(env, 1);
  3516. fclose(f);
  3517. run_onload(env);
  3518. }
  3519. /**
  3520. * Clean up the terminal and exit the editor.
  3521. */
  3522. void quit(const char * message) {
  3523. mouse_disable();
  3524. set_buffered();
  3525. reset();
  3526. clear_screen();
  3527. show_cursor();
  3528. unset_bracketed_paste();
  3529. unset_alternate_screen();
  3530. krk_freeVM();
  3531. if (message) {
  3532. fprintf(stdout, "%s\n", message);
  3533. }
  3534. exit(0);
  3535. }
  3536. /**
  3537. * Try to quit, but don't continue if there are
  3538. * modified buffers open.
  3539. */
  3540. void try_quit(void) {
  3541. for (int i = 0; i < buffers_len; i++ ) {
  3542. buffer_t * _env = buffers[i];
  3543. if (_env->modified) {
  3544. if (_env->file_name) {
  3545. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3546. } else {
  3547. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3548. }
  3549. return;
  3550. }
  3551. }
  3552. /* Close all buffers */
  3553. while (buffers_len) {
  3554. buffer_close(buffers[0]);
  3555. }
  3556. quit(NULL);
  3557. }
  3558. /**
  3559. * Switch to the previous buffer
  3560. */
  3561. BIM_ACTION(previous_tab, 0,
  3562. "Switch the previous tab"
  3563. )(void) {
  3564. buffer_t * last = NULL;
  3565. for (int i = 0; i < buffers_len; i++) {
  3566. buffer_t * _env = buffers[i];
  3567. if (_env == env) {
  3568. if (last) {
  3569. /* Wrap around */
  3570. env = last;
  3571. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3572. redraw_all();
  3573. update_title();
  3574. return;
  3575. } else {
  3576. env = buffers[buffers_len-1];
  3577. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3578. redraw_all();
  3579. update_title();
  3580. return;
  3581. }
  3582. }
  3583. last = _env;
  3584. }
  3585. }
  3586. /**
  3587. * Switch to the next buffer
  3588. */
  3589. BIM_ACTION(next_tab, 0,
  3590. "Switch to the next tab"
  3591. )(void) {
  3592. for (int i = 0; i < buffers_len; i++) {
  3593. buffer_t * _env = buffers[i];
  3594. if (_env == env) {
  3595. if (i != buffers_len - 1) {
  3596. env = buffers[i+1];
  3597. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3598. redraw_all();
  3599. update_title();
  3600. return;
  3601. } else {
  3602. /* Wrap around */
  3603. env = buffers[0];
  3604. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3605. redraw_all();
  3606. update_title();
  3607. return;
  3608. }
  3609. }
  3610. }
  3611. }
  3612. /**
  3613. * Check for modified lines in a file by examining `git diff` output.
  3614. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3615. */
  3616. int git_examine(char * filename) {
  3617. if (env->modified) return 1;
  3618. int fds[2];
  3619. pipe(fds);
  3620. int child = fork();
  3621. if (child == 0) {
  3622. FILE * dev_null = fopen("/dev/null","w");
  3623. close(fds[0]);
  3624. dup2(fds[1], STDOUT_FILENO);
  3625. dup2(fileno(dev_null), STDERR_FILENO);
  3626. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3627. exit(execvp("git",args));
  3628. } else if (child < 0) {
  3629. return 1;
  3630. }
  3631. close(fds[1]);
  3632. FILE * f = fdopen(fds[0],"r");
  3633. int line_offset = 0;
  3634. while (!feof(f)) {
  3635. int c = fgetc(f);
  3636. if (c < 0) break;
  3637. if (c == '@' && line_offset == 0) {
  3638. /* Read line offset, count */
  3639. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3640. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3641. int from_line = 0;
  3642. int from_count = 0;
  3643. int to_line = 0;
  3644. int to_count = 0;
  3645. fscanf(f,"%d",&from_line);
  3646. if (fgetc(f) == ',') {
  3647. fscanf(f,"%d",&from_count);
  3648. } else {
  3649. from_count = 1;
  3650. }
  3651. fscanf(f,"%d",&to_line);
  3652. if (fgetc(f) == ',') {
  3653. fscanf(f,"%d",&to_count);
  3654. } else {
  3655. to_count = 1;
  3656. }
  3657. if (to_line > env->line_count) continue;
  3658. if (from_count == 0 && to_count > 0) {
  3659. /* No -, all + means all of to_count is green */
  3660. for (int i = 0; i < to_count; ++i) {
  3661. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3662. }
  3663. } else if (from_count > 0 && to_count == 0) {
  3664. /*
  3665. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3666. * Note that to_line is one lower than the affected line, so we don't need to mess with indexes.
  3667. */
  3668. if (to_line >= env->line_count) continue;
  3669. env->lines[to_line]->rev_status = 4; /* Red */
  3670. } else if (from_count > 0 && from_count == to_count) {
  3671. /* from = to, all modified */
  3672. for (int i = 0; i < to_count; ++i) {
  3673. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3674. }
  3675. } else if (from_count > 0 && from_count < to_count) {
  3676. /* from < to, some modified, some added */
  3677. for (int i = 0; i < from_count; ++i) {
  3678. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3679. }
  3680. for (int i = from_count; i < to_count; ++i) {
  3681. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3682. }
  3683. } else if (to_count > 0 && from_count > to_count) {
  3684. /* from > to, we deleted but also modified some lines */
  3685. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3686. for (int i = 1; i < to_count; ++i) {
  3687. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3688. }
  3689. }
  3690. }
  3691. }
  3692. if (c == '\n') {
  3693. line_offset = 0;
  3694. continue;
  3695. }
  3696. line_offset++;
  3697. }
  3698. fclose(f);
  3699. return 0;
  3700. }
  3701. /**
  3702. * Write file contents to FILE
  3703. */
  3704. void output_file(buffer_t * env, FILE * f) {
  3705. int i, j;
  3706. for (i = 0; i < env->line_count; ++i) {
  3707. line_t * line = env->lines[i];
  3708. line->rev_status = 0;
  3709. for (j = 0; j < line->actual; j++) {
  3710. char_t c = line->text[j];
  3711. if (c.codepoint == 0) {
  3712. char buf[1] = {0};
  3713. fwrite(buf, 1, 1, f);
  3714. } else {
  3715. char tmp[8] = {0};
  3716. int i = to_eight(c.codepoint, tmp);
  3717. fwrite(tmp, i, 1, f);
  3718. }
  3719. }
  3720. if (env->crnl) fputc('\r', f);
  3721. fputc('\n', f);
  3722. }
  3723. }
  3724. /**
  3725. * Write active buffer to file
  3726. */
  3727. void write_file(char * file) {
  3728. if (!file) {
  3729. render_error("Need a file to write to.");
  3730. return;
  3731. }
  3732. char * _file = file;
  3733. if (file[0] == '~') {
  3734. char * home = getenv("HOME");
  3735. if (home) {
  3736. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3737. sprintf(_file, "%s%s", home, file+1);
  3738. }
  3739. }
  3740. FILE * f = fopen(_file, "w+");
  3741. if (file != _file) free(_file);
  3742. if (!f) {
  3743. render_error("Failed to open file for writing.");
  3744. return;
  3745. }
  3746. /* Go through each line and convert it back to UTF-8 */
  3747. output_file(env, f);
  3748. fclose(f);
  3749. /* Mark it no longer modified */
  3750. env->modified = 0;
  3751. env->last_save_history = env->history;
  3752. /* If there was no file name set, set one */
  3753. if (!env->file_name) {
  3754. env->file_name = malloc(strlen(file) + 1);
  3755. memcpy(env->file_name, file, strlen(file) + 1);
  3756. }
  3757. if (env->checkgitstatusonwrite) {
  3758. git_examine(file);
  3759. }
  3760. update_title();
  3761. redraw_all();
  3762. }
  3763. /**
  3764. * Close the active buffer
  3765. */
  3766. void close_buffer(void) {
  3767. buffer_t * previous_env = env;
  3768. buffer_t * new_env = buffer_close(env);
  3769. if (new_env == previous_env) {
  3770. /* ?? Failed to close buffer */
  3771. render_error("lolwat");
  3772. }
  3773. if (left_buffer && env == left_buffer) {
  3774. left_buffer = NULL;
  3775. right_buffer->left = 0;
  3776. right_buffer->width = global_config.term_width;
  3777. right_buffer = NULL;
  3778. } else if (left_buffer && env == right_buffer) {
  3779. right_buffer = NULL;
  3780. left_buffer->left = 0;
  3781. left_buffer->width = global_config.term_width;
  3782. left_buffer = NULL;
  3783. }
  3784. /* No more buffers, exit */
  3785. if (!new_env) {
  3786. quit(NULL);
  3787. }
  3788. /* Set the new active buffer */
  3789. env = new_env;
  3790. /* Redraw the screen */
  3791. redraw_all();
  3792. update_title();
  3793. }
  3794. /**
  3795. * Set the visual column the cursor should attempt to keep
  3796. * when moving up and down based on where the cursor currently is.
  3797. * This should happen whenever the user intentionally changes
  3798. * the cursor's horizontal positioning, such as with left/right
  3799. * arrow keys, word-move, search, mouse, etc.
  3800. */
  3801. void set_preferred_column(void) {
  3802. int c = 0;
  3803. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3804. c += env->lines[env->line_no-1]->text[i].display_width;
  3805. }
  3806. env->preferred_column = c;
  3807. }
  3808. BIM_ACTION(cursor_down, 0,
  3809. "Move the cursor one line down."
  3810. )(void) {
  3811. /* If this isn't already the last line... */
  3812. if (env->line_no < env->line_count) {
  3813. /* Move the cursor down */
  3814. env->line_no += 1;
  3815. /* Try to place the cursor horizontally at the preferred column */
  3816. int _x = 0;
  3817. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3818. char_t * c = &env->lines[env->line_no-1]->text[i];
  3819. _x += c->display_width;
  3820. env->col_no = i+1;
  3821. if (_x > env->preferred_column) {
  3822. break;
  3823. }
  3824. }
  3825. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3826. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3827. }
  3828. /*
  3829. * If the horizontal cursor position exceeds the width the new line,
  3830. * then move the cursor left to the extent of the new line.
  3831. *
  3832. * If we're in insert mode, we can go one cell beyond the end of the line
  3833. */
  3834. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3835. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3836. if (env->col_no == 0) env->col_no = 1;
  3837. }
  3838. if (env->loading) return;
  3839. /*
  3840. * If the screen was scrolled horizontally, unscroll it;
  3841. * if it will be scrolled on this line as well, that will
  3842. * be handled by place_cursor_actual
  3843. */
  3844. int redraw = 0;
  3845. if (env->coffset != 0) {
  3846. env->coffset = 0;
  3847. redraw = 1;
  3848. }
  3849. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3850. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  3851. env->offset += 1;
  3852. /* Tell terminal to scroll */
  3853. if (global_config.can_scroll && !left_buffer) {
  3854. if (!global_config.can_insert) {
  3855. shift_up(1);
  3856. redraw_tabbar();
  3857. } else {
  3858. delete_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  3859. }
  3860. /* A new line appears on screen at the bottom, draw it */
  3861. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  3862. if (env->offset + l < env->line_count + 1) {
  3863. redraw_line(env->offset + l-1);
  3864. } else {
  3865. draw_excess_line(l - 1);
  3866. }
  3867. } else {
  3868. redraw_text();
  3869. }
  3870. redraw_statusbar();
  3871. redraw_commandline();
  3872. place_cursor_actual();
  3873. return;
  3874. } else if (redraw) {
  3875. /* Otherwise, if we need to redraw because of coffset change, do that */
  3876. redraw_text();
  3877. }
  3878. set_history_break();
  3879. /* Update the status bar */
  3880. redraw_statusbar();
  3881. /* Place the terminal cursor again */
  3882. place_cursor_actual();
  3883. }
  3884. }
  3885. BIM_ACTION(cursor_up, 0,
  3886. "Move the cursor up one line."
  3887. )(void) {
  3888. /* If this isn't the first line already */
  3889. if (env->line_no > 1) {
  3890. /* Move the cursor down */
  3891. env->line_no -= 1;
  3892. /* Try to place the cursor horizontally at the preferred column */
  3893. int _x = 0;
  3894. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3895. char_t * c = &env->lines[env->line_no-1]->text[i];
  3896. _x += c->display_width;
  3897. env->col_no = i+1;
  3898. if (_x > env->preferred_column) {
  3899. break;
  3900. }
  3901. }
  3902. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3903. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3904. }
  3905. /*
  3906. * If the horizontal cursor position exceeds the width the new line,
  3907. * then move the cursor left to the extent of the new line.
  3908. *
  3909. * If we're in insert mode, we can go one cell beyond the end of the line
  3910. */
  3911. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3912. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3913. if (env->col_no == 0) env->col_no = 1;
  3914. }
  3915. if (env->loading) return;
  3916. /*
  3917. * If the screen was scrolled horizontally, unscroll it;
  3918. * if it will be scrolled on this line as well, that will
  3919. * be handled by place_cursor_actual
  3920. */
  3921. int redraw = 0;
  3922. if (env->coffset != 0) {
  3923. env->coffset = 0;
  3924. redraw = 1;
  3925. }
  3926. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  3927. if (env->line_no <= e) {
  3928. env->offset -= 1;
  3929. /* Tell terminal to scroll */
  3930. if (global_config.can_scroll && !left_buffer) {
  3931. if (!global_config.can_insert) {
  3932. shift_down(1);
  3933. redraw_tabbar();
  3934. } else {
  3935. insert_lines_at(global_config.tabs_visible ? 2 : 1, 1);
  3936. }
  3937. /*
  3938. * The line at the top of the screen should always be real
  3939. * so we can just call redraw_line here
  3940. */
  3941. redraw_line(env->offset);
  3942. } else {
  3943. redraw_tabbar();
  3944. redraw_text();
  3945. }
  3946. redraw_statusbar();
  3947. redraw_commandline();
  3948. place_cursor_actual();
  3949. return;
  3950. } else if (redraw) {
  3951. /* Otherwise, if we need to redraw because of coffset change, do that */
  3952. redraw_text();
  3953. }
  3954. set_history_break();
  3955. /* Update the status bar */
  3956. redraw_statusbar();
  3957. /* Place the terminal cursor again */
  3958. place_cursor_actual();
  3959. }
  3960. }
  3961. BIM_ACTION(cursor_left, 0,
  3962. "Move the cursor one character to the left."
  3963. )(void) {
  3964. if (env->col_no > 1) {
  3965. env->col_no -= 1;
  3966. /* Update the status bar */
  3967. redraw_statusbar();
  3968. /* Place the terminal cursor again */
  3969. place_cursor_actual();
  3970. }
  3971. set_history_break();
  3972. set_preferred_column();
  3973. }
  3974. BIM_ACTION(cursor_right, 0,
  3975. "Move the cursor one character to the right."
  3976. )(void) {
  3977. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  3978. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  3979. env->col_no += 1;
  3980. /* Update the status bar */
  3981. redraw_statusbar();
  3982. /* Place the terminal cursor again */
  3983. place_cursor_actual();
  3984. }
  3985. set_history_break();
  3986. set_preferred_column();
  3987. }
  3988. BIM_ACTION(cursor_home, 0,
  3989. "Move the cursor to the beginning of the line."
  3990. )(void) {
  3991. env->col_no = 1;
  3992. set_history_break();
  3993. set_preferred_column();
  3994. /* Update the status bar */
  3995. redraw_statusbar();
  3996. /* Place the terminal cursor again */
  3997. place_cursor_actual();
  3998. }
  3999. BIM_ACTION(cursor_end, 0,
  4000. "Move the cursor to the end of the line, or past the end in insert mode."
  4001. )(void) {
  4002. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4003. set_history_break();
  4004. set_preferred_column();
  4005. /* Update the status bar */
  4006. redraw_statusbar();
  4007. /* Place the terminal cursor again */
  4008. place_cursor_actual();
  4009. }
  4010. BIM_ACTION(leave_insert, 0,
  4011. "Leave insert modes and return to normal mode."
  4012. )(void) {
  4013. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4014. env->col_no = env->lines[env->line_no-1]->actual;
  4015. if (env->col_no == 0) env->col_no = 1;
  4016. set_preferred_column();
  4017. }
  4018. set_history_break();
  4019. env->mode = MODE_NORMAL;
  4020. redraw_commandline();
  4021. }
  4022. /**
  4023. * Helper for handling smart case sensitivity.
  4024. */
  4025. int search_matches(uint32_t a, uint32_t b, int mode) {
  4026. if (mode == 0) {
  4027. return a == b;
  4028. } else if (mode == 1) {
  4029. return tolower(a) == tolower(b);
  4030. }
  4031. return 0;
  4032. }
  4033. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  4034. int k = j;
  4035. uint32_t * match = needle;
  4036. if (*match == '^') {
  4037. if (j != 0) return 0;
  4038. match++;
  4039. }
  4040. while (k < line->actual + 1) {
  4041. if (*match == '\0') {
  4042. if (len) *len = k - j;
  4043. return 1;
  4044. }
  4045. if (*match == '$') {
  4046. if (k != line->actual) return 0;
  4047. match++;
  4048. continue;
  4049. }
  4050. if (*match == '.') {
  4051. if (match[1] == '*') {
  4052. int greedy = !(match[2] == '?');
  4053. /* Short-circuit chained .*'s */
  4054. if (match[greedy ? 2 : 3] == '.' && match[greedy ? 3 : 4] == '*') {
  4055. int _len;
  4056. if (subsearch_matches(line, k, &match[greedy ? 2 : 3], ignorecase, &_len)) {
  4057. if (len) *len = _len + k - j;
  4058. return 1;
  4059. }
  4060. return 0;
  4061. }
  4062. int _j = greedy ? line->actual : k;
  4063. int _break = -1;
  4064. int _len = -1;
  4065. if (!match[greedy ? 2 : 3]) {
  4066. _len = greedy ? (line->actual - _j) : 0;
  4067. _break = _j;
  4068. } else {
  4069. while (_j < line->actual + 1 && _j >= k) {
  4070. int len;
  4071. if (subsearch_matches(line, _j, &match[greedy ? 2 : 3], ignorecase, &len)) {
  4072. _break = _j;
  4073. _len = len;
  4074. break;
  4075. }
  4076. _j += (greedy ? -1 : 1);
  4077. }
  4078. }
  4079. if (_break != -1) {
  4080. if (len) *len = (_break - j) + _len;
  4081. return 1;
  4082. }
  4083. return 0;
  4084. } else {
  4085. if (k >= line->actual) return 0;
  4086. match++;
  4087. k++;
  4088. continue;
  4089. }
  4090. }
  4091. if (*match == '\\' && (match[1] == '$' || match[1] == '^' || match[1] == '/' || match[1] == '\\' || match[1] == '.')) {
  4092. match++;
  4093. } else if (*match == '\\' && match[1] == 't') {
  4094. if (line->text[k].codepoint != '\t') break;
  4095. match += 2;
  4096. k++;
  4097. continue;
  4098. }
  4099. if (k == line->actual) break;
  4100. if (!search_matches(*match, line->text[k].codepoint, ignorecase)) break;
  4101. match++;
  4102. k++;
  4103. }
  4104. return 0;
  4105. }
  4106. /**
  4107. * Replace text on a given line with other text.
  4108. */
  4109. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4110. line_t * line = env->lines[line_no-1];
  4111. int j = col;
  4112. while (j < line->actual + 1) {
  4113. int match_len;
  4114. if (subsearch_matches(line,j,needle,ignorecase,&match_len)) {
  4115. /* Perform replacement */
  4116. for (int i = 0; i < match_len; ++i) {
  4117. line_delete(line, j+1, line_no-1);
  4118. }
  4119. int t = 0;
  4120. for (uint32_t * r = replacement; *r; ++r) {
  4121. char_t _c;
  4122. _c.codepoint = *r;
  4123. _c.flags = 0;
  4124. _c.display_width = codepoint_width(*r);
  4125. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4126. if (line != nline) {
  4127. env->lines[line_no-1] = nline;
  4128. line = nline;
  4129. }
  4130. t++;
  4131. }
  4132. *out_col = j + t;
  4133. set_modified();
  4134. return;
  4135. }
  4136. j++;
  4137. }
  4138. *out_col = -1;
  4139. }
  4140. #define COMMAND_HISTORY_MAX 255
  4141. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4142. /**
  4143. * Add a command to the history. If that command was
  4144. * already in history, it is moved to the front of the list;
  4145. * otherwise, the whole list is shifted backwards and
  4146. * overflow is freed up.
  4147. */
  4148. void insert_command_history(char * cmd) {
  4149. /* See if this is already in the history. */
  4150. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4151. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4152. if (!strcmp((char*)command_history[i], cmd)) {
  4153. free(command_history[i]);
  4154. amount_to_shift = i;
  4155. break;
  4156. }
  4157. }
  4158. /* Remove last entry that will roll off the stack */
  4159. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4160. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4161. }
  4162. /* Roll the history */
  4163. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4164. command_history[0] = (unsigned char*)strdup(cmd);
  4165. }
  4166. static uint32_t term_colors[] = {
  4167. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  4168. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  4169. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  4170. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  4171. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  4172. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  4173. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  4174. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  4175. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  4176. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  4177. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  4178. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  4179. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  4180. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  4181. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  4182. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  4183. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  4184. 0xeeeeee,
  4185. };
  4186. /**
  4187. * Convert a color setting from terminal format
  4188. * to a hexadecimal color code and add it to the current
  4189. * buffer. This is used for HTML conversion, but could
  4190. * possibly be used for other purposes.
  4191. */
  4192. static void html_convert_color(const char * color_string) {
  4193. char tmp[100];
  4194. if (!strncmp(color_string,"2;",2)) {
  4195. /* 24-bit color */
  4196. int red, green, blue;
  4197. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  4198. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  4199. } else if (!strncmp(color_string,"5;",2)) {
  4200. /* 256 colors; needs lookup table */
  4201. int index;
  4202. sscanf(color_string+2,"%d",&index);
  4203. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  4204. } else {
  4205. /* 16 colors; needs lookup table */
  4206. int index;
  4207. uint32_t color;
  4208. sscanf(color_string+1,"%d",&index);
  4209. if (index >= 10) {
  4210. index -= 10;
  4211. color = term_colors[index+8];
  4212. } else if (index == 9) {
  4213. color = term_colors[0];
  4214. } else {
  4215. color = term_colors[index];
  4216. }
  4217. sprintf(tmp,"#%06x;", (unsigned int)color);
  4218. }
  4219. add_string(tmp);
  4220. char * italic = strstr(color_string,";3");
  4221. if (italic && italic[2] == '\0') {
  4222. add_string(" font-style: oblique;");
  4223. }
  4224. char * bold = strstr(color_string,";1");
  4225. if (bold && bold[2] == '\0') {
  4226. add_string(" font-weight: bold;");
  4227. }
  4228. char * underline = strstr(color_string,";4");
  4229. if (underline && underline[2] == '\0') {
  4230. add_string(" font-decoration: underline;");
  4231. }
  4232. }
  4233. int convert_to_html(void) {
  4234. buffer_t * old = env;
  4235. env = buffer_new();
  4236. setup_buffer(env);
  4237. env->loading = 1;
  4238. add_string("<!doctype html>\n");
  4239. add_string("<html>\n");
  4240. add_string(" <head>\n");
  4241. add_string(" <meta charset=\"UTF-8\">\n");
  4242. if (old->file_name) {
  4243. add_string(" <title>");
  4244. add_string(file_basename(old->file_name));
  4245. add_string("</title>\n");
  4246. }
  4247. add_string(" <style>\n");
  4248. add_string(" body {\n");
  4249. add_string(" margin: 0;\n");
  4250. add_string(" -webkit-text-size-adjust: none;\n");
  4251. add_string(" counter-reset: line-no;\n");
  4252. add_string(" background-color: ");
  4253. /* Convert color */
  4254. html_convert_color(COLOR_BG);
  4255. add_string("\n");
  4256. add_string(" }\n");
  4257. add_string(" .ul { text-decoration: underline; }\n");
  4258. for (int i = 0; i < 15; ++i) {
  4259. /* For each of the relevant flags... */
  4260. char tmp[20];
  4261. sprintf(tmp," .s%d { color: ", i);
  4262. add_string(tmp);
  4263. /* These are special */
  4264. if (i == FLAG_NOTICE) {
  4265. html_convert_color(COLOR_SEARCH_FG);
  4266. add_string(" background-color: ");
  4267. html_convert_color(COLOR_SEARCH_BG);
  4268. } else if (i == FLAG_ERROR) {
  4269. html_convert_color(COLOR_ERROR_FG);
  4270. add_string(" background-color: ");
  4271. html_convert_color(COLOR_ERROR_BG);
  4272. } else {
  4273. html_convert_color(flag_to_color(i));
  4274. }
  4275. add_string("}\n");
  4276. }
  4277. add_string(" pre {\n");
  4278. add_string(" margin: 0;\n");
  4279. add_string(" white-space: pre-wrap;\n");
  4280. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4281. add_string(" font-size: 10pt;\n");
  4282. add_string(" }\n");
  4283. add_string(" pre>span {\n");
  4284. add_string(" display: inline-block;\n");
  4285. add_string(" width: 100%;\n");
  4286. add_string(" }\n");
  4287. add_string(" pre>span>a::before {\n");
  4288. add_string(" counter-increment: line-no;\n");
  4289. add_string(" content: counter(line-no);\n");
  4290. add_string(" padding-right: 1em;\n");
  4291. add_string(" width: 3em;\n");
  4292. add_string(" display: inline-block;\n");
  4293. add_string(" text-align: right;\n");
  4294. add_string(" background-color: ");
  4295. html_convert_color(COLOR_NUMBER_BG);
  4296. add_string("\n");
  4297. add_string(" color: ");
  4298. html_convert_color(COLOR_NUMBER_FG);
  4299. add_string("\n");
  4300. add_string(" }\n");
  4301. add_string(" pre>span:target {\n");
  4302. add_string(" background-color: ");
  4303. html_convert_color(COLOR_ALT_BG);
  4304. add_string("\n");
  4305. add_string(" }\n");
  4306. add_string(" pre>span:target>a::before {\n");
  4307. add_string(" background-color: ");
  4308. html_convert_color(COLOR_NUMBER_FG);
  4309. add_string("\n");
  4310. add_string(" color: ");
  4311. html_convert_color(COLOR_NUMBER_BG);
  4312. add_string("\n");
  4313. add_string(" }\n");
  4314. for (int i = 1; i <= env->tabstop; ++i) {
  4315. char tmp[20];
  4316. sprintf(tmp, ".tab%d", i);
  4317. add_string(" ");
  4318. add_string(tmp);
  4319. add_string(">span {\n");
  4320. add_string(" display: inline-block;\n");
  4321. add_string(" overflow: hidden;\n");
  4322. add_string(" width: 0;\n");
  4323. add_string(" height: 0;\n");
  4324. add_string(" }\n");
  4325. add_string(" ");
  4326. add_string(tmp);
  4327. add_string("::after {\n");
  4328. add_string(" content: '»");
  4329. for (int j = 1; j < i; ++j) {
  4330. add_string("·");
  4331. }
  4332. add_string("';\n");
  4333. add_string(" background-color: ");
  4334. html_convert_color(COLOR_ALT_BG);
  4335. add_string("\n");
  4336. add_string(" color: ");
  4337. html_convert_color(COLOR_ALT_FG);
  4338. add_string("\n");
  4339. add_string(" }\n");
  4340. }
  4341. add_string(" .space {\n");
  4342. add_string(" border-left: 1px solid ");
  4343. html_convert_color(COLOR_ALT_FG);
  4344. add_string("\n");
  4345. add_string(" margin-left: -1px;\n");
  4346. add_string(" }\n");
  4347. add_string(" </style>\n");
  4348. add_string(" </head>\n");
  4349. add_string(" <body><pre>\n");
  4350. for (int i = 0; i < old->line_count; ++i) {
  4351. char tmp[100];
  4352. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4353. add_string(tmp);
  4354. int last_flag = -1;
  4355. int opened = 0;
  4356. int all_spaces = 1;
  4357. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4358. char_t c = old->lines[i]->text[j];
  4359. if (c.codepoint != ' ') all_spaces = 0;
  4360. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4361. if (opened) add_string("</span>");
  4362. opened = 1;
  4363. char tmp[100];
  4364. sprintf(tmp, "<span class=\"s%d%s\">",
  4365. c.flags & FLAG_MASK_COLORS,
  4366. (c.flags & FLAG_UNDERLINE) ? " ul" : "");
  4367. add_string(tmp);
  4368. last_flag = (c.flags & 0x1F);
  4369. }
  4370. if (c.codepoint == '<') {
  4371. add_string("&lt;");
  4372. } else if (c.codepoint == '>') {
  4373. add_string("&gt;");
  4374. } else if (c.codepoint == '&') {
  4375. add_string("&amp;");
  4376. } else if (c.codepoint == '\t') {
  4377. char tmp[100];
  4378. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4379. add_string(tmp);
  4380. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4381. add_string("<span class=\"space\"> </span>");
  4382. } else {
  4383. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4384. to_eight(c.codepoint, tmp);
  4385. add_string(tmp);
  4386. }
  4387. }
  4388. if (opened) {
  4389. add_string("</span>");
  4390. } else {
  4391. add_string("<wbr>");
  4392. }
  4393. add_string("</span>\n");
  4394. }
  4395. add_string("</pre></body>\n");
  4396. add_string("</html>\n");
  4397. env->loading = 0;
  4398. env->modified = 1;
  4399. if (old->file_name) {
  4400. char * base = file_basename(old->file_name);
  4401. char * tmp = malloc(strlen(base) + 5);
  4402. *tmp = '\0';
  4403. strcat(tmp, base);
  4404. strcat(tmp, ".htm");
  4405. env->file_name = tmp;
  4406. }
  4407. for (int i = 0; i < env->line_count; ++i) {
  4408. recalculate_tabs(env->lines[i]);
  4409. }
  4410. env->syntax = match_syntax(".htm");
  4411. schedule_complete_recalc();
  4412. return 0;
  4413. }
  4414. /**
  4415. * Based on vim's :TOhtml
  4416. * Convert syntax-highlighted buffer contents to HTML.
  4417. */
  4418. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  4419. convert_to_html();
  4420. redraw_all();
  4421. return 0;
  4422. }
  4423. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4424. int _prefix_command_run_script(char * cmd) {
  4425. if (env->mode == MODE_LINE_SELECTION) {
  4426. int range_top, range_bot;
  4427. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4428. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4429. int in[2];
  4430. pipe(in);
  4431. int out[2];
  4432. pipe(out);
  4433. int child = fork();
  4434. /* Open child process and set up pipes */
  4435. if (child == 0) {
  4436. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4437. close(out[0]);
  4438. close(in[1]);
  4439. dup2(out[1], STDOUT_FILENO);
  4440. dup2(in[0], STDIN_FILENO);
  4441. dup2(fileno(dev_null), STDERR_FILENO);
  4442. system(&cmd[1]); /* Yes we can just do this */
  4443. exit(1);
  4444. } else if (child < 0) {
  4445. render_error("Failed to fork");
  4446. return 1;
  4447. }
  4448. close(out[1]);
  4449. close(in[0]);
  4450. /* Write lines to child process */
  4451. FILE * f = fdopen(in[1],"w");
  4452. for (int i = range_top; i <= range_bot; ++i) {
  4453. line_t * line = env->lines[i-1];
  4454. for (int j = 0; j < line->actual; j++) {
  4455. char_t c = line->text[j];
  4456. if (c.codepoint == 0) {
  4457. char buf[1] = {0};
  4458. fwrite(buf, 1, 1, f);
  4459. } else {
  4460. char tmp[8] = {0};
  4461. int i = to_eight(c.codepoint, tmp);
  4462. fwrite(tmp, i, 1, f);
  4463. }
  4464. }
  4465. fputc('\n', f);
  4466. }
  4467. fclose(f);
  4468. close(in[1]);
  4469. /* Read results from child process into a new buffer */
  4470. FILE * result = fdopen(out[0],"r");
  4471. buffer_t * old = env;
  4472. env = buffer_new();
  4473. setup_buffer(env);
  4474. env->loading = 1;
  4475. uint8_t buf[BLOCK_SIZE];
  4476. state = 0;
  4477. while (!feof(result) && !ferror(result)) {
  4478. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4479. add_buffer(buf, r);
  4480. }
  4481. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4482. env->lines = remove_line(env->lines, env->line_no-1);
  4483. }
  4484. fclose(result);
  4485. env->loading = 0;
  4486. /* Return to the original buffer and replace the selected lines with the output */
  4487. buffer_t * new = env;
  4488. env = old;
  4489. for (int i = range_top; i <= range_bot; ++i) {
  4490. /* Remove the existing lines */
  4491. env->lines = remove_line(env->lines, range_top-1);
  4492. }
  4493. for (int i = 0; i < new->line_count; ++i) {
  4494. /* Add the new lines */
  4495. env->lines = add_line(env->lines, range_top + i - 1);
  4496. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4497. recalculate_tabs(env->lines[range_top+i-1]);
  4498. }
  4499. env->modified = 1;
  4500. /* Close the temporary buffer */
  4501. buffer_close(new);
  4502. } else {
  4503. /* Reset and draw some line feeds */
  4504. reset();
  4505. printf("\n\n");
  4506. /* Set buffered for shell application */
  4507. set_buffered();
  4508. /* Call the shell and wait for completion */
  4509. system(&cmd[1]);
  4510. /* Return to the editor, wait for user to press enter. */
  4511. set_unbuffered();
  4512. printf("\n\nPress ENTER to continue.");
  4513. int c;
  4514. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4515. /* Redraw the screen */
  4516. redraw_all();
  4517. }
  4518. /* Done processing command */
  4519. return 0;
  4520. }
  4521. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4522. char * c = needle;
  4523. char * replacement = NULL;
  4524. char * options = "";
  4525. while (*c) {
  4526. if (*c == divider) {
  4527. *c = '\0';
  4528. replacement = c + 1;
  4529. break;
  4530. }
  4531. c++;
  4532. }
  4533. if (!replacement) {
  4534. render_error("nothing to replace with");
  4535. return 1;
  4536. }
  4537. c = replacement;
  4538. while (*c) {
  4539. if (*c == divider) {
  4540. *c = '\0';
  4541. options = c + 1;
  4542. break;
  4543. }
  4544. c++;
  4545. }
  4546. int global = 0;
  4547. int case_insensitive = 0;
  4548. /* Parse options */
  4549. while (*options) {
  4550. switch (*options) {
  4551. case 'g':
  4552. global = 1;
  4553. break;
  4554. case 'i':
  4555. case_insensitive = 1;
  4556. break;
  4557. }
  4558. options++;
  4559. }
  4560. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4561. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4562. {
  4563. int i = 0;
  4564. uint32_t c, state = 0;
  4565. for (char * cin = needle; *cin; cin++) {
  4566. if (!decode(&state, &c, *cin)) {
  4567. needle_c[i] = c;
  4568. i++;
  4569. } else if (state == UTF8_REJECT) {
  4570. state = 0;
  4571. }
  4572. }
  4573. needle_c[i] = 0;
  4574. i = 0;
  4575. c = 0;
  4576. state = 0;
  4577. for (char * cin = replacement; *cin; cin++) {
  4578. if (!decode(&state, &c, *cin)) {
  4579. replacement_c[i] = c;
  4580. i++;
  4581. } else if (state == UTF8_REJECT) {
  4582. state = 0;
  4583. }
  4584. }
  4585. replacement_c[i] = 0;
  4586. }
  4587. int replacements = 0;
  4588. for (int line = range_top; line <= range_bot; ++line) {
  4589. int col = 0;
  4590. while (col != -1) {
  4591. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4592. if (col != -1) replacements++;
  4593. if (!global) break;
  4594. }
  4595. }
  4596. free(needle_c);
  4597. free(replacement_c);
  4598. if (replacements) {
  4599. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4600. set_history_break();
  4601. redraw_text();
  4602. } else {
  4603. render_error("Pattern not found: %s", needle);
  4604. }
  4605. return 0;
  4606. }
  4607. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4608. int range_top, range_bot;
  4609. if (env->mode == MODE_LINE_SELECTION) {
  4610. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4611. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4612. } else {
  4613. range_top = env->line_no;
  4614. range_bot = env->line_no;
  4615. }
  4616. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4617. }
  4618. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4619. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4620. }
  4621. BIM_COMMAND(e,"e","Open a file") {
  4622. if (argc > 1) {
  4623. /* This actually opens a new tab */
  4624. open_file(argv[1]);
  4625. update_title();
  4626. } else {
  4627. if (env->modified) {
  4628. render_error("File is modified, can not reload.");
  4629. return 1;
  4630. }
  4631. buffer_t * old_env = env;
  4632. open_file(env->file_name);
  4633. buffer_t * new_env = env;
  4634. env = old_env;
  4635. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4636. SWAP(line_t **, env->lines, new_env->lines);
  4637. SWAP(int, env->line_count, new_env->line_count);
  4638. SWAP(int, env->line_avail, new_env->line_avail);
  4639. SWAP(history_t *, env->history, new_env->history);
  4640. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4641. schedule_complete_recalc();
  4642. redraw_all();
  4643. }
  4644. return 0;
  4645. }
  4646. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4647. if (argc > 1) {
  4648. open_file(argv[1]);
  4649. update_title();
  4650. } else {
  4651. env = buffer_new();
  4652. setup_buffer(env);
  4653. redraw_all();
  4654. update_title();
  4655. }
  4656. return 0;
  4657. }
  4658. BIM_COMMAND(w,"w","Write a file") {
  4659. /* w: write file */
  4660. if (argc > 1) {
  4661. write_file(argv[1]);
  4662. } else {
  4663. write_file(env->file_name);
  4664. }
  4665. return 0;
  4666. }
  4667. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4668. write_file(env->file_name);
  4669. close_buffer();
  4670. return 0;
  4671. }
  4672. BIM_COMMAND(history,"history","Display command history") {
  4673. render_commandline_message(""); /* To clear command line */
  4674. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4675. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4676. }
  4677. render_commandline_message("\n");
  4678. redraw_tabbar();
  4679. redraw_commandline();
  4680. pause_for_key();
  4681. return 0;
  4682. }
  4683. BIM_COMMAND(q,"q","Close buffer") {
  4684. if (left_buffer && left_buffer == right_buffer) {
  4685. unsplit();
  4686. return 0;
  4687. }
  4688. if (env->modified) {
  4689. render_error("No write since last change. Use :q! to force exit.");
  4690. } else {
  4691. close_buffer();
  4692. }
  4693. update_title();
  4694. return 0;
  4695. }
  4696. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4697. close_buffer();
  4698. update_title();
  4699. return 0;
  4700. }
  4701. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4702. try_quit();
  4703. return 0;
  4704. }
  4705. BIM_ALIAS("qall",qall,qa)
  4706. BIM_COMMAND(qabang,"qa!","Force exit") {
  4707. /* Forcefully exit editor */
  4708. while (buffers_len) {
  4709. buffer_close(buffers[0]);
  4710. }
  4711. quit(NULL);
  4712. return 1; /* doesn't return */
  4713. }
  4714. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4715. previous_tab();
  4716. update_title();
  4717. return 0;
  4718. }
  4719. BIM_COMMAND(tabn,"tabn","Next tab") {
  4720. next_tab();
  4721. update_title();
  4722. return 0;
  4723. }
  4724. BIM_COMMAND(tabm,"tabm","Move the current tab to a new index") {
  4725. /* Figure out the current index */
  4726. int i = 0;
  4727. for (; i < buffers_len; i++) {
  4728. if (buffers[i] == env) break;
  4729. }
  4730. if (i == buffers_len) {
  4731. render_status_message("(invalid state?)");
  4732. return 1;
  4733. }
  4734. if (argc < 2) {
  4735. render_status_message("tab = %d", i);
  4736. return 1;
  4737. }
  4738. int newIndex = atoi(argv[1]);
  4739. if (newIndex == i) {
  4740. return 0;
  4741. }
  4742. /* Okay, this is stupid, but, remove the buffer */
  4743. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i -1));
  4744. /* Then make space at the destination */
  4745. memmove(&buffers[newIndex+1], &buffers[newIndex], sizeof(*buffers) * (buffers_len - newIndex -1));
  4746. buffers[newIndex] = env;
  4747. redraw_tabbar();
  4748. update_title();
  4749. return 0;
  4750. }
  4751. BIM_COMMAND(tab,"tab", "Open a specific tab") {
  4752. if (argc < 2) return bim_command_tabm("tabm", argc, argv);
  4753. int i = atoi(argv[1]);
  4754. if (i < 0 || i > buffers_len) {
  4755. render_error("Invalid tab index");
  4756. return 1;
  4757. }
  4758. env = buffers[i];
  4759. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  4760. redraw_all();
  4761. update_title();
  4762. return 0;
  4763. }
  4764. BIM_COMMAND(tabindicator,"tabindicator","Set the tab indicator") {
  4765. if (argc < 2) {
  4766. render_status_message("tabindicator=%s", global_config.tab_indicator);
  4767. return 0;
  4768. }
  4769. if (!global_config.can_unicode && strlen(argv[1]) != 1) return 0;
  4770. if (display_width_of_string(argv[1]) != 1) {
  4771. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4772. return 1;
  4773. }
  4774. if (global_config.tab_indicator) free(global_config.tab_indicator);
  4775. global_config.tab_indicator = strdup(argv[1]);
  4776. return 0;
  4777. }
  4778. BIM_COMMAND(spaceindicator,"spaceindicator","Set the space indicator") {
  4779. if (argc < 2) {
  4780. render_status_message("spaceindicator=%s", global_config.space_indicator);
  4781. return 0;
  4782. }
  4783. if (!global_config.can_unicode && strlen(argv[1]) != 1) return 0;
  4784. if (display_width_of_string(argv[1]) != 1) {
  4785. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4786. return 1;
  4787. }
  4788. if (global_config.space_indicator) free(global_config.space_indicator);
  4789. global_config.space_indicator = strdup(argv[1]);
  4790. return 0;
  4791. }
  4792. BIM_COMMAND(global_git,"global.git","Show or change the default status of git integration") {
  4793. if (argc < 2) {
  4794. render_status_message("global.git=%d", global_config.check_git);
  4795. } else {
  4796. global_config.check_git = !!atoi(argv[1]);
  4797. }
  4798. return 0;
  4799. }
  4800. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4801. if (!env) {
  4802. render_error("requires environment (did you mean global.git?)");
  4803. return 1;
  4804. }
  4805. if (argc < 2) {
  4806. render_status_message("git=%d", env->checkgitstatusonwrite);
  4807. } else {
  4808. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4809. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4810. git_examine(env->file_name);
  4811. redraw_text();
  4812. }
  4813. }
  4814. return 0;
  4815. }
  4816. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4817. if (argc < 2) {
  4818. render_status_message("colorgutter=%d", global_config.color_gutter);
  4819. } else {
  4820. global_config.color_gutter = !!atoi(argv[1]);
  4821. redraw_text();
  4822. }
  4823. return 0;
  4824. }
  4825. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4826. env->indent = 1;
  4827. redraw_statusbar();
  4828. return 0;
  4829. }
  4830. BIM_COMMAND(noindent,"noindent","Disable smart indentation") {
  4831. env->indent = 0;
  4832. redraw_statusbar();
  4833. return 0;
  4834. }
  4835. /* TODO: global.maxcolumn */
  4836. BIM_COMMAND(maxcolumn,"maxcolumn","Highlight past the given column to indicate maximum desired line length") {
  4837. if (argc < 2) {
  4838. render_status_message("maxcolumn=%d",env->maxcolumn);
  4839. return 0;
  4840. }
  4841. env->maxcolumn = atoi(argv[1]);
  4842. redraw_text();
  4843. return 0;
  4844. }
  4845. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  4846. render_status_message("cursorcolumn=%d", env->preferred_column);
  4847. return 0;
  4848. }
  4849. BIM_COMMAND(noh,"noh","Clear search term") {
  4850. if (global_config.search) {
  4851. free(global_config.search);
  4852. global_config.search = NULL;
  4853. for (int i = 0; i < env->line_count; ++i) {
  4854. for (int j = 0; j < env->lines[i]->actual; ++j) {
  4855. env->lines[i]->text[j].flags &= ~(FLAG_SEARCH);
  4856. }
  4857. }
  4858. redraw_text();
  4859. }
  4860. return 0;
  4861. }
  4862. BIM_COMMAND(help,"help","Show help text.") {
  4863. if (argc < 2) {
  4864. render_commandline_message(""); /* To clear command line */
  4865. render_commandline_message("\n");
  4866. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  4867. render_commandline_message("\n");
  4868. render_commandline_message(" Available commands:\n");
  4869. 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");
  4870. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4871. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4872. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4873. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4874. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4875. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4876. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4877. render_commandline_message("\n");
  4878. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  4879. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4880. render_commandline_message("\n");
  4881. } else {
  4882. int found = 0;
  4883. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  4884. if (!strcmp(c->name, argv[1])) {
  4885. render_commandline_message(""); /* To clear command line */
  4886. render_commandline_message("Help description for `%s`:\n", c->name);
  4887. render_commandline_message(" %s\n", c->description);
  4888. found = 1;
  4889. break;
  4890. }
  4891. }
  4892. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  4893. if (!strcmp(c->name, argv[1])) {
  4894. render_commandline_message(""); /* To clear command line */
  4895. render_commandline_message("Help description for `%s`:\n", c->name);
  4896. render_commandline_message(" %s\n", c->description);
  4897. found = 1;
  4898. break;
  4899. }
  4900. }
  4901. if (!found) {
  4902. render_error("Unknown command: %s", argv[1]);
  4903. return 1;
  4904. }
  4905. }
  4906. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4907. redraw_tabbar();
  4908. redraw_commandline();
  4909. /* Wait for a character so we can redraw the screen before continuing */
  4910. pause_for_key();
  4911. return 0;
  4912. }
  4913. BIM_COMMAND(version,"version","Show version information.") {
  4914. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  4915. return 0;
  4916. }
  4917. BIM_COMMAND(theme,"theme","Set color theme") {
  4918. if (argc < 2) {
  4919. render_status_message("theme=%s", current_theme);
  4920. } else {
  4921. for (struct theme_def * d = themes; themes && d->name; ++d) {
  4922. if (!strcmp(argv[1], d->name)) {
  4923. ptrdiff_t before = krk_currentThread.stackTop - krk_currentThread.stack;
  4924. krk_push(OBJECT_VAL(d->callable));
  4925. KrkValue result = krk_callStack(0);
  4926. krk_currentThread.stackTop = krk_currentThread.stack + before;
  4927. if (IS_NONE(result) && (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION)) {
  4928. render_error("Exception occurred in theme: %s", AS_INSTANCE(krk_currentThread.currentException)->_class->name->chars);
  4929. krk_dumpTraceback();
  4930. int key = 0;
  4931. while ((key = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  4932. }
  4933. redraw_all();
  4934. return 0;
  4935. }
  4936. }
  4937. }
  4938. return 0;
  4939. }
  4940. BIM_ALIAS("colorscheme",colorscheme,theme)
  4941. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  4942. if (argc < 2) {
  4943. render_status_message("splitpercent=%d", global_config.split_percent);
  4944. return 0;
  4945. } else {
  4946. global_config.split_percent = atoi(argv[1]);
  4947. if (left_buffer) {
  4948. update_split_size();
  4949. redraw_all();
  4950. }
  4951. }
  4952. return 0;
  4953. }
  4954. BIM_COMMAND(split,"split","Split the current view.") {
  4955. buffer_t * original = env;
  4956. if (argc > 1) {
  4957. int is_not_number = 0;
  4958. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  4959. if (is_not_number) {
  4960. /* Open a file for the new split */
  4961. open_file(argv[1]);
  4962. right_buffer = buffers[buffers_len-1];
  4963. } else {
  4964. /* Use an existing buffer for the new split */
  4965. int other = atoi(argv[1]);
  4966. if (other >= buffers_len || other < 0) {
  4967. render_error("Invalid buffer number: %d", other);
  4968. return 1;
  4969. }
  4970. right_buffer = buffers[other];
  4971. }
  4972. } else {
  4973. /* Use the current buffer for the new split */
  4974. right_buffer = original;
  4975. }
  4976. left_buffer = original;
  4977. update_split_size();
  4978. redraw_all();
  4979. return 0;
  4980. }
  4981. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  4982. unsplit();
  4983. return 0;
  4984. }
  4985. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  4986. if (argc < 2) {
  4987. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  4988. return 0;
  4989. } else {
  4990. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  4991. redraw_all();
  4992. }
  4993. return 0;
  4994. }
  4995. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  4996. if (argc < 2) {
  4997. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  4998. } else {
  4999. set_syntax_by_name(argv[1]);
  5000. }
  5001. return 0;
  5002. }
  5003. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  5004. schedule_complete_recalc();
  5005. redraw_all();
  5006. return 0;
  5007. }
  5008. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  5009. if (argc < 2) {
  5010. render_status_message("tabstop=%d", env->tabstop);
  5011. } else {
  5012. int t = atoi(argv[1]);
  5013. if (t > 0 && t < 12) {
  5014. env->tabstop = t;
  5015. for (int i = 0; i < env->line_count; ++i) {
  5016. recalculate_tabs(env->lines[i]);
  5017. }
  5018. redraw_all();
  5019. } else {
  5020. render_error("Invalid tabstop: %s", argv[1]);
  5021. }
  5022. }
  5023. return 0;
  5024. }
  5025. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  5026. env->tabs = 0;
  5027. if (argc > 1) {
  5028. bim_command_tabstop("tabstop", argc, argv);
  5029. }
  5030. redraw_statusbar();
  5031. return 0;
  5032. }
  5033. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  5034. env->tabs = 1;
  5035. if (argc > 1) {
  5036. bim_command_tabstop("tabstop", argc, argv);
  5037. }
  5038. redraw_statusbar();
  5039. return 0;
  5040. }
  5041. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  5042. if (global_config.yanks) {
  5043. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5044. free(global_config.yanks[i]);
  5045. }
  5046. free(global_config.yanks);
  5047. global_config.yanks = NULL;
  5048. global_config.yank_count = 0;
  5049. redraw_statusbar();
  5050. }
  5051. return 0;
  5052. }
  5053. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  5054. if (argc < 2) {
  5055. render_status_message("padding=%d", global_config.cursor_padding);
  5056. } else {
  5057. global_config.cursor_padding = atoi(argv[1]);
  5058. if (env) {
  5059. place_cursor_actual();
  5060. }
  5061. }
  5062. return 0;
  5063. }
  5064. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  5065. if (argc < 2) {
  5066. render_status_message("smartcase=%d", global_config.smart_case);
  5067. } else {
  5068. global_config.smart_case = atoi(argv[1]);
  5069. if (env) place_cursor_actual();
  5070. }
  5071. return 0;
  5072. }
  5073. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  5074. if (argc < 2) {
  5075. render_status_message("hlparen=%d", global_config.highlight_parens);
  5076. } else {
  5077. global_config.highlight_parens = atoi(argv[1]);
  5078. if (env) {
  5079. for (int i = 0; i < env->line_count; ++i) {
  5080. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5081. env->lines[i]->text[j].flags &= (~FLAG_SELECT);
  5082. }
  5083. }
  5084. redraw_text();
  5085. place_cursor_actual();
  5086. }
  5087. }
  5088. return 0;
  5089. }
  5090. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  5091. if (argc < 2) {
  5092. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  5093. } else {
  5094. global_config.highlight_current_line = atoi(argv[1]);
  5095. if (env) {
  5096. if (!global_config.highlight_current_line) {
  5097. for (int i = 0; i < env->line_count; ++i) {
  5098. env->lines[i]->is_current = 0;
  5099. }
  5100. }
  5101. redraw_text();
  5102. place_cursor_actual();
  5103. }
  5104. }
  5105. return 0;
  5106. }
  5107. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  5108. if (argc < 2) {
  5109. render_status_message("crnl=%d", env->crnl);
  5110. } else {
  5111. env->crnl = !!atoi(argv[1]);
  5112. redraw_statusbar();
  5113. }
  5114. return 0;
  5115. }
  5116. BIM_COMMAND(global_numbers,"global.numbers","Set whether numbers are displayed by default") {
  5117. if (argc < 2) {
  5118. render_status_message("global.numbers=%d", global_config.numbers);
  5119. } else {
  5120. global_config.numbers = !!atoi(argv[1]);
  5121. redraw_all();
  5122. }
  5123. return 0;
  5124. }
  5125. BIM_COMMAND(global_statusbar,"global.statusbar","Show or set whether to display the statusbar") {
  5126. if (argc < 2) {
  5127. render_status_message("global.statusbar=%d",!global_config.hide_statusbar);
  5128. } else {
  5129. global_config.hide_statusbar = !atoi(argv[1]);
  5130. global_config.bottom_size = global_config.hide_statusbar ? 1 : 2;
  5131. redraw_all();
  5132. }
  5133. return 0;
  5134. }
  5135. BIM_COMMAND(global_search_wraps,"wrapsearch","Enable search wrapping around from top or bottom") {
  5136. if (argc < 2) {
  5137. render_status_message("wrapsearch=%d",global_config.search_wraps);
  5138. } else {
  5139. global_config.search_wraps = !!atoi(argv[1]);
  5140. }
  5141. return 0;
  5142. }
  5143. BIM_COMMAND(smartcomplete,"smartcomplete","Enable autocompletion while typing") {
  5144. if (argc < 2) {
  5145. render_status_message("smartcomplete=%d",global_config.smart_complete);
  5146. } else {
  5147. global_config.smart_complete = !!atoi(argv[1]);
  5148. }
  5149. return 0;
  5150. }
  5151. BIM_COMMAND(global_autohide_tabs,"global.autohidetabs","Whether to show the tab bar when there is only one tab") {
  5152. if (argc < 2) {
  5153. render_status_message("global.autohidetabs=%d", global_config.autohide_tabs);
  5154. } else {
  5155. global_config.autohide_tabs = !!atoi(argv[1]);
  5156. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  5157. redraw_all();
  5158. }
  5159. return 0;
  5160. }
  5161. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  5162. if (argc < 2) {
  5163. render_status_message("numbers=%d", env->numbers);
  5164. } else {
  5165. env->numbers = !!atoi(argv[1]);
  5166. redraw_all();
  5167. }
  5168. return 0;
  5169. }
  5170. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  5171. if (argc < 2) {
  5172. render_status_message("relativenumber=%d", global_config.relative_lines);
  5173. } else {
  5174. global_config.relative_lines = atoi(argv[1]);
  5175. if (env) {
  5176. if (!global_config.relative_lines) {
  5177. for (int i = 0; i < env->line_count; ++i) {
  5178. env->lines[i]->is_current = 0;
  5179. }
  5180. }
  5181. redraw_text();
  5182. place_cursor_actual();
  5183. }
  5184. }
  5185. return 0;
  5186. }
  5187. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  5188. for (int i = 0; i < buffers_len; ++i) {
  5189. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  5190. }
  5191. redraw_tabbar();
  5192. redraw_commandline();
  5193. pause_for_key();
  5194. return 0;
  5195. }
  5196. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  5197. int c;
  5198. render_commandline_message("(press a key)");
  5199. while ((c = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
  5200. render_commandline_message("%d = %s", c, name_from_key(c));
  5201. return 0;
  5202. }
  5203. int isSubstitutionSymbol(int c) {
  5204. if (c >= '!' && c <= '/') return 1;
  5205. if (c >= ':' && c <= '@') return 1;
  5206. if (c >= '[' && c <= '`') return 1;
  5207. if (c >= '{' && c <= '~') return 1;
  5208. return 0;
  5209. }
  5210. int alldigits(const char * c) {
  5211. while (*c) {
  5212. if (!isdigit(*c)) return 0;
  5213. c++;
  5214. }
  5215. return 1;
  5216. }
  5217. /**
  5218. * Process a user command.
  5219. */
  5220. int process_krk_command(const char * cmd, KrkValue * outVal);
  5221. int process_command(char * cmd) {
  5222. if (cmd[0] == '-' && alldigits(&cmd[1])) {
  5223. goto_line(env->line_no-atoi(&cmd[1]));
  5224. return 0;
  5225. } else if (cmd[0] == '+' && alldigits(&cmd[1])) {
  5226. goto_line(env->line_no+atoi(&cmd[1]));
  5227. return 0;
  5228. } else if (alldigits(cmd)) {
  5229. goto_line(atoi(cmd));
  5230. return 0;
  5231. } else if (cmd[0] == '!') {
  5232. return _prefix_command_run_script(cmd);
  5233. } else if (cmd[0] == 's' && isSubstitutionSymbol(cmd[1])) {
  5234. return bim_command_repsome(cmd, 0, NULL);
  5235. } else if (cmd[0] == '%' && cmd[1] == 's') {
  5236. return bim_command_repall(cmd, 0, NULL);
  5237. }
  5238. /* See if it's a bim command in the classic format */
  5239. {
  5240. char * argv[3] = {NULL, NULL, NULL};
  5241. int argc = !!(*cmd);
  5242. char cmd_name[512] = {0};
  5243. for (char * c = (char*)cmd; *c; ++c) {
  5244. if (c-cmd == 511) break;
  5245. if (*c == ' ') {
  5246. cmd_name[c-cmd] = '\0';
  5247. while (*c == ' ') c++;
  5248. argv[1] = c;
  5249. if (*argv[1]) argc++;
  5250. break;
  5251. }
  5252. cmd_name[c-cmd] = *c;
  5253. }
  5254. argv[0] = cmd_name;
  5255. argv[argc] = NULL;
  5256. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5257. if (!strcmp(argv[0], c->name)) {
  5258. krk_resetStack();
  5259. return c->command((char*)cmd, argc, argv);
  5260. }
  5261. }
  5262. }
  5263. int retval = process_krk_command(cmd, NULL);
  5264. return retval;
  5265. }
  5266. struct Candidate {
  5267. char * text;
  5268. int type;
  5269. };
  5270. /**
  5271. * Wrap strcmp for use with qsort.
  5272. */
  5273. int compare_candidate(const void * a, const void * b) {
  5274. const struct Candidate *_a = a;
  5275. const struct Candidate *_b = b;
  5276. return strcmp(_a->text, _b->text);
  5277. }
  5278. /**
  5279. * List of file extensions to ignore when tab completing.
  5280. */
  5281. const char * tab_complete_ignore[] = {".o",NULL};
  5282. /**
  5283. * Wrapper around krk_valueGetAttribute...
  5284. */
  5285. static KrkValue findFromProperty(KrkValue current, KrkToken next) {
  5286. KrkValue member = OBJECT_VAL(krk_copyString(next.start, next.literalWidth));
  5287. krk_push(member);
  5288. KrkValue value = krk_valueGetAttribute_default(current, AS_CSTRING(member), NONE_VAL());
  5289. krk_pop();
  5290. return value;
  5291. }
  5292. /**
  5293. * Tab completion for command mode.
  5294. */
  5295. void command_tab_complete(char * buffer) {
  5296. /* Figure out which argument this is and where it starts */
  5297. int arg = 0;
  5298. char * buf = strdup(buffer);
  5299. char * b = buf;
  5300. int args_count = 0;
  5301. int args_space = 4;
  5302. char ** args = malloc(sizeof(char*)*args_space);
  5303. #define add_arg(argument) \
  5304. do { \
  5305. if (args_count == args_space) { \
  5306. args_space *= 2; \
  5307. args = realloc(args, sizeof(char*) * args_space); \
  5308. } \
  5309. args[args_count++] = argument; \
  5310. } while (0)
  5311. int candidate_count= 0;
  5312. int candidate_space = 4;
  5313. struct Candidate * candidates = malloc(sizeof(struct Candidate)*candidate_space);
  5314. /* Accept whitespace before first argument */
  5315. while (*b == ' ') b++;
  5316. char * start = b;
  5317. add_arg(start);
  5318. while (*b && *b != ' ') b++;
  5319. while (*b) {
  5320. while (*b == ' ') {
  5321. *b = '\0';
  5322. b++;
  5323. }
  5324. start = b;
  5325. arg++;
  5326. add_arg(start);
  5327. break;
  5328. }
  5329. /**
  5330. * Check a possible candidate and add it to the
  5331. * candidates list, expanding as necessary,
  5332. * if it matches for the current argument.
  5333. */
  5334. #define add_candidate(candidate,candtype) \
  5335. do { \
  5336. char * _arg = args[arg]; \
  5337. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5338. if (!r) { \
  5339. int skip = 0; \
  5340. for (int i = 0; i < candidate_count; ++i) { \
  5341. if (!strcmp(candidates[i].text,candidate)) { skip = 1; break; } \
  5342. } \
  5343. if (skip) break; \
  5344. if (candidate_count == candidate_space) { \
  5345. candidate_space *= 2; \
  5346. candidates = realloc(candidates,sizeof(struct Candidate) * candidate_space); \
  5347. } \
  5348. candidates[candidate_count].text = strdup(candidate); \
  5349. candidates[candidate_count].type = candtype; \
  5350. candidate_count++; \
  5351. } \
  5352. } while (0)
  5353. #define Candidate_Normal 0
  5354. #define Candidate_Command 1
  5355. #define Candidate_Builtin 2
  5356. int _candidates_are_files = 0;
  5357. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  5358. /* Complete command names */
  5359. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5360. add_candidate(c->name,Candidate_Command);
  5361. }
  5362. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5363. add_candidate(c->name,Candidate_Command);
  5364. }
  5365. goto _try_kuroko;
  5366. }
  5367. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5368. /* Complete syntax options */
  5369. add_candidate("none", Candidate_Builtin);
  5370. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  5371. add_candidate(s->name, Candidate_Builtin);
  5372. }
  5373. goto _accept_candidate;
  5374. }
  5375. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  5376. /* Complete color theme names */
  5377. for (struct theme_def * s = themes; themes && s->name; ++s) {
  5378. add_candidate(s->name, Candidate_Builtin);
  5379. }
  5380. goto _accept_candidate;
  5381. }
  5382. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  5383. for (struct ColorName * c = color_names; c->name; ++c) {
  5384. add_candidate(c->name, Candidate_Builtin);
  5385. }
  5386. goto _accept_candidate;
  5387. }
  5388. if (arg == 1 && (!strcmp(args[0], "action"))) {
  5389. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5390. add_candidate(a->name, Candidate_Builtin);
  5391. }
  5392. goto _accept_candidate;
  5393. }
  5394. if (arg == 1 && (!strcmp(args[0], "mapkey"))) {
  5395. for (int i = 0; args[arg][i]; ++i) {
  5396. if (args[arg][i] == ' ') {
  5397. while (args[arg][i] == ' ') {
  5398. args[arg][i] = '\0';
  5399. i++;
  5400. }
  5401. start = &args[arg][i];
  5402. arg++;
  5403. add_arg(start);
  5404. i = 0;
  5405. }
  5406. }
  5407. if (arg == 1) {
  5408. for (struct mode_names * m = mode_names; m->name; ++m) {
  5409. add_candidate(m->name, Candidate_Builtin);
  5410. }
  5411. } else if (arg == 2) {
  5412. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  5413. add_candidate(KeyNames[i].name, Candidate_Builtin);
  5414. }
  5415. } else if (arg == 3) {
  5416. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5417. add_candidate(a->name, Candidate_Builtin);
  5418. }
  5419. add_candidate("none", Candidate_Builtin);
  5420. } else if (arg == 4) {
  5421. for (char * c = "racnwmb"; *c; ++c) {
  5422. char tmp[] = {*c,'\0'};
  5423. add_candidate(tmp, Candidate_Builtin);
  5424. }
  5425. }
  5426. goto _accept_candidate;
  5427. }
  5428. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") ||
  5429. !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") ||
  5430. !strcmp(args[0],"rundir") || args[0][0] == '!')) {
  5431. /* Complete file paths */
  5432. /* First, find the deepest directory match */
  5433. char * tmp = strdup(args[arg]);
  5434. char * last_slash = strrchr(tmp, '/');
  5435. DIR * dirp;
  5436. if (last_slash) {
  5437. *last_slash = '\0';
  5438. if (last_slash == tmp) {
  5439. /* Started with slash, and it was the only slash */
  5440. dirp = opendir("/");
  5441. } else {
  5442. char * home;
  5443. if (*tmp == '~' && (home = getenv("HOME"))) {
  5444. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  5445. sprintf(t, "%s%s",home,tmp+1);
  5446. dirp = opendir(t);
  5447. free(t);
  5448. } else {
  5449. dirp = opendir(tmp);
  5450. }
  5451. }
  5452. } else {
  5453. /* No directory match, completing from current directory */
  5454. dirp = opendir(".");
  5455. tmp[0] = '\0';
  5456. }
  5457. if (!dirp) {
  5458. /* Directory match doesn't exist, no candidates to populate */
  5459. free(tmp);
  5460. goto done;
  5461. }
  5462. _candidates_are_files = 1;
  5463. struct dirent * ent = readdir(dirp);
  5464. while (ent != NULL) {
  5465. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5466. struct stat statbuf;
  5467. /* Figure out if this file is a directory */
  5468. if (last_slash) {
  5469. char * x;
  5470. char * home;
  5471. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  5472. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  5473. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  5474. } else {
  5475. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5476. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5477. }
  5478. stat(x, &statbuf);
  5479. free(x);
  5480. } else {
  5481. stat(ent->d_name, &statbuf);
  5482. }
  5483. /* Build the complete argument name to tab complete */
  5484. int type = Candidate_Normal;
  5485. char s[1024] = {0};
  5486. if (last_slash == tmp) {
  5487. strcat(s,"/");
  5488. } else if (*tmp) {
  5489. strcat(s,tmp);
  5490. strcat(s,"/");
  5491. }
  5492. strcat(s,ent->d_name);
  5493. /*
  5494. * If it is a directory, add a / to the end so the next completion
  5495. * attempt will complete the directory's contents.
  5496. */
  5497. if (S_ISDIR(statbuf.st_mode)) {
  5498. strcat(s,"/");
  5499. type = Candidate_Command;
  5500. }
  5501. int skip = 0;
  5502. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5503. if (str_ends_with(s, *c)) {
  5504. skip = 1;
  5505. break;
  5506. }
  5507. }
  5508. if (!skip) {
  5509. add_candidate(s, type);
  5510. }
  5511. }
  5512. ent = readdir(dirp);
  5513. }
  5514. closedir(dirp);
  5515. free(tmp);
  5516. goto _accept_candidate;
  5517. }
  5518. /* Hacky port of the kuroko repl completer */
  5519. {
  5520. _try_kuroko:
  5521. for (int i = 0; args[arg][i]; ++i) {
  5522. if (args[arg][i] == ' ') {
  5523. while (args[arg][i] == ' ') {
  5524. args[arg][i] = '\0';
  5525. i++;
  5526. }
  5527. start = &args[arg][i];
  5528. arg++;
  5529. add_arg(start);
  5530. i = 0;
  5531. }
  5532. }
  5533. krk_initScanner(args[arg]);
  5534. KrkToken * space = malloc(sizeof(KrkToken) * (strlen(args[arg]) + 2));
  5535. int count = 0;
  5536. do {
  5537. space[count++] = krk_scanToken();
  5538. } while (space[count-1].type != TOKEN_EOF && space[count-1].type != TOKEN_ERROR);
  5539. if (count == 1) {
  5540. goto _cleanup;
  5541. }
  5542. int base = 2;
  5543. int n = base;
  5544. if (space[count-base].type == TOKEN_DOT) {
  5545. /* Dots we need to look back at the previous tokens for */
  5546. n--;
  5547. base--;
  5548. } else if (space[count-base].type >= TOKEN_IDENTIFIER && space[count-base].type <= TOKEN_WITH) {
  5549. /* Something alphanumeric; only for the last element */
  5550. } else {
  5551. /* Some other symbol */
  5552. goto _cleanup;
  5553. }
  5554. while (n < count) {
  5555. if (space[count-n-1].type != TOKEN_DOT) break;
  5556. n++;
  5557. if (n == count) break;
  5558. if (space[count-n-1].type != TOKEN_IDENTIFIER) break;
  5559. n++;
  5560. }
  5561. if (n <= count) {
  5562. /* Now work forwards, starting from the current globals. */
  5563. KrkValue root = OBJECT_VAL(krk_currentThread.module);
  5564. int isGlobal = 1;
  5565. while (n > base) {
  5566. /* And look at the potential fields for instances/classes */
  5567. KrkValue next = findFromProperty(root, space[count-n]);
  5568. if (IS_NONE(next)) {
  5569. /* If we hit None, we found something invalid (or literally hit a None
  5570. * object, but really the difference is minimal in this case: Nothing
  5571. * useful to tab complete from here. */
  5572. if (!isGlobal) goto _cleanup;
  5573. /* Does this match a builtin? */
  5574. if (!krk_tableGet_fast(&vm.builtins->fields,
  5575. krk_copyString(space[count-n].start,space[count-n].literalWidth), &next) || IS_NONE(next)) {
  5576. goto _cleanup;
  5577. }
  5578. }
  5579. isGlobal = 0;
  5580. root = next;
  5581. n -= 2; /* To skip every other dot. */
  5582. }
  5583. /* Now figure out what we're completing - did we already have a partial symbol name? */
  5584. int length = (space[count-base].type == TOKEN_DOT) ? 0 : (space[count-base].length);
  5585. isGlobal = isGlobal && (length != 0);
  5586. /* Take the last symbol name from the chain and get its member list from dir() */
  5587. static char * syn_krk_keywords[] = {
  5588. "and","class","def","else","for","if","in","import","del",
  5589. "let","not","or","return","while","try","except","raise",
  5590. "continue","break","as","from","elif","lambda","with","is",
  5591. "pass","assert","yield","finally","async","await",
  5592. NULL
  5593. };
  5594. KrkInstance * fakeKeywordsObject = NULL;
  5595. for (;;) {
  5596. KrkValue dirList = krk_dirObject(1,(KrkValue[]){root},0);
  5597. krk_push(dirList);
  5598. if (!IS_INSTANCE(dirList)) {
  5599. render_error("Internal error while tab completing.");
  5600. goto _cleanup;
  5601. }
  5602. for (size_t i = 0; i < AS_LIST(dirList)->count; ++i) {
  5603. KrkString * s = AS_STRING(AS_LIST(dirList)->values[i]);
  5604. krk_push(OBJECT_VAL(s));
  5605. KrkToken asToken = {.start = s->chars, .literalWidth = s->length};
  5606. KrkValue thisValue = findFromProperty(root, asToken);
  5607. krk_push(thisValue);
  5608. if (IS_CLOSURE(thisValue) || IS_BOUND_METHOD(thisValue) ||
  5609. (IS_NATIVE(thisValue) && !(((KrkNative*)AS_OBJECT(thisValue))->flags & KRK_NATIVE_FLAGS_IS_DYNAMIC_PROPERTY))) {
  5610. size_t allocSize = s->length + 2;
  5611. char * tmp = malloc(allocSize);
  5612. size_t len = snprintf(tmp, allocSize, "%s(", s->chars);
  5613. s = krk_takeString(tmp, len);
  5614. krk_pop();
  5615. krk_push(OBJECT_VAL(s));
  5616. }
  5617. /* If this symbol is shorter than the current submatch, skip it. */
  5618. if (length && (int)s->length < length) continue;
  5619. if (!memcmp(s->chars, space[count-base].start, length)) {
  5620. char * tmp = malloc(strlen(args[arg]) + s->length + 1);
  5621. sprintf(tmp,"%s%s", args[arg], s->chars + length);
  5622. int type = Candidate_Normal;
  5623. if (IS_OBJECT(root) && AS_OBJECT(root) == (KrkObj*)vm.builtins) {
  5624. type = Candidate_Builtin;
  5625. } else if (IS_OBJECT(root) && AS_OBJECT(root) == (KrkObj*)fakeKeywordsObject) {
  5626. type = Candidate_Command;
  5627. }
  5628. add_candidate(tmp, type);
  5629. free(tmp);
  5630. }
  5631. }
  5632. /*
  5633. * If the object we were scanning was the current module,
  5634. * then we should also throw the builtins into the ring.
  5635. */
  5636. if (isGlobal && AS_OBJECT(root) == (KrkObj*)krk_currentThread.module) {
  5637. root = OBJECT_VAL(vm.builtins);
  5638. continue;
  5639. } else if (isGlobal && AS_OBJECT(root) == (KrkObj*)vm.builtins) {
  5640. fakeKeywordsObject = krk_newInstance(vm.baseClasses->objectClass);
  5641. root = OBJECT_VAL(fakeKeywordsObject);
  5642. krk_push(root);
  5643. for (char ** keyword = syn_krk_keywords; *keyword; keyword++) {
  5644. krk_attachNamedValue(&fakeKeywordsObject->fields, *keyword, NONE_VAL());
  5645. }
  5646. continue;
  5647. } else {
  5648. break;
  5649. }
  5650. }
  5651. }
  5652. _cleanup:
  5653. free(space);
  5654. krk_resetStack();
  5655. }
  5656. _accept_candidate:
  5657. if (candidate_count == 0) {
  5658. redraw_statusbar();
  5659. goto done;
  5660. }
  5661. if (candidate_count == 1) {
  5662. /* Only one completion possibility */
  5663. redraw_statusbar();
  5664. /* Fill out the rest of the command */
  5665. char * cstart = (buffer) + (start - buf);
  5666. for (unsigned int i = 0; i < strlen(candidates[0].text); ++i) {
  5667. *cstart = candidates[0].text[i];
  5668. cstart++;
  5669. }
  5670. *cstart = '\0';
  5671. } else {
  5672. /* Sort candidates */
  5673. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_candidate);
  5674. /* Print candidates in status bar */
  5675. char * tmp = malloc(global_config.term_width+1 + candidate_count * 100);
  5676. memset(tmp, 0, global_config.term_width+1);
  5677. int offset = 0;
  5678. for (int i = 0; i < candidate_count; ++i) {
  5679. char * printed_candidate = candidates[i].text;
  5680. if (_candidates_are_files) {
  5681. for (char * c = printed_candidate; *c; ++c) {
  5682. if (c[0] == '/' && c[1] != '\0') {
  5683. printed_candidate = c+1;
  5684. }
  5685. }
  5686. } else {
  5687. for (char * c = printed_candidate; *c; ++c) {
  5688. if ((c[0] == '.' || c[0] == '(') && c[1] != '\0') {
  5689. printed_candidate = c+1;
  5690. }
  5691. }
  5692. }
  5693. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5694. strcat(tmp, "...");
  5695. break;
  5696. }
  5697. if (offset > 0) {
  5698. strcat(tmp, " ");
  5699. offset++;
  5700. }
  5701. const char * colorString = color_string(
  5702. candidates[i].type == Candidate_Normal ? COLOR_STATUS_FG :
  5703. candidates[i].type == Candidate_Command ? COLOR_KEYWORD :
  5704. candidates[i].type == Candidate_Builtin ? COLOR_TYPE : COLOR_STATUS_FG,
  5705. COLOR_STATUS_BG);
  5706. /* Does not affect offset */
  5707. strcat(tmp, colorString);
  5708. strcat(tmp, printed_candidate);
  5709. offset += strlen(printed_candidate);
  5710. }
  5711. render_status_message("%s", tmp);
  5712. free(tmp);
  5713. /* Complete to longest common substring */
  5714. char * cstart = (buffer) + (start - buf);
  5715. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5716. for (int j = 1; j < candidate_count; ++j) {
  5717. if (candidates[0].text[i] != candidates[j].text[i]) goto _reject;
  5718. }
  5719. *cstart = candidates[0].text[i];
  5720. cstart++;
  5721. }
  5722. /* End of longest common substring */
  5723. _reject:
  5724. *cstart = '\0';
  5725. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5726. if (start > buf) { /* Start point needs to be something other than first byte */
  5727. char * tmp = cstart - 1;
  5728. if ((*tmp & 0xC0) == 0x80) {
  5729. /* Count back until we find the start byte and make sure we have the right number */
  5730. int count = 1;
  5731. int x = 0;
  5732. while (tmp >= start) {
  5733. x++;
  5734. tmp--;
  5735. if ((*tmp & 0xC0) == 0x80) {
  5736. count++;
  5737. } else if ((*tmp & 0xC0) == 0xC0) {
  5738. /* How many should we have? */
  5739. int i = 1;
  5740. int j = *tmp;
  5741. while (j & 0x20) {
  5742. i += 1;
  5743. j <<= 1;
  5744. }
  5745. if (count != i) {
  5746. *tmp = '\0';
  5747. break;
  5748. }
  5749. break;
  5750. } else {
  5751. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5752. tmp++;
  5753. *tmp = '\0';
  5754. break;
  5755. }
  5756. }
  5757. } else if ((*tmp & 0xC0) == 0xC0) {
  5758. *tmp = '\0';
  5759. }
  5760. }
  5761. }
  5762. /* Free candidates */
  5763. for (int i = 0; i < candidate_count; ++i) {
  5764. free(candidates[i].text);
  5765. }
  5766. done:
  5767. free(candidates);
  5768. free(buf);
  5769. }
  5770. /**
  5771. * Macros for use in command mode.
  5772. */
  5773. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5774. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5775. #define _restore_history(point) do { \
  5776. unsigned char * t = command_history[point]; \
  5777. global_config.command_col_no = 1; \
  5778. global_config.command_buffer->actual = 0; \
  5779. _syn_command(); \
  5780. uint32_t state = 0; \
  5781. uint32_t c = 0; \
  5782. while (*t) { \
  5783. if (!decode(&state, &c, *t)) { \
  5784. char_t _c = {codepoint_width(c), 0, c}; \
  5785. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1); \
  5786. global_config.command_col_no++; \
  5787. } else if (state == UTF8_REJECT) state = 0; \
  5788. t++; \
  5789. } \
  5790. _syn_restore(); \
  5791. } while (0)
  5792. /**
  5793. * Draw the command buffer and any prefix.
  5794. */
  5795. void render_command_input_buffer(void) {
  5796. if (!global_config.command_buffer) return;
  5797. /* Place the cursor at the bottom of the screen */
  5798. place_cursor(1, global_config.term_height);
  5799. paint_line(COLOR_BG);
  5800. set_colors(COLOR_ALT_FG, COLOR_BG);
  5801. /* If there's a mode name to render, draw it first */
  5802. int _left_gutter = 0;
  5803. if (env->mode == MODE_LINE_SELECTION) {
  5804. _left_gutter = printf("(LINE %d:%d)",
  5805. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5806. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5807. } else if (env->mode == MODE_COL_SELECTION) {
  5808. _left_gutter = printf("(COL %d:%d %d)",
  5809. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5810. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5811. (env->sel_col));
  5812. } else if (env->mode == MODE_CHAR_SELECTION) {
  5813. _left_gutter = printf("(CHAR)");
  5814. }
  5815. /* Figure out the cursor position and adjust the offset if necessary */
  5816. int x = 2 + _left_gutter - global_config.command_offset;
  5817. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5818. char_t * c = &global_config.command_buffer->text[i];
  5819. x += c->display_width;
  5820. }
  5821. if (x > global_config.term_width - 1) {
  5822. int diff = x - (global_config.term_width - 1);
  5823. global_config.command_offset += diff;
  5824. x -= diff;
  5825. }
  5826. if (x < 2 + _left_gutter) {
  5827. int diff = (2 + _left_gutter) - x;
  5828. global_config.command_offset -= diff;
  5829. x += diff;
  5830. }
  5831. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5832. if (global_config.command_offset) {
  5833. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5834. printf("<");
  5835. } else {
  5836. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5837. set_colors(COLOR_FG, COLOR_BG);
  5838. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5839. printf(global_config.search_direction == 0 ? "?" : "/");
  5840. } else if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  5841. printf("_");
  5842. } else {
  5843. printf(":");
  5844. }
  5845. }
  5846. /* Render the buffer */
  5847. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5848. /* Place and display the cursor */
  5849. place_cursor(x, global_config.term_height);
  5850. show_cursor();
  5851. }
  5852. BIM_ACTION(command_discard, 0,
  5853. "Discard the input buffer and cancel command or search."
  5854. )(void) {
  5855. free(global_config.command_buffer);
  5856. global_config.command_buffer = NULL;
  5857. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5858. env->line_no = global_config.prev_line;
  5859. env->col_no = global_config.prev_col;
  5860. /* Unhighlight search matches */
  5861. for (int i = 0; i < env->line_count; ++i) {
  5862. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5863. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5864. }
  5865. rehighlight_search(env->lines[i]);
  5866. }
  5867. }
  5868. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5869. redraw_all();
  5870. /* TODO exit some other modes? */
  5871. }
  5872. BIM_ACTION(enter_command, 0,
  5873. "Enter command input mode."
  5874. )(void) {
  5875. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  5876. global_config.command_offset = 0;
  5877. global_config.command_col_no = 1;
  5878. if (global_config.command_buffer) {
  5879. free(global_config.command_buffer);
  5880. }
  5881. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5882. global_config.command_buffer->available = 32;
  5883. global_config.command_syn_back = env->syntax;
  5884. global_config.command_syn = find_syntax_calculator("bimcmd");
  5885. global_config.history_point = -1;
  5886. render_command_input_buffer();
  5887. }
  5888. BIM_ACTION(command_accept, 0,
  5889. "Accept the command input and run the requested command."
  5890. )(void) {
  5891. /* Convert command buffer to UTF-8 char-array string */
  5892. size_t size = 0;
  5893. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5894. char tmp[8] = {0};
  5895. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  5896. }
  5897. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  5898. char * t = tmp;
  5899. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5900. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5901. }
  5902. *t = '\0';
  5903. /* Free the original editing buffer */
  5904. free(global_config.command_buffer);
  5905. global_config.command_buffer = NULL;
  5906. /* Run the converted command */
  5907. global_config.break_from_selection = 0;
  5908. insert_command_history(tmp);
  5909. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5910. process_command(tmp);
  5911. free(tmp);
  5912. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  5913. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  5914. recalculate_selected_lines();
  5915. }
  5916. env->mode = MODE_NORMAL;
  5917. }
  5918. /* Leave command mode */
  5919. }
  5920. BIM_ACTION(command_word_delete, 0,
  5921. "Delete the previous word from the input buffer."
  5922. )(void) {
  5923. _syn_command();
  5924. while (global_config.command_col_no > 1 &&
  5925. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  5926. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  5927. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5928. global_config.command_col_no--;
  5929. }
  5930. while (global_config.command_col_no > 1 &&
  5931. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  5932. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  5933. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5934. global_config.command_col_no--;
  5935. }
  5936. _syn_restore();
  5937. }
  5938. BIM_ACTION(command_tab_complete_buffer, 0,
  5939. "Complete command names and arguments in the input buffer."
  5940. )(void) {
  5941. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  5942. char * tmp = calloc(1024,1);
  5943. char * t = tmp;
  5944. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  5945. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5946. }
  5947. *t = '\0';
  5948. _syn_command();
  5949. while (global_config.command_col_no > 1) {
  5950. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5951. global_config.command_col_no--;
  5952. }
  5953. _syn_restore();
  5954. command_tab_complete(tmp);
  5955. _syn_command();
  5956. uint32_t state = 0, c= 0;
  5957. t = tmp;
  5958. while (*t) {
  5959. if (!decode(&state, &c, *t)) {
  5960. char_t _c = {codepoint_width(c), 0, c};
  5961. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5962. global_config.command_col_no++;
  5963. }
  5964. t++;
  5965. }
  5966. _syn_restore();
  5967. free(tmp);
  5968. }
  5969. BIM_ACTION(command_backspace, 0,
  5970. "Erase the character before the cursor in the input buffer."
  5971. )(void) {
  5972. if (global_config.command_col_no <= 1) {
  5973. if (global_config.command_buffer->actual == 0) {
  5974. command_discard();
  5975. }
  5976. return;
  5977. }
  5978. _syn_command();
  5979. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5980. _syn_restore();
  5981. global_config.command_col_no--;
  5982. global_config.command_offset = 0;
  5983. }
  5984. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  5985. "Scroll through command input history."
  5986. )(int direction) {
  5987. if (direction == -1) {
  5988. if (command_history[global_config.history_point+1]) {
  5989. _restore_history(global_config.history_point+1);
  5990. global_config.history_point++;
  5991. }
  5992. } else {
  5993. if (global_config.history_point > 0) {
  5994. global_config.history_point--;
  5995. _restore_history(global_config.history_point);
  5996. } else {
  5997. global_config.history_point = -1;
  5998. global_config.command_col_no = 1;
  5999. global_config.command_buffer->actual = 0;
  6000. }
  6001. }
  6002. }
  6003. BIM_ACTION(command_word_left, 0,
  6004. "Move to the start of the previous word in the input buffer."
  6005. )(void) {
  6006. if (global_config.command_col_no > 1) {
  6007. do {
  6008. global_config.command_col_no--;
  6009. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  6010. if (global_config.command_col_no == 1) return;
  6011. do {
  6012. global_config.command_col_no--;
  6013. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  6014. 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++;
  6015. }
  6016. }
  6017. BIM_ACTION(command_word_right, 0,
  6018. "Move to the start of the next word in the input buffer."
  6019. )(void) {
  6020. if (global_config.command_col_no < global_config.command_buffer->actual) {
  6021. do {
  6022. global_config.command_col_no++;
  6023. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  6024. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  6025. do {
  6026. global_config.command_col_no++;
  6027. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  6028. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  6029. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  6030. }
  6031. }
  6032. BIM_ACTION(command_cursor_left, 0,
  6033. "Move the cursor one character left in the input buffer."
  6034. )(void) {
  6035. if (global_config.command_col_no > 1) global_config.command_col_no--;
  6036. }
  6037. BIM_ACTION(command_cursor_right, 0,
  6038. "Move the cursor one character right in the input buffer."
  6039. )(void) {
  6040. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  6041. }
  6042. BIM_ACTION(command_cursor_home, 0,
  6043. "Move the cursor to the start of the input buffer."
  6044. )(void) {
  6045. global_config.command_col_no = 1;
  6046. }
  6047. BIM_ACTION(command_cursor_end, 0,
  6048. "Move the cursor to the end of the input buffer."
  6049. )(void) {
  6050. global_config.command_col_no = global_config.command_buffer->actual + 1;
  6051. }
  6052. BIM_ACTION(eat_mouse, 0,
  6053. "(temporary) Read, but ignore mouse input."
  6054. )(void) {
  6055. bim_getch();
  6056. bim_getch();
  6057. bim_getch();
  6058. }
  6059. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  6060. "Insert one character into the input buffer."
  6061. )(int c) {
  6062. char_t _c = {codepoint_width(c), 0, c};
  6063. _syn_command();
  6064. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  6065. _syn_restore();
  6066. global_config.command_col_no++;
  6067. }
  6068. /**
  6069. * Determine whether a string should be searched
  6070. * case-sensitive or not based on whether it contains
  6071. * any upper-case letters.
  6072. */
  6073. int smart_case(uint32_t * str) {
  6074. if (!global_config.smart_case) return 0;
  6075. for (uint32_t * s = str; *s; ++s) {
  6076. if (tolower(*s) != (int)*s) {
  6077. return 0;
  6078. }
  6079. }
  6080. return 1;
  6081. }
  6082. /**
  6083. * Search forward from the given cursor position
  6084. * to find a basic search match.
  6085. *
  6086. * This could be more complicated...
  6087. */
  6088. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  6089. int col = from_col;
  6090. int ignorecase = smart_case(str);
  6091. for (int i = from_line; i <= env->line_count; ++i) {
  6092. line_t * line = env->lines[i - 1];
  6093. int j = col - 1;
  6094. while (j < line->actual + 1) {
  6095. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  6096. *out_line = i;
  6097. *out_col = j + 1;
  6098. return;
  6099. }
  6100. j++;
  6101. }
  6102. col = 0;
  6103. }
  6104. }
  6105. /**
  6106. * Search backwards for matching string.
  6107. */
  6108. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  6109. int col = from_col;
  6110. int ignorecase = smart_case(str);
  6111. for (int i = from_line; i >= 1; --i) {
  6112. line_t * line = env->lines[i-1];
  6113. int j = col - 1;
  6114. while (j > -1) {
  6115. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  6116. *out_line = i;
  6117. *out_col = j + 1;
  6118. return;
  6119. }
  6120. j--;
  6121. }
  6122. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  6123. }
  6124. }
  6125. /**
  6126. * Re-mark search matches while editing text.
  6127. * This gets called after recalculate_syntax, so it works as we're typing or
  6128. * whenever syntax calculation would redraw other lines.
  6129. * XXX There's a bunch of code duplication between the (now three) search match functions.
  6130. * and search should be improved to support regex anyway, so this needs to be fixed.
  6131. */
  6132. void rehighlight_search(line_t * line) {
  6133. if (!global_config.search) return;
  6134. int j = 0;
  6135. while (j < line->actual) {
  6136. line->text[j].flags &= ~(FLAG_SEARCH);
  6137. j++;
  6138. }
  6139. int ignorecase = smart_case(global_config.search);
  6140. j = 0;
  6141. while (j < line->actual) {
  6142. int matchlen = 0;
  6143. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  6144. for (int i = j; matchlen > 0; ++i, matchlen--) {
  6145. line->text[i].flags |= FLAG_SEARCH;
  6146. }
  6147. }
  6148. j++;
  6149. }
  6150. }
  6151. /**
  6152. * Draw the matched search result.
  6153. */
  6154. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  6155. for (int i = 0; i < env->line_count; ++i) {
  6156. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6157. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6158. }
  6159. }
  6160. int my_index = 0, match_count = 0;
  6161. int line = -1, col = -1, _line = 1, _col = 1;
  6162. do {
  6163. int matchlen;
  6164. find_match(_line, _col, &line, &col, buffer, &matchlen);
  6165. if (line != -1) {
  6166. line_t * l = env->lines[line-1];
  6167. for (int i = col; matchlen > 0; ++i, --matchlen) {
  6168. l->text[i-1].flags |= FLAG_SEARCH;
  6169. }
  6170. match_count += 1;
  6171. if (col == env->col_no && line == env->line_no) my_index = match_count;
  6172. }
  6173. _line = line;
  6174. _col = col+1;
  6175. line = -1;
  6176. col = -1;
  6177. } while (_line != -1);
  6178. redraw_text();
  6179. place_cursor_actual();
  6180. redraw_statusbar();
  6181. redraw_commandline();
  6182. set_fg_color(COLOR_ALT_FG);
  6183. printf("[%d/%d] ", my_index, match_count);
  6184. set_fg_color(COLOR_KEYWORD);
  6185. printf(redraw_buffer == 1 ? "/" : "?");
  6186. set_fg_color(COLOR_FG);
  6187. uint32_t * c = buffer;
  6188. while (*c) {
  6189. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  6190. to_eight(*c, tmp);
  6191. printf("%s", tmp);
  6192. c++;
  6193. }
  6194. }
  6195. BIM_ACTION(start_file_search, 0, "Search for open files and switch tabs quickly.")(void) {
  6196. global_config.overlay_mode = OVERLAY_MODE_FILESEARCH;
  6197. global_config.command_offset = 0;
  6198. global_config.command_col_no = 1;
  6199. if (global_config.command_buffer) {
  6200. free(global_config.command_buffer);
  6201. }
  6202. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6203. global_config.command_buffer->available = 32;
  6204. global_config.command_syn_back = env->syntax;
  6205. global_config.command_syn = NULL; /* uh, dunno for now */
  6206. render_command_input_buffer();
  6207. }
  6208. BIM_ACTION(file_search_accept, 0, "Open the requested tab")(void) {
  6209. if (!global_config.command_buffer->actual) {
  6210. goto _finish;
  6211. }
  6212. /* See if the command buffer matches any open buffers */
  6213. buffer_t * match = NULL;
  6214. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6215. buffer_t * _env = buffers[i];
  6216. if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  6217. if (global_config.command_buffer->actual) {
  6218. char * f = _env->file_name ? file_basename(_env->file_name) : "";
  6219. /* TODO: Support unicode input here; needs conversion */
  6220. int i = 0;
  6221. for (; i < global_config.command_buffer->actual &&
  6222. f[i] == global_config.command_buffer->text[i].codepoint; ++i);
  6223. if (global_config.command_buffer->actual == i) {
  6224. match = _env;
  6225. break;
  6226. }
  6227. }
  6228. }
  6229. }
  6230. if (match) {
  6231. env = match;
  6232. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  6233. }
  6234. _finish:
  6235. /* Free the original editing buffer */
  6236. free(global_config.command_buffer);
  6237. global_config.command_buffer = NULL;
  6238. /* Leave command mode */
  6239. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6240. redraw_all();
  6241. }
  6242. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  6243. "Enter search mode."
  6244. )(int direction) {
  6245. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  6246. global_config.command_offset = 0;
  6247. global_config.command_col_no = 1;
  6248. global_config.prev_line = env->line_no;
  6249. global_config.prev_col = env->col_no;
  6250. global_config.prev_coffset = env->coffset;
  6251. global_config.prev_offset = env->offset;
  6252. global_config.search_direction = direction;
  6253. if (global_config.command_buffer) {
  6254. free(global_config.command_buffer);
  6255. }
  6256. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6257. global_config.command_buffer->available = 32;
  6258. global_config.command_syn_back = env->syntax;
  6259. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  6260. render_command_input_buffer();
  6261. }
  6262. BIM_ACTION(search_accept, 0,
  6263. "Accept the search term and return to the previous mode."
  6264. )(void) {
  6265. /* Store the accepted search */
  6266. if (!global_config.command_buffer->actual) {
  6267. if (global_config.search) {
  6268. search_next();
  6269. }
  6270. goto _finish;
  6271. }
  6272. if (global_config.search) {
  6273. free(global_config.search);
  6274. }
  6275. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  6276. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6277. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  6278. }
  6279. global_config.search[global_config.command_buffer->actual] = 0;
  6280. _finish:
  6281. /* Free the original editing buffer */
  6282. free(global_config.command_buffer);
  6283. global_config.command_buffer = NULL;
  6284. /* Leave command mode */
  6285. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6286. if (global_config.search) draw_search_match(global_config.search, global_config.search_direction);
  6287. }
  6288. /**
  6289. * Find the next search result, or loop back around if at the end.
  6290. */
  6291. BIM_ACTION(search_next, 0,
  6292. "Jump to the next search match."
  6293. )(void) {
  6294. if (!global_config.search) return;
  6295. if (env->coffset) env->coffset = 0;
  6296. int line = -1, col = -1, wrapped = 0;
  6297. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  6298. if (line == -1) {
  6299. if (!global_config.search_wraps) return;
  6300. find_match(1,1, &line, &col, global_config.search, NULL);
  6301. if (line == -1) return;
  6302. wrapped = 1;
  6303. }
  6304. env->col_no = col;
  6305. env->line_no = line;
  6306. set_preferred_column();
  6307. draw_search_match(global_config.search, 1);
  6308. if (wrapped) {
  6309. set_fg_color(COLOR_ALT_FG);
  6310. printf(" (search wrapped to top)");
  6311. }
  6312. }
  6313. /**
  6314. * Find the previous search result, or loop to the end of the file.
  6315. */
  6316. BIM_ACTION(search_prev, 0,
  6317. "Jump to the preceding search match."
  6318. )(void) {
  6319. if (!global_config.search) return;
  6320. if (env->coffset) env->coffset = 0;
  6321. int line = -1, col = -1, wrapped = 0;
  6322. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  6323. if (line == -1) {
  6324. if (!global_config.search_wraps) return;
  6325. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  6326. if (line == -1) return;
  6327. wrapped = 1;
  6328. }
  6329. env->col_no = col;
  6330. env->line_no = line;
  6331. set_preferred_column();
  6332. draw_search_match(global_config.search, 0);
  6333. if (wrapped) {
  6334. set_fg_color(COLOR_ALT_FG);
  6335. printf(" (search wrapped to bottom)");
  6336. }
  6337. }
  6338. /**
  6339. * Find the matching paren for this one.
  6340. *
  6341. * This approach skips having to do its own syntax parsing
  6342. * to deal with, eg., erroneous parens in comments. It does
  6343. * this by finding the matching paren with the same flag
  6344. * value, thus parens in strings will match, parens outside
  6345. * of strings will match, but parens in strings won't
  6346. * match parens outside of strings and so on.
  6347. */
  6348. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  6349. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  6350. return; /* Invalid cursor position */
  6351. }
  6352. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  6353. int paren_match = 0;
  6354. int direction = 0;
  6355. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  6356. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  6357. int count = 0;
  6358. /* TODO what about unicode parens? */
  6359. for (int i = 0; paren_pairs[i]; ++i) {
  6360. if (start == paren_pairs[i]) {
  6361. direction = (i % 2 == 0) ? 1 : -1;
  6362. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  6363. break;
  6364. }
  6365. }
  6366. if (!paren_match) return;
  6367. /* Scan for match */
  6368. int line = env->line_no;
  6369. int col = env->col_no - in_col + 1;
  6370. do {
  6371. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  6372. /* Only match on same syntax */
  6373. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  6374. /* Count up on same direction */
  6375. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  6376. /* Count down on opposite direction */
  6377. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  6378. count--;
  6379. /* When count == 0 we have a match */
  6380. if (count == 0) goto _match_found;
  6381. }
  6382. }
  6383. col += direction;
  6384. }
  6385. line += direction;
  6386. /* Reached first/last line with no match */
  6387. if (line == 0 || line == env->line_count + 1) {
  6388. return;
  6389. }
  6390. /* Reset column to start/end of line, depending on direction */
  6391. if (direction > 0) {
  6392. col = 1;
  6393. } else {
  6394. col = env->lines[line-1]->actual;
  6395. }
  6396. } while (1);
  6397. _match_found:
  6398. *out_line = line;
  6399. *out_col = col;
  6400. }
  6401. /**
  6402. * Switch to the left split view
  6403. * (Primarily to handle cases where the left and right are the same buffer)
  6404. */
  6405. BIM_ACTION(use_left_buffer, 0,
  6406. "Switch to the left split view."
  6407. )(void) {
  6408. if (left_buffer == right_buffer && env->left != 0) {
  6409. view_right_offset = env->offset;
  6410. env->width = env->left;
  6411. env->left = 0;
  6412. env->offset = view_left_offset;
  6413. }
  6414. env = left_buffer;
  6415. update_title();
  6416. }
  6417. /**
  6418. * Switch to the right split view
  6419. * (Primarily to handle cases where the left and right are the same buffer)
  6420. */
  6421. BIM_ACTION(use_right_buffer, 0,
  6422. "Switch to the right split view."
  6423. )(void) {
  6424. if (left_buffer == right_buffer && env->left == 0) {
  6425. view_left_offset = env->offset;
  6426. env->left = env->width;
  6427. env->width = global_config.term_width - env->width;
  6428. env->offset = view_right_offset;
  6429. }
  6430. env = right_buffer;
  6431. update_title();
  6432. }
  6433. void handle_common_mouse(int buttons, int x, int y) {
  6434. if (buttons == 64) {
  6435. /* Scroll up */
  6436. if (global_config.shift_scrolling) {
  6437. env->loading = 1;
  6438. int shifted = 0;
  6439. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6440. if (env->offset > 0) {
  6441. env->offset--;
  6442. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  6443. cursor_up();
  6444. }
  6445. shifted++;
  6446. }
  6447. }
  6448. env->loading = 0;
  6449. if (!shifted) return;
  6450. if (global_config.can_scroll && !left_buffer) {
  6451. if (!global_config.can_insert) {
  6452. shift_down(shifted);
  6453. redraw_tabbar();
  6454. } else {
  6455. insert_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6456. }
  6457. for (int i = 0; i < shifted; ++i) {
  6458. redraw_line(env->offset+i);
  6459. }
  6460. } else {
  6461. redraw_tabbar();
  6462. redraw_text();
  6463. }
  6464. redraw_statusbar();
  6465. redraw_commandline();
  6466. place_cursor_actual();
  6467. } else {
  6468. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6469. cursor_up();
  6470. }
  6471. }
  6472. return;
  6473. } else if (buttons == 65) {
  6474. /* Scroll down */
  6475. if (global_config.shift_scrolling) {
  6476. env->loading = 1;
  6477. int shifted = 0;
  6478. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6479. if (env->offset < env->line_count-1) {
  6480. env->offset++;
  6481. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  6482. if (env->line_no <= e) {
  6483. cursor_down();
  6484. }
  6485. shifted++;
  6486. }
  6487. }
  6488. env->loading = 0;
  6489. if (!shifted) return;
  6490. if (global_config.can_scroll && !left_buffer) {
  6491. if (!global_config.can_insert) {
  6492. shift_up(shifted);
  6493. redraw_tabbar();
  6494. } else {
  6495. delete_lines_at(global_config.tabs_visible ? 2 : 1, shifted);
  6496. }
  6497. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  6498. for (int i = 0; i < shifted; ++i) {
  6499. if (env->offset + l - i < env->line_count + 1) {
  6500. redraw_line(env->offset + l-1-i);
  6501. } else {
  6502. draw_excess_line(l - 1 - i);
  6503. }
  6504. }
  6505. } else {
  6506. redraw_tabbar();
  6507. redraw_text();
  6508. }
  6509. redraw_statusbar();
  6510. redraw_commandline();
  6511. place_cursor_actual();
  6512. } else {
  6513. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6514. cursor_down();
  6515. }
  6516. }
  6517. return;
  6518. } else if (buttons == 3) {
  6519. /* Move cursor to position */
  6520. if (x < 0) return;
  6521. if (y < 0) return;
  6522. if (y == 1 && global_config.tabs_visible) {
  6523. /* Pick from tabs */
  6524. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  6525. int _x = 0;
  6526. if (global_config.tab_offset) _x = 1;
  6527. if (global_config.tab_offset && _x >= x) {
  6528. global_config.tab_offset--;
  6529. redraw_tabbar();
  6530. return;
  6531. }
  6532. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6533. buffer_t * _env = buffers[i];
  6534. char tmp[64];
  6535. int size = 0;
  6536. int filled = draw_tab_name(_env, tmp, global_config.term_width - _x, &size);
  6537. _x += size;
  6538. if (_x >= x) {
  6539. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  6540. env = buffers[i];
  6541. redraw_all();
  6542. update_title();
  6543. return;
  6544. }
  6545. if (filled) break;
  6546. }
  6547. if (x > _x && global_config.tab_offset < buffers_len - 1) {
  6548. global_config.tab_offset++;
  6549. redraw_tabbar();
  6550. }
  6551. return;
  6552. }
  6553. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  6554. int current_mode = env->mode;
  6555. if (x < env->left && env == right_buffer) {
  6556. use_left_buffer();
  6557. } else if (x > env->width && env == left_buffer) {
  6558. use_right_buffer();
  6559. }
  6560. env->mode = current_mode;
  6561. redraw_all();
  6562. }
  6563. if (env->left) {
  6564. x -= env->left;
  6565. }
  6566. /* Figure out y coordinate */
  6567. int line_no = y + env->offset - global_config.tabs_visible;
  6568. int col_no = -1;
  6569. if (line_no > env->line_count) {
  6570. line_no = env->line_count;
  6571. }
  6572. if (line_no != env->line_no) {
  6573. env->coffset = 0;
  6574. }
  6575. /* Account for the left hand gutter */
  6576. int num_size = num_width() + gutter_width();
  6577. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  6578. /* Determine where the cursor is physically */
  6579. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  6580. char_t * c = &env->lines[line_no-1]->text[i];
  6581. _x += c->display_width;
  6582. if (_x > x-1) {
  6583. col_no = i+1;
  6584. break;
  6585. }
  6586. }
  6587. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  6588. col_no = env->lines[line_no-1]->actual;
  6589. }
  6590. env->line_no = line_no;
  6591. env->col_no = col_no;
  6592. set_history_break();
  6593. set_preferred_column();
  6594. redraw_statusbar();
  6595. place_cursor_actual();
  6596. }
  6597. return;
  6598. }
  6599. /**
  6600. * Handle mouse event
  6601. */
  6602. BIM_ACTION(handle_mouse, 0,
  6603. "Process mouse actions."
  6604. )(void) {
  6605. int buttons = bim_getch() - 32;
  6606. int x = bim_getch() - 32;
  6607. int y = bim_getch() - 32;
  6608. handle_common_mouse(buttons, x, y);
  6609. }
  6610. BIM_ACTION(eat_mouse_sgr, 0,
  6611. "Receive, but do not process, mouse actions."
  6612. )(void) {
  6613. do {
  6614. int _c = bim_getch();
  6615. if (_c == -1 || _c == 'm' || _c == 'M') break;
  6616. } while (1);
  6617. }
  6618. BIM_ACTION(handle_mouse_sgr, 0,
  6619. "Process SGR-style mouse actions."
  6620. )(void) {
  6621. int values[3] = {0};
  6622. char tmp[512] = {0};
  6623. char * c = tmp;
  6624. int buttons = 0;
  6625. do {
  6626. int _c = bim_getch();
  6627. if (_c == -1) {
  6628. break;
  6629. }
  6630. if (_c == 'm') {
  6631. buttons = 3;
  6632. break;
  6633. } else if (_c == 'M') {
  6634. buttons = 0;
  6635. break;
  6636. }
  6637. *c = _c;
  6638. ++c;
  6639. } while (1);
  6640. char * j = tmp;
  6641. char * last = tmp;
  6642. int i = 0;
  6643. while (*j) {
  6644. if (*j == ';') {
  6645. *j = '\0';
  6646. values[i] = atoi(last);
  6647. last = j+1;
  6648. i++;
  6649. if (i == 3) break;
  6650. }
  6651. j++;
  6652. }
  6653. if (last && i < 3) values[i] = atoi(last);
  6654. if (buttons != 3) {
  6655. buttons = values[0];
  6656. }
  6657. int x = values[1];
  6658. int y = values[2];
  6659. handle_common_mouse(buttons, x, y);
  6660. }
  6661. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  6662. "Insert one character."
  6663. )(unsigned int c) {
  6664. if (!c) {
  6665. render_error("Inserted nil byte?");
  6666. return;
  6667. }
  6668. char_t _c;
  6669. _c.codepoint = c;
  6670. _c.flags = 0;
  6671. _c.display_width = codepoint_width(c);
  6672. line_t * line = env->lines[env->line_no - 1];
  6673. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6674. if (line != nline) {
  6675. env->lines[env->line_no - 1] = nline;
  6676. }
  6677. env->col_no += 1;
  6678. set_preferred_column();
  6679. set_modified();
  6680. }
  6681. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  6682. "Replace a single character."
  6683. )(unsigned int c) {
  6684. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6685. if (c >= KEY_ESCAPE) {
  6686. render_error("Invalid key for replacement");
  6687. return;
  6688. }
  6689. char_t _c;
  6690. _c.codepoint = c;
  6691. _c.flags = 0;
  6692. _c.display_width = codepoint_width(c);
  6693. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6694. redraw_line(env->line_no-1);
  6695. set_modified();
  6696. }
  6697. BIM_ACTION(undo_history, ACTION_IS_RW,
  6698. "Undo history until the last breakpoint."
  6699. )(void) {
  6700. if (!global_config.history_enabled) return;
  6701. env->loading = 1;
  6702. history_t * e = env->history;
  6703. if (e->type == HISTORY_SENTINEL) {
  6704. env->loading = 0;
  6705. render_commandline_message("Already at oldest change");
  6706. return;
  6707. }
  6708. int count_chars = 0;
  6709. int count_lines = 0;
  6710. do {
  6711. if (e->type == HISTORY_SENTINEL) break;
  6712. switch (e->type) {
  6713. case HISTORY_INSERT:
  6714. /* Delete */
  6715. line_delete(
  6716. env->lines[e->contents.insert_delete_replace.lineno],
  6717. e->contents.insert_delete_replace.offset+1,
  6718. e->contents.insert_delete_replace.lineno
  6719. );
  6720. count_chars++;
  6721. break;
  6722. case HISTORY_DELETE:
  6723. {
  6724. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6725. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6726. env->lines[e->contents.insert_delete_replace.lineno],
  6727. _c,
  6728. e->contents.insert_delete_replace.offset-1,
  6729. e->contents.insert_delete_replace.lineno
  6730. );
  6731. }
  6732. count_chars++;
  6733. break;
  6734. case HISTORY_REPLACE:
  6735. {
  6736. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6737. line_replace(
  6738. env->lines[e->contents.insert_delete_replace.lineno],
  6739. _o,
  6740. e->contents.insert_delete_replace.offset,
  6741. e->contents.insert_delete_replace.lineno
  6742. );
  6743. }
  6744. count_chars++;
  6745. break;
  6746. case HISTORY_REMOVE_LINE:
  6747. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6748. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6749. count_lines++;
  6750. break;
  6751. case HISTORY_ADD_LINE:
  6752. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6753. count_lines++;
  6754. break;
  6755. case HISTORY_REPLACE_LINE:
  6756. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6757. count_lines++;
  6758. break;
  6759. case HISTORY_SPLIT_LINE:
  6760. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6761. count_lines++;
  6762. break;
  6763. case HISTORY_MERGE_LINES:
  6764. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6765. count_lines++;
  6766. break;
  6767. case HISTORY_BREAK:
  6768. /* Ignore break */
  6769. break;
  6770. default:
  6771. render_error("Unknown type %d!\n", e->type);
  6772. break;
  6773. }
  6774. env->line_no = env->history->line;
  6775. env->col_no = env->history->col;
  6776. env->history = e->previous;
  6777. e = env->history;
  6778. } while (e->type != HISTORY_BREAK);
  6779. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6780. if (env->line_no < 1) env->line_no = 1;
  6781. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6782. if (env->col_no < 1) env->col_no = 1;
  6783. env->modified = (env->history != env->last_save_history);
  6784. env->loading = 0;
  6785. for (int i = 0; i < env->line_count; ++i) {
  6786. env->lines[i]->istate = 0;
  6787. recalculate_tabs(env->lines[i]);
  6788. }
  6789. schedule_complete_recalc();
  6790. place_cursor_actual();
  6791. update_title();
  6792. redraw_all();
  6793. render_commandline_message("%d character%s, %d line%s changed",
  6794. count_chars, (count_chars == 1) ? "" : "s",
  6795. count_lines, (count_lines == 1) ? "" : "s");
  6796. }
  6797. BIM_ACTION(redo_history, ACTION_IS_RW,
  6798. "Redo history until the next breakpoint."
  6799. )(void) {
  6800. if (!global_config.history_enabled) return;
  6801. env->loading = 1;
  6802. history_t * e = env->history->next;
  6803. if (!e) {
  6804. env->loading = 0;
  6805. render_commandline_message("Already at newest change");
  6806. return;
  6807. }
  6808. int count_chars = 0;
  6809. int count_lines = 0;
  6810. while (e) {
  6811. if (e->type == HISTORY_BREAK) {
  6812. env->history = e;
  6813. break;
  6814. }
  6815. switch (e->type) {
  6816. case HISTORY_INSERT:
  6817. {
  6818. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6819. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6820. env->lines[e->contents.insert_delete_replace.lineno],
  6821. _c,
  6822. e->contents.insert_delete_replace.offset,
  6823. e->contents.insert_delete_replace.lineno
  6824. );
  6825. }
  6826. count_chars++;
  6827. break;
  6828. case HISTORY_DELETE:
  6829. /* Delete */
  6830. line_delete(
  6831. env->lines[e->contents.insert_delete_replace.lineno],
  6832. e->contents.insert_delete_replace.offset,
  6833. e->contents.insert_delete_replace.lineno
  6834. );
  6835. count_chars++;
  6836. break;
  6837. case HISTORY_REPLACE:
  6838. {
  6839. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6840. line_replace(
  6841. env->lines[e->contents.insert_delete_replace.lineno],
  6842. _o,
  6843. e->contents.insert_delete_replace.offset,
  6844. e->contents.insert_delete_replace.lineno
  6845. );
  6846. }
  6847. count_chars++;
  6848. break;
  6849. case HISTORY_ADD_LINE:
  6850. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6851. count_lines++;
  6852. break;
  6853. case HISTORY_REMOVE_LINE:
  6854. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6855. count_lines++;
  6856. break;
  6857. case HISTORY_REPLACE_LINE:
  6858. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6859. count_lines++;
  6860. break;
  6861. case HISTORY_MERGE_LINES:
  6862. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6863. count_lines++;
  6864. break;
  6865. case HISTORY_SPLIT_LINE:
  6866. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6867. count_lines++;
  6868. break;
  6869. case HISTORY_BREAK:
  6870. /* Ignore break */
  6871. break;
  6872. default:
  6873. render_error("Unknown type %d!\n", e->type);
  6874. break;
  6875. }
  6876. env->history = e;
  6877. e = e->next;
  6878. }
  6879. env->line_no = env->history->line;
  6880. env->col_no = env->history->col;
  6881. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6882. if (env->line_no < 1) env->line_no = 1;
  6883. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6884. if (env->col_no < 1) env->col_no = 1;
  6885. env->modified = (env->history != env->last_save_history);
  6886. env->loading = 0;
  6887. for (int i = 0; i < env->line_count; ++i) {
  6888. env->lines[i]->istate = 0;
  6889. recalculate_tabs(env->lines[i]);
  6890. }
  6891. schedule_complete_recalc();
  6892. place_cursor_actual();
  6893. update_title();
  6894. redraw_all();
  6895. render_commandline_message("%d character%s, %d line%s changed",
  6896. count_chars, (count_chars == 1) ? "" : "s",
  6897. count_lines, (count_lines == 1) ? "" : "s");
  6898. }
  6899. int is_whitespace(int codepoint) {
  6900. return codepoint == ' ' || codepoint == '\t';
  6901. }
  6902. int is_normal(int codepoint) {
  6903. return isalnum(codepoint) || codepoint == '_';
  6904. }
  6905. int is_special(int codepoint) {
  6906. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6907. }
  6908. BIM_ACTION(word_left, 0,
  6909. "Move the cursor left to the previous word."
  6910. )(void) {
  6911. if (!env->lines[env->line_no-1]) return;
  6912. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6913. env->col_no -= 1;
  6914. }
  6915. if (env->col_no == 1) {
  6916. if (env->line_no == 1) goto _place;
  6917. env->line_no--;
  6918. env->col_no = env->lines[env->line_no-1]->actual;
  6919. goto _place;
  6920. }
  6921. int (*inverse_comparator)(int) = is_special;
  6922. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6923. inverse_comparator = is_normal;
  6924. }
  6925. do {
  6926. if (env->col_no > 1) {
  6927. env->col_no -= 1;
  6928. }
  6929. } 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));
  6930. _place:
  6931. set_preferred_column();
  6932. place_cursor_actual();
  6933. }
  6934. BIM_ACTION(big_word_left, 0,
  6935. "Move the cursor left to the previous WORD."
  6936. )(void) {
  6937. int line_no = env->line_no;
  6938. int col_no = env->col_no;
  6939. do {
  6940. col_no--;
  6941. while (col_no == 0) {
  6942. line_no--;
  6943. if (line_no == 0) {
  6944. goto_line(1);
  6945. set_preferred_column();
  6946. return;
  6947. }
  6948. col_no = env->lines[line_no-1]->actual;
  6949. }
  6950. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6951. do {
  6952. col_no--;
  6953. if (col_no == 0) {
  6954. env->col_no = 1;
  6955. env->line_no = line_no;
  6956. set_preferred_column();
  6957. redraw_statusbar();
  6958. place_cursor_actual();
  6959. return;
  6960. }
  6961. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6962. env->col_no = col_no;
  6963. env->line_no = line_no;
  6964. set_preferred_column();
  6965. cursor_right();
  6966. }
  6967. BIM_ACTION(word_right, 0,
  6968. "Move the cursor right to the start of the next word."
  6969. )(void) {
  6970. if (!env->lines[env->line_no-1]) return;
  6971. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6972. /* next line */
  6973. if (env->line_no == env->line_count) return;
  6974. env->line_no++;
  6975. env->col_no = 0;
  6976. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6977. goto _place;
  6978. }
  6979. }
  6980. 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)) {
  6981. 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)) {
  6982. env->col_no++;
  6983. }
  6984. goto _place;
  6985. }
  6986. int (*inverse_comparator)(int) = is_special;
  6987. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6988. inverse_comparator = is_normal;
  6989. }
  6990. 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)) {
  6991. env->col_no++;
  6992. }
  6993. 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)) {
  6994. env->col_no++;
  6995. }
  6996. _place:
  6997. set_preferred_column();
  6998. place_cursor_actual();
  6999. }
  7000. BIM_ACTION(big_word_right, 0,
  7001. "Move the cursor right to the start of the next WORD."
  7002. )(void) {
  7003. int line_no = env->line_no;
  7004. int col_no = env->col_no;
  7005. do {
  7006. col_no++;
  7007. if (col_no > env->lines[line_no-1]->actual) {
  7008. line_no++;
  7009. if (line_no > env->line_count) {
  7010. env->line_no = env->line_count;
  7011. env->col_no = env->lines[env->line_no-1]->actual;
  7012. set_preferred_column();
  7013. redraw_statusbar();
  7014. place_cursor_actual();
  7015. return;
  7016. }
  7017. col_no = 0;
  7018. break;
  7019. }
  7020. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7021. do {
  7022. col_no++;
  7023. while (col_no > env->lines[line_no-1]->actual) {
  7024. line_no++;
  7025. if (line_no >= env->line_count) {
  7026. env->col_no = env->lines[env->line_count-1]->actual;
  7027. env->line_no = env->line_count;
  7028. set_preferred_column();
  7029. redraw_statusbar();
  7030. place_cursor_actual();
  7031. return;
  7032. }
  7033. col_no = 1;
  7034. }
  7035. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  7036. env->col_no = col_no;
  7037. env->line_no = line_no;
  7038. set_preferred_column();
  7039. redraw_statusbar();
  7040. place_cursor_actual();
  7041. return;
  7042. }
  7043. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  7044. "Delete the character at the cursor, or merge with previous line."
  7045. )(void) {
  7046. if (env->col_no > 1) {
  7047. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7048. env->col_no -= 1;
  7049. if (env->coffset > 0) env->coffset--;
  7050. redraw_line(env->line_no-1);
  7051. set_modified();
  7052. redraw_statusbar();
  7053. place_cursor_actual();
  7054. } else if (env->line_no > 1) {
  7055. int tmp = env->lines[env->line_no - 2]->actual;
  7056. merge_lines(env->lines, env->line_no - 1);
  7057. env->line_no -= 1;
  7058. env->col_no = tmp+1;
  7059. set_preferred_column();
  7060. redraw_text();
  7061. set_modified();
  7062. redraw_statusbar();
  7063. place_cursor_actual();
  7064. }
  7065. }
  7066. BIM_ACTION(delete_word, ACTION_IS_RW,
  7067. "Delete the previous word."
  7068. )(void) {
  7069. if (!env->lines[env->line_no-1]) return;
  7070. if (env->col_no > 1) {
  7071. /* Start by deleting whitespace */
  7072. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7073. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7074. env->col_no -= 1;
  7075. if (env->coffset > 0) env->coffset--;
  7076. }
  7077. int (*inverse_comparator)(int) = is_special;
  7078. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  7079. inverse_comparator = is_normal;
  7080. }
  7081. do {
  7082. if (env->col_no > 1) {
  7083. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  7084. env->col_no -= 1;
  7085. if (env->coffset > 0) env->coffset--;
  7086. }
  7087. } 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));
  7088. set_preferred_column();
  7089. redraw_text();
  7090. set_modified();
  7091. redraw_statusbar();
  7092. place_cursor_actual();
  7093. }
  7094. }
  7095. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  7096. "Insert a line break, splitting the current line into two."
  7097. )(void) {
  7098. if (env->indent) {
  7099. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  7100. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7101. (env->col_no > 3) &&
  7102. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7103. delete_at_cursor();
  7104. }
  7105. }
  7106. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  7107. env->lines = add_line(env->lines, env->line_no);
  7108. } else {
  7109. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  7110. }
  7111. unhighlight_matching_paren();
  7112. env->coffset = 0;
  7113. env->col_no = 1;
  7114. env->line_no += 1;
  7115. set_preferred_column();
  7116. add_indent(env->line_no-1,env->line_no-2,0);
  7117. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7118. env->offset += 1;
  7119. }
  7120. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7121. set_modified();
  7122. }
  7123. BIM_ACTION(yank_lines, 0,
  7124. "Copy lines into the paste buffer."
  7125. )(void) {
  7126. int start = env->start_line;
  7127. int end = env->line_no;
  7128. if (global_config.yanks) {
  7129. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7130. free(global_config.yanks[i]);
  7131. }
  7132. free(global_config.yanks);
  7133. }
  7134. int lines_to_yank;
  7135. int start_point;
  7136. if (start <= end) {
  7137. lines_to_yank = end - start + 1;
  7138. start_point = start - 1;
  7139. } else {
  7140. lines_to_yank = start - end + 1;
  7141. start_point = end - 1;
  7142. }
  7143. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7144. global_config.yank_count = lines_to_yank;
  7145. global_config.yank_is_full_lines = 1;
  7146. for (int i = 0; i < lines_to_yank; ++i) {
  7147. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7148. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7149. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7150. global_config.yanks[i]->istate = 0;
  7151. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7152. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7153. global_config.yanks[i]->text[j].flags = 0;
  7154. }
  7155. }
  7156. }
  7157. /**
  7158. * Helper to yank part of a line into a new yank line.
  7159. */
  7160. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  7161. if (start_off + count > env->lines[line_no]->actual) {
  7162. if (start_off >= env->lines[line_no]->actual) {
  7163. start_off = env->lines[line_no]->actual;
  7164. count = 0;
  7165. } else {
  7166. count = env->lines[line_no]->actual - start_off;
  7167. }
  7168. }
  7169. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  7170. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  7171. global_config.yanks[yank_no]->actual = count;
  7172. global_config.yanks[yank_no]->istate = 0;
  7173. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  7174. for (int i = 0; i < count; ++i) {
  7175. global_config.yanks[yank_no]->text[i].flags = 0;
  7176. }
  7177. }
  7178. /**
  7179. * Yank text...
  7180. */
  7181. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  7182. if (global_config.yanks) {
  7183. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7184. free(global_config.yanks[i]);
  7185. }
  7186. free(global_config.yanks);
  7187. }
  7188. int lines_to_yank = end_line - start_line + 1;
  7189. int start_point = start_line - 1;
  7190. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  7191. global_config.yank_count = lines_to_yank;
  7192. global_config.yank_is_full_lines = 0;
  7193. if (lines_to_yank == 1) {
  7194. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  7195. } else {
  7196. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  7197. /* Yank middle lines */
  7198. for (int i = 1; i < lines_to_yank - 1; ++i) {
  7199. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  7200. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  7201. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  7202. global_config.yanks[i]->istate = 0;
  7203. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  7204. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  7205. global_config.yanks[i]->text[j].flags = 0;
  7206. }
  7207. }
  7208. /* Yank end line */
  7209. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  7210. }
  7211. }
  7212. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  7213. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  7214. )(int direction) {
  7215. if (direction == -1 && env->sel_col <= 0) return;
  7216. int prev_width = 0;
  7217. int s = (env->line_no < env->start_line) ? env->line_no : env->start_line;
  7218. int e = (env->line_no < env->start_line) ? env->start_line : env->line_no;
  7219. for (int i = s; i <= e; i++) {
  7220. line_t * line = env->lines[i - 1];
  7221. int _x = 0;
  7222. int col = 1;
  7223. int j = 0;
  7224. for (; j < line->actual; ++j) {
  7225. char_t * c = &line->text[j];
  7226. _x += c->display_width;
  7227. col = j+1;
  7228. if (_x > env->sel_col) break;
  7229. prev_width = c->display_width;
  7230. }
  7231. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  7232. line_delete(line, line->actual, i - 1);
  7233. set_modified();
  7234. } else if (_x > env->sel_col) {
  7235. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  7236. set_modified();
  7237. }
  7238. }
  7239. if (direction == -1) {
  7240. env->sel_col -= prev_width;
  7241. env->col_no--;
  7242. }
  7243. redraw_text();
  7244. }
  7245. void realign_column_cursor(void) {
  7246. line_t * line = env->lines[env->line_no - 1];
  7247. int _x = 0, col = 1, j = 0;
  7248. for (; j < line->actual; ++j) {
  7249. char_t * c = &line->text[j];
  7250. _x += c->display_width;
  7251. col = j + 1;
  7252. if (_x > env->sel_col) break;
  7253. }
  7254. env->col_no = col;
  7255. }
  7256. BIM_ACTION(column_left, 0, "Move the column cursor left.")(void) {
  7257. if (env->sel_col > 0) {
  7258. env->sel_col -= 1;
  7259. env->preferred_column = env->sel_col;
  7260. /* Figure out where the cursor should be */
  7261. realign_column_cursor();
  7262. redraw_all();
  7263. }
  7264. }
  7265. BIM_ACTION(column_right, 0, "Move the column cursor right.")(void) {
  7266. env->sel_col += 1;
  7267. env->preferred_column = env->sel_col;
  7268. /* Figure out where the cursor should be */
  7269. realign_column_cursor();
  7270. redraw_all();
  7271. }
  7272. BIM_ACTION(column_up, 0, "Move the column cursor up.")(void) {
  7273. if (env->line_no > 1 && env->start_line > 1) {
  7274. env->line_no--;
  7275. env->start_line--;
  7276. /* Figure out where the cursor should be */
  7277. realign_column_cursor();
  7278. place_cursor_actual();
  7279. redraw_all();
  7280. }
  7281. }
  7282. BIM_ACTION(column_down, 0, "Move the column cursor down.")(void) {
  7283. if (env->line_no < env->line_count && env->start_line < env->line_count) {
  7284. env->line_no++;
  7285. env->start_line++;
  7286. /* Figure out where the cursor should be */
  7287. realign_column_cursor();
  7288. place_cursor_actual();
  7289. redraw_all();
  7290. }
  7291. }
  7292. uint32_t * get_word_under_cursor(void) {
  7293. /* Figure out size */
  7294. int c_before = 0;
  7295. int c_after = 0;
  7296. int i = env->col_no;
  7297. while (i > 0) {
  7298. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7299. c_before++;
  7300. i--;
  7301. }
  7302. i = env->col_no+1;
  7303. while (i < env->lines[env->line_no-1]->actual+1) {
  7304. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7305. c_after++;
  7306. i++;
  7307. }
  7308. if (!c_before && !c_after) return NULL;
  7309. /* Populate with characters */
  7310. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  7311. int j = 0;
  7312. while (c_before) {
  7313. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  7314. c_before--;
  7315. j++;
  7316. }
  7317. int x = 0;
  7318. while (c_after) {
  7319. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  7320. j++;
  7321. x++;
  7322. c_after--;
  7323. }
  7324. out[j] = 0;
  7325. return out;
  7326. }
  7327. BIM_ACTION(search_under_cursor, 0,
  7328. "Search for the word currently under the cursor."
  7329. )(void) {
  7330. if (global_config.search) free(global_config.search);
  7331. global_config.search = get_word_under_cursor();
  7332. /* Find it */
  7333. search_next();
  7334. }
  7335. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7336. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  7337. )(int type, int c) {
  7338. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  7339. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7340. env->col_no = i - !!(type == 't');
  7341. place_cursor_actual();
  7342. set_preferred_column();
  7343. return;
  7344. }
  7345. }
  7346. }
  7347. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7348. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  7349. )(int type, int c) {
  7350. for (int i = env->col_no-1; i >= 1; --i) {
  7351. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7352. env->col_no = i + !!(type == 'T');
  7353. place_cursor_actual();
  7354. set_preferred_column();
  7355. return;
  7356. }
  7357. }
  7358. }
  7359. /**
  7360. * Clear the navigation number buffer
  7361. */
  7362. void reset_nav_buffer(int c) {
  7363. if (c == KEY_TIMEOUT) return;
  7364. if (nav_buffer && (c < '0' || c > '9')) {
  7365. nav_buffer = 0;
  7366. redraw_commandline();
  7367. }
  7368. }
  7369. /**
  7370. * Determine if a column + line number are within range of the
  7371. * current character selection specified by start_line, etc.
  7372. *
  7373. * Used to determine how syntax flags should be set when redrawing
  7374. * selected text in CHAR SELECTION mode.
  7375. */
  7376. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7377. if (start_line == end_line) {
  7378. if ( end_col < start_col) {
  7379. int tmp = end_col;
  7380. end_col = start_col;
  7381. start_col = tmp;
  7382. }
  7383. return (col >= start_col && col <= end_col);
  7384. }
  7385. if (start_line > end_line) {
  7386. int tmp = end_line;
  7387. end_line = start_line;
  7388. start_line = tmp;
  7389. tmp = end_col;
  7390. end_col = start_col;
  7391. start_col = tmp;
  7392. }
  7393. if (line < start_line || line > end_line) return 0;
  7394. if (line == start_line) {
  7395. return col >= start_col;
  7396. }
  7397. if (line == end_line) {
  7398. return col <= end_col;
  7399. }
  7400. return 1;
  7401. }
  7402. /**
  7403. * Macro for redrawing selected lines with appropriate highlighting.
  7404. */
  7405. #define _redraw_line(line, force_start_line) \
  7406. do { \
  7407. if (!(force_start_line) && (line) == env->start_line) break; \
  7408. if ((line) > env->line_count + 1) { \
  7409. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7410. draw_excess_line((line) - env->offset - 1); \
  7411. } \
  7412. break; \
  7413. } \
  7414. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7415. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7416. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7417. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7418. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7419. } \
  7420. } else { \
  7421. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7422. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7423. } \
  7424. } \
  7425. redraw_line((line)-1); \
  7426. } while (0)
  7427. #define _redraw_line_char(line, force_start_line) \
  7428. do { \
  7429. if (!(force_start_line) && (line) == env->start_line) break; \
  7430. if ((line) > env->line_count + 1) { \
  7431. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7432. draw_excess_line((line) - env->offset - 1); \
  7433. } \
  7434. break; \
  7435. } \
  7436. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7437. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7438. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7439. /* Line is completely outside selection */ \
  7440. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7441. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7442. } \
  7443. } else { \
  7444. if ((line) == env->start_line || (line) == env->line_no) { \
  7445. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7446. env->lines[(line)-1]->text[j].flags &= ~(FLAG_SELECT); \
  7447. } \
  7448. } \
  7449. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7450. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  7451. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7452. } \
  7453. } \
  7454. } \
  7455. redraw_line((line)-1); \
  7456. } while (0)
  7457. #define _redraw_line_col(line, force_start_line) \
  7458. do {\
  7459. if (!(force_start_line) && (line) == env->start_line) break; \
  7460. if ((line) > env->line_count + 1) { \
  7461. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7462. draw_excess_line((line) - env->offset - 1); \
  7463. } \
  7464. break; \
  7465. } \
  7466. redraw_line((line)-1); \
  7467. } while (0)
  7468. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  7469. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  7470. )(int direction) {
  7471. int lines_to_cover = 0;
  7472. int start_point = 0;
  7473. if (env->start_line <= env->line_no) {
  7474. start_point = env->start_line - 1;
  7475. lines_to_cover = env->line_no - env->start_line + 1;
  7476. } else {
  7477. start_point = env->line_no - 1;
  7478. lines_to_cover = env->start_line - env->line_no + 1;
  7479. }
  7480. for (int i = 0; i < lines_to_cover; ++i) {
  7481. if (env->lines[start_point + i]->actual < 1) continue;
  7482. if (direction == -1) {
  7483. if (env->tabs) {
  7484. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7485. line_delete(env->lines[start_point + i],1,start_point+i);
  7486. _redraw_line(start_point+i+1,1);
  7487. }
  7488. } else {
  7489. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7490. line_delete(env->lines[start_point + i],1,start_point+i);
  7491. _redraw_line(start_point+i+1,1);
  7492. } else {
  7493. for (int j = 0; j < env->tabstop; ++j) {
  7494. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  7495. line_delete(env->lines[start_point + i],1,start_point+i);
  7496. }
  7497. }
  7498. }
  7499. _redraw_line(start_point+i+1,1);
  7500. }
  7501. } else if (direction == 1) {
  7502. if (env->tabs) {
  7503. char_t c;
  7504. c.codepoint = '\t';
  7505. c.display_width = env->tabstop;
  7506. c.flags = FLAG_SELECT;
  7507. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7508. } else {
  7509. for (int j = 0; j < env->tabstop; ++j) {
  7510. char_t c;
  7511. c.codepoint = ' ';
  7512. c.display_width = 1;
  7513. c.flags = FLAG_SELECT;
  7514. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7515. }
  7516. }
  7517. _redraw_line(start_point+i+1,1);
  7518. }
  7519. }
  7520. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7521. env->col_no = env->lines[env->line_no-1]->actual;
  7522. }
  7523. set_preferred_column();
  7524. set_modified();
  7525. }
  7526. void recalculate_selected_lines(void) {
  7527. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7528. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7529. if (start < 1) start = 1;
  7530. if (start > env->line_count) start = env->line_count;
  7531. if (end < 1) end = 1;
  7532. if (end > env->line_count) end = env->line_count;
  7533. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  7534. for (int j = 0; j < env->lines[i-1]->actual; j++) {
  7535. env->lines[i-1]->text[j].flags &= ~(FLAG_SELECT);
  7536. }
  7537. }
  7538. redraw_all();
  7539. }
  7540. BIM_ACTION(enter_line_selection, 0,
  7541. "Enter line selection mode."
  7542. )(void) {
  7543. /* Set mode */
  7544. env->mode = MODE_LINE_SELECTION;
  7545. /* Store start position */
  7546. env->start_line = env->line_no;
  7547. env->prev_line = env->start_line;
  7548. env->start_col = env->col_no;
  7549. /* Redraw commandline to get -- LINE SELECTION -- text */
  7550. redraw_commandline();
  7551. unhighlight_matching_paren();
  7552. /* Set this line as selected for syntax highlighting */
  7553. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  7554. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  7555. }
  7556. /* And redraw it */
  7557. redraw_line(env->line_no-1);
  7558. }
  7559. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  7560. "Swap between LINE and CHAR selection modes."
  7561. )(int mode) {
  7562. env->mode = mode;
  7563. if (mode == MODE_LINE_SELECTION) {
  7564. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7565. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7566. for (int i = start; i <= end; ++i) {
  7567. _redraw_line(i, 1);
  7568. }
  7569. } else if (mode == MODE_CHAR_SELECTION) {
  7570. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7571. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7572. for (int i = start; i <= end; ++i) {
  7573. _redraw_line_char(i, 1);
  7574. }
  7575. }
  7576. }
  7577. BIM_ACTION(delete_and_yank_lines, 0,
  7578. "Delete and yank the selected lines."
  7579. )(void) {
  7580. yank_lines();
  7581. if (env->start_line <= env->line_no) {
  7582. int lines_to_delete = env->line_no - env->start_line + 1;
  7583. for (int i = 0; i < lines_to_delete; ++i) {
  7584. env->lines = remove_line(env->lines, env->start_line-1);
  7585. }
  7586. env->line_no = env->start_line;
  7587. } else {
  7588. int lines_to_delete = env->start_line - env->line_no + 1;
  7589. for (int i = 0; i < lines_to_delete; ++i) {
  7590. env->lines = remove_line(env->lines, env->line_no-1);
  7591. }
  7592. }
  7593. if (env->line_no > env->line_count) {
  7594. env->line_no = env->line_count;
  7595. }
  7596. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7597. env->col_no = env->lines[env->line_no-1]->actual;
  7598. }
  7599. set_preferred_column();
  7600. set_modified();
  7601. }
  7602. BIM_ACTION(enter_insert, ACTION_IS_RW,
  7603. "Enter insert mode."
  7604. )(void) {
  7605. env->mode = MODE_INSERT;
  7606. set_history_break();
  7607. }
  7608. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  7609. "Delete and yank the selected lines and then enter insert mode."
  7610. )(void) {
  7611. delete_and_yank_lines();
  7612. env->lines = add_line(env->lines, env->line_no-1);
  7613. redraw_text();
  7614. env->mode = MODE_INSERT;
  7615. }
  7616. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  7617. "Replace characters in the selected lines."
  7618. )(int c) {
  7619. if (c >= KEY_ESCAPE) {
  7620. render_error("Invalid key for replacement");
  7621. return;
  7622. }
  7623. char_t _c = {codepoint_width(c), 0, c};
  7624. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  7625. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  7626. for (int line = start_point; line <= end_point; ++line) {
  7627. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7628. line_replace(env->lines[line-1], _c, i, line-1);
  7629. }
  7630. }
  7631. }
  7632. BIM_ACTION(leave_selection, 0,
  7633. "Leave selection modes and return to normal mode."
  7634. )(void) {
  7635. set_history_break();
  7636. env->mode = MODE_NORMAL;
  7637. recalculate_selected_lines();
  7638. }
  7639. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  7640. "Insert a character on all lines at the current column."
  7641. )(int c) {
  7642. char_t _c;
  7643. _c.codepoint = c;
  7644. _c.flags = 0;
  7645. _c.display_width = codepoint_width(c);
  7646. int inserted_width = 0;
  7647. /* For each line */
  7648. int s = (env->line_no < env->start_line) ? env->line_no : env->start_line;
  7649. int e = (env->line_no < env->start_line) ? env->start_line : env->line_no;
  7650. for (int i = s; i <= e; i++) {
  7651. line_t * line = env->lines[i - 1];
  7652. int _x = 0;
  7653. int col = 1;
  7654. int j = 0;
  7655. for (; j < line->actual; ++j) {
  7656. char_t * c = &line->text[j];
  7657. _x += c->display_width;
  7658. col = j+1;
  7659. if (_x > env->sel_col) break;
  7660. }
  7661. if ((_x == env->sel_col && j == line->actual)) {
  7662. _x = env->sel_col + 1;
  7663. col = line->actual + 1;
  7664. }
  7665. if (_x > env->sel_col) {
  7666. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7667. if (line != nline) {
  7668. env->lines[i - 1] = nline;
  7669. line = nline;
  7670. }
  7671. set_modified();
  7672. }
  7673. recalculate_tabs(line);
  7674. inserted_width = line->text[col-1].display_width;
  7675. if (i == env->line_no) env->col_no = col + 1;
  7676. }
  7677. env->sel_col += inserted_width;
  7678. env->preferred_column = env->sel_col;
  7679. place_cursor_actual();
  7680. }
  7681. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  7682. "Enter column insert mode."
  7683. )(void) {
  7684. env->mode = MODE_COL_INSERT;
  7685. }
  7686. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  7687. "Enter column insert mode after the selected column."
  7688. )(void) {
  7689. env->sel_col += 1;
  7690. enter_col_insert();
  7691. }
  7692. BIM_ACTION(enter_col_selection, 0,
  7693. "Enter column selection mode."
  7694. )(void) {
  7695. /* Set mode */
  7696. env->mode = MODE_COL_SELECTION;
  7697. /* Store cursor */
  7698. env->start_line = env->line_no;
  7699. env->sel_col = env->preferred_column;
  7700. env->prev_line = env->start_line;
  7701. /* Redraw commandline */
  7702. redraw_commandline();
  7703. /* Nothing else to do here; rely on cursor */
  7704. }
  7705. BIM_ACTION(yank_characters, 0,
  7706. "Yank the selected characters to the paste buffer."
  7707. )(void) {
  7708. int end_line = env->line_no;
  7709. int end_col = env->col_no;
  7710. if (env->start_line == end_line) {
  7711. if (env->start_col > end_col) {
  7712. int tmp = env->start_col;
  7713. env->start_col = end_col;
  7714. end_col = tmp;
  7715. }
  7716. } else if (env->start_line > end_line) {
  7717. int tmp = env->start_line;
  7718. env->start_line = end_line;
  7719. end_line = tmp;
  7720. tmp = env->start_col;
  7721. env->start_col = end_col;
  7722. end_col = tmp;
  7723. }
  7724. yank_text(env->start_line, env->start_col, end_line, end_col);
  7725. }
  7726. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  7727. "Delete and yank the selected characters."
  7728. )(void) {
  7729. int end_line = env->line_no;
  7730. int end_col = env->col_no;
  7731. if (env->start_line == end_line) {
  7732. if (env->start_col > end_col) {
  7733. int tmp = env->start_col;
  7734. env->start_col = end_col;
  7735. end_col = tmp;
  7736. }
  7737. yank_text(env->start_line, env->start_col, end_line, end_col);
  7738. for (int i = env->start_col; i <= end_col; ++i) {
  7739. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7740. }
  7741. env->col_no = env->start_col;
  7742. } else {
  7743. if (env->start_line > end_line) {
  7744. int tmp = env->start_line;
  7745. env->start_line = end_line;
  7746. end_line = tmp;
  7747. tmp = env->start_col;
  7748. env->start_col = end_col;
  7749. end_col = tmp;
  7750. }
  7751. /* Copy lines */
  7752. yank_text(env->start_line, env->start_col, end_line, end_col);
  7753. /* Delete lines */
  7754. for (int i = env->start_line+1; i < end_line; ++i) {
  7755. env->lines = remove_line(env->lines, env->start_line);
  7756. } /* end_line is no longer valid; should be start_line+1*/
  7757. /* Delete from env->start_col forward */
  7758. int tmp = env->lines[env->start_line-1]->actual;
  7759. for (int i = env->start_col; i <= tmp; ++i) {
  7760. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7761. }
  7762. for (int i = 1; i <= end_col; ++i) {
  7763. line_delete(env->lines[env->start_line], 1, env->start_line);
  7764. }
  7765. /* Merge start and end lines */
  7766. merge_lines(env->lines, env->start_line);
  7767. env->line_no = env->start_line;
  7768. env->col_no = env->start_col;
  7769. }
  7770. if (env->line_no > env->line_count) {
  7771. env->line_no = env->line_count;
  7772. }
  7773. set_preferred_column();
  7774. set_modified();
  7775. }
  7776. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  7777. "Delete and yank the selected characters and then enter insert mode."
  7778. )(void) {
  7779. delete_and_yank_chars();
  7780. redraw_text();
  7781. enter_insert();
  7782. }
  7783. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  7784. "Replace the selected characters."
  7785. )(int c) {
  7786. if (c >= KEY_ESCAPE) {
  7787. render_error("Invalid key for replacement");
  7788. return;
  7789. }
  7790. char_t _c = {codepoint_width(c), 0, c};
  7791. /* This should probably be a function line "do_over_range" or something */
  7792. if (env->start_line == env->line_no) {
  7793. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  7794. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  7795. for (int i = s; i <= e; ++i) {
  7796. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  7797. }
  7798. redraw_text();
  7799. } else {
  7800. if (env->start_line < env->line_no) {
  7801. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  7802. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7803. }
  7804. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  7805. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7806. line_replace(env->lines[line-1], _c, i, line-1);
  7807. }
  7808. }
  7809. for (int s = 0; s < env->col_no; ++s) {
  7810. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7811. }
  7812. } else {
  7813. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  7814. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7815. }
  7816. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  7817. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7818. line_replace(env->lines[line-1], _c, i, line-1);
  7819. }
  7820. }
  7821. for (int s = 0; s < env->start_col; ++s) {
  7822. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7823. }
  7824. }
  7825. }
  7826. }
  7827. BIM_ACTION(enter_char_selection, 0,
  7828. "Enter character selection mode."
  7829. )(void) {
  7830. /* Set mode */
  7831. env->mode = MODE_CHAR_SELECTION;
  7832. /* Set cursor positions */
  7833. env->start_line = env->line_no;
  7834. env->start_col = env->col_no;
  7835. env->prev_line = env->start_line;
  7836. /* Redraw commandline for -- CHAR SELECTION -- */
  7837. redraw_commandline();
  7838. unhighlight_matching_paren();
  7839. /* Select single character */
  7840. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7841. redraw_line(env->line_no-1);
  7842. }
  7843. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  7844. "Move the cursor to the end of the selection and enter insert mode."
  7845. )(void) {
  7846. recalculate_selected_lines();
  7847. if (env->line_no == env->start_line) {
  7848. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  7849. } else if (env->line_no < env->start_line) {
  7850. env->col_no = env->start_col + 1;
  7851. env->line_no = env->start_line;
  7852. } else {
  7853. env->col_no += 1;
  7854. }
  7855. env->mode = MODE_INSERT;
  7856. }
  7857. void free_completion_match(struct completion_match * match) {
  7858. if (match->string) free(match->string);
  7859. if (match->file) free(match->file);
  7860. if (match->search) free(match->search);
  7861. }
  7862. /**
  7863. * Read ctags file to find matches for a symbol
  7864. */
  7865. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  7866. int _matches_len = 4;
  7867. int *matches_len = &_matches_len;
  7868. *matches_count = 0;
  7869. *matches = malloc(sizeof(struct completion_match) * (*matches_len));
  7870. FILE * tags = fopen("tags","r");
  7871. if (tags) {
  7872. char tmp[4096]; /* max line */
  7873. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  7874. if (tmp[0] == '!') continue;
  7875. int i = 0;
  7876. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  7877. if (comp[i] == '\0') {
  7878. if (complete_match && tmp[i] != '\t') continue;
  7879. int j = i;
  7880. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7881. tmp[j] = '\0'; j++;
  7882. char * file = &tmp[j];
  7883. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7884. tmp[j] = '\0'; j++;
  7885. char * search = &tmp[j];
  7886. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  7887. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  7888. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  7889. tmp[j] = '\0'; j++;
  7890. add_match(tmp,file,search);
  7891. }
  7892. }
  7893. fclose(tags);
  7894. }
  7895. if (env->syntax && env->syntax->completion_matcher) {
  7896. env->syntax->completion_matcher(comp,matches,matches_count,complete_match,matches_len, env);
  7897. }
  7898. return 0;
  7899. }
  7900. /**
  7901. * Draw an autocomplete popover with matches.
  7902. */
  7903. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  7904. int original_length = 0;
  7905. while (tmp[original_length]) original_length++;
  7906. int max_width = 0;
  7907. for (int i = 0; i < matches_count; ++i) {
  7908. /* TODO unicode width */
  7909. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  7910. if (my_width > (unsigned int)max_width) {
  7911. max_width = my_width;
  7912. }
  7913. }
  7914. /* Figure out how much space we have to display the window */
  7915. int cursor_y = env->line_no - env->offset + global_config.tabs_visible;
  7916. int max_y = global_config.term_height - global_config.bottom_size - cursor_y;
  7917. /* Find a good place to put the box horizontally */
  7918. int num_size = num_width() + gutter_width();
  7919. int x = num_size + 1 - env->coffset;
  7920. /* Determine where the cursor is physically */
  7921. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  7922. char_t * c = &env->lines[env->line_no-1]->text[i];
  7923. x += c->display_width;
  7924. }
  7925. int box_width = max_width;
  7926. int box_x = x;
  7927. int box_y = cursor_y + 1;
  7928. if (max_width > env->width - num_width() - gutter_width()) {
  7929. box_width = env->width - num_width() - gutter_width();
  7930. box_x = num_width() + gutter_width() + 1;
  7931. } else if (env->width - x < max_width) {
  7932. box_width = max_width;
  7933. box_x = env->width - max_width;
  7934. }
  7935. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  7936. for (int x = index; x < max_count+index; ++x) {
  7937. int i = x % matches_count;
  7938. place_cursor(box_x + env->left, box_y+x-index);
  7939. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  7940. /* TODO wide characters */
  7941. int match_width = strlen(matches[i].string);
  7942. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  7943. for (int j = 0; j < box_width; ++j) {
  7944. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  7945. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  7946. if (j < match_width) printf("%c", matches[i].string[j]);
  7947. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  7948. else printf(" ");
  7949. }
  7950. }
  7951. if (max_count == 0) {
  7952. place_cursor(box_x + env->left, box_y);
  7953. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7954. printf(" (no matches) ");
  7955. } else if (max_count != matches_count) {
  7956. place_cursor(box_x + env->left, box_y+max_count);
  7957. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7958. printf(" (%d more) ", matches_count-max_count);
  7959. }
  7960. }
  7961. /**
  7962. * Autocomplete words (function/variable names, etc.) in input mode.
  7963. */
  7964. int omni_complete(int quit_quietly_on_none) {
  7965. int retval = 0;
  7966. int index = 0;
  7967. int c;
  7968. int (*qualifier)(int c) = simple_keyword_qualifier;
  7969. if (env->syntax && env->syntax->completion_qualifier) {
  7970. qualifier = env->syntax->completion_qualifier;
  7971. }
  7972. /* Pull the word from before the cursor */
  7973. int c_before = 0;
  7974. int i = env->col_no-1;
  7975. while (i > 0) {
  7976. int c = env->lines[env->line_no-1]->text[i-1].codepoint;
  7977. if (!qualifier(c)) break;
  7978. c_before++;
  7979. i--;
  7980. }
  7981. if (!c_before && quit_quietly_on_none) return 0;
  7982. /* Populate with characters */
  7983. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  7984. int j = 0;
  7985. while (c_before) {
  7986. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  7987. c_before--;
  7988. j++;
  7989. }
  7990. tmp[j] = 0;
  7991. /*
  7992. * TODO matches should probably be a struct with more data than just
  7993. * the matching string; maybe offset where the needle was found,
  7994. * class information, source file information - anything we can extract
  7995. * from ctags, but also other information for other sources of completion.
  7996. */
  7997. struct completion_match *matches;
  7998. int matches_count;
  7999. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  8000. if (read_tags(tmp, &matches, &matches_count, 0)) {
  8001. goto _completion_done;
  8002. }
  8003. /* Draw box with matches at cursor-width(tmp) */
  8004. if (quit_quietly_on_none && matches_count == 0) {
  8005. free(tmp);
  8006. free(matches);
  8007. return 0;
  8008. }
  8009. draw_completion_matches(tmp, matches, matches_count, 0);
  8010. _completion_done:
  8011. place_cursor_actual();
  8012. while (1) {
  8013. c = bim_getch();
  8014. if (c == -1) continue;
  8015. if (matches_count < 1) {
  8016. redraw_all();
  8017. break;
  8018. }
  8019. if (c == 15) {
  8020. index = (index + 1) % matches_count;
  8021. draw_completion_matches(tmp, matches, matches_count, index);
  8022. place_cursor_actual();
  8023. continue;
  8024. } else if (c == '\t') {
  8025. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  8026. insert_char(matches[index].string[i]);
  8027. }
  8028. set_preferred_column();
  8029. redraw_text();
  8030. place_cursor_actual();
  8031. goto _finish_completion;
  8032. } else if (isgraph(c) && c != '}') {
  8033. /* insert and continue matching */
  8034. insert_char(c);
  8035. set_preferred_column();
  8036. redraw_text();
  8037. place_cursor_actual();
  8038. retval = 1;
  8039. goto _finish_completion;
  8040. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  8041. delete_at_cursor();
  8042. set_preferred_column();
  8043. redraw_text();
  8044. place_cursor_actual();
  8045. retval = 1;
  8046. goto _finish_completion;
  8047. }
  8048. /* TODO: Keyboard navigation of the matches list would be nice */
  8049. redraw_all();
  8050. break;
  8051. }
  8052. bim_unget(c);
  8053. _finish_completion:
  8054. for (int i = 0; i < matches_count; ++i) {
  8055. free_completion_match(&matches[i]);
  8056. }
  8057. free(matches);
  8058. free(tmp);
  8059. return retval;
  8060. }
  8061. /**
  8062. * Set the search string from a UTF-8 sequence.
  8063. * Since the search string is normally a series of codepoints, this saves
  8064. * some effort when trying to search for things we pulled from the outside world.
  8065. * (eg., ctags search terms)
  8066. */
  8067. void set_search_from_bytes(char * bytes) {
  8068. if (global_config.search) free(global_config.search);
  8069. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) + 1));
  8070. uint32_t * s = global_config.search;
  8071. char * tmp = bytes;
  8072. uint32_t c, istate = 0;
  8073. while (*tmp) {
  8074. if (!decode(&istate, &c, *tmp)) {
  8075. *s = c;
  8076. s++;
  8077. *s = 0;
  8078. } else if (istate == UTF8_REJECT) {
  8079. istate = 0;
  8080. }
  8081. tmp++;
  8082. }
  8083. }
  8084. BIM_ACTION(goto_definition, 0,
  8085. "Jump to the definition of the word under under cursor."
  8086. )(void) {
  8087. uint32_t * word = get_word_under_cursor();
  8088. if (!word) {
  8089. render_error("No match");
  8090. return;
  8091. }
  8092. struct completion_match *matches;
  8093. int matches_count;
  8094. if (read_tags(word, &matches, &matches_count, 1)) {
  8095. render_error("No tags file");
  8096. goto _done;
  8097. }
  8098. if (!matches_count) {
  8099. render_error("No match");
  8100. goto _done;
  8101. }
  8102. #define _perform_correct_search(i) do { \
  8103. if (matches[i].search[0] == '/') { \
  8104. set_search_from_bytes(&matches[i].search[1]); \
  8105. search_next(); \
  8106. } else { \
  8107. goto_line(atoi(matches[i].search)); \
  8108. } \
  8109. } while (0)
  8110. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  8111. _perform_correct_search(0);
  8112. } else {
  8113. /* Check if there were other matches that are in this file */
  8114. for (int i =1; env->file_name && i < matches_count; ++i) {
  8115. if (!strcmp(matches[i].file, env->file_name)) {
  8116. _perform_correct_search(i);
  8117. goto _done;
  8118. }
  8119. }
  8120. /* Check buffers */
  8121. for (int i = 0; i < buffers_len; ++i) {
  8122. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  8123. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  8124. env = buffers[i];
  8125. redraw_tabbar();
  8126. _perform_correct_search(i);
  8127. goto _done;
  8128. }
  8129. }
  8130. /* Okay, let's try opening */
  8131. buffer_t * old_buf = env;
  8132. open_file(matches[0].file);
  8133. if (env != old_buf) {
  8134. _perform_correct_search(0);
  8135. } else {
  8136. render_error("Could not locate file containing definition");
  8137. }
  8138. }
  8139. _done:
  8140. for (int i = 0; i < matches_count; ++i) {
  8141. free_completion_match(&matches[i]);
  8142. }
  8143. free(matches);
  8144. free(word);
  8145. }
  8146. /**
  8147. * Read one codepoint, with verbatim support.
  8148. */
  8149. int read_one_character(char * message) {
  8150. /* Read one character and replace */
  8151. if (!global_config.overlay_mode) {
  8152. render_commandline_message(message);
  8153. place_cursor_actual();
  8154. }
  8155. int c;
  8156. while ((c = bim_getkey(DEFAULT_KEY_WAIT))) {
  8157. if (c == KEY_TIMEOUT) continue;
  8158. if (c == KEY_CTRL_V) {
  8159. if (!global_config.overlay_mode) {
  8160. render_commandline_message(message);
  8161. printf(" ^V");
  8162. place_cursor_actual();
  8163. }
  8164. while ((c = bim_getch()) == -1);
  8165. break;
  8166. }
  8167. break;
  8168. }
  8169. redraw_commandline();
  8170. return c;
  8171. }
  8172. int read_one_byte(char * message) {
  8173. if (!global_config.overlay_mode) {
  8174. render_commandline_message(message);
  8175. place_cursor_actual();
  8176. }
  8177. int c;
  8178. while ((c = bim_getch())) {
  8179. if (c == -1) continue;
  8180. break;
  8181. }
  8182. redraw_commandline();
  8183. return c;
  8184. }
  8185. BIM_ACTION(cursor_left_with_wrap, 0,
  8186. "Move the cursor one position left, wrapping to the previous line."
  8187. )(void) {
  8188. if (env->line_no > 1 && env->col_no == 1) {
  8189. env->line_no--;
  8190. env->col_no = env->lines[env->line_no-1]->actual;
  8191. set_preferred_column();
  8192. place_cursor_actual();
  8193. } else {
  8194. cursor_left();
  8195. }
  8196. }
  8197. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  8198. "Insert a new line before the current line and enter insert mode."
  8199. )(void) {
  8200. set_history_break();
  8201. env->lines = add_line(env->lines, env->line_no-1);
  8202. env->col_no = 1;
  8203. add_indent(env->line_no-1,env->line_no,0);
  8204. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8205. redraw_text();
  8206. set_preferred_column();
  8207. set_modified();
  8208. place_cursor_actual();
  8209. env->mode = MODE_INSERT;
  8210. }
  8211. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  8212. "Insert a new line after the current line and enter insert mode."
  8213. )(void) {
  8214. set_history_break();
  8215. unhighlight_matching_paren();
  8216. env->lines = add_line(env->lines, env->line_no);
  8217. env->col_no = 1;
  8218. env->line_no += 1;
  8219. add_indent(env->line_no-1,env->line_no-2,0);
  8220. set_preferred_column();
  8221. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  8222. env->offset += 1;
  8223. }
  8224. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  8225. redraw_text();
  8226. set_modified();
  8227. place_cursor_actual();
  8228. env->mode = MODE_INSERT;
  8229. }
  8230. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  8231. "Place the cursor after the selected character and enter insert mode."
  8232. )(void) {
  8233. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  8234. env->col_no += 1;
  8235. }
  8236. enter_insert();
  8237. }
  8238. BIM_ACTION(delete_forward, ACTION_IS_RW,
  8239. "Delete the character under the cursor."
  8240. )(void) {
  8241. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  8242. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  8243. redraw_text();
  8244. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1 && env->line_count > env->line_no) {
  8245. merge_lines(env->lines, env->line_no);
  8246. redraw_text();
  8247. }
  8248. set_modified();
  8249. redraw_statusbar();
  8250. place_cursor_actual();
  8251. }
  8252. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  8253. "Delete the character under the cursor and enter insert mode."
  8254. )(void) {
  8255. set_history_break();
  8256. delete_forward();
  8257. env->mode = MODE_INSERT;
  8258. }
  8259. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  8260. "Paste yanked text before (`P`) or after (`p`) the cursor."
  8261. )(int direction) {
  8262. if (global_config.yanks) {
  8263. env->slowop = 1;
  8264. if (!global_config.yank_is_full_lines) {
  8265. /* Handle P for paste before, p for past after */
  8266. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  8267. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  8268. target_column = env->lines[env->line_no-1]->actual + 1;
  8269. }
  8270. if (global_config.yank_count > 1) {
  8271. /* Spit the current line at the current position */
  8272. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  8273. }
  8274. /* Insert first line at current position */
  8275. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  8276. 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);
  8277. }
  8278. if (global_config.yank_count > 1) {
  8279. /* Insert full lines */
  8280. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8281. env->lines = add_line(env->lines, env->line_no);
  8282. }
  8283. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8284. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  8285. }
  8286. /* Insert characters from last line into (what was) the next line */
  8287. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  8288. 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);
  8289. }
  8290. }
  8291. } else {
  8292. /* Insert full lines */
  8293. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8294. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  8295. }
  8296. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8297. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  8298. }
  8299. }
  8300. env->slowop = 0;
  8301. schedule_complete_recalc();
  8302. /* Recalculate whole document syntax */
  8303. if (direction == 1) {
  8304. if (global_config.yank_is_full_lines) {
  8305. env->line_no += 1;
  8306. } else {
  8307. if (global_config.yank_count == 1) {
  8308. env->col_no = env->col_no + global_config.yanks[0]->actual;
  8309. } else {
  8310. env->line_no = env->line_no + global_config.yank_count - 1;
  8311. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  8312. }
  8313. }
  8314. }
  8315. if (global_config.yank_is_full_lines) {
  8316. env->col_no = 1;
  8317. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8318. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8319. env->col_no = i + 1;
  8320. break;
  8321. }
  8322. }
  8323. }
  8324. set_history_break();
  8325. set_modified();
  8326. redraw_all();
  8327. }
  8328. }
  8329. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  8330. "Move the cursor to the end of the current line and enter insert mode."
  8331. )(void) {
  8332. env->col_no = env->lines[env->line_no-1]->actual+1;
  8333. env->mode = MODE_INSERT;
  8334. set_history_break();
  8335. }
  8336. BIM_ACTION(enter_replace, ACTION_IS_RW,
  8337. "Enter replace mode."
  8338. )(void) {
  8339. env->mode = MODE_REPLACE;
  8340. set_history_break();
  8341. }
  8342. BIM_ACTION(toggle_numbers, 0,
  8343. "Toggle the display of line numbers."
  8344. )(void) {
  8345. env->numbers = !env->numbers;
  8346. redraw_all();
  8347. place_cursor_actual();
  8348. }
  8349. BIM_ACTION(toggle_gutter, 0,
  8350. "Toggle the display of the revision status gutter."
  8351. )(void) {
  8352. env->gutter = !env->gutter;
  8353. redraw_all();
  8354. place_cursor_actual();
  8355. }
  8356. BIM_ACTION(toggle_indent, 0,
  8357. "Toggle smart indentation."
  8358. )(void) {
  8359. env->indent = !env->indent;
  8360. redraw_statusbar();
  8361. place_cursor_actual();
  8362. }
  8363. BIM_ACTION(toggle_smartcomplete, 0,
  8364. "Toggle smart completion."
  8365. )(void) {
  8366. global_config.smart_complete = !global_config.smart_complete;
  8367. redraw_statusbar();
  8368. place_cursor_actual();
  8369. }
  8370. BIM_ACTION(expand_split_right, 0,
  8371. "Move the view split divider to the right."
  8372. )(void) {
  8373. global_config.split_percent += 1;
  8374. update_split_size();
  8375. redraw_all();
  8376. }
  8377. BIM_ACTION(expand_split_left, 0,
  8378. "Move the view split divider to the left."
  8379. )(void) {
  8380. global_config.split_percent -= 1;
  8381. update_split_size();
  8382. redraw_all();
  8383. }
  8384. BIM_ACTION(go_page_up, 0,
  8385. "Jump up a screenfull."
  8386. )(void) {
  8387. int destination = env->line_no - (global_config.term_height - 6);
  8388. if (destination < 1) destination = 1;
  8389. goto_line(destination);
  8390. }
  8391. BIM_ACTION(go_page_down, 0,
  8392. "Jump down a screenfull."
  8393. )(void) {
  8394. goto_line(env->line_no + (global_config.term_height - 6));
  8395. }
  8396. BIM_ACTION(jump_to_matching_bracket, 0,
  8397. "Find and jump to the matching bracket for the character under the cursor."
  8398. )(void) {
  8399. recalculate_selected_lines();
  8400. int paren_line = -1, paren_col = -1;
  8401. find_matching_paren(&paren_line, &paren_col, 1);
  8402. if (paren_line != -1) {
  8403. env->line_no = paren_line;
  8404. env->col_no = paren_col;
  8405. set_preferred_column();
  8406. place_cursor_actual();
  8407. redraw_statusbar();
  8408. }
  8409. }
  8410. BIM_ACTION(jump_to_previous_blank, 0,
  8411. "Jump to the preceding blank line before the cursor."
  8412. )(void) {
  8413. env->col_no = 1;
  8414. if (env->line_no == 1) return;
  8415. do {
  8416. env->line_no--;
  8417. if (env->lines[env->line_no-1]->actual == 0) break;
  8418. } while (env->line_no > 1);
  8419. set_preferred_column();
  8420. redraw_statusbar();
  8421. }
  8422. BIM_ACTION(jump_to_next_blank, 0,
  8423. "Jump to the next blank line after the cursor."
  8424. )(void) {
  8425. env->col_no = 1;
  8426. if (env->line_no == env->line_count) return;
  8427. do {
  8428. env->line_no++;
  8429. if (env->lines[env->line_no-1]->actual == 0) break;
  8430. } while (env->line_no < env->line_count);
  8431. set_preferred_column();
  8432. redraw_statusbar();
  8433. }
  8434. BIM_ACTION(first_non_whitespace, 0,
  8435. "Jump to the first non-whitespace character in the current line."
  8436. )(void) {
  8437. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8438. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8439. env->col_no = i + 1;
  8440. break;
  8441. }
  8442. }
  8443. set_preferred_column();
  8444. redraw_statusbar();
  8445. }
  8446. BIM_ACTION(next_line_non_whitespace, 0,
  8447. "Jump to the first non-whitespace character in the next next line."
  8448. )(void) {
  8449. if (env->line_no < env->line_count) {
  8450. env->line_no++;
  8451. env->col_no = 1;
  8452. } else {
  8453. return;
  8454. }
  8455. first_non_whitespace();
  8456. }
  8457. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  8458. "Delete the preceding character, with special handling for indentation."
  8459. )(void) {
  8460. if (!env->tabs && env->col_no > 1) {
  8461. int i;
  8462. for (i = 0; i < env->col_no-1; ++i) {
  8463. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  8464. }
  8465. if (i == env->col_no-1) {
  8466. /* Backspace until aligned */
  8467. delete_at_cursor();
  8468. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  8469. delete_at_cursor();
  8470. }
  8471. return;
  8472. }
  8473. }
  8474. delete_at_cursor();
  8475. }
  8476. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  8477. "(temporary) Perform smart symbol completion from ctags."
  8478. )(void) {
  8479. /* This should probably be a submode */
  8480. while (omni_complete(0) == 1);
  8481. }
  8482. BIM_ACTION(smart_tab, ACTION_IS_RW,
  8483. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  8484. )(void) {
  8485. if (env->tabs) {
  8486. insert_char('\t');
  8487. } else {
  8488. for (int i = 0; i < env->tabstop; ++i) {
  8489. insert_char(' ');
  8490. }
  8491. }
  8492. }
  8493. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  8494. "Insert a `/` ending a C-style comment."
  8495. )(int c) {
  8496. /* smart *end* of comment anyway */
  8497. if (env->indent) {
  8498. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  8499. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  8500. (env->col_no > 3) &&
  8501. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  8502. env->col_no--;
  8503. replace_char('/');
  8504. env->col_no++;
  8505. place_cursor_actual();
  8506. return;
  8507. }
  8508. }
  8509. insert_char(c);
  8510. }
  8511. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  8512. "Insert a closing brace and smartly position it if it is the first character on a line."
  8513. )(int c) {
  8514. if (env->indent) {
  8515. int was_whitespace = 1;
  8516. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8517. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  8518. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  8519. was_whitespace = 0;
  8520. break;
  8521. }
  8522. }
  8523. insert_char(c);
  8524. if (was_whitespace) {
  8525. int line = -1, col = -1;
  8526. env->col_no--;
  8527. find_matching_paren(&line,&col, 1);
  8528. if (line != -1) {
  8529. line = find_brace_line_start(line, col);
  8530. while (env->lines[env->line_no-1]->actual) {
  8531. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  8532. }
  8533. add_indent(env->line_no-1,line-1,1);
  8534. env->col_no = env->lines[env->line_no-1]->actual + 1;
  8535. insert_char(c);
  8536. }
  8537. }
  8538. set_preferred_column();
  8539. return;
  8540. }
  8541. insert_char(c);
  8542. }
  8543. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  8544. "Enter line selection and move the cursor up one line."
  8545. )(void) {
  8546. enter_line_selection();
  8547. cursor_up();
  8548. }
  8549. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  8550. "Enter line selection and move the cursor down one line."
  8551. )(void) {
  8552. enter_line_selection();
  8553. cursor_down();
  8554. }
  8555. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  8556. "Shift the current line or screen view horizontally, depending on settings."
  8557. )(int amount) {
  8558. env->coffset += amount;
  8559. if (env->coffset < 0) env->coffset = 0;
  8560. redraw_text();
  8561. }
  8562. static int state_before_paste = 0;
  8563. static int line_before_paste = 0;
  8564. BIM_ACTION(paste_begin, 0, "Begin bracketed paste; disable indentation, completion, etc.")(void) {
  8565. if (global_config.smart_complete) state_before_paste |= 0x01;
  8566. if (env->indent) state_before_paste |= 0x02;
  8567. global_config.smart_complete = 0;
  8568. env->indent = 0;
  8569. env->slowop = 1;
  8570. line_before_paste = env->line_no;
  8571. }
  8572. BIM_ACTION(paste_end, 0, "End bracketed paste; restore indentation, completion, etc.")(void) {
  8573. if (state_before_paste & 0x01) global_config.smart_complete = 1;
  8574. if (state_before_paste & 0x02) env->indent = 1;
  8575. env->slowop = 0;
  8576. int line_to_recalculate = (line_before_paste > 1 ? line_before_paste - 1 : 0);
  8577. recalculate_syntax(env->lines[line_to_recalculate], line_to_recalculate);
  8578. redraw_all();
  8579. }
  8580. struct action_map _NORMAL_MAP[] = {
  8581. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  8582. {'V', enter_line_selection, 0, 0},
  8583. {'v', enter_char_selection, 0, 0},
  8584. {KEY_CTRL_V, enter_col_selection, 0, 0},
  8585. {'O', prepend_and_insert, opt_rw, 0},
  8586. {'o', append_and_insert, opt_rw, 0},
  8587. {'a', insert_after_cursor, opt_rw, 0},
  8588. {'s', delete_forward_and_insert, opt_rw, 0},
  8589. {'x', delete_forward, opt_rep | opt_rw, 0},
  8590. {'P', paste, opt_arg | opt_rw, -1},
  8591. {'p', paste, opt_arg | opt_rw, 1},
  8592. {'r', replace_char, opt_char | opt_rw, 0},
  8593. {'A', insert_at_end, opt_rw, 0},
  8594. {'u', undo_history, opt_rw, 0},
  8595. {KEY_CTRL_R, redo_history, opt_rw, 0},
  8596. {KEY_CTRL_L, redraw_all, 0, 0},
  8597. {KEY_CTRL_G, goto_definition, 0, 0},
  8598. {'i', enter_insert, opt_rw, 0},
  8599. {'R', enter_replace, opt_rw, 0},
  8600. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  8601. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  8602. {KEY_ALT_UP, previous_tab, 0, 0},
  8603. {KEY_ALT_DOWN, next_tab, 0, 0},
  8604. {KEY_CTRL_UNDERSCORE, start_file_search, 0, 0},
  8605. {-1, NULL, 0, 0},
  8606. };
  8607. struct action_map _INSERT_MAP[] = {
  8608. {KEY_ESCAPE, leave_insert, 0, 0},
  8609. {KEY_DELETE, delete_forward, 0, 0},
  8610. {KEY_CTRL_C, leave_insert, 0, 0},
  8611. {KEY_BACKSPACE, smart_backspace, 0, 0},
  8612. {KEY_ENTER, insert_line_feed, 0, 0},
  8613. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  8614. {KEY_CTRL_V, insert_char, opt_byte, 0},
  8615. {KEY_CTRL_W, delete_word, 0, 0},
  8616. {'\t', smart_tab, 0, 0},
  8617. {'/', smart_comment_end, opt_arg, '/'},
  8618. {'}', smart_brace_end, opt_arg, '}'},
  8619. {KEY_PASTE_BEGIN, paste_begin, 0, 0},
  8620. {KEY_PASTE_END, paste_end, 0, 0},
  8621. {-1, NULL, 0, 0},
  8622. };
  8623. struct action_map _REPLACE_MAP[] = {
  8624. {KEY_ESCAPE, leave_insert, 0, 0},
  8625. {KEY_DELETE, delete_forward, 0, 0},
  8626. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8627. {KEY_ENTER, insert_line_feed, 0, 0},
  8628. {-1, NULL, 0, 0},
  8629. };
  8630. struct action_map _LINE_SELECTION_MAP[] = {
  8631. {KEY_ESCAPE, leave_selection, 0, 0},
  8632. {KEY_CTRL_C, leave_selection, 0, 0},
  8633. {'V', leave_selection, 0, 0},
  8634. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  8635. {'y', yank_lines, opt_norm, 0},
  8636. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8637. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  8638. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  8639. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8640. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8641. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8642. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  8643. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  8644. {KEY_SHIFT_UP, cursor_up, 0, 0},
  8645. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  8646. {-1, NULL, 0, 0},
  8647. };
  8648. struct action_map _CHAR_SELECTION_MAP[] = {
  8649. {KEY_ESCAPE, leave_selection, 0, 0},
  8650. {KEY_CTRL_C, leave_selection, 0, 0},
  8651. {'v', leave_selection, 0, 0},
  8652. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  8653. {'y', yank_characters, opt_norm, 0},
  8654. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8655. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8656. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8657. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8658. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  8659. {'r', replace_chars, opt_char | opt_rw, 0},
  8660. {'A', insert_at_end_of_selection, opt_rw, 0},
  8661. {-1, NULL, 0, 0},
  8662. };
  8663. struct action_map _COL_SELECTION_MAP[] = {
  8664. {KEY_ESCAPE, leave_selection, 0, 0},
  8665. {KEY_CTRL_C, leave_selection, 0, 0},
  8666. {KEY_CTRL_V, leave_selection, 0, 0},
  8667. {'I', enter_col_insert, opt_rw, 0},
  8668. {'a', enter_col_insert_after, opt_rw, 0},
  8669. {'d', delete_at_column, opt_arg | opt_rw, 1},
  8670. {-1, NULL, 0, 0},
  8671. };
  8672. struct action_map _COL_INSERT_MAP[] = {
  8673. {KEY_ESCAPE, leave_selection, 0, 0},
  8674. {KEY_CTRL_C, leave_selection, 0, 0},
  8675. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  8676. {KEY_DELETE, delete_at_column, opt_arg, 1},
  8677. {KEY_ENTER, NULL, 0, 0},
  8678. {KEY_CTRL_W, NULL, 0, 0},
  8679. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  8680. {KEY_LEFT, column_left, 0, 0},
  8681. {KEY_RIGHT, column_right, 0, 0},
  8682. {KEY_UP, column_up, 0, 0},
  8683. {KEY_DOWN, column_down, 0, 0},
  8684. {-1, NULL, 0, 0},
  8685. };
  8686. struct action_map _NAVIGATION_MAP[] = {
  8687. /* Common navigation */
  8688. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  8689. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  8690. {':', enter_command, 0, 0},
  8691. {'/', enter_search, opt_arg, 1},
  8692. {'?', enter_search, opt_arg, 0},
  8693. {'n', search_next, opt_rep, 0},
  8694. {'N', search_prev, opt_rep, 0},
  8695. {'j', cursor_down, opt_rep, 0},
  8696. {'k', cursor_up, opt_rep, 0},
  8697. {'h', cursor_left, opt_rep, 0},
  8698. {'l', cursor_right, opt_rep, 0},
  8699. {'b', word_left, opt_rep, 0},
  8700. {'w', word_right, opt_rep, 0},
  8701. {'B', big_word_left, opt_rep, 0},
  8702. {'W', big_word_right, opt_rep, 0},
  8703. {'<', shift_horizontally, opt_arg, -1},
  8704. {'>', shift_horizontally, opt_arg, 1},
  8705. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  8706. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  8707. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  8708. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  8709. {'G', goto_line, opt_nav, 0},
  8710. {'*', search_under_cursor, 0, 0},
  8711. {' ', go_page_down, opt_rep, 0},
  8712. {'%', jump_to_matching_bracket, 0, 0},
  8713. {'{', jump_to_previous_blank, opt_rep, 0},
  8714. {'}', jump_to_next_blank, opt_rep, 0},
  8715. {'$', cursor_end, 0, 0},
  8716. {'|', cursor_home, 0, 0},
  8717. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  8718. {'^', first_non_whitespace, 0, 0},
  8719. {'0', cursor_home, 0, 0},
  8720. {-1, NULL, 0, 0},
  8721. };
  8722. struct action_map _ESCAPE_MAP[] = {
  8723. {KEY_F1, toggle_numbers, 0, 0},
  8724. {KEY_F2, toggle_indent, 0, 0},
  8725. {KEY_F3, toggle_gutter, 0, 0},
  8726. {KEY_F4, toggle_smartcomplete, 0, 0},
  8727. {KEY_MOUSE, handle_mouse, 0, 0},
  8728. {KEY_MOUSE_SGR, handle_mouse_sgr, 0, 0},
  8729. {KEY_UP, cursor_up, opt_rep, 0},
  8730. {KEY_DOWN, cursor_down, opt_rep, 0},
  8731. {KEY_RIGHT, cursor_right, opt_rep, 0},
  8732. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  8733. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  8734. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  8735. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  8736. {KEY_LEFT, cursor_left, opt_rep, 0},
  8737. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  8738. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  8739. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  8740. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  8741. {KEY_HOME, cursor_home, 0, 0},
  8742. {KEY_END, cursor_end, 0, 0},
  8743. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  8744. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  8745. {KEY_CTRL_Z, suspend, 0, 0},
  8746. {-1, NULL, 0, 0}
  8747. };
  8748. struct action_map _COMMAND_MAP[] = {
  8749. {KEY_ENTER, command_accept, 0, 0},
  8750. {'\t', command_tab_complete_buffer, 0, 0},
  8751. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  8752. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  8753. {-1, NULL, 0, 0}
  8754. };
  8755. struct action_map _FILESEARCH_MAP[] = {
  8756. {KEY_ENTER, file_search_accept, 0, 0},
  8757. {KEY_UP, NULL, 0, 0},
  8758. {KEY_DOWN, NULL, 0, 0},
  8759. {-1, NULL, 0, 0}
  8760. };
  8761. struct action_map _SEARCH_MAP[] = {
  8762. {KEY_ENTER, search_accept, 0, 0},
  8763. {KEY_UP, NULL, 0, 0},
  8764. {KEY_DOWN, NULL, 0, 0},
  8765. {-1, NULL, 0, 0}
  8766. };
  8767. struct action_map _INPUT_BUFFER_MAP[] = {
  8768. /* These are generic and shared with search */
  8769. {KEY_ESCAPE, command_discard, 0, 0},
  8770. {KEY_CTRL_C, command_discard, 0, 0},
  8771. {KEY_BACKSPACE, command_backspace, 0, 0},
  8772. {KEY_CTRL_W, command_word_delete, 0, 0},
  8773. {KEY_MOUSE, eat_mouse, 0, 0},
  8774. {KEY_MOUSE_SGR, eat_mouse_sgr, 0, 0},
  8775. {KEY_LEFT, command_cursor_left, 0, 0},
  8776. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  8777. {KEY_RIGHT, command_cursor_right, 0, 0},
  8778. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  8779. {KEY_HOME, command_cursor_home, 0, 0},
  8780. {KEY_END, command_cursor_end, 0, 0},
  8781. {-1, NULL, 0, 0}
  8782. };
  8783. /* DIRECTORY_BROWSE_MAP is only to override KEY_ENTER and should not be remapped,
  8784. * so unlike the others it is not going to be redefined as a pointer. */
  8785. struct action_map DIRECTORY_BROWSE_MAP[] = {
  8786. {KEY_ENTER, open_file_from_line, 0, 0},
  8787. {-1, NULL, 0, 0}
  8788. };
  8789. struct action_map * NORMAL_MAP = NULL;
  8790. struct action_map * INSERT_MAP = NULL;
  8791. struct action_map * REPLACE_MAP = NULL;
  8792. struct action_map * LINE_SELECTION_MAP = NULL;
  8793. struct action_map * CHAR_SELECTION_MAP = NULL;
  8794. struct action_map * COL_SELECTION_MAP = NULL;
  8795. struct action_map * COL_INSERT_MAP = NULL;
  8796. struct action_map * NAVIGATION_MAP = NULL;
  8797. struct action_map * ESCAPE_MAP = NULL;
  8798. struct action_map * COMMAND_MAP = NULL;
  8799. struct action_map * SEARCH_MAP = NULL;
  8800. struct action_map * FILESEARCH_MAP = NULL;
  8801. struct action_map * INPUT_BUFFER_MAP = NULL;
  8802. struct mode_names mode_names[] = {
  8803. {"Normal","norm",&NORMAL_MAP},
  8804. {"Insert","insert",&INSERT_MAP},
  8805. {"Replace","replace",&REPLACE_MAP},
  8806. {"Line Selection","line",&LINE_SELECTION_MAP},
  8807. {"Char Selection","char",&CHAR_SELECTION_MAP},
  8808. {"Col Selection","col",&COL_SELECTION_MAP},
  8809. {"Col Insert","colinsert",&COL_INSERT_MAP},
  8810. {"Navigation (Select)","nav",&NAVIGATION_MAP},
  8811. {"Escape (Select, Insert)","esc",&ESCAPE_MAP},
  8812. {"Command","command",&COMMAND_MAP},
  8813. {"Search","search",&SEARCH_MAP},
  8814. {"Input (Command, Search)","input",&INPUT_BUFFER_MAP},
  8815. {NULL,NULL,NULL},
  8816. };
  8817. int handle_action(struct action_map * basemap, int key) {
  8818. for (struct action_map * map = basemap; map->key != -1; map++) {
  8819. if (map->key == key) {
  8820. if (!map->method) return 1;
  8821. if ((map->options & opt_rw) && (env->readonly)) {
  8822. render_error("Buffer is read-only");
  8823. return 2;
  8824. }
  8825. /* Determine how to format this request */
  8826. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  8827. int c = 0;
  8828. if (map->options & opt_char) {
  8829. c = read_one_character(name_from_key(key));
  8830. }
  8831. if (map->options & opt_byte) {
  8832. c = read_one_byte(name_from_key(key));
  8833. }
  8834. for (int i = 0; i < reps; ++i) {
  8835. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  8836. map->method(map->arg, c);
  8837. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  8838. map->method(c);
  8839. } else if (map->options & opt_arg) {
  8840. map->method(map->arg);
  8841. } else if (map->options & opt_nav) {
  8842. if (nav_buffer) {
  8843. map->method(atoi(nav_buf));
  8844. reset_nav_buffer(0);
  8845. } else {
  8846. map->method(-1);
  8847. }
  8848. } else {
  8849. map->method();
  8850. }
  8851. }
  8852. if (map->options & opt_norm) {
  8853. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  8854. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  8855. else {
  8856. env->mode = MODE_NORMAL;
  8857. redraw_all();
  8858. }
  8859. }
  8860. return 1;
  8861. }
  8862. }
  8863. return 0;
  8864. }
  8865. int handle_nav_buffer(int key) {
  8866. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  8867. if (nav_buffer < NAV_BUFFER_MAX) {
  8868. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  8869. nav_buf[nav_buffer] = key;
  8870. nav_buf[nav_buffer+1] = 0;
  8871. nav_buffer++;
  8872. /* Print the number buffer */
  8873. redraw_commandline();
  8874. }
  8875. return 0;
  8876. }
  8877. return 1;
  8878. }
  8879. /**
  8880. * NORMAL mode
  8881. *
  8882. * Default editor mode - just cursor navigation and keybinds
  8883. * to enter the other modes.
  8884. */
  8885. void normal_mode(void) {
  8886. int last_mode = MODE_NORMAL;
  8887. int refresh = 0;
  8888. while (1) {
  8889. if (global_config.overlay_mode) {
  8890. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  8891. if (refresh) {
  8892. render_command_input_buffer();
  8893. refresh = 0;
  8894. }
  8895. int key = bim_getkey(DEFAULT_KEY_WAIT);
  8896. if (key != KEY_TIMEOUT) {
  8897. refresh = 1;
  8898. if (!handle_action(COMMAND_MAP, key))
  8899. if (!handle_action(INPUT_BUFFER_MAP, key))
  8900. if (key < KEY_ESCAPE) command_insert_char(key);
  8901. }
  8902. continue;
  8903. } else if (global_config.overlay_mode == OVERLAY_MODE_FILESEARCH) {
  8904. if (refresh) {
  8905. redraw_tabbar();
  8906. render_command_input_buffer();
  8907. refresh = 0;
  8908. }
  8909. int key = bim_getkey(DEFAULT_KEY_WAIT);
  8910. if (key != KEY_TIMEOUT) {
  8911. refresh = 1;
  8912. if (!handle_action(FILESEARCH_MAP, key))
  8913. if (!handle_action(INPUT_BUFFER_MAP, key))
  8914. if (key < KEY_ESCAPE) command_insert_char(key);
  8915. }
  8916. continue;
  8917. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8918. if (refresh) {
  8919. render_command_input_buffer();
  8920. refresh = 0;
  8921. }
  8922. int key = bim_getkey(DEFAULT_KEY_WAIT);
  8923. if (key != KEY_TIMEOUT) {
  8924. refresh = 1;
  8925. if (!handle_action(SEARCH_MAP, key)) {
  8926. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  8927. if (key < KEY_ESCAPE) command_insert_char(key);
  8928. }
  8929. }
  8930. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8931. /* Find the next search match */
  8932. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  8933. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  8934. buffer[i] = global_config.command_buffer->text[i].codepoint;
  8935. }
  8936. buffer[global_config.command_buffer->actual] = 0;
  8937. int line = -1, col = -1;
  8938. if (global_config.search_direction == 1) {
  8939. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  8940. if (line == -1 && global_config.search_wraps) {
  8941. find_match(1, 1, &line, &col, buffer, NULL);
  8942. }
  8943. } else {
  8944. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  8945. if (line == -1 && global_config.search_wraps) {
  8946. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, buffer);
  8947. }
  8948. }
  8949. if (line != -1) {
  8950. env->col_no = col;
  8951. env->line_no = line;
  8952. set_preferred_column();
  8953. } else {
  8954. env->coffset = global_config.prev_coffset;
  8955. env->offset = global_config.prev_offset;
  8956. env->col_no = global_config.prev_col;
  8957. set_preferred_column();
  8958. env->line_no = global_config.prev_line;
  8959. }
  8960. draw_search_match(buffer, 0);
  8961. free(buffer);
  8962. }
  8963. }
  8964. continue;
  8965. }
  8966. }
  8967. if (env->mode != last_mode) {
  8968. redraw_statusbar();
  8969. redraw_commandline();
  8970. last_mode = env->mode;
  8971. }
  8972. if (env->mode == MODE_NORMAL) {
  8973. place_cursor_actual();
  8974. int key = 0;
  8975. do {
  8976. key = bim_getkey(DEFAULT_KEY_WAIT);
  8977. } while (key == KEY_TIMEOUT);
  8978. if (handle_nav_buffer(key)) {
  8979. if (!handle_action(NORMAL_MAP, key))
  8980. if (!handle_action(NAVIGATION_MAP, key))
  8981. handle_action(ESCAPE_MAP, key);
  8982. }
  8983. reset_nav_buffer(key);
  8984. } else if (env->mode == MODE_INSERT) {
  8985. if (!refresh) place_cursor_actual();
  8986. int key = bim_getkey(refresh ? 10 : DEFAULT_KEY_WAIT);
  8987. if (key == KEY_TIMEOUT) {
  8988. place_cursor_actual();
  8989. if (refresh > 1) {
  8990. redraw_text();
  8991. } else if (refresh) {
  8992. redraw_line(env->line_no-1);
  8993. }
  8994. refresh = 0;
  8995. } else if (handle_action(INSERT_MAP, key)) {
  8996. refresh = 2;
  8997. } else if (handle_action(ESCAPE_MAP, key)) {
  8998. /* Do nothing */
  8999. } else if (key < KEY_ESCAPE) {
  9000. insert_char(key);
  9001. if (global_config.smart_complete) {
  9002. redraw_line(env->line_no-1);
  9003. while (omni_complete(1) == 1);
  9004. }
  9005. refresh |= 1;
  9006. }
  9007. } else if (env->mode == MODE_REPLACE) {
  9008. place_cursor_actual();
  9009. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9010. if (key != KEY_TIMEOUT) {
  9011. if (handle_action(REPLACE_MAP, key)) {
  9012. redraw_text();
  9013. } else if (!handle_action(ESCAPE_MAP, key)) {
  9014. /* Perform replacement */
  9015. if (key < KEY_ESCAPE) {
  9016. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  9017. replace_char(key);
  9018. env->col_no += 1;
  9019. } else {
  9020. insert_char(key);
  9021. redraw_line(env->line_no-1);
  9022. }
  9023. set_preferred_column();
  9024. }
  9025. }
  9026. }
  9027. } else if (env->mode == MODE_LINE_SELECTION) {
  9028. place_cursor_actual();
  9029. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9030. if (key == KEY_TIMEOUT) continue;
  9031. if (handle_nav_buffer(key)) {
  9032. if (!handle_action(LINE_SELECTION_MAP, key))
  9033. if (!handle_action(NAVIGATION_MAP, key))
  9034. handle_action(ESCAPE_MAP, key);
  9035. }
  9036. reset_nav_buffer(key);
  9037. if (env->mode == MODE_LINE_SELECTION) {
  9038. /* Mark current line */
  9039. _redraw_line(env->line_no,0);
  9040. _redraw_line(env->start_line,1);
  9041. /* Properly mark everything in the span we just moved through */
  9042. if (env->prev_line < env->line_no) {
  9043. for (int i = env->prev_line; i < env->line_no; ++i) {
  9044. _redraw_line(i,0);
  9045. }
  9046. env->prev_line = env->line_no;
  9047. } else if (env->prev_line > env->line_no) {
  9048. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9049. _redraw_line(i,0);
  9050. }
  9051. env->prev_line = env->line_no;
  9052. }
  9053. redraw_commandline();
  9054. }
  9055. } else if (env->mode == MODE_CHAR_SELECTION) {
  9056. place_cursor_actual();
  9057. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9058. if (key == KEY_TIMEOUT) continue;
  9059. if (handle_nav_buffer(key)) {
  9060. if (!handle_action(CHAR_SELECTION_MAP, key))
  9061. if (!handle_action(NAVIGATION_MAP, key))
  9062. handle_action(ESCAPE_MAP, key);
  9063. }
  9064. reset_nav_buffer(key);
  9065. if (env->mode == MODE_CHAR_SELECTION) {
  9066. /* Mark current line */
  9067. _redraw_line_char(env->line_no,1);
  9068. /* Properly mark everything in the span we just moved through */
  9069. if (env->prev_line < env->line_no) {
  9070. for (int i = env->prev_line; i < env->line_no; ++i) {
  9071. _redraw_line_char(i,1);
  9072. }
  9073. env->prev_line = env->line_no;
  9074. } else if (env->prev_line > env->line_no) {
  9075. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9076. _redraw_line_char(i,1);
  9077. }
  9078. env->prev_line = env->line_no;
  9079. }
  9080. }
  9081. } else if (env->mode == MODE_COL_SELECTION) {
  9082. place_cursor_actual();
  9083. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9084. if (key == KEY_TIMEOUT) continue;
  9085. if (handle_nav_buffer(key)) {
  9086. if (!handle_action(COL_SELECTION_MAP, key))
  9087. if (!handle_action(NAVIGATION_MAP, key))
  9088. handle_action(ESCAPE_MAP, key);
  9089. }
  9090. reset_nav_buffer(key);
  9091. if (env->mode == MODE_COL_SELECTION) {
  9092. _redraw_line_col(env->line_no, 0);
  9093. /* Properly mark everything in the span we just moved through */
  9094. if (env->prev_line < env->line_no) {
  9095. for (int i = env->prev_line; i < env->line_no; ++i) {
  9096. _redraw_line_col(i,0);
  9097. }
  9098. env->prev_line = env->line_no;
  9099. } else if (env->prev_line > env->line_no) {
  9100. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  9101. _redraw_line_col(i,0);
  9102. }
  9103. env->prev_line = env->line_no;
  9104. }
  9105. redraw_commandline();
  9106. }
  9107. } else if (env->mode == MODE_COL_INSERT) {
  9108. int key = bim_getkey(refresh ? 10 : DEFAULT_KEY_WAIT);
  9109. if (key == KEY_TIMEOUT) {
  9110. if (refresh) {
  9111. redraw_commandline();
  9112. redraw_text();
  9113. }
  9114. refresh = 0;
  9115. } else if (handle_action(COL_INSERT_MAP, key)) {
  9116. /* pass */
  9117. } else if (key < KEY_ESCAPE) {
  9118. insert_char_at_column(key);
  9119. refresh = 1;
  9120. }
  9121. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  9122. place_cursor_actual();
  9123. int key = bim_getkey(DEFAULT_KEY_WAIT);
  9124. if (handle_nav_buffer(key)) {
  9125. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  9126. if (!handle_action(NAVIGATION_MAP, key))
  9127. handle_action(ESCAPE_MAP, key);
  9128. }
  9129. reset_nav_buffer(key);
  9130. }
  9131. }
  9132. }
  9133. KrkClass * CommandDef;
  9134. struct CommandDef {
  9135. KrkInstance inst;
  9136. struct command_def * command;
  9137. };
  9138. int process_krk_command(const char * cmd, KrkValue * outVal) {
  9139. place_cursor(global_config.term_width, global_config.term_height);
  9140. fprintf(stdout, "\n");
  9141. /* By resetting, we're at 0 frames. */
  9142. krk_resetStack();
  9143. /* Push something so we're not at the bottom of the stack when an
  9144. * exception happens, or we'll get the normal interpreter behavior
  9145. * and won't be able to examine the exception ourselves. */
  9146. krk_push(NONE_VAL());
  9147. /* If we don't set outSlots for the top frame a syntax error will
  9148. * get printed by the interpreter and we can't catch it here. */
  9149. krk_currentThread.frames[0].outSlots = 1;
  9150. /* Call the interpreter */
  9151. KrkValue out = krk_interpret(cmd,"<bim>");
  9152. /* If the user typed just a command name, try to execute it. */
  9153. if (krk_isInstanceOf(out,CommandDef)) {
  9154. krk_push(out);
  9155. out = krk_callStack(0);
  9156. }
  9157. if (outVal) *outVal = out;
  9158. int retval = (IS_INTEGER(out)) ? AS_INTEGER(out) : 0;
  9159. int hadOutput = 0;
  9160. /* If we got an exception during execution, print it now */
  9161. if (krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION) {
  9162. if (krk_isInstanceOf(krk_currentThread.currentException, vm.exceptions->syntaxError)) {
  9163. }
  9164. set_fg_color(COLOR_RED);
  9165. fflush(stdout);
  9166. krk_dumpTraceback();
  9167. set_fg_color(COLOR_FG);
  9168. fflush(stdout);
  9169. hadOutput = 1;
  9170. krk_resetStack();
  9171. }
  9172. /* Otherwise, we can look at the result here. */
  9173. if (!IS_NONE(out) && !(IS_INTEGER(out) && AS_INTEGER(out) == 0)) {
  9174. krk_push(out);
  9175. KrkValue repr = krk_callDirect(krk_getType(out)->_reprer, 1);
  9176. if (IS_STRING(repr)) {
  9177. fprintf(stdout, " => %s\n", AS_CSTRING(repr));
  9178. clear_to_end();
  9179. }
  9180. krk_resetStack();
  9181. hadOutput = 1;
  9182. }
  9183. /* If we had either an exception or a non-zero, non-None result,
  9184. * we want to wait for a key press before continuing, and avoid
  9185. * clearing the screen if the user is going to enter another command. */
  9186. if (hadOutput) {
  9187. int c;
  9188. while ((c = bim_getch())== -1);
  9189. if (c != ':') {
  9190. bim_unget(c);
  9191. } else {
  9192. enter_command();
  9193. global_config.command_offset = 0;
  9194. global_config.command_col_no = 1;
  9195. render_command_input_buffer();
  9196. return retval;
  9197. }
  9198. }
  9199. global_config.break_from_selection = 1;
  9200. if (!global_config.had_error) redraw_all();
  9201. global_config.had_error = 0;
  9202. return retval;
  9203. }
  9204. /**
  9205. * Show help text for -?
  9206. */
  9207. static void show_usage(char * argv[]) {
  9208. #define _s "\033[3m"
  9209. #define _e "\033[0m\n"
  9210. printf(
  9211. "bim - Text editor\n"
  9212. "\n"
  9213. "usage: %s [options] [file]\n"
  9214. " %s [options] -- -\n"
  9215. "\n"
  9216. " -R " _s "open initial buffer read-only" _e
  9217. " -O " _s "set various options; examples:" _e
  9218. " noaltscreen " _s "disable alternate screen buffer" _e
  9219. " nounicode " _s "disable unicode display" _e
  9220. " nosyntax " _s "disable syntax highlighting on load" _e
  9221. " nohistory " _s "disable undo/redo" _e
  9222. " nomouse " _s "disable mouse support" _e
  9223. " cansgrmouse " _s "enable SGR mouse escape sequences" _e
  9224. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  9225. " " _s "-C includes line numbers, -c does not" _e
  9226. " -u " _s "override bimrc file" _e
  9227. " -? " _s "show this help text" _e
  9228. "\n"
  9229. "Long options:\n"
  9230. " --help " _s "show this help text" _e
  9231. " --version " _s "show version information and available plugins" _e
  9232. " --dump-mappings " _s "dump markdown description of key mappings" _e
  9233. " --dump-commands " _s "dump markdown description of all commands" _e
  9234. " --dump-config " _s "dump key mappings as a bimscript" _e
  9235. " --html FILE " _s "convert FILE to syntax-highlighted HTML" _e
  9236. "\n", argv[0], argv[0]);
  9237. #undef _e
  9238. #undef _s
  9239. }
  9240. BIM_COMMAND(runkrk,"runkrk", "Run a kuroko script") {
  9241. if (argc < 2) return 1;
  9242. /* In case we're running in a weird context? */
  9243. int previousExitFrame = krk_currentThread.exitOnFrame;
  9244. krk_currentThread.exitOnFrame = krk_currentThread.frameCount;
  9245. krk_runfile(argv[1],argv[1]);
  9246. krk_currentThread.exitOnFrame = previousExitFrame;
  9247. redraw_all();
  9248. return 0;
  9249. }
  9250. /**
  9251. * Enable or disable terminal features/quirks and other options.
  9252. * Used by -O and by the `quirks` bimrc command.
  9253. */
  9254. int set_capability(char * arg) {
  9255. char * argname;
  9256. int value;
  9257. if (strstr(arg,"no") == arg) {
  9258. argname = &arg[2];
  9259. value = 0;
  9260. } else if (strstr(arg,"can") == arg) {
  9261. argname = &arg[3];
  9262. value = 1;
  9263. } else {
  9264. render_error("Capabilities must by 'no{CAP}' or 'can{CAP}': %s", arg);
  9265. return 2;
  9266. }
  9267. /* Terminal features / quirks */
  9268. if (!strcmp(argname, "24bit")) global_config.can_24bit = value;
  9269. else if (!strcmp(argname, "256color")) global_config.can_256color = value;
  9270. else if (!strcmp(argname, "altscreen")) global_config.can_altscreen = value;
  9271. else if (!strcmp(argname, "bce")) global_config.can_bce = value;
  9272. else if (!strcmp(argname, "bright")) global_config.can_bright = value;
  9273. else if (!strcmp(argname, "hideshow")) global_config.can_hideshow = value;
  9274. else if (!strcmp(argname, "italic")) global_config.can_italic = value;
  9275. else if (!strcmp(argname, "mouse")) global_config.can_mouse = value;
  9276. else if (!strcmp(argname, "scroll")) global_config.can_scroll = value;
  9277. else if (!strcmp(argname, "title")) global_config.can_title = value;
  9278. else if (!strcmp(argname, "unicode")) global_config.can_unicode = value;
  9279. else if (!strcmp(argname, "insert")) global_config.can_insert = value;
  9280. else if (!strcmp(argname, "paste")) global_config.can_bracketedpaste = value;
  9281. else if (!strcmp(argname, "sgrmouse")) global_config.can_sgrmouse = value;
  9282. /* Startup options */
  9283. else if (!strcmp(argname, "syntax")) global_config.highlight_on_open = value;
  9284. else if (!strcmp(argname, "history")) global_config.history_enabled = value;
  9285. else {
  9286. render_error("Unknown capability: %s", argname);
  9287. return 1;
  9288. }
  9289. return 0;
  9290. }
  9291. BIM_COMMAND(setcap, "setcap", "Enable or disable quirks/features.") {
  9292. for (int i = 1; i < argc; ++i) {
  9293. if (set_capability(argv[i])) return 1;
  9294. }
  9295. return 0;
  9296. }
  9297. BIM_COMMAND(quirk,"quirk","Handle quirks based on environment variables") {
  9298. if (argc < 3) goto _quirk_arg_error;
  9299. char * varname = argv[1];
  9300. char * teststr = argv[2];
  9301. char * value = getenv(varname);
  9302. if (!value) return 0;
  9303. if (strstr(value, teststr) == value) {
  9304. /* Process quirk strings */
  9305. for (int i = 3; i < argc; ++i) {
  9306. set_capability(argv[i]);
  9307. }
  9308. }
  9309. return 0;
  9310. _quirk_arg_error:
  9311. render_error("Usage: quirk ENVVAR value no... can...");
  9312. return 1;
  9313. }
  9314. /**
  9315. * Load bimrc configuration file.
  9316. *
  9317. * At the moment, this a simple key=value list.
  9318. */
  9319. void load_bimrc(void) {
  9320. if (!global_config.bimrc_path) return;
  9321. /* Default is ~/.bimrc */
  9322. char * tmp = strdup(global_config.bimrc_path);
  9323. if (!*tmp) {
  9324. free(tmp);
  9325. return;
  9326. }
  9327. /* Parse ~ at the front of the path. */
  9328. if (*tmp == '~') {
  9329. char path[1024] = {0};
  9330. char * home = getenv("HOME");
  9331. if (!home) {
  9332. /* $HOME is unset? */
  9333. free(tmp);
  9334. return;
  9335. }
  9336. /* New path is $HOME/.bimrc */
  9337. snprintf(path, 1024, "%s%s", home, tmp+1);
  9338. free(tmp);
  9339. tmp = strdup(path);
  9340. }
  9341. struct stat statbuf;
  9342. if (stat(tmp, &statbuf)) {
  9343. free(tmp);
  9344. return;
  9345. }
  9346. char * args[] = {"runkrk", tmp, NULL};
  9347. if (bim_command_runkrk("runkrk", 2, args)) {
  9348. /* Wait */
  9349. render_error("Errors were encountered when loading bimrc. Press ENTER to continue.");
  9350. int c;
  9351. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  9352. }
  9353. free(tmp);
  9354. }
  9355. static int checkClass(KrkClass * _class, KrkClass * base) {
  9356. while (_class) {
  9357. if (_class == base) return 1;
  9358. _class = _class->base;
  9359. }
  9360. return 0;
  9361. }
  9362. static KrkValue krk_bim_syntax_dict;
  9363. static KrkValue krk_bim_register_syntax(int argc, KrkValue argv[], int hasKw) {
  9364. if (argc < 1 || !IS_CLASS(argv[0]) || !checkClass(AS_CLASS(argv[0]), syntaxStateClass))
  9365. return krk_runtimeError(vm.exceptions->typeError, "Can not register '%s' as a syntax highlighter, expected subclass of SyntaxState.", krk_typeName(argv[0]));
  9366. KrkValue name = krk_valueGetAttribute_default(argv[0], "name", NONE_VAL());
  9367. KrkValue extensions = krk_valueGetAttribute_default(argv[0], "extensions", NONE_VAL());
  9368. KrkValue spaces = krk_valueGetAttribute_default(argv[0], "spaces", BOOLEAN_VAL(0));
  9369. KrkValue calculate = krk_valueGetAttribute_default(argv[0], "calculate", NONE_VAL());
  9370. if (!IS_STRING(name))
  9371. return krk_runtimeError(vm.exceptions->typeError, "%s.name must be str", AS_CLASS(argv[0])->name->chars);
  9372. if (!IS_TUPLE(extensions))
  9373. return krk_runtimeError(vm.exceptions->typeError, "%s.extensions must be tuple<str>", AS_CLASS(argv[0])->name->chars);
  9374. if (!IS_BOOLEAN(spaces))
  9375. return krk_runtimeError(vm.exceptions->typeError, "%s.spaces must be bool", AS_CLASS(argv[0])->name->chars);
  9376. if (!IS_CLOSURE(calculate))
  9377. return krk_runtimeError(vm.exceptions->typeError, "%s.calculate must be method, not '%s'", AS_CLASS(argv[0])->name->chars, krk_typeName(calculate));
  9378. /* Convert tuple of strings */
  9379. char ** ext = malloc(sizeof(char *) * (AS_TUPLE(extensions)->values.count + 1)); /* +1 for NULL */
  9380. ext[AS_TUPLE(extensions)->values.count] = NULL;
  9381. for (size_t i = 0; i < AS_TUPLE(extensions)->values.count; ++i) {
  9382. if (!IS_STRING(AS_TUPLE(extensions)->values.values[i])) {
  9383. free(ext);
  9384. return krk_runtimeError(vm.exceptions->typeError, "%s.extensions must by tuple<str>", AS_CLASS(argv[0])->name->chars);
  9385. }
  9386. ext[i] = AS_CSTRING(AS_TUPLE(extensions)->values.values[i]);
  9387. }
  9388. add_syntax((struct syntax_definition) {
  9389. AS_CSTRING(name), /* name */
  9390. ext, /* NULL-terminated array of extensions */
  9391. NULL, /* calculate function */
  9392. AS_BOOLEAN(spaces), /* spaces */
  9393. NULL, /* qualifier */
  9394. NULL, /* matcher */
  9395. AS_OBJECT(calculate), /* krkFunc */
  9396. AS_OBJECT(argv[0]),
  9397. });
  9398. /* And save it in the module stuff. */
  9399. krk_tableSet(AS_DICT(krk_bim_syntax_dict), name, argv[0]);
  9400. return NONE_VAL();
  9401. }
  9402. static KrkValue krk_bim_theme_dict;
  9403. static KrkValue krk_bim_define_theme(int argc, KrkValue argv[], int hasKw) {
  9404. if (argc < 1 || !IS_CLOSURE(argv[0]))
  9405. return krk_runtimeError(vm.exceptions->typeError, "themes must be functions, not '%s'", krk_typeName(argv[0]));
  9406. KrkValue name = OBJECT_VAL(AS_CLOSURE(argv[0])->function->name);
  9407. add_colorscheme((struct theme_def) {
  9408. AS_CSTRING(name),
  9409. AS_OBJECT(argv[0]),
  9410. });
  9411. krk_tableSet(AS_DICT(krk_bim_theme_dict), name, argv[0]);
  9412. return argv[0];
  9413. }
  9414. int c_keyword_qualifier(int c) {
  9415. return isalnum(c) || (c == '_');
  9416. }
  9417. #define BIM_STATE() \
  9418. if (unlikely(argc < 1 || !krk_isInstanceOf(argv[0],syntaxStateClass))) return krk_runtimeError(vm.exceptions->typeError, "expected state"); \
  9419. KrkInstance * _self = AS_INSTANCE(argv[0]); \
  9420. struct SyntaxState * self = (struct SyntaxState*)_self; \
  9421. struct syntax_state * state = &self->state;
  9422. static KrkTuple * _bim_state_chars = NULL;
  9423. static KrkValue bim_krk_state_getstate(int argc, KrkValue argv[], int hasKw) {
  9424. BIM_STATE();
  9425. if (argc > 1 && IS_INTEGER(argv[1])) {
  9426. state->state = AS_INTEGER(argv[1]);
  9427. } else if (argc > 1 && IS_NONE(argv[1])) {
  9428. state->state = -1;
  9429. }
  9430. return INTEGER_VAL(state->state);
  9431. }
  9432. static KrkValue bim_krk_state_setstate(int argc, KrkValue argv[], int hasKw) {
  9433. BIM_STATE();
  9434. if (argc > 1 && IS_INTEGER(argv[1])) {
  9435. state->state = AS_INTEGER(argv[1]);
  9436. } else if (argc > 1 && IS_NONE(argv[1])) {
  9437. state->state = -1;
  9438. } else {
  9439. return krk_runtimeError(vm.exceptions->typeError, "expected int");
  9440. }
  9441. return NONE_VAL();
  9442. }
  9443. static KrkValue bim_krk_state_index(int argc, KrkValue argv[], int hasKw) {
  9444. BIM_STATE();
  9445. return INTEGER_VAL(state->i);
  9446. }
  9447. static KrkValue bim_krk_state_lineno(int argc, KrkValue argv[], int hasKw) {
  9448. BIM_STATE();
  9449. return INTEGER_VAL(state->line_no);
  9450. }
  9451. static KrkValue bim_krk_state_get(int argc, KrkValue argv[], int hasKw) {
  9452. BIM_STATE();
  9453. long arg = AS_INTEGER(argv[1]);
  9454. int charRel = charrel(arg);
  9455. if (charRel == -1) return NONE_VAL();
  9456. if (charRel >= 32 && charRel <= 126) return _bim_state_chars->values.values[charRel - 32];
  9457. char tmp[8] = {0};
  9458. size_t len = to_eight(charRel, tmp);
  9459. return OBJECT_VAL(krk_copyString(tmp,len));
  9460. }
  9461. static KrkValue bim_krk_state_getslice(int argc, KrkValue argv[], int hasKw) {
  9462. BIM_STATE();
  9463. struct StringBuilder sb = {0};
  9464. if (!(IS_INTEGER(argv[1]) || IS_NONE(argv[1]))) return krk_runtimeError(vm.exceptions->typeError, "Bad index");
  9465. if (!(IS_INTEGER(argv[2]) || IS_NONE(argv[2]))) return krk_runtimeError(vm.exceptions->typeError, "Bad index");
  9466. int start = IS_NONE(argv[1]) ? 0 : AS_INTEGER(argv[1]);
  9467. int end = IS_NONE(argv[2]) ? (krk_integer_type)(state->line->actual - state->i) : AS_INTEGER(argv[2]);
  9468. if (end < start) end = start;
  9469. for (int i = start; i < end; ++i) {
  9470. int charRel = charrel(i);
  9471. if (charRel == -1) break;
  9472. char tmp[8] = {0};
  9473. size_t len = to_eight(charRel, tmp);
  9474. pushStringBuilderStr(&sb, tmp, len);
  9475. }
  9476. return finishStringBuilder(&sb);
  9477. }
  9478. static KrkValue bim_krk_state_isdigit(int argc, KrkValue argv[], int hasKw) {
  9479. if (IS_NONE(argv[1])) return BOOLEAN_VAL(0);
  9480. if (!IS_STRING(argv[1])) {
  9481. krk_runtimeError(vm.exceptions->typeError, "not a string: %s", krk_typeName(argv[1]));
  9482. return BOOLEAN_VAL(0);
  9483. }
  9484. if (AS_STRING(argv[1])->codesLength > 1) {
  9485. krk_runtimeError(vm.exceptions->typeError, "arg must be str of len 1");
  9486. return BOOLEAN_VAL(0);
  9487. }
  9488. unsigned int c = krk_unicodeCodepoint(AS_STRING(argv[1]), 0);
  9489. return BOOLEAN_VAL(!!isdigit(c));
  9490. }
  9491. static KrkValue bim_krk_state_isxdigit(int argc, KrkValue argv[], int hasKw) {
  9492. if (!IS_STRING(argv[1])) return BOOLEAN_VAL(0);
  9493. if (AS_STRING(argv[1])->length > 1) return BOOLEAN_VAL(0);
  9494. int c = AS_CSTRING(argv[1])[0];
  9495. return BOOLEAN_VAL(!!isxdigit(c));
  9496. }
  9497. static KrkValue bim_krk_state_paint(int argc, KrkValue argv[], int hasKw) {
  9498. BIM_STATE();
  9499. long howMuch = AS_INTEGER(argv[1]);
  9500. if (howMuch == -1) howMuch = state->line->actual;
  9501. long whatFlag = AS_INTEGER(argv[2]);
  9502. paint(howMuch, whatFlag);
  9503. return NONE_VAL();
  9504. }
  9505. static KrkValue bim_krk_state_paintComment(int argc, KrkValue argv[], int hasKw) {
  9506. BIM_STATE();
  9507. paint_comment(state);
  9508. return NONE_VAL();
  9509. }
  9510. static KrkValue bim_krk_state_skip(int argc, KrkValue argv[], int hasKw) {
  9511. BIM_STATE();
  9512. skip();
  9513. return NONE_VAL();
  9514. }
  9515. static KrkValue bim_krk_state_cKeywordQualifier(int argc, KrkValue argv[], int hasKw) {
  9516. if (IS_INTEGER(argv[0])) return BOOLEAN_VAL(!!c_keyword_qualifier(AS_INTEGER(argv[0])));
  9517. if (!IS_STRING(argv[0])) return BOOLEAN_VAL(0);
  9518. if (AS_STRING(argv[0])->length > 1) return BOOLEAN_VAL(0);
  9519. return BOOLEAN_VAL(!!c_keyword_qualifier(AS_CSTRING(argv[0])[0]));
  9520. }
  9521. static int callQualifier(KrkValue qualifier, int codepoint) {
  9522. if (IS_NATIVE(qualifier) && AS_NATIVE(qualifier)->function == bim_krk_state_cKeywordQualifier) return AS_BOOLEAN(!!c_keyword_qualifier(codepoint));
  9523. krk_push(qualifier);
  9524. krk_push(INTEGER_VAL(codepoint));
  9525. KrkValue result = krk_callStack(1);
  9526. if (IS_BOOLEAN(result)) return AS_BOOLEAN(result);
  9527. return 0;
  9528. }
  9529. #define KRK_STRING_FAST(string,offset) (uint32_t)\
  9530. (string->type <= 1 ? ((uint8_t*)string->codes)[offset] : \
  9531. (string->type == 2 ? ((uint16_t*)string->codes)[offset] : \
  9532. ((uint32_t*)string->codes)[offset]))
  9533. static KrkValue bim_krk_state_findKeywords(int argc, KrkValue argv[], int hasKw) {
  9534. BIM_STATE();
  9535. if (unlikely(argc < 4 || !(IS_INSTANCE(argv[1]) && AS_INSTANCE(argv[1])->_class == vm.baseClasses->listClass) || !IS_INTEGER(argv[2])))
  9536. return krk_runtimeError(vm.exceptions->typeError, "invalid arguments to SyntaxState.findKeywords");
  9537. KrkValue qualifier = argv[3];
  9538. int flag = AS_INTEGER(argv[2]);
  9539. if (callQualifier(qualifier, lastchar())) return BOOLEAN_VAL(0);
  9540. if (!callQualifier(qualifier, charat())) return BOOLEAN_VAL(0);
  9541. for (size_t keyword = 0; keyword < AS_LIST(argv[1])->count; ++keyword) {
  9542. if (!IS_STRING(AS_LIST(argv[1])->values[keyword]))
  9543. return krk_runtimeError(vm.exceptions->typeError, "expected list of strings, found '%s'", krk_typeName(AS_LIST(argv[1])->values[keyword]));
  9544. KrkString * me = AS_STRING(AS_LIST(argv[1])->values[keyword]);
  9545. size_t d = 0;
  9546. if (me->type == KRK_STRING_ASCII) {
  9547. while (state->i + (int)d < state->line->actual &&
  9548. d < me->codesLength &&
  9549. state->line->text[state->i+d].codepoint == me->chars[d]) d++;
  9550. } else {
  9551. krk_unicodeString(me);
  9552. while (state->i + (int)d < state->line->actual &&
  9553. d < me->codesLength &&
  9554. state->line->text[state->i+d].codepoint == KRK_STRING_FAST(me,d)) d++;
  9555. }
  9556. if (d == me->codesLength && (state->i + (int)d >= state->line->actual ||
  9557. !callQualifier(qualifier,state->line->text[state->i+d].codepoint))) {
  9558. paint((int)me->codesLength, flag);
  9559. return BOOLEAN_VAL(1);
  9560. }
  9561. }
  9562. return BOOLEAN_VAL(0);
  9563. }
  9564. static KrkValue bim_krk_state_matchAndPaint(int argc, KrkValue argv[], int hasKw) {
  9565. BIM_STATE();
  9566. if (argc < 4 || !IS_STRING(argv[1]) || !IS_INTEGER(argv[2]))
  9567. return krk_runtimeError(vm.exceptions->typeError, "invalid arguments to SyntaxState.matchAndPaint");
  9568. KrkValue qualifier = argv[3];
  9569. int flag = AS_INTEGER(argv[2]);
  9570. KrkString * me = AS_STRING(argv[1]);
  9571. size_t d = 0;
  9572. if (me->type == KRK_STRING_ASCII) {
  9573. while (state->i + (int)d < state->line->actual &&
  9574. d < me->codesLength &&
  9575. state->line->text[state->i+d].codepoint == me->chars[d]) d++;
  9576. } else {
  9577. krk_unicodeString(me);
  9578. while (state->i + (int)d < state->line->actual &&
  9579. d < me->codesLength &&
  9580. state->line->text[state->i+d].codepoint == KRK_STRING_FAST(me,d)) d++;
  9581. }
  9582. if (d == me->codesLength && (state->i + (int)d >= state->line->actual ||
  9583. !callQualifier(qualifier,state->line->text[state->i+d].codepoint))) {
  9584. paint((int)me->codesLength, flag);
  9585. return BOOLEAN_VAL(1);
  9586. }
  9587. return BOOLEAN_VAL(0);
  9588. }
  9589. static KrkValue bim_krk_state_rewind(int argc, KrkValue argv[], int hasKw) {
  9590. BIM_STATE();
  9591. state->i -= AS_INTEGER(argv[1]);
  9592. return NONE_VAL();
  9593. }
  9594. static KrkValue bim_krk_state_commentBuzzwords(int argc, KrkValue argv[], int hasKw) {
  9595. BIM_STATE();
  9596. return BOOLEAN_VAL(common_comment_buzzwords(state));
  9597. }
  9598. static KrkValue bim_krk_state_init(int argc, KrkValue argv[], int hasKw) {
  9599. BIM_STATE();
  9600. if (argc < 2 || !krk_isInstanceOf(argv[1], syntaxStateClass)) {
  9601. return krk_runtimeError(vm.exceptions->typeError, "Can only initialize subhighlighter from an existing highlighter.");
  9602. }
  9603. *state = ((struct SyntaxState*)AS_INSTANCE(argv[1]))->state;
  9604. return argv[0];
  9605. }
  9606. static KrkValue krk_bim_get_commands(int argc, KrkValue argv[], int hasKw) {
  9607. KrkValue myList = krk_list_of(0, NULL,0);
  9608. krk_push(myList);
  9609. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  9610. krk_writeValueArray(AS_LIST(myList), OBJECT_VAL(krk_copyString(c->name,strlen(c->name))));
  9611. }
  9612. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  9613. krk_writeValueArray(AS_LIST(myList), OBJECT_VAL(krk_copyString(c->name,strlen(c->name))));
  9614. }
  9615. return krk_pop();
  9616. }
  9617. KrkClass * ActionDef;
  9618. struct ActionDef {
  9619. KrkInstance inst;
  9620. struct action_def * action;
  9621. };
  9622. static KrkValue bim_krk_action_call(int argc, KrkValue argv[], int hasKw) {
  9623. struct ActionDef * self = (void*)AS_OBJECT(argv[0]);
  9624. /* Figure out arguments */
  9625. int args = 0;
  9626. if (self->action->options & ARG_IS_CUSTOM) args++;
  9627. if (self->action->options & ARG_IS_INPUT) args++;
  9628. if (self->action->options & ARG_IS_PROMPT) args++;
  9629. int argsAsInts[3] = { 0, 0, 0 };
  9630. for (int i = 0; i < args; i++) {
  9631. if (argc < i + 2)
  9632. return krk_runtimeError(vm.exceptions->argumentError, "%s() takes %d argument%s",
  9633. self->action->name, args, args == 1 ? "" : "s");
  9634. if (IS_INTEGER(argv[i+1])) {
  9635. argsAsInts[i] = AS_INTEGER(argv[i+1]);
  9636. } else if (IS_STRING(argv[i+1]) && AS_STRING(argv[i+1])->codesLength == 1) {
  9637. argsAsInts[i] = krk_unicodeCodepoint(AS_STRING(argv[i+1]), 0);
  9638. } else if (IS_BOOLEAN(argv[i+1])) {
  9639. argsAsInts[i] = AS_BOOLEAN(argv[i+1]);
  9640. } else {
  9641. return krk_runtimeError(vm.exceptions->typeError,
  9642. "argument to %s() must be int, bool, or str of len 1",
  9643. self->action->name);
  9644. }
  9645. }
  9646. self->action->action(argsAsInts[0], argsAsInts[1], argsAsInts[2]);
  9647. return NONE_VAL();
  9648. }
  9649. static KrkValue bim_krk_command_call(int argc, KrkValue argv[], int hasKw) {
  9650. struct CommandDef * self = (void*)AS_OBJECT(argv[0]);
  9651. char ** args = malloc(sizeof(char*)*argc);
  9652. args[0] = strdup(self->command->name);
  9653. for (int i = 1; i < argc; ++i) {
  9654. if (IS_STRING(argv[i])) {
  9655. args[i] = strdup(AS_CSTRING(argv[i]));
  9656. } else {
  9657. krk_push(argv[i]);
  9658. KrkValue asString = krk_callDirect(krk_getType(argv[i])->_tostr, 1);
  9659. args[i] = strdup(AS_CSTRING(asString));
  9660. }
  9661. }
  9662. int result = self->command->command(args[0], argc, args);
  9663. for (int i = 0; i < argc; ++i) {
  9664. free(args[i]);
  9665. }
  9666. free(args);
  9667. return INTEGER_VAL(result);
  9668. }
  9669. static void makeClass(KrkInstance * module, KrkClass ** _class, const char * name, KrkClass * base) {
  9670. KrkString * str_Name = krk_copyString(name,strlen(name));
  9671. krk_push(OBJECT_VAL(str_Name));
  9672. *_class = krk_newClass(str_Name, base);
  9673. krk_push(OBJECT_VAL(*_class));
  9674. /* Bind it */
  9675. krk_attachNamedObject(&module->fields,name,(KrkObj*)*_class);
  9676. krk_pop();
  9677. krk_pop();
  9678. }
  9679. void import_directory(char * dirName) {
  9680. const char * extra = "";