2009-05-02 72 views
3

我需要這幾次,直到現在它才發生在我身上,也許Vim可以爲我做到這一點。我經常保存數量很多,名字不重要的文件(無論如何它們都是臨時的)。如何在Vim中編寫連續的命名文件?

我有一個完整的文件目錄:file001.txt,file002.txt ...(它們並沒有真正命名爲「filexxx.txt」 - 但是爲了討論......)。我經常保存一個新文件,並將其命名爲file434.txt。既然這是我經常做的事情,我想跳過命名檢查部分。

有沒有一種方法可以使vim腳本檢查目錄中最後一個文件xxxx.txt,並將當前緩衝區保存爲filexxx + 1。我應該如何去寫這樣的東西?有沒有人做過這樣的事情?

所有的建議讚賞。

回答

10

將下面的~/.vim/plugin/nextunused.vim

 
" nextunused.vim 

" find the next unused filename that matches the given pattern 
" counting up from 0. The pattern is used by printf(), so use %d for 
" an integer and %03d for an integer left padded with zeroes of length 3. 
function! GetNextUnused(pattern) 
    let i = 0 
    while filereadable(printf(a:pattern,i)) 
    let i += 1 
    endwhile 
    return printf(a:pattern,i) 
endfunction 

" edit the next unused filename that matches the given pattern 
command! -nargs=1 EditNextUnused :execute ':e ' . GetNextUnused('<args>') 
" write the current buffer to the next unused filename that matches the given pattern 
command! -nargs=1 WriteNextUnused :execute ':w ' . GetNextUnused('<args>') 

" To use, try 
" :EditNextUnused temp%d.txt 
" 
" or 
" 
" :WriteNextUnused path/to/file%03d.extension 
" 

所以,如果你在temp0000.txt通過temp0100.txt都已經使用 目錄和你做:WriteNextUnused temp%04d.txt,它將當前緩衝區寫入temp0101.txt

+0

+1對於純vim和注意需要python – ojblass 2009-05-02 05:24:26

0

你可以用許多強大的語言編寫腳本(取決於你的vim編譯的方式),比如perl,python,ruby。如果你有可能使用一個適合這些語言的解釋器編譯的vim,這可能是你編寫你想要的腳本的最簡單的方法。

1

那你可以掏腰包的腳本怎麼樣?這是一個快速的Python腳本,應該能夠完成你所需要的。將該腳本保存爲「highest.py」到您路徑中的某處。從VIM,進入命令行模式,然後鍵入

:蟒蛇highest.py「文件* .TXT」

它返回在當前目錄編號最高的文件,或者沒有文件相匹配的消息。它處理前導0,可以推廣到更復雜的模式。

#!/usr/bin/python 
# 
# Finds the highest numbered file in a directory that matches a given pattern 
# Patterns are specified with a *, where the * will be where the number will occur. 
# 

import os 
import re 
import sys 

highest = ""; 
highestGroup = -1; 

if (len(sys.argv) != 2): 
     print "Usage: python high.py \"pattern*.txt\"" 
     exit() 

pattern = sys.argv[1].replace('*', '(\d*)') 

exp = re.compile(pattern) 

dirList=os.listdir(".") 

for fname in dirList: 
     matched = re.match(exp, fname) 
     if matched: 
       if ((highest == "") or (int(matched.group(1)) > highestGroup)): 
         highest = fname 
         highestGroup = int(matched.group(1)) 

if (highest == ""): 
     print "No files match the pattern: ", pattern 
else: 
     print highest 
相關問題