vvim.cpp 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355
  1. #include "vvim.h"
  2. #include <QKeyEvent>
  3. #include <QTextBlock>
  4. #include <QTextDocument>
  5. #include <QString>
  6. #include <QScrollBar>
  7. #include <QDebug>
  8. #include <QClipboard>
  9. #include <QApplication>
  10. #include <QMimeData>
  11. #include "vconfigmanager.h"
  12. #include "veditor.h"
  13. #include "utils/veditutils.h"
  14. #include "vconstants.h"
  15. #include "vmdeditor.h"
  16. extern VConfigManager *g_config;
  17. const QChar VVim::c_unnamedRegister = QChar('"');
  18. const QChar VVim::c_blackHoleRegister = QChar('_');
  19. const QChar VVim::c_selectionRegister = QChar('+');
  20. QMap<QChar, VVim::Register> VVim::s_registers;
  21. const int VVim::SearchHistory::c_capacity = 50;
  22. #define ADDKEY(x, y) case (x): {ch = (y); break;}
  23. // Returns NULL QChar if invalid.
  24. static QChar keyToChar(int p_key, int p_modifiers)
  25. {
  26. if (p_key >= Qt::Key_0 && p_key <= Qt::Key_9) {
  27. return QChar('0' + (p_key - Qt::Key_0));
  28. } else if (p_key >= Qt::Key_A && p_key <= Qt::Key_Z) {
  29. if (p_modifiers == Qt::ShiftModifier
  30. || VUtils::isControlModifierForVim(p_modifiers)) {
  31. return QChar('A' + (p_key - Qt::Key_A));
  32. } else {
  33. return QChar('a' + (p_key - Qt::Key_A));
  34. }
  35. }
  36. QChar ch;
  37. switch (p_key) {
  38. ADDKEY(Qt::Key_Tab, '\t');
  39. ADDKEY(Qt::Key_Space, ' ');
  40. ADDKEY(Qt::Key_Exclam, '!');
  41. ADDKEY(Qt::Key_QuoteDbl, '"');
  42. ADDKEY(Qt::Key_NumberSign, '#');
  43. ADDKEY(Qt::Key_Dollar, '$');
  44. ADDKEY(Qt::Key_Percent, '%');
  45. ADDKEY(Qt::Key_Ampersand, '&');
  46. ADDKEY(Qt::Key_Apostrophe, '\'');
  47. ADDKEY(Qt::Key_ParenLeft, '(');
  48. ADDKEY(Qt::Key_ParenRight, ')');
  49. ADDKEY(Qt::Key_Asterisk, '*');
  50. ADDKEY(Qt::Key_Plus, '+');
  51. ADDKEY(Qt::Key_Comma, ',');
  52. ADDKEY(Qt::Key_Minus, '-');
  53. ADDKEY(Qt::Key_Period, '.');
  54. ADDKEY(Qt::Key_Slash, '/');
  55. ADDKEY(Qt::Key_Colon, ':');
  56. ADDKEY(Qt::Key_Semicolon, ';');
  57. ADDKEY(Qt::Key_Less, '<');
  58. ADDKEY(Qt::Key_Equal, '=');
  59. ADDKEY(Qt::Key_Greater, '>');
  60. ADDKEY(Qt::Key_Question, '?');
  61. ADDKEY(Qt::Key_At, '@');
  62. ADDKEY(Qt::Key_BracketLeft, '[');
  63. ADDKEY(Qt::Key_Backslash, '\\');
  64. ADDKEY(Qt::Key_BracketRight, ']');
  65. ADDKEY(Qt::Key_AsciiCircum, '^');
  66. ADDKEY(Qt::Key_Underscore, '_');
  67. ADDKEY(Qt::Key_QuoteLeft, '`');
  68. ADDKEY(Qt::Key_BraceLeft, '{');
  69. ADDKEY(Qt::Key_Bar, '|');
  70. ADDKEY(Qt::Key_BraceRight, '}');
  71. ADDKEY(Qt::Key_AsciiTilde, '~');
  72. default:
  73. break;
  74. }
  75. return ch;
  76. }
  77. static QString keyToString(int p_key, int p_modifiers)
  78. {
  79. QChar ch = keyToChar(p_key, p_modifiers);
  80. if (ch.isNull()) {
  81. return QString();
  82. }
  83. if (VUtils::isControlModifierForVim(p_modifiers)) {
  84. return QString("^") + ch;
  85. } else {
  86. return ch;
  87. }
  88. }
  89. VVim::VVim(VEditor *p_editor)
  90. : QObject(p_editor->getEditor()),
  91. m_editor(p_editor),
  92. m_editConfig(&p_editor->getConfig()),
  93. m_mode(VimMode::Invalid),
  94. m_resetPositionInBlock(true),
  95. m_regName(c_unnamedRegister),
  96. m_leaderKey(Key(Qt::Key_Space)),
  97. m_replayLeaderSequence(false),
  98. m_registerPending(false),
  99. m_insertModeAfterCommand(false),
  100. m_positionBeforeVisualMode(0)
  101. {
  102. Q_ASSERT(m_editConfig->m_enableVimMode);
  103. setMode(VimMode::Normal);
  104. initRegisters();
  105. connect(m_editor->object(), &VEditorObject::mousePressed,
  106. this, &VVim::handleMousePressed);
  107. connect(m_editor->object(), &VEditorObject::mouseMoved,
  108. this, &VVim::handleMouseMoved);
  109. connect(m_editor->object(), &VEditorObject::mouseReleased,
  110. this, &VVim::handleMouseReleased);
  111. }
  112. // Set @p_cursor's position specified by @p_positionInBlock.
  113. // If @p_positionInBlock is bigger than the block's length, move to the end of block.
  114. // Need to setTextCursor() after calling this.
  115. static void setCursorPositionInBlock(QTextCursor &p_cursor, int p_positionInBlock,
  116. QTextCursor::MoveMode p_mode)
  117. {
  118. QTextBlock block = p_cursor.block();
  119. if (block.length() > p_positionInBlock) {
  120. p_cursor.setPosition(block.position() + p_positionInBlock, p_mode);
  121. } else {
  122. p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
  123. }
  124. }
  125. // Find the start and end of the spaces @p_cursor locates in (within a single block).
  126. // @p_start and @p_end will be the global position of the start and end of the spaces.
  127. // @p_start will equals to @p_end if @p_cursor is not a space.
  128. static void findCurrentSpace(const QTextCursor &p_cursor, int &p_start, int &p_end)
  129. {
  130. QTextBlock block = p_cursor.block();
  131. QString text = block.text();
  132. int pib = p_cursor.positionInBlock();
  133. if (pib < text.size() && !text[pib].isSpace()) {
  134. p_start = p_end = p_cursor.position();
  135. return;
  136. }
  137. p_start = 0;
  138. for (int i = pib - 1; i >= 0; --i) {
  139. if (!text[i].isSpace()) {
  140. p_start = i + 1;
  141. break;
  142. }
  143. }
  144. p_end = block.length() - 1;
  145. for (int i = pib; i < text.size(); ++i) {
  146. if (!text[i].isSpace()) {
  147. p_end = i;
  148. break;
  149. }
  150. }
  151. p_start += block.position();
  152. p_end += block.position();
  153. }
  154. // Move @p_cursor to skip spaces if current cursor is placed at a space
  155. // (may move across blocks). It will stop by the empty block on the way.
  156. // Forward: wwwwsssss|wwww
  157. // Backward: wwww|ssssswwww
  158. static void moveCursorAcrossSpaces(QTextCursor &p_cursor,
  159. QTextCursor::MoveMode p_mode,
  160. bool p_forward,
  161. bool p_stopAtBoundary = false)
  162. {
  163. while (true) {
  164. QTextBlock block = p_cursor.block();
  165. QString text = block.text();
  166. int pib = p_cursor.positionInBlock();
  167. if (p_forward) {
  168. for (; pib < text.size(); ++pib) {
  169. if (!text[pib].isSpace()) {
  170. break;
  171. }
  172. }
  173. if (pib == text.size() && !p_stopAtBoundary) {
  174. // Move to next block.
  175. p_cursor.movePosition(QTextCursor::Down, p_mode, 1);
  176. if (block.blockNumber() == p_cursor.block().blockNumber()) {
  177. // Already at the last block.
  178. p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
  179. break;
  180. } else {
  181. p_cursor.movePosition(QTextCursor::StartOfBlock, p_mode, 1);
  182. if (p_cursor.block().length() <= 1) {
  183. break;
  184. }
  185. }
  186. } else {
  187. // Found non-space character.
  188. p_cursor.setPosition(block.position() + pib, p_mode);
  189. break;
  190. }
  191. } else {
  192. int idx = pib - 1;
  193. for (; idx >= 0; --idx) {
  194. if (!text[idx].isSpace()) {
  195. break;
  196. }
  197. }
  198. if (idx == -1 && !p_stopAtBoundary) {
  199. // Move to previous block.
  200. p_cursor.movePosition(QTextCursor::Up, p_mode, 1);
  201. if (block.blockNumber() == p_cursor.block().blockNumber()) {
  202. // Already at the first block.
  203. p_cursor.movePosition(QTextCursor::StartOfBlock, p_mode, 1);
  204. break;
  205. } else {
  206. p_cursor.movePosition(QTextCursor::EndOfBlock, p_mode, 1);
  207. if (p_cursor.block().length() <= 1) {
  208. break;
  209. }
  210. }
  211. } else {
  212. // Found non-space character.
  213. p_cursor.setPosition(block.position() + idx + 1, p_mode);
  214. break;
  215. }
  216. }
  217. }
  218. }
  219. // Expand the selection of @p_cursor to contain additional spaces at the two ends
  220. // within a block.
  221. static void expandSelectionAcrossSpacesWithinBlock(QTextCursor &p_cursor)
  222. {
  223. QTextBlock block = p_cursor.block();
  224. QString text = block.text();
  225. int start = p_cursor.selectionStart() - block.position();
  226. int end = p_cursor.selectionEnd() - block.position();
  227. for (int i = start - 1; i >= 0; --i) {
  228. if (!text[i].isSpace()) {
  229. start = i + 1;
  230. break;
  231. }
  232. }
  233. for (int i = end; i < text.size(); ++i) {
  234. if (!text[i].isSpace()) {
  235. end = i;
  236. break;
  237. }
  238. }
  239. start += block.position();
  240. end += block.position();
  241. if (start == p_cursor.selectionStart() && end == p_cursor.selectionEnd()) {
  242. return;
  243. }
  244. if (p_cursor.anchor() <= p_cursor.position()) {
  245. p_cursor.setPosition(start, QTextCursor::MoveAnchor);
  246. p_cursor.setPosition(end, QTextCursor::KeepAnchor);
  247. } else {
  248. p_cursor.setPosition(end, QTextCursor::MoveAnchor);
  249. p_cursor.setPosition(start, QTextCursor::KeepAnchor);
  250. }
  251. }
  252. // In Change action, after deleting selected block text, we need to insert a new
  253. // block for user input.
  254. // @p_deletionStart is the global position of the start of the deletion.
  255. // Should be called immediately after the deletion.
  256. static void insertChangeBlockAfterDeletion(QTextCursor &p_cursor, int p_deletionStart)
  257. {
  258. if (p_cursor.position() < p_deletionStart) {
  259. // Insert a new block below.
  260. p_cursor.movePosition(QTextCursor::EndOfBlock);
  261. p_cursor.insertBlock();
  262. } else {
  263. // Insert a new block above.
  264. p_cursor.movePosition(QTextCursor::StartOfBlock);
  265. p_cursor.insertBlock();
  266. p_cursor.movePosition(QTextCursor::PreviousBlock);
  267. }
  268. if (g_config->getAutoIndent()) {
  269. VEditUtils::indentBlockAsBlock(p_cursor, false);
  270. }
  271. }
  272. // Given the percentage of the text, return the corresponding block number.
  273. // Notice that the block number is based on 0.
  274. // Returns -1 if it is not valid.
  275. static int percentageToBlockNumber(const QTextDocument *p_doc, int p_percent)
  276. {
  277. if (p_percent > 100 || p_percent <= 0) {
  278. return -1;
  279. }
  280. int nrBlock = p_doc->blockCount();
  281. int num = nrBlock * (p_percent * 1.0 / 100) - 1;
  282. return num >= 0 ? num : 0;
  283. }
  284. // Replace each of the character of selected text with @p_char.
  285. // Returns true if replacement has taken place.
  286. // Need to setTextCursor() after calling this.
  287. static bool replaceSelectedTextWithCharacter(QTextCursor &p_cursor, QChar p_char)
  288. {
  289. if (!p_cursor.hasSelection()) {
  290. return false;
  291. }
  292. int start = p_cursor.selectionStart();
  293. int end = p_cursor.selectionEnd();
  294. p_cursor.setPosition(start, QTextCursor::MoveAnchor);
  295. while (p_cursor.position() < end) {
  296. if (p_cursor.atBlockEnd()) {
  297. p_cursor.movePosition(QTextCursor::NextCharacter);
  298. } else {
  299. p_cursor.deleteChar();
  300. // insertText() will move the cursor right after the inserted text.
  301. p_cursor.insertText(p_char);
  302. }
  303. }
  304. return true;
  305. }
  306. // Reverse the case of selected text.
  307. // Returns true if the reverse has taken place.
  308. // Need to setTextCursor() after calling this.
  309. static bool reverseSelectedTextCase(QTextCursor &p_cursor)
  310. {
  311. if (!p_cursor.hasSelection()) {
  312. return false;
  313. }
  314. QTextDocument *doc = p_cursor.document();
  315. int start = p_cursor.selectionStart();
  316. int end = p_cursor.selectionEnd();
  317. p_cursor.setPosition(start, QTextCursor::MoveAnchor);
  318. while (p_cursor.position() < end) {
  319. if (p_cursor.atBlockEnd()) {
  320. p_cursor.movePosition(QTextCursor::NextCharacter);
  321. } else {
  322. QChar ch = doc->characterAt(p_cursor.position());
  323. bool changed = false;
  324. if (ch.isLower()) {
  325. ch = ch.toUpper();
  326. changed = true;
  327. } else if (ch.isUpper()) {
  328. ch = ch.toLower();
  329. changed = true;
  330. }
  331. if (changed) {
  332. p_cursor.deleteChar();
  333. // insertText() will move the cursor right after the inserted text.
  334. p_cursor.insertText(ch);
  335. } else {
  336. p_cursor.movePosition(QTextCursor::NextCharacter);
  337. }
  338. }
  339. }
  340. return true;
  341. }
  342. // Join current cursor line and the next line.
  343. static void joinTwoLines(QTextCursor &p_cursor, bool p_modifySpaces)
  344. {
  345. QTextDocument *doc = p_cursor.document();
  346. QTextBlock firstBlock = p_cursor.block();
  347. QString textToAppend = firstBlock.next().text();
  348. p_cursor.movePosition(QTextCursor::EndOfBlock);
  349. if (p_modifySpaces) {
  350. bool insertSpaces = false;
  351. if (firstBlock.length() > 1) {
  352. QChar lastChar = doc->characterAt(p_cursor.position() - 1);
  353. if (!lastChar.isSpace()) {
  354. insertSpaces = true;
  355. }
  356. }
  357. if (insertSpaces) {
  358. p_cursor.insertText(" ");
  359. }
  360. // Remove indentation.
  361. int idx = 0;
  362. for (idx = 0; idx < textToAppend.size(); ++idx) {
  363. if (!textToAppend[idx].isSpace()) {
  364. break;
  365. }
  366. }
  367. textToAppend = textToAppend.right(textToAppend.size() - idx);
  368. }
  369. // Now p_cursor is at the end of the first block.
  370. int position = p_cursor.block().position() + p_cursor.positionInBlock();
  371. p_cursor.insertText(textToAppend);
  372. // Delete the second block.
  373. p_cursor.movePosition(QTextCursor::NextBlock);
  374. VEditUtils::removeBlock(p_cursor);
  375. // Position p_cursor right at the front of appended text.
  376. p_cursor.setPosition(position);
  377. }
  378. // Join lines specified by [@p_firstBlock, @p_firstBlock + p_blockCount).
  379. // Need to check the block range (based on 0).
  380. static bool joinLines(QTextCursor &p_cursor,
  381. int p_firstBlock,
  382. int p_blockCount,
  383. bool p_modifySpaces)
  384. {
  385. QTextDocument *doc = p_cursor.document();
  386. int totalBlockCount = doc->blockCount();
  387. if (p_blockCount <= 0
  388. || p_firstBlock >= totalBlockCount - 1) {
  389. return false;
  390. }
  391. p_blockCount = qMin(p_blockCount, totalBlockCount - p_firstBlock);
  392. p_cursor.setPosition(doc->findBlockByNumber(p_firstBlock).position());
  393. for (int i = 1; i < p_blockCount; ++i) {
  394. joinTwoLines(p_cursor, p_modifySpaces);
  395. }
  396. return true;
  397. }
  398. bool VVim::handleKeyPressEvent(QKeyEvent *p_event, int *p_autoIndentPos)
  399. {
  400. bool ret = handleKeyPressEvent(p_event->key(), p_event->modifiers(), p_autoIndentPos);
  401. if (ret) {
  402. p_event->accept();
  403. }
  404. return ret;
  405. }
  406. bool VVim::handleKeyPressEvent(int key, int modifiers, int *p_autoIndentPos)
  407. {
  408. bool ret = false;
  409. bool resetPositionInBlock = true;
  410. Key keyInfo(key, modifiers);
  411. bool unindent = false;
  412. int autoIndentPos = p_autoIndentPos ? *p_autoIndentPos : -1;
  413. // Handle Insert mode key press.
  414. if (VimMode::Insert == m_mode) {
  415. if (key == Qt::Key_Escape
  416. || (key == Qt::Key_BracketLeft && VUtils::isControlModifierForVim(modifiers))) {
  417. // See if we need to cancel auto indent.
  418. bool cancelAutoIndent = false;
  419. if (p_autoIndentPos && *p_autoIndentPos > -1) {
  420. QTextCursor cursor = m_editor->textCursorW();
  421. cancelAutoIndent = VEditUtils::needToCancelAutoIndent(*p_autoIndentPos, cursor);
  422. if (cancelAutoIndent) {
  423. autoIndentPos = -1;
  424. VEditUtils::deleteIndentAndListMark(cursor);
  425. m_editor->setTextCursorW(cursor);
  426. }
  427. }
  428. // Clear selection and enter Normal mode.
  429. if (!cancelAutoIndent) {
  430. clearSelection();
  431. }
  432. setMode(VimMode::Normal);
  433. goto clear_accept;
  434. }
  435. if (m_registerPending) {
  436. // Ctrl and Shift may be sent out first.
  437. if (key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Meta) {
  438. goto accept;
  439. }
  440. // Expecting a register name.
  441. QChar reg = keyToRegisterName(keyInfo);
  442. if (!reg.isNull()) {
  443. // Insert register content.
  444. m_editor->insertPlainTextW(getRegister(reg).read());
  445. }
  446. goto clear_accept;
  447. } else if (key == Qt::Key_R && VUtils::isControlModifierForVim(modifiers)) {
  448. // Ctrl+R, insert the content of a register.
  449. m_pendingKeys.append(keyInfo);
  450. m_registerPending = true;
  451. goto accept;
  452. }
  453. if (key == Qt::Key_O && VUtils::isControlModifierForVim(modifiers)) {
  454. // Ctrl+O, enter normal mode, execute one command, then return to insert mode.
  455. m_insertModeAfterCommand = true;
  456. clearSelection();
  457. setMode(VimMode::Normal);
  458. goto accept;
  459. }
  460. // Let it be handled outside VVim.
  461. goto exit;
  462. }
  463. // Ctrl and Shift may be sent out first.
  464. if (key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Meta) {
  465. goto accept;
  466. }
  467. if (m_replayLeaderSequence) {
  468. qDebug() << "replaying sequence" << keyToChar(key, modifiers);
  469. }
  470. m_pendingKeys.append(keyInfo);
  471. if (expectingLeaderSequence()) {
  472. if (processLeaderSequence(keyInfo)) {
  473. goto accept;
  474. } else {
  475. goto clear_accept;
  476. }
  477. }
  478. if (expectingRegisterName()) {
  479. // Expecting a register name.
  480. QChar reg = keyToRegisterName(keyInfo);
  481. if (!reg.isNull()) {
  482. m_keys.clear();
  483. setCurrentRegisterName(reg);
  484. Register &r = getRegister(reg);
  485. if (r.isNamedRegister()) {
  486. r.m_append = (modifiers == Qt::ShiftModifier);
  487. } else {
  488. Q_ASSERT(!r.m_append);
  489. }
  490. goto accept;
  491. }
  492. goto clear_accept;
  493. }
  494. if (expectingMarkName()) {
  495. // Expecting a mark name to create a mark.
  496. if (keyInfo.isAlphabet() && modifiers == Qt::NoModifier) {
  497. m_keys.clear();
  498. m_marks.setMark(keyToChar(key, modifiers), m_editor->textCursorW());
  499. }
  500. goto clear_accept;
  501. }
  502. if (expectingMarkTarget()) {
  503. // Expecting a mark name as the target.
  504. Movement mm = Movement::Invalid;
  505. const Key &aKey = m_keys.first();
  506. if (aKey == Key(Qt::Key_Apostrophe)) {
  507. mm = Movement::MarkJumpLine;
  508. } else {
  509. Q_ASSERT(aKey == Key(Qt::Key_QuoteLeft));
  510. mm = Movement::MarkJump;
  511. }
  512. tryAddMoveAction();
  513. addMovementToken(mm, keyInfo);
  514. processCommand(m_tokens);
  515. goto clear_accept;
  516. }
  517. if (expectingCharacterTarget()) {
  518. // Expecting a target character for f/F/t/T.
  519. Movement mm = Movement::Invalid;
  520. const Key &aKey = m_keys.first();
  521. if (aKey.m_key == Qt::Key_F) {
  522. if (aKey.m_modifiers == Qt::NoModifier) {
  523. mm = Movement::FindForward;
  524. } else {
  525. mm = Movement::FindBackward;
  526. }
  527. } else {
  528. if (aKey.m_modifiers == Qt::NoModifier) {
  529. mm = Movement::TillForward;
  530. } else {
  531. mm = Movement::TillBackward;
  532. }
  533. }
  534. tryAddMoveAction();
  535. addMovementToken(mm, keyInfo);
  536. m_lastFindToken = m_tokens.last();
  537. processCommand(m_tokens);
  538. goto clear_accept;
  539. }
  540. if (expectingReplaceCharacter()) {
  541. // Expecting a character to replace with for r.
  542. addActionToken(Action::Replace);
  543. addKeyToken(keyInfo);
  544. processCommand(m_tokens);
  545. goto clear_accept;
  546. }
  547. // Check leader key here. If leader key conflicts with other keys, it will
  548. // overwrite it.
  549. // Leader sequence is just like an action.
  550. if (keyInfo == m_leaderKey
  551. && !hasActionToken()
  552. && !hasNonDigitPendingKeys()
  553. && !m_replayLeaderSequence) {
  554. tryGetRepeatToken(m_keys, m_tokens);
  555. Q_ASSERT(m_keys.isEmpty());
  556. m_pendingKeys.pop_back();
  557. m_pendingKeys.append(Key(Qt::Key_Backslash));
  558. m_keys.append(Key(Qt::Key_Backslash));
  559. goto accept;
  560. }
  561. // We will add key to m_keys. If all m_keys can combined to a token, add
  562. // a new token to m_tokens, clear m_keys and try to process m_tokens.
  563. switch (key) {
  564. case Qt::Key_0:
  565. {
  566. if (modifiers == Qt::NoModifier
  567. || modifiers == Qt::KeypadModifier) {
  568. if (checkPendingKey(Key(Qt::Key_G))) {
  569. // StartOfVisualLine.
  570. tryAddMoveAction();
  571. m_tokens.append(Token(Movement::StartOfVisualLine));
  572. processCommand(m_tokens);
  573. } else if (m_keys.isEmpty()) {
  574. // StartOfLine.
  575. tryAddMoveAction();
  576. m_tokens.append(Token(Movement::StartOfLine));
  577. processCommand(m_tokens);
  578. } else if (m_keys.last().isDigit()) {
  579. // Repeat.
  580. m_keys.append(keyInfo);
  581. resetPositionInBlock = false;
  582. goto accept;
  583. }
  584. }
  585. break;
  586. }
  587. case Qt::Key_1:
  588. case Qt::Key_2:
  589. case Qt::Key_3:
  590. case Qt::Key_4:
  591. case Qt::Key_5:
  592. case Qt::Key_6:
  593. case Qt::Key_7:
  594. case Qt::Key_8:
  595. case Qt::Key_9:
  596. {
  597. if (modifiers == Qt::NoModifier
  598. || modifiers == Qt::KeypadModifier) {
  599. if (!m_keys.isEmpty() && numberFromKeySequence(m_keys) == -1) {
  600. // Invalid sequence.
  601. break;
  602. }
  603. m_keys.append(keyInfo);
  604. resetPositionInBlock = false;
  605. goto accept;
  606. }
  607. break;
  608. }
  609. case Qt::Key_Left:
  610. case Qt::Key_Down:
  611. case Qt::Key_Up:
  612. case Qt::Key_Right:
  613. case Qt::Key_H:
  614. case Qt::Key_J:
  615. case Qt::Key_K:
  616. case Qt::Key_L:
  617. {
  618. if (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier) {
  619. // Check if we could generate a Repeat token.
  620. tryGetRepeatToken(m_keys, m_tokens);
  621. // Generate a Movement token.
  622. Movement mm = Movement::Invalid;
  623. if (!m_keys.isEmpty()) {
  624. // gj, gk.
  625. Key gKey(Qt::Key_G);
  626. if (m_keys.size() == 1 && m_keys.at(0) == gKey) {
  627. if (key == Qt::Key_J) {
  628. mm = Movement::VisualDown;
  629. } else if (key == Qt::Key_K) {
  630. mm = Movement::VisualUp;
  631. } else {
  632. break;
  633. }
  634. } else {
  635. // Not a valid sequence.
  636. break;
  637. }
  638. } else {
  639. // h, j, k, l.
  640. switch (key) {
  641. case Qt::Key_H:
  642. case Qt::Key_Left:
  643. mm = Movement::Left;
  644. break;
  645. case Qt::Key_L:
  646. case Qt::Key_Right:
  647. mm = Movement::Right;
  648. break;
  649. case Qt::Key_J:
  650. case Qt::Key_Down:
  651. mm = Movement::Down;
  652. break;
  653. case Qt::Key_K:
  654. case Qt::Key_Up:
  655. mm = Movement::Up;
  656. break;
  657. default:
  658. V_ASSERT(false);
  659. }
  660. }
  661. V_ASSERT(mm != Movement::Invalid);
  662. tryAddMoveAction();
  663. addMovementToken(mm);
  664. processCommand(m_tokens);
  665. resetPositionInBlock = false;
  666. } else if (modifiers == Qt::ShiftModifier) {
  667. if (key == Qt::Key_J) {
  668. tryGetRepeatToken(m_keys, m_tokens);
  669. if (hasActionToken()) {
  670. break;
  671. }
  672. if (checkPendingKey(Key(Qt::Key_G))) {
  673. // gJ, JoinNoModification.
  674. addActionToken(Action::JoinNoModification);
  675. } else if (m_keys.isEmpty()) {
  676. // J, Join.
  677. addActionToken(Action::Join);
  678. }
  679. processCommand(m_tokens);
  680. }
  681. }
  682. break;
  683. }
  684. case Qt::Key_I:
  685. {
  686. if (modifiers == Qt::NoModifier) {
  687. if (hasActionTokenValidForTextObject()) {
  688. // Inner text object.
  689. tryGetRepeatToken(m_keys, m_tokens);
  690. if (!m_keys.isEmpty()) {
  691. // Invalid sequence;
  692. break;
  693. }
  694. m_keys.append(keyInfo);
  695. goto accept;
  696. }
  697. // Enter Insert mode.
  698. // Different from Vim:
  699. // We enter Insert mode even in Visual and VisualLine mode. We
  700. // also keep the selection after the mode change.
  701. if (checkMode(VimMode::Normal)
  702. || checkMode(VimMode::Visual)
  703. || checkMode(VimMode::VisualLine)) {
  704. setMode(VimMode::Insert, false);
  705. }
  706. } else if (modifiers == Qt::ShiftModifier) {
  707. QTextCursor cursor = m_editor->textCursorW();
  708. if (m_mode == VimMode::Normal) {
  709. // Insert at the first non-space character.
  710. VEditUtils::moveCursorFirstNonSpaceCharacter(cursor, QTextCursor::MoveAnchor);
  711. } else if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
  712. // Insert at the start of line.
  713. cursor.movePosition(QTextCursor::StartOfBlock,
  714. QTextCursor::MoveAnchor,
  715. 1);
  716. }
  717. m_editor->setTextCursorW(cursor);
  718. setMode(VimMode::Insert);
  719. } else if (VUtils::isControlModifierForVim(modifiers)) {
  720. // Ctrl+I, jump to next location.
  721. if (!m_tokens.isEmpty()
  722. || !checkMode(VimMode::Normal)) {
  723. break;
  724. }
  725. tryGetRepeatToken(m_keys, m_tokens);
  726. if (!m_keys.isEmpty()) {
  727. break;
  728. }
  729. addActionToken(Action::JumpNextLocation);
  730. processCommand(m_tokens);
  731. break;
  732. }
  733. break;
  734. }
  735. case Qt::Key_A:
  736. {
  737. if (modifiers == Qt::NoModifier) {
  738. if (hasActionTokenValidForTextObject()) {
  739. // Around text object.
  740. tryGetRepeatToken(m_keys, m_tokens);
  741. if (!m_keys.isEmpty()) {
  742. // Invalid sequence;
  743. break;
  744. }
  745. m_keys.append(keyInfo);
  746. goto accept;
  747. }
  748. // Enter Insert mode.
  749. // Move cursor back one character.
  750. if (m_mode == VimMode::Normal) {
  751. QTextCursor cursor = m_editor->textCursorW();
  752. V_ASSERT(!cursor.hasSelection());
  753. if (!cursor.atBlockEnd()) {
  754. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
  755. m_editor->setTextCursorW(cursor);
  756. }
  757. setMode(VimMode::Insert);
  758. }
  759. } else if (modifiers == Qt::ShiftModifier) {
  760. // Insert at the end of line.
  761. QTextCursor cursor = m_editor->textCursorW();
  762. if (m_mode == VimMode::Normal) {
  763. cursor.movePosition(QTextCursor::EndOfBlock,
  764. QTextCursor::MoveAnchor,
  765. 1);
  766. m_editor->setTextCursorW(cursor);
  767. } else if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
  768. if (!cursor.atBlockEnd()) {
  769. cursor.clearSelection();
  770. cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
  771. m_editor->setTextCursorW(cursor);
  772. }
  773. }
  774. setMode(VimMode::Insert);
  775. }
  776. break;
  777. }
  778. case Qt::Key_O:
  779. {
  780. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  781. // Insert a new block under/above current block and enter insert mode.
  782. bool insertAbove = modifiers == Qt::ShiftModifier;
  783. if (m_mode == VimMode::Normal) {
  784. QTextCursor cursor = m_editor->textCursorW();
  785. cursor.beginEditBlock();
  786. cursor.movePosition(insertAbove ? QTextCursor::StartOfBlock
  787. : QTextCursor::EndOfBlock,
  788. QTextCursor::MoveAnchor,
  789. 1);
  790. cursor.insertBlock();
  791. if (insertAbove) {
  792. cursor.movePosition(QTextCursor::PreviousBlock,
  793. QTextCursor::MoveAnchor,
  794. 1);
  795. }
  796. bool textInserted = false;
  797. if (g_config->getAutoIndent()) {
  798. textInserted = VEditUtils::indentBlockAsBlock(cursor, false);
  799. if (g_config->getAutoList()) {
  800. textInserted = VEditUtils::insertListMarkAsPreviousBlock(cursor)
  801. || textInserted;
  802. }
  803. }
  804. cursor.endEditBlock();
  805. m_editor->setTextCursorW(cursor);
  806. if (textInserted) {
  807. autoIndentPos = cursor.position();
  808. }
  809. setMode(VimMode::Insert);
  810. }
  811. break;
  812. } else if (VUtils::isControlModifierForVim(modifiers)) {
  813. // Ctrl+O, jump to previous location.
  814. if (!m_tokens.isEmpty()
  815. || !checkMode(VimMode::Normal)) {
  816. break;
  817. }
  818. tryGetRepeatToken(m_keys, m_tokens);
  819. if (!m_keys.isEmpty()) {
  820. break;
  821. }
  822. addActionToken(Action::JumpPreviousLocation);
  823. processCommand(m_tokens);
  824. break;
  825. }
  826. break;
  827. }
  828. case Qt::Key_S:
  829. {
  830. tryGetRepeatToken(m_keys, m_tokens);
  831. if (!m_keys.isEmpty() || hasActionToken()) {
  832. break;
  833. }
  834. if (modifiers == Qt::NoModifier) {
  835. addActionToken(Action::Change);
  836. // Movement will be ignored in Visual mode.
  837. addMovementToken(Movement::Right);
  838. processCommand(m_tokens);
  839. } else if (modifiers == Qt::ShiftModifier) {
  840. // S, change current line.
  841. addActionToken(Action::Change);
  842. addRangeToken(Range::Line);
  843. processCommand(m_tokens);
  844. }
  845. break;
  846. }
  847. case Qt::Key_Dollar:
  848. {
  849. if (modifiers == Qt::ShiftModifier) {
  850. // $, move to end of line.
  851. tryGetRepeatToken(m_keys, m_tokens);
  852. if (m_keys.isEmpty()) {
  853. tryAddMoveAction();
  854. m_tokens.append(Token(Movement::EndOfLine));
  855. processCommand(m_tokens);
  856. }
  857. }
  858. break;
  859. }
  860. case Qt::Key_G:
  861. {
  862. Movement mm = Movement::Invalid;
  863. if (modifiers == Qt::NoModifier) {
  864. tryGetRepeatToken(m_keys, m_tokens);
  865. if (m_keys.isEmpty()) {
  866. // First g, pend it.
  867. m_keys.append(keyInfo);
  868. goto accept;
  869. } else if (m_keys.size() == 1 && m_keys.at(0) == keyInfo) {
  870. // gg, go to a certain line or first line.
  871. if (!m_tokens.isEmpty() && m_tokens.last().isRepeat()) {
  872. mm = Movement::LineJump;
  873. } else {
  874. mm = Movement::StartOfDocument;
  875. }
  876. }
  877. } else if (modifiers == Qt::ShiftModifier) {
  878. tryGetRepeatToken(m_keys, m_tokens);
  879. if (m_keys.isEmpty()) {
  880. // G, go to a certain line or the last line.
  881. if (!m_tokens.isEmpty() && m_tokens.last().isRepeat()) {
  882. mm = Movement::LineJump;
  883. } else {
  884. mm = Movement::EndOfDocument;
  885. }
  886. }
  887. }
  888. if (mm != Movement::Invalid) {
  889. tryAddMoveAction();
  890. m_tokens.append(Token(mm));
  891. processCommand(m_tokens);
  892. }
  893. break;
  894. }
  895. // Should be kept together with Qt::Key_PageUp.
  896. case Qt::Key_B:
  897. {
  898. if (VUtils::isControlModifierForVim(modifiers)) {
  899. // Ctrl+B, page up, fall through.
  900. modifiers = Qt::NoModifier;
  901. } else if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  902. tryGetRepeatToken(m_keys, m_tokens);
  903. if (!m_keys.isEmpty()) {
  904. if (modifiers == Qt::NoModifier && checkPendingKey(Key(Qt::Key_Z))) {
  905. // zb, redraw to make a certain line the bottom of window.
  906. addActionToken(Action::RedrawAtBottom);
  907. processCommand(m_tokens);
  908. break;
  909. }
  910. break;
  911. }
  912. // b, go to the start of previous or current word.
  913. Movement mm = Movement::WordBackward;
  914. if (modifiers == Qt::ShiftModifier) {
  915. // B, go to the start of previous or current WORD.
  916. mm = Movement::WORDBackward;
  917. }
  918. tryAddMoveAction();
  919. m_tokens.append(Token(mm));
  920. processCommand(m_tokens);
  921. break;
  922. } else {
  923. break;
  924. }
  925. V_FALLTHROUGH;
  926. }
  927. case Qt::Key_PageUp:
  928. {
  929. if (modifiers == Qt::NoModifier) {
  930. tryGetRepeatToken(m_keys, m_tokens);
  931. if (!m_keys.isEmpty()) {
  932. // Not a valid sequence.
  933. break;
  934. }
  935. Movement mm = Movement::PageUp;
  936. tryAddMoveAction();
  937. m_tokens.append(Token(mm));
  938. processCommand(m_tokens);
  939. resetPositionInBlock = false;
  940. }
  941. break;
  942. }
  943. case Qt::Key_U:
  944. {
  945. tryGetRepeatToken(m_keys, m_tokens);
  946. bool toLower = modifiers == Qt::NoModifier;
  947. if (VUtils::isControlModifierForVim(modifiers)) {
  948. // Ctrl+U, HalfPageUp.
  949. if (!m_keys.isEmpty()) {
  950. // Not a valid sequence.
  951. break;
  952. }
  953. Movement mm = Movement::HalfPageUp;
  954. tryAddMoveAction();
  955. m_tokens.append(Token(mm));
  956. processCommand(m_tokens);
  957. resetPositionInBlock = false;
  958. } else if (m_keys.isEmpty() && !hasActionToken()) {
  959. if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
  960. // u/U for tolower and toupper selected text.
  961. QTextCursor cursor = m_editor->textCursorW();
  962. cursor.beginEditBlock();
  963. // Different from Vim:
  964. // If there is no selection in Visual mode, we do nothing.
  965. if (m_mode == VimMode::VisualLine) {
  966. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  967. message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  968. : tr("line")));
  969. }
  970. convertCaseOfSelectedText(cursor, toLower);
  971. cursor.endEditBlock();
  972. m_editor->setTextCursorW(cursor);
  973. setMode(VimMode::Normal);
  974. break;
  975. }
  976. // u, Undo.
  977. if (modifiers == Qt::NoModifier) {
  978. addActionToken(Action::Undo);
  979. processCommand(m_tokens);
  980. }
  981. break;
  982. } else {
  983. if (hasActionToken()) {
  984. // guu/gUU.
  985. if ((toLower && checkActionToken(Action::ToLower))
  986. || (!toLower && checkActionToken(Action::ToUpper))) {
  987. addRangeToken(Range::Line);
  988. processCommand(m_tokens);
  989. break;
  990. } else {
  991. // An invalid sequence.
  992. break;
  993. }
  994. } else if (checkPendingKey(Key(Qt::Key_G))) {
  995. // gu/gU, ToLower/ToUpper action.
  996. if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
  997. QTextCursor cursor = m_editor->textCursorW();
  998. cursor.beginEditBlock();
  999. // Different from Vim:
  1000. // If there is no selection in Visual mode, we do nothing.
  1001. if (m_mode == VimMode::VisualLine) {
  1002. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  1003. message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  1004. : tr("line")));
  1005. }
  1006. convertCaseOfSelectedText(cursor, toLower);
  1007. cursor.endEditBlock();
  1008. m_editor->setTextCursorW(cursor);
  1009. setMode(VimMode::Normal);
  1010. break;
  1011. }
  1012. addActionToken(toLower ? Action::ToLower : Action::ToUpper);
  1013. m_keys.clear();
  1014. goto accept;
  1015. } else {
  1016. // An invalid sequence.
  1017. break;
  1018. }
  1019. }
  1020. break;
  1021. }
  1022. // Ctrl+F is used for Find dialog, not used here.
  1023. case Qt::Key_PageDown:
  1024. {
  1025. if (modifiers == Qt::NoModifier) {
  1026. tryGetRepeatToken(m_keys, m_tokens);
  1027. if (!m_keys.isEmpty()) {
  1028. // Not a valid sequence.
  1029. break;
  1030. }
  1031. Movement mm = Movement::PageDown;
  1032. tryAddMoveAction();
  1033. m_tokens.append(Token(mm));
  1034. processCommand(m_tokens);
  1035. resetPositionInBlock = false;
  1036. }
  1037. break;
  1038. }
  1039. case Qt::Key_D:
  1040. {
  1041. if (VUtils::isControlModifierForVim(modifiers)) {
  1042. // Ctrl+D, HalfPageDown.
  1043. tryGetRepeatToken(m_keys, m_tokens);
  1044. if (!m_keys.isEmpty()) {
  1045. // Not a valid sequence.
  1046. break;
  1047. }
  1048. Movement mm = Movement::HalfPageDown;
  1049. tryAddMoveAction();
  1050. m_tokens.append(Token(mm));
  1051. processCommand(m_tokens);
  1052. resetPositionInBlock = false;
  1053. } else if (modifiers == Qt::NoModifier) {
  1054. // d, delete action.
  1055. tryGetRepeatToken(m_keys, m_tokens);
  1056. if (hasActionToken()) {
  1057. // This is another d, something like dd.
  1058. if (checkActionToken(Action::Delete)) {
  1059. addRangeToken(Range::Line);
  1060. processCommand(m_tokens);
  1061. break;
  1062. } else {
  1063. // An invalid sequence.
  1064. break;
  1065. }
  1066. } else {
  1067. // The first d, an Action.
  1068. addActionToken(Action::Delete);
  1069. if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
  1070. // Movement will be ignored.
  1071. addMovementToken(Movement::Left);
  1072. processCommand(m_tokens);
  1073. setMode(VimMode::Normal);
  1074. break;
  1075. }
  1076. goto accept;
  1077. }
  1078. } else if (modifiers == Qt::ShiftModifier) {
  1079. tryGetRepeatToken(m_keys, m_tokens);
  1080. if (!hasActionToken()) {
  1081. if (checkMode(VimMode::Normal)) {
  1082. // D, same as d$.
  1083. addActionToken(Action::Delete);
  1084. addMovementToken(Movement::EndOfLine);
  1085. processCommand(m_tokens);
  1086. } else if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
  1087. // D, same as dd.
  1088. addActionToken(Action::Delete);
  1089. addRangeToken(Range::Line);
  1090. processCommand(m_tokens);
  1091. setMode(VimMode::Normal);
  1092. }
  1093. }
  1094. break;
  1095. }
  1096. break;
  1097. }
  1098. case Qt::Key_BracketRight:
  1099. {
  1100. if (modifiers == Qt::NoModifier) {
  1101. tryGetRepeatToken(m_keys, m_tokens);
  1102. if (checkPendingKey(Key(Qt::Key_I))
  1103. || checkPendingKey(Key(Qt::Key_A))) {
  1104. // BracketInner/BracketAround.
  1105. Range range = Range::BracketInner;
  1106. if (checkPendingKey(Key(Qt::Key_A))) {
  1107. range = Range::BracketAround;
  1108. }
  1109. addRangeToken(range);
  1110. processCommand(m_tokens);
  1111. break;
  1112. } else if (hasActionToken() || !checkMode(VimMode::Normal)) {
  1113. // Invalid sequence.
  1114. break;
  1115. } else if (m_keys.isEmpty()) {
  1116. // First ], pend it.
  1117. m_keys.append(keyInfo);
  1118. goto accept;
  1119. } else if (checkPendingKey(keyInfo)) {
  1120. // ]], goto next title, regardless of level.
  1121. processTitleJump(m_tokens, true, 1);
  1122. } else if (checkPendingKey(Key(Qt::Key_BracketLeft))) {
  1123. // [], goto previous title at the same level.
  1124. processTitleJump(m_tokens, false, 0);
  1125. }
  1126. break;
  1127. }
  1128. break;
  1129. }
  1130. // Should be kept together with Qt::Key_Escape.
  1131. case Qt::Key_BracketLeft:
  1132. {
  1133. if (VUtils::isControlModifierForVim(modifiers)) {
  1134. // fallthrough.
  1135. } else if (modifiers == Qt::NoModifier) {
  1136. tryGetRepeatToken(m_keys, m_tokens);
  1137. if (checkPendingKey(Key(Qt::Key_I))
  1138. || checkPendingKey(Key(Qt::Key_A))) {
  1139. // BracketInner/BracketAround.
  1140. Range range = Range::BracketInner;
  1141. if (checkPendingKey(Key(Qt::Key_A))) {
  1142. range = Range::BracketAround;
  1143. }
  1144. addRangeToken(range);
  1145. processCommand(m_tokens);
  1146. break;
  1147. } else if (hasActionToken() || !checkMode(VimMode::Normal)) {
  1148. // Invalid sequence.
  1149. break;
  1150. } else if (m_keys.isEmpty()) {
  1151. // First [, pend it.
  1152. m_keys.append(keyInfo);
  1153. goto accept;
  1154. } else if (checkPendingKey(keyInfo)) {
  1155. // [[, goto previous title, regardless of level.
  1156. processTitleJump(m_tokens, false, 1);
  1157. } else if (checkPendingKey(Key(Qt::Key_BracketRight))) {
  1158. // ][, goto next title at the same level.
  1159. processTitleJump(m_tokens, true, 0);
  1160. }
  1161. break;
  1162. } else {
  1163. break;
  1164. }
  1165. V_FALLTHROUGH;
  1166. }
  1167. case Qt::Key_Escape:
  1168. {
  1169. // Clear selection and enter normal mode.
  1170. int position = -1;
  1171. if (checkMode(VimMode::Visual)) {
  1172. QTextCursor cursor = m_editor->textCursorW();
  1173. if (cursor.position() > cursor.anchor()) {
  1174. position = cursor.position() - 1;
  1175. }
  1176. }
  1177. bool ret = clearSelection();
  1178. if (!ret && checkMode(VimMode::Normal)) {
  1179. emit m_editor->object()->requestCloseFindReplaceDialog();
  1180. }
  1181. setMode(VimMode::Normal, true, position);
  1182. break;
  1183. }
  1184. case Qt::Key_V:
  1185. {
  1186. if (modifiers == Qt::NoModifier) {
  1187. if (checkMode(VimMode::Visual)) {
  1188. setMode(VimMode::Normal, true);
  1189. } else {
  1190. // Toggle Visual Mode.
  1191. setMode(VimMode::Visual);
  1192. maintainSelectionInVisualMode();
  1193. }
  1194. } else if (modifiers == Qt::ShiftModifier) {
  1195. // Visual Line Mode.
  1196. clearSelection();
  1197. VimMode mode = VimMode::VisualLine;
  1198. if (m_mode == VimMode::VisualLine) {
  1199. mode = VimMode::Normal;
  1200. }
  1201. setMode(mode);
  1202. if (m_mode == VimMode::VisualLine) {
  1203. QTextCursor cursor = m_editor->textCursorW();
  1204. expandSelectionToWholeLines(cursor);
  1205. m_editor->setTextCursorW(cursor);
  1206. }
  1207. } else if (VUtils::isControlModifierForVim(modifiers)) {
  1208. if (g_config->getVimExemptionKeys().contains('v')) {
  1209. // Let it be handled outside.
  1210. resetState();
  1211. goto exit;
  1212. }
  1213. }
  1214. break;
  1215. }
  1216. case Qt::Key_AsciiCircum:
  1217. {
  1218. if (modifiers == Qt::ShiftModifier) {
  1219. // ~, go to first non-space character of current line (block).
  1220. tryGetRepeatToken(m_keys, m_tokens);
  1221. if (!m_keys.isEmpty()) {
  1222. // Not a valid sequence.
  1223. break;
  1224. }
  1225. Movement mm = Movement::FirstCharacter;
  1226. tryAddMoveAction();
  1227. m_tokens.append(Token(mm));
  1228. processCommand(m_tokens);
  1229. }
  1230. break;
  1231. }
  1232. case Qt::Key_W:
  1233. {
  1234. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1235. bool shift = modifiers == Qt::ShiftModifier;
  1236. tryGetRepeatToken(m_keys, m_tokens);
  1237. if (checkPendingKey(Key(Qt::Key_I))
  1238. || checkPendingKey(Key(Qt::Key_A))) {
  1239. // WordInner/WORDInner/WordAournd/WORDAround.
  1240. bool around = checkPendingKey(Key(Qt::Key_A));
  1241. Range range = Range::Invalid;
  1242. if (shift) {
  1243. if (around) {
  1244. range = Range::WORDAround;
  1245. } else {
  1246. range = Range::WORDInner;
  1247. }
  1248. } else {
  1249. if (around) {
  1250. range = Range::WordAround;
  1251. } else {
  1252. range = Range::WordInner;
  1253. }
  1254. }
  1255. addRangeToken(range);
  1256. processCommand(m_tokens);
  1257. break;
  1258. } else if (!m_keys.isEmpty()) {
  1259. // Not a valid sequence.
  1260. break;
  1261. }
  1262. // w, go to the start of next word.
  1263. Movement mm = Movement::WordForward;
  1264. if (shift) {
  1265. // W, go to the start of next WORD.
  1266. mm = Movement::WORDForward;
  1267. }
  1268. if (checkActionToken(Action::Change)) {
  1269. // In Change action, cw equals to ce.
  1270. if (shift) {
  1271. mm = Movement::ForwardEndOfWORD;
  1272. } else {
  1273. mm = Movement::ForwardEndOfWord;
  1274. }
  1275. } else {
  1276. tryAddMoveAction();
  1277. }
  1278. addMovementToken(mm);
  1279. processCommand(m_tokens);
  1280. break;
  1281. }
  1282. break;
  1283. }
  1284. case Qt::Key_E:
  1285. {
  1286. // e, E, ge, gE.
  1287. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1288. tryGetRepeatToken(m_keys, m_tokens);
  1289. Movement mm = Movement::Invalid;
  1290. if (!m_keys.isEmpty()) {
  1291. if (m_keys.size() == 1 && m_keys.at(0) == Key(Qt::Key_G)) {
  1292. // ge, gE.
  1293. if (modifiers == Qt::NoModifier) {
  1294. mm = Movement::BackwardEndOfWord;
  1295. } else {
  1296. mm = Movement::BackwardEndOfWORD;
  1297. }
  1298. } else {
  1299. // Not a valid sequence.
  1300. break;
  1301. }
  1302. } else {
  1303. // e, E.
  1304. if (modifiers == Qt::NoModifier) {
  1305. mm = Movement::ForwardEndOfWord;
  1306. } else {
  1307. mm = Movement::ForwardEndOfWORD;
  1308. }
  1309. }
  1310. tryAddMoveAction();
  1311. m_tokens.append(Token(mm));
  1312. processCommand(m_tokens);
  1313. }
  1314. break;
  1315. }
  1316. case Qt::Key_QuoteDbl:
  1317. {
  1318. if (modifiers == Qt::ShiftModifier) {
  1319. tryGetRepeatToken(m_keys, m_tokens);
  1320. if (checkPendingKey(Key(Qt::Key_I))
  1321. || checkPendingKey(Key(Qt::Key_A))) {
  1322. // DoubleQuoteInner/DoubleQuoteAround.
  1323. Range range = Range::DoubleQuoteInner;
  1324. if (checkPendingKey(Key(Qt::Key_A))) {
  1325. range = Range::DoubleQuoteAround;
  1326. }
  1327. addRangeToken(range);
  1328. processCommand(m_tokens);
  1329. break;
  1330. } else if (!m_keys.isEmpty() || hasActionToken()) {
  1331. // Invalid sequence.
  1332. break;
  1333. }
  1334. // ", specify a register.
  1335. m_keys.append(keyInfo);
  1336. goto accept;
  1337. }
  1338. break;
  1339. }
  1340. case Qt::Key_X:
  1341. {
  1342. if (modifiers == Qt::ShiftModifier || modifiers == Qt::NoModifier) {
  1343. // x, or X to delete one char.
  1344. tryGetRepeatToken(m_keys, m_tokens);
  1345. if (!m_keys.isEmpty() || hasActionToken()) {
  1346. break;
  1347. }
  1348. addActionToken(Action::Delete);
  1349. if (modifiers == Qt::ShiftModifier) {
  1350. if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
  1351. // X, same as dd.
  1352. addRangeToken(Range::Line);
  1353. } else {
  1354. // X, delete one char.
  1355. addMovementToken(Movement::Left);
  1356. }
  1357. } else {
  1358. // x.
  1359. // Movement will be ignored in Visual mode.
  1360. addMovementToken(Movement::Right);
  1361. }
  1362. processCommand(m_tokens);
  1363. setMode(VimMode::Normal);
  1364. break;
  1365. }
  1366. break;
  1367. }
  1368. case Qt::Key_Y:
  1369. {
  1370. if (modifiers == Qt::NoModifier) {
  1371. // y, copy action.
  1372. tryGetRepeatToken(m_keys, m_tokens);
  1373. if (hasActionToken()) {
  1374. // This is another y, something like yy.
  1375. if (checkActionToken(Action::Copy) && checkMode(VimMode::Normal)) {
  1376. addRangeToken(Range::Line);
  1377. processCommand(m_tokens);
  1378. } else {
  1379. // An invalid sequence.
  1380. break;
  1381. }
  1382. } else {
  1383. // The first y, an Action.
  1384. if (m_mode == VimMode::Visual || m_mode == VimMode::VisualLine) {
  1385. copySelectedText(m_mode == VimMode::VisualLine);
  1386. setMode(VimMode::Normal);
  1387. break;
  1388. }
  1389. addActionToken(Action::Copy);
  1390. goto accept;
  1391. }
  1392. } else if (modifiers == Qt::ShiftModifier) {
  1393. tryGetRepeatToken(m_keys, m_tokens);
  1394. if (!hasActionToken()) {
  1395. // Y, same as yy.
  1396. addActionToken(Action::Copy);
  1397. addRangeToken(Range::Line);
  1398. processCommand(m_tokens);
  1399. setMode(VimMode::Normal);
  1400. }
  1401. break;
  1402. }
  1403. break;
  1404. }
  1405. case Qt::Key_P:
  1406. {
  1407. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1408. // p/P, paste/pastebefore action.
  1409. tryGetRepeatToken(m_keys, m_tokens);
  1410. if (hasActionToken() || !m_keys.isEmpty()) {
  1411. // An invalid sequence.
  1412. break;
  1413. }
  1414. addActionToken(modifiers == Qt::NoModifier ? Action::Paste
  1415. : Action::PasteBefore);
  1416. processCommand(m_tokens);
  1417. break;
  1418. }
  1419. break;
  1420. }
  1421. case Qt::Key_C:
  1422. {
  1423. if (modifiers == Qt::NoModifier) {
  1424. // c, change action.
  1425. tryGetRepeatToken(m_keys, m_tokens);
  1426. if (hasActionToken()) {
  1427. // This is another c, something like cc.
  1428. if (checkActionToken(Action::Change)) {
  1429. addRangeToken(Range::Line);
  1430. processCommand(m_tokens);
  1431. break;
  1432. } else {
  1433. // An invalid sequence.
  1434. break;
  1435. }
  1436. } else {
  1437. // The first c, an action.
  1438. addActionToken(Action::Change);
  1439. if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
  1440. // Movement will be ignored.
  1441. addMovementToken(Movement::Left);
  1442. processCommand(m_tokens);
  1443. break;
  1444. }
  1445. goto accept;
  1446. }
  1447. } else if (modifiers == Qt::ShiftModifier) {
  1448. tryGetRepeatToken(m_keys, m_tokens);
  1449. if (!hasActionToken() && m_mode == VimMode::Normal) {
  1450. // C, same as c$.
  1451. addActionToken(Action::Change);
  1452. addMovementToken(Movement::EndOfLine);
  1453. processCommand(m_tokens);
  1454. }
  1455. break;
  1456. } else if (VUtils::isControlModifierForVim(modifiers)) {
  1457. if (g_config->getVimExemptionKeys().contains('c')) {
  1458. // Let it be handled outside.
  1459. resetState();
  1460. goto exit;
  1461. }
  1462. }
  1463. break;
  1464. }
  1465. case Qt::Key_Less:
  1466. unindent = true;
  1467. // Fall through.
  1468. case Qt::Key_Greater:
  1469. {
  1470. if (modifiers == Qt::ShiftModifier) {
  1471. // >/<, Indent/Unindent.
  1472. tryGetRepeatToken(m_keys, m_tokens);
  1473. if (hasActionToken()) {
  1474. // This is another >/<, something like >>/<<.
  1475. if ((!unindent && checkActionToken(Action::Indent))
  1476. || (unindent && checkActionToken(Action::UnIndent))) {
  1477. addRangeToken(Range::Line);
  1478. processCommand(m_tokens);
  1479. break;
  1480. } else if (checkPendingKey(Key(Qt::Key_I))
  1481. || checkPendingKey(Key(Qt::Key_A))) {
  1482. // AngleBracketInner/AngleBracketAround.
  1483. Range range = Range::AngleBracketInner;
  1484. if (checkPendingKey(Key(Qt::Key_A))) {
  1485. range = Range::AngleBracketAround;
  1486. }
  1487. addRangeToken(range);
  1488. processCommand(m_tokens);
  1489. break;
  1490. }
  1491. } else {
  1492. // The first >/<, an Action.
  1493. addActionToken(unindent ? Action::UnIndent : Action::Indent);
  1494. if (checkMode(VimMode::Visual)
  1495. || checkMode(VimMode::VisualLine)) {
  1496. // Movement will be ignored.
  1497. addMovementToken(Movement::Left);
  1498. processCommand(m_tokens);
  1499. break;
  1500. }
  1501. goto accept;
  1502. }
  1503. }
  1504. break;
  1505. }
  1506. case Qt::Key_Equal:
  1507. {
  1508. if (modifiers == Qt::NoModifier) {
  1509. // =, AutoIndent.
  1510. tryGetRepeatToken(m_keys, m_tokens);
  1511. if (hasActionToken()) {
  1512. // ==.
  1513. if (checkActionToken(Action::AutoIndent)) {
  1514. addRangeToken(Range::Line);
  1515. processCommand(m_tokens);
  1516. break;
  1517. }
  1518. } else {
  1519. // The first =, an Action.
  1520. addActionToken(Action::AutoIndent);
  1521. if (checkMode(VimMode::Visual)
  1522. || checkMode(VimMode::VisualLine)) {
  1523. // Movement will be ignored.
  1524. addMovementToken(Movement::Left);
  1525. processCommand(m_tokens);
  1526. break;
  1527. }
  1528. goto accept;
  1529. }
  1530. }
  1531. break;
  1532. }
  1533. case Qt::Key_F:
  1534. {
  1535. if (m_mode == VimMode::VisualLine) {
  1536. break;
  1537. }
  1538. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1539. // f/F, find forward/backward within a block.
  1540. tryGetRepeatToken(m_keys, m_tokens);
  1541. if (m_keys.isEmpty()) {
  1542. m_keys.append(keyInfo);
  1543. goto accept;
  1544. }
  1545. break;
  1546. }
  1547. break;
  1548. }
  1549. case Qt::Key_T:
  1550. {
  1551. if (m_mode == VimMode::VisualLine) {
  1552. break;
  1553. }
  1554. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1555. // t/T, find till forward/backward within a block.
  1556. tryGetRepeatToken(m_keys, m_tokens);
  1557. if (m_keys.isEmpty()) {
  1558. m_keys.append(keyInfo);
  1559. goto accept;
  1560. } else if (modifiers == Qt::NoModifier && checkPendingKey(Key(Qt::Key_Z))) {
  1561. // zt, redraw to make a certain line the top of window.
  1562. addActionToken(Action::RedrawAtTop);
  1563. processCommand(m_tokens);
  1564. break;
  1565. }
  1566. break;
  1567. }
  1568. break;
  1569. }
  1570. case Qt::Key_Comma:
  1571. {
  1572. if (m_mode == VimMode::VisualLine) {
  1573. break;
  1574. }
  1575. // ,, repeat last find target movement, but reversely.
  1576. tryGetRepeatToken(m_keys, m_tokens);
  1577. if (m_keys.isEmpty()) {
  1578. repeatLastFindMovement(true);
  1579. break;
  1580. }
  1581. break;
  1582. }
  1583. case Qt::Key_Semicolon:
  1584. {
  1585. if (m_mode == VimMode::VisualLine) {
  1586. break;
  1587. }
  1588. // ;, repeat last find target movement.
  1589. tryGetRepeatToken(m_keys, m_tokens);
  1590. if (m_keys.isEmpty()) {
  1591. repeatLastFindMovement(false);
  1592. break;
  1593. }
  1594. break;
  1595. }
  1596. case Qt::Key_R:
  1597. {
  1598. if (m_mode == VimMode::VisualLine) {
  1599. break;
  1600. }
  1601. if (VUtils::isControlModifierForVim(modifiers)) {
  1602. // Redo.
  1603. tryGetRepeatToken(m_keys, m_tokens);
  1604. if (!m_keys.isEmpty() || hasActionToken()) {
  1605. break;
  1606. }
  1607. addActionToken(Action::Redo);
  1608. processCommand(m_tokens);
  1609. break;
  1610. } else if (modifiers == Qt::NoModifier) {
  1611. // r, replace.
  1612. tryGetRepeatToken(m_keys, m_tokens);
  1613. if (m_keys.isEmpty() && !hasActionToken()) {
  1614. m_keys.append(keyInfo);
  1615. goto accept;
  1616. }
  1617. }
  1618. break;
  1619. }
  1620. case Qt::Key_Z:
  1621. {
  1622. if (modifiers == Qt::NoModifier) {
  1623. tryGetRepeatToken(m_keys, m_tokens);
  1624. if (m_keys.isEmpty() && !hasActionToken()) {
  1625. // First z, pend it.
  1626. m_keys.append(keyInfo);
  1627. goto accept;
  1628. } else if (checkPendingKey(keyInfo)) {
  1629. // zz, redraw to make a certain line the center of the window.
  1630. addActionToken(Action::RedrawAtCenter);
  1631. processCommand(m_tokens);
  1632. break;
  1633. }
  1634. break;
  1635. }
  1636. break;
  1637. }
  1638. case Qt::Key_Colon:
  1639. {
  1640. if (modifiers == Qt::ShiftModifier) {
  1641. if (m_keys.isEmpty()
  1642. && m_tokens.isEmpty()
  1643. && checkMode(VimMode::Normal)) {
  1644. emit commandLineTriggered(CommandLineType::Command);
  1645. }
  1646. }
  1647. break;
  1648. }
  1649. case Qt::Key_Percent:
  1650. {
  1651. if (modifiers == Qt::ShiftModifier) {
  1652. if (m_keys.isEmpty()) {
  1653. // %, FindPair movement.
  1654. tryAddMoveAction();
  1655. addMovementToken(Movement::FindPair);
  1656. processCommand(m_tokens);
  1657. break;
  1658. } else {
  1659. tryGetRepeatToken(m_keys, m_tokens);
  1660. if (m_keys.isEmpty() && hasRepeatToken()) {
  1661. // xx%, jump to a certain line (percentage of the documents).
  1662. // Change the repeat from percentage to line number.
  1663. Token *token = getRepeatToken();
  1664. int bn = percentageToBlockNumber(m_editor->documentW(), token->m_repeat);
  1665. if (bn == -1) {
  1666. break;
  1667. } else {
  1668. // Repeat of LineJump is based on 1.
  1669. token->m_repeat = bn + 1;
  1670. }
  1671. tryAddMoveAction();
  1672. addMovementToken(Movement::LineJump);
  1673. processCommand(m_tokens);
  1674. break;
  1675. }
  1676. }
  1677. break;
  1678. }
  1679. break;
  1680. }
  1681. case Qt::Key_M:
  1682. {
  1683. if (modifiers == Qt::NoModifier) {
  1684. if (m_keys.isEmpty() && m_tokens.isEmpty()) {
  1685. // m, creating a mark.
  1686. // We can create marks in Visual mode, too.
  1687. m_keys.append(keyInfo);
  1688. goto accept;
  1689. }
  1690. }
  1691. break;
  1692. }
  1693. case Qt::Key_Apostrophe:
  1694. {
  1695. if (modifiers == Qt::NoModifier) {
  1696. tryGetRepeatToken(m_keys, m_tokens);
  1697. if (checkPendingKey(Key(Qt::Key_I))
  1698. || checkPendingKey(Key(Qt::Key_A))) {
  1699. // QuoteInner/QuoteAround.
  1700. Range range = Range::QuoteInner;
  1701. if (checkPendingKey(Key(Qt::Key_A))) {
  1702. range = Range::QuoteAround;
  1703. }
  1704. addRangeToken(range);
  1705. processCommand(m_tokens);
  1706. break;
  1707. }
  1708. // ', jump to the start of line of a mark.
  1709. // Repeat is useless in this case.
  1710. if (m_keys.isEmpty()) {
  1711. m_keys.append(keyInfo);
  1712. goto accept;
  1713. }
  1714. }
  1715. break;
  1716. }
  1717. case Qt::Key_QuoteLeft:
  1718. {
  1719. if (modifiers == Qt::NoModifier) {
  1720. tryGetRepeatToken(m_keys, m_tokens);
  1721. if (checkPendingKey(Key(Qt::Key_I))
  1722. || checkPendingKey(Key(Qt::Key_A))) {
  1723. // BackQuoteInner/BackQuoteAround.
  1724. Range range = Range::BackQuoteInner;
  1725. if (checkPendingKey(Key(Qt::Key_A))) {
  1726. range = Range::BackQuoteAround;
  1727. }
  1728. addRangeToken(range);
  1729. processCommand(m_tokens);
  1730. break;
  1731. }
  1732. // `, jump to a mark.
  1733. // Repeat is useless in this case.
  1734. if (m_keys.isEmpty()) {
  1735. m_keys.append(keyInfo);
  1736. goto accept;
  1737. }
  1738. }
  1739. break;
  1740. }
  1741. case Qt::Key_ParenLeft:
  1742. // Fall through.
  1743. case Qt::Key_ParenRight:
  1744. {
  1745. if (modifiers == Qt::ShiftModifier) {
  1746. tryGetRepeatToken(m_keys, m_tokens);
  1747. if (checkPendingKey(Key(Qt::Key_I))
  1748. || checkPendingKey(Key(Qt::Key_A))) {
  1749. // ParenthesisInner/ParenthesisAround.
  1750. Range range = Range::ParenthesisInner;
  1751. if (checkPendingKey(Key(Qt::Key_A))) {
  1752. range = Range::ParenthesisAround;
  1753. }
  1754. addRangeToken(range);
  1755. processCommand(m_tokens);
  1756. break;
  1757. }
  1758. }
  1759. break;
  1760. }
  1761. case Qt::Key_BraceLeft:
  1762. {
  1763. if (modifiers == Qt::ShiftModifier) {
  1764. tryGetRepeatToken(m_keys, m_tokens);
  1765. if (checkPendingKey(Key(Qt::Key_I))
  1766. || checkPendingKey(Key(Qt::Key_A))) {
  1767. // BraceInner/BraceAround.
  1768. Range range = Range::BraceInner;
  1769. if (checkPendingKey(Key(Qt::Key_A))) {
  1770. range = Range::BraceAround;
  1771. }
  1772. addRangeToken(range);
  1773. processCommand(m_tokens);
  1774. break;
  1775. } else if (m_keys.isEmpty()) {
  1776. // {, ParagraphUp movement.
  1777. tryAddMoveAction();
  1778. addMovementToken(Movement::ParagraphUp);
  1779. processCommand(m_tokens);
  1780. } else if (!hasActionToken()
  1781. && checkPendingKey(Key(Qt::Key_BracketLeft))) {
  1782. // [{, goto previous title at one higher level.
  1783. if (checkMode(VimMode::Normal)) {
  1784. processTitleJump(m_tokens, false, -1);
  1785. }
  1786. }
  1787. break;
  1788. }
  1789. break;
  1790. }
  1791. case Qt::Key_BraceRight:
  1792. {
  1793. if (modifiers == Qt::ShiftModifier) {
  1794. tryGetRepeatToken(m_keys, m_tokens);
  1795. if (checkPendingKey(Key(Qt::Key_I))
  1796. || checkPendingKey(Key(Qt::Key_A))) {
  1797. // BraceInner/BraceAround.
  1798. Range range = Range::BraceInner;
  1799. if (checkPendingKey(Key(Qt::Key_A))) {
  1800. range = Range::BraceAround;
  1801. }
  1802. addRangeToken(range);
  1803. processCommand(m_tokens);
  1804. break;
  1805. } else if (m_keys.isEmpty()) {
  1806. // }, ParagraphDown movement.
  1807. tryAddMoveAction();
  1808. addMovementToken(Movement::ParagraphDown);
  1809. processCommand(m_tokens);
  1810. } else if (!hasActionToken()
  1811. && checkPendingKey(Key(Qt::Key_BracketRight))) {
  1812. // ]}, goto next title at one higher level.
  1813. if (checkMode(VimMode::Normal)) {
  1814. processTitleJump(m_tokens, true, -1);
  1815. }
  1816. }
  1817. break;
  1818. }
  1819. break;
  1820. }
  1821. case Qt::Key_AsciiTilde:
  1822. {
  1823. if (modifiers == Qt::ShiftModifier) {
  1824. tryGetRepeatToken(m_keys, m_tokens);
  1825. if (hasActionToken() || !m_keys.isEmpty()) {
  1826. break;
  1827. }
  1828. // Reverse the case.
  1829. addActionToken(Action::ReverseCase);
  1830. processCommand(m_tokens);
  1831. break;
  1832. }
  1833. break;
  1834. }
  1835. case Qt::Key_Slash:
  1836. {
  1837. if (modifiers == Qt::NoModifier) {
  1838. if (m_tokens.isEmpty()
  1839. && m_keys.isEmpty()
  1840. && checkMode(VimMode::Normal)) {
  1841. emit commandLineTriggered(CommandLineType::SearchForward);
  1842. }
  1843. }
  1844. break;
  1845. }
  1846. case Qt::Key_Question:
  1847. {
  1848. if (modifiers == Qt::ShiftModifier) {
  1849. if (m_tokens.isEmpty()
  1850. && m_keys.isEmpty()
  1851. && checkMode(VimMode::Normal)) {
  1852. emit commandLineTriggered(CommandLineType::SearchBackward);
  1853. }
  1854. }
  1855. break;
  1856. }
  1857. case Qt::Key_N:
  1858. {
  1859. if (modifiers == Qt::NoModifier || modifiers == Qt::ShiftModifier) {
  1860. // n, FindNext/FindPrevious movement.
  1861. tryGetRepeatToken(m_keys, m_tokens);
  1862. if (!m_keys.isEmpty()) {
  1863. break;
  1864. }
  1865. Movement mm = Movement::FindNext;
  1866. if (modifiers == Qt::ShiftModifier) {
  1867. mm = Movement::FindPrevious;
  1868. }
  1869. tryAddMoveAction();
  1870. addMovementToken(mm);
  1871. processCommand(m_tokens);
  1872. }
  1873. break;
  1874. }
  1875. case Qt::Key_Asterisk:
  1876. {
  1877. if (modifiers == Qt::ShiftModifier) {
  1878. // *, FindNextWordUnderCursor movement.
  1879. tryGetRepeatToken(m_keys, m_tokens);
  1880. if (!m_keys.isEmpty()) {
  1881. break;
  1882. }
  1883. tryAddMoveAction();
  1884. addMovementToken(Movement::FindNextWordUnderCursor);
  1885. processCommand(m_tokens);
  1886. }
  1887. break;
  1888. }
  1889. case Qt::Key_NumberSign:
  1890. {
  1891. if (modifiers == Qt::ShiftModifier) {
  1892. // #, FindPreviousWordUnderCursor movement.
  1893. tryGetRepeatToken(m_keys, m_tokens);
  1894. if (!m_keys.isEmpty()) {
  1895. break;
  1896. }
  1897. tryAddMoveAction();
  1898. addMovementToken(Movement::FindPreviousWordUnderCursor);
  1899. processCommand(m_tokens);
  1900. }
  1901. break;
  1902. }
  1903. default:
  1904. break;
  1905. }
  1906. clear_accept:
  1907. resetState();
  1908. amendCursorPosition();
  1909. if (m_insertModeAfterCommand
  1910. && !checkMode(VimMode::Visual)
  1911. && !checkMode(VimMode::VisualLine)) {
  1912. m_insertModeAfterCommand = false;
  1913. setMode(VimMode::Insert);
  1914. }
  1915. m_editor->makeBlockVisible(m_editor->textCursorW().block());
  1916. accept:
  1917. ret = true;
  1918. // Only alter the autoIndentPos when the key is handled by Vim.
  1919. if (p_autoIndentPos) {
  1920. *p_autoIndentPos = autoIndentPos;
  1921. }
  1922. exit:
  1923. m_resetPositionInBlock = resetPositionInBlock;
  1924. emit vimStatusUpdated(this);
  1925. return ret;
  1926. }
  1927. void VVim::resetState()
  1928. {
  1929. m_keys.clear();
  1930. m_tokens.clear();
  1931. m_pendingKeys.clear();
  1932. setCurrentRegisterName(c_unnamedRegister);
  1933. m_resetPositionInBlock = true;
  1934. m_registerPending = false;
  1935. }
  1936. VimMode VVim::getMode() const
  1937. {
  1938. return m_mode;
  1939. }
  1940. void VVim::setMode(VimMode p_mode, bool p_clearSelection, int p_position)
  1941. {
  1942. if (m_mode != p_mode) {
  1943. QTextCursor cursor = m_editor->textCursorW();
  1944. int position = p_position;
  1945. if (position == -1) {
  1946. if (m_mode == VimMode::Visual
  1947. && p_mode == VimMode::Normal
  1948. && cursor.position() > cursor.anchor()) {
  1949. position = cursor.position() - 1;
  1950. } else if (m_mode == VimMode::Insert
  1951. && p_mode == VimMode::Normal
  1952. && !cursor.atBlockStart()) {
  1953. position = cursor.position() - 1;
  1954. if (position < 0) {
  1955. position = 0;
  1956. }
  1957. }
  1958. }
  1959. if (p_clearSelection) {
  1960. clearSelection();
  1961. }
  1962. if (p_mode == VimMode::Insert) {
  1963. m_editor->setInputMethodEnabled(true);
  1964. } else if (g_config->getEnableSmartImInVimMode()) {
  1965. m_editor->setInputMethodEnabled(false);
  1966. }
  1967. m_mode = p_mode;
  1968. resetState();
  1969. VMdEditor *mdEditor = dynamic_cast<VMdEditor *>(m_editor);
  1970. switch (m_mode) {
  1971. case VimMode::Insert:
  1972. setCursorBlockMode(m_editor, CursorBlock::None);
  1973. if (mdEditor) {
  1974. mdEditor->setHighlightCursorLineBlockEnabled(false);
  1975. }
  1976. break;
  1977. case VimMode::Visual:
  1978. m_positionBeforeVisualMode = cursor.anchor();
  1979. V_FALLTHROUGH;
  1980. default:
  1981. setCursorBlockMode(m_editor, CursorBlock::RightSide);
  1982. if (mdEditor && g_config->getHighlightCursorLine()) {
  1983. QString color;
  1984. if (m_mode == VimMode::Normal) {
  1985. color = g_config->getEditorVimNormalBg();
  1986. } else {
  1987. color = g_config->getEditorVimVisualBg();
  1988. }
  1989. mdEditor->setCursorLineBlockBg(color);
  1990. mdEditor->setHighlightCursorLineBlockEnabled(true);
  1991. }
  1992. break;
  1993. }
  1994. if (position != -1) {
  1995. cursor.setPosition(position);
  1996. m_editor->setTextCursorW(cursor);
  1997. }
  1998. amendCursorPosition();
  1999. emit modeChanged(m_mode);
  2000. emit vimStatusUpdated(this);
  2001. }
  2002. }
  2003. void VVim::processCommand(QList<Token> &p_tokens)
  2004. {
  2005. if (p_tokens.isEmpty()) {
  2006. return;
  2007. }
  2008. V_ASSERT(p_tokens.at(0).isAction());
  2009. Token act = p_tokens.takeFirst();
  2010. switch (act.m_action) {
  2011. case Action::Move:
  2012. processMoveAction(p_tokens);
  2013. break;
  2014. case Action::Delete:
  2015. processDeleteAction(p_tokens);
  2016. break;
  2017. case Action::Copy:
  2018. processCopyAction(p_tokens);
  2019. break;
  2020. case Action::Paste:
  2021. processPasteAction(p_tokens, false);
  2022. break;
  2023. case Action::PasteBefore:
  2024. processPasteAction(p_tokens, true);
  2025. break;
  2026. case Action::Change:
  2027. processChangeAction(p_tokens);
  2028. break;
  2029. case Action::Indent:
  2030. processIndentAction(p_tokens, IndentType::Indent);
  2031. break;
  2032. case Action::UnIndent:
  2033. processIndentAction(p_tokens, IndentType::UnIndent);
  2034. break;
  2035. case Action::AutoIndent:
  2036. processIndentAction(p_tokens, IndentType::AutoIndent);
  2037. break;
  2038. case Action::ToLower:
  2039. processToLowerAction(p_tokens, true);
  2040. break;
  2041. case Action::ToUpper:
  2042. processToLowerAction(p_tokens, false);
  2043. break;
  2044. case Action::Undo:
  2045. processUndoAction(p_tokens);
  2046. break;
  2047. case Action::Redo:
  2048. processRedoAction(p_tokens);
  2049. break;
  2050. case Action::RedrawAtTop:
  2051. processRedrawLineAction(p_tokens, 0);
  2052. break;
  2053. case Action::RedrawAtCenter:
  2054. processRedrawLineAction(p_tokens, 1);
  2055. break;
  2056. case Action::RedrawAtBottom:
  2057. processRedrawLineAction(p_tokens, 2);
  2058. break;
  2059. case Action::JumpPreviousLocation:
  2060. processJumpLocationAction(p_tokens, false);
  2061. break;
  2062. case Action::JumpNextLocation:
  2063. processJumpLocationAction(p_tokens, true);
  2064. break;
  2065. case Action::Replace:
  2066. processReplaceAction(p_tokens);
  2067. break;
  2068. case Action::ReverseCase:
  2069. processReverseCaseAction(p_tokens);
  2070. break;
  2071. case Action::Join:
  2072. processJoinAction(p_tokens, true);
  2073. break;
  2074. case Action::JoinNoModification:
  2075. processJoinAction(p_tokens, false);
  2076. break;
  2077. default:
  2078. p_tokens.clear();
  2079. break;
  2080. }
  2081. Q_ASSERT(p_tokens.isEmpty());
  2082. }
  2083. int VVim::numberFromKeySequence(const QList<Key> &p_keys)
  2084. {
  2085. int num = 0;
  2086. for (auto const & key : p_keys) {
  2087. if (key.isDigit()) {
  2088. num = num * 10 + key.toDigit();
  2089. } else {
  2090. return -1;
  2091. }
  2092. }
  2093. return num == 0 ? -1 : num;
  2094. }
  2095. bool VVim::tryGetRepeatToken(QList<Key> &p_keys, QList<Token> &p_tokens)
  2096. {
  2097. if (!p_keys.isEmpty()) {
  2098. int repeat = numberFromKeySequence(p_keys);
  2099. if (repeat != -1) {
  2100. p_tokens.append(Token(repeat));
  2101. p_keys.clear();
  2102. return true;
  2103. }
  2104. }
  2105. return false;
  2106. }
  2107. void VVim::processMoveAction(QList<Token> &p_tokens)
  2108. {
  2109. // Only moving left/right could change this.
  2110. static int positionInBlock = 0;
  2111. Token to = p_tokens.takeFirst();
  2112. V_ASSERT(to.isRepeat() || to.isMovement());
  2113. Token mvToken;
  2114. int repeat = -1;
  2115. if (to.isRepeat()) {
  2116. repeat = to.m_repeat;
  2117. mvToken = p_tokens.takeFirst();
  2118. } else {
  2119. mvToken = to;
  2120. }
  2121. if (!mvToken.isMovement() || !p_tokens.isEmpty()) {
  2122. p_tokens.clear();
  2123. return;
  2124. }
  2125. QTextCursor cursor = m_editor->textCursorW();
  2126. if (m_resetPositionInBlock) {
  2127. positionInBlock = cursor.positionInBlock();
  2128. }
  2129. QTextCursor::MoveMode moveMode = (m_mode == VimMode::Visual
  2130. || m_mode == VimMode::VisualLine)
  2131. ? QTextCursor::KeepAnchor
  2132. : QTextCursor::MoveAnchor;
  2133. bool hasMoved = processMovement(cursor, moveMode, mvToken, repeat);
  2134. if (hasMoved) {
  2135. // Maintain positionInBlock.
  2136. switch (mvToken.m_movement) {
  2137. case Movement::Left:
  2138. case Movement::Right:
  2139. positionInBlock = cursor.positionInBlock();
  2140. break;
  2141. case Movement::Up:
  2142. case Movement::Down:
  2143. case Movement::PageUp:
  2144. case Movement::PageDown:
  2145. case Movement::HalfPageUp:
  2146. case Movement::HalfPageDown:
  2147. setCursorPositionInBlock(cursor, positionInBlock, moveMode);
  2148. break;
  2149. default:
  2150. break;
  2151. }
  2152. if (checkMode(VimMode::VisualLine)) {
  2153. expandSelectionToWholeLines(cursor);
  2154. } else if (checkMode(VimMode::Visual)) {
  2155. maintainSelectionInVisualMode(&cursor);
  2156. }
  2157. m_editor->setTextCursorW(cursor);
  2158. }
  2159. }
  2160. bool VVim::processMovement(QTextCursor &p_cursor,
  2161. QTextCursor::MoveMode p_moveMode,
  2162. const Token &p_token,
  2163. int p_repeat)
  2164. {
  2165. V_ASSERT(p_token.isMovement());
  2166. bool hasMoved = false;
  2167. bool inclusive = true;
  2168. bool forward = true;
  2169. QTextDocument *doc = p_cursor.document();
  2170. switch (p_token.m_movement) {
  2171. case Movement::Left:
  2172. {
  2173. if (p_repeat == -1) {
  2174. p_repeat = 1;
  2175. }
  2176. int pib = p_cursor.positionInBlock();
  2177. p_repeat = qMin(pib, p_repeat);
  2178. if (p_repeat > 0) {
  2179. p_cursor.movePosition(QTextCursor::Left, p_moveMode, p_repeat);
  2180. hasMoved = true;
  2181. }
  2182. break;
  2183. }
  2184. case Movement::Right:
  2185. {
  2186. if (p_repeat == -1) {
  2187. p_repeat = 1;
  2188. }
  2189. if (checkMode(VimMode::Visual)) {
  2190. int pos = p_cursor.position();
  2191. if (pos == p_cursor.anchor() - 1 && pos == m_positionBeforeVisualMode) {
  2192. ++p_repeat;
  2193. }
  2194. }
  2195. int pib = p_cursor.positionInBlock();
  2196. int length = p_cursor.block().length();
  2197. if (length - pib <= p_repeat) {
  2198. p_repeat = length - pib - 1;
  2199. }
  2200. if (p_repeat > 0) {
  2201. p_cursor.movePosition(QTextCursor::Right, p_moveMode, p_repeat);
  2202. hasMoved = true;
  2203. }
  2204. break;
  2205. }
  2206. case Movement::Up:
  2207. {
  2208. if (p_repeat == -1) {
  2209. p_repeat = 1;
  2210. }
  2211. p_repeat = qMin(p_cursor.block().blockNumber(), p_repeat);
  2212. if (p_repeat > 0) {
  2213. p_cursor.movePosition(QTextCursor::PreviousBlock, p_moveMode, p_repeat);
  2214. hasMoved = true;
  2215. }
  2216. break;
  2217. }
  2218. case Movement::Down:
  2219. {
  2220. if (p_repeat == -1) {
  2221. p_repeat = 1;
  2222. }
  2223. int blockCount = doc->blockCount();
  2224. p_repeat = qMin(blockCount - 1 - p_cursor.block().blockNumber(), p_repeat);
  2225. if (p_repeat > 0) {
  2226. p_cursor.movePosition(QTextCursor::NextBlock, p_moveMode, p_repeat);
  2227. hasMoved = true;
  2228. }
  2229. break;
  2230. }
  2231. case Movement::VisualUp:
  2232. {
  2233. if (p_repeat == -1) {
  2234. p_repeat = 1;
  2235. }
  2236. p_cursor.movePosition(QTextCursor::Up, p_moveMode, p_repeat);
  2237. hasMoved = true;
  2238. break;
  2239. }
  2240. case Movement::VisualDown:
  2241. {
  2242. if (p_repeat == -1) {
  2243. p_repeat = 1;
  2244. }
  2245. p_cursor.movePosition(QTextCursor::Down, p_moveMode, p_repeat);
  2246. hasMoved = true;
  2247. break;
  2248. }
  2249. case Movement::PageUp:
  2250. {
  2251. if (p_repeat == -1) {
  2252. p_repeat = 1;
  2253. }
  2254. int blockStep = blockCountOfPageStep() * p_repeat;
  2255. int block = p_cursor.block().blockNumber();
  2256. block = qMax(0, block - blockStep);
  2257. p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
  2258. hasMoved = true;
  2259. break;
  2260. }
  2261. case Movement::PageDown:
  2262. {
  2263. if (p_repeat == -1) {
  2264. p_repeat = 1;
  2265. }
  2266. int blockStep = blockCountOfPageStep() * p_repeat;
  2267. int block = p_cursor.block().blockNumber();
  2268. block = qMin(block + blockStep, doc->blockCount() - 1);
  2269. p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
  2270. hasMoved = true;
  2271. break;
  2272. }
  2273. case Movement::HalfPageUp:
  2274. {
  2275. if (p_repeat == -1) {
  2276. p_repeat = 1;
  2277. }
  2278. int blockStep = blockCountOfPageStep();
  2279. int halfBlockStep = qMax(blockStep / 2, 1);
  2280. blockStep = p_repeat * halfBlockStep;
  2281. int block = p_cursor.block().blockNumber();
  2282. block = qMax(0, block - blockStep);
  2283. p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
  2284. hasMoved = true;
  2285. break;
  2286. }
  2287. case Movement::HalfPageDown:
  2288. {
  2289. if (p_repeat == -1) {
  2290. p_repeat = 1;
  2291. }
  2292. int blockStep = blockCountOfPageStep();
  2293. int halfBlockStep = qMax(blockStep / 2, 1);
  2294. blockStep = p_repeat * halfBlockStep;
  2295. int block = p_cursor.block().blockNumber();
  2296. block = qMin(block + blockStep, doc->blockCount() - 1);
  2297. p_cursor.setPosition(doc->findBlockByNumber(block).position(), p_moveMode);
  2298. hasMoved = true;
  2299. break;
  2300. }
  2301. case Movement::StartOfLine:
  2302. {
  2303. Q_ASSERT(p_repeat == -1);
  2304. // Start of the Line (block).
  2305. if (!p_cursor.atBlockStart()) {
  2306. p_cursor.movePosition(QTextCursor::StartOfBlock, p_moveMode, 1);
  2307. hasMoved = true;
  2308. }
  2309. break;
  2310. }
  2311. case Movement::StartOfVisualLine:
  2312. {
  2313. // Start of the visual line.
  2314. if (!p_cursor.atBlockStart()) {
  2315. p_cursor.movePosition(QTextCursor::StartOfLine, p_moveMode, 1);
  2316. hasMoved = true;
  2317. }
  2318. break;
  2319. }
  2320. case Movement::EndOfLine:
  2321. {
  2322. // End of line (block).
  2323. if (p_repeat == -1) {
  2324. p_repeat = 1;
  2325. } else if (p_repeat > 1) {
  2326. // Move down (p_repeat-1) blocks.
  2327. p_cursor.movePosition(QTextCursor::NextBlock, p_moveMode, p_repeat - 1);
  2328. }
  2329. // Move to the end of block.
  2330. p_cursor.movePosition(QTextCursor::EndOfBlock, p_moveMode, 1);
  2331. hasMoved = true;
  2332. break;
  2333. }
  2334. case Movement::FirstCharacter:
  2335. {
  2336. // p_repeat is not considered in this command.
  2337. // If all the block is space, just move to the end of block; otherwise,
  2338. // move to the first non-space character.
  2339. VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
  2340. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2341. // Move one character forward.
  2342. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2343. }
  2344. hasMoved = true;
  2345. break;
  2346. }
  2347. case Movement::LineJump:
  2348. {
  2349. // Jump to the first non-space character of @p_repeat line (block).
  2350. V_ASSERT(p_repeat > 0);
  2351. // Record current location.
  2352. m_locations.addLocation(p_cursor);
  2353. // @p_repeat starts from 1 while block number starts from 0.
  2354. QTextBlock block = doc->findBlockByNumber(p_repeat - 1);
  2355. if (block.isValid()) {
  2356. p_cursor.setPosition(block.position(), p_moveMode);
  2357. } else {
  2358. // Go beyond the document.
  2359. p_cursor.movePosition(QTextCursor::End, p_moveMode, 1);
  2360. }
  2361. VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
  2362. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2363. // Move one character forward.
  2364. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2365. }
  2366. hasMoved = true;
  2367. break;
  2368. }
  2369. case Movement::StartOfDocument:
  2370. {
  2371. // Jump to the first non-space character of the start of the document.
  2372. V_ASSERT(p_repeat == -1);
  2373. // Record current location.
  2374. m_locations.addLocation(p_cursor);
  2375. p_cursor.movePosition(QTextCursor::Start, p_moveMode, 1);
  2376. VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
  2377. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2378. // Move one character forward.
  2379. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2380. }
  2381. hasMoved = true;
  2382. break;
  2383. }
  2384. case Movement::EndOfDocument:
  2385. {
  2386. // Jump to the first non-space character of the end of the document.
  2387. V_ASSERT(p_repeat == -1);
  2388. // Record current location.
  2389. m_locations.addLocation(p_cursor);
  2390. p_cursor.movePosition(QTextCursor::End, p_moveMode, 1);
  2391. VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
  2392. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2393. // Move one character forward.
  2394. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2395. }
  2396. hasMoved = true;
  2397. break;
  2398. }
  2399. case Movement::WordForward:
  2400. {
  2401. // Go to the start of next word.
  2402. if (p_repeat == -1) {
  2403. p_repeat = 1;
  2404. }
  2405. while (p_repeat) {
  2406. if (p_cursor.atEnd()) {
  2407. break;
  2408. }
  2409. p_cursor.movePosition(QTextCursor::NextWord, p_moveMode);
  2410. if (p_cursor.atBlockEnd()) {
  2411. // dw/yw/cw will stop at the end of the line.
  2412. if (p_repeat == 1
  2413. && checkMode(VimMode::Normal)
  2414. && p_moveMode == QTextCursor::KeepAnchor) {
  2415. --p_repeat;
  2416. }
  2417. continue;
  2418. } else if (doc->characterAt(p_cursor.position()).isSpace()
  2419. || VEditUtils::isSpaceBlock(p_cursor.block())) {
  2420. continue;
  2421. }
  2422. --p_repeat;
  2423. }
  2424. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2425. // Move one character forward.
  2426. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2427. }
  2428. hasMoved = true;
  2429. break;
  2430. }
  2431. case Movement::WORDForward:
  2432. {
  2433. // Go to the start of next WORD.
  2434. if (p_repeat == -1) {
  2435. p_repeat = 1;
  2436. }
  2437. while (p_repeat) {
  2438. if (p_cursor.atEnd()) {
  2439. break;
  2440. }
  2441. int start, end;
  2442. // [start, end] is current WORD.
  2443. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2444. // Move cursor to end of current WORD.
  2445. p_cursor.setPosition(end, p_moveMode);
  2446. if (p_repeat == 1
  2447. && checkMode(VimMode::Normal)
  2448. && p_moveMode == QTextCursor::KeepAnchor) {
  2449. // dW/yW/cW will stop at the end of the line.
  2450. moveCursorAcrossSpaces(p_cursor, p_moveMode, true, true);
  2451. if (p_cursor.atBlockEnd()) {
  2452. --p_repeat;
  2453. continue;
  2454. }
  2455. }
  2456. // Skip spaces.
  2457. moveCursorAcrossSpaces(p_cursor, p_moveMode, true);
  2458. if (p_cursor.atBlockEnd()) {
  2459. continue;
  2460. }
  2461. --p_repeat;
  2462. }
  2463. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2464. // Move one character forward.
  2465. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2466. }
  2467. hasMoved = true;
  2468. break;
  2469. }
  2470. case Movement::ForwardEndOfWord:
  2471. {
  2472. // Go to the end of current word or next word.
  2473. if (p_repeat == -1) {
  2474. p_repeat = 1;
  2475. }
  2476. int pos = p_cursor.position();
  2477. bool leftSideBefore = useLeftSideOfCursor(p_cursor);
  2478. // First move to the end of current word.
  2479. p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode, 1);
  2480. if (p_cursor.position() > pos) {
  2481. if (p_cursor.position() > pos + 1 || (leftSideBefore && useLeftSideOfCursor(p_cursor))) {
  2482. // We did move.
  2483. p_repeat -= 1;
  2484. }
  2485. }
  2486. while (p_repeat) {
  2487. if (p_cursor.atEnd()) {
  2488. break;
  2489. }
  2490. pos = p_cursor.position();
  2491. p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
  2492. if (p_cursor.position() == pos) {
  2493. // Need to move to the start of next word.
  2494. p_cursor.movePosition(QTextCursor::NextWord, p_moveMode);
  2495. if (p_cursor.atBlockEnd()) {
  2496. continue;
  2497. }
  2498. p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
  2499. if (p_cursor.atBlockStart()) {
  2500. continue;
  2501. }
  2502. }
  2503. --p_repeat;
  2504. }
  2505. // Move one character back.
  2506. if (!p_cursor.atBlockStart()) {
  2507. if (p_moveMode == QTextCursor::MoveAnchor
  2508. || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))) {
  2509. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2510. }
  2511. }
  2512. hasMoved = true;
  2513. break;
  2514. }
  2515. case Movement::ForwardEndOfWORD:
  2516. {
  2517. // Go to the end of current WORD or next WORD.
  2518. if (p_repeat == -1) {
  2519. p_repeat = 1;
  2520. }
  2521. int pos = p_cursor.position();
  2522. bool leftSideBefore = useLeftSideOfCursor(p_cursor);
  2523. while (p_repeat) {
  2524. if (p_cursor.atEnd()) {
  2525. break;
  2526. }
  2527. // Skip spaces.
  2528. moveCursorAcrossSpaces(p_cursor, p_moveMode, true);
  2529. if (p_cursor.atBlockEnd()) {
  2530. continue;
  2531. }
  2532. int start, end;
  2533. // [start, end] is current WORD.
  2534. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2535. // Move cursor to the end of current WORD.
  2536. p_cursor.setPosition(end, p_moveMode);
  2537. if (p_cursor.position() > pos + 1
  2538. || (leftSideBefore && useLeftSideOfCursor(p_cursor))) {
  2539. --p_repeat;
  2540. }
  2541. }
  2542. // Move one character back.
  2543. if (!p_cursor.atBlockStart()) {
  2544. if (p_moveMode == QTextCursor::MoveAnchor
  2545. || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))) {
  2546. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2547. }
  2548. }
  2549. hasMoved = true;
  2550. break;
  2551. }
  2552. case Movement::WordBackward:
  2553. {
  2554. // Go to the start of previous word or current word.
  2555. if (p_repeat == -1) {
  2556. p_repeat = 1;
  2557. }
  2558. int pos = p_cursor.position();
  2559. // first move to the start of current word.
  2560. p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
  2561. if (p_cursor.position() == pos && useLeftSideOfCursor(p_cursor)) {
  2562. // Cursor did not move and now is at the start of a word.
  2563. // Actually we are using the left side character so we need to move
  2564. // to previous word.
  2565. p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
  2566. }
  2567. if (p_cursor.position() < pos) {
  2568. if (p_cursor.position() < pos - 1 || !useLeftSideOfCursor(p_cursor)) {
  2569. // We did move.
  2570. p_repeat -= 1;
  2571. }
  2572. }
  2573. while (p_repeat) {
  2574. if (p_cursor.atStart()) {
  2575. break;
  2576. }
  2577. pos = p_cursor.position();
  2578. p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
  2579. if (p_cursor.position() == pos) {
  2580. // Need to move to the start of previous word.
  2581. p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
  2582. if (p_cursor.atBlockEnd()) {
  2583. continue;
  2584. }
  2585. if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
  2586. continue;
  2587. }
  2588. }
  2589. --p_repeat;
  2590. }
  2591. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2592. // Move one character forward.
  2593. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2594. }
  2595. hasMoved = true;
  2596. break;
  2597. }
  2598. case Movement::WORDBackward:
  2599. {
  2600. // Go to the start of previous WORD or current WORD.
  2601. if (p_repeat == -1) {
  2602. p_repeat = 1;
  2603. }
  2604. int pos = p_cursor.position();
  2605. while (p_repeat) {
  2606. if (p_cursor.atStart()) {
  2607. break;
  2608. }
  2609. // Skip Spaces.
  2610. moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
  2611. if (p_cursor.atBlockStart()) {
  2612. continue;
  2613. }
  2614. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2615. int start, end;
  2616. // [start, end] is current WORD.
  2617. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2618. // Move cursor to the start of current WORD.
  2619. p_cursor.setPosition(start, p_moveMode);
  2620. if (p_cursor.position() < pos - 1 || !useLeftSideOfCursor(p_cursor)) {
  2621. --p_repeat;
  2622. }
  2623. }
  2624. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2625. // Move one character forward.
  2626. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2627. }
  2628. hasMoved = true;
  2629. break;
  2630. }
  2631. case Movement::BackwardEndOfWord:
  2632. {
  2633. // Go to the end of previous word.
  2634. if (p_repeat == -1) {
  2635. p_repeat = 1;
  2636. }
  2637. if (useLeftSideOfCursor(p_cursor)) {
  2638. // Move one previous char.
  2639. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2640. }
  2641. int pos = p_cursor.position();
  2642. // Move across spaces backward.
  2643. moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
  2644. int start, end;
  2645. VEditUtils::findCurrentWord(p_cursor, start, end);
  2646. if (pos != p_cursor.position() || start == end || start == pos) {
  2647. // We are alreay at the end of previous word.
  2648. --p_repeat;
  2649. // Move it to the start of current word.
  2650. p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
  2651. } else {
  2652. p_cursor.movePosition(QTextCursor::StartOfWord, p_moveMode);
  2653. }
  2654. while (p_repeat) {
  2655. if (p_cursor.atStart()) {
  2656. break;
  2657. }
  2658. p_cursor.movePosition(QTextCursor::PreviousWord, p_moveMode);
  2659. if (p_cursor.atBlockEnd()) {
  2660. continue;
  2661. }
  2662. if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
  2663. continue;
  2664. }
  2665. --p_repeat;
  2666. }
  2667. // Move it to the end.
  2668. p_cursor.movePosition(QTextCursor::EndOfWord, p_moveMode);
  2669. // Move one character back.
  2670. if (!p_cursor.atBlockStart()) {
  2671. if (p_moveMode == QTextCursor::MoveAnchor
  2672. || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))
  2673. || p_cursor.position() <= p_cursor.anchor()) {
  2674. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2675. }
  2676. }
  2677. hasMoved = true;
  2678. break;
  2679. }
  2680. case Movement::BackwardEndOfWORD:
  2681. {
  2682. // Go to the end of previous WORD.
  2683. if (p_repeat == -1) {
  2684. p_repeat = 1;
  2685. }
  2686. if (useLeftSideOfCursor(p_cursor)) {
  2687. // Move one previous char.
  2688. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2689. }
  2690. int pos = p_cursor.position();
  2691. // Move across spaces backward.
  2692. moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
  2693. int start, end;
  2694. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2695. if (pos != p_cursor.position() || start == end) {
  2696. // We are alreay at the end of previous WORD.
  2697. --p_repeat;
  2698. // Move it to the start of current WORD.
  2699. p_cursor.setPosition(start, p_moveMode);
  2700. } else {
  2701. // Move it to the start of current WORD.
  2702. p_cursor.setPosition(start, p_moveMode);
  2703. }
  2704. while (p_repeat) {
  2705. if (p_cursor.atStart()) {
  2706. break;
  2707. }
  2708. moveCursorAcrossSpaces(p_cursor, p_moveMode, false);
  2709. if (p_cursor.atBlockStart()) {
  2710. continue;
  2711. }
  2712. if (p_cursor.atBlockStart() && doc->characterAt(p_cursor.position()).isSpace()) {
  2713. continue;
  2714. }
  2715. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2716. p_cursor.setPosition(start, p_moveMode);
  2717. --p_repeat;
  2718. }
  2719. // Move it to the end.
  2720. VEditUtils::findCurrentWORD(p_cursor, start, end);
  2721. p_cursor.setPosition(end, p_moveMode);
  2722. // Move one character back.
  2723. if (!p_cursor.atBlockStart()) {
  2724. if (p_moveMode == QTextCursor::MoveAnchor
  2725. || (checkMode(VimMode::Visual) && !useLeftSideOfCursor(p_cursor))
  2726. || p_cursor.position() <= p_cursor.anchor()) {
  2727. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2728. }
  2729. }
  2730. hasMoved = true;
  2731. break;
  2732. }
  2733. case Movement::TillBackward:
  2734. forward = false;
  2735. // Fall through.
  2736. case Movement::TillForward:
  2737. inclusive = false;
  2738. goto handle_target;
  2739. case Movement::FindBackward:
  2740. forward = false;
  2741. // Fall through.
  2742. case Movement::FindForward:
  2743. {
  2744. handle_target:
  2745. if (p_repeat == -1) {
  2746. p_repeat = 1;
  2747. }
  2748. const Key &key = p_token.m_key;
  2749. QChar target = keyToChar(key.m_key, key.m_modifiers);
  2750. if (!target.isNull()) {
  2751. hasMoved = VEditUtils::findTargetWithinBlock(p_cursor,
  2752. p_moveMode,
  2753. target,
  2754. forward,
  2755. inclusive,
  2756. useLeftSideOfCursor(p_cursor),
  2757. p_repeat);
  2758. }
  2759. break;
  2760. }
  2761. case Movement::MarkJump:
  2762. // Fall through.
  2763. case Movement::MarkJumpLine:
  2764. {
  2765. // repeat is useless here.
  2766. const Key &key = p_token.m_key;
  2767. QChar target = keyToChar(key.m_key, key.m_modifiers);
  2768. Location loc = m_marks.getMarkLocation(target);
  2769. if (loc.isValid()) {
  2770. if (loc.m_blockNumber >= doc->blockCount()) {
  2771. // Invalid block number.
  2772. message(tr("Mark not set"));
  2773. m_marks.clearMark(target);
  2774. break;
  2775. }
  2776. // Different from Vim:
  2777. // We just use the block number for mark, so if we delete the line
  2778. // where the mark locates, we could not detect if it is set or not.
  2779. QTextBlock block = doc->findBlockByNumber(loc.m_blockNumber);
  2780. p_cursor.setPosition(block.position(), p_moveMode);
  2781. if (p_token.m_movement == Movement::MarkJump) {
  2782. setCursorPositionInBlock(p_cursor, loc.m_positionInBlock, p_moveMode);
  2783. } else {
  2784. // Jump to the first non-space character.
  2785. VEditUtils::moveCursorFirstNonSpaceCharacter(p_cursor, p_moveMode);
  2786. }
  2787. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2788. // Move one character forward.
  2789. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2790. }
  2791. hasMoved = true;
  2792. }
  2793. break;
  2794. }
  2795. case Movement::FindPair:
  2796. {
  2797. Q_ASSERT(p_repeat == -1);
  2798. int anchor = p_cursor.anchor();
  2799. int position = p_cursor.position();
  2800. QList<QPair<QChar, QChar>> pairs;
  2801. pairs.append(QPair<QChar, QChar>('(', ')'));
  2802. pairs.append(QPair<QChar, QChar>('[', ']'));
  2803. pairs.append(QPair<QChar, QChar>('{', '}'));
  2804. // Find forward for a pair (), [], and {}.
  2805. QList<QChar> targets;
  2806. for (auto const & pair : pairs) {
  2807. targets.append(pair.first);
  2808. targets.append(pair.second);
  2809. }
  2810. // First check if current char hits the targets.
  2811. bool useLeftSideBefore = useLeftSideOfCursor(p_cursor);
  2812. QChar ch = doc->characterAt(useLeftSideBefore ? position - 1
  2813. : position);
  2814. int idx = targets.indexOf(ch);
  2815. if (idx == -1) {
  2816. idx = VEditUtils::findTargetsWithinBlock(p_cursor,
  2817. targets,
  2818. true,
  2819. useLeftSideOfCursor(p_cursor),
  2820. true);
  2821. } else if (useLeftSideBefore) {
  2822. // Move one character back to let p_cursor position at the pair.
  2823. p_cursor.movePosition(QTextCursor::PreviousCharacter, p_moveMode);
  2824. }
  2825. if (idx == -1) {
  2826. break;
  2827. }
  2828. idx /= 2;
  2829. int pairPosition = p_cursor.position();
  2830. bool ret = VEditUtils::selectPairTargetAround(p_cursor,
  2831. pairs.at(idx).first,
  2832. pairs.at(idx).second,
  2833. true,
  2834. true,
  2835. 1);
  2836. if (ret) {
  2837. // Found matched pair.
  2838. int first = p_cursor.position();
  2839. int second = p_cursor.anchor();
  2840. if (first > second) {
  2841. int tmp = first;
  2842. first = second;
  2843. second = tmp;
  2844. }
  2845. if (!(checkMode(VimMode::Normal) && p_moveMode == QTextCursor::KeepAnchor)) {
  2846. --second;
  2847. }
  2848. int target = first;
  2849. if (first == pairPosition) {
  2850. target = second;
  2851. }
  2852. if (anchor > target
  2853. && !p_cursor.atEnd()
  2854. && !useLeftSideOfCursor(p_cursor)) {
  2855. ++anchor;
  2856. }
  2857. p_cursor.setPosition(anchor);
  2858. p_cursor.setPosition(target, p_moveMode);
  2859. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2860. // Move one character forward.
  2861. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2862. }
  2863. hasMoved = true;
  2864. break;
  2865. } else {
  2866. // Restore the cursor position.
  2867. p_cursor.setPosition(anchor);
  2868. if (anchor != position) {
  2869. p_cursor.setPosition(position, QTextCursor::KeepAnchor);
  2870. }
  2871. }
  2872. break;
  2873. }
  2874. case Movement::FindPrevious:
  2875. forward = false;
  2876. // Fall through.
  2877. case Movement::FindNext:
  2878. {
  2879. if (p_repeat == -1) {
  2880. p_repeat = 1;
  2881. }
  2882. if (m_searchHistory.isEmpty()) {
  2883. break;
  2884. }
  2885. // Record current location.
  2886. m_locations.addLocation(p_cursor);
  2887. bool useLeftSideBefore = useLeftSideOfCursor(p_cursor);
  2888. const SearchItem &item = m_searchHistory.lastItem();
  2889. while (--p_repeat >= 0) {
  2890. bool found = m_editor->findText(item.m_text,
  2891. item.m_options,
  2892. forward ? item.m_forward : !item.m_forward,
  2893. &p_cursor,
  2894. p_moveMode,
  2895. useLeftSideBefore);
  2896. if (found) {
  2897. hasMoved = true;
  2898. useLeftSideBefore = false;
  2899. } else {
  2900. break;
  2901. }
  2902. }
  2903. if (hasMoved) {
  2904. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2905. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2906. }
  2907. }
  2908. break;
  2909. }
  2910. case Movement::FindPreviousWordUnderCursor:
  2911. forward = false;
  2912. // Fall through.
  2913. case Movement::FindNextWordUnderCursor:
  2914. {
  2915. if (p_repeat == -1) {
  2916. p_repeat = 1;
  2917. }
  2918. // Get current word under cursor.
  2919. // Different from Vim:
  2920. // We do not recognize a word as strict as Vim.
  2921. int start, end;
  2922. VEditUtils::findCurrentWord(p_cursor, start, end);
  2923. if (start == end) {
  2924. // Spaces, find next word.
  2925. QTextCursor cursor = p_cursor;
  2926. while (true) {
  2927. moveCursorAcrossSpaces(cursor, p_moveMode, true);
  2928. if (cursor.atEnd()) {
  2929. break;
  2930. }
  2931. if (!doc->characterAt(cursor.position()).isSpace()) {
  2932. VEditUtils::findCurrentWord(cursor, start, end);
  2933. Q_ASSERT(start != end);
  2934. break;
  2935. }
  2936. }
  2937. if (start == end) {
  2938. break;
  2939. }
  2940. }
  2941. QTextCursor cursor = p_cursor;
  2942. cursor.setPosition(start);
  2943. cursor.setPosition(end, QTextCursor::KeepAnchor);
  2944. QString text = cursor.selectedText();
  2945. if (text.isEmpty()) {
  2946. break;
  2947. }
  2948. // Record current location.
  2949. m_locations.addLocation(p_cursor);
  2950. p_cursor.setPosition(start, p_moveMode);
  2951. // Case-insensitive, non-regularexpression.
  2952. SearchItem item;
  2953. item.m_rawStr = text;
  2954. item.m_text = text;
  2955. item.m_forward = forward;
  2956. m_searchHistory.addItem(item);
  2957. m_searchHistory.resetIndex();
  2958. while (--p_repeat >= 0) {
  2959. hasMoved = m_editor->findText(item.m_text, item.m_options,
  2960. item.m_forward,
  2961. &p_cursor, p_moveMode);
  2962. }
  2963. Q_ASSERT(hasMoved);
  2964. if (!p_cursor.atEnd() && useLeftSideOfCursor(p_cursor)) {
  2965. p_cursor.movePosition(QTextCursor::NextCharacter, p_moveMode);
  2966. }
  2967. break;
  2968. }
  2969. case Movement::ParagraphUp:
  2970. forward = false;
  2971. // Fall through.
  2972. case Movement::ParagraphDown:
  2973. {
  2974. if (p_repeat == -1) {
  2975. p_repeat = 1;
  2976. }
  2977. // Record current location.
  2978. m_locations.addLocation(p_cursor);
  2979. int oriPos = p_cursor.position();
  2980. int position = VEditUtils::findNextEmptyBlock(p_cursor,
  2981. forward,
  2982. p_repeat);
  2983. if (position == -1) {
  2984. // No empty block. Move to the first/last character.
  2985. p_cursor.movePosition(forward ? QTextCursor::End : QTextCursor::Start,
  2986. p_moveMode);
  2987. hasMoved = p_cursor.position() != oriPos;
  2988. } else {
  2989. p_cursor.setPosition(position, p_moveMode);
  2990. hasMoved = true;
  2991. }
  2992. break;
  2993. }
  2994. default:
  2995. break;
  2996. }
  2997. return hasMoved;
  2998. }
  2999. bool VVim::selectRange(QTextCursor &p_cursor, const QTextDocument *p_doc,
  3000. Range p_range, int p_repeat)
  3001. {
  3002. bool hasMoved = false;
  3003. QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
  3004. bool around = false;
  3005. QChar opening;
  3006. QChar closing;
  3007. bool crossBlock = false;
  3008. bool multipleTargets = false;
  3009. Q_UNUSED(p_doc);
  3010. switch (p_range) {
  3011. case Range::Line:
  3012. {
  3013. // Visual mode, just select selected lines.
  3014. if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
  3015. expandSelectionToWholeLines(p_cursor);
  3016. hasMoved = true;
  3017. break;
  3018. }
  3019. // Current line and next (p_repeat - 1) lines.
  3020. if (p_repeat == -1) {
  3021. p_repeat = 1;
  3022. }
  3023. if (p_repeat > 1) {
  3024. p_cursor.movePosition(QTextCursor::NextBlock, moveMode, p_repeat - 1);
  3025. }
  3026. expandSelectionToWholeLines(p_cursor);
  3027. hasMoved = true;
  3028. break;
  3029. }
  3030. case Range::WordAround:
  3031. around = true;
  3032. // Fall through.
  3033. case Range::WordInner:
  3034. {
  3035. Q_ASSERT(p_repeat == -1);
  3036. bool spaces = false;
  3037. int start, end;
  3038. VEditUtils::findCurrentWord(p_cursor, start, end);
  3039. if (start == end) {
  3040. // Select the space between previous word and next word.
  3041. findCurrentSpace(p_cursor, start, end);
  3042. spaces = true;
  3043. }
  3044. if (start != end) {
  3045. p_cursor.setPosition(start, QTextCursor::MoveAnchor);
  3046. p_cursor.setPosition(end, moveMode);
  3047. hasMoved = true;
  3048. if (around) {
  3049. if (spaces) {
  3050. // Select the word by the end of spaces.
  3051. if (!p_cursor.atBlockEnd()) {
  3052. p_cursor.movePosition(QTextCursor::EndOfWord, moveMode);
  3053. }
  3054. } else {
  3055. // Select additional spaces at two ends.
  3056. expandSelectionAcrossSpacesWithinBlock(p_cursor);
  3057. }
  3058. }
  3059. }
  3060. break;
  3061. }
  3062. case Range::WORDAround:
  3063. around = true;
  3064. // Fall through.
  3065. case Range::WORDInner:
  3066. {
  3067. Q_ASSERT(p_repeat == -1);
  3068. bool spaces = false;
  3069. int start, end;
  3070. findCurrentSpace(p_cursor, start, end);
  3071. if (start == end) {
  3072. VEditUtils::findCurrentWORD(p_cursor, start, end);
  3073. } else {
  3074. // Select the space between previous WORD and next WORD.
  3075. spaces = true;
  3076. }
  3077. if (start != end) {
  3078. p_cursor.setPosition(start, QTextCursor::MoveAnchor);
  3079. p_cursor.setPosition(end, moveMode);
  3080. hasMoved = true;
  3081. if (around) {
  3082. if (spaces) {
  3083. // Select the WORD by the end of spaces.
  3084. if (!p_cursor.atBlockEnd()) {
  3085. // Skip spaces (mainly across block).
  3086. moveCursorAcrossSpaces(p_cursor, moveMode, true);
  3087. // [start, end] is current WORD.
  3088. VEditUtils::findCurrentWORD(p_cursor, start, end);
  3089. // Move cursor to the end of current WORD.
  3090. p_cursor.setPosition(end, moveMode);
  3091. }
  3092. } else {
  3093. // Select additional spaces at two ends.
  3094. expandSelectionAcrossSpacesWithinBlock(p_cursor);
  3095. }
  3096. }
  3097. }
  3098. break;
  3099. }
  3100. case Range::ParenthesisAround:
  3101. {
  3102. around = true;
  3103. opening = '(';
  3104. closing = ')';
  3105. crossBlock = true;
  3106. multipleTargets = true;
  3107. goto handlePairTarget;
  3108. }
  3109. case Range::ParenthesisInner:
  3110. {
  3111. around = false;
  3112. opening = '(';
  3113. closing = ')';
  3114. crossBlock = true;
  3115. multipleTargets = true;
  3116. goto handlePairTarget;
  3117. }
  3118. case Range::BracketAround:
  3119. {
  3120. around = true;
  3121. opening = '[';
  3122. closing = ']';
  3123. crossBlock = true;
  3124. multipleTargets = true;
  3125. goto handlePairTarget;
  3126. }
  3127. case Range::BracketInner:
  3128. {
  3129. around = false;
  3130. opening = '[';
  3131. closing = ']';
  3132. crossBlock = true;
  3133. multipleTargets = true;
  3134. goto handlePairTarget;
  3135. }
  3136. case Range::AngleBracketAround:
  3137. {
  3138. around = true;
  3139. opening = '<';
  3140. closing = '>';
  3141. crossBlock = true;
  3142. multipleTargets = true;
  3143. goto handlePairTarget;
  3144. }
  3145. case Range::AngleBracketInner:
  3146. {
  3147. around = false;
  3148. opening = '<';
  3149. closing = '>';
  3150. crossBlock = true;
  3151. multipleTargets = true;
  3152. goto handlePairTarget;
  3153. }
  3154. case Range::BraceAround:
  3155. {
  3156. around = true;
  3157. opening = '{';
  3158. closing = '}';
  3159. crossBlock = true;
  3160. multipleTargets = true;
  3161. goto handlePairTarget;
  3162. }
  3163. case Range::BraceInner:
  3164. {
  3165. around = false;
  3166. opening = '{';
  3167. closing = '}';
  3168. crossBlock = true;
  3169. multipleTargets = true;
  3170. goto handlePairTarget;
  3171. }
  3172. case Range::DoubleQuoteAround:
  3173. {
  3174. around = true;
  3175. opening = '"';
  3176. closing = '"';
  3177. crossBlock = false;
  3178. multipleTargets = false;
  3179. goto handlePairTarget;
  3180. }
  3181. case Range::DoubleQuoteInner:
  3182. {
  3183. around = false;
  3184. opening = '"';
  3185. closing = '"';
  3186. crossBlock = false;
  3187. multipleTargets = false;
  3188. goto handlePairTarget;
  3189. }
  3190. case Range::BackQuoteAround:
  3191. {
  3192. around = true;
  3193. opening = '`';
  3194. closing = '`';
  3195. crossBlock = false;
  3196. multipleTargets = false;
  3197. goto handlePairTarget;
  3198. }
  3199. case Range::BackQuoteInner:
  3200. {
  3201. around = false;
  3202. opening = '`';
  3203. closing = '`';
  3204. crossBlock = false;
  3205. multipleTargets = false;
  3206. goto handlePairTarget;
  3207. }
  3208. case Range::QuoteAround:
  3209. {
  3210. around = true;
  3211. opening = '\'';
  3212. closing = '\'';
  3213. crossBlock = false;
  3214. multipleTargets = false;
  3215. goto handlePairTarget;
  3216. }
  3217. case Range::QuoteInner:
  3218. {
  3219. around = false;
  3220. opening = '\'';
  3221. closing = '\'';
  3222. crossBlock = false;
  3223. multipleTargets = false;
  3224. handlePairTarget:
  3225. if (p_repeat == -1) {
  3226. p_repeat = 1;
  3227. } else if (p_repeat > 1 && !multipleTargets) {
  3228. // According to the behavior of Vim.
  3229. p_repeat = 1;
  3230. around = true;
  3231. }
  3232. hasMoved = VEditUtils::selectPairTargetAround(p_cursor,
  3233. opening,
  3234. closing,
  3235. around,
  3236. crossBlock,
  3237. p_repeat);
  3238. break;
  3239. }
  3240. default:
  3241. break;
  3242. }
  3243. return hasMoved;
  3244. }
  3245. void VVim::processDeleteAction(QList<Token> &p_tokens)
  3246. {
  3247. Token to = p_tokens.takeFirst();
  3248. int repeat = -1;
  3249. if (to.isRepeat()) {
  3250. repeat = to.m_repeat;
  3251. to = p_tokens.takeFirst();
  3252. }
  3253. if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
  3254. p_tokens.clear();
  3255. return;
  3256. }
  3257. QTextCursor cursor = m_editor->textCursorW();
  3258. QTextDocument *doc = m_editor->documentW();
  3259. bool hasMoved = false;
  3260. QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
  3261. if (to.isRange()) {
  3262. cursor.beginEditBlock();
  3263. hasMoved = selectRange(cursor, doc, to.m_range, repeat);
  3264. if (hasMoved) {
  3265. // Whether the range may cross blocks.
  3266. bool mayCrossBlock = false;
  3267. switch (to.m_range) {
  3268. case Range::Line:
  3269. {
  3270. // dd, delete current line.
  3271. if (cursor.hasSelection()) {
  3272. repeat = VEditUtils::selectedBlockCount(cursor);
  3273. deleteSelectedText(cursor, true);
  3274. } else {
  3275. VEditUtils::removeBlock(cursor);
  3276. saveToRegister("\n");
  3277. repeat = 1;
  3278. }
  3279. message(tr("%1 fewer %2").arg(repeat).arg(repeat > 1 ? tr("lines")
  3280. : tr("line")));
  3281. break;
  3282. }
  3283. case Range::ParenthesisInner:
  3284. // Fall through.
  3285. case Range::ParenthesisAround:
  3286. // Fall through.
  3287. case Range::BracketInner:
  3288. // Fall through.
  3289. case Range::BracketAround:
  3290. // Fall through.
  3291. case Range::AngleBracketInner:
  3292. // Fall through.
  3293. case Range::AngleBracketAround:
  3294. // Fall through.
  3295. case Range::BraceInner:
  3296. // Fall through.
  3297. case Range::BraceAround:
  3298. // Fall through.
  3299. mayCrossBlock = true;
  3300. V_FALLTHROUGH;
  3301. case Range::WordAround:
  3302. // Fall through.
  3303. case Range::WordInner:
  3304. // Fall through.
  3305. case Range::WORDAround:
  3306. // Fall through.
  3307. case Range::WORDInner:
  3308. // Fall through.
  3309. case Range::QuoteInner:
  3310. // Fall through.
  3311. case Range::QuoteAround:
  3312. // Fall through.
  3313. case Range::DoubleQuoteInner:
  3314. // Fall through.
  3315. case Range::DoubleQuoteAround:
  3316. // Fall through.
  3317. case Range::BackQuoteInner:
  3318. // Fall through.
  3319. case Range::BackQuoteAround:
  3320. {
  3321. if (cursor.hasSelection()) {
  3322. bool clearEmptyBlock = false;
  3323. if (mayCrossBlock
  3324. && VEditUtils::selectedBlockCount(cursor) > 1) {
  3325. clearEmptyBlock = true;
  3326. }
  3327. int blockCount = 0;
  3328. if (clearEmptyBlock) {
  3329. blockCount = doc->blockCount();
  3330. }
  3331. deleteSelectedText(cursor, clearEmptyBlock);
  3332. if (clearEmptyBlock) {
  3333. int nrBlock = blockCount - doc->blockCount();
  3334. Q_ASSERT(nrBlock > 0);
  3335. message(tr("%1 fewer %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  3336. : tr("line")));
  3337. }
  3338. }
  3339. break;
  3340. }
  3341. default:
  3342. return;
  3343. }
  3344. }
  3345. cursor.endEditBlock();
  3346. goto exit;
  3347. }
  3348. V_ASSERT(to.isMovement());
  3349. // Filter out not supported movement for DELETE action.
  3350. switch (to.m_movement) {
  3351. case Movement::PageUp:
  3352. case Movement::PageDown:
  3353. case Movement::HalfPageUp:
  3354. case Movement::HalfPageDown:
  3355. return;
  3356. default:
  3357. break;
  3358. }
  3359. cursor.beginEditBlock();
  3360. if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
  3361. // Visual mode, omitting repeat and movement.
  3362. // Different from Vim:
  3363. // If there is no selection in Visual mode, we do nothing.
  3364. if (cursor.hasSelection()) {
  3365. hasMoved = true;
  3366. deleteSelectedText(cursor, m_mode == VimMode::VisualLine);
  3367. } else if (checkMode(VimMode::Visual)) {
  3368. hasMoved = true;
  3369. VEditUtils::removeBlock(cursor);
  3370. saveToRegister("\n");
  3371. }
  3372. cursor.endEditBlock();
  3373. goto exit;
  3374. }
  3375. hasMoved = processMovement(cursor, moveMode, to, repeat);
  3376. if (repeat == -1) {
  3377. repeat = 1;
  3378. }
  3379. if (hasMoved) {
  3380. bool clearEmptyBlock = false;
  3381. switch (to.m_movement) {
  3382. case Movement::Up:
  3383. {
  3384. expandSelectionToWholeLines(cursor);
  3385. clearEmptyBlock = true;
  3386. qDebug() << "delete up" << repeat << "lines";
  3387. break;
  3388. }
  3389. case Movement::Down:
  3390. {
  3391. expandSelectionToWholeLines(cursor);
  3392. clearEmptyBlock = true;
  3393. qDebug() << "delete down" << repeat << "lines";
  3394. break;
  3395. }
  3396. case Movement::EndOfLine:
  3397. {
  3398. // End of line (block).
  3399. if (repeat > 1) {
  3400. clearEmptyBlock = true;
  3401. }
  3402. qDebug() << "delete till end of" << repeat << "line";
  3403. break;
  3404. }
  3405. case Movement::LineJump:
  3406. {
  3407. expandSelectionToWholeLines(cursor);
  3408. clearEmptyBlock = true;
  3409. qDebug() << "delete till line" << repeat;
  3410. break;
  3411. }
  3412. case Movement::StartOfDocument:
  3413. {
  3414. expandSelectionToWholeLines(cursor);
  3415. clearEmptyBlock = true;
  3416. qDebug() << "delete till start of document";
  3417. break;
  3418. }
  3419. case Movement::EndOfDocument:
  3420. {
  3421. expandSelectionToWholeLines(cursor);
  3422. clearEmptyBlock = true;
  3423. qDebug() << "delete till end of document";
  3424. break;
  3425. }
  3426. // ParagraphUp and ParagraphDown are a little different from Vim in
  3427. // block deletion.
  3428. default:
  3429. break;
  3430. }
  3431. if (clearEmptyBlock) {
  3432. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  3433. message(tr("%1 fewer %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  3434. : tr("line")));
  3435. }
  3436. deleteSelectedText(cursor, clearEmptyBlock);
  3437. }
  3438. cursor.endEditBlock();
  3439. exit:
  3440. if (hasMoved) {
  3441. m_editor->setTextCursorW(cursor);
  3442. }
  3443. }
  3444. void VVim::processCopyAction(QList<Token> &p_tokens)
  3445. {
  3446. Token to = p_tokens.takeFirst();
  3447. int repeat = -1;
  3448. if (to.isRepeat()) {
  3449. repeat = to.m_repeat;
  3450. to = p_tokens.takeFirst();
  3451. }
  3452. if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
  3453. p_tokens.clear();
  3454. return;
  3455. }
  3456. QTextCursor cursor = m_editor->textCursorW();
  3457. QTextDocument *doc = m_editor->documentW();
  3458. int oriPos = cursor.position();
  3459. bool changed = false;
  3460. QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
  3461. if (to.isRange()) {
  3462. cursor.beginEditBlock();
  3463. changed = selectRange(cursor, doc, to.m_range, repeat);
  3464. if (changed) {
  3465. // Whether the range may cross blocks.
  3466. bool mayCrossBlock = false;
  3467. switch (to.m_range) {
  3468. case Range::Line:
  3469. {
  3470. // yy, copy current line.
  3471. if (cursor.hasSelection()) {
  3472. repeat = VEditUtils::selectedBlockCount(cursor);
  3473. copySelectedText(cursor, true);
  3474. } else {
  3475. saveToRegister("\n");
  3476. repeat = 1;
  3477. }
  3478. message(tr("%1 %2 yanked").arg(repeat).arg(repeat > 1 ? tr("lines")
  3479. : tr("line")));
  3480. break;
  3481. }
  3482. case Range::ParenthesisInner:
  3483. // Fall through.
  3484. case Range::ParenthesisAround:
  3485. // Fall through.
  3486. case Range::BracketInner:
  3487. // Fall through.
  3488. case Range::BracketAround:
  3489. // Fall through.
  3490. case Range::AngleBracketInner:
  3491. // Fall through.
  3492. case Range::AngleBracketAround:
  3493. // Fall through.
  3494. case Range::BraceInner:
  3495. // Fall through.
  3496. case Range::BraceAround:
  3497. // Fall through.
  3498. mayCrossBlock = true;
  3499. V_FALLTHROUGH;
  3500. case Range::WordAround:
  3501. // Fall through.
  3502. case Range::WordInner:
  3503. // Fall through.
  3504. case Range::WORDAround:
  3505. // Fall through.
  3506. case Range::WORDInner:
  3507. // Fall through.
  3508. case Range::QuoteInner:
  3509. // Fall through.
  3510. case Range::QuoteAround:
  3511. // Fall through.
  3512. case Range::DoubleQuoteInner:
  3513. // Fall through.
  3514. case Range::DoubleQuoteAround:
  3515. // Fall through.
  3516. case Range::BackQuoteInner:
  3517. // Fall through.
  3518. case Range::BackQuoteAround:
  3519. {
  3520. if (cursor.hasSelection()) {
  3521. bool multipleBlocks = false;
  3522. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  3523. if (mayCrossBlock && nrBlock > 1) {
  3524. multipleBlocks = true;
  3525. }
  3526. // No need to add new line even crossing multiple blocks.
  3527. copySelectedText(cursor, false);
  3528. if (multipleBlocks) {
  3529. message(tr("%1 %2 yanked").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  3530. : tr("line")));
  3531. }
  3532. }
  3533. break;
  3534. }
  3535. default:
  3536. return;
  3537. }
  3538. }
  3539. if (cursor.position() != oriPos) {
  3540. cursor.setPosition(oriPos);
  3541. changed = true;
  3542. }
  3543. cursor.endEditBlock();
  3544. goto exit;
  3545. }
  3546. V_ASSERT(to.isMovement());
  3547. // Filter out not supported movement for Copy action.
  3548. switch (to.m_movement) {
  3549. case Movement::PageUp:
  3550. case Movement::PageDown:
  3551. case Movement::HalfPageUp:
  3552. case Movement::HalfPageDown:
  3553. return;
  3554. default:
  3555. break;
  3556. }
  3557. cursor.beginEditBlock();
  3558. changed = processMovement(cursor, moveMode, to, repeat);
  3559. if (repeat == -1) {
  3560. repeat = 1;
  3561. }
  3562. if (changed) {
  3563. bool addNewLine = false;
  3564. switch (to.m_movement) {
  3565. case Movement::Up:
  3566. {
  3567. expandSelectionToWholeLines(cursor);
  3568. addNewLine = true;
  3569. qDebug() << "copy up" << repeat << "lines";
  3570. break;
  3571. }
  3572. case Movement::Down:
  3573. {
  3574. expandSelectionToWholeLines(cursor);
  3575. addNewLine = true;
  3576. qDebug() << "copy down" << repeat << "lines";
  3577. break;
  3578. }
  3579. case Movement::EndOfLine:
  3580. {
  3581. // End of line (block).
  3582. // Do not need to add new line even if repeat > 1.
  3583. qDebug() << "copy till end of" << repeat << "line";
  3584. break;
  3585. }
  3586. case Movement::LineJump:
  3587. {
  3588. expandSelectionToWholeLines(cursor);
  3589. addNewLine = true;
  3590. qDebug() << "copy till line" << repeat;
  3591. break;
  3592. }
  3593. case Movement::StartOfDocument:
  3594. {
  3595. expandSelectionToWholeLines(cursor);
  3596. addNewLine = true;
  3597. qDebug() << "copy till start of document";
  3598. break;
  3599. }
  3600. case Movement::EndOfDocument:
  3601. {
  3602. expandSelectionToWholeLines(cursor);
  3603. addNewLine = true;
  3604. qDebug() << "copy till end of document";
  3605. break;
  3606. }
  3607. default:
  3608. break;
  3609. }
  3610. if (addNewLine) {
  3611. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  3612. message(tr("%1 %2 yanked").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  3613. : tr("line")));
  3614. }
  3615. copySelectedText(cursor, addNewLine);
  3616. if (cursor.position() != oriPos) {
  3617. cursor.setPosition(oriPos);
  3618. }
  3619. }
  3620. cursor.endEditBlock();
  3621. exit:
  3622. if (changed) {
  3623. m_editor->setTextCursorW(cursor);
  3624. }
  3625. }
  3626. void VVim::processPasteAction(QList<Token> &p_tokens, bool p_pasteBefore)
  3627. {
  3628. int repeat = 1;
  3629. if (!p_tokens.isEmpty()) {
  3630. Token to = p_tokens.takeFirst();
  3631. if (!p_tokens.isEmpty() || !to.isRepeat()) {
  3632. p_tokens.clear();
  3633. return;
  3634. }
  3635. repeat = to.m_repeat;
  3636. }
  3637. Register &reg = getRegister(m_regName);
  3638. QString value = reg.read();
  3639. bool isBlock = reg.isBlock();
  3640. if (value.isEmpty()) {
  3641. if (checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine)) {
  3642. setMode(VimMode::Normal);
  3643. }
  3644. return;
  3645. }
  3646. if (!(checkMode(VimMode::Normal)
  3647. || checkMode(VimMode::Visual)
  3648. || checkMode(VimMode::VisualLine))) {
  3649. return;
  3650. }
  3651. QString text;
  3652. text.reserve(repeat * value.size() + 1);
  3653. for (int i = 0; i < repeat; ++i) {
  3654. text.append(value);
  3655. }
  3656. bool changed = false;
  3657. int nrBlock = 0;
  3658. int restorePos = -1;
  3659. QTextCursor cursor = m_editor->textCursorW();
  3660. cursor.beginEditBlock();
  3661. // Different from Vim:
  3662. // In visual mode, by default vim select the current char, so paste operation will replace
  3663. // current char, but here it is strange to follow this specification.
  3664. bool isVisualLine = checkMode(VimMode::VisualLine);
  3665. if (!checkMode(VimMode::Normal)) {
  3666. // Visual or VisualLine mode.
  3667. if (cursor.hasSelection()) {
  3668. int pos = cursor.selectionStart();
  3669. deleteSelectedText(cursor, isVisualLine);
  3670. if (isVisualLine) {
  3671. // Insert a new block for insertion.
  3672. insertChangeBlockAfterDeletion(cursor, pos);
  3673. restorePos = cursor.position();
  3674. if (isBlock) {
  3675. nrBlock = text.count('\n');
  3676. // insertChangeBlockAfterDeletion() already insert a new line, so eliminate one here.
  3677. text = text.left(text.size() - 1);
  3678. }
  3679. } else if (isBlock) {
  3680. // Insert new block right at current cursor.
  3681. nrBlock = text.count('\n');
  3682. cursor.insertBlock();
  3683. restorePos = cursor.position();
  3684. } else if (text.count('\n') > 0) {
  3685. restorePos = cursor.position();
  3686. }
  3687. changed = true;
  3688. }
  3689. } else {
  3690. // Normal mode.
  3691. if (isBlock) {
  3692. if (p_pasteBefore) {
  3693. cursor.movePosition(QTextCursor::StartOfBlock);
  3694. cursor.insertBlock();
  3695. cursor.movePosition(QTextCursor::PreviousBlock);
  3696. } else {
  3697. cursor.movePosition(QTextCursor::EndOfBlock);
  3698. cursor.insertBlock();
  3699. }
  3700. restorePos = cursor.position();
  3701. nrBlock = text.count('\n');
  3702. // inserBlock() already insert a new line, so eliminate one here.
  3703. text = text.left(text.size() - 1);
  3704. } else {
  3705. // Not a block.
  3706. if (!p_pasteBefore && !cursor.atBlockEnd()) {
  3707. // Insert behind current cursor.
  3708. cursor.movePosition(QTextCursor::Right);
  3709. }
  3710. if (text.count('\n') > 0) {
  3711. restorePos = cursor.position();
  3712. }
  3713. }
  3714. changed = true;
  3715. }
  3716. if (changed) {
  3717. cursor.insertText(text);
  3718. if (restorePos == -1) {
  3719. // Move cursor one character left.
  3720. cursor.movePosition(QTextCursor::Left);
  3721. } else {
  3722. // Move cursor at the right position.
  3723. cursor.setPosition(restorePos);
  3724. }
  3725. if (nrBlock > 0) {
  3726. message(tr("%1 more %2").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  3727. : tr("line")));
  3728. }
  3729. }
  3730. cursor.endEditBlock();
  3731. if (!checkMode(VimMode::Normal)) {
  3732. setMode(VimMode::Normal);
  3733. }
  3734. if (changed) {
  3735. m_editor->setTextCursorW(cursor);
  3736. }
  3737. qDebug() << "text pasted" << text;
  3738. }
  3739. void VVim::processChangeAction(QList<Token> &p_tokens)
  3740. {
  3741. Token to = p_tokens.takeFirst();
  3742. int repeat = -1;
  3743. if (to.isRepeat()) {
  3744. repeat = to.m_repeat;
  3745. to = p_tokens.takeFirst();
  3746. }
  3747. if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
  3748. p_tokens.clear();
  3749. return;
  3750. }
  3751. QTextCursor cursor = m_editor->textCursorW();
  3752. QTextDocument *doc = m_editor->documentW();
  3753. bool hasMoved = false;
  3754. QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
  3755. if (to.isRange()) {
  3756. cursor.beginEditBlock();
  3757. hasMoved = selectRange(cursor, doc, to.m_range, repeat);
  3758. if (hasMoved) {
  3759. int pos = cursor.selectionStart();
  3760. switch (to.m_range) {
  3761. case Range::Line:
  3762. {
  3763. // cc, change current line.
  3764. if (cursor.hasSelection()) {
  3765. deleteSelectedText(cursor, true);
  3766. insertChangeBlockAfterDeletion(cursor, pos);
  3767. } else {
  3768. saveToRegister("\n");
  3769. }
  3770. break;
  3771. }
  3772. case Range::ParenthesisInner:
  3773. // Fall through.
  3774. case Range::ParenthesisAround:
  3775. // Fall through.
  3776. case Range::BracketInner:
  3777. // Fall through.
  3778. case Range::BracketAround:
  3779. // Fall through.
  3780. case Range::AngleBracketInner:
  3781. // Fall through.
  3782. case Range::AngleBracketAround:
  3783. // Fall through.
  3784. case Range::BraceInner:
  3785. // Fall through.
  3786. case Range::BraceAround:
  3787. // Fall through.
  3788. case Range::WordAround:
  3789. // Fall through.
  3790. case Range::WordInner:
  3791. // Fall through.
  3792. case Range::WORDAround:
  3793. // Fall through.
  3794. case Range::WORDInner:
  3795. // Fall through.
  3796. case Range::QuoteInner:
  3797. // Fall through.
  3798. case Range::QuoteAround:
  3799. // Fall through.
  3800. case Range::DoubleQuoteInner:
  3801. // Fall through.
  3802. case Range::DoubleQuoteAround:
  3803. // Fall through.
  3804. case Range::BackQuoteInner:
  3805. // Fall through.
  3806. case Range::BackQuoteAround:
  3807. {
  3808. if (cursor.hasSelection()) {
  3809. deleteSelectedText(cursor, false);
  3810. }
  3811. break;
  3812. }
  3813. default:
  3814. return;
  3815. }
  3816. }
  3817. cursor.endEditBlock();
  3818. goto exit;
  3819. }
  3820. V_ASSERT(to.isMovement());
  3821. // Filter out not supported movement for Change action.
  3822. switch (to.m_movement) {
  3823. case Movement::PageUp:
  3824. case Movement::PageDown:
  3825. case Movement::HalfPageUp:
  3826. case Movement::HalfPageDown:
  3827. return;
  3828. default:
  3829. break;
  3830. }
  3831. cursor.beginEditBlock();
  3832. if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
  3833. // Visual mode, omitting repeat and movement.
  3834. // Different from Vim:
  3835. // If there is no selection in Visual mode, we do nothing.
  3836. bool visualLine = checkMode(VimMode::VisualLine);
  3837. if (cursor.hasSelection()) {
  3838. hasMoved = true;
  3839. int pos = cursor.selectionStart();
  3840. deleteSelectedText(cursor, visualLine);
  3841. if (visualLine) {
  3842. insertChangeBlockAfterDeletion(cursor, pos);
  3843. }
  3844. } else if (visualLine) {
  3845. hasMoved = true;
  3846. saveToRegister("\n");
  3847. }
  3848. cursor.endEditBlock();
  3849. goto exit;
  3850. }
  3851. hasMoved = processMovement(cursor, moveMode, to, repeat);
  3852. if (repeat == -1) {
  3853. repeat = 1;
  3854. }
  3855. if (hasMoved) {
  3856. bool clearEmptyBlock = false;
  3857. switch (to.m_movement) {
  3858. case Movement::Left:
  3859. {
  3860. qDebug() << "change backward" << repeat << "chars";
  3861. break;
  3862. }
  3863. case Movement::Right:
  3864. {
  3865. qDebug() << "change forward" << repeat << "chars";
  3866. break;
  3867. }
  3868. case Movement::Up:
  3869. {
  3870. expandSelectionToWholeLines(cursor);
  3871. clearEmptyBlock = true;
  3872. qDebug() << "change up" << repeat << "lines";
  3873. break;
  3874. }
  3875. case Movement::Down:
  3876. {
  3877. expandSelectionToWholeLines(cursor);
  3878. clearEmptyBlock = true;
  3879. qDebug() << "change down" << repeat << "lines";
  3880. break;
  3881. }
  3882. case Movement::VisualUp:
  3883. {
  3884. qDebug() << "change visual up" << repeat << "lines";
  3885. break;
  3886. }
  3887. case Movement::VisualDown:
  3888. {
  3889. qDebug() << "change visual down" << repeat << "lines";
  3890. break;
  3891. }
  3892. case Movement::StartOfLine:
  3893. {
  3894. qDebug() << "change till start of line";
  3895. break;
  3896. }
  3897. case Movement::EndOfLine:
  3898. {
  3899. // End of line (block).
  3900. if (repeat > 1) {
  3901. clearEmptyBlock = true;
  3902. }
  3903. qDebug() << "change till end of" << repeat << "line";
  3904. break;
  3905. }
  3906. case Movement::FirstCharacter:
  3907. {
  3908. qDebug() << "change till first non-space character";
  3909. break;
  3910. }
  3911. case Movement::LineJump:
  3912. {
  3913. expandSelectionToWholeLines(cursor);
  3914. clearEmptyBlock = true;
  3915. qDebug() << "change till line" << repeat;
  3916. break;
  3917. }
  3918. case Movement::StartOfDocument:
  3919. {
  3920. expandSelectionToWholeLines(cursor);
  3921. clearEmptyBlock = true;
  3922. qDebug() << "change till start of document";
  3923. break;
  3924. }
  3925. case Movement::EndOfDocument:
  3926. {
  3927. expandSelectionToWholeLines(cursor);
  3928. clearEmptyBlock = true;
  3929. qDebug() << "change till end of document";
  3930. break;
  3931. }
  3932. case Movement::WordForward:
  3933. {
  3934. qDebug() << "change" << repeat << "words forward";
  3935. break;
  3936. }
  3937. case Movement::WORDForward:
  3938. {
  3939. qDebug() << "change" << repeat << "WORDs forward";
  3940. break;
  3941. }
  3942. case Movement::ForwardEndOfWord:
  3943. {
  3944. qDebug() << "change" << repeat << "end of words forward";
  3945. break;
  3946. }
  3947. case Movement::ForwardEndOfWORD:
  3948. {
  3949. qDebug() << "change" << repeat << "end of WORDs forward";
  3950. break;
  3951. }
  3952. case Movement::WordBackward:
  3953. {
  3954. qDebug() << "change" << repeat << "words backward";
  3955. break;
  3956. }
  3957. case Movement::WORDBackward:
  3958. {
  3959. qDebug() << "change" << repeat << "WORDs backward";
  3960. break;
  3961. }
  3962. case Movement::BackwardEndOfWord:
  3963. {
  3964. qDebug() << "change" << repeat << "end of words backward";
  3965. break;
  3966. }
  3967. case Movement::BackwardEndOfWORD:
  3968. {
  3969. qDebug() << "change" << repeat << "end of WORDs backward";
  3970. break;
  3971. }
  3972. default:
  3973. break;
  3974. }
  3975. if (cursor.hasSelection()) {
  3976. int pos = cursor.selectionStart();
  3977. bool allDeleted = false;
  3978. if (pos == 0) {
  3979. QTextBlock block = m_editor->documentW()->lastBlock();
  3980. if (block.position() + block.length() - 1 == cursor.selectionEnd()) {
  3981. allDeleted = true;
  3982. }
  3983. }
  3984. deleteSelectedText(cursor, clearEmptyBlock);
  3985. if (clearEmptyBlock && !allDeleted) {
  3986. insertChangeBlockAfterDeletion(cursor, pos);
  3987. }
  3988. }
  3989. }
  3990. cursor.endEditBlock();
  3991. exit:
  3992. if (hasMoved) {
  3993. m_editor->setTextCursorW(cursor);
  3994. }
  3995. setMode(VimMode::Insert);
  3996. }
  3997. void VVim::processIndentAction(QList<Token> &p_tokens, IndentType p_type)
  3998. {
  3999. Token to = p_tokens.takeFirst();
  4000. int repeat = -1;
  4001. if (to.isRepeat()) {
  4002. repeat = to.m_repeat;
  4003. to = p_tokens.takeFirst();
  4004. }
  4005. if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
  4006. p_tokens.clear();
  4007. return;
  4008. }
  4009. QTextCursor cursor = m_editor->textCursorW();
  4010. QString op;
  4011. switch (p_type) {
  4012. case IndentType::Indent:
  4013. op = ">";
  4014. break;
  4015. case IndentType::UnIndent:
  4016. op = "<";
  4017. break;
  4018. case IndentType::AutoIndent:
  4019. op = "=";
  4020. break;
  4021. default:
  4022. Q_ASSERT(false);
  4023. }
  4024. if (to.isRange()) {
  4025. bool changed = selectRange(cursor, m_editor->documentW(), to.m_range, repeat);
  4026. if (changed) {
  4027. switch (to.m_range) {
  4028. case Range::Line:
  4029. {
  4030. // >>/<<, indent/unindent current line.
  4031. if (repeat == -1) {
  4032. repeat = 1;
  4033. }
  4034. if (p_type == IndentType::AutoIndent) {
  4035. VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
  4036. } else {
  4037. VEditUtils::indentSelectedBlocks(cursor,
  4038. m_editConfig->m_tabSpaces,
  4039. p_type == IndentType::Indent);
  4040. }
  4041. message(tr("%1 %2 %3ed 1 time").arg(repeat)
  4042. .arg(repeat > 1 ? tr("lines")
  4043. : tr("line"))
  4044. .arg(op));
  4045. break;
  4046. }
  4047. case Range::ParenthesisInner:
  4048. // Fall through.
  4049. case Range::ParenthesisAround:
  4050. // Fall through.
  4051. case Range::BracketInner:
  4052. // Fall through.
  4053. case Range::BracketAround:
  4054. // Fall through.
  4055. case Range::AngleBracketInner:
  4056. // Fall through.
  4057. case Range::AngleBracketAround:
  4058. // Fall through.
  4059. case Range::BraceInner:
  4060. // Fall through.
  4061. case Range::BraceAround:
  4062. // Fall through.
  4063. case Range::WordAround:
  4064. // Fall through.
  4065. case Range::WordInner:
  4066. // Fall through.
  4067. case Range::WORDAround:
  4068. // Fall through.
  4069. case Range::WORDInner:
  4070. // Fall through.
  4071. case Range::QuoteInner:
  4072. // Fall through.
  4073. case Range::QuoteAround:
  4074. // Fall through.
  4075. case Range::DoubleQuoteInner:
  4076. // Fall through.
  4077. case Range::DoubleQuoteAround:
  4078. // Fall through.
  4079. case Range::BackQuoteInner:
  4080. // Fall through.
  4081. case Range::BackQuoteAround:
  4082. {
  4083. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  4084. if (p_type == IndentType::AutoIndent) {
  4085. VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
  4086. } else {
  4087. VEditUtils::indentSelectedBlocks(cursor,
  4088. m_editConfig->m_tabSpaces,
  4089. p_type == IndentType::Indent);
  4090. }
  4091. message(tr("%1 %2 %3ed 1 time").arg(nrBlock)
  4092. .arg(nrBlock > 1 ? tr("lines")
  4093. : tr("line"))
  4094. .arg(op));
  4095. break;
  4096. }
  4097. default:
  4098. return;
  4099. }
  4100. }
  4101. return;
  4102. }
  4103. V_ASSERT(to.isMovement());
  4104. // Filter out not supported movement for Indent/UnIndent action.
  4105. switch (to.m_movement) {
  4106. case Movement::PageUp:
  4107. case Movement::PageDown:
  4108. case Movement::HalfPageUp:
  4109. case Movement::HalfPageDown:
  4110. return;
  4111. default:
  4112. break;
  4113. }
  4114. if (checkMode(VimMode::VisualLine) || checkMode(VimMode::Visual)) {
  4115. // Visual mode, omitting repeat and movement.
  4116. // Different from Vim:
  4117. // Do not exit Visual mode after indentation/unindentation.
  4118. if (p_type == IndentType::AutoIndent) {
  4119. VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
  4120. } else {
  4121. VEditUtils::indentSelectedBlocks(cursor,
  4122. m_editConfig->m_tabSpaces,
  4123. p_type == IndentType::Indent);
  4124. }
  4125. return;
  4126. }
  4127. processMovement(cursor,
  4128. QTextCursor::KeepAnchor,
  4129. to,
  4130. repeat);
  4131. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  4132. if (p_type == IndentType::AutoIndent) {
  4133. VEditUtils::indentSelectedBlocksAsBlock(cursor, false);
  4134. } else {
  4135. VEditUtils::indentSelectedBlocks(cursor,
  4136. m_editConfig->m_tabSpaces,
  4137. p_type == IndentType::Indent);
  4138. }
  4139. message(tr("%1 %2 %3ed 1 time").arg(nrBlock)
  4140. .arg(nrBlock > 1 ? tr("lines")
  4141. : tr("line"))
  4142. .arg(op));
  4143. }
  4144. void VVim::processToLowerAction(QList<Token> &p_tokens, bool p_toLower)
  4145. {
  4146. Token to = p_tokens.takeFirst();
  4147. int repeat = -1;
  4148. if (to.isRepeat()) {
  4149. repeat = to.m_repeat;
  4150. to = p_tokens.takeFirst();
  4151. }
  4152. if ((!to.isMovement() && !to.isRange()) || !p_tokens.isEmpty()) {
  4153. p_tokens.clear();
  4154. return;
  4155. }
  4156. QTextCursor cursor = m_editor->textCursorW();
  4157. QTextDocument *doc = m_editor->documentW();
  4158. bool changed = false;
  4159. QTextCursor::MoveMode moveMode = QTextCursor::KeepAnchor;
  4160. int oriPos = cursor.position();
  4161. if (to.isRange()) {
  4162. cursor.beginEditBlock();
  4163. changed = selectRange(cursor, doc, to.m_range, repeat);
  4164. if (changed) {
  4165. oriPos = cursor.selectionStart();
  4166. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  4167. message(tr("%1 %2 changed").arg(nrBlock)
  4168. .arg(nrBlock > 1 ? tr("lines") : tr("line")));
  4169. convertCaseOfSelectedText(cursor, p_toLower);
  4170. cursor.setPosition(oriPos);
  4171. }
  4172. cursor.endEditBlock();
  4173. goto exit;
  4174. }
  4175. V_ASSERT(to.isMovement());
  4176. // Filter out not supported movement for ToLower/ToUpper action.
  4177. switch (to.m_movement) {
  4178. case Movement::PageUp:
  4179. case Movement::PageDown:
  4180. case Movement::HalfPageUp:
  4181. case Movement::HalfPageDown:
  4182. return;
  4183. default:
  4184. break;
  4185. }
  4186. cursor.beginEditBlock();
  4187. changed = processMovement(cursor,
  4188. moveMode,
  4189. to,
  4190. repeat);
  4191. if (repeat == -1) {
  4192. repeat = 1;
  4193. }
  4194. if (changed) {
  4195. oriPos = cursor.selectionStart();
  4196. switch (to.m_movement) {
  4197. case Movement::Up:
  4198. {
  4199. expandSelectionToWholeLines(cursor);
  4200. break;
  4201. }
  4202. case Movement::Down:
  4203. {
  4204. expandSelectionToWholeLines(cursor);
  4205. break;
  4206. }
  4207. case Movement::LineJump:
  4208. {
  4209. expandSelectionToWholeLines(cursor);
  4210. break;
  4211. }
  4212. case Movement::StartOfDocument:
  4213. {
  4214. expandSelectionToWholeLines(cursor);
  4215. break;
  4216. }
  4217. case Movement::EndOfDocument:
  4218. {
  4219. expandSelectionToWholeLines(cursor);
  4220. break;
  4221. }
  4222. default:
  4223. break;
  4224. }
  4225. int nrBlock = VEditUtils::selectedBlockCount(cursor);
  4226. message(tr("%1 %2 changed").arg(nrBlock).arg(nrBlock > 1 ? tr("lines")
  4227. : tr("line")));
  4228. convertCaseOfSelectedText(cursor, p_toLower);
  4229. cursor.setPosition(oriPos);
  4230. }
  4231. cursor.endEditBlock();
  4232. exit:
  4233. if (changed) {
  4234. m_editor->setTextCursorW(cursor);
  4235. }
  4236. }
  4237. void VVim::processUndoAction(QList<Token> &p_tokens)
  4238. {
  4239. int repeat = 1;
  4240. if (!p_tokens.isEmpty()) {
  4241. Token to = p_tokens.takeFirst();
  4242. if (!p_tokens.isEmpty() || !to.isRepeat()) {
  4243. p_tokens.clear();
  4244. return;
  4245. }
  4246. repeat = to.m_repeat;
  4247. }
  4248. QTextDocument *doc = m_editor->documentW();
  4249. int i = 0;
  4250. for (i = 0; i < repeat && doc->isUndoAvailable(); ++i) {
  4251. m_editor->undoW();
  4252. }
  4253. message(tr("Undo %1 %2").arg(i).arg(i > 1 ? tr("changes") : tr("change")));
  4254. }
  4255. void VVim::processRedoAction(QList<Token> &p_tokens)
  4256. {
  4257. int repeat = 1;
  4258. if (!p_tokens.isEmpty()) {
  4259. Token to = p_tokens.takeFirst();
  4260. if (!p_tokens.isEmpty() || !to.isRepeat()) {
  4261. p_tokens.clear();
  4262. return;
  4263. }
  4264. repeat = to.m_repeat;
  4265. }
  4266. QTextDocument *doc = m_editor->documentW();
  4267. int i = 0;
  4268. for (i = 0; i < repeat && doc->isRedoAvailable(); ++i) {
  4269. m_editor->redoW();
  4270. }
  4271. message(tr("Redo %1 %2").arg(i).arg(i > 1 ? tr("changes") : tr("change")));
  4272. }
  4273. void VVim::processRedrawLineAction(QList<Token> &p_tokens, int p_dest)
  4274. {
  4275. QTextCursor cursor = m_editor->textCursorW();
  4276. int repeat = cursor.block().blockNumber();
  4277. if (!p_tokens.isEmpty()) {
  4278. Token to = p_tokens.takeFirst();
  4279. if (!p_tokens.isEmpty() || !to.isRepeat()) {
  4280. p_tokens.clear();
  4281. return;
  4282. }
  4283. repeat = to.m_repeat - 1;
  4284. }
  4285. m_editor->scrollBlockInPage(repeat, p_dest);
  4286. }
  4287. void VVim::processJumpLocationAction(QList<Token> &p_tokens, bool p_next)
  4288. {
  4289. int repeat = 1;
  4290. if (!p_tokens.isEmpty()) {
  4291. Token to = p_tokens.takeFirst();
  4292. if (!p_tokens.isEmpty() || !to.isRepeat()) {
  4293. p_tokens.clear();
  4294. return;
  4295. }
  4296. repeat = to.m_repeat;
  4297. }
  4298. QTextCursor cursor = m_editor->textCursorW();
  4299. Location loc;
  4300. if (p_next) {
  4301. while (m_locations.hasNext() && repeat > 0) {
  4302. --repeat;
  4303. loc = m_locations.nextLocation();
  4304. }
  4305. } else {
  4306. while (m_locations.hasPrevious() && repeat > 0) {
  4307. --repeat;
  4308. loc = m_locations.previousLocation(cursor);
  4309. }
  4310. }
  4311. if (loc.isValid()) {
  4312. QTextDocument *doc = m_editor->documentW();
  4313. if (loc.m_blockNumber >= doc->blockCount()) {
  4314. message(tr("Mark has invalid line number"));
  4315. return;
  4316. }
  4317. QTextBlock block = doc->findBlockByNumber(loc.m_blockNumber);
  4318. int pib = loc.m_positionInBlock;
  4319. if (pib >= block.length()) {
  4320. pib = block.length() - 1;
  4321. }
  4322. if (!m_editor->isBlockVisible(block)) {
  4323. // Scroll the block to the center of screen.
  4324. m_editor->scrollBlockInPage(block.blockNumber(), 1);
  4325. }
  4326. cursor.setPosition(block.position() + pib);
  4327. m_editor->setTextCursorW(cursor);
  4328. }
  4329. }
  4330. void VVim::processReplaceAction(QList<Token> &p_tokens)
  4331. {
  4332. int repeat = 1;
  4333. QChar replaceChar;
  4334. Q_ASSERT(!p_tokens.isEmpty());
  4335. Token to = p_tokens.takeFirst();
  4336. if (to.isRepeat()) {
  4337. repeat = to.m_repeat;
  4338. Q_ASSERT(!p_tokens.isEmpty());
  4339. to = p_tokens.takeFirst();
  4340. }
  4341. Q_ASSERT(to.isKey() && p_tokens.isEmpty());
  4342. replaceChar = keyToChar(to.m_key.m_key, to.m_key.m_modifiers);
  4343. if (replaceChar.isNull()) {
  4344. return;
  4345. }
  4346. if (!(checkMode(VimMode::Normal)
  4347. || checkMode(VimMode::Visual)
  4348. || checkMode(VimMode::VisualLine))) {
  4349. return;
  4350. }
  4351. // Replace the next repeat characters with replaceChar until the end of line.
  4352. // If repeat is greater than the number of left characters in current line,
  4353. // do nothing.
  4354. // In visual mode, repeat is ignored.
  4355. QTextCursor cursor = m_editor->textCursorW();
  4356. cursor.beginEditBlock();
  4357. if (checkMode(VimMode::Normal)) {
  4358. // Select the characters to be replaced.
  4359. cursor.clearSelection();
  4360. int pib = cursor.positionInBlock();
  4361. int nrChar = cursor.block().length() - 1 - pib;
  4362. if (repeat <= nrChar) {
  4363. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, repeat);
  4364. }
  4365. }
  4366. bool changed = replaceSelectedTextWithCharacter(cursor, replaceChar);
  4367. cursor.endEditBlock();
  4368. if (changed) {
  4369. m_editor->setTextCursorW(cursor);
  4370. setMode(VimMode::Normal);
  4371. }
  4372. }
  4373. void VVim::processReverseCaseAction(QList<Token> &p_tokens)
  4374. {
  4375. int repeat = 1;
  4376. if (!p_tokens.isEmpty()) {
  4377. Token to = p_tokens.takeFirst();
  4378. Q_ASSERT(to.isRepeat() && p_tokens.isEmpty());
  4379. repeat = to.m_repeat;
  4380. }
  4381. if (!(checkMode(VimMode::Normal)
  4382. || checkMode(VimMode::Visual)
  4383. || checkMode(VimMode::VisualLine))) {
  4384. return;
  4385. }
  4386. // Reverse the next repeat characters' case until the end of line.
  4387. // If repeat is greater than the number of left characters in current line,
  4388. // just change the actual number of left characters.
  4389. // In visual mode, repeat is ignored and reverse the selected text.
  4390. QTextCursor cursor = m_editor->textCursorW();
  4391. cursor.beginEditBlock();
  4392. if (checkMode(VimMode::Normal)) {
  4393. // Select the characters to be replaced.
  4394. cursor.clearSelection();
  4395. int pib = cursor.positionInBlock();
  4396. int nrChar = cursor.block().length() - 1 - pib;
  4397. cursor.movePosition(QTextCursor::Right,
  4398. QTextCursor::KeepAnchor,
  4399. repeat > nrChar ? nrChar : repeat);
  4400. }
  4401. bool changed = reverseSelectedTextCase(cursor);
  4402. cursor.endEditBlock();
  4403. if (changed) {
  4404. m_editor->setTextCursorW(cursor);
  4405. setMode(VimMode::Normal);
  4406. }
  4407. }
  4408. void VVim::processJoinAction(QList<Token> &p_tokens, bool p_modifySpaces)
  4409. {
  4410. int repeat = 2;
  4411. if (!p_tokens.isEmpty()) {
  4412. Token to = p_tokens.takeFirst();
  4413. Q_ASSERT(to.isRepeat() && p_tokens.isEmpty());
  4414. repeat = qMax(to.m_repeat, repeat);
  4415. }
  4416. if (!(checkMode(VimMode::Normal)
  4417. || checkMode(VimMode::Visual)
  4418. || checkMode(VimMode::VisualLine))) {
  4419. return;
  4420. }
  4421. // Join repeat lines, with the minimum of two lines. Do nothing when on the
  4422. // last line.
  4423. // If @p_modifySpaces is true, remove the indent and insert up to two spaces.
  4424. // If repeat is too big, it is reduced to the number of lines available.
  4425. // In visual mode, repeat is ignored and join the highlighted lines.
  4426. int firstBlock = -1;
  4427. int blockCount = repeat;
  4428. QTextCursor cursor = m_editor->textCursorW();
  4429. cursor.beginEditBlock();
  4430. if (checkMode(VimMode::Normal)) {
  4431. firstBlock = cursor.block().blockNumber();
  4432. } else {
  4433. QTextDocument *doc = m_editor->documentW();
  4434. firstBlock = doc->findBlock(cursor.selectionStart()).blockNumber();
  4435. int lastBlock = doc->findBlock(cursor.selectionEnd()).blockNumber();
  4436. blockCount = lastBlock - firstBlock + 1;
  4437. }
  4438. bool changed = joinLines(cursor, firstBlock, blockCount, p_modifySpaces);
  4439. cursor.endEditBlock();
  4440. if (changed) {
  4441. m_editor->setTextCursorW(cursor);
  4442. setMode(VimMode::Normal);
  4443. }
  4444. }
  4445. bool VVim::clearSelection()
  4446. {
  4447. QTextCursor cursor = m_editor->textCursorW();
  4448. if (cursor.hasSelection()) {
  4449. cursor.clearSelection();
  4450. m_editor->setTextCursorW(cursor);
  4451. return true;
  4452. }
  4453. return false;
  4454. }
  4455. int VVim::blockCountOfPageStep() const
  4456. {
  4457. int lineCount = m_editor->documentW()->blockCount();
  4458. QScrollBar *bar = m_editor->verticalScrollBarW();
  4459. int steps = (bar->maximum() - bar->minimum() + bar->pageStep());
  4460. int pageLineCount = lineCount * (bar->pageStep() * 1.0 / steps);
  4461. return pageLineCount;
  4462. }
  4463. void VVim::maintainSelectionInVisualMode(QTextCursor *p_cursor)
  4464. {
  4465. // We need to always select the character on current position.
  4466. QTextCursor *cursor = p_cursor;
  4467. QTextCursor tmpCursor = m_editor->textCursorW();
  4468. if (!cursor) {
  4469. cursor = &tmpCursor;
  4470. }
  4471. bool hasChanged = false;
  4472. int pos = cursor->position();
  4473. int anchor = cursor->anchor();
  4474. if (pos > anchor) {
  4475. Q_ASSERT(pos > m_positionBeforeVisualMode);
  4476. if (anchor > m_positionBeforeVisualMode) {
  4477. // Re-select.
  4478. cursor->setPosition(m_positionBeforeVisualMode);
  4479. cursor->setPosition(pos, QTextCursor::KeepAnchor);
  4480. hasChanged = true;
  4481. }
  4482. setCursorBlockMode(m_editor, CursorBlock::LeftSide);
  4483. } else if (pos == anchor) {
  4484. Q_ASSERT(anchor >= m_positionBeforeVisualMode);
  4485. // Re-select.
  4486. if (anchor == m_positionBeforeVisualMode) {
  4487. cursor->setPosition(m_positionBeforeVisualMode + 1);
  4488. cursor->setPosition(pos, QTextCursor::KeepAnchor);
  4489. hasChanged = true;
  4490. setCursorBlockMode(m_editor, CursorBlock::RightSide);
  4491. } else {
  4492. cursor->setPosition(m_positionBeforeVisualMode);
  4493. cursor->setPosition(pos, QTextCursor::KeepAnchor);
  4494. hasChanged = true;
  4495. setCursorBlockMode(m_editor, CursorBlock::LeftSide);
  4496. }
  4497. } else {
  4498. // Re-select.
  4499. if (anchor <= m_positionBeforeVisualMode) {
  4500. cursor->setPosition(m_positionBeforeVisualMode + 1);
  4501. cursor->setPosition(pos, QTextCursor::KeepAnchor);
  4502. hasChanged = true;
  4503. }
  4504. setCursorBlockMode(m_editor, CursorBlock::RightSide);
  4505. }
  4506. if (hasChanged && !p_cursor) {
  4507. m_editor->setTextCursorW(*cursor);
  4508. }
  4509. }
  4510. void VVim::expandSelectionToWholeLines(QTextCursor &p_cursor)
  4511. {
  4512. QTextDocument *doc = m_editor->documentW();
  4513. int curPos = p_cursor.position();
  4514. int anchorPos = p_cursor.anchor();
  4515. QTextBlock curBlock = doc->findBlock(curPos);
  4516. QTextBlock anchorBlock = doc->findBlock(anchorPos);
  4517. if (curPos >= anchorPos) {
  4518. p_cursor.setPosition(anchorBlock.position(), QTextCursor::MoveAnchor);
  4519. p_cursor.setPosition(curBlock.position() + curBlock.length() - 1,
  4520. QTextCursor::KeepAnchor);
  4521. } else {
  4522. p_cursor.setPosition(anchorBlock.position() + anchorBlock.length() - 1,
  4523. QTextCursor::MoveAnchor);
  4524. p_cursor.setPosition(curBlock.position(),
  4525. QTextCursor::KeepAnchor);
  4526. }
  4527. }
  4528. void VVim::initRegisters()
  4529. {
  4530. if (!s_registers.isEmpty()) {
  4531. return;
  4532. }
  4533. for (char ch = 'a'; ch <= 'z'; ++ch) {
  4534. s_registers[QChar(ch)] = Register(QChar(ch));
  4535. }
  4536. s_registers[c_unnamedRegister] = Register(c_unnamedRegister);
  4537. s_registers[c_blackHoleRegister] = Register(c_blackHoleRegister);
  4538. s_registers[c_selectionRegister] = Register(c_selectionRegister);
  4539. }
  4540. bool VVim::expectingRegisterName() const
  4541. {
  4542. return m_keys.size() == 1
  4543. && m_keys.at(0) == Key(Qt::Key_QuoteDbl, Qt::ShiftModifier);
  4544. }
  4545. bool VVim::expectingCharacterTarget() const
  4546. {
  4547. if (m_keys.size() != 1) {
  4548. return false;
  4549. }
  4550. const Key &key = m_keys.first();
  4551. return (key == Key(Qt::Key_F, Qt::NoModifier)
  4552. || key == Key(Qt::Key_F, Qt::ShiftModifier)
  4553. || key == Key(Qt::Key_T, Qt::NoModifier)
  4554. || key == Key(Qt::Key_T, Qt::ShiftModifier));
  4555. }
  4556. bool VVim::expectingReplaceCharacter() const
  4557. {
  4558. return m_keys.size() == 1
  4559. && m_keys.first() == Key(Qt::Key_R, Qt::NoModifier);
  4560. }
  4561. bool VVim::expectingLeaderSequence() const
  4562. {
  4563. if (m_replayLeaderSequence || m_keys.isEmpty()) {
  4564. return false;
  4565. }
  4566. return m_keys.first() == Key(Qt::Key_Backslash);
  4567. }
  4568. bool VVim::expectingMarkName() const
  4569. {
  4570. return checkPendingKey(Key(Qt::Key_M)) && m_tokens.isEmpty();
  4571. }
  4572. bool VVim::expectingMarkTarget() const
  4573. {
  4574. return checkPendingKey(Key(Qt::Key_Apostrophe))
  4575. || checkPendingKey(Key(Qt::Key_QuoteLeft));
  4576. }
  4577. QChar VVim::keyToRegisterName(const Key &p_key) const
  4578. {
  4579. if (p_key.isAlphabet()) {
  4580. return p_key.toAlphabet().toLower();
  4581. }
  4582. switch (p_key.m_key) {
  4583. case Qt::Key_QuoteDbl:
  4584. if (p_key.m_modifiers == Qt::ShiftModifier) {
  4585. return c_unnamedRegister;
  4586. }
  4587. break;
  4588. case Qt::Key_Plus:
  4589. if (p_key.m_modifiers == Qt::ShiftModifier) {
  4590. return c_selectionRegister;
  4591. }
  4592. break;
  4593. case Qt::Key_Underscore:
  4594. if (p_key.m_modifiers == Qt::ShiftModifier) {
  4595. return c_blackHoleRegister;
  4596. }
  4597. break;
  4598. default:
  4599. break;
  4600. }
  4601. return QChar();
  4602. }
  4603. bool VVim::hasActionToken() const
  4604. {
  4605. // There will be only one action token and it is placed at the front.
  4606. bool has = false;
  4607. if (m_tokens.isEmpty()) {
  4608. return false;
  4609. }
  4610. if (m_tokens.at(0).isAction()) {
  4611. has = true;
  4612. }
  4613. for (int i = 1; i < m_tokens.size(); ++i) {
  4614. V_ASSERT(!m_tokens.at(i).isAction());
  4615. }
  4616. return has;
  4617. }
  4618. bool VVim::hasRepeatToken() const
  4619. {
  4620. // There will be only one repeat token.
  4621. bool has = false;
  4622. if (m_tokens.isEmpty()) {
  4623. return false;
  4624. }
  4625. for (int i = 0; i < m_tokens.size(); ++i) {
  4626. if (m_tokens.at(i).isRepeat()) {
  4627. V_ASSERT(!has);
  4628. has = true;
  4629. }
  4630. }
  4631. return has;
  4632. }
  4633. bool VVim::hasActionTokenValidForTextObject() const
  4634. {
  4635. if (hasActionToken()) {
  4636. Action act = m_tokens.first().m_action;
  4637. if (act == Action::Delete
  4638. || act == Action::Copy
  4639. || act == Action::Change
  4640. || act == Action::ToLower
  4641. || act == Action::ToUpper
  4642. || act == Action::Indent
  4643. || act == Action::UnIndent) {
  4644. return true;
  4645. }
  4646. }
  4647. return false;
  4648. }
  4649. bool VVim::checkActionToken(Action p_action) const
  4650. {
  4651. if (hasActionToken()) {
  4652. return m_tokens.first().m_action == p_action;
  4653. }
  4654. return false;
  4655. }
  4656. bool VVim::checkPendingKey(const Key &p_key) const
  4657. {
  4658. return (m_keys.size() == 1 && m_keys.first() == p_key);
  4659. }
  4660. void VVim::tryAddMoveAction()
  4661. {
  4662. if (!hasActionToken()) {
  4663. addActionToken(Action::Move);
  4664. }
  4665. }
  4666. void VVim::addActionToken(Action p_action)
  4667. {
  4668. V_ASSERT(!hasActionToken());
  4669. m_tokens.prepend(Token(p_action));
  4670. }
  4671. const VVim::Token *VVim::getActionToken() const
  4672. {
  4673. V_ASSERT(hasActionToken());
  4674. return &m_tokens.first();
  4675. }
  4676. VVim::Token *VVim::getRepeatToken()
  4677. {
  4678. V_ASSERT(hasRepeatToken());
  4679. for (auto & token : m_tokens) {
  4680. if (token.isRepeat()) {
  4681. return &token;
  4682. }
  4683. }
  4684. return NULL;
  4685. }
  4686. void VVim::addRangeToken(Range p_range)
  4687. {
  4688. m_tokens.append(Token(p_range));
  4689. }
  4690. void VVim::addMovementToken(Movement p_movement)
  4691. {
  4692. m_tokens.append(Token(p_movement));
  4693. }
  4694. void VVim::addMovementToken(Movement p_movement, Key p_key)
  4695. {
  4696. m_tokens.append(Token(p_movement, p_key));
  4697. }
  4698. void VVim::addKeyToken(Key p_key)
  4699. {
  4700. m_tokens.append(Token(p_key));
  4701. }
  4702. void VVim::deleteSelectedText(QTextCursor &p_cursor, bool p_clearEmptyBlock)
  4703. {
  4704. if (p_cursor.hasSelection()) {
  4705. QString deletedText = VEditUtils::selectedText(p_cursor);
  4706. p_cursor.removeSelectedText();
  4707. if (p_clearEmptyBlock && p_cursor.block().length() == 1) {
  4708. deletedText += "\n";
  4709. VEditUtils::removeBlock(p_cursor);
  4710. }
  4711. saveToRegister(deletedText);
  4712. }
  4713. }
  4714. void VVim::copySelectedText(bool p_addNewLine)
  4715. {
  4716. QTextCursor cursor = m_editor->textCursorW();
  4717. if (cursor.hasSelection()) {
  4718. cursor.beginEditBlock();
  4719. copySelectedText(cursor, p_addNewLine);
  4720. cursor.endEditBlock();
  4721. m_editor->setTextCursorW(cursor);
  4722. }
  4723. }
  4724. void VVim::copySelectedText(QTextCursor &p_cursor, bool p_addNewLine)
  4725. {
  4726. if (p_cursor.hasSelection()) {
  4727. QString text = VEditUtils::selectedText(p_cursor);
  4728. p_cursor.clearSelection();
  4729. if (p_addNewLine) {
  4730. text += "\n";
  4731. }
  4732. saveToRegister(text);
  4733. }
  4734. }
  4735. void VVim::convertCaseOfSelectedText(QTextCursor &p_cursor, bool p_toLower)
  4736. {
  4737. if (p_cursor.hasSelection()) {
  4738. QTextDocument *doc = p_cursor.document();
  4739. int start = p_cursor.selectionStart();
  4740. int end = p_cursor.selectionEnd();
  4741. p_cursor.clearSelection();
  4742. p_cursor.setPosition(start);
  4743. int pos = p_cursor.position();
  4744. while (pos < end) {
  4745. QChar ch = doc->characterAt(pos);
  4746. bool modified = false;
  4747. if (p_toLower) {
  4748. if (ch.isUpper()) {
  4749. ch = ch.toLower();
  4750. modified = true;
  4751. }
  4752. } else if (ch.isLower()) {
  4753. ch = ch.toUpper();
  4754. modified = true;
  4755. }
  4756. if (modified) {
  4757. p_cursor.deleteChar();
  4758. p_cursor.insertText(ch);
  4759. } else {
  4760. p_cursor.movePosition(QTextCursor::NextCharacter);
  4761. }
  4762. pos = p_cursor.position();
  4763. }
  4764. }
  4765. }
  4766. void VVim::saveToRegister(const QString &p_text)
  4767. {
  4768. QString text(p_text);
  4769. VEditUtils::removeObjectReplacementCharacter(text);
  4770. qDebug() << QString("save text(%1) to register(%2)").arg(text).arg(m_regName);
  4771. Register &reg = getRegister(m_regName);
  4772. reg.update(text);
  4773. if (!reg.isBlackHoleRegister() && !reg.isUnnamedRegister()) {
  4774. // Save it to unnamed register.
  4775. setRegister(c_unnamedRegister, reg.m_value);
  4776. }
  4777. }
  4778. void VVim::Register::update(const QString &p_value)
  4779. {
  4780. QChar newLine('\n');
  4781. bool newIsBlock = false;
  4782. if (p_value.endsWith(newLine)) {
  4783. newIsBlock = true;
  4784. }
  4785. bool oriIsBlock = isBlock();
  4786. if (isNamedRegister() && m_append) {
  4787. // Append @p_value to m_value.
  4788. if (newIsBlock) {
  4789. if (oriIsBlock) {
  4790. m_value += p_value;
  4791. } else {
  4792. m_value.append(newLine);
  4793. m_value += p_value;
  4794. }
  4795. } else if (oriIsBlock) {
  4796. m_value += p_value;
  4797. m_value.append(newLine);
  4798. } else {
  4799. m_value += p_value;
  4800. }
  4801. } else {
  4802. // Set m_value to @p_value.
  4803. m_value = p_value;
  4804. }
  4805. if (isSelectionRegister()) {
  4806. // Change system clipboard.
  4807. QClipboard *clipboard = QApplication::clipboard();
  4808. clipboard->setText(m_value);
  4809. }
  4810. }
  4811. const QString &VVim::Register::read()
  4812. {
  4813. if (isSelectionRegister()) {
  4814. // Update from system clipboard.
  4815. QClipboard *clipboard = QApplication::clipboard();
  4816. const QMimeData *mimeData = clipboard->mimeData();
  4817. if (mimeData->hasText()) {
  4818. m_value = mimeData->text();
  4819. } else {
  4820. m_value.clear();
  4821. }
  4822. }
  4823. return m_value;
  4824. }
  4825. void VVim::repeatLastFindMovement(bool p_reverse)
  4826. {
  4827. if (!m_lastFindToken.isValid()) {
  4828. return;
  4829. }
  4830. V_ASSERT(m_lastFindToken.isMovement());
  4831. Movement mm = m_lastFindToken.m_movement;
  4832. Key key = m_lastFindToken.m_key;
  4833. V_ASSERT(key.isValid());
  4834. if (p_reverse) {
  4835. switch (mm) {
  4836. case Movement::FindForward:
  4837. mm = Movement::FindBackward;
  4838. break;
  4839. case Movement::FindBackward:
  4840. mm = Movement::FindForward;
  4841. break;
  4842. case Movement::TillForward:
  4843. mm = Movement::TillBackward;
  4844. break;
  4845. case Movement::TillBackward:
  4846. mm = Movement::TillForward;
  4847. break;
  4848. default:
  4849. break;
  4850. }
  4851. }
  4852. tryAddMoveAction();
  4853. addMovementToken(mm, key);
  4854. processCommand(m_tokens);
  4855. }
  4856. void VVim::message(const QString &p_msg)
  4857. {
  4858. if (!p_msg.isEmpty()) {
  4859. qDebug() << "vim msg:" << p_msg;
  4860. emit vimMessage(p_msg);
  4861. }
  4862. }
  4863. const QMap<QChar, VVim::Register> &VVim::getRegisters() const
  4864. {
  4865. return s_registers;
  4866. }
  4867. const VVim::Marks &VVim::getMarks() const
  4868. {
  4869. return m_marks;
  4870. }
  4871. QChar VVim::getCurrentRegisterName() const
  4872. {
  4873. return m_regName;
  4874. }
  4875. QString VVim::getPendingKeys() const
  4876. {
  4877. QString str;
  4878. for (auto const & key : m_pendingKeys) {
  4879. str.append(keyToString(key.m_key, key.m_modifiers));
  4880. }
  4881. return str;
  4882. }
  4883. void VVim::setCurrentRegisterName(QChar p_reg)
  4884. {
  4885. m_regName = p_reg;
  4886. }
  4887. bool VVim::checkMode(VimMode p_mode)
  4888. {
  4889. return m_mode == p_mode;
  4890. }
  4891. bool VVim::processCommandLine(VVim::CommandLineType p_type, const QString &p_cmd)
  4892. {
  4893. setMode(VimMode::Normal);
  4894. bool ret = false;
  4895. switch (p_type) {
  4896. case CommandLineType::Command:
  4897. ret = executeCommand(p_cmd);
  4898. break;
  4899. case CommandLineType::SearchForward:
  4900. // Fall through.
  4901. case CommandLineType::SearchBackward:
  4902. {
  4903. SearchItem item = fetchSearchItem(p_type, p_cmd);
  4904. m_editor->findText(item.m_text, item.m_options, item.m_forward);
  4905. m_searchHistory.addItem(item);
  4906. m_searchHistory.resetIndex();
  4907. break;
  4908. }
  4909. default:
  4910. break;
  4911. }
  4912. return ret;
  4913. }
  4914. void VVim::processCommandLineChanged(VVim::CommandLineType p_type,
  4915. const QString &p_cmd)
  4916. {
  4917. setMode(VimMode::Normal);
  4918. if (p_type == CommandLineType::SearchForward
  4919. || p_type == CommandLineType::SearchBackward) {
  4920. // Peek text.
  4921. SearchItem item = fetchSearchItem(p_type, p_cmd);
  4922. m_editor->peekText(item.m_text, item.m_options, item.m_forward);
  4923. }
  4924. }
  4925. void VVim::processCommandLineCancelled()
  4926. {
  4927. m_searchHistory.resetIndex();
  4928. m_editor->clearIncrementalSearchedWordHighlight();
  4929. }
  4930. VVim::SearchItem VVim::fetchSearchItem(VVim::CommandLineType p_type,
  4931. const QString &p_cmd)
  4932. {
  4933. Q_ASSERT(p_type == CommandLineType::SearchForward
  4934. || p_type == CommandLineType::SearchBackward);
  4935. SearchItem item;
  4936. item.m_rawStr = p_cmd;
  4937. item.m_text = p_cmd;
  4938. item.m_forward = p_type == CommandLineType::SearchForward;
  4939. if (p_cmd.indexOf("\\C") > -1) {
  4940. item.m_options |= FindOption::CaseSensitive;
  4941. item.m_text.remove("\\C");
  4942. }
  4943. item.m_options |= FindOption::RegularExpression;
  4944. return item;
  4945. }
  4946. bool VVim::executeCommand(const QString &p_cmd)
  4947. {
  4948. bool validCommand = true;
  4949. QString msg;
  4950. Q_ASSERT(m_tokens.isEmpty() && m_keys.isEmpty());
  4951. if (p_cmd.isEmpty()) {
  4952. return true;
  4953. }else if (p_cmd.size() == 1) {
  4954. if (p_cmd == "w") {
  4955. // :w, save current file.
  4956. emit m_editor->object()->saveNote();
  4957. msg = tr("Note has been saved");
  4958. } else if (p_cmd == "q") {
  4959. // :q, quit edit mode.
  4960. emit m_editor->object()->discardAndRead();
  4961. msg = tr("Quit");
  4962. } else if (p_cmd == "x") {
  4963. // :x, save if there is any change and quit edit mode.
  4964. emit m_editor->object()->saveAndRead();
  4965. msg = tr("Quit with note having been saved");
  4966. } else {
  4967. validCommand = false;
  4968. }
  4969. } else if (p_cmd.size() == 2) {
  4970. if (p_cmd == "wq") {
  4971. // :wq, save change and quit edit mode.
  4972. // We treat it same as :x.
  4973. emit m_editor->object()->saveAndRead();
  4974. msg = tr("Quit with note having been saved");
  4975. } else if (p_cmd == "q!") {
  4976. // :q!, discard change and quit edit mode.
  4977. emit m_editor->object()->discardAndRead();
  4978. msg = tr("Quit");
  4979. } else {
  4980. validCommand = false;
  4981. }
  4982. } else if (p_cmd == "nohlsearch") {
  4983. // :nohlsearch, clear highlight search.
  4984. clearSearchHighlight();
  4985. } else {
  4986. validCommand = false;
  4987. }
  4988. if (!validCommand) {
  4989. bool allDigits = true;
  4990. for (int i = 0; i < p_cmd.size(); ++i) {
  4991. if (!p_cmd[i].isDigit()) {
  4992. allDigits = false;
  4993. break;
  4994. }
  4995. }
  4996. // All digits.
  4997. // Jump to a specific line.
  4998. if (allDigits) {
  4999. bool ok;
  5000. int num = p_cmd.toInt(&ok, 10);
  5001. if (num == 0) {
  5002. num = 1;
  5003. }
  5004. if (ok && num > 0) {
  5005. m_tokens.append(Token(num));
  5006. tryAddMoveAction();
  5007. addMovementToken(Movement::LineJump);
  5008. processCommand(m_tokens);
  5009. validCommand = true;
  5010. }
  5011. }
  5012. }
  5013. if (!validCommand) {
  5014. message(tr("Not an editor command: %1").arg(p_cmd));
  5015. } else {
  5016. message(msg);
  5017. }
  5018. return validCommand;
  5019. }
  5020. bool VVim::hasNonDigitPendingKeys(const QList<Key> &p_keys)
  5021. {
  5022. for (auto const &key : p_keys) {
  5023. if (!key.isDigit()) {
  5024. return true;
  5025. }
  5026. }
  5027. return false;
  5028. }
  5029. bool VVim::hasNonDigitPendingKeys()
  5030. {
  5031. return hasNonDigitPendingKeys(m_keys);
  5032. }
  5033. bool VVim::processLeaderSequence(const Key &p_key)
  5034. {
  5035. // Different from Vim:
  5036. // If it is not a valid sequence, we just do nothing here.
  5037. V_ASSERT(checkPendingKey(Key(Qt::Key_Backslash)));
  5038. bool validSequence = true;
  5039. QList<Key> replaySeq;
  5040. if (p_key == Key(Qt::Key_Y)) {
  5041. // <leader>y, "+y
  5042. replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
  5043. replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
  5044. replaySeq.append(Key(Qt::Key_Y));
  5045. } else if (p_key == Key(Qt::Key_D)) {
  5046. // <leader>d, "+d
  5047. replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
  5048. replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
  5049. replaySeq.append(Key(Qt::Key_D));
  5050. } else if (p_key == Key(Qt::Key_P)) {
  5051. // <leader>p, "+p
  5052. replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
  5053. replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
  5054. replaySeq.append(Key(Qt::Key_P));
  5055. } else if (p_key == Key(Qt::Key_P, Qt::ShiftModifier)) {
  5056. // <leader>P, "+P
  5057. replaySeq.append(Key(Qt::Key_QuoteDbl, Qt::ShiftModifier));
  5058. replaySeq.append(Key(Qt::Key_Plus, Qt::ShiftModifier));
  5059. replaySeq.append(Key(Qt::Key_P, Qt::ShiftModifier));
  5060. } else if (p_key == Key(Qt::Key_Space)) {
  5061. // <leader><space>, clear search highlight
  5062. clearSearchHighlight();
  5063. } else if (p_key == Key(Qt::Key_W)) {
  5064. // <leader>w, save note
  5065. emit m_editor->object()->saveNote();
  5066. message(tr("Note has been saved"));
  5067. } else {
  5068. validSequence = false;
  5069. }
  5070. if (!replaySeq.isEmpty()) {
  5071. // Replay the sequence.
  5072. m_replayLeaderSequence = true;
  5073. m_keys.clear();
  5074. for (int i = 0; i < 2; ++i) {
  5075. m_pendingKeys.pop_back();
  5076. }
  5077. for (auto const &key : replaySeq) {
  5078. bool ret = handleKeyPressEvent(key.m_key, key.m_modifiers);
  5079. if (!ret) {
  5080. break;
  5081. }
  5082. }
  5083. m_replayLeaderSequence = false;
  5084. } else {
  5085. resetState();
  5086. }
  5087. return validSequence;
  5088. }
  5089. VVim::LocationStack::LocationStack(int p_maximum)
  5090. : m_pointer(0), c_maximumLocations(p_maximum < 10 ? 10 : p_maximum)
  5091. {
  5092. }
  5093. bool VVim::LocationStack::hasPrevious() const
  5094. {
  5095. return m_pointer > 0;
  5096. }
  5097. bool VVim::LocationStack::hasNext() const
  5098. {
  5099. return m_pointer < m_locations.size() - 1;
  5100. }
  5101. void VVim::LocationStack::addLocation(const QTextCursor &p_cursor)
  5102. {
  5103. int blockNumber = p_cursor.block().blockNumber();
  5104. int pib = p_cursor.positionInBlock();
  5105. // Remove older location with the same block number.
  5106. for (auto it = m_locations.begin(); it != m_locations.end();) {
  5107. if (it->m_blockNumber == blockNumber) {
  5108. it = m_locations.erase(it);
  5109. break;
  5110. } else {
  5111. ++it;
  5112. }
  5113. }
  5114. if (m_locations.size() >= c_maximumLocations) {
  5115. m_locations.removeFirst();
  5116. }
  5117. m_locations.append(Location(blockNumber, pib));
  5118. m_pointer = m_locations.size();
  5119. qDebug() << QString("add location (%1,%2), pointer=%3")
  5120. .arg(blockNumber).arg(pib).arg(m_pointer);
  5121. }
  5122. const VVim::Location &VVim::LocationStack::previousLocation(const QTextCursor &p_cursor)
  5123. {
  5124. V_ASSERT(hasPrevious());
  5125. if (m_pointer == m_locations.size()) {
  5126. // Add current location to the stack.
  5127. addLocation(p_cursor);
  5128. m_pointer = m_locations.size() - 1;
  5129. }
  5130. // Jump to previous location.
  5131. if (m_pointer > 0) {
  5132. --m_pointer;
  5133. }
  5134. qDebug() << QString("previous location (%1,%2), pointer=%3, size=%4")
  5135. .arg(m_locations.at(m_pointer).m_blockNumber)
  5136. .arg(m_locations.at(m_pointer).m_positionInBlock)
  5137. .arg(m_pointer).arg(m_locations.size());
  5138. return m_locations.at(m_pointer);
  5139. }
  5140. const VVim::Location &VVim::LocationStack::nextLocation()
  5141. {
  5142. V_ASSERT(hasNext());
  5143. ++m_pointer;
  5144. qDebug() << QString("next location (%1,%2), pointer=%3, size=%4")
  5145. .arg(m_locations.at(m_pointer).m_blockNumber)
  5146. .arg(m_locations.at(m_pointer).m_positionInBlock)
  5147. .arg(m_pointer).arg(m_locations.size());
  5148. return m_locations.at(m_pointer);
  5149. }
  5150. VVim::Marks::Marks()
  5151. {
  5152. for (char ch = 'a'; ch <= 'z'; ++ch) {
  5153. m_marks[QChar(ch)] = Mark();
  5154. }
  5155. }
  5156. void VVim::Marks::setMark(QChar p_name, const QTextCursor &p_cursor)
  5157. {
  5158. auto it = m_marks.find(p_name);
  5159. if (it == m_marks.end()) {
  5160. return;
  5161. }
  5162. it->m_location.m_blockNumber = p_cursor.block().blockNumber();
  5163. it->m_location.m_positionInBlock = p_cursor.positionInBlock();
  5164. it->m_text = p_cursor.block().text().trimmed();
  5165. it->m_name = p_name;
  5166. m_lastUsedMark = p_name;
  5167. qDebug() << QString("set mark %1 to (%2,%3)")
  5168. .arg(p_name)
  5169. .arg(it->m_location.m_blockNumber)
  5170. .arg(it->m_location.m_positionInBlock);
  5171. }
  5172. void VVim::Marks::clearMark(QChar p_name)
  5173. {
  5174. auto it = m_marks.find(p_name);
  5175. if (it == m_marks.end()) {
  5176. return;
  5177. }
  5178. it->m_location = Location();
  5179. it->m_text.clear();
  5180. if (m_lastUsedMark == p_name) {
  5181. m_lastUsedMark = QChar();
  5182. }
  5183. }
  5184. VVim::Location VVim::Marks::getMarkLocation(QChar p_name)
  5185. {
  5186. auto it = m_marks.find(p_name);
  5187. if (it == m_marks.end()) {
  5188. return Location();
  5189. }
  5190. if (it->m_location.isValid()) {
  5191. m_lastUsedMark = p_name;
  5192. }
  5193. return it->m_location;
  5194. }
  5195. const QMap<QChar, VVim::Mark> &VVim::Marks::getMarks() const
  5196. {
  5197. return m_marks;
  5198. }
  5199. QChar VVim::Marks::getLastUsedMark() const
  5200. {
  5201. return m_lastUsedMark;
  5202. }
  5203. void VVim::processTitleJump(const QList<Token> &p_tokens, bool p_forward, int p_relativeLevel)
  5204. {
  5205. int repeat = 1;
  5206. if (p_tokens.size() == 1) {
  5207. Token to = p_tokens.first();
  5208. if (to.isRepeat()) {
  5209. repeat = to.m_repeat;
  5210. } else {
  5211. return;
  5212. }
  5213. } else if (!p_tokens.isEmpty()) {
  5214. return;
  5215. }
  5216. QTextCursor cursor = m_editor->textCursorW();
  5217. if (m_editor->jumpTitle(p_forward, p_relativeLevel, repeat)) {
  5218. // Record current location.
  5219. m_locations.addLocation(cursor);
  5220. }
  5221. }
  5222. void VVim::SearchHistory::addItem(const SearchItem &p_item)
  5223. {
  5224. m_isLastItemForward = p_item.m_forward;
  5225. if (m_isLastItemForward) {
  5226. m_forwardItems.push_back(p_item);
  5227. m_forwardIdx = m_forwardItems.size();
  5228. } else {
  5229. m_backwardItems.push_back(p_item);
  5230. m_backwardIdx = m_forwardItems.size();
  5231. }
  5232. qDebug() << "search history add item" << m_isLastItemForward
  5233. << m_forwardIdx << m_forwardItems.size()
  5234. << m_backwardIdx << m_backwardItems.size();
  5235. }
  5236. const VVim::SearchItem &VVim::SearchHistory::lastItem() const
  5237. {
  5238. if (m_isLastItemForward) {
  5239. Q_ASSERT(!m_forwardItems.isEmpty());
  5240. return m_forwardItems.back();
  5241. } else {
  5242. Q_ASSERT(!m_backwardItems.isEmpty());
  5243. return m_backwardItems.back();
  5244. }
  5245. }
  5246. const VVim::SearchItem &VVim::SearchHistory::nextItem(bool p_forward)
  5247. {
  5248. Q_ASSERT(hasNext(p_forward));
  5249. return p_forward ? m_forwardItems.at(++m_forwardIdx)
  5250. : m_backwardItems.at(++m_backwardIdx);
  5251. }
  5252. // Return previous item in the @p_forward stack.
  5253. const VVim::SearchItem &VVim::SearchHistory::previousItem(bool p_forward)
  5254. {
  5255. Q_ASSERT(hasPrevious(p_forward));
  5256. qDebug() << "previousItem" << p_forward << m_forwardItems.size() << m_backwardItems.size()
  5257. << m_forwardIdx << m_backwardIdx;
  5258. return p_forward ? m_forwardItems.at(--m_forwardIdx)
  5259. : m_backwardItems.at(--m_backwardIdx);
  5260. }
  5261. void VVim::SearchHistory::resetIndex()
  5262. {
  5263. m_forwardIdx = m_forwardItems.size();
  5264. m_backwardIdx = m_backwardItems.size();
  5265. }
  5266. QString VVim::getNextCommandHistory(VVim::CommandLineType p_type,
  5267. const QString &p_cmd)
  5268. {
  5269. Q_UNUSED(p_cmd);
  5270. bool forward = false;
  5271. QString cmd;
  5272. switch (p_type) {
  5273. case CommandLineType::SearchForward:
  5274. forward = true;
  5275. // Fall through.
  5276. case CommandLineType::SearchBackward:
  5277. if (m_searchHistory.hasNext(forward)) {
  5278. return m_searchHistory.nextItem(forward).m_rawStr;
  5279. } else {
  5280. m_searchHistory.resetIndex();
  5281. }
  5282. break;
  5283. default:
  5284. break;
  5285. }
  5286. return cmd;
  5287. }
  5288. // Get the previous command in history of @p_type. @p_cmd is the current input.
  5289. QString VVim::getPreviousCommandHistory(VVim::CommandLineType p_type,
  5290. const QString &p_cmd)
  5291. {
  5292. Q_UNUSED(p_cmd);
  5293. bool forward = false;
  5294. QString cmd;
  5295. switch (p_type) {
  5296. case CommandLineType::SearchForward:
  5297. forward = true;
  5298. // Fall through.
  5299. case CommandLineType::SearchBackward:
  5300. if (m_searchHistory.hasPrevious(forward)) {
  5301. return m_searchHistory.previousItem(forward).m_rawStr;
  5302. }
  5303. break;
  5304. default:
  5305. break;
  5306. }
  5307. return cmd;
  5308. }
  5309. void VVim::clearSearchHighlight()
  5310. {
  5311. m_editor->clearSearchedWordHighlight();
  5312. }
  5313. QString VVim::readRegister(int p_key, int p_modifiers)
  5314. {
  5315. Key keyInfo(p_key, p_modifiers);
  5316. QChar reg = keyToRegisterName(keyInfo);
  5317. if (!reg.isNull()) {
  5318. return getRegister(reg).read();
  5319. }
  5320. return "";
  5321. }
  5322. void VVim::amendCursorPosition()
  5323. {
  5324. if (checkMode(VimMode::Normal)) {
  5325. QTextCursor cursor = m_editor->textCursorW();
  5326. if (cursor.atBlockEnd() && !cursor.atBlockStart()) {
  5327. // Normal mode and cursor at the end of a non-empty block.
  5328. cursor.movePosition(QTextCursor::PreviousCharacter);
  5329. m_editor->setTextCursorW(cursor);
  5330. }
  5331. }
  5332. }
  5333. void VVim::handleMousePressed(QMouseEvent *p_event)
  5334. {
  5335. Q_UNUSED(p_event);
  5336. QTextCursor cursor = m_editor->textCursorW();
  5337. if ((checkMode(VimMode::Visual) || checkMode(VimMode::VisualLine))
  5338. && p_event->buttons() != Qt::RightButton) {
  5339. setMode(VimMode::Normal);
  5340. } else if (checkMode(VimMode::Normal)) {
  5341. if (cursor.hasSelection()) {
  5342. setMode(VimMode::Visual, false);
  5343. maintainSelectionInVisualMode();
  5344. }
  5345. }
  5346. }
  5347. void VVim::handleMouseMoved(QMouseEvent *p_event)
  5348. {
  5349. if (p_event->buttons() != Qt::LeftButton) {
  5350. return;
  5351. }
  5352. QTextCursor cursor = m_editor->textCursorW();
  5353. if (cursor.hasSelection()) {
  5354. if (checkMode(VimMode::Normal)) {
  5355. int pos = cursor.position();
  5356. int anchor = cursor.anchor();
  5357. QTextBlock block = cursor.document()->findBlock(anchor);
  5358. if (anchor > 0 && anchor == block.position() + block.length() - 1) {
  5359. // Move anchor left.
  5360. cursor.setPosition(anchor - 1);
  5361. cursor.setPosition(pos, QTextCursor::KeepAnchor);
  5362. m_editor->setTextCursorW(cursor);
  5363. }
  5364. setMode(VimMode::Visual, false);
  5365. maintainSelectionInVisualMode();
  5366. } else if (checkMode(VimMode::Visual)) {
  5367. // We need to assure we always select the character on m_positionBeforeVisualMode.
  5368. maintainSelectionInVisualMode();
  5369. }
  5370. } else if (checkMode(VimMode::Visual)) {
  5371. // User move cursor in Visual mode. Now the cursor and anchor
  5372. // are at the same position.
  5373. maintainSelectionInVisualMode();
  5374. }
  5375. }
  5376. void VVim::handleMouseReleased(QMouseEvent *p_event)
  5377. {
  5378. if (checkMode(VimMode::Normal) && p_event->button() == Qt::LeftButton) {
  5379. QTextCursor cursor = m_editor->textCursorW();
  5380. if (cursor.hasSelection()) {
  5381. return;
  5382. }
  5383. amendCursorPosition();
  5384. }
  5385. }
  5386. void VVim::setCursorBlockMode(VEditor *p_cursor, CursorBlock p_mode)
  5387. {
  5388. p_cursor->setCursorBlockModeW(p_mode);
  5389. }
  5390. bool VVim::useLeftSideOfCursor(const QTextCursor &p_cursor)
  5391. {
  5392. if (!checkMode(VimMode::Visual)) {
  5393. return false;
  5394. }
  5395. Q_ASSERT(m_positionBeforeVisualMode >= 0);
  5396. return p_cursor.position() > m_positionBeforeVisualMode;
  5397. }