vvim.cpp 161 KB

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