修正vimrepress的一个bug » 荒野无灯weblog

Keep It Simple, Stupid.

荒野无灯weblog

修正vimrepress的一个bug

继前两篇文章:《Hacklog » 给vimrepress增加显示分类的功能并让它支持CodeColorer插件》,《Hacklog » 修改wordpress xmlrpc API搞定通过vimrepress上传图片时没办法显示缩略图的问题》,这是第三篇关于这个插件的了。
用VIM写博客很方便,不用打开浏览拖来拖去了。帖代码或者HTML标签神马的也不用
一个一个敲,用zencoding-vim 这个插件即可。
这次修复的bug是在《Hacklog » 给vimrepress增加显示分类的功能并让它支持CodeColorer插件
一文中说的那个httplib.IncompleteRead: IncompleteRead(8579 bytes read, 32490 more expected) error.一般网络比较差的时候,或者只要显示的文章标题条数超过10条,100%出此错误。
在T上问依云童鞋,他给出我一个网址,最终解决了这个问题。
传送门:baverman的《Bad servers, chunked encoding and IncompleteRead

总结下这两天对vimpress插件做的修改:

  1. 增加显示分类的功能
  2. 添加对wordpress CodeColorer插件的支持
  3. 修改上传图片后插入时的HTML标签模板,使之默认显示中等大小图片,由a标签指向原图(需要修改wordpress xmlrpc server)
  4. 修正显示文章列表时的bug

由于以下源码里面有cc标签,不能在cc标签里面包含cc标签,因此cc标签那个闭合符号
我给用空格隔开了(由 变成了 [ / cc ] )。


"#######################################################################
" Copyright (C) 2007 Adrien Friggeri.
"
" This program is free software; you can redistribute it and/or modify
" it under the terms of the GNU General Public License as published by
" the Free Software Foundation; either version 2, or (at your option)
" any later version.
"
" This program is distributed in the hope that it will be useful,
" but WITHOUT ANY WARRANTY; without even the implied warranty of
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
" GNU General Public License for more details.
"
" You should have received a copy of the GNU General Public License
" along with this program; if not, write to the Free Software Foundation,
" Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  
" 
" Maintainer:   Adrien Friggeri 
"               Pigeond 
"               Preston M.[BOYPT] 
"               Justin Sattery 
"               Lenin Lee 
"               Conner McDaniel 
"
" URL:      http://www.friggeri.net/projets/vimblog/
"           http://pigeond.net/blog/2009/05/07/vimpress-again/
"           http://pigeond.net/git/?p=vimpress.git
"           http://apt-blog.net
"           http://fzysqr.com/
"
" VimRepress 
"    - A mod of a mod of a mod of Vimpress.   
"    - A vim plugin fot writting your wordpress blog.
"
" Version:  2.1.0beta
"
" Configure: Add blog configure into your .vimrc (password optional)
"
" let VIMPRESS=[{'username':'user',
"               \'password':'pass',
"               \'blog_url':'http://your-first-blog.com/'
"               \},
"               \{'username':'user',
"               \'blog_url':'http://your-second-blog.com/'
"               \}]
"
"#######################################################################

if !has("python")
    finish
endif

function! CompSave(ArgLead, CmdLine, CursorPos)
  return "publish\ndraft\n"
endfunction

function! CompPrev(ArgLead, CmdLine, CursorPos)
  return "local\npublish\ndraft\n"
endfunction

function! CompEditType(ArgLead, CmdLine, CursorPos)
  return "post\npage\n"
endfunction

fun! Completable(findstart, base)
  if a:findstart
    " locate the start of the word
    let line = getline('.')
    let start = col('.') - 1
    while start > 0 && line[start - 1] =~ '\a'
      let start -= 1
    endwhile
    return start
  else
    " find matching items
    let res = []
    for m in split(s:completable,"|")
      if m =~ '^' . a:base
        call add(res, m)
      endif
    endfor
    return res
  endif
endfun

command! -nargs=* -complete=custom,CompEditType BlogList exec('py blog_list()')
command! -nargs=? -complete=custom,CompEditType BlogCate exec("py blog_list_cates()") 

command! -nargs=? -complete=custom,CompEditType BlogNew exec('py blog_new()')
command! -nargs=? -complete=custom,CompSave BlogSave exec('py blog_save()')
command! -nargs=? -complete=custom,CompPrev BlogPreview exec('py blog_preview()')
command! -nargs=1 -complete=file BlogUpload exec('py blog_upload_media()')
command! -nargs=1 BlogOpen exec('py blog_guess_open()')
command! -nargs=? BlogSwitch exec('py blog_config_switch()')
command! -nargs=? BlogCode exec('py blog_append_code()')

