[Journal - Alias Substitution and Custom Code]

Alias Substitution and Custom Code

Friday, March 18, 2005

WebEdit.NET's token expansion capabilities enable running custom code that generates the text to insert. This is best used with alias expansion, because the text typed is overwritten entirely, and so need not be part of the final text (which means it can be short & catchy).

Suppose you have the following code, which generates members implementing an interface (it is exposed as a macro, so it's handy to call from the console window as well):

// build this way: <build:addin?C#,0>

using System;
using Gregor.Core;
using Gregor.Editing.EditAssistance;

[Module()]
public class M {

[Gregor.Core.Macro(true)]
public static string GetInterfaceImplementation(
                            [DefaultValue("C#")]string sLangName
)
{
    CLanguageInfo lang = App.Context.LanguagePool.GetLanguageByName(sLangName);
    Check.Reference(lang, "Language '" + sLangName + "' not supported.");

    string sType = Gregor.UICore.Dialogs.FInput.ShowInput("Implement Interface",
                                                          "Enter full type name:",
                                                          "System.IDisposable");
    if(Flow.IsString(sType))
    {
        Type tp = Reflect.FindType(sType, true);
        Check.Reference(tp, "Type '" + sType + "' not found.");
        CTypeInfoEx typeInfo = Reflect.GetTypeInfo(tp);

        CCodeAssistantBase assy = (CCodeAssistantBase) lang.CodeAssistant;
        Check.Reference(assy, "No code assistant available for this language.");

        CCodeAssistanceInfo assyInfo = new CCodeAssistanceInfo(typeInfo, "    ");
        Check.Expression(assy.ImplementInterface(assyInfo), "I failed.");

        return assyInfo.Result;
    }

    return string.Empty;
}

} // module M

Next, define an alias in one of the properly configured alias files for the language (for example, CSharpAliases.xml in the Tokens sub dir). Place a call to the custom method in the alias's value:

<aliases>
  <alias key="_ImplementInterface"
         icon="Interface.ico"
         value="$M.GetInterfaceImplementation(&quot;C#&quot;)%" />
</aliases>

Add the alias key "_ImplementInterface" as a token to (one of) the token list(s) you have configured for auto-text (for example, CSharpAutoComplete.txt), and you're all set.

This technique is also another approach of integrating the coding assistance functionality found in Gregor.Editing.EditAssistance.