设为首页 收藏本站
查看: 387|回复: 0

[经验分享] python写vim script 之 山寨版 GTD

[复制链接]

尚未签到

发表于 2017-5-5 11:25:20 | 显示全部楼层 |阅读模式
一直想找个用vim来管理todo列表的script, 没发现特别好用的,
自己写了个,用sqlite来保存数据.
将下面代码存为 SzTodo.vim,放到plugin目录里.
用 :SzTodo  启动.


let  g:sztodo_db_path="/root/.vim/todo"
let  s:list_type="unfinished"
let  s:cur_buf = 0
function! MakeTemplate()
python << EOF
import vim   
vim.command("call SwitchToDetailView()")
vim.command("call SetSyntax()")
template = "=" * 50 + "\n" \
+ "tag:" +"\n" \
+ "title:" +  "\n" \
+ "=" * 50 + "\n"
for index,line in enumerate(template.split("\n")):
if index ==0 :
vim.current.buffer[0]=line
else :
vim.current.buffer.append(line)
EOF
endfunction
function! SaveTodoItem()
python << EOF
import vim   
def loadData(lines):
item=ToDoItem()
content=""
seperates=0
for line in lines:
if line.startswith("====="): seperates=seperates+1
if line.startswith("id:"): item.id=line[3:].strip()
if line.startswith("tag:"): item.tag=line[4:].strip()
if line.startswith("title:"): item.title=line[6:].strip()
if line.startswith("status:"): item.status=line[7:].strip()
if seperates==2 and not line.startswith("===="):
content=content+line+"\n"
item.content=content[:-1]
return item
def addItem(item):
insertSql="insert into SzTodo(tag,title,create_date,status,content) values (?,?,?,?,?)"
con=sqlite.connect(getDbFileName())
cur=con.cursor()
values=(item.tag,item.title,item.create_date,item.status,item.content)
cur.execute(insertSql,values)
con.commit()
con.close()
def updateItem(item):
updateSql="update SzTodo set tag=?,title=?,create_date=?,status=?,content=? where id=?"
con=sqlite.connect(getDbFileName())
cur=con.cursor()
values=(item.tag,item.title,item.create_date,item.status,item.content,item.id)
cur.execute(updateSql,values)
con.commit()
con.close()

data=vim.current.buffer[:]
todoItem=loadData(data)
if not todoItem.title:
print "title can't be empty"
else:
if todoItem.id.strip() == "" :
todoItem.create_date=getCurrentDate()
todoItem.status="unstarted"
addItem(todoItem)
else :
updateItem(todoItem)
print "todo has been saved"
EOF
exec bufwinnr(s:cur_buf) . "wincmd w"  
call ListItems()
endfunction
function! ListItems()
python << EOF
import vim   
listFinished=vim.eval("s:list_type")
vim.current.buffer[:]=None
vim.command("set nonumber")
if listFinished=="finished":
selectSql="select id,tag,title,create_date,content from SzTodo where status == 'done' "
else:
selectSql="select id,tag,title,create_date,content from SzTodo where status != 'done' "
con=sqlite.connect(getDbFileName())
cur=con.cursor()
items=[]
cur.execute(selectSql)

