1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-23 14:42:11 +02:00

2004-12-10 Alain Magloire

Fix for 77874.
	In order to fix this we removed all of the Eclipse-1.0 classes
	that we copied in the CDT.
	The good news is that it is now part of Eclipse-3.x platform and we no
	need to carry the duplicate.
	The templates support was rewritten to use the JFace templates support
	classes.

	* src/org/eclipse/cdt/internal/corext/template/*: remove to use
	JFace Templates support.
	* src/org/eclipse/cdt/internal/corext/template/c/*: rewritten to use
	JFace Templates classes.
	* src/org/eclipse/cdt/intenal/corext/texmanipulation/*: remove to use
	JFace TextEdit support
	* src/org/eclipse/cdt/internal/ui/preferences/CTemplatePreferencePage.java:
	Rewritten to take advantage of JFace support for Templates.
	* src/org/eclipse/cdt/internal/ui/text/link/*: Remove use JFace
	* src/org/eclipse/cdt/internal/ui/text/template/*: Remove use JFace templates
	* plugin.xml
	* plugin.properties
	* template/default-templates.xml
This commit is contained in:
Alain Magloire 2004-12-10 17:22:41 +00:00
parent 3b8838d4bc
commit 3c9660722e
65 changed files with 890 additions and 6857 deletions

View file

@ -1,3 +1,26 @@
2004-12-10 Alain Magloire
Fix for 77874.
In order to fix this we removed all of the Eclipse-1.0 classes
that we copied in the CDT.
The good news is that it is now part of Eclipse-3.x platform and we no
need to carry the duplicate.
The templates support was rewritten to use the JFace templates support
classes.
* src/org/eclipse/cdt/internal/corext/template/*: remove to use
JFace Templates support.
* src/org/eclipse/cdt/internal/corext/template/c/*: rewritten to use
JFace Templates classes.
* src/org/eclipse/cdt/intenal/corext/texmanipulation/*: remove to use
JFace TextEdit support
* src/org/eclipse/cdt/internal/ui/preferences/CTemplatePreferencePage.java:
Rewritten to take advantage of JFace support for Templates.
* src/org/eclipse/cdt/internal/ui/text/link/*: Remove use JFace
* src/org/eclipse/cdt/internal/ui/text/template/*: Remove use JFace templates
* plugin.xml
* plugin.properties
* template/default-templates.xml
2004-12-08 Bogdan Gheorghe 2004-12-08 Bogdan Gheorghe
Fix for 76123 Fix for 76123
* src/org/eclipse/cdt/internal/ui/search/CSearchResultPage.java * src/org/eclipse/cdt/internal/ui/search/CSearchResultPage.java

View file

@ -13,6 +13,7 @@ bin.includes = about.html,\
about.html,\ about.html,\
icons/,\ icons/,\
plugin.properties,\ plugin.properties,\
templates/, \
cdtui.jar cdtui.jar
source.cdtui.jar = src/,\ source.cdtui.jar = src/,\
utils.ui/,\ utils.ui/,\

View file

@ -284,3 +284,6 @@ cCompareFontDefiniton.description= The C/C++ compare text font is used by C/C++
# External Search Editor # External Search Editor
ExternalSearchEditor.name=External Search Editor ExternalSearchEditor.name=External Search Editor
#--- templates
c.contextType.name = C

View file

@ -555,8 +555,8 @@
</page> </page>
<page <page
name="%CPluginTemplatePreferencePage.name" name="%CPluginTemplatePreferencePage.name"
category="org.eclipse.cdt.ui.preferences.CPluginPreferencePage" category="org.eclipse.cdt.ui.preferences.CEditorPreferencePage"
class="org.eclipse.cdt.internal.ui.preferences.TemplatePreferencePage" class="org.eclipse.cdt.internal.ui.preferences.CTemplatePreferencePage"
id="org.eclipse.cdt.ui.preferences.TemplatePreferencePage"> id="org.eclipse.cdt.ui.preferences.TemplatePreferencePage">
</page> </page>
<page <page
@ -1194,4 +1194,17 @@
</provider> </provider>
</extension> </extension>
<!--- Template extension for the editor -->
<extension
point="org.eclipse.ui.editors.templates">
<contextType
name="%c.contextType.name"
class="org.eclipse.cdt.internal.corext.template.c.CContextType"
id="org.eclipse.cdt.ui.text.templates.c">
</contextType>
<include
file="templates/default-templates.xml">
</include>
</extension>
</plugin> </plugin>

View file

@ -1,167 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.textmanipulation.MultiTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.NopTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.cdt.internal.corext.textmanipulation.TextBufferEditor;
import org.eclipse.cdt.internal.corext.textmanipulation.TextEdit;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
/**
* A context type is a context factory.
*/
public abstract class ContextType implements ITemplateEditor {
/** name of the context type */
private final String fName;
/** variables used by this content type */
private final Map fVariables= new HashMap();
/**
* Creates a context type with a name.
*
* @param name the name of the context. It has to be unique wrt to other context names.
*/
public ContextType(String name) {
fName= name;
}
/**
* Returns the name of the context type.
*/
public String getName() {
return fName;
}
/**
* Adds a template variable to the context type.
*/
public void addVariable(TemplateVariable variable) {
fVariables.put(variable.getName(), variable);
}
/**
* Removes a template variable from the context type.
*/
public void removeVariable(TemplateVariable variable) {
fVariables.remove(variable.getName());
}
/**
* Removes all template variables from the context type.
*/
public void removeAllVariables() {
fVariables.clear();
}
/**
* Returns an iterator for the variables known to the context type.
*/
public Iterator variableIterator() {
return fVariables.values().iterator();
}
/**
* Creates a template context.
*/
public abstract TemplateContext createContext();
/*
* @see ITemplateEditor#edit(TemplateBuffer)
*/
public void edit(TemplateBuffer templateBuffer, TemplateContext context) throws CoreException {
TextBuffer textBuffer= TextBuffer.create(templateBuffer.getString());
TemplatePosition[] variables= templateBuffer.getVariables();
MultiTextEdit positions= variablesToPositions(variables);
MultiTextEdit multiEdit= new MultiTextEdit();
// iterate over all variables and try to resolve them
for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i];
if (variable.isResolved())
continue;
String name= variable.getName();
int[] offsets= variable.getOffsets();
int length= variable.getLength();
TemplateVariable evaluator= (TemplateVariable) fVariables.get(name);
String value= (evaluator == null)
? null
: evaluator.evaluate(context);
if (value == null)
continue;
variable.setLength(value.length());
variable.setResolved(evaluator.isResolved(context));
for (int k= 0; k != offsets.length; k++)
multiEdit.add(SimpleTextEdit.createReplace(offsets[k], length, value));
}
TextBufferEditor editor= new TextBufferEditor(textBuffer);
editor.add(positions);
editor.add(multiEdit);
editor.performEdits(null);
positionsToVariables(positions, variables);
templateBuffer.setContent(textBuffer.getContent(), variables);
}
private static MultiTextEdit variablesToPositions(TemplatePosition[] variables) {
MultiTextEdit positions= new MultiTextEdit();
for (int i= 0; i != variables.length; i++) {
int[] offsets= variables[i].getOffsets();
for (int j= 0; j != offsets.length; j++)
positions.add(new NopTextEdit(offsets[j], 0));
}
return positions;
}
private static void positionsToVariables(MultiTextEdit positions, TemplatePosition[] variables) {
Iterator iterator= positions.iterator();
for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i];
int[] offsets= new int[variable.getOffsets().length];
for (int j= 0; j != offsets.length; j++)
offsets[j]= ((TextEdit) iterator.next()).getTextRange().getOffset();
variable.setOffsets(offsets);
}
}
/**
* Returns the templates associated with this context type.
*/
public Template[] getTemplates() {
Template[] templates= Templates.getInstance().getTemplates();
Vector vector= new Vector();
for (int i= 0; i != templates.length; i++)
if (templates[i].getContextTypeName().equals(fName))
vector.add(templates[i]);
return (Template[]) vector.toArray(new Template[vector.size()]);
}
}

View file

@ -1,79 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.cdt.internal.corext.template.c.CFunctionContextType;
import org.eclipse.cdt.internal.corext.template.c.CGlobalContextType;
import org.eclipse.cdt.internal.corext.template.c.CStructureContextType;
import org.eclipse.cdt.internal.corext.template.c.CppFunctionContextType;
import org.eclipse.cdt.internal.corext.template.c.CppGlobalContextType;
import org.eclipse.cdt.internal.corext.template.c.CppStructureContextType;
/**
* A singleton to keep track of all known context types.
*/
public class ContextTypeRegistry {
/** the singleton */
private static ContextTypeRegistry fInstance;
/** all known context types */
private final Map fContextTypes= new HashMap();
/**
* Returns the single instance of this class.
*/
public static ContextTypeRegistry getInstance() {
if (fInstance == null)
fInstance= new ContextTypeRegistry();
return fInstance;
}
/**
* Adds a context type to the registry.
*/
public void add(ContextType contextType) {
fContextTypes.put(contextType.getName(), contextType);
}
/**
* Removes a context type from the registry.
*/
public void remove(ContextType contextType) {
fContextTypes.remove(contextType.getName());
}
/**
* Returns the context type if the name is valid, <code>null</code> otherwise.
*/
public ContextType getContextType(String name) {
return (ContextType) fContextTypes.get(name);
}
/**
* Returns an iterator over the registered context type names.
*/
public Iterator iterator() {
return fContextTypes.keySet().iterator();
}
// XXX bootstrap with C and C++ types
private ContextTypeRegistry() {
add(new CGlobalContextType());
add(new CStructureContextType());
add(new CFunctionContextType());
add(new CppGlobalContextType());
add(new CppStructureContextType());
add(new CppFunctionContextType());
}
}

View file

@ -1,70 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.util.Assert;
/**
* A typical text based document template context.
*/
public abstract class DocumentTemplateContext extends TemplateContext {
/** The text of the document. */
private final String fString;
/** The completion position. */
private final int fCompletionPosition;
/**
* Creates a document template context.
*/
protected DocumentTemplateContext(ContextType type, String string, int completionPosition) {
super(type);
Assert.isNotNull(string);
Assert.isTrue(completionPosition >= 0 && completionPosition <= string.length());
fString= string;
fCompletionPosition= completionPosition;
}
/**
* Returns the string of the context.
*/
public String getString() {
return fString;
}
/**
* Returns the completion position within the string of the context.
*/
public int getCompletionPosition() {
return fCompletionPosition;
}
/**
* Returns the keyword which triggered template insertion.
*/
public String getKey() {
return fString.substring(getStart(), getEnd());
}
/**
* Returns the beginning offset of the keyword.
*/
public int getStart() {
return fCompletionPosition;
}
/**
* Returns the end offset of the keyword.
*/
public int getEnd() {
return fCompletionPosition;
}
}

View file

@ -1,34 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
/**
* A template editor implements an action to edit a template buffer in its context.
*/
public interface ITemplateEditor {
/**
* Modifies a template buffer.
*
* @param buffer the template buffer
* @param context the template context
* @throws CoreException if the buffer cannot be successfully modified
*/
void edit(TemplateBuffer buffer, TemplateContext context) throws CoreException;
public class TemplateContextKind {
public static final String C_GLOBAL_CONTEXT_TYPE = "C Global"; //$NON-NLS-1$
public static final String C_FUNCTION_CONTEXT_TYPE = "C Function"; //$NON-NLS-1$
public static final String C_STRUCTURE_CONTEXT_TYPE = "C Structure"; //$NON-NLS-1$
public static final String CPP_GLOBAL_CONTEXT_TYPE = "C++ Global"; //$NON-NLS-1$
public static final String CPP_FUNCTION_CONTEXT_TYPE = "C++ Function"; //$NON-NLS-1$
public static final String CPP_STRUCTURE_CONTEXT_TYPE = "C++ Structure"; //$NON-NLS-1$
}
}

View file

@ -1,55 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
* A simple template variable, which always evaluates to a defined string.
*/
public class SimpleTemplateVariable extends TemplateVariable {
/** The string to which this variable evaluates. */
private String fEvaluationString;
/** A flag indicating if this variable can be resolved. */
private boolean fResolved;
/*
* @see TemplateVariable#TemplateVariable(String, String)
*/
protected SimpleTemplateVariable(String name, String description) {
super(name, description);
}
/**
* Sets the string to which this variable evaluates.
*
* @param evaluationString the evaluation string, may be <code>null</code>.
*/
public final void setEvaluationString(String evaluationString) {
fEvaluationString= evaluationString;
}
/*
* @see TemplateVariable#evaluate(TemplateContext)
*/
public String evaluate(TemplateContext context) {
return fEvaluationString;
}
/**
* Sets the resolved flag.
*/
public final void setResolved(boolean resolved) {
fResolved= resolved;
}
/*
* @see TemplateVariable#isResolved(TemplateContext)
*/
public boolean isResolved(TemplateContext context) {
return fResolved;
}
}

View file

