Resharper 声称要吃自己的狗粮,具体来说,他们声称 Resharper 的许多功能都是在 R# (OpenAPI) 之上编写的。我正在编写一个简单的插件来修复当前所选文档的注释。当这个插件运行时,它会抛出一个异常,如下所示:
文档只能在命令范围内修改
我已经研究了这个错误并且找不到任何帮助解决这个问题,所以我希望你可能已经编写了一个插件来完成这个。如果没有,我希望该片段足以帮助其他人开发自己的插件。
using System;
using System.IO;
using System.Windows.Forms;
using JetBrains.ActionManagement;
using JetBrains.DocumentModel;
using JetBrains.IDE;
using JetBrains.TextControl;
using JetBrains.Util;
namespace TinkerToys.Actions
{
[ActionHandler("TinkerToys.RewriteComment")]
public class RewriteCommentAction : IActionHandler
{
#region Implementation of IActionHandler
/// <summary>
/// Updates action visual presentation. If presentation.Enabled is set to false, Execute
/// will not be called.
/// </summary>
/// <param name="context">DataContext</param>
/// <param name="presentation">presentation to update</param>
/// <param name="nextUpdate">delegate to call</param>
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
ITextControl textControl = context.GetData(DataConstants.TEXT_CONTROL);
return textControl != null;
}
/// <summary>
/// Executes action. Called after Update, that set ActionPresentation.Enabled to true.
/// </summary>
/// <param name="context">DataContext</param>
/// <param name="nextExecute">delegate to call</param>
public void Execute(IDataContext context, DelegateExecute nextExecute)
{
ITextControl textControl = context.GetData(DataConstants.TEXT_CONTROL);
if (textControl != null) {
TextRange textSelectRange;
ISelectionModel textSelectionModel = textControl.SelectionModel;
if ((textSelectionModel != null) && textSelectionModel.HasSelection()) {
textSelectRange = textSelectionModel.Range;
} else {
textSelectRange = new TextRange(0, textControl.Document.GetTextLength());
}
IDocument textDocument = textControl.Document;
String textSelection = textDocument.GetText(textSelectRange);
if (textSelection != null) {
StringReader sReader = new StringReader(textSelection);
StringWriter sWriter = new StringWriter();
Converter.Convert(sReader, sWriter);
textSelection = sWriter.ToString();
textDocument.ReplaceText(textSelectRange, textSelection);
}
}
}
#endregion
}
}
那么它非常想要的这个命令范围是什么?在发布之前我有一些额外的日志记录,所以我绝对确定范围和文本都是有效的。此外,该错误似乎表明我缺少一些我一直无法找到的范围。
是的,我想我可以使用宏来完成相同的任务。回想起来,我写了一个简单的 vs 插件来做同样的事情。我正在/正在查看 R# 的原因是因为它具有语言特定的元素解析,除了原始文本之外它还可以提供。但是对于这个问题,我认为宏或标准加载项也可以正常工作。