python < < EOF
# -*- coding: utf-8 -*-
import urllib, urllib2, vim, xml.dom.minidom, xmlrpclib, sys, string, re, os, mimetypes, webbrowser, tempfile, time,operator,httplib
try:
    import markdown
except ImportError:
    try:
        import markdown2 as markdown
    except ImportError:
        class markdown_stub(object):
            def markdown(self, n):
                raise VimPressException("The package python-markdown is required and is either not present or not properly installed.")
        markdown = markdown_stub()

#patch start
#read function  patch to avoid httplib.IncompleteRead: IncompleteRead(8579 bytes read, 32490 more expected)
#by baverman[http://bobrochel.blogspot.com/2010/11/bad-servers-chunked-encoding-and.html]
def patch_http_response_read(func):
    def inner(*args):
        try:
            return func(*args)
        except httplib.IncompleteRead, e:
            return e.partial

    return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
#patch end

image_template = '%(file)s'
blog_username = None
blog_password = None
blog_url = None
blog_conf_index = 0
vimpress_view = 'edit'
vimpress_temp_dir = ''

mw_api = None
wp_api = None
marker = ("=========== Meta ============", "=============================", "========== Content ==========")
list_view_key_map = dict(enter = "", delete = "")

tag_string = ""
tag_re = re.compile(tag_string % dict(url = '(?P\S+)', file = '(?P\S+)'))

default_meta = dict(strid = "", title = "", slug = "", 
        cats = "", tags = "", editformat = "HTML", edittype = "post", textattach = '')

class VimPressException(Exception):
    pass

class VimPressFailedGetMkd(VimPressException):
    pass

def blog_meta_parse():
    """
    Parses the meta data region of a blog editing buffer.
    @returns a dictionary of the meta data
    """
    meta = dict()
    start = 0
    while not vim.current.buffer[start][1:].startswith(marker[0]):
        start +=1

    end = start + 1
    while not vim.current.buffer[end][1:].startswith(marker[2]):
        if not vim.current.buffer[end].startswith('"===='):
            line = vim.current.buffer[end][1:].strip().split(":")
            k, v = line[0].strip().lower(), ':'.join(line[1:])
            meta[k.strip().lower()] = v.strip()
        end += 1

    meta["post_begin"] = end + 1
    return meta

def blog_meta_area_update(**kw):
    """
    Updates the meta data region of a blog editing buffer.
    @params **kwargs - keyworded arguments
    """
    start = 0
    while not vim.current.buffer[start][1:].startswith(marker[0]):
        start +=1

    end = start + 1
    while not vim.current.buffer[end][1:].startswith(marker[2]):
        if not vim.current.buffer[end].startswith('"===='):
            line = vim.current.buffer[end][1:].strip().split(":")
            k, v = line[0].strip().lower(), ':'.join(line[1:])
            if k in kw:
                new_line = "\"%s: %s" % (line[0], kw[k])
                vim.current.buffer[end] = new_line
        end += 1

def blog_fill_meta_area(meta):
    """
    Creates the meta data region for a blog editing buffer using a dictionary of meta data. Empty keywords
    are replaced by default values from the default_meta variable.
    @params meta - a dictionary of meta data
    """
    for k in default_meta.keys():
        if k not in meta:
            meta[k] = default_meta[k]

    meta.update(dict(bg = marker[0], mid = marker[1], ed = marker[2]))
    template = dict( \
        post = \
""""%(bg)s
"StrID : %(strid)s
"Title : %(title)s
"Slug  : %(slug)s
"Cats  : %(cats)s
"Tags  : %(tags)s
"%(mid)s
"EditType   : %(edittype)s
"EditFormat : %(editformat)s
"TextAttach : %(textattach)s
"%(ed)s""", 
        page = \
""""%(bg)s
"StrID : %(strid)s
"Title : %(title)s
"Slug  : %(slug)s
"%(mid)s
"EditType   : %(edittype)s
"EditFormat : %(editformat)s
"TextAttach : %(textattach)s
"%(ed)s""") 

    if meta["edittype"] not in ("post", "page"):
        raise VimPressException("Invalid option: %(edittype)s " % meta)
    meta_text = template[meta["edittype"].lower()] % meta
    meta = meta_text.split('\n')
    vim.current.buffer[0] = meta[0]
    vim.current.buffer.append(meta[1:])

def blog_get_mkd_attachment(post):
    """
    Attempts to find a vimpress tag containing a URL for a markdown attachment and parses it.
    @params post - the content of a post
    @returns a dictionary with the attachment's content and URL
    """

    attach = dict()
    try:
        lead = post.rindex("

All Comments (0)
Gravatar image
No Comments