@ -1,160 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
* A template consiting of a name and a pattern.
*/
public class Template {
/** The name of this template */
private String fName;
/** A description of this template */
private String fDescription;
/** The name of the context type of this template */
private String fContextTypeName;
/** The template pattern. */
private String fPattern;
/** A flag indicating if the template is active or not. */
private boolean fEnabled= true;
/**
* Creates an empty template.
*/
public Template() {
this("", "", "", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
/**
* Creates a copy of a template.
*/
public Template(Template template) {
this(template.getName(), template.getDescription(), template.getContextTypeName(), template.getPattern());
}
/**
* Creates a template.
*
* @param name the name of the template.
* @param description the description of the template.
* @param contextTypeName the name of the context type in which the template can be applied.
* @param pattern the template pattern.
*/
public Template(String name, String description, String contextTypeName, String pattern) {
fName= name;
fDescription= description;
fContextTypeName= contextTypeName;
fPattern= pattern;
}
/*
* @see Object#equals(Object)
*/
public boolean equals(Object object) {
if (!(object instanceof Template))
return false;
Template template= (Template) object;
if (template == this)
return true;
return
template.fName.equals(fName) &&
template.fPattern.equals(fPattern) &&
template.fContextTypeName.equals(fContextTypeName);
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fName.hashCode() ^ fPattern.hashCode() ^ fContextTypeName.hashCode();
}
/**
* Sets the description of the template.
*/
public void setDescription(String description) {
fDescription= description;
}
/**
* Returns the description of the template.
*/
public String getDescription() {
return fDescription;
}
/**
* Sets the name of the context type in which the template can be applied.
*/
public void setContext(String contextTypeName) {
fContextTypeName= contextTypeName;
}
/**
* Returns the name of the context type in which the template can be applied.
*/
public String getContextTypeName() {
return fContextTypeName;
}
/**
* Sets the name of the template.
*/
public void setName(String name) {
fName= name;
}
/**
* Returns the name of the template.
*/
public String getName() {
return fName;
}
/**
* Sets the pattern of the template.
*/
public void setPattern(String pattern) {
fPattern= pattern;
}
/**
* Returns the template pattern.
*/
public String getPattern() {
return fPattern;
}
/**
* Sets the enable state of the template.
*/
public void setEnabled(boolean enable) {
fEnabled= enable;
}
/**
* Returns <code>true</code> if template is enabled, <code>false</code> otherwise.
*/
public boolean isEnabled() {
return fEnabled;
}
/**
* Returns <code>true</code> if template matches the prefix and context,
* <code>false</code> otherwise.
*/
public boolean matches(String prefix, String contextTypeName) {
return
fEnabled &&
fContextTypeName.equals(contextTypeName) &&
(prefix.length() != 0) &&
fName.toLowerCase().startsWith(prefix.toLowerCase());
}
}

View file

@ -1,64 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
/**
* A template buffer is a container for a string and variables.
*/
public final class TemplateBuffer {
/** The string of the template buffer */
private String fString;
/** The variable positions of the template buffer */
private TemplatePosition[] fVariables;
/**
* Creates a template buffer.
*
* @param string the string
* @param variables the variable positions
* @throws CoreException for illegal variable positions
*/
public TemplateBuffer(String string, TemplatePosition[] variables) throws CoreException {
setContent(string, variables);
}
/**
* Sets the content of the template buffer.
*
* @param string the string
* @param variables the variable positions
* @throws CoreException for illegal variable positions
*/
public final void setContent(String string, TemplatePosition[] variables) throws CoreException {
Assert.isNotNull(string);
Assert.isNotNull(variables);
// XXX assert non-overlapping variable properties
fString= string;
fVariables= variables;
}
/**
* Returns the string of the template buffer.
*/
public final String getString() {
return fString;
}
/**
* Returns the variable positions of the template buffer.
*/
public final TemplatePosition[] getVariables() {
return fVariables;
}
}

View file

@ -1,42 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
/**
* A template context. A template context is associated with a context type.
*/
public abstract class TemplateContext {
/** context type of this context */
private final ContextType fContextType;
/**
* Creates a template context of a particular context type.
*/
protected TemplateContext(ContextType contextType) {
fContextType= contextType;
}
/**
* Returns the context type of this context.
*/
public ContextType getContextType() {
return fContextType;
}
/**
* Evaluates the template and returns a template buffer.
*/
public abstract TemplateBuffer evaluate(Template template) throws CoreException;
/**
* Tests if the specified template can be evaluated in this context.
*/
public abstract boolean canEvaluate(Template template);
}

View file

@ -1,52 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class TemplateMessages {
private static final String RESOURCE_BUNDLE= TemplateMessages.class.getName();
private static ResourceBundle fgResourceBundle;
static {
try {
fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
} catch (MissingResourceException x) {
fgResourceBundle = null;
}
}
private TemplateMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
} catch (NullPointerException e) {
return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Gets a string from the resource bundle and formats it with the argument
*
* @param key the string used to get the bundle value, must not be null
*/
public static String getFormattedString(String key, Object arg) {
return MessageFormat.format(getString(key), new Object[] { arg });
}
/**
* Gets a string from the resource bundle and formats it with arguments
*/
public static String getFormattedString(String key, Object[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -1,111 +0,0 @@
#########################################
# (c) Copyright IBM Corp. 2000, 2001.
# All Rights Reserved.
#########################################
# preference page
TemplatePreferencePage.error.import=Failed to import templates.
TemplatePreferencePage.error.export=Failed to export templates.
TemplatePreferencePage.error.read.title=Reading Templates
TemplatePreferencePage.error.write.title=Reading Templates
TemplatePreferencePage.message=&Create, edit or remove templates:
TemplatePreferencePage.title=Templates
TemplatePreferencePage.new=&New...
TemplatePreferencePage.edit=&Edit...
TemplatePreferencePage.import=&Import...
TemplatePreferencePage.export=E&xport...
TemplatePreferencePage.export.all=Ex&port All...
TemplatePreferencePage.remove=&Remove
TemplatePreferencePage.enable.all=Ena&ble All
TemplatePreferencePage.disable.all=Di&sable All
TemplatePreferencePage.editor=Template
TemplatePreferencePage.column.name=Name
TemplatePreferencePage.column.context=Context
TemplatePreferencePage.column.description=Description
TemplatePreferencePage.use.code.formatter=Use Code &Formatter
TemplatePreferencePage.import.title=Importing Templates
TemplatePreferencePage.import.extension=*.xml
TemplatePreferencePage.export.title=Exporting {0} {0,choice,1#Template|2#Templates}
TemplatePreferencePage.export.filename=templates.xml
TemplatePreferencePage.export.extension=*.xml
TemplatePreferencePage.export.exists.title=Exporting Templates
TemplatePreferencePage.export.exists.message={0} already exists.\nDo you want to replace it?
TemplatePreferencePage.question.create.new.title=Edit Template
TemplatePreferencePage.question.create.new.message=The name of the template was changed.\nDo you want to create a new template?
TemplatePreferencePage.preview=Preview
# edit template dialog
EditTemplateDialog.error.noname=Template name must not be empty.
EditTemplateDialog.error.adjacent.variables=Template pattern has adjacent variables.
EditTemplateDialog.title.new=New Template
EditTemplateDialog.title.edit=Edit Template
EditTemplateDialog.name=&Name:
EditTemplateDialog.description=&Description:
EditTemplateDialog.context=&Context:
EditTemplateDialog.pattern=&Pattern:
EditTemplateDialog.insert.variable=Insert &Variable...
EditTemplateDialog.undo=&Undo@Ctrl+Z
EditTemplateDialog.cut=Cu&t@Ctrl+X
EditTemplateDialog.copy=&Copy@Ctrl+C
EditTemplateDialog.paste=&Paste@Ctrl+V
EditTemplateDialog.select.all=Select &All@Ctrl+A
EditTemplateDialog.content.assist=Insert &Variable...@Ctrl+Space
EditTemplateDialog.pattern=Pattern
# template variable dialog
TemplateVariableDialog.title=Select a template variable.
TemplateVariableDialog.column.name=Name
TemplateVariableDialog.column.description=Description
TemplateVariableDialog.insert=&Insert
TemplateVariableProposal.error.title=Error applying template variable proposal
TemplateVariableProcessor.error.title=Error creating template variable proposals
# template set
TemplateSet.error.read=Error occured while reading templates.
TemplateSet.error.write=Error occured while writing templates.
TemplateSet.error.missingAttribute=Missing required attribute
# templates
Templates.error.title=Error accessing templates.
Templates.error.read=Error occured while reading templates.
Templates.error.write=Error occured while writing templates.
# template engine
TemplateEngine.error.title=Could not create template proposals.
# template proposal
TemplateProposal.delimiter=\ -
# template evaluator
TemplateEvaluator.error.title=Template Evaluation Error
# template collector
TemplateCollector.variable.description.file=Filename of compilation unit
TemplateCollector.variable.description.line=Current line number
TemplateCollector.variable.description.date=Current date
TemplateCollector.variable.description.time=Current time
TemplateCollector.variable.description.user=User name
TemplateCollector.variable.description.array=A proposal for an array
TemplateCollector.variable.description.array.type=A proposal for the element type of an array
TemplateCollector.variable.description.array.element=A proposal for the element name of an array
TemplateCollector.variable.description.index=A proposal for an index (int)
TemplateCollector.variable.description.collector=A proposal for a collector (java.util.Collector)
TemplateCollector.variable.description.iterator=A proposal for an iterator (java.util.Iterator)
TemplateCollector.variable.description.return.type=Return type (evaluates to void)
TemplateCollector.variable.description.arguments=Method arguments (evaluates to empty string)
# template translator
TemplateTranslator.error.incomplete.variable=Template has incomplete variables.
TemplateTranslator.error.invalid.identifier=Template has invalid variable identifiers.

View file

@ -1,97 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
*
*/
public class TemplatePosition {
/** The name of the template position */
private final String fName;
/** The default value of the template position */
private final String fDefaultValue;
/** The length of the template positions. */
private int fLength;
/** The offsets of the template positions. */
private int[] fOffsets;
/** A flag indicating if the template position has been resolved. */
private boolean fResolved;
/**
* Creates a template position.
*
* @param name the name of the template position.
* @param defaultValue the default value of the position.
* @param offsets the array of offsets of the position.
* @param the length of the position.
*/
public TemplatePosition(String name, String defaultValue, int[] offsets, int length) {
fName= name;
fDefaultValue= defaultValue;
fOffsets= offsets;
fLength= length;
fResolved= false;
}
/**
* Returns the name of the position.
*/
public String getName() {
return fName;
}
/**
* Returns the default value of the position.
*/
public String getDefaultValue() {
return fDefaultValue;
}
/**
* Sets the length of the position.
*/
public void setLength(int length) {
fLength= length;
}
/**
* Returns the length of the position.
*/
public int getLength() {
return fLength;
}
/**
* Sets the offsets of the position.
*/
public void setOffsets(int[] offsets) {
fOffsets= offsets;
}
/**
* Returns the offsets of the position.
*/
public int[] getOffsets() {
return fOffsets;
}
/**
* Sets the resolved flag of the position.
*/
public void setResolved(boolean resolved) {
fResolved= resolved;
}
/**
* Returns <code>true</code> if the position is resolved, <code>false</code> otherwise.
*/
public boolean isResolved() {
return fResolved;
}
}

View file

@ -1,300 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.cdt.internal.ui.CStatusConstants;
import org.eclipse.cdt.internal.ui.CUIException;
import org.eclipse.cdt.internal.ui.CUIStatus;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <code>TemplateSet</code> manages a collection of templates and makes them
* persistent.
*/
public class TemplateSet {
private static class TemplateComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
if (arg0 == arg1)
return 0;
if (arg0 == null)
return -1;
Template template0= (Template) arg0;
Template template1= (Template) arg1;
return template0.getName().compareTo(template1.getName());
}
}
private static final String TEMPLATE_TAG= "template"; //$NON-NLS-1$
private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
private List fTemplates= new ArrayList();
private Comparator fTemplateComparator= new TemplateComparator();
private Template[] fSortedTemplates= new Template[0];
/**
* Convenience method for reading templates from a file.
*
* @see addFromStream(InputStream)
*/
public void addFromFile(File file) throws CoreException {
InputStream stream= null;
try {
stream= new FileInputStream(file);
addFromStream(stream);
} catch (IOException e) {
throwReadException(e);
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {}
}
}
/**
* Reads templates from a XML stream and adds them to the template set.
*/
public void addFromStream(InputStream stream) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder parser= factory.newDocumentBuilder();
Document document= parser.parse(new InputSource(stream));
NodeList elements= document.getElementsByTagName(TEMPLATE_TAG);
int count= elements.getLength();
for (int i= 0; i != count; i++) {
Node node= elements.item(i);
NamedNodeMap attributes= node.getAttributes();
if (attributes == null)
continue;
String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
Node enabledNode= attributes.getNamedItem(ENABLED_ATTRIBUTE);
if (name == null || description == null || context == null)
throw new SAXException(TemplateMessages.getString("TemplateSet.error.missingAttribute")); //$NON-NLS-1$
boolean enabled= (enabledNode == null) || (enabledNode.getNodeValue().equals("true")); //$NON-NLS-1$
StringBuffer buffer= new StringBuffer();
NodeList children= node.getChildNodes();
for (int j= 0; j != children.getLength(); j++) {
String value= children.item(j).getNodeValue();
if (value != null)
buffer.append(value);
}
String pattern= buffer.toString().trim();
Template template= new Template(name, description, context, pattern);
template.setEnabled(enabled);
add(template);
}
sort();
} catch (ParserConfigurationException e) {
throwReadException(e);
} catch (IOException e) {
throwReadException(e);
} catch (SAXException e) {
throwReadException(e);
}
}
private String getAttributeValue(NamedNodeMap attributes, String name) {
Node node= attributes.getNamedItem(name);
return node == null
? null
: node.getNodeValue();
}
/**
* Convenience method for saving to a file.
*
* @see saveToStream(OutputStream)
*/
public void saveToFile(File file) throws CoreException {
OutputStream stream= null;
try {
stream= new FileOutputStream(file);
saveToStream(stream);
} catch (IOException e) {
throwWriteException(e);
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {}
}
}
/**
* Saves the template set as XML.
*/
public void saveToStream(OutputStream stream) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document document= builder.newDocument();
Node root= document.createElement("templates"); // $NON-NLS-1$ //$NON-NLS-1$
document.appendChild(root);
for (int i= 0; i != fTemplates.size(); i++) {
Template template= (Template) fTemplates.get(i);
Node node= document.createElement("template"); // $NON-NLS-1$ //$NON-NLS-1$
root.appendChild(node);
NamedNodeMap attributes= node.getAttributes();
Attr name= document.createAttribute(NAME_ATTRIBUTE);
name.setValue(template.getName());
attributes.setNamedItem(name);
Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
description.setValue(template.getDescription());
attributes.setNamedItem(description);
Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
context.setValue(template.getContextTypeName());
attributes.setNamedItem(context);
Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE);
enabled.setValue(template.isEnabled() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
attributes.setNamedItem(enabled);
Text pattern= document.createTextNode(template.getPattern());
node.appendChild(pattern);
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(stream);
transformer.transform(source,result);
} catch (ParserConfigurationException e) {
throwWriteException(e);
} catch (TransformerException e) {
throwWriteException(e);
}
}
private static void throwReadException(Throwable t) throws CoreException {
IStatus status= new CUIStatus(CStatusConstants.TEMPLATE_IO_EXCEPTION,
TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
throw new CUIException(status);
}
private static void throwWriteException(Throwable t) throws CoreException {
IStatus status= new CUIStatus(CStatusConstants.TEMPLATE_IO_EXCEPTION,
TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
throw new CUIException(status);
}
/**
* Adds a template to the set.
*/
public void add(Template template) {
if (exists(template))
return; // ignore duplicate
fTemplates.add(template);
sort();
}
private boolean exists(Template template) {
for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) {
Template anotherTemplate = (Template) iterator.next();
if (template.equals(anotherTemplate))
return true;
}
return false;
}
/**
* Removes a template to the set.
*/
public void remove(Template template) {
fTemplates.remove(template);
sort();
}
/**
* Empties the set.
*/
public void clear() {
fTemplates.clear();
sort();
}
/**
* Returns all templates.
*/
public Template[] getTemplates() {
return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
}
private void sort() {
fSortedTemplates= (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
Arrays.sort(fSortedTemplates, fTemplateComparator);
}
}

View file

@ -1,215 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
/**
* The template translator translates a string into a template buffer.
* The EBNF grammer of a valid string is as follows:
*
* <p>
* template := (text | escape)*.<br />
* text := character - dollar.<br />
* escape := dollar ('{' identifier '}' | dollar).<br />
* dollar := '$'.<br />
* </p>
*/
public class TemplateTranslator {
// states
private static final int TEXT= 0;
private static final int ESCAPE= 1;
private static final int IDENTIFIER= 2;
// tokens
private static final char ESCAPE_CHARACTER= '$';
private static final char IDENTIFIER_BEGIN= '{';
private static final char IDENTIFIER_END= '}';
/** a buffer for the translation result string */
private final StringBuffer fBuffer= new StringBuffer();
/** position offsets of variables */
private final Vector fOffsets= new Vector();
/** position lengths of variables */
private final Vector fLengths= new Vector();
/** the current parsing state */
private int fState;
/** the last translation error */
private String fErrorMessage;
/**
* Returns an error message if an error occured for the last translation, <code>null</code>
* otherwise.
*/
public String getErrorMessage() {
return fErrorMessage;
}
/**
* Translates a template string to <code>TemplateBuffer</code>. <code>null</code>
* is returned if there was an error. <code>getErrorMessage()</code> retrieves the
* associated error message.
*
* @param string the string to translate.
* @return returns the template buffer corresponding to the string, <code>null</code>
* if there was an error.
* @see getErrorMessage()
*/
public TemplateBuffer translate(String string) throws CoreException {
fBuffer.setLength(0);
fOffsets.clear();
fLengths.clear();
fState= TEXT;
fErrorMessage= null;
if (!parse(string))
return null;
switch (fState) {
case TEXT:
break;
// illegal, but be tolerant
case ESCAPE:
fErrorMessage= TemplateMessages.getString("TemplateTranslator.error.incomplete.variable"); //$NON-NLS-1$
fBuffer.append(ESCAPE_CHARACTER);
return null;
// illegal, but be tolerant
case IDENTIFIER:
fErrorMessage= TemplateMessages.getString("TemplateTranslator.error.incomplete.variable"); //$NON-NLS-1$
fBuffer.append(ESCAPE_CHARACTER);
return null;
}
int[] offsets= new int[fOffsets.size()];
int[] lengths= new int[fLengths.size()];
for (int i= 0; i < fOffsets.size(); i++) {
offsets[i]= ((Integer) fOffsets.get(i)).intValue();
lengths[i]= ((Integer) fLengths.get(i)).intValue();
}
String translatedString= fBuffer.toString();
TemplatePosition[] variables= findVariables(translatedString, offsets, lengths);
return new TemplateBuffer(translatedString, variables);
}
private static TemplatePosition[] findVariables(String string, int[] offsets, int[] lengths) {
Map map= new HashMap();
for (int i= 0; i != offsets.length; i++) {
int offset= offsets[i];
int length= lengths[i];
String content= string.substring(offset, offset + length);
Vector vector= (Vector) map.get(content);
if (vector == null) {
vector= new Vector();
map.put(content, vector);
}
vector.add(new Integer(offset));
}
TemplatePosition[] variables= new TemplatePosition[map.size()];
int k= 0;
Set keys= map.keySet();
for (Iterator i= keys.iterator(); i.hasNext(); ) {
String name= (String) i.next();
Vector vector= (Vector) map.get(name);
int[] offsets_= new int[vector.size()];
for (int j= 0; j != offsets_.length; j++)
offsets_[j]= ((Integer) vector.get(j)).intValue();
variables[k]= new TemplatePosition(name, name, offsets_, name.length());
k++;
}
return variables;
}
/** internal parser */
private boolean parse(String string) {
for (int i= 0; i != string.length(); i++) {
char ch= string.charAt(i);
switch (fState) {
case TEXT:
switch (ch) {
case ESCAPE_CHARACTER:
fState= ESCAPE;
break;
default:
fBuffer.append(ch);
break;
}
break;
case ESCAPE:
switch (ch) {
case ESCAPE_CHARACTER:
fBuffer.append(ch);
fState= TEXT;
break;
case IDENTIFIER_BEGIN:
fOffsets.add(new Integer(fBuffer.length()));
fState= IDENTIFIER;
break;
default:
// illegal single escape character, but be tolerant
fErrorMessage= TemplateMessages.getString("TemplateTranslator.error.incomplete.variable"); //$NON-NLS-1$
fBuffer.append(ESCAPE_CHARACTER);
fBuffer.append(ch);
fState= TEXT;
return false;
}
break;
case IDENTIFIER:
switch (ch) {
case IDENTIFIER_END:
int offset = ((Integer) fOffsets.get(fOffsets.size() - 1)).intValue();
fLengths.add(new Integer(fBuffer.length() - offset));
fState= TEXT;
break;
default:
if (!Character.isUnicodeIdentifierStart(ch) &&
!Character.isUnicodeIdentifierPart(ch))
{
// illegal identifier character
fErrorMessage= TemplateMessages.getString("TemplateTranslator.error.invalid.identifier"); //$NON-NLS-1$
return false;
}
fBuffer.append(ch);
break;
}
break;
}
}
return true;
}
}

View file

@ -1,65 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
* A template variable.
*/
public abstract class TemplateVariable {
/** name of the variable */
private final String fName;
/** description of the variable */
private final String fDescription;
/**
* Creates an instance of <code>TemplateVariable</code>.
*
* @param name the name of the variable
* @param description the description for the variable
*/
protected TemplateVariable(String name, String description) {
fName= name;
fDescription= description;
}
/**
* Returns the name of the variable.
*/
public String getName() {
return fName;
}
/**
* Returns the description for the variable.
*/
public String getDescription() {
return fDescription;
}
/**
* Tests if this variable can be evaluated.
*/
// public abstract boolean canEvaluate(TemplateContext context);
/**
* Evaluates this variable
*
* @return the evaluated string, or <code>null</code> if not evaluatable.
*/
public abstract String evaluate(TemplateContext context);
/**
* Returns whether this variable is resolved.
* By default, the variable is not resolved.
* Clients can overwrite this method to force resolution of the variable.
*/
public boolean isResolved(TemplateContext context) {
return false;
}
}

View file

@ -1,134 +0,0 @@
package org.eclipse.cdt.internal.corext.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.ui.internal.util.BundleUtility;
import org.osgi.framework.Bundle;
/**
* <code>Templates</code> gives access to the available templates.
*/
public class Templates extends TemplateSet {
private static final String DEFAULT_FILE= "default-templates.xml"; //$NON-NLS-1$
private static final String NL_DEFAULT_FILE= "$nl$/org/eclipse/cdt/internal/corext/template/default-templates.xml"; //$NON-NLS-1$
private static final String TEMPLATE_FILE= "templates.xml"; //$NON-NLS-1$
/** Singleton. */
private static Templates fgTemplates;
/**
* Returns an instance of templates.
*/
public static Templates getInstance() {
if (fgTemplates == null)
fgTemplates= create();
return fgTemplates;
}
private static Templates create() {
Templates templates= new Templates();
try {
File templateFile= getTemplateFile();
if (templateFile.exists()) {
templates.addFromFile(templateFile);
} else {
templates.addFromStream(getDefaultsAsStream());
templates.saveToFile(templateFile);
}
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
ErrorDialog.openError(null,
TemplateMessages.getString("Templates.error.title"), //$NON-NLS-1$
e.getMessage(), e.getStatus());
templates.clear();
}
return templates;
}
/**
* Resets the template set.
*/
public void reset() throws CoreException {
clear();
addFromFile(getTemplateFile());
}
/**
* Resets the template set with the default templates.
*/
public void restoreDefaults() throws CoreException {
clear();
addFromStream(getDefaultsAsStream());
}
/**
* Saves the template set.
*/
public void save() throws CoreException {
saveToFile(getTemplateFile());
}
private static InputStream getDefaultsAsStream() {
URL defFile = getDefaultTemplateFile();
if (defFile == null) return Templates.class.getResourceAsStream(DEFAULT_FILE);
try {
return defFile.openStream();
} catch (IOException e) {
return null;
}
//return Templates.class.getResourceAsStream(getDefaultTemplateFile());
}
/**
* Gets the resolved $nl$ path to the NL_DEFAULT_TEMPLATE file as a URL.
* If it doesn't exist, then null is returned. Calling procedures use
* DEFAULT_TEMPLATES if null is returned from this.
*/
public static URL getDefaultTemplateFile() {
Bundle bundle = Platform.getBundle("org.eclipse.cdt.ui"); //$NON-NLS-1$
if (!BundleUtility.isReady(bundle))
return null;
URL fullPathString = BundleUtility.find(bundle, NL_DEFAULT_FILE);
if (fullPathString == null) {
try {
fullPathString = new URL(NL_DEFAULT_FILE);
} catch (MalformedURLException e) {
return null;
}
}
return fullPathString;
}
private static File getTemplateFile() {
IPath path= CUIPlugin.getDefault().getStateLocation();
path= path.append(TEMPLATE_FILE);
return path.toFile();
}
}

View file

@ -5,23 +5,30 @@ package org.eclipse.cdt.internal.corext.template.c;
* All Rights Reserved. * All Rights Reserved.
*/ */
import org.eclipse.cdt.internal.corext.template.ContextType; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor; import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.corext.template.Template; import org.eclipse.cdt.internal.ui.util.Strings;
import org.eclipse.cdt.internal.corext.template.TemplateBuffer;
import org.eclipse.cdt.internal.corext.template.TemplateTranslator;
import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.cdt.internal.corext.textmanipulation.TextUtil;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.CoreException; import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.TemplateException;
import org.eclipse.jface.text.templates.TemplateTranslator;
/** /**
* A context for c/c++ * A context for c/c++
*/ */
public class CContext extends CompilationUnitContext { public class CContext extends TranslationUnitContext {
/** The platform default line delimiter. */
private static final String PLATFORM_LINE_DELIMITER= System.getProperty("line.separator"); //$NON-NLS-1$
/** /**
* Creates a javadoc template context. * Creates a javadoc template context.
@ -31,43 +38,72 @@ public class CContext extends CompilationUnitContext {
* @param completionPosition the completion position within the document. * @param completionPosition the completion position within the document.
* @param unit the compilation unit (may be <code>null</code>). * @param unit the compilation unit (may be <code>null</code>).
*/ */
public CContext(ContextType type, String string, int completionPosition, public CContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength,
ICompilationUnit compilationUnit) ITranslationUnit translationUnit)
{ {
super(type, string, completionPosition, compilationUnit); super(type, document, completionOffset, completionLength, translationUnit);
} }
/* /*
* @see DocumentTemplateContext#getStart() * @see DocumentTemplateContext#getStart()
*/ */
public int getStart() { public int getStart() {
String string= getString(); try {
int start= getCompletionPosition(); IDocument document= getDocument();
while ((start != 0) && Character.isUnicodeIdentifierPart(string.charAt(start - 1))) if (getCompletionLength() == 0) {
int start= getCompletionOffset();
while ((start != 0) && Character.isUnicodeIdentifierPart(document.getChar(start - 1)))
start--; start--;
if ((start != 0) && Character.isUnicodeIdentifierStart(string.charAt(start - 1))) if ((start != 0) && Character.isUnicodeIdentifierStart(document.getChar(start - 1)))
start--; start--;
return start; return start;
} }
/** int start= getCompletionOffset();
* Returns the indentation level at the position of code completion. int end= getCompletionOffset() + getCompletionLength();
*/
public int getIndentationLevel() { while (start != 0 && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) {
String string= getString(); start--;
int start= getStart(); }
while (start != end && Character.isWhitespace(document.getChar(start))) {
start++;
}
if (start == end) {
start= getCompletionOffset();
}
return start;
} catch (BadLocationException e) {
return super.getStart();
}
}
public int getEnd() {
if (getCompletionLength() == 0)
return super.getEnd();
try { try {
TextBuffer textBuffer= TextBuffer.create(string); IDocument document= getDocument();
String lineContent= textBuffer.getLineContentOfOffset(start);
return TextUtil.getIndent(lineContent, CUIPlugin.getDefault().getPreferenceStore().getInt(CSourceViewerConfiguration.PREFERENCE_TAB_WIDTH)); int start= getCompletionOffset();
int end= getCompletionOffset() + getCompletionLength();
} catch (CoreException e) { while (start != end && Character.isWhitespace(document.getChar(end - 1))) {
return 0; end--;
}
return end;
} catch (BadLocationException e) {
return super.getEnd();
} }
} }
@ -75,27 +111,57 @@ public class CContext extends CompilationUnitContext {
* @see TemplateContext#canEvaluate(Template templates) * @see TemplateContext#canEvaluate(Template templates)
*/ */
public boolean canEvaluate(Template template) { public boolean canEvaluate(Template template) {
return template.matches(getKey(), getContextType().getName()); String key= getKey();
return template.matches(key, getContextType().getId())
&& key.length() != 0 && template.getName().toLowerCase().startsWith(key.toLowerCase());
//return template.matches(getKey(), getContextType().getName());
} }
/* /*
* @see TemplateContext#evaluate(Template) * @see TemplateContext#evaluate(Template)
*/ */
public TemplateBuffer evaluate(Template template) throws CoreException { public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
if (!canEvaluate(template)) if (!canEvaluate(template))
return null; return null;
TemplateTranslator translator= new TemplateTranslator(); TemplateTranslator translator= new TemplateTranslator();
TemplateBuffer buffer= translator.translate(template.getPattern()); TemplateBuffer buffer= translator.translate(template.getPattern());
getContextType().edit(buffer, this); getContextType().resolve(buffer, this);
ITemplateEditor formatter= new CFormatter(); String lineDelimiter= null;
formatter.edit(buffer, this); try {
lineDelimiter= getDocument().getLineDelimiter(0);
} catch (BadLocationException e) {
}
if (lineDelimiter == null) {
lineDelimiter= PLATFORM_LINE_DELIMITER;
}
IPreferenceStore prefs= CUIPlugin.getDefault().getPreferenceStore();
boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
CFormatter formatter= new CFormatter(lineDelimiter, getIndentation(), useCodeFormatter);
formatter.edit(buffer, this, getIndentation());
return buffer; return buffer;
} }
/**
* Returns the indentation level at the position of code completion.
*/
private int getIndentation() {
int start= getStart();
IDocument document= getDocument();
try {
IRegion region= document.getLineInformationOfOffset(start);
String lineContent= document.get(region.getOffset(), region.getLength());
return Strings.computeIndent(lineContent, CodeFormatterUtil.getTabWidth());
} catch (BadLocationException e) {
return 0;
}
}
} }

View file

@ -0,0 +1,59 @@
/**********************************************************************
* Copyright (c) 2002,2003,2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.templates.GlobalTemplateVariables;
/**
* CContextType
*/
public class CContextType extends TranslationUnitContextType {
public final static String CCONTEXT_TYPE = "org.eclipse.cdt.ui.text.templates.c"; //$NON-NLS-1$
/**
* @param name
*/
public CContextType() {
super();
// global
addResolver(new GlobalTemplateVariables.Cursor());
addResolver(new GlobalTemplateVariables.WordSelection());
addResolver(new GlobalTemplateVariables.LineSelection());
addResolver(new GlobalTemplateVariables.Dollar());
addResolver(new GlobalTemplateVariables.Date());
addResolver(new GlobalTemplateVariables.Year());
addResolver(new GlobalTemplateVariables.Time());
addResolver(new GlobalTemplateVariables.User());
// translation unit
addResolver(new File());
addResolver(new ReturnType());
addResolver(new Method());
addResolver(new Type());
addResolver(new Package());
addResolver(new Project());
addResolver(new Arguments());
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.corext.template.c.TranslationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, org.eclipse.cdt.core.model.ITranslationUnit)
*/
public TranslationUnitContext createContext(IDocument document, int offset,
int length, ITranslationUnit translationUnit) {
return new CContext(this, document, offset, length, translationUnit);
}
}

View file

@ -5,193 +5,312 @@ package org.eclipse.cdt.internal.corext.template.c;
* All Rights Reserved. * All Rights Reserved.
*/ */
import org.eclipse.cdt.internal.corext.template.ITemplateEditor; import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.corext.template.TemplateBuffer; import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.internal.corext.template.TemplateContext; import org.eclipse.cdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.cdt.internal.corext.template.TemplatePosition; import org.eclipse.cdt.internal.ui.util.Strings;
import org.eclipse.cdt.internal.corext.textmanipulation.MultiTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.NopTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.cdt.internal.corext.textmanipulation.TextBufferEditor;
import org.eclipse.cdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.cdt.internal.corext.textmanipulation.TextRegion;
import org.eclipse.cdt.internal.corext.textmanipulation.TextUtil;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateVariable;
import org.eclipse.text.edits.DeleteEdit;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.RangeMarker;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
/** /**
* A template editor using the Java formatter to format a template buffer. * A template editor using the Java formatter to format a template buffer.
*/ */
public class CFormatter implements ITemplateEditor { public class CFormatter {
private static final String CURSOR= "cursor"; //$NON-NLS-1$ // private static final String CURSOR= "cursor"; //$NON-NLS-1$
private static final String MARKER= "/*${cursor}*/"; //$NON-NLS-1$ // private static final String MARKER= "/*${cursor}*/"; //$NON-NLS-1$
/* /** The line delimiter to use if code formatter is not used. */
* @see ITemplateEditor#edit(TemplateBuffer, TemplateContext) private final String fLineDelimiter;
*/ /** The initial indent level */
public void edit(TemplateBuffer buffer, TemplateContext context) throws CoreException { private final int fInitialIndentLevel;
int indentationLevel= ((CContext) context).getIndentationLevel();
//if (TemplatePreferencePage.useCodeFormatter()) /** The java partitioner */
// format(buffer, indentationLevel); private boolean fUseCodeFormatter;
//else
indentate(buffer, indentationLevel); public CFormatter(String lineDelimiter, int initialIndentLevel, boolean useCodeFormatter) {
fLineDelimiter= lineDelimiter;
fUseCodeFormatter= useCodeFormatter;
fInitialIndentLevel= initialIndentLevel;
}
public void edit(TemplateBuffer buffer, CContext context, int indentationLevel) throws BadLocationException {
try {
if (fUseCodeFormatter)
// try to format and fall back to indenting
try {
format(buffer, context);
} catch (BadLocationException e) {
indent(buffer);
} catch (MalformedTreeException e) {
indent(buffer);
}
else {
indent(buffer);
}
// don't trim the buffer if the replacement area is empty
// case: surrounding empty lines with block
if (context.getStart() == context.getCompletionOffset())
if (context.getDocument().get(context.getStart(), context.getEnd() - context.getEnd()).trim().length() == 0)
return;
trimBegin(buffer); trimBegin(buffer);
} catch (MalformedTreeException e) {
throw new BadLocationException();
}
} }
private static int getCaretOffset(TemplatePosition[] variables) { // private static int getCaretOffset(TemplateVariable[] variables) {
for (int i= 0; i != variables.length; i++) { // for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i]; // TemplateVariable variable= variables[i];
//
// if (variable.getName().equals(CURSOR)) {
// return variable.getOffsets()[0];
// }
// }
//
// return -1;
// }
if (variable.getName().equals(CURSOR)) // private boolean isInsideCommentOrString(String string, int offset) {
return variable.getOffsets()[0]; //
// IDocument document= new Document(string);
// CUIPlugin.getDefault().getTextTools().setupCDocument(document);
//
// try {
// ITypedRegion partition= document.getPartition(offset);
// String partitionType= partition.getType();
//
// return partitionType != null && (
// partitionType.equals(ICPartitions.C_MULTILINE_COMMENT) ||
// partitionType.equals(ICPartitions.C_SINGLE_LINE_COMMENT) ||
// partitionType.equals(ICPartitions.C_STRING));
// } catch (BadLocationException e) {
// return false;
// }
// }
private void format(TemplateBuffer templateBuffer, CContext context) throws BadLocationException {
// XXX 4360, 15247
// workaround for code formatter limitations
// handle a special case where cursor position is surrounded by whitespaces
// String string= templateBuffer.getString();
// TemplateVariable[] variables= templateBuffer.getVariables();
//
// int caretOffset= getCaretOffset(variables);
// if ((caretOffset > 0) && Character.isWhitespace(string.charAt(caretOffset - 1)) &&
// (caretOffset < string.length()) && Character.isWhitespace(string.charAt(caretOffset)) &&
// ! isInsideCommentOrString(string, caretOffset))
// {
// List positions= variablesToPositions(variables);
//
// TextEdit insert= new InsertEdit(caretOffset, MARKER);
// string= edit(string, positions, insert);
// positionsToVariables(positions, variables);
// templateBuffer.setContent(string, variables);
//
// plainFormat(templateBuffer, context);
//
// string= templateBuffer.getString();
// variables= templateBuffer.getVariables();
// caretOffset= getCaretOffset(variables);
//
// positions= variablesToPositions(variables);
// TextEdit delete= new DeleteEdit(caretOffset, MARKER.length());
// string= edit(string, positions, delete);
// positionsToVariables(positions, variables);
// templateBuffer.setContent(string, variables);
//
// } else {
// plainFormat(templateBuffer, context);
// }
plainFormat(templateBuffer, context);
} }
return -1; private void plainFormat(TemplateBuffer templateBuffer, CContext context) throws BadLocationException {
IDocument doc= new Document(templateBuffer.getString());
TemplateVariable[] variables= templateBuffer.getVariables();
List offsets= variablesToPositions(variables);
Map options;
if (context.getTranslationUnit() != null)
options= context.getTranslationUnit().getCProject().getOptions(true);
else
options= CCorePlugin.getOptions();
TextEdit edit= CodeFormatterUtil.format(CodeFormatter.K_UNKNOWN, doc.get(), fInitialIndentLevel, fLineDelimiter, options);
if (edit == null)
throw new BadLocationException(); // fall back to indenting
MultiTextEdit root;
if (edit instanceof MultiTextEdit)
root= (MultiTextEdit) edit;
else {
root= new MultiTextEdit(0, doc.getLength());
root.addChild(edit);
}
for (Iterator it= offsets.iterator(); it.hasNext();) {
TextEdit position= (TextEdit) it.next();
try {
root.addChild(position);
} catch (MalformedTreeException e) {
// position conflicts with formatter edit
// ignore this position
}
} }
root.apply(doc, TextEdit.UPDATE_REGIONS);
private static void indentate(TemplateBuffer templateBuffer, int indentationLevel) throws CoreException { positionsToVariables(offsets, variables);
String string= templateBuffer.getString(); templateBuffer.setContent(doc.get(), variables);
TemplatePosition[] variables= templateBuffer.getVariables(); }
String indentation= TextUtil.createIndentString(indentationLevel);
private void indent(TemplateBuffer templateBuffer) throws BadLocationException, MalformedTreeException {
MultiTextEdit positions= variablesToPositions(variables);
MultiTextEdit multiEdit= new MultiTextEdit(); TemplateVariable[] variables= templateBuffer.getVariables();
List positions= variablesToPositions(variables);
TextBuffer textBuffer= TextBuffer.create(string);
int lineCount= textBuffer.getNumberOfLines(); IDocument document= new Document(templateBuffer.getString());
for (int i= 0; i < lineCount; i++) { MultiTextEdit root= new MultiTextEdit(0, document.getLength());
TextRegion region= textBuffer.getLineInformation(i); root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()]));
multiEdit.add(SimpleTextEdit.createInsert(region.getOffset(), indentation));
String indent= Strings.createIndentString(fInitialIndentLevel);
// first line
int offset= document.getLineOffset(0);
TextEdit edit= new InsertEdit(offset, indent);
root.addChild(edit);
root.apply(document, TextEdit.UPDATE_REGIONS);
root.removeChild(edit);
formatDelimiter(document, root, 0);
// following lines
int lineCount= document.getNumberOfLines();
for (int line= 1; line < lineCount; line++) {
IRegion region= document.getLineInformation(line);
offset= region.getOffset();
int nws = offset;
for (int i = offset; i < region.getLength(); ++i) {
if (! Character.isWhitespace(document.getChar(i))) {
nws = i;
break;
}
}
edit= new ReplaceEdit(offset, nws - offset, indent);
root.addChild(edit);
root.apply(document, TextEdit.UPDATE_REGIONS);
root.removeChild(edit);
formatDelimiter(document, root, line);
} }
string= edit(string, positions, multiEdit);
positionsToVariables(positions, variables); positionsToVariables(positions, variables);
templateBuffer.setContent(document.get(), variables);
templateBuffer.setContent(string, variables);
} }
private static void trimBegin(TemplateBuffer templateBuffer) throws CoreException { /**
String string= templateBuffer.getString(); * Changes the delimiter to the configured line delimiter.
TemplatePosition[] variables= templateBuffer.getVariables(); *
* @param document the temporary document being edited
* @param root the root edit containing all positions that will be updated along the way
* @param line the line to format
* @throws BadLocationException if applying the changes fails
*/
private void formatDelimiter(IDocument document, MultiTextEdit root, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null) {
TextEdit edit= new ReplaceEdit(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter);
root.addChild(edit);
root.apply(document, TextEdit.UPDATE_REGIONS);
root.removeChild(edit);
}
}
MultiTextEdit positions= variablesToPositions(variables); private static void trimBegin(TemplateBuffer templateBuffer) throws BadLocationException {
String string= templateBuffer.getString();
TemplateVariable[] variables= templateBuffer.getVariables();
List positions= variablesToPositions(variables);
int i= 0; int i= 0;
while ((i != string.length()) && Character.isWhitespace(string.charAt(i))) while ((i != string.length()) && Character.isWhitespace(string.charAt(i)))
i++; i++;
string= edit(string, positions, SimpleTextEdit.createDelete(0, i)); string= edit(string, positions, new DeleteEdit(0, i));
positionsToVariables(positions, variables); positionsToVariables(positions, variables);
templateBuffer.setContent(string, variables); templateBuffer.setContent(string, variables);
} }
private static String edit(String string, MultiTextEdit positions, MultiTextEdit multiEdit) throws CoreException { private static String edit(String string, List positions, TextEdit edit) throws BadLocationException {
TextBuffer textBuffer= TextBuffer.create(string); MultiTextEdit root= new MultiTextEdit(0, string.length());
TextBufferEditor editor= new TextBufferEditor(textBuffer); root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()]));
editor.add(positions); root.addChild(edit);
editor.add(multiEdit); IDocument document= new Document(string);
editor.performEdits(null); root.apply(document);
return textBuffer.getContent(); return document.get();
} }
private static String edit(String string, MultiTextEdit positions, TextEdit singleEdit) throws CoreException { private static List variablesToPositions(TemplateVariable[] variables) {
TextBuffer textBuffer= TextBuffer.create(string); List positions= new ArrayList(5);
TextBufferEditor editor= new TextBufferEditor(textBuffer);
editor.add(positions);
editor.add(singleEdit);
editor.performEdits(null);
return textBuffer.getContent();
}
private static int[] variablesToOffsets(TemplatePosition[] variables) {
Vector vector= new Vector();
for (int i= 0; i != variables.length; i++) { for (int i= 0; i != variables.length; i++) {
int[] offsets= variables[i].getOffsets(); int[] offsets= variables[i].getOffsets();
for (int j= 0; j != offsets.length; j++)
vector.add(new Integer(offsets[j]));
}
int[] offsets= new int[vector.size()]; // trim positions off whitespace
for (int i= 0; i != offsets.length; i++) String value= variables[i].getDefaultValue();
offsets[i]= ((Integer) vector.get(i)).intValue(); int wsStart= 0;
while (wsStart < value.length() && Character.isWhitespace(value.charAt(wsStart)) && !Strings.isLineDelimiterChar(value.charAt(wsStart)))
wsStart++;
Arrays.sort(offsets); variables[i].getValues()[0]= value.substring(wsStart);
return offsets; for (int j= 0; j != offsets.length; j++) {
} offsets[j] += wsStart;
positions.add(new RangeMarker(offsets[j], 0));
private static void offsetsToVariables(int[] allOffsets, TemplatePosition[] variables) {
int[] currentIndices= new int[variables.length];
for (int i= 0; i != currentIndices.length; i++)
currentIndices[i]= 0;
int[][] offsets= new int[variables.length][];
for (int i= 0; i != variables.length; i++)
offsets[i]= variables[i].getOffsets();
for (int i= 0; i != allOffsets.length; i++) {
int min= Integer.MAX_VALUE;
int minVariableIndex= -1;
for (int j= 0; j != variables.length; j++) {
int currentIndex= currentIndices[j];
// determine minimum
if (currentIndex == offsets[j].length)
continue;
int offset= offsets[j][currentIndex];
if (offset < min) {
min= offset;
minVariableIndex= j;
} }
} }
offsets[minVariableIndex][currentIndices[minVariableIndex]]= allOffsets[i];
currentIndices[minVariableIndex]++;
}
for (int i= 0; i != variables.length; i++)
variables[i].setOffsets(offsets[i]);
}
private static MultiTextEdit variablesToPositions(TemplatePosition[] variables) {
MultiTextEdit positions= new MultiTextEdit();
for (int i= 0; i != variables.length; i++) {
int[] offsets= variables[i].getOffsets();
for (int j= 0; j != offsets.length; j++)
positions.add(new NopTextEdit(offsets[j], 0));
}
return positions; return positions;
} }
private static void positionsToVariables(MultiTextEdit positions, TemplatePosition[] variables) { private static void positionsToVariables(List positions, TemplateVariable[] variables) {
Iterator iterator= positions.iterator(); Iterator iterator= positions.iterator();
for (int i= 0; i != variables.length; i++) { for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i]; TemplateVariable variable= variables[i];
int[] offsets= new int[variable.getOffsets().length]; int[] offsets= new int[variable.getOffsets().length];
for (int j= 0; j != offsets.length; j++) for (int j= 0; j != offsets.length; j++)
offsets[j]= ((TextEdit) iterator.next()).getTextRange().getOffset(); offsets[j]= ((TextEdit) iterator.next()).getOffset();
variable.setOffsets(offsets); variable.setOffsets(offsets);
} }
} }
} }

View file

@ -1,54 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on 19/12/2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
public class CFunctionContextType extends CompilationUnitContextType {
/**
* @param name
*/
public CFunctionContextType() {
super(ITemplateEditor.TemplateContextKind.C_FUNCTION_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
// @@@ Need to add some specific C ones
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.corext.template.ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,50 +0,0 @@
package org.eclipse.cdt.internal.corext.template.c;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
/**
* A context type for javadoc.
*/
public class CGlobalContextType extends CompilationUnitContextType {
/**
* Creates a C context type.
*/
public CGlobalContextType() {
super(ITemplateEditor.TemplateContextKind.C_GLOBAL_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
// @@@ Need to add some specific C ones
}
/*
* @see ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,55 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on 19/12/2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
public class CStructureContextType extends CompilationUnitContextType {
/**
* @param name
*/
public CStructureContextType() {
super(ITemplateEditor.TemplateContextKind.C_STRUCTURE_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
// @@@ Need to add some specific C ones
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.corext.template.ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on 19/12/2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
public class CppFunctionContextType extends CompilationUnitContextType {
public CppFunctionContextType() {
super(ITemplateEditor.TemplateContextKind.CPP_FUNCTION_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.corext.template.ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,47 +0,0 @@
package org.eclipse.cdt.internal.corext.template.c;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
/**
* A context type for javadoc.
*/
public class CppGlobalContextType extends CompilationUnitContextType {
/**
* Creates a C context type.
*/
public CppGlobalContextType() {
super(ITemplateEditor.TemplateContextKind.CPP_GLOBAL_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
}
/*
* @see ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on 19/12/2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
public class CppStructureContextType extends CompilationUnitContextType {
public CppStructureContextType() {
super(ITemplateEditor.TemplateContextKind.CPP_STRUCTURE_CONTEXT_TYPE);
// global
addVariable(new GlobalVariables.Cursor());
addVariable(new GlobalVariables.Dollar());
addVariable(new GlobalVariables.Date());
addVariable(new GlobalVariables.Time());
addVariable(new GlobalVariables.User());
// compilation unit
addVariable(new File());
/* addVariable(new Method());
addVariable(new ReturnType());
addVariable(new Arguments());
addVariable(new Type());
addVariable(new Package()); */
addVariable(new Project());
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.corext.template.ContextType#createContext()
*/
public TemplateContext createContext() {
return new CContext(this, fString, fPosition, fCompilationUnit);
}
}

View file

@ -1,80 +0,0 @@
package org.eclipse.cdt.internal.corext.template.c;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.template.SimpleTemplateVariable;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
import java.text.DateFormat;
/**
* Global variables which are available in any context.
*/
public class GlobalVariables {
/**
* The cursor variable determines the cursor placement after template edition.
*/
static class Cursor extends SimpleTemplateVariable {
public Cursor() {
super("cursor", TemplateMessages.getString("GlobalVariables.variable.description.cursor")); //$NON-NLS-1$ //$NON-NLS-2$
setEvaluationString(""); //$NON-NLS-1$
setResolved(true);
}
}
/**
* The dollar variable inserts an escaped dollar symbol.
*/
static class Dollar extends SimpleTemplateVariable {
public Dollar() {
super("dollar", TemplateMessages.getString("GlobalVariables.variable.description.dollar")); //$NON-NLS-1$ //$NON-NLS-2$
setEvaluationString("$"); //$NON-NLS-1$
setResolved(true);
}
}
/**
* The date variable evaluates to the current date.
*/
static class Date extends SimpleTemplateVariable {
public Date() {
super("date", TemplateMessages.getString("GlobalVariables.variable.description.date")); //$NON-NLS-1$ //$NON-NLS-2$
setResolved(true);
}
public String evaluate(TemplateContext context) {
return DateFormat.getDateInstance().format(new java.util.Date());
}
}
/**
* The time variable evaluates to the current time.
*/
static class Time extends SimpleTemplateVariable {
public Time() {
super("time", TemplateMessages.getString("GlobalVariables.variable.description.time")); //$NON-NLS-1$ //$NON-NLS-2$
setResolved(true);
}
public String evaluate(TemplateContext context) {
return DateFormat.getTimeInstance().format(new java.util.Date());
}
}
/**
* The user variable evaluates to the current user.
*/
static class User extends SimpleTemplateVariable {
public User() {
super("user", TemplateMessages.getString("GlobalVariables.variable.description.user")); //$NON-NLS-1$ //$NON-NLS-2$
setResolved(true);
}
public String evaluate(TemplateContext context) {
return System.getProperty("user.name"); //$NON-NLS-1$
}
}
}

View file

@ -1,17 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.corext.template.c;
public interface ICompilationUnit {
}

View file

@ -5,18 +5,20 @@ package org.eclipse.cdt.internal.corext.template.c;
* All Rights Reserved. * All Rights Reserved.
*/ */
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.corext.template.ContextType; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.corext.template.DocumentTemplateContext; import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.templates.DocumentTemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
/** /**
* A compilation unit context. * A compilation unit context.
*/ */
public abstract class CompilationUnitContext extends DocumentTemplateContext { public abstract class TranslationUnitContext extends DocumentTemplateContext {
/** The compilation unit, may be <code>null</code>. */ /** The compilation unit, may be <code>null</code>. */
private final ICompilationUnit fCompilationUnit; private final ITranslationUnit fTranslationUnit;
/** /**
* Creates a compilation unit context. * Creates a compilation unit context.
@ -26,18 +28,18 @@ public abstract class CompilationUnitContext extends DocumentTemplateContext {
* @param completionPosition the completion position within the document. * @param completionPosition the completion position within the document.
* @param compilationUnit the compilation unit (may be <code>null</code>). * @param compilationUnit the compilation unit (may be <code>null</code>).
*/ */
protected CompilationUnitContext(ContextType type, String string, int completionPosition, protected TranslationUnitContext(TemplateContextType type, IDocument document, int completionOffset,
ICompilationUnit compilationUnit) int completionLength, ITranslationUnit translationUnit)
{ {
super(type, string, completionPosition); super(type, document, completionOffset, completionLength);
fCompilationUnit= compilationUnit; fTranslationUnit= translationUnit;
} }
/** /**
* Returns the compilation unit if one is associated with this context, <code>null</code> otherwise. * Returns the compilation unit if one is associated with this context, <code>null</code> otherwise.
*/ */
public final ICompilationUnit getCompilationUnit() { public final ITranslationUnit getTranslationUnit() {
return fCompilationUnit; return fTranslationUnit;
} }
/** /**
@ -45,21 +47,20 @@ public abstract class CompilationUnitContext extends DocumentTemplateContext {
* if no enclosing element of that type exists. * if no enclosing element of that type exists.
*/ */
public ICElement findEnclosingElement(int elementType) { public ICElement findEnclosingElement(int elementType) {
if (fCompilationUnit == null) if (fTranslationUnit == null)
return null; return null;
/* try { try {
ICElement element= fCompilationUnit.getElementAt(getStart()); ICElement element= fTranslationUnit.getElementAtOffset(getStart());
while (element != null && element.getElementType() != elementType) while (element != null && element.getElementType() != elementType)
element= element.getParent(); element= element.getParent();
return element; return element;
} catch (JavaModelException e) { } catch (CModelException e) {
return null;
} */
return null; return null;
} }
}
} }

View file

@ -1,19 +1,21 @@
package org.eclipse.cdt.internal.corext.template.c; package org.eclipse.cdt.internal.corext.template.c;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.templates.TemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.TemplateVariableResolver;
/* /*
* (c) Copyright IBM Corp. 2000, 2001. * (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved. * All Rights Reserved.
*/ */
import org.eclipse.cdt.internal.corext.template.ContextType;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
import org.eclipse.cdt.internal.corext.template.TemplateVariable;
/** /**
* Compilation unit context type. * Compilation unit context type.
*/ */
public abstract class CompilationUnitContextType extends ContextType { public abstract class TranslationUnitContextType extends TemplateContextType {
/** the document string */ /** the document string */
protected String fString; protected String fString;
@ -22,14 +24,14 @@ public abstract class CompilationUnitContextType extends ContextType {
protected int fPosition; protected int fPosition;
/** the associated compilation unit, may be <code>null</code> */ /** the associated compilation unit, may be <code>null</code> */
protected ICompilationUnit fCompilationUnit; protected ITranslationUnit fTranslationUnit;
protected static class ReturnType extends TemplateVariable { protected static class ReturnType extends TemplateVariableResolver {
public ReturnType() { public ReturnType() {
super("return_type", TemplateMessages.getString("JavaContextType.variable.description.return.type")); //$NON-NLS-1$ //$NON-NLS-2$ super("return_type", TemplateMessages.getString("JavaContextType.variable.description.return.type")); //$NON-NLS-1$ //$NON-NLS-2$
} }
public String evaluate(TemplateContext context) { public String evaluate(TemplateContext context) {
/* IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD); /* IJavaElement element= ((TranslationUnitContext) context).findEnclosingElement(IJavaElement.METHOD);
if (element == null) if (element == null)
return null; return null;
@ -45,12 +47,12 @@ public abstract class CompilationUnitContextType extends ContextType {
} }
} }
protected static class File extends TemplateVariable { protected static class File extends TemplateVariableResolver {
public File() { public File() {
super("file", TemplateMessages.getString("JavaContextType.variable.description.file")); //$NON-NLS-1$ //$NON-NLS-2$ super("file", TemplateMessages.getString("JavaContextType.variable.description.file")); //$NON-NLS-1$ //$NON-NLS-2$
} }
public String evaluate(TemplateContext context) { public String evaluate(TemplateContext context) {
//ICompilationUnit unit= ((CompilationUnitContext) context).getCompilationUnit(); //ICompilationUnit unit= ((TranslationUnitContext) context).getCompilationUnit();
//return (unit == null) ? null : unit.getElementName(); //return (unit == null) ? null : unit.getElementName();
return null; return null;
@ -60,7 +62,7 @@ public abstract class CompilationUnitContextType extends ContextType {
} }
} }
protected static class EnclosingJavaElement extends TemplateVariable { protected static class EnclosingJavaElement extends TemplateVariableResolver {
protected final int fElementType; protected final int fElementType;
public EnclosingJavaElement(String name, String description, int elementType) { public EnclosingJavaElement(String name, String description, int elementType) {
@ -68,7 +70,7 @@ public abstract class CompilationUnitContextType extends ContextType {
fElementType= elementType; fElementType= elementType;
} }
public String evaluate(TemplateContext context) { public String evaluate(TemplateContext context) {
/*IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(fElementType); /*IJavaElement element= ((TranslationUnitContext) context).findEnclosingElement(fElementType);
return (element == null) ? null : element.getElementName(); */ return (element == null) ? null : element.getElementName(); */
return null; return null;
} }
@ -118,12 +120,12 @@ public abstract class CompilationUnitContextType extends ContextType {
} }
} }
*/ */
protected static class Arguments extends TemplateVariable { protected static class Arguments extends TemplateVariableResolver {
public Arguments() { public Arguments() {
super("enclosing_method_arguments", TemplateMessages.getString("JavaContextType.variable.description.enclosing.method.arguments")); //$NON-NLS-1$ //$NON-NLS-2$ super("enclosing_method_arguments", TemplateMessages.getString("JavaContextType.variable.description.enclosing.method.arguments")); //$NON-NLS-1$ //$NON-NLS-2$
} }
public String evaluate(TemplateContext context) { public String evaluate(TemplateContext context) {
/*IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD); /*IJavaElement element= ((TranslationUnitContext) context).findEnclosingElement(IJavaElement.METHOD);
if (element == null) if (element == null)
return null; return null;
@ -151,7 +153,7 @@ public abstract class CompilationUnitContextType extends ContextType {
/* /*
protected static class Line extends TemplateVariable { protected static class Line extends TemplateVariable {
public Line() { public Line() {
super("line", TemplateMessages.getString("CompilationUnitContextType.variable.description.line")); super("line", TemplateMessages.getString("TranslationUnitContextType.variable.description.line"));
} }
public String evaluate(TemplateContext context) { public String evaluate(TemplateContext context) {
return ((JavaTemplateContext) context).guessLineNumber(); return ((JavaTemplateContext) context).guessLineNumber();
@ -162,19 +164,21 @@ public abstract class CompilationUnitContextType extends ContextType {
/* /*
* @see ContextType#ContextType(String) * @see ContextType#ContextType(String)
*/ */
public CompilationUnitContextType(String name) { public TranslationUnitContextType() {
super(name); super();
} }
/** /**
* Sets context parameters. Needs to be called before createContext(). * Sets context parameters. Needs to be called before createContext().
*/ */
public void setContextParameters(String string, int position, ICompilationUnit compilationUnit) { public void setContextParameters(String string, int position, ITranslationUnit translationUnit) {
fString= string; fString= string;
fPosition= position; fPosition= position;
fCompilationUnit= compilationUnit; fTranslationUnit= translationUnit;
} }
public abstract TranslationUnitContext createContext(IDocument document, int offset, int length, ITranslationUnit translationUnit);
} }

View file

@ -1,128 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
(c) Copyright IBM Corp. 2000, 2001. 2004
All Rights Reserved.
-->
<!-- NOTE TO TRANSLATOR:
* Only these ENTITY strings listed in the DOCTYPE definition
* are to be translated. The rest of this file should remain
* English as it produces compilable code.
-->
<!DOCTYPE document [
<!ENTITY withtempvar "with temporary variable">
<!ENTITY statement "statement">
<!-- block is a noun -->
<!ENTITY block "block">
<!ENTITY method "method">
<!ENTITY declaration "declaration">
<!ENTITY usinganamespace "using a namespace">
<!ENTITY statement "statement">
<!ENTITY createnewobject "create new object">
<!ENTITY defaultmultilinecomment "default multiline comment">
<!ENTITY printtostdout "print to standard output">
<!ENTITY printtostderr "print to standard error">
<!ENTITY authorname "author name">
<!ENTITY commentText "To change this generated comment edit the template variable &quot;comment&quot;:
* Window&gt;Preferences&gt;C&gt;Templates.">
]>
<templates><template name="for" description="for loop" context="C Function" enabled="true">
for (${var} = 0; ${var} &lt; ${max}; ++${var}) {
${cursor}
}
</template>
<template name="for" description="for loop &withtempvar;" context="C Function" enabled="true">
for (int ${var} = 0; ${var} &lt; ${max}; ++${var}) {
${cursor}
}
</template>
<template name="do" description="do while &statement;" context="C Function" enabled="true">
do {
${cursor}
} while (${condition});
</template>
<template name="switch" description="switch case &statement;" context="C Function" enabled="true">
switch (${key}) {
case ${value}:
${cursor}
break;
default:
break;
}
</template>
<template name="if" description="if &statement;" context="C Function" enabled="true">
if (${condition}) {
${cursor}
}
</template>
<template name="ifelse" description="if else &statement;" context="C Function" enabled="true">
if (${condition}) {
${cursor}
} else {
}
</template>
<template name="elseif" description="else if &block;" context="C Function" enabled="true">
else if (${condition}) {
${cursor}
}
</template>
<template name="else" description="else &block;" context="C Function" enabled="true">
else {
${cursor}
}
</template>
<template name="try" description="try catch &block;" context="C++ Function" enabled="true">
try {
${cursor}
} catch (${Exception} e) {
}
</template>
<template name="catch" description="catch &block;" context="C++ Function" enabled="true">
catch (${Exception} e) {
${cursor}
}
</template>
<template name="main" description="main &method;" context="C Global" enabled="true">
int
main(int argc, char **argv) {
${cursor}
}
</template>
<template name="class" description="class &declaration;" context="C++ Global" enabled="true">
class ${name} {
${cursor}
private:
};
</template>
<template name="using" description="&usinganamespace;" context="C++ Global" enabled="true">
using namespace ${namespace};
</template>
<template name="namespace" description="namespace &declaration;" context="C++ Global" enabled="true">
namespace ${namespace} {
${cursor}
}
</template>
<template name="new" description="&createnewobject;" context="C++ Function" enabled="true">${type} ${name} = new ${type}(${arguments});</template><template name="comment" description="&defaultmultilinecomment;" context="C Global" enabled="true">
/*
* author ${user}
*
* &commentText;
*/
</template>
<template name="stdout" description="&printtostdout;" context="C Function" enabled="true">
printf(${cursor});
</template>
<template name="stderr" description="&printtostderr;" context="C Function" enabled="true">
fprintf(stderr, ${cursor});
</template>
<template name="author" description="&authorname;" context="C Global" enabled="true">
author ${user}
</template>
</templates>

View file

@ -1,146 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
/**
* A text edit that moves text inside a text buffer.
*/
public final class MoveTextEdit extends TextEdit {
/* package */ static class TargetMark extends NopTextEdit {
private MoveTextEdit fMoveTextEdit;
public TargetMark(TextRange range, MoveTextEdit edit) {
super(range);
fMoveTextEdit= edit;
}
/* package */ MoveTextEdit getMoveTextEdit() {
return fMoveTextEdit;
}
public TextEdit perform(TextBuffer buffer) throws CoreException {
fMoveTextEdit.internalPerform(buffer);
return super.perform(buffer);
}
public TextEdit copy() {
Assert.isTrue(false, "This should never happen"); //$NON-NLS-1$
return super.copy();
}
}
private TextRange fTarget;
private TextRange fSource;
private int fPerformCounter;
/**
* Creates a new <code>MoveTextEdit</code>. The text edit doesn't support
* overlapping moves. So for a <code>MoveTextEdit</code> <code>destination &lt;= offset &&
* offset + length - 1 &lt;= destination</code> must be <code>true</code>.
*
* @param offset the offset of the text to be moved
* @param length the text length to be moved
* @param destination the destination offset
*/
public MoveTextEdit(int offset, int length, int destination) {
Assert.isTrue(destination <= offset || offset + length <= destination);
fSource= new TextRange(offset, length);
fTarget= new TextRange(destination);
}
/**
* Creates a new <code>MoveTextEdit</code> with the given source and target range.
*
* @param source the source
* @param target the target
*/
private MoveTextEdit(TextRange source,TextRange target) {
fSource= source;
fTarget= target;
}
/**
* Returns the move text edit's source range. This method returns the same range
* as <code>TextEdit#getTextRange()</code>
*
* @return the edit's source range
*/
public TextRange getSourceRange() {
return fSource;
}
/**
* Returns the move text edit's target range.
*
* @return the edit's target range
*/
public TextRange getTargetRange() {
return fTarget;
}
/* non Java-doc
* @see TextEdit#getTextRange()
*/
public TextRange getTextRange() {
return fSource;
}
/* non Java-doc
* @see TextEdit#connect(TextBufferEditor)
*/
public void connect(TextBufferEditor editor) throws CoreException {
editor.add(new TargetMark(fTarget, this));
}
/* non Java-doc
* @see TextEdit#perform(TextBuffer)
*/
public TextEdit perform(TextBuffer buffer) throws CoreException {
internalPerform(buffer);
return new MoveTextEdit(fTarget, fSource);
}
/* non Java-doc
* @see TextEdit#copy()
*/
public TextEdit copy() {
TextRange source= getSourceRange();
TextRange target= getTargetRange();
return new MoveTextEdit(source.fOffset, source.fLength, target.fOffset);
}
//---- Helper method ---------------------------------------------------------------------------------
protected void internalPerform(TextBuffer buffer) throws CoreException {
Assert.isTrue(fPerformCounter < 2);
if (++fPerformCounter == 2) {
TextRange source= getSourceRange();
TextRange target= getTargetRange();
String current= buffer.getContent(source.fOffset, source.fLength);
buffer.replace(source, ""); //$NON-NLS-1$
buffer.replace(target, current);
}
}
/* package */ boolean isUpMove() {
return fSource.fOffset < fTarget.fOffset;
}
/* package */ boolean isDownMove() {
return fSource.fOffset > fTarget.fOffset;
}
/* package */ TextRange getChildRange() {
int offset= fSource.fOffset;
int length= fSource.fLength;
int destination= fTarget.fOffset;
if (destination <= offset)
return new TextRange(destination, offset + length - destination);
else
return new TextRange(offset, destination - offset);
}
}

View file

@ -1,136 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.internal.utils.Assert;
import org.eclipse.core.runtime.CoreException;
public class MultiTextEdit {
private List fChildren;
/**
* Creates a new composite text edit.
*/
public MultiTextEdit() {
fChildren= new ArrayList(3);
}
protected MultiTextEdit(List children) throws CoreException {
fChildren= new ArrayList(children.size());
for (Iterator iter= children.iterator(); iter.hasNext();) {
fChildren.add(((TextEdit)iter.next()).copy());
}
}
protected List getChildren() {
return fChildren;
}
/**
* Adds all <code>TextEdits</code> managed by the given multt text edit.
*
* @param edit the multi text edit to be added.
*/
public void add(MultiTextEdit edit) {
Assert.isNotNull(edit);
fChildren.add(edit);
}
/**
* Adds a text edit.
*
* @param edit the text edit to be added
*/
public void add(TextEdit edit) {
Assert.isNotNull(edit);
fChildren.add(edit);
}
/**
* Returns the children managed by this text edit collection.
*
* @return the children of this composite text edit
*/
public Iterator iterator() {
return fChildren.iterator();
}
/**
* Connects this text edit to the given <code>TextBufferEditor</code>.
* Note that this method <b>should only be called</b> by a <code>
* TextBufferEditor</code>.
*<p>
* This default implementation does nothing. Subclasses may override
* if needed.
*
* @param editor the text buffer editor this text edit has been added to
*/
public void connect(TextBufferEditor editor) throws CoreException {
for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
Object element= iter.next();
if (element instanceof TextEdit)
editor.add((TextEdit)element);
else
editor.add((MultiTextEdit)element);
}
}
/**
* Creates and returns a copy of this text edit collection. The copy method should
* be implemented in a way so that the copy can be added to a different <code>
* TextBuffer</code> without causing any harm to the object from which the copy
* has been created.
*
* @return a copy of this object.
*/
public MultiTextEdit copy() throws CoreException {
return new MultiTextEdit(fChildren);
}
/**
* Returns the <code>TextRange</code> that this text edit is going to
* manipulate. If this method is called before the <code>MultiTextEdit</code>
* has been added to a <code>TextBufferEditor</code> it may return <code>
* null</code> to indicate this situation.
*
* @return the <code>TextRange</code>s this <code>TextEdit is going
* to manipulate
*/
public TextRange getTextRange() {
int size= fChildren.size();
if (size == 0)
return new TextRange(0,0);
TextRange range= ((TextEdit)fChildren.get(0)).getTextRange();
int start= range.getOffset();
int end= range.getInclusiveEnd();
for (int i= 1; i < size; i++) {
range= ((TextEdit)fChildren.get(i)).getTextRange();
start= Math.min(start, range.getOffset());
end= Math.max(end, range.getInclusiveEnd());
}
return new TextRange(start, end - start + 1);
}
/**
* Returns the element modified by this text edit. The method
* may return <code>null</code> if the modification isn't related to a
* element or if the content of the modified text buffer doesn't
* follow any syntax.
* <p>
* This default implementation returns <code>null</code>
*
* @return the element modified by this text edit
*/
public Object getModifiedElement() {
return null;
}
}

View file

@ -1,61 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
/**
* A text edit that does nothing. A <code>NopTextEdit</code> can be used to track
* positions when executing <code>TextEdits</code> associated with a <code>
* TextBufferEditor</code>.
*/
public class NopTextEdit extends TextEdit {
private TextRange fTextRange;
/**
* Creates a new <code>NopTextEdit</code> for the given
* offset and length.
*
* @param offset the starting offset this text edit is "working on"
* @param length the length this text edit is "working on"
*/
public NopTextEdit(int offset, int length) {
this(new TextRange(offset, length));
}
/**
* Creates a new <code>NopTextEdit</code> for the given
* range.
*
* @param range the <code>TextRange</code> this text edit is "working on"
*/
public NopTextEdit(TextRange range) {
fTextRange= range;
}
/* non Java-doc
* @see TextEdit#getTextRange
*/
public TextRange getTextRange() {
return fTextRange;
}
/* non Java-doc
* @see TextEdit#perform
*/
public TextEdit perform(TextBuffer buffer) throws CoreException {
return new NopTextEdit(fTextRange);
}
/* non Java-doc
* @see TextEdit#perform
*/
public TextEdit copy() {
return new NopTextEdit(fTextRange.copy());
}
}

View file

@ -1,106 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
public abstract class SimpleTextEdit extends TextEdit {
private TextRange fRange;
private String fText;
public static SimpleTextEdit createReplace(int offset, int length, String text) {
return new SimpleTextEditImpl(offset, length, text);
}
public static SimpleTextEdit createInsert(int offset, String text) {
return new SimpleTextEditImpl(offset, 0, text);
}
public static SimpleTextEdit createDelete(int offset, int length) {
return new SimpleTextEditImpl(offset, length, ""); //$NON-NLS-1$
}
private final static class SimpleTextEditImpl extends SimpleTextEdit {
protected SimpleTextEditImpl(TextRange range, String text) {
super(range, text);
}
protected SimpleTextEditImpl(int offset, int length, String text) {
super(offset, length, text);
}
public TextEdit copy() {
return new SimpleTextEditImpl(getTextRange().copy(), getText());
}
}
protected SimpleTextEdit() {
this(TextRange.UNDEFINED, ""); //$NON-NLS-1$
}
protected SimpleTextEdit(int offset, int length, String text) {
this(new TextRange(offset, length), text);
}
protected SimpleTextEdit(TextRange range, String text) {
Assert.isNotNull(range);
Assert.isNotNull(text);
fRange= range;
fText= text;
}
/**
* Returns the text edit's text
*
* @return the text edit's text
*/
public String getText() {
return fText;
}
/**
* Sets the text edit's text
* <p>
* This method should only be called from within the <code>
* connect</code> method.
*
* @param text the text edit's text
*/
protected final void setText(String text) {
fText= text;
Assert.isNotNull(fText);
}
/**
* Sets the text edit's range.
* <p>
* This method should only be called from within the <code>
* connect</code> method.
*
* @param range the text edit's range.
*/
protected void setTextRange(TextRange range) {
fRange= range;
Assert.isNotNull(fRange);
}
/* non Java-doc
* @see TextEdit#getTextRange
*/
public TextRange getTextRange() {
return fRange;
}
/* non Java-doc
* @see TextEdit#doPerform
*/
public final TextEdit perform(TextBuffer buffer) throws CoreException {
String current= buffer.getContent(fRange.fOffset, fRange.fLength);
buffer.replace(fRange, fText);
return new SimpleTextEditImpl(fRange, current);
}
}

View file

@ -1,25 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
/**
* A <code>SwapTextEdit</code> exchanges to text ranges.
*/
public class SwapTextEdit extends MultiTextEdit {
/**
* Create a new <code>SwapTextEdit</code>
*
* @param offset1 the offset of the first text range
* @param length1 the length of the first text range
* @param offset2 the offset of the second text range
* @param length2 the length of the second text range
*/
public SwapTextEdit(int offset1, int length1, int offset2, int length2) {
add(new MoveTextEdit(offset1, length1, offset2));
add(new MoveTextEdit(offset2, length2, offset1));
}
}

View file

@ -1,217 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.cdt.internal.corext.textmanipulation.TextEditNode.RootNode;
import org.eclipse.cdt.internal.ui.CStatusConstants;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.util.Assert;
/**
* A <code>TextBufferEditor</code> manages a set of <code>TextEdit</code>s and applies
* them as a whole to a <code>TextBuffer</code>. Added <code>TextEdit</code>s must
* not overlap. The only exception from this rule are insertion point. There can be more than
* one insert point at the same text position. Clients should use the method <code>
* canPerformEdits</code> to validate if all added text edits follow these rules.
* <p>
* Clients can attach more than one <code>TextBufferEditor</code> to a single <code>
* TextBuffer</code>. If so <code>canPerformEdits</code> validates all text edits from
* all text buffer editors working on the same text buffer.
*/
public class TextBufferEditor {
private TextBuffer fBuffer;
private List fEdits;
private RootNode fRootNode;
private int fNumberOfNodes;
private int fConnectCount;
private int fMode;
/* package */ static final int UNDEFINED= 0;
/* package */ static final int REDO= 1;
/* package */ static final int UNDO= 2;
/**
* Creates a new <code>TextBufferEditor</code> for the given
* <code>TextBuffer</code>.
*
* @param the text buffer this editor is working on.
*/
public TextBufferEditor(TextBuffer buffer) {
fBuffer= buffer;
Assert.isNotNull(fBuffer);
fEdits= new ArrayList();
}
/**
* Returns the text buffer this editor is working on.
*
* @return the text buffer this editor is working on
*/
public TextBuffer getTextBuffer() {
return fBuffer;
}
/**
* Adds a <code>TextEdit</code> to this text editor. Adding a <code>TextEdit</code>
* to a <code>TextBufferEditor</code> transfers ownership of the edit to the editor. So
* after a edit has been added to a editor the creator of that edit <b>must</b> not continue
* modifing it.
*
* @param edit the text edit to be added
* @exception CoreException if the text edit can not be added
* to this text buffer editor
*/
public void add(TextEdit edit) throws CoreException {
Assert.isTrue(fMode == UNDEFINED || fMode == REDO);
internalAdd(edit);
fMode= REDO;
}
/**
* Adds a <code>MultiTextEdit</code> to this text editor. Adding a <code>MultiTextEdit</code>
* to a <code>TextBufferEditor</code> transfers ownership of the edit to the editor. So
* after a edit has been added to a editor the creator of that edit <b>must</b> not continue
* modifing it.
*
* @param edit the multi text edit to be added
* @exception CoreException if the multi text edit can not be added
* to this text buffer editor
*/
public void add(MultiTextEdit edit) throws CoreException {
Assert.isTrue(fMode == UNDEFINED || fMode == REDO);
edit.connect(this);
fMode= REDO;
}
/**
* Adds a <code>UndoMemento</code> to this text editor. Adding a <code>UndoMemento</code>
* to a <code>TextBufferEditor</code> transfers ownership of the memento to the editor. So
* after a memento has been added to a editor the creator of that memento <b>must</b> not continue
* modifing it.
*
* @param undo the undo memento to be added
* @exception CoreException if the undo memento can not be added
* to this text buffer editor
*/
public void add(UndoMemento undo) throws CoreException {
Assert.isTrue(fMode == UNDEFINED);
List list= undo.fEdits;
// Add them reverse since we are adding undos.
for (int i= list.size() - 1; i >= 0; i--) {
internalAdd((TextEdit)list.get(i));
}
fMode= undo.fMode;
}
/**
* Checks if the <code>TextEdit</code> added to this text editor can be executed.
*
* @return <code>true</code> if the edits can be executed. Return <code>false
* </code>otherwise. One major reason why text edits cannot be executed
* is a wrong offset or length value of a <code>TextEdit</code>.
*/
public boolean canPerformEdits() {
if (fRootNode != null)
return true;
fRootNode= buildTree();
if (fRootNode == null)
return false;
if (fRootNode.validate(fBuffer.getLength()))
return true;
fRootNode= null;
return false;
}
/**
* Clears the text buffer editor.
*/
public void clear() {
fRootNode= null;
fMode= UNDEFINED;
fEdits.clear();
}
/**
* Executes the text edits added to this text buffer editor and clears all added
* text edits.
*
* @param pm a progress monitor to report progress
* @return an object representing the undo of the executed <code>TextEdit</code>s
* @exception CoreException if the edits cannot be executed
*/
public UndoMemento performEdits(IProgressMonitor pm) throws CoreException {
if (pm == null)
pm= new NullProgressMonitor();
int size= fEdits.size();
if (size == 0)
return new UndoMemento(fMode == UNDO ? REDO : UNDO);
if (fRootNode == null) {
fRootNode= buildTree();
if (fRootNode == null || !fRootNode.validate(fBuffer.getLength())) {
IStatus s= new Status(IStatus.ERROR, CUIPlugin.PLUGIN_ID, CStatusConstants.INTERNAL_ERROR,
TextManipulationMessages.getString("TextBufferEditor.rootNodeEmpty"), null); //$NON-NLS-1$
throw new CoreException(s);
}
}
try {
pm.beginTask("", fNumberOfNodes + 10); //$NON-NLS-1$
UndoMemento undo= null;
if (fMode == REDO) {
undo= fRootNode.performDo(fBuffer, pm);
fRootNode.performedDo();
} else {
undo= fRootNode.performUndo(fBuffer, pm);
fRootNode.performedUndo();
}
pm.worked(10);
return undo;
} finally {
pm.done();
clear();
}
}
//---- Helper methods ------------------------------------------------------------
private RootNode buildTree() {
TextEditNode[] nodes= new TextEditNode[fEdits.size()];
for (int i= fEdits.size() - 1; i >= 0; i--) {
nodes[i]= TextEditNode.create((TextEdit)fEdits.get(i));
}
fNumberOfNodes= nodes.length;
Arrays.sort(nodes, new TextEditNodeComparator());
RootNode root= new RootNode(fBuffer.getLength());
for (int i= 0; i < nodes.length; i++) {
root.add(nodes[i]);
}
return root;
}
private void internalAdd(TextEdit edit) throws CoreException {
edit.index= fEdits.size();
edit.isSynthetic= fConnectCount > 0;
try {
fConnectCount++;
edit.connect(this);
} finally {
fConnectCount--;
}
fEdits.add(edit);
}
}

View file

@ -1,106 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
/**
* A text edit describes an elementary text manipulation operation. Text edits
* are executed by adding them to a <code>TextBufferEditor</code> and then
* calling <code>perform</code> on the <code>TextBufferEditor</code>.
* <p>
* After a <code>TextEdit</code> has been added to a <code>TextBufferEditor</code>
* the method <code>connect</code> is sent to the text edit. A <code>TextEdit</code>
* is allowed to do some adjustments of the text range it is going to manipulate while inside
* the hook <code>connect</code>.
*
* @see TextBufferEditor
*/
public abstract class TextEdit {
// index that determines the insertion order into a text buffer
/* package */ int index;
/* package */ boolean isSynthetic;
/**
* Connects this text edit to the given <code>TextBufferEditor</code>. A text edit
* must not keep a reference to the passed text buffer editor. It is guaranteed that
* the buffer passed to <code>perform<code> is equal to the buffer managed by
* the given text buffer editor. But they don't have to be identical.
* <p>
* Note that this method <b>should only be called</b> by a <code>
* TextBufferEditor</code>.
*<p>
* This default implementation does nothing. Subclasses may override
* if needed.
*
* @param editor the text buffer editor this text edit has been added to
*/
public void connect(TextBufferEditor editor) throws CoreException {
// does nothing
}
/**
* Returns the <code>TextRange</code> that this text edit is going to
* manipulate. If this method is called before the <code>TextEdit</code>
* has been added to a <code>TextBufferEditor</code> it may return <code>
* null</code> or <code>TextRange.UNDEFINED</code> to indicate this situation.
*
* @return the <code>TextRange</code>s this <code>TextEdit is going
* to manipulate
*/
public abstract TextRange getTextRange();
/**
* Performs the text edit. Note that this method <b>should only be called</b>
* by a <code>TextBufferEditor</code>.
*
* @param buffer the actual buffer to manipulate
* @return a text edit that can undo this text edit
*/
public abstract TextEdit perform(TextBuffer buffer) throws CoreException;
/**
* This method gets called after all <code>TextEdit</code>s added to a text buffer
* editor are executed. Implementors of this method can do some clean-up or can
* release allocated resources that are now longer needed.
* <p>
* This default implementation does nothing.
*/
public void performed() {
// do nothing
}
/**
* Creates and returns a copy of this object. The copy method should
* be implemented in a way so that the copy can be added to a different
* <code>TextBufferEditor</code> without causing any harm to the object
* from which the copy has been created.
*
* @return a copy of this object.
*/
public abstract TextEdit copy() throws CoreException;
/**
* Returns the element modified by this text edit. The method
* may return <code>null</code> if the modification isn't related to a
* element or if the content of the modified text buffer doesn't
* follow any syntax.
* <p>
* This default implementation returns <code>null</code>
*
* @return the element modified by this text edit
*/
public Object getModifiedElement() {
return null;
}
/** @deprecated reimplement getModifiedElement */
public final Object getModifiedLanguageElement() {
return null;
}
}

View file

@ -1,496 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.util.Assert;
/**
* A helper class to arrange <code>TextEdit</code>s into a tree to optimize their
* execution.
*/
/* package */ abstract class TextEditNode {
/* package */ TextEditNode fParent;
/* package */ List fChildren;
/* package */ TextEdit fEdit;
/* package */ static class DefaultNode extends TextEditNode {
public DefaultNode(TextEdit edit) {
super(edit);
}
}
/* package */ static class RootNode extends TextEditNode {
private int fUndoIndex;
public RootNode(int length) {
super(new NopTextEdit(new TextRange(0, length)));
fEdit.isSynthetic= true;
}
public boolean covers(TextEditNode node) {
return true;
}
public UndoMemento performDo(TextBuffer buffer, IProgressMonitor pm) throws CoreException {
DoRangeUpdater updater= new DoRangeUpdater();
UndoMemento undo= new UndoMemento(TextBufferEditor.UNDO);
try {
buffer.registerUpdater(updater);
performDo(buffer, updater, undo, pm);
} finally {
buffer.unregisterUpdater(updater);
updater.setActiveNode(null);
}
return undo;
}
public UndoMemento performUndo(TextBuffer buffer, IProgressMonitor pm) throws CoreException {
UndoRangeUpdater updater= new UndoRangeUpdater(this);
UndoMemento undo= new UndoMemento(TextBufferEditor.REDO);
try {
buffer.registerUpdater(updater);
performUndo(buffer, updater, undo, pm);
} finally {
buffer.unregisterUpdater(updater);
updater.setActiveNode(null);
}
return undo;
}
protected void setUndoIndex(int index) {
fUndoIndex= index;
}
protected int getUndoIndex() {
return fUndoIndex;
}
}
/* package */ abstract static class AbstractMoveNode extends TextEditNode {
private int state;
private int fTargetIndex;
private int fSourceIndex;
private List fAffectedChildren;
public AbstractMoveNode(TextEdit edit) {
super(edit);
reset();
}
protected abstract TextRange getSourceRange();
protected abstract TextRange getTargetRange();
protected abstract boolean isUpMove();
protected boolean isDownMove() {
return !isUpMove();
}
public boolean isMove() {
return true;
}
protected void checkRange(DocumentEvent event) {
TextRange range= getChildRange();
int eventOffset= event.getOffset();
int eventLength= event.getLength();
int eventEnd = eventOffset + eventLength - 1;
// "Edit changes text that lies outside its defined range"
Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= range.getInclusiveEnd());
}
protected boolean activeNodeChanged(int delta) {
TextRange targetRange= getTargetRange();
TextRange sourceRange= getSourceRange();
switch (state) {
case 0: // the move delete
init();
Assert.isTrue(Math.abs(delta) == sourceRange.fLength);
if (isUpMove()) {
updateOffset(fAffectedChildren, delta);
targetRange.fOffset+= delta;
}
sourceRange.fLength= 0;
state= 1;
break;
case 1:
TextEditNode target= (TextEditNode)fParent.fChildren.get(fTargetIndex);
TextEditNode source= (TextEditNode)fParent.fChildren.get(fSourceIndex);
updateOffset(source.fChildren, targetRange.fOffset - sourceRange.fOffset);
target.fChildren= source.fChildren;
if (target.fChildren != null) {
for (Iterator iter= target.fChildren.iterator(); iter.hasNext();) {
((TextEditNode)iter.next()).fParent= target;
}
}
source.fChildren= null;
if (isDownMove()) {
updateOffset(fAffectedChildren, delta);
sourceRange.fOffset+= delta;
}
targetRange.fLength= delta;
reset();
break;
}
return true;
}
private static void updateOffset(List nodes, int delta) {
if (nodes == null)
return;
for (int i= nodes.size() - 1; i >= 0; i--) {
TextEditNode node= (TextEditNode)nodes.get(i);
TextRange range= node.getTextRange();
range.fOffset+= delta;
updateOffset(node.fChildren, delta);
}
}
private void init() {
TextRange source= getSourceRange();
TextRange target= getTargetRange();
List children= fParent.fChildren;
for (int i= children.size() - 1; i >= 0; i--) {
TextEditNode child= (TextEditNode)children.get(i);
TextRange range= child.fEdit.getTextRange();
if (range == source)
fSourceIndex= i;
else if (range == target)
fTargetIndex= i;
}
int start= Math.min(fTargetIndex, fSourceIndex);
int end= Math.max(fTargetIndex, fSourceIndex);
fAffectedChildren= new ArrayList(3);
for (int i= start + 1; i < end; i++) {
fAffectedChildren.add(children.get(i));
}
}
private void reset() {
state= 0;
fSourceIndex= -1;
fTargetIndex= -1;
}
}
/* package */ static class MoveNode extends AbstractMoveNode {
public MoveNode(TextEdit edit) {
super(edit);
}
protected TextRange getChildRange() {
return ((MoveTextEdit)fEdit).getChildRange();
}
protected TextRange getSourceRange() {
return ((MoveTextEdit)fEdit).getSourceRange();
}
protected TextRange getTargetRange() {
return ((MoveTextEdit)fEdit).getTargetRange();
}
protected boolean isUpMove() {
return ((MoveTextEdit)fEdit).isUpMove();
}
public boolean isMovePartner(TextEditNode other) {
if (!(other instanceof TargetMarkNode))
return false;
return fEdit == ((MoveTextEdit.TargetMark)other.fEdit).getMoveTextEdit();
}
public boolean covers(TextEditNode node) {
if (node instanceof TargetMarkNode) {
MoveTextEdit.TargetMark edit= (MoveTextEdit.TargetMark)node.fEdit;
if (edit.getMoveTextEdit() == fEdit)
return false;
}
return getParentRange().covers(node.getChildRange());
}
}
/* package */ static class TargetMarkNode extends AbstractMoveNode {
public TargetMarkNode(TextEdit edit) {
super(edit);
}
protected TextRange getChildRange() {
return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getChildRange();
}
protected TextRange getSourceRange() {
return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getSourceRange();
}
protected TextRange getTargetRange() {
return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getTargetRange();
}
protected boolean isUpMove() {
return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().isUpMove();
}
public boolean isMovePartner(TextEditNode other) {
return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit() == other.fEdit;
}
}
//---- Range updating ---------------------------------------------------------------------------
private static abstract class RangeUpdater implements IDocumentListener {
protected TextEditNode fActiveNode;
public void documentAboutToBeChanged(DocumentEvent event) {
}
public void setActiveNode(TextEditNode node) {
fActiveNode= node;
}
public void updateParents(int delta) {
TextEditNode node= fActiveNode.fParent;
while (node != null) {
node.childNodeChanged(delta);
node= node.fParent;
}
}
public static int getDelta(DocumentEvent event) {
return (event.getText() == null ? 0 : event.getText().length()) - event.getLength();
}
}
private static class DoRangeUpdater extends RangeUpdater {
private List fProcessedNodes= new ArrayList(10);
public void setActiveNode(TextEditNode node) {
if (fActiveNode != null)
fProcessedNodes.add(fActiveNode);
super.setActiveNode(node);
}
public void documentChanged(DocumentEvent event) {
fActiveNode.checkRange(event);
int delta= getDelta(event);
if (!fActiveNode.activeNodeChanged(delta)) {
for (Iterator iter= fProcessedNodes.iterator(); iter.hasNext();) {
((TextEditNode)iter.next()).previousNodeChanged(delta);
}
}
updateParents(delta);
}
}
private static class UndoRangeUpdater extends RangeUpdater {
private RootNode fRootNode;
public UndoRangeUpdater(RootNode root) {
fRootNode= root;
}
public void setActiveNode(TextEditNode node) {
super.setActiveNode(node);
}
public void documentChanged(DocumentEvent event) {
fActiveNode.checkRange(event);
int delta= getDelta(event);
if (!fActiveNode.activeNodeChanged(delta)) {
int start= fRootNode.getUndoIndex() + 1;
List children= fRootNode.fChildren;
int size= children != null ? children.size() : 0;
for (int i= start; i < size; i++) {
updateUndo((TextEditNode)children.get(i), delta);
}
}
updateParents(delta);
}
private void updateUndo(TextEditNode node, int delta) {
node.previousNodeChanged(delta);
List children= node.fChildren;
int size= children != null ? children.size() : 0;
for (int i= 0; i < size; i++) {
updateUndo((TextEditNode)children.get(i), delta);
}
}
}
//---- Creating instances ---------------------------------------------------------------------------
static TextEditNode create(TextEdit edit) {
if (edit instanceof MoveTextEdit)
return new MoveNode(edit);
if (edit instanceof MoveTextEdit.TargetMark)
return new TargetMarkNode(edit);
return new DefaultNode(edit);
}
static RootNode createRoot(int length) {
return new RootNode(length);
}
protected TextEditNode(TextEdit edit) {
fEdit= edit;
}
//---- Adding children ---------------------------------------------------------------------------
protected void add(TextEditNode node) {
if (fChildren == null) {
fChildren= new ArrayList(1);
node.fParent= this;
fChildren.add(node);
return;
}
// Optimize using binary search
for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
TextEditNode child= (TextEditNode)iter.next();
if (child.covers(node)) {
child.add(node);
return;
}
}
for (int i= 0; i < fChildren.size(); ) {
TextEditNode child= (TextEditNode)fChildren.get(i);
if (node.covers(child)) {
fChildren.remove(i);
node.add(child);
} else {
i++;
}
}
node.fParent= this;
fChildren.add(node);
}
public boolean covers(TextEditNode node) {
return false;
}
//---- Accessing --------------------------------------------------------------------------------------
protected RootNode getRoot() {
TextEditNode candidate= this;
while(candidate.fParent != null)
candidate= candidate.fParent;
return (RootNode)candidate;
}
//---- Query interface --------------------------------------------------------------------------------
protected boolean isSynthetic() {
return fEdit.isSynthetic;
}
public boolean isMove() {
return false;
}
//---- Accessing Ranges ------------------------------------------------------------------------------
protected void checkRange(DocumentEvent event) {
TextRange range= getTextRange();
int eventOffset= event.getOffset();
int eventLength= event.getLength();
int eventEnd = eventOffset + eventLength - 1;
// "Edit changes text that lies outside its defined range"
Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= range.getInclusiveEnd());
}
protected TextRange getTextRange() {
return fEdit.getTextRange();
}
protected TextRange getChildRange() {
return getTextRange();
}
protected TextRange getParentRange() {
return getTextRange();
}
public boolean validate(int bufferLength) {
if (fChildren == null)
return true;
// Only Moves and Nops can be parents
if (!(fEdit instanceof MoveTextEdit || fEdit instanceof NopTextEdit))
return false;
TextRange lastRange= null;
for (Iterator iter= fChildren.iterator(); iter.hasNext(); ) {
TextEditNode node= (TextEditNode)iter.next();
if (!node.validate(bufferLength))
return false;
TextRange range= node.fEdit.getTextRange();
if (!range.isValid() || range.fOffset + range.fLength > bufferLength)
return false;
if (lastRange != null && !(range.isInsertionPointAt(lastRange.fOffset) || range.liesBehind(lastRange)))
return false;
lastRange= range;
}
return true;
}
//---- Updating ----------------------------------------------------------------------------------------
protected boolean activeNodeChanged(int delta) {
TextRange range= getTextRange();
range.fLength+= delta;
// we didn't adjust any processed nodes.
return false;
}
protected void previousNodeChanged(int delta) {
TextRange range= getTextRange();
range.fOffset+= delta;
}
protected void childNodeChanged(int delta) {
getTextRange().fLength+= delta;
}
//---- Do it ---------------------------------------------------------------------------------------------
protected void performDo(TextBuffer buffer, RangeUpdater updater, UndoMemento undo, IProgressMonitor pm) throws CoreException {
int size= fChildren != null ? fChildren.size() : 0;
for (int i= size - 1; i >= 0; i--) {
TextEditNode child= (TextEditNode)fChildren.get(i);
child.performDo(buffer, updater, undo, pm);
}
updater.setActiveNode(this);
if (isSynthetic())
fEdit.perform(buffer);
else
undo.add(fEdit.perform(buffer));
pm.worked(1);
}
public void performedDo() {
int size= fChildren != null ? fChildren.size() : 0;
for (int i= size - 1; i >= 0; i--) {
TextEditNode child= (TextEditNode)fChildren.get(i);
child.performedDo();
}
fEdit.performed();
}
//---- Undo it -------------------------------------------------------------------------------------------
protected void performUndo(TextBuffer buffer, RangeUpdater updater, UndoMemento undo, IProgressMonitor pm) throws CoreException {
int size= fChildren != null ? fChildren.size() : 0;
for (int i= 0; i < size; i++) {
setUndoIndex(i);
TextEditNode child= (TextEditNode)fChildren.get(i);
child.performUndo(buffer, updater, undo, pm);
}
updater.setActiveNode(this);
if (isSynthetic())
fEdit.perform(buffer);
else
undo.add(fEdit.perform(buffer));
pm.worked(1);
}
protected void setUndoIndex(int index) {
}
public void performedUndo() {
int size= fChildren != null ? fChildren.size() : 0;
for (int i= 0; i < size; i++) {
TextEditNode child= (TextEditNode)fChildren.get(i);
child.performedUndo();
}
fEdit.performed();
}
// protected void createUndoList(List list) {
// int size= fChildren != null ? fChildren.size() : 0;
// for (int i= 0; i < size; i++) {
// TextEditNode child= (TextEditNode)fChildren.get(i);
// child.createUndoList(list);
// }
// list.add(this);
// }
}

View file

@ -1,48 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.Comparator;
/**
* A special comparator to comapre <code>TextRange</code>s.
*/
class TextEditNodeComparator implements Comparator {
public int compare(Object o1, Object o2) {
TextEditNode node1= (TextEditNode)o1;
TextEditNode node2= (TextEditNode)o2;
TextRange pos1= node1.getTextRange();
TextRange pos2= node2.getTextRange();
int offset1= pos1.fOffset;
int offset2= pos2.fOffset;
if (offset1 < offset2)
return -1;
if (offset1 > offset2)
return 1;
// same offset
int length1= pos1.fLength;
int length2= pos2.fLength;
// insertion points come before anything else at the same position.
if (length1 == 0 && length2 != 0)
return -1;
if (length1 != 0 && length2 == 0)
return 1;
// Longer edits come before shorter edits
if (length1 < length2)
return 1;
if (length1 > length2)
return -1;
if (node1.fEdit.index < node2.fEdit.index)
return -1;
return 1;
}
}

View file

@ -1,147 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.util.Assert;
public class TextUtil {
/**
* Returns the length of the string desribed by <code>start</code> and
* <code>end</code>.
*
* @param start the start position. The position is inclusive
* @param end the end position. The position is inclusive
* @return the length of the string desribed by <code>start</code> and
* <code>end</code>
*/
public static int getLength(int start, int end) {
return end - start + 1;
}
/**
* Returns the indent of the given line.
* @param line the text line
* @param tabWidth the width of the '\t' character.
*/
public static int getIndent(String line, int tabWidth) {
int result= 0;
int blanks= 0;
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
switch (c) {
case '\t':
result++;
blanks= 0;
break;
case ' ':
blanks++;
if (blanks == tabWidth) {
result++;
blanks= 0;
}
break;
default:
return result;
}
}
return result;
}
/**
* Removes the given number of idents from the line and returns a new
* copy of the line. Asserts that the given line has the requested
* number of indents.
*/
public static String removeIndent(int numberOfIndents, String line, int tabWidth) {
if (numberOfIndents <= 0)
return new String(line);
int start= 0;
int indents= 0;
int blanks= 0;
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
switch (c) {
case '\t':
indents++;
blanks= 0;
break;
case ' ':
blanks++;
if (blanks == tabWidth) {
indents++;
blanks= 0;
}
break;
default:
Assert.isTrue(false, "Line does not have requested number of indents"); //$NON-NLS-1$
}
if (indents == numberOfIndents) {
start= i + 1;
break;
}
}
if (start == size)
return ""; //$NON-NLS-1$
else
return line.substring(start);
}
/**
* Removes any leading indents from the given string.
*/
public static String removeLeadingIndents(String line, int tabWidth) {
int indents= getIndent(line, tabWidth);
return removeIndent(indents, line, tabWidth);
}
/**
* Creates a string that consists of the given number of tab characters.
*/
public static String createIndentString(int indent) {
StringBuffer result= new StringBuffer();
for (int i= 0; i < indent; i++) {
result.append('\t');
}
return result.toString();
}
/**
* Removes any leading white spaces from the given string.
* The method returns a new string.
*/
public static String removeLeadingWhiteSpaces(String line) {
int size= line.length();
int start= 0;
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c != '\t' && c != ' ') {
start= i;
break;
}
}
return line.substring(start);
}
/**
* Returns <code>true</code> if the given string consists only of
* white spaces (e.g. space and '\t'). If the string is empty,
* <code>true</code> is returned.
*/
public static boolean containsOnlyWhiteSpaces(String line) {
int size= line.length();
for (int i= 0; i < size; i++) {
char c= line.charAt(i);
if (c != '\t' && c != ' ')
return false;
}
return true;
}
}

View file

@ -1,29 +0,0 @@
package org.eclipse.cdt.internal.corext.textmanipulation;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.List;
/**
* This class encapsulates the reverse change of a number of <code>TextEdit</code>s
* executed on a <code>TextBufferEditor</code>
*/
public final class UndoMemento {
/* package */ int fMode;
/* package */ List fEdits;
/* package */ UndoMemento(int mode) {
fMode= mode;
fEdits= new ArrayList(10);
}
/* package */ void add(TextEdit edit) {
fEdits.add(edit);
}
}

View file

@ -15,7 +15,9 @@ import java.util.Map;
import org.eclipse.cdt.core.ToolFactory; import org.eclipse.cdt.core.ToolFactory;
import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.core.formatter.CodeFormatter;
import org.eclipse.cdt.internal.corext.Assert; import org.eclipse.cdt.internal.corext.Assert;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.DefaultPositionUpdater;
@ -29,6 +31,13 @@ import org.eclipse.text.edits.TextEdit;
public class CodeFormatterUtil { public class CodeFormatterUtil {
// /**
// * Creates a string that represents the given number of indents (can be spaces or tabs..)
// */
// public static String createIndentString(int indent) {
// String str= format(CodeFormatter.K_EXPRESSION, "x", indent, null, "", (Map) null); //$NON-NLS-1$ //$NON-NLS-2$
// return str.substring(0, str.indexOf('x'));
// }
/** /**
* Evaluates the edit on the given string. * Evaluates the edit on the given string.
@ -129,5 +138,9 @@ public class CodeFormatterUtil {
return doc; return doc;
} }
public static int getTabWidth() {
Preferences preferences= CUIPlugin.getDefault().getPluginPreferences();
return preferences.getInt(CSourceViewerConfiguration.PREFERENCE_TAB_WIDTH);
}
} }

View file

@ -0,0 +1,101 @@
/**********************************************************************
* Copyright (c) 2002,2003,2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.templates.TemplatePreferencePage;
/**
* CTemplatePreferencePage
*/
public class CTemplatePreferencePage extends TemplatePreferencePage {
public CTemplatePreferencePage() {
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setTemplateStore(CUIPlugin.getDefault().getTemplateStore());
setContextTypeRegistry(CUIPlugin.getDefault().getTemplateContextRegistry());
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), ICHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
}
/*
* @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#getFormatterPreferenceKey()
*/
protected String getFormatterPreferenceKey() {
return PreferenceConstants.TEMPLATES_USE_CODEFORMATTER;
}
/*
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public boolean performOk() {
boolean ok= super.performOk();
CUIPlugin.getDefault().savePluginPreferences();
return ok;
}
/*
* @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createViewer(org.eclipse.swt.widgets.Composite)
*/
protected SourceViewer createViewer(Composite parent) {
Label label= new Label(parent, SWT.NONE);
label.setText(PreferencesMessages.getString("TemplatePreferencePage.Viewer.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= 2;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
CTextTools tools= CUIPlugin.getDefault().getTextTools();
viewer.configure(new CSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(new Document());
viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
control.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = PreferencesMessages.getString("TemplatePreferencePage.preview"); //$NON-NLS-1$
}});
return viewer;
}
}

View file

@ -1,534 +0,0 @@
package org.eclipse.cdt.internal.ui.preferences;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.cdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.cdt.internal.corext.template.Template;
import org.eclipse.cdt.internal.corext.template.TemplateMessages;
import org.eclipse.cdt.internal.corext.template.TemplateTranslator;
import org.eclipse.cdt.internal.ui.IContextMenuConstants;
import org.eclipse.cdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.cdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistPreference;
import org.eclipse.cdt.internal.ui.text.template.TemplateVariableProcessor;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
/**
* Dialog to edit a template.
*/
public class EditTemplateDialog extends StatusDialog {
private static class SimpleCSourceViewerConfiguration extends CSourceViewerConfiguration {
private final IContentAssistProcessor fProcessor;
SimpleCSourceViewerConfiguration(CTextTools tools, CEditor editor, IContentAssistProcessor processor) {
super(tools, editor);
fProcessor= processor;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
IPreferenceStore store= CUIPlugin.getDefault().getPreferenceStore();
ContentAssistant assistant= new ContentAssistant();
assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE);
//assistant.enableAutoInsert(store.getBoolean(ContentAssistPreference.AUTOINSERT));
boolean enabled = (store.getBoolean(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_DOT)
|| store.getBoolean(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_ARROW)
|| store.getBoolean(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_DOUBLECOLON)
);
assistant.enableAutoActivation(enabled);
assistant.setAutoActivationDelay(store.getInt(ContentAssistPreference.AUTOACTIVATION_DELAY));
assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
//assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
Display display= sourceViewer.getTextWidget().getDisplay();
Color background= createColor(store, ContentAssistPreference.PROPOSALS_BACKGROUND, display);
assistant.setContextInformationPopupBackground(background);
assistant.setContextSelectorBackground(background);
assistant.setProposalSelectorBackground(background);
Color foreground= createColor(store, ContentAssistPreference.PROPOSALS_FOREGROUND, display);
assistant.setContextInformationPopupForeground(foreground);
assistant.setContextSelectorForeground(foreground);
assistant.setProposalSelectorForeground(foreground);
return assistant;
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
}
private static class TextViewerAction extends Action implements IUpdate {
private int fOperationCode= -1;
private ITextOperationTarget fOperationTarget;
public TextViewerAction(ITextViewer viewer, int operationCode) {
fOperationCode= operationCode;
fOperationTarget= viewer.getTextOperationTarget();
update();
}
/**
* Updates the enabled state of the action.
* Fires a property change if the enabled state changes.
*
* @see Action#firePropertyChange(String, Object, Object)
*/
public void update() {
boolean wasEnabled= isEnabled();
boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
setEnabled(isEnabled);
if (wasEnabled != isEnabled) {
firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
}
}
/**
* @see Action#run()
*/
public void run() {
if (fOperationCode != -1 && fOperationTarget != null) {
fOperationTarget.doOperation(fOperationCode);
}
}
}
private final Template fTemplate;
protected Text fNameText;
private Text fDescriptionText;
protected Combo fContextCombo;
protected SourceViewer fPatternEditor;
private Button fInsertVariableButton;
protected TemplateTranslator fTranslator= new TemplateTranslator();
protected boolean fSuppressError= true; // #4354
private Map fGlobalActions= new HashMap(10);
private List fSelectionActions = new ArrayList(3);
private Vector fContextTypes= new Vector();
protected final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor();
public EditTemplateDialog(Shell parent, Template template, boolean edit) {
super(parent);
setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
String title= edit
? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$
: TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$
setTitle(title);
fTemplate= template;
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
for (Iterator iterator= registry.iterator(); iterator.hasNext(); )
fContextTypes.add(iterator.next());
if (fContextTypes.size() > 0)
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType((String) fContextTypes.get(0)));
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
parent.setLayout(layout);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
fNameText= createText(composite);
fNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (fSuppressError && (fNameText.getText().trim().length() != 0))
fSuppressError= false;
updateButtons();
}
});
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$
fContextCombo= new Combo(composite, SWT.READ_ONLY);
for (Iterator iterator= fContextTypes.iterator(); iterator.hasNext(); )
fContextCombo.add((String) iterator.next());
fContextCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String name= fContextCombo.getText();
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name));
}
});
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$
fDescriptionText= createText(parent);
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$
fPatternEditor= createEditor(parent);
fInsertVariableButton= new Button(parent, SWT.NONE);
GridData data = getButtonGridData(fInsertVariableButton);
fInsertVariableButton.setLayoutData(data);
fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$
fInsertVariableButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fPatternEditor.getTextWidget().setFocus();
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
fNameText.setText(fTemplate.getName());
fDescriptionText.setText(fTemplate.getDescription());
fContextCombo.select(getIndex(fTemplate.getContextTypeName()));
initializeActions();
return composite;
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
private static Label createLabel(Composite parent, String name) {
Label label= new Label(parent, SWT.NULL);
label.setText(name);
label.setLayoutData(new GridData());
return label;
}
private static Text createText(Composite parent) {
Text text= new Text(parent, SWT.BORDER);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return text;
}
private SourceViewer createEditor(Composite parent) {
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
CTextTools tools= CUIPlugin.getDefault().getTextTools();
viewer.configure(new SimpleCSourceViewerConfiguration(tools, null, fProcessor));
viewer.setEditable(true);
viewer.setDocument(new Document(fTemplate.getPattern()));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(60);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
control.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = TemplateMessages.getString("EditTemplateDialog.pattern"); //$NON-NLS-1$
}});
viewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
try {
fTranslator.translate(event.getDocumentEvent().getDocument().get());
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
// XXX dialog
}
updateUndoAction();
updateButtons();
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateSelectionDependentActions();
}
});
if (viewer instanceof ITextViewerExtension) {
((ITextViewerExtension) viewer).prependVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent event) {
handleVerifyKeyPressed(event);
}
});
} else {
viewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
public void keyReleased(KeyEvent e) {}
});
}
return viewer;
}
protected void handleKeyPressed(KeyEvent event) {
if (event.stateMask != SWT.CTRL)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
break;
// CTRL-Z
case (int) 'z' - (int) 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
break;
}
}
protected void handleVerifyKeyPressed(VerifyEvent event) {
if (!event.doit)
return;
if (event.stateMask != SWT.CTRL)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
event.doit= false;
break;
// CTRL-Z
case (int) 'z' - (int) 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
event.doit= false;
break;
}
}
private void initializeActions() {
TextViewerAction action= new TextViewerAction(fPatternEditor, ITextOperationTarget.UNDO);
action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
action= new TextViewerAction(fPatternEditor, ITextOperationTarget.CUT);
action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.CUT, action);
action= new TextViewerAction(fPatternEditor, ITextOperationTarget.COPY);
action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.COPY, action);
action= new TextViewerAction(fPatternEditor, ITextOperationTarget.PASTE);
action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
action= new TextViewerAction(fPatternEditor, ITextOperationTarget.SELECT_ALL);
action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
action= new TextViewerAction(fPatternEditor, ISourceViewer.CONTENTASSIST_PROPOSALS);
action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$
fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
fSelectionActions.add(ITextEditorActionConstants.CUT);
fSelectionActions.add(ITextEditorActionConstants.COPY);
fSelectionActions.add(ITextEditorActionConstants.PASTE);
// create context menu
MenuManager manager= new MenuManager(null, null);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
StyledText text= fPatternEditor.getTextWidget();
Menu menu= manager.createContextMenu(text);
text.setMenu(menu);
}
protected void fillContextMenu(IMenuManager menu) {
menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$
}
protected void updateSelectionDependentActions() {
Iterator iterator= fSelectionActions.iterator();
while (iterator.hasNext())
updateAction((String)iterator.next());
}
protected void updateUndoAction() {
IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
protected void updateAction(String actionId) {
IAction action= (IAction) fGlobalActions.get(actionId);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
private int getIndex(String context) {
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
registry.getContextType(context);
if (context == null)
return -1;
return fContextTypes.indexOf(context);
}
protected void okPressed() {
fTemplate.setName(fNameText.getText());
fTemplate.setDescription(fDescriptionText.getText());
fTemplate.setContext(fContextCombo.getText());
fTemplate.setPattern(fPatternEditor.getTextWidget().getText());
super.okPressed();
}
protected void updateButtons() {
boolean valid= fNameText.getText().trim().length() != 0;
StatusInfo status= new StatusInfo();
if (!valid) {
if (fSuppressError)
status.setError(""); //$NON-NLS-1$
else
status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$
} else if (fTranslator.getErrorMessage() != null) {
status.setError(fTranslator.getErrorMessage());
}
updateStatus(status);
}
}

View file

@ -1,604 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.preferences;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.cdt.internal.corext.template.ContextType;
import org.eclipse.cdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.corext.template.Template;
import org.eclipse.cdt.internal.corext.template.TemplateMessages;
import org.eclipse.cdt.internal.corext.template.TemplateSet;
import org.eclipse.cdt.internal.corext.template.Templates;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.text.CSourceViewerConfiguration;
import org.eclipse.cdt.internal.ui.text.CTextTools;
import org.eclipse.cdt.internal.ui.text.template.TemplateContentProvider;
import org.eclipse.cdt.internal.ui.text.template.TemplateLabelProvider;
import org.eclipse.cdt.internal.ui.util.SWTUtil;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// preference store keys
private static final String PREF_FORMAT_TEMPLATES= CUIPlugin.PLUGIN_ID + ".template.format"; //$NON-NLS-1$
private Templates fTemplates;
private CheckboxTableViewer fTableViewer;
private Button fAddButton;
private Button fEditButton;
private Button fImportButton;
private Button fExportButton;
private Button fExportAllButton;
private Button fRemoveButton;
private Button fEnableAllButton;
private Button fDisableAllButton;
private SourceViewer fPatternViewer;
//private Button fFormatButton;
public TemplatePreferencePage() {
super();
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$
fTemplates= Templates.getInstance();
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
parent.setLayout(layout);
Table table= new Table(parent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(80);
data.heightHint= convertHeightInCharsToPixels(10);
table.setLayoutData(data);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableLayout tableLayout= new TableLayout();
table.setLayout(tableLayout);
TableColumn column1= new TableColumn(table, SWT.NONE);
column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$
TableColumn column2= new TableColumn(table, SWT.NONE);
column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$
TableColumn column3= new TableColumn(table, SWT.NONE);
column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$
tableLayout.addColumnData(new ColumnWeightData(30));
tableLayout.addColumnData(new ColumnWeightData(20));
tableLayout.addColumnData(new ColumnWeightData(70));
fTableViewer= new CheckboxTableViewer(table);
fTableViewer.setLabelProvider(new TemplateLabelProvider());
fTableViewer.setContentProvider(new TemplateContentProvider());
fTableViewer.setSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object object1, Object object2) {
if ((object1 instanceof Template) && (object2 instanceof Template)) {
Template left= (Template) object1;
Template right= (Template) object2;
int result= left.getName().compareToIgnoreCase(right.getName());
if (result != 0)
return result;
return left.getDescription().compareToIgnoreCase(right.getDescription());
}
return super.compare(viewer, object1, object2);
}
public boolean isSorterProperty(Object element, String property) {
return true;
}
});
fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent e) {
edit();
}
});
fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent e) {
selectionChanged1();
}
});
fTableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Template template= (Template) event.getElement();
template.setEnabled(event.getChecked());
}
});
Composite buttons= new Composite(parent, SWT.NULL);
buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
buttons.setLayout(layout);
fAddButton= new Button(buttons, SWT.PUSH);
fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$
fAddButton.setLayoutData(getButtonGridData(fAddButton));
fAddButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
add();
}
});
fEditButton= new Button(buttons, SWT.PUSH);
fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$
fEditButton.setLayoutData(getButtonGridData(fEditButton));
fEditButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
edit();
}
});
fRemoveButton= new Button(buttons, SWT.PUSH);
fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$
fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton));
fRemoveButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
remove();
}
});
createSpacer(buttons);
fImportButton= new Button(buttons, SWT.PUSH);
fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$
fImportButton.setLayoutData(getButtonGridData(fImportButton));
fImportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
import_();
}
});
fExportButton= new Button(buttons, SWT.PUSH);
fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$
fExportButton.setLayoutData(getButtonGridData(fExportButton));
fExportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
export();
}
});
fExportAllButton= new Button(buttons, SWT.PUSH);
fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$
fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton));
fExportAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
exportAll();
}
});
createSpacer(buttons);
fEnableAllButton= new Button(buttons, SWT.PUSH);
fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$
fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton));
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(true);
}
});
fDisableAllButton= new Button(buttons, SWT.PUSH);
fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$
fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton));
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(false);
}
});
fPatternViewer= createViewer(parent);
createSpacer(parent);
//fFormatButton= new Button(parent, SWT.CHECK);
//fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$
fTableViewer.setInput(fTemplates);
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
//IPreferenceStore prefs= CUIPlugin.getDefault().getPreferenceStore();
//fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES));
updateButtons();
WorkbenchHelp.setHelp(parent, ICHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
return parent;
}
private Template[] getEnabledTemplates() {
Template[] templates= fTemplates.getTemplates();
List list= new ArrayList(templates.length);
for (int i= 0; i != templates.length; i++)
if (templates[i].isEnabled())
list.add(templates[i]);
return (Template[]) list.toArray(new Template[list.size()]);
}
private SourceViewer createViewer(Composite parent) {
Label label= new Label(parent, SWT.NONE);
label.setText(PreferencesMessages.getString("TemplatePreferencePage.Viewer.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= 2;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
CTextTools tools= CUIPlugin.getDefault().getTextTools();
viewer.configure(new CSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(new Document());
viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
control.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = TemplateMessages.getString("TemplatePreferencePage.preview"); //$NON-NLS-1$
}});
return viewer;
}
public void createSpacer(Composite parent) {
Label spacer= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
data.heightHint= 4;
spacer.setLayoutData(data);
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.widthHint= SWTUtil.getButtonWidthHint(button);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
protected void selectionChanged1() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
if (selection.size() == 1) {
Template template= (Template) selection.getFirstElement();
fPatternViewer.getTextWidget().setText(template.getPattern());
} else {
fPatternViewer.getTextWidget().setText(""); //$NON-NLS-1$
}
updateButtons();
}
private void updateButtons() {
int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size();
int itemCount= fTableViewer.getTable().getItemCount();
fEditButton.setEnabled(selectionCount == 1);
fExportButton.setEnabled(selectionCount > 0);
fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount);
fEnableAllButton.setEnabled(itemCount > 0);
fDisableAllButton.setEnabled(itemCount > 0);
}
protected void add() {
Template template= new Template();
ContextTypeRegistry registry=ContextTypeRegistry.getInstance();
ContextType type= registry.getContextType(ITemplateEditor.TemplateContextKind.C_GLOBAL_CONTEXT_TYPE);
String contextTypeName;
if (type != null)
contextTypeName= type.getName();
else {
Iterator iterator= registry.iterator();
contextTypeName= (String) iterator.next();
}
template.setContext(contextTypeName); //$NON-NLS-1$
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false);
if (dialog.open() == Window.OK) {
fTemplates.add(template);
fTableViewer.refresh();
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
protected void edit() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] objects= selection.toArray();
if ((objects == null) || (objects.length != 1))
return;
Template template= (Template) selection.getFirstElement();
edit(template);
}
private void edit(Template template) {
Template newTemplate= new Template(template);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true);
if (dialog.open() == Window.OK) {
if (!newTemplate.getName().equals(template.getName()) &&
MessageDialog.openQuestion(getShell(),
TemplateMessages.getString("TemplatePreferencePage.question.create.new.title"), //$NON-NLS-1$
TemplateMessages.getString("TemplatePreferencePage.question.create.new.message"))) //$NON-NLS-1$
{
template= newTemplate;
fTemplates.add(template);
fTableViewer.refresh();
} else {
template.setName(newTemplate.getName());
template.setDescription(newTemplate.getDescription());
template.setContext(newTemplate.getContextTypeName());
template.setPattern(newTemplate.getPattern());
fTableViewer.refresh(template);
}
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
protected void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
try {
fTemplates.addFromFile(new File(path));
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
protected void exportAll() {
export(fTemplates);
}
protected void export() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] templates= selection.toArray();
TemplateSet templateSet= new TemplateSet();
for (int i= 0; i != templates.length; i++)
templateSet.add((Template) templates[i]);
export(templateSet);
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$
dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
File file= new File(path);
if (!file.exists() || confirmOverwrite(file)) {
try {
templateSet.saveToFile(file);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openWriteErrorDialog(e);
}
}
}
private boolean confirmOverwrite(File file) {
return MessageDialog.openQuestion(getShell(),
TemplateMessages.getString("TemplatePreferencePage.export.exists.title"), //$NON-NLS-1$
TemplateMessages.getFormattedString("TemplatePreferencePage.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$
}
protected void remove() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Iterator elements= selection.iterator();
while (elements.hasNext()) {
Template template= (Template) elements.next();
fTemplates.remove(template);
}
fTableViewer.refresh();
}
protected void enableAll(boolean enable) {
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i != templates.length; i++)
templates[i].setEnabled(enable);
fTableViewer.setAllChecked(enable);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {}
/*
* @see Control#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible)
setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
//IPreferenceStore prefs= CUIPlugin.getDefault().getPreferenceStore();
//fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openReadErrorDialog(e);
}
// refresh
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
//IPreferenceStore prefs= CUIPlugin.getDefault().getPreferenceStore();
//prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection());
try {
fTemplates.save();
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openWriteErrorDialog(e);
}
return super.performOk();
}
/*
* @see PreferencePage#performCancel()
*/
public boolean performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openReadErrorDialog(e);
}
return super.performCancel();
}
/**
* Initializes the default values of this page in the preference bundle.
* Will be called on startup of the JavaPlugin
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_FORMAT_TEMPLATES, true);
}
public static boolean useCodeFormatter() {
IPreferenceStore prefs= CUIPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FORMAT_TEMPLATES);
}
private void openReadErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.read.title"), //$NON-NLS-1$
null, e.getStatus());
}
private void openWriteErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$
null, e.getStatus());
}
}

View file

@ -11,7 +11,6 @@ import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.model.IWorkingCopy;
@ -23,9 +22,7 @@ import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchScope; import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.OrPattern; import org.eclipse.cdt.core.search.OrPattern;
import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.corext.template.ContextType; import org.eclipse.cdt.internal.corext.template.c.CContextType;
import org.eclipse.cdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.cdt.internal.corext.template.ITemplateEditor;
import org.eclipse.cdt.internal.ui.CHelpProviderManager; import org.eclipse.cdt.internal.ui.CHelpProviderManager;
import org.eclipse.cdt.internal.ui.CPluginImages; import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.cdt.internal.ui.CUIMessages; import org.eclipse.cdt.internal.ui.CUIMessages;
@ -37,7 +34,6 @@ import org.eclipse.cdt.ui.IFunctionSummary;
import org.eclipse.cdt.ui.IWorkingCopyManager; import org.eclipse.cdt.ui.IWorkingCopyManager;
import org.eclipse.cdt.ui.text.ICHelpInvocationContext; import org.eclipse.cdt.ui.text.ICHelpInvocationContext;
import org.eclipse.cdt.ui.text.ICCompletionProposal; import org.eclipse.cdt.ui.text.ICCompletionProposal;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProject;
import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadLocationException;
@ -49,6 +45,7 @@ import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationExtension; import org.eclipse.jface.text.contentassist.IContextInformationExtension;
import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorPart;
@ -105,9 +102,7 @@ public class CCompletionProcessor implements IContentAssistProcessor {
private CCompletionProposalComparator fComparator; private CCompletionProposalComparator fComparator;
private IContextInformationValidator fValidator; private IContextInformationValidator fValidator;
private TemplateEngine[] fGlobalContextTemplateEngine; private TemplateEngine fTemplateEngine;
private TemplateEngine[] fFunctionContextTemplateEngine;
private TemplateEngine[] fStructureContextTemplateEngine;
//private boolean fRestrictToMatchingCase; //private boolean fRestrictToMatchingCase;
private boolean fAllowAddIncludes; private boolean fAllowAddIncludes;
@ -117,7 +112,6 @@ public class CCompletionProcessor implements IContentAssistProcessor {
private CompletionEngine completionEngine = null; private CompletionEngine completionEngine = null;
private SearchEngine searchEngine = null; private SearchEngine searchEngine = null;
//private CSearchResultLabelProvider labelProvider = null;
IWorkingCopy fCurrentSourceUnit = null; IWorkingCopy fCurrentSourceUnit = null;
@ -130,7 +124,6 @@ public class CCompletionProcessor implements IContentAssistProcessor {
fEditor = (CEditor) editor; fEditor = (CEditor) editor;
// Needed for search // Needed for search
//labelProvider = new CSearchResultLabelProvider();
searchResultCollector = new BasicSearchResultCollector (); searchResultCollector = new BasicSearchResultCollector ();
resultCollector = new ResultCollector(); resultCollector = new ResultCollector();
completionEngine = new CompletionEngine(resultCollector); completionEngine = new CompletionEngine(resultCollector);
@ -144,77 +137,16 @@ public class CCompletionProcessor implements IContentAssistProcessor {
fComparator = new CCompletionProposalComparator(); fComparator = new CCompletionProposalComparator();
} }
private boolean isCppContext(){ private void setupTemplateEngine() {
String filename = null; TemplateContextType contextType = CUIPlugin.getDefault().getTemplateContextRegistry().getContextType(CContextType.CCONTEXT_TYPE);
if (fEditor != null && fEditor.getEditorInput() != null) { if (contextType == null) {
filename = fEditor.getEditorInput().getName(); contextType= new CContextType();
} CUIPlugin.getDefault().getTemplateContextRegistry().addContextType(contextType);
if (filename == null) {
return true;
} else if (filename.endsWith(".c")) { //$NON-NLS-1$
//Straight C files are always C
return false;
} else if (
filename.endsWith(".cpp") //$NON-NLS-1$
|| filename.endsWith(".cc") //$NON-NLS-1$
|| filename.endsWith(".cxx") //$NON-NLS-1$
|| filename.endsWith(".C") //$NON-NLS-1$
|| filename.endsWith(".hxx")) { //$NON-NLS-1$
return true;
} else {
//Defer to the nature of the project
IFile file = fEditor.getInputFile();
if (file != null && CoreModel.hasCCNature(file.getProject())) {
return true;
}
return false;
} }
if (contextType != null) {
fTemplateEngine = new TemplateEngine(contextType);
} }
private void setupTemplateEngine(){
//Determine if this is a C or a C++ file for the context completion + //This is _totally_ ugly and likely belongs in the main editor class.
String globalContextNames[] = new String[2];
String functionContextNames[] = new String[2];
String structureContextNames[] = new String[2];
ArrayList globalTemplateList = new ArrayList(2);
ArrayList functionTemplateList = new ArrayList(2);
ArrayList structureTemplateList = new ArrayList(2);
if(isCppContext()){
// CPP context
globalContextNames[0] = ITemplateEditor.TemplateContextKind.CPP_GLOBAL_CONTEXT_TYPE; //$NON-NLS-1$
globalContextNames[1] = ITemplateEditor.TemplateContextKind.C_GLOBAL_CONTEXT_TYPE; //$NON-NLS-1$
functionContextNames[0] = ITemplateEditor.TemplateContextKind.CPP_FUNCTION_CONTEXT_TYPE; //$NON-NLS-1$
functionContextNames[1] = ITemplateEditor.TemplateContextKind.C_FUNCTION_CONTEXT_TYPE; //$NON-NLS-1$
structureContextNames[0] = ITemplateEditor.TemplateContextKind.CPP_STRUCTURE_CONTEXT_TYPE; //$NON-NLS-1$
structureContextNames[1] = ITemplateEditor.TemplateContextKind.C_STRUCTURE_CONTEXT_TYPE; //$NON-NLS-1$
}else {
// C context
globalContextNames[0] = ITemplateEditor.TemplateContextKind.C_GLOBAL_CONTEXT_TYPE; //$NON-NLS-1$
structureContextNames[0] = ITemplateEditor.TemplateContextKind.C_STRUCTURE_CONTEXT_TYPE; //$NON-NLS-1$
functionContextNames[0] = ITemplateEditor.TemplateContextKind.C_FUNCTION_CONTEXT_TYPE; //$NON-NLS-1$
}
ContextType contextType;
for (int i = 0; i < globalContextNames.length; i++) {
contextType = ContextTypeRegistry.getInstance().getContextType(globalContextNames[i]);
if (contextType != null) {
globalTemplateList.add(new TemplateEngine(contextType));
}
}
for (int i = 0; i < functionContextNames.length; i++) {
contextType = ContextTypeRegistry.getInstance().getContextType(functionContextNames[i]);
if (contextType != null) {
functionTemplateList.add(new TemplateEngine(contextType));
}
}
for (int i = 0; i < structureContextNames.length; i++) {
contextType = ContextTypeRegistry.getInstance().getContextType(structureContextNames[i]);
if (contextType != null) {
structureTemplateList.add(new TemplateEngine(contextType));
}
}
fGlobalContextTemplateEngine = (TemplateEngine[]) globalTemplateList.toArray(new TemplateEngine[globalTemplateList.size()]);
fFunctionContextTemplateEngine = (TemplateEngine[]) functionTemplateList.toArray(new TemplateEngine[functionTemplateList.size()]);
fStructureContextTemplateEngine = (TemplateEngine[]) structureTemplateList.toArray(new TemplateEngine[structureTemplateList.size()]);
} }
/** /**
* Tells this processor to order the proposals alphabetically. * Tells this processor to order the proposals alphabetically.
@ -345,8 +277,8 @@ public class CCompletionProcessor implements IContentAssistProcessor {
return null; return null;
} }
} }
ICCompletionProposal[] results = null;
ICCompletionProposal[] results = null;
try { try {
results = evalProposals(document, offset, unit, viewer); results = evalProposals(document, offset, unit, viewer);
} catch (Exception e) { } catch (Exception e) {
@ -396,8 +328,7 @@ public class CCompletionProcessor implements IContentAssistProcessor {
addProposalsFromSearch(fCurrentCompletionNode, completions); addProposalsFromSearch(fCurrentCompletionNode, completions);
addProposalsFromCompletionContributors(fCurrentCompletionNode, completions); addProposalsFromCompletionContributors(fCurrentCompletionNode, completions);
addProposalsFromTemplates(viewer, fCurrentCompletionNode, completions); addProposalsFromTemplates(viewer, fCurrentCompletionNode, completions);
return (ICCompletionProposal[]) completions.toArray(new ICCompletionProposal[0]);
return order ( (ICCompletionProposal[]) completions.toArray(new ICCompletionProposal[0]) );
} }
return null; return null;
} }
@ -411,32 +342,26 @@ public class CCompletionProcessor implements IContentAssistProcessor {
IASTCompletionNode.CompletionKind kind = completionNode.getCompletionKind(); IASTCompletionNode.CompletionKind kind = completionNode.getCompletionKind();
if( (kind == IASTCompletionNode.CompletionKind.VARIABLE_TYPE) ||
(kind == IASTCompletionNode.CompletionKind.CLASS_REFERENCE) ) // if ((kind == IASTCompletionNode.CompletionKind.VARIABLE_TYPE) ||
addProposalsFromTemplateEngine(viewer, fGlobalContextTemplateEngine, completions); // (kind == IASTCompletionNode.CompletionKind.CLASS_REFERENCE)
if( (kind == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE) // || (kind == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE)) {
|| (kind == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE) ) addProposalsFromTemplateEngine(viewer, fTemplateEngine, completions);
addProposalsFromTemplateEngine(viewer, fFunctionContextTemplateEngine, completions); // }
if(kind == IASTCompletionNode.CompletionKind.FIELD_TYPE)
addProposalsFromTemplateEngine(viewer, fStructureContextTemplateEngine, completions);
} }
private void addProposalsFromTemplateEngine(ITextViewer viewer, TemplateEngine[] fTemplateEngine, List completions){ private void addProposalsFromTemplateEngine(ITextViewer viewer, TemplateEngine fTemplateEngine, List completions){
for (int i = 0; i < fTemplateEngine.length; i++) { if (fTemplateEngine != null) {
if (fTemplateEngine[i] == null) {
continue;
}
try { try {
fTemplateEngine[i].reset(); fTemplateEngine.reset();
fTemplateEngine[i].complete(viewer, fCurrentOffset, null); fTemplateEngine.complete(viewer, fCurrentOffset, null);
} catch (Exception x) { } catch (Exception x) {
CUIPlugin.getDefault().log(x); CUIPlugin.getDefault().log(x);
} }
completions.addAll(fTemplateEngine.getResults());
completions.addAll(fTemplateEngine[i].getResults()); }
} }
}
private void addProposalsFromCompletionContributors(IASTCompletionNode completionNode, List completions) { private void addProposalsFromCompletionContributors(IASTCompletionNode completionNode, List completions) {
if(completionNode == null) if(completionNode == null)
return; return;

View file

@ -14,6 +14,7 @@ package org.eclipse.cdt.internal.ui.text.contentassist;
import java.util.Comparator; import java.util.Comparator;
import org.eclipse.cdt.ui.text.*; import org.eclipse.cdt.ui.text.*;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
public class CCompletionProposalComparator implements Comparator { public class CCompletionProposalComparator implements Comparator {

View file

@ -1,31 +0,0 @@
package org.eclipse.cdt.internal.ui.text.link;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.text.Position;
/**
* A listener for highlight change notification and exititing linked mode.
*/
public interface LinkedPositionListener {
/**
* Notifies that the linked mode has been left. On success, all changes
* are kept, otherwise all changes made to the linked positions are restored
* to the state before entering linked mode.
*/
void exit(boolean success);
/**
* Notifies the changed linked position. The listener is asked
* to reposition the caret at the given offset.
*
* @param position the linked position which initiated the change.
* @param caretOffset the caret offset relative to the position.
*/
void setCurrentPosition(Position position, int caretOffset);
}

