<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by kily zhou on Medium]]></title>
        <description><![CDATA[Stories by kily zhou on Medium]]></description>
        <link>https://medium.com/@keelii?source=rss-2d785b39d56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zoMvWaqbkZfUJnvV.jpg</url>
            <title>Stories by kily zhou on Medium</title>
            <link>https://medium.com/@keelii?source=rss-2d785b39d56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:02:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keelii/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[VIM 代码片段插件 ultisnips 使用教程]]></title>
            <link>https://medium.com/@keelii/vim-%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E6%8F%92%E4%BB%B6-ultisnips-%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B-5c15f8556d65?source=rss-2d785b39d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c15f8556d65</guid>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[kily zhou]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 14:26:15 GMT</pubDate>
            <atom:updated>2018-09-29T14:26:15.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>安装</h4><p><a href="https://github.com/SirVer/ultisnips">Ultisnips</a> 插件安装分两部分，一个是 ultisnips 插件本身，另外一个是代码片段仓库。一般来说把默认的代码片段仓库下载下来按需修改后上传到自己的 github 即可。如果你和我一样也使用 vim-plug 来管理插件的话，添加下面的代码到你的 vimrc 中保存刷新即可</p><pre>Plug &#39;SirVer/ultisnips&#39;<br># 你自己的代码仓库 git 地址<br>Plug &#39;keelii/vim-snippets&#39;</pre><p>上面的示例中所有的代码片段都存放在插件安装目录下面的 vim-snippets/UltiSnips 中，文件命名格式为 ft.snippets, ft 就是 vim 中的 filetype，其中有个 all.snippets 是唯一一个所有文件都适用的代码片段</p><h4>配置</h4><p>快捷键设置，我一般使用 tab 来触发代码片段补全，<strong>且不使用 YCM</strong> （官方文档表示使用YCM的话就不能使用tab补全）</p><pre>let g:UltiSnipsExpandTrigger=&quot;&lt;tab&gt;&quot;<br>&quot; 使用 tab 切换下一个触发点，shit+tab 上一个触发点<br>let g:UltiSnipsJumpForwardTrigger=&quot;&lt;tab&gt;&quot;<br>let g:UltiSnipsJumpBackwardTrigger=&quot;&lt;S-tab&gt;&quot;<br>&quot; 使用 UltiSnipsEdit 命令时垂直分割屏幕<br>let g:UltiSnipsEditSplit=&quot;vertical&quot;</pre><h4>依赖</h4><p>ultisnips 插件需要你的 vim 支持 python，可以在 vim 命令模式下使用下面的检测你的 vim 版本是否支持 python</p><pre># 1 表示支持<br>:echo has(&quot;python&quot;)<br>:echo has(&quot;python3&quot;)</pre><h4>定义一个代码片段</h4><h4>定义格式</h4><pre>snippet 触发字符 [&quot;代码片段说明&quot; [参数]]<br>代码片段内容<br>endsnippet</pre><h4>最小化的一个代码片段</h4><pre>snippet if &quot;if (condition) { ... }&quot;<br>if (${1:true}) {<br>    $0<br>}<br>endsnippet</pre><p>这时当你在 vim 中输入 if 敲 tab 就会展开一条 if 语句，第一个触发点是 if 条件表达式，最后一个是 if 语句体</p><p>${1:true} 表示这是第一个触发点，占位符为 true，如果占位符没有默认值可直接使用 $1, $2, $3...</p><h4>可视选择区的内容为占位符</h4><pre>snippet if &quot;if (...)&quot;<br>if (${1:true}) {<br>    ${VISUAL}<br>}<br>endsnippet</pre><p>${VISUAL} 表示在 vim 中使用可视模式下选择的文本，这个在重构代码的时候<strong>非常有用</strong>（后面会有高级用法），上个图感受一下</p><figure><img alt="if-with-visual-mode" src="https://cdn-images-1.medium.com/max/787/0*r1G_Gos8diKznIYM.gif" /><figcaption>if-with-visual-mode</figcaption></figure><h4>代码片段的参数</h4><ul><li>b 表示触发字符应该在一行的开始</li><li>i 表示触发字符可以在单词内（连续展示会使用这个选项）</li><li>w 表示触发字符的前后必须是一个字母分界点</li><li>r 表示触发字符可以是一个正则表达式</li><li>t 表示展开的代码片段中如果有制表符，原样输出，即使你的 vimrc 里面设置了 expandtab</li><li>m 表示删除代码片段右边的所有空白字符</li><li>e 表示自定义上下文</li><li>A 表示自动触发，不需要按 tab，类似于 VIM 中的 abbr</li></ul><h4>内容解释器</h4><p>Ultisnips 定义的代码片段中支持三种不同的语言注入：shell, vimscript, python，在代码片段中用反引号表示</p><h4>shell 代码</h4><p>就是在你的命令行 shell 能执行的代码片段，比如输出当前时间</p><pre>➜ date<br>2018年 8月27日 星期一 18时19分38秒 CST</pre><p>在代码片段中用反引号「`」引用即可</p><pre>snippet today<br>Today is the `date`.<br>endsnippet</pre><p>输入 today 按 tab 展开后（格式和上面shell中的不一样，估计是因为 vim 语言设置的问题）：</p><pre>Today is the Mon Aug 27 18:24:51 CST 2018.</pre><h4>vimscript 代码</h4><p>使用 indent 来输出当前缩进值，使用前缀 !v 表示是 vimscript</p><pre>snippet indent<br>Indent is: `!v indent(&quot;.&quot;)`.<br>endsnippet</pre><figure><img alt="vimscript-indent-size" src="https://cdn-images-1.medium.com/max/787/0*BxhFgEI9MUtgY7Qb.gif" /><figcaption>vimscript-indent-size</figcaption></figure><h4>python 代码</h4><p>在代码片段中解释执行 python 代码是 ultisnips 最强大的功能，以前缀 !p 开始。系统会向 python 中注入一些变量，可以使用 python 代码直接对其进行操作</p><ul><li>fn - 表示当前文件名</li><li>path - 当前文件名的路径</li><li>t - 占位符的字典，可以使用 t[1], t[2], t.v 来取占位符内容</li><li>snip - <a href="https://github.com/SirVer/ultisnips/blob/6fdc3647f72e0a1f321ea6bd092ecd01f7c187ba/pythonx/UltiSnips/text_objects/_python_code.py#L56">UltiSnips.TextObjects.SnippetUtil</a> 对象的一个实例</li><li>match - 正则代码片段时返回的匹配元素（非常强大）</li></ul><p>其中最常用的 snip 对象提供了下面一些变量：</p><ul><li>snip.rv 表示 return value，python 代码执行后处理过的字符串赋给 rv 即可</li><li>snip.fn 表示当前文件名</li><li>snip.ft 表示当前文件类型</li><li>snip.v 表示 VISUAL 模式变量，其中 snip.v.mode 表示模式类型，snip.v.text 表示 VISUAL 模式中选择的字符</li></ul><figure><img alt="python-snippet-var" src="https://cdn-images-1.medium.com/max/787/0*rxKya_1UsdQelJbW.gif" /><figcaption>python-snippet-var</figcaption></figure><h4>占位符选择</h4><p>UltiSnips 支持使用快捷键切换占位符，我使用 &lt;tab&gt; 和 &lt;shift-tab&gt; 来切换 下一个 和 上一个 占位符，占位符切换的作用域为当前代码片段内部（即使占位符已被修改过），当光标移动出去以后就不起作用了</p><figure><img alt="mul-placeholder-editing" src="https://cdn-images-1.medium.com/max/787/0*UtQja9OVX-CbW6m_.gif" /><figcaption>mul-placeholder-editing</figcaption></figure><h4>自定义上下文</h4><p>自定义上下文可以通过正则匹配来决定代码片断是否可用，比如判断在指定的 if 语句里面才起作用的代码片断，定义格式如下：</p><blockquote>snippet 触发字符 “描述” “表达式” 参数</blockquote><p>比如我们定义一个 <strong>只有</strong> 在上一行以 if (DEVELOPMENT) { 开头才可以展开的代码片段</p><pre>snippet dbg &quot;if (DEVELOPMENT) dbg&quot; &quot;re.match(&#39;^if \(DEVELOPMENT\) \{&#39;, snip.buffer[snip.line-1])&quot; be<br>debugger;<br>endsnippet</pre><h4>常见用法</h4><h4>行内连续展开</h4><p>这个常见于需要连续展开代码片段的情况，比如，有两个片段，一个打印变量，一个处理 JSON 序列化。这时需要使用参数选项 in-word</p><figure><img alt="continue-expand-snippets" src="https://cdn-images-1.medium.com/max/787/0*Xl8W-_UK6eqreR_O.gif" /><figcaption>continue-expand-snippets</figcaption></figure><h4>使用正则代码片段</h4><p>通常写代码的时候需要使用 log, print 等来打印上下文中的变量。使用普通片段按 cl 展示 console.log() 然后把变量字符复制进括号，这样操作会比较复杂。使用正则来动态匹配前面的字符可以很好的解决这个问题</p><pre># 展开 console.log<br>snippet &quot;([^\s]\w+)\.log&quot; &quot;console.log(postfix)&quot; r<br>console.log(`!p snip.rv = match.group(1)`)$0<br>endsnippet<br># 当前行转换成大写<br>snippet &quot;([^\s].*)\.upper&quot; &quot;Uppercase(postfix)&quot; r<br>`!p snip.rv = match.group(1).upper()`$0<br>endsnippet<br># 上一个单词转换成小写<br>snippet &quot;([^\s]\w+)\.lower&quot; &quot;Lowercase(postfix)&quot; r<br>`!p snip.rv = match.group(1).lower()`$0<br>endsnippet</pre><p>动图演示</p><figure><img alt="expand-regexp-snippets" src="https://cdn-images-1.medium.com/max/787/0*h8PSw0BXrMRTNTl0.gif" /><figcaption>expand-regexp-snippets</figcaption></figure><p><strong>注意</strong>：正则代码片段只适用于单行文本处理，如果是多行转换还是得用到下面的 python + VISUAL 代码片段来处理</p><h4>使用 python 解释器 + VISUAL 模式实现代码注释功能</h4><p>通常我们需要使用一大堆插件来实现各种代码的注释功能。不过 Ultisnips 提供了 VISUAL 模式可以提取 vim 可视模式中选择的内容到代码片段里面，于是我们就可以结合起来制作一个<strong>具有注释功能的代码片段</strong></p><p>流程大概是这样的：</p><ol><li>进入 vim 可视模式，选择要注释的内容</li><li>按 tab，清除选择内容</li><li>输入代码片段触发字符，按 tab 完成</li></ol><p>由于实现的 python 代码相对复杂一些，主要分成两个方法。单行注释和多行注释，注意 Ultisnips 中可以直接写 python 但是大段的方法建议放在插件目录下面的 pythonx 目录下面，使用的时候在对应的代码片段中的全局 python 代码 global !p 引入即可</p><p><strong>单行注释</strong>(pythonx/javascript_snippets.py)：</p><pre>def comment(snip, START=&quot;&quot;, END=&quot;&quot;):<br>    lines = snip.v.text.split(&#39;\n&#39;)[:-1]<br>    first_line = lines[0]<br>    spaces = &#39;&#39;<br>    initial_indent = snip._initial_indent<br><br>    # Get the first non-empty line<br>    for idx, l in enumerate(lines):<br>        if l.strip() != &#39;&#39;:<br>            first_line = lines[idx]<br>            sp = re.findall(r&#39;^\s+&#39;, first_line)<br>            if len(sp):<br>                spaces = sp[0]<br>            break            <br><br>    # Uncomment<br>    if first_line.strip().startswith(START):<br>        result = [line.replace(START, &quot;&quot;, 1).replace(END, &quot;&quot;, 1) if line.strip() else line for line in lines]<br>    else:<br>        result = [f&#39;{spaces}{START}{line[len(spaces):]}{END}&#39; if line.strip() else line for line in lines ]<br><br>    # Remove initial indent<br>    if result[0] and initial_indent:<br>        result[0] = result[0].replace(initial_indent, &#39;&#39;, 1)<br><br>    if result:<br>        return &#39;\n&#39;.join(result)<br>    else:<br>        return &#39;&#39;</pre><p><strong>多行注释：</strong></p><pre>def comment_inline(snip, START=&quot;/* &quot;, END=&quot; */&quot;):<br>    text = snip.v.text<br>    lines = text.split(&#39;\n&#39;)[:-1]<br>    first_line = lines[0]<br>    initial_indent = snip._initial_indent<br>    spaces = &#39;&#39;<br><br>    # Get the first non-empty line<br>    for idx, l in enumerate(lines):<br>        if l.strip() != &#39;&#39;:<br>            first_line = lines[idx]<br>            sp = re.findall(r&#39;^\s+&#39;, first_line)<br>            if len(sp):<br>                spaces = sp[0]<br>            break            <br><br>    if text.strip().startswith(START):<br>        result = text.replace(START, &#39;&#39;, 1).replace(END, &#39;&#39;, 1)<br>    else:<br>        result = text.replace(spaces, spaces + START, 1).rstrip(&#39;\n&#39;) + END + &#39;\n&#39;<br><br>    if initial_indent:<br>        result = result.replace(initial_indent, &#39;&#39;, 1)<br><br>    return result</pre><p><strong>代码片段定义：</strong></p><pre>global !p<br>from javascript_snippets import (<br>	comment, comment_inline<br>)<br>endglobal<br><br># ...<br><br>snippet c &quot;Toggle comment every single line&quot;<br>`!p<br>snip.rv = comment(snip, START=&#39;// &#39;, END=&#39;&#39;)<br>`$0<br>endsnippet<br><br>snippet ci &quot;Toggle comment inline.&quot;<br>`!p<br>snip.rv = comment_inline(snip, START=&quot;/* &quot;, END=&quot; */&quot;)<br>`$0<br>endsnippet</pre><p>动图演示</p><figure><img alt="python-snippets-to-comment" src="https://cdn-images-1.medium.com/max/787/0*qLuUUsAAKtIGVLvD.gif" /><figcaption>python-snippets-to-comment</figcaption></figure><p>不同的语言可以在对应的片段文件中定义并传入注释符号参数即可，有了这个功能就可以愉快的删除其它的 vim 注释插件了 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c15f8556d65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>