修正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 ] )。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
"#######################################################################
"
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 <adrien @friggeri.net>
"               Pigeond <http: //pigeond.net/blog/>
"
              Preston M.[BOYPT] <pentie @gmail.com>
"               Justin Sattery <justin .slattery@fzysqr.com>
"
              Lenin Lee <lenin .lee@gmail.com>
"               Conner McDaniel <connermcd @gmail.com>
"

" 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 &#038;&#038; 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(<f -args>)')
command! -nargs=? -complete=custom,CompEditType BlogCate exec("
py blog_list_cates()")

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

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 = '<a href="
%(url)s"><img title="%(file)s" alt="%(file)s" src="%(thumb_url)s" class="aligncenter" />'
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 = "
<enter>", delete = "<delete>")

tag_string = "
<!-- #VIMPRESS_TAG# %(url)s %(file)s -->"
tag_re = re.compile(tag_string % dict(url = '(?P<mkd_url>\S+)', file = '(?P<mkd_name>\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("<!-- ")
        data = re.search(tag_re, post[lead:])
        if data is None:
            raise ValueError()
        attach.update(data.groupdict())
        attach["mkd_rawtext"] = urllib2.urlopen(attach["mkd_url"]).read()
    except ValueError, e:
        return dict()
    except IOError:
        raise VimPressFailedGetMkd("The attachment URL was found but was unable to be read.")

    return attach

def blog_upload_markdown_attachment(post_id, attach_name, mkd_rawtext):
    """
    Uploads the markdown attachment.
    @params post_id     - the id of the post or page
            attach_name - the name of the attachment
            mkd_rawtext - the Markdown content
    """

    bits = xmlrpclib.Binary(mkd_rawtext)

    # New Post, new file
    if post_id == '' or attach_name == '':
        attach_name = "vimpress_%s_mkd.txt" % hex(int(time.time()))[2:]
        overwrite = False
    else:
        overwrite = True

    sys.stdout.write("Markdown file uploading ... ")
    result = mw_api.newMediaObject(1, blog_username, blog_password,
                dict(name = attach_name,
                    type = "text/plain", bits = bits,
                    overwrite = overwrite))
    sys.stdout.write("%s\n" % result["file"])
    return result

def __exception_check(func):
    def __check(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except VimPressException, e:
            sys.stderr.write(str(e))
        except xmlrpclib.Fault, e:
            sys.stderr.write("xmlrpc error: %s" % e.faultString.encode("utf-8"))
        except xmlrpclib.ProtocolError, e:
            sys.stderr.write("xmlrpc error: %s %s" % (e.url, e.errmsg))
        except IOError, e:
            sys.stderr.write("network error: %s" % e)

    return __check

def __vim_encoding_check(func):
    def __check(*args, **kw):
        orig_enc = vim.eval("&#038;encoding")
        if orig_enc != "utf-8":
            modified = vim.eval("&#038;modified")
            buf_list = '\n'.join(vim.current.buffer).decode(orig_enc).encode('utf-8').split('\n')
            del vim.current.buffer[:]
            vim.command("setl encoding=utf-8")
            vim.current.buffer[0] = buf_list[0]
            if len(buf_list) > 1:
                vim.current.buffer.append(buf_list[1:])
            if modified == '0':
                vim.command('setl nomodified')
        return func(*args, **kw)
    return __check

def __xmlrpc_api_check(func):
    def __check(*args, **kw):
        if wp_api is None or mw_api is None:
            blog_update_config()
        return func(*args, **kw)
    return __check

@__exception_check
@__vim_encoding_check
@__xmlrpc_api_check
def blog_save(pub = "draft"):
    """
    Saves the current editing buffer.
    @params pub - either "draft" or "publish"
    """

    if vimpress_view != 'edit':
        raise VimPressException("Command not available at list view.")
    if pub not in ("publish", "draft"):
        raise VimPressException(":BlogSave draft|publish")

    is_publish = (pub == "publish")

    meta = blog_meta_parse()
    rawtext = '\n'.join(vim.current.buffer[meta["post_begin"]:])

    #Translate markdown and upload as attachment
    if meta["editformat"].strip().lower() == "markdown":
        attach = blog_upload_markdown_attachment(
                meta["strid"], meta["textattach"], rawtext)
        blog_meta_area_update(textattach = attach["file"])
        text = markdown.markdown(rawtext.decode('utf-8')).encode('utf-8')

        # Add tag string at the last of the post.
        text += tag_string % attach
    else:
        text = rawtext

    edit_type = meta["edittype"]
    strid = meta["strid"]

    if edit_type.lower() not in ("post", "page"):
        raise VimPressException(
                "Fail to work with edit type %s " % edit_type)

    post_struct = dict(title = meta["title"], wp_slug = meta["slug"],
                    description = text)
    if edit_type == "post":
        post_struct.update(categories = meta["cats"].split(','),
                        mt_keywords = meta["tags"].split(','))

    # New posts
    if strid == '':
        if edit_type == "post":
            strid = mw_api.newPost('', blog_username, blog_password,
                    post_struct, is_publish)
        elif edit_type == "page":
            strid = wp_api.newPage('', blog_username, blog_password,
                    post_struct, is_publish)

        blog_meta_area_update(strid = strid)
        meta["strid"] = strid

        notify = "%s %s.   ID=%s" % \
                (edit_type.capitalize(),
                        "Published" if is_publish else "Saved as draft", strid)

    # Old posts
    else:
        if edit_type == "post":
            mw_api.editPost(strid, blog_username, blog_password,
                    post_struct, is_publish)
        elif edit_type == "page":
            wp_api.editPage('', strid, blog_username, blog_password,
                    post_struct, is_publish)

        notify = "%s edited and %s.   ID=%s" % \
                (edit_type.capitalize(), "published" if is_publish else "saved as a draft", strid)

    sys.stdout.write(notify)
    vim.command('setl nomodified')

    return meta

@__exception_check
@__vim_encoding_check
@__xmlrpc_api_check
def blog_new(edit_type = "post"):
    """
    Creates a new editing buffer of specified type.
    @params edit_type - either "post" or "page"
    """

    global vimpress_view

    if edit_type.lower() not in ("post", "page"):
        raise VimPressException("Invalid option: %s " % edit_type)

    if vimpress_view.startswith("list"):
        currentContent = ['']
        for v in list_view_key_map.values():
            if vim.eval("mapcheck('%s')" % v):
                vim.command('unmap <buffer> %s' % v)
    else:
        currentContent = vim.current.buffer[:]

    blog_wise_open_view()
    vimpress_view = 'edit'
    meta_dict = dict(edittype = edit_type)
    blog_fill_meta_area(meta_dict)
    vim.current.buffer.append(currentContent)
    vim.current.window.cursor = (1, 0)
    vim.command('setl nomodified')
    vim.command('setl textwidth=0')

@__xmlrpc_api_check
def blog_edit(edit_type, post_id):
    """
    Opens a new editing buffer with blog content of specified type and id.
    @params edit_type - either "post" or "page"
            post_id   - the id of the post or page
    """

    global vimpress_view
    vimpress_view = 'edit'

    blog_wise_open_view()

    if edit_type.lower() not in ("post", "page"):
        raise VimPressException("Invalid option: %s " % edit_type)

    if edit_type.lower() == "post":
        data = mw_api.getPost(post_id, blog_username, blog_password)
    else:
        data = wp_api.getPage('', post_id, blog_username, blog_password)

    meta_dict = dict(\
            strid = str(post_id),
            title = data["title"].encode("utf-8"),
            slug = data["wp_slug"].encode("utf-8"))
    content = data["description"].encode("utf-8")

    if edit_type.lower() == "post":
        meta_dict["cats"] = ",".join(data["categories"]).encode("utf-8")
        meta_dict["tags"] = data["mt_keywords"].encode("utf-8")

    meta_dict['editformat'] = "HTML"
    meta_dict['edittype'] = edit_type

    try:
        attach = blog_get_mkd_attachment(content)
        if "mkd_rawtext" in attach:
            meta_dict['editformat'] = "Markdown"
            meta_dict['textattach'] = attach["mkd_name"]
            content = attach["mkd_rawtext"]
    except VimPressFailedGetMkd:
        pass

    blog_fill_meta_area(meta_dict)
    meta = blog_meta_parse()
    vim.current.buffer.append(content.split('\n'))
    vim.current.window.cursor = (meta["post_begin"], 0)
    vim.command('setl nomodified')
    vim.command('setl textwidth=0')

    for v in list_view_key_map.values():
        if vim.eval("mapcheck('%s')" % v):
            vim.command('unmap </buffer><buffer> %s' % v)

@__xmlrpc_api_check
def blog_delete(edit_type, post_id):
    """
    Deletes a page or post of specified id.
    @params edit_type - either "page" or "post"
            post_id   - the id of the post or page
    """

    global vimpress_view
    if edit_type.lower() not in ("post", "page"):
        raise VimPressException("Invalid option: %s " % edit_type)

    if edit_type.lower() == "post":
        deleted = mw_api.deletePost('0123456789ABCDEF', post_id, blog_username, blog_password, True)
    else:
        deleted = wp_api.deletePage('', blog_username, blog_password, post_id)

    if deleted:
        sys.stdout.write("Deleted %s id %s. \n" % (edit_type, str(post_id)))
    else:
        sys.stdout.write("There was a problem deleting the %s.\n" % edit_type)

    if vimpress_view.startswith("list"):
        blog_list(edit_type)

@__exception_check
def blog_list_on_key_press(action):
    """
    Calls blog open on the current line of a listing buffer.
    """

    global vimpress_view
    if action.lower() not in ("open", "delete"):
        raise VimPressException("Invalid option: %s" % action)

    global vimpress_view
    row = vim.current.window.cursor[0]
    line = vim.current.buffer[row - 1]
    id = line.split()[0]
    title = line[len(id):].strip()

    try:
        int(id)
    except ValueError:
        raise VimPressException("Move cursor to a post/page line and press KEY.")

    if len(title) > 30:
        title = title[:30] + ' ...'

    if action.lower() == "delete":
        confirm = vim_input("Confirm Delete [%s]: %s? [yes/NO]" % (id,title))
        if confirm != 'yes':
            sys.stdout.write("Delete Aborted.\n")
            return

    vim.command("setl modifiable")
    del vim.current.buffer[:]
    vim.command("setl nomodified")

    if vimpress_view == "list_page":
        edit_type = "page"
    elif vimpress_view == "list_post":
        edit_type = "post"
    else:
        raise VimPressException("Command only available in list view.")

    if action == "open":
        blog_edit(edit_type, int(id))
    elif action == "delete":
        blog_delete(edit_type, int(id))

@__exception_check
@__vim_encoding_check
@__xmlrpc_api_check
def blog_list(edit_type = "post", count = "30"):
    """
    Creates a listing buffer of specified type.
    @params edit_type - either "post(s)" or "page(s)"
            count     - number to show (only for posts)
    """

    global vimpress_view
    vimpress_view = 'list'

    blog_wise_open_view()
    vim.current.buffer[0] = ""====== List of %ss in %s =========" % (edit_type.capitalize(), blog_url)

    if edit_type.lower() not in ("
post", "posts", "page", "pages"):
        raise VimPressException("
Invalid option: %s " % edit_type)

    if edit_type.lower() in ("
post", "posts"):
        vimpress_view = 'list_post'
        allposts = mw_api.getRecentPosts('',blog_username, blog_password, int(count))
        vim.current.buffer.append(\
            [(u"
%(postid)s\t%(title)s" % p).encode('utf8') for p in allposts])
    else:
        vimpress_view = 'list_page'
        pages = wp_api.getPageList('', blog_username, blog_password)
        vim.current.buffer.append(\
            [(u"
%(page_id)s\t%(page_title)s" % p).encode('utf8') for p in pages])

    vim.command("
setl nomodified")
    vim.command("
setl nomodifiable")
    vim.current.window.cursor = (2, 0)
    vim.command("
map <silent> <buffer> %(enter)s :py blog_list_on_key_press('open')<cr>" % list_view_key_map)
    vim.command("
map <silent> <buffer> %(delete)s :py blog_list_on_key_press('delete')<cr>" % list_view_key_map)
    sys.stdout.write("
Press <enter> to edit. <delete> to move to trash.\n")

@__exception_check
@__vim_encoding_check
@__xmlrpc_api_check
def blog_upload_media(file_path):
    "
""
    Uploads a file to the blog.
    @params file_path - the file's path
    """
    if vimpress_view != '
edit':
        raise VimPressException("Command not available at list view.")
    if not os.path.exists(file_path):
        raise VimPressException("File does not exist: %s" % file_path)

    name = os.path.basename(file_path)
    filetype = mimetypes.guess_type(file_path)[0]
    with open(file_path) as f:
        bits = xmlrpclib.Binary(f.read())

    result = mw_api.newMediaObject('
', blog_username, blog_password,
            dict(name = name, type = filetype, bits = bits))

    ran = vim.current.range
    if filetype.startswith("image"):
        img = image_template % result
        ran.append(img)
    else:
        ran.append(result["url"])
    ran.append('
')

@__exception_check
@__vim_encoding_check
def blog_append_code(code_type = ""):
    if vimpress_view != '
edit':
        raise VimPressException("Command not available at list view.")
    html = \
"""[cc%s]
[ / cc ]"""
    if code_type != "":
        args = '
lang="%s"' % code_type
    else:
        args = '
'

    row, col = vim.current.window.cursor
    code_block = (html % args).split('
\n')
    vim.current.range.append(code_block)
    vim.current.window.cursor = (row + len(code_block), 0)

@__exception_check
@__vim_encoding_check
@__xmlrpc_api_check
def blog_list_cates():
    global vimpress_view
    vimpress_view = '
list'
    l = mw_api.getCategories('
', blog_username, blog_password)
    l.sort(key=operator.itemgetter("categoryName"))
    vim.command('
setl modifiable')
    del vim.current.buffer[:]
    vim.command("set syntax=blogsyntax")
    vim.current.buffer[0] = ""====== List of Category ========="
    tmp_i=1
    tmp_catnames=[]
    tmp_str=""
    for i in l:
        if tmp_i%5 == 0:
            tmp_catnames.append(tmp_str)
            tmp_str=""
        else:
            tmp_str=tmp_str+"\t"+i["categoryName"].encode("utf-8").ljust(14)
        tmp_i=tmp_i+1
    tmp_catnames.append(tmp_str)
    for j in tmp_catnames:
        vim.current.buffer.append(j)
    vim.command('
setl nomodified')
    vim.command('
setl nomodifiable')


@__exception_check
@__vim_encoding_check
def blog_preview(pub = "local"):
    """
    Opens a browser window displaying the content.
    @params pub - If "local", the content is shown in a browser locally.
                  If "draft", the content is saved as a draft and previewed remotely.
                  If "publish", the content is published and displayed remotely.
    """
    if vimpress_view != '
edit':
        raise VimPressException("Command not available at list view.")
    meta = blog_meta_parse()
    rawtext = '
\n'.join(vim.current.buffer[meta["post_begin"]:])

    if pub == "local":
        if meta["editformat"].strip().lower() == "markdown":
            html = markdown.markdown(rawtext.decode('
utf-8')).encode('utf-8')
            html_preview(html, meta)
        else:
            html_preview(rawtext, meta)
    elif pub == "publish" or pub == "draft":
        meta = blog_save(pub)
        if meta["edittype"] == "page":
            prev_url = "%s?pageid=%s&#038;preview=true" % (blog_url, meta["strid"])
        else:
            prev_url = "%s?p=%s&#038;preview=true" % (blog_url, meta["strid"])
        webbrowser.open(prev_url)
        if pub == "draft":
            sys.stdout.write("\nYou have to login in the browser to preview the post when save as draft.")
    else:
        raise VimPressException("Invalid option: %s " % pub)


@__exception_check
def blog_guess_open(what):
    """
    Tries several methods to get the post id from different user inputs, such as args, url, postid etc.
    """
    post_id = '
'
    blog_index = -1
    if type(what) is str:

        for i, p in enumerate(vim.eval("VIMPRESS")):
            if what.startswith(p["blog_url"]):
                blog_index = i

        # User input a url contained in the profiles
        if blog_index != -1:
            guess_id = re.search(r"\S+?p=(\d+)$", what)

            # permantlinks
            if guess_id is None:

                # try again for /archives/%post_id%
                guess_id = re.search(r"\S+/archives/(\d+)", what)

                # fail,  try get full link from headers
                if guess_id is None:
                    headers = urllib.urlopen(what).headers.headers
                    for link in headers:
                        if link.startswith("Link:"):
                            post_id = re.search(r"< \S+?p=(\d+)>", link).group(1)

                    # fail, just give up
                    if post_id == '
':
                        raise VimPressException("Failed to get post/page id from '
%s'." % what)
                else:
                    post_id = guess_id.group(1)

            # full link with ID (http://blog.url/?p=ID)
            else:
                post_id = guess_id.group(1)

        # Uesr input something not a usabe url, try numberic
        else:
            try:
                post_id = str(int(what))
            except ValueError:
                pass

    # detected something
    if post_id != '
':
        if blog_index != -1 and blog_index != blog_conf_index:
            blog_config_switch(blog_index)
        blog_edit("post", post_id)
    else:
        raise VimPressException("Failed to get post/page id from '
%s'." % what)


@__exception_check
def blog_update_config():
    """
    Updates the script'
s configuration variables.
    """
    global blog_username, blog_password, blog_url, mw_api, wp_api
    try:
        config = vim.eval("VIMPRESS")[blog_conf_index]
        blog_username = config['username']
        blog_url = config['blog_url']
        sys.stdout.write("Vimpress is connecting to %s ......\n" % blog_url)
        blog_password = config.get('password', '')
        if blog_password == '':
           blog_password = vim_input("Enter password for %s" % blog_url, True)
        mw_api = xmlrpclib.ServerProxy("%s/xmlrpc.php" % blog_url).metaWeblog
        wp_api = xmlrpclib.ServerProxy("%s/xmlrpc.php" % blog_url).wp
                #sys.stdout.write("Connected to %s \n" % blog_url)
        # Setting tags and categories for completefunc
        terms = []
        terms.extend([i["description"].encode("utf-8")
            for i in mw_api.getCategories('', blog_username, blog_password)])
        # adding tags may make the menu too much items to choose.
        #terms.extend([i["name"].encode("utf-8") for i in wp_api.getTags('', blog_username, blog_password)])
        vim.command('let s:completable = "%s"' % '|'.join(terms))

    except vim.error:
        raise VimPressException("Could not find vimpress configuration. Please read ':help vimpress' for more information.")
    except KeyError, e:
        raise VimPressException("Configuration error: %s" % e)

@__vim_encoding_check
def vim_input(message = 'input', secret = False):
    vim.command('call inputsave()')
    vim.command("let user_input = %s('%s :')" % (("inputsecret" if secret else "input"), message))
    vim.command('call inputrestore()')
    return vim.eval('user_input')

@__exception_check
@__vim_encoding_check
def blog_config_switch(conf_index = -1):
    """

    Switches the blog to the next index of the configuration array.
    """
    global blog_conf_index
    try:
        conf_index = int(conf_index)
    except ValueError:
        raise VimPressException("Invalid Index: %s" % conf_index)

    conf = vim.eval("VIMPRESS")
    if conf_index == -1:
        blog_conf_index += 1
        if blog_conf_index >= len(conf):
            blog_conf_index = 0
    else:
        if conf_index >= len(conf):
            raise VimPressException("Invalid Index: %d" % conf_index)
        blog_conf_index = conf_index

    blog_update_config()
    if vimpress_view.startswith('list'):
        blog_list()
    sys.stdout.write("Vimpress switched to %s" % blog_url)

def html_preview(text_html, meta):
    """

    Opens a browser with a local preview of the content.
    @params text_html - the html content
            meta      - a dictionary of the meta data
    """
    global vimpress_temp_dir
    if vimpress_temp_dir == '':
        vimpress_temp_dir = tempfile.mkdtemp(suffix="vimpress")
   
    html = \
"""
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style type="text/css"> ul, li { margin: 1em; } :link,:visited { text-decoration:none } h1,h2,h3,h4,h5,h6,pre,code { font-size:1em; } a img,:link img,:visited img { border:none } body { margin:0 auto; width:770px; font-family: Helvetica, Arial, Sans-serif; font-size:12px; color:#444; }
</style>
</meta>
</head>
<body>
%(content)s
</body>
</html>
""" % dict(content = text_html, title = meta["title"])
    with open(os.path.join(vimpress_temp_dir, "vimpress_temp.html"), 'w') as f:
        f.write(html)
    webbrowser.open("file://%s" % f.name)

def blog_wise_open_view():
    """

    Wisely decides whether to wipe out the content of current buffer or open a new splited window.
    """
    if vim.current.buffer.name is None and \
            (vim.eval('&#038;modified') == '0' or \
                len(vim.current.buffer) == 1):
        vim.command('setl modifiable')
        del vim.current.buffer[:]
        vim.command('setl nomodified')
    else:
        vim.command(":new")
    vim.command('setl syntax=blogsyntax')
    vim.command('setl completefunc=Completable')

...

更多
2 Responses Post a comment
  1. 荒野无灯

    我一直在用wp的HTML编辑器,因此用VIM可能会更习惯 :cool:

Leave a Reply

Note: You may use basic HTML in your comments. Your email address will not be published.

Subscribe to this comment feed via RSS