View file

@ -1,449 +0,0 @@
package org.eclipse.cdt.internal.ui.text.link;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.ui.CUIPlugin;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.util.Assert;
/**
* This class manages linked positions in a document. Positions are linked
* by type names. If positions have the same type name, they are considered
* as <em>linked</em>.
*
* The manager remains active on a document until any of the following actions
* occurs:
*
* <ul>
* <li>A document change is performed which would invalidate any of the
* above constraints.</li>
*
* <li>The method <code>uninstall()</code> is called.</li>
*
* <li>Another instance of <code>LinkedPositionManager</code> tries to
* gain control of the same document.
* </ul>
*/
public class LinkedPositionManager implements IDocumentListener, IPositionUpdater {
private static class PositionComparator implements Comparator {
/*
* @see Comparator#compare(Object, Object)
*/
public int compare(Object object0, Object object1) {
Position position0= (Position) object0;
Position position1= (Position) object1;
return position0.getOffset() - position1.getOffset();
}
}
private class Replace implements IDocumentExtension.IReplace {
private Position fReplacePosition;
private int fReplaceDeltaOffset;
private int fReplaceLength;
private String fReplaceText;
public Replace(Position position, int deltaOffset, int length, String text) {
fReplacePosition= position;
fReplaceDeltaOffset= deltaOffset;
fReplaceLength= length;
fReplaceText= text;
}
public void perform(IDocument document, IDocumentListener owner) {
document.removeDocumentListener(owner);
try {
document.replace(fReplacePosition.getOffset() + fReplaceDeltaOffset, fReplaceLength, fReplaceText);
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
// TBD
}
document.addDocumentListener(owner);
}
}
private static final String LINKED_POSITION= "LinkedPositionManager.linked.position"; //$NON-NLS-1$
private static final Comparator fgPositionComparator= new PositionComparator();
private static final Map fgActiveManagers= new HashMap();
private IDocument fDocument;
private LinkedPositionListener fListener;
/**
* Creates a <code>LinkedPositionManager</code> for a <code>IDocument</code>.
*
* @param document the document to use with linked positions.
*/
public LinkedPositionManager(IDocument document) {
Assert.isNotNull(document);
fDocument= document;
install();
}
/**
* Sets a listener to notify changes of current linked position.
*/
public void setLinkedPositionListener(LinkedPositionListener listener) {
fListener= listener;
}
/**
* Adds a linked position to the manager.
* There are the following constraints for linked positions:
*
* <ul>
* <li>Any two positions have spacing of at least one character.
* This implies that two positions must not overlap.</li>
*
* <li>The string at any position must not contain line delimiters.</li>
* </ul>
*
* @param offset the offset of the position.
* @param length the length of the position.
*/
public void addPosition(int offset, int length) throws BadLocationException {
Position[] positions= getPositions(fDocument);
if (positions != null) {
for (int i = 0; i < positions.length; i++)
if (collides(positions[i], offset, length))
throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$
}
String type= fDocument.get(offset, length);
if (containsLineDelimiters(type))
throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$
try {
fDocument.addPosition(LINKED_POSITION, new TypedPosition(offset, length, type));
} catch (BadPositionCategoryException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
}
}
/**
* Tests if a manager is already active for a document.
*/
public static boolean hasActiveManager(IDocument document) {
return fgActiveManagers.get(document) != null;
}
private void install() {
LinkedPositionManager manager= (LinkedPositionManager) fgActiveManagers.get(fDocument);
if (manager != null)
manager.leave(true);
fgActiveManagers.put(fDocument, this);
fDocument.addPositionCategory(LINKED_POSITION);
fDocument.addPositionUpdater(this);
fDocument.addDocumentListener(this);
}
/**
* Leaves the linked mode. If unsuccessful, the linked positions
* are restored to the values at the time they were added.
*/
public void uninstall(boolean success) {
fDocument.removeDocumentListener(this);
try {
Position[] positions= getPositions(fDocument);
if ((!success) && (positions != null)) {
// restore
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
fDocument.replace(position.getOffset(), position.getLength(), position.getType());
}
}
fDocument.removePositionCategory(LINKED_POSITION);
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
} catch (BadPositionCategoryException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
} finally {
fDocument.removePositionUpdater(this);
fgActiveManagers.remove(fDocument);
}
}
/**
* Returns the first linked position.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getFirstPosition() {
return getNextPosition(-1);
}
/**
* Returns the next linked position with an offset greater than <code>offset</code>.
* If another position with the same type and offset lower than <code>offset</code>
* exists, the position is skipped.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getNextPosition(int offset) {
Position[] positions= getPositions(fDocument);
return findNextPosition(positions, offset);
}
private static Position findNextPosition(Position[] positions, int offset) {
// skip already visited types
for (int i= 0; i != positions.length; i++) {
if (positions[i].getOffset() > offset) {
String type= ((TypedPosition) positions[i]).getType();
int j;
for (j = 0; j != i; j++)
if (((TypedPosition) positions[j]).getType().equals(type))
break;
if (j == i)
return positions[i];
}
}
return null;
}
/**
* Returns the position with the greatest offset smaller than <code>offset</code>.
*
* @return returns <code>null</code> if no linked position exist.
*/
public Position getPreviousPosition(int offset) {
Position[] positions= getPositions(fDocument);
if (positions == null)
return null;
Position lastPosition= null;
Position position= getFirstPosition();
while ((position != null) && (position.getOffset() < offset)) {
lastPosition= position;
position= findNextPosition(positions, position.getOffset());
}
return lastPosition;
}
private static Position[] getPositions(IDocument document) {
try {
Position[] positions= document.getPositions(LINKED_POSITION);
Arrays.sort(positions, fgPositionComparator);
return positions;
} catch (BadPositionCategoryException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
}
return null;
}
public static boolean includes(Position position, int offset, int length) {
return
(offset >= position.getOffset()) &&
(offset + length <= position.getOffset() + position.getLength());
}
public static boolean excludes(Position position, int offset, int length) {
return
(offset + length <= position.getOffset()) ||
(position.getOffset() + position.getLength() <= offset);
}
/*
* Collides if spacing if positions intersect each other or are adjacent.
*/
private static boolean collides(Position position, int offset, int length) {
return
(offset <= position.getOffset() + position.getLength()) &&
(position.getOffset() <= offset + length);
}
private void leave(boolean success) {
uninstall(success);
if (fListener != null)
fListener.exit(success);
}
/*
* @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
IDocument document= event.getDocument();
Position[] positions= getPositions(document);
Position position= findCurrentEditablePosition(positions, event.getOffset());
// modification outside editable position
if (position == null) {
position= findCurrentPosition(positions, event.getOffset());
// modification outside any position
if (position == null) {
// check for destruction of constraints (spacing of at least 1)
if ((event.getText().length() == 0) &&
(findCurrentPosition(positions, event.getOffset()) != null) &&
(findCurrentPosition(positions, event.getOffset() + event.getLength()) != null))
{
leave(true);
}
// modification intersects non-editable position
} else {
leave(true);
}
// modification intersects editable position
} else {
// modificaction inside editable position
if (includes(position, event.getOffset(), event.getLength())) {
if (containsLineDelimiters(event.getText()))
leave(true);
// modificaction exceeds editable position
} else {
leave(true);
}
}
}
/*
* @see IDocumentListener#documentChanged(DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
IDocument document= event.getDocument();
Position[] positions= getPositions(document);
TypedPosition currentPosition= (TypedPosition) findCurrentEditablePosition(positions, event.getOffset());
// ignore document changes (assume it won't invalidate constraints)
if (currentPosition == null)
return;
int deltaOffset= event.getOffset() - currentPosition.getOffset();
if (fListener != null)
fListener.setCurrentPosition(currentPosition, deltaOffset + event.getText().length());
for (int i= 0; i != positions.length; i++) {
TypedPosition p= (TypedPosition) positions[i];
if (p.getType().equals(currentPosition.getType()) && !p.equals(currentPosition)) {
Replace replace= new Replace(p, deltaOffset, event.getLength(), event.getText());
((IDocumentExtension) document).registerPostNotificationReplace(this, replace);
}
}
}
/*
* @see IPositionUpdater#update(DocumentEvent)
*/
public void update(DocumentEvent event) {
int deltaLength= event.getText().length() - event.getLength();
Position[] positions= getPositions(event.getDocument());
TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, event.getOffset());
// document change outside positions
if (currentPosition == null) {
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
int offset= position.getOffset();
if (offset >= event.getOffset())
position.setOffset(offset + deltaLength);
}
// document change within a position
} else {
int length= currentPosition.getLength();
for (int i= 0; i != positions.length; i++) {
TypedPosition position= (TypedPosition) positions[i];
int offset= position.getOffset();
if (position.equals(currentPosition)) {
position.setLength(length + deltaLength);
} else if (offset > currentPosition.getOffset()) {
position.setOffset(offset + deltaLength);
}
}
}
}
private static Position findCurrentPosition(Position[] positions, int offset) {
for (int i= 0; i != positions.length; i++)
if (includes(positions[i], offset, 0))
return positions[i];
return null;
}
private static Position findCurrentEditablePosition(Position[] positions, int offset) {
Position position= positions[0];
while ((position != null) && !includes(position, offset, 0))
position= findNextPosition(positions, position.getOffset());
return position;
}
private boolean containsLineDelimiters(String string) {
String[] delimiters= fDocument.getLegalLineDelimiters();
for (int i= 0; i != delimiters.length; i++)
if (string.indexOf(delimiters[i]) != -1)
return true;
return false;
}
/**
* Test if ok to modify through UI.
*/
public boolean anyPositionIncludes(int offset, int length) {
Position[] positions= getPositions(fDocument);
Position position= findCurrentEditablePosition(positions, offset);
if (position == null)
return false;
return includes(position, offset, length);
}
}

