Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
usr_21.txt  ForVim version 9.2.  Last change: 2026 Feb 14     VIM USER MANUALbyBramMoolenaar   Go away and come backThis chapter goes into mixing the use of other programs with Vim.  Either byexecuting program from inside Vim or by leaving Vim and coming back later.Furthermore, thisis about the ways to remember the state of Vim and restoreit later.21.1  Suspend and resume21.2  Executing shell commands21.3  Remembering information;viminfo21.4  Sessions21.5  Views21.6  Modelines     Next chapter:usr_22.txt  Finding the file to edit Previous chapter:usr_20.txt  Typing command-line commands quicklyTable of contents:usr_toc.txt==============================================================================21.1  Suspend and resumeLike mostUnix programs Vim can be suspended by pressingCTRL-Z.  This stopsVim and takes you back to the shellit was started in.  You can thendo anyother commands until you are bored with them.  Then bring back Vim with the"fg" command.CTRL-Z{any sequence of shell commands}fgYou are right back where you left Vim, nothing has changed.   Incase pressingCTRL-Z doesn't work, you can also use ":suspend".Don't forget to bring Vim back to the foreground, you would lose any changesthat you made!OnlyUnix has support for this.  On other systems Vim will starta shell foryou.  This also has the functionality of being able to execute shell commands.But it'sa new shell, not the one that you started Vim from.   When you are running theGUI you can'tgo back to the shell where Vim wasstarted.CTRL-Z will minimize the Vimwindow instead.==============================================================================21.2  Executing shell commandsTo executea single shell command from Vim use ":!{command}".  For example, toseea directory listing::!ls:!dirThe first oneis for Unix, the second one for MS-Windows.   Vim will execute the program.  Whenit ends you will geta prompt to hit<Enter>.  This allows you to havea lookat the output from the command beforereturning to the text you were editing.   The "!"is also used in other places wherea programis run.  Let's takea lookat an overview::!{program}execute{program}:r !{program}execute{program} and read its output:w !{program}execute{program} and send text to its input:[range]!{program}filter text through{program}Notice that the presence ofa range before "!{program}" makesa bigdifference.  Withoutit executes the program normally, with the rangea numberof text linesis filtered through the program.Executinga whole row of programs this wayis possible.  Buta shellis muchbetterat it.  You can starta new shell this way::shellThisis similar to usingCTRL-Z tosuspend Vim.  The differenceis thata newshellis started.When using theGUI the shell will be using the Vimwindow for its input andoutput.  Since Vimis notaterminal emulator, this will not work perfectly.If you have trouble, try toggling the'guipty' option.  If this still doesn'twork well enough, starta newterminal to run the shell in.  For example with::!xterm&==============================================================================21.3  Remembering information;viminfoAfter editing fora while you will have text in registers, marks invariousfiles,a command linehistory filled with carefully crafted commands.  Whenyou exit Vim all of thisis lost.  But you can getit back!Theviminfo fileis designed to store status information:Command-line and SearchpatternhistoryText inregistersMarks forvarious filesThe bufferlistGlobalvariablesEach time you exit Vimit will store this information ina file, theviminfofile.  When Vim starts again, theviminfo fileis read and the informationrestored.The'viminfo' optionis set by default to restorea limited number of items.You might want to setit to remember more information.  Thisis done throughthe following command::set viminfo=stringThestringspecifies what to save.  Thesyntax of thisstringis an optioncharacter followed by an argument.  The option/argument pairs are separated bycommas.   Takea lookat how you can build up your ownviminfo string.  First, the'optionis used to specify how many files for which you save marks (a-z).  Picka nice even number for this option (1000, for instance).  Your command nowlooks like this::set viminfo='1000Thef option controls whether global marks (A-Z and 0-9) are stored.  If thisoptionis 0, none are stored.  Ifitis 1 or youdo not specify anf option,the marks are stored.  You want this feature, so now you have this::set viminfo='1000,f1The< option controls how many lines are saved for each of the registers.  Bydefault, all the lines are saved.  If 0, nothingis saved.  To avoid addingthousands of lines to yourviminfo file (which might never get used and makesstarting Vim slower) you usea maximum of 500 lines::set viminfo='1000,f1,<500Otheroptions you might want to use::number of lines to save from the command linehistory@number of lines to save from the input linehistory/number of lines to save from the searchhistoryrremovable media, for which no marks will be stored (can beused several times)!globalvariables that start with anuppercaseletter anddon't containlowercase lettershdisable'hlsearch' highlighting whenstarting%the bufferlist (only restored whenstarting Vim without filearguments)cconvert the text using'encoding'nname used for theviminfo file (must be the last option)See the'viminfo' option andviminfo-file for more information.When you run Vim multiple times, the last oneexiting will store itsinformation.  This may cause information that previouslyexiting Vims storedto be lost.  Each item can be remembered only once.GETTING BACK TO WHERE YOU STOPPED VIMYou are halfway editinga file and it's time to leave for holidays.  You exitVim andgo enjoy yourselves, forgetting all about your work.  Aftera coupleof weeks you start Vim, and type:'0And you are right back where you left Vim.  So you can get on with your work.   Vim createsamark each time you exit Vim.  The last oneis '0.  Theposition that'0 pointed tois made '1.  And '1is made to '2, and so forth.Mark '9is lost.   The:marks commandis useful to find out where'0 to '9 will take you.GETTING BACK TO SOME FILEIf you want togo back toa file that you edited recently, but not whenexiting Vim, thereisa slightly more complicated way.  You can seealist offiles by typing the command::oldfiles1: ~/.viminfo2: ~/text/resume.txt3: /tmp/draftNow you would like to edit the second file, whichis in thelist preceded by"2:".  You type::e #<2Instead of ":e" you can use any command that hasa file name argument, the"#<2" item works in the same placeas "%" (current file name) and "#"(alternate file name).  So you can also split thewindow to edit the thirdfile::split #<3That #<123 thingisa bit complicated when you just want to edita file.Fortunately thereisa simpler way::browse oldfiles1: ~/.viminfo2: ~/text/resume.txt3: /tmp/draft-- More--You get the samelist of filesas with:oldfiles.  If you want to edit"resume.txt" first press "q" to stop the listing.  You will geta prompt:Type number and <Enter> (empty cancels):Type "2" and press<Enter> to edit the second file.If you know that the filename containsa pattern, you can also:filter thelist of files::filter /resume/ :browse oldfilesSince thereis only one single matching filename, Vim will directly edit thatfile without prompting.  If thefilter matches several files, you'll getprompted for thelist of matching files instead::filter! /resume/ browse oldfiles1: ~/.viminfo3: /tmp/draftType number and <Enter> (q or empty cancels):Note: this time we filtered out all files NOT matching resume.More infoat:oldfiles,v:oldfiles andc_#<.MOVE INFO FROM ONE VIM TO ANOTHERYou can use the ":wviminfo" and ":rviminfo" commands to save and restore theinformation while still running Vim.  Thisis useful for exchanging registercontents between two instances of Vim, for example.  In the first Vim do::wviminfo! ~/tmp/viminfoAnd in the second Vim do::rviminfo! ~/tmp/viminfoObviously, the "w" stands for "write" and the "r" for "read".   The! characteris used by ":wviminfo" to forcefully overwrite an existingfile.  Whenitis omitted, and the file exists, the informationis merged intothe file.   The! character used for ":rviminfo" means that all the informationisused, this may overwrite existing information.  Without the! only informationthat wasn't setis used.   These commands can also be used to store info and useit again later.  Youcould makea directory full ofviminfo files, each containing info foradifferent purpose.==============================================================================21.4  SessionsSuppose you are editing along, anditis theend of the day.  You want to quitwork and pick up where you left off the next day.  You cando this by savingyour editing session and restoringit the next day.A Vim session contains all the information about what you are editing.This includes things suchas the file list,window layout, global variables,options and other information.  (Exactly whatis rememberedis controlled bythe'sessionoptions' option, described below.)   The following command createsa session file::mksession vimbook.vimLater if you want to restore this session, you can use this command::source vimbook.vimIf you want to start Vim and restorea specific session, you can use thefollowing command:vim -S vimbook.vimThis tells Vim to reada specific file on startup.  The 'S' stands forsession (actually, you can source any Vimscript with -S, thusit mightaswell stand for "source").Thewindows that were open are restored, with the same position and sizeasbefore.  Mappings and option values are like before.   What exactlyis restored depends on the'sessionoptions' option.  Thedefault value is:"blank,buffers,curdir,folds,help,options,tabpages,winsize,terminal".blankkeep emptywindowsbuffersall buffers, not only the ones inawindowcurdirthe current directoryfoldsfolds, also manually created oneshelpthehelpwindowoptionsalloptions and mappingstabpagesalltab pageswinsizewindow sizesterminalincludeterminalwindowsChange this to your liking.  To also restore the size of the Vim window, forexample, use::set sessionoptions+=resizeSESSION HERE, SESSION THEREThe obvious way to use sessionsis when working on different projects.Suppose you store your session files in the directory "~/.vim".  You arecurrently working on the "secret" project and have to switch to the "boring"project::wall:mksession! ~/.vim/secret.vim:source ~/.vim/boring.vimThis first uses ":wall" to write all modified files.  Then the current sessionis saved, using ":mksession!".  This overwrites the previous session.  Thenext time you load the secret session you can continue where you wereat thispoint.  And finally you load the new "boring" session.If you openhelp windows, split and closevarious windows, and generally messup thewindow layout, you cango back to the last saved session::source ~/.vim/boring.vimThus you have completecontrol over whether you want to continue next timewhere you are now, by saving the current setup ina session, or keep thesession fileasastarting point.   Another way of using sessionsis to createawindow layout that you like touse, and save this ina session.  Then you cango back to this layout wheneveryou want.   For example, thisisa nice layout to use:+----------------------------------------+|   VIM- mainhelp file  || ||Move around:  Use the cursor keys, or "h|help.txt================================|explorer   | ||dir    |~ ||dir    |~ ||file    |~ ||file    |~ ||file    |~ ||file    |~ |~/=========[No File]===================|| |+----------------------------------------+This hasahelpwindowat the top, so that you can read this text.  The narrowverticalwindow on the left containsa file explorer.  Thisisa Vimpluginthat lists the contents ofa directory.  You can select files to edit there.More about this in the next chapter.   Create this froma just started Vim with::helpCTRL-W w:vertical split ~/You can resize thewindowsa bit to your liking.  Then save the session with::mksession ~/.vim/mine.vimNow you can start Vim with this layout:vim -S ~/.vim/mine.vimHint: To opena file you see listed in the explorerwindow in the emptywindow, move the cursor to the filename and press "O".  Double clicking withthe mouse will alsodo this.UNIX AND MS-WINDOWSSome people have todo work onMS-Windows systems one day and onUnix anotherday.  If you are one of them, consider adding "slash" and "unix" to'sessionoptions'.  The session files will then be written ina format that canbe used on both systems.  Thisis the command toput in yourvimrc file::set sessionoptions+=unix,slashVim will use theUnix format then, because theMS-Windows Vim can read andwriteUnix files, butUnix Vim can't readMS-Windows format session files.Similarly,MS-Windows Vim understands file names with/ to separate names, butUnix Vim doesn't understand \.SESSIONS AND VIMINFOSessions store many things, but not the position of marks, contents ofregisters and the command line history.  You need to use theviminfo featurefor these things.   In most situations you will want to use sessions separately from viminfo.This can be used to switch to another session, but keep the command linehistory.  Andyank text intoregisters in one session, and pasteit back inanother session.   You might prefer to keep the info with the session.  You will have todothis yourself then.  Example::mksession! ~/.vim/secret.vim:wviminfo! ~/.vim/secret.viminfoAnd to restore this again::source ~/.vim/secret.vim:rviminfo! ~/.vim/secret.viminfo==============================================================================21.5  ViewsA session stores the looks of the whole of Vim.  When you want to store theproperties for onewindow only, usea view.   The use ofaviewis for when you want to edita file ina specific way.For example, you have line numbers enabled with the'number' option anddefineda few folds.  Just like with sessions, you can remember thisview onthe file and restoreit later.  Actually, when you storea session,it storestheview of each window.   There are two basic ways to use views.  The firstis to let Vim picka namefor theview file.  You can restore theview when you later edit the samefile.  To store theview for the current window::mkviewVim will decide where to store the view.  When you later edit the same fileyou get theview back with this command::loadviewThat's easy, isn't it?   Now you want toview the file without the'number' option on, or with allfolds open, you can set theoptions to make thewindow look that way.  Thenstore thisview with::mkview 1Obviously, you can get this back with::loadview 1Now you can switch between the two views on the file by using ":loadview" withand without the "1" argument.   You can store up to ten views for the same file this way, one unnumberedand nine numbered 1 to 9.A VIEW WITH A NAMEThe second basic way to use viewsis by storing theview ina file witha nameyou choose.  Thisview can be loaded while editing another file.  Vim willthen switch to editing the file specified in the view.  Thus you can use thisto quickly switch to editing another file, with all itsoptions setas yousaved them.   For example, to save theview of the current file::mkview ~/.vim/main.vimYou can restoreit with::source ~/.vim/main.vim==============================================================================21.6  ModelinesWhen editinga specific file, you might setoptions specifically for thatfile.  Typing these commands each timeis boring.  Usinga session orview foreditinga file doesn't work when sharing the file between several people.   The solution for this situationis addingamodeline to the file.  Thisisa line of text that tells Vim the values of options, to be used in this fileonly.A typical exampleisaC program where you make indents bya multiple of 4spaces.  This requires setting the'shiftwidth' option to 4.  Thismodelinewilldo that:/* vim:set shiftwidth=4: */Put this lineas one of the first or last five lines in the file.  Whenediting the file, you will notice that'shiftwidth' will have been set tofour.  When editing another file, it's set back to the default value of eight.   For some files themodeline fits well in the header, thusit can beputatthe top of the file.  For text files and other files where themodeline getsin the way of the normal contents,putitat theend of the file.The'modelines' optionspecifies how many linesat the start andend of thefile are inspected for containinga modeline.  To inspect ten lines::set modelines=10The'modeline' option can be used to switch this off.  Do this when you areworkingas root onUnix or Administrator on MS-Windows, or when you don'ttrust the files you are editing::set nomodelineUse this format for the modeline:any-text vim:set {option}={value} ... : any-textThe "any-text" indicates that you canput any text before and after the partthat Vim will use.  This allows makingit look likea comment, like what wasdone above with/* and */.   The "vim:" partis what makes Vim recognize this line.  Theremust bewhitespace before "vim", or "vim"must beat the start of the line.  Thususing something like "gvim:" will not work.   The part between the colonsisa ":set" command.  It works the same wayastyping the ":set" command, except that you need toinsertabackslash beforeacolon (otherwiseit would be seenas theend of the modeline).Another example:// vim:set textwidth=72 dir=c\:\tmp:  use c:\tmp hereThereis an extrabackslash before the first colon, so that it's included inthe ":set" command.  The text after the second colonis ignored, thusa remarkcan be placed there.For more details seemodeline.==============================================================================Next chapter:usr_22.txt  Finding the file to editCopyright: seemanual-copyright  vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp