[vim]Python编写插件学习笔记3 - 命令行参数

0 环境

  1. Windows 11 22H2
  2. gVim82 (D:/ProgramFiles/Vim)
  3. Python311 (D:/ProgramFiles/Python311)
  4. Vundle v0.10.2

阅读本文前,需要先了解前文:

1 前提说明

由于本人并未仔细学习 vimscript 相关内容,只是凭自己的理解尝试写 vim 插件,只是本着 “够用就就行” 的基本原则实现自己想要的功能。

所以,多少会有不足的内容,甚至更好的方案,本文则不详述。

命令行参数,只是想实现像平时使用 vim 命令一样,正常使用自己的插件。

举例说明:vim 的 make 命令

:make
:make clean

这样使用确实很方便。

2 Python 实现

# -*- coding: utf-8 -*-
### test.py

def TestVim(type):
    print("TestVim: " + type)

3 vimscript 实现

" test.vim

let s:script_dir = fnamemodify(resolve(expand('<sfile>', ':p')), ':h')

function! TestVim(type)					# 定义参数

python3 << EOF
# python part start

import sys
import vim

script_dir = vim.eval('s:script_dir')
sys.path.insert(0, script_dir)

from test import TestVim				# 引用

TestVim(vim.eval('a:type'))				# 传入参数

# python part end
EOF

endfunction
  • 加载
:so %
  • 测试
:call TestVim("init")
TestVim: init
:call TestVim("build")
TestVim: build

注意:这样实现,参数只能是字符串,注意添加双引号。

4 配置

以上可以通过 call 命令来调用插件内的函数。但不能直接通过命令方式调用。

需要添加配置:

" test.vim
" 脚本末尾
" 接收 0 个或 1 个参数
command! -nargs=? TestVim call TestVim(<q-args>)
  • 加载
:so %
  • 测试
:TestVim
TestVim: 
:TestVim init
TestVim: init
:TestVim build
TestVim: build

:TestVim init build
TestVim: init build		# "init build" 被作为一个字符串

5 命令行参数说明

5.1 -nargs

  • -nargs=0 - 无参数(默认)
  • -nargs=1 - 仅 1 个参数
  • -nargs=* - 任意多个参数(0,1, 或多个),使用空白符分隔
  • -nargs=? - 0 或1 个参数
  • -nargs=+ - 任意多个参数(1 或多个),但必须提供参数

5.2 <q-args> - “quoted args”

将命令行接收的参数使用双引号括起来,视作一个单一字符串。之后,再当其作一个合法值传给表达式使用。

如果没有传入参数, 表示为一个空字符串。

5.3 <f-args> - “function args”

表示命令行传递参数给用户定义的函数。

传入的命令行参数,会以空格和 Tab 进行分割,再将各个参数使用引号括起来,均视作字符串。

之后,以引号括起来的,被逗号分割的参数列表会替换 参数,传入用户定义的函数。

如果命令行未传入参数, 则被移除。

如果命令行需要输入空格符,必须使用反斜杠符号 (\) 进行转义。

示例:

command		   <f-args> ~
XX ab		   'ab'
XX a\b		   'a\b'
XX a\ b		   'a b'
XX a\  b	   'a ', 'b'
XX a\\b		   'a\b'
XX a\\ b	   'a\', 'b'
XX a\\\b	   'a\\b'
XX a\\\ b	   'a\ b'
XX a\\\\b	   'a\\b'
XX a\\\\ b	   'a\\', 'b'

6 参考

  1. Writing Vim plugin in Python (candidtim.github.io)
  2. How to Write Vim Plugins with Python - DZone
  3. Learn Vimscript the Hard Way (stevelosh.com)
  4. Vim script for Python Developers · GitHub
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值