Xtext-based editors automatically support code templates. That means that you get the corresponding preference page where users can add and change template proposals. If you want to ship a couple of default templates, you have to put a file named templates.xml inside the templates directory of the generated UI-plug-in. This file contains templates in a format as described in the Eclipse online help .
By default Xtext registers context types that follow certain patterns. A context type will be created
In addition to the standard template proposal extension mechanism, Xtext ships with a predefined set of TemplateVariableResolvers to resolve special variable types in templates. Besides the standard template variables available in GlobalTemplateVariables like ${user}, ${date}, ${time}, ${cursor}, etc., these TemplateVariableResolvers support the automatic resolving of cross references enumeration values. Both resolvers are explained in the following sections.
It is best practice to edit the templates in the preferences page, export them into the templates.xml-file and put this one into the templates folder of your UI-plug-in. However, these templates will not be visible by default. To fix it, you have to manually edit the xml-file and insert an id attribute for each template element. Note that the attribute name is case sensitive.
Xtext comes with a specific template variable resolver called CrossReferenceTemplateVariableResolver (src), which can be used to pre-populate placeholders for cross-references within a template. The respective template variable is called CrossReference and its syntax is as follows:
${<displayText>:CrossReference([<MyPackageName>.]<MyType>.<myRef>)}
This small example yields the text event => state and allows selecting any events and states using a drop down:
<template
name="transition"
description="event transition"
id="transition"
context="org.xtext.example.SecretCompartments.Transition"
enabled="true">
${event:CrossReference('Transition.event')} =>
${state:CrossReference('Transition.state')
</template>
The EnumTemplateVariableResolver (src) resolves a template variable to EEnumLiterals which are assignment-compatible to the enumeration type declared as the first parameter of the the Enum template variable.
The syntax is as follows:
${<displayText>:Enum([<MyPackage>.]<EnumType>)
For example the following template (taken from another example):
<template
name="Entity"
description="template for an Entity"
id="entity"
context="org.eclipse.xtext.example.Domainmodel.Entity"
enabled="true">
${public:Enum('Visibility')} entity ${Name} {
${cursor}
}
</template>
yields the text public entity Name {} where the text public is the default value of the Visibility. The editor provides a drop down that is populated with the other literal values as defined in the EEnum.