View file

@ -1,53 +0,0 @@
package org.eclipse.cdt.internal.ui.text.link;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class LinkedPositionMessages {
private static final String RESOURCE_BUNDLE= LinkedPositionMessages.class.getName();
private static ResourceBundle fgResourceBundle;
static {
try {
fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
} catch (MissingResourceException x) {
fgResourceBundle = null;
}
}
private LinkedPositionMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
} catch (NullPointerException e) {
return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Gets a string from the resource bundle and formats it with the argument
*
* @param key the string used to get the bundle value, must not be null
*/
public static String getFormattedString(String key, Object arg) {
return MessageFormat.format(getString(key), new Object[] { arg });
}
/**
* Gets a string from the resource bundle and formats it with arguments
*/
public static String getFormattedString(String key, Object[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -1,9 +0,0 @@
#########################################
# (c) Copyright IBM Corp. 2000, 2001.
# All Rights Reserved.
#########################################
LinkedPositionUI.error.title=Error in LinkedPositionError
LinkedPositionManager.error.contains.line.delimiters=String contains line delimiters.
LinkedPositionManager.error.position.collision=Linked position collides with another linked position.

View file

@ -1,547 +0,0 @@
package org.eclipse.cdt.internal.ui.text.link;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements LinkedPositionListener,
ITextInputListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
public static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
public static final int UPDATE_CARET= 8; // update caret
private static final String CARET_POSITION= "LinkedPositionUI.caret.position"; //$NON-NLS-1$
private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION);
private static final IPreferenceStore fgStore= CUIPlugin.getDefault().getPreferenceStore();
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFramePosition;
private int fCaretOffset;
private ExitPolicy fExitPolicy;
private ExitListener fExitListener;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fManager.setLinkedPositionListener(this);
initializeHighlightColor(viewer);
}
/**
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(CEditor.LINKED_POSITION_COLOR)) {
initializeHighlightColor(fViewer);
redrawRegion();
}
}
private void initializeHighlightColor(ITextViewer viewer) {
if (fFrameColor != null)
fFrameColor.dispose();
StyledText text= viewer.getTextWidget();
if (text != null) {
Display display= text.getDisplay();
fFrameColor= createColor(fgStore, CEditor.LINKED_POSITION_COLOR, display);
}
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fFramePosition.equals(position)) {
redrawRegion();
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Sets an <code>ExitPolicy</code> which decides when and how
* the linked mode is exited.
*/
public void setExitPolicy(ExitPolicy policy) {
fExitPolicy= policy;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see exit(boolean)
*/
public void enter() {
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(CARET_POSITION);
document.addPositionUpdater(fgUpdater);
try {
if (fFinalCaretOffset != -1)
document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset));
} catch (BadLocationException e) {
openErrorDialog(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.prependVerifyKeyListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
fFramePosition= fManager.getFirstPosition();
if (fFramePosition == null)
leave(UNINSTALL | COMMIT | UPDATE_CARET);
fgStore.addPropertyChangeListener(this);
}
/**
* @see LinkedPositionManager.LinkedPositionListener#exit(boolean)
*/
public void exit(boolean success) {
// no UNINSTALL since manager has already uninstalled itself
leave((success ? COMMIT : 0) | UPDATE_CARET);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
fgStore.removePropertyChangeListener(this);
if (fFrameColor != null) {
fFrameColor.dispose();
fFrameColor= null;
}
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(this);
fViewer.removeTextInputListener(this);
try {
IRegion region= fViewer.getVisibleRegion();
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(CARET_POSITION);
if ((positions != null) && (positions.length != 0)) {
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
document.removePositionUpdater(fgUpdater);
document.removePositionCategory(CARET_POSITION);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
CUIPlugin.getDefault().log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
redrawRegion();
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
redrawRegion();
}
}
private void previous() {
redrawRegion();
Position position= fManager.getPreviousPosition(fFramePosition.getOffset());
if (position == null) {
fViewer.getTextWidget().getDisplay().beep();
} else {
fFramePosition= position;
selectRegion();
redrawRegion();
}
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit )
return;
Point selection= fViewer.getSelectedRange();
int offset= selection.x;
int length= selection.y;
ExitFlags exitFlags= fExitPolicy == null ? null : fExitPolicy.doExit(fManager, event, offset, length);
if (exitFlags != null) {
leave(UNINSTALL | exitFlags.flags);
event.doit= exitFlags.doit;
return;
}
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
selection= fViewer.getTextWidget().getSelection();
IRegion region= fViewer.getVisibleRegion();
offset= selection.x + region.getOffset();
length= selection.y - selection.x;
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ENTER
case 0x0D:
leave(UNINSTALL | COMMIT | UPDATE_CARET);
event.doit= false;
break;
// ESC
case 0x1B:
leave(UNINSTALL | COMMIT);
event.doit= false;
break;
case ';':
leave(UNINSTALL | COMMIT);
event.doit= true;
break;
}
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
IRegion region= fViewer.getVisibleRegion();
int offset= event.start + region.getOffset();
int length= event.end - event.start;
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion region= fViewer.getVisibleRegion();
// #6824
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
private static Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private static Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
private void redrawRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
fViewer.getTextWidget().redrawRange(offset, length, true);
}
private void selectRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int start= fFramePosition.getOffset() - region.getOffset();
int end= fFramePosition.getLength() + start;
fViewer.getTextWidget().setSelection(start, end);
}
private void updateCaret() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
fViewer.getTextWidget().setCaretOffset(offset);
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void openErrorDialog(Shell shell, Exception e) {
MessageDialog.openError(shell, LinkedPositionMessages.getString("LinkedPositionUI.error.title"), e.getMessage()); //$NON-NLS-1$
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
public static class ExitFlags {
public int flags;
public boolean doit;
public ExitFlags(int flags, boolean doit) {
this.flags= flags;
this.doit= doit;
}
}
public interface ExitPolicy {
ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length);
}
}

