有没有办法编辑 Xcode 的内置代码片段?有一个编辑按钮,但按下它似乎不允许更改代码片段的文本。
任何见解都值得赞赏。
最佳答案
您仍然无法编辑内置系统片段。但是,您可以编辑“用户”片段。
我认为最简单的解决方案是创建所有默认代码片段的副本,但修改它们,使它们成为“用户”代码片段并覆盖默认版本。我编写了一个 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.")
您会注意到它实际上并没有更改 Xcode 的任何内部文件。它只是添加文件,并且 Xcode 足够智能,可以使用添加的文件而不是原始片段。您可以随时回滚到原始版本,只需删除片段的用户版本即可。您还可以根据需要多次运行脚本,而不必担心覆盖以前运行脚本生成的任何用户代码片段。
关于Xcode 内置代码片段编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4963034/