| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355 |
- #include "vvim.h"
- #include <QKeyEvent>
- #include <QTextBlock>
- #include <QTextDocument>
- #include <QString>
- #include <QScrollBar>
- #include <QDebug>
- #include <QClipboard>
- #include <QApplication>
- #include <QMimeData>
- #include "vconfigmanager.h"
- #include "veditor.h"
- #include "utils/veditutils.h"
- #include "vconstants.h"
- #include "vmdeditor.h"
- extern VConfigManager *g_config;
- const QChar VVim::c_unnamedRegister = QChar('"');
- const QChar VVim::c_blackHoleRegister = QChar('_');
- const QChar VVim::c_selectionRegister = QChar('+');
- QMap<QChar, VVim::Register> VVim::s_registers;
- const int VVim::SearchHistory::c_capacity = 50;
- #define ADDKEY(x, y) case (x): {ch = (y); break;}
- // Returns NULL QChar if invalid.
- static QChar keyToChar(int p_key, int p_modifiers)
- {
- if (p_key >= Qt::Key_0 && p_key <= Qt::Key_9) {
- return QChar('0' + (p_key - Qt::Key_0));
- } else if (p_key >= Qt::Key_A && p_key <= Qt::Key_Z) {
- if (p_modifiers == Qt::ShiftModifier
- || VUtils::isControlModifierForVim(p_modifiers)) {
- return QChar('A' + (p_key - Qt::Key_A));
- } else {
- return QChar('a' + (p_key - Qt::Key_A));
- }
- }
- QChar ch;
- switch (p_key) {
- ADDKEY(Qt::Key_Tab, '\t');
- ADDKEY(Qt::Key_Space, ' ');
- ADDKEY(Qt::Key_Exclam, '!');
- ADDKEY(Qt::Key_QuoteDbl, '"');
- ADDKEY(Qt::Key_NumberSign, '#');
- ADDKEY(Qt::Key_Dollar, '$');
- ADDKEY(Qt::Key_Percent, '%');
- ADDKEY(Qt::Key_Ampersand, '&');
- ADDKEY(Qt::Key_Apostrophe, '\'');
- ADDKEY(Qt::Key_ParenLeft, '(');
- ADDKEY(Qt::Key_ParenRight, ')');
- ADDKEY(Qt::Key_Asterisk, '*');
- ADDKEY(Qt::Key_Plus, '+');
- ADDKEY(Qt::Key_Comma, ',');
- ADDKEY(Qt::Key_Minus, '-');
- ADDKEY(Qt::Key_Period, '.');
- ADDKEY(Qt::Key_Slash, '/');
- ADDKEY(Qt::Key_Colon, ':');
- ADDKEY(Qt::Key_Semicolon, ';');
- ADDKEY(Qt::Key_Less, '<');
- ADDKEY(Qt::Key_Equal, '=');
- ADDKEY(Qt::Key_Greater, '>');
- ADDKEY(Qt::Key_Question, '?');
- ADDKEY(Qt::Key_At, '@');
- ADDKEY(Qt::Key_BracketLeft, '[');
- ADDKEY(Qt::Key_Backslash, '\\');
- ADDKEY(Qt::Key_BracketRight, ']');
- ADDKEY(Qt::Key_AsciiCircum, '^');
- ADDKEY(Qt::Key_Underscore, '_');
- ADDKEY(Qt::Key_QuoteLeft, '`');
- ADDKEY(Qt::Key_BraceLeft, '{');
- ADDKEY(Qt::Key_Bar, '|');
- ADDKEY(Qt::Key_BraceRight, '}');
- ADDKEY(Qt::Key_AsciiTilde, '~');
- default:
- break;
- }
- return ch;
- }
- static QString keyToString(int p_key, int p_modifiers)
- {
- QChar ch = keyToChar(p_key, p_modifiers);
- if (ch.isNull()) {
- return QString();
- }
- if (VUtils::isControlModifierForVim(p_modifiers)) {
- return QString("^") + ch;
- } else {
- return ch;
- }
- }
- VVim::VVim(VEditor *p_editor)
- : QObject(p_editor->getEditor()),
- m_editor(p_editor),
- m_editConfig(&p_editor->getConfig()),
- m_mode(VimMode::Invalid),
- m_resetPositionInBlock(true),
- m_regName(c_unnamedRegister),
- m_leaderKey(Key(Qt::Key_Space)),
- m_replayLeaderSequence(false),
- m_registerPending(false),
- m_insertModeAfterCommand(false),
- m_positionBeforeVisualMode(0)
- {
- Q_ASSERT(m_editConfig->m_enableVimMode);
- setMode(VimMode::Normal);
- initRegisters();
- connect(m_editor->object(), &VEditorObject::mousePressed,
- this, &VVim::handleMousePressed);
- connect(m_editor->object(), &VEditorObject::mouseMoved,
- this, &VVim::handleMouseMoved);
- connect(m_editor->object(), &VEditorObject::mouseReleased,
- this, &VVim::handleMouseReleased);
- }
- // Set @p_cursor's position specified by @p_positionInBlock.
- // If @p_positionInBlock is bigger than the block's length, move to the end of block.
- // Need to setTextCursor() after calling this.
- static void setCursorPositionInBlock(QTextCursor &p_cursor, int p_positionInBlock,
- QTextCursor::MoveMode p_mode)
- {
- QTextBlock block = p_cursor.block();
- if (block.length() > p_positionInBlock) {
- p_cursor.setPosition(block.position() + p_positionInBlock, p_mode);
- } else {
- p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
- }
- }
- // Find the start and end of the spaces @p_cursor locates in (within a single block).
- // @p_start and @p_end will be the global position of the start and end of the spaces.
- // @p_start will equals to @p_end if @p_cursor is not a space.
- static void findCurrentSpace(const QTextCursor &p_cursor, int &p_start, int &p_end)
- {
- QTextBlock block = p_cursor.block();
- QString text = block.text();
- int pib = p_cursor.positionInBlock();
- if (pib < text.size() && !text[pib].isSpace()) {
- p_start = p_end = p_cursor.position();
- return;
- }
- p_start = 0;
- for (int i = pib - 1; i >= 0; --i) {
- if (!text[i].isSpace()) {
- p_start = i + 1;
- break;
- }
- }
- p_end = block.length() - 1;
- for (int i = pib; i < text.size(); ++i) {
- if (!text[i].isSpace()) {
- p_end = i;
- break;
- }
- }
- p_start += block.position();
- p_end += block.position();
- }
- // Move @p_cursor to skip spaces if current cursor is placed at a space
- // (may move across blocks). It will stop by the empty block on the way.
- // Forward: wwwwsssss|wwww
- // Backward: wwww|ssssswwww
- static void moveCursorAcrossSpaces(QTextCursor &p_cursor,
- QTextCursor::MoveMode p_mode,
- bool p_forward,
- bool p_stopAtBoundary = false)
- {
- while (true) {
- QTextBlock block = p_cursor.block();
- QString text = block.text();
- int pib = p_cursor.positionInBlock();
- if (p_forward) {
- for (; pib < text.size(); ++pib) {
- if (!text[pib].isSpace()) {
- break;
- }
- }
- if (pib == text.size() && !p_stopAtBoundary) {
- // Move to next block.
- p_cursor.movePosition(QTextCursor::Down, p_mode, 1);
- if (block.blockNumber() == p_cursor.block().blockNumber()) {
- // Already at the last block.
- p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
- break;
- } else {
- p_cursor.movePosition(QTextCursor::StartOfBlock, p_mode, 1);
- if (p_cursor.block().length() <= 1) {
- break;
- }
- }
- } else {
- // Found non-space character.
- p_cursor.setPosition(block.position() + pib, p_mode);
- break;
- }
- } else {
- int idx = pib - 1;
- for (; idx >= 0; --idx) {
- if (!text[idx].isSpace()) {
- break;
- }
- }
- if (idx == -1 && !p_stopAtBoundary) {
- // Move to previous block.
- p_cursor.movePosition(QTextCursor::Up, p_mode, 1);
- if (block.blockNumber() == p_cursor.block().blockNumber()) {
- // Already at the first block.
- p_cursor.movePosition(QTextCursor::StartOfBlock, p_mode, 1);
- break;
- } else {
- p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
- if (p_cursor.block().length() <= 1) {
- break;
- }
- }
- } else {
- // Found non-space character.
- p_cursor.setPosition(block.position() + idx + 1, p_mode);
- break;
- }
- }
- }
- }
- // Expand the selection of @p_cursor to contain additional spaces at the two ends
- // within a block.
- static void expandSelectionAcrossSpacesWithinBlock(QTextCursor &p_cursor)
- {
- QTextBlock block = p_cursor.block();
- QString text = block.text();
- int start = p_cursor.selectionStart() - block.position();
- int end = p_cursor.selectionEnd() - block.position();
- for (int i = start - 1; i >= 0; --i) {
- if (!text[i].isSpace()) {
- start = i + 1;
- break;
- }
- }
- for (int i = end; i < text.size(); ++i) {
- if (!text[i].isSpace()) {
- end = i;
- break;
- }
- }
- start += block.position();
- end += block.position();
- if (start == p_cursor.selectionStart() && end == p_cursor.selectionEnd()) {
- return;
- }
- if (p_cursor.anchor() <= p_cursor.position()) {
- p_cursor.setPosition(start, QTextCursor::MoveAnchor);
- p_cursor.setPosition(end, QTextCursor::KeepAnchor);
- } else {
- p_cursor.setPosition(end, QTextCursor::MoveAnchor);
- p_cursor.setPosition(start, QTextCursor::KeepAnchor);
- }
- }
- // In Change action, after deleting selected block text, we need to insert a new
- // block for user input.
- // @p_deletionStart is the global position of the start of the deletion.
- // Should be called immediately after the deletion.
- static void insertChangeBlockAfterDeletion(QTextCursor &p_cursor, int p_deletionStart)
- {
- if (p_cursor.position() < p_deletionStart) {
- // Insert a new block below.
- p_cursor.movePosition(QTextCursor::EndOfBlock);
- p_cursor.insertBlock();
- } else {
- // Insert a new block above.
- p_cursor.movePosition(QTextCursor::StartOfBlock);
- p_cursor.insertBlock();
- p_cursor.movePosition(QTextCursor::PreviousBlock);
- }
- if (g_config->getAutoIndent()) {
- VEditUtils::indentBlockAsBlock(p_cursor, false);
- }
- }
- // Given the percentage of the text, return the corresponding block number.
- // Notice that the block number is based on 0.
- // Returns -1 if it is not valid.
- static int percentageToBlockNumber(const QTextDocument *p_doc, int p_percent)
- {
- if (p_percent > 100 || p_percent <= 0) {
- return -1;
- }
- int nrBlock = p_doc->blockCount();
- int num = nrBlock * (p_percent * 1.0 / 100) - 1;
- return num >= 0 ? num : 0;
- }
- // Replace each of the character of selected text with @p_char.
- // Returns true if replacement has taken place.
- // Need to setTextCursor() after calling this.
- static bool replaceSelectedTextWithCharacter(QTextCursor &p_cursor, QChar p_char)
- {
- if (!p_cursor.hasSelection()) {
- return false;
- }
- int start = p_cursor.selectionStart();
- int end = p_cursor.selectionEnd();
- p_cursor.setPosition(start, QTextCursor::MoveAnchor);
- while (p_cursor.position() < end) {
- if (p_cursor.atBlockEnd()) {
- p_cursor.movePosition(QTextCursor::NextCharacter);
- } else {
- p_cursor.deleteChar();
- // insertText() will move the cursor right after the inserted text.
- p_cursor.insertText(p_char);
- }
- }
- return true;
- }
- // Reverse the case of selected text.
- // Returns true if the reverse has taken place.
- // Need to setTextCursor() after calling this.
- static bool reverseSelectedTextCase(QTextCursor &p_cursor)
- {
- if (!p_cursor.hasSelection()) {
- return false;
- }
- QTextDocument *doc = p_cursor.document();
- int start = p_cursor.selectionStart();
- int end = p_cursor.selectionEnd();
- p_cursor.setPosition(start, QTextCursor::MoveAnchor);
- while (p_cursor.position() < end) {
- if (p_cursor.atBlockEnd()) {
- p_cursor.movePosition(QTextCursor::NextCharacter);
- } else {
- QChar ch = doc->characterAt(p_cursor.position());
- bool changed = false;
- if (ch.isLower()) {
- ch = ch.toUpper();
- changed = true;
- } else if (ch.isUpper()) {
- ch = ch.toLower();
- changed = true;
- }
- if (changed) {
- p_cursor.deleteChar();
- // insertText() will move the cursor right after the inserted text.
- p_cursor.insertText(ch);
- } else {
- p_cursor.movePosition(QTextCursor::NextCharacter);
- }
- }
- }
- return true;
- }
- // Join current cursor line and the next line.
- static void joinTwoLines(QTextCursor &p_cursor, bool p_modifySpaces)
- {
- QTextDocument *doc = p_cursor.document();
- QTextBlock firstBlock = p_cursor.block();
- QString textToAppend = firstBlock.next().text();
- p_cursor.movePosition(QTextCursor::EndOfBlock);
- if (p_modifySpaces) {
- bool insertSpaces = false;
- if (firstBlock.length() > 1) {
- QChar lastChar = doc->characterAt(p_cursor.position() - 1);
- if (!lastChar.isSpace()) {
- insertSpaces = true;
- }
- }
- if (insertSpaces) {
- p_cursor.insertText(" ");
- }
- // Remove indentation.
- int idx = 0;
- for (idx = 0; idx < textToAppend.size(); ++idx) {
- if (!textToAppend[idx].isSpace()) {
- break;
- }
- }
- textToAppend = textToAppend.right(textToAppend.size() - idx);
- }
- // Now p_cursor is at the end of the first block.
- int position = p_cursor.block().position() + p_cursor.positionInBlock();
- p_cursor.insertText(textToAppend);
- // Delete the second block.
- p_cursor.movePosition(QTextCursor::NextBlock);
- VEditUtils::removeBlock(p_cursor);
- // Position p_cursor right at the front of appended text.
- p_cursor.setPosition(position);
- }
- // Join lines specified by [@p_firstBlock, @p_firstBlock + p_blockCount).
- // Need to check the block range (based on 0).
- static bool joinLines(QTextCursor &p_cursor,
- int p_firstBlock,
- int p_blockCount,
- bool p_modifySpaces)
- {
- QTextDocument *doc = p_cursor.document();
- int totalBlockCount = doc->blockCount();
- if (p_blockCount <= 0
- || p_firstBlock >= totalBlockCount - 1) {
- return false;
- }
- p_blockCount = qMin(p_blockCount, totalBlockCount - p_firstBlock);
- p_cursor.setPosition(doc->findBlockByNumber(p_firstBlock).position());
- for (int i = 1; i < p_blockCount; ++i) {
- joinTwoLines(p_cursor, p_modifySpaces);
- }
- return true;
- }
- bool VVim::handleKeyPressEvent(QKeyEvent *p_event, int *p_autoIndentPos)
- {
- bool ret = handleKeyPressEvent(p_event->key(), p_event->modifiers(), p_autoIndentPos);
- if (ret) {
- p_event->accept();
- }
- return ret;
- }
- bool VVim::handleKeyPressEvent(int key, int modifiers, int *p_autoIndentPos)
- {
- bool ret = false;
- bool resetPositionInBlock = true;
- Key keyInfo(key, modifiers);
- bool unindent = false;
- int autoIndentPos = p_autoIndentPos ? *p_autoIndentPos : -1;
- // Handle Insert mode key press.
- if (VimMode::Insert == m_mode) {
- if (key == Qt::Key_Escape
- || (key == Qt::Key_BracketLeft && VUtils::isControlModifierForVim(modifiers))) {
- // See if we need to cancel auto indent.
- bool cancelAutoIndent = false;
- if (p_autoIndentPos && *p_autoIndentPos > -1) {
- QTextCursor cursor = m_editor->textCursorW();
- cancelAutoIndent = VEditUtils::needToCancelAutoIndent(*p_autoIndentPos, cursor);
- if (cancelAutoIndent) {
- autoIndentPos = -1;
- VEditUtils::deleteIndentAndListMark(cursor);
- m_editor->setTextCursorW(cursor);
- }
- }
- // Clear selection and enter Normal mode.
- if (!cancelAutoIndent) {
- clearSelection();
- }
- setMode(VimMode::Normal);
- goto clear_accept;
- }
- if (m_registerPending) {
- // Ctrl and Shift may be sent out first.
- if (key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Meta) {
- goto accept;
- }
- // Expecting a register name.
- QChar reg = keyToRegisterName(keyInfo);
- if (!reg.isNull()) {
- // Insert register content.
- m_editor->insertPlainTextW(getRegister(reg).read());
- }
- goto clear_accept;
- } else if (key == Qt::Key_R && VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+R, insert the content of a register.
- m_pendingKeys.append(keyInfo);
- m_registerPending = true;
- goto accept;
- }
- if (key == Qt::Key_O && VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+O, enter normal mode, execute one command, then return to insert mode.
- m_insertModeAfterCommand = true;
- clearSelection();
- setMode(VimMode::Normal);
- goto accept;
- }
- // Let it be handled outside VVim.
- goto exit;
- }
- // Ctrl and Shift may be sent out first.
- if (key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Meta) {
- goto accept;
- }
- if (m_replayLeaderSequence) {
- qDebug() << "replaying sequence" << keyToChar(key, modifiers);
- }
- m_pendingKeys.append(keyInfo);
- if (expectingLeaderSequence()) {
- if (processLeaderSequence(keyInfo)) {
- goto accept;
- } else {
- goto clear_accept;
- }
- }
- if (expectingRegisterName()) {
- // Expecting a register name.
- QChar reg = keyToRegisterName(keyInfo);
- if (!reg.isNull()) {
- m_keys.clear();
- setCurrentRegisterName(reg);
- Register &r = getRegister(reg);
- if (r.isNamedRegister()) {
- r.m_append = (modifiers == Qt::ShiftModifier);
- } else {
- Q_ASSERT(!r.m_append);
- }
- goto accept;
- }
- goto clear_accept;
- }
- if (expectingMarkName()) {
- // Expecting a mark name to create a mark.
- if (keyInfo.isAlphabet() && modifiers == Qt::NoModifier) {
- m_keys.clear();
- m_marks.setMark(keyToChar(key, modifiers), m_editor->textCursorW());
- }
- goto clear_accept;
- }
- if (expectingMarkTarget()) {
- // Expecting a mark name as the target.
- Movement mm = Movement::Invalid;
- const Key &aKey = m_keys.first();
- if (aKey == Key(Qt::Key_Apostrophe)) {
- mm = Movement::MarkJumpLine;
- } else {
- Q_ASSERT(aKey == Key(Qt::Key_QuoteLeft));
- mm = Movement::MarkJump;
- }
- tryAddMoveAction();
- addMovementToken(mm, keyInfo);
- processCommand(m_tokens);
- goto clear_accept;
- }
- if (expectingCharacterTarget()) {
- // Expecting a target character for f/F/t/T.
- Movement mm = Movement::Invalid;
- const Key &aKey = m_keys.first();
- if (aKey.m_key == Qt::Key_F) {
- if (aKey.m_modifiers == Qt::NoModifier) {
- mm = Movement::FindForward;
- } else {
- mm = Movement::FindBackward;
- }
- } else {
- if (aKey.m_modifiers == Qt::NoModifier) {
- mm = Movement::TillForward;
- } else {
- mm = Movement::TillBackward;
- }
- }
- tryAddMoveAction();
- addMovementToken(mm, keyInfo);
- m_lastFindToken = m_tokens.last();
- processCommand(m_tokens);
- goto clear_accept;
- }
- if (expectingReplaceCharacter()) {
- // Expecting a character to replace with for r.
- addActionToken(Action::Replace);
- addKeyToken(keyInfo);
- processCommand(m_tokens);
- goto clear_accept;
- }
- // Check leader key here. If leader key conflicts with other keys, it will
- // overwrite it.
- // Leader sequence is just like an action.
- if (keyInfo == m_leaderKey
- && !hasActionToken()
- && !hasNonDigitPendingKeys()
- && !m_replayLeaderSequence) {
- tryGetRepeatToken(m_keys, m_tokens);
- Q_ASSERT(m_keys.isEmpty());
- m_pendingKeys.pop_back();
- m_pendingKeys.append(Key(Qt::Key_Backslash));
- m_keys.append(Key(Qt::Key_Backslash));
- goto accept;
- }
- // We will add key to m_keys. If all m_keys can combined to a token, add
- // a new token to m_tokens, clear m_keys and try to process m_tokens.
- switch (key) {
- case Qt::Key_0:
- {
- if (modifiers == Qt::NoModifier
- || modifiers == Qt::KeypadModifier) {
- if (checkPendingKey(Key(Qt::Key_G))) {
- // StartOfVisualLine.
- tryAddMoveAction();
- m_tokens.append(Token(Movement::StartOfVisualLine));
- processCommand(m_tokens);
- } else if (m_keys.isEmpty()) {
- // StartOfLine.
- tryAddMoveAction();
- m_tokens.append(Token(Movement::StartOfLine));
- processCommand(m_tokens);
- } else if (m_keys.last().isDigit()) {
- // Repeat.
- m_keys.append(keyInfo);
- resetPositionInBlock = false;
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_1:
- case Qt::Key_2:
- case Qt::Key_3:
- case Qt::Key_4:
- case Qt::Key_5:
- case Qt::Key_6:
- case Qt::Key_7:
- case Qt::Key_8:
- case Qt::Key_9:
- {
- if (modifiers == Qt::NoModifier
- || modifiers == Qt::KeypadModifier) {
- if (!m_keys.isEmpty() && numberFromKeySequence(m_keys) == -1) {
- // Invalid sequence.
- break;
- }
- m_keys.append(keyInfo);
- resetPositionInBlock = false;
- goto accept;
- }
- break;
- }
- case Qt::Key_Left:
- case Qt::Key_Down:
- case Qt::Key_Up:
- case Qt::Key_Right:
- case Qt::Key_H:
- case Qt::Key_J:
- case Qt::Key_K:
- case Qt::Key_L:
- {
- if (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier) {
- // Check if we could generate a Repeat token.
- tryGetRepeatToken(m_keys, m_tokens);
- // Generate a Movement token.
- Movement mm = Movement::Invalid;
- if (!m_keys.isEmpty()) {
- // gj, gk.
- Key gKey(Qt::Key_G);
- if (m_keys.size() == 1 && m_keys.at(0) == gKey) {
- if (key == Qt::Key_J) {
- mm = Movement::VisualDown;
- } else if (key == Qt::Key_K) {
- mm = Movement::VisualUp;
- } else {
- break;
- }
- } else {
- // Not a valid sequence.
- break;
- }
- } else {
- // h, j, k, l.
- switch (key) {
- case Qt::Key_H:
- case Qt::Key_Left:
- mm = Movement::Left;
- break;
- case Qt::Key_L:
- case Qt::Key_Right:
- mm = Movement::Right;
- break;
- case Qt::Key_J:
- case Qt::Key_Down:
- mm = Movement::Down;
- break;
- case Qt::Key_K:
- case Qt::Key_Up:
- mm = Movement::Up;
- break;
- default:
- V_ASSERT(false);
- }
- }
- V_ASSERT(mm != Movement::Invalid);
- tryAddMoveAction();
- addMovementToken(mm);
- processCommand(m_tokens);
- resetPositionInBlock = false;
- } else if (modifiers == Qt::ShiftModifier) {
- if (key == Qt::Key_J) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- break;
- }
- if (checkPendingKey(Key(Qt::Key_G))) {
- // gJ, JoinNoModification.
- addActionToken(Action::JoinNoModification);
- } else if (m_keys.isEmpty()) {
- // J, Join.
- addActionToken(Action::Join);
- }
- processCommand(m_tokens);
- }
- }
- break;
- }
- case Qt::Key_I:
- {
- if (modifiers == Qt::NoModifier) {
- if (hasActionTokenValidForTextObject()) {
- // Inner text object.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Invalid sequence;
- break;
- }
- m_keys.append(keyInfo);
- goto accept;
- }
- // Enter Insert mode.
- // Different from Vim:
- // We enter Insert mode even in Visual and VisualLine mode. We
- // also keep the selection after the mode change.
- if (checkMode(VimMode::Normal)
- || checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine)) {
- setMode(VimMode::Insert, false);
- }
- } else if (modifiers == Qt::ShiftModifier) {
- QTextCursor cursor = m_editor->textCursorW();
- if (m_mode == VimMode::Normal) {
- // Insert at the first non-space character.
- VEditUtils::moveCursorFirstNonSpaceCharacter(cursor, QTextCursor::MoveAnchor);
- } else if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
- // Insert at the start of line.
- cursor.movePosition(QTextCursor::StartOfBlock,
- QTextCursor::MoveAnchor,
- 1);
- }
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Insert);
- } else if (VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+I, jump to next location.
- if (!m_tokens.isEmpty()
- || !checkMode(VimMode::Normal)) {
- break;
- }
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- break;
- }
- addActionToken(Action::JumpNextLocation);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- case Qt::Key_A:
- {
- if (modifiers == Qt::NoModifier) {
- if (hasActionTokenValidForTextObject()) {
- // Around text object.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Invalid sequence;
- break;
- }
- m_keys.append(keyInfo);
- goto accept;
- }
- // Enter Insert mode.
- // Move cursor back one character.
- if (m_mode == VimMode::Normal) {
- QTextCursor cursor = m_editor->textCursorW();
- V_ASSERT(!cursor.hasSelection());
- if (!cursor.atBlockEnd()) {
- cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
- m_editor->setTextCursorW(cursor);
- }
- setMode(VimMode::Insert);
- }
- } else if (modifiers == Qt::ShiftModifier) {
- // Insert at the end of line.
- QTextCursor cursor = m_editor->textCursorW();
- if (m_mode == VimMode::Normal) {
- cursor.movePosition(QTextCursor::EndOfBlock,
- QTextCursor::MoveAnchor,
- 1);
- m_editor->setTextCursorW(cursor);
- } else if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
- if (!cursor.atBlockEnd()) {
- cursor.clearSelection();
- cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
- m_editor->setTextCursorW(cursor);
- }
- }
- setMode(VimMode::Insert);
- }
- break;
- }
- case Qt::Key_O:
- {
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- // Insert a new block under/above current block and enter insert mode.
- bool insertAbove = modifiers == Qt::ShiftModifier;
- if (m_mode == VimMode::Normal) {
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- cursor.movePosition(insertAbove ? QTextCursor::StartOfBlock
- : QTextCursor::EndOfBlock,
- QTextCursor::MoveAnchor,
- 1);
- cursor.insertBlock();
- if (insertAbove) {
- cursor.movePosition(QTextCursor::PreviousBlock,
- QTextCursor::MoveAnchor,
- 1);
- }
- bool textInserted = false;
- if (g_config->getAutoIndent()) {
- textInserted = VEditUtils::indentBlockAsBlock(cursor, false);
- if (g_config->getAutoList()) {
- textInserted = VEditUtils::insertListMarkAsPreviousBlock(cursor)
- || textInserted;
- }
- }
- cursor.endEditBlock();
- m_editor->setTextCursorW(cursor);
- if (textInserted) {
- autoIndentPos = cursor.position();
- }
- setMode(VimMode::Insert);
- }
- break;
- } else if (VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+O, jump to previous location.
- if (!m_tokens.isEmpty()
- || !checkMode(VimMode::Normal)) {
- break;
- }
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- break;
- }
- addActionToken(Action::JumpPreviousLocation);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- case Qt::Key_S:
- {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty() || hasActionToken()) {
- break;
- }
- if (modifiers == Qt::NoModifier) {
- addActionToken(Action::Change);
- // Movement will be ignored in Visual mode.
- addMovementToken(Movement::Right);
- processCommand(m_tokens);
- } else if (modifiers == Qt::ShiftModifier) {
- // S, change current line.
- addActionToken(Action::Change);
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- }
- break;
- }
- case Qt::Key_Dollar:
- {
- if (modifiers == Qt::ShiftModifier) {
- // $, move to end of line.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- tryAddMoveAction();
- m_tokens.append(Token(Movement::EndOfLine));
- processCommand(m_tokens);
- }
- }
- break;
- }
- case Qt::Key_G:
- {
- Movement mm = Movement::Invalid;
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- // First g, pend it.
- m_keys.append(keyInfo);
- goto accept;
- } else if (m_keys.size() == 1 && m_keys.at(0) == keyInfo) {
- // gg, go to a certain line or first line.
- if (!m_tokens.isEmpty() && m_tokens.last().isRepeat()) {
- mm = Movement::LineJump;
- } else {
- mm = Movement::StartOfDocument;
- }
- }
- } else if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- // G, go to a certain line or the last line.
- if (!m_tokens.isEmpty() && m_tokens.last().isRepeat()) {
- mm = Movement::LineJump;
- } else {
- mm = Movement::EndOfDocument;
- }
- }
- }
- if (mm != Movement::Invalid) {
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- }
- break;
- }
- // Should be kept together with Qt::Key_PageUp.
- case Qt::Key_B:
- {
- if (VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+B, page up, fall through.
- modifiers = Qt::NoModifier;
- } else if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- if (modifiers == Qt::NoModifier && checkPendingKey(Key(Qt::Key_Z))) {
- // zb, redraw to make a certain line the bottom of window.
- addActionToken(Action::RedrawAtBottom);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- // b, go to the start of previous or current word.
- Movement mm = Movement::WordBackward;
- if (modifiers == Qt::ShiftModifier) {
- // B, go to the start of previous or current WORD.
- mm = Movement::WORDBackward;
- }
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- break;
- } else {
- break;
- }
- V_FALLTHROUGH;
- }
- case Qt::Key_PageUp:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- Movement mm = Movement::PageUp;
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- resetPositionInBlock = false;
- }
- break;
- }
- case Qt::Key_U:
- {
- tryGetRepeatToken(m_keys, m_tokens);
- bool toLower = modifiers == Qt::NoModifier;
- if (VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+U, HalfPageUp.
- if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- Movement mm = Movement::HalfPageUp;
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- resetPositionInBlock = false;
- } else if (m_keys.isEmpty() && !hasActionToken()) {
- if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
- // u/U for tolower and toupper selected text.
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- // Different from Vim:
- // If there is no selection in Visual mode, we do nothing.
- if (m_mode == VimMode::VisualLine) {
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- convertCaseOfSelectedText(cursor, toLower);
- cursor.endEditBlock();
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Normal);
- break;
- }
- // u, Undo.
- if (modifiers == Qt::NoModifier) {
- addActionToken(Action::Undo);
- processCommand(m_tokens);
- }
- break;
- } else {
- if (hasActionToken()) {
- // guu/gUU.
- if ((toLower && checkActionToken(Action::ToLower))
- || (!toLower && checkActionToken(Action::ToUpper))) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- break;
- } else {
- // An invalid sequence.
- break;
- }
- } else if (checkPendingKey(Key(Qt::Key_G))) {
- // gu/gU, ToLower/ToUpper action.
- if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- // Different from Vim:
- // If there is no selection in Visual mode, we do nothing.
- if (m_mode == VimMode::VisualLine) {
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- convertCaseOfSelectedText(cursor, toLower);
- cursor.endEditBlock();
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Normal);
- break;
- }
- addActionToken(toLower ? Action::ToLower : Action::ToUpper);
- m_keys.clear();
- goto accept;
- } else {
- // An invalid sequence.
- break;
- }
- }
- break;
- }
- // Ctrl+F is used for Find dialog, not used here.
- case Qt::Key_PageDown:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- Movement mm = Movement::PageDown;
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- resetPositionInBlock = false;
- }
- break;
- }
- case Qt::Key_D:
- {
- if (VUtils::isControlModifierForVim(modifiers)) {
- // Ctrl+D, HalfPageDown.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- Movement mm = Movement::HalfPageDown;
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- resetPositionInBlock = false;
- } else if (modifiers == Qt::NoModifier) {
- // d, delete action.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- // This is another d, something like dd.
- if (checkActionToken(Action::Delete)) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- break;
- } else {
- // An invalid sequence.
- break;
- }
- } else {
- // The first d, an Action.
- addActionToken(Action::Delete);
- if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
- // Movement will be ignored.
- addMovementToken(Movement::Left);
- processCommand(m_tokens);
- setMode(VimMode::Normal);
- break;
- }
- goto accept;
- }
- } else if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!hasActionToken()) {
- if (checkMode(VimMode::Normal)) {
- // D, same as d$.
- addActionToken(Action::Delete);
- addMovementToken(Movement::EndOfLine);
- processCommand(m_tokens);
- } else if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
- // D, same as dd.
- addActionToken(Action::Delete);
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- setMode(VimMode::Normal);
- }
- }
- break;
- }
- break;
- }
- case Qt::Key_BracketRight:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // BracketInner/BracketAround.
- Range range = Range::BracketInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::BracketAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (hasActionToken() || !checkMode(VimMode::Normal)) {
- // Invalid sequence.
- break;
- } else if (m_keys.isEmpty()) {
- // First ], pend it.
- m_keys.append(keyInfo);
- goto accept;
- } else if (checkPendingKey(keyInfo)) {
- // ]], goto next title, regardless of level.
- processTitleJump(m_tokens, true, 1);
- } else if (checkPendingKey(Key(Qt::Key_BracketLeft))) {
- // [], goto previous title at the same level.
- processTitleJump(m_tokens, false, 0);
- }
- break;
- }
- break;
- }
- // Should be kept together with Qt::Key_Escape.
- case Qt::Key_BracketLeft:
- {
- if (VUtils::isControlModifierForVim(modifiers)) {
- // fallthrough.
- } else if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // BracketInner/BracketAround.
- Range range = Range::BracketInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::BracketAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (hasActionToken() || !checkMode(VimMode::Normal)) {
- // Invalid sequence.
- break;
- } else if (m_keys.isEmpty()) {
- // First [, pend it.
- m_keys.append(keyInfo);
- goto accept;
- } else if (checkPendingKey(keyInfo)) {
- // [[, goto previous title, regardless of level.
- processTitleJump(m_tokens, false, 1);
- } else if (checkPendingKey(Key(Qt::Key_BracketRight))) {
- // ][, goto next title at the same level.
- processTitleJump(m_tokens, true, 0);
- }
- break;
- } else {
- break;
- }
- V_FALLTHROUGH;
- }
- case Qt::Key_Escape:
- {
- // Clear selection and enter normal mode.
- int position = -1;
- if (checkMode(VimMode::Visual)) {
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.position() > cursor.anchor()) {
- position = cursor.position() - 1;
- }
- }
- bool ret = clearSelection();
- if (!ret && checkMode(VimMode::Normal)) {
- emit m_editor->object()->requestCloseFindReplaceDialog();
- }
- setMode(VimMode::Normal, true, position);
- break;
- }
- case Qt::Key_V:
- {
- if (modifiers == Qt::NoModifier) {
- if (checkMode(VimMode::Visual)) {
- setMode(VimMode::Normal, true);
- } else {
- // Toggle Visual Mode.
- setMode(VimMode::Visual);
- maintainSelectionInVisualMode();
- }
- } else if (modifiers == Qt::ShiftModifier) {
- // Visual Line Mode.
- clearSelection();
- VimMode mode = VimMode::VisualLine;
- if (m_mode == VimMode::VisualLine) {
- mode = VimMode::Normal;
- }
- setMode(mode);
- if (m_mode == VimMode::VisualLine) {
- QTextCursor cursor = m_editor->textCursorW();
- expandSelectionToWholeLines(cursor);
- m_editor->setTextCursorW(cursor);
- }
- } else if (VUtils::isControlModifierForVim(modifiers)) {
- if (g_config->getVimExemptionKeys().contains('v')) {
- // Let it be handled outside.
- resetState();
- goto exit;
- }
- }
- break;
- }
- case Qt::Key_AsciiCircum:
- {
- if (modifiers == Qt::ShiftModifier) {
- // ~, go to first non-space character of current line (block).
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- Movement mm = Movement::FirstCharacter;
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- }
- break;
- }
- case Qt::Key_W:
- {
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- bool shift = modifiers == Qt::ShiftModifier;
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // WordInner/WORDInner/WordAournd/WORDAround.
- bool around = checkPendingKey(Key(Qt::Key_A));
- Range range = Range::Invalid;
- if (shift) {
- if (around) {
- range = Range::WORDAround;
- } else {
- range = Range::WORDInner;
- }
- } else {
- if (around) {
- range = Range::WordAround;
- } else {
- range = Range::WordInner;
- }
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (!m_keys.isEmpty()) {
- // Not a valid sequence.
- break;
- }
- // w, go to the start of next word.
- Movement mm = Movement::WordForward;
- if (shift) {
- // W, go to the start of next WORD.
- mm = Movement::WORDForward;
- }
- if (checkActionToken(Action::Change)) {
- // In Change action, cw equals to ce.
- if (shift) {
- mm = Movement::ForwardEndOfWORD;
- } else {
- mm = Movement::ForwardEndOfWord;
- }
- } else {
- tryAddMoveAction();
- }
- addMovementToken(mm);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- case Qt::Key_E:
- {
- // e, E, ge, gE.
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- Movement mm = Movement::Invalid;
- if (!m_keys.isEmpty()) {
- if (m_keys.size() == 1 && m_keys.at(0) == Key(Qt::Key_G)) {
- // ge, gE.
- if (modifiers == Qt::NoModifier) {
- mm = Movement::BackwardEndOfWord;
- } else {
- mm = Movement::BackwardEndOfWORD;
- }
- } else {
- // Not a valid sequence.
- break;
- }
- } else {
- // e, E.
- if (modifiers == Qt::NoModifier) {
- mm = Movement::ForwardEndOfWord;
- } else {
- mm = Movement::ForwardEndOfWORD;
- }
- }
- tryAddMoveAction();
- m_tokens.append(Token(mm));
- processCommand(m_tokens);
- }
- break;
- }
- case Qt::Key_QuoteDbl:
- {
- if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // DoubleQuoteInner/DoubleQuoteAround.
- Range range = Range::DoubleQuoteInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::DoubleQuoteAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (!m_keys.isEmpty() || hasActionToken()) {
- // Invalid sequence.
- break;
- }
- // ", specify a register.
- m_keys.append(keyInfo);
- goto accept;
- }
- break;
- }
- case Qt::Key_X:
- {
- if (modifiers == Qt::ShiftModifier || modifiers == Qt::NoModifier) {
- // x, or X to delete one char.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty() || hasActionToken()) {
- break;
- }
- addActionToken(Action::Delete);
- if (modifiers == Qt::ShiftModifier) {
- if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
- // X, same as dd.
- addRangeToken(Range::Line);
- } else {
- // X, delete one char.
- addMovementToken(Movement::Left);
- }
- } else {
- // x.
- // Movement will be ignored in Visual mode.
- addMovementToken(Movement::Right);
- }
- processCommand(m_tokens);
- setMode(VimMode::Normal);
- break;
- }
- break;
- }
- case Qt::Key_Y:
- {
- if (modifiers == Qt::NoModifier) {
- // y, copy action.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- // This is another y, something like yy.
- if (checkActionToken(Action::Copy) && checkMode(VimMode::Normal)) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- } else {
- // An invalid sequence.
- break;
- }
- } else {
- // The first y, an Action.
- if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
- copySelectedText(m_mode == VimMode::VisualLine);
- setMode(VimMode::Normal);
- break;
- }
- addActionToken(Action::Copy);
- goto accept;
- }
- } else if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!hasActionToken()) {
- // Y, same as yy.
- addActionToken(Action::Copy);
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- setMode(VimMode::Normal);
- }
- break;
- }
- break;
- }
- case Qt::Key_P:
- {
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- // p/P, paste/pastebefore action.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken() || !m_keys.isEmpty()) {
- // An invalid sequence.
- break;
- }
- addActionToken(modifiers == Qt::NoModifier ? Action::Paste
- : Action::PasteBefore);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- case Qt::Key_C:
- {
- if (modifiers == Qt::NoModifier) {
- // c, change action.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- // This is another c, something like cc.
- if (checkActionToken(Action::Change)) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- break;
- } else {
- // An invalid sequence.
- break;
- }
- } else {
- // The first c, an action.
- addActionToken(Action::Change);
- if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
- // Movement will be ignored.
- addMovementToken(Movement::Left);
- processCommand(m_tokens);
- break;
- }
- goto accept;
- }
- } else if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (!hasActionToken() && m_mode == VimMode::Normal) {
- // C, same as c$.
- addActionToken(Action::Change);
- addMovementToken(Movement::EndOfLine);
- processCommand(m_tokens);
- }
- break;
- } else if (VUtils::isControlModifierForVim(modifiers)) {
- if (g_config->getVimExemptionKeys().contains('c')) {
- // Let it be handled outside.
- resetState();
- goto exit;
- }
- }
- break;
- }
- case Qt::Key_Less:
- unindent = true;
- // Fall through.
- case Qt::Key_Greater:
- {
- if (modifiers == Qt::ShiftModifier) {
- // >/<, Indent/Unindent.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- // This is another >/<, something like >>/<<.
- if ((!unindent && checkActionToken(Action::Indent))
- || (unindent && checkActionToken(Action::UnIndent))) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- break;
- } else if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // AngleBracketInner/AngleBracketAround.
- Range range = Range::AngleBracketInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::AngleBracketAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- }
- } else {
- // The first >/<, an Action.
- addActionToken(unindent ? Action::UnIndent : Action::Indent);
- if (checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine)) {
- // Movement will be ignored.
- addMovementToken(Movement::Left);
- processCommand(m_tokens);
- break;
- }
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_Equal:
- {
- if (modifiers == Qt::NoModifier) {
- // =, AutoIndent.
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken()) {
- // ==.
- if (checkActionToken(Action::AutoIndent)) {
- addRangeToken(Range::Line);
- processCommand(m_tokens);
- break;
- }
- } else {
- // The first =, an Action.
- addActionToken(Action::AutoIndent);
- if (checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine)) {
- // Movement will be ignored.
- addMovementToken(Movement::Left);
- processCommand(m_tokens);
- break;
- }
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_F:
- {
- if (m_mode == VimMode::VisualLine) {
- break;
- }
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- // f/F, find forward/backward within a block.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- m_keys.append(keyInfo);
- goto accept;
- }
- break;
- }
- break;
- }
- case Qt::Key_T:
- {
- if (m_mode == VimMode::VisualLine) {
- break;
- }
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- // t/T, find till forward/backward within a block.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- m_keys.append(keyInfo);
- goto accept;
- } else if (modifiers == Qt::NoModifier && checkPendingKey(Key(Qt::Key_Z))) {
- // zt, redraw to make a certain line the top of window.
- addActionToken(Action::RedrawAtTop);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- break;
- }
- case Qt::Key_Comma:
- {
- if (m_mode == VimMode::VisualLine) {
- break;
- }
- // ,, repeat last find target movement, but reversely.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- repeatLastFindMovement(true);
- break;
- }
- break;
- }
- case Qt::Key_Semicolon:
- {
- if (m_mode == VimMode::VisualLine) {
- break;
- }
- // ;, repeat last find target movement.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty()) {
- repeatLastFindMovement(false);
- break;
- }
- break;
- }
- case Qt::Key_R:
- {
- if (m_mode == VimMode::VisualLine) {
- break;
- }
- if (VUtils::isControlModifierForVim(modifiers)) {
- // Redo.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty() || hasActionToken()) {
- break;
- }
- addActionToken(Action::Redo);
- processCommand(m_tokens);
- break;
- } else if (modifiers == Qt::NoModifier) {
- // r, replace.
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty() && !hasActionToken()) {
- m_keys.append(keyInfo);
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_Z:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty() && !hasActionToken()) {
- // First z, pend it.
- m_keys.append(keyInfo);
- goto accept;
- } else if (checkPendingKey(keyInfo)) {
- // zz, redraw to make a certain line the center of the window.
- addActionToken(Action::RedrawAtCenter);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- break;
- }
- case Qt::Key_Colon:
- {
- if (modifiers == Qt::ShiftModifier) {
- if (m_keys.isEmpty()
- && m_tokens.isEmpty()
- && checkMode(VimMode::Normal)) {
- emit commandLineTriggered(CommandLineType::Command);
- }
- }
- break;
- }
- case Qt::Key_Percent:
- {
- if (modifiers == Qt::ShiftModifier) {
- if (m_keys.isEmpty()) {
- // %, FindPair movement.
- tryAddMoveAction();
- addMovementToken(Movement::FindPair);
- processCommand(m_tokens);
- break;
- } else {
- tryGetRepeatToken(m_keys, m_tokens);
- if (m_keys.isEmpty() && hasRepeatToken()) {
- // xx%, jump to a certain line (percentage of the documents).
- // Change the repeat from percentage to line number.
- Token *token = getRepeatToken();
- int bn = percentageToBlockNumber(m_editor->documentW(), token->m_repeat);
- if (bn == -1) {
- break;
- } else {
- // Repeat of LineJump is based on 1.
- token->m_repeat = bn + 1;
- }
- tryAddMoveAction();
- addMovementToken(Movement::LineJump);
- processCommand(m_tokens);
- break;
- }
- }
- break;
- }
- break;
- }
- case Qt::Key_M:
- {
- if (modifiers == Qt::NoModifier) {
- if (m_keys.isEmpty() && m_tokens.isEmpty()) {
- // m, creating a mark.
- // We can create marks in Visual mode, too.
- m_keys.append(keyInfo);
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_Apostrophe:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // QuoteInner/QuoteAround.
- Range range = Range::QuoteInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::QuoteAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- }
- // ', jump to the start of line of a mark.
- // Repeat is useless in this case.
- if (m_keys.isEmpty()) {
- m_keys.append(keyInfo);
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_QuoteLeft:
- {
- if (modifiers == Qt::NoModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // BackQuoteInner/BackQuoteAround.
- Range range = Range::BackQuoteInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::BackQuoteAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- }
- // `, jump to a mark.
- // Repeat is useless in this case.
- if (m_keys.isEmpty()) {
- m_keys.append(keyInfo);
- goto accept;
- }
- }
- break;
- }
- case Qt::Key_ParenLeft:
- // Fall through.
- case Qt::Key_ParenRight:
- {
- if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // ParenthesisInner/ParenthesisAround.
- Range range = Range::ParenthesisInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::ParenthesisAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- }
- }
- break;
- }
- case Qt::Key_BraceLeft:
- {
- if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // BraceInner/BraceAround.
- Range range = Range::BraceInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::BraceAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (m_keys.isEmpty()) {
- // {, ParagraphUp movement.
- tryAddMoveAction();
- addMovementToken(Movement::ParagraphUp);
- processCommand(m_tokens);
- } else if (!hasActionToken()
- && checkPendingKey(Key(Qt::Key_BracketLeft))) {
- // [{, goto previous title at one higher level.
- if (checkMode(VimMode::Normal)) {
- processTitleJump(m_tokens, false, -1);
- }
- }
- break;
- }
- break;
- }
- case Qt::Key_BraceRight:
- {
- if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (checkPendingKey(Key(Qt::Key_I))
- || checkPendingKey(Key(Qt::Key_A))) {
- // BraceInner/BraceAround.
- Range range = Range::BraceInner;
- if (checkPendingKey(Key(Qt::Key_A))) {
- range = Range::BraceAround;
- }
- addRangeToken(range);
- processCommand(m_tokens);
- break;
- } else if (m_keys.isEmpty()) {
- // }, ParagraphDown movement.
- tryAddMoveAction();
- addMovementToken(Movement::ParagraphDown);
- processCommand(m_tokens);
- } else if (!hasActionToken()
- && checkPendingKey(Key(Qt::Key_BracketRight))) {
- // ]}, goto next title at one higher level.
- if (checkMode(VimMode::Normal)) {
- processTitleJump(m_tokens, true, -1);
- }
- }
- break;
- }
- break;
- }
- case Qt::Key_AsciiTilde:
- {
- if (modifiers == Qt::ShiftModifier) {
- tryGetRepeatToken(m_keys, m_tokens);
- if (hasActionToken() || !m_keys.isEmpty()) {
- break;
- }
- // Reverse the case.
- addActionToken(Action::ReverseCase);
- processCommand(m_tokens);
- break;
- }
- break;
- }
- case Qt::Key_Slash:
- {
- if (modifiers == Qt::NoModifier) {
- if (m_tokens.isEmpty()
- && m_keys.isEmpty()
- && checkMode(VimMode::Normal)) {
- emit commandLineTriggered(CommandLineType::SearchForward);
- }
- }
- break;
- }
- case Qt::Key_Question:
- {
- if (modifiers == Qt::ShiftModifier) {
- if (m_tokens.isEmpty()
- && m_keys.isEmpty()
- && checkMode(VimMode::Normal)) {
- emit commandLineTriggered(CommandLineType::SearchBackward);
- }
- }
- break;
- }
- case Qt::Key_N:
- {
- if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
- // n, FindNext/FindPrevious movement.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- break;
- }
- Movement mm = Movement::FindNext;
- if (modifiers == Qt::ShiftModifier) {
- mm = Movement::FindPrevious;
- }
- tryAddMoveAction();
- addMovementToken(mm);
- processCommand(m_tokens);
- }
- break;
- }
- case Qt::Key_Asterisk:
- {
- if (modifiers == Qt::ShiftModifier) {
- // *, FindNextWordUnderCursor movement.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- break;
- }
- tryAddMoveAction();
- addMovementToken(Movement::FindNextWordUnderCursor);
- processCommand(m_tokens);
- }
- break;
- }
- case Qt::Key_NumberSign:
- {
- if (modifiers == Qt::ShiftModifier) {
- // #, FindPreviousWordUnderCursor movement.
- tryGetRepeatToken(m_keys, m_tokens);
- if (!m_keys.isEmpty()) {
- break;
- }
- tryAddMoveAction();
- addMovementToken(Movement::FindPreviousWordUnderCursor);
- processCommand(m_tokens);
- }
- break;
- }
- default:
- break;
- }
- clear_accept:
- resetState();
- amendCursorPosition();
- if (m_insertModeAfterCommand
- && !checkMode(VimMode::Visual)
- && !checkMode(VimMode::VisualLine)) {
- m_insertModeAfterCommand = false;
- setMode(VimMode::Insert);
- }
- m_editor->makeBlockVisible(m_editor->textCursorW().block());
- accept:
- ret = true;
- // Only alter the autoIndentPos when the key is handled by Vim.
- if (p_autoIndentPos) {
- *p_autoIndentPos = autoIndentPos;
- }
- exit:
- m_resetPositionInBlock = resetPositionInBlock;
- emit vimStatusUpdated(this);
- return ret;
- }
- void VVim::resetState()
- {
- m_keys.clear();
- m_tokens.clear();
- m_pendingKeys.clear();
- setCurrentRegisterName(c_unnamedRegister);
- m_resetPositionInBlock = true;
- m_registerPending = false;
- }
- VimMode VVim::getMode() const
- {
- return m_mode;
- }
- void VVim::setMode(VimMode p_mode, bool p_clearSelection, int p_position)
- {
- if (m_mode != p_mode) {
- QTextCursor cursor = m_editor->textCursorW();
- int position = p_position;
- if (position == -1) {
- if (m_mode == VimMode::Visual
- && p_mode == VimMode::Normal
- && cursor.position() > cursor.anchor()) {
- position = cursor.position() - 1;
- } else if (m_mode == VimMode::Insert
- && p_mode == VimMode::Normal
- && !cursor.atBlockStart()) {
- position = cursor.position() - 1;
- if (position < 0) {
- position = 0;
- }
- }
- }
- if (p_clearSelection) {
- clearSelection();
- }
- if (p_mode == VimMode::Insert) {
- m_editor->setInputMethodEnabled(true);
- } else if (g_config->getEnableSmartImInVimMode()) {
- m_editor->setInputMethodEnabled(false);
- }
- m_mode = p_mode;
- resetState();
- VMdEditor *mdEditor = dynamic_cast<VMdEditor *>(m_editor);
- switch (m_mode) {
- case VimMode::Insert:
- setCursorBlockMode(m_editor, CursorBlock::None);
- if (mdEditor) {
- mdEditor->setHighlightCursorLineBlockEnabled(false);
- }
- break;
- case VimMode::Visual:
- m_positionBeforeVisualMode = cursor.anchor();
- V_FALLTHROUGH;
- default:
- setCursorBlockMode(m_editor, CursorBlock::RightSide);
- if (mdEditor && g_config->getHighlightCursorLine()) {
- QString color;
- if (m_mode == VimMode::Normal) {
- color = g_config->getEditorVimNormalBg();
- } else {
- color = g_config->getEditorVimVisualBg();
- }
- mdEditor->setCursorLineBlockBg(color);
- mdEditor->setHighlightCursorLineBlockEnabled(true);
- }
- break;
- }
- if (position != -1) {
- cursor.setPosition(position);
- m_editor->setTextCursorW(cursor);
- }
- amendCursorPosition();
- emit modeChanged(m_mode);
- emit vimStatusUpdated(this);
- }
- }
- void VVim::processCommand(QList<Token> &p_tokens)
- {
- if (p_tokens.isEmpty()) {
- return;
- }
- V_ASSERT(p_tokens.at(0).isAction());
- Token act = p_tokens.takeFirst();
- switch (act.m_action) {
- case Action::Move:
- processMoveAction(p_tokens);
- break;
- case Action::Delete:
- processDeleteAction(p_tokens);
- break;
- case Action::Copy:
- processCopyAction(p_tokens);
- break;
- case Action::Paste:
- processPasteAction(p_tokens, false);
- break;
- case Action::PasteBefore:
- processPasteAction(p_tokens, true);
- break;
- case Action::Change:
- processChangeAction(p_tokens);
- break;
- case Action::Indent:
- processIndentAction(p_tokens, IndentType::Indent);
- break;
- case Action::UnIndent:
- processIndentAction(p_tokens, IndentType::UnIndent);
- break;
- case Action::AutoIndent:
- processIndentAction(p_tokens, IndentType::AutoIndent);
- break;
- case Action::ToLower:
- processToLowerAction(p_tokens, true);
- break;
- case Action::ToUpper:
- processToLowerAction(p_tokens, false);
- break;
- case Action::Undo:
- processUndoAction(p_tokens);
- break;
- case Action::Redo:
- processRedoAction(p_tokens);
- break;
- case Action::RedrawAtTop:
- processRedrawLineAction(p_tokens, 0);
- break;
- case Action::RedrawAtCenter:
- processRedrawLineAction(p_tokens, 1);
- break;
- case Action::RedrawAtBottom:
- processRedrawLineAction(p_tokens, 2);
- break;
- case Action::JumpPreviousLocation:
- processJumpLocationAction(p_tokens, false);
- break;
- case Action::JumpNextLocation:
- processJumpLocationAction(p_tokens, true);
- break;
- case Action::Replace:
- processReplaceAction(p_tokens);
- break;
- case Action::ReverseCase:
- processReverseCaseAction(p_tokens);
- break;
- case Action::Join:
- processJoinAction(p_tokens, true);
- break;
- case Action::JoinNoModification:
- processJoinAction(p_tokens, false);
- break;
- default:
- p_tokens.clear();
- break;
- }
- Q_ASSERT(p_tokens.isEmpty());
- }
- int VVim::numberFromKeySequence(const QList<Key> &p_keys)
- {
- int num = 0;
- for (auto const & key : p_keys) {
- if (key.isDigit()) {
- num = num * 10 + key.toDigit();
- } else {
- return -1;
- }
- }
- return num == 0 ? -1 : num;
- }
- bool VVim::tryGetRepeatToken(QList<Key> &p_keys, QList<Token> &p_tokens)
- {
- if (!p_keys.isEmpty()) {
- int repeat = numberFromKeySequence(p_keys);
- if (repeat != -1) {
- p_tokens.append(Token(repeat));
- p_keys.clear();
- return true;
- }
- }
- return false;
- }
- void VVim::processMoveAction(QList<Token> &p_tokens)
- {
- // Only moving left/right could change this.
- static int positionInBlock = 0;
- Token to = p_tokens.takeFirst();
- V_ASSERT(to.isRepeat() || to.isMovement());
- Token mvToken;
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- mvToken = p_tokens.takeFirst();
- } else {
- mvToken = to;
- }
- if (!mvToken.isMovement() || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- if (m_resetPositionInBlock) {
- positionInBlock = cursor.positionInBlock();
- }
- QTextCursor::MoveMode moveMode = (m_mode == VimMode::Visual
- || m_mode == VimMode::VisualLine)
- ? QTextCursor::KeepAnchor
- : QTextCursor::MoveAnchor;
- bool hasMoved = processMovement(cursor, moveMode, mvToken, repeat);
- if (hasMoved) {
- // Maintain positionInBlock.
- switch (mvToken.m_movement) {
- case Movement::Left:
- case Movement::Right:
- positionInBlock = cursor.positionInBlock();
- break;
- case Movement::Up:
- case Movement::Down:
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- setCursorPositionInBlock(cursor, positionInBlock, moveMode);
- break;
- default:
- break;
- }
- if (checkMode(VimMode::VisualLine)) {
- expandSelectionToWholeLines(cursor);
- } else if (checkMode(VimMode::Visual)) {
- maintainSelectionInVisualMode(&cursor);
- }
- m_editor->setTextCursorW(cursor);
- }
- }
- bool VVim::processMovement(QTextCursor &p_cursor,
- QTextCursor::MoveMode p_moveMode,
- const Token &p_token,
- int p_repeat)
- {
- V_ASSERT(p_token.isMovement());
- bool hasMoved = false;
- bool inclusive = true;
- bool forward = true;
- QTextDocument *doc = p_cursor.document();
- switch (p_token.m_movement) {
- case Movement::Left:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int pib = p_cursor.positionInBlock();
- p_repeat = qMin(pib, p_repeat);
- if (p_repeat > 0) {
- p_cursor.movePosition(QTextCursor::Left, p_moveMode, p_repeat);
- hasMoved = true;
- }
- break;
- }
- case Movement::Right:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- if (checkMode(VimMode::Visual)) {
- int pos = p_cursor.position();
- if (pos == p_cursor.anchor() - 1 && pos == m_positionBeforeVisualMode) {
- ++p_repeat;
- }
- }
- int pib = p_cursor.positionInBlock();
- int length = p_cursor.block().length();
- if (length - pib <= p_repeat) {
- p_repeat = length - pib - 1;
- }
- if (p_repeat > 0) {
- p_cursor.movePosition(QTextCursor::Right, p_moveMode, p_repeat);
- hasMoved = true;
- }
- break;
- }
- case Movement::Up:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- p_repeat = qMin(p_cursor.block().blockNumber(), p_repeat);
- if (p_repeat > 0) {
- p_cursor.movePosition(QTextCursor::PreviousBlock, p_moveMode, p_repeat);
- hasMoved = true;
- }
- break;
- }
- case Movement::Down:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int blockCount = doc->blockCount();
- p_repeat = qMin(blockCount - 1 - p_cursor.block().blockNumber(), p_repeat);
- if (p_repeat > 0) {
- p_cursor.movePosition(QTextCursor::NextBlock, p_moveMode, p_repeat);
- hasMoved = true;
- }
- break;
- }
- case Movement::VisualUp:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- p_cursor.movePosition(QTextCursor::Up, p_moveMode, p_repeat);
- hasMoved = true;
- break;
- }
- case Movement::VisualDown:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- p_cursor.movePosition(QTextCursor::Down, p_moveMode, p_repeat);
- hasMoved = true;
- break;
- }
- case Movement::PageUp:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int blockStep = blockCountOfPageStep() * p_repeat;
- int block = p_cursor.block().blockNumber();
- block = qMax(0, block - blockStep);
- p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
- hasMoved = true;
- break;
- }
- case Movement::PageDown:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int blockStep = blockCountOfPageStep() * p_repeat;
- int block = p_cursor.block().blockNumber();
- block = qMin(block + blockStep, doc->blockCount() - 1);
- p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
- hasMoved = true;
- break;
- }
- case Movement::HalfPageUp:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int blockStep = blockCountOfPageStep();
- int halfBlockStep = qMax(blockStep / 2, 1);
- blockStep = p_repeat * halfBlockStep;
- int block = p_cursor.block().blockNumber();
- block = qMax(0, block - blockStep);
- p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
- hasMoved = true;
- break;
- }
- case Movement::HalfPageDown:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int blockStep = blockCountOfPageStep();
- int halfBlockStep = qMax(blockStep / 2, 1);
- blockStep = p_repeat * halfBlockStep;
- int block = p_cursor.block().blockNumber();
- block = qMin(block + blockStep, doc->blockCount() - 1);
- p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
- hasMoved = true;
- break;
- }
- case Movement::StartOfLine:
- {
- Q_ASSERT(p_repeat == -1);
- // Start of the Line (block).
- if (!p_cursor.atBlockStart()) {
- p_cursor.movePosition(QTextCursor::StartOfBlock, p_moveMode, 1);
- hasMoved = true;
- }
- break;
- }
- case Movement::StartOfVisualLine:
- {
- // Start of the visual line.
- if (!p_cursor.atBlockStart()) {
- p_cursor.movePosition(QTextCursor::StartOfLine, p_moveMode, 1);
- hasMoved = true;
- }
- break;
- }
- case Movement::EndOfLine:
- {
- // End of line (block).
- if (p_repeat == -1) {
- p_repeat = 1;
- } else if (p_repeat > 1) {
- // Move down (p_repeat-1) blocks.
- p_cursor.movePosition(QTextCursor::NextBlock, p_moveMode, p_repeat - 1);
- }
- // Move to the end of block.
- p_cursor.movePosition(QTextCursor::EndOfBlock, p_moveMode, 1);
- hasMoved = true;
- break;
- }
- case Movement::FirstCharacter:
- {
- // p_repeat is not considered in this command.
- // If all the block is space, just move to the end of block; otherwise,
- // move to the first non-space character.
- VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::LineJump:
- {
- // Jump to the first non-space character of @p_repeat line (block).
- V_ASSERT(p_repeat > 0);
- // Record current location.
- m_locations.addLocation(p_cursor);
- // @p_repeat starts from 1 while block number starts from 0.
- QTextBlock block = doc->findBlockByNumber(p_repeat - 1);
- if (block.isValid()) {
- p_cursor.setPosition(block.position(), p_moveMode);
- } else {
- // Go beyond the document.
- p_cursor.movePosition(QTextCursor::End, p_moveMode, 1);
- }
- VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::StartOfDocument:
- {
- // Jump to the first non-space character of the start of the document.
- V_ASSERT(p_repeat == -1);
- // Record current location.
- m_locations.addLocation(p_cursor);
- p_cursor.movePosition(QTextCursor::Start, p_moveMode, 1);
- VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::EndOfDocument:
- {
- // Jump to the first non-space character of the end of the document.
- V_ASSERT(p_repeat == -1);
- // Record current location.
- m_locations.addLocation(p_cursor);
- p_cursor.movePosition(QTextCursor::End, p_moveMode, 1);
- VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::WordForward:
- {
- // Go to the start of next word.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- while (p_repeat) {
- if (p_cursor.atEnd()) {
- break;
- }
- p_cursor.movePosition(QTextCursor::NextWord, p_moveMode);
- if (p_cursor.atBlockEnd()) {
- // dw/yw/cw will stop at the end of the line.
- if (p_repeat == 1
- && checkMode(VimMode::Normal)
- && p_moveMode == QTextCursor::KeepAnchor) {
- --p_repeat;
- }
- continue;
- } else if (doc->characterAt(p_cursor.position()).isSpace()
- || VEditUtils::isSpaceBlock(p_cursor.block())) {
- continue;
- }
- --p_repeat;
- }
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::WORDForward:
- {
- // Go to the start of next WORD.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- while (p_repeat) {
- if (p_cursor.atEnd()) {
- break;
- }
- int start, end;
- // [start, end] is current WORD.
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- // Move cursor to end of current WORD.
- p_cursor.setPosition(end, p_moveMode);
- if (p_repeat == 1
- && checkMode(VimMode::Normal)
- && p_moveMode == QTextCursor::KeepAnchor) {
- // dW/yW/cW will stop at the end of the line.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, true, true);
- if (p_cursor.atBlockEnd()) {
- --p_repeat;
- continue;
- }
- }
- // Skip spaces.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, true);
- if (p_cursor.atBlockEnd()) {
- continue;
- }
- --p_repeat;
- }
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::ForwardEndOfWord:
- {
- // Go to the end of current word or next word.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int pos = p_cursor.position();
- bool leftSideBefore = useLeftSideOfCursor(p_cursor);
- // First move to the end of current word.
- p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode, 1);
- if (p_cursor.position() > pos) {
- if (p_cursor.position() > pos + 1 || (leftSideBefore && useLeftSideOfCursor(p_cursor))) {
- // We did move.
- p_repeat -= 1;
- }
- }
- while (p_repeat) {
- if (p_cursor.atEnd()) {
- break;
- }
- pos = p_cursor.position();
- p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
- if (p_cursor.position() == pos) {
- // Need to move to the start of next word.
- p_cursor.movePosition(QTextCursor::NextWord, p_moveMode);
- if (p_cursor.atBlockEnd()) {
- continue;
- }
- p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
- if (p_cursor.atBlockStart()) {
- continue;
- }
- }
- --p_repeat;
- }
- // Move one character back.
- if (!p_cursor.atBlockStart()) {
- if (p_moveMode == QTextCursor::MoveAnchor
- || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))) {
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- }
- hasMoved = true;
- break;
- }
- case Movement::ForwardEndOfWORD:
- {
- // Go to the end of current WORD or next WORD.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int pos = p_cursor.position();
- bool leftSideBefore = useLeftSideOfCursor(p_cursor);
- while (p_repeat) {
- if (p_cursor.atEnd()) {
- break;
- }
- // Skip spaces.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, true);
- if (p_cursor.atBlockEnd()) {
- continue;
- }
- int start, end;
- // [start, end] is current WORD.
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- // Move cursor to the end of current WORD.
- p_cursor.setPosition(end, p_moveMode);
- if (p_cursor.position() > pos + 1
- || (leftSideBefore && useLeftSideOfCursor(p_cursor))) {
- --p_repeat;
- }
- }
- // Move one character back.
- if (!p_cursor.atBlockStart()) {
- if (p_moveMode == QTextCursor::MoveAnchor
- || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))) {
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- }
- hasMoved = true;
- break;
- }
- case Movement::WordBackward:
- {
- // Go to the start of previous word or current word.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int pos = p_cursor.position();
- // first move to the start of current word.
- p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
- if (p_cursor.position() == pos && useLeftSideOfCursor(p_cursor)) {
- // Cursor did not move and now is at the start of a word.
- // Actually we are using the left side character so we need to move
- // to previous word.
- p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
- }
- if (p_cursor.position() < pos) {
- if (p_cursor.position() < pos - 1 || !useLeftSideOfCursor(p_cursor)) {
- // We did move.
- p_repeat -= 1;
- }
- }
- while (p_repeat) {
- if (p_cursor.atStart()) {
- break;
- }
- pos = p_cursor.position();
- p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
- if (p_cursor.position() == pos) {
- // Need to move to the start of previous word.
- p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
- if (p_cursor.atBlockEnd()) {
- continue;
- }
- if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
- continue;
- }
- }
- --p_repeat;
- }
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::WORDBackward:
- {
- // Go to the start of previous WORD or current WORD.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- int pos = p_cursor.position();
- while (p_repeat) {
- if (p_cursor.atStart()) {
- break;
- }
- // Skip Spaces.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
- if (p_cursor.atBlockStart()) {
- continue;
- }
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- int start, end;
- // [start, end] is current WORD.
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- // Move cursor to the start of current WORD.
- p_cursor.setPosition(start, p_moveMode);
- if (p_cursor.position() < pos - 1 || !useLeftSideOfCursor(p_cursor)) {
- --p_repeat;
- }
- }
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- }
- case Movement::BackwardEndOfWord:
- {
- // Go to the end of previous word.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- if (useLeftSideOfCursor(p_cursor)) {
- // Move one previous char.
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- int pos = p_cursor.position();
- // Move across spaces backward.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
- int start, end;
- VEditUtils::findCurrentWord(p_cursor, start, end);
- if (pos != p_cursor.position() || start == end || start == pos) {
- // We are alreay at the end of previous word.
- --p_repeat;
- // Move it to the start of current word.
- p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
- } else {
- p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
- }
- while (p_repeat) {
- if (p_cursor.atStart()) {
- break;
- }
- p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
- if (p_cursor.atBlockEnd()) {
- continue;
- }
- if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
- continue;
- }
- --p_repeat;
- }
- // Move it to the end.
- p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
- // Move one character back.
- if (!p_cursor.atBlockStart()) {
- if (p_moveMode == QTextCursor::MoveAnchor
- || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))
- || p_cursor.position() <= p_cursor.anchor()) {
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- }
- hasMoved = true;
- break;
- }
- case Movement::BackwardEndOfWORD:
- {
- // Go to the end of previous WORD.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- if (useLeftSideOfCursor(p_cursor)) {
- // Move one previous char.
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- int pos = p_cursor.position();
- // Move across spaces backward.
- moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
- int start, end;
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- if (pos != p_cursor.position() || start == end) {
- // We are alreay at the end of previous WORD.
- --p_repeat;
- // Move it to the start of current WORD.
- p_cursor.setPosition(start, p_moveMode);
- } else {
- // Move it to the start of current WORD.
- p_cursor.setPosition(start, p_moveMode);
- }
- while (p_repeat) {
- if (p_cursor.atStart()) {
- break;
- }
- moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
- if (p_cursor.atBlockStart()) {
- continue;
- }
- if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
- continue;
- }
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- p_cursor.setPosition(start, p_moveMode);
- --p_repeat;
- }
- // Move it to the end.
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- p_cursor.setPosition(end, p_moveMode);
- // Move one character back.
- if (!p_cursor.atBlockStart()) {
- if (p_moveMode == QTextCursor::MoveAnchor
- || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))
- || p_cursor.position() <= p_cursor.anchor()) {
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- }
- hasMoved = true;
- break;
- }
- case Movement::TillBackward:
- forward = false;
- // Fall through.
- case Movement::TillForward:
- inclusive = false;
- goto handle_target;
- case Movement::FindBackward:
- forward = false;
- // Fall through.
- case Movement::FindForward:
- {
- handle_target:
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- const Key &key = p_token.m_key;
- QChar target = keyToChar(key.m_key, key.m_modifiers);
- if (!target.isNull()) {
- hasMoved = VEditUtils::findTargetWithinBlock(p_cursor,
- p_moveMode,
- target,
- forward,
- inclusive,
- useLeftSideOfCursor(p_cursor),
- p_repeat);
- }
- break;
- }
- case Movement::MarkJump:
- // Fall through.
- case Movement::MarkJumpLine:
- {
- // repeat is useless here.
- const Key &key = p_token.m_key;
- QChar target = keyToChar(key.m_key, key.m_modifiers);
- Location loc = m_marks.getMarkLocation(target);
- if (loc.isValid()) {
- if (loc.m_blockNumber >= doc->blockCount()) {
- // Invalid block number.
- message(tr("Mark not set"));
- m_marks.clearMark(target);
- break;
- }
- // Different from Vim:
- // We just use the block number for mark, so if we delete the line
- // where the mark locates, we could not detect if it is set or not.
- QTextBlock block = doc->findBlockByNumber(loc.m_blockNumber);
- p_cursor.setPosition(block.position(), p_moveMode);
- if (p_token.m_movement == Movement::MarkJump) {
- setCursorPositionInBlock(p_cursor, loc.m_positionInBlock, p_moveMode);
- } else {
- // Jump to the first non-space character.
- VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
- }
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- }
- break;
- }
- case Movement::FindPair:
- {
- Q_ASSERT(p_repeat == -1);
- int anchor = p_cursor.anchor();
- int position = p_cursor.position();
- QList<QPair<QChar, QChar>> pairs;
- pairs.append(QPair<QChar, QChar>('(', ')'));
- pairs.append(QPair<QChar, QChar>('[', ']'));
- pairs.append(QPair<QChar, QChar>('{', '}'));
- // Find forward for a pair (), [], and {}.
- QList<QChar> targets;
- for (auto const & pair : pairs) {
- targets.append(pair.first);
- targets.append(pair.second);
- }
- // First check if current char hits the targets.
- bool useLeftSideBefore = useLeftSideOfCursor(p_cursor);
- QChar ch = doc->characterAt(useLeftSideBefore ? position - 1
- : position);
- int idx = targets.indexOf(ch);
- if (idx == -1) {
- idx = VEditUtils::findTargetsWithinBlock(p_cursor,
- targets,
- true,
- useLeftSideOfCursor(p_cursor),
- true);
- } else if (useLeftSideBefore) {
- // Move one character back to let p_cursor position at the pair.
- p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
- }
- if (idx == -1) {
- break;
- }
- idx /= 2;
- int pairPosition = p_cursor.position();
- bool ret = VEditUtils::selectPairTargetAround(p_cursor,
- pairs.at(idx).first,
- pairs.at(idx).second,
- true,
- true,
- 1);
- if (ret) {
- // Found matched pair.
- int first = p_cursor.position();
- int second = p_cursor.anchor();
- if (first > second) {
- int tmp = first;
- first = second;
- second = tmp;
- }
- if (!(checkMode(VimMode::Normal) && p_moveMode == QTextCursor::KeepAnchor)) {
- --second;
- }
- int target = first;
- if (first == pairPosition) {
- target = second;
- }
- if (anchor > target
- && !p_cursor.atEnd()
- && !useLeftSideOfCursor(p_cursor)) {
- ++anchor;
- }
- p_cursor.setPosition(anchor);
- p_cursor.setPosition(target, p_moveMode);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- // Move one character forward.
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- hasMoved = true;
- break;
- } else {
- // Restore the cursor position.
- p_cursor.setPosition(anchor);
- if (anchor != position) {
- p_cursor.setPosition(position, QTextCursor::KeepAnchor);
- }
- }
- break;
- }
- case Movement::FindPrevious:
- forward = false;
- // Fall through.
- case Movement::FindNext:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- if (m_searchHistory.isEmpty()) {
- break;
- }
- // Record current location.
- m_locations.addLocation(p_cursor);
- bool useLeftSideBefore = useLeftSideOfCursor(p_cursor);
- const SearchItem &item = m_searchHistory.lastItem();
- while (--p_repeat >= 0) {
- bool found = m_editor->findText(item.m_text,
- item.m_options,
- forward ? item.m_forward : !item.m_forward,
- &p_cursor,
- p_moveMode,
- useLeftSideBefore);
- if (found) {
- hasMoved = true;
- useLeftSideBefore = false;
- } else {
- break;
- }
- }
- if (hasMoved) {
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- }
- break;
- }
- case Movement::FindPreviousWordUnderCursor:
- forward = false;
- // Fall through.
- case Movement::FindNextWordUnderCursor:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- // Get current word under cursor.
- // Different from Vim:
- // We do not recognize a word as strict as Vim.
- int start, end;
- VEditUtils::findCurrentWord(p_cursor, start, end);
- if (start == end) {
- // Spaces, find next word.
- QTextCursor cursor = p_cursor;
- while (true) {
- moveCursorAcrossSpaces(cursor, p_moveMode, true);
- if (cursor.atEnd()) {
- break;
- }
- if (!doc->characterAt(cursor.position()).isSpace()) {
- VEditUtils::findCurrentWord(cursor, start, end);
- Q_ASSERT(start != end);
- break;
- }
- }
- if (start == end) {
- break;
- }
- }
- QTextCursor cursor = p_cursor;
- cursor.setPosition(start);
- cursor.setPosition(end, QTextCursor::KeepAnchor);
- QString text = cursor.selectedText();
- if (text.isEmpty()) {
- break;
- }
- // Record current location.
- m_locations.addLocation(p_cursor);
- p_cursor.setPosition(start, p_moveMode);
- // Case-insensitive, non-regularexpression.
- SearchItem item;
- item.m_rawStr = text;
- item.m_text = text;
- item.m_forward = forward;
- m_searchHistory.addItem(item);
- m_searchHistory.resetIndex();
- while (--p_repeat >= 0) {
- hasMoved = m_editor->findText(item.m_text, item.m_options,
- item.m_forward,
- &p_cursor, p_moveMode);
- }
- Q_ASSERT(hasMoved);
- if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
- p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
- }
- break;
- }
- case Movement::ParagraphUp:
- forward = false;
- // Fall through.
- case Movement::ParagraphDown:
- {
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- // Record current location.
- m_locations.addLocation(p_cursor);
- int oriPos = p_cursor.position();
- int position = VEditUtils::findNextEmptyBlock(p_cursor,
- forward,
- p_repeat);
- if (position == -1) {
- // No empty block. Move to the first/last character.
- p_cursor.movePosition(forward ? QTextCursor::End : QTextCursor::Start,
- p_moveMode);
- hasMoved = p_cursor.position() != oriPos;
- } else {
- p_cursor.setPosition(position, p_moveMode);
- hasMoved = true;
- }
- break;
- }
- default:
- break;
- }
- return hasMoved;
- }
- bool VVim::selectRange(QTextCursor &p_cursor, const QTextDocument *p_doc,
- Range p_range, int p_repeat)
- {
- bool hasMoved = false;
- QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
- bool around = false;
- QChar opening;
- QChar closing;
- bool crossBlock = false;
- bool multipleTargets = false;
- Q_UNUSED(p_doc);
- switch (p_range) {
- case Range::Line:
- {
- // Visual mode, just select selected lines.
- if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
- expandSelectionToWholeLines(p_cursor);
- hasMoved = true;
- break;
- }
- // Current line and next (p_repeat - 1) lines.
- if (p_repeat == -1) {
- p_repeat = 1;
- }
- if (p_repeat > 1) {
- p_cursor.movePosition(QTextCursor::NextBlock, moveMode, p_repeat - 1);
- }
- expandSelectionToWholeLines(p_cursor);
- hasMoved = true;
- break;
- }
- case Range::WordAround:
- around = true;
- // Fall through.
- case Range::WordInner:
- {
- Q_ASSERT(p_repeat == -1);
- bool spaces = false;
- int start, end;
- VEditUtils::findCurrentWord(p_cursor, start, end);
- if (start == end) {
- // Select the space between previous word and next word.
- findCurrentSpace(p_cursor, start, end);
- spaces = true;
- }
- if (start != end) {
- p_cursor.setPosition(start, QTextCursor::MoveAnchor);
- p_cursor.setPosition(end, moveMode);
- hasMoved = true;
- if (around) {
- if (spaces) {
- // Select the word by the end of spaces.
- if (!p_cursor.atBlockEnd()) {
- p_cursor.movePosition(QTextCursor::EndOfWord, moveMode);
- }
- } else {
- // Select additional spaces at two ends.
- expandSelectionAcrossSpacesWithinBlock(p_cursor);
- }
- }
- }
- break;
- }
- case Range::WORDAround:
- around = true;
- // Fall through.
- case Range::WORDInner:
- {
- Q_ASSERT(p_repeat == -1);
- bool spaces = false;
- int start, end;
- findCurrentSpace(p_cursor, start, end);
- if (start == end) {
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- } else {
- // Select the space between previous WORD and next WORD.
- spaces = true;
- }
- if (start != end) {
- p_cursor.setPosition(start, QTextCursor::MoveAnchor);
- p_cursor.setPosition(end, moveMode);
- hasMoved = true;
- if (around) {
- if (spaces) {
- // Select the WORD by the end of spaces.
- if (!p_cursor.atBlockEnd()) {
- // Skip spaces (mainly across block).
- moveCursorAcrossSpaces(p_cursor, moveMode, true);
- // [start, end] is current WORD.
- VEditUtils::findCurrentWORD(p_cursor, start, end);
- // Move cursor to the end of current WORD.
- p_cursor.setPosition(end, moveMode);
- }
- } else {
- // Select additional spaces at two ends.
- expandSelectionAcrossSpacesWithinBlock(p_cursor);
- }
- }
- }
- break;
- }
- case Range::ParenthesisAround:
- {
- around = true;
- opening = '(';
- closing = ')';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::ParenthesisInner:
- {
- around = false;
- opening = '(';
- closing = ')';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::BracketAround:
- {
- around = true;
- opening = '[';
- closing = ']';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::BracketInner:
- {
- around = false;
- opening = '[';
- closing = ']';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::AngleBracketAround:
- {
- around = true;
- opening = '<';
- closing = '>';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::AngleBracketInner:
- {
- around = false;
- opening = '<';
- closing = '>';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::BraceAround:
- {
- around = true;
- opening = '{';
- closing = '}';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::BraceInner:
- {
- around = false;
- opening = '{';
- closing = '}';
- crossBlock = true;
- multipleTargets = true;
- goto handlePairTarget;
- }
- case Range::DoubleQuoteAround:
- {
- around = true;
- opening = '"';
- closing = '"';
- crossBlock = false;
- multipleTargets = false;
- goto handlePairTarget;
- }
- case Range::DoubleQuoteInner:
- {
- around = false;
- opening = '"';
- closing = '"';
- crossBlock = false;
- multipleTargets = false;
- goto handlePairTarget;
- }
- case Range::BackQuoteAround:
- {
- around = true;
- opening = '`';
- closing = '`';
- crossBlock = false;
- multipleTargets = false;
- goto handlePairTarget;
- }
- case Range::BackQuoteInner:
- {
- around = false;
- opening = '`';
- closing = '`';
- crossBlock = false;
- multipleTargets = false;
- goto handlePairTarget;
- }
- case Range::QuoteAround:
- {
- around = true;
- opening = '\'';
- closing = '\'';
- crossBlock = false;
- multipleTargets = false;
- goto handlePairTarget;
- }
- case Range::QuoteInner:
- {
- around = false;
- opening = '\'';
- closing = '\'';
- crossBlock = false;
- multipleTargets = false;
- handlePairTarget:
- if (p_repeat == -1) {
- p_repeat = 1;
- } else if (p_repeat > 1 && !multipleTargets) {
- // According to the behavior of Vim.
- p_repeat = 1;
- around = true;
- }
- hasMoved = VEditUtils::selectPairTargetAround(p_cursor,
- opening,
- closing,
- around,
- crossBlock,
- p_repeat);
- break;
- }
- default:
- break;
- }
- return hasMoved;
- }
- void VVim::processDeleteAction(QList<Token> &p_tokens)
- {
- Token to = p_tokens.takeFirst();
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- to = p_tokens.takeFirst();
- }
- if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- QTextDocument *doc = m_editor->documentW();
- bool hasMoved = false;
- QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
- if (to.isRange()) {
- cursor.beginEditBlock();
- hasMoved = selectRange(cursor, doc, to.m_range, repeat);
- if (hasMoved) {
- // Whether the range may cross blocks.
- bool mayCrossBlock = false;
- switch (to.m_range) {
- case Range::Line:
- {
- // dd, delete current line.
- if (cursor.hasSelection()) {
- repeat = VEditUtils::selectedBlockCount(cursor);
- deleteSelectedText(cursor, true);
- } else {
- VEditUtils::removeBlock(cursor);
- saveToRegister("\n");
- repeat = 1;
- }
- message(tr("%1 fewer %2").arg(repeat).arg(repeat > 1 ? tr("lines")
- : tr("line")));
- break;
- }
- case Range::ParenthesisInner:
- // Fall through.
- case Range::ParenthesisAround:
- // Fall through.
- case Range::BracketInner:
- // Fall through.
- case Range::BracketAround:
- // Fall through.
- case Range::AngleBracketInner:
- // Fall through.
- case Range::AngleBracketAround:
- // Fall through.
- case Range::BraceInner:
- // Fall through.
- case Range::BraceAround:
- // Fall through.
- mayCrossBlock = true;
- V_FALLTHROUGH;
- case Range::WordAround:
- // Fall through.
- case Range::WordInner:
- // Fall through.
- case Range::WORDAround:
- // Fall through.
- case Range::WORDInner:
- // Fall through.
- case Range::QuoteInner:
- // Fall through.
- case Range::QuoteAround:
- // Fall through.
- case Range::DoubleQuoteInner:
- // Fall through.
- case Range::DoubleQuoteAround:
- // Fall through.
- case Range::BackQuoteInner:
- // Fall through.
- case Range::BackQuoteAround:
- {
- if (cursor.hasSelection()) {
- bool clearEmptyBlock = false;
- if (mayCrossBlock
- && VEditUtils::selectedBlockCount(cursor) > 1) {
- clearEmptyBlock = true;
- }
- int blockCount = 0;
- if (clearEmptyBlock) {
- blockCount = doc->blockCount();
- }
- deleteSelectedText(cursor, clearEmptyBlock);
- if (clearEmptyBlock) {
- int nrBlock = blockCount - doc->blockCount();
- Q_ASSERT(nrBlock > 0);
- message(tr("%1 fewer %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- }
- break;
- }
- default:
- return;
- }
- }
- cursor.endEditBlock();
- goto exit;
- }
- V_ASSERT(to.isMovement());
- // Filter out not supported movement for DELETE action.
- switch (to.m_movement) {
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- return;
- default:
- break;
- }
- cursor.beginEditBlock();
- if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
- // Visual mode, omitting repeat and movement.
- // Different from Vim:
- // If there is no selection in Visual mode, we do nothing.
- if (cursor.hasSelection()) {
- hasMoved = true;
- deleteSelectedText(cursor, m_mode == VimMode::VisualLine);
- } else if (checkMode(VimMode::Visual)) {
- hasMoved = true;
- VEditUtils::removeBlock(cursor);
- saveToRegister("\n");
- }
- cursor.endEditBlock();
- goto exit;
- }
- hasMoved = processMovement(cursor, moveMode, to, repeat);
- if (repeat == -1) {
- repeat = 1;
- }
- if (hasMoved) {
- bool clearEmptyBlock = false;
- switch (to.m_movement) {
- case Movement::Up:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "delete up" << repeat << "lines";
- break;
- }
- case Movement::Down:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "delete down" << repeat << "lines";
- break;
- }
- case Movement::EndOfLine:
- {
- // End of line (block).
- if (repeat > 1) {
- clearEmptyBlock = true;
- }
- qDebug() << "delete till end of" << repeat << "line";
- break;
- }
- case Movement::LineJump:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "delete till line" << repeat;
- break;
- }
- case Movement::StartOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "delete till start of document";
- break;
- }
- case Movement::EndOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "delete till end of document";
- break;
- }
- // ParagraphUp and ParagraphDown are a little different from Vim in
- // block deletion.
- default:
- break;
- }
- if (clearEmptyBlock) {
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 fewer %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- deleteSelectedText(cursor, clearEmptyBlock);
- }
- cursor.endEditBlock();
- exit:
- if (hasMoved) {
- m_editor->setTextCursorW(cursor);
- }
- }
- void VVim::processCopyAction(QList<Token> &p_tokens)
- {
- Token to = p_tokens.takeFirst();
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- to = p_tokens.takeFirst();
- }
- if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- QTextDocument *doc = m_editor->documentW();
- int oriPos = cursor.position();
- bool changed = false;
- QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
- if (to.isRange()) {
- cursor.beginEditBlock();
- changed = selectRange(cursor, doc, to.m_range, repeat);
- if (changed) {
- // Whether the range may cross blocks.
- bool mayCrossBlock = false;
- switch (to.m_range) {
- case Range::Line:
- {
- // yy, copy current line.
- if (cursor.hasSelection()) {
- repeat = VEditUtils::selectedBlockCount(cursor);
- copySelectedText(cursor, true);
- } else {
- saveToRegister("\n");
- repeat = 1;
- }
- message(tr("%1 %2 yanked").arg(repeat).arg(repeat > 1 ? tr("lines")
- : tr("line")));
- break;
- }
- case Range::ParenthesisInner:
- // Fall through.
- case Range::ParenthesisAround:
- // Fall through.
- case Range::BracketInner:
- // Fall through.
- case Range::BracketAround:
- // Fall through.
- case Range::AngleBracketInner:
- // Fall through.
- case Range::AngleBracketAround:
- // Fall through.
- case Range::BraceInner:
- // Fall through.
- case Range::BraceAround:
- // Fall through.
- mayCrossBlock = true;
- V_FALLTHROUGH;
- case Range::WordAround:
- // Fall through.
- case Range::WordInner:
- // Fall through.
- case Range::WORDAround:
- // Fall through.
- case Range::WORDInner:
- // Fall through.
- case Range::QuoteInner:
- // Fall through.
- case Range::QuoteAround:
- // Fall through.
- case Range::DoubleQuoteInner:
- // Fall through.
- case Range::DoubleQuoteAround:
- // Fall through.
- case Range::BackQuoteInner:
- // Fall through.
- case Range::BackQuoteAround:
- {
- if (cursor.hasSelection()) {
- bool multipleBlocks = false;
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- if (mayCrossBlock && nrBlock > 1) {
- multipleBlocks = true;
- }
- // No need to add new line even crossing multiple blocks.
- copySelectedText(cursor, false);
- if (multipleBlocks) {
- message(tr("%1 %2 yanked").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- }
- break;
- }
- default:
- return;
- }
- }
- if (cursor.position() != oriPos) {
- cursor.setPosition(oriPos);
- changed = true;
- }
- cursor.endEditBlock();
- goto exit;
- }
- V_ASSERT(to.isMovement());
- // Filter out not supported movement for Copy action.
- switch (to.m_movement) {
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- return;
- default:
- break;
- }
- cursor.beginEditBlock();
- changed = processMovement(cursor, moveMode, to, repeat);
- if (repeat == -1) {
- repeat = 1;
- }
- if (changed) {
- bool addNewLine = false;
- switch (to.m_movement) {
- case Movement::Up:
- {
- expandSelectionToWholeLines(cursor);
- addNewLine = true;
- qDebug() << "copy up" << repeat << "lines";
- break;
- }
- case Movement::Down:
- {
- expandSelectionToWholeLines(cursor);
- addNewLine = true;
- qDebug() << "copy down" << repeat << "lines";
- break;
- }
- case Movement::EndOfLine:
- {
- // End of line (block).
- // Do not need to add new line even if repeat > 1.
- qDebug() << "copy till end of" << repeat << "line";
- break;
- }
- case Movement::LineJump:
- {
- expandSelectionToWholeLines(cursor);
- addNewLine = true;
- qDebug() << "copy till line" << repeat;
- break;
- }
- case Movement::StartOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- addNewLine = true;
- qDebug() << "copy till start of document";
- break;
- }
- case Movement::EndOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- addNewLine = true;
- qDebug() << "copy till end of document";
- break;
- }
- default:
- break;
- }
- if (addNewLine) {
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 %2 yanked").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- copySelectedText(cursor, addNewLine);
- if (cursor.position() != oriPos) {
- cursor.setPosition(oriPos);
- }
- }
- cursor.endEditBlock();
- exit:
- if (changed) {
- m_editor->setTextCursorW(cursor);
- }
- }
- void VVim::processPasteAction(QList<Token> &p_tokens, bool p_pasteBefore)
- {
- int repeat = 1;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- if (!p_tokens.isEmpty() || !to.isRepeat()) {
- p_tokens.clear();
- return;
- }
- repeat = to.m_repeat;
- }
- Register ® = getRegister(m_regName);
- QString value = reg.read();
- bool isBlock = reg.isBlock();
- if (value.isEmpty()) {
- if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
- setMode(VimMode::Normal);
- }
- return;
- }
- if (!(checkMode(VimMode::Normal)
- || checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine))) {
- return;
- }
- QString text;
- text.reserve(repeat * value.size() + 1);
- for (int i = 0; i < repeat; ++i) {
- text.append(value);
- }
- bool changed = false;
- int nrBlock = 0;
- int restorePos = -1;
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- // Different from Vim:
- // In visual mode, by default vim select the current char, so paste operation will replace
- // current char, but here it is strange to follow this specification.
- bool isVisualLine = checkMode(VimMode::VisualLine);
- if (!checkMode(VimMode::Normal)) {
- // Visual or VisualLine mode.
- if (cursor.hasSelection()) {
- int pos = cursor.selectionStart();
- deleteSelectedText(cursor, isVisualLine);
- if (isVisualLine) {
- // Insert a new block for insertion.
- insertChangeBlockAfterDeletion(cursor, pos);
- restorePos = cursor.position();
- if (isBlock) {
- nrBlock = text.count('\n');
- // insertChangeBlockAfterDeletion() already insert a new line, so eliminate one here.
- text = text.left(text.size() - 1);
- }
- } else if (isBlock) {
- // Insert new block right at current cursor.
- nrBlock = text.count('\n');
- cursor.insertBlock();
- restorePos = cursor.position();
- } else if (text.count('\n') > 0) {
- restorePos = cursor.position();
- }
- changed = true;
- }
- } else {
- // Normal mode.
- if (isBlock) {
- if (p_pasteBefore) {
- cursor.movePosition(QTextCursor::StartOfBlock);
- cursor.insertBlock();
- cursor.movePosition(QTextCursor::PreviousBlock);
- } else {
- cursor.movePosition(QTextCursor::EndOfBlock);
- cursor.insertBlock();
- }
- restorePos = cursor.position();
- nrBlock = text.count('\n');
- // inserBlock() already insert a new line, so eliminate one here.
- text = text.left(text.size() - 1);
- } else {
- // Not a block.
- if (!p_pasteBefore && !cursor.atBlockEnd()) {
- // Insert behind current cursor.
- cursor.movePosition(QTextCursor::Right);
- }
- if (text.count('\n') > 0) {
- restorePos = cursor.position();
- }
- }
- changed = true;
- }
- if (changed) {
- cursor.insertText(text);
- if (restorePos == -1) {
- // Move cursor one character left.
- cursor.movePosition(QTextCursor::Left);
- } else {
- // Move cursor at the right position.
- cursor.setPosition(restorePos);
- }
- if (nrBlock > 0) {
- message(tr("%1 more %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- }
- }
- cursor.endEditBlock();
- if (!checkMode(VimMode::Normal)) {
- setMode(VimMode::Normal);
- }
- if (changed) {
- m_editor->setTextCursorW(cursor);
- }
- qDebug() << "text pasted" << text;
- }
- void VVim::processChangeAction(QList<Token> &p_tokens)
- {
- Token to = p_tokens.takeFirst();
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- to = p_tokens.takeFirst();
- }
- if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- QTextDocument *doc = m_editor->documentW();
- bool hasMoved = false;
- QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
- if (to.isRange()) {
- cursor.beginEditBlock();
- hasMoved = selectRange(cursor, doc, to.m_range, repeat);
- if (hasMoved) {
- int pos = cursor.selectionStart();
- switch (to.m_range) {
- case Range::Line:
- {
- // cc, change current line.
- if (cursor.hasSelection()) {
- deleteSelectedText(cursor, true);
- insertChangeBlockAfterDeletion(cursor, pos);
- } else {
- saveToRegister("\n");
- }
- break;
- }
- case Range::ParenthesisInner:
- // Fall through.
- case Range::ParenthesisAround:
- // Fall through.
- case Range::BracketInner:
- // Fall through.
- case Range::BracketAround:
- // Fall through.
- case Range::AngleBracketInner:
- // Fall through.
- case Range::AngleBracketAround:
- // Fall through.
- case Range::BraceInner:
- // Fall through.
- case Range::BraceAround:
- // Fall through.
- case Range::WordAround:
- // Fall through.
- case Range::WordInner:
- // Fall through.
- case Range::WORDAround:
- // Fall through.
- case Range::WORDInner:
- // Fall through.
- case Range::QuoteInner:
- // Fall through.
- case Range::QuoteAround:
- // Fall through.
- case Range::DoubleQuoteInner:
- // Fall through.
- case Range::DoubleQuoteAround:
- // Fall through.
- case Range::BackQuoteInner:
- // Fall through.
- case Range::BackQuoteAround:
- {
- if (cursor.hasSelection()) {
- deleteSelectedText(cursor, false);
- }
- break;
- }
- default:
- return;
- }
- }
- cursor.endEditBlock();
- goto exit;
- }
- V_ASSERT(to.isMovement());
- // Filter out not supported movement for Change action.
- switch (to.m_movement) {
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- return;
- default:
- break;
- }
- cursor.beginEditBlock();
- if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
- // Visual mode, omitting repeat and movement.
- // Different from Vim:
- // If there is no selection in Visual mode, we do nothing.
- bool visualLine = checkMode(VimMode::VisualLine);
- if (cursor.hasSelection()) {
- hasMoved = true;
- int pos = cursor.selectionStart();
- deleteSelectedText(cursor, visualLine);
- if (visualLine) {
- insertChangeBlockAfterDeletion(cursor, pos);
- }
- } else if (visualLine) {
- hasMoved = true;
- saveToRegister("\n");
- }
- cursor.endEditBlock();
- goto exit;
- }
- hasMoved = processMovement(cursor, moveMode, to, repeat);
- if (repeat == -1) {
- repeat = 1;
- }
- if (hasMoved) {
- bool clearEmptyBlock = false;
- switch (to.m_movement) {
- case Movement::Left:
- {
- qDebug() << "change backward" << repeat << "chars";
- break;
- }
- case Movement::Right:
- {
- qDebug() << "change forward" << repeat << "chars";
- break;
- }
- case Movement::Up:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "change up" << repeat << "lines";
- break;
- }
- case Movement::Down:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "change down" << repeat << "lines";
- break;
- }
- case Movement::VisualUp:
- {
- qDebug() << "change visual up" << repeat << "lines";
- break;
- }
- case Movement::VisualDown:
- {
- qDebug() << "change visual down" << repeat << "lines";
- break;
- }
- case Movement::StartOfLine:
- {
- qDebug() << "change till start of line";
- break;
- }
- case Movement::EndOfLine:
- {
- // End of line (block).
- if (repeat > 1) {
- clearEmptyBlock = true;
- }
- qDebug() << "change till end of" << repeat << "line";
- break;
- }
- case Movement::FirstCharacter:
- {
- qDebug() << "change till first non-space character";
- break;
- }
- case Movement::LineJump:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "change till line" << repeat;
- break;
- }
- case Movement::StartOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "change till start of document";
- break;
- }
- case Movement::EndOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- clearEmptyBlock = true;
- qDebug() << "change till end of document";
- break;
- }
- case Movement::WordForward:
- {
- qDebug() << "change" << repeat << "words forward";
- break;
- }
- case Movement::WORDForward:
- {
- qDebug() << "change" << repeat << "WORDs forward";
- break;
- }
- case Movement::ForwardEndOfWord:
- {
- qDebug() << "change" << repeat << "end of words forward";
- break;
- }
- case Movement::ForwardEndOfWORD:
- {
- qDebug() << "change" << repeat << "end of WORDs forward";
- break;
- }
- case Movement::WordBackward:
- {
- qDebug() << "change" << repeat << "words backward";
- break;
- }
- case Movement::WORDBackward:
- {
- qDebug() << "change" << repeat << "WORDs backward";
- break;
- }
- case Movement::BackwardEndOfWord:
- {
- qDebug() << "change" << repeat << "end of words backward";
- break;
- }
- case Movement::BackwardEndOfWORD:
- {
- qDebug() << "change" << repeat << "end of WORDs backward";
- break;
- }
- default:
- break;
- }
- if (cursor.hasSelection()) {
- int pos = cursor.selectionStart();
- bool allDeleted = false;
- if (pos == 0) {
- QTextBlock block = m_editor->documentW()->lastBlock();
- if (block.position() + block.length() - 1 == cursor.selectionEnd()) {
- allDeleted = true;
- }
- }
- deleteSelectedText(cursor, clearEmptyBlock);
- if (clearEmptyBlock && !allDeleted) {
- insertChangeBlockAfterDeletion(cursor, pos);
- }
- }
- }
- cursor.endEditBlock();
- exit:
- if (hasMoved) {
- m_editor->setTextCursorW(cursor);
- }
- setMode(VimMode::Insert);
- }
- void VVim::processIndentAction(QList<Token> &p_tokens, IndentType p_type)
- {
- Token to = p_tokens.takeFirst();
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- to = p_tokens.takeFirst();
- }
- if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- QString op;
- switch (p_type) {
- case IndentType::Indent:
- op = ">";
- break;
- case IndentType::UnIndent:
- op = "<";
- break;
- case IndentType::AutoIndent:
- op = "=";
- break;
- default:
- Q_ASSERT(false);
- }
- if (to.isRange()) {
- bool changed = selectRange(cursor, m_editor->documentW(), to.m_range, repeat);
- if (changed) {
- switch (to.m_range) {
- case Range::Line:
- {
- // >>/<<, indent/unindent current line.
- if (repeat == -1) {
- repeat = 1;
- }
- if (p_type == IndentType::AutoIndent) {
- VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
- } else {
- VEditUtils::indentSelectedBlocks(cursor,
- m_editConfig->m_tabSpaces,
- p_type == IndentType::Indent);
- }
- message(tr("%1 %2 %3ed 1 time").arg(repeat)
- .arg(repeat > 1 ? tr("lines")
- : tr("line"))
- .arg(op));
- break;
- }
- case Range::ParenthesisInner:
- // Fall through.
- case Range::ParenthesisAround:
- // Fall through.
- case Range::BracketInner:
- // Fall through.
- case Range::BracketAround:
- // Fall through.
- case Range::AngleBracketInner:
- // Fall through.
- case Range::AngleBracketAround:
- // Fall through.
- case Range::BraceInner:
- // Fall through.
- case Range::BraceAround:
- // Fall through.
- case Range::WordAround:
- // Fall through.
- case Range::WordInner:
- // Fall through.
- case Range::WORDAround:
- // Fall through.
- case Range::WORDInner:
- // Fall through.
- case Range::QuoteInner:
- // Fall through.
- case Range::QuoteAround:
- // Fall through.
- case Range::DoubleQuoteInner:
- // Fall through.
- case Range::DoubleQuoteAround:
- // Fall through.
- case Range::BackQuoteInner:
- // Fall through.
- case Range::BackQuoteAround:
- {
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- if (p_type == IndentType::AutoIndent) {
- VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
- } else {
- VEditUtils::indentSelectedBlocks(cursor,
- m_editConfig->m_tabSpaces,
- p_type == IndentType::Indent);
- }
- message(tr("%1 %2 %3ed 1 time").arg(nrBlock)
- .arg(nrBlock > 1 ? tr("lines")
- : tr("line"))
- .arg(op));
- break;
- }
- default:
- return;
- }
- }
- return;
- }
- V_ASSERT(to.isMovement());
- // Filter out not supported movement for Indent/UnIndent action.
- switch (to.m_movement) {
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- return;
- default:
- break;
- }
- if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
- // Visual mode, omitting repeat and movement.
- // Different from Vim:
- // Do not exit Visual mode after indentation/unindentation.
- if (p_type == IndentType::AutoIndent) {
- VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
- } else {
- VEditUtils::indentSelectedBlocks(cursor,
- m_editConfig->m_tabSpaces,
- p_type == IndentType::Indent);
- }
- return;
- }
- processMovement(cursor,
- QTextCursor::KeepAnchor,
- to,
- repeat);
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- if (p_type == IndentType::AutoIndent) {
- VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
- } else {
- VEditUtils::indentSelectedBlocks(cursor,
- m_editConfig->m_tabSpaces,
- p_type == IndentType::Indent);
- }
- message(tr("%1 %2 %3ed 1 time").arg(nrBlock)
- .arg(nrBlock > 1 ? tr("lines")
- : tr("line"))
- .arg(op));
- }
- void VVim::processToLowerAction(QList<Token> &p_tokens, bool p_toLower)
- {
- Token to = p_tokens.takeFirst();
- int repeat = -1;
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- to = p_tokens.takeFirst();
- }
- if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
- p_tokens.clear();
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- QTextDocument *doc = m_editor->documentW();
- bool changed = false;
- QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
- int oriPos = cursor.position();
- if (to.isRange()) {
- cursor.beginEditBlock();
- changed = selectRange(cursor, doc, to.m_range, repeat);
- if (changed) {
- oriPos = cursor.selectionStart();
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 %2 changed").arg(nrBlock)
- .arg(nrBlock > 1 ? tr("lines") : tr("line")));
- convertCaseOfSelectedText(cursor, p_toLower);
- cursor.setPosition(oriPos);
- }
- cursor.endEditBlock();
- goto exit;
- }
- V_ASSERT(to.isMovement());
- // Filter out not supported movement for ToLower/ToUpper action.
- switch (to.m_movement) {
- case Movement::PageUp:
- case Movement::PageDown:
- case Movement::HalfPageUp:
- case Movement::HalfPageDown:
- return;
- default:
- break;
- }
- cursor.beginEditBlock();
- changed = processMovement(cursor,
- moveMode,
- to,
- repeat);
- if (repeat == -1) {
- repeat = 1;
- }
- if (changed) {
- oriPos = cursor.selectionStart();
- switch (to.m_movement) {
- case Movement::Up:
- {
- expandSelectionToWholeLines(cursor);
- break;
- }
- case Movement::Down:
- {
- expandSelectionToWholeLines(cursor);
- break;
- }
- case Movement::LineJump:
- {
- expandSelectionToWholeLines(cursor);
- break;
- }
- case Movement::StartOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- break;
- }
- case Movement::EndOfDocument:
- {
- expandSelectionToWholeLines(cursor);
- break;
- }
- default:
- break;
- }
- int nrBlock = VEditUtils::selectedBlockCount(cursor);
- message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
- : tr("line")));
- convertCaseOfSelectedText(cursor, p_toLower);
- cursor.setPosition(oriPos);
- }
- cursor.endEditBlock();
- exit:
- if (changed) {
- m_editor->setTextCursorW(cursor);
- }
- }
- void VVim::processUndoAction(QList<Token> &p_tokens)
- {
- int repeat = 1;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- if (!p_tokens.isEmpty() || !to.isRepeat()) {
- p_tokens.clear();
- return;
- }
- repeat = to.m_repeat;
- }
- QTextDocument *doc = m_editor->documentW();
- int i = 0;
- for (i = 0; i < repeat && doc->isUndoAvailable(); ++i) {
- m_editor->undoW();
- }
- message(tr("Undo %1 %2").arg(i).arg(i > 1 ? tr("changes") : tr("change")));
- }
- void VVim::processRedoAction(QList<Token> &p_tokens)
- {
- int repeat = 1;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- if (!p_tokens.isEmpty() || !to.isRepeat()) {
- p_tokens.clear();
- return;
- }
- repeat = to.m_repeat;
- }
- QTextDocument *doc = m_editor->documentW();
- int i = 0;
- for (i = 0; i < repeat && doc->isRedoAvailable(); ++i) {
- m_editor->redoW();
- }
- message(tr("Redo %1 %2").arg(i).arg(i > 1 ? tr("changes") : tr("change")));
- }
- void VVim::processRedrawLineAction(QList<Token> &p_tokens, int p_dest)
- {
- QTextCursor cursor = m_editor->textCursorW();
- int repeat = cursor.block().blockNumber();
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- if (!p_tokens.isEmpty() || !to.isRepeat()) {
- p_tokens.clear();
- return;
- }
- repeat = to.m_repeat - 1;
- }
- m_editor->scrollBlockInPage(repeat, p_dest);
- }
- void VVim::processJumpLocationAction(QList<Token> &p_tokens, bool p_next)
- {
- int repeat = 1;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- if (!p_tokens.isEmpty() || !to.isRepeat()) {
- p_tokens.clear();
- return;
- }
- repeat = to.m_repeat;
- }
- QTextCursor cursor = m_editor->textCursorW();
- Location loc;
- if (p_next) {
- while (m_locations.hasNext() && repeat > 0) {
- --repeat;
- loc = m_locations.nextLocation();
- }
- } else {
- while (m_locations.hasPrevious() && repeat > 0) {
- --repeat;
- loc = m_locations.previousLocation(cursor);
- }
- }
- if (loc.isValid()) {
- QTextDocument *doc = m_editor->documentW();
- if (loc.m_blockNumber >= doc->blockCount()) {
- message(tr("Mark has invalid line number"));
- return;
- }
- QTextBlock block = doc->findBlockByNumber(loc.m_blockNumber);
- int pib = loc.m_positionInBlock;
- if (pib >= block.length()) {
- pib = block.length() - 1;
- }
- if (!m_editor->isBlockVisible(block)) {
- // Scroll the block to the center of screen.
- m_editor->scrollBlockInPage(block.blockNumber(), 1);
- }
- cursor.setPosition(block.position() + pib);
- m_editor->setTextCursorW(cursor);
- }
- }
- void VVim::processReplaceAction(QList<Token> &p_tokens)
- {
- int repeat = 1;
- QChar replaceChar;
- Q_ASSERT(!p_tokens.isEmpty());
- Token to = p_tokens.takeFirst();
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- Q_ASSERT(!p_tokens.isEmpty());
- to = p_tokens.takeFirst();
- }
- Q_ASSERT(to.isKey() && p_tokens.isEmpty());
- replaceChar = keyToChar(to.m_key.m_key, to.m_key.m_modifiers);
- if (replaceChar.isNull()) {
- return;
- }
- if (!(checkMode(VimMode::Normal)
- || checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine))) {
- return;
- }
- // Replace the next repeat characters with replaceChar until the end of line.
- // If repeat is greater than the number of left characters in current line,
- // do nothing.
- // In visual mode, repeat is ignored.
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- if (checkMode(VimMode::Normal)) {
- // Select the characters to be replaced.
- cursor.clearSelection();
- int pib = cursor.positionInBlock();
- int nrChar = cursor.block().length() - 1 - pib;
- if (repeat <= nrChar) {
- cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, repeat);
- }
- }
- bool changed = replaceSelectedTextWithCharacter(cursor, replaceChar);
- cursor.endEditBlock();
- if (changed) {
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Normal);
- }
- }
- void VVim::processReverseCaseAction(QList<Token> &p_tokens)
- {
- int repeat = 1;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- Q_ASSERT(to.isRepeat() && p_tokens.isEmpty());
- repeat = to.m_repeat;
- }
- if (!(checkMode(VimMode::Normal)
- || checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine))) {
- return;
- }
- // Reverse the next repeat characters' case until the end of line.
- // If repeat is greater than the number of left characters in current line,
- // just change the actual number of left characters.
- // In visual mode, repeat is ignored and reverse the selected text.
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- if (checkMode(VimMode::Normal)) {
- // Select the characters to be replaced.
- cursor.clearSelection();
- int pib = cursor.positionInBlock();
- int nrChar = cursor.block().length() - 1 - pib;
- cursor.movePosition(QTextCursor::Right,
- QTextCursor::KeepAnchor,
- repeat > nrChar ? nrChar : repeat);
- }
- bool changed = reverseSelectedTextCase(cursor);
- cursor.endEditBlock();
- if (changed) {
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Normal);
- }
- }
- void VVim::processJoinAction(QList<Token> &p_tokens, bool p_modifySpaces)
- {
- int repeat = 2;
- if (!p_tokens.isEmpty()) {
- Token to = p_tokens.takeFirst();
- Q_ASSERT(to.isRepeat() && p_tokens.isEmpty());
- repeat = qMax(to.m_repeat, repeat);
- }
- if (!(checkMode(VimMode::Normal)
- || checkMode(VimMode::Visual)
- || checkMode(VimMode::VisualLine))) {
- return;
- }
- // Join repeat lines, with the minimum of two lines. Do nothing when on the
- // last line.
- // If @p_modifySpaces is true, remove the indent and insert up to two spaces.
- // If repeat is too big, it is reduced to the number of lines available.
- // In visual mode, repeat is ignored and join the highlighted lines.
- int firstBlock = -1;
- int blockCount = repeat;
- QTextCursor cursor = m_editor->textCursorW();
- cursor.beginEditBlock();
- if (checkMode(VimMode::Normal)) {
- firstBlock = cursor.block().blockNumber();
- } else {
- QTextDocument *doc = m_editor->documentW();
- firstBlock = doc->findBlock(cursor.selectionStart()).blockNumber();
- int lastBlock = doc->findBlock(cursor.selectionEnd()).blockNumber();
- blockCount = lastBlock - firstBlock + 1;
- }
- bool changed = joinLines(cursor, firstBlock, blockCount, p_modifySpaces);
- cursor.endEditBlock();
- if (changed) {
- m_editor->setTextCursorW(cursor);
- setMode(VimMode::Normal);
- }
- }
- bool VVim::clearSelection()
- {
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.hasSelection()) {
- cursor.clearSelection();
- m_editor->setTextCursorW(cursor);
- return true;
- }
- return false;
- }
- int VVim::blockCountOfPageStep() const
- {
- int lineCount = m_editor->documentW()->blockCount();
- QScrollBar *bar = m_editor->verticalScrollBarW();
- int steps = (bar->maximum() - bar->minimum() + bar->pageStep());
- int pageLineCount = lineCount * (bar->pageStep() * 1.0 / steps);
- return pageLineCount;
- }
- void VVim::maintainSelectionInVisualMode(QTextCursor *p_cursor)
- {
- // We need to always select the character on current position.
- QTextCursor *cursor = p_cursor;
- QTextCursor tmpCursor = m_editor->textCursorW();
- if (!cursor) {
- cursor = &tmpCursor;
- }
- bool hasChanged = false;
- int pos = cursor->position();
- int anchor = cursor->anchor();
- if (pos > anchor) {
- Q_ASSERT(pos > m_positionBeforeVisualMode);
- if (anchor > m_positionBeforeVisualMode) {
- // Re-select.
- cursor->setPosition(m_positionBeforeVisualMode);
- cursor->setPosition(pos, QTextCursor::KeepAnchor);
- hasChanged = true;
- }
- setCursorBlockMode(m_editor, CursorBlock::LeftSide);
- } else if (pos == anchor) {
- Q_ASSERT(anchor >= m_positionBeforeVisualMode);
- // Re-select.
- if (anchor == m_positionBeforeVisualMode) {
- cursor->setPosition(m_positionBeforeVisualMode + 1);
- cursor->setPosition(pos, QTextCursor::KeepAnchor);
- hasChanged = true;
- setCursorBlockMode(m_editor, CursorBlock::RightSide);
- } else {
- cursor->setPosition(m_positionBeforeVisualMode);
- cursor->setPosition(pos, QTextCursor::KeepAnchor);
- hasChanged = true;
- setCursorBlockMode(m_editor, CursorBlock::LeftSide);
- }
- } else {
- // Re-select.
- if (anchor <= m_positionBeforeVisualMode) {
- cursor->setPosition(m_positionBeforeVisualMode + 1);
- cursor->setPosition(pos, QTextCursor::KeepAnchor);
- hasChanged = true;
- }
- setCursorBlockMode(m_editor, CursorBlock::RightSide);
- }
- if (hasChanged && !p_cursor) {
- m_editor->setTextCursorW(*cursor);
- }
- }
- void VVim::expandSelectionToWholeLines(QTextCursor &p_cursor)
- {
- QTextDocument *doc = m_editor->documentW();
- int curPos = p_cursor.position();
- int anchorPos = p_cursor.anchor();
- QTextBlock curBlock = doc->findBlock(curPos);
- QTextBlock anchorBlock = doc->findBlock(anchorPos);
- if (curPos >= anchorPos) {
- p_cursor.setPosition(anchorBlock.position(), QTextCursor::MoveAnchor);
- p_cursor.setPosition(curBlock.position() + curBlock.length() - 1,
- QTextCursor::KeepAnchor);
- } else {
- p_cursor.setPosition(anchorBlock.position() + anchorBlock.length() - 1,
- QTextCursor::MoveAnchor);
- p_cursor.setPosition(curBlock.position(),
- QTextCursor::KeepAnchor);
- }
- }
- void VVim::initRegisters()
- {
- if (!s_registers.isEmpty()) {
- return;
- }
- for (char ch = 'a'; ch <= 'z'; ++ch) {
- s_registers[QChar(ch)] = Register(QChar(ch));
- }
- s_registers[c_unnamedRegister] = Register(c_unnamedRegister);
- s_registers[c_blackHoleRegister] = Register(c_blackHoleRegister);
- s_registers[c_selectionRegister] = Register(c_selectionRegister);
- }
- bool VVim::expectingRegisterName() const
- {
- return m_keys.size() == 1
- && m_keys.at(0) == Key(Qt::Key_QuoteDbl, Qt::ShiftModifier);
- }
- bool VVim::expectingCharacterTarget() const
- {
- if (m_keys.size() != 1) {
- return false;
- }
- const Key &key = m_keys.first();
- return (key == Key(Qt::Key_F, Qt::NoModifier)
- || key == Key(Qt::Key_F, Qt::ShiftModifier)
- || key == Key(Qt::Key_T, Qt::NoModifier)
- || key == Key(Qt::Key_T, Qt::ShiftModifier));
- }
- bool VVim::expectingReplaceCharacter() const
- {
- return m_keys.size() == 1
- && m_keys.first() == Key(Qt::Key_R, Qt::NoModifier);
- }
- bool VVim::expectingLeaderSequence() const
- {
- if (m_replayLeaderSequence || m_keys.isEmpty()) {
- return false;
- }
- return m_keys.first() == Key(Qt::Key_Backslash);
- }
- bool VVim::expectingMarkName() const
- {
- return checkPendingKey(Key(Qt::Key_M)) && m_tokens.isEmpty();
- }
- bool VVim::expectingMarkTarget() const
- {
- return checkPendingKey(Key(Qt::Key_Apostrophe))
- || checkPendingKey(Key(Qt::Key_QuoteLeft));
- }
- QChar VVim::keyToRegisterName(const Key &p_key) const
- {
- if (p_key.isAlphabet()) {
- return p_key.toAlphabet().toLower();
- }
- switch (p_key.m_key) {
- case Qt::Key_QuoteDbl:
- if (p_key.m_modifiers == Qt::ShiftModifier) {
- return c_unnamedRegister;
- }
- break;
- case Qt::Key_Plus:
- if (p_key.m_modifiers == Qt::ShiftModifier) {
- return c_selectionRegister;
- }
- break;
- case Qt::Key_Underscore:
- if (p_key.m_modifiers == Qt::ShiftModifier) {
- return c_blackHoleRegister;
- }
- break;
- default:
- break;
- }
- return QChar();
- }
- bool VVim::hasActionToken() const
- {
- // There will be only one action token and it is placed at the front.
- bool has = false;
- if (m_tokens.isEmpty()) {
- return false;
- }
- if (m_tokens.at(0).isAction()) {
- has = true;
- }
- for (int i = 1; i < m_tokens.size(); ++i) {
- V_ASSERT(!m_tokens.at(i).isAction());
- }
- return has;
- }
- bool VVim::hasRepeatToken() const
- {
- // There will be only one repeat token.
- bool has = false;
- if (m_tokens.isEmpty()) {
- return false;
- }
- for (int i = 0; i < m_tokens.size(); ++i) {
- if (m_tokens.at(i).isRepeat()) {
- V_ASSERT(!has);
- has = true;
- }
- }
- return has;
- }
- bool VVim::hasActionTokenValidForTextObject() const
- {
- if (hasActionToken()) {
- Action act = m_tokens.first().m_action;
- if (act == Action::Delete
- || act == Action::Copy
- || act == Action::Change
- || act == Action::ToLower
- || act == Action::ToUpper
- || act == Action::Indent
- || act == Action::UnIndent) {
- return true;
- }
- }
- return false;
- }
- bool VVim::checkActionToken(Action p_action) const
- {
- if (hasActionToken()) {
- return m_tokens.first().m_action == p_action;
- }
- return false;
- }
- bool VVim::checkPendingKey(const Key &p_key) const
- {
- return (m_keys.size() == 1 && m_keys.first() == p_key);
- }
- void VVim::tryAddMoveAction()
- {
- if (!hasActionToken()) {
- addActionToken(Action::Move);
- }
- }
- void VVim::addActionToken(Action p_action)
- {
- V_ASSERT(!hasActionToken());
- m_tokens.prepend(Token(p_action));
- }
- const VVim::Token *VVim::getActionToken() const
- {
- V_ASSERT(hasActionToken());
- return &m_tokens.first();
- }
- VVim::Token *VVim::getRepeatToken()
- {
- V_ASSERT(hasRepeatToken());
- for (auto & token : m_tokens) {
- if (token.isRepeat()) {
- return &token;
- }
- }
- return NULL;
- }
- void VVim::addRangeToken(Range p_range)
- {
- m_tokens.append(Token(p_range));
- }
- void VVim::addMovementToken(Movement p_movement)
- {
- m_tokens.append(Token(p_movement));
- }
- void VVim::addMovementToken(Movement p_movement, Key p_key)
- {
- m_tokens.append(Token(p_movement, p_key));
- }
- void VVim::addKeyToken(Key p_key)
- {
- m_tokens.append(Token(p_key));
- }
- void VVim::deleteSelectedText(QTextCursor &p_cursor, bool p_clearEmptyBlock)
- {
- if (p_cursor.hasSelection()) {
- QString deletedText = VEditUtils::selectedText(p_cursor);
- p_cursor.removeSelectedText();
- if (p_clearEmptyBlock && p_cursor.block().length() == 1) {
- deletedText += "\n";
- VEditUtils::removeBlock(p_cursor);
- }
- saveToRegister(deletedText);
- }
- }
- void VVim::copySelectedText(bool p_addNewLine)
- {
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.hasSelection()) {
- cursor.beginEditBlock();
- copySelectedText(cursor, p_addNewLine);
- cursor.endEditBlock();
- m_editor->setTextCursorW(cursor);
- }
- }
- void VVim::copySelectedText(QTextCursor &p_cursor, bool p_addNewLine)
- {
- if (p_cursor.hasSelection()) {
- QString text = VEditUtils::selectedText(p_cursor);
- p_cursor.clearSelection();
- if (p_addNewLine) {
- text += "\n";
- }
- saveToRegister(text);
- }
- }
- void VVim::convertCaseOfSelectedText(QTextCursor &p_cursor, bool p_toLower)
- {
- if (p_cursor.hasSelection()) {
- QTextDocument *doc = p_cursor.document();
- int start = p_cursor.selectionStart();
- int end = p_cursor.selectionEnd();
- p_cursor.clearSelection();
- p_cursor.setPosition(start);
- int pos = p_cursor.position();
- while (pos < end) {
- QChar ch = doc->characterAt(pos);
- bool modified = false;
- if (p_toLower) {
- if (ch.isUpper()) {
- ch = ch.toLower();
- modified = true;
- }
- } else if (ch.isLower()) {
- ch = ch.toUpper();
- modified = true;
- }
- if (modified) {
- p_cursor.deleteChar();
- p_cursor.insertText(ch);
- } else {
- p_cursor.movePosition(QTextCursor::NextCharacter);
- }
- pos = p_cursor.position();
- }
- }
- }
- void VVim::saveToRegister(const QString &p_text)
- {
- QString text(p_text);
- VEditUtils::removeObjectReplacementCharacter(text);
- qDebug() << QString("save text(%1) to register(%2)").arg(text).arg(m_regName);
- Register ® = getRegister(m_regName);
- reg.update(text);
- if (!reg.isBlackHoleRegister() && !reg.isUnnamedRegister()) {
- // Save it to unnamed register.
- setRegister(c_unnamedRegister, reg.m_value);
- }
- }
- void VVim::Register::update(const QString &p_value)
- {
- QChar newLine('\n');
- bool newIsBlock = false;
- if (p_value.endsWith(newLine)) {
- newIsBlock = true;
- }
- bool oriIsBlock = isBlock();
- if (isNamedRegister() && m_append) {
- // Append @p_value to m_value.
- if (newIsBlock) {
- if (oriIsBlock) {
- m_value += p_value;
- } else {
- m_value.append(newLine);
- m_value += p_value;
- }
- } else if (oriIsBlock) {
- m_value += p_value;
- m_value.append(newLine);
- } else {
- m_value += p_value;
- }
- } else {
- // Set m_value to @p_value.
- m_value = p_value;
- }
- if (isSelectionRegister()) {
- // Change system clipboard.
- QClipboard *clipboard = QApplication::clipboard();
- clipboard->setText(m_value);
- }
- }
- const QString &VVim::Register::read()
- {
- if (isSelectionRegister()) {
- // Update from system clipboard.
- QClipboard *clipboard = QApplication::clipboard();
- const QMimeData *mimeData = clipboard->mimeData();
- if (mimeData->hasText()) {
- m_value = mimeData->text();
- } else {
- m_value.clear();
- }
- }
- return m_value;
- }
- void VVim::repeatLastFindMovement(bool p_reverse)
- {
- if (!m_lastFindToken.isValid()) {
- return;
- }
- V_ASSERT(m_lastFindToken.isMovement());
- Movement mm = m_lastFindToken.m_movement;
- Key key = m_lastFindToken.m_key;
- V_ASSERT(key.isValid());
- if (p_reverse) {
- switch (mm) {
- case Movement::FindForward:
- mm = Movement::FindBackward;
- break;
- case Movement::FindBackward:
- mm = Movement::FindForward;
- break;
- case Movement::TillForward:
- mm = Movement::TillBackward;
- break;
- case Movement::TillBackward:
- mm = Movement::TillForward;
- break;
- default:
- break;
- }
- }
- tryAddMoveAction();
- addMovementToken(mm, key);
- processCommand(m_tokens);
- }
- void VVim::message(const QString &p_msg)
- {
- if (!p_msg.isEmpty()) {
- qDebug() << "vim msg:" << p_msg;
- emit vimMessage(p_msg);
- }
- }
- const QMap<QChar, VVim::Register> &VVim::getRegisters() const
- {
- return s_registers;
- }
- const VVim::Marks &VVim::getMarks() const
- {
- return m_marks;
- }
- QChar VVim::getCurrentRegisterName() const
- {
- return m_regName;
- }
- QString VVim::getPendingKeys() const
- {
- QString str;
- for (auto const & key : m_pendingKeys) {
- str.append(keyToString(key.m_key, key.m_modifiers));
- }
- return str;
- }
- void VVim::setCurrentRegisterName(QChar p_reg)
- {
- m_regName = p_reg;
- }
- bool VVim::checkMode(VimMode p_mode)
- {
- return m_mode == p_mode;
- }
- bool VVim::processCommandLine(VVim::CommandLineType p_type, const QString &p_cmd)
- {
- setMode(VimMode::Normal);
- bool ret = false;
- switch (p_type) {
- case CommandLineType::Command:
- ret = executeCommand(p_cmd);
- break;
- case CommandLineType::SearchForward:
- // Fall through.
- case CommandLineType::SearchBackward:
- {
- SearchItem item = fetchSearchItem(p_type, p_cmd);
- m_editor->findText(item.m_text, item.m_options, item.m_forward);
- m_searchHistory.addItem(item);
- m_searchHistory.resetIndex();
- break;
- }
- default:
- break;
- }
- return ret;
- }
- void VVim::processCommandLineChanged(VVim::CommandLineType p_type,
- const QString &p_cmd)
- {
- setMode(VimMode::Normal);
- if (p_type == CommandLineType::SearchForward
- || p_type == CommandLineType::SearchBackward) {
- // Peek text.
- SearchItem item = fetchSearchItem(p_type, p_cmd);
- m_editor->peekText(item.m_text, item.m_options, item.m_forward);
- }
- }
- void VVim::processCommandLineCancelled()
- {
- m_searchHistory.resetIndex();
- m_editor->clearIncrementalSearchedWordHighlight();
- }
- VVim::SearchItem VVim::fetchSearchItem(VVim::CommandLineType p_type,
- const QString &p_cmd)
- {
- Q_ASSERT(p_type == CommandLineType::SearchForward
- || p_type == CommandLineType::SearchBackward);
- SearchItem item;
- item.m_rawStr = p_cmd;
- item.m_text = p_cmd;
- item.m_forward = p_type == CommandLineType::SearchForward;
- if (p_cmd.indexOf("\\C") > -1) {
- item.m_options |= FindOption::CaseSensitive;
- item.m_text.remove("\\C");
- }
- item.m_options |= FindOption::RegularExpression;
- return item;
- }
- bool VVim::executeCommand(const QString &p_cmd)
- {
- bool validCommand = true;
- QString msg;
- Q_ASSERT(m_tokens.isEmpty() && m_keys.isEmpty());
- if (p_cmd.isEmpty()) {
- return true;
- }else if (p_cmd.size() == 1) {
- if (p_cmd == "w") {
- // :w, save current file.
- emit m_editor->object()->saveNote();
- msg = tr("Note has been saved");
- } else if (p_cmd == "q") {
- // :q, quit edit mode.
- emit m_editor->object()->discardAndRead();
- msg = tr("Quit");
- } else if (p_cmd == "x") {
- // :x, save if there is any change and quit edit mode.
- emit m_editor->object()->saveAndRead();
- msg = tr("Quit with note having been saved");
- } else {
- validCommand = false;
- }
- } else if (p_cmd.size() == 2) {
- if (p_cmd == "wq") {
- // :wq, save change and quit edit mode.
- // We treat it same as :x.
- emit m_editor->object()->saveAndRead();
- msg = tr("Quit with note having been saved");
- } else if (p_cmd == "q!") {
- // :q!, discard change and quit edit mode.
- emit m_editor->object()->discardAndRead();
- msg = tr("Quit");
- } else {
- validCommand = false;
- }
- } else if (p_cmd == "nohlsearch") {
- // :nohlsearch, clear highlight search.
- clearSearchHighlight();
- } else {
- validCommand = false;
- }
- if (!validCommand) {
- bool allDigits = true;
- for (int i = 0; i < p_cmd.size(); ++i) {
- if (!p_cmd[i].isDigit()) {
- allDigits = false;
- break;
- }
- }
- // All digits.
- // Jump to a specific line.
- if (allDigits) {
- bool ok;
- int num = p_cmd.toInt(&ok, 10);
- if (num == 0) {
- num = 1;
- }
- if (ok && num > 0) {
- m_tokens.append(Token(num));
- tryAddMoveAction();
- addMovementToken(Movement::LineJump);
- processCommand(m_tokens);
- validCommand = true;
- }
- }
- }
- if (!validCommand) {
- message(tr("Not an editor command: %1").arg(p_cmd));
- } else {
- message(msg);
- }
- return validCommand;
- }
- bool VVim::hasNonDigitPendingKeys(const QList<Key> &p_keys)
- {
- for (auto const &key : p_keys) {
- if (!key.isDigit()) {
- return true;
- }
- }
- return false;
- }
- bool VVim::hasNonDigitPendingKeys()
- {
- return hasNonDigitPendingKeys(m_keys);
- }
- bool VVim::processLeaderSequence(const Key &p_key)
- {
- // Different from Vim:
- // If it is not a valid sequence, we just do nothing here.
- V_ASSERT(checkPendingKey(Key(Qt::Key_Backslash)));
- bool validSequence = true;
- QList<Key> replaySeq;
- if (p_key == Key(Qt::Key_Y)) {
- // <leader>y, "+y
- replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_Y));
- } else if (p_key == Key(Qt::Key_D)) {
- // <leader>d, "+d
- replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_D));
- } else if (p_key == Key(Qt::Key_P)) {
- // <leader>p, "+p
- replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_P));
- } else if (p_key == Key(Qt::Key_P, Qt::ShiftModifier)) {
- // <leader>P, "+P
- replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
- replaySeq.append(Key(Qt::Key_P, Qt::ShiftModifier));
- } else if (p_key == Key(Qt::Key_Space)) {
- // <leader><space>, clear search highlight
- clearSearchHighlight();
- } else if (p_key == Key(Qt::Key_W)) {
- // <leader>w, save note
- emit m_editor->object()->saveNote();
- message(tr("Note has been saved"));
- } else {
- validSequence = false;
- }
- if (!replaySeq.isEmpty()) {
- // Replay the sequence.
- m_replayLeaderSequence = true;
- m_keys.clear();
- for (int i = 0; i < 2; ++i) {
- m_pendingKeys.pop_back();
- }
- for (auto const &key : replaySeq) {
- bool ret = handleKeyPressEvent(key.m_key, key.m_modifiers);
- if (!ret) {
- break;
- }
- }
- m_replayLeaderSequence = false;
- } else {
- resetState();
- }
- return validSequence;
- }
- VVim::LocationStack::LocationStack(int p_maximum)
- : m_pointer(0), c_maximumLocations(p_maximum < 10 ? 10 : p_maximum)
- {
- }
- bool VVim::LocationStack::hasPrevious() const
- {
- return m_pointer > 0;
- }
- bool VVim::LocationStack::hasNext() const
- {
- return m_pointer < m_locations.size() - 1;
- }
- void VVim::LocationStack::addLocation(const QTextCursor &p_cursor)
- {
- int blockNumber = p_cursor.block().blockNumber();
- int pib = p_cursor.positionInBlock();
- // Remove older location with the same block number.
- for (auto it = m_locations.begin(); it != m_locations.end();) {
- if (it->m_blockNumber == blockNumber) {
- it = m_locations.erase(it);
- break;
- } else {
- ++it;
- }
- }
- if (m_locations.size() >= c_maximumLocations) {
- m_locations.removeFirst();
- }
- m_locations.append(Location(blockNumber, pib));
- m_pointer = m_locations.size();
- qDebug() << QString("add location (%1,%2), pointer=%3")
- .arg(blockNumber).arg(pib).arg(m_pointer);
- }
- const VVim::Location &VVim::LocationStack::previousLocation(const QTextCursor &p_cursor)
- {
- V_ASSERT(hasPrevious());
- if (m_pointer == m_locations.size()) {
- // Add current location to the stack.
- addLocation(p_cursor);
- m_pointer = m_locations.size() - 1;
- }
- // Jump to previous location.
- if (m_pointer > 0) {
- --m_pointer;
- }
- qDebug() << QString("previous location (%1,%2), pointer=%3, size=%4")
- .arg(m_locations.at(m_pointer).m_blockNumber)
- .arg(m_locations.at(m_pointer).m_positionInBlock)
- .arg(m_pointer).arg(m_locations.size());
- return m_locations.at(m_pointer);
- }
- const VVim::Location &VVim::LocationStack::nextLocation()
- {
- V_ASSERT(hasNext());
- ++m_pointer;
- qDebug() << QString("next location (%1,%2), pointer=%3, size=%4")
- .arg(m_locations.at(m_pointer).m_blockNumber)
- .arg(m_locations.at(m_pointer).m_positionInBlock)
- .arg(m_pointer).arg(m_locations.size());
- return m_locations.at(m_pointer);
- }
- VVim::Marks::Marks()
- {
- for (char ch = 'a'; ch <= 'z'; ++ch) {
- m_marks[QChar(ch)] = Mark();
- }
- }
- void VVim::Marks::setMark(QChar p_name, const QTextCursor &p_cursor)
- {
- auto it = m_marks.find(p_name);
- if (it == m_marks.end()) {
- return;
- }
- it->m_location.m_blockNumber = p_cursor.block().blockNumber();
- it->m_location.m_positionInBlock = p_cursor.positionInBlock();
- it->m_text = p_cursor.block().text().trimmed();
- it->m_name = p_name;
- m_lastUsedMark = p_name;
- qDebug() << QString("set mark %1 to (%2,%3)")
- .arg(p_name)
- .arg(it->m_location.m_blockNumber)
- .arg(it->m_location.m_positionInBlock);
- }
- void VVim::Marks::clearMark(QChar p_name)
- {
- auto it = m_marks.find(p_name);
- if (it == m_marks.end()) {
- return;
- }
- it->m_location = Location();
- it->m_text.clear();
- if (m_lastUsedMark == p_name) {
- m_lastUsedMark = QChar();
- }
- }
- VVim::Location VVim::Marks::getMarkLocation(QChar p_name)
- {
- auto it = m_marks.find(p_name);
- if (it == m_marks.end()) {
- return Location();
- }
- if (it->m_location.isValid()) {
- m_lastUsedMark = p_name;
- }
- return it->m_location;
- }
- const QMap<QChar, VVim::Mark> &VVim::Marks::getMarks() const
- {
- return m_marks;
- }
- QChar VVim::Marks::getLastUsedMark() const
- {
- return m_lastUsedMark;
- }
- void VVim::processTitleJump(const QList<Token> &p_tokens, bool p_forward, int p_relativeLevel)
- {
- int repeat = 1;
- if (p_tokens.size() == 1) {
- Token to = p_tokens.first();
- if (to.isRepeat()) {
- repeat = to.m_repeat;
- } else {
- return;
- }
- } else if (!p_tokens.isEmpty()) {
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- if (m_editor->jumpTitle(p_forward, p_relativeLevel, repeat)) {
- // Record current location.
- m_locations.addLocation(cursor);
- }
- }
- void VVim::SearchHistory::addItem(const SearchItem &p_item)
- {
- m_isLastItemForward = p_item.m_forward;
- if (m_isLastItemForward) {
- m_forwardItems.push_back(p_item);
- m_forwardIdx = m_forwardItems.size();
- } else {
- m_backwardItems.push_back(p_item);
- m_backwardIdx = m_forwardItems.size();
- }
- qDebug() << "search history add item" << m_isLastItemForward
- << m_forwardIdx << m_forwardItems.size()
- << m_backwardIdx << m_backwardItems.size();
- }
- const VVim::SearchItem &VVim::SearchHistory::lastItem() const
- {
- if (m_isLastItemForward) {
- Q_ASSERT(!m_forwardItems.isEmpty());
- return m_forwardItems.back();
- } else {
- Q_ASSERT(!m_backwardItems.isEmpty());
- return m_backwardItems.back();
- }
- }
- const VVim::SearchItem &VVim::SearchHistory::nextItem(bool p_forward)
- {
- Q_ASSERT(hasNext(p_forward));
- return p_forward ? m_forwardItems.at(++m_forwardIdx)
- : m_backwardItems.at(++m_backwardIdx);
- }
- // Return previous item in the @p_forward stack.
- const VVim::SearchItem &VVim::SearchHistory::previousItem(bool p_forward)
- {
- Q_ASSERT(hasPrevious(p_forward));
- qDebug() << "previousItem" << p_forward << m_forwardItems.size() << m_backwardItems.size()
- << m_forwardIdx << m_backwardIdx;
- return p_forward ? m_forwardItems.at(--m_forwardIdx)
- : m_backwardItems.at(--m_backwardIdx);
- }
- void VVim::SearchHistory::resetIndex()
- {
- m_forwardIdx = m_forwardItems.size();
- m_backwardIdx = m_backwardItems.size();
- }
- QString VVim::getNextCommandHistory(VVim::CommandLineType p_type,
- const QString &p_cmd)
- {
- Q_UNUSED(p_cmd);
- bool forward = false;
- QString cmd;
- switch (p_type) {
- case CommandLineType::SearchForward:
- forward = true;
- // Fall through.
- case CommandLineType::SearchBackward:
- if (m_searchHistory.hasNext(forward)) {
- return m_searchHistory.nextItem(forward).m_rawStr;
- } else {
- m_searchHistory.resetIndex();
- }
- break;
- default:
- break;
- }
- return cmd;
- }
- // Get the previous command in history of @p_type. @p_cmd is the current input.
- QString VVim::getPreviousCommandHistory(VVim::CommandLineType p_type,
- const QString &p_cmd)
- {
- Q_UNUSED(p_cmd);
- bool forward = false;
- QString cmd;
- switch (p_type) {
- case CommandLineType::SearchForward:
- forward = true;
- // Fall through.
- case CommandLineType::SearchBackward:
- if (m_searchHistory.hasPrevious(forward)) {
- return m_searchHistory.previousItem(forward).m_rawStr;
- }
- break;
- default:
- break;
- }
- return cmd;
- }
- void VVim::clearSearchHighlight()
- {
- m_editor->clearSearchedWordHighlight();
- }
- QString VVim::readRegister(int p_key, int p_modifiers)
- {
- Key keyInfo(p_key, p_modifiers);
- QChar reg = keyToRegisterName(keyInfo);
- if (!reg.isNull()) {
- return getRegister(reg).read();
- }
- return "";
- }
- void VVim::amendCursorPosition()
- {
- if (checkMode(VimMode::Normal)) {
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.atBlockEnd() && !cursor.atBlockStart()) {
- // Normal mode and cursor at the end of a non-empty block.
- cursor.movePosition(QTextCursor::PreviousCharacter);
- m_editor->setTextCursorW(cursor);
- }
- }
- }
- void VVim::handleMousePressed(QMouseEvent *p_event)
- {
- Q_UNUSED(p_event);
- QTextCursor cursor = m_editor->textCursorW();
- if ((checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine))
- && p_event->buttons() != Qt::RightButton) {
- setMode(VimMode::Normal);
- } else if (checkMode(VimMode::Normal)) {
- if (cursor.hasSelection()) {
- setMode(VimMode::Visual, false);
- maintainSelectionInVisualMode();
- }
- }
- }
- void VVim::handleMouseMoved(QMouseEvent *p_event)
- {
- if (p_event->buttons() != Qt::LeftButton) {
- return;
- }
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.hasSelection()) {
- if (checkMode(VimMode::Normal)) {
- int pos = cursor.position();
- int anchor = cursor.anchor();
- QTextBlock block = cursor.document()->findBlock(anchor);
- if (anchor > 0 && anchor == block.position() + block.length() - 1) {
- // Move anchor left.
- cursor.setPosition(anchor - 1);
- cursor.setPosition(pos, QTextCursor::KeepAnchor);
- m_editor->setTextCursorW(cursor);
- }
- setMode(VimMode::Visual, false);
- maintainSelectionInVisualMode();
- } else if (checkMode(VimMode::Visual)) {
- // We need to assure we always select the character on m_positionBeforeVisualMode.
- maintainSelectionInVisualMode();
- }
- } else if (checkMode(VimMode::Visual)) {
- // User move cursor in Visual mode. Now the cursor and anchor
- // are at the same position.
- maintainSelectionInVisualMode();
- }
- }
- void VVim::handleMouseReleased(QMouseEvent *p_event)
- {
- if (checkMode(VimMode::Normal) && p_event->button() == Qt::LeftButton) {
- QTextCursor cursor = m_editor->textCursorW();
- if (cursor.hasSelection()) {
- return;
- }
- amendCursorPosition();
- }
- }
- void VVim::setCursorBlockMode(VEditor *p_cursor, CursorBlock p_mode)
- {
- p_cursor->setCursorBlockModeW(p_mode);
- }
- bool VVim::useLeftSideOfCursor(const QTextCursor &p_cursor)
- {
- if (!checkMode(VimMode::Visual)) {
- return false;
- }
- Q_ASSERT(m_positionBeforeVisualMode >= 0);
- return p_cursor.position() > m_positionBeforeVisualMode;
- }
|