是否有办法编辑Xcode内置的代码片段?虽然有一个编辑按钮,但按下它似乎不能更改片段的文本。
非常感谢任何帮助和建议。
是否有办法编辑Xcode内置的代码片段?虽然有一个编辑按钮,但按下它似乎不能更改片段的文本。
非常感谢任何帮助和建议。
您仍然无法编辑内置的系统代码片段。但是,您可以编辑“用户”片段。
我的最简单的解决方案是创建所有默认片段的副本,但修改它们以使它们成为“用户”片段并覆盖默认版本。我编写了一个小的Python脚本来完成这项工作。它非常简单,在运行后,所有Xcode的片段都可以通过Xcode GUI神奇地进行编辑。无需手动在属性列表中进行操作:
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.")
你会发现它实际上并没有改变Xcode的任何内部文件,它只是添加了文件,而Xcode足够聪明来使用添加的文件而不是原始片段。你可以随时通过简单地删除用户版本的片段来回滚到原始版本。你也可以运行脚本多次,而不必担心覆盖之前运行脚本生成的任何用户片段。
plistlib.writePlist(entry, snippet_path)
之前创建和打开可写的plist了。顺便说一句,感谢你的代码。 - anonimos.makedirs(user_snippet_path)
将引发异常,因为该目录已经存在。 - memmons有一个很棒的小工具叫做“Snippet Edit”。我刚试用了一下,强烈推荐。显然它曾经是一款收费应用程序,但作者现在正在免费提供。
您可以手动编辑系统代码片段:
.codesnippets 文件是一个 .plist 文件,但有些字符串使用 CR/LF 输入,无法通过标准的 plist 编辑器进行编辑。
$ ls -l /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/SystemCodeSnippets.codesnippets
-rw-r--r-- 1 root wheel 190 May 16 18:23 /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/SystemCodeSnippets.codesnippets
plist字典键相当自说明,对于IDECodeSnippetIdentifier
键,您可以使用例如以下命令自行生成UUID:
$ uuidgen
42F6B133-5DA3-41DB-8874-4E10E447F723
如果您使用sudo
和您选择的编辑器编辑了文件,则必须重新启动Xcode以应用更改。
祝您编程愉快!
这可能是一个bug,也可能是一个特性。我认为这是后者。你可以添加自己的片段,但不能编辑内置的片段。我建议创建一个新片段并根据你的需求进行自定义。