View file

@ -1,39 +0,0 @@
package org.eclipse.cdt.internal.ui.text.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.template.TemplateSet;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
public class TemplateContentProvider implements IStructuredContentProvider {
private TemplateSet fTemplateSet;
/**
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object input) {
return fTemplateSet.getTemplates();
}
/**
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
fTemplateSet= (TemplateSet) newInput;
}
/**
* @see IContentProvider#dispose()
*/
public void dispose() {
fTemplateSet= null;
}
}

View file

@ -9,32 +9,54 @@ package org.eclipse.cdt.internal.ui.text.template;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.eclipse.cdt.internal.corext.template.ContextType; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.corext.template.Template; import org.eclipse.cdt.internal.corext.template.c.TranslationUnitContext;
import org.eclipse.cdt.internal.corext.template.Templates; import org.eclipse.cdt.internal.corext.template.c.TranslationUnitContextType;
import org.eclipse.cdt.internal.corext.template.c.CompilationUnitContext; import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.cdt.internal.corext.template.c.CompilationUnitContextType; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.corext.template.c.ICompilationUnit; import org.eclipse.cdt.ui.text.ICCompletionProposal;
import org.eclipse.cdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region; import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.TemplateProposal;
import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
public class TemplateEngine { public class TemplateEngine {
private ContextType fContextType; private TemplateContextType fContextType;
private ITableLabelProvider fLabelProvider= new TemplateLabelProvider();
private ArrayList fProposals= new ArrayList(); private ArrayList fProposals= new ArrayList();
public class CTemplateProposal extends TemplateProposal implements ICCompletionProposal {
/**
* @param template
* @param context
* @param region
* @param image
*/
public CTemplateProposal(Template template, TemplateContext context, IRegion region, Image image) {
super(template, context, region, image, 90);
}
// /* (non-Javadoc)
// * @see org.eclipse.cdt.ui.text.ICCompletionProposal#getRelevance()
// */
// public int getRelevance() {
// return 90;
// }
}
/** /**
* Creates the template engine for a particular context type. * Creates the template engine for a particular context type.
* See <code>TemplateContext</code> for supported context types. * See <code>TemplateContext</code> for supported context types.
*/ */
public TemplateEngine(ContextType contextType) { public TemplateEngine(TemplateContextType contextType) {
Assert.isNotNull(contextType); Assert.isNotNull(contextType);
fContextType= contextType; fContextType= contextType;
} }
@ -53,7 +75,7 @@ public class TemplateEngine {
* Returns the array of matching templates. * Returns the array of matching templates.
*/ */
public List getResults() { public List getResults() {
// return (ICCompletionProposal[]) fProposals.toArray(new ICCompletionProposal[fProposals.size()]); //return (TemplateProposal[]) fProposals.toArray(new TemplateProposal[fProposals.size()]);
return fProposals; return fProposals;
} }
@ -64,28 +86,33 @@ public class TemplateEngine {
* @param completionPosition the context position in the document of the text viewer * @param completionPosition the context position in the document of the text viewer
* @param compilationUnit the compilation unit (may be <code>null</code>) * @param compilationUnit the compilation unit (may be <code>null</code>)
*/ */
public void complete(ITextViewer viewer, int completionPosition, ICompilationUnit compilationUnit) public void complete(ITextViewer viewer, int completionPosition, ITranslationUnit translationUnit)
//throws JavaModelException
{ {
IDocument document= viewer.getDocument(); IDocument document= viewer.getDocument();
// prohibit recursion if (!(fContextType instanceof TranslationUnitContextType))
if (LinkedPositionManager.hasActiveManager(document))
return; return;
if (!(fContextType instanceof CompilationUnitContextType)) Point selection= viewer.getSelectedRange();
return;
((CompilationUnitContextType) fContextType).setContextParameters(document.get(), completionPosition, compilationUnit); // remember selected text
CompilationUnitContext context= (CompilationUnitContext) fContextType.createContext(); String selectedText= null;
if (selection.y != 0) {
try {
selectedText= document.get(selection.x, selection.y);
} catch (BadLocationException e) {}
}
((TranslationUnitContextType) fContextType).setContextParameters(document.get(), completionPosition, translationUnit);
TranslationUnitContext context= ((TranslationUnitContextType) fContextType).createContext(document, completionPosition, selection.y, translationUnit);
int start= context.getStart(); int start= context.getStart();
int end= context.getEnd(); int end= context.getEnd();
IRegion region= new Region(start, end - start); IRegion region= new Region(start, end - start);
Template[] templates= Templates.getInstance().getTemplates(); Template[] templates= CUIPlugin.getDefault().getTemplateStore().getTemplates();
for (int i= 0; i != templates.length; i++) for (int i= 0; i != templates.length; i++)
if (context.canEvaluate(templates[i])) if (context.canEvaluate(templates[i]))
fProposals.add(new TemplateProposal(templates[i], context, region, viewer, fLabelProvider.getColumnImage(templates[i], 0))); fProposals.add(new CTemplateProposal(templates[i], context, region, CPluginImages.get(CPluginImages.IMG_OBJS_TEMPLATE)));
} }
} }

View file

@ -1,72 +0,0 @@
package org.eclipse.cdt.internal.ui.text.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.graphics.Image;
import org.eclipse.cdt.internal.corext.template.Template;
import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
public class TemplateLabelProvider implements ITableLabelProvider {
/*
* @see ITableLabelProvider#getColumnImage(Object, int)
*/
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex != 0)
return null;
return CPluginImages.get(CPluginImages.IMG_OBJS_TEMPLATE);
}
/*
* @see ITableLabelProvider#getColumnText(Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
Template template = (Template) element;
switch (columnIndex) {
case 0:
return template.getName();
case 1:
return template.getContextTypeName();
case 2:
return template.getDescription();
default:
return null;
}
}
/*
* @see IBaseLabelProvider#addListener(ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
}
/*
* @see IBaseLabelProvider#dispose()
*/
public void dispose() {
}
/*
* @see IBaseLabelProvider#isLabelProperty(Object, String)
*/
public boolean isLabelProperty(Object element, String property) {
return false;
}
/*
* @see IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
}
}

View file

@ -1,225 +0,0 @@
package org.eclipse.cdt.internal.ui.text.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.cdt.internal.corext.template.Template;
import org.eclipse.cdt.internal.corext.template.TemplateBuffer;
import org.eclipse.cdt.internal.corext.template.TemplateContext;
import org.eclipse.cdt.internal.corext.template.TemplateMessages;
import org.eclipse.cdt.internal.corext.template.TemplatePosition;
import org.eclipse.cdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.cdt.internal.ui.text.link.LinkedPositionUI;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.text.ICCompletionProposal;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.util.Assert;
/**
* A template proposal.
*/
public class TemplateProposal implements ICCompletionProposal {
private final Template fTemplate;
private final TemplateContext fContext;
private final ITextViewer fViewer;
private final Image fImage;
private final IRegion fRegion;
private TemplateBuffer fTemplateBuffer;
private String fOldText;
private IRegion fSelectedRegion; // initialized by apply()
/**
* Creates a template proposal with a template and its context.
* @param template the template
* @param context the context in which the template was requested.
* @param image the icon of the proposal.
*/
public TemplateProposal(Template template, TemplateContext context, IRegion region, ITextViewer viewer, Image image) {
Assert.isNotNull(template);
Assert.isNotNull(context);
Assert.isNotNull(region);
Assert.isNotNull(viewer);
fTemplate= template;
fContext= context;
fViewer= viewer;
fImage= image;
fRegion= region;
}
/**
* @see ICompletionProposal#apply(IDocument)
*/
public void apply(IDocument document) {
try {
if (fTemplateBuffer == null)
fTemplateBuffer= fContext.evaluate(fTemplate);
int start= fRegion.getOffset();
int end= fRegion.getOffset() + fRegion.getLength();
// insert template string
String templateString= fTemplateBuffer.getString();
document.replace(start, end - start, templateString);
// translate positions
LinkedPositionManager manager= new LinkedPositionManager(document);
TemplatePosition[] variables= fTemplateBuffer.getVariables();
for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i];
if (variable.isResolved())
continue;
int[] offsets= variable.getOffsets();
int length= variable.getLength();
for (int j= 0; j != offsets.length; j++)
manager.addPosition(offsets[j] + start, length);
}
LinkedPositionUI editor= new LinkedPositionUI(fViewer, manager);
editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + start);
editor.enter();
fSelectedRegion= editor.getSelectedRegion();
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
openErrorDialog(e);
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openErrorDialog(e);
}
}
private static int getCaretOffset(TemplateBuffer buffer) {
TemplatePosition[] variables= buffer.getVariables();
for (int i= 0; i != variables.length; i++) {
TemplatePosition variable= variables[i];
if (variable.getName().equals("cursor")) //$NON-NLS-1$
return variable.getOffsets()[0];
}
return buffer.getString().length();
}
/**
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
}
/**
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
try {
if (fTemplateBuffer == null)
fTemplateBuffer= fContext.evaluate(fTemplate);
return textToHTML(fTemplateBuffer.getString());
} catch (CoreException e) {
CUIPlugin.getDefault().log(e);
openErrorDialog(e);
return null;
}
}
/**
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return fTemplate.getName() + TemplateMessages.getString("TemplateProposal.delimiter") + fTemplate.getDescription(); // $NON-NLS-1$ //$NON-NLS-1$
}
/**
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return fImage;
}
/**
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
private static String textToHTML(String string) {
StringBuffer buffer= new StringBuffer(string.length());
buffer.append("<pre>"); //$NON-NLS-1$
for (int i= 0; i != string.length(); i++) {
char ch= string.charAt(i);
switch (ch) {
case '&':
buffer.append("&amp;"); //$NON-NLS-1$
break;
case '<':
buffer.append("&lt;"); //$NON-NLS-1$
break;
case '>':
buffer.append("&gt;"); //$NON-NLS-1$
break;
case '\t':
buffer.append(" "); //$NON-NLS-1$
break;
case '\n':
buffer.append("<br>"); //$NON-NLS-1$
break;
default:
buffer.append(ch);
break;
}
}
buffer.append("</pre>"); //$NON-NLS-1$
return buffer.toString();
}
private void openErrorDialog(BadLocationException e) {
Shell shell= fViewer.getTextWidget().getShell();
MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$
}
private void openErrorDialog(CoreException e) {
Shell shell= fViewer.getTextWidget().getShell();
MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see IJavaCompletionProposal#getRelevance()
*/
public int getRelevance() {
return 9;
}
}