for index,row in enumerate(cur):  
formatedItem=str(row[0])+". "+str(unicode(row[2]).encode("utf-8"))
if index==0:
vim.current.buffer[0]=formatedItem
else :
vim.current.buffer.append(formatedItem)
con.commit()
con.close()
EOF
endfunction
function! SwitchToDetailView()  
let s:cur_buf = bufnr("%")  
let s:szdb_result_buf=bufnr("SztodoDetail")  
if bufwinnr(s:szdb_result_buf) > 0  
exec bufwinnr(s:szdb_result_buf) . "wincmd w"  
%d  
else  
exec 'silent! botright split SztodoDetail'   
exec "e SztodoDetail"  
exec "set nowrap"  
map <silent><buffer>s :call SaveTodoItem()<cr>
endif  
endfunction  
function! ShowItemDetail(preview)
python << EOF
import vim   
(row, col) = vim.current.window.cursor
line = vim.current.buffer[row-1]
id=line[0:line.find(".")]
selectSql="select id,tag,title,create_date,content,status from SzTodo where id=?"
con=sqlite.connect(getDbFileName())
cur=con.cursor()
cur.execute(selectSql,(id,))
todoItem=ToDoItem()
for row in cur:  
todoItem.id=row[0]
todoItem.tag=unicode(row[1]).encode("utf-8")
todoItem.title=unicode(row[2]).encode("utf-8")
todoItem.create_date=unicode(row[3]).encode("utf-8")
todoItem.content=unicode(row[4]).encode("utf-8")
todoItem.status=unicode(row[5]).encode("utf-8")
vim.command("call SwitchToDetailView()")  
vim.command("call SetSyntax()")
for index,line in enumerate(str(todoItem).split("\n")):
if index==0:
vim.current.buffer[0]=line
else:
vim.current.buffer.append(line)
EOF
if a:preview=="true"
exec bufwinnr(s:cur_buf) . "wincmd w"  
endif
endfunction
function! UpdateItemStatus(status)
let choice=input('you really want to update the todo item status to '.a:status."?[y/n]")
if choice=="n"
return
endif
python << EOF
import vim
(row, col) = vim.current.window.cursor
line = vim.current.buffer[row-1]
id=line[0:line.find(".")]
updateSql="update SzTodo set status = ? where id=?"
status=vim.eval("a:status")
con=sqlite.connect(getDbFileName())
cur=con.cursor()
cur.execute(updateSql,(status,id))
con.commit()
con.close()
EOF
endfunction
function! InitDb()
python << EOF
import vim   
import os
createSql="create table SzTodo (id integer primary key , tag char(20), title varchar(200), \
create_date varchar(10),status char(1),content varchar(5000))"
path=os.path.dirname(getDbFileName())
if not os.path.exists(path):
os.makedirs(path)
con=sqlite.connect(getDbFileName())
cur=con.cursor()
cur.execute(createSql)
con.commit()
con.close()
print "db has been created"
EOF
endfunction
function! s:DefSzTodoGlobal()
python << EOF
import vim   
from pysqlite2 import dbapi2 as sqlite
statusDict=dict(done="done",postpone="postpone",doing="doing",unstarted="unstarted")
class ToDoItem(object):
def __init__(self,id="",tag="",title="",content="",create_date="",status=""):
self.id=id
self.tag=tag
self.title=title
self.create_date=create_date
self.status=status
self.content=content
def __str__(self):
return "=" * 50 + "\n" \
+ "id:" + str(self.id) +"\n" \
+ "tag:" + self.tag +"\n" \
+ "title:" + self.title + "\n" \
+ "status:" + self.status + "\n" \
+ "=" * 50 + "\n" \
+ self.content
def getCurrentDate():
from datetime import datetime
t=datetime.now()
return t.strftime("%Y-%m-%d %H:%M")
def getDbFileName():
dbpath=vim.eval("g:sztodo_db_path")
path=os.path.join(dbpath,"todo.dat")
return path
EOF
endfunction
function! StartApp()
python << EOF
import vim   
import os
if not os.path.exists(getDbFileName()):
vim.command("call InitDb()")
vim.command("call ListItems()")
vim.command("call SetMapping()")
EOF
endfunction

function! SetMapping()
map <silent><buffer> o  :call ShowItemDetail("false")<cr>
map <silent><buffer> s  :call ShowItemDetail("true")<cr>
map <silent><buffer> i  :call MakeTemplate()<cr>
map <silent><buffer> r  :call ListItems()<cr>
map <silent><buffer> p  :call UpdateItemStatus("postpone")<cr>
map <silent><buffer> d  :call UpdateItemStatus("done")<cr>
command! -nargs=0 FinishedItem :call FinishedItem()
command! -nargs=0 UnfinishedItem :call UnfinishedItem()
endfunction
function! FinishedItem()
let s:list_type="finished"
call ListItems()
endfunction
function! UnfinishedItem()
let s:list_type="unfinished"
call ListItems()
endfunction
function! SetSyntax()
syn keyword sztodoKeyword tag title id status
syn keyword sztodoStatus unstarted done doing postpone
syn match tag "^tag:.*"
syn match title "^title:.*"
syn match id  "^id:.*"
syn match status  "^status:.*"
hi def link sztodoKeyword Keyword
hi def link sztodoStatus Identifier
hi def link tag String
hi def link id String
hi def link title String
hi def link status String
endfunction
call s:DefSzTodoGlobal()
command! -nargs=0 SzTodo :call StartApp()

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-373414-1-1.html 上篇帖子: Django Python sys.path以及DJANGO_SETTINGS_MODULE的设置 下篇帖子: python练习贴02 Ping服务器(监视)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表