Xcode内置片段编辑

Mar*_*ote 22 xcode code-snippets

有没有办法编辑Xcode的内置代码片段?有一个编辑按钮,但按下它似乎不允许更改片段的文本.

任何见解都表示赞赏.

Mat*_*ing 18

您仍然无法编辑内置系统片段.但是,您可以编辑"用户"代码段.

我认为最简单的解决方案是创建所有默认代码段的副本,但修改它们以便它们是"用户"代码段并覆盖默认版本.我写了一个Python脚本来完成这项工作.它非常简单,在运行之后,所有Xcode的片段都可以通过Xcode GUI进行神奇的编辑.不需要手动在plist周围乱窜:

import plistlib
import os.path

# Create user snippet directory if needed.
user_snippet_path = os.path.expanduser("~/Library/Developer/Xcode/UserData/CodeSnippets")
try: 
    os.makedirs(user_snippet_path)
except OSError, err:
    if err.errno != errno.EEXIST or not os.path.isdir(user_snippet_path): 
        raise

# Important, you'll need to quit and restart Xcode to notice the effects.
# Important, change this if you're on a Developer Preview of Xcode.
system_snippet_path = "/Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets"

print("Reading snippets from " + system_snippet_path)
plist = plistlib.readPlist(system_snippet_path)
for entry in plist:

    # Create a new user snippet file with modified
    # contents of the original snippet. Ignore paths that
    # already contain a user snippet to prevent overwriting
    # previously generated snippets.
    snippet_id = entry["IDECodeSnippetIdentifier"]
    snippet_path = user_snippet_path + "/" + snippet_id + ".codesnippet"
    if os.path.exists(snippet_path):
        print(snippet_path + " already exitsts: Skipping.")
        continue

    print("Writing " + snippet_path)

    # Marks the snippet as a user snippet. Xcode will
    # crash if a user snippet and a system snippet share
    # the same identifier.
    entry["IDECodeSnippetUserSnippet"] = True

    # Given two snippets with the same identifier,
    # Xcode will only show the snippet with the higher
    # "version number". This effectively hides the
    # default version of the snippet.
    entry["IDECodeSnippetVersion"] += 1

    plistlib.writePlist(entry, snippet_path)

print("Done writing snippets.")
Run Code Online (Sandbox Code Playgroud)

您会注意到它实际上并没有改变任何Xcode的内部文件.它只是添加文件,而Xcode足够智能,可以使用添加的文件而不是原始代码段.只需删除代码段的用户版本,即可随时回滚到原始文件.您也可以根据需要多次运行脚本,而不必担心覆盖以前运行的脚本生成的任何用户片段.

  • @ anonim.developer,谢谢你的提示.我在干净的机器上试过它,确实存在问题.如果用户的代码段目录尚不存在,实际上会发生这种情况.如果需要,plist lib将自动创建文件,但不会自动创建中间目录.我已经更新了脚本. (2认同)

sof*_*ved 12

有一个很棒的小工具叫做"Snippet Edit".我刚尝试过,强烈推荐它.显然它曾经是一个付费应用程序,但作者现在免费赠送它.

http://cocoaholic.com/snippet_edit/


小智 6

您可以手动编辑系统代码段:

  1. 转到此目录:"/ Developer/Library/Xcode/PrivatePlugIns".
  2. 显示"IDECodeSnippetLibrary.ideplugin"的包内容
  3. 打开"Contents/Resources/SystemCodeSnippets.codesnippets"作为文本文件
  4. 编辑它

.codesnippets文件是一个.plist,但是一些字符串是用CR/LF输入的,不能由标准的plist编辑器编辑.

  • 在Xcode 4.3.2中,这是在"/Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources"中. (3认同)

sud*_*-rf 2

这要么是一个错误,要么是一个功能。我相信是后者。您可以添加自己的代码片段,但无法编辑内置代码片段。我只是制作一个新的片段并根据您的需要对其进行自定义。