View file

@ -1,141 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.text.template;
import org.eclipse.cdt.internal.corext.template.ContextType;
import org.eclipse.cdt.internal.corext.template.TemplateVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
public class TemplateVariableProcessor implements IContentAssistProcessor {
private static Comparator fgTemplateVariableProposalComparator= new Comparator() {
public int compare(Object arg0, Object arg1) {
TemplateVariableProposal proposal0= (TemplateVariableProposal) arg0;
TemplateVariableProposal proposal1= (TemplateVariableProposal) arg1;
return proposal0.getDisplayString().compareTo(proposal1.getDisplayString());
}
public boolean equals(Object arg0) {
return false;
}
};
/** the context type */
private ContextType fContextType;
/**
* Sets the context type.
*/
public void setContextType(ContextType contextType) {
fContextType= contextType;
}
/*
* @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
if (fContextType == null)
return null;
List proposals= new ArrayList();
String text= viewer.getDocument().get();
int start= getStart(text, documentOffset);
int end= documentOffset;
String string= text.substring(start, end);
String prefix= (string.length() >= 2)
? string.substring(2)
: null;
int offset= start;
int length= end - start;
for (Iterator iterator= fContextType.variableIterator(); iterator.hasNext(); ) {
TemplateVariable variable= (TemplateVariable) iterator.next();
if (prefix == null || variable.getName().startsWith(prefix))
proposals.add(new TemplateVariableProposal(variable, offset, length, viewer));
}
Collections.sort(proposals, fgTemplateVariableProposalComparator);
return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
}
/* Guesses the start position of the completion */
private int getStart(String string, int end) {
int start= end;
if (start >= 1 && string.charAt(start - 1) == '$')
return start - 1;
while ((start != 0) && Character.isUnicodeIdentifierPart(string.charAt(start - 1)))
start--;
if (start >= 2 && string.charAt(start - 1) == '{' && string.charAt(start - 2) == '$')
return start - 2;
return end;
}
/*
* @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
return null;
}
/*
* @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return new char[] {'$'};
}
/*
* @see IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/*
* @see IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
return null;
}
/*
* @see IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
return null;
}
}

View file

@ -1,103 +0,0 @@
package org.eclipse.cdt.internal.ui.text.template;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.cdt.internal.corext.template.TemplateMessages;
import org.eclipse.cdt.internal.corext.template.TemplateVariable;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
/**
* A proposal for insertion of template variables.
*/
public class TemplateVariableProposal implements ICompletionProposal {
private TemplateVariable fVariable;
private int fOffset;
private int fLength;
private ITextViewer fViewer;
private Point fSelection;
/**
* Creates a template variable proposal.
*
* @param variable the template variable
* @param offset the offset to replace
* @param length the length to replace
* @param viewer the viewer
*/
public TemplateVariableProposal(TemplateVariable variable, int offset, int length, ITextViewer viewer) {
fVariable= variable;
fOffset= offset;
fLength= length;
fViewer= viewer;
}
/*
* @see ICompletionProposal#apply(IDocument)
*/
public void apply(IDocument document) {
try {
String variable= fVariable.getName().equals("dollar") ? "$$" : "${" + fVariable.getName() + '}'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
document.replace(fOffset, fLength, variable);
fSelection= new Point(fOffset + variable.length(), 0);
} catch (BadLocationException e) {
CUIPlugin.getDefault().log(e);
Shell shell= fViewer.getTextWidget().getShell();
MessageDialog.openError(shell, TemplateMessages.getString("TemplateVariableProposal.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
/*
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
return fSelection;
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
return null;
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return fVariable.getName() + " - " + fVariable.getDescription(); //$NON-NLS-1$
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return null;
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
}

View file

@ -206,7 +206,6 @@ public class Strings {
} }
if (start == size) if (start == size)
return ""; //$NON-NLS-1$ return ""; //$NON-NLS-1$
else
return line.substring(start); return line.substring(start);
} }
@ -371,5 +370,19 @@ public class Strings {
return false; return false;
return true; return true;
} }
/**
* Creates a string that consists of the given number of tab characters.
* @param indentLevel
* @return
*/
public static String createIndentString(int indentLevel) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < indentLevel; i++) {
result.append('\t');
}
return result.toString();
}
} }

View file

@ -12,6 +12,7 @@
package org.eclipse.cdt.ui; package org.eclipse.cdt.ui;
import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
@ -28,6 +29,7 @@ import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.core.model.IBufferFactory; import org.eclipse.cdt.internal.core.model.IBufferFactory;
import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.cdt.internal.corext.template.c.CContextType;
import org.eclipse.cdt.internal.ui.CElementAdapterFactory; import org.eclipse.cdt.internal.ui.CElementAdapterFactory;
import org.eclipse.cdt.internal.ui.ICStatusConstants; import org.eclipse.cdt.internal.ui.ICStatusConstants;
import org.eclipse.cdt.internal.ui.IContextMenuConstants; import org.eclipse.cdt.internal.ui.IContextMenuConstants;
@ -62,6 +64,8 @@ import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.source.ISharedTextColors; import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.templates.ContextTypeRegistry;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorInput;
@ -71,6 +75,8 @@ import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.ConfigurationElementSorter; import org.eclipse.ui.texteditor.ConfigurationElementSorter;
@ -186,6 +192,11 @@ public class CUIPlugin extends AbstractUIPlugin {
*/ */
public static final String ID_TYPE_HIERARCHY = "org.eclipse.cdt.ui.TypeHierarchyView"; //$NON-NLS-1$ public static final String ID_TYPE_HIERARCHY = "org.eclipse.cdt.ui.TypeHierarchyView"; //$NON-NLS-1$
/**
* The key to store customized templates.
* @since 3.0
*/
private static final String CUSTOM_TEMPLATES_KEY= "org.eclipse.cdt.ui.text.templates.custom"; //$NON-NLS-1$
/** /**
* The id of the C Element Creation action set * The id of the C Element Creation action set
@ -327,6 +338,19 @@ public class CUIPlugin extends AbstractUIPlugin {
private ResourceAdapterFactory fResourceAdapterFactory; private ResourceAdapterFactory fResourceAdapterFactory;
private CElementAdapterFactory fCElementAdapterFactory; private CElementAdapterFactory fCElementAdapterFactory;
/**
* The template context type registry for the java editor.
* @since 3.0
*/
private ContributionContextTypeRegistry fContextTypeRegistry;
/**
* The template store for the java editor.
* @since 3.0
*/
private TemplateStore fTemplateStore;
public CUIPlugin() { public CUIPlugin() {
fgCPlugin = this; fgCPlugin = this;
fDocumentProvider = null; fDocumentProvider = null;
@ -618,13 +642,12 @@ public class CUIPlugin extends AbstractUIPlugin {
int annotationHoverIndex= -1; int annotationHoverIndex= -1;
for (int i= 0; i < length; i++) { for (int i= 0; i < length; i++) {
if (!fCEditorTextHoverDescriptors[i].getId().startsWith(PLUGIN_ID)) { if (!fCEditorTextHoverDescriptors[i].getId().startsWith(PLUGIN_ID)) {
if (problemHoverIndex == -1 || annotationHoverIndex == -1) if (problemHoverIndex == -1 || annotationHoverIndex == -1) {
continue; continue;
else { }
last= i - 1; last= i - 1;
break; break;
} }
}
if (first == -1) if (first == -1)
first= i; first= i;
@ -687,4 +710,36 @@ public class CUIPlugin extends AbstractUIPlugin {
return fFoldingStructureProviderRegistry; return fFoldingStructureProviderRegistry;
} }
/**
* Returns the template context type registry for the java plugin.
*
* @return the template context type registry for the java plugin
* @since 3.0
*/
public ContextTypeRegistry getTemplateContextRegistry() {
if (fContextTypeRegistry == null) {
fContextTypeRegistry= new ContributionContextTypeRegistry();
fContextTypeRegistry.addContextType(CContextType.CCONTEXT_TYPE);
}
return fContextTypeRegistry;
}
/**
* Returns the template store for the java editor templates.
*
* @return the template store for the java editor templates
* @since 3.0
*/
public TemplateStore getTemplateStore() {
if (fTemplateStore == null) {
fTemplateStore = new ContributionTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), CUSTOM_TEMPLATES_KEY);
try {
fTemplateStore.load();
} catch (IOException e) {
log(e);
}
}
return fTemplateStore;
}
} }

View file

@ -356,6 +356,16 @@ public class PreferenceConstants {
*/ */
public static final String EDITOR_FOLDING_MACROS= "editor_folding_default_macros"; //$NON-NLS-1$ public static final String EDITOR_FOLDING_MACROS= "editor_folding_default_macros"; //$NON-NLS-1$
/**
* A named preference that controls if templates are formatted when applied.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 2.1
*/
public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.cdt.ui.text.templates.format"; //$NON-NLS-1$
/** /**
* Returns the CDT-UI preference store. * Returns the CDT-UI preference store.
* *

View file

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
(c) Copyright IBM Corp. 2000, 2001. 2004
All Rights Reserved.
-->
<!-- NOTE TO TRANSLATOR:
* Only these ENTITY strings listed in the DOCTYPE definition
* are to be translated. The rest of this file should remain
* English as it produces compilable code.
-->
<!DOCTYPE document [
<!ENTITY withtempvar "with temporary variable">
<!ENTITY statement "statement">
<!-- block is a noun -->
<!ENTITY block "block">
<!ENTITY method "method">
<!ENTITY declaration "declaration">
<!ENTITY usinganamespace "using a namespace">
<!ENTITY statement "statement">
<!ENTITY createnewobject "create new object">
<!ENTITY defaultmultilinecomment "default multiline comment">
<!ENTITY printtostdout "print to standard output">
<!ENTITY printtostderr "print to standard error">
<!ENTITY authorname "author name">
<!ENTITY commentText "To change this generated comment edit the template variable &quot;comment&quot;:
* Window&gt;Preferences&gt;C&gt;Templates.">
]>
<templates>
<template name="for" description="for loop" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.for" enabled="true">for (${var} = 0; ${var} &lt; ${max}; ++${var}) {
${cursor}
}</template>
<template name="for" description="for loop &withtempvar;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.for" enabled="true">for (int ${var} = 0; ${var} &lt; ${max}; ++${var}) {
${cursor}
}</template>
<template name="do" description="do while &statement;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.do" enabled="true">do {
${cursor}
} while (${condition});</template>
<template name="switch" description="switch case &statement;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.switch" enabled="true">switch (${key}) {
case ${value}:
${cursor}
break;
default:
break;
}</template>
<template name="if" description="if &statement;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.if" enabled="true">if (${condition}) {
${cursor}
}</template>
<template name="ifelse" description="if else &statement;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.ifelse" enabled="true">if (${condition}) {
${cursor}
} else {
}</template>
<template name="elseif" description="else if &block;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.elseif" enabled="true">else if (${condition}) {
${cursor}
}</template>
<template name="else" description="else &block;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.else" enabled="true">else {
${cursor}
}</template>
<template name="try" description="try catch &block;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.try" enabled="true">try {
${cursor}
} catch (${Exception} e) {
}</template>
<template name="catch" description="catch &block;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.catch" enabled="true">catch (${Exception} e) {
${cursor}
}</template>
<template name="main" description="main &method;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.main" enabled="true">int main(int argc, char **argv) {
${cursor}
}</template>
<template name="class" description="class &declaration;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.class" enabled="true">class ${name} {
${cursor}
private:
};</template>
<template name="using" description="&usinganamespace;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.using" enabled="true">using namespace ${namespace};
</template>
<template name="namespace" description="namespace &declaration;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.namespace" enabled="true">namespace ${namespace} {
${cursor}
}</template>
<template name="new" description="&createnewobject;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.cpp.new" enabled="true">${type} ${name} = new ${type}(${arguments});</template>
<template name="comment" description="&defaultmultilinecomment;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.comment" enabled="true">
/*
* author ${user}
*
* &commentText;
*/
</template>
<template name="stdout" description="&printtostdout;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.printf" enabled="true">printf(${cursor});</template>
<template name="stderr" description="&printtostderr;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.fprintf" enabled="true">fprintf(stderr, ${cursor});</template>
<template name="author" description="&authorname;" context="org.eclipse.cdt.ui.text.templates.c" id="org.eclipse.cdt.ui.text.templates.c.author" enabled="true">author ${user}</template>
</templates>